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.230 2002/03/18 01:12:14 provos Exp $");
45 #include <openssl/dh.h>
46 #include <openssl/bn.h>
47 #include <openssl/md5.h>
66 #include "myproposal.h"
68 #include "pathnames.h"
80 int allow_severity = LOG_INFO;
81 int deny_severity = LOG_WARNING;
88 #ifdef HAVE___PROGNAME
89 extern char *__progname;
94 /* Server configuration options. */
95 ServerOptions options;
97 /* Name of the server configuration file. */
98 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
101 * Flag indicating whether IPv4 or IPv6. This can be set on the command line.
102 * Default value is AF_UNSPEC means both IPv4 and IPv6.
105 int IPv4or6 = AF_INET;
107 int IPv4or6 = AF_UNSPEC;
111 * Debug mode flag. This can be set on the command line. If debug
112 * mode is enabled, extra debugging output will be sent to the system
113 * log, the daemon will not go to background, and will exit after processing
114 * the first connection.
118 /* Flag indicating that the daemon should only test the configuration and keys. */
121 /* Flag indicating that the daemon is being started from inetd. */
124 /* Flag indicating that sshd should not detach and become a daemon. */
125 int no_daemon_flag = 0;
127 /* debug goes to stderr unless inetd_flag is set */
130 /* Saved arguments to main(). */
135 * The sockets that the server is listening; this is used in the SIGHUP
138 #define MAX_LISTEN_SOCKS 16
139 int listen_socks[MAX_LISTEN_SOCKS];
140 int num_listen_socks = 0;
143 * the client's version string, passed by sshd2 in compat mode. if != NULL,
144 * sshd will skip the version-number exchange
146 char *client_version_string = NULL;
147 char *server_version_string = NULL;
149 /* for rekeying XXX fixme */
153 * Any really sensitive data in the application is contained in this
154 * structure. The idea is that this structure could be locked into memory so
155 * that the pages do not get written into swap. However, there are some
156 * problems. The private key contains BIGNUMs, and we do not (in principle)
157 * have access to the internals of them, and locking just the structure is
158 * not very useful. Currently, memory locking is not implemented.
161 Key *server_key; /* ephemeral server key */
162 Key *ssh1_host_key; /* ssh1 host key */
163 Key **host_keys; /* all private host keys */
166 u_char ssh1_cookie[SSH_SESSION_KEY_LENGTH];
170 * Flag indicating whether the RSA server key needs to be regenerated.
171 * Is set in the SIGALRM handler and cleared when the key is regenerated.
173 static volatile sig_atomic_t key_do_regen = 0;
175 /* This is set to true when a signal is received. */
176 static volatile sig_atomic_t received_sighup = 0;
177 static volatile sig_atomic_t received_sigterm = 0;
179 /* session identifier, used by RSA-auth */
180 u_char session_id[16];
183 u_char *session_id2 = NULL;
184 int session_id2_len = 0;
186 /* record remote hostname or ip */
187 u_int utmp_len = MAXHOSTNAMELEN;
189 /* options.max_startup sized array of fd ints */
190 int *startup_pipes = NULL;
191 int startup_pipe; /* in child */
193 /* Prototypes for various functions defined later in this file. */
194 void destroy_sensitive_data(void);
196 static void do_ssh1_kex(void);
197 static void do_ssh2_kex(void);
200 * Close all listening sockets
203 close_listen_socks(void)
206 for (i = 0; i < num_listen_socks; i++)
207 close(listen_socks[i]);
208 num_listen_socks = -1;
212 close_startup_pipes(void)
216 for (i = 0; i < options.max_startups; i++)
217 if (startup_pipes[i] != -1)
218 close(startup_pipes[i]);
222 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
223 * the effect is to reread the configuration file (and to regenerate
227 sighup_handler(int sig)
229 int save_errno = errno;
232 signal(SIGHUP, sighup_handler);
237 * Called from the main program after receiving SIGHUP.
238 * Restarts the server.
243 log("Received SIGHUP; restarting.");
244 close_listen_socks();
245 close_startup_pipes();
246 execv(saved_argv[0], saved_argv);
247 log("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0], strerror(errno));
252 * Generic signal handler for terminating signals in the master daemon.
255 sigterm_handler(int sig)
257 received_sigterm = sig;
261 * SIGCHLD handler. This is called whenever a child dies. This will then
262 * reap any zombies left by exited children.
265 main_sigchld_handler(int sig)
267 int save_errno = errno;
270 while (waitpid(-1, &status, WNOHANG) > 0)
273 signal(SIGCHLD, main_sigchld_handler);
278 * Signal handler for the alarm after the login grace period has expired.
281 grace_alarm_handler(int sig)
283 /* XXX no idea how fix this signal handler */
285 /* Close the connection. */
288 /* Log error and exit. */
289 fatal("Timeout before authentication for %s.", get_remote_ipaddr());
293 * Signal handler for the key regeneration alarm. Note that this
294 * alarm only occurs in the daemon waiting for connections, and it does not
295 * do anything with the private key or random state before forking.
296 * Thus there should be no concurrency control/asynchronous execution
300 generate_ephemeral_server_key(void)
305 verbose("Generating %s%d bit RSA key.",
306 sensitive_data.server_key ? "new " : "", options.server_key_bits);
307 if (sensitive_data.server_key != NULL)
308 key_free(sensitive_data.server_key);
309 sensitive_data.server_key = key_generate(KEY_RSA1,
310 options.server_key_bits);
311 verbose("RSA key generation complete.");
313 for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
316 sensitive_data.ssh1_cookie[i] = rand & 0xff;
323 key_regeneration_alarm(int sig)
325 int save_errno = errno;
326 signal(SIGALRM, SIG_DFL);
332 sshd_exchange_identification(int sock_in, int sock_out)
335 int remote_major, remote_minor;
338 char buf[256]; /* Must not be larger than remote_version. */
339 char remote_version[256]; /* Must be at least as big as buf. */
341 if ((options.protocol & SSH_PROTO_1) &&
342 (options.protocol & SSH_PROTO_2)) {
343 major = PROTOCOL_MAJOR_1;
345 } else if (options.protocol & SSH_PROTO_2) {
346 major = PROTOCOL_MAJOR_2;
347 minor = PROTOCOL_MINOR_2;
349 major = PROTOCOL_MAJOR_1;
350 minor = PROTOCOL_MINOR_1;
352 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", major, minor, SSH_VERSION);
353 server_version_string = xstrdup(buf);
355 if (client_version_string == NULL) {
356 /* Send our protocol version identification. */
357 if (atomicio(write, sock_out, server_version_string, strlen(server_version_string))
358 != strlen(server_version_string)) {
359 log("Could not write ident string to %s", get_remote_ipaddr());
363 /* Read other side's version identification. */
364 memset(buf, 0, sizeof(buf));
365 for (i = 0; i < sizeof(buf) - 1; i++) {
366 if (atomicio(read, sock_in, &buf[i], 1) != 1) {
367 log("Did not receive identification string from %s",
368 get_remote_ipaddr());
371 if (buf[i] == '\r') {
373 /* Kludge for F-Secure Macintosh < 1.0.2 */
375 strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
379 if (buf[i] == '\n') {
384 buf[sizeof(buf) - 1] = 0;
385 client_version_string = xstrdup(buf);
389 * Check that the versions match. In future this might accept
390 * several versions and set appropriate flags to handle them.
392 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
393 &remote_major, &remote_minor, remote_version) != 3) {
394 s = "Protocol mismatch.\n";
395 (void) atomicio(write, sock_out, s, strlen(s));
398 log("Bad protocol version identification '%.100s' from %s",
399 client_version_string, get_remote_ipaddr());
402 debug("Client protocol version %d.%d; client software version %.100s",
403 remote_major, remote_minor, remote_version);
405 compat_datafellows(remote_version);
407 if (datafellows & SSH_BUG_SCANNER) {
408 log("scanned from %s with %s. Don't panic.",
409 get_remote_ipaddr(), client_version_string);
414 switch (remote_major) {
416 if (remote_minor == 99) {
417 if (options.protocol & SSH_PROTO_2)
423 if (!(options.protocol & SSH_PROTO_1)) {
427 if (remote_minor < 3) {
428 packet_disconnect("Your ssh version is too old and "
429 "is no longer supported. Please install a newer version.");
430 } else if (remote_minor == 3) {
431 /* note that this disables agent-forwarding */
436 if (options.protocol & SSH_PROTO_2) {
445 chop(server_version_string);
446 debug("Local version string %.200s", server_version_string);
449 s = "Protocol major versions differ.\n";
450 (void) atomicio(write, sock_out, s, strlen(s));
453 log("Protocol major versions differ for %s: %.200s vs. %.200s",
455 server_version_string, client_version_string);
461 /* Destroy the host and server keys. They will no longer be needed. */
463 destroy_sensitive_data(void)
467 if (sensitive_data.server_key) {
468 key_free(sensitive_data.server_key);
469 sensitive_data.server_key = NULL;
471 for (i = 0; i < options.num_host_key_files; i++) {
472 if (sensitive_data.host_keys[i]) {
473 key_free(sensitive_data.host_keys[i]);
474 sensitive_data.host_keys[i] = NULL;
477 sensitive_data.ssh1_host_key = NULL;
478 memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
482 list_hostkey_types(void)
489 for (i = 0; i < options.num_host_key_files; i++) {
490 Key *key = sensitive_data.host_keys[i];
496 if (buffer_len(&b) > 0)
497 buffer_append(&b, ",", 1);
498 p = key_ssh_name(key);
499 buffer_append(&b, p, strlen(p));
503 buffer_append(&b, "\0", 1);
504 p = xstrdup(buffer_ptr(&b));
506 debug("list_hostkey_types: %s", p);
511 get_hostkey_by_type(int type)
514 for (i = 0; i < options.num_host_key_files; i++) {
515 Key *key = sensitive_data.host_keys[i];
516 if (key != NULL && key->type == type)
523 * returns 1 if connection should be dropped, 0 otherwise.
524 * dropping starts at connection #max_startups_begin with a probability
525 * of (max_startups_rate/100). the probability increases linearly until
526 * all connections are dropped for startups > max_startups
529 drop_connection(int startups)
533 if (startups < options.max_startups_begin)
535 if (startups >= options.max_startups)
537 if (options.max_startups_rate == 100)
540 p = 100 - options.max_startups_rate;
541 p *= startups - options.max_startups_begin;
542 p /= (double) (options.max_startups - options.max_startups_begin);
543 p += options.max_startups_rate;
545 r = arc4random() / (double) UINT_MAX;
547 debug("drop_connection: p %g, r %g", p, r);
548 return (r < p) ? 1 : 0;
554 fprintf(stderr, "sshd version %s\n", SSH_VERSION);
555 fprintf(stderr, "Usage: %s [options]\n", __progname);
556 fprintf(stderr, "Options:\n");
557 fprintf(stderr, " -f file Configuration file (default %s)\n", _PATH_SERVER_CONFIG_FILE);
558 fprintf(stderr, " -d Debugging mode (multiple -d means more debugging)\n");
559 fprintf(stderr, " -i Started from inetd\n");
560 fprintf(stderr, " -D Do not fork into daemon mode\n");
561 fprintf(stderr, " -t Only test configuration file and keys\n");
562 fprintf(stderr, " -q Quiet (no logging)\n");
563 fprintf(stderr, " -p port Listen on the specified port (default: 22)\n");
564 fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n");
565 fprintf(stderr, " -g seconds Grace period for authentication (default: 600)\n");
566 fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n");
567 fprintf(stderr, " -h file File from which to read host key (default: %s)\n",
568 _PATH_HOST_KEY_FILE);
569 fprintf(stderr, " -u len Maximum hostname length for utmp recording\n");
570 fprintf(stderr, " -4 Use IPv4 only\n");
571 fprintf(stderr, " -6 Use IPv6 only\n");
572 fprintf(stderr, " -o option Process the option as if it was read from a configuration file.\n");
577 * Main program for the daemon.
580 main(int ac, char **av)
584 int opt, sock_in = 0, sock_out = 0, newsock, j, i, fdsetsz, on = 1;
588 struct sockaddr_storage from;
589 const char *remote_ip;
592 struct linger linger;
594 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
595 int listen_sock, maxfd;
600 int ret, key_used = 0;
602 __progname = get_progname(av[0]);
609 /* Initialize configuration options to their default values. */
610 initialize_server_options(&options);
612 /* Parse command-line arguments. */
613 while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:u:o:dDeiqtQ46")) != -1) {
622 config_file_name = optarg;
625 if (0 == debug_flag) {
627 options.log_level = SYSLOG_LEVEL_DEBUG1;
628 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
631 fprintf(stderr, "Too high debugging level.\n");
648 options.log_level = SYSLOG_LEVEL_QUIET;
651 options.server_key_bits = atoi(optarg);
654 options.ports_from_cmdline = 1;
655 if (options.num_ports >= MAX_PORTS) {
656 fprintf(stderr, "too many ports.\n");
659 options.ports[options.num_ports++] = a2port(optarg);
660 if (options.ports[options.num_ports-1] == 0) {
661 fprintf(stderr, "Bad port number.\n");
666 if ((options.login_grace_time = convtime(optarg)) == -1) {
667 fprintf(stderr, "Invalid login grace time.\n");
672 if ((options.key_regeneration_time = convtime(optarg)) == -1) {
673 fprintf(stderr, "Invalid key regeneration interval.\n");
678 if (options.num_host_key_files >= MAX_HOSTKEYS) {
679 fprintf(stderr, "too many host keys.\n");
682 options.host_key_files[options.num_host_key_files++] = optarg;
685 client_version_string = optarg;
686 /* only makes sense with inetd_flag, i.e. no listen() */
693 utmp_len = atoi(optarg);
696 if (process_server_config_line(&options, optarg,
697 "command-line", 0) != 0)
706 SSLeay_add_all_algorithms();
707 channel_set_af(IPv4or6);
710 * Force logging to stderr until we have loaded the private host
711 * key (unless started from inetd)
714 options.log_level == SYSLOG_LEVEL_NOT_SET ?
715 SYSLOG_LEVEL_INFO : options.log_level,
716 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
717 SYSLOG_FACILITY_AUTH : options.log_facility,
721 /* Cray can define user privs drop all prives now!
722 * Not needed on PRIV_SU systems!
729 /* Read server configuration options from the configuration file. */
730 read_server_config(&options, config_file_name);
732 /* Fill in default values for those options not explicitly set. */
733 fill_default_server_options(&options);
735 /* Check that there are no remaining arguments. */
737 fprintf(stderr, "Extra argument %s.\n", av[optind]);
741 debug("sshd version %.100s", SSH_VERSION);
743 /* load private host keys */
744 sensitive_data.host_keys = xmalloc(options.num_host_key_files*sizeof(Key*));
745 for (i = 0; i < options.num_host_key_files; i++)
746 sensitive_data.host_keys[i] = NULL;
747 sensitive_data.server_key = NULL;
748 sensitive_data.ssh1_host_key = NULL;
749 sensitive_data.have_ssh1_key = 0;
750 sensitive_data.have_ssh2_key = 0;
752 for (i = 0; i < options.num_host_key_files; i++) {
753 key = key_load_private(options.host_key_files[i], "", NULL);
754 sensitive_data.host_keys[i] = key;
756 error("Could not load host key: %s",
757 options.host_key_files[i]);
758 sensitive_data.host_keys[i] = NULL;
763 sensitive_data.ssh1_host_key = key;
764 sensitive_data.have_ssh1_key = 1;
768 sensitive_data.have_ssh2_key = 1;
771 debug("private host key: #%d type %d %s", i, key->type,
774 if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
775 log("Disabling protocol version 1. Could not load host key");
776 options.protocol &= ~SSH_PROTO_1;
778 if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
779 log("Disabling protocol version 2. Could not load host key");
780 options.protocol &= ~SSH_PROTO_2;
782 if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
783 log("sshd: no hostkeys available -- exiting.");
787 /* Check certain values for sanity. */
788 if (options.protocol & SSH_PROTO_1) {
789 if (options.server_key_bits < 512 ||
790 options.server_key_bits > 32768) {
791 fprintf(stderr, "Bad server key size.\n");
795 * Check that server and host key lengths differ sufficiently. This
796 * is necessary to make double encryption work with rsaref. Oh, I
797 * hate software patents. I dont know if this can go? Niels
799 if (options.server_key_bits >
800 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) - SSH_KEY_BITS_RESERVED &&
801 options.server_key_bits <
802 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
803 options.server_key_bits =
804 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED;
805 debug("Forcing server key to %d bits to make it differ from host key.",
806 options.server_key_bits);
810 /* Configuration looks good, so exit if in test mode. */
814 #ifdef HAVE_SCO_PROTECTED_PW
815 (void) set_auth_parameters(ac, av);
818 /* Initialize the log (it is reinitialized below in case we forked). */
819 if (debug_flag && !inetd_flag)
821 log_init(__progname, options.log_level, options.log_facility, log_stderr);
824 * If not in debugging mode, and not started from inetd, disconnect
825 * from the controlling terminal, and fork. The original process
828 if (!(debug_flag || inetd_flag || no_daemon_flag)) {
831 #endif /* TIOCNOTTY */
832 if (daemon(0, 0) < 0)
833 fatal("daemon() failed: %.200s", strerror(errno));
835 /* Disconnect from the controlling tty. */
837 fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
839 (void) ioctl(fd, TIOCNOTTY, NULL);
842 #endif /* TIOCNOTTY */
844 /* Reinitialize the log (because of the fork above). */
845 log_init(__progname, options.log_level, options.log_facility, log_stderr);
847 /* Initialize the random number generator. */
850 /* Chdir to the root directory so that the current disk can be
851 unmounted if desired. */
855 signal(SIGPIPE, SIG_IGN);
857 /* Start listening for a socket, unless started from inetd. */
860 s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */
866 * We intentionally do not close the descriptors 0, 1, and 2
867 * as our code for setting the descriptors won\'t work if
868 * ttyfd happens to be one of those.
870 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
871 if (options.protocol & SSH_PROTO_1)
872 generate_ephemeral_server_key();
874 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
875 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
877 if (num_listen_socks >= MAX_LISTEN_SOCKS)
878 fatal("Too many listen sockets. "
879 "Enlarge MAX_LISTEN_SOCKS");
880 if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
881 ntop, sizeof(ntop), strport, sizeof(strport),
882 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
883 error("getnameinfo failed");
886 /* Create socket for listening. */
887 listen_sock = socket(ai->ai_family, SOCK_STREAM, 0);
888 if (listen_sock < 0) {
889 /* kernel may not support ipv6 */
890 verbose("socket: %.100s", strerror(errno));
893 if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) {
894 error("listen_sock O_NONBLOCK: %s", strerror(errno));
899 * Set socket options. We try to make the port
900 * reusable and have it close as fast as possible
901 * without waiting in unnecessary wait states on
904 setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
908 setsockopt(listen_sock, SOL_SOCKET, SO_LINGER,
909 &linger, sizeof(linger));
911 debug("Bind to port %s on %s.", strport, ntop);
913 /* Bind the socket to the desired port. */
914 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
916 error("Bind to port %s on %s failed: %.200s.",
917 strport, ntop, strerror(errno));
921 listen_socks[num_listen_socks] = listen_sock;
924 /* Start listening on the port. */
925 log("Server listening on %s port %s.", ntop, strport);
926 if (listen(listen_sock, 5) < 0)
927 fatal("listen: %.100s", strerror(errno));
930 freeaddrinfo(options.listen_addrs);
932 if (!num_listen_socks)
933 fatal("Cannot bind any address.");
935 if (options.protocol & SSH_PROTO_1)
936 generate_ephemeral_server_key();
939 * Arrange to restart on SIGHUP. The handler needs
942 signal(SIGHUP, sighup_handler);
944 signal(SIGTERM, sigterm_handler);
945 signal(SIGQUIT, sigterm_handler);
947 /* Arrange SIGCHLD to be caught. */
948 signal(SIGCHLD, main_sigchld_handler);
950 /* Write out the pid file after the sigterm handler is setup */
953 * Record our pid in /var/run/sshd.pid to make it
954 * easier to kill the correct sshd. We don't want to
955 * do this before the bind above because the bind will
956 * fail if there already is a daemon, and this will
957 * overwrite any old pid in the file.
959 f = fopen(options.pid_file, "wb");
961 fprintf(f, "%u\n", (u_int) getpid());
966 /* setup fd set for listen */
969 for (i = 0; i < num_listen_socks; i++)
970 if (listen_socks[i] > maxfd)
971 maxfd = listen_socks[i];
972 /* pipes connected to unauthenticated childs */
973 startup_pipes = xmalloc(options.max_startups * sizeof(int));
974 for (i = 0; i < options.max_startups; i++)
975 startup_pipes[i] = -1;
978 * Stay listening for connections until the system crashes or
979 * the daemon is killed with a signal.
986 fdsetsz = howmany(maxfd+1, NFDBITS) * sizeof(fd_mask);
987 fdset = (fd_set *)xmalloc(fdsetsz);
988 memset(fdset, 0, fdsetsz);
990 for (i = 0; i < num_listen_socks; i++)
991 FD_SET(listen_socks[i], fdset);
992 for (i = 0; i < options.max_startups; i++)
993 if (startup_pipes[i] != -1)
994 FD_SET(startup_pipes[i], fdset);
996 /* Wait in select until there is a connection. */
997 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
998 if (ret < 0 && errno != EINTR)
999 error("select: %.100s", strerror(errno));
1000 if (received_sigterm) {
1001 log("Received signal %d; terminating.",
1002 (int) received_sigterm);
1003 close_listen_socks();
1004 unlink(options.pid_file);
1007 if (key_used && key_do_regen) {
1008 generate_ephemeral_server_key();
1015 for (i = 0; i < options.max_startups; i++)
1016 if (startup_pipes[i] != -1 &&
1017 FD_ISSET(startup_pipes[i], fdset)) {
1019 * the read end of the pipe is ready
1020 * if the child has closed the pipe
1021 * after successful authentication
1022 * or if the child has died
1024 close(startup_pipes[i]);
1025 startup_pipes[i] = -1;
1028 for (i = 0; i < num_listen_socks; i++) {
1029 if (!FD_ISSET(listen_socks[i], fdset))
1031 fromlen = sizeof(from);
1032 newsock = accept(listen_socks[i], (struct sockaddr *)&from,
1035 if (errno != EINTR && errno != EWOULDBLOCK)
1036 error("accept: %.100s", strerror(errno));
1039 if (fcntl(newsock, F_SETFL, 0) < 0) {
1040 error("newsock del O_NONBLOCK: %s", strerror(errno));
1044 if (drop_connection(startups) == 1) {
1045 debug("drop connection #%d", startups);
1049 if (pipe(startup_p) == -1) {
1054 for (j = 0; j < options.max_startups; j++)
1055 if (startup_pipes[j] == -1) {
1056 startup_pipes[j] = startup_p[0];
1057 if (maxfd < startup_p[0])
1058 maxfd = startup_p[0];
1064 * Got connection. Fork a child to handle it, unless
1065 * we are in debugging mode.
1069 * In debugging mode. Close the listening
1070 * socket, and start processing the
1071 * connection without forking.
1073 debug("Server will not fork when running in debugging mode.");
1074 close_listen_socks();
1082 * Normal production daemon. Fork, and have
1083 * the child process the connection. The
1084 * parent continues listening.
1086 if ((pid = fork()) == 0) {
1088 * Child. Close the listening and max_startup
1089 * sockets. Start using the accepted socket.
1090 * Reinitialize logging (since our pid has
1091 * changed). We break out of the loop to handle
1094 startup_pipe = startup_p[1];
1095 close_startup_pipes();
1096 close_listen_socks();
1099 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1104 /* Parent. Stay in the loop. */
1106 error("fork: %.100s", strerror(errno));
1108 debug("Forked child %d.", pid);
1110 close(startup_p[1]);
1112 /* Mark that the key has been used (it was "given" to the child). */
1113 if ((options.protocol & SSH_PROTO_1) &&
1115 /* Schedule server key regeneration alarm. */
1116 signal(SIGALRM, key_regeneration_alarm);
1117 alarm(options.key_regeneration_time);
1123 /* Close the new socket (the child is now taking care of it). */
1126 /* child process check (or debug mode) */
1127 if (num_listen_socks < 0)
1132 /* This is the child processing a new connection. */
1135 * Disable the key regeneration alarm. We will not regenerate the
1136 * key since we are no longer in a position to give it to anyone. We
1137 * will not restart on SIGHUP since it no longer makes sense.
1140 signal(SIGALRM, SIG_DFL);
1141 signal(SIGHUP, SIG_DFL);
1142 signal(SIGTERM, SIG_DFL);
1143 signal(SIGQUIT, SIG_DFL);
1144 signal(SIGCHLD, SIG_DFL);
1145 signal(SIGINT, SIG_DFL);
1148 * Set socket options for the connection. We want the socket to
1149 * close as fast as possible without waiting for anything. If the
1150 * connection is not a socket, these will do nothing.
1152 /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
1154 linger.l_linger = 5;
1155 setsockopt(sock_in, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger));
1157 /* Set keepalives if requested. */
1158 if (options.keepalives &&
1159 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on,
1161 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1164 * Register our connection. This turns encryption off because we do
1167 packet_set_connection(sock_in, sock_out);
1169 remote_port = get_remote_port();
1170 remote_ip = get_remote_ipaddr();
1173 /* Check whether logins are denied from this host. */
1175 struct request_info req;
1177 request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1180 if (!hosts_access(&req)) {
1181 debug("Connection refused by tcp wrapper");
1184 fatal("libwrap refuse returns");
1187 #endif /* LIBWRAP */
1189 /* Log the connection. */
1190 verbose("Connection from %.500s port %d", remote_ip, remote_port);
1193 * We don\'t want to listen forever unless the other side
1194 * successfully authenticates itself. So we set up an alarm which is
1195 * cleared after successful authentication. A limit of zero
1196 * indicates no limit. Note that we don\'t set the alarm in debugging
1197 * mode; it is just annoying to have the server exit just when you
1198 * are about to discover the bug.
1200 signal(SIGALRM, grace_alarm_handler);
1202 alarm(options.login_grace_time);
1204 sshd_exchange_identification(sock_in, sock_out);
1206 * Check that the connection comes from a privileged port.
1207 * Rhosts-Authentication only makes sense from priviledged
1208 * programs. Of course, if the intruder has root access on his local
1209 * machine, he can connect from any port. So do not use these
1210 * authentication methods from machines that you do not trust.
1212 if (options.rhosts_authentication &&
1213 (remote_port >= IPPORT_RESERVED ||
1214 remote_port < IPPORT_RESERVED / 2)) {
1215 debug("Rhosts Authentication disabled, "
1216 "originating port %d not trusted.", remote_port);
1217 options.rhosts_authentication = 0;
1219 #if defined(KRB4) && !defined(KRB5)
1220 if (!packet_connection_is_ipv4() &&
1221 options.kerberos_authentication) {
1222 debug("Kerberos Authentication disabled, only available for IPv4.");
1223 options.kerberos_authentication = 0;
1225 #endif /* KRB4 && !KRB5 */
1227 /* If machine has AFS, set process authentication group. */
1234 packet_set_nonblocking();
1236 /* perform the key exchange */
1237 /* authenticate user and start session */
1240 authctxt = do_authentication2();
1243 authctxt = do_authentication();
1246 /* Perform session preparation. */
1247 do_authenticated(authctxt);
1249 /* The connection has been terminated. */
1250 verbose("Closing connection to %.100s", remote_ip);
1254 #endif /* USE_PAM */
1261 * Decrypt session_key_int using our private server key and private host key
1262 * (key with larger modulus first).
1265 ssh1_session_key(BIGNUM *session_key_int)
1269 if (BN_cmp(sensitive_data.server_key->rsa->n, sensitive_data.ssh1_host_key->rsa->n) > 0) {
1270 /* Server key has bigger modulus. */
1271 if (BN_num_bits(sensitive_data.server_key->rsa->n) <
1272 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1273 fatal("do_connection: %s: server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1274 get_remote_ipaddr(),
1275 BN_num_bits(sensitive_data.server_key->rsa->n),
1276 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1277 SSH_KEY_BITS_RESERVED);
1279 if (rsa_private_decrypt(session_key_int, session_key_int,
1280 sensitive_data.server_key->rsa) <= 0)
1282 if (rsa_private_decrypt(session_key_int, session_key_int,
1283 sensitive_data.ssh1_host_key->rsa) <= 0)
1286 /* Host key has bigger modulus (or they are equal). */
1287 if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
1288 BN_num_bits(sensitive_data.server_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1289 fatal("do_connection: %s: host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
1290 get_remote_ipaddr(),
1291 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1292 BN_num_bits(sensitive_data.server_key->rsa->n),
1293 SSH_KEY_BITS_RESERVED);
1295 if (rsa_private_decrypt(session_key_int, session_key_int,
1296 sensitive_data.ssh1_host_key->rsa) < 0)
1298 if (rsa_private_decrypt(session_key_int, session_key_int,
1299 sensitive_data.server_key->rsa) < 0)
1312 BIGNUM *session_key_int;
1313 u_char session_key[SSH_SESSION_KEY_LENGTH];
1315 u_int cipher_type, auth_mask, protocol_flags;
1319 * Generate check bytes that the client must send back in the user
1320 * packet in order for it to be accepted; this is used to defy ip
1321 * spoofing attacks. Note that this only works against somebody
1322 * doing IP spoofing from a remote machine; any machine on the local
1323 * network can still see outgoing packets and catch the random
1324 * cookie. This only affects rhosts authentication, and this is one
1325 * of the reasons why it is inherently insecure.
1327 for (i = 0; i < 8; i++) {
1329 rand = arc4random();
1330 cookie[i] = rand & 0xff;
1335 * Send our public key. We include in the packet 64 bits of random
1336 * data that must be matched in the reply in order to prevent IP
1339 packet_start(SSH_SMSG_PUBLIC_KEY);
1340 for (i = 0; i < 8; i++)
1341 packet_put_char(cookie[i]);
1343 /* Store our public server RSA key. */
1344 packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
1345 packet_put_bignum(sensitive_data.server_key->rsa->e);
1346 packet_put_bignum(sensitive_data.server_key->rsa->n);
1348 /* Store our public host RSA key. */
1349 packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1350 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
1351 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
1353 /* Put protocol flags. */
1354 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
1356 /* Declare which ciphers we support. */
1357 packet_put_int(cipher_mask_ssh1(0));
1359 /* Declare supported authentication types. */
1361 if (options.rhosts_authentication)
1362 auth_mask |= 1 << SSH_AUTH_RHOSTS;
1363 if (options.rhosts_rsa_authentication)
1364 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
1365 if (options.rsa_authentication)
1366 auth_mask |= 1 << SSH_AUTH_RSA;
1367 #if defined(KRB4) || defined(KRB5)
1368 if (options.kerberos_authentication)
1369 auth_mask |= 1 << SSH_AUTH_KERBEROS;
1371 #if defined(AFS) || defined(KRB5)
1372 if (options.kerberos_tgt_passing)
1373 auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
1376 if (options.afs_token_passing)
1377 auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
1379 if (options.challenge_response_authentication == 1)
1380 auth_mask |= 1 << SSH_AUTH_TIS;
1381 if (options.password_authentication)
1382 auth_mask |= 1 << SSH_AUTH_PASSWORD;
1383 packet_put_int(auth_mask);
1385 /* Send the packet and wait for it to be sent. */
1387 packet_write_wait();
1389 debug("Sent %d bit server key and %d bit host key.",
1390 BN_num_bits(sensitive_data.server_key->rsa->n),
1391 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1393 /* Read clients reply (cipher type and session key). */
1394 packet_read_expect(SSH_CMSG_SESSION_KEY);
1396 /* Get cipher type and check whether we accept this. */
1397 cipher_type = packet_get_char();
1399 if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
1400 packet_disconnect("Warning: client selects unsupported cipher.");
1402 /* Get check bytes from the packet. These must match those we
1403 sent earlier with the public key packet. */
1404 for (i = 0; i < 8; i++)
1405 if (cookie[i] != packet_get_char())
1406 packet_disconnect("IP Spoofing check bytes do not match.");
1408 debug("Encryption type: %.200s", cipher_name(cipher_type));
1410 /* Get the encrypted integer. */
1411 if ((session_key_int = BN_new()) == NULL)
1412 fatal("do_ssh1_kex: BN_new failed");
1413 packet_get_bignum(session_key_int);
1415 protocol_flags = packet_get_int();
1416 packet_set_protocol_flags(protocol_flags);
1419 /* Decrypt session_key_int using host/server keys */
1420 rsafail = ssh1_session_key(session_key_int);
1422 * Extract session key from the decrypted integer. The key is in the
1423 * least significant 256 bits of the integer; the first byte of the
1424 * key is in the highest bits.
1427 BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1428 len = BN_num_bytes(session_key_int);
1429 if (len < 0 || len > sizeof(session_key)) {
1430 error("do_connection: bad session key len from %s: "
1431 "session_key_int %d > sizeof(session_key) %lu",
1432 get_remote_ipaddr(), len, (u_long)sizeof(session_key));
1435 memset(session_key, 0, sizeof(session_key));
1436 BN_bn2bin(session_key_int,
1437 session_key + sizeof(session_key) - len);
1439 compute_session_id(session_id, cookie,
1440 sensitive_data.ssh1_host_key->rsa->n,
1441 sensitive_data.server_key->rsa->n);
1443 * Xor the first 16 bytes of the session key with the
1446 for (i = 0; i < 16; i++)
1447 session_key[i] ^= session_id[i];
1451 int bytes = BN_num_bytes(session_key_int);
1452 u_char *buf = xmalloc(bytes);
1455 log("do_connection: generating a fake encryption key");
1456 BN_bn2bin(session_key_int, buf);
1458 MD5_Update(&md, buf, bytes);
1459 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1460 MD5_Final(session_key, &md);
1462 MD5_Update(&md, session_key, 16);
1463 MD5_Update(&md, buf, bytes);
1464 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1465 MD5_Final(session_key + 16, &md);
1466 memset(buf, 0, bytes);
1468 for (i = 0; i < 16; i++)
1469 session_id[i] = session_key[i] ^ session_key[i + 16];
1471 /* Destroy the private and public keys. They will no longer be needed. */
1472 destroy_sensitive_data();
1474 /* Destroy the decrypted integer. It is no longer needed. */
1475 BN_clear_free(session_key_int);
1477 /* Set the session key. From this on all communications will be encrypted. */
1478 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
1480 /* Destroy our copy of the session key. It is no longer needed. */
1481 memset(session_key, 0, sizeof(session_key));
1483 debug("Received session key; encryption turned on.");
1485 /* Send an acknowledgement packet. Note that this packet is sent encrypted. */
1486 packet_start(SSH_SMSG_SUCCESS);
1488 packet_write_wait();
1492 * SSH2 key exchange: diffie-hellman-group1-sha1
1499 if (options.ciphers != NULL) {
1500 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1501 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
1503 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1504 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
1505 myproposal[PROPOSAL_ENC_ALGS_STOC] =
1506 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
1508 if (options.macs != NULL) {
1509 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
1510 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
1512 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
1514 /* start key exchange */
1515 kex = kex_setup(myproposal);
1517 kex->client_version_string=client_version_string;
1518 kex->server_version_string=server_version_string;
1519 kex->load_host_key=&get_hostkey_by_type;
1523 dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
1525 session_id2 = kex->session_id;
1526 session_id2_len = kex->session_id_len;
1529 /* send 1st encrypted/maced/compressed message */
1530 packet_start(SSH2_MSG_IGNORE);
1531 packet_put_cstring("markus");
1533 packet_write_wait();