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