]> andersk Git - openssh.git/blob - sshd.c
- Merged more OpenBSD CVS changes:
[openssh.git] / sshd.c
1 /*
2
3 sshd.c
4
5 Author: Tatu Ylonen <ylo@cs.hut.fi>
6
7 Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
8                    All rights reserved
9
10 Created: Fri Mar 17 17:09:28 1995 ylo
11
12 This program is the ssh daemon.  It listens for connections from clients, and
13 performs authentication, executes use commands or shell, and forwards
14 information to/from the application to the user client over an encrypted
15 connection.  This can also handle forwarding of X11, TCP/IP, and authentication
16 agent connections.
17
18 */
19
20 #include "includes.h"
21 RCSID("$Id$");
22
23 #include "xmalloc.h"
24 #include "rsa.h"
25 #include "ssh.h"
26 #include "pty.h"
27 #include "packet.h"
28 #include "buffer.h"
29 #include "cipher.h"
30 #include "mpaux.h"
31 #include "servconf.h"
32 #include "uidswap.h"
33 #include "compat.h"
34
35 #ifdef LIBWRAP
36 #include <tcpd.h>
37 #include <syslog.h>
38 int allow_severity = LOG_INFO;
39 int deny_severity = LOG_WARNING;
40 #endif /* LIBWRAP */
41
42 #ifndef O_NOCTTY
43 #define O_NOCTTY        0
44 #endif
45
46 /* Local Xauthority file. */
47 static char *xauthfile = NULL;
48
49 /* Server configuration options. */
50 ServerOptions options;
51
52 /* Name of the server configuration file. */
53 char *config_file_name = SERVER_CONFIG_FILE;
54
55 /* Debug mode flag.  This can be set on the command line.  If debug
56    mode is enabled, extra debugging output will be sent to the system
57    log, the daemon will not go to background, and will exit after processing
58    the first connection. */
59 int debug_flag = 0;
60
61 /* Flag indicating that the daemon is being started from inetd. */
62 int inetd_flag = 0;
63
64 /* debug goes to stderr unless inetd_flag is set */
65 int log_stderr = 0;
66
67 /* argv[0] without path. */
68 char *av0;
69
70 /* Saved arguments to main(). */
71 char **saved_argv;
72
73 /* This is set to the socket that the server is listening; this is used in
74    the SIGHUP signal handler. */
75 int listen_sock;
76
77 /* Flags set in auth-rsa from authorized_keys flags.  These are set in
78   auth-rsa.c. */
79 int no_port_forwarding_flag = 0;
80 int no_agent_forwarding_flag = 0;
81 int no_x11_forwarding_flag = 0;
82 int no_pty_flag = 0;
83 char *forced_command = NULL;  /* RSA authentication "command=" option. */
84 struct envstring *custom_environment = NULL; 
85                           /* RSA authentication "environment=" options. */
86
87 /* Session id for the current session. */
88 unsigned char session_id[16];
89
90 /* Any really sensitive data in the application is contained in this structure.
91    The idea is that this structure could be locked into memory so that the
92    pages do not get written into swap.  However, there are some problems.
93    The private key contains BIGNUMs, and we do not (in principle) have
94    access to the internals of them, and locking just the structure is not
95    very useful.  Currently, memory locking is not implemented. */
96 struct
97 {
98   /* Private part of server key. */
99   RSA *private_key;
100
101   /* Private part of host key. */
102   RSA *host_key;
103 } sensitive_data;
104
105 /* Flag indicating whether the current session key has been used.  This flag
106    is set whenever the key is used, and cleared when the key is regenerated. */
107 int key_used = 0;
108
109 /* This is set to true when SIGHUP is received. */
110 int received_sighup = 0;
111
112 /* Public side of the server key.  This value is regenerated regularly with
113    the private key. */
114 RSA *public_key;
115
116 /* Prototypes for various functions defined later in this file. */
117 void do_connection();
118 void do_authentication(char *user);
119 void do_authloop(struct passwd *pw);
120 void do_fake_authloop(char *user);
121 void do_authenticated(struct passwd *pw);
122 void do_exec_pty(const char *command, int ptyfd, int ttyfd, 
123                  const char *ttyname, struct passwd *pw, const char *term,
124                  const char *display, const char *auth_proto,
125                  const char *auth_data);
126 void do_exec_no_pty(const char *command, struct passwd *pw,
127                     const char *display, const char *auth_proto,
128                     const char *auth_data);
129 void do_child(const char *command, struct passwd *pw, const char *term,
130               const char *display, const char *auth_proto,
131               const char *auth_data, const char *ttyname);
132
133 #ifdef HAVE_LIBPAM
134 static int pamconv(int num_msg, const struct pam_message **msg,
135                 struct pam_response **resp, void *appdata_ptr);
136 void do_pam_account_and_session(const char *username, 
137                 const char *remote_user, const char *remote_host);
138 void pam_cleanup_proc(void *context);
139
140 static struct pam_conv conv = {
141     pamconv,
142     NULL
143 };
144 struct pam_handle_t *pamh = NULL;
145 const char *pampasswd = NULL;
146 char *pamconv_msg = NULL;
147
148 static int pamconv(int num_msg, const struct pam_message **msg,
149                    struct pam_response **resp, void *appdata_ptr)
150 {
151   int count = 0;
152   struct pam_response *reply = NULL;
153
154   /* PAM will free this later */
155   reply = malloc(num_msg * sizeof(*reply));
156   if (reply == NULL)
157     return PAM_CONV_ERR; 
158   
159   for(count = 0; count < num_msg; count++)
160   {
161     switch (msg[count]->msg_style)
162     {
163       case PAM_PROMPT_ECHO_OFF:
164         if (pampasswd == NULL)
165         {
166           free(reply);
167           return PAM_CONV_ERR;
168         }
169         reply[count].resp_retcode = PAM_SUCCESS;
170         reply[count].resp = xstrdup(pampasswd);
171         break;
172
173       case PAM_TEXT_INFO:
174         reply[count].resp_retcode = PAM_SUCCESS;
175         reply[count].resp = xstrdup("");
176         
177         if (msg[count]->msg == NULL) break;
178         debug("Adding PAM message: %s", msg[count]->msg);
179         if (pamconv_msg == NULL)
180         {
181           pamconv_msg = malloc(strlen(msg[count]->msg) + 2);
182           
183           if (pamconv_msg == NULL)
184             return PAM_CONV_ERR;
185             
186           strncpy(pamconv_msg, msg[count]->msg, strlen(msg[count]->msg));
187           pamconv_msg[strlen(msg[count]->msg)] = '\n';
188           pamconv_msg[strlen(msg[count]->msg) + 1] = '\0';
189         } else
190         {
191           pamconv_msg = realloc(pamconv_msg, strlen(pamconv_msg) + strlen(msg[count]->msg) + 2);
192           strncat(pamconv_msg, msg[count]->msg, strlen(msg[count]->msg));
193           pamconv_msg[strlen(pamconv_msg)] = '\n';
194           pamconv_msg[strlen(pamconv_msg) + 1] = '\0';
195         }
196         break;
197
198       case PAM_PROMPT_ECHO_ON:
199       case PAM_ERROR_MSG:
200       default:
201         free(reply);
202         return PAM_CONV_ERR;
203     }
204   }
205
206   *resp = reply;
207          
208   return PAM_SUCCESS;
209 }
210
211 void pam_cleanup_proc(void *context)
212 {
213   int pam_retval;
214   
215   if (pamh != NULL)
216   {
217     pam_retval = pam_close_session((pam_handle_t *)pamh, 0);
218     if (pam_retval != PAM_SUCCESS)
219     {
220       log("Cannot close PAM session: %.200s", 
221           pam_strerror((pam_handle_t *)pamh, pam_retval));
222     }
223      
224     pam_retval = pam_end((pam_handle_t *)pamh, pam_retval);
225     if (pam_retval != PAM_SUCCESS)
226     {
227       log("Cannot release PAM authentication: %.200s", 
228           pam_strerror((pam_handle_t *)pamh, pam_retval));
229     }
230   }
231 }
232
233 void do_pam_account_and_session(const char *username, const char *remote_user, const char *remote_host)
234 {
235   int pam_retval;
236   
237   if (remote_host != NULL)
238   {
239     debug("PAM setting rhost to \"%.200s\"", remote_host);
240     pam_retval = pam_set_item((pam_handle_t *)pamh, PAM_RHOST, remote_host);
241     if (pam_retval != PAM_SUCCESS)
242     {
243       log("PAM set rhost failed: %.200s", pam_strerror((pam_handle_t *)pamh, pam_retval));
244            do_fake_authloop(username);
245     }
246   }
247   
248   if (remote_user != NULL)
249   {
250     debug("PAM setting ruser to \"%.200s\"", remote_user);
251     pam_retval = pam_set_item((pam_handle_t *)pamh, PAM_RUSER, remote_user);
252     if (pam_retval != PAM_SUCCESS)
253     {
254       log("PAM set ruser failed: %.200s", pam_strerror((pam_handle_t *)pamh, pam_retval));
255            do_fake_authloop(username);
256     }
257   }
258   
259   pam_retval = pam_acct_mgmt((pam_handle_t *)pamh, 0);
260   if (pam_retval != PAM_SUCCESS)
261   {
262     log("PAM rejected by account configuration: %.200s", pam_strerror((pam_handle_t *)pamh, pam_retval));
263          do_fake_authloop(username);
264   }
265
266   pam_retval = pam_open_session((pam_handle_t *)pamh, 0);
267   if (pam_retval != PAM_SUCCESS)
268   {
269     log("PAM session setup failed: %.200s", pam_strerror((pam_handle_t *)pamh, pam_retval));
270          do_fake_authloop(username);
271   }
272 }
273 #endif /* HAVE_LIBPAM */
274
275 /* Signal handler for SIGHUP.  Sshd execs itself when it receives SIGHUP;
276    the effect is to reread the configuration file (and to regenerate
277    the server key). */
278
279 void sighup_handler(int sig)
280 {
281   received_sighup = 1;
282   signal(SIGHUP, sighup_handler);
283 }
284
285 /* Called from the main program after receiving SIGHUP.  Restarts the 
286    server. */
287
288 void sighup_restart()
289 {
290   log("Received SIGHUP; restarting.");
291   close(listen_sock);
292   execv(saved_argv[0], saved_argv);
293   log("RESTART FAILED: av0='%s', error: %s.", av0, strerror(errno));
294   exit(1);
295 }
296
297 /* Generic signal handler for terminating signals in the master daemon. 
298    These close the listen socket; not closing it seems to cause "Address
299    already in use" problems on some machines, which is inconvenient. */
300
301 void sigterm_handler(int sig)
302 {
303   log("Received signal %d; terminating.", sig);
304   close(listen_sock);
305   exit(255);
306 }
307
308 /* SIGCHLD handler.  This is called whenever a child dies.  This will then 
309    reap any zombies left by exited c. */
310
311 void main_sigchld_handler(int sig)
312 {
313   int save_errno = errno;
314   int status;
315   wait(&status);
316   signal(SIGCHLD, main_sigchld_handler);
317   errno = save_errno;
318 }
319
320 /* Signal handler for the alarm after the login grace period has expired. */
321
322 void grace_alarm_handler(int sig)
323 {
324   /* Close the connection. */
325   packet_close();
326   
327   /* Log error and exit. */
328   fatal("Timeout before authentication.");
329 }
330
331 /* Signal handler for the key regeneration alarm.  Note that this
332    alarm only occurs in the daemon waiting for connections, and it does not
333    do anything with the private key or random state before forking.  Thus there
334    should be no concurrency control/asynchronous execution problems. */
335
336 void key_regeneration_alarm(int sig)
337 {
338   int save_errno = errno;
339
340   /* Check if we should generate a new key. */
341   if (key_used)
342     {
343       /* This should really be done in the background. */
344       log("Generating new %d bit RSA key.", options.server_key_bits);
345
346       if (sensitive_data.private_key != NULL)
347         RSA_free(sensitive_data.private_key);
348       sensitive_data.private_key = RSA_new();
349
350       if (public_key != NULL) 
351         RSA_free(public_key);
352       public_key = RSA_new();
353
354       rsa_generate_key(sensitive_data.private_key, public_key, 
355                        options.server_key_bits);
356       arc4random_stir();
357       key_used = 0;
358       log("RSA key generation complete.");
359     }
360
361   /* Reschedule the alarm. */
362   signal(SIGALRM, key_regeneration_alarm);
363   alarm(options.key_regeneration_time);
364   errno = save_errno;
365 }
366
367 /* Main program for the daemon. */
368
369 int
370 main(int ac, char **av)
371 {
372   extern char *optarg;
373   extern int optind;
374   int opt, aux, sock_in, sock_out, newsock, i, pid, on = 1;
375   int remote_major, remote_minor;
376   int silentrsa = 0;
377   struct sockaddr_in sin;
378   char buf[100]; /* Must not be larger than remote_version. */
379   char remote_version[100]; /* Must be at least as big as buf. */
380   int remote_port;
381   char *comment;
382   FILE *f;
383   struct linger linger;
384
385   /* Save argv[0]. */
386   saved_argv = av;
387   if (strchr(av[0], '/'))
388     av0 = strrchr(av[0], '/') + 1;
389   else
390     av0 = av[0];
391
392   /* Initialize configuration options to their default values. */
393   initialize_server_options(&options);
394
395   /* Parse command-line arguments. */
396   while ((opt = getopt(ac, av, "f:p:b:k:h:g:diqQ")) != EOF)
397     {
398       switch (opt)
399         {
400         case 'f':
401           config_file_name = optarg;
402           break;
403         case 'd':
404           debug_flag = 1;
405           options.log_level = SYSLOG_LEVEL_DEBUG;
406           break;
407         case 'i':
408           inetd_flag = 1;
409           break;
410         case 'Q':
411           silentrsa = 1;
412           break;
413         case 'q':
414           options.log_level = SYSLOG_LEVEL_QUIET;
415           break;
416         case 'b':
417           options.server_key_bits = atoi(optarg);
418           break;
419         case 'p':
420           options.port = atoi(optarg);
421           break;
422         case 'g':
423           options.login_grace_time = atoi(optarg);
424           break;
425         case 'k':
426           options.key_regeneration_time = atoi(optarg);
427           break;
428         case 'h':
429           options.host_key_file = optarg;
430           break;
431         case '?':
432         default:
433           fprintf(stderr, "sshd version %s\n", SSH_VERSION);
434           fprintf(stderr, "Usage: %s [options]\n", av0);
435           fprintf(stderr, "Options:\n");
436           fprintf(stderr, "  -f file    Configuration file (default %s/sshd_config)\n", ETCDIR);
437           fprintf(stderr, "  -d         Debugging mode\n");
438           fprintf(stderr, "  -i         Started from inetd\n");
439           fprintf(stderr, "  -q         Quiet (no logging)\n");
440           fprintf(stderr, "  -p port    Listen on the specified port (default: 22)\n");
441           fprintf(stderr, "  -k seconds Regenerate server key every this many seconds (default: 3600)\n");
442           fprintf(stderr, "  -g seconds Grace period for authentication (default: 300)\n");
443           fprintf(stderr, "  -b bits    Size of server RSA key (default: 768 bits)\n");
444           fprintf(stderr, "  -h file    File from which to read host key (default: %s)\n",
445                   HOST_KEY_FILE);
446           exit(1);
447         }
448     }
449
450   /* check if RSA support exists */
451   if (rsa_alive() == 0) {
452     if (silentrsa == 0)
453       printf("sshd: no RSA support in libssl and libcrypto -- exiting.  See ssl(8)\n");
454     log("no RSA support in libssl and libcrypto -- exiting.  See ssl(8)");
455     exit(1);
456   }
457
458   /* Read server configuration options from the configuration file. */
459   read_server_config(&options, config_file_name);
460
461   /* Fill in default values for those options not explicitly set. */
462   fill_default_server_options(&options);
463
464   /* Check certain values for sanity. */
465   if (options.server_key_bits < 512 || 
466       options.server_key_bits > 32768)
467     {
468       fprintf(stderr, "Bad server key size.\n");
469       exit(1);
470     }
471   if (options.port < 1 || options.port > 65535)
472     {
473       fprintf(stderr, "Bad port number.\n");
474       exit(1);
475     }
476
477   /* Check that there are no remaining arguments. */
478   if (optind < ac)
479     {
480       fprintf(stderr, "Extra argument %s.\n", av[optind]);
481       exit(1);
482     }
483
484   /* Initialize the log (it is reinitialized below in case we forked). */
485
486   if (debug_flag && !inetd_flag)
487     log_stderr = 1;
488
489   log_init(av0, options.log_level, options.log_facility, log_stderr);
490
491   debug("sshd version %.100s", SSH_VERSION);
492
493   sensitive_data.host_key = RSA_new();
494   /* Load the host key.  It must have empty passphrase. */
495   if (!load_private_key(options.host_key_file, "", 
496                         sensitive_data.host_key, &comment))
497     {
498       if (debug_flag)
499         fprintf(stderr, "Could not load host key: %s: %s\n",
500                 options.host_key_file, strerror(errno));
501       else
502         {
503           int err = errno;
504           /* force logging */
505           log_init(av0, SYSLOG_LEVEL_DEBUG, options.log_facility, log_stderr);
506           error("Could not load host key: %.200s: %.100s", 
507                 options.host_key_file, strerror(err));
508         }
509       exit(1);
510     }
511   xfree(comment);
512
513   /* If not in debugging mode, and not started from inetd, disconnect from
514      the controlling terminal, and fork.  The original process exits. */
515   if (!debug_flag && !inetd_flag)
516     { 
517 #ifdef TIOCNOTTY
518       int fd;
519 #endif /* TIOCNOTTY */
520       if (daemon(0, 0) < 0)
521           fatal("daemon() failed: %.200s", strerror(errno));
522      
523       /* Disconnect from the controlling tty. */
524 #ifdef TIOCNOTTY
525       fd = open("/dev/tty", O_RDWR|O_NOCTTY);
526       if (fd >= 0)
527         {
528           (void)ioctl(fd, TIOCNOTTY, NULL);
529           close(fd);
530         }
531 #endif /* TIOCNOTTY */
532     }
533
534   /* Reinitialize the log (because of the fork above). */
535   log_init(av0, options.log_level, options.log_facility, log_stderr);
536
537   /* Check that server and host key lengths differ sufficiently.  This is
538      necessary to make double encryption work with rsaref.  Oh, I hate
539      software patents. I dont know if this can go? Niels */
540   if (options.server_key_bits > 
541       BN_num_bits(sensitive_data.host_key->n) - SSH_KEY_BITS_RESERVED &&
542       options.server_key_bits < 
543       BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED)
544     {
545       options.server_key_bits = 
546         BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED;
547       debug("Forcing server key to %d bits to make it differ from host key.", 
548             options.server_key_bits);
549     }
550
551   /* Do not display messages to stdout in RSA code. */
552   rsa_set_verbose(0);
553
554   /* Initialize the random number generator. */
555   arc4random_stir();
556   
557   /* Chdir to the root directory so that the current disk can be unmounted
558      if desired. */
559   chdir("/");
560   
561   /* Close connection cleanly after attack. */
562   cipher_attack_detected = packet_disconnect;
563
564   /* Start listening for a socket, unless started from inetd. */
565   if (inetd_flag)
566     {
567       int s1, s2;
568       s1 = dup(0);  /* Make sure descriptors 0, 1, and 2 are in use. */
569       s2 = dup(s1);
570       sock_in = dup(0);
571       sock_out = dup(1);
572       /* We intentionally do not close the descriptors 0, 1, and 2 as our
573          code for setting the descriptors won\'t work if ttyfd happens to
574          be one of those. */
575       debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
576
577       public_key = RSA_new();
578       sensitive_data.private_key = RSA_new();
579       /* Generate an rsa key. */
580       log("Generating %d bit RSA key.", options.server_key_bits);
581       rsa_generate_key(sensitive_data.private_key, public_key,
582                        options.server_key_bits);
583       arc4random_stir();
584       log("RSA key generation complete.");
585     }
586   else
587     {
588       /* Create socket for listening. */
589       listen_sock = socket(AF_INET, SOCK_STREAM, 0);
590       if (listen_sock < 0)
591         fatal("socket: %.100s", strerror(errno));
592
593       /* Set socket options.  We try to make the port reusable and have it
594          close as fast as possible without waiting in unnecessary wait states
595          on close. */
596       setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, 
597                  sizeof(on));
598       linger.l_onoff = 1;
599       linger.l_linger = 5;
600       setsockopt(listen_sock, SOL_SOCKET, SO_LINGER, (void *)&linger, 
601                  sizeof(linger));
602
603       /* Initialize the socket address. */
604       memset(&sin, 0, sizeof(sin));
605       sin.sin_family = AF_INET;
606       sin.sin_addr = options.listen_addr;
607       sin.sin_port = htons(options.port);
608
609       /* Bind the socket to the desired port. */
610       if (bind(listen_sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
611         {
612           error("bind: %.100s", strerror(errno));
613           shutdown(listen_sock, SHUT_RDWR);
614           close(listen_sock);
615           fatal("Bind to port %d failed.", options.port);
616         }
617
618       if (!debug_flag)
619         {
620           /* Record our pid in /etc/sshd_pid to make it easier to kill the
621              correct sshd.  We don\'t want to do this before the bind above
622              because the bind will fail if there already is a daemon, and this
623              will overwrite any old pid in the file. */
624           f = fopen(SSH_DAEMON_PID_FILE, "w");
625           if (f)
626             {
627               fprintf(f, "%u\n", (unsigned int)getpid());
628               fclose(f);
629             }
630         }
631
632       /* Start listening on the port. */
633       log("Server listening on port %d.", options.port);
634       if (listen(listen_sock, 5) < 0)
635         fatal("listen: %.100s", strerror(errno));
636
637       public_key = RSA_new();
638       sensitive_data.private_key = RSA_new();
639       /* Generate an rsa key. */
640       log("Generating %d bit RSA key.", options.server_key_bits);
641       rsa_generate_key(sensitive_data.private_key, public_key,
642                        options.server_key_bits);
643       arc4random_stir();
644       log("RSA key generation complete.");
645
646       /* Schedule server key regeneration alarm. */
647       signal(SIGALRM, key_regeneration_alarm);
648       alarm(options.key_regeneration_time);
649
650       /* Arrange to restart on SIGHUP.  The handler needs listen_sock. */
651       signal(SIGHUP, sighup_handler);
652       signal(SIGTERM, sigterm_handler);
653       signal(SIGQUIT, sigterm_handler);
654       
655       /* Arrange SIGCHLD to be caught. */
656       signal(SIGCHLD, main_sigchld_handler);
657
658       /* Stay listening for connections until the system crashes or the
659          daemon is killed with a signal. */
660       for (;;)
661         {
662           if (received_sighup)
663             sighup_restart();
664           /* Wait in accept until there is a connection. */
665           aux = sizeof(sin);
666           newsock = accept(listen_sock, (struct sockaddr *)&sin, &aux);
667           if (received_sighup)
668             sighup_restart();
669           if (newsock < 0)
670             {
671               if (errno == EINTR)
672                 continue;
673               error("accept: %.100s", strerror(errno));
674               continue;
675             }
676
677           /* Got connection.  Fork a child to handle it, unless we are in
678              debugging mode. */
679           if (debug_flag)
680             {
681               /* In debugging mode.  Close the listening socket, and start
682                  processing the connection without forking. */
683               debug("Server will not fork when running in debugging mode.");
684               close(listen_sock);
685               sock_in = newsock;
686               sock_out = newsock;
687               pid = getpid();
688               break;
689             }
690           else
691             {
692               /* Normal production daemon.  Fork, and have the child process
693                  the connection.  The parent continues listening. */
694               if ((pid = fork()) == 0)
695                 { 
696                   /* Child.  Close the listening socket, and start using
697                      the accepted socket.  Reinitialize logging (since our
698                      pid has changed).  We break out of the loop to handle
699                      the connection. */
700                   close(listen_sock);
701                   sock_in = newsock;
702                   sock_out = newsock;
703                   log_init(av0, options.log_level, options.log_facility, log_stderr);
704                   break;
705                 }
706             }
707
708           /* Parent.  Stay in the loop. */
709           if (pid < 0)
710             error("fork: %.100s", strerror(errno));
711           else
712             debug("Forked child %d.", pid);
713
714           /* Mark that the key has been used (it was "given" to the child). */
715           key_used = 1;
716
717           arc4random_stir();
718
719           /* Close the new socket (the child is now taking care of it). */
720           close(newsock);
721         }
722     }
723   
724   /* This is the child processing a new connection. */
725
726   /* Disable the key regeneration alarm.  We will not regenerate the key
727      since we are no longer in a position to give it to anyone.  We will
728      not restart on SIGHUP since it no longer makes sense. */
729   alarm(0);
730   signal(SIGALRM, SIG_DFL);
731   signal(SIGHUP, SIG_DFL);
732   signal(SIGTERM, SIG_DFL);
733   signal(SIGQUIT, SIG_DFL);
734   signal(SIGCHLD, SIG_DFL);
735
736   /* Set socket options for the connection.  We want the socket to close
737      as fast as possible without waiting for anything.  If the connection
738      is not a socket, these will do nothing. */
739   /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
740   linger.l_onoff = 1;
741   linger.l_linger = 5;
742   setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *)&linger, sizeof(linger));
743
744   /* Register our connection.  This turns encryption off because we do not
745      have a key. */
746   packet_set_connection(sock_in, sock_out);
747
748   remote_port = get_remote_port();
749
750   /* Check whether logins are denied from this host. */
751 #ifdef LIBWRAP
752   {
753     struct request_info req;
754
755     request_init(&req, RQ_DAEMON, av0, RQ_FILE, sock_in, NULL);
756     fromhost(&req);
757
758     if (!hosts_access(&req)) {
759       close(sock_in);
760       close(sock_out);
761       refuse(&req);
762     }
763     log("Connection from %.500s port %d", eval_client(&req), remote_port);
764   }
765 #else
766   /* Log the connection. */
767   log("Connection from %.100s port %d", get_remote_ipaddr(), remote_port);
768 #endif /* LIBWRAP */
769
770   /* We don\'t want to listen forever unless the other side successfully
771      authenticates itself.  So we set up an alarm which is cleared after
772      successful authentication.  A limit of zero indicates no limit.
773      Note that we don\'t set the alarm in debugging mode; it is just annoying
774      to have the server exit just when you are about to discover the bug. */
775   signal(SIGALRM, grace_alarm_handler);
776   if (!debug_flag)
777     alarm(options.login_grace_time);
778
779   /* Send our protocol version identification. */
780   snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", 
781           PROTOCOL_MAJOR, PROTOCOL_MINOR, SSH_VERSION);
782   if (write(sock_out, buf, strlen(buf)) != strlen(buf))
783     fatal("Could not write ident string.");
784
785   /* Read other side\'s version identification. */
786   for (i = 0; i < sizeof(buf) - 1; i++)
787     {
788       if (read(sock_in, &buf[i], 1) != 1)
789         fatal("Did not receive ident string.");
790       if (buf[i] == '\r')
791         {
792           buf[i] = '\n';
793           buf[i + 1] = 0;
794           break;
795         }
796       if (buf[i] == '\n')
797         {
798           /* buf[i] == '\n' */
799           buf[i + 1] = 0;
800           break;
801         }
802     }
803   buf[sizeof(buf) - 1] = 0;
804   
805   /* Check that the versions match.  In future this might accept several
806      versions and set appropriate flags to handle them. */
807   if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", &remote_major, &remote_minor, 
808              remote_version) != 3)
809     {
810       const char *s = "Protocol mismatch.\n";
811       (void) write(sock_out, s, strlen(s));
812       close(sock_in);
813       close(sock_out);
814       fatal("Bad protocol version identification: %.100s", buf);
815     }
816   debug("Client protocol version %d.%d; client software version %.100s",
817         remote_major, remote_minor, remote_version);
818   if (remote_major != PROTOCOL_MAJOR)
819     {
820       const char *s = "Protocol major versions differ.\n";
821       (void) write(sock_out, s, strlen(s));
822       close(sock_in);
823       close(sock_out);
824       fatal("Protocol major versions differ: %d vs. %d", 
825             PROTOCOL_MAJOR, remote_major);
826     }
827
828   /* Check that the client has sufficiently high software version. */
829   if (remote_major == 1 && remote_minor < 3)
830     packet_disconnect("Your ssh version is too old and is no longer supported.  Please install a newer version.");
831
832   if (remote_major == 1 && remote_minor == 3) {
833     enable_compat13();
834     if (strcmp(remote_version, "OpenSSH-1.1") != 0) {
835         debug("Agent forwarding disabled, remote version is not compatible.");
836         no_agent_forwarding_flag = 1;
837     }
838   }
839
840   /* Check that the connection comes from a privileged port.
841      Rhosts- and Rhosts-RSA-Authentication only make sense
842      from priviledged programs.
843      Of course, if the intruder has root access on his local machine,
844      he can connect from any port.  So do not use these authentication
845      methods from machines that you do not trust. */
846   if (remote_port >= IPPORT_RESERVED ||
847       remote_port <  IPPORT_RESERVED / 2)
848     {
849       options.rhosts_authentication = 0;
850       options.rhosts_rsa_authentication = 0;
851     }
852
853   packet_set_nonblocking();
854   
855   /* Handle the connection. */
856   do_connection();
857
858 #ifdef KRB4
859   /* Cleanup user's ticket cache file. */
860   if (options.kerberos_ticket_cleanup)
861     (void) dest_tkt();
862 #endif /* KRB4 */
863
864   /* Cleanup user's local Xauthority file. */
865   if (xauthfile) unlink(xauthfile);
866
867   /* The connection has been terminated. */
868   log("Closing connection to %.100s", inet_ntoa(sin.sin_addr));
869
870 #ifdef HAVE_LIBPAM
871   {
872     int retval;
873     
874     if (pamh != NULL)
875     {
876            debug("Closing PAM session.");
877       retval = pam_close_session((pam_handle_t *)pamh, 0);
878
879            debug("Terminating PAM library.");
880       if (pam_end((pam_handle_t *)pamh, retval) != PAM_SUCCESS)
881         log("Cannot release PAM authentication.");
882          
883       fatal_remove_cleanup(&pam_cleanup_proc, NULL);
884     }
885   }
886 #endif /* HAVE_LIBPAM */
887
888   packet_close();
889
890   exit(0);
891 }
892
893 /* Process an incoming connection.  Protocol version identifiers have already
894    been exchanged.  This sends server key and performs the key exchange.
895    Server and host keys will no longer be needed after this functions. */
896
897 void
898 do_connection()
899 {
900   int i, len;
901   BIGNUM *session_key_int;
902   unsigned char session_key[SSH_SESSION_KEY_LENGTH];
903   unsigned char check_bytes[8];
904   char *user;
905   unsigned int cipher_type, auth_mask, protocol_flags;
906   int plen, slen;
907   u_int32_t rand = 0;
908
909   /* Generate check bytes that the client must send back in the user packet
910      in order for it to be accepted; this is used to defy ip spoofing 
911      attacks.  Note that this only works against somebody doing IP spoofing 
912      from a remote machine; any machine on the local network can still see 
913      outgoing packets and catch the random cookie.  This only affects
914      rhosts authentication, and this is one of the reasons why it is
915      inherently insecure. */
916   for (i = 0; i < 8; i++) {
917     if (i % 4 == 0)
918       rand = arc4random();
919     check_bytes[i] = rand & 0xff;
920     rand >>= 8;
921   }
922   
923   /* Send our public key.  We include in the packet 64 bits of random
924      data that must be matched in the reply in order to prevent IP spoofing. */
925   packet_start(SSH_SMSG_PUBLIC_KEY);
926   for (i = 0; i < 8; i++)
927     packet_put_char(check_bytes[i]);
928
929   /* Store our public server RSA key. */
930   packet_put_int(BN_num_bits(public_key->n));
931   packet_put_bignum(public_key->e);
932   packet_put_bignum(public_key->n);
933
934   /* Store our public host RSA key. */
935   packet_put_int(BN_num_bits(sensitive_data.host_key->n));
936   packet_put_bignum(sensitive_data.host_key->e);
937   packet_put_bignum(sensitive_data.host_key->n);
938
939   /* Put protocol flags. */
940   packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
941
942   /* Declare which ciphers we support. */
943   packet_put_int(cipher_mask());
944
945   /* Declare supported authentication types. */
946   auth_mask = 0;
947   if (options.rhosts_authentication)
948     auth_mask |= 1 << SSH_AUTH_RHOSTS;
949   if (options.rhosts_rsa_authentication)
950     auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
951   if (options.rsa_authentication)
952     auth_mask |= 1 << SSH_AUTH_RSA;
953 #ifdef KRB4
954   if (options.kerberos_authentication)
955     auth_mask |= 1 << SSH_AUTH_KERBEROS;
956 #endif
957 #ifdef AFS
958   if (options.kerberos_tgt_passing)
959     auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
960   if (options.afs_token_passing)
961     auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
962 #endif
963   if (options.password_authentication)
964     auth_mask |= 1 << SSH_AUTH_PASSWORD;
965   packet_put_int(auth_mask);
966
967   /* Send the packet and wait for it to be sent. */
968   packet_send();
969   packet_write_wait();
970
971   debug("Sent %d bit public key and %d bit host key.", 
972         BN_num_bits(public_key->n), BN_num_bits(sensitive_data.host_key->n));
973
974   /* Read clients reply (cipher type and session key). */
975   packet_read_expect(&plen, SSH_CMSG_SESSION_KEY);
976
977   /* Get cipher type. */
978   cipher_type = packet_get_char();
979
980   /* Get check bytes from the packet.  These must match those we sent earlier
981      with the public key packet. */
982   for (i = 0; i < 8; i++)
983     if (check_bytes[i] != packet_get_char())
984       packet_disconnect("IP Spoofing check bytes do not match.");
985
986   debug("Encryption type: %.200s", cipher_name(cipher_type));
987
988   /* Get the encrypted integer. */
989   session_key_int = BN_new();
990   packet_get_bignum(session_key_int, &slen);
991
992   /* Get protocol flags. */
993   protocol_flags = packet_get_int();
994   packet_set_protocol_flags(protocol_flags);
995
996   packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY);
997
998   /* Decrypt it using our private server key and private host key (key with 
999      larger modulus first). */
1000   if (BN_cmp(sensitive_data.private_key->n, sensitive_data.host_key->n) > 0)
1001     {
1002       /* Private key has bigger modulus. */
1003       if (BN_num_bits(sensitive_data.private_key->n) < 
1004           BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
1005         fatal("do_connection: private_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1006               BN_num_bits(sensitive_data.private_key->n),
1007               BN_num_bits(sensitive_data.host_key->n),
1008               SSH_KEY_BITS_RESERVED);
1009       }
1010
1011       rsa_private_decrypt(session_key_int, session_key_int,
1012                           sensitive_data.private_key);
1013       rsa_private_decrypt(session_key_int, session_key_int,
1014                           sensitive_data.host_key);
1015     }
1016   else
1017     {
1018       /* Host key has bigger modulus (or they are equal). */
1019       if (BN_num_bits(sensitive_data.host_key->n) < 
1020           BN_num_bits(sensitive_data.private_key->n) + SSH_KEY_BITS_RESERVED) {
1021         fatal("do_connection: host_key %d < private_key %d + SSH_KEY_BITS_RESERVED %d",
1022               BN_num_bits(sensitive_data.host_key->n),
1023               BN_num_bits(sensitive_data.private_key->n),
1024               SSH_KEY_BITS_RESERVED);
1025       }
1026       rsa_private_decrypt(session_key_int, session_key_int,
1027                           sensitive_data.host_key);
1028       rsa_private_decrypt(session_key_int, session_key_int,
1029                           sensitive_data.private_key);
1030     }
1031
1032   /* Compute session id for this session. */
1033   compute_session_id(session_id, check_bytes,
1034                      BN_num_bits(sensitive_data.host_key->n),
1035                      sensitive_data.host_key->n, 
1036                      BN_num_bits(sensitive_data.private_key->n),
1037                      sensitive_data.private_key->n);
1038
1039   /* Extract session key from the decrypted integer.  The key is in the 
1040      least significant 256 bits of the integer; the first byte of the 
1041      key is in the highest bits. */
1042   BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1043   len = BN_num_bytes(session_key_int);
1044   if (len < 0 || len > sizeof(session_key))
1045     fatal("do_connection: bad len: session_key_int %d > sizeof(session_key) %d",
1046           len, sizeof(session_key));
1047   memset(session_key, 0, sizeof(session_key));
1048   BN_bn2bin(session_key_int, session_key + sizeof(session_key) - len);
1049   
1050   /* Xor the first 16 bytes of the session key with the session id. */
1051   for (i = 0; i < 16; i++)
1052     session_key[i] ^= session_id[i];
1053
1054   /* Destroy the decrypted integer.  It is no longer needed. */
1055   BN_clear_free(session_key_int);
1056   
1057   /* Set the session key.  From this on all communications will be
1058      encrypted. */
1059   packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, 
1060                             cipher_type, 0);
1061   
1062   /* Destroy our copy of the session key.  It is no longer needed. */
1063   memset(session_key, 0, sizeof(session_key));
1064
1065   debug("Received session key; encryption turned on.");
1066
1067   /* Send an acknowledgement packet.  Note that this packet is sent
1068      encrypted. */
1069   packet_start(SSH_SMSG_SUCCESS);
1070   packet_send();
1071   packet_write_wait();
1072
1073   /* Get the name of the user that we wish to log in as. */
1074   packet_read_expect(&plen, SSH_CMSG_USER);
1075
1076   /* Get the user name. */
1077   {
1078     int ulen;
1079     user = packet_get_string(&ulen);
1080     packet_integrity_check(plen, (4 + ulen), SSH_CMSG_USER);
1081   }
1082
1083   /* Destroy the private and public keys.  They will no longer be needed. */
1084   RSA_free(public_key);
1085   RSA_free(sensitive_data.private_key);
1086   RSA_free(sensitive_data.host_key);
1087
1088   setproctitle("%s", user);
1089   /* Do the authentication. */
1090   do_authentication(user);
1091 }
1092
1093 /* Check if the user is allowed to log in via ssh. If user is listed in
1094    DenyUsers or user's primary group is listed in DenyGroups, false will
1095    be returned. If AllowUsers isn't empty and user isn't listed there, or
1096    if AllowGroups isn't empty and user isn't listed there, false will be
1097    returned. Otherwise true is returned.
1098    XXX This function should also check if user has a valid shell */
1099
1100 static int
1101 allowed_user(struct passwd *pw)
1102 {
1103   struct group *grp;
1104   int i;
1105
1106   /* Shouldn't be called if pw is NULL, but better safe than sorry... */
1107   if (!pw)
1108     return 0;
1109
1110   /* XXX Should check for valid login shell */
1111
1112   /* Return false if user is listed in DenyUsers */
1113   if (options.num_deny_users > 0)
1114     {
1115       if (!pw->pw_name)
1116         return 0;
1117       for (i = 0; i < options.num_deny_users; i++)
1118         if (match_pattern(pw->pw_name, options.deny_users[i]))
1119           return 0;
1120     }
1121
1122   /* Return false if AllowUsers isn't empty and user isn't listed there */
1123   if (options.num_allow_users > 0)
1124     {
1125       if (!pw->pw_name)
1126         return 0;
1127       for (i = 0; i < options.num_allow_users; i++)
1128         if (match_pattern(pw->pw_name, options.allow_users[i]))
1129           break;
1130       /* i < options.num_allow_users iff we break for loop */
1131       if (i >= options.num_allow_users)
1132         return 0;
1133     }
1134
1135   /* Get the primary group name if we need it. Return false if it fails */
1136   if (options.num_deny_groups > 0 || options.num_allow_groups > 0 )
1137     {
1138       grp = getgrgid(pw->pw_gid);
1139       if (!grp)
1140         return 0;
1141
1142       /* Return false if user's group is listed in DenyGroups */
1143       if (options.num_deny_groups > 0)
1144         {
1145           if (!grp->gr_name)
1146             return 0;
1147           for (i = 0; i < options.num_deny_groups; i++)
1148             if (match_pattern(grp->gr_name, options.deny_groups[i]))
1149               return 0;
1150         }
1151
1152       /* Return false if AllowGroups isn't empty and user's group isn't
1153          listed there */
1154       if (options.num_allow_groups > 0)
1155         {
1156           if (!grp->gr_name)
1157             return 0;
1158           for (i = 0; i < options.num_allow_groups; i++)
1159             if (match_pattern(grp->gr_name, options.allow_groups[i]))
1160               break;
1161           /* i < options.num_allow_groups iff we break for loop */
1162           if (i >= options.num_allow_groups)
1163             return 0;
1164         }
1165     }
1166
1167   /* We found no reason not to let this user try to log on... */
1168   return 1;
1169 }
1170
1171 /* Performs authentication of an incoming connection.  Session key has already
1172    been exchanged and encryption is enabled.  User is the user name to log
1173    in as (received from the client). */
1174
1175 void
1176 do_authentication(char *user)
1177 {
1178   struct passwd *pw, pwcopy;
1179
1180 #ifdef AFS
1181   /* If machine has AFS, set process authentication group. */
1182   if (k_hasafs()) {
1183     k_setpag();
1184     k_unlog();
1185   }
1186 #endif /* AFS */
1187        
1188   /* Verify that the user is a valid user. */
1189   pw = getpwnam(user);
1190   if (!pw || !allowed_user(pw))
1191     do_fake_authloop(user);
1192   
1193   /* Take a copy of the returned structure. */
1194   memset(&pwcopy, 0, sizeof(pwcopy));
1195   pwcopy.pw_name = xstrdup(pw->pw_name);
1196   pwcopy.pw_passwd = xstrdup(pw->pw_passwd);
1197   pwcopy.pw_uid = pw->pw_uid;
1198   pwcopy.pw_gid = pw->pw_gid;
1199   pwcopy.pw_dir = xstrdup(pw->pw_dir);
1200   pwcopy.pw_shell = xstrdup(pw->pw_shell);
1201   pw = &pwcopy;
1202
1203 #ifdef HAVE_LIBPAM
1204   debug("Starting up PAM with username \"%.200s\"", pw->pw_name);
1205
1206   if (pam_start("sshd", pw->pw_name, &conv, (pam_handle_t**)&pamh) != PAM_SUCCESS)
1207     fatal("PAM initialisation failed: %.200s", pam_strerror((pam_handle_t *)pamh, pam_retval));
1208
1209   fatal_add_cleanup(&pam_cleanup_proc, NULL);
1210 #endif
1211
1212   /* If we are not running as root, the user must have the same uid as the
1213      server. */
1214   if (getuid() != 0 && pw->pw_uid != getuid())
1215     packet_disconnect("Cannot change user when server not running as root.");
1216
1217   debug("Attempting authentication for %.100s.", user);
1218
1219   /* If the user has no password, accept authentication immediately. */
1220   if (options.password_authentication &&
1221 #ifdef KRB4
1222       (!options.kerberos_authentication || options.kerberos_or_local_passwd) &&
1223 #endif /* KRB4 */
1224       auth_password(pw, ""))
1225     {
1226       /* Authentication with empty password succeeded. */
1227       debug("Login for user %.100s accepted without authentication.", user);
1228     } else {
1229       /* Loop until the user has been authenticated or the connection is closed,
1230          do_authloop() returns only if authentication is successfull */
1231       do_authloop(pw);
1232     }
1233
1234   /* XXX log unified auth message */
1235
1236   /* Check if the user is logging in as root and root logins are disallowed. */
1237   if (pw->pw_uid == 0 && !options.permit_root_login)
1238     {
1239       if (forced_command)
1240         log("Root login accepted for forced command.");
1241       else
1242         packet_disconnect("ROOT LOGIN REFUSED FROM %.200s", 
1243                           get_canonical_hostname());
1244     }
1245
1246   /* The user has been authenticated and accepted. */
1247   packet_start(SSH_SMSG_SUCCESS);
1248   packet_send();
1249   packet_write_wait();
1250
1251   /* Perform session preparation. */
1252   do_authenticated(pw);
1253 }
1254
1255 #define MAX_AUTH_FAILURES 5
1256
1257 /* read packets and try to authenticate local user *pw.
1258    return if authentication is successfull */
1259 void
1260 do_authloop(struct passwd *pw)
1261 {
1262   int authentication_failures = 0;
1263   unsigned int client_host_key_bits;
1264   BIGNUM *client_host_key_e, *client_host_key_n;
1265   BIGNUM *n;
1266   char *client_user, *password;
1267   int plen, dlen, nlen, ulen, elen;
1268
1269   /* Indicate that authentication is needed. */
1270   packet_start(SSH_SMSG_FAILURE);
1271   packet_send();
1272   packet_write_wait();
1273
1274   for (;;) {
1275     int authenticated = 0;
1276
1277     /* Get a packet from the client. */
1278     int type = packet_read(&plen);
1279   
1280     /* Process the packet. */
1281     switch (type)
1282       {
1283 #ifdef AFS
1284       case SSH_CMSG_HAVE_KERBEROS_TGT:
1285         if (!options.kerberos_tgt_passing)
1286           {
1287             /* packet_get_all(); */
1288             log("Kerberos tgt passing disabled.");
1289             break;
1290           }
1291         else {
1292           /* Accept Kerberos tgt. */
1293           char *tgt = packet_get_string(&dlen);
1294           packet_integrity_check(plen, 4 + dlen, type);
1295           if (!auth_kerberos_tgt(pw, tgt))
1296             debug("Kerberos tgt REFUSED for %s", pw->pw_name);
1297           xfree(tgt);
1298         }
1299         continue;
1300   
1301       case SSH_CMSG_HAVE_AFS_TOKEN:
1302         if (!options.afs_token_passing || !k_hasafs()) {
1303           /* packet_get_all(); */
1304           log("AFS token passing disabled.");
1305           break;
1306         }
1307         else {
1308           /* Accept AFS token. */
1309           char *token_string = packet_get_string(&dlen);
1310           packet_integrity_check(plen, 4 + dlen, type);
1311           if (!auth_afs_token(pw, token_string))
1312             debug("AFS token REFUSED for %s", pw->pw_name);
1313           xfree(token_string);
1314         }
1315         continue;
1316 #endif /* AFS */
1317             
1318 #ifdef KRB4
1319       case SSH_CMSG_AUTH_KERBEROS:
1320         if (!options.kerberos_authentication)
1321           {
1322             /* packet_get_all(); */
1323             log("Kerberos authentication disabled.");
1324             break;
1325           }
1326         else {
1327           /* Try Kerberos v4 authentication. */
1328           KTEXT_ST auth;
1329           char *tkt_user = NULL;
1330           char *kdata = packet_get_string((unsigned int *)&auth.length);
1331           packet_integrity_check(plen, 4 + auth.length, type);
1332   
1333           if (auth.length < MAX_KTXT_LEN)
1334             memcpy(auth.dat, kdata, auth.length);
1335           xfree(kdata);
1336           
1337           authenticated = auth_krb4(pw->pw_name, &auth, &tkt_user);
1338
1339           log("Kerberos authentication %s%s for account %s from %s", 
1340               authenticated ? "accepted " : "failed",
1341               tkt_user != NULL ? tkt_user : "",
1342               pw->pw_name, get_canonical_hostname());
1343           if (authenticated)
1344             xfree(tkt_user);
1345         }
1346         break;
1347 #endif /* KRB4 */
1348            
1349       case SSH_CMSG_AUTH_RHOSTS:
1350         if (!options.rhosts_authentication)
1351           {
1352             log("Rhosts authentication disabled.");
1353             break;
1354           }
1355   
1356         /* Get client user name.  Note that we just have to trust the client;
1357            this is one reason why rhosts authentication is insecure. 
1358            (Another is IP-spoofing on a local network.) */
1359         client_user = packet_get_string(&dlen);
1360         packet_integrity_check(plen, 4 + dlen, type);
1361   
1362         /* Try to authenticate using /etc/hosts.equiv and .rhosts. */
1363         authenticated = auth_rhosts(pw, client_user);
1364
1365         log("Rhosts authentication %s for %.100s, remote %.100s on %.700s.",
1366              authenticated ? "accepted" : "failed",
1367              pw->pw_name, client_user, get_canonical_hostname());
1368 #ifndef HAVE_LIBPAM
1369         xfree(client_user);
1370 #endif /* HAVE_LIBPAM */
1371         break;
1372   
1373       case SSH_CMSG_AUTH_RHOSTS_RSA:
1374         if (!options.rhosts_rsa_authentication)
1375           {
1376             log("Rhosts with RSA authentication disabled.");
1377             break;
1378           }
1379   
1380         /* Get client user name.  Note that we just have to trust
1381            the client; root on the client machine can claim to be
1382            any user. */
1383         client_user = packet_get_string(&ulen);
1384   
1385         /* Get the client host key. */
1386         client_host_key_e = BN_new();
1387         client_host_key_n = BN_new();
1388         client_host_key_bits = packet_get_int();
1389         packet_get_bignum(client_host_key_e, &elen);
1390         packet_get_bignum(client_host_key_n, &nlen);
1391   
1392         packet_integrity_check(plen, (4 + ulen) + 4 + elen + nlen, type);
1393   
1394         authenticated = auth_rhosts_rsa(pw, client_user, client_host_key_bits,
1395                                         client_host_key_e, client_host_key_n);
1396         log("Rhosts authentication %s for %.100s, remote %.100s.",
1397              authenticated ? "accepted" : "failed",
1398              pw->pw_name, client_user);
1399 #ifndef HAVE_LIBPAM
1400         xfree(client_user);
1401 #endif /* HAVE_LIBPAM */
1402         BN_clear_free(client_host_key_e);
1403         BN_clear_free(client_host_key_n);
1404         break;
1405         
1406       case SSH_CMSG_AUTH_RSA:
1407         if (!options.rsa_authentication)
1408           {
1409             log("RSA authentication disabled.");
1410             break;
1411           }
1412   
1413         /* RSA authentication requested. */
1414         n = BN_new();
1415         packet_get_bignum(n, &nlen);
1416         packet_integrity_check(plen, nlen, type);
1417         authenticated = auth_rsa(pw, n);
1418         BN_clear_free(n);
1419         log("RSA authentication %s for %.100s.",
1420             authenticated ? "accepted" : "failed",
1421             pw->pw_name);
1422         break;
1423   
1424       case SSH_CMSG_AUTH_PASSWORD:
1425         if (!options.password_authentication)
1426           {
1427             log("Password authentication disabled.");
1428             break;
1429           }
1430   
1431         /* Read user password.  It is in plain text, but was transmitted
1432            over the encrypted channel so it is not visible to an outside
1433            observer. */
1434         password = packet_get_string(&dlen);
1435         packet_integrity_check(plen, 4 + dlen, type);
1436   
1437 #ifdef HAVE_LIBPAM
1438         /* Do PAM auth with password */
1439         pampasswd = password;
1440         pam_retval = pam_authenticate((pam_handle_t *)pamh, 0);
1441         if (pam_retval == PAM_SUCCESS)
1442         {
1443           log("PAM Password authentication accepted for user \"%.100s\"", user);
1444           authenticated = 1;
1445           break;
1446         }
1447         
1448         log("PAM Password authentication for \"%.100s\" failed: %s", 
1449             user, pam_strerror((pam_handle_t *)pamh, pam_retval));
1450         break;
1451 #else /* HAVE_LIBPAM */
1452         /* Try authentication with the password. */
1453         authenticated = auth_password(pw, password);
1454
1455         memset(password, 0, strlen(password));
1456         xfree(password);
1457         break;
1458 #endif /* HAVE_LIBPAM */
1459   
1460       case SSH_CMSG_AUTH_TIS:
1461         /* TIS Authentication is unsupported */
1462         log("TIS authentication disabled.");
1463         break;
1464   
1465       default:
1466         /* Any unknown messages will be ignored (and failure returned)
1467            during authentication. */
1468         log("Unknown message during authentication: type %d", type);
1469         break; /* Respond with a failure message. */
1470       }
1471
1472     if (authenticated)
1473       break;
1474     if (++authentication_failures >= MAX_AUTH_FAILURES)
1475       packet_disconnect("Too many authentication failures for %.100s from %.200s", 
1476                          pw->pw_name, get_canonical_hostname());
1477     /* Send a message indicating that the authentication attempt failed. */
1478     packet_start(SSH_SMSG_FAILURE);
1479     packet_send();
1480     packet_write_wait();
1481   }
1482
1483 #ifdef HAVE_LIBPAM
1484   do_pam_account_and_session(pw->pw_name, client_user, get_canonical_hostname());
1485
1486   /* Clean up */
1487   if (client_user != NULL)
1488     xfree(client_user);
1489
1490   if (password != NULL)
1491   {
1492     memset(password, 0, strlen(password));
1493     xfree(password);
1494   }
1495 #endif /* HAVE_LIBPAM */
1496 }
1497
1498 /* The user does not exist or access is denied,
1499    but fake indication that authentication is needed. */
1500 void
1501 do_fake_authloop(char *user)
1502 {
1503   int authentication_failures = 0;
1504
1505   /* Indicate that authentication is needed. */
1506   packet_start(SSH_SMSG_FAILURE);
1507   packet_send();
1508   packet_write_wait();
1509
1510   /* Keep reading packets, and always respond with a failure.  This is to
1511      avoid disclosing whether such a user really exists. */
1512   for (;;)
1513     {
1514       /* Read a packet.  This will not return if the client disconnects. */
1515       int plen;
1516       int type = packet_read(&plen);
1517 #ifdef SKEY
1518       int passw_len;
1519       char *password, *skeyinfo;
1520       if (options.password_authentication &&
1521          options.skey_authentication == 1 &&
1522          type == SSH_CMSG_AUTH_PASSWORD &&
1523          (password = packet_get_string(&passw_len)) != NULL &&
1524          passw_len == 5 &&
1525          strncasecmp(password, "s/key", 5) == 0 &&
1526          (skeyinfo = skey_fake_keyinfo(user)) != NULL ){
1527         /* Send a fake s/key challenge. */
1528         packet_send_debug(skeyinfo);
1529       }
1530 #endif
1531       if (++authentication_failures >= MAX_AUTH_FAILURES)
1532         packet_disconnect("Too many authentication failures for %.100s from %.200s", 
1533                           user, get_canonical_hostname());
1534       /* Send failure.  This should be indistinguishable from a failed
1535          authentication. */
1536       packet_start(SSH_SMSG_FAILURE);
1537       packet_send();
1538       packet_write_wait();
1539     }
1540   /*NOTREACHED*/
1541   abort();
1542 }
1543
1544
1545 /* Remove local Xauthority file. */
1546 static void
1547 xauthfile_cleanup_proc(void *ignore)
1548 {
1549   debug("xauthfile_cleanup_proc called");
1550
1551   if (xauthfile != NULL) {
1552     unlink(xauthfile);
1553     xfree(xauthfile);
1554     xauthfile = NULL;
1555   }
1556 }
1557
1558 /* Prepares for an interactive session.  This is called after the user has
1559    been successfully authenticated.  During this message exchange, pseudo
1560    terminals are allocated, X11, TCP/IP, and authentication agent forwardings
1561    are requested, etc. */
1562
1563 void do_authenticated(struct passwd *pw)
1564 {
1565   int type;
1566   int compression_level = 0, enable_compression_after_reply = 0;
1567   int have_pty = 0, ptyfd = -1, ttyfd = -1, xauthfd = -1;
1568   int row, col, xpixel, ypixel, screen;
1569   char ttyname[64];
1570   char *command, *term = NULL, *display = NULL, *proto = NULL, *data = NULL;
1571   struct group *grp;
1572   gid_t tty_gid;
1573   mode_t tty_mode;
1574   int n_bytes;
1575   
1576   /* Cancel the alarm we set to limit the time taken for authentication. */
1577   alarm(0);
1578
1579   /* Inform the channel mechanism that we are the server side and that
1580      the client may request to connect to any port at all.  (The user could
1581      do it anyway, and we wouldn\'t know what is permitted except by the
1582      client telling us, so we can equally well trust the client not to request
1583      anything bogus.) */
1584   channel_permit_all_opens();
1585
1586   /* We stay in this loop until the client requests to execute a shell or a
1587      command. */
1588   while (1)
1589     {
1590       int plen, dlen;
1591
1592       /* Get a packet from the client. */
1593       type = packet_read(&plen);
1594       
1595       /* Process the packet. */
1596       switch (type)
1597         {
1598         case SSH_CMSG_REQUEST_COMPRESSION:
1599           packet_integrity_check(plen, 4, type);
1600           compression_level = packet_get_int();
1601           if (compression_level < 1 || compression_level > 9)
1602             {
1603               packet_send_debug("Received illegal compression level %d.",
1604                                 compression_level);
1605               goto fail;
1606             }
1607           /* Enable compression after we have responded with SUCCESS. */
1608           enable_compression_after_reply = 1;
1609           break;
1610
1611         case SSH_CMSG_REQUEST_PTY:
1612           if (no_pty_flag)
1613             {
1614               debug("Allocating a pty not permitted for this authentication.");
1615               goto fail;
1616             }
1617           if (have_pty)
1618             packet_disconnect("Protocol error: you already have a pty.");
1619
1620           debug("Allocating pty.");
1621
1622           /* Allocate a pty and open it. */
1623           if (!pty_allocate(&ptyfd, &ttyfd, ttyname))
1624             {
1625               error("Failed to allocate pty.");
1626               goto fail;
1627             }
1628
1629           /* Determine the group to make the owner of the tty. */
1630           grp = getgrnam("tty");
1631           if (grp)
1632             {
1633               tty_gid = grp->gr_gid;
1634               tty_mode = S_IRUSR|S_IWUSR|S_IWGRP;
1635             }
1636           else
1637             {
1638               tty_gid = pw->pw_gid;
1639               tty_mode = S_IRUSR|S_IWUSR|S_IWGRP|S_IWOTH;
1640             }
1641
1642           /* Change ownership of the tty. */
1643           if (chown(ttyname, pw->pw_uid, tty_gid) < 0)
1644             fatal("chown(%.100s, %d, %d) failed: %.100s",
1645                   ttyname, pw->pw_uid, tty_gid, strerror(errno));
1646           if (chmod(ttyname, tty_mode) < 0)
1647             fatal("chmod(%.100s, 0%o) failed: %.100s",
1648                   ttyname, tty_mode, strerror(errno));
1649
1650           /* Get TERM from the packet.  Note that the value may be of arbitrary
1651              length. */
1652
1653           term = packet_get_string(&dlen);
1654           packet_integrity_check(dlen, strlen(term), type);
1655           /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
1656           /* Remaining bytes */
1657           n_bytes = plen - (4 + dlen + 4*4);
1658           
1659           if (strcmp(term, "") == 0)
1660             term = NULL;
1661
1662           /* Get window size from the packet. */
1663           row = packet_get_int();
1664           col = packet_get_int();
1665           xpixel = packet_get_int();
1666           ypixel = packet_get_int();
1667           pty_change_window_size(ptyfd, row, col, xpixel, ypixel);
1668
1669           /* Get tty modes from the packet. */
1670           tty_parse_modes(ttyfd, &n_bytes);
1671           packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type);
1672
1673           /* Indicate that we now have a pty. */
1674           have_pty = 1;
1675           break;
1676
1677         case SSH_CMSG_X11_REQUEST_FORWARDING:
1678           if (!options.x11_forwarding)
1679             {
1680               packet_send_debug("X11 forwarding disabled in server configuration file.");
1681               goto fail;
1682             }
1683 #ifdef XAUTH_PATH
1684           if (no_x11_forwarding_flag)
1685             {
1686               packet_send_debug("X11 forwarding not permitted for this authentication.");
1687               goto fail;
1688             }
1689           debug("Received request for X11 forwarding with auth spoofing.");
1690           if (display)
1691             packet_disconnect("Protocol error: X11 display already set.");
1692           {
1693             int proto_len, data_len;
1694             proto = packet_get_string(&proto_len);
1695             data = packet_get_string(&data_len);
1696             packet_integrity_check(plen, 4+proto_len + 4+data_len + 4, type);
1697           }
1698           if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
1699             screen = packet_get_int();
1700           else
1701             screen = 0;
1702           display = x11_create_display_inet(screen);
1703           if (!display)
1704             goto fail;
1705
1706           /* Setup to always have a local .Xauthority. */
1707           xauthfile = xmalloc(MAXPATHLEN);
1708           snprintf(xauthfile, MAXPATHLEN, "/tmp/XauthXXXXXX");
1709           
1710           if ((xauthfd = mkstemp(xauthfile)) != -1) {
1711             fchown(xauthfd, pw->pw_uid, pw->pw_gid);
1712             close(xauthfd);
1713             fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
1714           }
1715           else {
1716             xfree(xauthfile);
1717             xauthfile = NULL;
1718           }
1719           break;
1720 #else /* XAUTH_PATH */
1721           /* No xauth program; we won't accept forwarding with spoofing. */
1722           packet_send_debug("No xauth program; cannot forward with spoofing.");
1723           goto fail;
1724 #endif /* XAUTH_PATH */
1725
1726         case SSH_CMSG_AGENT_REQUEST_FORWARDING:
1727           if (no_agent_forwarding_flag)
1728             {
1729               debug("Authentication agent forwarding not permitted for this authentication.");
1730               goto fail;
1731             }
1732           debug("Received authentication agent forwarding request.");
1733           auth_input_request_forwarding(pw);
1734           break;
1735
1736         case SSH_CMSG_PORT_FORWARD_REQUEST:
1737           if (no_port_forwarding_flag)
1738             {
1739               debug("Port forwarding not permitted for this authentication.");
1740               goto fail;
1741             }
1742           debug("Received TCP/IP port forwarding request.");
1743           channel_input_port_forward_request(pw->pw_uid == 0);
1744           break;
1745
1746         case SSH_CMSG_EXEC_SHELL:
1747           /* Set interactive/non-interactive mode. */
1748           packet_set_interactive(have_pty || display != NULL, 
1749                                  options.keepalives);
1750             
1751           if (forced_command != NULL)
1752             goto do_forced_command;
1753           debug("Forking shell.");
1754           packet_integrity_check(plen, 0, type);
1755           if (have_pty)
1756             do_exec_pty(NULL, ptyfd, ttyfd, ttyname, pw, term, display, proto,
1757                         data);
1758           else
1759             do_exec_no_pty(NULL, pw, display, proto, data);
1760           return;
1761
1762         case SSH_CMSG_EXEC_CMD:
1763           /* Set interactive/non-interactive mode. */
1764           packet_set_interactive(have_pty || display != NULL,
1765                                  options.keepalives);
1766
1767           if (forced_command != NULL)
1768             goto do_forced_command;
1769           /* Get command from the packet. */
1770           {
1771             int dlen;
1772             command = packet_get_string(&dlen);
1773             debug("Executing command '%.500s'", command);
1774             packet_integrity_check(plen, 4 + dlen, type);
1775           }
1776           if (have_pty)
1777             do_exec_pty(command, ptyfd, ttyfd, ttyname, pw, term, display,
1778                         proto, data);
1779           else
1780             do_exec_no_pty(command, pw, display, proto, data);
1781           xfree(command);
1782           return;
1783
1784         case SSH_CMSG_MAX_PACKET_SIZE:
1785           debug("The server does not support limiting packet size.");
1786           goto fail;
1787
1788         default:
1789           /* Any unknown messages in this phase are ignored, and a failure
1790              message is returned. */
1791           log("Unknown packet type received after authentication: %d", type);
1792           goto fail;
1793         }
1794
1795       /* The request was successfully processed. */
1796       packet_start(SSH_SMSG_SUCCESS);
1797       packet_send();
1798       packet_write_wait();
1799
1800       /* Enable compression now that we have replied if appropriate. */
1801       if (enable_compression_after_reply)
1802         {
1803           enable_compression_after_reply = 0;
1804           packet_start_compression(compression_level);
1805         }
1806
1807       continue;
1808
1809     fail:
1810       /* The request failed. */
1811       packet_start(SSH_SMSG_FAILURE);
1812       packet_send();
1813       packet_write_wait();
1814       continue;
1815       
1816     do_forced_command:
1817       /* There is a forced command specified for this login.  Execute it. */
1818       debug("Executing forced command: %.900s", forced_command);
1819       if (have_pty)
1820         do_exec_pty(forced_command, ptyfd, ttyfd, ttyname, pw, term, display,
1821                     proto, data);
1822       else
1823         do_exec_no_pty(forced_command, pw, display, proto, data);
1824       return;
1825     }
1826 }
1827
1828 /* This is called to fork and execute a command when we have no tty.  This
1829    will call do_child from the child, and server_loop from the parent after
1830    setting up file descriptors and such. */
1831
1832 void do_exec_no_pty(const char *command, struct passwd *pw,
1833                     const char *display, const char *auth_proto,
1834                     const char *auth_data)
1835 {  
1836   int pid;
1837
1838 #ifdef USE_PIPES
1839   int pin[2], pout[2], perr[2];
1840   /* Allocate pipes for communicating with the program. */
1841   if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
1842     packet_disconnect("Could not create pipes: %.100s",
1843                       strerror(errno));
1844 #else /* USE_PIPES */
1845   int inout[2], err[2];
1846   /* Uses socket pairs to communicate with the program. */
1847   if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
1848       socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
1849     packet_disconnect("Could not create socket pairs: %.100s",
1850                       strerror(errno));
1851 #endif /* USE_PIPES */
1852   
1853   setproctitle("%s@notty", pw->pw_name);
1854
1855   /* Fork the child. */
1856   if ((pid = fork()) == 0)
1857     {
1858       /* Child.  Reinitialize the log since the pid has changed. */
1859       log_init(av0, options.log_level, options.log_facility, log_stderr);
1860
1861       /* Create a new session and process group since the 4.4BSD setlogin()
1862          affects the entire process group. */
1863       if (setsid() < 0)
1864         error("setsid failed: %.100s", strerror(errno));
1865
1866 #ifdef USE_PIPES
1867       /* Redirect stdin.  We close the parent side of the socket pair,
1868          and make the child side the standard input. */
1869       close(pin[1]);
1870       if (dup2(pin[0], 0) < 0)
1871         perror("dup2 stdin");
1872       close(pin[0]);
1873       
1874       /* Redirect stdout. */
1875       close(pout[0]);
1876       if (dup2(pout[1], 1) < 0)
1877         perror("dup2 stdout");
1878       close(pout[1]);
1879
1880       /* Redirect stderr. */
1881       close(perr[0]);
1882       if (dup2(perr[1], 2) < 0)
1883         perror("dup2 stderr");
1884       close(perr[1]);
1885 #else /* USE_PIPES */
1886       /* Redirect stdin, stdout, and stderr.  Stdin and stdout will use the
1887          same socket, as some programs (particularly rdist) seem to depend
1888          on it. */
1889       close(inout[1]);
1890       close(err[1]);
1891       if (dup2(inout[0], 0) < 0) /* stdin */
1892         perror("dup2 stdin");
1893       if (dup2(inout[0], 1) < 0) /* stdout.  Note: same socket as stdin. */
1894         perror("dup2 stdout");
1895       if (dup2(err[0], 2) < 0) /* stderr */
1896         perror("dup2 stderr");
1897 #endif /* USE_PIPES */
1898
1899       /* Do processing for the child (exec command etc). */
1900       do_child(command, pw, NULL, display, auth_proto, auth_data, NULL);
1901       /*NOTREACHED*/
1902     }
1903   if (pid < 0)
1904     packet_disconnect("fork failed: %.100s", strerror(errno));
1905 #ifdef USE_PIPES
1906   /* We are the parent.  Close the child sides of the pipes. */
1907   close(pin[0]);
1908   close(pout[1]);
1909   close(perr[1]);
1910
1911   /* Enter the interactive session. */
1912   server_loop(pid, pin[1], pout[0], perr[0]);
1913   /* server_loop has closed pin[1], pout[1], and perr[1]. */
1914 #else /* USE_PIPES */
1915   /* We are the parent.  Close the child sides of the socket pairs. */
1916   close(inout[0]);
1917   close(err[0]);
1918   
1919   /* Enter the interactive session.  Note: server_loop must be able to handle
1920      the case that fdin and fdout are the same. */
1921   server_loop(pid, inout[1], inout[1], err[1]);
1922   /* server_loop has closed inout[1] and err[1]. */
1923 #endif /* USE_PIPES */
1924 }
1925
1926 struct pty_cleanup_context
1927 {
1928   const char *ttyname;
1929   int pid;
1930 };
1931
1932 /* Function to perform cleanup if we get aborted abnormally (e.g., due to a
1933    dropped connection). */
1934
1935 void pty_cleanup_proc(void *context)
1936 {
1937   struct pty_cleanup_context *cu = context;
1938
1939   debug("pty_cleanup_proc called");
1940
1941   /* Record that the user has logged out. */
1942   record_logout(cu->pid, cu->ttyname);
1943
1944   /* Release the pseudo-tty. */
1945   pty_release(cu->ttyname);
1946 }
1947
1948 /* This is called to fork and execute a command when we have a tty.  This
1949    will call do_child from the child, and server_loop from the parent after
1950    setting up file descriptors, controlling tty, updating wtmp, utmp,
1951    lastlog, and other such operations. */
1952
1953 void do_exec_pty(const char *command, int ptyfd, int ttyfd, 
1954                  const char *ttyname, struct passwd *pw, const char *term,
1955                  const char *display, const char *auth_proto, 
1956                  const char *auth_data)
1957 {
1958   int pid, fdout;
1959   const char *hostname;
1960   time_t last_login_time;
1961   char buf[100], *time_string;
1962   FILE *f;
1963   char line[256];
1964   struct stat st;
1965   int quiet_login;
1966   struct sockaddr_in from;
1967   int fromlen;
1968   struct pty_cleanup_context cleanup_context;
1969
1970   /* Get remote host name. */
1971   hostname = get_canonical_hostname();
1972
1973   /* Get the time when the user last logged in.  Buf will be set to contain
1974      the hostname the last login was from. */
1975   if(!options.use_login) {
1976     last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
1977                                           buf, sizeof(buf));
1978   }
1979
1980   setproctitle("%s@%s", pw->pw_name, strrchr(ttyname, '/') + 1);
1981
1982   /* Fork the child. */
1983   if ((pid = fork()) == 0)
1984     { 
1985       pid = getpid();
1986
1987       /* Child.  Reinitialize the log because the pid has changed. */
1988       log_init(av0, options.log_level, options.log_facility, log_stderr);
1989
1990       /* Close the master side of the pseudo tty. */
1991       close(ptyfd);
1992
1993       /* Make the pseudo tty our controlling tty. */
1994       pty_make_controlling_tty(&ttyfd, ttyname);
1995
1996       /* Redirect stdin from the pseudo tty. */
1997       if (dup2(ttyfd, fileno(stdin)) < 0)
1998         error("dup2 stdin failed: %.100s", strerror(errno));
1999
2000       /* Redirect stdout to the pseudo tty. */
2001       if (dup2(ttyfd, fileno(stdout)) < 0)
2002         error("dup2 stdin failed: %.100s", strerror(errno));
2003
2004       /* Redirect stderr to the pseudo tty. */
2005       if (dup2(ttyfd, fileno(stderr)) < 0)
2006         error("dup2 stdin failed: %.100s", strerror(errno));
2007
2008       /* Close the extra descriptor for the pseudo tty. */
2009       close(ttyfd);
2010
2011       /* Get IP address of client.  This is needed because we want to record 
2012          where the user logged in from.  If the connection is not a socket,
2013          let the ip address be 0.0.0.0. */
2014       memset(&from, 0, sizeof(from));
2015       if (packet_get_connection_in() == packet_get_connection_out())
2016         {
2017           fromlen = sizeof(from);
2018           if (getpeername(packet_get_connection_in(),
2019                           (struct sockaddr *)&from, &fromlen) < 0) {
2020             debug("getpeername: %.100s", strerror(errno));
2021             fatal_cleanup();
2022           }
2023         }
2024
2025       /* Record that there was a login on that terminal. */
2026       record_login(pid, ttyname, pw->pw_name, pw->pw_uid, hostname, 
2027                    &from);
2028
2029       /* Check if .hushlogin exists. */
2030       snprintf(line, sizeof line, "%.200s/.hushlogin", pw->pw_dir);
2031       quiet_login = stat(line, &st) >= 0;
2032
2033 #ifdef HAVE_LIBPAM
2034       /* output the results of the pamconv() */
2035       if (!quiet_login && pamconv_msg != NULL)
2036         fprintf(stderr, pamconv_msg);
2037 #endif
2038         
2039       /* If the user has logged in before, display the time of last login. 
2040          However, don't display anything extra if a command has been 
2041          specified (so that ssh can be used to execute commands on a remote
2042          machine without users knowing they are going to another machine). 
2043          Login(1) will do this for us as well, so check if login(1) is used */
2044       if (command == NULL && last_login_time != 0 && !quiet_login && 
2045           !options.use_login)
2046         {
2047           /* Convert the date to a string. */
2048           time_string = ctime(&last_login_time);
2049           /* Remove the trailing newline. */
2050           if (strchr(time_string, '\n'))
2051             *strchr(time_string, '\n') = 0;
2052           /* Display the last login time.  Host if displayed if known. */
2053           if (strcmp(buf, "") == 0)
2054             printf("Last login: %s\r\n", time_string);
2055           else
2056             printf("Last login: %s from %s\r\n", time_string, buf);
2057         }
2058
2059       /* Print /etc/motd unless a command was specified or printing it was
2060          disabled in server options or login(1) will be used.  Note that 
2061          some machines appear to print it in /etc/profile or similar. */
2062       if (command == NULL && options.print_motd && !quiet_login && 
2063           !options.use_login)
2064         {
2065           /* Print /etc/motd if it exists. */
2066           f = fopen("/etc/motd", "r");
2067           if (f)
2068             {
2069               while (fgets(line, sizeof(line), f))
2070                 fputs(line, stdout);
2071               fclose(f);
2072             }
2073         }
2074
2075       /* Do common processing for the child, such as execing the command. */
2076       do_child(command, pw, term, display, auth_proto, auth_data, ttyname);
2077       /*NOTREACHED*/
2078     }
2079   if (pid < 0)
2080     packet_disconnect("fork failed: %.100s", strerror(errno));
2081   /* Parent.  Close the slave side of the pseudo tty. */
2082   close(ttyfd);
2083   
2084   /* Create another descriptor of the pty master side for use as the standard
2085      input.  We could use the original descriptor, but this simplifies code
2086      in server_loop.  The descriptor is bidirectional. */
2087   fdout = dup(ptyfd);
2088   if (fdout < 0)
2089     packet_disconnect("dup failed: %.100s", strerror(errno));
2090
2091   /* Add a cleanup function to clear the utmp entry and record logout time
2092      in case we call fatal() (e.g., the connection gets closed). */
2093   cleanup_context.pid = pid;
2094   cleanup_context.ttyname = ttyname;
2095   fatal_add_cleanup(pty_cleanup_proc, (void *)&cleanup_context);
2096
2097   /* Enter interactive session. */
2098   server_loop(pid, ptyfd, fdout, -1);
2099   /* server_loop has not closed ptyfd and fdout. */
2100
2101   /* Cancel the cleanup function. */
2102   fatal_remove_cleanup(pty_cleanup_proc, (void *)&cleanup_context);
2103
2104   /* Record that the user has logged out. */
2105   record_logout(pid, ttyname);
2106
2107   /* Release the pseudo-tty. */
2108   pty_release(ttyname);
2109
2110   /* Close the server side of the socket pairs.  We must do this after the
2111      pty cleanup, so that another process doesn't get this pty while we're
2112      still cleaning up. */
2113   close(ptyfd);
2114   close(fdout);
2115 }
2116
2117 /* Sets the value of the given variable in the environment.  If the variable
2118    already exists, its value is overriden. */
2119
2120 void child_set_env(char ***envp, unsigned int *envsizep, const char *name,
2121                    const char *value)
2122 {
2123   unsigned int i, namelen;
2124   char **env;
2125
2126   /* Find the slot where the value should be stored.  If the variable already
2127      exists, we reuse the slot; otherwise we append a new slot at the end
2128      of the array, expanding if necessary. */
2129   env = *envp;
2130   namelen = strlen(name);
2131   for (i = 0; env[i]; i++)
2132     if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
2133       break;
2134   if (env[i])
2135     {
2136       /* Name already exists.  Reuse the slot. */
2137       xfree(env[i]);
2138     }
2139   else
2140     {
2141       /* New variable.  Expand the array if necessary. */
2142       if (i >= (*envsizep) - 1)
2143         {
2144           (*envsizep) += 50;
2145           env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
2146         }
2147
2148       /* Need to set the NULL pointer at end of array beyond the new 
2149          slot. */
2150       env[i + 1] = NULL;
2151     }
2152
2153   /* Allocate space and format the variable in the appropriate slot. */
2154   env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
2155   snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
2156 }
2157
2158 /* Reads environment variables from the given file and adds/overrides them
2159    into the environment.  If the file does not exist, this does nothing.
2160    Otherwise, it must consist of empty lines, comments (line starts with '#')
2161    and assignments of the form name=value.  No other forms are allowed. */
2162
2163 void read_environment_file(char ***env, unsigned int *envsize,
2164                            const char *filename)
2165 {
2166   FILE *f;
2167   char buf[4096];
2168   char *cp, *value;
2169   
2170   /* Open the environment file. */
2171   f = fopen(filename, "r");
2172   if (!f)
2173     return;  /* Not found. */
2174   
2175   /* Process each line. */
2176   while (fgets(buf, sizeof(buf), f))
2177     {
2178       /* Skip leading whitespace. */
2179       for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
2180         ;
2181
2182       /* Ignore empty and comment lines. */
2183       if (!*cp || *cp == '#' || *cp == '\n')
2184         continue;
2185
2186       /* Remove newline. */
2187       if (strchr(cp, '\n'))
2188         *strchr(cp, '\n') = '\0';
2189
2190       /* Find the equals sign.  Its lack indicates badly formatted line. */
2191       value = strchr(cp, '=');
2192       if (value == NULL)
2193         {
2194           fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
2195           continue;
2196         }
2197
2198       /* Replace the equals sign by nul, and advance value to the value 
2199          string. */
2200       *value = '\0';
2201       value++;
2202
2203       /* Set the value in environment. */
2204       child_set_env(env, envsize, cp, value);
2205     }
2206   
2207   fclose(f);
2208 }
2209
2210 /* Performs common processing for the child, such as setting up the 
2211    environment, closing extra file descriptors, setting the user and group 
2212    ids, and executing the command or shell. */
2213
2214 void do_child(const char *command, struct passwd *pw, const char *term,
2215               const char *display, const char *auth_proto, 
2216               const char *auth_data, const char *ttyname)
2217 {
2218   const char *shell, *cp = NULL;
2219   char buf[256];
2220   FILE *f;
2221   unsigned int envsize, i;
2222   char **env;
2223   extern char **environ;
2224   struct stat st;
2225   char *argv[10];
2226
2227 #ifndef HAVE_LIBPAM /* pam_nologin handles this */
2228   /* Check /etc/nologin. */
2229   f = fopen("/etc/nologin", "r");
2230   if (f)
2231     { /* /etc/nologin exists.  Print its contents and exit. */
2232       while (fgets(buf, sizeof(buf), f))
2233         fputs(buf, stderr);
2234       fclose(f);
2235       if (pw->pw_uid != 0)
2236         exit(254);
2237     }
2238 #endif /* HAVE_LIBPAM */
2239
2240 #ifdef HAVE_SETLOGIN
2241   /* Set login name in the kernel. */
2242   if (setlogin(pw->pw_name) < 0)
2243     error("setlogin failed: %s", strerror(errno));
2244 #endif /* HAVE_SETLOGIN */
2245
2246   /* Set uid, gid, and groups. */
2247   /* Login(1) does this as well, and it needs uid 0 for the "-h" switch,
2248      so we let login(1) to this for us. */
2249   if(!options.use_login) {
2250     if (getuid() == 0 || geteuid() == 0)
2251       { 
2252         if (setgid(pw->pw_gid) < 0)
2253           {
2254             perror("setgid");
2255             exit(1);
2256           }
2257         /* Initialize the group list. */
2258         if (initgroups(pw->pw_name, pw->pw_gid) < 0)
2259           {
2260             perror("initgroups");
2261             exit(1);
2262           }
2263         endgrent();
2264    
2265         /* Permanently switch to the desired uid. */
2266         permanently_set_uid(pw->pw_uid);
2267       }
2268    
2269     if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
2270       fatal("Failed to set uids to %d.", (int)pw->pw_uid);
2271   }
2272
2273   /* Get the shell from the password data.  An empty shell field is legal,
2274      and means /bin/sh. */
2275   shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
2276
2277 #ifdef AFS
2278   /* Try to get AFS tokens for the local cell. */
2279   if (k_hasafs()) {
2280     char cell[64];
2281     
2282     if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
2283       krb_afslog(cell, 0);
2284
2285     krb_afslog(0, 0);
2286   }
2287 #endif /* AFS */
2288   
2289   /* Initialize the environment.  In the first part we allocate space for
2290      all environment variables. */
2291   envsize = 100;
2292   env = xmalloc(envsize * sizeof(char *));
2293   env[0] = NULL;
2294
2295   if(!options.use_login) {
2296     /* Set basic environment. */
2297     child_set_env(&env, &envsize, "USER", pw->pw_name);
2298     child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
2299     child_set_env(&env, &envsize, "HOME", pw->pw_dir);
2300     child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
2301    
2302     snprintf(buf, sizeof buf, "%.200s/%.50s",
2303       _PATH_MAILDIR, pw->pw_name);
2304     child_set_env(&env, &envsize, "MAIL", buf);
2305    
2306     /* Normal systems set SHELL by default. */
2307     child_set_env(&env, &envsize, "SHELL", shell);
2308   }
2309
2310   /* Let it inherit timezone if we have one. */
2311   if (getenv("TZ"))
2312     child_set_env(&env, &envsize, "TZ", getenv("TZ"));
2313
2314   /* Set custom environment options from RSA authentication. */
2315   while (custom_environment) 
2316     {
2317       struct envstring *ce = custom_environment;
2318       char *s = ce->s;
2319       int i;
2320       for (i = 0; s[i] != '=' && s[i]; i++)
2321         ;
2322       if (s[i] == '=') 
2323         {
2324           s[i] = 0;
2325           child_set_env(&env, &envsize, s, s + i + 1);
2326         }
2327       custom_environment = ce->next;
2328       xfree(ce->s);
2329       xfree(ce);
2330     }
2331
2332   /* Set SSH_CLIENT. */
2333   snprintf(buf, sizeof buf, "%.50s %d %d", 
2334           get_remote_ipaddr(), get_remote_port(), options.port);
2335   child_set_env(&env, &envsize, "SSH_CLIENT", buf);
2336
2337   /* Set SSH_TTY if we have a pty. */
2338   if (ttyname)
2339     child_set_env(&env, &envsize, "SSH_TTY", ttyname);
2340
2341   /* Set TERM if we have a pty. */
2342   if (term)
2343     child_set_env(&env, &envsize, "TERM", term);
2344
2345   /* Set DISPLAY if we have one. */
2346   if (display)
2347     child_set_env(&env, &envsize, "DISPLAY", display);
2348
2349 #ifdef KRB4
2350   {
2351     extern char *ticket;
2352     
2353     if (ticket)
2354       child_set_env(&env, &envsize, "KRBTKFILE", ticket);
2355   }
2356 #endif /* KRB4 */
2357
2358 #ifdef HAVE_LIBPAM
2359   /* Pull in any environment variables that may have been set by PAM. */
2360   {
2361     char *equal_sign, var_name[256], var_val[256];
2362     long this_var;
2363     char **pam_env = pam_getenvlist((pam_handle_t *)pamh);
2364     for(this_var = 0; pam_env && pam_env[this_var]; this_var++)
2365       {
2366         if(strlen(pam_env[this_var]) < (sizeof(var_name) - 1))
2367           if((equal_sign = strstr(pam_env[this_var], "=")) != NULL)
2368             {
2369               memset(var_name, 0, sizeof(var_name));
2370               memset(var_val, 0, sizeof(var_val));
2371               strncpy(var_name, pam_env[this_var],
2372                       equal_sign - pam_env[this_var]);
2373               strcpy(var_val, equal_sign + 1);
2374               child_set_env(&env, &envsize, var_name, var_val);
2375             }
2376       }
2377   }
2378 #endif /* HAVE_LIBPAM */
2379
2380   /* Set XAUTHORITY to always be a local file. */
2381   if (xauthfile)
2382       child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
2383
2384   /* Set variable for forwarded authentication connection, if we have one. */
2385   if (auth_get_socket_name() != NULL)
2386       child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME, 
2387                     auth_get_socket_name());
2388
2389   /* Read $HOME/.ssh/environment. */
2390   if(!options.use_login) {
2391     snprintf(buf, sizeof buf, "%.200s/.ssh/environment", pw->pw_dir);
2392     read_environment_file(&env, &envsize, buf);
2393   }
2394
2395   /* If debugging, dump the environment to stderr. */
2396   if (debug_flag)
2397     {
2398       fprintf(stderr, "Environment:\n");
2399       for (i = 0; env[i]; i++)
2400         fprintf(stderr, "  %.200s\n", env[i]);
2401     }
2402
2403   /* Close the connection descriptors; note that this is the child, and the 
2404      server will still have the socket open, and it is important that we
2405      do not shutdown it.  Note that the descriptors cannot be closed before
2406      building the environment, as we call get_remote_ipaddr there. */
2407   if (packet_get_connection_in() == packet_get_connection_out())
2408     close(packet_get_connection_in());
2409   else
2410     {
2411       close(packet_get_connection_in());
2412       close(packet_get_connection_out());
2413     }
2414   /* Close all descriptors related to channels.  They will still remain
2415      open in the parent. */
2416   channel_close_all();
2417
2418   /* Close any extra file descriptors.  Note that there may still be
2419      descriptors left by system functions.  They will be closed later. */
2420   endpwent();
2421   endhostent();
2422
2423   /* Close any extra open file descriptors so that we don\'t have them
2424      hanging around in clients.  Note that we want to do this after
2425      initgroups, because at least on Solaris 2.3 it leaves file descriptors
2426      open. */
2427   for (i = 3; i < 64; i++)
2428     close(i);
2429
2430   /* Change current directory to the user\'s home directory. */
2431   if (chdir(pw->pw_dir) < 0)
2432     fprintf(stderr, "Could not chdir to home directory %s: %s\n",
2433             pw->pw_dir, strerror(errno));
2434
2435   /* Must take new environment into use so that .ssh/rc, /etc/sshrc and
2436      xauth are run in the proper environment. */
2437   environ = env;
2438
2439   /* Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
2440      in this order). */
2441   if(!options.use_login) {
2442     if (stat(SSH_USER_RC, &st) >= 0)
2443       {
2444         if (debug_flag)
2445         fprintf(stderr, "Running /bin/sh %s\n", SSH_USER_RC);
2446  
2447         f = popen("/bin/sh " SSH_USER_RC, "w");
2448         if (f)
2449         {
2450           if (auth_proto != NULL && auth_data != NULL)
2451             fprintf(f, "%s %s\n", auth_proto, auth_data);
2452           pclose(f);
2453         }
2454         else
2455         fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
2456       }
2457     else
2458       if (stat(SSH_SYSTEM_RC, &st) >= 0)
2459         {
2460         if (debug_flag)
2461           fprintf(stderr, "Running /bin/sh %s\n", SSH_SYSTEM_RC);
2462  
2463         f = popen("/bin/sh " SSH_SYSTEM_RC, "w");
2464         if (f)
2465           {
2466             if (auth_proto != NULL && auth_data != NULL)
2467               fprintf(f, "%s %s\n", auth_proto, auth_data);
2468             pclose(f);
2469           }
2470         else
2471           fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
2472         }
2473 #ifdef XAUTH_PATH
2474       else
2475         {
2476         /* Add authority data to .Xauthority if appropriate. */
2477         if (auth_proto != NULL && auth_data != NULL)
2478           {
2479             if (debug_flag)
2480               fprintf(stderr, "Running %.100s add %.100s %.100s %.100s\n",
2481                       XAUTH_PATH, display, auth_proto, auth_data);
2482             
2483             f = popen(XAUTH_PATH " -q -", "w");
2484             if (f)
2485               {
2486                 fprintf(f, "add %s %s %s\n", display, auth_proto, auth_data);
2487                 fclose(f);
2488               }
2489             else
2490               fprintf(stderr, "Could not run %s -q -\n", XAUTH_PATH);
2491           }
2492         }
2493 #endif /* XAUTH_PATH */
2494
2495     /* Get the last component of the shell name. */
2496     cp = strrchr(shell, '/');
2497     if (cp)
2498       cp++;
2499     else
2500       cp = shell;
2501   }
2502
2503   /* If we have no command, execute the shell.  In this case, the shell name
2504      to be passed in argv[0] is preceded by '-' to indicate that this is
2505      a login shell. */
2506   if (!command)
2507     {
2508       if(!options.use_login) {
2509         char buf[256];
2510
2511         /* Check for mail if we have a tty and it was enabled in server options. */
2512         if (ttyname && options.check_mail) {
2513           char *mailbox;
2514           struct stat mailstat;
2515           mailbox = getenv("MAIL");
2516           if(mailbox != NULL) {
2517             if(stat(mailbox, &mailstat) != 0 || mailstat.st_size == 0) {
2518               printf("No mail.\n");
2519             } else if(mailstat.st_mtime < mailstat.st_atime) {
2520               printf("You have mail.\n");
2521             } else {
2522               printf("You have new mail.\n");
2523             }
2524           }
2525         }
2526         /* Start the shell.  Set initial character to '-'. */
2527         buf[0] = '-';
2528         strncpy(buf + 1, cp, sizeof(buf) - 1);
2529         buf[sizeof(buf) - 1] = 0;
2530         /* Execute the shell. */
2531         argv[0] = buf;
2532         argv[1] = NULL;
2533         execve(shell, argv, env);
2534         /* Executing the shell failed. */
2535         perror(shell);
2536         exit(1);
2537
2538       } else {
2539         /* Launch login(1). */
2540
2541         execl(LOGIN_PROGRAM, "login", "-h", get_remote_ipaddr(), "-p", "-f", "--", pw->pw_name, NULL);
2542
2543         /* Login couldn't be executed, die. */
2544
2545         perror("login");
2546         exit(1);
2547       }
2548     }
2549
2550   /* Execute the command using the user's shell.  This uses the -c option
2551      to execute the command. */
2552   argv[0] = (char *)cp;
2553   argv[1] = "-c";
2554   argv[2] = (char *)command;
2555   argv[3] = NULL;
2556   execve(shell, argv, env);
2557   perror(shell);
2558   exit(1);
2559 }
This page took 1.827028 seconds and 5 git commands to generate.