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;
46 /* Local Xauthority file. */
47 static char *xauthfile = NULL;
49 /* Server configuration options. */
50 ServerOptions options;
52 /* Name of the server configuration file. */
53 char *config_file_name = SERVER_CONFIG_FILE;
55 /* Debug mode flag. This can be set on the command line. If debug
56 mode is enabled, extra debugging output will be sent to the system
57 log, the daemon will not go to background, and will exit after processing
58 the first connection. */
61 /* Flag indicating that the daemon is being started from inetd. */
64 /* debug goes to stderr unless inetd_flag is set */
67 /* argv[0] without path. */
70 /* Saved arguments to main(). */
73 /* This is set to the socket that the server is listening; this is used in
74 the SIGHUP signal handler. */
77 /* Flags set in auth-rsa from authorized_keys flags. These are set in
79 int no_port_forwarding_flag = 0;
80 int no_agent_forwarding_flag = 0;
81 int no_x11_forwarding_flag = 0;
83 char *forced_command = NULL; /* RSA authentication "command=" option. */
84 struct envstring *custom_environment = NULL;
85 /* RSA authentication "environment=" options. */
87 /* Session id for the current session. */
88 unsigned char session_id[16];
90 /* Any really sensitive data in the application is contained in this structure.
91 The idea is that this structure could be locked into memory so that the
92 pages do not get written into swap. However, there are some problems.
93 The private key contains BIGNUMs, and we do not (in principle) have
94 access to the internals of them, and locking just the structure is not
95 very useful. Currently, memory locking is not implemented. */
98 /* Private part of server key. */
101 /* Private part of host key. */
105 /* Flag indicating whether the current session key has been used. This flag
106 is set whenever the key is used, and cleared when the key is regenerated. */
109 /* This is set to true when SIGHUP is received. */
110 int received_sighup = 0;
112 /* Public side of the server key. This value is regenerated regularly with
116 /* Prototypes for various functions defined later in this file. */
117 void do_connection();
118 void do_authentication(char *user);
119 void do_authloop(struct passwd *pw);
120 void do_fake_authloop(char *user);
121 void do_authenticated(struct passwd *pw);
122 void do_exec_pty(const char *command, int ptyfd, int ttyfd,
123 const char *ttyname, struct passwd *pw, const char *term,
124 const char *display, const char *auth_proto,
125 const char *auth_data);
126 void do_exec_no_pty(const char *command, struct passwd *pw,
127 const char *display, const char *auth_proto,
128 const char *auth_data);
129 void do_child(const char *command, struct passwd *pw, const char *term,
130 const char *display, const char *auth_proto,
131 const char *auth_data, const char *ttyname);
134 static int pamconv(int num_msg, const struct pam_message **msg,
135 struct pam_response **resp, void *appdata_ptr);
136 void do_pam_account_and_session(const char *username,
137 const char *remote_user, const char *remote_host);
138 void pam_cleanup_proc(void *context);
140 static struct pam_conv conv = {
144 struct pam_handle_t *pamh = NULL;
145 const char *pampasswd = NULL;
146 char *pamconv_msg = NULL;
148 static int pamconv(int num_msg, const struct pam_message **msg,
149 struct pam_response **resp, void *appdata_ptr)
152 struct pam_response *reply = NULL;
154 /* PAM will free this later */
155 reply = malloc(num_msg * sizeof(*reply));
159 for(count = 0; count < num_msg; count++)
161 switch (msg[count]->msg_style)
163 case PAM_PROMPT_ECHO_OFF:
164 if (pampasswd == NULL)
169 reply[count].resp_retcode = PAM_SUCCESS;
170 reply[count].resp = xstrdup(pampasswd);
174 reply[count].resp_retcode = PAM_SUCCESS;
175 reply[count].resp = xstrdup("");
177 if (msg[count]->msg == NULL) break;
178 debug("Adding PAM message: %s", msg[count]->msg);
179 if (pamconv_msg == NULL)
181 pamconv_msg = malloc(strlen(msg[count]->msg) + 2);
183 if (pamconv_msg == NULL)
186 strncpy(pamconv_msg, msg[count]->msg, strlen(msg[count]->msg));
187 pamconv_msg[strlen(msg[count]->msg)] = '\n';
188 pamconv_msg[strlen(msg[count]->msg) + 1] = '\0';
191 pamconv_msg = realloc(pamconv_msg, strlen(pamconv_msg) + strlen(msg[count]->msg) + 2);
192 strncat(pamconv_msg, msg[count]->msg, strlen(msg[count]->msg));
193 pamconv_msg[strlen(pamconv_msg)] = '\n';
194 pamconv_msg[strlen(pamconv_msg) + 1] = '\0';
198 case PAM_PROMPT_ECHO_ON:
211 void pam_cleanup_proc(void *context)
217 pam_retval = pam_close_session((pam_handle_t *)pamh, 0);
218 if (pam_retval != PAM_SUCCESS)
220 log("Cannot close PAM session: %.200s",
221 pam_strerror((pam_handle_t *)pamh, pam_retval));
224 pam_retval = pam_end((pam_handle_t *)pamh, pam_retval);
225 if (pam_retval != PAM_SUCCESS)
227 log("Cannot release PAM authentication: %.200s",
228 pam_strerror((pam_handle_t *)pamh, pam_retval));
233 void do_pam_account_and_session(const char *username, const char *remote_user, const char *remote_host)
237 if (remote_host != NULL)
239 debug("PAM setting rhost to \"%.200s\"", remote_host);
240 pam_retval = pam_set_item((pam_handle_t *)pamh, PAM_RHOST, remote_host);
241 if (pam_retval != PAM_SUCCESS)
243 log("PAM set rhost failed: %.200s", pam_strerror((pam_handle_t *)pamh, pam_retval));
244 do_fake_authloop(username);
248 if (remote_user != NULL)
250 debug("PAM setting ruser to \"%.200s\"", remote_user);
251 pam_retval = pam_set_item((pam_handle_t *)pamh, PAM_RUSER, remote_user);
252 if (pam_retval != PAM_SUCCESS)
254 log("PAM set ruser failed: %.200s", pam_strerror((pam_handle_t *)pamh, pam_retval));
255 do_fake_authloop(username);
259 pam_retval = pam_acct_mgmt((pam_handle_t *)pamh, 0);
260 if (pam_retval != PAM_SUCCESS)
262 log("PAM rejected by account configuration: %.200s", pam_strerror((pam_handle_t *)pamh, pam_retval));
263 do_fake_authloop(username);
266 pam_retval = pam_open_session((pam_handle_t *)pamh, 0);
267 if (pam_retval != PAM_SUCCESS)
269 log("PAM session setup failed: %.200s", pam_strerror((pam_handle_t *)pamh, pam_retval));
270 do_fake_authloop(username);
273 #endif /* HAVE_LIBPAM */
275 /* Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
276 the effect is to reread the configuration file (and to regenerate
279 void sighup_handler(int sig)
282 signal(SIGHUP, sighup_handler);
285 /* Called from the main program after receiving SIGHUP. Restarts the
288 void sighup_restart()
290 log("Received SIGHUP; restarting.");
292 execv(saved_argv[0], saved_argv);
293 log("RESTART FAILED: av0='%s', error: %s.", av0, strerror(errno));
297 /* Generic signal handler for terminating signals in the master daemon.
298 These close the listen socket; not closing it seems to cause "Address
299 already in use" problems on some machines, which is inconvenient. */
301 void sigterm_handler(int sig)
303 log("Received signal %d; terminating.", sig);
308 /* SIGCHLD handler. This is called whenever a child dies. This will then
309 reap any zombies left by exited c. */
311 void main_sigchld_handler(int sig)
313 int save_errno = errno;
316 signal(SIGCHLD, main_sigchld_handler);
320 /* Signal handler for the alarm after the login grace period has expired. */
322 void grace_alarm_handler(int sig)
324 /* Close the connection. */
327 /* Log error and exit. */
328 fatal("Timeout before authentication.");
331 /* Signal handler for the key regeneration alarm. Note that this
332 alarm only occurs in the daemon waiting for connections, and it does not
333 do anything with the private key or random state before forking. Thus there
334 should be no concurrency control/asynchronous execution problems. */
336 void key_regeneration_alarm(int sig)
338 int save_errno = errno;
340 /* Check if we should generate a new key. */
343 /* This should really be done in the background. */
344 log("Generating new %d bit RSA key.", options.server_key_bits);
346 if (sensitive_data.private_key != NULL)
347 RSA_free(sensitive_data.private_key);
348 sensitive_data.private_key = RSA_new();
350 if (public_key != NULL)
351 RSA_free(public_key);
352 public_key = RSA_new();
354 rsa_generate_key(sensitive_data.private_key, public_key,
355 options.server_key_bits);
358 log("RSA key generation complete.");
361 /* Reschedule the alarm. */
362 signal(SIGALRM, key_regeneration_alarm);
363 alarm(options.key_regeneration_time);
367 /* Main program for the daemon. */
370 main(int ac, char **av)
374 int opt, aux, sock_in, sock_out, newsock, i, pid, on = 1;
375 int remote_major, remote_minor;
377 struct sockaddr_in sin;
378 char buf[100]; /* Must not be larger than remote_version. */
379 char remote_version[100]; /* Must be at least as big as buf. */
383 struct linger linger;
387 if (strchr(av[0], '/'))
388 av0 = strrchr(av[0], '/') + 1;
392 /* Initialize configuration options to their default values. */
393 initialize_server_options(&options);
395 /* Parse command-line arguments. */
396 while ((opt = getopt(ac, av, "f:p:b:k:h:g:diqQ")) != EOF)
401 config_file_name = optarg;
405 options.log_level = SYSLOG_LEVEL_DEBUG;
414 options.log_level = SYSLOG_LEVEL_QUIET;
417 options.server_key_bits = atoi(optarg);
420 options.port = atoi(optarg);
423 options.login_grace_time = atoi(optarg);
426 options.key_regeneration_time = atoi(optarg);
429 options.host_key_file = optarg;
433 fprintf(stderr, "sshd version %s\n", SSH_VERSION);
434 fprintf(stderr, "Usage: %s [options]\n", av0);
435 fprintf(stderr, "Options:\n");
436 fprintf(stderr, " -f file Configuration file (default %s/sshd_config)\n", ETCDIR);
437 fprintf(stderr, " -d Debugging mode\n");
438 fprintf(stderr, " -i Started from inetd\n");
439 fprintf(stderr, " -q Quiet (no logging)\n");
440 fprintf(stderr, " -p port Listen on the specified port (default: 22)\n");
441 fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n");
442 fprintf(stderr, " -g seconds Grace period for authentication (default: 300)\n");
443 fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n");
444 fprintf(stderr, " -h file File from which to read host key (default: %s)\n",
450 /* check if RSA support exists */
451 if (rsa_alive() == 0) {
453 printf("sshd: no RSA support in libssl and libcrypto -- exiting. See ssl(8)\n");
454 log("no RSA support in libssl and libcrypto -- exiting. See ssl(8)");
458 /* Read server configuration options from the configuration file. */
459 read_server_config(&options, config_file_name);
461 /* Fill in default values for those options not explicitly set. */
462 fill_default_server_options(&options);
464 /* Check certain values for sanity. */
465 if (options.server_key_bits < 512 ||
466 options.server_key_bits > 32768)
468 fprintf(stderr, "Bad server key size.\n");
471 if (options.port < 1 || options.port > 65535)
473 fprintf(stderr, "Bad port number.\n");
477 /* Check that there are no remaining arguments. */
480 fprintf(stderr, "Extra argument %s.\n", av[optind]);
484 /* Initialize the log (it is reinitialized below in case we forked). */
486 if (debug_flag && !inetd_flag)
489 log_init(av0, options.log_level, options.log_facility, log_stderr);
491 debug("sshd version %.100s", SSH_VERSION);
493 sensitive_data.host_key = RSA_new();
494 /* Load the host key. It must have empty passphrase. */
495 if (!load_private_key(options.host_key_file, "",
496 sensitive_data.host_key, &comment))
499 fprintf(stderr, "Could not load host key: %s: %s\n",
500 options.host_key_file, strerror(errno));
505 log_init(av0, SYSLOG_LEVEL_DEBUG, options.log_facility, log_stderr);
506 error("Could not load host key: %.200s: %.100s",
507 options.host_key_file, strerror(err));
513 /* If not in debugging mode, and not started from inetd, disconnect from
514 the controlling terminal, and fork. The original process exits. */
515 if (!debug_flag && !inetd_flag)
519 #endif /* TIOCNOTTY */
520 if (daemon(0, 0) < 0)
521 fatal("daemon() failed: %.200s", strerror(errno));
523 /* Disconnect from the controlling tty. */
525 fd = open("/dev/tty", O_RDWR|O_NOCTTY);
528 (void)ioctl(fd, TIOCNOTTY, NULL);
531 #endif /* TIOCNOTTY */
534 /* Reinitialize the log (because of the fork above). */
535 log_init(av0, options.log_level, options.log_facility, log_stderr);
537 /* Check that server and host key lengths differ sufficiently. This is
538 necessary to make double encryption work with rsaref. Oh, I hate
539 software patents. I dont know if this can go? Niels */
540 if (options.server_key_bits >
541 BN_num_bits(sensitive_data.host_key->n) - SSH_KEY_BITS_RESERVED &&
542 options.server_key_bits <
543 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED)
545 options.server_key_bits =
546 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED;
547 debug("Forcing server key to %d bits to make it differ from host key.",
548 options.server_key_bits);
551 /* Do not display messages to stdout in RSA code. */
554 /* Initialize the random number generator. */
557 /* Chdir to the root directory so that the current disk can be unmounted
561 /* Close connection cleanly after attack. */
562 cipher_attack_detected = packet_disconnect;
564 /* Start listening for a socket, unless started from inetd. */
568 s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */
572 /* We intentionally do not close the descriptors 0, 1, and 2 as our
573 code for setting the descriptors won\'t work if ttyfd happens to
575 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
577 public_key = RSA_new();
578 sensitive_data.private_key = RSA_new();
579 /* Generate an rsa key. */
580 log("Generating %d bit RSA key.", options.server_key_bits);
581 rsa_generate_key(sensitive_data.private_key, public_key,
582 options.server_key_bits);
584 log("RSA key generation complete.");
588 /* Create socket for listening. */
589 listen_sock = socket(AF_INET, SOCK_STREAM, 0);
591 fatal("socket: %.100s", strerror(errno));
593 /* Set socket options. We try to make the port reusable and have it
594 close as fast as possible without waiting in unnecessary wait states
596 setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on,
600 setsockopt(listen_sock, SOL_SOCKET, SO_LINGER, (void *)&linger,
603 /* Initialize the socket address. */
604 memset(&sin, 0, sizeof(sin));
605 sin.sin_family = AF_INET;
606 sin.sin_addr = options.listen_addr;
607 sin.sin_port = htons(options.port);
609 /* Bind the socket to the desired port. */
610 if (bind(listen_sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
612 error("bind: %.100s", strerror(errno));
613 shutdown(listen_sock, SHUT_RDWR);
615 fatal("Bind to port %d failed.", options.port);
620 /* Record our pid in /etc/sshd_pid to make it easier to kill the
621 correct sshd. We don\'t want to do this before the bind above
622 because the bind will fail if there already is a daemon, and this
623 will overwrite any old pid in the file. */
624 f = fopen(SSH_DAEMON_PID_FILE, "w");
627 fprintf(f, "%u\n", (unsigned int)getpid());
632 /* Start listening on the port. */
633 log("Server listening on port %d.", options.port);
634 if (listen(listen_sock, 5) < 0)
635 fatal("listen: %.100s", strerror(errno));
637 public_key = RSA_new();
638 sensitive_data.private_key = RSA_new();
639 /* Generate an rsa key. */
640 log("Generating %d bit RSA key.", options.server_key_bits);
641 rsa_generate_key(sensitive_data.private_key, public_key,
642 options.server_key_bits);
644 log("RSA key generation complete.");
646 /* Schedule server key regeneration alarm. */
647 signal(SIGALRM, key_regeneration_alarm);
648 alarm(options.key_regeneration_time);
650 /* Arrange to restart on SIGHUP. The handler needs listen_sock. */
651 signal(SIGHUP, sighup_handler);
652 signal(SIGTERM, sigterm_handler);
653 signal(SIGQUIT, sigterm_handler);
655 /* Arrange SIGCHLD to be caught. */
656 signal(SIGCHLD, main_sigchld_handler);
658 /* Stay listening for connections until the system crashes or the
659 daemon is killed with a signal. */
664 /* Wait in accept until there is a connection. */
666 newsock = accept(listen_sock, (struct sockaddr *)&sin, &aux);
673 error("accept: %.100s", strerror(errno));
677 /* Got connection. Fork a child to handle it, unless we are in
681 /* In debugging mode. Close the listening socket, and start
682 processing the connection without forking. */
683 debug("Server will not fork when running in debugging mode.");
692 /* Normal production daemon. Fork, and have the child process
693 the connection. The parent continues listening. */
694 if ((pid = fork()) == 0)
696 /* Child. Close the listening socket, and start using
697 the accepted socket. Reinitialize logging (since our
698 pid has changed). We break out of the loop to handle
703 log_init(av0, options.log_level, options.log_facility, log_stderr);
708 /* Parent. Stay in the loop. */
710 error("fork: %.100s", strerror(errno));
712 debug("Forked child %d.", pid);
714 /* Mark that the key has been used (it was "given" to the child). */
719 /* Close the new socket (the child is now taking care of it). */
724 /* This is the child processing a new connection. */
726 /* Disable the key regeneration alarm. We will not regenerate the key
727 since we are no longer in a position to give it to anyone. We will
728 not restart on SIGHUP since it no longer makes sense. */
730 signal(SIGALRM, SIG_DFL);
731 signal(SIGHUP, SIG_DFL);
732 signal(SIGTERM, SIG_DFL);
733 signal(SIGQUIT, SIG_DFL);
734 signal(SIGCHLD, SIG_DFL);
736 /* Set socket options for the connection. We want the socket to close
737 as fast as possible without waiting for anything. If the connection
738 is not a socket, these will do nothing. */
739 /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
742 setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *)&linger, sizeof(linger));
744 /* Register our connection. This turns encryption off because we do not
746 packet_set_connection(sock_in, sock_out);
748 remote_port = get_remote_port();
750 /* Check whether logins are denied from this host. */
753 struct request_info req;
755 request_init(&req, RQ_DAEMON, av0, RQ_FILE, sock_in, NULL);
758 if (!hosts_access(&req)) {
763 log("Connection from %.500s port %d", eval_client(&req), remote_port);
766 /* Log the connection. */
767 log("Connection from %.100s port %d", get_remote_ipaddr(), remote_port);
770 /* We don\'t want to listen forever unless the other side successfully
771 authenticates itself. So we set up an alarm which is cleared after
772 successful authentication. A limit of zero indicates no limit.
773 Note that we don\'t set the alarm in debugging mode; it is just annoying
774 to have the server exit just when you are about to discover the bug. */
775 signal(SIGALRM, grace_alarm_handler);
777 alarm(options.login_grace_time);
779 /* Send our protocol version identification. */
780 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n",
781 PROTOCOL_MAJOR, PROTOCOL_MINOR, SSH_VERSION);
782 if (write(sock_out, buf, strlen(buf)) != strlen(buf))
783 fatal("Could not write ident string.");
785 /* Read other side\'s version identification. */
786 for (i = 0; i < sizeof(buf) - 1; i++)
788 if (read(sock_in, &buf[i], 1) != 1)
789 fatal("Did not receive ident string.");
803 buf[sizeof(buf) - 1] = 0;
805 /* Check that the versions match. In future this might accept several
806 versions and set appropriate flags to handle them. */
807 if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", &remote_major, &remote_minor,
808 remote_version) != 3)
810 const char *s = "Protocol mismatch.\n";
811 (void) write(sock_out, s, strlen(s));
814 fatal("Bad protocol version identification: %.100s", buf);
816 debug("Client protocol version %d.%d; client software version %.100s",
817 remote_major, remote_minor, remote_version);
818 if (remote_major != PROTOCOL_MAJOR)
820 const char *s = "Protocol major versions differ.\n";
821 (void) write(sock_out, s, strlen(s));
824 fatal("Protocol major versions differ: %d vs. %d",
825 PROTOCOL_MAJOR, remote_major);
828 /* Check that the client has sufficiently high software version. */
829 if (remote_major == 1 && remote_minor < 3)
830 packet_disconnect("Your ssh version is too old and is no longer supported. Please install a newer version.");
832 if (remote_major == 1 && remote_minor == 3) {
834 if (strcmp(remote_version, "OpenSSH-1.1") != 0) {
835 debug("Agent forwarding disabled, remote version is not compatible.");
836 no_agent_forwarding_flag = 1;
840 /* Check that the connection comes from a privileged port.
841 Rhosts- and Rhosts-RSA-Authentication only make sense
842 from priviledged programs.
843 Of course, if the intruder has root access on his local machine,
844 he can connect from any port. So do not use these authentication
845 methods from machines that you do not trust. */
846 if (remote_port >= IPPORT_RESERVED ||
847 remote_port < IPPORT_RESERVED / 2)
849 options.rhosts_authentication = 0;
850 options.rhosts_rsa_authentication = 0;
853 packet_set_nonblocking();
855 /* Handle the connection. */
859 /* Cleanup user's ticket cache file. */
860 if (options.kerberos_ticket_cleanup)
864 /* Cleanup user's local Xauthority file. */
865 if (xauthfile) unlink(xauthfile);
867 /* The connection has been terminated. */
868 log("Closing connection to %.100s", inet_ntoa(sin.sin_addr));
876 debug("Closing PAM session.");
877 retval = pam_close_session((pam_handle_t *)pamh, 0);
879 debug("Terminating PAM library.");
880 if (pam_end((pam_handle_t *)pamh, retval) != PAM_SUCCESS)
881 log("Cannot release PAM authentication.");
883 fatal_remove_cleanup(&pam_cleanup_proc, NULL);
886 #endif /* HAVE_LIBPAM */
893 /* Process an incoming connection. Protocol version identifiers have already
894 been exchanged. This sends server key and performs the key exchange.
895 Server and host keys will no longer be needed after this functions. */
901 BIGNUM *session_key_int;
902 unsigned char session_key[SSH_SESSION_KEY_LENGTH];
903 unsigned char check_bytes[8];
905 unsigned int cipher_type, auth_mask, protocol_flags;
909 /* Generate check bytes that the client must send back in the user packet
910 in order for it to be accepted; this is used to defy ip spoofing
911 attacks. Note that this only works against somebody doing IP spoofing
912 from a remote machine; any machine on the local network can still see
913 outgoing packets and catch the random cookie. This only affects
914 rhosts authentication, and this is one of the reasons why it is
915 inherently insecure. */
916 for (i = 0; i < 8; i++) {
919 check_bytes[i] = rand & 0xff;
923 /* Send our public key. We include in the packet 64 bits of random
924 data that must be matched in the reply in order to prevent IP spoofing. */
925 packet_start(SSH_SMSG_PUBLIC_KEY);
926 for (i = 0; i < 8; i++)
927 packet_put_char(check_bytes[i]);
929 /* Store our public server RSA key. */
930 packet_put_int(BN_num_bits(public_key->n));
931 packet_put_bignum(public_key->e);
932 packet_put_bignum(public_key->n);
934 /* Store our public host RSA key. */
935 packet_put_int(BN_num_bits(sensitive_data.host_key->n));
936 packet_put_bignum(sensitive_data.host_key->e);
937 packet_put_bignum(sensitive_data.host_key->n);
939 /* Put protocol flags. */
940 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
942 /* Declare which ciphers we support. */
943 packet_put_int(cipher_mask());
945 /* Declare supported authentication types. */
947 if (options.rhosts_authentication)
948 auth_mask |= 1 << SSH_AUTH_RHOSTS;
949 if (options.rhosts_rsa_authentication)
950 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
951 if (options.rsa_authentication)
952 auth_mask |= 1 << SSH_AUTH_RSA;
954 if (options.kerberos_authentication)
955 auth_mask |= 1 << SSH_AUTH_KERBEROS;
958 if (options.kerberos_tgt_passing)
959 auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
960 if (options.afs_token_passing)
961 auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
963 if (options.password_authentication)
964 auth_mask |= 1 << SSH_AUTH_PASSWORD;
965 packet_put_int(auth_mask);
967 /* Send the packet and wait for it to be sent. */
971 debug("Sent %d bit public key and %d bit host key.",
972 BN_num_bits(public_key->n), BN_num_bits(sensitive_data.host_key->n));
974 /* Read clients reply (cipher type and session key). */
975 packet_read_expect(&plen, SSH_CMSG_SESSION_KEY);
977 /* Get cipher type. */
978 cipher_type = packet_get_char();
980 /* Get check bytes from the packet. These must match those we sent earlier
981 with the public key packet. */
982 for (i = 0; i < 8; i++)
983 if (check_bytes[i] != packet_get_char())
984 packet_disconnect("IP Spoofing check bytes do not match.");
986 debug("Encryption type: %.200s", cipher_name(cipher_type));
988 /* Get the encrypted integer. */
989 session_key_int = BN_new();
990 packet_get_bignum(session_key_int, &slen);
992 /* Get protocol flags. */
993 protocol_flags = packet_get_int();
994 packet_set_protocol_flags(protocol_flags);
996 packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY);
998 /* Decrypt it using our private server key and private host key (key with
999 larger modulus first). */
1000 if (BN_cmp(sensitive_data.private_key->n, sensitive_data.host_key->n) > 0)
1002 /* Private key has bigger modulus. */
1003 if (BN_num_bits(sensitive_data.private_key->n) <
1004 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
1005 fatal("do_connection: private_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1006 BN_num_bits(sensitive_data.private_key->n),
1007 BN_num_bits(sensitive_data.host_key->n),
1008 SSH_KEY_BITS_RESERVED);
1011 rsa_private_decrypt(session_key_int, session_key_int,
1012 sensitive_data.private_key);
1013 rsa_private_decrypt(session_key_int, session_key_int,
1014 sensitive_data.host_key);
1018 /* Host key has bigger modulus (or they are equal). */
1019 if (BN_num_bits(sensitive_data.host_key->n) <
1020 BN_num_bits(sensitive_data.private_key->n) + SSH_KEY_BITS_RESERVED) {
1021 fatal("do_connection: host_key %d < private_key %d + SSH_KEY_BITS_RESERVED %d",
1022 BN_num_bits(sensitive_data.host_key->n),
1023 BN_num_bits(sensitive_data.private_key->n),
1024 SSH_KEY_BITS_RESERVED);
1026 rsa_private_decrypt(session_key_int, session_key_int,
1027 sensitive_data.host_key);
1028 rsa_private_decrypt(session_key_int, session_key_int,
1029 sensitive_data.private_key);
1032 /* Compute session id for this session. */
1033 compute_session_id(session_id, check_bytes,
1034 BN_num_bits(sensitive_data.host_key->n),
1035 sensitive_data.host_key->n,
1036 BN_num_bits(sensitive_data.private_key->n),
1037 sensitive_data.private_key->n);
1039 /* Extract session key from the decrypted integer. The key is in the
1040 least significant 256 bits of the integer; the first byte of the
1041 key is in the highest bits. */
1042 BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1043 len = BN_num_bytes(session_key_int);
1044 if (len < 0 || len > sizeof(session_key))
1045 fatal("do_connection: bad len: session_key_int %d > sizeof(session_key) %d",
1046 len, sizeof(session_key));
1047 memset(session_key, 0, sizeof(session_key));
1048 BN_bn2bin(session_key_int, session_key + sizeof(session_key) - len);
1050 /* Xor the first 16 bytes of the session key with the session id. */
1051 for (i = 0; i < 16; i++)
1052 session_key[i] ^= session_id[i];
1054 /* Destroy the decrypted integer. It is no longer needed. */
1055 BN_clear_free(session_key_int);
1057 /* Set the session key. From this on all communications will be
1059 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH,
1062 /* Destroy our copy of the session key. It is no longer needed. */
1063 memset(session_key, 0, sizeof(session_key));
1065 debug("Received session key; encryption turned on.");
1067 /* Send an acknowledgement packet. Note that this packet is sent
1069 packet_start(SSH_SMSG_SUCCESS);
1071 packet_write_wait();
1073 /* Get the name of the user that we wish to log in as. */
1074 packet_read_expect(&plen, SSH_CMSG_USER);
1076 /* Get the user name. */
1079 user = packet_get_string(&ulen);
1080 packet_integrity_check(plen, (4 + ulen), SSH_CMSG_USER);
1083 /* Destroy the private and public keys. They will no longer be needed. */
1084 RSA_free(public_key);
1085 RSA_free(sensitive_data.private_key);
1086 RSA_free(sensitive_data.host_key);
1088 setproctitle("%s", user);
1089 /* Do the authentication. */
1090 do_authentication(user);
1093 /* Check if the user is allowed to log in via ssh. If user is listed in
1094 DenyUsers or user's primary group is listed in DenyGroups, false will
1095 be returned. If AllowUsers isn't empty and user isn't listed there, or
1096 if AllowGroups isn't empty and user isn't listed there, false will be
1097 returned. Otherwise true is returned.
1098 XXX This function should also check if user has a valid shell */
1101 allowed_user(struct passwd *pw)
1106 /* Shouldn't be called if pw is NULL, but better safe than sorry... */
1110 /* XXX Should check for valid login shell */
1112 /* Return false if user is listed in DenyUsers */
1113 if (options.num_deny_users > 0)
1117 for (i = 0; i < options.num_deny_users; i++)
1118 if (match_pattern(pw->pw_name, options.deny_users[i]))
1122 /* Return false if AllowUsers isn't empty and user isn't listed there */
1123 if (options.num_allow_users > 0)
1127 for (i = 0; i < options.num_allow_users; i++)
1128 if (match_pattern(pw->pw_name, options.allow_users[i]))
1130 /* i < options.num_allow_users iff we break for loop */
1131 if (i >= options.num_allow_users)
1135 /* Get the primary group name if we need it. Return false if it fails */
1136 if (options.num_deny_groups > 0 || options.num_allow_groups > 0 )
1138 grp = getgrgid(pw->pw_gid);
1142 /* Return false if user's group is listed in DenyGroups */
1143 if (options.num_deny_groups > 0)
1147 for (i = 0; i < options.num_deny_groups; i++)
1148 if (match_pattern(grp->gr_name, options.deny_groups[i]))
1152 /* Return false if AllowGroups isn't empty and user's group isn't
1154 if (options.num_allow_groups > 0)
1158 for (i = 0; i < options.num_allow_groups; i++)
1159 if (match_pattern(grp->gr_name, options.allow_groups[i]))
1161 /* i < options.num_allow_groups iff we break for loop */
1162 if (i >= options.num_allow_groups)
1167 /* We found no reason not to let this user try to log on... */
1171 /* Performs authentication of an incoming connection. Session key has already
1172 been exchanged and encryption is enabled. User is the user name to log
1173 in as (received from the client). */
1176 do_authentication(char *user)
1178 struct passwd *pw, pwcopy;
1181 /* If machine has AFS, set process authentication group. */
1188 /* Verify that the user is a valid user. */
1189 pw = getpwnam(user);
1190 if (!pw || !allowed_user(pw))
1191 do_fake_authloop(user);
1193 /* Take a copy of the returned structure. */
1194 memset(&pwcopy, 0, sizeof(pwcopy));
1195 pwcopy.pw_name = xstrdup(pw->pw_name);
1196 pwcopy.pw_passwd = xstrdup(pw->pw_passwd);
1197 pwcopy.pw_uid = pw->pw_uid;
1198 pwcopy.pw_gid = pw->pw_gid;
1199 pwcopy.pw_dir = xstrdup(pw->pw_dir);
1200 pwcopy.pw_shell = xstrdup(pw->pw_shell);
1204 debug("Starting up PAM with username \"%.200s\"", pw->pw_name);
1206 if (pam_start("sshd", pw->pw_name, &conv, (pam_handle_t**)&pamh) != PAM_SUCCESS)
1207 fatal("PAM initialisation failed: %.200s", pam_strerror((pam_handle_t *)pamh, pam_retval));
1209 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;
1263 unsigned int client_host_key_bits;
1264 BIGNUM *client_host_key_e, *client_host_key_n;
1266 char *client_user, *password;
1267 int plen, dlen, nlen, ulen, elen;
1269 /* Indicate that authentication is needed. */
1270 packet_start(SSH_SMSG_FAILURE);
1272 packet_write_wait();
1275 int authenticated = 0;
1277 /* Get a packet from the client. */
1278 int type = packet_read(&plen);
1280 /* Process the packet. */
1284 case SSH_CMSG_HAVE_KERBEROS_TGT:
1285 if (!options.kerberos_tgt_passing)
1287 /* packet_get_all(); */
1288 log("Kerberos tgt passing disabled.");
1292 /* Accept Kerberos tgt. */
1293 char *tgt = packet_get_string(&dlen);
1294 packet_integrity_check(plen, 4 + dlen, type);
1295 if (!auth_kerberos_tgt(pw, tgt))
1296 debug("Kerberos tgt REFUSED for %s", pw->pw_name);
1301 case SSH_CMSG_HAVE_AFS_TOKEN:
1302 if (!options.afs_token_passing || !k_hasafs()) {
1303 /* packet_get_all(); */
1304 log("AFS token passing disabled.");
1308 /* Accept AFS token. */
1309 char *token_string = packet_get_string(&dlen);
1310 packet_integrity_check(plen, 4 + dlen, type);
1311 if (!auth_afs_token(pw, token_string))
1312 debug("AFS token REFUSED for %s", pw->pw_name);
1313 xfree(token_string);
1319 case SSH_CMSG_AUTH_KERBEROS:
1320 if (!options.kerberos_authentication)
1322 /* packet_get_all(); */
1323 log("Kerberos authentication disabled.");
1327 /* Try Kerberos v4 authentication. */
1329 char *tkt_user = NULL;
1330 char *kdata = packet_get_string((unsigned int *)&auth.length);
1331 packet_integrity_check(plen, 4 + auth.length, type);
1333 if (auth.length < MAX_KTXT_LEN)
1334 memcpy(auth.dat, kdata, auth.length);
1337 authenticated = auth_krb4(pw->pw_name, &auth, &tkt_user);
1339 log("Kerberos authentication %s%s for account %s from %s",
1340 authenticated ? "accepted " : "failed",
1341 tkt_user != NULL ? tkt_user : "",
1342 pw->pw_name, get_canonical_hostname());
1349 case SSH_CMSG_AUTH_RHOSTS:
1350 if (!options.rhosts_authentication)
1352 log("Rhosts authentication disabled.");
1356 /* Get client user name. Note that we just have to trust the client;
1357 this is one reason why rhosts authentication is insecure.
1358 (Another is IP-spoofing on a local network.) */
1359 client_user = packet_get_string(&dlen);
1360 packet_integrity_check(plen, 4 + dlen, type);
1362 /* Try to authenticate using /etc/hosts.equiv and .rhosts. */
1363 authenticated = auth_rhosts(pw, client_user);
1365 log("Rhosts authentication %s for %.100s, remote %.100s on %.700s.",
1366 authenticated ? "accepted" : "failed",
1367 pw->pw_name, client_user, get_canonical_hostname());
1370 #endif /* HAVE_LIBPAM */
1373 case SSH_CMSG_AUTH_RHOSTS_RSA:
1374 if (!options.rhosts_rsa_authentication)
1376 log("Rhosts with RSA authentication disabled.");
1380 /* Get client user name. Note that we just have to trust
1381 the client; root on the client machine can claim to be
1383 client_user = packet_get_string(&ulen);
1385 /* Get the client host key. */
1386 client_host_key_e = BN_new();
1387 client_host_key_n = BN_new();
1388 client_host_key_bits = packet_get_int();
1389 packet_get_bignum(client_host_key_e, &elen);
1390 packet_get_bignum(client_host_key_n, &nlen);
1392 packet_integrity_check(plen, (4 + ulen) + 4 + elen + nlen, type);
1394 authenticated = auth_rhosts_rsa(pw, client_user, client_host_key_bits,
1395 client_host_key_e, client_host_key_n);
1396 log("Rhosts authentication %s for %.100s, remote %.100s.",
1397 authenticated ? "accepted" : "failed",
1398 pw->pw_name, client_user);
1401 #endif /* HAVE_LIBPAM */
1402 BN_clear_free(client_host_key_e);
1403 BN_clear_free(client_host_key_n);
1406 case SSH_CMSG_AUTH_RSA:
1407 if (!options.rsa_authentication)
1409 log("RSA authentication disabled.");
1413 /* RSA authentication requested. */
1415 packet_get_bignum(n, &nlen);
1416 packet_integrity_check(plen, nlen, type);
1417 authenticated = auth_rsa(pw, n);
1419 log("RSA authentication %s for %.100s.",
1420 authenticated ? "accepted" : "failed",
1424 case SSH_CMSG_AUTH_PASSWORD:
1425 if (!options.password_authentication)
1427 log("Password authentication disabled.");
1431 /* Read user password. It is in plain text, but was transmitted
1432 over the encrypted channel so it is not visible to an outside
1434 password = packet_get_string(&dlen);
1435 packet_integrity_check(plen, 4 + dlen, type);
1438 /* Do PAM auth with password */
1439 pampasswd = password;
1440 pam_retval = pam_authenticate((pam_handle_t *)pamh, 0);
1441 if (pam_retval == PAM_SUCCESS)
1443 log("PAM Password authentication accepted for user \"%.100s\"", user);
1448 log("PAM Password authentication for \"%.100s\" failed: %s",
1449 user, pam_strerror((pam_handle_t *)pamh, pam_retval));
1451 #else /* HAVE_LIBPAM */
1452 /* Try authentication with the password. */
1453 authenticated = auth_password(pw, password);
1455 memset(password, 0, strlen(password));
1458 #endif /* HAVE_LIBPAM */
1460 case SSH_CMSG_AUTH_TIS:
1461 /* TIS Authentication is unsupported */
1462 log("TIS authentication disabled.");
1466 /* Any unknown messages will be ignored (and failure returned)
1467 during authentication. */
1468 log("Unknown message during authentication: type %d", type);
1469 break; /* Respond with a failure message. */
1474 if (++authentication_failures >= MAX_AUTH_FAILURES)
1475 packet_disconnect("Too many authentication failures for %.100s from %.200s",
1476 pw->pw_name, get_canonical_hostname());
1477 /* Send a message indicating that the authentication attempt failed. */
1478 packet_start(SSH_SMSG_FAILURE);
1480 packet_write_wait();
1484 do_pam_account_and_session(pw->pw_name, client_user, get_canonical_hostname());
1487 if (client_user != NULL)
1490 if (password != NULL)
1492 memset(password, 0, strlen(password));
1495 #endif /* HAVE_LIBPAM */
1498 /* The user does not exist or access is denied,
1499 but fake indication that authentication is needed. */
1501 do_fake_authloop(char *user)
1503 int authentication_failures = 0;
1505 /* Indicate that authentication is needed. */
1506 packet_start(SSH_SMSG_FAILURE);
1508 packet_write_wait();
1510 /* Keep reading packets, and always respond with a failure. This is to
1511 avoid disclosing whether such a user really exists. */
1514 /* Read a packet. This will not return if the client disconnects. */
1516 int type = packet_read(&plen);
1519 char *password, *skeyinfo;
1520 if (options.password_authentication &&
1521 options.skey_authentication == 1 &&
1522 type == SSH_CMSG_AUTH_PASSWORD &&
1523 (password = packet_get_string(&passw_len)) != NULL &&
1525 strncasecmp(password, "s/key", 5) == 0 &&
1526 (skeyinfo = skey_fake_keyinfo(user)) != NULL ){
1527 /* Send a fake s/key challenge. */
1528 packet_send_debug(skeyinfo);
1531 if (++authentication_failures >= MAX_AUTH_FAILURES)
1532 packet_disconnect("Too many authentication failures for %.100s from %.200s",
1533 user, get_canonical_hostname());
1534 /* Send failure. This should be indistinguishable from a failed
1536 packet_start(SSH_SMSG_FAILURE);
1538 packet_write_wait();
1545 /* Remove local Xauthority file. */
1547 xauthfile_cleanup_proc(void *ignore)
1549 debug("xauthfile_cleanup_proc called");
1551 if (xauthfile != NULL) {
1558 /* Prepares for an interactive session. This is called after the user has
1559 been successfully authenticated. During this message exchange, pseudo
1560 terminals are allocated, X11, TCP/IP, and authentication agent forwardings
1561 are requested, etc. */
1563 void do_authenticated(struct passwd *pw)
1566 int compression_level = 0, enable_compression_after_reply = 0;
1567 int have_pty = 0, ptyfd = -1, ttyfd = -1, xauthfd = -1;
1568 int row, col, xpixel, ypixel, screen;
1570 char *command, *term = NULL, *display = NULL, *proto = NULL, *data = NULL;
1576 /* Cancel the alarm we set to limit the time taken for authentication. */
1579 /* Inform the channel mechanism that we are the server side and that
1580 the client may request to connect to any port at all. (The user could
1581 do it anyway, and we wouldn\'t know what is permitted except by the
1582 client telling us, so we can equally well trust the client not to request
1584 channel_permit_all_opens();
1586 /* We stay in this loop until the client requests to execute a shell or a
1592 /* Get a packet from the client. */
1593 type = packet_read(&plen);
1595 /* Process the packet. */
1598 case SSH_CMSG_REQUEST_COMPRESSION:
1599 packet_integrity_check(plen, 4, type);
1600 compression_level = packet_get_int();
1601 if (compression_level < 1 || compression_level > 9)
1603 packet_send_debug("Received illegal compression level %d.",
1607 /* Enable compression after we have responded with SUCCESS. */
1608 enable_compression_after_reply = 1;
1611 case SSH_CMSG_REQUEST_PTY:
1614 debug("Allocating a pty not permitted for this authentication.");
1618 packet_disconnect("Protocol error: you already have a pty.");
1620 debug("Allocating pty.");
1622 /* Allocate a pty and open it. */
1623 if (!pty_allocate(&ptyfd, &ttyfd, ttyname))
1625 error("Failed to allocate pty.");
1629 /* Determine the group to make the owner of the tty. */
1630 grp = getgrnam("tty");
1633 tty_gid = grp->gr_gid;
1634 tty_mode = S_IRUSR|S_IWUSR|S_IWGRP;
1638 tty_gid = pw->pw_gid;
1639 tty_mode = S_IRUSR|S_IWUSR|S_IWGRP|S_IWOTH;
1642 /* Change ownership of the tty. */
1643 if (chown(ttyname, pw->pw_uid, tty_gid) < 0)
1644 fatal("chown(%.100s, %d, %d) failed: %.100s",
1645 ttyname, pw->pw_uid, tty_gid, strerror(errno));
1646 if (chmod(ttyname, tty_mode) < 0)
1647 fatal("chmod(%.100s, 0%o) failed: %.100s",
1648 ttyname, tty_mode, strerror(errno));
1650 /* Get TERM from the packet. Note that the value may be of arbitrary
1653 term = packet_get_string(&dlen);
1654 packet_integrity_check(dlen, strlen(term), type);
1655 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
1656 /* Remaining bytes */
1657 n_bytes = plen - (4 + dlen + 4*4);
1659 if (strcmp(term, "") == 0)
1662 /* Get window size from the packet. */
1663 row = packet_get_int();
1664 col = packet_get_int();
1665 xpixel = packet_get_int();
1666 ypixel = packet_get_int();
1667 pty_change_window_size(ptyfd, row, col, xpixel, ypixel);
1669 /* Get tty modes from the packet. */
1670 tty_parse_modes(ttyfd, &n_bytes);
1671 packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type);
1673 /* Indicate that we now have a pty. */
1677 case SSH_CMSG_X11_REQUEST_FORWARDING:
1678 if (!options.x11_forwarding)
1680 packet_send_debug("X11 forwarding disabled in server configuration file.");
1684 if (no_x11_forwarding_flag)
1686 packet_send_debug("X11 forwarding not permitted for this authentication.");
1689 debug("Received request for X11 forwarding with auth spoofing.");
1691 packet_disconnect("Protocol error: X11 display already set.");
1693 int proto_len, data_len;
1694 proto = packet_get_string(&proto_len);
1695 data = packet_get_string(&data_len);
1696 packet_integrity_check(plen, 4+proto_len + 4+data_len + 4, type);
1698 if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
1699 screen = packet_get_int();
1702 display = x11_create_display_inet(screen);
1706 /* Setup to always have a local .Xauthority. */
1707 xauthfile = xmalloc(MAXPATHLEN);
1708 snprintf(xauthfile, MAXPATHLEN, "/tmp/XauthXXXXXX");
1710 if ((xauthfd = mkstemp(xauthfile)) != -1) {
1711 fchown(xauthfd, pw->pw_uid, pw->pw_gid);
1713 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
1720 #else /* XAUTH_PATH */
1721 /* No xauth program; we won't accept forwarding with spoofing. */
1722 packet_send_debug("No xauth program; cannot forward with spoofing.");
1724 #endif /* XAUTH_PATH */
1726 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
1727 if (no_agent_forwarding_flag)
1729 debug("Authentication agent forwarding not permitted for this authentication.");
1732 debug("Received authentication agent forwarding request.");
1733 auth_input_request_forwarding(pw);
1736 case SSH_CMSG_PORT_FORWARD_REQUEST:
1737 if (no_port_forwarding_flag)
1739 debug("Port forwarding not permitted for this authentication.");
1742 debug("Received TCP/IP port forwarding request.");
1743 channel_input_port_forward_request(pw->pw_uid == 0);
1746 case SSH_CMSG_EXEC_SHELL:
1747 /* Set interactive/non-interactive mode. */
1748 packet_set_interactive(have_pty || display != NULL,
1749 options.keepalives);
1751 if (forced_command != NULL)
1752 goto do_forced_command;
1753 debug("Forking shell.");
1754 packet_integrity_check(plen, 0, type);
1756 do_exec_pty(NULL, ptyfd, ttyfd, ttyname, pw, term, display, proto,
1759 do_exec_no_pty(NULL, pw, display, proto, data);
1762 case SSH_CMSG_EXEC_CMD:
1763 /* Set interactive/non-interactive mode. */
1764 packet_set_interactive(have_pty || display != NULL,
1765 options.keepalives);
1767 if (forced_command != NULL)
1768 goto do_forced_command;
1769 /* Get command from the packet. */
1772 command = packet_get_string(&dlen);
1773 debug("Executing command '%.500s'", command);
1774 packet_integrity_check(plen, 4 + dlen, type);
1777 do_exec_pty(command, ptyfd, ttyfd, ttyname, pw, term, display,
1780 do_exec_no_pty(command, pw, display, proto, data);
1784 case SSH_CMSG_MAX_PACKET_SIZE:
1785 debug("The server does not support limiting packet size.");
1789 /* Any unknown messages in this phase are ignored, and a failure
1790 message is returned. */
1791 log("Unknown packet type received after authentication: %d", type);
1795 /* The request was successfully processed. */
1796 packet_start(SSH_SMSG_SUCCESS);
1798 packet_write_wait();
1800 /* Enable compression now that we have replied if appropriate. */
1801 if (enable_compression_after_reply)
1803 enable_compression_after_reply = 0;
1804 packet_start_compression(compression_level);
1810 /* The request failed. */
1811 packet_start(SSH_SMSG_FAILURE);
1813 packet_write_wait();
1817 /* There is a forced command specified for this login. Execute it. */
1818 debug("Executing forced command: %.900s", forced_command);
1820 do_exec_pty(forced_command, ptyfd, ttyfd, ttyname, pw, term, display,
1823 do_exec_no_pty(forced_command, pw, display, proto, data);
1828 /* This is called to fork and execute a command when we have no tty. This
1829 will call do_child from the child, and server_loop from the parent after
1830 setting up file descriptors and such. */
1832 void do_exec_no_pty(const char *command, struct passwd *pw,
1833 const char *display, const char *auth_proto,
1834 const char *auth_data)
1839 int pin[2], pout[2], perr[2];
1840 /* Allocate pipes for communicating with the program. */
1841 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
1842 packet_disconnect("Could not create pipes: %.100s",
1844 #else /* USE_PIPES */
1845 int inout[2], err[2];
1846 /* Uses socket pairs to communicate with the program. */
1847 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
1848 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
1849 packet_disconnect("Could not create socket pairs: %.100s",
1851 #endif /* USE_PIPES */
1853 setproctitle("%s@notty", pw->pw_name);
1855 /* Fork the child. */
1856 if ((pid = fork()) == 0)
1858 /* Child. Reinitialize the log since the pid has changed. */
1859 log_init(av0, options.log_level, options.log_facility, log_stderr);
1861 /* Create a new session and process group since the 4.4BSD setlogin()
1862 affects the entire process group. */
1864 error("setsid failed: %.100s", strerror(errno));
1867 /* Redirect stdin. We close the parent side of the socket pair,
1868 and make the child side the standard input. */
1870 if (dup2(pin[0], 0) < 0)
1871 perror("dup2 stdin");
1874 /* Redirect stdout. */
1876 if (dup2(pout[1], 1) < 0)
1877 perror("dup2 stdout");
1880 /* Redirect stderr. */
1882 if (dup2(perr[1], 2) < 0)
1883 perror("dup2 stderr");
1885 #else /* USE_PIPES */
1886 /* Redirect stdin, stdout, and stderr. Stdin and stdout will use the
1887 same socket, as some programs (particularly rdist) seem to depend
1891 if (dup2(inout[0], 0) < 0) /* stdin */
1892 perror("dup2 stdin");
1893 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
1894 perror("dup2 stdout");
1895 if (dup2(err[0], 2) < 0) /* stderr */
1896 perror("dup2 stderr");
1897 #endif /* USE_PIPES */
1899 /* Do processing for the child (exec command etc). */
1900 do_child(command, pw, NULL, display, auth_proto, auth_data, NULL);
1904 packet_disconnect("fork failed: %.100s", strerror(errno));
1906 /* We are the parent. Close the child sides of the pipes. */
1911 /* Enter the interactive session. */
1912 server_loop(pid, pin[1], pout[0], perr[0]);
1913 /* server_loop has closed pin[1], pout[1], and perr[1]. */
1914 #else /* USE_PIPES */
1915 /* We are the parent. Close the child sides of the socket pairs. */
1919 /* Enter the interactive session. Note: server_loop must be able to handle
1920 the case that fdin and fdout are the same. */
1921 server_loop(pid, inout[1], inout[1], err[1]);
1922 /* server_loop has closed inout[1] and err[1]. */
1923 #endif /* USE_PIPES */
1926 struct pty_cleanup_context
1928 const char *ttyname;
1932 /* Function to perform cleanup if we get aborted abnormally (e.g., due to a
1933 dropped connection). */
1935 void pty_cleanup_proc(void *context)
1937 struct pty_cleanup_context *cu = context;
1939 debug("pty_cleanup_proc called");
1941 /* Record that the user has logged out. */
1942 record_logout(cu->pid, cu->ttyname);
1944 /* Release the pseudo-tty. */
1945 pty_release(cu->ttyname);
1948 /* This is called to fork and execute a command when we have a tty. This
1949 will call do_child from the child, and server_loop from the parent after
1950 setting up file descriptors, controlling tty, updating wtmp, utmp,
1951 lastlog, and other such operations. */
1953 void do_exec_pty(const char *command, int ptyfd, int ttyfd,
1954 const char *ttyname, struct passwd *pw, const char *term,
1955 const char *display, const char *auth_proto,
1956 const char *auth_data)
1959 const char *hostname;
1960 time_t last_login_time;
1961 char buf[100], *time_string;
1966 struct sockaddr_in from;
1968 struct pty_cleanup_context cleanup_context;
1970 /* Get remote host name. */
1971 hostname = get_canonical_hostname();
1973 /* Get the time when the user last logged in. Buf will be set to contain
1974 the hostname the last login was from. */
1975 if(!options.use_login) {
1976 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
1980 setproctitle("%s@%s", pw->pw_name, strrchr(ttyname, '/') + 1);
1982 /* Fork the child. */
1983 if ((pid = fork()) == 0)
1987 /* Child. Reinitialize the log because the pid has changed. */
1988 log_init(av0, options.log_level, options.log_facility, log_stderr);
1990 /* Close the master side of the pseudo tty. */
1993 /* Make the pseudo tty our controlling tty. */
1994 pty_make_controlling_tty(&ttyfd, ttyname);
1996 /* Redirect stdin from the pseudo tty. */
1997 if (dup2(ttyfd, fileno(stdin)) < 0)
1998 error("dup2 stdin failed: %.100s", strerror(errno));
2000 /* Redirect stdout to the pseudo tty. */
2001 if (dup2(ttyfd, fileno(stdout)) < 0)
2002 error("dup2 stdin failed: %.100s", strerror(errno));
2004 /* Redirect stderr to the pseudo tty. */
2005 if (dup2(ttyfd, fileno(stderr)) < 0)
2006 error("dup2 stdin failed: %.100s", strerror(errno));
2008 /* Close the extra descriptor for the pseudo tty. */
2011 /* Get IP address of client. This is needed because we want to record
2012 where the user logged in from. If the connection is not a socket,
2013 let the ip address be 0.0.0.0. */
2014 memset(&from, 0, sizeof(from));
2015 if (packet_get_connection_in() == packet_get_connection_out())
2017 fromlen = sizeof(from);
2018 if (getpeername(packet_get_connection_in(),
2019 (struct sockaddr *)&from, &fromlen) < 0) {
2020 debug("getpeername: %.100s", strerror(errno));
2025 /* Record that there was a login on that terminal. */
2026 record_login(pid, ttyname, pw->pw_name, pw->pw_uid, hostname,
2029 /* Check if .hushlogin exists. */
2030 snprintf(line, sizeof line, "%.200s/.hushlogin", pw->pw_dir);
2031 quiet_login = stat(line, &st) >= 0;
2034 /* output the results of the pamconv() */
2035 if (!quiet_login && pamconv_msg != NULL)
2036 fprintf(stderr, pamconv_msg);
2039 /* If the user has logged in before, display the time of last login.
2040 However, don't display anything extra if a command has been
2041 specified (so that ssh can be used to execute commands on a remote
2042 machine without users knowing they are going to another machine).
2043 Login(1) will do this for us as well, so check if login(1) is used */
2044 if (command == NULL && last_login_time != 0 && !quiet_login &&
2047 /* Convert the date to a string. */
2048 time_string = ctime(&last_login_time);
2049 /* Remove the trailing newline. */
2050 if (strchr(time_string, '\n'))
2051 *strchr(time_string, '\n') = 0;
2052 /* Display the last login time. Host if displayed if known. */
2053 if (strcmp(buf, "") == 0)
2054 printf("Last login: %s\r\n", time_string);
2056 printf("Last login: %s from %s\r\n", time_string, buf);
2059 /* Print /etc/motd unless a command was specified or printing it was
2060 disabled in server options or login(1) will be used. Note that
2061 some machines appear to print it in /etc/profile or similar. */
2062 if (command == NULL && options.print_motd && !quiet_login &&
2065 /* Print /etc/motd if it exists. */
2066 f = fopen("/etc/motd", "r");
2069 while (fgets(line, sizeof(line), f))
2070 fputs(line, stdout);
2075 /* Do common processing for the child, such as execing the command. */
2076 do_child(command, pw, term, display, auth_proto, auth_data, ttyname);
2080 packet_disconnect("fork failed: %.100s", strerror(errno));
2081 /* Parent. Close the slave side of the pseudo tty. */
2084 /* Create another descriptor of the pty master side for use as the standard
2085 input. We could use the original descriptor, but this simplifies code
2086 in server_loop. The descriptor is bidirectional. */
2089 packet_disconnect("dup failed: %.100s", strerror(errno));
2091 /* Add a cleanup function to clear the utmp entry and record logout time
2092 in case we call fatal() (e.g., the connection gets closed). */
2093 cleanup_context.pid = pid;
2094 cleanup_context.ttyname = ttyname;
2095 fatal_add_cleanup(pty_cleanup_proc, (void *)&cleanup_context);
2097 /* Enter interactive session. */
2098 server_loop(pid, ptyfd, fdout, -1);
2099 /* server_loop has not closed ptyfd and fdout. */
2101 /* Cancel the cleanup function. */
2102 fatal_remove_cleanup(pty_cleanup_proc, (void *)&cleanup_context);
2104 /* Record that the user has logged out. */
2105 record_logout(pid, ttyname);
2107 /* Release the pseudo-tty. */
2108 pty_release(ttyname);
2110 /* Close the server side of the socket pairs. We must do this after the
2111 pty cleanup, so that another process doesn't get this pty while we're
2112 still cleaning up. */
2117 /* Sets the value of the given variable in the environment. If the variable
2118 already exists, its value is overriden. */
2120 void child_set_env(char ***envp, unsigned int *envsizep, const char *name,
2123 unsigned int i, namelen;
2126 /* Find the slot where the value should be stored. If the variable already
2127 exists, we reuse the slot; otherwise we append a new slot at the end
2128 of the array, expanding if necessary. */
2130 namelen = strlen(name);
2131 for (i = 0; env[i]; i++)
2132 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
2136 /* Name already exists. Reuse the slot. */
2141 /* New variable. Expand the array if necessary. */
2142 if (i >= (*envsizep) - 1)
2145 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
2148 /* Need to set the NULL pointer at end of array beyond the new
2153 /* Allocate space and format the variable in the appropriate slot. */
2154 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
2155 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
2158 /* Reads environment variables from the given file and adds/overrides them
2159 into the environment. If the file does not exist, this does nothing.
2160 Otherwise, it must consist of empty lines, comments (line starts with '#')
2161 and assignments of the form name=value. No other forms are allowed. */
2163 void read_environment_file(char ***env, unsigned int *envsize,
2164 const char *filename)
2170 /* Open the environment file. */
2171 f = fopen(filename, "r");
2173 return; /* Not found. */
2175 /* Process each line. */
2176 while (fgets(buf, sizeof(buf), f))
2178 /* Skip leading whitespace. */
2179 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
2182 /* Ignore empty and comment lines. */
2183 if (!*cp || *cp == '#' || *cp == '\n')
2186 /* Remove newline. */
2187 if (strchr(cp, '\n'))
2188 *strchr(cp, '\n') = '\0';
2190 /* Find the equals sign. Its lack indicates badly formatted line. */
2191 value = strchr(cp, '=');
2194 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
2198 /* Replace the equals sign by nul, and advance value to the value
2203 /* Set the value in environment. */
2204 child_set_env(env, envsize, cp, value);
2210 /* Performs common processing for the child, such as setting up the
2211 environment, closing extra file descriptors, setting the user and group
2212 ids, and executing the command or shell. */
2214 void do_child(const char *command, struct passwd *pw, const char *term,
2215 const char *display, const char *auth_proto,
2216 const char *auth_data, const char *ttyname)
2218 const char *shell, *cp = NULL;
2221 unsigned int envsize, i;
2223 extern char **environ;
2227 #ifndef HAVE_LIBPAM /* pam_nologin handles this */
2228 /* Check /etc/nologin. */
2229 f = fopen("/etc/nologin", "r");
2231 { /* /etc/nologin exists. Print its contents and exit. */
2232 while (fgets(buf, sizeof(buf), f))
2235 if (pw->pw_uid != 0)
2238 #endif /* HAVE_LIBPAM */
2240 #ifdef HAVE_SETLOGIN
2241 /* Set login name in the kernel. */
2242 if (setlogin(pw->pw_name) < 0)
2243 error("setlogin failed: %s", strerror(errno));
2244 #endif /* HAVE_SETLOGIN */
2246 /* Set uid, gid, and groups. */
2247 /* Login(1) does this as well, and it needs uid 0 for the "-h" switch,
2248 so we let login(1) to this for us. */
2249 if(!options.use_login) {
2250 if (getuid() == 0 || geteuid() == 0)
2252 if (setgid(pw->pw_gid) < 0)
2257 /* Initialize the group list. */
2258 if (initgroups(pw->pw_name, pw->pw_gid) < 0)
2260 perror("initgroups");
2265 /* Permanently switch to the desired uid. */
2266 permanently_set_uid(pw->pw_uid);
2269 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
2270 fatal("Failed to set uids to %d.", (int)pw->pw_uid);
2273 /* Get the shell from the password data. An empty shell field is legal,
2274 and means /bin/sh. */
2275 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
2278 /* Try to get AFS tokens for the local cell. */
2282 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
2283 krb_afslog(cell, 0);
2289 /* Initialize the environment. In the first part we allocate space for
2290 all environment variables. */
2292 env = xmalloc(envsize * sizeof(char *));
2295 if(!options.use_login) {
2296 /* Set basic environment. */
2297 child_set_env(&env, &envsize, "USER", pw->pw_name);
2298 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
2299 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
2300 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
2302 snprintf(buf, sizeof buf, "%.200s/%.50s",
2303 _PATH_MAILDIR, pw->pw_name);
2304 child_set_env(&env, &envsize, "MAIL", buf);
2306 /* Normal systems set SHELL by default. */
2307 child_set_env(&env, &envsize, "SHELL", shell);
2310 /* Let it inherit timezone if we have one. */
2312 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
2314 /* Set custom environment options from RSA authentication. */
2315 while (custom_environment)
2317 struct envstring *ce = custom_environment;
2320 for (i = 0; s[i] != '=' && s[i]; i++)
2325 child_set_env(&env, &envsize, s, s + i + 1);
2327 custom_environment = ce->next;
2332 /* Set SSH_CLIENT. */
2333 snprintf(buf, sizeof buf, "%.50s %d %d",
2334 get_remote_ipaddr(), get_remote_port(), options.port);
2335 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
2337 /* Set SSH_TTY if we have a pty. */
2339 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
2341 /* Set TERM if we have a pty. */
2343 child_set_env(&env, &envsize, "TERM", term);
2345 /* Set DISPLAY if we have one. */
2347 child_set_env(&env, &envsize, "DISPLAY", display);
2351 extern char *ticket;
2354 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
2359 /* Pull in any environment variables that may have been set by PAM. */
2361 char *equal_sign, var_name[256], var_val[256];
2363 char **pam_env = pam_getenvlist((pam_handle_t *)pamh);
2364 for(this_var = 0; pam_env && pam_env[this_var]; this_var++)
2366 if(strlen(pam_env[this_var]) < (sizeof(var_name) - 1))
2367 if((equal_sign = strstr(pam_env[this_var], "=")) != NULL)
2369 memset(var_name, 0, sizeof(var_name));
2370 memset(var_val, 0, sizeof(var_val));
2371 strncpy(var_name, pam_env[this_var],
2372 equal_sign - pam_env[this_var]);
2373 strcpy(var_val, equal_sign + 1);
2374 child_set_env(&env, &envsize, var_name, var_val);
2378 #endif /* HAVE_LIBPAM */
2380 /* Set XAUTHORITY to always be a local file. */
2382 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
2384 /* Set variable for forwarded authentication connection, if we have one. */
2385 if (auth_get_socket_name() != NULL)
2386 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
2387 auth_get_socket_name());
2389 /* Read $HOME/.ssh/environment. */
2390 if(!options.use_login) {
2391 snprintf(buf, sizeof buf, "%.200s/.ssh/environment", pw->pw_dir);
2392 read_environment_file(&env, &envsize, buf);
2395 /* If debugging, dump the environment to stderr. */
2398 fprintf(stderr, "Environment:\n");
2399 for (i = 0; env[i]; i++)
2400 fprintf(stderr, " %.200s\n", env[i]);
2403 /* Close the connection descriptors; note that this is the child, and the
2404 server will still have the socket open, and it is important that we
2405 do not shutdown it. Note that the descriptors cannot be closed before
2406 building the environment, as we call get_remote_ipaddr there. */
2407 if (packet_get_connection_in() == packet_get_connection_out())
2408 close(packet_get_connection_in());
2411 close(packet_get_connection_in());
2412 close(packet_get_connection_out());
2414 /* Close all descriptors related to channels. They will still remain
2415 open in the parent. */
2416 channel_close_all();
2418 /* Close any extra file descriptors. Note that there may still be
2419 descriptors left by system functions. They will be closed later. */
2423 /* Close any extra open file descriptors so that we don\'t have them
2424 hanging around in clients. Note that we want to do this after
2425 initgroups, because at least on Solaris 2.3 it leaves file descriptors
2427 for (i = 3; i < 64; i++)
2430 /* Change current directory to the user\'s home directory. */
2431 if (chdir(pw->pw_dir) < 0)
2432 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
2433 pw->pw_dir, strerror(errno));
2435 /* Must take new environment into use so that .ssh/rc, /etc/sshrc and
2436 xauth are run in the proper environment. */
2439 /* Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
2441 if(!options.use_login) {
2442 if (stat(SSH_USER_RC, &st) >= 0)
2445 fprintf(stderr, "Running /bin/sh %s\n", SSH_USER_RC);
2447 f = popen("/bin/sh " SSH_USER_RC, "w");
2450 if (auth_proto != NULL && auth_data != NULL)
2451 fprintf(f, "%s %s\n", auth_proto, auth_data);
2455 fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
2458 if (stat(SSH_SYSTEM_RC, &st) >= 0)
2461 fprintf(stderr, "Running /bin/sh %s\n", SSH_SYSTEM_RC);
2463 f = popen("/bin/sh " SSH_SYSTEM_RC, "w");
2466 if (auth_proto != NULL && auth_data != NULL)
2467 fprintf(f, "%s %s\n", auth_proto, auth_data);
2471 fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
2476 /* Add authority data to .Xauthority if appropriate. */
2477 if (auth_proto != NULL && auth_data != NULL)
2480 fprintf(stderr, "Running %.100s add %.100s %.100s %.100s\n",
2481 XAUTH_PATH, display, auth_proto, auth_data);
2483 f = popen(XAUTH_PATH " -q -", "w");
2486 fprintf(f, "add %s %s %s\n", display, auth_proto, auth_data);
2490 fprintf(stderr, "Could not run %s -q -\n", XAUTH_PATH);
2493 #endif /* XAUTH_PATH */
2495 /* Get the last component of the shell name. */
2496 cp = strrchr(shell, '/');
2503 /* If we have no command, execute the shell. In this case, the shell name
2504 to be passed in argv[0] is preceded by '-' to indicate that this is
2508 if(!options.use_login) {
2511 /* Check for mail if we have a tty and it was enabled in server options. */
2512 if (ttyname && options.check_mail) {
2514 struct stat mailstat;
2515 mailbox = getenv("MAIL");
2516 if(mailbox != NULL) {
2517 if(stat(mailbox, &mailstat) != 0 || mailstat.st_size == 0) {
2518 printf("No mail.\n");
2519 } else if(mailstat.st_mtime < mailstat.st_atime) {
2520 printf("You have mail.\n");
2522 printf("You have new mail.\n");
2526 /* Start the shell. Set initial character to '-'. */
2528 strncpy(buf + 1, cp, sizeof(buf) - 1);
2529 buf[sizeof(buf) - 1] = 0;
2530 /* Execute the shell. */
2533 execve(shell, argv, env);
2534 /* Executing the shell failed. */
2539 /* Launch login(1). */
2541 execl(LOGIN_PROGRAM, "login", "-h", get_remote_ipaddr(), "-p", "-f", "--", pw->pw_name, NULL);
2543 /* Login couldn't be executed, die. */
2550 /* Execute the command using the user's shell. This uses the -c option
2551 to execute the command. */
2552 argv[0] = (char *)cp;
2554 argv[2] = (char *)command;
2556 execve(shell, argv, env);