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