5 Author: Tatu Ylonen <ylo@cs.hut.fi>
7 Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
10 Created: Fri Mar 17 17:09:28 1995 ylo
12 This program is the ssh daemon. It listens for connections from clients, and
13 performs authentication, executes use commands or shell, and forwards
14 information to/from the application to the user client over an encrypted
15 connection. This can also handle forwarding of X11, TCP/IP, and authentication
38 int allow_severity = LOG_INFO;
39 int deny_severity = LOG_WARNING;
50 /* Local Xauthority file. */
51 char *xauthfile = NULL;
53 /* Server configuration options. */
54 ServerOptions options;
56 /* Name of the server configuration file. */
57 char *config_file_name = SERVER_CONFIG_FILE;
59 /* Debug mode flag. This can be set on the command line. If debug
60 mode is enabled, extra debugging output will be sent to the system
61 log, the daemon will not go to background, and will exit after processing
62 the first connection. */
65 /* Flag indicating that the daemon is being started from inetd. */
68 /* argv[0] without path. */
71 /* Saved arguments to main(). */
74 /* This is set to the socket that the server is listening; this is used in
75 the SIGHUP signal handler. */
78 /* Flags set in auth-rsa from authorized_keys flags. These are set in
80 int no_port_forwarding_flag = 0;
81 int no_agent_forwarding_flag = 0;
82 int no_x11_forwarding_flag = 0;
84 char *forced_command = NULL; /* RSA authentication "command=" option. */
85 struct envstring *custom_environment = NULL;
86 /* RSA authentication "environment=" options. */
88 /* Session id for the current session. */
89 unsigned char session_id[16];
91 /* Any really sensitive data in the application is contained in this structure.
92 The idea is that this structure could be locked into memory so that the
93 pages do not get written into swap. However, there are some problems.
94 The private key contains BIGNUMs, and we do not (in principle) have
95 access to the internals of them, and locking just the structure is not
96 very useful. Currently, memory locking is not implemented. */
99 /* Private part of server key. */
102 /* Private part of host key. */
106 /* Flag indicating whether the current session key has been used. This flag
107 is set whenever the key is used, and cleared when the key is regenerated. */
110 /* This is set to true when SIGHUP is received. */
111 int received_sighup = 0;
113 /* Public side of the server key. This value is regenerated regularly with
117 /* Prototypes for various functions defined later in this file. */
118 void do_connection(int privileged_port);
119 void do_authentication(char *user, int privileged_port);
120 void do_authenticated(struct passwd *pw);
121 void do_exec_pty(const char *command, int ptyfd, int ttyfd,
122 const char *ttyname, struct passwd *pw, const char *term,
123 const char *display, const char *auth_proto,
124 const char *auth_data);
125 void do_exec_no_pty(const char *command, struct passwd *pw,
126 const char *display, const char *auth_proto,
127 const char *auth_data);
128 void do_child(const char *command, struct passwd *pw, const char *term,
129 const char *display, const char *auth_proto,
130 const char *auth_data, const char *ttyname);
132 static int pamconv(int num_msg, const struct pam_message **msg,
133 struct pam_response **resp, void *appdata_ptr);
134 void do_pam_authentication(const char *username, const char *password,
135 const char *remote_user, const char *remote_host);
136 void pam_cleanup_proc(void *context);
138 static struct pam_conv conv = {
142 struct pam_handle_t *pamh = NULL;
143 const char *pampasswd = NULL;
145 static int pamconv(int num_msg, const struct pam_message **msg,
146 struct pam_response **resp, void *appdata_ptr)
149 struct pam_response *reply = NULL;
151 /* PAM will free this later */
152 reply = malloc(num_msg * sizeof(*reply));
156 for(count = 0; count < num_msg; count++)
158 switch (msg[count]->msg_style)
160 case PAM_PROMPT_ECHO_OFF:
161 if (pampasswd == NULL)
166 reply[count].resp_retcode = PAM_SUCCESS;
167 reply[count].resp = xstrdup(pampasswd);
171 reply[count].resp_retcode = PAM_SUCCESS;
172 reply[count].resp = xstrdup("");
175 case PAM_PROMPT_ECHO_ON:
188 void pam_cleanup_proc(void *context)
194 retval = pam_close_session((pam_handle_t *)pamh, 0);
196 if (pam_end((pam_handle_t *)pamh, retval) != PAM_SUCCESS)
197 log("Cannot release PAM authentication.");
201 void do_pam_authentication(const char *username, const char *password, const char *remote_user, const char *remote_host)
205 pampasswd = password;
209 if (PAM_SUCCESS != pam_start("ssh", username, &conv, (pam_handle_t**)&pamh))
215 fatal_add_cleanup(&pam_cleanup_proc, NULL);
217 if (remote_host && (PAM_SUCCESS != pam_set_item((pam_handle_t *)pamh, PAM_RHOST, remote_host)))
223 if (remote_user && (PAM_SUCCESS != pam_set_item((pam_handle_t *)pamh, PAM_RUSER, remote_user)))
229 if (PAM_SUCCESS != pam_authenticate((pam_handle_t *)pamh, 0))
235 if (PAM_SUCCESS != pam_acct_mgmt((pam_handle_t *)pamh, 0))
241 if (PAM_SUCCESS != pam_open_session((pam_handle_t *)pamh, 0))
250 packet_start(SSH_SMSG_FAILURE);
253 packet_disconnect("PAM authentication failed.");
256 #endif /* HAVE_PAM */
258 /* Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
259 the effect is to reread the configuration file (and to regenerate
262 void sighup_handler(int sig)
265 signal(SIGHUP, sighup_handler);
268 /* Called from the main program after receiving SIGHUP. Restarts the
271 void sighup_restart()
273 log("Received SIGHUP; restarting.");
275 execv(saved_argv[0], saved_argv);
276 log("RESTART FAILED: av0='%s', error: %s.", av0, strerror(errno));
280 /* Generic signal handler for terminating signals in the master daemon.
281 These close the listen socket; not closing it seems to cause "Address
282 already in use" problems on some machines, which is inconvenient. */
284 void sigterm_handler(int sig)
286 log("Received signal %d; terminating.", sig);
291 /* SIGCHLD handler. This is called whenever a child dies. This will then
292 reap any zombies left by exited c. */
294 void main_sigchld_handler(int sig)
296 int save_errno = errno;
299 signal(SIGCHLD, main_sigchld_handler);
303 /* Signal handler for the alarm after the login grace period has expired. */
305 void grace_alarm_handler(int sig)
307 /* Close the connection. */
310 /* Log error and exit. */
311 fatal("Timeout before authentication.");
314 /* Signal handler for the key regeneration alarm. Note that this
315 alarm only occurs in the daemon waiting for connections, and it does not
316 do anything with the private key or random state before forking. Thus there
317 should be no concurrency control/asynchronous execution problems. */
319 void key_regeneration_alarm(int sig)
321 int save_errno = errno;
323 /* Check if we should generate a new key. */
326 /* This should really be done in the background. */
327 log("Generating new %d bit RSA key.", options.server_key_bits);
329 if (sensitive_data.private_key != NULL)
330 RSA_free(sensitive_data.private_key);
331 sensitive_data.private_key = RSA_new();
333 if (public_key != NULL)
334 RSA_free(public_key);
335 public_key = RSA_new();
337 rsa_generate_key(sensitive_data.private_key, public_key,
338 options.server_key_bits);
341 log("RSA key generation complete.");
344 /* Reschedule the alarm. */
345 signal(SIGALRM, key_regeneration_alarm);
346 alarm(options.key_regeneration_time);
350 /* Main program for the daemon. */
353 main(int ac, char **av)
357 int opt, aux, sock_in, sock_out, newsock, i, pid, on = 1;
358 int remote_major, remote_minor;
360 struct sockaddr_in sin;
361 char buf[100]; /* Must not be larger than remote_version. */
362 char remote_version[100]; /* Must be at least as big as buf. */
365 struct linger linger;
369 if (strchr(av[0], '/'))
370 av0 = strrchr(av[0], '/') + 1;
374 /* Initialize configuration options to their default values. */
375 initialize_server_options(&options);
377 /* Parse command-line arguments. */
378 while ((opt = getopt(ac, av, "f:p:b:k:h:g:diqQ")) != EOF)
383 config_file_name = optarg;
395 options.quiet_mode = 1;
398 options.server_key_bits = atoi(optarg);
401 options.port = atoi(optarg);
404 options.login_grace_time = atoi(optarg);
407 options.key_regeneration_time = atoi(optarg);
410 options.host_key_file = optarg;
414 fprintf(stderr, "sshd version %s\n", SSH_VERSION);
415 fprintf(stderr, "Usage: %s [options]\n", av0);
416 fprintf(stderr, "Options:\n");
417 fprintf(stderr, " -f file Configuration file (default %s/sshd_config)\n", ETCDIR);
418 fprintf(stderr, " -d Debugging mode\n");
419 fprintf(stderr, " -i Started from inetd\n");
420 fprintf(stderr, " -q Quiet (no logging)\n");
421 fprintf(stderr, " -p port Listen on the specified port (default: 22)\n");
422 fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n");
423 fprintf(stderr, " -g seconds Grace period for authentication (default: 300)\n");
424 fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n");
425 fprintf(stderr, " -h file File from which to read host key (default: %s)\n",
431 /* check if RSA support exists */
432 if (rsa_alive() == 0) {
434 printf("sshd: no RSA support in libssl and libcrypto -- exiting. See ssl(8)\n");
435 log("no RSA support in libssl and libcrypto -- exiting. See ssl(8)");
439 /* Read server configuration options from the configuration file. */
440 read_server_config(&options, config_file_name);
442 /* Fill in default values for those options not explicitly set. */
443 fill_default_server_options(&options);
445 /* Check certain values for sanity. */
446 if (options.server_key_bits < 512 ||
447 options.server_key_bits > 32768)
449 fprintf(stderr, "Bad server key size.\n");
452 if (options.port < 1 || options.port > 65535)
454 fprintf(stderr, "Bad port number.\n");
458 /* Check that there are no remaining arguments. */
461 fprintf(stderr, "Extra argument %s.\n", av[optind]);
465 /* Initialize the log (it is reinitialized below in case we forked). */
466 log_init(av0, debug_flag && !inetd_flag,
467 debug_flag || options.fascist_logging,
468 options.quiet_mode, options.log_facility);
470 debug("sshd version %.100s", SSH_VERSION);
472 sensitive_data.host_key = RSA_new();
473 /* Load the host key. It must have empty passphrase. */
474 if (!load_private_key(options.host_key_file, "",
475 sensitive_data.host_key, &comment))
478 fprintf(stderr, "Could not load host key: %s: %s\n",
479 options.host_key_file, strerror(errno));
483 log_init(av0, !inetd_flag, 1, 0, options.log_facility);
484 error("Could not load host key: %.200s: %.100s",
485 options.host_key_file, strerror(err));
491 /* If not in debugging mode, and not started from inetd, disconnect from
492 the controlling terminal, and fork. The original process exits. */
493 if (!debug_flag && !inetd_flag)
497 #endif /* TIOCNOTTY */
498 if (daemon(0, 0) < 0)
499 fatal("daemon() failed: %.200s", strerror(errno));
501 /* Disconnect from the controlling tty. */
503 fd = open("/dev/tty", O_RDWR|O_NOCTTY);
506 (void)ioctl(fd, TIOCNOTTY, NULL);
509 #endif /* TIOCNOTTY */
512 /* Reinitialize the log (because of the fork above). */
513 log_init(av0, debug_flag && !inetd_flag,
514 debug_flag || options.fascist_logging,
515 options.quiet_mode, options.log_facility);
517 /* Check that server and host key lengths differ sufficiently. This is
518 necessary to make double encryption work with rsaref. Oh, I hate
519 software patents. I dont know if this can go? Niels */
520 if (options.server_key_bits >
521 BN_num_bits(sensitive_data.host_key->n) - SSH_KEY_BITS_RESERVED &&
522 options.server_key_bits <
523 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED)
525 options.server_key_bits =
526 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED;
527 debug("Forcing server key to %d bits to make it differ from host key.",
528 options.server_key_bits);
531 /* Do not display messages to stdout in RSA code. */
534 /* Initialize the random number generator. */
537 /* Chdir to the root directory so that the current disk can be unmounted
541 /* Close connection cleanly after attack. */
542 cipher_attack_detected = packet_disconnect;
544 /* Start listening for a socket, unless started from inetd. */
548 s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */
552 /* We intentionally do not close the descriptors 0, 1, and 2 as our
553 code for setting the descriptors won\'t work if ttyfd happens to
555 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
557 public_key = RSA_new();
558 sensitive_data.private_key = RSA_new();
559 /* Generate an rsa key. */
560 log("Generating %d bit RSA key.", options.server_key_bits);
561 rsa_generate_key(sensitive_data.private_key, public_key,
562 options.server_key_bits);
564 log("RSA key generation complete.");
568 /* Create socket for listening. */
569 listen_sock = socket(AF_INET, SOCK_STREAM, 0);
571 fatal("socket: %.100s", strerror(errno));
573 /* Set socket options. We try to make the port reusable and have it
574 close as fast as possible without waiting in unnecessary wait states
576 setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on,
580 setsockopt(listen_sock, SOL_SOCKET, SO_LINGER, (void *)&linger,
583 /* Initialize the socket address. */
584 memset(&sin, 0, sizeof(sin));
585 sin.sin_family = AF_INET;
586 sin.sin_addr = options.listen_addr;
587 sin.sin_port = htons(options.port);
589 /* Bind the socket to the desired port. */
590 if (bind(listen_sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
592 error("bind: %.100s", strerror(errno));
593 shutdown(listen_sock, SHUT_RDWR);
595 fatal("Bind to port %d failed.", options.port);
600 /* Record our pid in /etc/sshd_pid to make it easier to kill the
601 correct sshd. We don\'t want to do this before the bind above
602 because the bind will fail if there already is a daemon, and this
603 will overwrite any old pid in the file. */
604 f = fopen(SSH_DAEMON_PID_FILE, "w");
607 fprintf(f, "%u\n", (unsigned int)getpid());
612 /* Start listening on the port. */
613 log("Server listening on port %d.", options.port);
614 if (listen(listen_sock, 5) < 0)
615 fatal("listen: %.100s", strerror(errno));
617 public_key = RSA_new();
618 sensitive_data.private_key = RSA_new();
619 /* Generate an rsa key. */
620 log("Generating %d bit RSA key.", options.server_key_bits);
621 rsa_generate_key(sensitive_data.private_key, public_key,
622 options.server_key_bits);
624 log("RSA key generation complete.");
626 /* Schedule server key regeneration alarm. */
627 signal(SIGALRM, key_regeneration_alarm);
628 alarm(options.key_regeneration_time);
630 /* Arrange to restart on SIGHUP. The handler needs listen_sock. */
631 signal(SIGHUP, sighup_handler);
632 signal(SIGTERM, sigterm_handler);
633 signal(SIGQUIT, sigterm_handler);
635 /* Arrange SIGCHLD to be caught. */
636 signal(SIGCHLD, main_sigchld_handler);
638 /* Stay listening for connections until the system crashes or the
639 daemon is killed with a signal. */
644 /* Wait in accept until there is a connection. */
646 newsock = accept(listen_sock, (struct sockaddr *)&sin, &aux);
653 error("accept: %.100s", strerror(errno));
657 /* Got connection. Fork a child to handle it, unless we are in
661 /* In debugging mode. Close the listening socket, and start
662 processing the connection without forking. */
663 debug("Server will not fork when running in debugging mode.");
672 /* Normal production daemon. Fork, and have the child process
673 the connection. The parent continues listening. */
674 if ((pid = fork()) == 0)
676 /* Child. Close the listening socket, and start using
677 the accepted socket. Reinitialize logging (since our
678 pid has changed). We break out of the loop to handle
683 log_init(av0, debug_flag && !inetd_flag,
684 options.fascist_logging || debug_flag,
685 options.quiet_mode, options.log_facility);
690 /* Parent. Stay in the loop. */
692 error("fork: %.100s", strerror(errno));
694 debug("Forked child %d.", pid);
696 /* Mark that the key has been used (it was "given" to the child). */
701 /* Close the new socket (the child is now taking care of it). */
706 /* This is the child processing a new connection. */
708 /* Disable the key regeneration alarm. We will not regenerate the key
709 since we are no longer in a position to give it to anyone. We will
710 not restart on SIGHUP since it no longer makes sense. */
712 signal(SIGALRM, SIG_DFL);
713 signal(SIGHUP, SIG_DFL);
714 signal(SIGTERM, SIG_DFL);
715 signal(SIGQUIT, SIG_DFL);
716 signal(SIGCHLD, SIG_DFL);
718 /* Set socket options for the connection. We want the socket to close
719 as fast as possible without waiting for anything. If the connection
720 is not a socket, these will do nothing. */
721 /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
724 setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *)&linger, sizeof(linger));
726 /* Register our connection. This turns encryption off because we do not
728 packet_set_connection(sock_in, sock_out);
730 /* Check whether logins are denied from this host. */
733 struct request_info req;
735 request_init(&req, RQ_DAEMON, av0, RQ_FILE, sock_in, NULL);
738 if (!hosts_access(&req)) {
743 log("Connection from %.500s port %d",
744 eval_client(&req), get_remote_port());
747 /* Log the connection. */
748 log("Connection from %.100s port %d",
749 get_remote_ipaddr(), get_remote_port());
752 /* We don\'t want to listen forever unless the other side successfully
753 authenticates itself. So we set up an alarm which is cleared after
754 successful authentication. A limit of zero indicates no limit.
755 Note that we don\'t set the alarm in debugging mode; it is just annoying
756 to have the server exit just when you are about to discover the bug. */
757 signal(SIGALRM, grace_alarm_handler);
759 alarm(options.login_grace_time);
761 /* Send our protocol version identification. */
762 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n",
763 PROTOCOL_MAJOR, PROTOCOL_MINOR, SSH_VERSION);
764 if (write(sock_out, buf, strlen(buf)) != strlen(buf))
765 fatal("Could not write ident string.");
767 /* Read other side\'s version identification. */
768 for (i = 0; i < sizeof(buf) - 1; i++)
770 if (read(sock_in, &buf[i], 1) != 1)
771 fatal("Did not receive ident string.");
785 buf[sizeof(buf) - 1] = 0;
787 /* Check that the versions match. In future this might accept several
788 versions and set appropriate flags to handle them. */
789 if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", &remote_major, &remote_minor,
790 remote_version) != 3)
792 const char *s = "Protocol mismatch.\n";
793 (void) write(sock_out, s, strlen(s));
796 fatal("Bad protocol version identification: %.100s", buf);
798 debug("Client protocol version %d.%d; client software version %.100s",
799 remote_major, remote_minor, remote_version);
800 if (remote_major != PROTOCOL_MAJOR)
802 const char *s = "Protocol major versions differ.\n";
803 (void) write(sock_out, s, strlen(s));
806 fatal("Protocol major versions differ: %d vs. %d",
807 PROTOCOL_MAJOR, remote_major);
810 /* Check that the client has sufficiently high software version. */
811 if (remote_major == 1 && remote_minor < 3)
812 packet_disconnect("Your ssh version is too old and is no longer supported. Please install a newer version.");
814 if (remote_major == 1 && remote_minor == 3) {
816 if (strcmp(remote_version, "OpenSSH-1.1") != 0) {
817 debug("Agent forwarding disabled, remote version is not compatible.");
818 no_agent_forwarding_flag = 1;
822 packet_set_nonblocking();
824 /* Handle the connection. We pass as argument whether the connection
825 came from a privileged port. */
826 do_connection(get_remote_port() < IPPORT_RESERVED);
829 /* Cleanup user's ticket cache file. */
830 if (options.kerberos_ticket_cleanup)
834 /* Cleanup user's local Xauthority file. */
835 if (xauthfile) unlink(xauthfile);
837 /* The connection has been terminated. */
838 log("Closing connection to %.100s", inet_ntoa(sin.sin_addr));
846 retval = pam_close_session((pam_handle_t *)pamh, 0);
848 if (pam_end((pam_handle_t *)pamh, retval) != PAM_SUCCESS)
849 log("Cannot release PAM authentication.");
851 fatal_remove_cleanup(&pam_cleanup_proc, NULL);
854 #endif /* HAVE_PAM */
861 /* Process an incoming connection. Protocol version identifiers have already
862 been exchanged. This sends server key and performs the key exchange.
863 Server and host keys will no longer be needed after this functions. */
865 void do_connection(int privileged_port)
868 BIGNUM *session_key_int;
869 unsigned char session_key[SSH_SESSION_KEY_LENGTH];
870 unsigned char check_bytes[8];
872 unsigned int cipher_type, auth_mask, protocol_flags;
876 /* Generate check bytes that the client must send back in the user packet
877 in order for it to be accepted; this is used to defy ip spoofing
878 attacks. Note that this only works against somebody doing IP spoofing
879 from a remote machine; any machine on the local network can still see
880 outgoing packets and catch the random cookie. This only affects
881 rhosts authentication, and this is one of the reasons why it is
882 inherently insecure. */
883 for (i = 0; i < 8; i++) {
886 check_bytes[i] = rand & 0xff;
890 /* Send our public key. We include in the packet 64 bits of random
891 data that must be matched in the reply in order to prevent IP spoofing. */
892 packet_start(SSH_SMSG_PUBLIC_KEY);
893 for (i = 0; i < 8; i++)
894 packet_put_char(check_bytes[i]);
896 /* Store our public server RSA key. */
897 packet_put_int(BN_num_bits(public_key->n));
898 packet_put_bignum(public_key->e);
899 packet_put_bignum(public_key->n);
901 /* Store our public host RSA key. */
902 packet_put_int(BN_num_bits(sensitive_data.host_key->n));
903 packet_put_bignum(sensitive_data.host_key->e);
904 packet_put_bignum(sensitive_data.host_key->n);
906 /* Put protocol flags. */
907 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
909 /* Declare which ciphers we support. */
910 packet_put_int(cipher_mask());
912 /* Declare supported authentication types. */
914 if (options.rhosts_authentication)
915 auth_mask |= 1 << SSH_AUTH_RHOSTS;
916 if (options.rhosts_rsa_authentication)
917 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
918 if (options.rsa_authentication)
919 auth_mask |= 1 << SSH_AUTH_RSA;
921 if (options.kerberos_authentication)
922 auth_mask |= 1 << SSH_AUTH_KERBEROS;
925 if (options.kerberos_tgt_passing)
926 auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
927 if (options.afs_token_passing)
928 auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
930 if (options.password_authentication)
931 auth_mask |= 1 << SSH_AUTH_PASSWORD;
932 packet_put_int(auth_mask);
934 /* Send the packet and wait for it to be sent. */
938 debug("Sent %d bit public key and %d bit host key.",
939 BN_num_bits(public_key->n), BN_num_bits(sensitive_data.host_key->n));
941 /* Read clients reply (cipher type and session key). */
942 packet_read_expect(&plen, SSH_CMSG_SESSION_KEY);
944 /* Get cipher type. */
945 cipher_type = packet_get_char();
947 /* Get check bytes from the packet. These must match those we sent earlier
948 with the public key packet. */
949 for (i = 0; i < 8; i++)
950 if (check_bytes[i] != packet_get_char())
951 packet_disconnect("IP Spoofing check bytes do not match.");
953 debug("Encryption type: %.200s", cipher_name(cipher_type));
955 /* Get the encrypted integer. */
956 session_key_int = BN_new();
957 packet_get_bignum(session_key_int, &slen);
959 /* Get protocol flags. */
960 protocol_flags = packet_get_int();
961 packet_set_protocol_flags(protocol_flags);
963 packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY);
965 /* Decrypt it using our private server key and private host key (key with
966 larger modulus first). */
967 if (BN_cmp(sensitive_data.private_key->n, sensitive_data.host_key->n) > 0)
969 /* Private key has bigger modulus. */
970 assert(BN_num_bits(sensitive_data.private_key->n) >=
971 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED);
972 rsa_private_decrypt(session_key_int, session_key_int,
973 sensitive_data.private_key);
974 rsa_private_decrypt(session_key_int, session_key_int,
975 sensitive_data.host_key);
979 /* Host key has bigger modulus (or they are equal). */
980 assert(BN_num_bits(sensitive_data.host_key->n) >=
981 BN_num_bits(sensitive_data.private_key->n) +
982 SSH_KEY_BITS_RESERVED);
983 rsa_private_decrypt(session_key_int, session_key_int,
984 sensitive_data.host_key);
985 rsa_private_decrypt(session_key_int, session_key_int,
986 sensitive_data.private_key);
989 /* Compute session id for this session. */
990 compute_session_id(session_id, check_bytes,
991 BN_num_bits(sensitive_data.host_key->n),
992 sensitive_data.host_key->n,
993 BN_num_bits(sensitive_data.private_key->n),
994 sensitive_data.private_key->n);
996 /* Extract session key from the decrypted integer. The key is in the
997 least significant 256 bits of the integer; the first byte of the
998 key is in the highest bits. */
999 BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1000 assert(BN_num_bytes(session_key_int) == sizeof(session_key));
1001 BN_bn2bin(session_key_int, session_key);
1003 /* Xor the first 16 bytes of the session key with the session id. */
1004 for (i = 0; i < 16; i++)
1005 session_key[i] ^= session_id[i];
1007 /* Destroy the decrypted integer. It is no longer needed. */
1008 BN_clear_free(session_key_int);
1010 /* Set the session key. From this on all communications will be
1012 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH,
1015 /* Destroy our copy of the session key. It is no longer needed. */
1016 memset(session_key, 0, sizeof(session_key));
1018 debug("Received session key; encryption turned on.");
1020 /* Send an acknowledgement packet. Note that this packet is sent
1022 packet_start(SSH_SMSG_SUCCESS);
1024 packet_write_wait();
1026 /* Get the name of the user that we wish to log in as. */
1027 packet_read_expect(&plen, SSH_CMSG_USER);
1029 /* Get the user name. */
1032 user = packet_get_string(&ulen);
1033 packet_integrity_check(plen, (4 + ulen), SSH_CMSG_USER);
1036 /* Destroy the private and public keys. They will no longer be needed. */
1037 RSA_free(public_key);
1038 RSA_free(sensitive_data.private_key);
1039 RSA_free(sensitive_data.host_key);
1041 setproctitle("%s", user);
1042 /* Do the authentication. */
1043 do_authentication(user, privileged_port);
1046 /* Check if the user is allowed to log in via ssh. If user is listed in
1047 DenyUsers or user's primary group is listed in DenyGroups, false will
1048 be returned. If AllowUsers isn't empty and user isn't listed there, or
1049 if AllowGroups isn't empty and user isn't listed there, false will be
1050 returned. Otherwise true is returned.
1051 XXX This function should also check if user has a valid shell */
1054 allowed_user(struct passwd *pw)
1059 /* Shouldn't be called if pw is NULL, but better safe than sorry... */
1063 /* XXX Should check for valid login shell */
1065 /* Return false if user is listed in DenyUsers */
1066 if (options.num_deny_users > 0)
1070 for (i = 0; i < options.num_deny_users; i++)
1071 if (match_pattern(pw->pw_name, options.deny_users[i]))
1075 /* Return false if AllowUsers isn't empty and user isn't listed there */
1076 if (options.num_allow_users > 0)
1080 for (i = 0; i < options.num_allow_users; i++)
1081 if (match_pattern(pw->pw_name, options.allow_users[i]))
1083 /* i < options.num_allow_users iff we break for loop */
1084 if (i >= options.num_allow_users)
1088 /* Get the primary group name if we need it. Return false if it fails */
1089 if (options.num_deny_groups > 0 || options.num_allow_groups > 0 )
1091 grp = getgrgid(pw->pw_gid);
1095 /* Return false if user's group is listed in DenyGroups */
1096 if (options.num_deny_groups > 0)
1100 for (i = 0; i < options.num_deny_groups; i++)
1101 if (match_pattern(grp->gr_name, options.deny_groups[i]))
1105 /* Return false if AllowGroups isn't empty and user's group isn't
1107 if (options.num_allow_groups > 0)
1111 for (i = 0; i < options.num_allow_groups; i++)
1112 if (match_pattern(grp->gr_name, options.allow_groups[i]))
1114 /* i < options.num_allow_groups iff we break for loop */
1115 if (i >= options.num_allow_groups)
1120 /* We found no reason not to let this user try to log on... */
1124 /* Performs authentication of an incoming connection. Session key has already
1125 been exchanged and encryption is enabled. User is the user name to log
1126 in as (received from the clinet). Privileged_port is true if the
1127 connection comes from a privileged port (used for .rhosts authentication).*/
1129 #define MAX_AUTH_FAILURES 5
1132 do_authentication(char *user, int privileged_port)
1135 int authenticated = 0;
1136 int authentication_failures = 0;
1137 char *password = NULL;
1138 struct passwd *pw, pwcopy;
1139 char *client_user = NULL;
1140 unsigned int client_host_key_bits;
1141 BIGNUM *client_host_key_e, *client_host_key_n;
1144 /* If machine has AFS, set process authentication group. */
1151 /* Verify that the user is a valid user. */
1152 pw = getpwnam(user);
1153 if (!pw || !allowed_user(pw))
1155 /* The user does not exist or access is denied,
1156 but fake indication that authentication is needed. */
1157 packet_start(SSH_SMSG_FAILURE);
1159 packet_write_wait();
1161 /* Keep reading packets, and always respond with a failure. This is to
1162 avoid disclosing whether such a user really exists. */
1165 /* Read a packet. This will not return if the client disconnects. */
1167 int type = packet_read(&plen);
1170 char *password, *skeyinfo;
1171 if (options.password_authentication &&
1172 options.skey_authentication == 1 &&
1173 type == SSH_CMSG_AUTH_PASSWORD &&
1174 (password = packet_get_string(&passw_len)) != NULL &&
1176 strncasecmp(password, "s/key", 5) == 0 &&
1177 (skeyinfo = skey_fake_keyinfo(user)) != NULL ){
1178 /* Send a fake s/key challenge. */
1179 packet_send_debug(skeyinfo);
1182 /* Send failure. This should be indistinguishable from a failed
1184 packet_start(SSH_SMSG_FAILURE);
1186 packet_write_wait();
1187 if (++authentication_failures >= MAX_AUTH_FAILURES) {
1188 packet_disconnect("Too many authentication failures for %.100s from %.200s",
1189 user, get_canonical_hostname());
1196 /* Take a copy of the returned structure. */
1197 memset(&pwcopy, 0, sizeof(pwcopy));
1198 pwcopy.pw_name = xstrdup(pw->pw_name);
1199 pwcopy.pw_passwd = xstrdup(pw->pw_passwd);
1200 pwcopy.pw_uid = pw->pw_uid;
1201 pwcopy.pw_gid = pw->pw_gid;
1202 pwcopy.pw_dir = xstrdup(pw->pw_dir);
1203 pwcopy.pw_shell = xstrdup(pw->pw_shell);
1206 /* If we are not running as root, the user must have the same uid as the
1208 if (getuid() != 0 && pw->pw_uid != getuid())
1209 packet_disconnect("Cannot change user when server not running as root.");
1211 debug("Attempting authentication for %.100s.", user);
1213 /* If the user has no password, accept authentication immediately. */
1214 if (options.password_authentication &&
1216 (!options.kerberos_authentication || options.kerberos_or_local_passwd) &&
1218 auth_password(pw, ""))
1220 /* Authentication with empty password succeeded. */
1221 debug("Login for user %.100s accepted without authentication.", user);
1222 /* authentication_type = SSH_AUTH_PASSWORD; */
1224 /* Success packet will be sent after loop below. */
1228 /* Indicate that authentication is needed. */
1229 packet_start(SSH_SMSG_FAILURE);
1231 packet_write_wait();
1234 /* Loop until the user has been authenticated or the connection is closed. */
1235 while (!authenticated)
1238 /* Get a packet from the client. */
1239 type = packet_read(&plen);
1241 /* Process the packet. */
1246 case SSH_CMSG_HAVE_KERBEROS_TGT:
1247 if (!options.kerberos_tgt_passing)
1249 /* packet_get_all(); */
1250 log("Kerberos tgt passing disabled.");
1254 /* Accept Kerberos tgt. */
1256 char *tgt = packet_get_string(&dlen);
1257 packet_integrity_check(plen, 4 + dlen, type);
1258 if (!auth_kerberos_tgt(pw, tgt))
1259 debug("Kerberos tgt REFUSED for %s", user);
1264 case SSH_CMSG_HAVE_AFS_TOKEN:
1265 if (!options.afs_token_passing || !k_hasafs()) {
1266 /* packet_get_all(); */
1267 log("AFS token passing disabled.");
1271 /* Accept AFS token. */
1273 char *token_string = packet_get_string(&dlen);
1274 packet_integrity_check(plen, 4 + dlen, type);
1275 if (!auth_afs_token(user, pw->pw_uid, token_string))
1276 debug("AFS token REFUSED for %s", user);
1277 xfree(token_string);
1283 case SSH_CMSG_AUTH_KERBEROS:
1284 if (!options.kerberos_authentication)
1286 /* packet_get_all(); */
1287 log("Kerberos authentication disabled.");
1291 /* Try Kerberos v4 authentication. */
1293 char *tkt_user = NULL;
1294 char *kdata = packet_get_string((unsigned int *)&auth.length);
1295 packet_integrity_check(plen, 4 + auth.length, type);
1297 if (auth.length < MAX_KTXT_LEN)
1298 memcpy(auth.dat, kdata, auth.length);
1301 if (auth_krb4(user, &auth, &tkt_user)) {
1302 /* Client has successfully authenticated to us. */
1303 log("Kerberos authentication accepted %s for account "
1304 "%s from %s", tkt_user, user, get_canonical_hostname());
1305 /* authentication_type = SSH_AUTH_KERBEROS; */
1310 log("Kerberos authentication failed for account "
1311 "%s from %s", user, get_canonical_hostname());
1317 case SSH_CMSG_AUTH_RHOSTS:
1318 if (!options.rhosts_authentication)
1320 log("Rhosts authentication disabled.");
1324 /* Rhosts authentication (also uses /etc/hosts.equiv). */
1325 if (!privileged_port)
1327 log("Rhosts authentication not available for connections from unprivileged port.");
1331 /* Get client user name. Note that we just have to trust the client;
1332 this is one reason why rhosts authentication is insecure.
1333 (Another is IP-spoofing on a local network.) */
1336 client_user = packet_get_string(&dlen);
1337 packet_integrity_check(plen, 4 + dlen, type);
1340 /* Try to authenticate using /etc/hosts.equiv and .rhosts. */
1341 if (auth_rhosts(pw, client_user, options.ignore_rhosts,
1342 options.strict_modes))
1344 /* Authentication accepted. */
1345 log("Rhosts authentication accepted for %.100s, remote %.100s on %.700s.",
1346 user, client_user, get_canonical_hostname());
1350 #endif /* HAVE_PAM */
1353 log("Rhosts authentication failed for %.100s, remote %.100s.",
1357 #endif /* HAVE_PAM */
1360 case SSH_CMSG_AUTH_RHOSTS_RSA:
1361 if (!options.rhosts_rsa_authentication)
1363 log("Rhosts with RSA authentication disabled.");
1367 /* Rhosts authentication (also uses /etc/hosts.equiv) with RSA
1368 host authentication. */
1369 if (!privileged_port)
1371 log("Rhosts authentication not available for connections from unprivileged port.");
1376 int ulen, elen, nlen;
1377 /* Get client user name. Note that we just have to trust
1378 the client; root on the client machine can claim to be
1380 client_user = packet_get_string(&ulen);
1382 /* Get the client host key. */
1383 client_host_key_e = BN_new();
1384 client_host_key_n = BN_new();
1385 client_host_key_bits = packet_get_int();
1386 packet_get_bignum(client_host_key_e, &elen);
1387 packet_get_bignum(client_host_key_n, &nlen);
1389 packet_integrity_check(plen, (4 + ulen) + 4 + elen + nlen, type);
1392 /* Try to authenticate using /etc/hosts.equiv and .rhosts. */
1393 if (auth_rhosts_rsa(pw, client_user,
1394 client_host_key_bits, client_host_key_e,
1395 client_host_key_n, options.ignore_rhosts,
1396 options.strict_modes))
1398 /* Authentication accepted. */
1402 #endif /* HAVE_PAM */
1403 BN_clear_free(client_host_key_e);
1404 BN_clear_free(client_host_key_n);
1407 log("Rhosts authentication failed for %.100s, remote %.100s.",
1411 #endif /* HAVE_PAM */
1412 BN_clear_free(client_host_key_e);
1413 BN_clear_free(client_host_key_n);
1416 case SSH_CMSG_AUTH_RSA:
1417 if (!options.rsa_authentication)
1419 log("RSA authentication disabled.");
1423 /* RSA authentication requested. */
1428 packet_get_bignum(n, &nlen);
1430 packet_integrity_check(plen, nlen, type);
1432 if (auth_rsa(pw, n, options.strict_modes))
1434 /* Successful authentication. */
1436 log("RSA authentication for %.100s accepted.", user);
1441 log("RSA authentication for %.100s failed.", user);
1445 case SSH_CMSG_AUTH_PASSWORD:
1446 if (!options.password_authentication)
1448 log("Password authentication disabled.");
1452 /* Password authentication requested. */
1453 /* Read user password. It is in plain text, but was transmitted
1454 over the encrypted channel so it is not visible to an outside
1458 password = packet_get_string(&passw_len);
1459 packet_integrity_check(plen, 4 + passw_len, type);
1463 /* Authentication will be handled later */
1464 /* keep password around until then */
1467 #else /* HAVE_PAM */
1468 /* Try authentication with the password. */
1469 if (auth_password(pw, password))
1471 /* Successful authentication. */
1472 /* Clear the password from memory. */
1473 memset(password, 0, strlen(password));
1475 log("Password authentication for %.100s accepted.", user);
1479 log("Password authentication for %.100s failed.", user);
1480 memset(password, 0, strlen(password));
1483 #endif /* HAVE_PAM */
1485 case SSH_CMSG_AUTH_TIS:
1486 /* TIS Authentication is unsupported */
1487 log("TIS authentication disabled.");
1491 /* Any unknown messages will be ignored (and failure returned)
1492 during authentication. */
1493 log("Unknown message during authentication: type %d", type);
1494 break; /* Respond with a failure message. */
1496 /* If successfully authenticated, break out of loop. */
1500 /* Send a message indicating that the authentication attempt failed. */
1501 packet_start(SSH_SMSG_FAILURE);
1503 packet_write_wait();
1505 if (++authentication_failures >= MAX_AUTH_FAILURES) {
1506 packet_disconnect("Too many authentication failures for %.100s from %.200s",
1507 pw->pw_name, get_canonical_hostname());
1511 /* Check if the user is logging in as root and root logins are disallowed. */
1512 if (pw->pw_uid == 0 && !options.permit_root_login)
1515 log("Root login accepted for forced command.", forced_command);
1517 packet_disconnect("ROOT LOGIN REFUSED FROM %.200s",
1518 get_canonical_hostname());
1522 do_pam_authentication(pw->pw_name, password, client_user, get_canonical_hostname());
1525 if (client_user != NULL)
1528 if (password != NULL)
1530 memset(password, 0, strlen(password));
1533 #endif /* HAVE_PAM */
1535 /* The user has been authenticated and accepted. */
1536 packet_start(SSH_SMSG_SUCCESS);
1538 packet_write_wait();
1540 /* Perform session preparation. */
1541 do_authenticated(pw);
1544 /* Prepares for an interactive session. This is called after the user has
1545 been successfully authenticated. During this message exchange, pseudo
1546 terminals are allocated, X11, TCP/IP, and authentication agent forwardings
1547 are requested, etc. */
1549 void do_authenticated(struct passwd *pw)
1552 int compression_level = 0, enable_compression_after_reply = 0;
1553 int have_pty = 0, ptyfd = -1, ttyfd = -1, xauthfd = -1;
1554 int row, col, xpixel, ypixel, screen;
1556 char *command, *term = NULL, *display = NULL, *proto = NULL, *data = NULL;
1562 /* Cancel the alarm we set to limit the time taken for authentication. */
1565 /* Inform the channel mechanism that we are the server side and that
1566 the client may request to connect to any port at all. (The user could
1567 do it anyway, and we wouldn\'t know what is permitted except by the
1568 client telling us, so we can equally well trust the client not to request
1570 channel_permit_all_opens();
1572 /* We stay in this loop until the client requests to execute a shell or a
1578 /* Get a packet from the client. */
1579 type = packet_read(&plen);
1581 /* Process the packet. */
1584 case SSH_CMSG_REQUEST_COMPRESSION:
1585 packet_integrity_check(plen, 4, type);
1586 compression_level = packet_get_int();
1587 if (compression_level < 1 || compression_level > 9)
1589 packet_send_debug("Received illegal compression level %d.",
1593 /* Enable compression after we have responded with SUCCESS. */
1594 enable_compression_after_reply = 1;
1597 case SSH_CMSG_REQUEST_PTY:
1600 debug("Allocating a pty not permitted for this authentication.");
1604 packet_disconnect("Protocol error: you already have a pty.");
1606 debug("Allocating pty.");
1608 /* Allocate a pty and open it. */
1609 if (!pty_allocate(&ptyfd, &ttyfd, ttyname))
1611 error("Failed to allocate pty.");
1615 /* Determine the group to make the owner of the tty. */
1616 grp = getgrnam("tty");
1619 tty_gid = grp->gr_gid;
1620 tty_mode = S_IRUSR|S_IWUSR|S_IWGRP;
1624 tty_gid = pw->pw_gid;
1625 tty_mode = S_IRUSR|S_IWUSR|S_IWGRP|S_IWOTH;
1628 /* Change ownership of the tty. */
1629 if (chown(ttyname, pw->pw_uid, tty_gid) < 0)
1630 fatal("chown(%.100s, %d, %d) failed: %.100s",
1631 ttyname, pw->pw_uid, tty_gid, strerror(errno));
1632 if (chmod(ttyname, tty_mode) < 0)
1633 fatal("chmod(%.100s, 0%o) failed: %.100s",
1634 ttyname, tty_mode, strerror(errno));
1636 /* Get TERM from the packet. Note that the value may be of arbitrary
1639 term = packet_get_string(&dlen);
1640 packet_integrity_check(dlen, strlen(term), type);
1641 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
1642 /* Remaining bytes */
1643 n_bytes = plen - (4 + dlen + 4*4);
1645 if (strcmp(term, "") == 0)
1648 /* Get window size from the packet. */
1649 row = packet_get_int();
1650 col = packet_get_int();
1651 xpixel = packet_get_int();
1652 ypixel = packet_get_int();
1653 pty_change_window_size(ptyfd, row, col, xpixel, ypixel);
1655 /* Get tty modes from the packet. */
1656 tty_parse_modes(ttyfd, &n_bytes);
1657 packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type);
1659 /* Indicate that we now have a pty. */
1663 case SSH_CMSG_X11_REQUEST_FORWARDING:
1664 if (!options.x11_forwarding)
1666 packet_send_debug("X11 forwarding disabled in server configuration file.");
1670 if (no_x11_forwarding_flag)
1672 packet_send_debug("X11 forwarding not permitted for this authentication.");
1675 debug("Received request for X11 forwarding with auth spoofing.");
1677 packet_disconnect("Protocol error: X11 display already set.");
1679 int proto_len, data_len;
1680 proto = packet_get_string(&proto_len);
1681 data = packet_get_string(&data_len);
1682 packet_integrity_check(plen, 4+proto_len + 4+data_len + 4, type);
1684 if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
1685 screen = packet_get_int();
1688 display = x11_create_display_inet(screen);
1692 /* Setup to always have a local .Xauthority. */
1693 xauthfile = xmalloc(MAXPATHLEN);
1694 snprintf(xauthfile, MAXPATHLEN, "/tmp/XauthXXXXXX");
1696 if ((xauthfd = mkstemp(xauthfile)) != -1) {
1697 fchown(xauthfd, pw->pw_uid, pw->pw_gid);
1705 #else /* XAUTH_PATH */
1706 /* No xauth program; we won't accept forwarding with spoofing. */
1707 packet_send_debug("No xauth program; cannot forward with spoofing.");
1709 #endif /* XAUTH_PATH */
1711 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
1712 if (no_agent_forwarding_flag)
1714 debug("Authentication agent forwarding not permitted for this authentication.");
1717 debug("Received authentication agent forwarding request.");
1718 auth_input_request_forwarding(pw);
1721 case SSH_CMSG_PORT_FORWARD_REQUEST:
1722 if (no_port_forwarding_flag)
1724 debug("Port forwarding not permitted for this authentication.");
1727 debug("Received TCP/IP port forwarding request.");
1728 channel_input_port_forward_request(pw->pw_uid == 0);
1731 case SSH_CMSG_EXEC_SHELL:
1732 /* Set interactive/non-interactive mode. */
1733 packet_set_interactive(have_pty || display != NULL,
1734 options.keepalives);
1736 if (forced_command != NULL)
1737 goto do_forced_command;
1738 debug("Forking shell.");
1739 packet_integrity_check(plen, 0, type);
1741 do_exec_pty(NULL, ptyfd, ttyfd, ttyname, pw, term, display, proto,
1744 do_exec_no_pty(NULL, pw, display, proto, data);
1747 case SSH_CMSG_EXEC_CMD:
1748 /* Set interactive/non-interactive mode. */
1749 packet_set_interactive(have_pty || display != NULL,
1750 options.keepalives);
1752 if (forced_command != NULL)
1753 goto do_forced_command;
1754 /* Get command from the packet. */
1757 command = packet_get_string(&dlen);
1758 debug("Executing command '%.500s'", command);
1759 packet_integrity_check(plen, 4 + dlen, type);
1762 do_exec_pty(command, ptyfd, ttyfd, ttyname, pw, term, display,
1765 do_exec_no_pty(command, pw, display, proto, data);
1769 case SSH_CMSG_MAX_PACKET_SIZE:
1770 debug("The server does not support limiting packet size.");
1774 /* Any unknown messages in this phase are ignored, and a failure
1775 message is returned. */
1776 log("Unknown packet type received after authentication: %d", type);
1780 /* The request was successfully processed. */
1781 packet_start(SSH_SMSG_SUCCESS);
1783 packet_write_wait();
1785 /* Enable compression now that we have replied if appropriate. */
1786 if (enable_compression_after_reply)
1788 enable_compression_after_reply = 0;
1789 packet_start_compression(compression_level);
1795 /* The request failed. */
1796 packet_start(SSH_SMSG_FAILURE);
1798 packet_write_wait();
1802 /* There is a forced command specified for this login. Execute it. */
1803 debug("Executing forced command: %.900s", forced_command);
1805 do_exec_pty(forced_command, ptyfd, ttyfd, ttyname, pw, term, display,
1808 do_exec_no_pty(forced_command, pw, display, proto, data);
1813 /* This is called to fork and execute a command when we have no tty. This
1814 will call do_child from the child, and server_loop from the parent after
1815 setting up file descriptors and such. */
1817 void do_exec_no_pty(const char *command, struct passwd *pw,
1818 const char *display, const char *auth_proto,
1819 const char *auth_data)
1824 int pin[2], pout[2], perr[2];
1825 /* Allocate pipes for communicating with the program. */
1826 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
1827 packet_disconnect("Could not create pipes: %.100s",
1829 #else /* USE_PIPES */
1830 int inout[2], err[2];
1831 /* Uses socket pairs to communicate with the program. */
1832 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
1833 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
1834 packet_disconnect("Could not create socket pairs: %.100s",
1836 #endif /* USE_PIPES */
1838 setproctitle("%s@notty", pw->pw_name);
1840 /* Fork the child. */
1841 if ((pid = fork()) == 0)
1843 /* Child. Reinitialize the log since the pid has changed. */
1844 log_init(av0, debug_flag && !inetd_flag, debug_flag,
1845 options.quiet_mode, options.log_facility);
1847 /* Create a new session and process group since the 4.4BSD setlogin()
1848 affects the entire process group. */
1850 error("setsid failed: %.100s", strerror(errno));
1853 /* Redirect stdin. We close the parent side of the socket pair,
1854 and make the child side the standard input. */
1856 if (dup2(pin[0], 0) < 0)
1857 perror("dup2 stdin");
1860 /* Redirect stdout. */
1862 if (dup2(pout[1], 1) < 0)
1863 perror("dup2 stdout");
1866 /* Redirect stderr. */
1868 if (dup2(perr[1], 2) < 0)
1869 perror("dup2 stderr");
1871 #else /* USE_PIPES */
1872 /* Redirect stdin, stdout, and stderr. Stdin and stdout will use the
1873 same socket, as some programs (particularly rdist) seem to depend
1877 if (dup2(inout[0], 0) < 0) /* stdin */
1878 perror("dup2 stdin");
1879 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
1880 perror("dup2 stdout");
1881 if (dup2(err[0], 2) < 0) /* stderr */
1882 perror("dup2 stderr");
1883 #endif /* USE_PIPES */
1885 /* Do processing for the child (exec command etc). */
1886 do_child(command, pw, NULL, display, auth_proto, auth_data, NULL);
1890 packet_disconnect("fork failed: %.100s", strerror(errno));
1892 /* We are the parent. Close the child sides of the pipes. */
1897 /* Enter the interactive session. */
1898 server_loop(pid, pin[1], pout[0], perr[0]);
1899 /* server_loop has closed pin[1], pout[1], and perr[1]. */
1900 #else /* USE_PIPES */
1901 /* We are the parent. Close the child sides of the socket pairs. */
1905 /* Enter the interactive session. Note: server_loop must be able to handle
1906 the case that fdin and fdout are the same. */
1907 server_loop(pid, inout[1], inout[1], err[1]);
1908 /* server_loop has closed inout[1] and err[1]. */
1909 #endif /* USE_PIPES */
1912 struct pty_cleanup_context
1914 const char *ttyname;
1918 /* Function to perform cleanup if we get aborted abnormally (e.g., due to a
1919 dropped connection). */
1921 void pty_cleanup_proc(void *context)
1923 struct pty_cleanup_context *cu = context;
1925 debug("pty_cleanup_proc called");
1928 /* Destroy user's ticket cache file. */
1932 /* Record that the user has logged out. */
1933 record_logout(cu->pid, cu->ttyname);
1935 /* Release the pseudo-tty. */
1936 pty_release(cu->ttyname);
1939 /* This is called to fork and execute a command when we have a tty. This
1940 will call do_child from the child, and server_loop from the parent after
1941 setting up file descriptors, controlling tty, updating wtmp, utmp,
1942 lastlog, and other such operations. */
1944 void do_exec_pty(const char *command, int ptyfd, int ttyfd,
1945 const char *ttyname, struct passwd *pw, const char *term,
1946 const char *display, const char *auth_proto,
1947 const char *auth_data)
1950 const char *hostname;
1951 time_t last_login_time;
1952 char buf[100], *time_string;
1957 struct sockaddr_in from;
1959 struct pty_cleanup_context cleanup_context;
1961 /* Get remote host name. */
1962 hostname = get_canonical_hostname();
1964 /* Get the time when the user last logged in. Buf will be set to contain
1965 the hostname the last login was from. */
1966 if(!options.use_login) {
1967 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
1971 setproctitle("%s@%s", pw->pw_name, strrchr(ttyname, '/') + 1);
1973 /* Fork the child. */
1974 if ((pid = fork()) == 0)
1978 /* Child. Reinitialize the log because the pid has changed. */
1979 log_init(av0, debug_flag && !inetd_flag, debug_flag, options.quiet_mode,
1980 options.log_facility);
1982 /* Close the master side of the pseudo tty. */
1985 /* Make the pseudo tty our controlling tty. */
1986 pty_make_controlling_tty(&ttyfd, ttyname);
1988 /* Redirect stdin from the pseudo tty. */
1989 if (dup2(ttyfd, fileno(stdin)) < 0)
1990 error("dup2 stdin failed: %.100s", strerror(errno));
1992 /* Redirect stdout to the pseudo tty. */
1993 if (dup2(ttyfd, fileno(stdout)) < 0)
1994 error("dup2 stdin failed: %.100s", strerror(errno));
1996 /* Redirect stderr to the pseudo tty. */
1997 if (dup2(ttyfd, fileno(stderr)) < 0)
1998 error("dup2 stdin failed: %.100s", strerror(errno));
2000 /* Close the extra descriptor for the pseudo tty. */
2003 /* Get IP address of client. This is needed because we want to record
2004 where the user logged in from. If the connection is not a socket,
2005 let the ip address be 0.0.0.0. */
2006 memset(&from, 0, sizeof(from));
2007 if (packet_get_connection_in() == packet_get_connection_out())
2009 fromlen = sizeof(from);
2010 if (getpeername(packet_get_connection_in(),
2011 (struct sockaddr *)&from, &fromlen) < 0)
2012 fatal("getpeername: %.100s", strerror(errno));
2015 /* Record that there was a login on that terminal. */
2016 record_login(pid, ttyname, pw->pw_name, pw->pw_uid, hostname,
2019 /* Check if .hushlogin exists. */
2020 snprintf(line, sizeof line, "%.200s/.hushlogin", pw->pw_dir);
2021 quiet_login = stat(line, &st) >= 0;
2023 /* If the user has logged in before, display the time of last login.
2024 However, don't display anything extra if a command has been
2025 specified (so that ssh can be used to execute commands on a remote
2026 machine without users knowing they are going to another machine).
2027 Login(1) will do this for us as well, so check if login(1) is used */
2028 if (command == NULL && last_login_time != 0 && !quiet_login &&
2031 /* Convert the date to a string. */
2032 time_string = ctime(&last_login_time);
2033 /* Remove the trailing newline. */
2034 if (strchr(time_string, '\n'))
2035 *strchr(time_string, '\n') = 0;
2036 /* Display the last login time. Host if displayed if known. */
2037 if (strcmp(buf, "") == 0)
2038 printf("Last login: %s\r\n", time_string);
2040 printf("Last login: %s from %s\r\n", time_string, buf);
2043 /* Print /etc/motd unless a command was specified or printing it was
2044 disabled in server options or login(1) will be used. Note that
2045 some machines appear to print it in /etc/profile or similar. */
2046 if (command == NULL && options.print_motd && !quiet_login &&
2049 /* Print /etc/motd if it exists. */
2050 f = fopen("/etc/motd", "r");
2053 while (fgets(line, sizeof(line), f))
2054 fputs(line, stdout);
2059 /* Do common processing for the child, such as execing the command. */
2060 do_child(command, pw, term, display, auth_proto, auth_data, ttyname);
2064 packet_disconnect("fork failed: %.100s", strerror(errno));
2065 /* Parent. Close the slave side of the pseudo tty. */
2068 /* Create another descriptor of the pty master side for use as the standard
2069 input. We could use the original descriptor, but this simplifies code
2070 in server_loop. The descriptor is bidirectional. */
2073 packet_disconnect("dup failed: %.100s", strerror(errno));
2075 /* Add a cleanup function to clear the utmp entry and record logout time
2076 in case we call fatal() (e.g., the connection gets closed). */
2077 cleanup_context.pid = pid;
2078 cleanup_context.ttyname = ttyname;
2079 fatal_add_cleanup(pty_cleanup_proc, (void *)&cleanup_context);
2081 /* Enter interactive session. */
2082 server_loop(pid, ptyfd, fdout, -1);
2083 /* server_loop has not closed ptyfd and fdout. */
2085 /* Cancel the cleanup function. */
2086 fatal_remove_cleanup(pty_cleanup_proc, (void *)&cleanup_context);
2088 /* Record that the user has logged out. */
2089 record_logout(pid, ttyname);
2091 /* Release the pseudo-tty. */
2092 pty_release(ttyname);
2094 /* Close the server side of the socket pairs. We must do this after the
2095 pty cleanup, so that another process doesn't get this pty while we're
2096 still cleaning up. */
2101 /* Sets the value of the given variable in the environment. If the variable
2102 already exists, its value is overriden. */
2104 void child_set_env(char ***envp, unsigned int *envsizep, const char *name,
2107 unsigned int i, namelen;
2110 /* Find the slot where the value should be stored. If the variable already
2111 exists, we reuse the slot; otherwise we append a new slot at the end
2112 of the array, expanding if necessary. */
2114 namelen = strlen(name);
2115 for (i = 0; env[i]; i++)
2116 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
2120 /* Name already exists. Reuse the slot. */
2125 /* New variable. Expand the array if necessary. */
2126 if (i >= (*envsizep) - 1)
2129 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
2132 /* Need to set the NULL pointer at end of array beyond the new
2137 /* Allocate space and format the variable in the appropriate slot. */
2138 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
2139 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
2142 /* Reads environment variables from the given file and adds/overrides them
2143 into the environment. If the file does not exist, this does nothing.
2144 Otherwise, it must consist of empty lines, comments (line starts with '#')
2145 and assignments of the form name=value. No other forms are allowed. */
2147 void read_environment_file(char ***env, unsigned int *envsize,
2148 const char *filename)
2154 /* Open the environment file. */
2155 f = fopen(filename, "r");
2157 return; /* Not found. */
2159 /* Process each line. */
2160 while (fgets(buf, sizeof(buf), f))
2162 /* Skip leading whitespace. */
2163 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
2166 /* Ignore empty and comment lines. */
2167 if (!*cp || *cp == '#' || *cp == '\n')
2170 /* Remove newline. */
2171 if (strchr(cp, '\n'))
2172 *strchr(cp, '\n') = '\0';
2174 /* Find the equals sign. Its lack indicates badly formatted line. */
2175 value = strchr(cp, '=');
2178 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
2182 /* Replace the equals sign by nul, and advance value to the value
2187 /* Set the value in environment. */
2188 child_set_env(env, envsize, cp, value);
2194 /* Performs common processing for the child, such as setting up the
2195 environment, closing extra file descriptors, setting the user and group
2196 ids, and executing the command or shell. */
2198 void do_child(const char *command, struct passwd *pw, const char *term,
2199 const char *display, const char *auth_proto,
2200 const char *auth_data, const char *ttyname)
2202 const char *shell, *cp = NULL;
2205 unsigned int envsize, i;
2207 extern char **environ;
2211 /* Check /etc/nologin. */
2212 f = fopen("/etc/nologin", "r");
2214 { /* /etc/nologin exists. Print its contents and exit. */
2215 while (fgets(buf, sizeof(buf), f))
2218 if (pw->pw_uid != 0)
2222 /* Set uid, gid, and groups. */
2223 /* Login(1) does this as well, and it needs uid 0 for the "-h" switch,
2224 so we let login(1) to this for us. */
2225 if(!options.use_login) {
2226 if (getuid() == 0 || geteuid() == 0)
2228 if (setgid(pw->pw_gid) < 0)
2233 /* Initialize the group list. */
2234 if (initgroups(pw->pw_name, pw->pw_gid) < 0)
2236 perror("initgroups");
2241 /* Permanently switch to the desired uid. */
2242 permanently_set_uid(pw->pw_uid);
2245 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
2246 fatal("Failed to set uids to %d.", (int)pw->pw_uid);
2249 /* Get the shell from the password data. An empty shell field is legal,
2250 and means /bin/sh. */
2251 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
2254 /* Try to get AFS tokens for the local cell. */
2258 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
2259 krb_afslog(cell, 0);
2265 /* Initialize the environment. In the first part we allocate space for
2266 all environment variables. */
2268 env = xmalloc(envsize * sizeof(char *));
2271 if(!options.use_login) {
2272 /* Set basic environment. */
2273 child_set_env(&env, &envsize, "USER", pw->pw_name);
2274 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
2275 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
2276 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
2278 snprintf(buf, sizeof buf, "%.200s/%.50s",
2279 _PATH_MAILDIR, pw->pw_name);
2280 child_set_env(&env, &envsize, "MAIL", buf);
2282 /* Normal systems set SHELL by default. */
2283 child_set_env(&env, &envsize, "SHELL", shell);
2286 /* Let it inherit timezone if we have one. */
2288 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
2290 /* Set custom environment options from RSA authentication. */
2291 while (custom_environment)
2293 struct envstring *ce = custom_environment;
2296 for (i = 0; s[i] != '=' && s[i]; i++)
2301 child_set_env(&env, &envsize, s, s + i + 1);
2303 custom_environment = ce->next;
2308 /* Set SSH_CLIENT. */
2309 snprintf(buf, sizeof buf, "%.50s %d %d",
2310 get_remote_ipaddr(), get_remote_port(), options.port);
2311 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
2313 /* Set SSH_TTY if we have a pty. */
2315 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
2317 /* Set TERM if we have a pty. */
2319 child_set_env(&env, &envsize, "TERM", term);
2321 /* Set DISPLAY if we have one. */
2323 child_set_env(&env, &envsize, "DISPLAY", display);
2327 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
2330 /* Set XAUTHORITY to always be a local file. */
2332 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
2334 /* Set variable for forwarded authentication connection, if we have one. */
2335 if (auth_get_socket_name() != NULL)
2336 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
2337 auth_get_socket_name());
2339 /* Read $HOME/.ssh/environment. */
2340 if(!options.use_login) {
2341 snprintf(buf, sizeof buf, "%.200s/.ssh/environment", pw->pw_dir);
2342 read_environment_file(&env, &envsize, buf);
2345 /* If debugging, dump the environment to stderr. */
2348 fprintf(stderr, "Environment:\n");
2349 for (i = 0; env[i]; i++)
2350 fprintf(stderr, " %.200s\n", env[i]);
2353 /* Close the connection descriptors; note that this is the child, and the
2354 server will still have the socket open, and it is important that we
2355 do not shutdown it. Note that the descriptors cannot be closed before
2356 building the environment, as we call get_remote_ipaddr there. */
2357 if (packet_get_connection_in() == packet_get_connection_out())
2358 close(packet_get_connection_in());
2361 close(packet_get_connection_in());
2362 close(packet_get_connection_out());
2364 /* Close all descriptors related to channels. They will still remain
2365 open in the parent. */
2366 channel_close_all();
2368 /* Close any extra file descriptors. Note that there may still be
2369 descriptors left by system functions. They will be closed later. */
2373 /* Close any extra open file descriptors so that we don\'t have them
2374 hanging around in clients. Note that we want to do this after
2375 initgroups, because at least on Solaris 2.3 it leaves file descriptors
2377 for (i = 3; i < 64; i++)
2380 /* Change current directory to the user\'s home directory. */
2381 if (chdir(pw->pw_dir) < 0)
2382 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
2383 pw->pw_dir, strerror(errno));
2385 /* Must take new environment into use so that .ssh/rc, /etc/sshrc and
2386 xauth are run in the proper environment. */
2389 /* Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
2391 if(!options.use_login) {
2392 if (stat(SSH_USER_RC, &st) >= 0)
2395 fprintf(stderr, "Running /bin/sh %s\n", SSH_USER_RC);
2397 f = popen("/bin/sh " SSH_USER_RC, "w");
2400 if (auth_proto != NULL && auth_data != NULL)
2401 fprintf(f, "%s %s\n", auth_proto, auth_data);
2405 fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
2408 if (stat(SSH_SYSTEM_RC, &st) >= 0)
2411 fprintf(stderr, "Running /bin/sh %s\n", SSH_SYSTEM_RC);
2413 f = popen("/bin/sh " SSH_SYSTEM_RC, "w");
2416 if (auth_proto != NULL && auth_data != NULL)
2417 fprintf(f, "%s %s\n", auth_proto, auth_data);
2421 fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
2426 /* Add authority data to .Xauthority if appropriate. */
2427 if (auth_proto != NULL && auth_data != NULL)
2430 fprintf(stderr, "Running %.100s add %.100s %.100s %.100s\n",
2431 XAUTH_PATH, display, auth_proto, auth_data);
2433 f = popen(XAUTH_PATH " -q -", "w");
2436 fprintf(f, "add %s %s %s\n", display, auth_proto, auth_data);
2440 fprintf(stderr, "Could not run %s -q -\n", XAUTH_PATH);
2443 #endif /* XAUTH_PATH */
2445 /* Get the last component of the shell name. */
2446 cp = strrchr(shell, '/');
2453 /* If we have no command, execute the shell. In this case, the shell name
2454 to be passed in argv[0] is preceded by '-' to indicate that this is
2458 if(!options.use_login) {
2461 /* Check for mail if we have a tty and it was enabled in server options. */
2462 if (ttyname && options.check_mail) {
2464 struct stat mailstat;
2465 mailbox = getenv("MAIL");
2466 if(mailbox != NULL) {
2467 if(stat(mailbox, &mailstat) != 0 || mailstat.st_size == 0) {
2468 printf("No mail.\n");
2469 } else if(mailstat.st_mtime < mailstat.st_atime) {
2470 printf("You have mail.\n");
2472 printf("You have new mail.\n");
2476 /* Start the shell. Set initial character to '-'. */
2478 strncpy(buf + 1, cp, sizeof(buf) - 1);
2479 buf[sizeof(buf) - 1] = 0;
2480 /* Execute the shell. */
2483 execve(shell, argv, env);
2484 /* Executing the shell failed. */
2489 /* Launch login(1). */
2491 execl("/usr/bin/login", "login", "-h", get_remote_ipaddr(), "-p", "-f", "--", pw->pw_name, NULL);
2493 /* Login couldn't be executed, die. */
2500 /* Execute the command using the user's shell. This uses the -c option
2501 to execute the command. */
2502 argv[0] = (char *)cp;
2504 argv[2] = (char *)command;
2506 execve(shell, argv, env);