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