1 /* $OpenBSD: sshd.c,v 1.336 2006/07/11 20:07:25 stevesk Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * This program is the ssh daemon. It listens for connections from clients,
7 * and 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
10 * authentication agent connections.
12 * As far as I am concerned, the code I have written for this software
13 * can be used freely for any purpose. Any derived versions of this
14 * software must be clearly marked as such, and if the derived work is
15 * incompatible with the protocol description in the RFC file, it must be
16 * called by a name other than "ssh" or "Secure Shell".
18 * SSH2 implementation:
19 * Privilege Separation:
21 * Copyright (c) 2000, 2001, 2002 Markus Friedl. All rights reserved.
22 * Copyright (c) 2002 Niels Provos. All rights reserved.
24 * Redistribution and use in source and binary forms, with or without
25 * modification, are permitted provided that the following conditions
27 * 1. Redistributions of source code must retain the above copyright
28 * notice, this list of conditions and the following disclaimer.
29 * 2. Redistributions in binary form must reproduce the above copyright
30 * notice, this list of conditions and the following disclaimer in the
31 * documentation and/or other materials provided with the distribution.
33 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
34 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
35 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
36 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
37 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
38 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
39 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
40 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
41 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
42 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
47 #include <sys/types.h>
48 #ifdef HAVE_SYS_STAT_H
49 # include <sys/stat.h>
51 #include <sys/ioctl.h>
52 #include <sys/socket.h>
64 #include <openssl/dh.h>
65 #include <openssl/bn.h>
66 #include <openssl/md5.h>
67 #include <openssl/rand.h>
68 #ifdef HAVE_SECUREWARE
69 #include <sys/security.h>
90 #include "myproposal.h"
92 #include "pathnames.h"
101 #include "monitor_mm.h"
103 #include "monitor_wrap.h"
104 #include "monitor_fdpass.h"
110 int allow_severity = LOG_INFO;
111 int deny_severity = LOG_WARNING;
119 #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
120 #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
121 #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
122 #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
124 extern char *__progname;
126 /* Server configuration options. */
127 ServerOptions options;
129 /* Name of the server configuration file. */
130 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
133 * Debug mode flag. This can be set on the command line. If debug
134 * mode is enabled, extra debugging output will be sent to the system
135 * log, the daemon will not go to background, and will exit after processing
136 * the first connection.
140 /* Flag indicating that the daemon should only test the configuration and keys. */
143 /* Flag indicating that the daemon is being started from inetd. */
146 /* Flag indicating that sshd should not detach and become a daemon. */
147 int no_daemon_flag = 0;
149 /* debug goes to stderr unless inetd_flag is set */
152 /* Saved arguments to main(). */
157 int rexeced_flag = 0;
163 * The sockets that the server is listening; this is used in the SIGHUP
166 #define MAX_LISTEN_SOCKS 16
167 int listen_socks[MAX_LISTEN_SOCKS];
168 int num_listen_socks = 0;
171 * the client's version string, passed by sshd2 in compat mode. if != NULL,
172 * sshd will skip the version-number exchange
174 char *client_version_string = NULL;
175 char *server_version_string = NULL;
177 /* for rekeying XXX fixme */
181 * Any really sensitive data in the application is contained in this
182 * structure. The idea is that this structure could be locked into memory so
183 * that the pages do not get written into swap. However, there are some
184 * problems. The private key contains BIGNUMs, and we do not (in principle)
185 * have access to the internals of them, and locking just the structure is
186 * not very useful. Currently, memory locking is not implemented.
189 Key *server_key; /* ephemeral server key */
190 Key *ssh1_host_key; /* ssh1 host key */
191 Key **host_keys; /* all private host keys */
194 u_char ssh1_cookie[SSH_SESSION_KEY_LENGTH];
198 * Flag indicating whether the RSA server key needs to be regenerated.
199 * Is set in the SIGALRM handler and cleared when the key is regenerated.
201 static volatile sig_atomic_t key_do_regen = 0;
203 /* This is set to true when a signal is received. */
204 static volatile sig_atomic_t received_sighup = 0;
205 static volatile sig_atomic_t received_sigterm = 0;
207 /* session identifier, used by RSA-auth */
208 u_char session_id[16];
211 u_char *session_id2 = NULL;
212 u_int session_id2_len = 0;
214 /* record remote hostname or ip */
215 u_int utmp_len = MAXHOSTNAMELEN;
217 /* options.max_startup sized array of fd ints */
218 int *startup_pipes = NULL;
219 int startup_pipe; /* in child */
221 /* variables used for privilege separation */
223 struct monitor *pmonitor = NULL;
225 /* global authentication context */
226 Authctxt *the_authctxt = NULL;
228 /* message to be displayed after login */
231 /* Prototypes for various functions defined later in this file. */
232 void destroy_sensitive_data(void);
233 void demote_sensitive_data(void);
235 static void do_ssh1_kex(void);
236 static void do_ssh2_kex(void);
239 * Close all listening sockets
242 close_listen_socks(void)
246 for (i = 0; i < num_listen_socks; i++)
247 close(listen_socks[i]);
248 num_listen_socks = -1;
252 close_startup_pipes(void)
257 for (i = 0; i < options.max_startups; i++)
258 if (startup_pipes[i] != -1)
259 close(startup_pipes[i]);
263 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
264 * the effect is to reread the configuration file (and to regenerate
270 sighup_handler(int sig)
272 int save_errno = errno;
275 signal(SIGHUP, sighup_handler);
280 * Called from the main program after receiving SIGHUP.
281 * Restarts the server.
286 logit("Received SIGHUP; restarting.");
287 close_listen_socks();
288 close_startup_pipes();
289 execv(saved_argv[0], saved_argv);
290 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
296 * Generic signal handler for terminating signals in the master daemon.
300 sigterm_handler(int sig)
302 received_sigterm = sig;
306 * SIGCHLD handler. This is called whenever a child dies. This will then
307 * reap any zombies left by exited children.
311 main_sigchld_handler(int sig)
313 int save_errno = errno;
317 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
318 (pid < 0 && errno == EINTR))
321 signal(SIGCHLD, main_sigchld_handler);
326 * Signal handler for the alarm after the login grace period has expired.
330 grace_alarm_handler(int sig)
332 /* XXX no idea how fix this signal handler */
334 if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
335 kill(pmonitor->m_pid, SIGALRM);
337 /* Log error and exit. */
338 fatal("Timeout before authentication for %s", get_remote_ipaddr());
342 * Signal handler for the key regeneration alarm. Note that this
343 * alarm only occurs in the daemon waiting for connections, and it does not
344 * do anything with the private key or random state before forking.
345 * Thus there should be no concurrency control/asynchronous execution
349 generate_ephemeral_server_key(void)
354 verbose("Generating %s%d bit RSA key.",
355 sensitive_data.server_key ? "new " : "", options.server_key_bits);
356 if (sensitive_data.server_key != NULL)
357 key_free(sensitive_data.server_key);
358 sensitive_data.server_key = key_generate(KEY_RSA1,
359 options.server_key_bits);
360 verbose("RSA key generation complete.");
362 for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
365 sensitive_data.ssh1_cookie[i] = rnd & 0xff;
373 key_regeneration_alarm(int sig)
375 int save_errno = errno;
377 signal(SIGALRM, SIG_DFL);
383 sshd_exchange_identification(int sock_in, int sock_out)
387 int remote_major, remote_minor;
390 char buf[256]; /* Must not be larger than remote_version. */
391 char remote_version[256]; /* Must be at least as big as buf. */
393 if ((options.protocol & SSH_PROTO_1) &&
394 (options.protocol & SSH_PROTO_2)) {
395 major = PROTOCOL_MAJOR_1;
397 } else if (options.protocol & SSH_PROTO_2) {
398 major = PROTOCOL_MAJOR_2;
399 minor = PROTOCOL_MINOR_2;
401 major = PROTOCOL_MAJOR_1;
402 minor = PROTOCOL_MINOR_1;
404 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", major, minor, SSH_VERSION);
405 server_version_string = xstrdup(buf);
407 /* Send our protocol version identification. */
408 if (atomicio(vwrite, sock_out, server_version_string,
409 strlen(server_version_string))
410 != strlen(server_version_string)) {
411 logit("Could not write ident string to %s", get_remote_ipaddr());
415 /* Read other sides version identification. */
416 memset(buf, 0, sizeof(buf));
417 for (i = 0; i < sizeof(buf) - 1; i++) {
418 if (atomicio(read, sock_in, &buf[i], 1) != 1) {
419 logit("Did not receive identification string from %s",
420 get_remote_ipaddr());
423 if (buf[i] == '\r') {
425 /* Kludge for F-Secure Macintosh < 1.0.2 */
427 strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
431 if (buf[i] == '\n') {
436 buf[sizeof(buf) - 1] = 0;
437 client_version_string = xstrdup(buf);
440 * Check that the versions match. In future this might accept
441 * several versions and set appropriate flags to handle them.
443 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
444 &remote_major, &remote_minor, remote_version) != 3) {
445 s = "Protocol mismatch.\n";
446 (void) atomicio(vwrite, sock_out, s, strlen(s));
449 logit("Bad protocol version identification '%.100s' from %s",
450 client_version_string, get_remote_ipaddr());
453 debug("Client protocol version %d.%d; client software version %.100s",
454 remote_major, remote_minor, remote_version);
456 compat_datafellows(remote_version);
458 if (datafellows & SSH_BUG_PROBE) {
459 logit("probed from %s with %s. Don't panic.",
460 get_remote_ipaddr(), client_version_string);
464 if (datafellows & SSH_BUG_SCANNER) {
465 logit("scanned from %s with %s. Don't panic.",
466 get_remote_ipaddr(), client_version_string);
471 switch (remote_major) {
473 if (remote_minor == 99) {
474 if (options.protocol & SSH_PROTO_2)
480 if (!(options.protocol & SSH_PROTO_1)) {
484 if (remote_minor < 3) {
485 packet_disconnect("Your ssh version is too old and "
486 "is no longer supported. Please install a newer version.");
487 } else if (remote_minor == 3) {
488 /* note that this disables agent-forwarding */
493 if (options.protocol & SSH_PROTO_2) {
502 chop(server_version_string);
503 debug("Local version string %.200s", server_version_string);
506 s = "Protocol major versions differ.\n";
507 (void) atomicio(vwrite, sock_out, s, strlen(s));
510 logit("Protocol major versions differ for %s: %.200s vs. %.200s",
512 server_version_string, client_version_string);
517 /* Destroy the host and server keys. They will no longer be needed. */
519 destroy_sensitive_data(void)
523 if (sensitive_data.server_key) {
524 key_free(sensitive_data.server_key);
525 sensitive_data.server_key = NULL;
527 for (i = 0; i < options.num_host_key_files; i++) {
528 if (sensitive_data.host_keys[i]) {
529 key_free(sensitive_data.host_keys[i]);
530 sensitive_data.host_keys[i] = NULL;
533 sensitive_data.ssh1_host_key = NULL;
534 memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
537 /* Demote private to public keys for network child */
539 demote_sensitive_data(void)
544 if (sensitive_data.server_key) {
545 tmp = key_demote(sensitive_data.server_key);
546 key_free(sensitive_data.server_key);
547 sensitive_data.server_key = tmp;
550 for (i = 0; i < options.num_host_key_files; i++) {
551 if (sensitive_data.host_keys[i]) {
552 tmp = key_demote(sensitive_data.host_keys[i]);
553 key_free(sensitive_data.host_keys[i]);
554 sensitive_data.host_keys[i] = tmp;
555 if (tmp->type == KEY_RSA1)
556 sensitive_data.ssh1_host_key = tmp;
560 /* We do not clear ssh1_host key and cookie. XXX - Okay Niels? */
564 privsep_preauth_child(void)
571 /* Enable challenge-response authentication for privilege separation */
572 privsep_challenge_enable();
574 for (i = 0; i < 256; i++)
575 rnd[i] = arc4random();
576 RAND_seed(rnd, sizeof(rnd));
578 /* Demote the private keys to public keys. */
579 demote_sensitive_data();
581 if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL)
582 fatal("Privilege separation user %s does not exist",
584 memset(pw->pw_passwd, 0, strlen(pw->pw_passwd));
587 /* Change our root directory */
588 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
589 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
591 if (chdir("/") == -1)
592 fatal("chdir(\"/\"): %s", strerror(errno));
594 /* Drop our privileges */
595 debug3("privsep user:group %u:%u", (u_int)pw->pw_uid,
598 /* XXX not ready, too heavy after chroot */
599 do_setusercontext(pw);
601 gidset[0] = pw->pw_gid;
602 if (setgroups(1, gidset) < 0)
603 fatal("setgroups: %.100s", strerror(errno));
604 permanently_set_uid(pw);
609 privsep_preauth(Authctxt *authctxt)
614 /* Set up unprivileged child process to deal with network data */
615 pmonitor = monitor_init();
616 /* Store a pointer to the kex for later rekeying */
617 pmonitor->m_pkex = &xxx_kex;
621 fatal("fork of unprivileged child failed");
622 } else if (pid != 0) {
623 debug2("Network child is on pid %ld", (long)pid);
625 close(pmonitor->m_recvfd);
626 pmonitor->m_pid = pid;
627 monitor_child_preauth(authctxt, pmonitor);
628 close(pmonitor->m_sendfd);
631 monitor_sync(pmonitor);
633 /* Wait for the child's exit status */
634 while (waitpid(pid, &status, 0) < 0)
641 close(pmonitor->m_sendfd);
643 /* Demote the child */
644 if (getuid() == 0 || geteuid() == 0)
645 privsep_preauth_child();
646 setproctitle("%s", "[net]");
652 privsep_postauth(Authctxt *authctxt)
654 #ifdef DISABLE_FD_PASSING
657 if (authctxt->pw->pw_uid == 0 || options.use_login) {
659 /* File descriptor passing is broken or root login */
664 /* New socket pair */
665 monitor_reinit(pmonitor);
667 pmonitor->m_pid = fork();
668 if (pmonitor->m_pid == -1)
669 fatal("fork of unprivileged child failed");
670 else if (pmonitor->m_pid != 0) {
671 debug2("User child is on pid %ld", (long)pmonitor->m_pid);
672 close(pmonitor->m_recvfd);
673 buffer_clear(&loginmsg);
674 monitor_child_postauth(pmonitor);
680 close(pmonitor->m_sendfd);
682 /* Demote the private keys to public keys. */
683 demote_sensitive_data();
685 /* Drop privileges */
686 do_setusercontext(authctxt->pw);
689 /* It is safe now to apply the key state */
690 monitor_apply_keystate(pmonitor);
693 * Tell the packet layer that authentication was successful, since
694 * this information is not part of the key state.
696 packet_set_authenticated();
700 list_hostkey_types(void)
708 for (i = 0; i < options.num_host_key_files; i++) {
709 Key *key = sensitive_data.host_keys[i];
715 if (buffer_len(&b) > 0)
716 buffer_append(&b, ",", 1);
717 p = key_ssh_name(key);
718 buffer_append(&b, p, strlen(p));
722 buffer_append(&b, "\0", 1);
723 ret = xstrdup(buffer_ptr(&b));
725 debug("list_hostkey_types: %s", ret);
730 get_hostkey_by_type(int type)
734 for (i = 0; i < options.num_host_key_files; i++) {
735 Key *key = sensitive_data.host_keys[i];
736 if (key != NULL && key->type == type)
743 get_hostkey_by_index(int ind)
745 if (ind < 0 || ind >= options.num_host_key_files)
747 return (sensitive_data.host_keys[ind]);
751 get_hostkey_index(Key *key)
755 for (i = 0; i < options.num_host_key_files; i++) {
756 if (key == sensitive_data.host_keys[i])
763 * returns 1 if connection should be dropped, 0 otherwise.
764 * dropping starts at connection #max_startups_begin with a probability
765 * of (max_startups_rate/100). the probability increases linearly until
766 * all connections are dropped for startups > max_startups
769 drop_connection(int startups)
773 if (startups < options.max_startups_begin)
775 if (startups >= options.max_startups)
777 if (options.max_startups_rate == 100)
780 p = 100 - options.max_startups_rate;
781 p *= startups - options.max_startups_begin;
782 p /= options.max_startups - options.max_startups_begin;
783 p += options.max_startups_rate;
784 r = arc4random() % 100;
786 debug("drop_connection: p %d, r %d", p, r);
787 return (r < p) ? 1 : 0;
793 fprintf(stderr, "%s, %s\n",
794 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
796 "usage: sshd [-46Ddeiqt] [-b bits] [-f config_file] [-g login_grace_time]\n"
797 " [-h host_key_file] [-k key_gen_time] [-o option] [-p port] [-u len]\n"
803 send_rexec_state(int fd, Buffer *conf)
807 debug3("%s: entering fd = %d config len %d", __func__, fd,
811 * Protocol from reexec master to child:
812 * string configuration
813 * u_int ephemeral_key_follows
814 * bignum e (only if ephemeral_key_follows == 1)
820 * string rngseed (only if OpenSSL is not self-seeded)
823 buffer_put_cstring(&m, buffer_ptr(conf));
825 if (sensitive_data.server_key != NULL &&
826 sensitive_data.server_key->type == KEY_RSA1) {
827 buffer_put_int(&m, 1);
828 buffer_put_bignum(&m, sensitive_data.server_key->rsa->e);
829 buffer_put_bignum(&m, sensitive_data.server_key->rsa->n);
830 buffer_put_bignum(&m, sensitive_data.server_key->rsa->d);
831 buffer_put_bignum(&m, sensitive_data.server_key->rsa->iqmp);
832 buffer_put_bignum(&m, sensitive_data.server_key->rsa->p);
833 buffer_put_bignum(&m, sensitive_data.server_key->rsa->q);
835 buffer_put_int(&m, 0);
837 #ifndef OPENSSL_PRNG_ONLY
838 rexec_send_rng_seed(&m);
841 if (ssh_msg_send(fd, 0, &m) == -1)
842 fatal("%s: ssh_msg_send failed", __func__);
846 debug3("%s: done", __func__);
850 recv_rexec_state(int fd, Buffer *conf)
856 debug3("%s: entering fd = %d", __func__, fd);
860 if (ssh_msg_recv(fd, &m) == -1)
861 fatal("%s: ssh_msg_recv failed", __func__);
862 if (buffer_get_char(&m) != 0)
863 fatal("%s: rexec version mismatch", __func__);
865 cp = buffer_get_string(&m, &len);
867 buffer_append(conf, cp, len + 1);
870 if (buffer_get_int(&m)) {
871 if (sensitive_data.server_key != NULL)
872 key_free(sensitive_data.server_key);
873 sensitive_data.server_key = key_new_private(KEY_RSA1);
874 buffer_get_bignum(&m, sensitive_data.server_key->rsa->e);
875 buffer_get_bignum(&m, sensitive_data.server_key->rsa->n);
876 buffer_get_bignum(&m, sensitive_data.server_key->rsa->d);
877 buffer_get_bignum(&m, sensitive_data.server_key->rsa->iqmp);
878 buffer_get_bignum(&m, sensitive_data.server_key->rsa->p);
879 buffer_get_bignum(&m, sensitive_data.server_key->rsa->q);
880 rsa_generate_additional_parameters(
881 sensitive_data.server_key->rsa);
884 #ifndef OPENSSL_PRNG_ONLY
885 rexec_recv_rng_seed(&m);
890 debug3("%s: done", __func__);
894 * Main program for the daemon.
897 main(int ac, char **av)
901 int opt, j, i, on = 1;
902 int sock_in = -1, sock_out = -1, newsock = -1;
906 struct sockaddr_storage from;
907 const char *remote_ip;
911 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
913 int listen_sock, maxfd;
914 int startup_p[2] = { -1 , -1 }, config_s[2] = { -1 , -1 };
918 int ret, key_used = 0;
921 #ifdef HAVE_SECUREWARE
922 (void)set_auth_parameters(ac, av);
924 __progname = ssh_get_progname(av[0]);
927 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
930 saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
931 for (i = 0; i < ac; i++)
932 saved_argv[i] = xstrdup(av[i]);
933 saved_argv[i] = NULL;
935 #ifndef HAVE_SETPROCTITLE
936 /* Prepare for later setproctitle emulation */
937 compat_init_setproctitle(ac, av);
941 if (geteuid() == 0 && setgroups(0, NULL) == -1)
942 debug("setgroups(): %.200s", strerror(errno));
944 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
947 /* Initialize configuration options to their default values. */
948 initialize_server_options(&options);
950 /* Parse command-line arguments. */
951 while ((opt = getopt(ac, av, "f:p:b:k:h:g:u:o:dDeiqrtQR46")) != -1) {
954 options.address_family = AF_INET;
957 options.address_family = AF_INET6;
960 config_file_name = optarg;
963 if (debug_flag == 0) {
965 options.log_level = SYSLOG_LEVEL_DEBUG1;
966 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
989 options.log_level = SYSLOG_LEVEL_QUIET;
992 options.server_key_bits = (int)strtonum(optarg, 256,
996 options.ports_from_cmdline = 1;
997 if (options.num_ports >= MAX_PORTS) {
998 fprintf(stderr, "too many ports.\n");
1001 options.ports[options.num_ports++] = a2port(optarg);
1002 if (options.ports[options.num_ports-1] == 0) {
1003 fprintf(stderr, "Bad port number.\n");
1008 if ((options.login_grace_time = convtime(optarg)) == -1) {
1009 fprintf(stderr, "Invalid login grace time.\n");
1014 if ((options.key_regeneration_time = convtime(optarg)) == -1) {
1015 fprintf(stderr, "Invalid key regeneration interval.\n");
1020 if (options.num_host_key_files >= MAX_HOSTKEYS) {
1021 fprintf(stderr, "too many host keys.\n");
1024 options.host_key_files[options.num_host_key_files++] = optarg;
1030 utmp_len = (u_int)strtonum(optarg, 0, MAXHOSTNAMELEN+1, NULL);
1031 if (utmp_len > MAXHOSTNAMELEN) {
1032 fprintf(stderr, "Invalid utmp length.\n");
1037 line = xstrdup(optarg);
1038 if (process_server_config_line(&options, line,
1039 "command-line", 0) != 0)
1049 if (rexeced_flag || inetd_flag)
1051 if (rexec_flag && (av[0] == NULL || *av[0] != '/'))
1052 fatal("sshd re-exec requires execution with an absolute path");
1054 closefrom(REEXEC_MIN_FREE_FD);
1056 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1058 SSLeay_add_all_algorithms();
1061 * Force logging to stderr until we have loaded the private host
1062 * key (unless started from inetd)
1064 log_init(__progname,
1065 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1066 SYSLOG_LEVEL_INFO : options.log_level,
1067 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1068 SYSLOG_FACILITY_AUTH : options.log_facility,
1069 log_stderr || !inetd_flag);
1072 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1073 * root's environment
1075 if (getenv("KRB5CCNAME") != NULL)
1076 unsetenv("KRB5CCNAME");
1079 /* Cray can define user privs drop all privs now!
1080 * Not needed on PRIV_SU systems!
1085 sensitive_data.server_key = NULL;
1086 sensitive_data.ssh1_host_key = NULL;
1087 sensitive_data.have_ssh1_key = 0;
1088 sensitive_data.have_ssh2_key = 0;
1090 /* Fetch our configuration */
1093 recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1095 load_server_config(config_file_name, &cfg);
1097 parse_server_config(&options,
1098 rexeced_flag ? "rexec" : config_file_name, &cfg);
1105 /* Fill in default values for those options not explicitly set. */
1106 fill_default_server_options(&options);
1108 /* set default channel AF */
1109 channel_set_af(options.address_family);
1111 /* Check that there are no remaining arguments. */
1113 fprintf(stderr, "Extra argument %s.\n", av[optind]);
1117 debug("sshd version %.100s", SSH_RELEASE);
1119 /* load private host keys */
1120 sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1122 for (i = 0; i < options.num_host_key_files; i++)
1123 sensitive_data.host_keys[i] = NULL;
1125 for (i = 0; i < options.num_host_key_files; i++) {
1126 key = key_load_private(options.host_key_files[i], "", NULL);
1127 sensitive_data.host_keys[i] = key;
1129 error("Could not load host key: %s",
1130 options.host_key_files[i]);
1131 sensitive_data.host_keys[i] = NULL;
1134 switch (key->type) {
1136 sensitive_data.ssh1_host_key = key;
1137 sensitive_data.have_ssh1_key = 1;
1141 sensitive_data.have_ssh2_key = 1;
1144 debug("private host key: #%d type %d %s", i, key->type,
1147 if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1148 logit("Disabling protocol version 1. Could not load host key");
1149 options.protocol &= ~SSH_PROTO_1;
1151 if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1152 logit("Disabling protocol version 2. Could not load host key");
1153 options.protocol &= ~SSH_PROTO_2;
1155 if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1156 logit("sshd: no hostkeys available -- exiting.");
1160 /* Check certain values for sanity. */
1161 if (options.protocol & SSH_PROTO_1) {
1162 if (options.server_key_bits < 512 ||
1163 options.server_key_bits > 32768) {
1164 fprintf(stderr, "Bad server key size.\n");
1168 * Check that server and host key lengths differ sufficiently. This
1169 * is necessary to make double encryption work with rsaref. Oh, I
1170 * hate software patents. I dont know if this can go? Niels
1172 if (options.server_key_bits >
1173 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
1174 SSH_KEY_BITS_RESERVED && options.server_key_bits <
1175 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1176 SSH_KEY_BITS_RESERVED) {
1177 options.server_key_bits =
1178 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1179 SSH_KEY_BITS_RESERVED;
1180 debug("Forcing server key to %d bits to make it differ from host key.",
1181 options.server_key_bits);
1188 if (getpwnam(SSH_PRIVSEP_USER) == NULL)
1189 fatal("Privilege separation user %s does not exist",
1191 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1192 (S_ISDIR(st.st_mode) == 0))
1193 fatal("Missing privilege separation directory: %s",
1194 _PATH_PRIVSEP_CHROOT_DIR);
1197 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1198 (st.st_uid != getuid () ||
1199 (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1201 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1203 fatal("%s must be owned by root and not group or "
1204 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1207 /* Configuration looks good, so exit if in test mode. */
1212 * Clear out any supplemental groups we may have inherited. This
1213 * prevents inadvertent creation of files with bad modes (in the
1214 * portable version at least, it's certainly possible for PAM
1215 * to create a file, and we can't control the code in every
1216 * module which might be used).
1218 if (setgroups(0, NULL) < 0)
1219 debug("setgroups() failed: %.200s", strerror(errno));
1222 rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1223 for (i = 0; i < rexec_argc; i++) {
1224 debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1225 rexec_argv[i] = saved_argv[i];
1227 rexec_argv[rexec_argc] = "-R";
1228 rexec_argv[rexec_argc + 1] = NULL;
1231 /* Initialize the log (it is reinitialized below in case we forked). */
1232 if (debug_flag && (!inetd_flag || rexeced_flag))
1234 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1237 * If not in debugging mode, and not started from inetd, disconnect
1238 * from the controlling terminal, and fork. The original process
1241 if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1244 #endif /* TIOCNOTTY */
1245 if (daemon(0, 0) < 0)
1246 fatal("daemon() failed: %.200s", strerror(errno));
1248 /* Disconnect from the controlling tty. */
1250 fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1252 (void) ioctl(fd, TIOCNOTTY, NULL);
1255 #endif /* TIOCNOTTY */
1257 /* Reinitialize the log (because of the fork above). */
1258 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1260 /* Initialize the random number generator. */
1263 /* Chdir to the root directory so that the current disk can be
1264 unmounted if desired. */
1267 /* ignore SIGPIPE */
1268 signal(SIGPIPE, SIG_IGN);
1270 /* Start listening for a socket, unless started from inetd. */
1276 close(REEXEC_CONFIG_PASS_FD);
1277 sock_in = sock_out = dup(STDIN_FILENO);
1279 startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
1280 close(REEXEC_STARTUP_PIPE_FD);
1283 sock_in = dup(STDIN_FILENO);
1284 sock_out = dup(STDOUT_FILENO);
1287 * We intentionally do not close the descriptors 0, 1, and 2
1288 * as our code for setting the descriptors won't work if
1289 * ttyfd happens to be one of those.
1291 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1292 dup2(fd, STDIN_FILENO);
1293 dup2(fd, STDOUT_FILENO);
1294 if (fd > STDOUT_FILENO)
1297 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
1298 if ((options.protocol & SSH_PROTO_1) &&
1299 sensitive_data.server_key == NULL)
1300 generate_ephemeral_server_key();
1302 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
1303 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1305 if (num_listen_socks >= MAX_LISTEN_SOCKS)
1306 fatal("Too many listen sockets. "
1307 "Enlarge MAX_LISTEN_SOCKS");
1308 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1309 ntop, sizeof(ntop), strport, sizeof(strport),
1310 NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1311 error("getnameinfo failed: %.100s",
1312 (ret != EAI_SYSTEM) ? gai_strerror(ret) :
1316 /* Create socket for listening. */
1317 listen_sock = socket(ai->ai_family, ai->ai_socktype,
1319 if (listen_sock < 0) {
1320 /* kernel may not support ipv6 */
1321 verbose("socket: %.100s", strerror(errno));
1324 if (set_nonblock(listen_sock) == -1) {
1329 * Set socket options.
1330 * Allow local port reuse in TIME_WAIT.
1332 if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
1333 &on, sizeof(on)) == -1)
1334 error("setsockopt SO_REUSEADDR: %s", strerror(errno));
1336 debug("Bind to port %s on %s.", strport, ntop);
1338 /* Bind the socket to the desired port. */
1339 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1341 error("Bind to port %s on %s failed: %.200s.",
1342 strport, ntop, strerror(errno));
1346 listen_socks[num_listen_socks] = listen_sock;
1349 /* Start listening on the port. */
1350 if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1351 fatal("listen on [%s]:%s: %.100s",
1352 ntop, strport, strerror(errno));
1353 logit("Server listening on %s port %s.", ntop, strport);
1355 freeaddrinfo(options.listen_addrs);
1357 if (!num_listen_socks)
1358 fatal("Cannot bind any address.");
1360 if (options.protocol & SSH_PROTO_1)
1361 generate_ephemeral_server_key();
1364 * Arrange to restart on SIGHUP. The handler needs
1367 signal(SIGHUP, sighup_handler);
1369 signal(SIGTERM, sigterm_handler);
1370 signal(SIGQUIT, sigterm_handler);
1372 /* Arrange SIGCHLD to be caught. */
1373 signal(SIGCHLD, main_sigchld_handler);
1375 /* Write out the pid file after the sigterm handler is setup */
1378 * Record our pid in /var/run/sshd.pid to make it
1379 * easier to kill the correct sshd. We don't want to
1380 * do this before the bind above because the bind will
1381 * fail if there already is a daemon, and this will
1382 * overwrite any old pid in the file.
1384 f = fopen(options.pid_file, "wb");
1386 error("Couldn't create pid file \"%s\": %s",
1387 options.pid_file, strerror(errno));
1389 fprintf(f, "%ld\n", (long) getpid());
1394 /* setup fd set for listen */
1397 for (i = 0; i < num_listen_socks; i++)
1398 if (listen_socks[i] > maxfd)
1399 maxfd = listen_socks[i];
1400 /* pipes connected to unauthenticated childs */
1401 startup_pipes = xcalloc(options.max_startups, sizeof(int));
1402 for (i = 0; i < options.max_startups; i++)
1403 startup_pipes[i] = -1;
1406 * Stay listening for connections until the system crashes or
1407 * the daemon is killed with a signal.
1410 if (received_sighup)
1414 fdset = (fd_set *)xcalloc(howmany(maxfd + 1, NFDBITS),
1417 for (i = 0; i < num_listen_socks; i++)
1418 FD_SET(listen_socks[i], fdset);
1419 for (i = 0; i < options.max_startups; i++)
1420 if (startup_pipes[i] != -1)
1421 FD_SET(startup_pipes[i], fdset);
1423 /* Wait in select until there is a connection. */
1424 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1425 if (ret < 0 && errno != EINTR)
1426 error("select: %.100s", strerror(errno));
1427 if (received_sigterm) {
1428 logit("Received signal %d; terminating.",
1429 (int) received_sigterm);
1430 close_listen_socks();
1431 unlink(options.pid_file);
1434 if (key_used && key_do_regen) {
1435 generate_ephemeral_server_key();
1442 for (i = 0; i < options.max_startups; i++)
1443 if (startup_pipes[i] != -1 &&
1444 FD_ISSET(startup_pipes[i], fdset)) {
1446 * the read end of the pipe is ready
1447 * if the child has closed the pipe
1448 * after successful authentication
1449 * or if the child has died
1451 close(startup_pipes[i]);
1452 startup_pipes[i] = -1;
1455 for (i = 0; i < num_listen_socks; i++) {
1456 if (!FD_ISSET(listen_socks[i], fdset))
1458 fromlen = sizeof(from);
1459 newsock = accept(listen_socks[i],
1460 (struct sockaddr *)&from, &fromlen);
1462 if (errno != EINTR && errno != EWOULDBLOCK)
1463 error("accept: %.100s", strerror(errno));
1466 if (unset_nonblock(newsock) == -1) {
1470 if (drop_connection(startups) == 1) {
1471 debug("drop connection #%d", startups);
1475 if (pipe(startup_p) == -1) {
1480 if (rexec_flag && socketpair(AF_UNIX,
1481 SOCK_STREAM, 0, config_s) == -1) {
1482 error("reexec socketpair: %s",
1485 close(startup_p[0]);
1486 close(startup_p[1]);
1490 for (j = 0; j < options.max_startups; j++)
1491 if (startup_pipes[j] == -1) {
1492 startup_pipes[j] = startup_p[0];
1493 if (maxfd < startup_p[0])
1494 maxfd = startup_p[0];
1500 * Got connection. Fork a child to handle it, unless
1501 * we are in debugging mode.
1505 * In debugging mode. Close the listening
1506 * socket, and start processing the
1507 * connection without forking.
1509 debug("Server will not fork when running in debugging mode.");
1510 close_listen_socks();
1513 close(startup_p[0]);
1514 close(startup_p[1]);
1518 send_rexec_state(config_s[0],
1525 * Normal production daemon. Fork, and have
1526 * the child process the connection. The
1527 * parent continues listening.
1529 if ((pid = fork()) == 0) {
1531 * Child. Close the listening and
1532 * max_startup sockets. Start using
1533 * the accepted socket. Reinitialize
1534 * logging (since our pid has changed).
1535 * We break out of the loop to handle
1538 startup_pipe = startup_p[1];
1539 close_startup_pipes();
1540 close_listen_socks();
1543 log_init(__progname,
1545 options.log_facility,
1553 /* Parent. Stay in the loop. */
1555 error("fork: %.100s", strerror(errno));
1557 debug("Forked child %ld.", (long)pid);
1559 close(startup_p[1]);
1562 send_rexec_state(config_s[0], &cfg);
1568 * Mark that the key has been used (it
1569 * was "given" to the child).
1571 if ((options.protocol & SSH_PROTO_1) &&
1573 /* Schedule server key regeneration alarm. */
1574 signal(SIGALRM, key_regeneration_alarm);
1575 alarm(options.key_regeneration_time);
1582 /* child process check (or debug mode) */
1583 if (num_listen_socks < 0)
1588 /* This is the child processing a new connection. */
1589 setproctitle("%s", "[accepted]");
1592 * Create a new session and process group since the 4.4BSD
1593 * setlogin() affects the entire process group. We don't
1594 * want the child to be able to affect the parent.
1596 #if !defined(SSHD_ACQUIRES_CTTY)
1598 * If setsid is called, on some platforms sshd will later acquire a
1599 * controlling terminal which will result in "could not set
1600 * controlling tty" errors.
1602 if (!debug_flag && !inetd_flag && setsid() < 0)
1603 error("setsid: %.100s", strerror(errno));
1609 debug("rexec start in %d out %d newsock %d pipe %d sock %d",
1610 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1611 dup2(newsock, STDIN_FILENO);
1612 dup2(STDIN_FILENO, STDOUT_FILENO);
1613 if (startup_pipe == -1)
1614 close(REEXEC_STARTUP_PIPE_FD);
1616 dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
1618 dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1620 if (startup_pipe != -1)
1621 close(startup_pipe);
1623 execv(rexec_argv[0], rexec_argv);
1625 /* Reexec has failed, fall back and continue */
1626 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1627 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1628 log_init(__progname, options.log_level,
1629 options.log_facility, log_stderr);
1632 startup_pipe = REEXEC_STARTUP_PIPE_FD;
1634 close(REEXEC_CONFIG_PASS_FD);
1635 newsock = sock_out = sock_in = dup(STDIN_FILENO);
1636 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1637 dup2(fd, STDIN_FILENO);
1638 dup2(fd, STDOUT_FILENO);
1639 if (fd > STDERR_FILENO)
1642 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
1643 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1647 * Disable the key regeneration alarm. We will not regenerate the
1648 * key since we are no longer in a position to give it to anyone. We
1649 * will not restart on SIGHUP since it no longer makes sense.
1652 signal(SIGALRM, SIG_DFL);
1653 signal(SIGHUP, SIG_DFL);
1654 signal(SIGTERM, SIG_DFL);
1655 signal(SIGQUIT, SIG_DFL);
1656 signal(SIGCHLD, SIG_DFL);
1657 signal(SIGINT, SIG_DFL);
1660 * Register our connection. This turns encryption off because we do
1663 packet_set_connection(sock_in, sock_out);
1664 packet_set_server();
1666 /* Set SO_KEEPALIVE if requested. */
1667 if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
1668 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
1669 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1671 if ((remote_port = get_remote_port()) < 0) {
1672 debug("get_remote_port failed");
1677 * We use get_canonical_hostname with usedns = 0 instead of
1678 * get_remote_ipaddr here so IP options will be checked.
1680 (void) get_canonical_hostname(0);
1682 * The rest of the code depends on the fact that
1683 * get_remote_ipaddr() caches the remote ip, even if
1684 * the socket goes away.
1686 remote_ip = get_remote_ipaddr();
1688 #ifdef SSH_AUDIT_EVENTS
1689 audit_connection_from(remote_ip, remote_port);
1692 /* Check whether logins are denied from this host. */
1693 if (packet_connection_is_on_socket()) {
1694 struct request_info req;
1696 request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1699 if (!hosts_access(&req)) {
1700 debug("Connection refused by tcp wrapper");
1703 fatal("libwrap refuse returns");
1706 #endif /* LIBWRAP */
1708 /* Log the connection. */
1709 verbose("Connection from %.500s port %d", remote_ip, remote_port);
1712 * We don't want to listen forever unless the other side
1713 * successfully authenticates itself. So we set up an alarm which is
1714 * cleared after successful authentication. A limit of zero
1715 * indicates no limit. Note that we don't set the alarm in debugging
1716 * mode; it is just annoying to have the server exit just when you
1717 * are about to discover the bug.
1719 signal(SIGALRM, grace_alarm_handler);
1721 alarm(options.login_grace_time);
1723 sshd_exchange_identification(sock_in, sock_out);
1725 packet_set_nonblocking();
1727 /* allocate authentication context */
1728 authctxt = xcalloc(1, sizeof(*authctxt));
1730 authctxt->loginmsg = &loginmsg;
1732 /* XXX global for cleanup, access from other modules */
1733 the_authctxt = authctxt;
1735 /* prepare buffer to collect messages to display to user after login */
1736 buffer_init(&loginmsg);
1739 if (privsep_preauth(authctxt) == 1)
1742 /* perform the key exchange */
1743 /* authenticate user and start session */
1746 do_authentication2(authctxt);
1749 do_authentication(authctxt);
1752 * If we use privilege separation, the unprivileged child transfers
1753 * the current keystate and exits
1756 mm_send_keystate(pmonitor);
1762 * Cancel the alarm we set to limit the time taken for
1766 signal(SIGALRM, SIG_DFL);
1767 if (startup_pipe != -1) {
1768 close(startup_pipe);
1772 #ifdef SSH_AUDIT_EVENTS
1773 audit_event(SSH_AUTH_SUCCESS);
1777 * In privilege separation, we fork another child and prepare
1778 * file descriptor passing.
1781 privsep_postauth(authctxt);
1782 /* the monitor process [priv] will not return */
1784 destroy_sensitive_data();
1787 /* Start session. */
1788 do_authenticated(authctxt);
1790 /* The connection has been terminated. */
1791 verbose("Closing connection to %.100s", remote_ip);
1794 if (options.use_pam)
1796 #endif /* USE_PAM */
1798 #ifdef SSH_AUDIT_EVENTS
1799 PRIVSEP(audit_event(SSH_CONNECTION_CLOSE));
1811 * Decrypt session_key_int using our private server key and private host key
1812 * (key with larger modulus first).
1815 ssh1_session_key(BIGNUM *session_key_int)
1819 if (BN_cmp(sensitive_data.server_key->rsa->n,
1820 sensitive_data.ssh1_host_key->rsa->n) > 0) {
1821 /* Server key has bigger modulus. */
1822 if (BN_num_bits(sensitive_data.server_key->rsa->n) <
1823 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1824 SSH_KEY_BITS_RESERVED) {
1825 fatal("do_connection: %s: "
1826 "server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1827 get_remote_ipaddr(),
1828 BN_num_bits(sensitive_data.server_key->rsa->n),
1829 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1830 SSH_KEY_BITS_RESERVED);
1832 if (rsa_private_decrypt(session_key_int, session_key_int,
1833 sensitive_data.server_key->rsa) <= 0)
1835 if (rsa_private_decrypt(session_key_int, session_key_int,
1836 sensitive_data.ssh1_host_key->rsa) <= 0)
1839 /* Host key has bigger modulus (or they are equal). */
1840 if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
1841 BN_num_bits(sensitive_data.server_key->rsa->n) +
1842 SSH_KEY_BITS_RESERVED) {
1843 fatal("do_connection: %s: "
1844 "host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
1845 get_remote_ipaddr(),
1846 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1847 BN_num_bits(sensitive_data.server_key->rsa->n),
1848 SSH_KEY_BITS_RESERVED);
1850 if (rsa_private_decrypt(session_key_int, session_key_int,
1851 sensitive_data.ssh1_host_key->rsa) < 0)
1853 if (rsa_private_decrypt(session_key_int, session_key_int,
1854 sensitive_data.server_key->rsa) < 0)
1867 BIGNUM *session_key_int;
1868 u_char session_key[SSH_SESSION_KEY_LENGTH];
1870 u_int cipher_type, auth_mask, protocol_flags;
1874 * Generate check bytes that the client must send back in the user
1875 * packet in order for it to be accepted; this is used to defy ip
1876 * spoofing attacks. Note that this only works against somebody
1877 * doing IP spoofing from a remote machine; any machine on the local
1878 * network can still see outgoing packets and catch the random
1879 * cookie. This only affects rhosts authentication, and this is one
1880 * of the reasons why it is inherently insecure.
1882 for (i = 0; i < 8; i++) {
1885 cookie[i] = rnd & 0xff;
1890 * Send our public key. We include in the packet 64 bits of random
1891 * data that must be matched in the reply in order to prevent IP
1894 packet_start(SSH_SMSG_PUBLIC_KEY);
1895 for (i = 0; i < 8; i++)
1896 packet_put_char(cookie[i]);
1898 /* Store our public server RSA key. */
1899 packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
1900 packet_put_bignum(sensitive_data.server_key->rsa->e);
1901 packet_put_bignum(sensitive_data.server_key->rsa->n);
1903 /* Store our public host RSA key. */
1904 packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1905 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
1906 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
1908 /* Put protocol flags. */
1909 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
1911 /* Declare which ciphers we support. */
1912 packet_put_int(cipher_mask_ssh1(0));
1914 /* Declare supported authentication types. */
1916 if (options.rhosts_rsa_authentication)
1917 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
1918 if (options.rsa_authentication)
1919 auth_mask |= 1 << SSH_AUTH_RSA;
1920 if (options.challenge_response_authentication == 1)
1921 auth_mask |= 1 << SSH_AUTH_TIS;
1922 if (options.password_authentication)
1923 auth_mask |= 1 << SSH_AUTH_PASSWORD;
1924 packet_put_int(auth_mask);
1926 /* Send the packet and wait for it to be sent. */
1928 packet_write_wait();
1930 debug("Sent %d bit server key and %d bit host key.",
1931 BN_num_bits(sensitive_data.server_key->rsa->n),
1932 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1934 /* Read clients reply (cipher type and session key). */
1935 packet_read_expect(SSH_CMSG_SESSION_KEY);
1937 /* Get cipher type and check whether we accept this. */
1938 cipher_type = packet_get_char();
1940 if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
1941 packet_disconnect("Warning: client selects unsupported cipher.");
1943 /* Get check bytes from the packet. These must match those we
1944 sent earlier with the public key packet. */
1945 for (i = 0; i < 8; i++)
1946 if (cookie[i] != packet_get_char())
1947 packet_disconnect("IP Spoofing check bytes do not match.");
1949 debug("Encryption type: %.200s", cipher_name(cipher_type));
1951 /* Get the encrypted integer. */
1952 if ((session_key_int = BN_new()) == NULL)
1953 fatal("do_ssh1_kex: BN_new failed");
1954 packet_get_bignum(session_key_int);
1956 protocol_flags = packet_get_int();
1957 packet_set_protocol_flags(protocol_flags);
1960 /* Decrypt session_key_int using host/server keys */
1961 rsafail = PRIVSEP(ssh1_session_key(session_key_int));
1964 * Extract session key from the decrypted integer. The key is in the
1965 * least significant 256 bits of the integer; the first byte of the
1966 * key is in the highest bits.
1969 BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1970 len = BN_num_bytes(session_key_int);
1971 if (len < 0 || (u_int)len > sizeof(session_key)) {
1972 error("do_connection: bad session key len from %s: "
1973 "session_key_int %d > sizeof(session_key) %lu",
1974 get_remote_ipaddr(), len, (u_long)sizeof(session_key));
1977 memset(session_key, 0, sizeof(session_key));
1978 BN_bn2bin(session_key_int,
1979 session_key + sizeof(session_key) - len);
1981 derive_ssh1_session_id(
1982 sensitive_data.ssh1_host_key->rsa->n,
1983 sensitive_data.server_key->rsa->n,
1984 cookie, session_id);
1986 * Xor the first 16 bytes of the session key with the
1989 for (i = 0; i < 16; i++)
1990 session_key[i] ^= session_id[i];
1994 int bytes = BN_num_bytes(session_key_int);
1995 u_char *buf = xmalloc(bytes);
1998 logit("do_connection: generating a fake encryption key");
1999 BN_bn2bin(session_key_int, buf);
2001 MD5_Update(&md, buf, bytes);
2002 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2003 MD5_Final(session_key, &md);
2005 MD5_Update(&md, session_key, 16);
2006 MD5_Update(&md, buf, bytes);
2007 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2008 MD5_Final(session_key + 16, &md);
2009 memset(buf, 0, bytes);
2011 for (i = 0; i < 16; i++)
2012 session_id[i] = session_key[i] ^ session_key[i + 16];
2014 /* Destroy the private and public keys. No longer. */
2015 destroy_sensitive_data();
2018 mm_ssh1_session_id(session_id);
2020 /* Destroy the decrypted integer. It is no longer needed. */
2021 BN_clear_free(session_key_int);
2023 /* Set the session key. From this on all communications will be encrypted. */
2024 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
2026 /* Destroy our copy of the session key. It is no longer needed. */
2027 memset(session_key, 0, sizeof(session_key));
2029 debug("Received session key; encryption turned on.");
2031 /* Send an acknowledgment packet. Note that this packet is sent encrypted. */
2032 packet_start(SSH_SMSG_SUCCESS);
2034 packet_write_wait();
2038 * SSH2 key exchange: diffie-hellman-group1-sha1
2045 if (options.ciphers != NULL) {
2046 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2047 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
2049 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2050 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
2051 myproposal[PROPOSAL_ENC_ALGS_STOC] =
2052 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
2054 if (options.macs != NULL) {
2055 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2056 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2058 if (options.compression == COMP_NONE) {
2059 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2060 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2061 } else if (options.compression == COMP_DELAYED) {
2062 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2063 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com";
2066 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
2068 /* start key exchange */
2069 kex = kex_setup(myproposal);
2070 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2071 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
2072 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2073 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2075 kex->client_version_string=client_version_string;
2076 kex->server_version_string=server_version_string;
2077 kex->load_host_key=&get_hostkey_by_type;
2078 kex->host_key_index=&get_hostkey_index;
2082 dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
2084 session_id2 = kex->session_id;
2085 session_id2_len = kex->session_id_len;
2088 /* send 1st encrypted/maced/compressed message */
2089 packet_start(SSH2_MSG_IGNORE);
2090 packet_put_cstring("markus");
2092 packet_write_wait();
2097 /* server specific fatal cleanup */
2102 do_cleanup(the_authctxt);
2103 #ifdef SSH_AUDIT_EVENTS
2104 /* done after do_cleanup so it can cancel the PAM auth 'thread' */
2105 if (!use_privsep || mm_is_monitor())
2106 audit_event(SSH_CONNECTION_ABANDON);