2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * This program is the ssh daemon. It listens for connections from clients,
6 * and performs authentication, executes use commands or shell, and forwards
7 * information to/from the application to the user client over an encrypted
8 * connection. This can also handle forwarding of X11, TCP/IP, and
9 * authentication agent connections.
11 * As far as I am concerned, the code I have written for this software
12 * can be used freely for any purpose. Any derived versions of this
13 * software must be clearly marked as such, and if the derived work is
14 * incompatible with the protocol description in the RFC file, it must be
15 * called by a name other than "ssh" or "Secure Shell".
17 * SSH2 implementation:
19 * Copyright (c) 2000 Markus Friedl. All rights reserved.
21 * Redistribution and use in source and binary forms, with or without
22 * modification, are permitted provided that the following conditions
24 * 1. Redistributions of source code must retain the above copyright
25 * notice, this list of conditions and the following disclaimer.
26 * 2. Redistributions in binary form must reproduce the above copyright
27 * notice, this list of conditions and the following disclaimer in the
28 * documentation and/or other materials provided with the distribution.
30 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43 RCSID("$OpenBSD: sshd.c,v 1.228 2002/02/27 21:23:13 stevesk Exp $");
45 #include <openssl/dh.h>
46 #include <openssl/bn.h>
47 #include <openssl/md5.h>
66 #include "myproposal.h"
68 #include "pathnames.h"
83 int allow_severity = LOG_INFO;
84 int deny_severity = LOG_WARNING;
91 #ifdef HAVE___PROGNAME
92 extern char *__progname;
97 /* Server configuration options. */
98 ServerOptions options;
100 /* Name of the server configuration file. */
101 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
104 * Flag indicating whether IPv4 or IPv6. This can be set on the command line.
105 * Default value is AF_UNSPEC means both IPv4 and IPv6.
108 int IPv4or6 = AF_INET;
110 int IPv4or6 = AF_UNSPEC;
114 * Debug mode flag. This can be set on the command line. If debug
115 * mode is enabled, extra debugging output will be sent to the system
116 * log, the daemon will not go to background, and will exit after processing
117 * the first connection.
121 /* Flag indicating that the daemon should only test the configuration and keys. */
124 /* Flag indicating that the daemon is being started from inetd. */
127 /* Flag indicating that sshd should not detach and become a daemon. */
128 int no_daemon_flag = 0;
130 /* debug goes to stderr unless inetd_flag is set */
133 /* Saved arguments to main(). */
138 * The sockets that the server is listening; this is used in the SIGHUP
141 #define MAX_LISTEN_SOCKS 16
142 int listen_socks[MAX_LISTEN_SOCKS];
143 int num_listen_socks = 0;
146 * the client's version string, passed by sshd2 in compat mode. if != NULL,
147 * sshd will skip the version-number exchange
149 char *client_version_string = NULL;
150 char *server_version_string = NULL;
152 /* for rekeying XXX fixme */
156 * Any really sensitive data in the application is contained in this
157 * structure. The idea is that this structure could be locked into memory so
158 * that the pages do not get written into swap. However, there are some
159 * problems. The private key contains BIGNUMs, and we do not (in principle)
160 * have access to the internals of them, and locking just the structure is
161 * not very useful. Currently, memory locking is not implemented.
164 Key *server_key; /* ephemeral server key */
165 Key *ssh1_host_key; /* ssh1 host key */
166 Key **host_keys; /* all private host keys */
169 u_char ssh1_cookie[SSH_SESSION_KEY_LENGTH];
173 * Flag indicating whether the RSA server key needs to be regenerated.
174 * Is set in the SIGALRM handler and cleared when the key is regenerated.
176 static volatile sig_atomic_t key_do_regen = 0;
178 /* This is set to true when a signal is received. */
179 static volatile sig_atomic_t received_sighup = 0;
180 static volatile sig_atomic_t received_sigterm = 0;
182 /* session identifier, used by RSA-auth */
183 u_char session_id[16];
186 u_char *session_id2 = NULL;
187 int session_id2_len = 0;
189 /* record remote hostname or ip */
190 u_int utmp_len = MAXHOSTNAMELEN;
192 /* options.max_startup sized array of fd ints */
193 int *startup_pipes = NULL;
194 int startup_pipe; /* in child */
196 /* Prototypes for various functions defined later in this file. */
197 void destroy_sensitive_data(void);
199 static void do_ssh1_kex(void);
200 static void do_ssh2_kex(void);
203 * Close all listening sockets
206 close_listen_socks(void)
209 for (i = 0; i < num_listen_socks; i++)
210 close(listen_socks[i]);
211 num_listen_socks = -1;
215 close_startup_pipes(void)
219 for (i = 0; i < options.max_startups; i++)
220 if (startup_pipes[i] != -1)
221 close(startup_pipes[i]);
225 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
226 * the effect is to reread the configuration file (and to regenerate
230 sighup_handler(int sig)
232 int save_errno = errno;
235 signal(SIGHUP, sighup_handler);
240 * Called from the main program after receiving SIGHUP.
241 * Restarts the server.
246 log("Received SIGHUP; restarting.");
247 close_listen_socks();
248 close_startup_pipes();
249 execv(saved_argv[0], saved_argv);
250 log("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0], strerror(errno));
255 * Generic signal handler for terminating signals in the master daemon.
258 sigterm_handler(int sig)
260 received_sigterm = sig;
264 * SIGCHLD handler. This is called whenever a child dies. This will then
265 * reap any zombies left by exited children.
268 main_sigchld_handler(int sig)
270 int save_errno = errno;
273 while (waitpid(-1, &status, WNOHANG) > 0)
276 signal(SIGCHLD, main_sigchld_handler);
281 * Signal handler for the alarm after the login grace period has expired.
284 grace_alarm_handler(int sig)
286 /* XXX no idea how fix this signal handler */
288 /* Close the connection. */
291 /* Log error and exit. */
292 fatal("Timeout before authentication for %s.", get_remote_ipaddr());
296 * Signal handler for the key regeneration alarm. Note that this
297 * alarm only occurs in the daemon waiting for connections, and it does not
298 * do anything with the private key or random state before forking.
299 * Thus there should be no concurrency control/asynchronous execution
303 generate_ephemeral_server_key(void)
308 verbose("Generating %s%d bit RSA key.",
309 sensitive_data.server_key ? "new " : "", options.server_key_bits);
310 if (sensitive_data.server_key != NULL)
311 key_free(sensitive_data.server_key);
312 sensitive_data.server_key = key_generate(KEY_RSA1,
313 options.server_key_bits);
314 verbose("RSA key generation complete.");
316 for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
319 sensitive_data.ssh1_cookie[i] = rand & 0xff;
326 key_regeneration_alarm(int sig)
328 int save_errno = errno;
329 signal(SIGALRM, SIG_DFL);
335 sshd_exchange_identification(int sock_in, int sock_out)
338 int remote_major, remote_minor;
341 char buf[256]; /* Must not be larger than remote_version. */
342 char remote_version[256]; /* Must be at least as big as buf. */
344 if ((options.protocol & SSH_PROTO_1) &&
345 (options.protocol & SSH_PROTO_2)) {
346 major = PROTOCOL_MAJOR_1;
348 } else if (options.protocol & SSH_PROTO_2) {
349 major = PROTOCOL_MAJOR_2;
350 minor = PROTOCOL_MINOR_2;
352 major = PROTOCOL_MAJOR_1;
353 minor = PROTOCOL_MINOR_1;
355 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", major, minor, SSH_VERSION);
356 server_version_string = xstrdup(buf);
358 if (client_version_string == NULL) {
359 /* Send our protocol version identification. */
360 if (atomicio(write, sock_out, server_version_string, strlen(server_version_string))
361 != strlen(server_version_string)) {
362 log("Could not write ident string to %s", get_remote_ipaddr());
366 /* Read other side's version identification. */
367 memset(buf, 0, sizeof(buf));
368 for (i = 0; i < sizeof(buf) - 1; i++) {
369 if (atomicio(read, sock_in, &buf[i], 1) != 1) {
370 log("Did not receive identification string from %s",
371 get_remote_ipaddr());
374 if (buf[i] == '\r') {
376 /* Kludge for F-Secure Macintosh < 1.0.2 */
378 strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
382 if (buf[i] == '\n') {
387 buf[sizeof(buf) - 1] = 0;
388 client_version_string = xstrdup(buf);
392 * Check that the versions match. In future this might accept
393 * several versions and set appropriate flags to handle them.
395 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
396 &remote_major, &remote_minor, remote_version) != 3) {
397 s = "Protocol mismatch.\n";
398 (void) atomicio(write, sock_out, s, strlen(s));
401 log("Bad protocol version identification '%.100s' from %s",
402 client_version_string, get_remote_ipaddr());
405 debug("Client protocol version %d.%d; client software version %.100s",
406 remote_major, remote_minor, remote_version);
408 compat_datafellows(remote_version);
410 if (datafellows & SSH_BUG_SCANNER) {
411 log("scanned from %s with %s. Don't panic.",
412 get_remote_ipaddr(), client_version_string);
417 switch (remote_major) {
419 if (remote_minor == 99) {
420 if (options.protocol & SSH_PROTO_2)
426 if (!(options.protocol & SSH_PROTO_1)) {
430 if (remote_minor < 3) {
431 packet_disconnect("Your ssh version is too old and "
432 "is no longer supported. Please install a newer version.");
433 } else if (remote_minor == 3) {
434 /* note that this disables agent-forwarding */
439 if (options.protocol & SSH_PROTO_2) {
448 chop(server_version_string);
449 debug("Local version string %.200s", server_version_string);
452 s = "Protocol major versions differ.\n";
453 (void) atomicio(write, sock_out, s, strlen(s));
456 log("Protocol major versions differ for %s: %.200s vs. %.200s",
458 server_version_string, client_version_string);
464 /* Destroy the host and server keys. They will no longer be needed. */
466 destroy_sensitive_data(void)
470 if (sensitive_data.server_key) {
471 key_free(sensitive_data.server_key);
472 sensitive_data.server_key = NULL;
474 for (i = 0; i < options.num_host_key_files; i++) {
475 if (sensitive_data.host_keys[i]) {
476 key_free(sensitive_data.host_keys[i]);
477 sensitive_data.host_keys[i] = NULL;
480 sensitive_data.ssh1_host_key = NULL;
481 memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
485 list_hostkey_types(void)
492 for (i = 0; i < options.num_host_key_files; i++) {
493 Key *key = sensitive_data.host_keys[i];
499 if (buffer_len(&b) > 0)
500 buffer_append(&b, ",", 1);
501 p = key_ssh_name(key);
502 buffer_append(&b, p, strlen(p));
506 buffer_append(&b, "\0", 1);
507 p = xstrdup(buffer_ptr(&b));
509 debug("list_hostkey_types: %s", p);
514 get_hostkey_by_type(int type)
517 for (i = 0; i < options.num_host_key_files; i++) {
518 Key *key = sensitive_data.host_keys[i];
519 if (key != NULL && key->type == type)
526 * returns 1 if connection should be dropped, 0 otherwise.
527 * dropping starts at connection #max_startups_begin with a probability
528 * of (max_startups_rate/100). the probability increases linearly until
529 * all connections are dropped for startups > max_startups
532 drop_connection(int startups)
536 if (startups < options.max_startups_begin)
538 if (startups >= options.max_startups)
540 if (options.max_startups_rate == 100)
543 p = 100 - options.max_startups_rate;
544 p *= startups - options.max_startups_begin;
545 p /= (double) (options.max_startups - options.max_startups_begin);
546 p += options.max_startups_rate;
548 r = arc4random() / (double) UINT_MAX;
550 debug("drop_connection: p %g, r %g", p, r);
551 return (r < p) ? 1 : 0;
557 fprintf(stderr, "sshd version %s\n", SSH_VERSION);
558 fprintf(stderr, "Usage: %s [options]\n", __progname);
559 fprintf(stderr, "Options:\n");
560 fprintf(stderr, " -f file Configuration file (default %s)\n", _PATH_SERVER_CONFIG_FILE);
561 fprintf(stderr, " -d Debugging mode (multiple -d means more debugging)\n");
562 fprintf(stderr, " -i Started from inetd\n");
563 fprintf(stderr, " -D Do not fork into daemon mode\n");
564 fprintf(stderr, " -t Only test configuration file and keys\n");
565 fprintf(stderr, " -q Quiet (no logging)\n");
566 fprintf(stderr, " -p port Listen on the specified port (default: 22)\n");
567 fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n");
568 fprintf(stderr, " -g seconds Grace period for authentication (default: 600)\n");
569 fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n");
570 fprintf(stderr, " -h file File from which to read host key (default: %s)\n",
571 _PATH_HOST_KEY_FILE);
572 fprintf(stderr, " -u len Maximum hostname length for utmp recording\n");
573 fprintf(stderr, " -4 Use IPv4 only\n");
574 fprintf(stderr, " -6 Use IPv6 only\n");
575 fprintf(stderr, " -o option Process the option as if it was read from a configuration file.\n");
580 * Main program for the daemon.
583 main(int ac, char **av)
587 int opt, sock_in = 0, sock_out = 0, newsock, j, i, fdsetsz, on = 1;
591 struct sockaddr_storage from;
592 const char *remote_ip;
595 struct linger linger;
597 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
598 int listen_sock, maxfd;
602 int ret, key_used = 0;
604 __progname = get_progname(av[0]);
611 /* Initialize configuration options to their default values. */
612 initialize_server_options(&options);
614 /* Parse command-line arguments. */
615 while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:u:o:dDeiqtQ46")) != -1) {
624 config_file_name = optarg;
627 if (0 == debug_flag) {
629 options.log_level = SYSLOG_LEVEL_DEBUG1;
630 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
633 fprintf(stderr, "Too high debugging level.\n");
650 options.log_level = SYSLOG_LEVEL_QUIET;
653 options.server_key_bits = atoi(optarg);
656 options.ports_from_cmdline = 1;
657 if (options.num_ports >= MAX_PORTS) {
658 fprintf(stderr, "too many ports.\n");
661 options.ports[options.num_ports++] = a2port(optarg);
662 if (options.ports[options.num_ports-1] == 0) {
663 fprintf(stderr, "Bad port number.\n");
668 if ((options.login_grace_time = convtime(optarg)) == -1) {
669 fprintf(stderr, "Invalid login grace time.\n");
674 if ((options.key_regeneration_time = convtime(optarg)) == -1) {
675 fprintf(stderr, "Invalid key regeneration interval.\n");
680 if (options.num_host_key_files >= MAX_HOSTKEYS) {
681 fprintf(stderr, "too many host keys.\n");
684 options.host_key_files[options.num_host_key_files++] = optarg;
687 client_version_string = optarg;
688 /* only makes sense with inetd_flag, i.e. no listen() */
695 utmp_len = atoi(optarg);
698 if (process_server_config_line(&options, optarg,
699 "command-line", 0) != 0)
708 SSLeay_add_all_algorithms();
709 channel_set_af(IPv4or6);
712 * Force logging to stderr until we have loaded the private host
713 * key (unless started from inetd)
716 options.log_level == SYSLOG_LEVEL_NOT_SET ?
717 SYSLOG_LEVEL_INFO : options.log_level,
718 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
719 SYSLOG_FACILITY_AUTH : options.log_facility,
723 /* Cray can define user privs drop all prives now!
724 * Not needed on PRIV_SU systems!
731 /* Read server configuration options from the configuration file. */
732 read_server_config(&options, config_file_name);
734 /* Fill in default values for those options not explicitly set. */
735 fill_default_server_options(&options);
737 /* Check that there are no remaining arguments. */
739 fprintf(stderr, "Extra argument %s.\n", av[optind]);
743 debug("sshd version %.100s", SSH_VERSION);
745 /* load private host keys */
746 sensitive_data.host_keys = xmalloc(options.num_host_key_files*sizeof(Key*));
747 for (i = 0; i < options.num_host_key_files; i++)
748 sensitive_data.host_keys[i] = NULL;
749 sensitive_data.server_key = NULL;
750 sensitive_data.ssh1_host_key = NULL;
751 sensitive_data.have_ssh1_key = 0;
752 sensitive_data.have_ssh2_key = 0;
754 for (i = 0; i < options.num_host_key_files; i++) {
755 key = key_load_private(options.host_key_files[i], "", NULL);
756 sensitive_data.host_keys[i] = key;
758 error("Could not load host key: %s",
759 options.host_key_files[i]);
760 sensitive_data.host_keys[i] = NULL;
765 sensitive_data.ssh1_host_key = key;
766 sensitive_data.have_ssh1_key = 1;
770 sensitive_data.have_ssh2_key = 1;
773 debug("private host key: #%d type %d %s", i, key->type,
776 if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
777 log("Disabling protocol version 1. Could not load host key");
778 options.protocol &= ~SSH_PROTO_1;
781 /* The GSSAPI key exchange can run without a host key */
782 if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
783 log("Disabling protocol version 2. Could not load host key");
784 options.protocol &= ~SSH_PROTO_2;
787 if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
788 log("sshd: no hostkeys available -- exiting.");
792 /* Check certain values for sanity. */
793 if (options.protocol & SSH_PROTO_1) {
794 if (options.server_key_bits < 512 ||
795 options.server_key_bits > 32768) {
796 fprintf(stderr, "Bad server key size.\n");
800 * Check that server and host key lengths differ sufficiently. This
801 * is necessary to make double encryption work with rsaref. Oh, I
802 * hate software patents. I dont know if this can go? Niels
804 if (options.server_key_bits >
805 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) - SSH_KEY_BITS_RESERVED &&
806 options.server_key_bits <
807 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
808 options.server_key_bits =
809 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED;
810 debug("Forcing server key to %d bits to make it differ from host key.",
811 options.server_key_bits);
815 /* Configuration looks good, so exit if in test mode. */
819 #ifdef HAVE_SCO_PROTECTED_PW
820 (void) set_auth_parameters(ac, av);
823 /* Initialize the log (it is reinitialized below in case we forked). */
824 if (debug_flag && !inetd_flag)
826 log_init(__progname, options.log_level, options.log_facility, log_stderr);
829 * If not in debugging mode, and not started from inetd, disconnect
830 * from the controlling terminal, and fork. The original process
833 if (!(debug_flag || inetd_flag || no_daemon_flag)) {
836 #endif /* TIOCNOTTY */
837 if (daemon(0, 0) < 0)
838 fatal("daemon() failed: %.200s", strerror(errno));
840 /* Disconnect from the controlling tty. */
842 fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
844 (void) ioctl(fd, TIOCNOTTY, NULL);
847 #endif /* TIOCNOTTY */
849 /* Reinitialize the log (because of the fork above). */
850 log_init(__progname, options.log_level, options.log_facility, log_stderr);
852 /* Initialize the random number generator. */
855 /* Chdir to the root directory so that the current disk can be
856 unmounted if desired. */
860 signal(SIGPIPE, SIG_IGN);
862 /* Start listening for a socket, unless started from inetd. */
865 s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */
871 * We intentionally do not close the descriptors 0, 1, and 2
872 * as our code for setting the descriptors won\'t work if
873 * ttyfd happens to be one of those.
875 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
876 if (options.protocol & SSH_PROTO_1)
877 generate_ephemeral_server_key();
879 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
880 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
882 if (num_listen_socks >= MAX_LISTEN_SOCKS)
883 fatal("Too many listen sockets. "
884 "Enlarge MAX_LISTEN_SOCKS");
885 if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
886 ntop, sizeof(ntop), strport, sizeof(strport),
887 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
888 error("getnameinfo failed");
891 /* Create socket for listening. */
892 listen_sock = socket(ai->ai_family, SOCK_STREAM, 0);
893 if (listen_sock < 0) {
894 /* kernel may not support ipv6 */
895 verbose("socket: %.100s", strerror(errno));
898 if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) {
899 error("listen_sock O_NONBLOCK: %s", strerror(errno));
904 * Set socket options. We try to make the port
905 * reusable and have it close as fast as possible
906 * without waiting in unnecessary wait states on
909 setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
913 setsockopt(listen_sock, SOL_SOCKET, SO_LINGER,
914 &linger, sizeof(linger));
916 debug("Bind to port %s on %s.", strport, ntop);
918 /* Bind the socket to the desired port. */
919 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
921 error("Bind to port %s on %s failed: %.200s.",
922 strport, ntop, strerror(errno));
926 listen_socks[num_listen_socks] = listen_sock;
929 /* Start listening on the port. */
930 log("Server listening on %s port %s.", ntop, strport);
931 if (listen(listen_sock, 5) < 0)
932 fatal("listen: %.100s", strerror(errno));
935 freeaddrinfo(options.listen_addrs);
937 if (!num_listen_socks)
938 fatal("Cannot bind any address.");
940 if (options.protocol & SSH_PROTO_1)
941 generate_ephemeral_server_key();
944 * Arrange to restart on SIGHUP. The handler needs
947 signal(SIGHUP, sighup_handler);
949 signal(SIGTERM, sigterm_handler);
950 signal(SIGQUIT, sigterm_handler);
952 /* Arrange SIGCHLD to be caught. */
953 signal(SIGCHLD, main_sigchld_handler);
955 /* Write out the pid file after the sigterm handler is setup */
958 * Record our pid in /var/run/sshd.pid to make it
959 * easier to kill the correct sshd. We don't want to
960 * do this before the bind above because the bind will
961 * fail if there already is a daemon, and this will
962 * overwrite any old pid in the file.
964 f = fopen(options.pid_file, "wb");
966 fprintf(f, "%u\n", (u_int) getpid());
971 /* setup fd set for listen */
974 for (i = 0; i < num_listen_socks; i++)
975 if (listen_socks[i] > maxfd)
976 maxfd = listen_socks[i];
977 /* pipes connected to unauthenticated childs */
978 startup_pipes = xmalloc(options.max_startups * sizeof(int));
979 for (i = 0; i < options.max_startups; i++)
980 startup_pipes[i] = -1;
983 * Stay listening for connections until the system crashes or
984 * the daemon is killed with a signal.
991 fdsetsz = howmany(maxfd+1, NFDBITS) * sizeof(fd_mask);
992 fdset = (fd_set *)xmalloc(fdsetsz);
993 memset(fdset, 0, fdsetsz);
995 for (i = 0; i < num_listen_socks; i++)
996 FD_SET(listen_socks[i], fdset);
997 for (i = 0; i < options.max_startups; i++)
998 if (startup_pipes[i] != -1)
999 FD_SET(startup_pipes[i], fdset);
1001 /* Wait in select until there is a connection. */
1002 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1003 if (ret < 0 && errno != EINTR)
1004 error("select: %.100s", strerror(errno));
1005 if (received_sigterm) {
1006 log("Received signal %d; terminating.",
1007 (int) received_sigterm);
1008 close_listen_socks();
1009 unlink(options.pid_file);
1012 if (key_used && key_do_regen) {
1013 generate_ephemeral_server_key();
1020 for (i = 0; i < options.max_startups; i++)
1021 if (startup_pipes[i] != -1 &&
1022 FD_ISSET(startup_pipes[i], fdset)) {
1024 * the read end of the pipe is ready
1025 * if the child has closed the pipe
1026 * after successful authentication
1027 * or if the child has died
1029 close(startup_pipes[i]);
1030 startup_pipes[i] = -1;
1033 for (i = 0; i < num_listen_socks; i++) {
1034 if (!FD_ISSET(listen_socks[i], fdset))
1036 fromlen = sizeof(from);
1037 newsock = accept(listen_socks[i], (struct sockaddr *)&from,
1040 if (errno != EINTR && errno != EWOULDBLOCK)
1041 error("accept: %.100s", strerror(errno));
1044 if (fcntl(newsock, F_SETFL, 0) < 0) {
1045 error("newsock del O_NONBLOCK: %s", strerror(errno));
1049 if (drop_connection(startups) == 1) {
1050 debug("drop connection #%d", startups);
1054 if (pipe(startup_p) == -1) {
1059 for (j = 0; j < options.max_startups; j++)
1060 if (startup_pipes[j] == -1) {
1061 startup_pipes[j] = startup_p[0];
1062 if (maxfd < startup_p[0])
1063 maxfd = startup_p[0];
1069 * Got connection. Fork a child to handle it, unless
1070 * we are in debugging mode.
1074 * In debugging mode. Close the listening
1075 * socket, and start processing the
1076 * connection without forking.
1078 debug("Server will not fork when running in debugging mode.");
1079 close_listen_socks();
1087 * Normal production daemon. Fork, and have
1088 * the child process the connection. The
1089 * parent continues listening.
1091 if ((pid = fork()) == 0) {
1093 * Child. Close the listening and max_startup
1094 * sockets. Start using the accepted socket.
1095 * Reinitialize logging (since our pid has
1096 * changed). We break out of the loop to handle
1099 startup_pipe = startup_p[1];
1100 close_startup_pipes();
1101 close_listen_socks();
1104 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1109 /* Parent. Stay in the loop. */
1111 error("fork: %.100s", strerror(errno));
1113 debug("Forked child %d.", pid);
1115 close(startup_p[1]);
1117 /* Mark that the key has been used (it was "given" to the child). */
1118 if ((options.protocol & SSH_PROTO_1) &&
1120 /* Schedule server key regeneration alarm. */
1121 signal(SIGALRM, key_regeneration_alarm);
1122 alarm(options.key_regeneration_time);
1128 /* Close the new socket (the child is now taking care of it). */
1131 /* child process check (or debug mode) */
1132 if (num_listen_socks < 0)
1137 /* This is the child processing a new connection. */
1140 * Disable the key regeneration alarm. We will not regenerate the
1141 * key since we are no longer in a position to give it to anyone. We
1142 * will not restart on SIGHUP since it no longer makes sense.
1145 signal(SIGALRM, SIG_DFL);
1146 signal(SIGHUP, SIG_DFL);
1147 signal(SIGTERM, SIG_DFL);
1148 signal(SIGQUIT, SIG_DFL);
1149 signal(SIGCHLD, SIG_DFL);
1150 signal(SIGINT, SIG_DFL);
1153 * Set socket options for the connection. We want the socket to
1154 * close as fast as possible without waiting for anything. If the
1155 * connection is not a socket, these will do nothing.
1157 /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
1159 linger.l_linger = 5;
1160 setsockopt(sock_in, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger));
1162 /* Set keepalives if requested. */
1163 if (options.keepalives &&
1164 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on,
1166 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1169 * Register our connection. This turns encryption off because we do
1172 packet_set_connection(sock_in, sock_out);
1174 remote_port = get_remote_port();
1175 remote_ip = get_remote_ipaddr();
1178 /* Check whether logins are denied from this host. */
1180 struct request_info req;
1182 request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1185 if (!hosts_access(&req)) {
1186 debug("Connection refused by tcp wrapper");
1189 fatal("libwrap refuse returns");
1192 #endif /* LIBWRAP */
1194 /* Log the connection. */
1195 verbose("Connection from %.500s port %d", remote_ip, remote_port);
1198 * We don\'t want to listen forever unless the other side
1199 * successfully authenticates itself. So we set up an alarm which is
1200 * cleared after successful authentication. A limit of zero
1201 * indicates no limit. Note that we don\'t set the alarm in debugging
1202 * mode; it is just annoying to have the server exit just when you
1203 * are about to discover the bug.
1205 signal(SIGALRM, grace_alarm_handler);
1207 alarm(options.login_grace_time);
1209 sshd_exchange_identification(sock_in, sock_out);
1211 * Check that the connection comes from a privileged port.
1212 * Rhosts-Authentication only makes sense from priviledged
1213 * programs. Of course, if the intruder has root access on his local
1214 * machine, he can connect from any port. So do not use these
1215 * authentication methods from machines that you do not trust.
1217 if (options.rhosts_authentication &&
1218 (remote_port >= IPPORT_RESERVED ||
1219 remote_port < IPPORT_RESERVED / 2)) {
1220 debug("Rhosts Authentication disabled, "
1221 "originating port %d not trusted.", remote_port);
1222 options.rhosts_authentication = 0;
1224 #if defined(KRB4) && !defined(KRB5)
1225 if (!packet_connection_is_ipv4() &&
1226 options.kerberos_authentication) {
1227 debug("Kerberos Authentication disabled, only available for IPv4.");
1228 options.kerberos_authentication = 0;
1230 #endif /* KRB4 && !KRB5 */
1232 /* If machine has AFS, set process authentication group. */
1239 packet_set_nonblocking();
1241 /* perform the key exchange */
1242 /* authenticate user and start session */
1245 do_authentication2();
1248 do_authentication();
1250 /* The connection has been terminated. */
1251 verbose("Closing connection to %.100s", remote_ip);
1255 #endif /* USE_PAM */
1269 BIGNUM *session_key_int;
1270 u_char session_key[SSH_SESSION_KEY_LENGTH];
1272 u_int cipher_type, auth_mask, protocol_flags;
1276 * Generate check bytes that the client must send back in the user
1277 * packet in order for it to be accepted; this is used to defy ip
1278 * spoofing attacks. Note that this only works against somebody
1279 * doing IP spoofing from a remote machine; any machine on the local
1280 * network can still see outgoing packets and catch the random
1281 * cookie. This only affects rhosts authentication, and this is one
1282 * of the reasons why it is inherently insecure.
1284 for (i = 0; i < 8; i++) {
1286 rand = arc4random();
1287 cookie[i] = rand & 0xff;
1292 * Send our public key. We include in the packet 64 bits of random
1293 * data that must be matched in the reply in order to prevent IP
1296 packet_start(SSH_SMSG_PUBLIC_KEY);
1297 for (i = 0; i < 8; i++)
1298 packet_put_char(cookie[i]);
1300 /* Store our public server RSA key. */
1301 packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
1302 packet_put_bignum(sensitive_data.server_key->rsa->e);
1303 packet_put_bignum(sensitive_data.server_key->rsa->n);
1305 /* Store our public host RSA key. */
1306 packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1307 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
1308 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
1310 /* Put protocol flags. */
1311 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
1313 /* Declare which ciphers we support. */
1314 packet_put_int(cipher_mask_ssh1(0));
1316 /* Declare supported authentication types. */
1318 if (options.rhosts_authentication)
1319 auth_mask |= 1 << SSH_AUTH_RHOSTS;
1320 if (options.rhosts_rsa_authentication)
1321 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
1322 if (options.rsa_authentication)
1323 auth_mask |= 1 << SSH_AUTH_RSA;
1324 #if defined(KRB4) || defined(KRB5)
1325 if (options.kerberos_authentication)
1326 auth_mask |= 1 << SSH_AUTH_KERBEROS;
1328 #if defined(AFS) || defined(KRB5)
1329 if (options.kerberos_tgt_passing)
1330 auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
1333 if (options.afs_token_passing)
1334 auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
1336 if (options.challenge_response_authentication == 1)
1337 auth_mask |= 1 << SSH_AUTH_TIS;
1338 if (options.password_authentication)
1339 auth_mask |= 1 << SSH_AUTH_PASSWORD;
1340 packet_put_int(auth_mask);
1342 /* Send the packet and wait for it to be sent. */
1344 packet_write_wait();
1346 debug("Sent %d bit server key and %d bit host key.",
1347 BN_num_bits(sensitive_data.server_key->rsa->n),
1348 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1350 /* Read clients reply (cipher type and session key). */
1351 packet_read_expect(SSH_CMSG_SESSION_KEY);
1353 /* Get cipher type and check whether we accept this. */
1354 cipher_type = packet_get_char();
1356 if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
1357 packet_disconnect("Warning: client selects unsupported cipher.");
1359 /* Get check bytes from the packet. These must match those we
1360 sent earlier with the public key packet. */
1361 for (i = 0; i < 8; i++)
1362 if (cookie[i] != packet_get_char())
1363 packet_disconnect("IP Spoofing check bytes do not match.");
1365 debug("Encryption type: %.200s", cipher_name(cipher_type));
1367 /* Get the encrypted integer. */
1368 if ((session_key_int = BN_new()) == NULL)
1369 fatal("do_ssh1_kex: BN_new failed");
1370 packet_get_bignum(session_key_int);
1372 protocol_flags = packet_get_int();
1373 packet_set_protocol_flags(protocol_flags);
1376 packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY);
1379 * Decrypt it using our private server key and private host key (key
1380 * with larger modulus first).
1382 if (BN_cmp(sensitive_data.server_key->rsa->n, sensitive_data.ssh1_host_key->rsa->n) > 0) {
1383 /* Server key has bigger modulus. */
1384 if (BN_num_bits(sensitive_data.server_key->rsa->n) <
1385 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1386 fatal("do_connection: %s: server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1387 get_remote_ipaddr(),
1388 BN_num_bits(sensitive_data.server_key->rsa->n),
1389 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1390 SSH_KEY_BITS_RESERVED);
1392 if (rsa_private_decrypt(session_key_int, session_key_int,
1393 sensitive_data.server_key->rsa) <= 0)
1395 if (rsa_private_decrypt(session_key_int, session_key_int,
1396 sensitive_data.ssh1_host_key->rsa) <= 0)
1399 /* Host key has bigger modulus (or they are equal). */
1400 if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
1401 BN_num_bits(sensitive_data.server_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1402 fatal("do_connection: %s: host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
1403 get_remote_ipaddr(),
1404 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1405 BN_num_bits(sensitive_data.server_key->rsa->n),
1406 SSH_KEY_BITS_RESERVED);
1408 if (rsa_private_decrypt(session_key_int, session_key_int,
1409 sensitive_data.ssh1_host_key->rsa) < 0)
1411 if (rsa_private_decrypt(session_key_int, session_key_int,
1412 sensitive_data.server_key->rsa) < 0)
1416 * Extract session key from the decrypted integer. The key is in the
1417 * least significant 256 bits of the integer; the first byte of the
1418 * key is in the highest bits.
1421 BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1422 len = BN_num_bytes(session_key_int);
1423 if (len < 0 || len > sizeof(session_key)) {
1424 error("do_connection: bad session key len from %s: "
1425 "session_key_int %d > sizeof(session_key) %lu",
1426 get_remote_ipaddr(), len, (u_long)sizeof(session_key));
1429 memset(session_key, 0, sizeof(session_key));
1430 BN_bn2bin(session_key_int,
1431 session_key + sizeof(session_key) - len);
1433 compute_session_id(session_id, cookie,
1434 sensitive_data.ssh1_host_key->rsa->n,
1435 sensitive_data.server_key->rsa->n);
1437 * Xor the first 16 bytes of the session key with the
1440 for (i = 0; i < 16; i++)
1441 session_key[i] ^= session_id[i];
1445 int bytes = BN_num_bytes(session_key_int);
1446 u_char *buf = xmalloc(bytes);
1449 log("do_connection: generating a fake encryption key");
1450 BN_bn2bin(session_key_int, buf);
1452 MD5_Update(&md, buf, bytes);
1453 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1454 MD5_Final(session_key, &md);
1456 MD5_Update(&md, session_key, 16);
1457 MD5_Update(&md, buf, bytes);
1458 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1459 MD5_Final(session_key + 16, &md);
1460 memset(buf, 0, bytes);
1462 for (i = 0; i < 16; i++)
1463 session_id[i] = session_key[i] ^ session_key[i + 16];
1465 /* Destroy the private and public keys. They will no longer be needed. */
1466 destroy_sensitive_data();
1468 /* Destroy the decrypted integer. It is no longer needed. */
1469 BN_clear_free(session_key_int);
1471 /* Set the session key. From this on all communications will be encrypted. */
1472 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
1474 /* Destroy our copy of the session key. It is no longer needed. */
1475 memset(session_key, 0, sizeof(session_key));
1477 debug("Received session key; encryption turned on.");
1479 /* Send an acknowledgement packet. Note that this packet is sent encrypted. */
1480 packet_start(SSH_SMSG_SUCCESS);
1482 packet_write_wait();
1486 * SSH2 key exchange: diffie-hellman-group1-sha1
1493 if (options.ciphers != NULL) {
1494 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1495 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
1497 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1498 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
1499 myproposal[PROPOSAL_ENC_ALGS_STOC] =
1500 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
1502 if (options.macs != NULL) {
1503 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
1504 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
1506 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
1512 char *newstr = NULL;
1513 orig = myproposal[PROPOSAL_KEX_ALGS];
1515 /* If we don't have a host key, then all of the algorithms
1516 * currently in myproposal are useless */
1517 if (strlen(myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS])==0)
1520 if (options.gss_keyex)
1521 gss = ssh_gssapi_mechanisms(1,NULL);
1526 int len = strlen(orig) + strlen(gss) +2;
1527 newstr=xmalloc(len);
1528 snprintf(newstr,len,"%s,%s",gss,orig);
1534 /* If we've got GSSAPI mechanisms, then we've also got the 'null'
1535 host key algorithm, but we're not allowed to advertise it, unless
1536 its the only host key algorithm we're supporting */
1537 if (gss && (strlen(myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS])) == 0) {
1538 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS]="null";
1541 myproposal[PROPOSAL_KEX_ALGS]=newstr;
1543 fatal("No supported key exchange algorithms");
1547 /* start key exchange */
1548 kex = kex_setup(myproposal);
1550 kex->client_version_string=client_version_string;
1551 kex->server_version_string=server_version_string;
1552 kex->load_host_key=&get_hostkey_by_type;
1556 dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
1558 session_id2 = kex->session_id;
1559 session_id2_len = kex->session_id_len;
1562 /* send 1st encrypted/maced/compressed message */
1563 packet_start(SSH2_MSG_IGNORE);
1564 packet_put_cstring("markus");
1566 packet_write_wait();