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