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