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