2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * Created: Fri Mar 17 17:09:28 1995 ylo
6 * This program is the ssh daemon. It listens for connections from clients, and
7 * performs authentication, executes use commands or shell, and forwards
8 * information to/from the application to the user client over an encrypted
9 * connection. This can also handle forwarding of X11, TCP/IP, and authentication
12 * SSH2 implementation,
13 * Copyright (c) 2000 Markus Friedl. All rights reserved.
17 RCSID("$OpenBSD: sshd.c,v 1.122 2000/07/11 08:11:34 deraadt Exp $");
32 #include <openssl/dh.h>
33 #include <openssl/bn.h>
34 #include <openssl/hmac.h>
36 #include <openssl/dsa.h>
37 #include <openssl/rsa.h>
42 #include "myproposal.h"
48 int allow_severity = LOG_INFO;
49 int deny_severity = LOG_WARNING;
56 /* Server configuration options. */
57 ServerOptions options;
59 /* Name of the server configuration file. */
60 char *config_file_name = SERVER_CONFIG_FILE;
63 * Flag indicating whether IPv4 or IPv6. This can be set on the command line.
64 * Default value is AF_UNSPEC means both IPv4 and IPv6.
67 int IPv4or6 = AF_INET;
69 int IPv4or6 = AF_UNSPEC;
73 * Debug mode flag. This can be set on the command line. If debug
74 * mode is enabled, extra debugging output will be sent to the system
75 * log, the daemon will not go to background, and will exit after processing
76 * the first connection.
80 /* Flag indicating that the daemon is being started from inetd. */
83 /* debug goes to stderr unless inetd_flag is set */
86 /* argv[0] without path. */
89 /* Saved arguments to main(). */
94 * The sockets that the server is listening; this is used in the SIGHUP
97 #define MAX_LISTEN_SOCKS 16
98 int listen_socks[MAX_LISTEN_SOCKS];
99 int num_listen_socks = 0;
102 * the client's version string, passed by sshd2 in compat mode. if != NULL,
103 * sshd will skip the version-number exchange
105 char *client_version_string = NULL;
106 char *server_version_string = NULL;
109 * Any really sensitive data in the application is contained in this
110 * structure. The idea is that this structure could be locked into memory so
111 * that the pages do not get written into swap. However, there are some
112 * problems. The private key contains BIGNUMs, and we do not (in principle)
113 * have access to the internals of them, and locking just the structure is
114 * not very useful. Currently, memory locking is not implemented.
117 RSA *private_key; /* Private part of empheral server key. */
118 RSA *host_key; /* Private part of host key. */
119 Key *dsa_host_key; /* Private DSA host key. */
123 * Flag indicating whether the current session key has been used. This flag
124 * is set whenever the key is used, and cleared when the key is regenerated.
128 /* This is set to true when SIGHUP is received. */
129 int received_sighup = 0;
131 /* Public side of the server key. This value is regenerated regularly with
135 /* session identifier, used by RSA-auth */
136 unsigned char session_id[16];
139 unsigned char *session_id2 = NULL;
140 int session_id2_len = 0;
142 /* Prototypes for various functions defined later in this file. */
147 * Close all listening sockets
150 close_listen_socks(void)
153 for (i = 0; i < num_listen_socks; i++)
154 close(listen_socks[i]);
155 num_listen_socks = -1;
159 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
160 * the effect is to reread the configuration file (and to regenerate
164 sighup_handler(int sig)
167 signal(SIGHUP, sighup_handler);
171 * Called from the main program after receiving SIGHUP.
172 * Restarts the server.
177 log("Received SIGHUP; restarting.");
178 close_listen_socks();
179 execv(saved_argv[0], saved_argv);
180 log("RESTART FAILED: av0='%s', error: %s.", av0, strerror(errno));
185 * Generic signal handler for terminating signals in the master daemon.
186 * These close the listen socket; not closing it seems to cause "Address
187 * already in use" problems on some machines, which is inconvenient.
190 sigterm_handler(int sig)
192 log("Received signal %d; terminating.", sig);
193 close_listen_socks();
194 unlink(options.pid_file);
199 * SIGCHLD handler. This is called whenever a child dies. This will then
200 * reap any zombies left by exited c.
203 main_sigchld_handler(int sig)
205 int save_errno = errno;
208 while (waitpid(-1, &status, WNOHANG) > 0)
211 signal(SIGCHLD, main_sigchld_handler);
216 * Signal handler for the alarm after the login grace period has expired.
219 grace_alarm_handler(int sig)
221 /* Close the connection. */
224 /* Log error and exit. */
225 fatal("Timeout before authentication for %s.", get_remote_ipaddr());
229 * Signal handler for the key regeneration alarm. Note that this
230 * alarm only occurs in the daemon waiting for connections, and it does not
231 * do anything with the private key or random state before forking.
232 * Thus there should be no concurrency control/asynchronous execution
235 /* XXX do we really want this work to be done in a signal handler ? -m */
237 key_regeneration_alarm(int sig)
239 int save_errno = errno;
241 /* Check if we should generate a new key. */
243 /* This should really be done in the background. */
244 log("Generating new %d bit RSA key.", options.server_key_bits);
246 if (sensitive_data.private_key != NULL)
247 RSA_free(sensitive_data.private_key);
248 sensitive_data.private_key = RSA_new();
250 if (public_key != NULL)
251 RSA_free(public_key);
252 public_key = RSA_new();
254 rsa_generate_key(sensitive_data.private_key, public_key,
255 options.server_key_bits);
258 log("RSA key generation complete.");
260 /* Reschedule the alarm. */
261 signal(SIGALRM, key_regeneration_alarm);
262 alarm(options.key_regeneration_time);
267 sshd_exchange_identification(int sock_in, int sock_out)
270 int remote_major, remote_minor;
273 char buf[256]; /* Must not be larger than remote_version. */
274 char remote_version[256]; /* Must be at least as big as buf. */
276 if ((options.protocol & SSH_PROTO_1) &&
277 (options.protocol & SSH_PROTO_2)) {
278 major = PROTOCOL_MAJOR_1;
280 } else if (options.protocol & SSH_PROTO_2) {
281 major = PROTOCOL_MAJOR_2;
282 minor = PROTOCOL_MINOR_2;
284 major = PROTOCOL_MAJOR_1;
285 minor = PROTOCOL_MINOR_1;
287 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", major, minor, SSH_VERSION);
288 server_version_string = xstrdup(buf);
290 if (client_version_string == NULL) {
291 /* Send our protocol version identification. */
292 if (atomicio(write, sock_out, server_version_string, strlen(server_version_string))
293 != strlen(server_version_string)) {
294 log("Could not write ident string to %s.", get_remote_ipaddr());
298 /* Read other side\'s version identification. */
299 for (i = 0; i < sizeof(buf) - 1; i++) {
300 if (atomicio(read, sock_in, &buf[i], 1) != 1) {
301 log("Did not receive ident string from %s.", get_remote_ipaddr());
304 if (buf[i] == '\r') {
309 if (buf[i] == '\n') {
315 buf[sizeof(buf) - 1] = 0;
316 client_version_string = xstrdup(buf);
320 * Check that the versions match. In future this might accept
321 * several versions and set appropriate flags to handle them.
323 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
324 &remote_major, &remote_minor, remote_version) != 3) {
325 s = "Protocol mismatch.\n";
326 (void) atomicio(write, sock_out, s, strlen(s));
329 log("Bad protocol version identification '%.100s' from %s",
330 client_version_string, get_remote_ipaddr());
333 debug("Client protocol version %d.%d; client software version %.100s",
334 remote_major, remote_minor, remote_version);
336 compat_datafellows(remote_version);
339 switch(remote_major) {
341 if (remote_minor == 99) {
342 if (options.protocol & SSH_PROTO_2)
348 if (!(options.protocol & SSH_PROTO_1)) {
352 if (remote_minor < 3) {
353 packet_disconnect("Your ssh version is too old and "
354 "is no longer supported. Please install a newer version.");
355 } else if (remote_minor == 3) {
356 /* note that this disables agent-forwarding */
361 if (options.protocol & SSH_PROTO_2) {
370 chop(server_version_string);
371 chop(client_version_string);
372 debug("Local version string %.200s", server_version_string);
375 s = "Protocol major versions differ.\n";
376 (void) atomicio(write, sock_out, s, strlen(s));
379 log("Protocol major versions differ for %s: %.200s vs. %.200s",
381 server_version_string, client_version_string);
385 packet_set_ssh2_format();
390 destroy_sensitive_data(void)
392 /* Destroy the private and public keys. They will no longer be needed. */
394 RSA_free(public_key);
395 if (sensitive_data.private_key)
396 RSA_free(sensitive_data.private_key);
397 if (sensitive_data.host_key)
398 RSA_free(sensitive_data.host_key);
399 if (sensitive_data.dsa_host_key != NULL)
400 key_free(sensitive_data.dsa_host_key);
403 int *startup_pipes = NULL; /* options.max_startup sized array of fd ints */
404 int startup_pipe; /* in child */
407 * Main program for the daemon.
410 main(int ac, char **av)
414 int opt, sock_in = 0, sock_out = 0, newsock, j, i, fdsetsz, on = 1;
419 struct sockaddr_storage from;
420 const char *remote_ip;
423 struct linger linger;
425 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
426 int listen_sock, maxfd;
435 if (strchr(av[0], '/'))
436 av0 = strrchr(av[0], '/') + 1;
440 /* Initialize configuration options to their default values. */
441 initialize_server_options(&options);
443 /* Parse command-line arguments. */
444 while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:diqQ46")) != EOF) {
453 config_file_name = optarg;
457 options.log_level = SYSLOG_LEVEL_DEBUG;
466 options.log_level = SYSLOG_LEVEL_QUIET;
469 options.server_key_bits = atoi(optarg);
472 options.ports_from_cmdline = 1;
473 if (options.num_ports >= MAX_PORTS)
474 fatal("too many ports.\n");
475 options.ports[options.num_ports++] = atoi(optarg);
478 options.login_grace_time = atoi(optarg);
481 options.key_regeneration_time = atoi(optarg);
484 options.host_key_file = optarg;
487 client_version_string = optarg;
488 /* only makes sense with inetd_flag, i.e. no listen() */
493 fprintf(stderr, "sshd version %s\n", SSH_VERSION);
494 fprintf(stderr, "Usage: %s [options]\n", av0);
495 fprintf(stderr, "Options:\n");
496 fprintf(stderr, " -f file Configuration file (default %s)\n", SERVER_CONFIG_FILE);
497 fprintf(stderr, " -d Debugging mode\n");
498 fprintf(stderr, " -i Started from inetd\n");
499 fprintf(stderr, " -q Quiet (no logging)\n");
500 fprintf(stderr, " -p port Listen on the specified port (default: 22)\n");
501 fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n");
502 fprintf(stderr, " -g seconds Grace period for authentication (default: 300)\n");
503 fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n");
504 fprintf(stderr, " -h file File from which to read host key (default: %s)\n",
506 fprintf(stderr, " -4 Use IPv4 only\n");
507 fprintf(stderr, " -6 Use IPv6 only\n");
513 * Force logging to stderr until we have loaded the private host
514 * key (unless started from inetd)
517 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
518 options.log_facility == -1 ? SYSLOG_FACILITY_AUTH : options.log_facility,
519 !silent && !inetd_flag);
521 /* Read server configuration options from the configuration file. */
522 read_server_config(&options, config_file_name);
524 /* Fill in default values for those options not explicitly set. */
525 fill_default_server_options(&options);
527 /* Check that there are no remaining arguments. */
529 fprintf(stderr, "Extra argument %s.\n", av[optind]);
533 debug("sshd version %.100s", SSH_VERSION);
535 sensitive_data.dsa_host_key = NULL;
536 sensitive_data.host_key = NULL;
538 /* check if RSA support exists */
539 if ((options.protocol & SSH_PROTO_1) &&
541 log("no RSA support in libssl and libcrypto. See ssl(8)");
542 log("Disabling protocol version 1");
543 options.protocol &= ~SSH_PROTO_1;
545 /* Load the RSA/DSA host key. It must have empty passphrase. */
546 if (options.protocol & SSH_PROTO_1) {
548 sensitive_data.host_key = RSA_new();
550 k.rsa = sensitive_data.host_key;
552 if (!load_private_key(options.host_key_file, "", &k, NULL)) {
553 error("Could not load host key: %.200s: %.100s",
554 options.host_key_file, strerror(errno));
555 log("Disabling protocol version 1");
556 options.protocol &= ~SSH_PROTO_1;
560 if (options.protocol & SSH_PROTO_2) {
561 sensitive_data.dsa_host_key = key_new(KEY_DSA);
562 if (!load_private_key(options.host_dsa_key_file, "", sensitive_data.dsa_host_key, NULL)) {
564 error("Could not load DSA host key: %.200s", options.host_dsa_key_file);
565 log("Disabling protocol version 2");
566 options.protocol &= ~SSH_PROTO_2;
569 if (! options.protocol & (SSH_PROTO_1|SSH_PROTO_2)) {
571 fprintf(stderr, "sshd: no hostkeys available -- exiting.\n");
572 log("sshd: no hostkeys available -- exiting.\n");
576 /* Check certain values for sanity. */
577 if (options.protocol & SSH_PROTO_1) {
578 if (options.server_key_bits < 512 ||
579 options.server_key_bits > 32768) {
580 fprintf(stderr, "Bad server key size.\n");
584 * Check that server and host key lengths differ sufficiently. This
585 * is necessary to make double encryption work with rsaref. Oh, I
586 * hate software patents. I dont know if this can go? Niels
588 if (options.server_key_bits >
589 BN_num_bits(sensitive_data.host_key->n) - SSH_KEY_BITS_RESERVED &&
590 options.server_key_bits <
591 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
592 options.server_key_bits =
593 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED;
594 debug("Forcing server key to %d bits to make it differ from host key.",
595 options.server_key_bits);
599 /* Initialize the log (it is reinitialized below in case we forked). */
600 if (debug_flag && !inetd_flag)
602 log_init(av0, options.log_level, options.log_facility, log_stderr);
605 * If not in debugging mode, and not started from inetd, disconnect
606 * from the controlling terminal, and fork. The original process
609 if (!debug_flag && !inetd_flag) {
612 #endif /* TIOCNOTTY */
613 if (daemon(0, 0) < 0)
614 fatal("daemon() failed: %.200s", strerror(errno));
616 /* Disconnect from the controlling tty. */
618 fd = open("/dev/tty", O_RDWR | O_NOCTTY);
620 (void) ioctl(fd, TIOCNOTTY, NULL);
623 #endif /* TIOCNOTTY */
625 /* Reinitialize the log (because of the fork above). */
626 log_init(av0, options.log_level, options.log_facility, log_stderr);
628 /* Do not display messages to stdout in RSA code. */
631 /* Initialize the random number generator. */
634 /* Chdir to the root directory so that the current disk can be
635 unmounted if desired. */
638 /* Start listening for a socket, unless started from inetd. */
641 s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */
646 * We intentionally do not close the descriptors 0, 1, and 2
647 * as our code for setting the descriptors won\'t work if
648 * ttyfd happens to be one of those.
650 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
652 if (options.protocol & SSH_PROTO_1) {
653 public_key = RSA_new();
654 sensitive_data.private_key = RSA_new();
655 log("Generating %d bit RSA key.", options.server_key_bits);
656 rsa_generate_key(sensitive_data.private_key, public_key,
657 options.server_key_bits);
659 log("RSA key generation complete.");
662 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
663 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
665 if (num_listen_socks >= MAX_LISTEN_SOCKS)
666 fatal("Too many listen sockets. "
667 "Enlarge MAX_LISTEN_SOCKS");
668 if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
669 ntop, sizeof(ntop), strport, sizeof(strport),
670 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
671 error("getnameinfo failed");
674 /* Create socket for listening. */
675 listen_sock = socket(ai->ai_family, SOCK_STREAM, 0);
676 if (listen_sock < 0) {
677 /* kernel may not support ipv6 */
678 verbose("socket: %.100s", strerror(errno));
681 if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) {
682 error("listen_sock O_NONBLOCK: %s", strerror(errno));
687 * Set socket options. We try to make the port
688 * reusable and have it close as fast as possible
689 * without waiting in unnecessary wait states on
692 setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
693 (void *) &on, sizeof(on));
696 setsockopt(listen_sock, SOL_SOCKET, SO_LINGER,
697 (void *) &linger, sizeof(linger));
699 debug("Bind to port %s on %s.", strport, ntop);
701 /* Bind the socket to the desired port. */
702 if ((bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) &&
704 error("Bind to port %s on %s failed: %.200s.",
705 strport, ntop, strerror(errno));
709 listen_socks[num_listen_socks] = listen_sock;
712 /* Start listening on the port. */
713 log("Server listening on %s port %s.", ntop, strport);
714 if (listen(listen_sock, 5) < 0)
715 fatal("listen: %.100s", strerror(errno));
718 freeaddrinfo(options.listen_addrs);
720 if (!num_listen_socks)
721 fatal("Cannot bind any address.");
725 * Record our pid in /etc/sshd_pid to make it easier
726 * to kill the correct sshd. We don\'t want to do
727 * this before the bind above because the bind will
728 * fail if there already is a daemon, and this will
729 * overwrite any old pid in the file.
731 f = fopen(options.pid_file, "w");
733 fprintf(f, "%u\n", (unsigned int) getpid());
737 if (options.protocol & SSH_PROTO_1) {
738 public_key = RSA_new();
739 sensitive_data.private_key = RSA_new();
741 log("Generating %d bit RSA key.", options.server_key_bits);
742 rsa_generate_key(sensitive_data.private_key, public_key,
743 options.server_key_bits);
745 log("RSA key generation complete.");
747 /* Schedule server key regeneration alarm. */
748 signal(SIGALRM, key_regeneration_alarm);
749 alarm(options.key_regeneration_time);
752 /* Arrange to restart on SIGHUP. The handler needs listen_sock. */
753 signal(SIGHUP, sighup_handler);
755 signal(SIGTERM, sigterm_handler);
756 signal(SIGQUIT, sigterm_handler);
758 /* Arrange SIGCHLD to be caught. */
759 signal(SIGCHLD, main_sigchld_handler);
761 /* setup fd set for listen */
764 for (i = 0; i < num_listen_socks; i++)
765 if (listen_socks[i] > maxfd)
766 maxfd = listen_socks[i];
767 /* pipes connected to unauthenticated childs */
768 startup_pipes = xmalloc(options.max_startups * sizeof(int));
769 for (i = 0; i < options.max_startups; i++)
770 startup_pipes[i] = -1;
773 * Stay listening for connections until the system crashes or
774 * the daemon is killed with a signal.
781 fdsetsz = howmany(maxfd, NFDBITS) * sizeof(fd_mask);
782 fdset = (fd_set *)xmalloc(fdsetsz);
783 memset(fdset, 0, fdsetsz);
785 for (i = 0; i < num_listen_socks; i++)
786 FD_SET(listen_socks[i], fdset);
787 for (i = 0; i < options.max_startups; i++)
788 if (startup_pipes[i] != -1)
789 FD_SET(startup_pipes[i], fdset);
791 /* Wait in select until there is a connection. */
792 if (select(maxfd + 1, fdset, NULL, NULL, NULL) < 0) {
794 error("select: %.100s", strerror(errno));
797 for (i = 0; i < options.max_startups; i++)
798 if (startup_pipes[i] != -1 &&
799 FD_ISSET(startup_pipes[i], fdset)) {
801 * the read end of the pipe is ready
802 * if the child has closed the pipe
803 * after successfull authentication
804 * or if the child has died
806 close(startup_pipes[i]);
807 startup_pipes[i] = -1;
810 for (i = 0; i < num_listen_socks; i++) {
811 if (!FD_ISSET(listen_socks[i], fdset))
813 fromlen = sizeof(from);
814 newsock = accept(listen_socks[i], (struct sockaddr *)&from,
817 if (errno != EINTR && errno != EWOULDBLOCK)
818 error("accept: %.100s", strerror(errno));
821 if (fcntl(newsock, F_SETFL, 0) < 0) {
822 error("newsock del O_NONBLOCK: %s", strerror(errno));
825 if (startups >= options.max_startups) {
829 if (pipe(startup_p) == -1) {
834 for (j = 0; j < options.max_startups; j++)
835 if (startup_pipes[j] == -1) {
836 startup_pipes[j] = startup_p[0];
837 if (maxfd < startup_p[0])
838 maxfd = startup_p[0];
844 * Got connection. Fork a child to handle it, unless
845 * we are in debugging mode.
849 * In debugging mode. Close the listening
850 * socket, and start processing the
851 * connection without forking.
853 debug("Server will not fork when running in debugging mode.");
854 close_listen_socks();
862 * Normal production daemon. Fork, and have
863 * the child process the connection. The
864 * parent continues listening.
866 if ((pid = fork()) == 0) {
868 * Child. Close the listening and max_startup
869 * sockets. Start using the accepted socket.
870 * Reinitialize logging (since our pid has
871 * changed). We break out of the loop to handle
874 startup_pipe = startup_p[1];
875 for (j = 0; j < options.max_startups; j++)
876 if (startup_pipes[j] != -1)
877 close(startup_pipes[j]);
878 close_listen_socks();
881 log_init(av0, options.log_level, options.log_facility, log_stderr);
886 /* Parent. Stay in the loop. */
888 error("fork: %.100s", strerror(errno));
890 debug("Forked child %d.", pid);
894 /* Mark that the key has been used (it was "given" to the child). */
899 /* Close the new socket (the child is now taking care of it). */
902 /* child process check (or debug mode) */
903 if (num_listen_socks < 0)
908 /* This is the child processing a new connection. */
911 * Disable the key regeneration alarm. We will not regenerate the
912 * key since we are no longer in a position to give it to anyone. We
913 * will not restart on SIGHUP since it no longer makes sense.
916 signal(SIGALRM, SIG_DFL);
917 signal(SIGHUP, SIG_DFL);
918 signal(SIGTERM, SIG_DFL);
919 signal(SIGQUIT, SIG_DFL);
920 signal(SIGCHLD, SIG_DFL);
923 * Set socket options for the connection. We want the socket to
924 * close as fast as possible without waiting for anything. If the
925 * connection is not a socket, these will do nothing.
927 /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
930 setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
933 * Register our connection. This turns encryption off because we do
936 packet_set_connection(sock_in, sock_out);
938 remote_port = get_remote_port();
939 remote_ip = get_remote_ipaddr();
941 /* Check whether logins are denied from this host. */
943 /* XXX LIBWRAP noes not know about IPv6 */
945 struct request_info req;
947 request_init(&req, RQ_DAEMON, av0, RQ_FILE, sock_in, NULL);
950 if (!hosts_access(&req)) {
955 /*XXX IPv6 verbose("Connection from %.500s port %d", eval_client(&req), remote_port); */
958 /* Log the connection. */
959 verbose("Connection from %.500s port %d", remote_ip, remote_port);
962 * We don\'t want to listen forever unless the other side
963 * successfully authenticates itself. So we set up an alarm which is
964 * cleared after successful authentication. A limit of zero
965 * indicates no limit. Note that we don\'t set the alarm in debugging
966 * mode; it is just annoying to have the server exit just when you
967 * are about to discover the bug.
969 signal(SIGALRM, grace_alarm_handler);
971 alarm(options.login_grace_time);
973 sshd_exchange_identification(sock_in, sock_out);
975 * Check that the connection comes from a privileged port. Rhosts-
976 * and Rhosts-RSA-Authentication only make sense from priviledged
977 * programs. Of course, if the intruder has root access on his local
978 * machine, he can connect from any port. So do not use these
979 * authentication methods from machines that you do not trust.
981 if (remote_port >= IPPORT_RESERVED ||
982 remote_port < IPPORT_RESERVED / 2) {
983 options.rhosts_authentication = 0;
984 options.rhosts_rsa_authentication = 0;
987 if (!packet_connection_is_ipv4() &&
988 options.kerberos_authentication) {
989 debug("Kerberos Authentication disabled, only available for IPv4.");
990 options.kerberos_authentication = 0;
994 packet_set_nonblocking();
996 /* perform the key exchange */
997 /* authenticate user and start session */
1000 do_authentication2();
1003 do_authentication();
1007 /* Cleanup user's ticket cache file. */
1008 if (options.kerberos_ticket_cleanup)
1012 /* The connection has been terminated. */
1013 verbose("Closing connection to %.100s", remote_ip);
1017 #endif /* USE_PAM */
1031 BIGNUM *session_key_int;
1032 unsigned char session_key[SSH_SESSION_KEY_LENGTH];
1033 unsigned char cookie[8];
1034 unsigned int cipher_type, auth_mask, protocol_flags;
1038 * Generate check bytes that the client must send back in the user
1039 * packet in order for it to be accepted; this is used to defy ip
1040 * spoofing attacks. Note that this only works against somebody
1041 * doing IP spoofing from a remote machine; any machine on the local
1042 * network can still see outgoing packets and catch the random
1043 * cookie. This only affects rhosts authentication, and this is one
1044 * of the reasons why it is inherently insecure.
1046 for (i = 0; i < 8; i++) {
1048 rand = arc4random();
1049 cookie[i] = rand & 0xff;
1054 * Send our public key. We include in the packet 64 bits of random
1055 * data that must be matched in the reply in order to prevent IP
1058 packet_start(SSH_SMSG_PUBLIC_KEY);
1059 for (i = 0; i < 8; i++)
1060 packet_put_char(cookie[i]);
1062 /* Store our public server RSA key. */
1063 packet_put_int(BN_num_bits(public_key->n));
1064 packet_put_bignum(public_key->e);
1065 packet_put_bignum(public_key->n);
1067 /* Store our public host RSA key. */
1068 packet_put_int(BN_num_bits(sensitive_data.host_key->n));
1069 packet_put_bignum(sensitive_data.host_key->e);
1070 packet_put_bignum(sensitive_data.host_key->n);
1072 /* Put protocol flags. */
1073 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
1075 /* Declare which ciphers we support. */
1076 packet_put_int(cipher_mask1());
1078 /* Declare supported authentication types. */
1080 if (options.rhosts_authentication)
1081 auth_mask |= 1 << SSH_AUTH_RHOSTS;
1082 if (options.rhosts_rsa_authentication)
1083 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
1084 if (options.rsa_authentication)
1085 auth_mask |= 1 << SSH_AUTH_RSA;
1087 if (options.kerberos_authentication)
1088 auth_mask |= 1 << SSH_AUTH_KERBEROS;
1091 if (options.kerberos_tgt_passing)
1092 auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
1093 if (options.afs_token_passing)
1094 auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
1097 if (options.skey_authentication == 1)
1098 auth_mask |= 1 << SSH_AUTH_TIS;
1100 if (options.password_authentication)
1101 auth_mask |= 1 << SSH_AUTH_PASSWORD;
1102 packet_put_int(auth_mask);
1104 /* Send the packet and wait for it to be sent. */
1106 packet_write_wait();
1108 debug("Sent %d bit public key and %d bit host key.",
1109 BN_num_bits(public_key->n), BN_num_bits(sensitive_data.host_key->n));
1111 /* Read clients reply (cipher type and session key). */
1112 packet_read_expect(&plen, SSH_CMSG_SESSION_KEY);
1114 /* Get cipher type and check whether we accept this. */
1115 cipher_type = packet_get_char();
1117 if (!(cipher_mask() & (1 << cipher_type)))
1118 packet_disconnect("Warning: client selects unsupported cipher.");
1120 /* Get check bytes from the packet. These must match those we
1121 sent earlier with the public key packet. */
1122 for (i = 0; i < 8; i++)
1123 if (cookie[i] != packet_get_char())
1124 packet_disconnect("IP Spoofing check bytes do not match.");
1126 debug("Encryption type: %.200s", cipher_name(cipher_type));
1128 /* Get the encrypted integer. */
1129 session_key_int = BN_new();
1130 packet_get_bignum(session_key_int, &slen);
1132 protocol_flags = packet_get_int();
1133 packet_set_protocol_flags(protocol_flags);
1135 packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY);
1138 * Decrypt it using our private server key and private host key (key
1139 * with larger modulus first).
1141 if (BN_cmp(sensitive_data.private_key->n, sensitive_data.host_key->n) > 0) {
1142 /* Private key has bigger modulus. */
1143 if (BN_num_bits(sensitive_data.private_key->n) <
1144 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
1145 fatal("do_connection: %s: private_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1146 get_remote_ipaddr(),
1147 BN_num_bits(sensitive_data.private_key->n),
1148 BN_num_bits(sensitive_data.host_key->n),
1149 SSH_KEY_BITS_RESERVED);
1151 rsa_private_decrypt(session_key_int, session_key_int,
1152 sensitive_data.private_key);
1153 rsa_private_decrypt(session_key_int, session_key_int,
1154 sensitive_data.host_key);
1156 /* Host key has bigger modulus (or they are equal). */
1157 if (BN_num_bits(sensitive_data.host_key->n) <
1158 BN_num_bits(sensitive_data.private_key->n) + SSH_KEY_BITS_RESERVED) {
1159 fatal("do_connection: %s: host_key %d < private_key %d + SSH_KEY_BITS_RESERVED %d",
1160 get_remote_ipaddr(),
1161 BN_num_bits(sensitive_data.host_key->n),
1162 BN_num_bits(sensitive_data.private_key->n),
1163 SSH_KEY_BITS_RESERVED);
1165 rsa_private_decrypt(session_key_int, session_key_int,
1166 sensitive_data.host_key);
1167 rsa_private_decrypt(session_key_int, session_key_int,
1168 sensitive_data.private_key);
1171 compute_session_id(session_id, cookie,
1172 sensitive_data.host_key->n,
1173 sensitive_data.private_key->n);
1175 /* Destroy the private and public keys. They will no longer be needed. */
1176 destroy_sensitive_data();
1179 * Extract session key from the decrypted integer. The key is in the
1180 * least significant 256 bits of the integer; the first byte of the
1181 * key is in the highest bits.
1183 BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1184 len = BN_num_bytes(session_key_int);
1185 if (len < 0 || len > sizeof(session_key))
1186 fatal("do_connection: bad len from %s: session_key_int %d > sizeof(session_key) %d",
1187 get_remote_ipaddr(),
1188 len, sizeof(session_key));
1189 memset(session_key, 0, sizeof(session_key));
1190 BN_bn2bin(session_key_int, session_key + sizeof(session_key) - len);
1192 /* Destroy the decrypted integer. It is no longer needed. */
1193 BN_clear_free(session_key_int);
1195 /* Xor the first 16 bytes of the session key with the session id. */
1196 for (i = 0; i < 16; i++)
1197 session_key[i] ^= session_id[i];
1199 /* Set the session key. From this on all communications will be encrypted. */
1200 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
1202 /* Destroy our copy of the session key. It is no longer needed. */
1203 memset(session_key, 0, sizeof(session_key));
1205 debug("Received session key; encryption turned on.");
1207 /* Send an acknowledgement packet. Note that this packet is sent encrypted. */
1208 packet_start(SSH_SMSG_SUCCESS);
1210 packet_write_wait();
1214 * SSH2 key exchange: diffie-hellman-group1-sha1
1219 Buffer *server_kexinit;
1220 Buffer *client_kexinit;
1221 int payload_len, dlen;
1223 unsigned int klen, kout;
1224 unsigned char *signature = NULL;
1225 unsigned char *server_host_key_blob = NULL;
1226 unsigned int sbloblen;
1228 BIGNUM *dh_client_pub = 0;
1229 BIGNUM *shared_secret = 0;
1231 unsigned char *kbuf;
1232 unsigned char *hash;
1234 char *cprop[PROPOSAL_MAX];
1238 if (options.ciphers != NULL) {
1239 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1240 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
1242 server_kexinit = kex_init(myproposal);
1243 client_kexinit = xmalloc(sizeof(*client_kexinit));
1244 buffer_init(client_kexinit);
1246 /* algorithm negotiation */
1247 kex_exchange_kexinit(server_kexinit, client_kexinit, cprop);
1248 kex = kex_choose_conf(cprop, myproposal, 1);
1249 for (i = 0; i < PROPOSAL_MAX; i++)
1254 debug("Wait SSH2_MSG_KEXDH_INIT.");
1255 packet_read_expect(&payload_len, SSH2_MSG_KEXDH_INIT);
1258 dh_client_pub = BN_new();
1259 if (dh_client_pub == NULL)
1260 fatal("dh_client_pub == NULL");
1261 packet_get_bignum2(dh_client_pub, &dlen);
1264 fprintf(stderr, "\ndh_client_pub= ");
1265 bignum_print(dh_client_pub);
1266 fprintf(stderr, "\n");
1267 debug("bits %d", BN_num_bits(dh_client_pub));
1270 /* generate DH key */
1271 dh = dh_new_group1(); /* XXX depends on 'kex' */
1274 fprintf(stderr, "\np= ");
1275 bignum_print(dh->p);
1276 fprintf(stderr, "\ng= ");
1277 bignum_print(dh->g);
1278 fprintf(stderr, "\npub= ");
1279 bignum_print(dh->pub_key);
1280 fprintf(stderr, "\n");
1282 if (!dh_pub_is_valid(dh, dh_client_pub))
1283 packet_disconnect("bad client public DH value");
1286 kbuf = xmalloc(klen);
1287 kout = DH_compute_key(kbuf, dh_client_pub, dh);
1290 debug("shared secret: len %d/%d", klen, kout);
1291 fprintf(stderr, "shared secret == ");
1292 for (i = 0; i< kout; i++)
1293 fprintf(stderr, "%02x", (kbuf[i])&0xff);
1294 fprintf(stderr, "\n");
1296 shared_secret = BN_new();
1298 BN_bin2bn(kbuf, kout, shared_secret);
1299 memset(kbuf, 0, klen);
1302 /* XXX precompute? */
1303 dsa_make_key_blob(sensitive_data.dsa_host_key, &server_host_key_blob, &sbloblen);
1305 /* calc H */ /* XXX depends on 'kex' */
1307 client_version_string,
1308 server_version_string,
1309 buffer_ptr(client_kexinit), buffer_len(client_kexinit),
1310 buffer_ptr(server_kexinit), buffer_len(server_kexinit),
1311 (char *)server_host_key_blob, sbloblen,
1316 buffer_free(client_kexinit);
1317 buffer_free(server_kexinit);
1318 xfree(client_kexinit);
1319 xfree(server_kexinit);
1321 fprintf(stderr, "hash == ");
1322 for (i = 0; i< 20; i++)
1323 fprintf(stderr, "%02x", (hash[i])&0xff);
1324 fprintf(stderr, "\n");
1326 /* save session id := H */
1327 /* XXX hashlen depends on KEX */
1328 session_id2_len = 20;
1329 session_id2 = xmalloc(session_id2_len);
1330 memcpy(session_id2, hash, session_id2_len);
1333 /* XXX hashlen depends on KEX */
1334 dsa_sign(sensitive_data.dsa_host_key, &signature, &slen, hash, 20);
1336 destroy_sensitive_data();
1338 /* send server hostkey, DH pubkey 'f' and singed H */
1339 packet_start(SSH2_MSG_KEXDH_REPLY);
1340 packet_put_string((char *)server_host_key_blob, sbloblen);
1341 packet_put_bignum2(dh->pub_key); /* f */
1342 packet_put_string((char *)signature, slen);
1345 xfree(server_host_key_blob);
1346 packet_write_wait();
1348 kex_derive_keys(kex, hash, shared_secret);
1349 packet_set_kex(kex);
1351 /* have keys, free DH */
1354 debug("send SSH2_MSG_NEWKEYS.");
1355 packet_start(SSH2_MSG_NEWKEYS);
1357 packet_write_wait();
1358 debug("done: send SSH2_MSG_NEWKEYS.");
1360 debug("Wait SSH2_MSG_NEWKEYS.");
1361 packet_read_expect(&payload_len, SSH2_MSG_NEWKEYS);
1362 debug("GOT SSH2_MSG_NEWKEYS.");
1365 /* send 1st encrypted/maced/compressed message */
1366 packet_start(SSH2_MSG_IGNORE);
1367 packet_put_cstring("markus");
1369 packet_write_wait();
1371 debug("done: KEX2.");