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