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.99 2000/04/07 09:17:39 markus Exp $");
33 # include <openssl/dh.h>
34 # include <openssl/bn.h>
35 # include <openssl/hmac.h>
36 # include <openssl/dsa.h>
37 # include <openssl/rsa.h>
42 # include <ssl/hmac.h>
51 #include "myproposal.h"
56 int allow_severity = LOG_INFO;
57 int deny_severity = LOG_WARNING;
64 /* Server configuration options. */
65 ServerOptions options;
67 /* Name of the server configuration file. */
68 char *config_file_name = SERVER_CONFIG_FILE;
71 * Flag indicating whether IPv4 or IPv6. This can be set on the command line.
72 * Default value is AF_UNSPEC means both IPv4 and IPv6.
75 int IPv4or6 = AF_INET;
77 int IPv4or6 = AF_UNSPEC;
80 /* Flag indicating whether SSH2 is enabled */
84 * Debug mode flag. This can be set on the command line. If debug
85 * mode is enabled, extra debugging output will be sent to the system
86 * log, the daemon will not go to background, and will exit after processing
87 * the first connection.
91 /* Flag indicating that the daemon is being started from inetd. */
94 /* debug goes to stderr unless inetd_flag is set */
97 /* argv[0] without path. */
100 /* Saved arguments to main(). */
104 * The sockets that the server is listening; this is used in the SIGHUP
107 #define MAX_LISTEN_SOCKS 16
108 int listen_socks[MAX_LISTEN_SOCKS];
109 int num_listen_socks = 0;
112 * the client's version string, passed by sshd2 in compat mode. if != NULL,
113 * sshd will skip the version-number exchange
115 char *client_version_string = NULL;
116 char *server_version_string = NULL;
119 * Any really sensitive data in the application is contained in this
120 * structure. The idea is that this structure could be locked into memory so
121 * that the pages do not get written into swap. However, there are some
122 * problems. The private key contains BIGNUMs, and we do not (in principle)
123 * have access to the internals of them, and locking just the structure is
124 * not very useful. Currently, memory locking is not implemented.
127 RSA *private_key; /* Private part of server key. */
128 RSA *host_key; /* Private part of host key. */
132 * Flag indicating whether the current session key has been used. This flag
133 * is set whenever the key is used, and cleared when the key is regenerated.
137 /* This is set to true when SIGHUP is received. */
138 int received_sighup = 0;
140 /* Public side of the server key. This value is regenerated regularly with
144 /* session identifier, used by RSA-auth */
145 unsigned char session_id[16];
147 /* Prototypes for various functions defined later in this file. */
152 * Close all listening sockets
155 close_listen_socks(void)
158 for (i = 0; i < num_listen_socks; i++)
159 close(listen_socks[i]);
160 num_listen_socks = -1;
164 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
165 * the effect is to reread the configuration file (and to regenerate
169 sighup_handler(int sig)
172 signal(SIGHUP, sighup_handler);
176 * Called from the main program after receiving SIGHUP.
177 * Restarts the server.
182 log("Received SIGHUP; restarting.");
183 close_listen_socks();
184 execv(saved_argv[0], saved_argv);
185 log("RESTART FAILED: av0='%s', error: %s.", av0, strerror(errno));
190 * Generic signal handler for terminating signals in the master daemon.
191 * These close the listen socket; not closing it seems to cause "Address
192 * already in use" problems on some machines, which is inconvenient.
195 sigterm_handler(int sig)
197 log("Received signal %d; terminating.", sig);
198 close_listen_socks();
203 * SIGCHLD handler. This is called whenever a child dies. This will then
204 * reap any zombies left by exited c.
207 main_sigchld_handler(int sig)
209 int save_errno = errno;
212 while (waitpid(-1, &status, WNOHANG) > 0)
215 signal(SIGCHLD, main_sigchld_handler);
220 * Signal handler for the alarm after the login grace period has expired.
223 grace_alarm_handler(int sig)
225 /* Close the connection. */
228 /* Log error and exit. */
229 fatal("Timeout before authentication for %s.", get_remote_ipaddr());
233 * Signal handler for the key regeneration alarm. Note that this
234 * alarm only occurs in the daemon waiting for connections, and it does not
235 * do anything with the private key or random state before forking.
236 * Thus there should be no concurrency control/asynchronous execution
240 key_regeneration_alarm(int sig)
242 int save_errno = errno;
244 /* Check if we should generate a new key. */
246 /* This should really be done in the background. */
247 log("Generating new %d bit RSA key.", options.server_key_bits);
249 if (sensitive_data.private_key != NULL)
250 RSA_free(sensitive_data.private_key);
251 sensitive_data.private_key = RSA_new();
253 if (public_key != NULL)
254 RSA_free(public_key);
255 public_key = RSA_new();
257 rsa_generate_key(sensitive_data.private_key, public_key,
258 options.server_key_bits);
261 log("RSA key generation complete.");
263 /* Reschedule the alarm. */
264 signal(SIGALRM, key_regeneration_alarm);
265 alarm(options.key_regeneration_time);
274 if(*t == '\n' || *t == '\r') {
285 sshd_exchange_identification(int sock_in, int sock_out)
288 int remote_major, remote_minor;
290 char buf[256]; /* Must not be larger than remote_version. */
291 char remote_version[256]; /* Must be at least as big as buf. */
293 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n",
294 allow_ssh2 ? 1 : PROTOCOL_MAJOR,
295 allow_ssh2 ? 99 : PROTOCOL_MINOR,
297 server_version_string = xstrdup(buf);
299 if (client_version_string == NULL) {
300 /* Send our protocol version identification. */
301 if (atomicio(write, sock_out, server_version_string, strlen(server_version_string))
302 != strlen(server_version_string)) {
303 log("Could not write ident string to %s.", get_remote_ipaddr());
307 /* Read other side\'s version identification. */
308 for (i = 0; i < sizeof(buf) - 1; i++) {
309 if (read(sock_in, &buf[i], 1) != 1) {
310 log("Did not receive ident string from %s.", get_remote_ipaddr());
313 if (buf[i] == '\r') {
319 if (buf[i] == '\n') {
325 buf[sizeof(buf) - 1] = 0;
326 client_version_string = xstrdup(buf);
330 * Check that the versions match. In future this might accept
331 * several versions and set appropriate flags to handle them.
333 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
334 &remote_major, &remote_minor, remote_version) != 3) {
335 s = "Protocol mismatch.\n";
336 (void) atomicio(write, sock_out, s, strlen(s));
339 log("Bad protocol version identification '%.100s' from %s",
340 client_version_string, get_remote_ipaddr());
343 debug("Client protocol version %d.%d; client software version %.100s",
344 remote_major, remote_minor, remote_version);
346 compat_datafellows(remote_version);
348 switch(remote_major) {
350 if (remote_minor < 3) {
351 packet_disconnect("Your ssh version is too old and"
352 "is no longer supported. Please install a newer version.");
353 } else if (remote_minor == 3) {
354 /* note that this disables agent-forwarding */
357 if (remote_minor != 99)
367 s = "Protocol major versions differ.\n";
368 (void) atomicio(write, sock_out, s, strlen(s));
371 log("Protocol major versions differ for %s: %d vs. %d",
372 get_remote_ipaddr(), PROTOCOL_MAJOR, remote_major);
376 chop(server_version_string);
377 chop(client_version_string);
381 * Main program for the daemon.
384 main(int ac, char **av)
388 int opt, sock_in = 0, sock_out = 0, newsock, i, fdsetsz, pid, on = 1;
392 struct sockaddr_storage from;
393 const char *remote_ip;
397 struct linger linger;
399 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
400 int listen_sock, maxfd;
404 if (strchr(av[0], '/'))
405 av0 = strrchr(av[0], '/') + 1;
409 /* Initialize configuration options to their default values. */
410 initialize_server_options(&options);
412 /* Parse command-line arguments. */
413 while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:diqQ246")) != EOF) {
425 config_file_name = optarg;
429 options.log_level = SYSLOG_LEVEL_DEBUG;
438 options.log_level = SYSLOG_LEVEL_QUIET;
441 options.server_key_bits = atoi(optarg);
444 options.ports_from_cmdline = 1;
445 if (options.num_ports >= MAX_PORTS)
446 fatal("too many ports.\n");
447 options.ports[options.num_ports++] = atoi(optarg);
450 options.login_grace_time = atoi(optarg);
453 options.key_regeneration_time = atoi(optarg);
456 options.host_key_file = optarg;
459 client_version_string = optarg;
460 /* only makes sense with inetd_flag, i.e. no listen() */
465 fprintf(stderr, "sshd version %s\n", SSH_VERSION);
466 fprintf(stderr, "Usage: %s [options]\n", av0);
467 fprintf(stderr, "Options:\n");
468 fprintf(stderr, " -f file Configuration file (default %s)\n", SERVER_CONFIG_FILE);
469 fprintf(stderr, " -d Debugging mode\n");
470 fprintf(stderr, " -i Started from inetd\n");
471 fprintf(stderr, " -q Quiet (no logging)\n");
472 fprintf(stderr, " -p port Listen on the specified port (default: 22)\n");
473 fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n");
474 fprintf(stderr, " -g seconds Grace period for authentication (default: 300)\n");
475 fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n");
476 fprintf(stderr, " -h file File from which to read host key (default: %s)\n",
478 fprintf(stderr, " -4 Use IPv4 only\n");
479 fprintf(stderr, " -6 Use IPv6 only\n");
485 * Force logging to stderr until we have loaded the private host
486 * key (unless started from inetd)
489 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
490 options.log_facility == -1 ? SYSLOG_FACILITY_AUTH : options.log_facility,
493 /* check if RSA support exists */
494 if (rsa_alive() == 0) {
496 printf("sshd: no RSA support in libssl and libcrypto -- exiting. See ssl(8)\n");
497 log("no RSA support in libssl and libcrypto -- exiting. See ssl(8)");
500 /* Read server configuration options from the configuration file. */
501 read_server_config(&options, config_file_name);
503 /* Fill in default values for those options not explicitly set. */
504 fill_default_server_options(&options);
506 /* Check certain values for sanity. */
507 if (options.server_key_bits < 512 ||
508 options.server_key_bits > 32768) {
509 fprintf(stderr, "Bad server key size.\n");
512 /* Check that there are no remaining arguments. */
514 fprintf(stderr, "Extra argument %s.\n", av[optind]);
518 debug("sshd version %.100s", SSH_VERSION);
520 sensitive_data.host_key = RSA_new();
522 /* Load the host key. It must have empty passphrase. */
523 if (!load_private_key(options.host_key_file, "",
524 sensitive_data.host_key, &comment)) {
525 error("Could not load host key: %.200s: %.100s",
526 options.host_key_file, strerror(errno));
531 /* Initialize the log (it is reinitialized below in case we
533 if (debug_flag && !inetd_flag)
535 log_init(av0, options.log_level, options.log_facility, log_stderr);
537 /* If not in debugging mode, and not started from inetd,
538 disconnect from the controlling terminal, and fork. The
539 original process exits. */
540 if (!debug_flag && !inetd_flag) {
543 #endif /* TIOCNOTTY */
544 if (daemon(0, 0) < 0)
545 fatal("daemon() failed: %.200s", strerror(errno));
547 /* Disconnect from the controlling tty. */
549 fd = open("/dev/tty", O_RDWR | O_NOCTTY);
551 (void) ioctl(fd, TIOCNOTTY, NULL);
554 #endif /* TIOCNOTTY */
556 /* Reinitialize the log (because of the fork above). */
557 log_init(av0, options.log_level, options.log_facility, log_stderr);
559 /* Check that server and host key lengths differ sufficiently.
560 This is necessary to make double encryption work with rsaref.
561 Oh, I hate software patents. I dont know if this can go? Niels */
562 if (options.server_key_bits >
563 BN_num_bits(sensitive_data.host_key->n) - SSH_KEY_BITS_RESERVED &&
564 options.server_key_bits <
565 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
566 options.server_key_bits =
567 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED;
568 debug("Forcing server key to %d bits to make it differ from host key.",
569 options.server_key_bits);
571 /* Do not display messages to stdout in RSA code. */
574 /* Initialize the random number generator. */
577 /* Chdir to the root directory so that the current disk can be
578 unmounted if desired. */
581 /* Start listening for a socket, unless started from inetd. */
584 s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */
588 /* We intentionally do not close the descriptors 0, 1, and 2
589 as our code for setting the descriptors won\'t work
590 if ttyfd happens to be one of those. */
591 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
593 public_key = RSA_new();
594 sensitive_data.private_key = RSA_new();
596 log("Generating %d bit RSA key.", options.server_key_bits);
597 rsa_generate_key(sensitive_data.private_key, public_key,
598 options.server_key_bits);
600 log("RSA key generation complete.");
602 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
603 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
605 if (num_listen_socks >= MAX_LISTEN_SOCKS)
606 fatal("Too many listen sockets. "
607 "Enlarge MAX_LISTEN_SOCKS");
608 if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
609 ntop, sizeof(ntop), strport, sizeof(strport),
610 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
611 error("getnameinfo failed");
614 /* Create socket for listening. */
615 listen_sock = socket(ai->ai_family, SOCK_STREAM, 0);
616 if (listen_sock < 0) {
617 /* kernel may not support ipv6 */
618 verbose("socket: %.100s", strerror(errno));
621 if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) {
622 error("listen_sock O_NONBLOCK: %s", strerror(errno));
627 * Set socket options. We try to make the port
628 * reusable and have it close as fast as possible
629 * without waiting in unnecessary wait states on
632 setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
633 (void *) &on, sizeof(on));
636 setsockopt(listen_sock, SOL_SOCKET, SO_LINGER,
637 (void *) &linger, sizeof(linger));
639 debug("Bind to port %s on %s.", strport, ntop);
641 /* Bind the socket to the desired port. */
642 if ((bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) &&
644 error("Bind to port %s on %s failed: %.200s.",
645 strport, ntop, strerror(errno));
649 listen_socks[num_listen_socks] = listen_sock;
652 /* Start listening on the port. */
653 log("Server listening on %s port %s.", ntop, strport);
654 if (listen(listen_sock, 5) < 0)
655 fatal("listen: %.100s", strerror(errno));
658 freeaddrinfo(options.listen_addrs);
660 if (!num_listen_socks)
661 fatal("Cannot bind any address.");
665 * Record our pid in /etc/sshd_pid to make it easier
666 * to kill the correct sshd. We don\'t want to do
667 * this before the bind above because the bind will
668 * fail if there already is a daemon, and this will
669 * overwrite any old pid in the file.
671 f = fopen(SSH_DAEMON_PID_FILE, "w");
673 fprintf(f, "%u\n", (unsigned int) getpid());
678 public_key = RSA_new();
679 sensitive_data.private_key = RSA_new();
681 log("Generating %d bit RSA key.", options.server_key_bits);
682 rsa_generate_key(sensitive_data.private_key, public_key,
683 options.server_key_bits);
685 log("RSA key generation complete.");
687 /* Schedule server key regeneration alarm. */
688 signal(SIGALRM, key_regeneration_alarm);
689 alarm(options.key_regeneration_time);
691 /* Arrange to restart on SIGHUP. The handler needs listen_sock. */
692 signal(SIGHUP, sighup_handler);
693 signal(SIGTERM, sigterm_handler);
694 signal(SIGQUIT, sigterm_handler);
696 /* Arrange SIGCHLD to be caught. */
697 signal(SIGCHLD, main_sigchld_handler);
699 /* setup fd set for listen */
701 for (i = 0; i < num_listen_socks; i++)
702 if (listen_socks[i] > maxfd)
703 maxfd = listen_socks[i];
704 fdsetsz = howmany(maxfd, NFDBITS) * sizeof(fd_mask);
705 fdset = (fd_set *)xmalloc(fdsetsz);
708 * Stay listening for connections until the system crashes or
709 * the daemon is killed with a signal.
714 /* Wait in select until there is a connection. */
715 memset(fdset, 0, fdsetsz);
716 for (i = 0; i < num_listen_socks; i++)
717 FD_SET(listen_socks[i], fdset);
718 if (select(maxfd + 1, fdset, NULL, NULL, NULL) < 0) {
720 error("select: %.100s", strerror(errno));
723 for (i = 0; i < num_listen_socks; i++) {
724 if (!FD_ISSET(listen_socks[i], fdset))
726 fromlen = sizeof(from);
727 newsock = accept(listen_socks[i], (struct sockaddr *)&from,
730 if (errno != EINTR && errno != EWOULDBLOCK)
731 error("accept: %.100s", strerror(errno));
734 if (fcntl(newsock, F_SETFL, 0) < 0) {
735 error("newsock del O_NONBLOCK: %s", strerror(errno));
739 * Got connection. Fork a child to handle it, unless
740 * we are in debugging mode.
744 * In debugging mode. Close the listening
745 * socket, and start processing the
746 * connection without forking.
748 debug("Server will not fork when running in debugging mode.");
749 close_listen_socks();
756 * Normal production daemon. Fork, and have
757 * the child process the connection. The
758 * parent continues listening.
760 if ((pid = fork()) == 0) {
762 * Child. Close the listening socket, and start using the
763 * accepted socket. Reinitialize logging (since our pid has
764 * changed). We break out of the loop to handle the connection.
766 close_listen_socks();
769 log_init(av0, options.log_level, options.log_facility, log_stderr);
774 /* Parent. Stay in the loop. */
776 error("fork: %.100s", strerror(errno));
778 debug("Forked child %d.", pid);
780 /* Mark that the key has been used (it was "given" to the child). */
785 /* Close the new socket (the child is now taking care of it). */
787 } /* for (i = 0; i < num_listen_socks; i++) */
788 /* child process check (or debug mode) */
789 if (num_listen_socks < 0)
794 /* This is the child processing a new connection. */
797 * Disable the key regeneration alarm. We will not regenerate the
798 * key since we are no longer in a position to give it to anyone. We
799 * will not restart on SIGHUP since it no longer makes sense.
802 signal(SIGALRM, SIG_DFL);
803 signal(SIGHUP, SIG_DFL);
804 signal(SIGTERM, SIG_DFL);
805 signal(SIGQUIT, SIG_DFL);
806 signal(SIGCHLD, SIG_DFL);
809 * Set socket options for the connection. We want the socket to
810 * close as fast as possible without waiting for anything. If the
811 * connection is not a socket, these will do nothing.
813 /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
816 setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
819 * Register our connection. This turns encryption off because we do
822 packet_set_connection(sock_in, sock_out);
824 remote_port = get_remote_port();
825 remote_ip = get_remote_ipaddr();
827 /* Check whether logins are denied from this host. */
829 /* XXX LIBWRAP noes not know about IPv6 */
831 struct request_info req;
833 request_init(&req, RQ_DAEMON, av0, RQ_FILE, sock_in, NULL);
836 if (!hosts_access(&req)) {
841 /*XXX IPv6 verbose("Connection from %.500s port %d", eval_client(&req), remote_port); */
844 /* Log the connection. */
845 verbose("Connection from %.500s port %d", remote_ip, remote_port);
848 * We don\'t want to listen forever unless the other side
849 * successfully authenticates itself. So we set up an alarm which is
850 * cleared after successful authentication. A limit of zero
851 * indicates no limit. Note that we don\'t set the alarm in debugging
852 * mode; it is just annoying to have the server exit just when you
853 * are about to discover the bug.
855 signal(SIGALRM, grace_alarm_handler);
857 alarm(options.login_grace_time);
859 sshd_exchange_identification(sock_in, sock_out);
861 * Check that the connection comes from a privileged port. Rhosts-
862 * and Rhosts-RSA-Authentication only make sense from priviledged
863 * programs. Of course, if the intruder has root access on his local
864 * machine, he can connect from any port. So do not use these
865 * authentication methods from machines that you do not trust.
867 if (remote_port >= IPPORT_RESERVED ||
868 remote_port < IPPORT_RESERVED / 2) {
869 options.rhosts_authentication = 0;
870 options.rhosts_rsa_authentication = 0;
873 if (!packet_connection_is_ipv4() &&
874 options.kerberos_authentication) {
875 debug("Kerberos Authentication disabled, only available for IPv4.");
876 options.kerberos_authentication = 0;
880 packet_set_nonblocking();
882 /* perform the key exchange */
883 /* authenticate user and start session */
886 do_authentication2();
893 /* Cleanup user's ticket cache file. */
894 if (options.kerberos_ticket_cleanup)
898 /* The connection has been terminated. */
899 verbose("Closing connection to %.100s", remote_ip);
917 BIGNUM *session_key_int;
918 unsigned char session_key[SSH_SESSION_KEY_LENGTH];
919 unsigned char cookie[8];
920 unsigned int cipher_type, auth_mask, protocol_flags;
924 * Generate check bytes that the client must send back in the user
925 * packet in order for it to be accepted; this is used to defy ip
926 * spoofing attacks. Note that this only works against somebody
927 * doing IP spoofing from a remote machine; any machine on the local
928 * network can still see outgoing packets and catch the random
929 * cookie. This only affects rhosts authentication, and this is one
930 * of the reasons why it is inherently insecure.
932 for (i = 0; i < 8; i++) {
935 cookie[i] = rand & 0xff;
940 * Send our public key. We include in the packet 64 bits of random
941 * data that must be matched in the reply in order to prevent IP
944 packet_start(SSH_SMSG_PUBLIC_KEY);
945 for (i = 0; i < 8; i++)
946 packet_put_char(cookie[i]);
948 /* Store our public server RSA key. */
949 packet_put_int(BN_num_bits(public_key->n));
950 packet_put_bignum(public_key->e);
951 packet_put_bignum(public_key->n);
953 /* Store our public host RSA key. */
954 packet_put_int(BN_num_bits(sensitive_data.host_key->n));
955 packet_put_bignum(sensitive_data.host_key->e);
956 packet_put_bignum(sensitive_data.host_key->n);
958 /* Put protocol flags. */
959 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
961 /* Declare which ciphers we support. */
962 packet_put_int(cipher_mask1());
964 /* Declare supported authentication types. */
966 if (options.rhosts_authentication)
967 auth_mask |= 1 << SSH_AUTH_RHOSTS;
968 if (options.rhosts_rsa_authentication)
969 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
970 if (options.rsa_authentication)
971 auth_mask |= 1 << SSH_AUTH_RSA;
973 if (options.kerberos_authentication)
974 auth_mask |= 1 << SSH_AUTH_KERBEROS;
977 if (options.kerberos_tgt_passing)
978 auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
979 if (options.afs_token_passing)
980 auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
983 if (options.skey_authentication == 1)
984 auth_mask |= 1 << SSH_AUTH_TIS;
986 if (options.password_authentication)
987 auth_mask |= 1 << SSH_AUTH_PASSWORD;
988 packet_put_int(auth_mask);
990 /* Send the packet and wait for it to be sent. */
994 debug("Sent %d bit public key and %d bit host key.",
995 BN_num_bits(public_key->n), BN_num_bits(sensitive_data.host_key->n));
997 /* Read clients reply (cipher type and session key). */
998 packet_read_expect(&plen, SSH_CMSG_SESSION_KEY);
1000 /* Get cipher type and check whether we accept this. */
1001 cipher_type = packet_get_char();
1003 if (!(cipher_mask() & (1 << cipher_type)))
1004 packet_disconnect("Warning: client selects unsupported cipher.");
1006 /* Get check bytes from the packet. These must match those we
1007 sent earlier with the public key packet. */
1008 for (i = 0; i < 8; i++)
1009 if (cookie[i] != packet_get_char())
1010 packet_disconnect("IP Spoofing check bytes do not match.");
1012 debug("Encryption type: %.200s", cipher_name(cipher_type));
1014 /* Get the encrypted integer. */
1015 session_key_int = BN_new();
1016 packet_get_bignum(session_key_int, &slen);
1018 protocol_flags = packet_get_int();
1019 packet_set_protocol_flags(protocol_flags);
1021 packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY);
1024 * Decrypt it using our private server key and private host key (key
1025 * with larger modulus first).
1027 if (BN_cmp(sensitive_data.private_key->n, sensitive_data.host_key->n) > 0) {
1028 /* Private key has bigger modulus. */
1029 if (BN_num_bits(sensitive_data.private_key->n) <
1030 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
1031 fatal("do_connection: %s: private_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1032 get_remote_ipaddr(),
1033 BN_num_bits(sensitive_data.private_key->n),
1034 BN_num_bits(sensitive_data.host_key->n),
1035 SSH_KEY_BITS_RESERVED);
1037 rsa_private_decrypt(session_key_int, session_key_int,
1038 sensitive_data.private_key);
1039 rsa_private_decrypt(session_key_int, session_key_int,
1040 sensitive_data.host_key);
1042 /* Host key has bigger modulus (or they are equal). */
1043 if (BN_num_bits(sensitive_data.host_key->n) <
1044 BN_num_bits(sensitive_data.private_key->n) + SSH_KEY_BITS_RESERVED) {
1045 fatal("do_connection: %s: host_key %d < private_key %d + SSH_KEY_BITS_RESERVED %d",
1046 get_remote_ipaddr(),
1047 BN_num_bits(sensitive_data.host_key->n),
1048 BN_num_bits(sensitive_data.private_key->n),
1049 SSH_KEY_BITS_RESERVED);
1051 rsa_private_decrypt(session_key_int, session_key_int,
1052 sensitive_data.host_key);
1053 rsa_private_decrypt(session_key_int, session_key_int,
1054 sensitive_data.private_key);
1057 compute_session_id(session_id, cookie,
1058 sensitive_data.host_key->n,
1059 sensitive_data.private_key->n);
1061 /* Destroy the private and public keys. They will no longer be needed. */
1062 RSA_free(public_key);
1063 RSA_free(sensitive_data.private_key);
1064 RSA_free(sensitive_data.host_key);
1067 * Extract session key from the decrypted integer. The key is in the
1068 * least significant 256 bits of the integer; the first byte of the
1069 * key is in the highest bits.
1071 BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1072 len = BN_num_bytes(session_key_int);
1073 if (len < 0 || len > sizeof(session_key))
1074 fatal("do_connection: bad len from %s: session_key_int %d > sizeof(session_key) %d",
1075 get_remote_ipaddr(),
1076 len, sizeof(session_key));
1077 memset(session_key, 0, sizeof(session_key));
1078 BN_bn2bin(session_key_int, session_key + sizeof(session_key) - len);
1080 /* Destroy the decrypted integer. It is no longer needed. */
1081 BN_clear_free(session_key_int);
1083 /* Xor the first 16 bytes of the session key with the session id. */
1084 for (i = 0; i < 16; i++)
1085 session_key[i] ^= session_id[i];
1087 /* Set the session key. From this on all communications will be encrypted. */
1088 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
1090 /* Destroy our copy of the session key. It is no longer needed. */
1091 memset(session_key, 0, sizeof(session_key));
1093 debug("Received session key; encryption turned on.");
1095 /* Send an acknowledgement packet. Note that this packet is sent encrypted. */
1096 packet_start(SSH_SMSG_SUCCESS);
1098 packet_write_wait();
1102 * SSH2 key exchange: diffie-hellman-group1-sha1
1107 Buffer *server_kexinit;
1108 Buffer *client_kexinit;
1109 int payload_len, dlen;
1111 unsigned int klen, kout;
1113 unsigned char *signature = NULL;
1114 unsigned char *server_host_key_blob = NULL;
1115 unsigned int sbloblen;
1117 BIGNUM *dh_client_pub = 0;
1118 BIGNUM *shared_secret = 0;
1120 unsigned char *kbuf;
1121 unsigned char *hash;
1123 Key *server_host_key;
1124 char *cprop[PROPOSAL_MAX];
1125 char *sprop[PROPOSAL_MAX];
1129 debug("Sending KEX init.");
1131 for (i = 0; i < PROPOSAL_MAX; i++)
1132 sprop[i] = xstrdup(myproposal[i]);
1133 server_kexinit = kex_init(sprop);
1134 packet_start(SSH2_MSG_KEXINIT);
1135 packet_put_raw(buffer_ptr(server_kexinit), buffer_len(server_kexinit));
1137 packet_write_wait();
1141 packet_read_expect(&payload_len, SSH2_MSG_KEXINIT);
1144 * save raw KEXINIT payload in buffer. this is used during
1145 * computation of the session_id and the session keys.
1147 client_kexinit = xmalloc(sizeof(*client_kexinit));
1148 buffer_init(client_kexinit);
1149 ptr = packet_get_raw(&payload_len);
1150 buffer_append(client_kexinit, ptr, payload_len);
1153 for (i = 0; i < 16; i++)
1154 (void) packet_get_char();
1155 /* save kex init proposal strings */
1156 for (i = 0; i < PROPOSAL_MAX; i++) {
1157 cprop[i] = packet_get_string(NULL);
1158 debug("got kexinit string: %s", cprop[i]);
1161 i = (int) packet_get_char();
1162 debug("first kex follow == %d", i);
1163 i = packet_get_int();
1164 debug("reserved == %d", i);
1166 debug("done read kexinit");
1167 kex = kex_choose_conf(cprop, sprop, 1);
1171 debug("Wait SSH2_MSG_KEXDH_INIT.");
1172 packet_read_expect(&payload_len, SSH2_MSG_KEXDH_INIT);
1175 dh_client_pub = BN_new();
1176 if (dh_client_pub == NULL)
1177 fatal("dh_client_pub == NULL");
1178 packet_get_bignum2(dh_client_pub, &dlen);
1181 fprintf(stderr, "\ndh_client_pub= ");
1182 bignum_print(dh_client_pub);
1183 fprintf(stderr, "\n");
1184 debug("bits %d", BN_num_bits(dh_client_pub));
1187 /* generate DH key */
1188 dh = new_dh_group1(); /* XXX depends on 'kex' */
1191 fprintf(stderr, "\np= ");
1192 bignum_print(dh->p);
1193 fprintf(stderr, "\ng= ");
1194 bignum_print(dh->g);
1195 fprintf(stderr, "\npub= ");
1196 bignum_print(dh->pub_key);
1197 fprintf(stderr, "\n");
1201 kbuf = xmalloc(klen);
1202 kout = DH_compute_key(kbuf, dh_client_pub, dh);
1205 debug("shared secret: len %d/%d", klen, kout);
1206 fprintf(stderr, "shared secret == ");
1207 for (i = 0; i< kout; i++)
1208 fprintf(stderr, "%02x", (kbuf[i])&0xff);
1209 fprintf(stderr, "\n");
1211 shared_secret = BN_new();
1213 BN_bin2bn(kbuf, kout, shared_secret);
1214 memset(kbuf, 0, klen);
1217 server_host_key = dsa_get_serverkey(options.dsa_key_file);
1218 dsa_make_serverkey_blob(server_host_key, &server_host_key_blob, &sbloblen);
1220 /* calc H */ /* XXX depends on 'kex' */
1222 client_version_string,
1223 server_version_string,
1224 buffer_ptr(client_kexinit), buffer_len(client_kexinit),
1225 buffer_ptr(server_kexinit), buffer_len(server_kexinit),
1226 (char *)server_host_key_blob, sbloblen,
1231 buffer_free(client_kexinit);
1232 buffer_free(server_kexinit);
1233 xfree(client_kexinit);
1234 xfree(server_kexinit);
1236 fprintf(stderr, "hash == ");
1237 for (i = 0; i< 20; i++)
1238 fprintf(stderr, "%02x", (hash[i])&0xff);
1239 fprintf(stderr, "\n");
1242 dsa_sign(server_host_key, &signature, &slen, hash, 20);
1243 /* hashlen depends on KEX */
1244 key_free(server_host_key);
1246 /* send server hostkey, DH pubkey 'f' and singed H */
1247 packet_start(SSH2_MSG_KEXDH_REPLY);
1248 packet_put_string((char *)server_host_key_blob, sbloblen);
1249 packet_put_bignum2(dh->pub_key); // f
1250 packet_put_string((char *)signature, slen);
1252 packet_write_wait();
1254 kex_derive_keys(kex, hash, shared_secret);
1255 packet_set_kex(kex);
1257 /* have keys, free DH */
1260 debug("send SSH2_MSG_NEWKEYS.");
1261 packet_start(SSH2_MSG_NEWKEYS);
1263 packet_write_wait();
1264 debug("done: send SSH2_MSG_NEWKEYS.");
1266 debug("Wait SSH2_MSG_NEWKEYS.");
1267 packet_read_expect(&payload_len, SSH2_MSG_NEWKEYS);
1268 debug("GOT SSH2_MSG_NEWKEYS.");
1270 /* send 1st encrypted/maced/compressed message */
1271 packet_start(SSH2_MSG_IGNORE);
1272 packet_put_cstring("markus");
1274 packet_write_wait();
1276 debug("done: KEX2.");