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
35 #ifdef HAVE_MAILLOCK_H
36 # include <maillock.h>
42 int allow_severity = LOG_INFO;
43 int deny_severity = LOG_WARNING;
50 /* Local Xauthority file. */
51 static 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 /* debug goes to stderr unless inetd_flag is set */
71 /* argv[0] without path. */
74 /* Saved arguments to main(). */
77 /* This is set to the socket that the server is listening; this is used in
78 the SIGHUP signal handler. */
81 /* Flags set in auth-rsa from authorized_keys flags. These are set in
83 int no_port_forwarding_flag = 0;
84 int no_agent_forwarding_flag = 0;
85 int no_x11_forwarding_flag = 0;
87 char *forced_command = NULL; /* RSA authentication "command=" option. */
88 struct envstring *custom_environment = NULL;
89 /* RSA authentication "environment=" options. */
91 /* Session id for the current session. */
92 unsigned char session_id[16];
94 /* Any really sensitive data in the application is contained in this structure.
95 The idea is that this structure could be locked into memory so that the
96 pages do not get written into swap. However, there are some problems.
97 The private key contains BIGNUMs, and we do not (in principle) have
98 access to the internals of them, and locking just the structure is not
99 very useful. Currently, memory locking is not implemented. */
102 /* Private part of server key. */
105 /* Private part of host key. */
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. */
113 /* This is set to true when SIGHUP is received. */
114 int received_sighup = 0;
116 /* Public side of the server key. This value is regenerated regularly with
120 /* Prototypes for various functions defined later in this file. */
121 void do_connection();
122 void do_authentication(char *user);
123 void do_authloop(struct passwd *pw);
124 void do_fake_authloop(char *user);
125 void do_authenticated(struct passwd *pw);
126 void do_exec_pty(const char *command, int ptyfd, int ttyfd,
127 const char *ttyname, struct passwd *pw, const char *term,
128 const char *display, const char *auth_proto,
129 const char *auth_data);
130 void do_exec_no_pty(const char *command, struct passwd *pw,
131 const char *display, const char *auth_proto,
132 const char *auth_data);
133 void do_child(const char *command, struct passwd *pw, const char *term,
134 const char *display, const char *auth_proto,
135 const char *auth_data, const char *ttyname);
138 static int pamconv(int num_msg, const struct pam_message **msg,
139 struct pam_response **resp, void *appdata_ptr);
140 void do_pam_account_and_session(char *username, char *remote_user,
141 const char *remote_host);
142 void pam_cleanup_proc(void *context);
144 static struct pam_conv conv = {
148 struct pam_handle_t *pamh = NULL;
149 const char *pampasswd = NULL;
150 char *pamconv_msg = NULL;
152 static int pamconv(int num_msg, const struct pam_message **msg,
153 struct pam_response **resp, void *appdata_ptr)
155 struct pam_response *reply;
160 /* PAM will free this later */
161 reply = malloc(num_msg * sizeof(*reply));
165 for(count = 0; count < num_msg; count++)
167 switch (msg[count]->msg_style)
169 case PAM_PROMPT_ECHO_OFF:
170 if (pampasswd == NULL)
175 reply[count].resp_retcode = PAM_SUCCESS;
176 reply[count].resp = xstrdup(pampasswd);
180 reply[count].resp_retcode = PAM_SUCCESS;
181 reply[count].resp = xstrdup("");
183 if (msg[count]->msg == NULL)
185 debug("Adding PAM message: %s", msg[count]->msg);
187 msg_len = strlen(msg[count]->msg);
190 size_t n = strlen(pamconv_msg);
191 pamconv_msg = xrealloc(pamconv_msg, n + msg_len + 2);
195 pamconv_msg = p = xmalloc(msg_len + 2);
196 memcpy(p, msg[count]->msg, msg_len);
198 p[msg_len + 1] = '\0';
201 case PAM_PROMPT_ECHO_ON:
214 void pam_cleanup_proc(void *context)
220 pam_retval = pam_close_session((pam_handle_t *)pamh, 0);
221 if (pam_retval != PAM_SUCCESS)
223 log("Cannot close PAM session: %.200s",
224 pam_strerror((pam_handle_t *)pamh, pam_retval));
227 pam_retval = pam_end((pam_handle_t *)pamh, pam_retval);
228 if (pam_retval != PAM_SUCCESS)
230 log("Cannot release PAM authentication: %.200s",
231 pam_strerror((pam_handle_t *)pamh, pam_retval));
236 void do_pam_account_and_session(char *username, char *remote_user,
237 const char *remote_host)
241 if (remote_host != NULL)
243 debug("PAM setting rhost to \"%.200s\"", remote_host);
244 pam_retval = pam_set_item((pam_handle_t *)pamh, PAM_RHOST, remote_host);
245 if (pam_retval != PAM_SUCCESS)
247 log("PAM set rhost failed: %.200s", pam_strerror((pam_handle_t *)pamh, pam_retval));
248 do_fake_authloop(username);
252 if (remote_user != NULL)
254 debug("PAM setting ruser to \"%.200s\"", remote_user);
255 pam_retval = pam_set_item((pam_handle_t *)pamh, PAM_RUSER, remote_user);
256 if (pam_retval != PAM_SUCCESS)
258 log("PAM set ruser failed: %.200s", pam_strerror((pam_handle_t *)pamh, pam_retval));
259 do_fake_authloop(username);
263 pam_retval = pam_acct_mgmt((pam_handle_t *)pamh, 0);
264 if (pam_retval != PAM_SUCCESS)
266 log("PAM rejected by account configuration: %.200s", pam_strerror((pam_handle_t *)pamh, pam_retval));
267 do_fake_authloop(username);
270 pam_retval = pam_open_session((pam_handle_t *)pamh, 0);
271 if (pam_retval != PAM_SUCCESS)
273 log("PAM session setup failed: %.200s", pam_strerror((pam_handle_t *)pamh, pam_retval));
274 do_fake_authloop(username);
277 #endif /* HAVE_LIBPAM */
279 /* Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
280 the effect is to reread the configuration file (and to regenerate
283 void sighup_handler(int sig)
286 signal(SIGHUP, sighup_handler);
289 /* Called from the main program after receiving SIGHUP. Restarts the
292 void sighup_restart()
294 log("Received SIGHUP; restarting.");
296 execv(saved_argv[0], saved_argv);
297 log("RESTART FAILED: av0='%s', error: %s.", av0, strerror(errno));
301 /* Generic signal handler for terminating signals in the master daemon.
302 These close the listen socket; not closing it seems to cause "Address
303 already in use" problems on some machines, which is inconvenient. */
305 void sigterm_handler(int sig)
307 log("Received signal %d; terminating.", sig);
312 /* SIGCHLD handler. This is called whenever a child dies. This will then
313 reap any zombies left by exited c. */
315 void main_sigchld_handler(int sig)
317 int save_errno = errno;
320 signal(SIGCHLD, main_sigchld_handler);
324 /* Signal handler for the alarm after the login grace period has expired. */
326 void grace_alarm_handler(int sig)
328 /* Close the connection. */
331 /* Log error and exit. */
332 fatal("Timeout before authentication.");
335 /* Signal handler for the key regeneration alarm. Note that this
336 alarm only occurs in the daemon waiting for connections, and it does not
337 do anything with the private key or random state before forking. Thus there
338 should be no concurrency control/asynchronous execution problems. */
340 void key_regeneration_alarm(int sig)
342 int save_errno = errno;
344 /* Check if we should generate a new key. */
347 /* This should really be done in the background. */
348 log("Generating new %d bit RSA key.", options.server_key_bits);
350 if (sensitive_data.private_key != NULL)
351 RSA_free(sensitive_data.private_key);
352 sensitive_data.private_key = RSA_new();
354 if (public_key != NULL)
355 RSA_free(public_key);
356 public_key = RSA_new();
358 rsa_generate_key(sensitive_data.private_key, public_key,
359 options.server_key_bits);
362 log("RSA key generation complete.");
365 /* Reschedule the alarm. */
366 signal(SIGALRM, key_regeneration_alarm);
367 alarm(options.key_regeneration_time);
371 /* Main program for the daemon. */
374 main(int ac, char **av)
378 int opt, aux, sock_in, sock_out, newsock, i, pid, on = 1;
379 int remote_major, remote_minor;
381 struct sockaddr_in sin;
382 char buf[100]; /* Must not be larger than remote_version. */
383 char remote_version[100]; /* Must be at least as big as buf. */
387 struct linger linger;
391 if (strchr(av[0], '/'))
392 av0 = strrchr(av[0], '/') + 1;
396 /* Initialize configuration options to their default values. */
397 initialize_server_options(&options);
399 /* Parse command-line arguments. */
400 while ((opt = getopt(ac, av, "f:p:b:k:h:g:diqQ")) != EOF)
405 config_file_name = optarg;
409 options.log_level = SYSLOG_LEVEL_DEBUG;
418 options.log_level = SYSLOG_LEVEL_QUIET;
421 options.server_key_bits = atoi(optarg);
424 options.port = atoi(optarg);
427 options.login_grace_time = atoi(optarg);
430 options.key_regeneration_time = atoi(optarg);
433 options.host_key_file = optarg;
437 fprintf(stderr, "sshd version %s\n", SSH_VERSION);
438 fprintf(stderr, "Usage: %s [options]\n", av0);
439 fprintf(stderr, "Options:\n");
440 fprintf(stderr, " -f file Configuration file (default %s/sshd_config)\n", ETCDIR);
441 fprintf(stderr, " -d Debugging mode\n");
442 fprintf(stderr, " -i Started from inetd\n");
443 fprintf(stderr, " -q Quiet (no logging)\n");
444 fprintf(stderr, " -p port Listen on the specified port (default: 22)\n");
445 fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n");
446 fprintf(stderr, " -g seconds Grace period for authentication (default: 300)\n");
447 fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n");
448 fprintf(stderr, " -h file File from which to read host key (default: %s)\n",
454 /* check if RSA support exists */
455 if (rsa_alive() == 0) {
457 printf("sshd: no RSA support in libssl and libcrypto -- exiting. See ssl(8)\n");
458 log("no RSA support in libssl and libcrypto -- exiting. See ssl(8)");
462 /* Read server configuration options from the configuration file. */
463 read_server_config(&options, config_file_name);
465 /* Fill in default values for those options not explicitly set. */
466 fill_default_server_options(&options);
468 /* Check certain values for sanity. */
469 if (options.server_key_bits < 512 ||
470 options.server_key_bits > 32768)
472 fprintf(stderr, "Bad server key size.\n");
475 if (options.port < 1 || options.port > 65535)
477 fprintf(stderr, "Bad port number.\n");
481 /* Check that there are no remaining arguments. */
484 fprintf(stderr, "Extra argument %s.\n", av[optind]);
488 /* Force logging to stderr while loading the private host key
489 unless started from inetd */
490 log_init(av0, options.log_level, options.log_facility, !inetd_flag);
492 debug("sshd version %.100s", SSH_VERSION);
494 sensitive_data.host_key = RSA_new();
496 /* Load the host key. It must have empty passphrase. */
497 if (!load_private_key(options.host_key_file, "",
498 sensitive_data.host_key, &comment))
500 error("Could not load host key: %.200s: %.100s",
501 options.host_key_file, strerror(errno));
506 /* Initialize the log (it is reinitialized below in case we forked). */
507 if (debug_flag && !inetd_flag)
509 log_init(av0, options.log_level, options.log_facility, log_stderr);
511 /* If not in debugging mode, and not started from inetd, disconnect from
512 the controlling terminal, and fork. The original process exits. */
513 if (!debug_flag && !inetd_flag)
517 #endif /* TIOCNOTTY */
518 if (daemon(0, 0) < 0)
519 fatal("daemon() failed: %.200s", strerror(errno));
521 /* Disconnect from the controlling tty. */
523 fd = open("/dev/tty", O_RDWR|O_NOCTTY);
526 (void)ioctl(fd, TIOCNOTTY, NULL);
529 #endif /* TIOCNOTTY */
532 /* Reinitialize the log (because of the fork above). */
533 log_init(av0, options.log_level, options.log_facility, log_stderr);
535 /* Check that server and host key lengths differ sufficiently. This is
536 necessary to make double encryption work with rsaref. Oh, I hate
537 software patents. I dont know if this can go? Niels */
538 if (options.server_key_bits >
539 BN_num_bits(sensitive_data.host_key->n) - SSH_KEY_BITS_RESERVED &&
540 options.server_key_bits <
541 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED)
543 options.server_key_bits =
544 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED;
545 debug("Forcing server key to %d bits to make it differ from host key.",
546 options.server_key_bits);
549 /* Do not display messages to stdout in RSA code. */
552 /* Initialize the random number generator. */
555 /* Chdir to the root directory so that the current disk can be unmounted
559 /* Close connection cleanly after attack. */
560 cipher_attack_detected = packet_disconnect;
562 /* Start listening for a socket, unless started from inetd. */
566 s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */
570 /* We intentionally do not close the descriptors 0, 1, and 2 as our
571 code for setting the descriptors won\'t work if ttyfd happens to
573 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
575 public_key = RSA_new();
576 sensitive_data.private_key = RSA_new();
577 /* Generate an rsa key. */
578 log("Generating %d bit RSA key.", options.server_key_bits);
579 rsa_generate_key(sensitive_data.private_key, public_key,
580 options.server_key_bits);
582 log("RSA key generation complete.");
586 /* Create socket for listening. */
587 listen_sock = socket(AF_INET, SOCK_STREAM, 0);
589 fatal("socket: %.100s", strerror(errno));
591 /* Set socket options. We try to make the port reusable and have it
592 close as fast as possible without waiting in unnecessary wait states
594 setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on,
598 setsockopt(listen_sock, SOL_SOCKET, SO_LINGER, (void *)&linger,
601 /* Initialize the socket address. */
602 memset(&sin, 0, sizeof(sin));
603 sin.sin_family = AF_INET;
604 sin.sin_addr = options.listen_addr;
605 sin.sin_port = htons(options.port);
607 /* Bind the socket to the desired port. */
608 if (bind(listen_sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
610 error("bind: %.100s", strerror(errno));
611 shutdown(listen_sock, SHUT_RDWR);
613 fatal("Bind to port %d failed.", options.port);
618 /* Record our pid in /etc/sshd_pid to make it easier to kill the
619 correct sshd. We don\'t want to do this before the bind above
620 because the bind will fail if there already is a daemon, and this
621 will overwrite any old pid in the file. */
622 f = fopen(SSH_DAEMON_PID_FILE, "w");
625 fprintf(f, "%u\n", (unsigned int)getpid());
630 /* Start listening on the port. */
631 log("Server listening on port %d.", options.port);
632 if (listen(listen_sock, 5) < 0)
633 fatal("listen: %.100s", strerror(errno));
635 public_key = RSA_new();
636 sensitive_data.private_key = RSA_new();
637 /* Generate an rsa key. */
638 log("Generating %d bit RSA key.", options.server_key_bits);
639 rsa_generate_key(sensitive_data.private_key, public_key,
640 options.server_key_bits);
642 log("RSA key generation complete.");
644 /* Schedule server key regeneration alarm. */
645 signal(SIGALRM, key_regeneration_alarm);
646 alarm(options.key_regeneration_time);
648 /* Arrange to restart on SIGHUP. The handler needs listen_sock. */
649 signal(SIGHUP, sighup_handler);
650 signal(SIGTERM, sigterm_handler);
651 signal(SIGQUIT, sigterm_handler);
653 /* Arrange SIGCHLD to be caught. */
654 signal(SIGCHLD, main_sigchld_handler);
656 /* Stay listening for connections until the system crashes or the
657 daemon is killed with a signal. */
662 /* Wait in accept until there is a connection. */
664 newsock = accept(listen_sock, (struct sockaddr *)&sin, &aux);
671 error("accept: %.100s", strerror(errno));
675 /* Got connection. Fork a child to handle it, unless we are in
679 /* In debugging mode. Close the listening socket, and start
680 processing the connection without forking. */
681 debug("Server will not fork when running in debugging mode.");
690 /* Normal production daemon. Fork, and have the child process
691 the connection. The parent continues listening. */
692 if ((pid = fork()) == 0)
694 /* Child. Close the listening socket, and start using
695 the accepted socket. Reinitialize logging (since our
696 pid has changed). We break out of the loop to handle
701 log_init(av0, options.log_level, options.log_facility, log_stderr);
706 /* Parent. Stay in the loop. */
708 error("fork: %.100s", strerror(errno));
710 debug("Forked child %d.", pid);
712 /* Mark that the key has been used (it was "given" to the child). */
717 /* Close the new socket (the child is now taking care of it). */
722 /* This is the child processing a new connection. */
724 /* Disable the key regeneration alarm. We will not regenerate the key
725 since we are no longer in a position to give it to anyone. We will
726 not restart on SIGHUP since it no longer makes sense. */
728 signal(SIGALRM, SIG_DFL);
729 signal(SIGHUP, SIG_DFL);
730 signal(SIGTERM, SIG_DFL);
731 signal(SIGQUIT, SIG_DFL);
732 signal(SIGCHLD, SIG_DFL);
734 /* Set socket options for the connection. We want the socket to close
735 as fast as possible without waiting for anything. If the connection
736 is not a socket, these will do nothing. */
737 /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
740 setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *)&linger, sizeof(linger));
742 /* Register our connection. This turns encryption off because we do not
744 packet_set_connection(sock_in, sock_out);
746 remote_port = get_remote_port();
748 /* Check whether logins are denied from this host. */
751 struct request_info req;
753 request_init(&req, RQ_DAEMON, av0, RQ_FILE, sock_in, NULL);
756 if (!hosts_access(&req)) {
761 log("Connection from %.500s port %d", eval_client(&req), remote_port);
764 /* Log the connection. */
765 log("Connection from %.100s port %d", get_remote_ipaddr(), remote_port);
768 /* We don\'t want to listen forever unless the other side successfully
769 authenticates itself. So we set up an alarm which is cleared after
770 successful authentication. A limit of zero indicates no limit.
771 Note that we don\'t set the alarm in debugging mode; it is just annoying
772 to have the server exit just when you are about to discover the bug. */
773 signal(SIGALRM, grace_alarm_handler);
775 alarm(options.login_grace_time);
777 /* Send our protocol version identification. */
778 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n",
779 PROTOCOL_MAJOR, PROTOCOL_MINOR, SSH_VERSION);
780 if (write(sock_out, buf, strlen(buf)) != strlen(buf))
781 fatal("Could not write ident string.");
783 /* Read other side\'s version identification. */
784 for (i = 0; i < sizeof(buf) - 1; i++)
786 if (read(sock_in, &buf[i], 1) != 1)
787 fatal("Did not receive ident string.");
801 buf[sizeof(buf) - 1] = 0;
803 /* Check that the versions match. In future this might accept several
804 versions and set appropriate flags to handle them. */
805 if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", &remote_major, &remote_minor,
806 remote_version) != 3)
808 const char *s = "Protocol mismatch.\n";
809 (void) write(sock_out, s, strlen(s));
812 fatal("Bad protocol version identification: %.100s", buf);
814 debug("Client protocol version %d.%d; client software version %.100s",
815 remote_major, remote_minor, remote_version);
816 if (remote_major != PROTOCOL_MAJOR)
818 const char *s = "Protocol major versions differ.\n";
819 (void) write(sock_out, s, strlen(s));
822 fatal("Protocol major versions differ: %d vs. %d",
823 PROTOCOL_MAJOR, remote_major);
826 /* Check that the client has sufficiently high software version. */
827 if (remote_major == 1 && remote_minor < 3)
828 packet_disconnect("Your ssh version is too old and is no longer supported. Please install a newer version.");
830 if (remote_major == 1 && remote_minor == 3) {
832 if (strcmp(remote_version, "OpenSSH-1.1") != 0) {
833 debug("Agent forwarding disabled, remote version is not compatible.");
834 no_agent_forwarding_flag = 1;
838 /* Check that the connection comes from a privileged port.
839 Rhosts- and Rhosts-RSA-Authentication only make sense
840 from priviledged programs.
841 Of course, if the intruder has root access on his local machine,
842 he can connect from any port. So do not use these authentication
843 methods from machines that you do not trust. */
844 if (remote_port >= IPPORT_RESERVED ||
845 remote_port < IPPORT_RESERVED / 2)
847 options.rhosts_authentication = 0;
848 options.rhosts_rsa_authentication = 0;
851 packet_set_nonblocking();
853 /* Handle the connection. */
857 /* Cleanup user's ticket cache file. */
858 if (options.kerberos_ticket_cleanup)
862 /* Cleanup user's local Xauthority file. */
863 if (xauthfile) unlink(xauthfile);
865 /* The connection has been terminated. */
866 log("Closing connection to %.100s", inet_ntoa(sin.sin_addr));
874 debug("Closing PAM session.");
875 retval = pam_close_session((pam_handle_t *)pamh, 0);
877 debug("Terminating PAM library.");
878 if (pam_end((pam_handle_t *)pamh, retval) != PAM_SUCCESS)
879 log("Cannot release PAM authentication.");
881 fatal_remove_cleanup(&pam_cleanup_proc, NULL);
884 #endif /* HAVE_LIBPAM */
891 /* Process an incoming connection. Protocol version identifiers have already
892 been exchanged. This sends server key and performs the key exchange.
893 Server and host keys will no longer be needed after this functions. */
899 BIGNUM *session_key_int;
900 unsigned char session_key[SSH_SESSION_KEY_LENGTH];
901 unsigned char check_bytes[8];
903 unsigned int cipher_type, auth_mask, protocol_flags;
907 /* Generate check bytes that the client must send back in the user packet
908 in order for it to be accepted; this is used to defy ip spoofing
909 attacks. Note that this only works against somebody doing IP spoofing
910 from a remote machine; any machine on the local network can still see
911 outgoing packets and catch the random cookie. This only affects
912 rhosts authentication, and this is one of the reasons why it is
913 inherently insecure. */
914 for (i = 0; i < 8; i++) {
917 check_bytes[i] = rand & 0xff;
921 /* Send our public key. We include in the packet 64 bits of random
922 data that must be matched in the reply in order to prevent IP spoofing. */
923 packet_start(SSH_SMSG_PUBLIC_KEY);
924 for (i = 0; i < 8; i++)
925 packet_put_char(check_bytes[i]);
927 /* Store our public server RSA key. */
928 packet_put_int(BN_num_bits(public_key->n));
929 packet_put_bignum(public_key->e);
930 packet_put_bignum(public_key->n);
932 /* Store our public host RSA key. */
933 packet_put_int(BN_num_bits(sensitive_data.host_key->n));
934 packet_put_bignum(sensitive_data.host_key->e);
935 packet_put_bignum(sensitive_data.host_key->n);
937 /* Put protocol flags. */
938 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
940 /* Declare which ciphers we support. */
941 packet_put_int(cipher_mask());
943 /* Declare supported authentication types. */
945 if (options.rhosts_authentication)
946 auth_mask |= 1 << SSH_AUTH_RHOSTS;
947 if (options.rhosts_rsa_authentication)
948 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
949 if (options.rsa_authentication)
950 auth_mask |= 1 << SSH_AUTH_RSA;
952 if (options.kerberos_authentication)
953 auth_mask |= 1 << SSH_AUTH_KERBEROS;
956 if (options.kerberos_tgt_passing)
957 auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
958 if (options.afs_token_passing)
959 auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
961 if (options.password_authentication)
962 auth_mask |= 1 << SSH_AUTH_PASSWORD;
963 packet_put_int(auth_mask);
965 /* Send the packet and wait for it to be sent. */
969 debug("Sent %d bit public key and %d bit host key.",
970 BN_num_bits(public_key->n), BN_num_bits(sensitive_data.host_key->n));
972 /* Read clients reply (cipher type and session key). */
973 packet_read_expect(&plen, SSH_CMSG_SESSION_KEY);
975 /* Get cipher type. */
976 cipher_type = packet_get_char();
978 /* Get check bytes from the packet. These must match those we sent earlier
979 with the public key packet. */
980 for (i = 0; i < 8; i++)
981 if (check_bytes[i] != packet_get_char())
982 packet_disconnect("IP Spoofing check bytes do not match.");
984 debug("Encryption type: %.200s", cipher_name(cipher_type));
986 /* Get the encrypted integer. */
987 session_key_int = BN_new();
988 packet_get_bignum(session_key_int, &slen);
990 /* Get protocol flags. */
991 protocol_flags = packet_get_int();
992 packet_set_protocol_flags(protocol_flags);
994 packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY);
996 /* Decrypt it using our private server key and private host key (key with
997 larger modulus first). */
998 if (BN_cmp(sensitive_data.private_key->n, sensitive_data.host_key->n) > 0)
1000 /* Private key has bigger modulus. */
1001 if (BN_num_bits(sensitive_data.private_key->n) <
1002 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
1003 fatal("do_connection: private_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1004 BN_num_bits(sensitive_data.private_key->n),
1005 BN_num_bits(sensitive_data.host_key->n),
1006 SSH_KEY_BITS_RESERVED);
1009 rsa_private_decrypt(session_key_int, session_key_int,
1010 sensitive_data.private_key);
1011 rsa_private_decrypt(session_key_int, session_key_int,
1012 sensitive_data.host_key);
1016 /* Host key has bigger modulus (or they are equal). */
1017 if (BN_num_bits(sensitive_data.host_key->n) <
1018 BN_num_bits(sensitive_data.private_key->n) + SSH_KEY_BITS_RESERVED) {
1019 fatal("do_connection: host_key %d < private_key %d + SSH_KEY_BITS_RESERVED %d",
1020 BN_num_bits(sensitive_data.host_key->n),
1021 BN_num_bits(sensitive_data.private_key->n),
1022 SSH_KEY_BITS_RESERVED);
1024 rsa_private_decrypt(session_key_int, session_key_int,
1025 sensitive_data.host_key);
1026 rsa_private_decrypt(session_key_int, session_key_int,
1027 sensitive_data.private_key);
1030 /* Compute session id for this session. */
1031 compute_session_id(session_id, check_bytes,
1032 sensitive_data.host_key->n,
1033 sensitive_data.private_key->n);
1035 /* Extract session key from the decrypted integer. The key is in the
1036 least significant 256 bits of the integer; the first byte of the
1037 key is in the highest bits. */
1038 BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1039 len = BN_num_bytes(session_key_int);
1040 if (len < 0 || len > sizeof(session_key))
1041 fatal("do_connection: bad len: session_key_int %d > sizeof(session_key) %d",
1042 len, sizeof(session_key));
1043 memset(session_key, 0, sizeof(session_key));
1044 BN_bn2bin(session_key_int, session_key + sizeof(session_key) - len);
1046 /* Xor the first 16 bytes of the session key with the session id. */
1047 for (i = 0; i < 16; i++)
1048 session_key[i] ^= session_id[i];
1050 /* Destroy the decrypted integer. It is no longer needed. */
1051 BN_clear_free(session_key_int);
1053 /* Set the session key. From this on all communications will be
1055 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
1057 /* Destroy our copy of the session key. It is no longer needed. */
1058 memset(session_key, 0, sizeof(session_key));
1060 debug("Received session key; encryption turned on.");
1062 /* Send an acknowledgement packet. Note that this packet is sent
1064 packet_start(SSH_SMSG_SUCCESS);
1066 packet_write_wait();
1068 /* Get the name of the user that we wish to log in as. */
1069 packet_read_expect(&plen, SSH_CMSG_USER);
1071 /* Get the user name. */
1074 user = packet_get_string(&ulen);
1075 packet_integrity_check(plen, (4 + ulen), SSH_CMSG_USER);
1078 /* Destroy the private and public keys. They will no longer be needed. */
1079 RSA_free(public_key);
1080 RSA_free(sensitive_data.private_key);
1081 RSA_free(sensitive_data.host_key);
1083 setproctitle("%s", user);
1084 /* Do the authentication. */
1085 do_authentication(user);
1088 /* Check if the user is allowed to log in via ssh. If user is listed in
1089 DenyUsers or user's primary group is listed in DenyGroups, false will
1090 be returned. If AllowUsers isn't empty and user isn't listed there, or
1091 if AllowGroups isn't empty and user isn't listed there, false will be
1092 returned. Otherwise true is returned.
1093 XXX This function should also check if user has a valid shell */
1096 allowed_user(struct passwd *pw)
1101 /* Shouldn't be called if pw is NULL, but better safe than sorry... */
1105 /* XXX Should check for valid login shell */
1107 /* Return false if user is listed in DenyUsers */
1108 if (options.num_deny_users > 0)
1112 for (i = 0; i < options.num_deny_users; i++)
1113 if (match_pattern(pw->pw_name, options.deny_users[i]))
1117 /* Return false if AllowUsers isn't empty and user isn't listed there */
1118 if (options.num_allow_users > 0)
1122 for (i = 0; i < options.num_allow_users; i++)
1123 if (match_pattern(pw->pw_name, options.allow_users[i]))
1125 /* i < options.num_allow_users iff we break for loop */
1126 if (i >= options.num_allow_users)
1130 /* Get the primary group name if we need it. Return false if it fails */
1131 if (options.num_deny_groups > 0 || options.num_allow_groups > 0 )
1133 grp = getgrgid(pw->pw_gid);
1137 /* Return false if user's group is listed in DenyGroups */
1138 if (options.num_deny_groups > 0)
1142 for (i = 0; i < options.num_deny_groups; i++)
1143 if (match_pattern(grp->gr_name, options.deny_groups[i]))
1147 /* Return false if AllowGroups isn't empty and user's group isn't
1149 if (options.num_allow_groups > 0)
1153 for (i = 0; i < options.num_allow_groups; i++)
1154 if (match_pattern(grp->gr_name, options.allow_groups[i]))
1156 /* i < options.num_allow_groups iff we break for loop */
1157 if (i >= options.num_allow_groups)
1162 /* We found no reason not to let this user try to log on... */
1166 /* Performs authentication of an incoming connection. Session key has already
1167 been exchanged and encryption is enabled. User is the user name to log
1168 in as (received from the client). */
1171 do_authentication(char *user)
1173 struct passwd *pw, pwcopy;
1176 /* If machine has AFS, set process authentication group. */
1183 /* Verify that the user is a valid user. */
1184 pw = getpwnam(user);
1185 if (!pw || !allowed_user(pw))
1186 do_fake_authloop(user);
1188 /* Take a copy of the returned structure. */
1189 memset(&pwcopy, 0, sizeof(pwcopy));
1190 pwcopy.pw_name = xstrdup(pw->pw_name);
1191 pwcopy.pw_passwd = xstrdup(pw->pw_passwd);
1192 pwcopy.pw_uid = pw->pw_uid;
1193 pwcopy.pw_gid = pw->pw_gid;
1194 pwcopy.pw_dir = xstrdup(pw->pw_dir);
1195 pwcopy.pw_shell = xstrdup(pw->pw_shell);
1202 debug("Starting up PAM with username \"%.200s\"", pw->pw_name);
1204 pam_retval = pam_start("sshd", pw->pw_name, &conv, (pam_handle_t**)&pamh);
1205 if (pam_retval != PAM_SUCCESS)
1206 fatal("PAM initialisation failed: %.200s", pam_strerror((pam_handle_t *)pamh, pam_retval));
1208 fatal_add_cleanup(&pam_cleanup_proc, NULL);
1212 /* If we are not running as root, the user must have the same uid as the
1214 if (getuid() != 0 && pw->pw_uid != getuid())
1215 packet_disconnect("Cannot change user when server not running as root.");
1217 debug("Attempting authentication for %.100s.", user);
1219 /* If the user has no password, accept authentication immediately. */
1220 if (options.password_authentication &&
1222 (!options.kerberos_authentication || options.kerberos_or_local_passwd) &&
1224 auth_password(pw, ""))
1226 /* Authentication with empty password succeeded. */
1227 debug("Login for user %.100s accepted without authentication.", user);
1229 /* Loop until the user has been authenticated or the connection is closed,
1230 do_authloop() returns only if authentication is successfull */
1234 /* XXX log unified auth message */
1236 /* Check if the user is logging in as root and root logins are disallowed. */
1237 if (pw->pw_uid == 0 && !options.permit_root_login)
1240 log("Root login accepted for forced command.");
1242 packet_disconnect("ROOT LOGIN REFUSED FROM %.200s",
1243 get_canonical_hostname());
1246 /* The user has been authenticated and accepted. */
1247 packet_start(SSH_SMSG_SUCCESS);
1249 packet_write_wait();
1251 /* Perform session preparation. */
1252 do_authenticated(pw);
1255 #define MAX_AUTH_FAILURES 5
1257 /* read packets and try to authenticate local user *pw.
1258 return if authentication is successfull */
1260 do_authloop(struct passwd *pw)
1262 int authentication_failures = 0;
1264 BIGNUM *client_host_key_e, *client_host_key_n;
1266 char *client_user = NULL, *password = NULL;
1267 int plen, dlen, nlen, ulen, elen;
1270 #endif /* HAVE_LIBPAM */
1272 /* Indicate that authentication is needed. */
1273 packet_start(SSH_SMSG_FAILURE);
1275 packet_write_wait();
1278 int authenticated = 0;
1280 /* Get a packet from the client. */
1281 int type = packet_read(&plen);
1283 /* Process the packet. */
1287 case SSH_CMSG_HAVE_KERBEROS_TGT:
1288 if (!options.kerberos_tgt_passing)
1290 /* packet_get_all(); */
1291 log("Kerberos tgt passing disabled.");
1295 /* Accept Kerberos tgt. */
1296 char *tgt = packet_get_string(&dlen);
1297 packet_integrity_check(plen, 4 + dlen, type);
1298 if (!auth_kerberos_tgt(pw, tgt))
1299 debug("Kerberos tgt REFUSED for %s", pw->pw_name);
1304 case SSH_CMSG_HAVE_AFS_TOKEN:
1305 if (!options.afs_token_passing || !k_hasafs()) {
1306 /* packet_get_all(); */
1307 log("AFS token passing disabled.");
1311 /* Accept AFS token. */
1312 char *token_string = packet_get_string(&dlen);
1313 packet_integrity_check(plen, 4 + dlen, type);
1314 if (!auth_afs_token(pw, token_string))
1315 debug("AFS token REFUSED for %s", pw->pw_name);
1316 xfree(token_string);
1322 case SSH_CMSG_AUTH_KERBEROS:
1323 if (!options.kerberos_authentication)
1325 /* packet_get_all(); */
1326 log("Kerberos authentication disabled.");
1330 /* Try Kerberos v4 authentication. */
1332 char *tkt_user = NULL;
1333 char *kdata = packet_get_string((unsigned int *)&auth.length);
1334 packet_integrity_check(plen, 4 + auth.length, type);
1336 if (auth.length < MAX_KTXT_LEN)
1337 memcpy(auth.dat, kdata, auth.length);
1340 authenticated = auth_krb4(pw->pw_name, &auth, &tkt_user);
1342 log("Kerberos authentication %s%s for account %s from %s",
1343 authenticated ? "accepted " : "failed",
1344 tkt_user != NULL ? tkt_user : "",
1345 pw->pw_name, get_canonical_hostname());
1352 case SSH_CMSG_AUTH_RHOSTS:
1353 if (!options.rhosts_authentication)
1355 log("Rhosts authentication disabled.");
1359 /* Get client user name. Note that we just have to trust the client;
1360 this is one reason why rhosts authentication is insecure.
1361 (Another is IP-spoofing on a local network.) */
1362 client_user = packet_get_string(&dlen);
1363 packet_integrity_check(plen, 4 + dlen, type);
1365 /* Try to authenticate using /etc/hosts.equiv and .rhosts. */
1366 authenticated = auth_rhosts(pw, client_user);
1368 log("Rhosts authentication %s for %.100s, remote %.100s on %.700s.",
1369 authenticated ? "accepted" : "failed",
1370 pw->pw_name, client_user, get_canonical_hostname());
1373 #endif /* HAVE_LIBPAM */
1376 case SSH_CMSG_AUTH_RHOSTS_RSA:
1377 if (!options.rhosts_rsa_authentication)
1379 log("Rhosts with RSA authentication disabled.");
1383 /* Get client user name. Note that we just have to trust
1384 the client; root on the client machine can claim to be
1386 client_user = packet_get_string(&ulen);
1388 /* Get the client host key. */
1389 client_host_key_e = BN_new();
1390 client_host_key_n = BN_new();
1391 bits = packet_get_int();
1392 packet_get_bignum(client_host_key_e, &elen);
1393 packet_get_bignum(client_host_key_n, &nlen);
1395 if (bits != BN_num_bits(client_host_key_n))
1396 error("Warning: keysize mismatch for client_host_key: "
1397 "actual %d, announced %d", BN_num_bits(client_host_key_n), bits);
1398 packet_integrity_check(plen, (4 + ulen) + 4 + elen + nlen, type);
1400 authenticated = auth_rhosts_rsa(pw, client_user,
1401 client_host_key_e, client_host_key_n);
1402 log("Rhosts authentication %s for %.100s, remote %.100s.",
1403 authenticated ? "accepted" : "failed",
1404 pw->pw_name, client_user);
1407 #endif /* HAVE_LIBPAM */
1408 BN_clear_free(client_host_key_e);
1409 BN_clear_free(client_host_key_n);
1412 case SSH_CMSG_AUTH_RSA:
1413 if (!options.rsa_authentication)
1415 log("RSA authentication disabled.");
1419 /* RSA authentication requested. */
1421 packet_get_bignum(n, &nlen);
1422 packet_integrity_check(plen, nlen, type);
1424 authenticated = auth_rsa(pw, n);
1425 log("RSA authentication %s for %.100s.",
1426 authenticated ? "accepted" : "failed",
1431 case SSH_CMSG_AUTH_PASSWORD:
1432 if (!options.password_authentication)
1434 log("Password authentication disabled.");
1438 /* Read user password. It is in plain text, but was transmitted
1439 over the encrypted channel so it is not visible to an outside
1441 password = packet_get_string(&dlen);
1442 packet_integrity_check(plen, 4 + dlen, type);
1445 /* Do PAM auth with password */
1446 pampasswd = password;
1447 pam_retval = pam_authenticate((pam_handle_t *)pamh, 0);
1448 if (pam_retval == PAM_SUCCESS)
1450 log("PAM Password authentication accepted for user \"%.100s\"", pw->pw_name);
1455 log("PAM Password authentication for \"%.100s\" failed: %s",
1456 pw->pw_name, pam_strerror((pam_handle_t *)pamh, pam_retval));
1458 #else /* HAVE_LIBPAM */
1459 /* Try authentication with the password. */
1460 authenticated = auth_password(pw, password);
1461 log("Password authentication %s for %.100s.",
1462 authenticated ? "accepted" : "failed",
1465 memset(password, 0, strlen(password));
1468 #endif /* HAVE_LIBPAM */
1470 case SSH_CMSG_AUTH_TIS:
1471 /* TIS Authentication is unsupported */
1472 log("TIS authentication disabled.");
1476 /* Any unknown messages will be ignored (and failure returned)
1477 during authentication. */
1478 log("Unknown message during authentication: type %d", type);
1479 break; /* Respond with a failure message. */
1484 if (++authentication_failures >= MAX_AUTH_FAILURES)
1485 packet_disconnect("Too many authentication failures for %.100s from %.200s",
1486 pw->pw_name, get_canonical_hostname());
1487 /* Send a message indicating that the authentication attempt failed. */
1488 packet_start(SSH_SMSG_FAILURE);
1490 packet_write_wait();
1494 do_pam_account_and_session(pw->pw_name, client_user, get_canonical_hostname());
1497 if (client_user != NULL)
1500 if (password != NULL)
1502 memset(password, 0, strlen(password));
1505 #endif /* HAVE_LIBPAM */
1508 /* The user does not exist or access is denied,
1509 but fake indication that authentication is needed. */
1511 do_fake_authloop(char *user)
1513 int authentication_failures = 0;
1515 /* Indicate that authentication is needed. */
1516 packet_start(SSH_SMSG_FAILURE);
1518 packet_write_wait();
1520 /* Keep reading packets, and always respond with a failure. This is to
1521 avoid disclosing whether such a user really exists. */
1524 /* Read a packet. This will not return if the client disconnects. */
1526 int type = packet_read(&plen);
1529 char *password, *skeyinfo;
1530 if (options.password_authentication &&
1531 options.skey_authentication == 1 &&
1532 type == SSH_CMSG_AUTH_PASSWORD &&
1533 (password = packet_get_string(&passw_len)) != NULL &&
1535 strncasecmp(password, "s/key", 5) == 0 &&
1536 (skeyinfo = skey_fake_keyinfo(user)) != NULL ){
1537 /* Send a fake s/key challenge. */
1538 packet_send_debug(skeyinfo);
1541 if (++authentication_failures >= MAX_AUTH_FAILURES)
1542 packet_disconnect("Too many authentication failures for %.100s from %.200s",
1543 user, get_canonical_hostname());
1544 /* Send failure. This should be indistinguishable from a failed
1546 packet_start(SSH_SMSG_FAILURE);
1548 packet_write_wait();
1555 /* Remove local Xauthority file. */
1557 xauthfile_cleanup_proc(void *ignore)
1559 debug("xauthfile_cleanup_proc called");
1561 if (xauthfile != NULL) {
1568 /* Prepares for an interactive session. This is called after the user has
1569 been successfully authenticated. During this message exchange, pseudo
1570 terminals are allocated, X11, TCP/IP, and authentication agent forwardings
1571 are requested, etc. */
1573 void do_authenticated(struct passwd *pw)
1576 int compression_level = 0, enable_compression_after_reply = 0;
1577 int have_pty = 0, ptyfd = -1, ttyfd = -1, xauthfd = -1;
1578 int row, col, xpixel, ypixel, screen;
1580 char *command, *term = NULL, *display = NULL, *proto = NULL, *data = NULL;
1586 /* Cancel the alarm we set to limit the time taken for authentication. */
1589 /* Inform the channel mechanism that we are the server side and that
1590 the client may request to connect to any port at all. (The user could
1591 do it anyway, and we wouldn\'t know what is permitted except by the
1592 client telling us, so we can equally well trust the client not to request
1594 channel_permit_all_opens();
1596 /* We stay in this loop until the client requests to execute a shell or a
1602 /* Get a packet from the client. */
1603 type = packet_read(&plen);
1605 /* Process the packet. */
1608 case SSH_CMSG_REQUEST_COMPRESSION:
1609 packet_integrity_check(plen, 4, type);
1610 compression_level = packet_get_int();
1611 if (compression_level < 1 || compression_level > 9)
1613 packet_send_debug("Received illegal compression level %d.",
1617 /* Enable compression after we have responded with SUCCESS. */
1618 enable_compression_after_reply = 1;
1621 case SSH_CMSG_REQUEST_PTY:
1624 debug("Allocating a pty not permitted for this authentication.");
1628 packet_disconnect("Protocol error: you already have a pty.");
1630 debug("Allocating pty.");
1632 /* Allocate a pty and open it. */
1633 if (!pty_allocate(&ptyfd, &ttyfd, ttyname))
1635 error("Failed to allocate pty.");
1639 /* Determine the group to make the owner of the tty. */
1640 grp = getgrnam("tty");
1643 tty_gid = grp->gr_gid;
1644 tty_mode = S_IRUSR|S_IWUSR|S_IWGRP;
1648 tty_gid = pw->pw_gid;
1649 tty_mode = S_IRUSR|S_IWUSR|S_IWGRP|S_IWOTH;
1652 /* Change ownership of the tty. */
1653 if (chown(ttyname, pw->pw_uid, tty_gid) < 0)
1654 fatal("chown(%.100s, %d, %d) failed: %.100s",
1655 ttyname, pw->pw_uid, tty_gid, strerror(errno));
1656 if (chmod(ttyname, tty_mode) < 0)
1657 fatal("chmod(%.100s, 0%o) failed: %.100s",
1658 ttyname, tty_mode, strerror(errno));
1660 /* Get TERM from the packet. Note that the value may be of arbitrary
1663 term = packet_get_string(&dlen);
1664 packet_integrity_check(dlen, strlen(term), type);
1665 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
1666 /* Remaining bytes */
1667 n_bytes = plen - (4 + dlen + 4*4);
1669 if (strcmp(term, "") == 0)
1672 /* Get window size from the packet. */
1673 row = packet_get_int();
1674 col = packet_get_int();
1675 xpixel = packet_get_int();
1676 ypixel = packet_get_int();
1677 pty_change_window_size(ptyfd, row, col, xpixel, ypixel);
1679 /* Get tty modes from the packet. */
1680 tty_parse_modes(ttyfd, &n_bytes);
1681 packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type);
1683 /* Indicate that we now have a pty. */
1687 case SSH_CMSG_X11_REQUEST_FORWARDING:
1688 if (!options.x11_forwarding)
1690 packet_send_debug("X11 forwarding disabled in server configuration file.");
1694 if (no_x11_forwarding_flag)
1696 packet_send_debug("X11 forwarding not permitted for this authentication.");
1699 debug("Received request for X11 forwarding with auth spoofing.");
1701 packet_disconnect("Protocol error: X11 display already set.");
1703 int proto_len, data_len;
1704 proto = packet_get_string(&proto_len);
1705 data = packet_get_string(&data_len);
1706 packet_integrity_check(plen, 4+proto_len + 4+data_len + 4, type);
1708 if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
1709 screen = packet_get_int();
1712 display = x11_create_display_inet(screen);
1716 /* Setup to always have a local .Xauthority. */
1717 xauthfile = xmalloc(MAXPATHLEN);
1718 snprintf(xauthfile, MAXPATHLEN, "/tmp/XauthXXXXXX");
1720 if ((xauthfd = mkstemp(xauthfile)) != -1) {
1721 fchown(xauthfd, pw->pw_uid, pw->pw_gid);
1723 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
1730 #else /* XAUTH_PATH */
1731 /* No xauth program; we won't accept forwarding with spoofing. */
1732 packet_send_debug("No xauth program; cannot forward with spoofing.");
1734 #endif /* XAUTH_PATH */
1736 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
1737 if (no_agent_forwarding_flag)
1739 debug("Authentication agent forwarding not permitted for this authentication.");
1742 debug("Received authentication agent forwarding request.");
1743 auth_input_request_forwarding(pw);
1746 case SSH_CMSG_PORT_FORWARD_REQUEST:
1747 if (no_port_forwarding_flag)
1749 debug("Port forwarding not permitted for this authentication.");
1752 debug("Received TCP/IP port forwarding request.");
1753 channel_input_port_forward_request(pw->pw_uid == 0);
1756 case SSH_CMSG_MAX_PACKET_SIZE:
1757 if (packet_set_maxsize(packet_get_int()) < 0)
1761 case SSH_CMSG_EXEC_SHELL:
1762 /* Set interactive/non-interactive mode. */
1763 packet_set_interactive(have_pty || display != NULL,
1764 options.keepalives);
1766 if (forced_command != NULL)
1767 goto do_forced_command;
1768 debug("Forking shell.");
1769 packet_integrity_check(plen, 0, type);
1771 do_exec_pty(NULL, ptyfd, ttyfd, ttyname, pw, term, display, proto,
1774 do_exec_no_pty(NULL, pw, display, proto, data);
1777 case SSH_CMSG_EXEC_CMD:
1778 /* Set interactive/non-interactive mode. */
1779 packet_set_interactive(have_pty || display != NULL,
1780 options.keepalives);
1782 if (forced_command != NULL)
1783 goto do_forced_command;
1784 /* Get command from the packet. */
1787 command = packet_get_string(&dlen);
1788 debug("Executing command '%.500s'", command);
1789 packet_integrity_check(plen, 4 + dlen, type);
1792 do_exec_pty(command, ptyfd, ttyfd, ttyname, pw, term, display,
1795 do_exec_no_pty(command, pw, display, proto, data);
1800 /* Any unknown messages in this phase are ignored, and a failure
1801 message is returned. */
1802 log("Unknown packet type received after authentication: %d", type);
1806 /* The request was successfully processed. */
1807 packet_start(SSH_SMSG_SUCCESS);
1809 packet_write_wait();
1811 /* Enable compression now that we have replied if appropriate. */
1812 if (enable_compression_after_reply)
1814 enable_compression_after_reply = 0;
1815 packet_start_compression(compression_level);
1821 /* The request failed. */
1822 packet_start(SSH_SMSG_FAILURE);
1824 packet_write_wait();
1828 /* There is a forced command specified for this login. Execute it. */
1829 debug("Executing forced command: %.900s", forced_command);
1831 do_exec_pty(forced_command, ptyfd, ttyfd, ttyname, pw, term, display,
1834 do_exec_no_pty(forced_command, pw, display, proto, data);
1839 /* This is called to fork and execute a command when we have no tty. This
1840 will call do_child from the child, and server_loop from the parent after
1841 setting up file descriptors and such. */
1843 void do_exec_no_pty(const char *command, struct passwd *pw,
1844 const char *display, const char *auth_proto,
1845 const char *auth_data)
1850 int pin[2], pout[2], perr[2];
1851 /* Allocate pipes for communicating with the program. */
1852 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
1853 packet_disconnect("Could not create pipes: %.100s",
1855 #else /* USE_PIPES */
1856 int inout[2], err[2];
1857 /* Uses socket pairs to communicate with the program. */
1858 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
1859 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
1860 packet_disconnect("Could not create socket pairs: %.100s",
1862 #endif /* USE_PIPES */
1864 setproctitle("%s@notty", pw->pw_name);
1866 /* Fork the child. */
1867 if ((pid = fork()) == 0)
1869 /* Child. Reinitialize the log since the pid has changed. */
1870 log_init(av0, options.log_level, options.log_facility, log_stderr);
1872 /* Create a new session and process group since the 4.4BSD setlogin()
1873 affects the entire process group. */
1875 error("setsid failed: %.100s", strerror(errno));
1878 /* Redirect stdin. We close the parent side of the socket pair,
1879 and make the child side the standard input. */
1881 if (dup2(pin[0], 0) < 0)
1882 perror("dup2 stdin");
1885 /* Redirect stdout. */
1887 if (dup2(pout[1], 1) < 0)
1888 perror("dup2 stdout");
1891 /* Redirect stderr. */
1893 if (dup2(perr[1], 2) < 0)
1894 perror("dup2 stderr");
1896 #else /* USE_PIPES */
1897 /* Redirect stdin, stdout, and stderr. Stdin and stdout will use the
1898 same socket, as some programs (particularly rdist) seem to depend
1902 if (dup2(inout[0], 0) < 0) /* stdin */
1903 perror("dup2 stdin");
1904 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
1905 perror("dup2 stdout");
1906 if (dup2(err[0], 2) < 0) /* stderr */
1907 perror("dup2 stderr");
1908 #endif /* USE_PIPES */
1910 /* Do processing for the child (exec command etc). */
1911 do_child(command, pw, NULL, display, auth_proto, auth_data, NULL);
1915 packet_disconnect("fork failed: %.100s", strerror(errno));
1917 /* We are the parent. Close the child sides of the pipes. */
1922 /* Enter the interactive session. */
1923 server_loop(pid, pin[1], pout[0], perr[0]);
1924 /* server_loop has closed pin[1], pout[1], and perr[1]. */
1925 #else /* USE_PIPES */
1926 /* We are the parent. Close the child sides of the socket pairs. */
1930 /* Enter the interactive session. Note: server_loop must be able to handle
1931 the case that fdin and fdout are the same. */
1932 server_loop(pid, inout[1], inout[1], err[1]);
1933 /* server_loop has closed inout[1] and err[1]. */
1934 #endif /* USE_PIPES */
1937 struct pty_cleanup_context
1939 const char *ttyname;
1943 /* Function to perform cleanup if we get aborted abnormally (e.g., due to a
1944 dropped connection). */
1946 void pty_cleanup_proc(void *context)
1948 struct pty_cleanup_context *cu = context;
1950 debug("pty_cleanup_proc called");
1952 /* Record that the user has logged out. */
1953 record_logout(cu->pid, cu->ttyname);
1955 /* Release the pseudo-tty. */
1956 pty_release(cu->ttyname);
1959 /* This is called to fork and execute a command when we have a tty. This
1960 will call do_child from the child, and server_loop from the parent after
1961 setting up file descriptors, controlling tty, updating wtmp, utmp,
1962 lastlog, and other such operations. */
1964 void do_exec_pty(const char *command, int ptyfd, int ttyfd,
1965 const char *ttyname, struct passwd *pw, const char *term,
1966 const char *display, const char *auth_proto,
1967 const char *auth_data)
1970 const char *hostname;
1971 time_t last_login_time;
1972 char buf[100], *time_string;
1977 struct sockaddr_in from;
1979 struct pty_cleanup_context cleanup_context;
1981 /* Get remote host name. */
1982 hostname = get_canonical_hostname();
1984 /* Get the time when the user last logged in. Buf will be set to contain
1985 the hostname the last login was from. */
1986 if(!options.use_login) {
1987 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
1991 setproctitle("%s@%s", pw->pw_name, strrchr(ttyname, '/') + 1);
1993 /* Fork the child. */
1994 if ((pid = fork()) == 0)
1998 /* Child. Reinitialize the log because the pid has changed. */
1999 log_init(av0, options.log_level, options.log_facility, log_stderr);
2001 /* Close the master side of the pseudo tty. */
2004 /* Make the pseudo tty our controlling tty. */
2005 pty_make_controlling_tty(&ttyfd, ttyname);
2007 /* Redirect stdin from the pseudo tty. */
2008 if (dup2(ttyfd, fileno(stdin)) < 0)
2009 error("dup2 stdin failed: %.100s", strerror(errno));
2011 /* Redirect stdout to the pseudo tty. */
2012 if (dup2(ttyfd, fileno(stdout)) < 0)
2013 error("dup2 stdin failed: %.100s", strerror(errno));
2015 /* Redirect stderr to the pseudo tty. */
2016 if (dup2(ttyfd, fileno(stderr)) < 0)
2017 error("dup2 stdin failed: %.100s", strerror(errno));
2019 /* Close the extra descriptor for the pseudo tty. */
2022 /* Get IP address of client. This is needed because we want to record
2023 where the user logged in from. If the connection is not a socket,
2024 let the ip address be 0.0.0.0. */
2025 memset(&from, 0, sizeof(from));
2026 if (packet_get_connection_in() == packet_get_connection_out())
2028 fromlen = sizeof(from);
2029 if (getpeername(packet_get_connection_in(),
2030 (struct sockaddr *)&from, &fromlen) < 0) {
2031 debug("getpeername: %.100s", strerror(errno));
2036 /* Record that there was a login on that terminal. */
2037 record_login(pid, ttyname, pw->pw_name, pw->pw_uid, hostname,
2040 /* Check if .hushlogin exists. */
2041 snprintf(line, sizeof line, "%.200s/.hushlogin", pw->pw_dir);
2042 quiet_login = stat(line, &st) >= 0;
2045 /* output the results of the pamconv() */
2046 if (!quiet_login && pamconv_msg != NULL)
2047 fprintf(stderr, pamconv_msg);
2050 /* If the user has logged in before, display the time of last login.
2051 However, don't display anything extra if a command has been
2052 specified (so that ssh can be used to execute commands on a remote
2053 machine without users knowing they are going to another machine).
2054 Login(1) will do this for us as well, so check if login(1) is used */
2055 if (command == NULL && last_login_time != 0 && !quiet_login &&
2058 /* Convert the date to a string. */
2059 time_string = ctime(&last_login_time);
2060 /* Remove the trailing newline. */
2061 if (strchr(time_string, '\n'))
2062 *strchr(time_string, '\n') = 0;
2063 /* Display the last login time. Host if displayed if known. */
2064 if (strcmp(buf, "") == 0)
2065 printf("Last login: %s\r\n", time_string);
2067 printf("Last login: %s from %s\r\n", time_string, buf);
2070 /* Print /etc/motd unless a command was specified or printing it was
2071 disabled in server options or login(1) will be used. Note that
2072 some machines appear to print it in /etc/profile or similar. */
2073 if (command == NULL && options.print_motd && !quiet_login &&
2076 /* Print /etc/motd if it exists. */
2077 f = fopen("/etc/motd", "r");
2080 while (fgets(line, sizeof(line), f))
2081 fputs(line, stdout);
2086 /* Do common processing for the child, such as execing the command. */
2087 do_child(command, pw, term, display, auth_proto, auth_data, ttyname);
2091 packet_disconnect("fork failed: %.100s", strerror(errno));
2092 /* Parent. Close the slave side of the pseudo tty. */
2095 /* Create another descriptor of the pty master side for use as the standard
2096 input. We could use the original descriptor, but this simplifies code
2097 in server_loop. The descriptor is bidirectional. */
2100 packet_disconnect("dup failed: %.100s", strerror(errno));
2102 /* Add a cleanup function to clear the utmp entry and record logout time
2103 in case we call fatal() (e.g., the connection gets closed). */
2104 cleanup_context.pid = pid;
2105 cleanup_context.ttyname = ttyname;
2106 fatal_add_cleanup(pty_cleanup_proc, (void *)&cleanup_context);
2108 /* Enter interactive session. */
2109 server_loop(pid, ptyfd, fdout, -1);
2110 /* server_loop has not closed ptyfd and fdout. */
2112 /* Cancel the cleanup function. */
2113 fatal_remove_cleanup(pty_cleanup_proc, (void *)&cleanup_context);
2115 /* Record that the user has logged out. */
2116 record_logout(pid, ttyname);
2118 /* Release the pseudo-tty. */
2119 pty_release(ttyname);
2121 /* Close the server side of the socket pairs. We must do this after the
2122 pty cleanup, so that another process doesn't get this pty while we're
2123 still cleaning up. */
2128 /* Sets the value of the given variable in the environment. If the variable
2129 already exists, its value is overriden. */
2131 void child_set_env(char ***envp, unsigned int *envsizep, const char *name,
2134 unsigned int i, namelen;
2137 /* Find the slot where the value should be stored. If the variable already
2138 exists, we reuse the slot; otherwise we append a new slot at the end
2139 of the array, expanding if necessary. */
2141 namelen = strlen(name);
2142 for (i = 0; env[i]; i++)
2143 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
2147 /* Name already exists. Reuse the slot. */
2152 /* New variable. Expand the array if necessary. */
2153 if (i >= (*envsizep) - 1)
2156 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
2159 /* Need to set the NULL pointer at end of array beyond the new
2164 /* Allocate space and format the variable in the appropriate slot. */
2165 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
2166 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
2169 /* Reads environment variables from the given file and adds/overrides them
2170 into the environment. If the file does not exist, this does nothing.
2171 Otherwise, it must consist of empty lines, comments (line starts with '#')
2172 and assignments of the form name=value. No other forms are allowed. */
2174 void read_environment_file(char ***env, unsigned int *envsize,
2175 const char *filename)
2181 /* Open the environment file. */
2182 f = fopen(filename, "r");
2184 return; /* Not found. */
2186 /* Process each line. */
2187 while (fgets(buf, sizeof(buf), f))
2189 /* Skip leading whitespace. */
2190 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
2193 /* Ignore empty and comment lines. */
2194 if (!*cp || *cp == '#' || *cp == '\n')
2197 /* Remove newline. */
2198 if (strchr(cp, '\n'))
2199 *strchr(cp, '\n') = '\0';
2201 /* Find the equals sign. Its lack indicates badly formatted line. */
2202 value = strchr(cp, '=');
2205 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
2209 /* Replace the equals sign by nul, and advance value to the value
2214 /* Set the value in environment. */
2215 child_set_env(env, envsize, cp, value);
2221 /* Performs common processing for the child, such as setting up the
2222 environment, closing extra file descriptors, setting the user and group
2223 ids, and executing the command or shell. */
2225 void do_child(const char *command, struct passwd *pw, const char *term,
2226 const char *display, const char *auth_proto,
2227 const char *auth_data, const char *ttyname)
2229 const char *shell, *cp = NULL;
2232 unsigned int envsize, i;
2234 extern char **environ;
2238 #ifndef HAVE_LIBPAM /* pam_nologin handles this */
2239 /* Check /etc/nologin. */
2240 f = fopen("/etc/nologin", "r");
2242 { /* /etc/nologin exists. Print its contents and exit. */
2243 while (fgets(buf, sizeof(buf), f))
2246 if (pw->pw_uid != 0)
2249 #endif /* HAVE_LIBPAM */
2251 #ifdef HAVE_SETLOGIN
2252 /* Set login name in the kernel. */
2253 if (setlogin(pw->pw_name) < 0)
2254 error("setlogin failed: %s", strerror(errno));
2255 #endif /* HAVE_SETLOGIN */
2257 /* Set uid, gid, and groups. */
2258 /* Login(1) does this as well, and it needs uid 0 for the "-h" switch,
2259 so we let login(1) to this for us. */
2260 if(!options.use_login) {
2261 if (getuid() == 0 || geteuid() == 0)
2263 if (setgid(pw->pw_gid) < 0)
2268 /* Initialize the group list. */
2269 if (initgroups(pw->pw_name, pw->pw_gid) < 0)
2271 perror("initgroups");
2276 /* Permanently switch to the desired uid. */
2277 permanently_set_uid(pw->pw_uid);
2280 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
2281 fatal("Failed to set uids to %d.", (int)pw->pw_uid);
2284 /* Get the shell from the password data. An empty shell field is legal,
2285 and means /bin/sh. */
2286 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
2289 /* Try to get AFS tokens for the local cell. */
2293 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
2294 krb_afslog(cell, 0);
2300 /* Initialize the environment. In the first part we allocate space for
2301 all environment variables. */
2303 env = xmalloc(envsize * sizeof(char *));
2306 if(!options.use_login) {
2307 /* Set basic environment. */
2308 child_set_env(&env, &envsize, "USER", pw->pw_name);
2309 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
2310 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
2311 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
2313 snprintf(buf, sizeof buf, "%.200s/%.50s",
2314 _PATH_MAILDIR, pw->pw_name);
2315 child_set_env(&env, &envsize, "MAIL", buf);
2317 /* Normal systems set SHELL by default. */
2318 child_set_env(&env, &envsize, "SHELL", shell);
2321 /* Let it inherit timezone if we have one. */
2323 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
2325 /* Set custom environment options from RSA authentication. */
2326 while (custom_environment)
2328 struct envstring *ce = custom_environment;
2331 for (i = 0; s[i] != '=' && s[i]; i++)
2336 child_set_env(&env, &envsize, s, s + i + 1);
2338 custom_environment = ce->next;
2343 /* Set SSH_CLIENT. */
2344 snprintf(buf, sizeof buf, "%.50s %d %d",
2345 get_remote_ipaddr(), get_remote_port(), options.port);
2346 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
2348 /* Set SSH_TTY if we have a pty. */
2350 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
2352 /* Set TERM if we have a pty. */
2354 child_set_env(&env, &envsize, "TERM", term);
2356 /* Set DISPLAY if we have one. */
2358 child_set_env(&env, &envsize, "DISPLAY", display);
2362 extern char *ticket;
2365 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
2370 /* Pull in any environment variables that may have been set by PAM. */
2372 char *equal_sign, var_name[256], var_val[256];
2374 char **pam_env = pam_getenvlist((pam_handle_t *)pamh);
2375 for(this_var = 0; pam_env && pam_env[this_var]; this_var++)
2377 if(strlen(pam_env[this_var]) < (sizeof(var_name) - 1))
2378 if((equal_sign = strstr(pam_env[this_var], "=")) != NULL)
2380 memset(var_name, 0, sizeof(var_name));
2381 memset(var_val, 0, sizeof(var_val));
2382 strncpy(var_name, pam_env[this_var],
2383 equal_sign - pam_env[this_var]);
2384 strcpy(var_val, equal_sign + 1);
2385 child_set_env(&env, &envsize, var_name, var_val);
2389 #endif /* HAVE_LIBPAM */
2391 /* Set XAUTHORITY to always be a local file. */
2393 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
2395 /* Set variable for forwarded authentication connection, if we have one. */
2396 if (auth_get_socket_name() != NULL)
2397 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
2398 auth_get_socket_name());
2400 /* Read $HOME/.ssh/environment. */
2401 if(!options.use_login) {
2402 snprintf(buf, sizeof buf, "%.200s/.ssh/environment", pw->pw_dir);
2403 read_environment_file(&env, &envsize, buf);
2406 /* If debugging, dump the environment to stderr. */
2409 fprintf(stderr, "Environment:\n");
2410 for (i = 0; env[i]; i++)
2411 fprintf(stderr, " %.200s\n", env[i]);
2414 /* Close the connection descriptors; note that this is the child, and the
2415 server will still have the socket open, and it is important that we
2416 do not shutdown it. Note that the descriptors cannot be closed before
2417 building the environment, as we call get_remote_ipaddr there. */
2418 if (packet_get_connection_in() == packet_get_connection_out())
2419 close(packet_get_connection_in());
2422 close(packet_get_connection_in());
2423 close(packet_get_connection_out());
2425 /* Close all descriptors related to channels. They will still remain
2426 open in the parent. */
2427 channel_close_all();
2429 /* Close any extra file descriptors. Note that there may still be
2430 descriptors left by system functions. They will be closed later. */
2434 /* Close any extra open file descriptors so that we don\'t have them
2435 hanging around in clients. Note that we want to do this after
2436 initgroups, because at least on Solaris 2.3 it leaves file descriptors
2438 for (i = 3; i < 64; i++)
2441 /* Change current directory to the user\'s home directory. */
2442 if (chdir(pw->pw_dir) < 0)
2443 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
2444 pw->pw_dir, strerror(errno));
2446 /* Must take new environment into use so that .ssh/rc, /etc/sshrc and
2447 xauth are run in the proper environment. */
2450 /* Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
2452 if(!options.use_login) {
2453 if (stat(SSH_USER_RC, &st) >= 0)
2456 fprintf(stderr, "Running /bin/sh %s\n", SSH_USER_RC);
2458 f = popen("/bin/sh " SSH_USER_RC, "w");
2461 if (auth_proto != NULL && auth_data != NULL)
2462 fprintf(f, "%s %s\n", auth_proto, auth_data);
2466 fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
2469 if (stat(SSH_SYSTEM_RC, &st) >= 0)
2472 fprintf(stderr, "Running /bin/sh %s\n", SSH_SYSTEM_RC);
2474 f = popen("/bin/sh " SSH_SYSTEM_RC, "w");
2477 if (auth_proto != NULL && auth_data != NULL)
2478 fprintf(f, "%s %s\n", auth_proto, auth_data);
2482 fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
2487 /* Add authority data to .Xauthority if appropriate. */
2488 if (auth_proto != NULL && auth_data != NULL)
2491 fprintf(stderr, "Running %.100s add %.100s %.100s %.100s\n",
2492 XAUTH_PATH, display, auth_proto, auth_data);
2494 f = popen(XAUTH_PATH " -q -", "w");
2497 fprintf(f, "add %s %s %s\n", display, auth_proto, auth_data);
2501 fprintf(stderr, "Could not run %s -q -\n", XAUTH_PATH);
2504 #endif /* XAUTH_PATH */
2506 /* Get the last component of the shell name. */
2507 cp = strrchr(shell, '/');
2514 /* If we have no command, execute the shell. In this case, the shell name
2515 to be passed in argv[0] is preceded by '-' to indicate that this is
2519 if(!options.use_login) {
2522 /* Check for mail if we have a tty and it was enabled in server options. */
2523 if (ttyname && options.check_mail) {
2525 struct stat mailstat;
2526 mailbox = getenv("MAIL");
2527 if(mailbox != NULL) {
2528 if(stat(mailbox, &mailstat) != 0 || mailstat.st_size == 0) {
2529 printf("No mail.\n");
2530 } else if(mailstat.st_mtime < mailstat.st_atime) {
2531 printf("You have mail.\n");
2533 printf("You have new mail.\n");
2537 /* Start the shell. Set initial character to '-'. */
2539 strncpy(buf + 1, cp, sizeof(buf) - 1);
2540 buf[sizeof(buf) - 1] = 0;
2541 /* Execute the shell. */
2544 execve(shell, argv, env);
2545 /* Executing the shell failed. */
2550 /* Launch login(1). */
2552 execl(LOGIN_PROGRAM, "login", "-h", get_remote_ipaddr(), "-p", "-f", "--", pw->pw_name, NULL);
2554 /* Login couldn't be executed, die. */
2561 /* Execute the command using the user's shell. This uses the -c option
2562 to execute the command. */
2563 argv[0] = (char *)cp;
2565 argv[2] = (char *)command;
2567 execve(shell, argv, env);