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