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