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