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.105 2000/04/14 10:30:33 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"
47 int allow_severity = LOG_INFO;
48 int deny_severity = LOG_WARNING;
55 /* Server configuration options. */
56 ServerOptions options;
58 /* Name of the server configuration file. */
59 char *config_file_name = SERVER_CONFIG_FILE;
62 * Flag indicating whether IPv4 or IPv6. This can be set on the command line.
63 * Default value is AF_UNSPEC means both IPv4 and IPv6.
66 int IPv4or6 = AF_INET;
68 int IPv4or6 = AF_UNSPEC;
72 * Debug mode flag. This can be set on the command line. If debug
73 * mode is enabled, extra debugging output will be sent to the system
74 * log, the daemon will not go to background, and will exit after processing
75 * the first connection.
79 /* Flag indicating that the daemon is being started from inetd. */
82 /* debug goes to stderr unless inetd_flag is set */
85 /* argv[0] without path. */
88 /* Saved arguments to main(). */
92 * The sockets that the server is listening; this is used in the SIGHUP
95 #define MAX_LISTEN_SOCKS 16
96 int listen_socks[MAX_LISTEN_SOCKS];
97 int num_listen_socks = 0;
100 * the client's version string, passed by sshd2 in compat mode. if != NULL,
101 * sshd will skip the version-number exchange
103 char *client_version_string = NULL;
104 char *server_version_string = NULL;
107 * Any really sensitive data in the application is contained in this
108 * structure. The idea is that this structure could be locked into memory so
109 * that the pages do not get written into swap. However, there are some
110 * problems. The private key contains BIGNUMs, and we do not (in principle)
111 * have access to the internals of them, and locking just the structure is
112 * not very useful. Currently, memory locking is not implemented.
115 RSA *private_key; /* Private part of server key. */
116 RSA *host_key; /* Private part of host key. */
120 * Flag indicating whether the current session key has been used. This flag
121 * is set whenever the key is used, and cleared when the key is regenerated.
125 /* This is set to true when SIGHUP is received. */
126 int received_sighup = 0;
128 /* Public side of the server key. This value is regenerated regularly with
132 /* session identifier, used by RSA-auth */
133 unsigned char session_id[16];
135 /* Prototypes for various functions defined later in this file. */
140 * Close all listening sockets
143 close_listen_socks(void)
146 for (i = 0; i < num_listen_socks; i++)
147 close(listen_socks[i]);
148 num_listen_socks = -1;
152 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
153 * the effect is to reread the configuration file (and to regenerate
157 sighup_handler(int sig)
160 signal(SIGHUP, sighup_handler);
164 * Called from the main program after receiving SIGHUP.
165 * Restarts the server.
170 log("Received SIGHUP; restarting.");
171 close_listen_socks();
172 execv(saved_argv[0], saved_argv);
173 log("RESTART FAILED: av0='%s', error: %s.", av0, strerror(errno));
178 * Generic signal handler for terminating signals in the master daemon.
179 * These close the listen socket; not closing it seems to cause "Address
180 * already in use" problems on some machines, which is inconvenient.
183 sigterm_handler(int sig)
185 log("Received signal %d; terminating.", sig);
186 close_listen_socks();
191 * SIGCHLD handler. This is called whenever a child dies. This will then
192 * reap any zombies left by exited c.
195 main_sigchld_handler(int sig)
197 int save_errno = errno;
200 while (waitpid(-1, &status, WNOHANG) > 0)
203 signal(SIGCHLD, main_sigchld_handler);
208 * Signal handler for the alarm after the login grace period has expired.
211 grace_alarm_handler(int sig)
213 /* Close the connection. */
216 /* Log error and exit. */
217 fatal("Timeout before authentication for %s.", get_remote_ipaddr());
221 * Signal handler for the key regeneration alarm. Note that this
222 * alarm only occurs in the daemon waiting for connections, and it does not
223 * do anything with the private key or random state before forking.
224 * Thus there should be no concurrency control/asynchronous execution
228 key_regeneration_alarm(int sig)
230 int save_errno = errno;
232 /* Check if we should generate a new key. */
234 /* This should really be done in the background. */
235 log("Generating new %d bit RSA key.", options.server_key_bits);
237 if (sensitive_data.private_key != NULL)
238 RSA_free(sensitive_data.private_key);
239 sensitive_data.private_key = RSA_new();
241 if (public_key != NULL)
242 RSA_free(public_key);
243 public_key = RSA_new();
245 rsa_generate_key(sensitive_data.private_key, public_key,
246 options.server_key_bits);
249 log("RSA key generation complete.");
251 /* Reschedule the alarm. */
252 signal(SIGALRM, key_regeneration_alarm);
253 alarm(options.key_regeneration_time);
262 if(*t == '\n' || *t == '\r') {
273 sshd_exchange_identification(int sock_in, int sock_out)
276 int remote_major, remote_minor;
279 char buf[256]; /* Must not be larger than remote_version. */
280 char remote_version[256]; /* Must be at least as big as buf. */
282 if ((options.protocol & SSH_PROTO_1) &&
283 (options.protocol & SSH_PROTO_2)) {
284 major = PROTOCOL_MAJOR_1;
286 } else if (options.protocol & SSH_PROTO_2) {
287 major = PROTOCOL_MAJOR_2;
288 minor = PROTOCOL_MINOR_2;
290 major = PROTOCOL_MAJOR_1;
291 minor = PROTOCOL_MINOR_1;
293 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", major, minor, SSH_VERSION);
294 server_version_string = xstrdup(buf);
296 if (client_version_string == NULL) {
297 /* Send our protocol version identification. */
298 if (atomicio(write, sock_out, server_version_string, strlen(server_version_string))
299 != strlen(server_version_string)) {
300 log("Could not write ident string to %s.", get_remote_ipaddr());
304 /* Read other side\'s version identification. */
305 for (i = 0; i < sizeof(buf) - 1; i++) {
306 if (read(sock_in, &buf[i], 1) != 1) {
307 log("Did not receive ident string from %s.", get_remote_ipaddr());
310 if (buf[i] == '\r') {
315 if (buf[i] == '\n') {
321 buf[sizeof(buf) - 1] = 0;
322 client_version_string = xstrdup(buf);
326 * Check that the versions match. In future this might accept
327 * several versions and set appropriate flags to handle them.
329 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
330 &remote_major, &remote_minor, remote_version) != 3) {
331 s = "Protocol mismatch.\n";
332 (void) atomicio(write, sock_out, s, strlen(s));
335 log("Bad protocol version identification '%.100s' from %s",
336 client_version_string, get_remote_ipaddr());
339 debug("Client protocol version %d.%d; client software version %.100s",
340 remote_major, remote_minor, remote_version);
342 compat_datafellows(remote_version);
345 switch(remote_major) {
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 */
358 if (remote_minor == 99) {
359 if (options.protocol & SSH_PROTO_2)
366 if (options.protocol & SSH_PROTO_2) {
375 chop(server_version_string);
376 chop(client_version_string);
377 debug("Local version string %.200s", server_version_string);
380 s = "Protocol major versions differ.\n";
381 (void) atomicio(write, sock_out, s, strlen(s));
384 log("Protocol major versions differ for %s: %.200s vs. %.200s",
386 server_version_string, client_version_string);
392 * Main program for the daemon.
395 main(int ac, char **av)
399 int opt, sock_in = 0, sock_out = 0, newsock, i, fdsetsz, pid, on = 1;
403 struct sockaddr_storage from;
404 const char *remote_ip;
408 struct linger linger;
410 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
411 int listen_sock, maxfd;
415 if (strchr(av[0], '/'))
416 av0 = strrchr(av[0], '/') + 1;
420 /* Initialize configuration options to their default values. */
421 initialize_server_options(&options);
423 /* Parse command-line arguments. */
424 while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:diqQ46")) != EOF) {
433 config_file_name = optarg;
437 options.log_level = SYSLOG_LEVEL_DEBUG;
446 options.log_level = SYSLOG_LEVEL_QUIET;
449 options.server_key_bits = atoi(optarg);
452 options.ports_from_cmdline = 1;
453 if (options.num_ports >= MAX_PORTS)
454 fatal("too many ports.\n");
455 options.ports[options.num_ports++] = atoi(optarg);
458 options.login_grace_time = atoi(optarg);
461 options.key_regeneration_time = atoi(optarg);
464 options.host_key_file = optarg;
467 client_version_string = optarg;
468 /* only makes sense with inetd_flag, i.e. no listen() */
473 fprintf(stderr, "sshd version %s\n", SSH_VERSION);
474 fprintf(stderr, "Usage: %s [options]\n", av0);
475 fprintf(stderr, "Options:\n");
476 fprintf(stderr, " -f file Configuration file (default %s)\n", SERVER_CONFIG_FILE);
477 fprintf(stderr, " -d Debugging mode\n");
478 fprintf(stderr, " -i Started from inetd\n");
479 fprintf(stderr, " -q Quiet (no logging)\n");
480 fprintf(stderr, " -p port Listen on the specified port (default: 22)\n");
481 fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n");
482 fprintf(stderr, " -g seconds Grace period for authentication (default: 300)\n");
483 fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n");
484 fprintf(stderr, " -h file File from which to read host key (default: %s)\n",
486 fprintf(stderr, " -4 Use IPv4 only\n");
487 fprintf(stderr, " -6 Use IPv6 only\n");
493 * Force logging to stderr until we have loaded the private host
494 * key (unless started from inetd)
497 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
498 options.log_facility == -1 ? SYSLOG_FACILITY_AUTH : options.log_facility,
501 /* check if RSA support exists */
502 if (rsa_alive() == 0) {
504 printf("sshd: no RSA support in libssl and libcrypto -- exiting. See ssl(8)\n");
505 log("no RSA support in libssl and libcrypto -- exiting. See ssl(8)");
508 /* Read server configuration options from the configuration file. */
509 read_server_config(&options, config_file_name);
511 /* Fill in default values for those options not explicitly set. */
512 fill_default_server_options(&options);
514 /* Check certain values for sanity. */
515 if (options.server_key_bits < 512 ||
516 options.server_key_bits > 32768) {
517 fprintf(stderr, "Bad server key size.\n");
520 /* Check that there are no remaining arguments. */
522 fprintf(stderr, "Extra argument %s.\n", av[optind]);
526 debug("sshd version %.100s", SSH_VERSION);
528 sensitive_data.host_key = RSA_new();
530 /* Load the host key. It must have empty passphrase. */
531 if (!load_private_key(options.host_key_file, "",
532 sensitive_data.host_key, &comment)) {
533 error("Could not load host key: %.200s: %.100s",
534 options.host_key_file, strerror(errno));
539 /* Initialize the log (it is reinitialized below in case we
541 if (debug_flag && !inetd_flag)
543 log_init(av0, options.log_level, options.log_facility, log_stderr);
545 /* If not in debugging mode, and not started from inetd,
546 disconnect from the controlling terminal, and fork. The
547 original process exits. */
548 if (!debug_flag && !inetd_flag) {
551 #endif /* TIOCNOTTY */
552 if (daemon(0, 0) < 0)
553 fatal("daemon() failed: %.200s", strerror(errno));
555 /* Disconnect from the controlling tty. */
557 fd = open("/dev/tty", O_RDWR | O_NOCTTY);
559 (void) ioctl(fd, TIOCNOTTY, NULL);
562 #endif /* TIOCNOTTY */
564 /* Reinitialize the log (because of the fork above). */
565 log_init(av0, options.log_level, options.log_facility, log_stderr);
567 /* Check that server and host key lengths differ sufficiently.
568 This is necessary to make double encryption work with rsaref.
569 Oh, I hate software patents. I dont know if this can go? Niels */
570 if (options.server_key_bits >
571 BN_num_bits(sensitive_data.host_key->n) - SSH_KEY_BITS_RESERVED &&
572 options.server_key_bits <
573 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
574 options.server_key_bits =
575 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED;
576 debug("Forcing server key to %d bits to make it differ from host key.",
577 options.server_key_bits);
579 /* Do not display messages to stdout in RSA code. */
582 /* Initialize the random number generator. */
585 /* Chdir to the root directory so that the current disk can be
586 unmounted if desired. */
589 /* Start listening for a socket, unless started from inetd. */
592 s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */
596 /* We intentionally do not close the descriptors 0, 1, and 2
597 as our code for setting the descriptors won\'t work
598 if ttyfd happens to be one of those. */
599 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
601 public_key = RSA_new();
602 sensitive_data.private_key = RSA_new();
604 /* XXX check options.protocol */
605 log("Generating %d bit RSA key.", options.server_key_bits);
606 rsa_generate_key(sensitive_data.private_key, public_key,
607 options.server_key_bits);
609 log("RSA key generation complete.");
611 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
612 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
614 if (num_listen_socks >= MAX_LISTEN_SOCKS)
615 fatal("Too many listen sockets. "
616 "Enlarge MAX_LISTEN_SOCKS");
617 if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
618 ntop, sizeof(ntop), strport, sizeof(strport),
619 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
620 error("getnameinfo failed");
623 /* Create socket for listening. */
624 listen_sock = socket(ai->ai_family, SOCK_STREAM, 0);
625 if (listen_sock < 0) {
626 /* kernel may not support ipv6 */
627 verbose("socket: %.100s", strerror(errno));
630 if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) {
631 error("listen_sock O_NONBLOCK: %s", strerror(errno));
636 * Set socket options. We try to make the port
637 * reusable and have it close as fast as possible
638 * without waiting in unnecessary wait states on
641 setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
642 (void *) &on, sizeof(on));
645 setsockopt(listen_sock, SOL_SOCKET, SO_LINGER,
646 (void *) &linger, sizeof(linger));
648 debug("Bind to port %s on %s.", strport, ntop);
650 /* Bind the socket to the desired port. */
651 if ((bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) &&
653 error("Bind to port %s on %s failed: %.200s.",
654 strport, ntop, strerror(errno));
658 listen_socks[num_listen_socks] = listen_sock;
661 /* Start listening on the port. */
662 log("Server listening on %s port %s.", ntop, strport);
663 if (listen(listen_sock, 5) < 0)
664 fatal("listen: %.100s", strerror(errno));
667 freeaddrinfo(options.listen_addrs);
669 if (!num_listen_socks)
670 fatal("Cannot bind any address.");
674 * Record our pid in /etc/sshd_pid to make it easier
675 * to kill the correct sshd. We don\'t want to do
676 * this before the bind above because the bind will
677 * fail if there already is a daemon, and this will
678 * overwrite any old pid in the file.
680 f = fopen(SSH_DAEMON_PID_FILE, "w");
682 fprintf(f, "%u\n", (unsigned int) getpid());
687 public_key = RSA_new();
688 sensitive_data.private_key = RSA_new();
690 log("Generating %d bit RSA key.", options.server_key_bits);
691 rsa_generate_key(sensitive_data.private_key, public_key,
692 options.server_key_bits);
694 log("RSA key generation complete.");
696 /* Schedule server key regeneration alarm. */
697 signal(SIGALRM, key_regeneration_alarm);
698 alarm(options.key_regeneration_time);
700 /* Arrange to restart on SIGHUP. The handler needs listen_sock. */
701 signal(SIGHUP, sighup_handler);
702 signal(SIGTERM, sigterm_handler);
703 signal(SIGQUIT, sigterm_handler);
705 /* Arrange SIGCHLD to be caught. */
706 signal(SIGCHLD, main_sigchld_handler);
708 /* setup fd set for listen */
710 for (i = 0; i < num_listen_socks; i++)
711 if (listen_socks[i] > maxfd)
712 maxfd = listen_socks[i];
713 fdsetsz = howmany(maxfd, NFDBITS) * sizeof(fd_mask);
714 fdset = (fd_set *)xmalloc(fdsetsz);
717 * Stay listening for connections until the system crashes or
718 * the daemon is killed with a signal.
723 /* Wait in select until there is a connection. */
724 memset(fdset, 0, fdsetsz);
725 for (i = 0; i < num_listen_socks; i++)
726 FD_SET(listen_socks[i], fdset);
727 if (select(maxfd + 1, fdset, NULL, NULL, NULL) < 0) {
729 error("select: %.100s", strerror(errno));
732 for (i = 0; i < num_listen_socks; i++) {
733 if (!FD_ISSET(listen_socks[i], fdset))
735 fromlen = sizeof(from);
736 newsock = accept(listen_socks[i], (struct sockaddr *)&from,
739 if (errno != EINTR && errno != EWOULDBLOCK)
740 error("accept: %.100s", strerror(errno));
743 if (fcntl(newsock, F_SETFL, 0) < 0) {
744 error("newsock del O_NONBLOCK: %s", strerror(errno));
748 * Got connection. Fork a child to handle it, unless
749 * we are in debugging mode.
753 * In debugging mode. Close the listening
754 * socket, and start processing the
755 * connection without forking.
757 debug("Server will not fork when running in debugging mode.");
758 close_listen_socks();
765 * Normal production daemon. Fork, and have
766 * the child process the connection. The
767 * parent continues listening.
769 if ((pid = fork()) == 0) {
771 * Child. Close the listening socket, and start using the
772 * accepted socket. Reinitialize logging (since our pid has
773 * changed). We break out of the loop to handle the connection.
775 close_listen_socks();
778 log_init(av0, options.log_level, options.log_facility, log_stderr);
783 /* Parent. Stay in the loop. */
785 error("fork: %.100s", strerror(errno));
787 debug("Forked child %d.", pid);
789 /* Mark that the key has been used (it was "given" to the child). */
794 /* Close the new socket (the child is now taking care of it). */
796 } /* for (i = 0; i < num_listen_socks; i++) */
797 /* child process check (or debug mode) */
798 if (num_listen_socks < 0)
803 /* This is the child processing a new connection. */
806 * Disable the key regeneration alarm. We will not regenerate the
807 * key since we are no longer in a position to give it to anyone. We
808 * will not restart on SIGHUP since it no longer makes sense.
811 signal(SIGALRM, SIG_DFL);
812 signal(SIGHUP, SIG_DFL);
813 signal(SIGTERM, SIG_DFL);
814 signal(SIGQUIT, SIG_DFL);
815 signal(SIGCHLD, SIG_DFL);
818 * Set socket options for the connection. We want the socket to
819 * close as fast as possible without waiting for anything. If the
820 * connection is not a socket, these will do nothing.
822 /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
825 setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
828 * Register our connection. This turns encryption off because we do
831 packet_set_connection(sock_in, sock_out);
833 remote_port = get_remote_port();
834 remote_ip = get_remote_ipaddr();
836 /* Check whether logins are denied from this host. */
838 /* XXX LIBWRAP noes not know about IPv6 */
840 struct request_info req;
842 request_init(&req, RQ_DAEMON, av0, RQ_FILE, sock_in, NULL);
845 if (!hosts_access(&req)) {
850 /*XXX IPv6 verbose("Connection from %.500s port %d", eval_client(&req), remote_port); */
853 /* Log the connection. */
854 verbose("Connection from %.500s port %d", remote_ip, remote_port);
857 * We don\'t want to listen forever unless the other side
858 * successfully authenticates itself. So we set up an alarm which is
859 * cleared after successful authentication. A limit of zero
860 * indicates no limit. Note that we don\'t set the alarm in debugging
861 * mode; it is just annoying to have the server exit just when you
862 * are about to discover the bug.
864 signal(SIGALRM, grace_alarm_handler);
866 alarm(options.login_grace_time);
868 sshd_exchange_identification(sock_in, sock_out);
870 * Check that the connection comes from a privileged port. Rhosts-
871 * and Rhosts-RSA-Authentication only make sense from priviledged
872 * programs. Of course, if the intruder has root access on his local
873 * machine, he can connect from any port. So do not use these
874 * authentication methods from machines that you do not trust.
876 if (remote_port >= IPPORT_RESERVED ||
877 remote_port < IPPORT_RESERVED / 2) {
878 options.rhosts_authentication = 0;
879 options.rhosts_rsa_authentication = 0;
882 if (!packet_connection_is_ipv4() &&
883 options.kerberos_authentication) {
884 debug("Kerberos Authentication disabled, only available for IPv4.");
885 options.kerberos_authentication = 0;
889 packet_set_nonblocking();
891 /* perform the key exchange */
892 /* authenticate user and start session */
895 do_authentication2();
902 /* Cleanup user's ticket cache file. */
903 if (options.kerberos_ticket_cleanup)
907 /* The connection has been terminated. */
908 verbose("Closing connection to %.100s", remote_ip);
926 BIGNUM *session_key_int;
927 unsigned char session_key[SSH_SESSION_KEY_LENGTH];
928 unsigned char cookie[8];
929 unsigned int cipher_type, auth_mask, protocol_flags;
933 * Generate check bytes that the client must send back in the user
934 * packet in order for it to be accepted; this is used to defy ip
935 * spoofing attacks. Note that this only works against somebody
936 * doing IP spoofing from a remote machine; any machine on the local
937 * network can still see outgoing packets and catch the random
938 * cookie. This only affects rhosts authentication, and this is one
939 * of the reasons why it is inherently insecure.
941 for (i = 0; i < 8; i++) {
944 cookie[i] = rand & 0xff;
949 * Send our public key. We include in the packet 64 bits of random
950 * data that must be matched in the reply in order to prevent IP
953 packet_start(SSH_SMSG_PUBLIC_KEY);
954 for (i = 0; i < 8; i++)
955 packet_put_char(cookie[i]);
957 /* Store our public server RSA key. */
958 packet_put_int(BN_num_bits(public_key->n));
959 packet_put_bignum(public_key->e);
960 packet_put_bignum(public_key->n);
962 /* Store our public host RSA key. */
963 packet_put_int(BN_num_bits(sensitive_data.host_key->n));
964 packet_put_bignum(sensitive_data.host_key->e);
965 packet_put_bignum(sensitive_data.host_key->n);
967 /* Put protocol flags. */
968 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
970 /* Declare which ciphers we support. */
971 packet_put_int(cipher_mask1());
973 /* Declare supported authentication types. */
975 if (options.rhosts_authentication)
976 auth_mask |= 1 << SSH_AUTH_RHOSTS;
977 if (options.rhosts_rsa_authentication)
978 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
979 if (options.rsa_authentication)
980 auth_mask |= 1 << SSH_AUTH_RSA;
982 if (options.kerberos_authentication)
983 auth_mask |= 1 << SSH_AUTH_KERBEROS;
986 if (options.kerberos_tgt_passing)
987 auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
988 if (options.afs_token_passing)
989 auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
992 if (options.skey_authentication == 1)
993 auth_mask |= 1 << SSH_AUTH_TIS;
995 if (options.password_authentication)
996 auth_mask |= 1 << SSH_AUTH_PASSWORD;
997 packet_put_int(auth_mask);
999 /* Send the packet and wait for it to be sent. */
1001 packet_write_wait();
1003 debug("Sent %d bit public key and %d bit host key.",
1004 BN_num_bits(public_key->n), BN_num_bits(sensitive_data.host_key->n));
1006 /* Read clients reply (cipher type and session key). */
1007 packet_read_expect(&plen, SSH_CMSG_SESSION_KEY);
1009 /* Get cipher type and check whether we accept this. */
1010 cipher_type = packet_get_char();
1012 if (!(cipher_mask() & (1 << cipher_type)))
1013 packet_disconnect("Warning: client selects unsupported cipher.");
1015 /* Get check bytes from the packet. These must match those we
1016 sent earlier with the public key packet. */
1017 for (i = 0; i < 8; i++)
1018 if (cookie[i] != packet_get_char())
1019 packet_disconnect("IP Spoofing check bytes do not match.");
1021 debug("Encryption type: %.200s", cipher_name(cipher_type));
1023 /* Get the encrypted integer. */
1024 session_key_int = BN_new();
1025 packet_get_bignum(session_key_int, &slen);
1027 protocol_flags = packet_get_int();
1028 packet_set_protocol_flags(protocol_flags);
1030 packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY);
1033 * Decrypt it using our private server key and private host key (key
1034 * with larger modulus first).
1036 if (BN_cmp(sensitive_data.private_key->n, sensitive_data.host_key->n) > 0) {
1037 /* Private key has bigger modulus. */
1038 if (BN_num_bits(sensitive_data.private_key->n) <
1039 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
1040 fatal("do_connection: %s: private_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1041 get_remote_ipaddr(),
1042 BN_num_bits(sensitive_data.private_key->n),
1043 BN_num_bits(sensitive_data.host_key->n),
1044 SSH_KEY_BITS_RESERVED);
1046 rsa_private_decrypt(session_key_int, session_key_int,
1047 sensitive_data.private_key);
1048 rsa_private_decrypt(session_key_int, session_key_int,
1049 sensitive_data.host_key);
1051 /* Host key has bigger modulus (or they are equal). */
1052 if (BN_num_bits(sensitive_data.host_key->n) <
1053 BN_num_bits(sensitive_data.private_key->n) + SSH_KEY_BITS_RESERVED) {
1054 fatal("do_connection: %s: host_key %d < private_key %d + SSH_KEY_BITS_RESERVED %d",
1055 get_remote_ipaddr(),
1056 BN_num_bits(sensitive_data.host_key->n),
1057 BN_num_bits(sensitive_data.private_key->n),
1058 SSH_KEY_BITS_RESERVED);
1060 rsa_private_decrypt(session_key_int, session_key_int,
1061 sensitive_data.host_key);
1062 rsa_private_decrypt(session_key_int, session_key_int,
1063 sensitive_data.private_key);
1066 compute_session_id(session_id, cookie,
1067 sensitive_data.host_key->n,
1068 sensitive_data.private_key->n);
1070 /* Destroy the private and public keys. They will no longer be needed. */
1071 RSA_free(public_key);
1072 RSA_free(sensitive_data.private_key);
1073 RSA_free(sensitive_data.host_key);
1076 * Extract session key from the decrypted integer. The key is in the
1077 * least significant 256 bits of the integer; the first byte of the
1078 * key is in the highest bits.
1080 BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1081 len = BN_num_bytes(session_key_int);
1082 if (len < 0 || len > sizeof(session_key))
1083 fatal("do_connection: bad len from %s: session_key_int %d > sizeof(session_key) %d",
1084 get_remote_ipaddr(),
1085 len, sizeof(session_key));
1086 memset(session_key, 0, sizeof(session_key));
1087 BN_bn2bin(session_key_int, session_key + sizeof(session_key) - len);
1089 /* Destroy the decrypted integer. It is no longer needed. */
1090 BN_clear_free(session_key_int);
1092 /* Xor the first 16 bytes of the session key with the session id. */
1093 for (i = 0; i < 16; i++)
1094 session_key[i] ^= session_id[i];
1096 /* Set the session key. From this on all communications will be encrypted. */
1097 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
1099 /* Destroy our copy of the session key. It is no longer needed. */
1100 memset(session_key, 0, sizeof(session_key));
1102 debug("Received session key; encryption turned on.");
1104 /* Send an acknowledgement packet. Note that this packet is sent encrypted. */
1105 packet_start(SSH_SMSG_SUCCESS);
1107 packet_write_wait();
1111 * SSH2 key exchange: diffie-hellman-group1-sha1
1116 Buffer *server_kexinit;
1117 Buffer *client_kexinit;
1118 int payload_len, dlen;
1120 unsigned int klen, kout;
1122 unsigned char *signature = NULL;
1123 unsigned char *server_host_key_blob = NULL;
1124 unsigned int sbloblen;
1126 BIGNUM *dh_client_pub = 0;
1127 BIGNUM *shared_secret = 0;
1129 unsigned char *kbuf;
1130 unsigned char *hash;
1132 Key *server_host_key;
1133 char *cprop[PROPOSAL_MAX];
1134 char *sprop[PROPOSAL_MAX];
1138 if (options.ciphers != NULL) {
1139 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1140 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
1143 debug("Sending KEX init.");
1145 for (i = 0; i < PROPOSAL_MAX; i++)
1146 sprop[i] = xstrdup(myproposal[i]);
1147 server_kexinit = kex_init(sprop);
1148 packet_start(SSH2_MSG_KEXINIT);
1149 packet_put_raw(buffer_ptr(server_kexinit), buffer_len(server_kexinit));
1151 packet_write_wait();
1155 packet_read_expect(&payload_len, SSH2_MSG_KEXINIT);
1158 * save raw KEXINIT payload in buffer. this is used during
1159 * computation of the session_id and the session keys.
1161 client_kexinit = xmalloc(sizeof(*client_kexinit));
1162 buffer_init(client_kexinit);
1163 ptr = packet_get_raw(&payload_len);
1164 buffer_append(client_kexinit, ptr, payload_len);
1167 for (i = 0; i < 16; i++)
1168 (void) packet_get_char();
1169 /* save kex init proposal strings */
1170 for (i = 0; i < PROPOSAL_MAX; i++) {
1171 cprop[i] = packet_get_string(NULL);
1172 debug("got kexinit string: %s", cprop[i]);
1175 i = (int) packet_get_char();
1176 debug("first kex follow == %d", i);
1177 i = packet_get_int();
1178 debug("reserved == %d", i);
1180 debug("done read kexinit");
1181 kex = kex_choose_conf(cprop, sprop, 1);
1185 debug("Wait SSH2_MSG_KEXDH_INIT.");
1186 packet_read_expect(&payload_len, SSH2_MSG_KEXDH_INIT);
1189 dh_client_pub = BN_new();
1190 if (dh_client_pub == NULL)
1191 fatal("dh_client_pub == NULL");
1192 packet_get_bignum2(dh_client_pub, &dlen);
1195 fprintf(stderr, "\ndh_client_pub= ");
1196 bignum_print(dh_client_pub);
1197 fprintf(stderr, "\n");
1198 debug("bits %d", BN_num_bits(dh_client_pub));
1201 /* generate DH key */
1202 dh = dh_new_group1(); /* XXX depends on 'kex' */
1205 fprintf(stderr, "\np= ");
1206 bignum_print(dh->p);
1207 fprintf(stderr, "\ng= ");
1208 bignum_print(dh->g);
1209 fprintf(stderr, "\npub= ");
1210 bignum_print(dh->pub_key);
1211 fprintf(stderr, "\n");
1213 if (!dh_pub_is_valid(dh, dh_client_pub))
1214 packet_disconnect("bad client public DH value");
1217 kbuf = xmalloc(klen);
1218 kout = DH_compute_key(kbuf, dh_client_pub, dh);
1221 debug("shared secret: len %d/%d", klen, kout);
1222 fprintf(stderr, "shared secret == ");
1223 for (i = 0; i< kout; i++)
1224 fprintf(stderr, "%02x", (kbuf[i])&0xff);
1225 fprintf(stderr, "\n");
1227 shared_secret = BN_new();
1229 BN_bin2bn(kbuf, kout, shared_secret);
1230 memset(kbuf, 0, klen);
1233 server_host_key = dsa_get_serverkey(options.dsa_key_file);
1234 dsa_make_serverkey_blob(server_host_key, &server_host_key_blob, &sbloblen);
1236 /* calc H */ /* XXX depends on 'kex' */
1238 client_version_string,
1239 server_version_string,
1240 buffer_ptr(client_kexinit), buffer_len(client_kexinit),
1241 buffer_ptr(server_kexinit), buffer_len(server_kexinit),
1242 (char *)server_host_key_blob, sbloblen,
1247 buffer_free(client_kexinit);
1248 buffer_free(server_kexinit);
1249 xfree(client_kexinit);
1250 xfree(server_kexinit);
1252 fprintf(stderr, "hash == ");
1253 for (i = 0; i< 20; i++)
1254 fprintf(stderr, "%02x", (hash[i])&0xff);
1255 fprintf(stderr, "\n");
1258 dsa_sign(server_host_key, &signature, &slen, hash, 20);
1259 /* hashlen depends on KEX */
1260 key_free(server_host_key);
1262 /* send server hostkey, DH pubkey 'f' and singed H */
1263 packet_start(SSH2_MSG_KEXDH_REPLY);
1264 packet_put_string((char *)server_host_key_blob, sbloblen);
1265 packet_put_bignum2(dh->pub_key); // f
1266 packet_put_string((char *)signature, slen);
1268 packet_write_wait();
1270 kex_derive_keys(kex, hash, shared_secret);
1271 packet_set_kex(kex);
1273 /* have keys, free DH */
1276 debug("send SSH2_MSG_NEWKEYS.");
1277 packet_start(SSH2_MSG_NEWKEYS);
1279 packet_write_wait();
1280 debug("done: send SSH2_MSG_NEWKEYS.");
1282 debug("Wait SSH2_MSG_NEWKEYS.");
1283 packet_read_expect(&payload_len, SSH2_MSG_NEWKEYS);
1284 debug("GOT SSH2_MSG_NEWKEYS.");
1287 /* send 1st encrypted/maced/compressed message */
1288 packet_start(SSH2_MSG_IGNORE);
1289 packet_put_cstring("markus");
1291 packet_write_wait();
1293 debug("done: KEX2.");