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