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.116 2000/05/17 08:20:16 markus 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(). */
93 * The sockets that the server is listening; this is used in the SIGHUP
96 #define MAX_LISTEN_SOCKS 16
97 int listen_socks[MAX_LISTEN_SOCKS];
98 int num_listen_socks = 0;
101 * the client's version string, passed by sshd2 in compat mode. if != NULL,
102 * sshd will skip the version-number exchange
104 char *client_version_string = NULL;
105 char *server_version_string = NULL;
108 * Any really sensitive data in the application is contained in this
109 * structure. The idea is that this structure could be locked into memory so
110 * that the pages do not get written into swap. However, there are some
111 * problems. The private key contains BIGNUMs, and we do not (in principle)
112 * have access to the internals of them, and locking just the structure is
113 * not very useful. Currently, memory locking is not implemented.
116 RSA *private_key; /* Private part of empheral server key. */
117 RSA *host_key; /* Private part of host key. */
118 Key *dsa_host_key; /* Private DSA host key. */
122 * Flag indicating whether the current session key has been used. This flag
123 * is set whenever the key is used, and cleared when the key is regenerated.
127 /* This is set to true when SIGHUP is received. */
128 int received_sighup = 0;
130 /* Public side of the server key. This value is regenerated regularly with
134 /* session identifier, used by RSA-auth */
135 unsigned char session_id[16];
138 unsigned char *session_id2 = NULL;
139 int session_id2_len = 0;
141 /* Prototypes for various functions defined later in this file. */
146 * Close all listening sockets
149 close_listen_socks(void)
152 for (i = 0; i < num_listen_socks; i++)
153 close(listen_socks[i]);
154 num_listen_socks = -1;
158 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
159 * the effect is to reread the configuration file (and to regenerate
163 sighup_handler(int sig)
166 signal(SIGHUP, sighup_handler);
170 * Called from the main program after receiving SIGHUP.
171 * Restarts the server.
176 log("Received SIGHUP; restarting.");
177 close_listen_socks();
178 execv(saved_argv[0], saved_argv);
179 log("RESTART FAILED: av0='%s', error: %s.", av0, strerror(errno));
184 * Generic signal handler for terminating signals in the master daemon.
185 * These close the listen socket; not closing it seems to cause "Address
186 * already in use" problems on some machines, which is inconvenient.
189 sigterm_handler(int sig)
191 log("Received signal %d; terminating.", sig);
192 close_listen_socks();
193 unlink(options.pid_file);
198 * SIGCHLD handler. This is called whenever a child dies. This will then
199 * reap any zombies left by exited c.
202 main_sigchld_handler(int sig)
204 int save_errno = errno;
207 while (waitpid(-1, &status, WNOHANG) > 0)
210 signal(SIGCHLD, main_sigchld_handler);
215 * Signal handler for the alarm after the login grace period has expired.
218 grace_alarm_handler(int sig)
220 /* Close the connection. */
223 /* Log error and exit. */
224 fatal("Timeout before authentication for %s.", get_remote_ipaddr());
228 * Signal handler for the key regeneration alarm. Note that this
229 * alarm only occurs in the daemon waiting for connections, and it does not
230 * do anything with the private key or random state before forking.
231 * Thus there should be no concurrency control/asynchronous execution
234 /* XXX do we really want this work to be done in a signal handler ? -m */
236 key_regeneration_alarm(int sig)
238 int save_errno = errno;
240 /* Check if we should generate a new key. */
242 /* This should really be done in the background. */
243 log("Generating new %d bit RSA key.", options.server_key_bits);
245 if (sensitive_data.private_key != NULL)
246 RSA_free(sensitive_data.private_key);
247 sensitive_data.private_key = RSA_new();
249 if (public_key != NULL)
250 RSA_free(public_key);
251 public_key = RSA_new();
253 rsa_generate_key(sensitive_data.private_key, public_key,
254 options.server_key_bits);
257 log("RSA key generation complete.");
259 /* Reschedule the alarm. */
260 signal(SIGALRM, key_regeneration_alarm);
261 alarm(options.key_regeneration_time);
266 sshd_exchange_identification(int sock_in, int sock_out)
269 int remote_major, remote_minor;
272 char buf[256]; /* Must not be larger than remote_version. */
273 char remote_version[256]; /* Must be at least as big as buf. */
275 if ((options.protocol & SSH_PROTO_1) &&
276 (options.protocol & SSH_PROTO_2)) {
277 major = PROTOCOL_MAJOR_1;
279 } else if (options.protocol & SSH_PROTO_2) {
280 major = PROTOCOL_MAJOR_2;
281 minor = PROTOCOL_MINOR_2;
283 major = PROTOCOL_MAJOR_1;
284 minor = PROTOCOL_MINOR_1;
286 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", major, minor, SSH_VERSION);
287 server_version_string = xstrdup(buf);
289 if (client_version_string == NULL) {
290 /* Send our protocol version identification. */
291 if (atomicio(write, sock_out, server_version_string, strlen(server_version_string))
292 != strlen(server_version_string)) {
293 log("Could not write ident string to %s.", get_remote_ipaddr());
297 /* Read other side\'s version identification. */
298 for (i = 0; i < sizeof(buf) - 1; i++) {
299 if (read(sock_in, &buf[i], 1) != 1) {
300 log("Did not receive ident string from %s.", get_remote_ipaddr());
303 if (buf[i] == '\r') {
308 if (buf[i] == '\n') {
314 buf[sizeof(buf) - 1] = 0;
315 client_version_string = xstrdup(buf);
319 * Check that the versions match. In future this might accept
320 * several versions and set appropriate flags to handle them.
322 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
323 &remote_major, &remote_minor, remote_version) != 3) {
324 s = "Protocol mismatch.\n";
325 (void) atomicio(write, sock_out, s, strlen(s));
328 log("Bad protocol version identification '%.100s' from %s",
329 client_version_string, get_remote_ipaddr());
332 debug("Client protocol version %d.%d; client software version %.100s",
333 remote_major, remote_minor, remote_version);
335 compat_datafellows(remote_version);
338 switch(remote_major) {
340 if (remote_minor == 99) {
341 if (options.protocol & SSH_PROTO_2)
347 if (!(options.protocol & SSH_PROTO_1)) {
351 if (remote_minor < 3) {
352 packet_disconnect("Your ssh version is too old and"
353 "is no longer supported. Please install a newer version.");
354 } else if (remote_minor == 3) {
355 /* note that this disables agent-forwarding */
360 if (options.protocol & SSH_PROTO_2) {
369 chop(server_version_string);
370 chop(client_version_string);
371 debug("Local version string %.200s", server_version_string);
374 s = "Protocol major versions differ.\n";
375 (void) atomicio(write, sock_out, s, strlen(s));
378 log("Protocol major versions differ for %s: %.200s vs. %.200s",
380 server_version_string, client_version_string);
384 packet_set_ssh2_format();
389 destroy_sensitive_data(void)
391 /* Destroy the private and public keys. They will no longer be needed. */
393 RSA_free(public_key);
394 if (sensitive_data.private_key)
395 RSA_free(sensitive_data.private_key);
396 if (sensitive_data.host_key)
397 RSA_free(sensitive_data.host_key);
398 if (sensitive_data.dsa_host_key != NULL)
399 key_free(sensitive_data.dsa_host_key);
403 * Main program for the daemon.
406 main(int ac, char **av)
410 int opt, sock_in = 0, sock_out = 0, newsock, i, fdsetsz, on = 1;
415 struct sockaddr_storage from;
416 const char *remote_ip;
419 struct linger linger;
421 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
422 int listen_sock, maxfd;
426 if (strchr(av[0], '/'))
427 av0 = strrchr(av[0], '/') + 1;
431 /* Initialize configuration options to their default values. */
432 initialize_server_options(&options);
434 /* Parse command-line arguments. */
435 while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:diqQ46")) != EOF) {
444 config_file_name = optarg;
448 options.log_level = SYSLOG_LEVEL_DEBUG;
457 options.log_level = SYSLOG_LEVEL_QUIET;
460 options.server_key_bits = atoi(optarg);
463 options.ports_from_cmdline = 1;
464 if (options.num_ports >= MAX_PORTS)
465 fatal("too many ports.\n");
466 options.ports[options.num_ports++] = atoi(optarg);
469 options.login_grace_time = atoi(optarg);
472 options.key_regeneration_time = atoi(optarg);
475 options.host_key_file = optarg;
478 client_version_string = optarg;
479 /* only makes sense with inetd_flag, i.e. no listen() */
484 fprintf(stderr, "sshd version %s\n", SSH_VERSION);
485 fprintf(stderr, "Usage: %s [options]\n", av0);
486 fprintf(stderr, "Options:\n");
487 fprintf(stderr, " -f file Configuration file (default %s)\n", SERVER_CONFIG_FILE);
488 fprintf(stderr, " -d Debugging mode\n");
489 fprintf(stderr, " -i Started from inetd\n");
490 fprintf(stderr, " -q Quiet (no logging)\n");
491 fprintf(stderr, " -p port Listen on the specified port (default: 22)\n");
492 fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n");
493 fprintf(stderr, " -g seconds Grace period for authentication (default: 300)\n");
494 fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n");
495 fprintf(stderr, " -h file File from which to read host key (default: %s)\n",
497 fprintf(stderr, " -4 Use IPv4 only\n");
498 fprintf(stderr, " -6 Use IPv6 only\n");
504 * Force logging to stderr until we have loaded the private host
505 * key (unless started from inetd)
508 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
509 options.log_facility == -1 ? SYSLOG_FACILITY_AUTH : options.log_facility,
510 !silent && !inetd_flag);
512 /* Read server configuration options from the configuration file. */
513 read_server_config(&options, config_file_name);
515 /* Fill in default values for those options not explicitly set. */
516 fill_default_server_options(&options);
518 /* Check that there are no remaining arguments. */
520 fprintf(stderr, "Extra argument %s.\n", av[optind]);
524 debug("sshd version %.100s", SSH_VERSION);
526 sensitive_data.dsa_host_key = NULL;
527 sensitive_data.host_key = NULL;
529 /* check if RSA support exists */
530 if ((options.protocol & SSH_PROTO_1) &&
532 log("no RSA support in libssl and libcrypto. See ssl(8)");
533 log("Disabling protocol version 1");
534 options.protocol &= ~SSH_PROTO_1;
536 /* Load the RSA/DSA host key. It must have empty passphrase. */
537 if (options.protocol & SSH_PROTO_1) {
539 sensitive_data.host_key = RSA_new();
541 k.rsa = sensitive_data.host_key;
543 if (!load_private_key(options.host_key_file, "", &k, NULL)) {
544 error("Could not load host key: %.200s: %.100s",
545 options.host_key_file, strerror(errno));
546 log("Disabling protocol version 1");
547 options.protocol &= ~SSH_PROTO_1;
551 if (options.protocol & SSH_PROTO_2) {
552 sensitive_data.dsa_host_key = key_new(KEY_DSA);
553 if (!load_private_key(options.host_dsa_key_file, "", sensitive_data.dsa_host_key, NULL)) {
555 error("Could not load DSA host key: %.200s", options.host_dsa_key_file);
556 log("Disabling protocol version 2");
557 options.protocol &= ~SSH_PROTO_2;
560 if (! options.protocol & (SSH_PROTO_1|SSH_PROTO_2)) {
562 fprintf(stderr, "sshd: no hostkeys available -- exiting.\n");
563 log("sshd: no hostkeys available -- exiting.\n");
567 /* Check certain values for sanity. */
568 if (options.protocol & SSH_PROTO_1) {
569 if (options.server_key_bits < 512 ||
570 options.server_key_bits > 32768) {
571 fprintf(stderr, "Bad server key size.\n");
575 * Check that server and host key lengths differ sufficiently. This
576 * is necessary to make double encryption work with rsaref. Oh, I
577 * hate software patents. I dont know if this can go? Niels
579 if (options.server_key_bits >
580 BN_num_bits(sensitive_data.host_key->n) - SSH_KEY_BITS_RESERVED &&
581 options.server_key_bits <
582 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
583 options.server_key_bits =
584 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED;
585 debug("Forcing server key to %d bits to make it differ from host key.",
586 options.server_key_bits);
590 /* Initialize the log (it is reinitialized below in case we forked). */
591 if (debug_flag && !inetd_flag)
593 log_init(av0, options.log_level, options.log_facility, log_stderr);
596 * If not in debugging mode, and not started from inetd, disconnect
597 * from the controlling terminal, and fork. The original process
600 if (!debug_flag && !inetd_flag) {
603 #endif /* TIOCNOTTY */
604 if (daemon(0, 0) < 0)
605 fatal("daemon() failed: %.200s", strerror(errno));
607 /* Disconnect from the controlling tty. */
609 fd = open("/dev/tty", O_RDWR | O_NOCTTY);
611 (void) ioctl(fd, TIOCNOTTY, NULL);
614 #endif /* TIOCNOTTY */
616 /* Reinitialize the log (because of the fork above). */
617 log_init(av0, options.log_level, options.log_facility, log_stderr);
619 /* Do not display messages to stdout in RSA code. */
622 /* Initialize the random number generator. */
625 /* Chdir to the root directory so that the current disk can be
626 unmounted if desired. */
629 /* Start listening for a socket, unless started from inetd. */
632 s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */
637 * We intentionally do not close the descriptors 0, 1, and 2
638 * as our code for setting the descriptors won\'t work if
639 * ttyfd happens to be one of those.
641 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
643 if (options.protocol & SSH_PROTO_1) {
644 public_key = RSA_new();
645 sensitive_data.private_key = RSA_new();
646 log("Generating %d bit RSA key.", options.server_key_bits);
647 rsa_generate_key(sensitive_data.private_key, public_key,
648 options.server_key_bits);
650 log("RSA key generation complete.");
653 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
654 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
656 if (num_listen_socks >= MAX_LISTEN_SOCKS)
657 fatal("Too many listen sockets. "
658 "Enlarge MAX_LISTEN_SOCKS");
659 if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
660 ntop, sizeof(ntop), strport, sizeof(strport),
661 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
662 error("getnameinfo failed");
665 /* Create socket for listening. */
666 listen_sock = socket(ai->ai_family, SOCK_STREAM, 0);
667 if (listen_sock < 0) {
668 /* kernel may not support ipv6 */
669 verbose("socket: %.100s", strerror(errno));
672 if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) {
673 error("listen_sock O_NONBLOCK: %s", strerror(errno));
678 * Set socket options. We try to make the port
679 * reusable and have it close as fast as possible
680 * without waiting in unnecessary wait states on
683 setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
684 (void *) &on, sizeof(on));
687 setsockopt(listen_sock, SOL_SOCKET, SO_LINGER,
688 (void *) &linger, sizeof(linger));
690 debug("Bind to port %s on %s.", strport, ntop);
692 /* Bind the socket to the desired port. */
693 if ((bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) &&
695 error("Bind to port %s on %s failed: %.200s.",
696 strport, ntop, strerror(errno));
700 listen_socks[num_listen_socks] = listen_sock;
703 /* Start listening on the port. */
704 log("Server listening on %s port %s.", ntop, strport);
705 if (listen(listen_sock, 5) < 0)
706 fatal("listen: %.100s", strerror(errno));
709 freeaddrinfo(options.listen_addrs);
711 if (!num_listen_socks)
712 fatal("Cannot bind any address.");
716 * Record our pid in /etc/sshd_pid to make it easier
717 * to kill the correct sshd. We don\'t want to do
718 * this before the bind above because the bind will
719 * fail if there already is a daemon, and this will
720 * overwrite any old pid in the file.
722 f = fopen(options.pid_file, "w");
724 fprintf(f, "%u\n", (unsigned int) getpid());
728 if (options.protocol & SSH_PROTO_1) {
729 public_key = RSA_new();
730 sensitive_data.private_key = RSA_new();
732 log("Generating %d bit RSA key.", options.server_key_bits);
733 rsa_generate_key(sensitive_data.private_key, public_key,
734 options.server_key_bits);
736 log("RSA key generation complete.");
738 /* Schedule server key regeneration alarm. */
739 signal(SIGALRM, key_regeneration_alarm);
740 alarm(options.key_regeneration_time);
743 /* Arrange to restart on SIGHUP. The handler needs listen_sock. */
744 signal(SIGHUP, sighup_handler);
745 signal(SIGTERM, sigterm_handler);
746 signal(SIGQUIT, sigterm_handler);
748 /* Arrange SIGCHLD to be caught. */
749 signal(SIGCHLD, main_sigchld_handler);
751 /* setup fd set for listen */
753 for (i = 0; i < num_listen_socks; i++)
754 if (listen_socks[i] > maxfd)
755 maxfd = listen_socks[i];
756 fdsetsz = howmany(maxfd, NFDBITS) * sizeof(fd_mask);
757 fdset = (fd_set *)xmalloc(fdsetsz);
760 * Stay listening for connections until the system crashes or
761 * the daemon is killed with a signal.
766 /* Wait in select until there is a connection. */
767 memset(fdset, 0, fdsetsz);
768 for (i = 0; i < num_listen_socks; i++)
769 FD_SET(listen_socks[i], fdset);
770 if (select(maxfd + 1, fdset, NULL, NULL, NULL) < 0) {
772 error("select: %.100s", strerror(errno));
775 for (i = 0; i < num_listen_socks; i++) {
776 if (!FD_ISSET(listen_socks[i], fdset))
778 fromlen = sizeof(from);
779 newsock = accept(listen_socks[i], (struct sockaddr *)&from,
782 if (errno != EINTR && errno != EWOULDBLOCK)
783 error("accept: %.100s", strerror(errno));
786 if (fcntl(newsock, F_SETFL, 0) < 0) {
787 error("newsock del O_NONBLOCK: %s", strerror(errno));
791 * Got connection. Fork a child to handle it, unless
792 * we are in debugging mode.
796 * In debugging mode. Close the listening
797 * socket, and start processing the
798 * connection without forking.
800 debug("Server will not fork when running in debugging mode.");
801 close_listen_socks();
808 * Normal production daemon. Fork, and have
809 * the child process the connection. The
810 * parent continues listening.
812 if ((pid = fork()) == 0) {
814 * Child. Close the listening socket, and start using the
815 * accepted socket. Reinitialize logging (since our pid has
816 * changed). We break out of the loop to handle the connection.
818 close_listen_socks();
821 log_init(av0, options.log_level, options.log_facility, log_stderr);
826 /* Parent. Stay in the loop. */
828 error("fork: %.100s", strerror(errno));
830 debug("Forked child %d.", pid);
832 /* Mark that the key has been used (it was "given" to the child). */
837 /* Close the new socket (the child is now taking care of it). */
839 } /* for (i = 0; i < num_listen_socks; i++) */
840 /* child process check (or debug mode) */
841 if (num_listen_socks < 0)
846 /* This is the child processing a new connection. */
849 * Disable the key regeneration alarm. We will not regenerate the
850 * key since we are no longer in a position to give it to anyone. We
851 * will not restart on SIGHUP since it no longer makes sense.
854 signal(SIGALRM, SIG_DFL);
855 signal(SIGHUP, SIG_DFL);
856 signal(SIGTERM, SIG_DFL);
857 signal(SIGQUIT, SIG_DFL);
858 signal(SIGCHLD, SIG_DFL);
861 * Set socket options for the connection. We want the socket to
862 * close as fast as possible without waiting for anything. If the
863 * connection is not a socket, these will do nothing.
865 /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
868 setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
871 * Register our connection. This turns encryption off because we do
874 packet_set_connection(sock_in, sock_out);
876 remote_port = get_remote_port();
877 remote_ip = get_remote_ipaddr();
879 /* Check whether logins are denied from this host. */
881 /* XXX LIBWRAP noes not know about IPv6 */
883 struct request_info req;
885 request_init(&req, RQ_DAEMON, av0, RQ_FILE, sock_in, NULL);
888 if (!hosts_access(&req)) {
893 /*XXX IPv6 verbose("Connection from %.500s port %d", eval_client(&req), remote_port); */
896 /* Log the connection. */
897 verbose("Connection from %.500s port %d", remote_ip, remote_port);
900 * We don\'t want to listen forever unless the other side
901 * successfully authenticates itself. So we set up an alarm which is
902 * cleared after successful authentication. A limit of zero
903 * indicates no limit. Note that we don\'t set the alarm in debugging
904 * mode; it is just annoying to have the server exit just when you
905 * are about to discover the bug.
907 signal(SIGALRM, grace_alarm_handler);
909 alarm(options.login_grace_time);
911 sshd_exchange_identification(sock_in, sock_out);
913 * Check that the connection comes from a privileged port. Rhosts-
914 * and Rhosts-RSA-Authentication only make sense from priviledged
915 * programs. Of course, if the intruder has root access on his local
916 * machine, he can connect from any port. So do not use these
917 * authentication methods from machines that you do not trust.
919 if (remote_port >= IPPORT_RESERVED ||
920 remote_port < IPPORT_RESERVED / 2) {
921 options.rhosts_authentication = 0;
922 options.rhosts_rsa_authentication = 0;
925 if (!packet_connection_is_ipv4() &&
926 options.kerberos_authentication) {
927 debug("Kerberos Authentication disabled, only available for IPv4.");
928 options.kerberos_authentication = 0;
932 packet_set_nonblocking();
934 /* perform the key exchange */
935 /* authenticate user and start session */
938 do_authentication2();
945 /* Cleanup user's ticket cache file. */
946 if (options.kerberos_ticket_cleanup)
950 /* The connection has been terminated. */
951 verbose("Closing connection to %.100s", remote_ip);
969 BIGNUM *session_key_int;
970 unsigned char session_key[SSH_SESSION_KEY_LENGTH];
971 unsigned char cookie[8];
972 unsigned int cipher_type, auth_mask, protocol_flags;
976 * Generate check bytes that the client must send back in the user
977 * packet in order for it to be accepted; this is used to defy ip
978 * spoofing attacks. Note that this only works against somebody
979 * doing IP spoofing from a remote machine; any machine on the local
980 * network can still see outgoing packets and catch the random
981 * cookie. This only affects rhosts authentication, and this is one
982 * of the reasons why it is inherently insecure.
984 for (i = 0; i < 8; i++) {
987 cookie[i] = rand & 0xff;
992 * Send our public key. We include in the packet 64 bits of random
993 * data that must be matched in the reply in order to prevent IP
996 packet_start(SSH_SMSG_PUBLIC_KEY);
997 for (i = 0; i < 8; i++)
998 packet_put_char(cookie[i]);
1000 /* Store our public server RSA key. */
1001 packet_put_int(BN_num_bits(public_key->n));
1002 packet_put_bignum(public_key->e);
1003 packet_put_bignum(public_key->n);
1005 /* Store our public host RSA key. */
1006 packet_put_int(BN_num_bits(sensitive_data.host_key->n));
1007 packet_put_bignum(sensitive_data.host_key->e);
1008 packet_put_bignum(sensitive_data.host_key->n);
1010 /* Put protocol flags. */
1011 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
1013 /* Declare which ciphers we support. */
1014 packet_put_int(cipher_mask1());
1016 /* Declare supported authentication types. */
1018 if (options.rhosts_authentication)
1019 auth_mask |= 1 << SSH_AUTH_RHOSTS;
1020 if (options.rhosts_rsa_authentication)
1021 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
1022 if (options.rsa_authentication)
1023 auth_mask |= 1 << SSH_AUTH_RSA;
1025 if (options.kerberos_authentication)
1026 auth_mask |= 1 << SSH_AUTH_KERBEROS;
1029 if (options.kerberos_tgt_passing)
1030 auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
1031 if (options.afs_token_passing)
1032 auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
1035 if (options.skey_authentication == 1)
1036 auth_mask |= 1 << SSH_AUTH_TIS;
1038 if (options.password_authentication)
1039 auth_mask |= 1 << SSH_AUTH_PASSWORD;
1040 packet_put_int(auth_mask);
1042 /* Send the packet and wait for it to be sent. */
1044 packet_write_wait();
1046 debug("Sent %d bit public key and %d bit host key.",
1047 BN_num_bits(public_key->n), BN_num_bits(sensitive_data.host_key->n));
1049 /* Read clients reply (cipher type and session key). */
1050 packet_read_expect(&plen, SSH_CMSG_SESSION_KEY);
1052 /* Get cipher type and check whether we accept this. */
1053 cipher_type = packet_get_char();
1055 if (!(cipher_mask() & (1 << cipher_type)))
1056 packet_disconnect("Warning: client selects unsupported cipher.");
1058 /* Get check bytes from the packet. These must match those we
1059 sent earlier with the public key packet. */
1060 for (i = 0; i < 8; i++)
1061 if (cookie[i] != packet_get_char())
1062 packet_disconnect("IP Spoofing check bytes do not match.");
1064 debug("Encryption type: %.200s", cipher_name(cipher_type));
1066 /* Get the encrypted integer. */
1067 session_key_int = BN_new();
1068 packet_get_bignum(session_key_int, &slen);
1070 protocol_flags = packet_get_int();
1071 packet_set_protocol_flags(protocol_flags);
1073 packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY);
1076 * Decrypt it using our private server key and private host key (key
1077 * with larger modulus first).
1079 if (BN_cmp(sensitive_data.private_key->n, sensitive_data.host_key->n) > 0) {
1080 /* Private key has bigger modulus. */
1081 if (BN_num_bits(sensitive_data.private_key->n) <
1082 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
1083 fatal("do_connection: %s: private_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1084 get_remote_ipaddr(),
1085 BN_num_bits(sensitive_data.private_key->n),
1086 BN_num_bits(sensitive_data.host_key->n),
1087 SSH_KEY_BITS_RESERVED);
1089 rsa_private_decrypt(session_key_int, session_key_int,
1090 sensitive_data.private_key);
1091 rsa_private_decrypt(session_key_int, session_key_int,
1092 sensitive_data.host_key);
1094 /* Host key has bigger modulus (or they are equal). */
1095 if (BN_num_bits(sensitive_data.host_key->n) <
1096 BN_num_bits(sensitive_data.private_key->n) + SSH_KEY_BITS_RESERVED) {
1097 fatal("do_connection: %s: host_key %d < private_key %d + SSH_KEY_BITS_RESERVED %d",
1098 get_remote_ipaddr(),
1099 BN_num_bits(sensitive_data.host_key->n),
1100 BN_num_bits(sensitive_data.private_key->n),
1101 SSH_KEY_BITS_RESERVED);
1103 rsa_private_decrypt(session_key_int, session_key_int,
1104 sensitive_data.host_key);
1105 rsa_private_decrypt(session_key_int, session_key_int,
1106 sensitive_data.private_key);
1109 compute_session_id(session_id, cookie,
1110 sensitive_data.host_key->n,
1111 sensitive_data.private_key->n);
1113 /* Destroy the private and public keys. They will no longer be needed. */
1114 destroy_sensitive_data();
1117 * Extract session key from the decrypted integer. The key is in the
1118 * least significant 256 bits of the integer; the first byte of the
1119 * key is in the highest bits.
1121 BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1122 len = BN_num_bytes(session_key_int);
1123 if (len < 0 || len > sizeof(session_key))
1124 fatal("do_connection: bad len from %s: session_key_int %d > sizeof(session_key) %d",
1125 get_remote_ipaddr(),
1126 len, sizeof(session_key));
1127 memset(session_key, 0, sizeof(session_key));
1128 BN_bn2bin(session_key_int, session_key + sizeof(session_key) - len);
1130 /* Destroy the decrypted integer. It is no longer needed. */
1131 BN_clear_free(session_key_int);
1133 /* Xor the first 16 bytes of the session key with the session id. */
1134 for (i = 0; i < 16; i++)
1135 session_key[i] ^= session_id[i];
1137 /* Set the session key. From this on all communications will be encrypted. */
1138 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
1140 /* Destroy our copy of the session key. It is no longer needed. */
1141 memset(session_key, 0, sizeof(session_key));
1143 debug("Received session key; encryption turned on.");
1145 /* Send an acknowledgement packet. Note that this packet is sent encrypted. */
1146 packet_start(SSH_SMSG_SUCCESS);
1148 packet_write_wait();
1152 * SSH2 key exchange: diffie-hellman-group1-sha1
1157 Buffer *server_kexinit;
1158 Buffer *client_kexinit;
1159 int payload_len, dlen;
1161 unsigned int klen, kout;
1163 unsigned char *signature = NULL;
1164 unsigned char *server_host_key_blob = NULL;
1165 unsigned int sbloblen;
1167 BIGNUM *dh_client_pub = 0;
1168 BIGNUM *shared_secret = 0;
1170 unsigned char *kbuf;
1171 unsigned char *hash;
1173 char *cprop[PROPOSAL_MAX];
1174 char *sprop[PROPOSAL_MAX];
1178 if (options.ciphers != NULL) {
1179 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1180 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
1183 debug("Sending KEX init.");
1185 for (i = 0; i < PROPOSAL_MAX; i++)
1186 sprop[i] = xstrdup(myproposal[i]);
1187 server_kexinit = kex_init(sprop);
1188 packet_start(SSH2_MSG_KEXINIT);
1189 packet_put_raw(buffer_ptr(server_kexinit), buffer_len(server_kexinit));
1191 packet_write_wait();
1195 packet_read_expect(&payload_len, SSH2_MSG_KEXINIT);
1198 * save raw KEXINIT payload in buffer. this is used during
1199 * computation of the session_id and the session keys.
1201 client_kexinit = xmalloc(sizeof(*client_kexinit));
1202 buffer_init(client_kexinit);
1203 ptr = packet_get_raw(&payload_len);
1204 buffer_append(client_kexinit, ptr, payload_len);
1207 for (i = 0; i < 16; i++)
1208 (void) packet_get_char();
1209 /* save kex init proposal strings */
1210 for (i = 0; i < PROPOSAL_MAX; i++) {
1211 cprop[i] = packet_get_string(NULL);
1212 debug("got kexinit string: %s", cprop[i]);
1215 i = (int) packet_get_char();
1216 debug("first kex follow == %d", i);
1217 i = packet_get_int();
1218 debug("reserved == %d", i);
1220 debug("done read kexinit");
1221 kex = kex_choose_conf(cprop, sprop, 1);
1225 debug("Wait SSH2_MSG_KEXDH_INIT.");
1226 packet_read_expect(&payload_len, SSH2_MSG_KEXDH_INIT);
1229 dh_client_pub = BN_new();
1230 if (dh_client_pub == NULL)
1231 fatal("dh_client_pub == NULL");
1232 packet_get_bignum2(dh_client_pub, &dlen);
1235 fprintf(stderr, "\ndh_client_pub= ");
1236 bignum_print(dh_client_pub);
1237 fprintf(stderr, "\n");
1238 debug("bits %d", BN_num_bits(dh_client_pub));
1241 /* generate DH key */
1242 dh = dh_new_group1(); /* XXX depends on 'kex' */
1245 fprintf(stderr, "\np= ");
1246 bignum_print(dh->p);
1247 fprintf(stderr, "\ng= ");
1248 bignum_print(dh->g);
1249 fprintf(stderr, "\npub= ");
1250 bignum_print(dh->pub_key);
1251 fprintf(stderr, "\n");
1253 if (!dh_pub_is_valid(dh, dh_client_pub))
1254 packet_disconnect("bad client public DH value");
1257 kbuf = xmalloc(klen);
1258 kout = DH_compute_key(kbuf, dh_client_pub, dh);
1261 debug("shared secret: len %d/%d", klen, kout);
1262 fprintf(stderr, "shared secret == ");
1263 for (i = 0; i< kout; i++)
1264 fprintf(stderr, "%02x", (kbuf[i])&0xff);
1265 fprintf(stderr, "\n");
1267 shared_secret = BN_new();
1269 BN_bin2bn(kbuf, kout, shared_secret);
1270 memset(kbuf, 0, klen);
1273 /* XXX precompute? */
1274 dsa_make_key_blob(sensitive_data.dsa_host_key, &server_host_key_blob, &sbloblen);
1276 /* calc H */ /* XXX depends on 'kex' */
1278 client_version_string,
1279 server_version_string,
1280 buffer_ptr(client_kexinit), buffer_len(client_kexinit),
1281 buffer_ptr(server_kexinit), buffer_len(server_kexinit),
1282 (char *)server_host_key_blob, sbloblen,
1287 buffer_free(client_kexinit);
1288 buffer_free(server_kexinit);
1289 xfree(client_kexinit);
1290 xfree(server_kexinit);
1292 fprintf(stderr, "hash == ");
1293 for (i = 0; i< 20; i++)
1294 fprintf(stderr, "%02x", (hash[i])&0xff);
1295 fprintf(stderr, "\n");
1297 /* save session id := H */
1298 /* XXX hashlen depends on KEX */
1299 session_id2_len = 20;
1300 session_id2 = xmalloc(session_id2_len);
1301 memcpy(session_id2, hash, session_id2_len);
1304 /* XXX hashlen depends on KEX */
1305 dsa_sign(sensitive_data.dsa_host_key, &signature, &slen, hash, 20);
1307 destroy_sensitive_data();
1309 /* send server hostkey, DH pubkey 'f' and singed H */
1310 packet_start(SSH2_MSG_KEXDH_REPLY);
1311 packet_put_string((char *)server_host_key_blob, sbloblen);
1312 packet_put_bignum2(dh->pub_key); /* f */
1313 packet_put_string((char *)signature, slen);
1316 xfree(server_host_key_blob);
1317 packet_write_wait();
1319 kex_derive_keys(kex, hash, shared_secret);
1320 packet_set_kex(kex);
1322 /* have keys, free DH */
1325 debug("send SSH2_MSG_NEWKEYS.");
1326 packet_start(SSH2_MSG_NEWKEYS);
1328 packet_write_wait();
1329 debug("done: send SSH2_MSG_NEWKEYS.");
1331 debug("Wait SSH2_MSG_NEWKEYS.");
1332 packet_read_expect(&payload_len, SSH2_MSG_NEWKEYS);
1333 debug("GOT SSH2_MSG_NEWKEYS.");
1336 /* send 1st encrypted/maced/compressed message */
1337 packet_start(SSH2_MSG_IGNORE);
1338 packet_put_cstring("markus");
1340 packet_write_wait();
1342 debug("done: KEX2.");