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