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.132 2000/10/13 18:34:46 markus Exp $");
60 #include <openssl/dh.h>
61 #include <openssl/bn.h>
62 #include <openssl/hmac.h>
64 #include <openssl/dsa.h>
65 #include <openssl/rsa.h>
71 #include "myproposal.h"
77 int allow_severity = LOG_INFO;
78 int deny_severity = LOG_WARNING;
89 /* Server configuration options. */
90 ServerOptions options;
92 /* Name of the server configuration file. */
93 char *config_file_name = SERVER_CONFIG_FILE;
96 * Flag indicating whether IPv4 or IPv6. This can be set on the command line.
97 * Default value is AF_UNSPEC means both IPv4 and IPv6.
99 int IPv4or6 = AF_UNSPEC;
102 * Debug mode flag. This can be set on the command line. If debug
103 * mode is enabled, extra debugging output will be sent to the system
104 * log, the daemon will not go to background, and will exit after processing
105 * the first connection.
109 /* Flag indicating that the daemon is being started from inetd. */
112 /* debug goes to stderr unless inetd_flag is set */
115 /* argv[0] without path. */
118 /* Saved arguments to main(). */
122 * The sockets that the server is listening; this is used in the SIGHUP
125 #define MAX_LISTEN_SOCKS 16
126 int listen_socks[MAX_LISTEN_SOCKS];
127 int num_listen_socks = 0;
130 * the client's version string, passed by sshd2 in compat mode. if != NULL,
131 * sshd will skip the version-number exchange
133 char *client_version_string = NULL;
134 char *server_version_string = NULL;
137 * Any really sensitive data in the application is contained in this
138 * structure. The idea is that this structure could be locked into memory so
139 * that the pages do not get written into swap. However, there are some
140 * problems. The private key contains BIGNUMs, and we do not (in principle)
141 * have access to the internals of them, and locking just the structure is
142 * not very useful. Currently, memory locking is not implemented.
145 RSA *private_key; /* Private part of empheral server key. */
146 RSA *host_key; /* Private part of host key. */
147 Key *dsa_host_key; /* Private DSA host key. */
151 * Flag indicating whether the current session key has been used. This flag
152 * is set whenever the key is used, and cleared when the key is regenerated.
156 /* This is set to true when SIGHUP is received. */
157 int received_sighup = 0;
159 /* Public side of the server key. This value is regenerated regularly with
163 /* session identifier, used by RSA-auth */
164 unsigned char session_id[16];
167 unsigned char *session_id2 = NULL;
168 int session_id2_len = 0;
170 /* record remote hostname or ip */
171 unsigned int utmp_len = MAXHOSTNAMELEN;
173 /* Prototypes for various functions defined later in this file. */
177 void ssh_dh1_server(Kex *, Buffer *_kexinit, Buffer *);
178 void ssh_dhgex_server(Kex *, Buffer *_kexinit, Buffer *);
181 * Close all listening sockets
184 close_listen_socks(void)
187 for (i = 0; i < num_listen_socks; i++)
188 close(listen_socks[i]);
189 num_listen_socks = -1;
193 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
194 * the effect is to reread the configuration file (and to regenerate
198 sighup_handler(int sig)
201 signal(SIGHUP, sighup_handler);
205 * Called from the main program after receiving SIGHUP.
206 * Restarts the server.
211 log("Received SIGHUP; restarting.");
212 close_listen_socks();
213 execv(saved_argv[0], saved_argv);
214 execv("/proc/curproc/file", saved_argv);
215 log("RESTART FAILED: av0='%s', error: %s.", av0, strerror(errno));
220 * Generic signal handler for terminating signals in the master daemon.
221 * These close the listen socket; not closing it seems to cause "Address
222 * already in use" problems on some machines, which is inconvenient.
225 sigterm_handler(int sig)
227 log("Received signal %d; terminating.", sig);
228 close_listen_socks();
229 unlink(options.pid_file);
234 * SIGCHLD handler. This is called whenever a child dies. This will then
235 * reap any zombies left by exited c.
238 main_sigchld_handler(int sig)
240 int save_errno = errno;
243 while (waitpid(-1, &status, WNOHANG) > 0)
246 signal(SIGCHLD, main_sigchld_handler);
251 * Signal handler for the alarm after the login grace period has expired.
254 grace_alarm_handler(int sig)
256 /* Close the connection. */
259 /* Log error and exit. */
260 fatal("Timeout before authentication for %s.", get_remote_ipaddr());
264 * Signal handler for the key regeneration alarm. Note that this
265 * alarm only occurs in the daemon waiting for connections, and it does not
266 * do anything with the private key or random state before forking.
267 * Thus there should be no concurrency control/asynchronous execution
270 /* XXX do we really want this work to be done in a signal handler ? -m */
272 key_regeneration_alarm(int sig)
274 int save_errno = errno;
276 /* Check if we should generate a new key. */
278 /* This should really be done in the background. */
279 log("Generating new %d bit RSA key.", options.server_key_bits);
281 if (sensitive_data.private_key != NULL)
282 RSA_free(sensitive_data.private_key);
283 sensitive_data.private_key = RSA_new();
285 if (public_key != NULL)
286 RSA_free(public_key);
287 public_key = RSA_new();
289 rsa_generate_key(sensitive_data.private_key, public_key,
290 options.server_key_bits);
293 log("RSA key generation complete.");
295 /* Reschedule the alarm. */
296 signal(SIGALRM, key_regeneration_alarm);
297 alarm(options.key_regeneration_time);
302 sshd_exchange_identification(int sock_in, int sock_out)
305 int remote_major, remote_minor;
308 char buf[256]; /* Must not be larger than remote_version. */
309 char remote_version[256]; /* Must be at least as big as buf. */
311 if ((options.protocol & SSH_PROTO_1) &&
312 (options.protocol & SSH_PROTO_2)) {
313 major = PROTOCOL_MAJOR_1;
315 } else if (options.protocol & SSH_PROTO_2) {
316 major = PROTOCOL_MAJOR_2;
317 minor = PROTOCOL_MINOR_2;
319 major = PROTOCOL_MAJOR_1;
320 minor = PROTOCOL_MINOR_1;
322 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", major, minor, SSH_VERSION);
323 server_version_string = xstrdup(buf);
325 if (client_version_string == NULL) {
326 /* Send our protocol version identification. */
327 if (atomicio(write, sock_out, server_version_string, strlen(server_version_string))
328 != strlen(server_version_string)) {
329 log("Could not write ident string to %s.", get_remote_ipaddr());
333 /* Read other side\'s version identification. */
334 for (i = 0; i < sizeof(buf) - 1; i++) {
335 if (atomicio(read, sock_in, &buf[i], 1) != 1) {
336 log("Did not receive ident string from %s.", get_remote_ipaddr());
339 if (buf[i] == '\r') {
342 /* Kludge for F-Secure Macintosh < 1.0.2 */
344 strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
348 if (buf[i] == '\n') {
354 buf[sizeof(buf) - 1] = 0;
355 client_version_string = xstrdup(buf);
359 * Check that the versions match. In future this might accept
360 * several versions and set appropriate flags to handle them.
362 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
363 &remote_major, &remote_minor, remote_version) != 3) {
364 s = "Protocol mismatch.\n";
365 (void) atomicio(write, sock_out, s, strlen(s));
368 log("Bad protocol version identification '%.100s' from %s",
369 client_version_string, get_remote_ipaddr());
372 debug("Client protocol version %d.%d; client software version %.100s",
373 remote_major, remote_minor, remote_version);
375 compat_datafellows(remote_version);
378 switch(remote_major) {
380 if (remote_minor == 99) {
381 if (options.protocol & SSH_PROTO_2)
387 if (!(options.protocol & SSH_PROTO_1)) {
391 if (remote_minor < 3) {
392 packet_disconnect("Your ssh version is too old and "
393 "is no longer supported. Please install a newer version.");
394 } else if (remote_minor == 3) {
395 /* note that this disables agent-forwarding */
400 if (options.protocol & SSH_PROTO_2) {
409 chop(server_version_string);
410 chop(client_version_string);
411 debug("Local version string %.200s", server_version_string);
414 s = "Protocol major versions differ.\n";
415 (void) atomicio(write, sock_out, s, strlen(s));
418 log("Protocol major versions differ for %s: %.200s vs. %.200s",
420 server_version_string, client_version_string);
424 packet_set_ssh2_format();
429 destroy_sensitive_data(void)
431 /* Destroy the private and public keys. They will no longer be needed. */
433 RSA_free(public_key);
434 if (sensitive_data.private_key)
435 RSA_free(sensitive_data.private_key);
436 if (sensitive_data.host_key)
437 RSA_free(sensitive_data.host_key);
438 if (sensitive_data.dsa_host_key != NULL)
439 key_free(sensitive_data.dsa_host_key);
443 * returns 1 if connection should be dropped, 0 otherwise.
444 * dropping starts at connection #max_startups_begin with a probability
445 * of (max_startups_rate/100). the probability increases linearly until
446 * all connections are dropped for startups > max_startups
449 drop_connection(int startups)
453 if (startups < options.max_startups_begin)
455 if (startups >= options.max_startups)
457 if (options.max_startups_rate == 100)
460 p = 100 - options.max_startups_rate;
461 p *= startups - options.max_startups_begin;
462 p /= (double) (options.max_startups - options.max_startups_begin);
463 p += options.max_startups_rate;
465 r = arc4random() / (double) UINT_MAX;
467 debug("drop_connection: p %g, r %g", p, r);
468 return (r < p) ? 1 : 0;
471 int *startup_pipes = NULL; /* options.max_startup sized array of fd ints */
472 int startup_pipe; /* in child */
475 * Main program for the daemon.
478 main(int ac, char **av)
482 int opt, sock_in = 0, sock_out = 0, newsock, j, i, fdsetsz, on = 1;
487 struct sockaddr_storage from;
488 const char *remote_ip;
491 struct linger linger;
493 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
494 int listen_sock, maxfd;
500 if (strchr(av[0], '/'))
501 av0 = strrchr(av[0], '/') + 1;
505 /* Initialize configuration options to their default values. */
506 initialize_server_options(&options);
508 /* Parse command-line arguments. */
509 while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:u:diqQ46")) != EOF) {
518 config_file_name = optarg;
521 if (0 == debug_flag) {
523 options.log_level = SYSLOG_LEVEL_DEBUG1;
524 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
527 fprintf(stderr, "Too high debugging level.\n");
538 options.log_level = SYSLOG_LEVEL_QUIET;
541 options.server_key_bits = atoi(optarg);
544 options.ports_from_cmdline = 1;
545 if (options.num_ports >= MAX_PORTS) {
546 fprintf(stderr, "too many ports.\n");
549 options.ports[options.num_ports++] = atoi(optarg);
552 options.login_grace_time = atoi(optarg);
555 options.key_regeneration_time = atoi(optarg);
558 options.host_key_file = optarg;
561 client_version_string = optarg;
562 /* only makes sense with inetd_flag, i.e. no listen() */
566 utmp_len = atoi(optarg);
570 fprintf(stderr, "sshd version %s\n", SSH_VERSION);
571 fprintf(stderr, "Usage: %s [options]\n", av0);
572 fprintf(stderr, "Options:\n");
573 fprintf(stderr, " -f file Configuration file (default %s)\n", SERVER_CONFIG_FILE);
574 fprintf(stderr, " -d Debugging mode (multiple -d means more debugging)\n");
575 fprintf(stderr, " -i Started from inetd\n");
576 fprintf(stderr, " -q Quiet (no logging)\n");
577 fprintf(stderr, " -p port Listen on the specified port (default: 22)\n");
578 fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n");
579 fprintf(stderr, " -g seconds Grace period for authentication (default: 300)\n");
580 fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n");
581 fprintf(stderr, " -h file File from which to read host key (default: %s)\n",
583 fprintf(stderr, " -u len Maximum hostname length for utmp recording\n");
584 fprintf(stderr, " -4 Use IPv4 only\n");
585 fprintf(stderr, " -6 Use IPv6 only\n");
591 * Force logging to stderr until we have loaded the private host
592 * key (unless started from inetd)
595 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
596 options.log_facility == -1 ? SYSLOG_FACILITY_AUTH : options.log_facility,
597 !silent && !inetd_flag);
599 /* Read server configuration options from the configuration file. */
600 read_server_config(&options, config_file_name);
602 /* Fill in default values for those options not explicitly set. */
603 fill_default_server_options(&options);
605 /* Check that there are no remaining arguments. */
607 fprintf(stderr, "Extra argument %s.\n", av[optind]);
611 debug("sshd version %.100s", SSH_VERSION);
613 sensitive_data.dsa_host_key = NULL;
614 sensitive_data.host_key = NULL;
616 /* check if RSA support exists */
617 if ((options.protocol & SSH_PROTO_1) &&
619 log("no RSA support in libssl and libcrypto. See ssl(8)");
620 log("Disabling protocol version 1");
621 options.protocol &= ~SSH_PROTO_1;
623 /* Load the RSA/DSA host key. It must have empty passphrase. */
624 if (options.protocol & SSH_PROTO_1) {
626 sensitive_data.host_key = RSA_new();
628 k.rsa = sensitive_data.host_key;
630 if (!load_private_key(options.host_key_file, "", &k, NULL)) {
631 error("Could not load host key: %.200s: %.100s",
632 options.host_key_file, strerror(errno));
633 log("Disabling protocol version 1");
634 options.protocol &= ~SSH_PROTO_1;
638 if (options.protocol & SSH_PROTO_2) {
639 sensitive_data.dsa_host_key = key_new(KEY_DSA);
640 if (!load_private_key(options.host_dsa_key_file, "", sensitive_data.dsa_host_key, NULL)) {
642 error("Could not load DSA host key: %.200s", options.host_dsa_key_file);
643 log("Disabling protocol version 2");
644 options.protocol &= ~SSH_PROTO_2;
647 if (! options.protocol & (SSH_PROTO_1|SSH_PROTO_2)) {
649 fprintf(stderr, "sshd: no hostkeys available -- exiting.\n");
650 log("sshd: no hostkeys available -- exiting.\n");
654 /* Check certain values for sanity. */
655 if (options.protocol & SSH_PROTO_1) {
656 if (options.server_key_bits < 512 ||
657 options.server_key_bits > 32768) {
658 fprintf(stderr, "Bad server key size.\n");
662 * Check that server and host key lengths differ sufficiently. This
663 * is necessary to make double encryption work with rsaref. Oh, I
664 * hate software patents. I dont know if this can go? Niels
666 if (options.server_key_bits >
667 BN_num_bits(sensitive_data.host_key->n) - SSH_KEY_BITS_RESERVED &&
668 options.server_key_bits <
669 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
670 options.server_key_bits =
671 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED;
672 debug("Forcing server key to %d bits to make it differ from host key.",
673 options.server_key_bits);
677 /* Initialize the log (it is reinitialized below in case we forked). */
678 if (debug_flag && !inetd_flag)
680 log_init(av0, options.log_level, options.log_facility, log_stderr);
683 * If not in debugging mode, and not started from inetd, disconnect
684 * from the controlling terminal, and fork. The original process
687 if (!debug_flag && !inetd_flag) {
690 #endif /* TIOCNOTTY */
691 if (daemon(0, 0) < 0)
692 fatal("daemon() failed: %.200s", strerror(errno));
694 /* Disconnect from the controlling tty. */
696 fd = open("/dev/tty", O_RDWR | O_NOCTTY);
698 (void) ioctl(fd, TIOCNOTTY, NULL);
701 #endif /* TIOCNOTTY */
703 /* Reinitialize the log (because of the fork above). */
704 log_init(av0, options.log_level, options.log_facility, log_stderr);
706 /* Do not display messages to stdout in RSA code. */
709 /* Initialize the random number generator. */
712 /* Chdir to the root directory so that the current disk can be
713 unmounted if desired. */
716 /* Start listening for a socket, unless started from inetd. */
719 s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */
725 * We intentionally do not close the descriptors 0, 1, and 2
726 * as our code for setting the descriptors won\'t work if
727 * ttyfd happens to be one of those.
729 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
731 if (options.protocol & SSH_PROTO_1) {
732 public_key = RSA_new();
733 sensitive_data.private_key = RSA_new();
734 log("Generating %d bit RSA key.", options.server_key_bits);
735 rsa_generate_key(sensitive_data.private_key, public_key,
736 options.server_key_bits);
738 log("RSA key generation complete.");
741 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
742 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
744 if (num_listen_socks >= MAX_LISTEN_SOCKS)
745 fatal("Too many listen sockets. "
746 "Enlarge MAX_LISTEN_SOCKS");
747 if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
748 ntop, sizeof(ntop), strport, sizeof(strport),
749 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
750 error("getnameinfo failed");
753 /* Create socket for listening. */
754 listen_sock = socket(ai->ai_family, SOCK_STREAM, 0);
755 if (listen_sock < 0) {
756 /* kernel may not support ipv6 */
757 verbose("socket: %.100s", strerror(errno));
760 if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) {
761 error("listen_sock O_NONBLOCK: %s", strerror(errno));
766 * Set socket options. We try to make the port
767 * reusable and have it close as fast as possible
768 * without waiting in unnecessary wait states on
771 setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
772 (void *) &on, sizeof(on));
775 setsockopt(listen_sock, SOL_SOCKET, SO_LINGER,
776 (void *) &linger, sizeof(linger));
778 debug("Bind to port %s on %s.", strport, ntop);
780 /* Bind the socket to the desired port. */
781 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
782 error("Bind to port %s on %s failed: %.200s.",
783 strport, ntop, strerror(errno));
787 listen_socks[num_listen_socks] = listen_sock;
790 /* Start listening on the port. */
791 log("Server listening on %s port %s.", ntop, strport);
792 if (listen(listen_sock, 5) < 0)
793 fatal("listen: %.100s", strerror(errno));
796 freeaddrinfo(options.listen_addrs);
798 if (!num_listen_socks)
799 fatal("Cannot bind any address.");
803 * Record our pid in /etc/sshd_pid to make it easier
804 * to kill the correct sshd. We don\'t want to do
805 * this before the bind above because the bind will
806 * fail if there already is a daemon, and this will
807 * overwrite any old pid in the file.
809 f = fopen(options.pid_file, "w");
811 fprintf(f, "%u\n", (unsigned int) getpid());
815 if (options.protocol & SSH_PROTO_1) {
816 public_key = RSA_new();
817 sensitive_data.private_key = RSA_new();
819 log("Generating %d bit RSA key.", options.server_key_bits);
820 rsa_generate_key(sensitive_data.private_key, public_key,
821 options.server_key_bits);
823 log("RSA key generation complete.");
825 /* Schedule server key regeneration alarm. */
826 signal(SIGALRM, key_regeneration_alarm);
827 alarm(options.key_regeneration_time);
830 /* Arrange to restart on SIGHUP. The handler needs listen_sock. */
831 signal(SIGHUP, sighup_handler);
833 signal(SIGTERM, sigterm_handler);
834 signal(SIGQUIT, sigterm_handler);
836 /* Arrange SIGCHLD to be caught. */
837 signal(SIGCHLD, main_sigchld_handler);
839 /* setup fd set for listen */
842 for (i = 0; i < num_listen_socks; i++)
843 if (listen_socks[i] > maxfd)
844 maxfd = listen_socks[i];
845 /* pipes connected to unauthenticated childs */
846 startup_pipes = xmalloc(options.max_startups * sizeof(int));
847 for (i = 0; i < options.max_startups; i++)
848 startup_pipes[i] = -1;
851 * Stay listening for connections until the system crashes or
852 * the daemon is killed with a signal.
859 fdsetsz = howmany(maxfd, NFDBITS) * sizeof(fd_mask);
860 fdset = (fd_set *)xmalloc(fdsetsz);
861 memset(fdset, 0, fdsetsz);
863 for (i = 0; i < num_listen_socks; i++)
864 FD_SET(listen_socks[i], fdset);
865 for (i = 0; i < options.max_startups; i++)
866 if (startup_pipes[i] != -1)
867 FD_SET(startup_pipes[i], fdset);
869 /* Wait in select until there is a connection. */
870 if (select(maxfd + 1, fdset, NULL, NULL, NULL) < 0) {
872 error("select: %.100s", strerror(errno));
875 for (i = 0; i < options.max_startups; i++)
876 if (startup_pipes[i] != -1 &&
877 FD_ISSET(startup_pipes[i], fdset)) {
879 * the read end of the pipe is ready
880 * if the child has closed the pipe
881 * after successfull authentication
882 * or if the child has died
884 close(startup_pipes[i]);
885 startup_pipes[i] = -1;
888 for (i = 0; i < num_listen_socks; i++) {
889 if (!FD_ISSET(listen_socks[i], fdset))
891 fromlen = sizeof(from);
892 newsock = accept(listen_socks[i], (struct sockaddr *)&from,
895 if (errno != EINTR && errno != EWOULDBLOCK)
896 error("accept: %.100s", strerror(errno));
899 if (fcntl(newsock, F_SETFL, 0) < 0) {
900 error("newsock del O_NONBLOCK: %s", strerror(errno));
903 if (drop_connection(startups) == 1) {
904 debug("drop connection #%d", startups);
908 if (pipe(startup_p) == -1) {
913 for (j = 0; j < options.max_startups; j++)
914 if (startup_pipes[j] == -1) {
915 startup_pipes[j] = startup_p[0];
916 if (maxfd < startup_p[0])
917 maxfd = startup_p[0];
924 * Got connection. Fork a child to handle it, unless
925 * we are in debugging mode.
929 * In debugging mode. Close the listening
930 * socket, and start processing the
931 * connection without forking.
933 debug("Server will not fork when running in debugging mode.");
934 close_listen_socks();
942 * Normal production daemon. Fork, and have
943 * the child process the connection. The
944 * parent continues listening.
946 if ((pid = fork()) == 0) {
948 * Child. Close the listening and max_startup
949 * sockets. Start using the accepted socket.
950 * Reinitialize logging (since our pid has
951 * changed). We break out of the loop to handle
954 startup_pipe = startup_p[1];
955 for (j = 0; j < options.max_startups; j++)
956 if (startup_pipes[j] != -1)
957 close(startup_pipes[j]);
958 close_listen_socks();
961 log_init(av0, options.log_level, options.log_facility, log_stderr);
966 /* Parent. Stay in the loop. */
968 error("fork: %.100s", strerror(errno));
970 debug("Forked child %d.", pid);
974 /* Mark that the key has been used (it was "given" to the child). */
979 /* Close the new socket (the child is now taking care of it). */
982 /* child process check (or debug mode) */
983 if (num_listen_socks < 0)
988 /* This is the child processing a new connection. */
991 * Disable the key regeneration alarm. We will not regenerate the
992 * key since we are no longer in a position to give it to anyone. We
993 * will not restart on SIGHUP since it no longer makes sense.
996 signal(SIGALRM, SIG_DFL);
997 signal(SIGHUP, SIG_DFL);
998 signal(SIGTERM, SIG_DFL);
999 signal(SIGQUIT, SIG_DFL);
1000 signal(SIGCHLD, SIG_DFL);
1001 signal(SIGPIPE, SIG_IGN);
1004 * Set socket options for the connection. We want the socket to
1005 * close as fast as possible without waiting for anything. If the
1006 * connection is not a socket, these will do nothing.
1008 /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
1010 linger.l_linger = 5;
1011 setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
1014 * Register our connection. This turns encryption off because we do
1017 packet_set_connection(sock_in, sock_out);
1019 remote_port = get_remote_port();
1020 remote_ip = get_remote_ipaddr();
1022 /* Check whether logins are denied from this host. */
1025 struct request_info req;
1027 request_init(&req, RQ_DAEMON, av0, RQ_FILE, sock_in, NULL);
1030 if (!hosts_access(&req)) {
1035 verbose("Connection from %.500s port %d", eval_client(&req), remote_port);
1037 #endif /* LIBWRAP */
1038 /* Log the connection. */
1039 verbose("Connection from %.500s port %d", remote_ip, remote_port);
1042 * We don\'t want to listen forever unless the other side
1043 * successfully authenticates itself. So we set up an alarm which is
1044 * cleared after successful authentication. A limit of zero
1045 * indicates no limit. Note that we don\'t set the alarm in debugging
1046 * mode; it is just annoying to have the server exit just when you
1047 * are about to discover the bug.
1049 signal(SIGALRM, grace_alarm_handler);
1051 alarm(options.login_grace_time);
1053 sshd_exchange_identification(sock_in, sock_out);
1055 * Check that the connection comes from a privileged port. Rhosts-
1056 * and Rhosts-RSA-Authentication only make sense from priviledged
1057 * programs. Of course, if the intruder has root access on his local
1058 * machine, he can connect from any port. So do not use these
1059 * authentication methods from machines that you do not trust.
1061 if (remote_port >= IPPORT_RESERVED ||
1062 remote_port < IPPORT_RESERVED / 2) {
1063 options.rhosts_authentication = 0;
1064 options.rhosts_rsa_authentication = 0;
1067 if (!packet_connection_is_ipv4() &&
1068 options.krb4_authentication) {
1069 debug("Kerberos Authentication disabled, only available for IPv4.");
1070 options.krb4_authentication = 0;
1074 packet_set_nonblocking();
1076 /* perform the key exchange */
1077 /* authenticate user and start session */
1080 do_authentication2();
1083 do_authentication();
1087 /* Cleanup user's ticket cache file. */
1088 if (options.krb4_ticket_cleanup)
1092 /* The connection has been terminated. */
1093 verbose("Closing connection to %.100s", remote_ip);
1097 #endif /* USE_PAM */
1112 BIGNUM *session_key_int;
1113 unsigned char session_key[SSH_SESSION_KEY_LENGTH];
1114 unsigned char cookie[8];
1115 unsigned int cipher_type, auth_mask, protocol_flags;
1119 * Generate check bytes that the client must send back in the user
1120 * packet in order for it to be accepted; this is used to defy ip
1121 * spoofing attacks. Note that this only works against somebody
1122 * doing IP spoofing from a remote machine; any machine on the local
1123 * network can still see outgoing packets and catch the random
1124 * cookie. This only affects rhosts authentication, and this is one
1125 * of the reasons why it is inherently insecure.
1127 for (i = 0; i < 8; i++) {
1129 rand = arc4random();
1130 cookie[i] = rand & 0xff;
1135 * Send our public key. We include in the packet 64 bits of random
1136 * data that must be matched in the reply in order to prevent IP
1139 packet_start(SSH_SMSG_PUBLIC_KEY);
1140 for (i = 0; i < 8; i++)
1141 packet_put_char(cookie[i]);
1143 /* Store our public server RSA key. */
1144 packet_put_int(BN_num_bits(public_key->n));
1145 packet_put_bignum(public_key->e);
1146 packet_put_bignum(public_key->n);
1148 /* Store our public host RSA key. */
1149 packet_put_int(BN_num_bits(sensitive_data.host_key->n));
1150 packet_put_bignum(sensitive_data.host_key->e);
1151 packet_put_bignum(sensitive_data.host_key->n);
1153 /* Put protocol flags. */
1154 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
1156 /* Declare which ciphers we support. */
1157 packet_put_int(cipher_mask_ssh1(0));
1159 /* Declare supported authentication types. */
1161 if (options.rhosts_authentication)
1162 auth_mask |= 1 << SSH_AUTH_RHOSTS;
1163 if (options.rhosts_rsa_authentication)
1164 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
1165 if (options.rsa_authentication)
1166 auth_mask |= 1 << SSH_AUTH_RSA;
1168 if (options.krb4_authentication)
1169 auth_mask |= 1 << SSH_AUTH_KRB4;
1172 if (options.krb5_authentication) {
1173 auth_mask |= 1 << SSH_AUTH_KRB5;
1174 /* compatibility with MetaCentre ssh */
1175 auth_mask |= 1 << SSH_AUTH_KRB4;
1177 if (options.krb5_tgt_passing)
1178 auth_mask |= 1 << SSH_PASS_KRB5_TGT;
1182 if (options.krb4_tgt_passing)
1183 auth_mask |= 1 << SSH_PASS_KRB4_TGT;
1184 if (options.afs_token_passing)
1185 auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
1188 if (options.skey_authentication == 1)
1189 auth_mask |= 1 << SSH_AUTH_TIS;
1191 if (options.password_authentication)
1192 auth_mask |= 1 << SSH_AUTH_PASSWORD;
1193 packet_put_int(auth_mask);
1195 /* Send the packet and wait for it to be sent. */
1197 packet_write_wait();
1199 debug("Sent %d bit public key and %d bit host key.",
1200 BN_num_bits(public_key->n), BN_num_bits(sensitive_data.host_key->n));
1202 /* Read clients reply (cipher type and session key). */
1203 packet_read_expect(&plen, SSH_CMSG_SESSION_KEY);
1205 /* Get cipher type and check whether we accept this. */
1206 cipher_type = packet_get_char();
1208 if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
1209 packet_disconnect("Warning: client selects unsupported cipher.");
1211 /* Get check bytes from the packet. These must match those we
1212 sent earlier with the public key packet. */
1213 for (i = 0; i < 8; i++)
1214 if (cookie[i] != packet_get_char())
1215 packet_disconnect("IP Spoofing check bytes do not match.");
1217 debug("Encryption type: %.200s", cipher_name(cipher_type));
1219 /* Get the encrypted integer. */
1220 session_key_int = BN_new();
1221 packet_get_bignum(session_key_int, &slen);
1223 protocol_flags = packet_get_int();
1224 packet_set_protocol_flags(protocol_flags);
1226 packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY);
1229 * Decrypt it using our private server key and private host key (key
1230 * with larger modulus first).
1232 if (BN_cmp(sensitive_data.private_key->n, sensitive_data.host_key->n) > 0) {
1233 /* Server key has bigger modulus. */
1234 if (BN_num_bits(sensitive_data.private_key->n) <
1235 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
1236 fatal("do_connection: %s: private_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1237 get_remote_ipaddr(),
1238 BN_num_bits(sensitive_data.private_key->n),
1239 BN_num_bits(sensitive_data.host_key->n),
1240 SSH_KEY_BITS_RESERVED);
1242 if (rsa_private_decrypt(session_key_int, session_key_int,
1243 sensitive_data.private_key) <= 0)
1245 if (rsa_private_decrypt(session_key_int, session_key_int,
1246 sensitive_data.host_key) <= 0)
1249 /* Host key has bigger modulus (or they are equal). */
1250 if (BN_num_bits(sensitive_data.host_key->n) <
1251 BN_num_bits(sensitive_data.private_key->n) + SSH_KEY_BITS_RESERVED) {
1252 fatal("do_connection: %s: host_key %d < private_key %d + SSH_KEY_BITS_RESERVED %d",
1253 get_remote_ipaddr(),
1254 BN_num_bits(sensitive_data.host_key->n),
1255 BN_num_bits(sensitive_data.private_key->n),
1256 SSH_KEY_BITS_RESERVED);
1258 if (rsa_private_decrypt(session_key_int, session_key_int,
1259 sensitive_data.host_key) < 0)
1261 if (rsa_private_decrypt(session_key_int, session_key_int,
1262 sensitive_data.private_key) < 0)
1266 compute_session_id(session_id, cookie,
1267 sensitive_data.host_key->n,
1268 sensitive_data.private_key->n);
1270 /* Destroy the private and public keys. They will no longer be needed. */
1271 destroy_sensitive_data();
1274 * Extract session key from the decrypted integer. The key is in the
1275 * least significant 256 bits of the integer; the first byte of the
1276 * key is in the highest bits.
1279 BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1280 len = BN_num_bytes(session_key_int);
1281 if (len < 0 || len > sizeof(session_key)) {
1282 error("do_connection: bad session key len from %s: "
1283 "session_key_int %d > sizeof(session_key) %d",
1284 get_remote_ipaddr(), len, sizeof(session_key));
1287 memset(session_key, 0, sizeof(session_key));
1288 BN_bn2bin(session_key_int,
1289 session_key + sizeof(session_key) - len);
1293 log("do_connection: generating a fake encryption key");
1294 for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
1296 rand = arc4random();
1297 session_key[i] = rand & 0xff;
1302 /* Destroy the decrypted integer. It is no longer needed. */
1303 BN_clear_free(session_key_int);
1305 /* Xor the first 16 bytes of the session key with the session id. */
1306 for (i = 0; i < 16; i++)
1307 session_key[i] ^= session_id[i];
1309 /* Set the session key. From this on all communications will be encrypted. */
1310 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
1312 /* Destroy our copy of the session key. It is no longer needed. */
1313 memset(session_key, 0, sizeof(session_key));
1315 debug("Received session key; encryption turned on.");
1317 /* Send an acknowledgement packet. Note that this packet is sent encrypted. */
1318 packet_start(SSH_SMSG_SUCCESS);
1320 packet_write_wait();
1324 * SSH2 key exchange: diffie-hellman-group1-sha1
1329 Buffer *server_kexinit;
1330 Buffer *client_kexinit;
1334 char *cprop[PROPOSAL_MAX];
1338 if (options.ciphers != NULL) {
1339 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1340 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
1342 server_kexinit = kex_init(myproposal);
1343 client_kexinit = xmalloc(sizeof(*client_kexinit));
1344 buffer_init(client_kexinit);
1346 /* algorithm negotiation */
1347 kex_exchange_kexinit(server_kexinit, client_kexinit, cprop);
1348 kex = kex_choose_conf(cprop, myproposal, 1);
1349 for (i = 0; i < PROPOSAL_MAX; i++)
1352 switch (kex->kex_type) {
1354 ssh_dh1_server(kex, client_kexinit, server_kexinit);
1357 ssh_dhgex_server(kex, client_kexinit, server_kexinit);
1360 fatal("Unsupported key exchange %d", kex->kex_type);
1363 debug("send SSH2_MSG_NEWKEYS.");
1364 packet_start(SSH2_MSG_NEWKEYS);
1366 packet_write_wait();
1367 debug("done: send SSH2_MSG_NEWKEYS.");
1369 debug("Wait SSH2_MSG_NEWKEYS.");
1370 packet_read_expect(&payload_len, SSH2_MSG_NEWKEYS);
1371 debug("GOT SSH2_MSG_NEWKEYS.");
1374 /* send 1st encrypted/maced/compressed message */
1375 packet_start(SSH2_MSG_IGNORE);
1376 packet_put_cstring("markus");
1378 packet_write_wait();
1381 debug("done: KEX2.");
1388 /* diffie-hellman-group1-sha1 */
1391 ssh_dh1_server(Kex *kex, Buffer *client_kexinit, Buffer *server_kexinit)
1396 int payload_len, dlen;
1398 unsigned char *signature = NULL;
1399 unsigned char *server_host_key_blob = NULL;
1400 unsigned int sbloblen;
1401 unsigned int klen, kout;
1402 unsigned char *kbuf;
1403 unsigned char *hash;
1404 BIGNUM *shared_secret = 0;
1406 BIGNUM *dh_client_pub = 0;
1409 debug("Wait SSH2_MSG_KEXDH_INIT.");
1410 packet_read_expect(&payload_len, SSH2_MSG_KEXDH_INIT);
1413 dh_client_pub = BN_new();
1414 if (dh_client_pub == NULL)
1415 fatal("dh_client_pub == NULL");
1416 packet_get_bignum2(dh_client_pub, &dlen);
1419 fprintf(stderr, "\ndh_client_pub= ");
1420 BN_print_fp(stderr, dh_client_pub);
1421 fprintf(stderr, "\n");
1422 debug("bits %d", BN_num_bits(dh_client_pub));
1425 /* generate DH key */
1426 dh = dh_new_group1(); /* XXX depends on 'kex' */
1429 fprintf(stderr, "\np= ");
1430 BN_print_fp(stderr, dh->p);
1431 fprintf(stderr, "\ng= ");
1433 fprintf(stderr, "\npub= ");
1434 BN_print_fp(stderr, dh->pub_key);
1435 fprintf(stderr, "\n");
1436 DHparams_print_fp(stderr, dh);
1438 if (!dh_pub_is_valid(dh, dh_client_pub))
1439 packet_disconnect("bad client public DH value");
1442 kbuf = xmalloc(klen);
1443 kout = DH_compute_key(kbuf, dh_client_pub, dh);
1446 debug("shared secret: len %d/%d", klen, kout);
1447 fprintf(stderr, "shared secret == ");
1448 for (i = 0; i< kout; i++)
1449 fprintf(stderr, "%02x", (kbuf[i])&0xff);
1450 fprintf(stderr, "\n");
1452 shared_secret = BN_new();
1454 BN_bin2bn(kbuf, kout, shared_secret);
1455 memset(kbuf, 0, klen);
1458 /* XXX precompute? */
1459 dsa_make_key_blob(sensitive_data.dsa_host_key,
1460 &server_host_key_blob, &sbloblen);
1462 /* calc H */ /* XXX depends on 'kex' */
1464 client_version_string,
1465 server_version_string,
1466 buffer_ptr(client_kexinit), buffer_len(client_kexinit),
1467 buffer_ptr(server_kexinit), buffer_len(server_kexinit),
1468 (char *)server_host_key_blob, sbloblen,
1473 buffer_free(client_kexinit);
1474 buffer_free(server_kexinit);
1475 xfree(client_kexinit);
1476 xfree(server_kexinit);
1478 fprintf(stderr, "hash == ");
1479 for (i = 0; i< 20; i++)
1480 fprintf(stderr, "%02x", (hash[i])&0xff);
1481 fprintf(stderr, "\n");
1483 /* save session id := H */
1484 /* XXX hashlen depends on KEX */
1485 session_id2_len = 20;
1486 session_id2 = xmalloc(session_id2_len);
1487 memcpy(session_id2, hash, session_id2_len);
1490 /* XXX hashlen depends on KEX */
1491 dsa_sign(sensitive_data.dsa_host_key, &signature, &slen, hash, 20);
1493 destroy_sensitive_data();
1495 /* send server hostkey, DH pubkey 'f' and singed H */
1496 packet_start(SSH2_MSG_KEXDH_REPLY);
1497 packet_put_string((char *)server_host_key_blob, sbloblen);
1498 packet_put_bignum2(dh->pub_key); /* f */
1499 packet_put_string((char *)signature, slen);
1502 xfree(server_host_key_blob);
1503 packet_write_wait();
1505 kex_derive_keys(kex, hash, shared_secret);
1506 packet_set_kex(kex);
1508 /* have keys, free DH */
1512 /* diffie-hellman-group-exchange-sha1 */
1515 ssh_dhgex_server(Kex *kex, Buffer *client_kexinit, Buffer *server_kexinit)
1520 int payload_len, dlen;
1522 unsigned char *signature = NULL;
1523 unsigned char *server_host_key_blob = NULL;
1524 unsigned int sbloblen;
1525 unsigned int klen, kout;
1526 unsigned char *kbuf;
1527 unsigned char *hash;
1528 BIGNUM *shared_secret = 0;
1530 BIGNUM *dh_client_pub = 0;
1533 debug("Wait SSH2_MSG_KEX_DH_GEX_REQUEST.");
1534 packet_read_expect(&payload_len, SSH2_MSG_KEX_DH_GEX_REQUEST);
1535 nbits = packet_get_int();
1536 dh = choose_dh(nbits);
1538 debug("Sending SSH2_MSG_KEX_DH_GEX_GROUP.");
1539 packet_start(SSH2_MSG_KEX_DH_GEX_GROUP);
1540 packet_put_bignum2(dh->p);
1541 packet_put_bignum2(dh->g);
1543 packet_write_wait();
1545 debug("Wait SSH2_MSG_KEX_DH_GEX_INIT.");
1546 packet_read_expect(&payload_len, SSH2_MSG_KEX_DH_GEX_INIT);
1549 dh_client_pub = BN_new();
1550 if (dh_client_pub == NULL)
1551 fatal("dh_client_pub == NULL");
1552 packet_get_bignum2(dh_client_pub, &dlen);
1555 fprintf(stderr, "\ndh_client_pub= ");
1556 BN_print_fp(stderr, dh_client_pub);
1557 fprintf(stderr, "\n");
1558 debug("bits %d", BN_num_bits(dh_client_pub));
1562 fprintf(stderr, "\np= ");
1563 BN_print_fp(stderr, dh->p);
1564 fprintf(stderr, "\ng= ");
1566 fprintf(stderr, "\npub= ");
1567 BN_print_fp(stderr, dh->pub_key);
1568 fprintf(stderr, "\n");
1569 DHparams_print_fp(stderr, dh);
1571 if (!dh_pub_is_valid(dh, dh_client_pub))
1572 packet_disconnect("bad client public DH value");
1575 kbuf = xmalloc(klen);
1576 kout = DH_compute_key(kbuf, dh_client_pub, dh);
1579 debug("shared secret: len %d/%d", klen, kout);
1580 fprintf(stderr, "shared secret == ");
1581 for (i = 0; i< kout; i++)
1582 fprintf(stderr, "%02x", (kbuf[i])&0xff);
1583 fprintf(stderr, "\n");
1585 shared_secret = BN_new();
1587 BN_bin2bn(kbuf, kout, shared_secret);
1588 memset(kbuf, 0, klen);
1591 /* XXX precompute? */
1592 dsa_make_key_blob(sensitive_data.dsa_host_key,
1593 &server_host_key_blob, &sbloblen);
1595 /* calc H */ /* XXX depends on 'kex' */
1596 hash = kex_hash_gex(
1597 client_version_string,
1598 server_version_string,
1599 buffer_ptr(client_kexinit), buffer_len(client_kexinit),
1600 buffer_ptr(server_kexinit), buffer_len(server_kexinit),
1601 (char *)server_host_key_blob, sbloblen,
1602 nbits, dh->p, dh->g,
1607 buffer_free(client_kexinit);
1608 buffer_free(server_kexinit);
1609 xfree(client_kexinit);
1610 xfree(server_kexinit);
1612 fprintf(stderr, "hash == ");
1613 for (i = 0; i< 20; i++)
1614 fprintf(stderr, "%02x", (hash[i])&0xff);
1615 fprintf(stderr, "\n");
1617 /* save session id := H */
1618 /* XXX hashlen depends on KEX */
1619 session_id2_len = 20;
1620 session_id2 = xmalloc(session_id2_len);
1621 memcpy(session_id2, hash, session_id2_len);
1624 /* XXX hashlen depends on KEX */
1625 dsa_sign(sensitive_data.dsa_host_key, &signature, &slen, hash, 20);
1627 destroy_sensitive_data();
1629 /* send server hostkey, DH pubkey 'f' and singed H */
1630 packet_start(SSH2_MSG_KEX_DH_GEX_REPLY);
1631 packet_put_string((char *)server_host_key_blob, sbloblen);
1632 packet_put_bignum2(dh->pub_key); /* f */
1633 packet_put_string((char *)signature, slen);
1636 xfree(server_host_key_blob);
1637 packet_write_wait();
1639 kex_derive_keys(kex, hash, shared_secret);
1640 packet_set_kex(kex);
1642 /* have keys, free DH */