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"
81 #include <openssl/md5.h>
88 int allow_severity = LOG_INFO;
89 int deny_severity = LOG_WARNING;
96 #ifdef HAVE___PROGNAME
97 extern char *__progname;
102 /* Server configuration options. */
103 ServerOptions options;
105 /* Name of the server configuration file. */
106 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
109 * Flag indicating whether IPv4 or IPv6. This can be set on the command line.
110 * Default value is AF_UNSPEC means both IPv4 and IPv6.
113 int IPv4or6 = AF_INET;
115 int IPv4or6 = AF_UNSPEC;
119 * Debug mode flag. This can be set on the command line. If debug
120 * mode is enabled, extra debugging output will be sent to the system
121 * log, the daemon will not go to background, and will exit after processing
122 * the first connection.
126 /* Flag indicating that the daemon should only test the configuration and keys. */
129 /* Flag indicating that the daemon is being started from inetd. */
132 /* Flag indicating that sshd should not detach and become a daemon. */
133 int no_daemon_flag = 0;
135 /* debug goes to stderr unless inetd_flag is set */
138 /* Saved arguments to main(). */
143 * The sockets that the server is listening; this is used in the SIGHUP
146 #define MAX_LISTEN_SOCKS 16
147 int listen_socks[MAX_LISTEN_SOCKS];
148 int num_listen_socks = 0;
151 * the client's version string, passed by sshd2 in compat mode. if != NULL,
152 * sshd will skip the version-number exchange
154 char *client_version_string = NULL;
155 char *server_version_string = NULL;
157 /* for rekeying XXX fixme */
161 * Any really sensitive data in the application is contained in this
162 * structure. The idea is that this structure could be locked into memory so
163 * that the pages do not get written into swap. However, there are some
164 * problems. The private key contains BIGNUMs, and we do not (in principle)
165 * have access to the internals of them, and locking just the structure is
166 * not very useful. Currently, memory locking is not implemented.
169 Key *server_key; /* ephemeral server key */
170 Key *ssh1_host_key; /* ssh1 host key */
171 Key **host_keys; /* all private host keys */
174 u_char ssh1_cookie[SSH_SESSION_KEY_LENGTH];
178 * Flag indicating whether the RSA server key needs to be regenerated.
179 * Is set in the SIGALRM handler and cleared when the key is regenerated.
181 static volatile sig_atomic_t key_do_regen = 0;
183 /* This is set to true when a signal is received. */
184 static volatile sig_atomic_t received_sighup = 0;
185 static volatile sig_atomic_t received_sigterm = 0;
187 /* session identifier, used by RSA-auth */
188 u_char session_id[16];
191 u_char *session_id2 = NULL;
192 int session_id2_len = 0;
194 /* record remote hostname or ip */
195 u_int utmp_len = MAXHOSTNAMELEN;
197 /* options.max_startup sized array of fd ints */
198 int *startup_pipes = NULL;
199 int startup_pipe; /* in child */
201 /* Prototypes for various functions defined later in this file. */
202 void destroy_sensitive_data(void);
204 static void do_ssh1_kex(void);
205 static void do_ssh2_kex(void);
208 * Close all listening sockets
211 close_listen_socks(void)
214 for (i = 0; i < num_listen_socks; i++)
215 close(listen_socks[i]);
216 num_listen_socks = -1;
220 close_startup_pipes(void)
224 for (i = 0; i < options.max_startups; i++)
225 if (startup_pipes[i] != -1)
226 close(startup_pipes[i]);
230 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
231 * the effect is to reread the configuration file (and to regenerate
235 sighup_handler(int sig)
237 int save_errno = errno;
240 signal(SIGHUP, sighup_handler);
245 * Called from the main program after receiving SIGHUP.
246 * Restarts the server.
251 log("Received SIGHUP; restarting.");
252 close_listen_socks();
253 close_startup_pipes();
254 execv(saved_argv[0], saved_argv);
255 log("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0], strerror(errno));
260 * Generic signal handler for terminating signals in the master daemon.
263 sigterm_handler(int sig)
265 received_sigterm = sig;
269 * SIGCHLD handler. This is called whenever a child dies. This will then
270 * reap any zombies left by exited children.
273 main_sigchld_handler(int sig)
275 int save_errno = errno;
278 while (waitpid(-1, &status, WNOHANG) > 0)
281 signal(SIGCHLD, main_sigchld_handler);
286 * Signal handler for the alarm after the login grace period has expired.
289 grace_alarm_handler(int sig)
291 /* XXX no idea how fix this signal handler */
293 /* Close the connection. */
296 /* Log error and exit. */
297 fatal("Timeout before authentication for %s.", get_remote_ipaddr());
301 * Signal handler for the key regeneration alarm. Note that this
302 * alarm only occurs in the daemon waiting for connections, and it does not
303 * do anything with the private key or random state before forking.
304 * Thus there should be no concurrency control/asynchronous execution
308 generate_ephemeral_server_key(void)
313 verbose("Generating %s%d bit RSA key.",
314 sensitive_data.server_key ? "new " : "", options.server_key_bits);
315 if (sensitive_data.server_key != NULL)
316 key_free(sensitive_data.server_key);
317 sensitive_data.server_key = key_generate(KEY_RSA1,
318 options.server_key_bits);
319 verbose("RSA key generation complete.");
321 for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
324 sensitive_data.ssh1_cookie[i] = rand & 0xff;
331 key_regeneration_alarm(int sig)
333 int save_errno = errno;
334 signal(SIGALRM, SIG_DFL);
340 sshd_exchange_identification(int sock_in, int sock_out)
343 int remote_major, remote_minor;
346 char buf[256]; /* Must not be larger than remote_version. */
347 char remote_version[256]; /* Must be at least as big as buf. */
349 if ((options.protocol & SSH_PROTO_1) &&
350 (options.protocol & SSH_PROTO_2)) {
351 major = PROTOCOL_MAJOR_1;
353 } else if (options.protocol & SSH_PROTO_2) {
354 major = PROTOCOL_MAJOR_2;
355 minor = PROTOCOL_MINOR_2;
357 major = PROTOCOL_MAJOR_1;
358 minor = PROTOCOL_MINOR_1;
360 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", major, minor, SSH_VERSION);
361 server_version_string = xstrdup(buf);
363 if (client_version_string == NULL) {
364 /* Send our protocol version identification. */
365 if (atomicio(write, sock_out, server_version_string, strlen(server_version_string))
366 != strlen(server_version_string)) {
367 log("Could not write ident string to %s", get_remote_ipaddr());
371 /* Read other side's version identification. */
372 memset(buf, 0, sizeof(buf));
373 for (i = 0; i < sizeof(buf) - 1; i++) {
374 if (atomicio(read, sock_in, &buf[i], 1) != 1) {
375 log("Did not receive identification string from %s",
376 get_remote_ipaddr());
379 if (buf[i] == '\r') {
381 /* Kludge for F-Secure Macintosh < 1.0.2 */
383 strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
387 if (buf[i] == '\n') {
392 buf[sizeof(buf) - 1] = 0;
393 client_version_string = xstrdup(buf);
397 * Check that the versions match. In future this might accept
398 * several versions and set appropriate flags to handle them.
400 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
401 &remote_major, &remote_minor, remote_version) != 3) {
402 s = "Protocol mismatch.\n";
403 (void) atomicio(write, sock_out, s, strlen(s));
406 log("Bad protocol version identification '%.100s' from %s",
407 client_version_string, get_remote_ipaddr());
410 debug("Client protocol version %d.%d; client software version %.100s",
411 remote_major, remote_minor, remote_version);
413 compat_datafellows(remote_version);
415 if (datafellows & SSH_BUG_SCANNER) {
416 log("scanned from %s with %s. Don't panic.",
417 get_remote_ipaddr(), client_version_string);
422 switch (remote_major) {
424 if (remote_minor == 99) {
425 if (options.protocol & SSH_PROTO_2)
431 if (!(options.protocol & SSH_PROTO_1)) {
435 if (remote_minor < 3) {
436 packet_disconnect("Your ssh version is too old and "
437 "is no longer supported. Please install a newer version.");
438 } else if (remote_minor == 3) {
439 /* note that this disables agent-forwarding */
444 if (options.protocol & SSH_PROTO_2) {
453 chop(server_version_string);
454 debug("Local version string %.200s", server_version_string);
457 s = "Protocol major versions differ.\n";
458 (void) atomicio(write, sock_out, s, strlen(s));
461 log("Protocol major versions differ for %s: %.200s vs. %.200s",
463 server_version_string, client_version_string);
469 /* Destroy the host and server keys. They will no longer be needed. */
471 destroy_sensitive_data(void)
475 if (sensitive_data.server_key) {
476 key_free(sensitive_data.server_key);
477 sensitive_data.server_key = NULL;
479 for (i = 0; i < options.num_host_key_files; i++) {
480 if (sensitive_data.host_keys[i]) {
481 key_free(sensitive_data.host_keys[i]);
482 sensitive_data.host_keys[i] = NULL;
485 sensitive_data.ssh1_host_key = NULL;
486 memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
490 list_hostkey_types(void)
497 for (i = 0; i < options.num_host_key_files; i++) {
498 Key *key = sensitive_data.host_keys[i];
504 if (buffer_len(&b) > 0)
505 buffer_append(&b, ",", 1);
506 p = key_ssh_name(key);
507 buffer_append(&b, p, strlen(p));
511 buffer_append(&b, "\0", 1);
512 p = xstrdup(buffer_ptr(&b));
514 debug("list_hostkey_types: %s", p);
519 get_hostkey_by_type(int type)
522 for (i = 0; i < options.num_host_key_files; i++) {
523 Key *key = sensitive_data.host_keys[i];
524 if (key != NULL && key->type == type)
531 * returns 1 if connection should be dropped, 0 otherwise.
532 * dropping starts at connection #max_startups_begin with a probability
533 * of (max_startups_rate/100). the probability increases linearly until
534 * all connections are dropped for startups > max_startups
537 drop_connection(int startups)
541 if (startups < options.max_startups_begin)
543 if (startups >= options.max_startups)
545 if (options.max_startups_rate == 100)
548 p = 100 - options.max_startups_rate;
549 p *= startups - options.max_startups_begin;
550 p /= (double) (options.max_startups - options.max_startups_begin);
551 p += options.max_startups_rate;
553 r = arc4random() / (double) UINT_MAX;
555 debug("drop_connection: p %g, r %g", p, r);
556 return (r < p) ? 1 : 0;
562 fprintf(stderr, "sshd version %s\n", SSH_VERSION);
563 fprintf(stderr, "Usage: %s [options]\n", __progname);
564 fprintf(stderr, "Options:\n");
565 fprintf(stderr, " -f file Configuration file (default %s)\n", _PATH_SERVER_CONFIG_FILE);
566 fprintf(stderr, " -d Debugging mode (multiple -d means more debugging)\n");
567 fprintf(stderr, " -i Started from inetd\n");
568 fprintf(stderr, " -D Do not fork into daemon mode\n");
569 fprintf(stderr, " -t Only test configuration file and keys\n");
570 fprintf(stderr, " -q Quiet (no logging)\n");
571 fprintf(stderr, " -p port Listen on the specified port (default: 22)\n");
572 fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n");
573 fprintf(stderr, " -g seconds Grace period for authentication (default: 600)\n");
574 fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n");
575 fprintf(stderr, " -h file File from which to read host key (default: %s)\n",
576 _PATH_HOST_KEY_FILE);
577 fprintf(stderr, " -u len Maximum hostname length for utmp recording\n");
578 fprintf(stderr, " -4 Use IPv4 only\n");
579 fprintf(stderr, " -6 Use IPv6 only\n");
580 fprintf(stderr, " -o option Process the option as if it was read from a configuration file.\n");
585 * Main program for the daemon.
588 main(int ac, char **av)
592 int opt, sock_in = 0, sock_out = 0, newsock, j, i, fdsetsz, on = 1;
596 struct sockaddr_storage from;
597 const char *remote_ip;
600 struct linger linger;
602 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
603 int listen_sock, maxfd;
607 int ret, key_used = 0;
609 __progname = get_progname(av[0]);
616 /* Initialize configuration options to their default values. */
617 initialize_server_options(&options);
619 /* Parse command-line arguments. */
620 while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:u:o:dDeiqtQ46")) != -1) {
629 config_file_name = optarg;
632 if (0 == debug_flag) {
634 options.log_level = SYSLOG_LEVEL_DEBUG1;
635 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
638 fprintf(stderr, "Too high debugging level.\n");
655 options.log_level = SYSLOG_LEVEL_QUIET;
658 options.server_key_bits = atoi(optarg);
661 options.ports_from_cmdline = 1;
662 if (options.num_ports >= MAX_PORTS) {
663 fprintf(stderr, "too many ports.\n");
666 options.ports[options.num_ports++] = a2port(optarg);
667 if (options.ports[options.num_ports-1] == 0) {
668 fprintf(stderr, "Bad port number.\n");
673 if ((options.login_grace_time = convtime(optarg)) == -1) {
674 fprintf(stderr, "Invalid login grace time.\n");
679 if ((options.key_regeneration_time = convtime(optarg)) == -1) {
680 fprintf(stderr, "Invalid key regeneration interval.\n");
685 if (options.num_host_key_files >= MAX_HOSTKEYS) {
686 fprintf(stderr, "too many host keys.\n");
689 options.host_key_files[options.num_host_key_files++] = optarg;
692 client_version_string = optarg;
693 /* only makes sense with inetd_flag, i.e. no listen() */
700 utmp_len = atoi(optarg);
703 if (process_server_config_line(&options, optarg,
704 "command-line", 0) != 0)
713 SSLeay_add_all_algorithms();
714 channel_set_af(IPv4or6);
717 * Force logging to stderr until we have loaded the private host
718 * key (unless started from inetd)
721 options.log_level == SYSLOG_LEVEL_NOT_SET ?
722 SYSLOG_LEVEL_INFO : options.log_level,
723 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
724 SYSLOG_FACILITY_AUTH : options.log_facility,
728 /* Cray can define user privs drop all prives now!
729 * Not needed on PRIV_SU systems!
736 /* Read server configuration options from the configuration file. */
737 read_server_config(&options, config_file_name);
739 /* Fill in default values for those options not explicitly set. */
740 fill_default_server_options(&options);
742 /* Check that there are no remaining arguments. */
744 fprintf(stderr, "Extra argument %s.\n", av[optind]);
748 debug("sshd version %.100s", SSH_VERSION);
750 /* load private host keys */
751 sensitive_data.host_keys = xmalloc(options.num_host_key_files*sizeof(Key*));
752 for (i = 0; i < options.num_host_key_files; i++)
753 sensitive_data.host_keys[i] = NULL;
754 sensitive_data.server_key = NULL;
755 sensitive_data.ssh1_host_key = NULL;
756 sensitive_data.have_ssh1_key = 0;
757 sensitive_data.have_ssh2_key = 0;
759 for (i = 0; i < options.num_host_key_files; i++) {
760 key = key_load_private(options.host_key_files[i], "", NULL);
761 sensitive_data.host_keys[i] = key;
763 error("Could not load host key: %s",
764 options.host_key_files[i]);
765 sensitive_data.host_keys[i] = NULL;
770 sensitive_data.ssh1_host_key = key;
771 sensitive_data.have_ssh1_key = 1;
775 sensitive_data.have_ssh2_key = 1;
778 debug("private host key: #%d type %d %s", i, key->type,
781 if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
782 log("Disabling protocol version 1. Could not load host key");
783 options.protocol &= ~SSH_PROTO_1;
786 /* The GSSAPI key exchange can run without a host key */
787 if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
788 log("Disabling protocol version 2. Could not load host key");
789 options.protocol &= ~SSH_PROTO_2;
792 if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
793 log("sshd: no hostkeys available -- exiting.");
797 /* Check certain values for sanity. */
798 if (options.protocol & SSH_PROTO_1) {
799 if (options.server_key_bits < 512 ||
800 options.server_key_bits > 32768) {
801 fprintf(stderr, "Bad server key size.\n");
805 * Check that server and host key lengths differ sufficiently. This
806 * is necessary to make double encryption work with rsaref. Oh, I
807 * hate software patents. I dont know if this can go? Niels
809 if (options.server_key_bits >
810 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) - SSH_KEY_BITS_RESERVED &&
811 options.server_key_bits <
812 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
813 options.server_key_bits =
814 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED;
815 debug("Forcing server key to %d bits to make it differ from host key.",
816 options.server_key_bits);
820 /* Configuration looks good, so exit if in test mode. */
828 #ifdef HAVE_SCO_PROTECTED_PW
829 (void) set_auth_parameters(ac, av);
832 /* Initialize the log (it is reinitialized below in case we forked). */
833 if (debug_flag && !inetd_flag)
835 log_init(__progname, options.log_level, options.log_facility, log_stderr);
838 * If not in debugging mode, and not started from inetd, disconnect
839 * from the controlling terminal, and fork. The original process
842 if (!(debug_flag || inetd_flag || no_daemon_flag)) {
845 #endif /* TIOCNOTTY */
846 if (daemon(0, 0) < 0)
847 fatal("daemon() failed: %.200s", strerror(errno));
849 /* Disconnect from the controlling tty. */
851 fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
853 (void) ioctl(fd, TIOCNOTTY, NULL);
856 #endif /* TIOCNOTTY */
858 /* Reinitialize the log (because of the fork above). */
859 log_init(__progname, options.log_level, options.log_facility, log_stderr);
861 /* Initialize the random number generator. */
864 /* Chdir to the root directory so that the current disk can be
865 unmounted if desired. */
869 signal(SIGPIPE, SIG_IGN);
871 /* Start listening for a socket, unless started from inetd. */
874 s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */
880 * We intentionally do not close the descriptors 0, 1, and 2
881 * as our code for setting the descriptors won\'t work if
882 * ttyfd happens to be one of those.
884 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
885 if (options.protocol & SSH_PROTO_1)
886 generate_ephemeral_server_key();
888 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
889 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
891 if (num_listen_socks >= MAX_LISTEN_SOCKS)
892 fatal("Too many listen sockets. "
893 "Enlarge MAX_LISTEN_SOCKS");
894 if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
895 ntop, sizeof(ntop), strport, sizeof(strport),
896 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
897 error("getnameinfo failed");
900 /* Create socket for listening. */
901 listen_sock = socket(ai->ai_family, SOCK_STREAM, 0);
902 if (listen_sock < 0) {
903 /* kernel may not support ipv6 */
904 verbose("socket: %.100s", strerror(errno));
907 if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) {
908 error("listen_sock O_NONBLOCK: %s", strerror(errno));
913 * Set socket options. We try to make the port
914 * reusable and have it close as fast as possible
915 * without waiting in unnecessary wait states on
918 setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
922 setsockopt(listen_sock, SOL_SOCKET, SO_LINGER,
923 &linger, sizeof(linger));
925 debug("Bind to port %s on %s.", strport, ntop);
927 /* Bind the socket to the desired port. */
928 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
930 error("Bind to port %s on %s failed: %.200s.",
931 strport, ntop, strerror(errno));
935 listen_socks[num_listen_socks] = listen_sock;
938 /* Start listening on the port. */
939 log("Server listening on %s port %s.", ntop, strport);
940 if (listen(listen_sock, 5) < 0)
941 fatal("listen: %.100s", strerror(errno));
944 freeaddrinfo(options.listen_addrs);
946 if (!num_listen_socks)
947 fatal("Cannot bind any address.");
949 if (options.protocol & SSH_PROTO_1)
950 generate_ephemeral_server_key();
953 * Arrange to restart on SIGHUP. The handler needs
956 signal(SIGHUP, sighup_handler);
958 signal(SIGTERM, sigterm_handler);
959 signal(SIGQUIT, sigterm_handler);
961 /* Arrange SIGCHLD to be caught. */
962 signal(SIGCHLD, main_sigchld_handler);
964 /* Write out the pid file after the sigterm handler is setup */
967 * Record our pid in /var/run/sshd.pid to make it
968 * easier to kill the correct sshd. We don't want to
969 * do this before the bind above because the bind will
970 * fail if there already is a daemon, and this will
971 * overwrite any old pid in the file.
973 f = fopen(options.pid_file, "wb");
975 fprintf(f, "%u\n", (u_int) getpid());
980 /* setup fd set for listen */
983 for (i = 0; i < num_listen_socks; i++)
984 if (listen_socks[i] > maxfd)
985 maxfd = listen_socks[i];
986 /* pipes connected to unauthenticated childs */
987 startup_pipes = xmalloc(options.max_startups * sizeof(int));
988 for (i = 0; i < options.max_startups; i++)
989 startup_pipes[i] = -1;
992 * Stay listening for connections until the system crashes or
993 * the daemon is killed with a signal.
1000 fdsetsz = howmany(maxfd+1, NFDBITS) * sizeof(fd_mask);
1001 fdset = (fd_set *)xmalloc(fdsetsz);
1002 memset(fdset, 0, fdsetsz);
1004 for (i = 0; i < num_listen_socks; i++)
1005 FD_SET(listen_socks[i], fdset);
1006 for (i = 0; i < options.max_startups; i++)
1007 if (startup_pipes[i] != -1)
1008 FD_SET(startup_pipes[i], fdset);
1010 /* Wait in select until there is a connection. */
1011 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1012 if (ret < 0 && errno != EINTR)
1013 error("select: %.100s", strerror(errno));
1014 if (received_sigterm) {
1015 log("Received signal %d; terminating.",
1016 (int) received_sigterm);
1017 close_listen_socks();
1018 unlink(options.pid_file);
1021 if (key_used && key_do_regen) {
1022 generate_ephemeral_server_key();
1029 for (i = 0; i < options.max_startups; i++)
1030 if (startup_pipes[i] != -1 &&
1031 FD_ISSET(startup_pipes[i], fdset)) {
1033 * the read end of the pipe is ready
1034 * if the child has closed the pipe
1035 * after successful authentication
1036 * or if the child has died
1038 close(startup_pipes[i]);
1039 startup_pipes[i] = -1;
1042 for (i = 0; i < num_listen_socks; i++) {
1043 if (!FD_ISSET(listen_socks[i], fdset))
1045 fromlen = sizeof(from);
1046 newsock = accept(listen_socks[i], (struct sockaddr *)&from,
1049 if (errno != EINTR && errno != EWOULDBLOCK)
1050 error("accept: %.100s", strerror(errno));
1053 if (fcntl(newsock, F_SETFL, 0) < 0) {
1054 error("newsock del O_NONBLOCK: %s", strerror(errno));
1058 if (drop_connection(startups) == 1) {
1059 debug("drop connection #%d", startups);
1063 if (pipe(startup_p) == -1) {
1068 for (j = 0; j < options.max_startups; j++)
1069 if (startup_pipes[j] == -1) {
1070 startup_pipes[j] = startup_p[0];
1071 if (maxfd < startup_p[0])
1072 maxfd = startup_p[0];
1078 * Got connection. Fork a child to handle it, unless
1079 * we are in debugging mode.
1083 * In debugging mode. Close the listening
1084 * socket, and start processing the
1085 * connection without forking.
1087 debug("Server will not fork when running in debugging mode.");
1088 close_listen_socks();
1096 * Normal production daemon. Fork, and have
1097 * the child process the connection. The
1098 * parent continues listening.
1100 if ((pid = fork()) == 0) {
1102 * Child. Close the listening and max_startup
1103 * sockets. Start using the accepted socket.
1104 * Reinitialize logging (since our pid has
1105 * changed). We break out of the loop to handle
1108 startup_pipe = startup_p[1];
1109 close_startup_pipes();
1110 close_listen_socks();
1113 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1118 /* Parent. Stay in the loop. */
1120 error("fork: %.100s", strerror(errno));
1122 debug("Forked child %d.", pid);
1124 close(startup_p[1]);
1126 /* Mark that the key has been used (it was "given" to the child). */
1127 if ((options.protocol & SSH_PROTO_1) &&
1129 /* Schedule server key regeneration alarm. */
1130 signal(SIGALRM, key_regeneration_alarm);
1131 alarm(options.key_regeneration_time);
1137 /* Close the new socket (the child is now taking care of it). */
1140 /* child process check (or debug mode) */
1141 if (num_listen_socks < 0)
1146 /* This is the child processing a new connection. */
1149 * Disable the key regeneration alarm. We will not regenerate the
1150 * key since we are no longer in a position to give it to anyone. We
1151 * will not restart on SIGHUP since it no longer makes sense.
1154 signal(SIGALRM, SIG_DFL);
1155 signal(SIGHUP, SIG_DFL);
1156 signal(SIGTERM, SIG_DFL);
1157 signal(SIGQUIT, SIG_DFL);
1158 signal(SIGCHLD, SIG_DFL);
1159 signal(SIGINT, SIG_DFL);
1162 * Set socket options for the connection. We want the socket to
1163 * close as fast as possible without waiting for anything. If the
1164 * connection is not a socket, these will do nothing.
1166 /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
1168 linger.l_linger = 5;
1169 setsockopt(sock_in, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger));
1171 /* Set keepalives if requested. */
1172 if (options.keepalives &&
1173 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on,
1175 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1178 * Register our connection. This turns encryption off because we do
1181 packet_set_connection(sock_in, sock_out);
1183 remote_port = get_remote_port();
1184 remote_ip = get_remote_ipaddr();
1187 /* Check whether logins are denied from this host. */
1189 struct request_info req;
1191 request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1194 if (!hosts_access(&req)) {
1195 debug("Connection refused by tcp wrapper");
1198 fatal("libwrap refuse returns");
1201 #endif /* LIBWRAP */
1203 /* Log the connection. */
1204 verbose("Connection from %.500s port %d", remote_ip, remote_port);
1207 * We don\'t want to listen forever unless the other side
1208 * successfully authenticates itself. So we set up an alarm which is
1209 * cleared after successful authentication. A limit of zero
1210 * indicates no limit. Note that we don\'t set the alarm in debugging
1211 * mode; it is just annoying to have the server exit just when you
1212 * are about to discover the bug.
1214 signal(SIGALRM, grace_alarm_handler);
1216 alarm(options.login_grace_time);
1218 sshd_exchange_identification(sock_in, sock_out);
1220 * Check that the connection comes from a privileged port.
1221 * Rhosts-Authentication only makes sense from priviledged
1222 * programs. Of course, if the intruder has root access on his local
1223 * machine, he can connect from any port. So do not use these
1224 * authentication methods from machines that you do not trust.
1226 if (options.rhosts_authentication &&
1227 (remote_port >= IPPORT_RESERVED ||
1228 remote_port < IPPORT_RESERVED / 2)) {
1229 debug("Rhosts Authentication disabled, "
1230 "originating port %d not trusted.", remote_port);
1231 options.rhosts_authentication = 0;
1233 #if defined(KRB4) && !defined(KRB5)
1234 if (!packet_connection_is_ipv4() &&
1235 options.kerberos_authentication) {
1236 debug("Kerberos Authentication disabled, only available for IPv4.");
1237 options.kerberos_authentication = 0;
1239 #endif /* KRB4 && !KRB5 */
1241 /* If machine has AFS, set process authentication group. */
1248 packet_set_nonblocking();
1250 /* perform the key exchange */
1251 /* authenticate user and start session */
1254 do_authentication2();
1257 do_authentication();
1259 /* The connection has been terminated. */
1260 verbose("Closing connection to %.100s", remote_ip);
1264 #endif /* USE_PAM */
1278 BIGNUM *session_key_int;
1279 u_char session_key[SSH_SESSION_KEY_LENGTH];
1281 u_int cipher_type, auth_mask, protocol_flags;
1285 * Generate check bytes that the client must send back in the user
1286 * packet in order for it to be accepted; this is used to defy ip
1287 * spoofing attacks. Note that this only works against somebody
1288 * doing IP spoofing from a remote machine; any machine on the local
1289 * network can still see outgoing packets and catch the random
1290 * cookie. This only affects rhosts authentication, and this is one
1291 * of the reasons why it is inherently insecure.
1293 for (i = 0; i < 8; i++) {
1295 rand = arc4random();
1296 cookie[i] = rand & 0xff;
1301 * Send our public key. We include in the packet 64 bits of random
1302 * data that must be matched in the reply in order to prevent IP
1305 packet_start(SSH_SMSG_PUBLIC_KEY);
1306 for (i = 0; i < 8; i++)
1307 packet_put_char(cookie[i]);
1309 /* Store our public server RSA key. */
1310 packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
1311 packet_put_bignum(sensitive_data.server_key->rsa->e);
1312 packet_put_bignum(sensitive_data.server_key->rsa->n);
1314 /* Store our public host RSA key. */
1315 packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1316 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
1317 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
1319 /* Put protocol flags. */
1320 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
1322 /* Declare which ciphers we support. */
1323 packet_put_int(cipher_mask_ssh1(0));
1325 /* Declare supported authentication types. */
1327 if (options.rhosts_authentication)
1328 auth_mask |= 1 << SSH_AUTH_RHOSTS;
1329 if (options.rhosts_rsa_authentication)
1330 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
1331 if (options.rsa_authentication)
1332 auth_mask |= 1 << SSH_AUTH_RSA;
1333 #if defined(KRB4) || defined(KRB5)
1334 if (options.kerberos_authentication)
1335 auth_mask |= 1 << SSH_AUTH_KERBEROS;
1337 #if defined(AFS) || defined(KRB5)
1338 if (options.kerberos_tgt_passing)
1339 auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
1342 if (options.afs_token_passing)
1343 auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
1345 if (options.challenge_response_authentication == 1)
1346 auth_mask |= 1 << SSH_AUTH_TIS;
1349 if (options.gss_authentication)
1350 auth_mask |= 1 << SSH_AUTH_GSSAPI;
1353 if (options.password_authentication)
1354 auth_mask |= 1 << SSH_AUTH_PASSWORD;
1355 packet_put_int(auth_mask);
1357 /* Send the packet and wait for it to be sent. */
1359 packet_write_wait();
1361 debug("Sent %d bit server key and %d bit host key.",
1362 BN_num_bits(sensitive_data.server_key->rsa->n),
1363 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1365 /* Read clients reply (cipher type and session key). */
1366 packet_read_expect(SSH_CMSG_SESSION_KEY);
1368 /* Get cipher type and check whether we accept this. */
1369 cipher_type = packet_get_char();
1371 if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
1372 packet_disconnect("Warning: client selects unsupported cipher.");
1374 /* Get check bytes from the packet. These must match those we
1375 sent earlier with the public key packet. */
1376 for (i = 0; i < 8; i++)
1377 if (cookie[i] != packet_get_char())
1378 packet_disconnect("IP Spoofing check bytes do not match.");
1380 debug("Encryption type: %.200s", cipher_name(cipher_type));
1382 /* Get the encrypted integer. */
1383 if ((session_key_int = BN_new()) == NULL)
1384 fatal("do_ssh1_kex: BN_new failed");
1385 packet_get_bignum(session_key_int);
1387 protocol_flags = packet_get_int();
1388 packet_set_protocol_flags(protocol_flags);
1392 * Decrypt it using our private server key and private host key (key
1393 * with larger modulus first).
1395 if (BN_cmp(sensitive_data.server_key->rsa->n, sensitive_data.ssh1_host_key->rsa->n) > 0) {
1396 /* Server key has bigger modulus. */
1397 if (BN_num_bits(sensitive_data.server_key->rsa->n) <
1398 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1399 fatal("do_connection: %s: server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1400 get_remote_ipaddr(),
1401 BN_num_bits(sensitive_data.server_key->rsa->n),
1402 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1403 SSH_KEY_BITS_RESERVED);
1405 if (rsa_private_decrypt(session_key_int, session_key_int,
1406 sensitive_data.server_key->rsa) <= 0)
1408 if (rsa_private_decrypt(session_key_int, session_key_int,
1409 sensitive_data.ssh1_host_key->rsa) <= 0)
1412 /* Host key has bigger modulus (or they are equal). */
1413 if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
1414 BN_num_bits(sensitive_data.server_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1415 fatal("do_connection: %s: host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
1416 get_remote_ipaddr(),
1417 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1418 BN_num_bits(sensitive_data.server_key->rsa->n),
1419 SSH_KEY_BITS_RESERVED);
1421 if (rsa_private_decrypt(session_key_int, session_key_int,
1422 sensitive_data.ssh1_host_key->rsa) < 0)
1424 if (rsa_private_decrypt(session_key_int, session_key_int,
1425 sensitive_data.server_key->rsa) < 0)
1429 * Extract session key from the decrypted integer. The key is in the
1430 * least significant 256 bits of the integer; the first byte of the
1431 * key is in the highest bits.
1434 BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1435 len = BN_num_bytes(session_key_int);
1436 if (len < 0 || len > sizeof(session_key)) {
1437 error("do_connection: bad session key len from %s: "
1438 "session_key_int %d > sizeof(session_key) %lu",
1439 get_remote_ipaddr(), len, (u_long)sizeof(session_key));
1442 memset(session_key, 0, sizeof(session_key));
1443 BN_bn2bin(session_key_int,
1444 session_key + sizeof(session_key) - len);
1446 compute_session_id(session_id, cookie,
1447 sensitive_data.ssh1_host_key->rsa->n,
1448 sensitive_data.server_key->rsa->n);
1450 * Xor the first 16 bytes of the session key with the
1453 for (i = 0; i < 16; i++)
1454 session_key[i] ^= session_id[i];
1458 int bytes = BN_num_bytes(session_key_int);
1459 u_char *buf = xmalloc(bytes);
1462 log("do_connection: generating a fake encryption key");
1463 BN_bn2bin(session_key_int, buf);
1465 MD5_Update(&md, buf, bytes);
1466 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1467 MD5_Final(session_key, &md);
1469 MD5_Update(&md, session_key, 16);
1470 MD5_Update(&md, buf, bytes);
1471 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1472 MD5_Final(session_key + 16, &md);
1473 memset(buf, 0, bytes);
1475 for (i = 0; i < 16; i++)
1476 session_id[i] = session_key[i] ^ session_key[i + 16];
1481 * Before we destroy the host and server keys, hash them so we can
1482 * send the hash over to the client via a secure channel so that it
1488 unsigned char *data;
1489 unsigned int data_len;
1490 extern unsigned char ssh1_key_digest[]; /* in gss-serv.c */
1493 debug("Calculating MD5 hash of server and host keys...");
1495 /* Write all the keys to a temporary buffer */
1499 buffer_put_bignum(&buf, sensitive_data.server_key->rsa->e);
1500 buffer_put_bignum(&buf, sensitive_data.server_key->rsa->n);
1503 buffer_put_bignum(&buf, sensitive_data.ssh1_host_key->rsa->e);
1504 buffer_put_bignum(&buf, sensitive_data.ssh1_host_key->rsa->n);
1506 /* Get the resulting data */
1507 data = (unsigned char *) buffer_ptr(&buf);
1508 data_len = buffer_len(&buf);
1511 MD5_Init(&md5context);
1512 MD5_Update(&md5context, data, data_len);
1513 MD5_Final(ssh1_key_digest, &md5context);
1521 /* Destroy the private and public keys. They will no longer be needed. */
1522 destroy_sensitive_data();
1524 /* Destroy the decrypted integer. It is no longer needed. */
1525 BN_clear_free(session_key_int);
1527 /* Set the session key. From this on all communications will be encrypted. */
1528 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
1530 /* Destroy our copy of the session key. It is no longer needed. */
1531 memset(session_key, 0, sizeof(session_key));
1533 debug("Received session key; encryption turned on.");
1535 /* Send an acknowledgement packet. Note that this packet is sent encrypted. */
1536 packet_start(SSH_SMSG_SUCCESS);
1538 packet_write_wait();
1542 * SSH2 key exchange: diffie-hellman-group1-sha1
1549 if (options.ciphers != NULL) {
1550 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1551 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
1553 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1554 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
1555 myproposal[PROPOSAL_ENC_ALGS_STOC] =
1556 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
1558 if (options.macs != NULL) {
1559 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
1560 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
1562 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
1568 char *newstr = NULL;
1569 orig = myproposal[PROPOSAL_KEX_ALGS];
1571 /* If we don't have a host key, then all of the algorithms
1572 * currently in myproposal are useless */
1573 if (strlen(myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS])==0)
1576 if (options.gss_keyex)
1577 gss = ssh_gssapi_mechanisms(1,NULL);
1582 int len = strlen(orig) + strlen(gss) +2;
1583 newstr=xmalloc(len);
1584 snprintf(newstr,len,"%s,%s",gss,orig);
1590 /* If we've got GSSAPI mechanisms, then we've also got the 'null'
1591 host key algorithm, but we're not allowed to advertise it, unless
1592 its the only host key algorithm we're supporting */
1593 if (gss && (strlen(myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS])) == 0) {
1594 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS]="null";
1597 myproposal[PROPOSAL_KEX_ALGS]=newstr;
1599 fatal("No supported key exchange algorithms");
1603 /* start key exchange */
1604 kex = kex_setup(myproposal);
1606 kex->client_version_string=client_version_string;
1607 kex->server_version_string=server_version_string;
1608 kex->load_host_key=&get_hostkey_by_type;
1612 dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
1614 session_id2 = kex->session_id;
1615 session_id2_len = kex->session_id_len;
1618 /* send 1st encrypted/maced/compressed message */
1619 packet_start(SSH2_MSG_IGNORE);
1620 packet_put_cstring("markus");
1622 packet_write_wait();