2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * This program is the ssh daemon. It listens for connections from clients,
6 * and performs authentication, executes use commands or shell, and forwards
7 * information to/from the application to the user client over an encrypted
8 * connection. This can also handle forwarding of X11, TCP/IP, and
9 * authentication agent connections.
11 * As far as I am concerned, the code I have written for this software
12 * can be used freely for any purpose. Any derived versions of this
13 * software must be clearly marked as such, and if the derived work is
14 * incompatible with the protocol description in the RFC file, it must be
15 * called by a name other than "ssh" or "Secure Shell".
17 * SSH2 implementation:
18 * Privilege Separation:
20 * Copyright (c) 2000, 2001, 2002 Markus Friedl. All rights reserved.
21 * Copyright (c) 2002 Niels Provos. All rights reserved.
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
26 * 1. Redistributions of source code must retain the above copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
32 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
33 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
34 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
35 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
36 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
37 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
41 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
46 #include <sys/types.h>
47 #ifdef HAVE_SYS_STAT_H
48 # include <sys/stat.h>
50 #include <sys/ioctl.h>
58 #include <openssl/dh.h>
59 #include <openssl/bn.h>
60 #include <openssl/md5.h>
61 #include <openssl/rand.h>
62 #ifdef HAVE_SECUREWARE
63 #include <sys/security.h>
84 #include "myproposal.h"
86 #include "pathnames.h"
95 #include "monitor_mm.h"
97 #include "monitor_wrap.h"
98 #include "monitor_fdpass.h"
103 int allow_severity = LOG_INFO;
104 int deny_severity = LOG_WARNING;
112 #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
113 #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
114 #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
115 #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
117 extern char *__progname;
119 /* Server configuration options. */
120 ServerOptions options;
122 /* Name of the server configuration file. */
123 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
126 * Debug mode flag. This can be set on the command line. If debug
127 * mode is enabled, extra debugging output will be sent to the system
128 * log, the daemon will not go to background, and will exit after processing
129 * the first connection.
133 /* Flag indicating that the daemon should only test the configuration and keys. */
136 /* Flag indicating that the daemon is being started from inetd. */
139 /* Flag indicating that sshd should not detach and become a daemon. */
140 int no_daemon_flag = 0;
142 /* debug goes to stderr unless inetd_flag is set */
145 /* Saved arguments to main(). */
150 int rexeced_flag = 0;
156 * The sockets that the server is listening; this is used in the SIGHUP
159 #define MAX_LISTEN_SOCKS 16
160 int listen_socks[MAX_LISTEN_SOCKS];
161 int num_listen_socks = 0;
164 * the client's version string, passed by sshd2 in compat mode. if != NULL,
165 * sshd will skip the version-number exchange
167 char *client_version_string = NULL;
168 char *server_version_string = NULL;
170 /* for rekeying XXX fixme */
174 * Any really sensitive data in the application is contained in this
175 * structure. The idea is that this structure could be locked into memory so
176 * that the pages do not get written into swap. However, there are some
177 * problems. The private key contains BIGNUMs, and we do not (in principle)
178 * have access to the internals of them, and locking just the structure is
179 * not very useful. Currently, memory locking is not implemented.
182 Key *server_key; /* ephemeral server key */
183 Key *ssh1_host_key; /* ssh1 host key */
184 Key **host_keys; /* all private host keys */
187 u_char ssh1_cookie[SSH_SESSION_KEY_LENGTH];
191 * Flag indicating whether the RSA server key needs to be regenerated.
192 * Is set in the SIGALRM handler and cleared when the key is regenerated.
194 static volatile sig_atomic_t key_do_regen = 0;
196 /* This is set to true when a signal is received. */
197 static volatile sig_atomic_t received_sighup = 0;
198 static volatile sig_atomic_t received_sigterm = 0;
200 /* session identifier, used by RSA-auth */
201 u_char session_id[16];
204 u_char *session_id2 = NULL;
205 u_int session_id2_len = 0;
207 /* record remote hostname or ip */
208 u_int utmp_len = MAXHOSTNAMELEN;
210 /* options.max_startup sized array of fd ints */
211 int *startup_pipes = NULL;
212 int startup_pipe; /* in child */
214 /* variables used for privilege separation */
216 struct monitor *pmonitor = NULL;
218 /* global authentication context */
219 Authctxt *the_authctxt = NULL;
221 /* message to be displayed after login */
224 /* Prototypes for various functions defined later in this file. */
225 void destroy_sensitive_data(void);
226 void demote_sensitive_data(void);
228 static void do_ssh1_kex(void);
229 static void do_ssh2_kex(void);
232 * Close all listening sockets
235 close_listen_socks(void)
239 for (i = 0; i < num_listen_socks; i++)
240 close(listen_socks[i]);
241 num_listen_socks = -1;
245 close_startup_pipes(void)
250 for (i = 0; i < options.max_startups; i++)
251 if (startup_pipes[i] != -1)
252 close(startup_pipes[i]);
256 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
257 * the effect is to reread the configuration file (and to regenerate
263 sighup_handler(int sig)
265 int save_errno = errno;
268 signal(SIGHUP, sighup_handler);
273 * Called from the main program after receiving SIGHUP.
274 * Restarts the server.
279 logit("Received SIGHUP; restarting.");
280 close_listen_socks();
281 close_startup_pipes();
282 execv(saved_argv[0], saved_argv);
283 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
289 * Generic signal handler for terminating signals in the master daemon.
293 sigterm_handler(int sig)
295 received_sigterm = sig;
299 * SIGCHLD handler. This is called whenever a child dies. This will then
300 * reap any zombies left by exited children.
304 main_sigchld_handler(int sig)
306 int save_errno = errno;
310 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
311 (pid < 0 && errno == EINTR))
314 signal(SIGCHLD, main_sigchld_handler);
319 * Signal handler for the alarm after the login grace period has expired.
323 grace_alarm_handler(int sig)
325 /* XXX no idea how fix this signal handler */
327 if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
328 kill(pmonitor->m_pid, SIGALRM);
330 /* Log error and exit. */
331 fatal("Timeout before authentication for %s", get_remote_ipaddr());
335 * Signal handler for the key regeneration alarm. Note that this
336 * alarm only occurs in the daemon waiting for connections, and it does not
337 * do anything with the private key or random state before forking.
338 * Thus there should be no concurrency control/asynchronous execution
342 generate_ephemeral_server_key(void)
347 verbose("Generating %s%d bit RSA key.",
348 sensitive_data.server_key ? "new " : "", options.server_key_bits);
349 if (sensitive_data.server_key != NULL)
350 key_free(sensitive_data.server_key);
351 sensitive_data.server_key = key_generate(KEY_RSA1,
352 options.server_key_bits);
353 verbose("RSA key generation complete.");
355 for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
358 sensitive_data.ssh1_cookie[i] = rnd & 0xff;
366 key_regeneration_alarm(int sig)
368 int save_errno = errno;
370 signal(SIGALRM, SIG_DFL);
376 sshd_exchange_identification(int sock_in, int sock_out)
380 int remote_major, remote_minor;
383 char buf[256]; /* Must not be larger than remote_version. */
384 char remote_version[256]; /* Must be at least as big as buf. */
386 if ((options.protocol & SSH_PROTO_1) &&
387 (options.protocol & SSH_PROTO_2)) {
388 major = PROTOCOL_MAJOR_1;
390 } else if (options.protocol & SSH_PROTO_2) {
391 major = PROTOCOL_MAJOR_2;
392 minor = PROTOCOL_MINOR_2;
394 major = PROTOCOL_MAJOR_1;
395 minor = PROTOCOL_MINOR_1;
397 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", major, minor, SSH_VERSION);
398 server_version_string = xstrdup(buf);
400 /* Send our protocol version identification. */
401 if (atomicio(vwrite, sock_out, server_version_string,
402 strlen(server_version_string))
403 != strlen(server_version_string)) {
404 logit("Could not write ident string to %s", get_remote_ipaddr());
408 /* Read other sides version identification. */
409 memset(buf, 0, sizeof(buf));
410 for (i = 0; i < sizeof(buf) - 1; i++) {
411 if (atomicio(read, sock_in, &buf[i], 1) != 1) {
412 logit("Did not receive identification string from %s",
413 get_remote_ipaddr());
416 if (buf[i] == '\r') {
418 /* Kludge for F-Secure Macintosh < 1.0.2 */
420 strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
424 if (buf[i] == '\n') {
429 buf[sizeof(buf) - 1] = 0;
430 client_version_string = xstrdup(buf);
433 * Check that the versions match. In future this might accept
434 * several versions and set appropriate flags to handle them.
436 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
437 &remote_major, &remote_minor, remote_version) != 3) {
438 s = "Protocol mismatch.\n";
439 (void) atomicio(vwrite, sock_out, s, strlen(s));
442 logit("Bad protocol version identification '%.100s' from %s",
443 client_version_string, get_remote_ipaddr());
446 debug("Client protocol version %d.%d; client software version %.100s",
447 remote_major, remote_minor, remote_version);
449 compat_datafellows(remote_version);
451 if (datafellows & SSH_BUG_PROBE) {
452 logit("probed from %s with %s. Don't panic.",
453 get_remote_ipaddr(), client_version_string);
457 if (datafellows & SSH_BUG_SCANNER) {
458 logit("scanned from %s with %s. Don't panic.",
459 get_remote_ipaddr(), client_version_string);
464 switch (remote_major) {
466 if (remote_minor == 99) {
467 if (options.protocol & SSH_PROTO_2)
473 if (!(options.protocol & SSH_PROTO_1)) {
477 if (remote_minor < 3) {
478 packet_disconnect("Your ssh version is too old and "
479 "is no longer supported. Please install a newer version.");
480 } else if (remote_minor == 3) {
481 /* note that this disables agent-forwarding */
486 if (options.protocol & SSH_PROTO_2) {
495 chop(server_version_string);
496 debug("Local version string %.200s", server_version_string);
499 s = "Protocol major versions differ.\n";
500 (void) atomicio(vwrite, sock_out, s, strlen(s));
503 logit("Protocol major versions differ for %s: %.200s vs. %.200s",
505 server_version_string, client_version_string);
510 /* Destroy the host and server keys. They will no longer be needed. */
512 destroy_sensitive_data(void)
516 if (sensitive_data.server_key) {
517 key_free(sensitive_data.server_key);
518 sensitive_data.server_key = NULL;
520 for (i = 0; i < options.num_host_key_files; i++) {
521 if (sensitive_data.host_keys[i]) {
522 key_free(sensitive_data.host_keys[i]);
523 sensitive_data.host_keys[i] = NULL;
526 sensitive_data.ssh1_host_key = NULL;
527 memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
530 /* Demote private to public keys for network child */
532 demote_sensitive_data(void)
537 if (sensitive_data.server_key) {
538 tmp = key_demote(sensitive_data.server_key);
539 key_free(sensitive_data.server_key);
540 sensitive_data.server_key = tmp;
543 for (i = 0; i < options.num_host_key_files; i++) {
544 if (sensitive_data.host_keys[i]) {
545 tmp = key_demote(sensitive_data.host_keys[i]);
546 key_free(sensitive_data.host_keys[i]);
547 sensitive_data.host_keys[i] = tmp;
548 if (tmp->type == KEY_RSA1)
549 sensitive_data.ssh1_host_key = tmp;
553 /* We do not clear ssh1_host key and cookie. XXX - Okay Niels? */
557 privsep_preauth_child(void)
564 /* Enable challenge-response authentication for privilege separation */
565 privsep_challenge_enable();
567 for (i = 0; i < 256; i++)
568 rnd[i] = arc4random();
569 RAND_seed(rnd, sizeof(rnd));
571 /* Demote the private keys to public keys. */
572 demote_sensitive_data();
574 if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL)
575 fatal("Privilege separation user %s does not exist",
577 memset(pw->pw_passwd, 0, strlen(pw->pw_passwd));
580 /* Change our root directory */
581 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
582 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
584 if (chdir("/") == -1)
585 fatal("chdir(\"/\"): %s", strerror(errno));
587 /* Drop our privileges */
588 debug3("privsep user:group %u:%u", (u_int)pw->pw_uid,
591 /* XXX not ready, too heavy after chroot */
592 do_setusercontext(pw);
594 gidset[0] = pw->pw_gid;
595 if (setgroups(1, gidset) < 0)
596 fatal("setgroups: %.100s", strerror(errno));
597 permanently_set_uid(pw);
602 privsep_preauth(Authctxt *authctxt)
607 /* Set up unprivileged child process to deal with network data */
608 pmonitor = monitor_init();
609 /* Store a pointer to the kex for later rekeying */
610 pmonitor->m_pkex = &xxx_kex;
614 fatal("fork of unprivileged child failed");
615 } else if (pid != 0) {
616 debug2("Network child is on pid %ld", (long)pid);
618 close(pmonitor->m_recvfd);
619 pmonitor->m_pid = pid;
620 monitor_child_preauth(authctxt, pmonitor);
621 close(pmonitor->m_sendfd);
624 monitor_sync(pmonitor);
626 /* Wait for the child's exit status */
627 while (waitpid(pid, &status, 0) < 0)
634 close(pmonitor->m_sendfd);
636 /* Demote the child */
637 if (getuid() == 0 || geteuid() == 0)
638 privsep_preauth_child();
639 setproctitle("%s", "[net]");
645 privsep_postauth(Authctxt *authctxt)
647 #ifdef DISABLE_FD_PASSING
650 if (authctxt->pw->pw_uid == 0 || options.use_login) {
652 /* File descriptor passing is broken or root login */
657 /* New socket pair */
658 monitor_reinit(pmonitor);
660 pmonitor->m_pid = fork();
661 if (pmonitor->m_pid == -1)
662 fatal("fork of unprivileged child failed");
663 else if (pmonitor->m_pid != 0) {
664 debug2("User child is on pid %ld", (long)pmonitor->m_pid);
665 close(pmonitor->m_recvfd);
666 buffer_clear(&loginmsg);
667 monitor_child_postauth(pmonitor);
673 close(pmonitor->m_sendfd);
675 /* Demote the private keys to public keys. */
676 demote_sensitive_data();
678 /* Drop privileges */
679 do_setusercontext(authctxt->pw);
682 /* It is safe now to apply the key state */
683 monitor_apply_keystate(pmonitor);
686 * Tell the packet layer that authentication was successful, since
687 * this information is not part of the key state.
689 packet_set_authenticated();
693 list_hostkey_types(void)
701 for (i = 0; i < options.num_host_key_files; i++) {
702 Key *key = sensitive_data.host_keys[i];
708 if (buffer_len(&b) > 0)
709 buffer_append(&b, ",", 1);
710 p = key_ssh_name(key);
711 buffer_append(&b, p, strlen(p));
715 buffer_append(&b, "\0", 1);
716 ret = xstrdup(buffer_ptr(&b));
718 debug("list_hostkey_types: %s", ret);
723 get_hostkey_by_type(int type)
727 for (i = 0; i < options.num_host_key_files; i++) {
728 Key *key = sensitive_data.host_keys[i];
729 if (key != NULL && key->type == type)
736 get_hostkey_by_index(int ind)
738 if (ind < 0 || ind >= options.num_host_key_files)
740 return (sensitive_data.host_keys[ind]);
744 get_hostkey_index(Key *key)
748 for (i = 0; i < options.num_host_key_files; i++) {
749 if (key == sensitive_data.host_keys[i])
756 * returns 1 if connection should be dropped, 0 otherwise.
757 * dropping starts at connection #max_startups_begin with a probability
758 * of (max_startups_rate/100). the probability increases linearly until
759 * all connections are dropped for startups > max_startups
762 drop_connection(int startups)
766 if (startups < options.max_startups_begin)
768 if (startups >= options.max_startups)
770 if (options.max_startups_rate == 100)
773 p = 100 - options.max_startups_rate;
774 p *= startups - options.max_startups_begin;
775 p /= options.max_startups - options.max_startups_begin;
776 p += options.max_startups_rate;
777 r = arc4random() % 100;
779 debug("drop_connection: p %d, r %d", p, r);
780 return (r < p) ? 1 : 0;
786 fprintf(stderr, "%s, %s\n",
787 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
789 "usage: sshd [-46Ddeiqt] [-b bits] [-f config_file] [-g login_grace_time]\n"
790 " [-h host_key_file] [-k key_gen_time] [-o option] [-p port] [-u len]\n"
796 send_rexec_state(int fd, Buffer *conf)
800 debug3("%s: entering fd = %d config len %d", __func__, fd,
804 * Protocol from reexec master to child:
805 * string configuration
806 * u_int ephemeral_key_follows
807 * bignum e (only if ephemeral_key_follows == 1)
813 * string rngseed (only if OpenSSL is not self-seeded)
816 buffer_put_cstring(&m, buffer_ptr(conf));
818 if (sensitive_data.server_key != NULL &&
819 sensitive_data.server_key->type == KEY_RSA1) {
820 buffer_put_int(&m, 1);
821 buffer_put_bignum(&m, sensitive_data.server_key->rsa->e);
822 buffer_put_bignum(&m, sensitive_data.server_key->rsa->n);
823 buffer_put_bignum(&m, sensitive_data.server_key->rsa->d);
824 buffer_put_bignum(&m, sensitive_data.server_key->rsa->iqmp);
825 buffer_put_bignum(&m, sensitive_data.server_key->rsa->p);
826 buffer_put_bignum(&m, sensitive_data.server_key->rsa->q);
828 buffer_put_int(&m, 0);
830 #ifndef OPENSSL_PRNG_ONLY
831 rexec_send_rng_seed(&m);
834 if (ssh_msg_send(fd, 0, &m) == -1)
835 fatal("%s: ssh_msg_send failed", __func__);
839 debug3("%s: done", __func__);
843 recv_rexec_state(int fd, Buffer *conf)
849 debug3("%s: entering fd = %d", __func__, fd);
853 if (ssh_msg_recv(fd, &m) == -1)
854 fatal("%s: ssh_msg_recv failed", __func__);
855 if (buffer_get_char(&m) != 0)
856 fatal("%s: rexec version mismatch", __func__);
858 cp = buffer_get_string(&m, &len);
860 buffer_append(conf, cp, len + 1);
863 if (buffer_get_int(&m)) {
864 if (sensitive_data.server_key != NULL)
865 key_free(sensitive_data.server_key);
866 sensitive_data.server_key = key_new_private(KEY_RSA1);
867 buffer_get_bignum(&m, sensitive_data.server_key->rsa->e);
868 buffer_get_bignum(&m, sensitive_data.server_key->rsa->n);
869 buffer_get_bignum(&m, sensitive_data.server_key->rsa->d);
870 buffer_get_bignum(&m, sensitive_data.server_key->rsa->iqmp);
871 buffer_get_bignum(&m, sensitive_data.server_key->rsa->p);
872 buffer_get_bignum(&m, sensitive_data.server_key->rsa->q);
873 rsa_generate_additional_parameters(
874 sensitive_data.server_key->rsa);
877 #ifndef OPENSSL_PRNG_ONLY
878 rexec_recv_rng_seed(&m);
883 debug3("%s: done", __func__);
887 * Main program for the daemon.
890 main(int ac, char **av)
894 int opt, j, i, fdsetsz, on = 1;
895 int sock_in = -1, sock_out = -1, newsock = -1;
899 struct sockaddr_storage from;
900 const char *remote_ip;
904 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
906 int listen_sock, maxfd;
907 int startup_p[2] = { -1 , -1 }, config_s[2] = { -1 , -1 };
911 int ret, key_used = 0;
914 #ifdef HAVE_SECUREWARE
915 (void)set_auth_parameters(ac, av);
917 __progname = ssh_get_progname(av[0]);
920 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
923 saved_argv = xmalloc(sizeof(*saved_argv) * (ac + 1));
924 for (i = 0; i < ac; i++)
925 saved_argv[i] = xstrdup(av[i]);
926 saved_argv[i] = NULL;
928 #ifndef HAVE_SETPROCTITLE
929 /* Prepare for later setproctitle emulation */
930 compat_init_setproctitle(ac, av);
934 if (geteuid() == 0 && setgroups(0, NULL) == -1)
935 debug("setgroups(): %.200s", strerror(errno));
937 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
940 /* Initialize configuration options to their default values. */
941 initialize_server_options(&options);
943 /* Parse command-line arguments. */
944 while ((opt = getopt(ac, av, "f:p:b:k:h:g:u:o:dDeiqrtQR46")) != -1) {
947 options.address_family = AF_INET;
950 options.address_family = AF_INET6;
953 config_file_name = optarg;
956 if (debug_flag == 0) {
958 options.log_level = SYSLOG_LEVEL_DEBUG1;
959 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
982 options.log_level = SYSLOG_LEVEL_QUIET;
985 options.server_key_bits = (int)strtonum(optarg, 256,
989 options.ports_from_cmdline = 1;
990 if (options.num_ports >= MAX_PORTS) {
991 fprintf(stderr, "too many ports.\n");
994 options.ports[options.num_ports++] = a2port(optarg);
995 if (options.ports[options.num_ports-1] == 0) {
996 fprintf(stderr, "Bad port number.\n");
1001 if ((options.login_grace_time = convtime(optarg)) == -1) {
1002 fprintf(stderr, "Invalid login grace time.\n");
1007 if ((options.key_regeneration_time = convtime(optarg)) == -1) {
1008 fprintf(stderr, "Invalid key regeneration interval.\n");
1013 if (options.num_host_key_files >= MAX_HOSTKEYS) {
1014 fprintf(stderr, "too many host keys.\n");
1017 options.host_key_files[options.num_host_key_files++] = optarg;
1023 utmp_len = (u_int)strtonum(optarg, 0, MAXHOSTNAMELEN+1, NULL);
1024 if (utmp_len > MAXHOSTNAMELEN) {
1025 fprintf(stderr, "Invalid utmp length.\n");
1030 line = xstrdup(optarg);
1031 if (process_server_config_line(&options, line,
1032 "command-line", 0) != 0)
1042 if (rexeced_flag || inetd_flag)
1044 if (rexec_flag && (av[0] == NULL || *av[0] != '/'))
1045 fatal("sshd re-exec requires execution with an absolute path");
1047 closefrom(REEXEC_MIN_FREE_FD);
1049 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1051 SSLeay_add_all_algorithms();
1054 * Force logging to stderr until we have loaded the private host
1055 * key (unless started from inetd)
1057 log_init(__progname,
1058 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1059 SYSLOG_LEVEL_INFO : options.log_level,
1060 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1061 SYSLOG_FACILITY_AUTH : options.log_facility,
1062 log_stderr || !inetd_flag);
1065 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1066 * root's environment
1068 if (getenv("KRB5CCNAME") != NULL)
1069 unsetenv("KRB5CCNAME");
1072 /* Cray can define user privs drop all privs now!
1073 * Not needed on PRIV_SU systems!
1078 sensitive_data.server_key = NULL;
1079 sensitive_data.ssh1_host_key = NULL;
1080 sensitive_data.have_ssh1_key = 0;
1081 sensitive_data.have_ssh2_key = 0;
1083 /* Fetch our configuration */
1086 recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1088 load_server_config(config_file_name, &cfg);
1090 parse_server_config(&options,
1091 rexeced_flag ? "rexec" : config_file_name, &cfg);
1098 /* Fill in default values for those options not explicitly set. */
1099 fill_default_server_options(&options);
1101 /* set default channel AF */
1102 channel_set_af(options.address_family);
1104 /* Check that there are no remaining arguments. */
1106 fprintf(stderr, "Extra argument %s.\n", av[optind]);
1110 debug("sshd version %.100s", SSH_RELEASE);
1112 /* load private host keys */
1113 sensitive_data.host_keys = xmalloc(options.num_host_key_files *
1115 for (i = 0; i < options.num_host_key_files; i++)
1116 sensitive_data.host_keys[i] = NULL;
1118 for (i = 0; i < options.num_host_key_files; i++) {
1119 key = key_load_private(options.host_key_files[i], "", NULL);
1120 sensitive_data.host_keys[i] = key;
1122 error("Could not load host key: %s",
1123 options.host_key_files[i]);
1124 sensitive_data.host_keys[i] = NULL;
1127 switch (key->type) {
1129 sensitive_data.ssh1_host_key = key;
1130 sensitive_data.have_ssh1_key = 1;
1134 sensitive_data.have_ssh2_key = 1;
1137 debug("private host key: #%d type %d %s", i, key->type,
1140 if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1141 logit("Disabling protocol version 1. Could not load host key");
1142 options.protocol &= ~SSH_PROTO_1;
1144 if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1145 logit("Disabling protocol version 2. Could not load host key");
1146 options.protocol &= ~SSH_PROTO_2;
1148 if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1149 logit("sshd: no hostkeys available -- exiting.");
1153 /* Check certain values for sanity. */
1154 if (options.protocol & SSH_PROTO_1) {
1155 if (options.server_key_bits < 512 ||
1156 options.server_key_bits > 32768) {
1157 fprintf(stderr, "Bad server key size.\n");
1161 * Check that server and host key lengths differ sufficiently. This
1162 * is necessary to make double encryption work with rsaref. Oh, I
1163 * hate software patents. I dont know if this can go? Niels
1165 if (options.server_key_bits >
1166 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
1167 SSH_KEY_BITS_RESERVED && options.server_key_bits <
1168 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1169 SSH_KEY_BITS_RESERVED) {
1170 options.server_key_bits =
1171 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1172 SSH_KEY_BITS_RESERVED;
1173 debug("Forcing server key to %d bits to make it differ from host key.",
1174 options.server_key_bits);
1181 if (getpwnam(SSH_PRIVSEP_USER) == NULL)
1182 fatal("Privilege separation user %s does not exist",
1184 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1185 (S_ISDIR(st.st_mode) == 0))
1186 fatal("Missing privilege separation directory: %s",
1187 _PATH_PRIVSEP_CHROOT_DIR);
1190 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1191 (st.st_uid != getuid () ||
1192 (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1194 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1196 fatal("%s must be owned by root and not group or "
1197 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1200 /* Configuration looks good, so exit if in test mode. */
1205 * Clear out any supplemental groups we may have inherited. This
1206 * prevents inadvertent creation of files with bad modes (in the
1207 * portable version at least, it's certainly possible for PAM
1208 * to create a file, and we can't control the code in every
1209 * module which might be used).
1211 if (setgroups(0, NULL) < 0)
1212 debug("setgroups() failed: %.200s", strerror(errno));
1215 rexec_argv = xmalloc(sizeof(char *) * (rexec_argc + 2));
1216 for (i = 0; i < rexec_argc; i++) {
1217 debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1218 rexec_argv[i] = saved_argv[i];
1220 rexec_argv[rexec_argc] = "-R";
1221 rexec_argv[rexec_argc + 1] = NULL;
1224 /* Initialize the log (it is reinitialized below in case we forked). */
1225 if (debug_flag && (!inetd_flag || rexeced_flag))
1227 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1230 * If not in debugging mode, and not started from inetd, disconnect
1231 * from the controlling terminal, and fork. The original process
1234 if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1237 #endif /* TIOCNOTTY */
1238 if (daemon(0, 0) < 0)
1239 fatal("daemon() failed: %.200s", strerror(errno));
1241 /* Disconnect from the controlling tty. */
1243 fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1245 (void) ioctl(fd, TIOCNOTTY, NULL);
1248 #endif /* TIOCNOTTY */
1250 /* Reinitialize the log (because of the fork above). */
1251 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1253 /* Initialize the random number generator. */
1256 /* Chdir to the root directory so that the current disk can be
1257 unmounted if desired. */
1260 /* ignore SIGPIPE */
1261 signal(SIGPIPE, SIG_IGN);
1263 /* Start listening for a socket, unless started from inetd. */
1269 close(REEXEC_CONFIG_PASS_FD);
1270 sock_in = sock_out = dup(STDIN_FILENO);
1272 startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
1273 close(REEXEC_STARTUP_PIPE_FD);
1276 sock_in = dup(STDIN_FILENO);
1277 sock_out = dup(STDOUT_FILENO);
1280 * We intentionally do not close the descriptors 0, 1, and 2
1281 * as our code for setting the descriptors won't work if
1282 * ttyfd happens to be one of those.
1284 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1285 dup2(fd, STDIN_FILENO);
1286 dup2(fd, STDOUT_FILENO);
1287 if (fd > STDOUT_FILENO)
1290 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
1291 if ((options.protocol & SSH_PROTO_1) &&
1292 sensitive_data.server_key == NULL)
1293 generate_ephemeral_server_key();
1295 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
1296 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1298 if (num_listen_socks >= MAX_LISTEN_SOCKS)
1299 fatal("Too many listen sockets. "
1300 "Enlarge MAX_LISTEN_SOCKS");
1301 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1302 ntop, sizeof(ntop), strport, sizeof(strport),
1303 NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1304 error("getnameinfo failed: %.100s",
1305 (ret != EAI_SYSTEM) ? gai_strerror(ret) :
1309 /* Create socket for listening. */
1310 listen_sock = socket(ai->ai_family, ai->ai_socktype,
1312 if (listen_sock < 0) {
1313 /* kernel may not support ipv6 */
1314 verbose("socket: %.100s", strerror(errno));
1317 if (set_nonblock(listen_sock) == -1) {
1322 * Set socket options.
1323 * Allow local port reuse in TIME_WAIT.
1325 if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
1326 &on, sizeof(on)) == -1)
1327 error("setsockopt SO_REUSEADDR: %s", strerror(errno));
1329 debug("Bind to port %s on %s.", strport, ntop);
1331 /* Bind the socket to the desired port. */
1332 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1334 error("Bind to port %s on %s failed: %.200s.",
1335 strport, ntop, strerror(errno));
1339 listen_socks[num_listen_socks] = listen_sock;
1342 /* Start listening on the port. */
1343 if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1344 fatal("listen on [%s]:%s: %.100s",
1345 ntop, strport, strerror(errno));
1346 logit("Server listening on %s port %s.", ntop, strport);
1348 freeaddrinfo(options.listen_addrs);
1350 if (!num_listen_socks)
1351 fatal("Cannot bind any address.");
1353 if (options.protocol & SSH_PROTO_1)
1354 generate_ephemeral_server_key();
1357 * Arrange to restart on SIGHUP. The handler needs
1360 signal(SIGHUP, sighup_handler);
1362 signal(SIGTERM, sigterm_handler);
1363 signal(SIGQUIT, sigterm_handler);
1365 /* Arrange SIGCHLD to be caught. */
1366 signal(SIGCHLD, main_sigchld_handler);
1368 /* Write out the pid file after the sigterm handler is setup */
1371 * Record our pid in /var/run/sshd.pid to make it
1372 * easier to kill the correct sshd. We don't want to
1373 * do this before the bind above because the bind will
1374 * fail if there already is a daemon, and this will
1375 * overwrite any old pid in the file.
1377 f = fopen(options.pid_file, "wb");
1379 error("Couldn't create pid file \"%s\": %s",
1380 options.pid_file, strerror(errno));
1382 fprintf(f, "%ld\n", (long) getpid());
1387 /* setup fd set for listen */
1390 for (i = 0; i < num_listen_socks; i++)
1391 if (listen_socks[i] > maxfd)
1392 maxfd = listen_socks[i];
1393 /* pipes connected to unauthenticated childs */
1394 startup_pipes = xmalloc(options.max_startups * sizeof(int));
1395 for (i = 0; i < options.max_startups; i++)
1396 startup_pipes[i] = -1;
1399 * Stay listening for connections until the system crashes or
1400 * the daemon is killed with a signal.
1403 if (received_sighup)
1407 fdsetsz = howmany(maxfd+1, NFDBITS) * sizeof(fd_mask);
1408 fdset = (fd_set *)xmalloc(fdsetsz);
1409 memset(fdset, 0, fdsetsz);
1411 for (i = 0; i < num_listen_socks; i++)
1412 FD_SET(listen_socks[i], fdset);
1413 for (i = 0; i < options.max_startups; i++)
1414 if (startup_pipes[i] != -1)
1415 FD_SET(startup_pipes[i], fdset);
1417 /* Wait in select until there is a connection. */
1418 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1419 if (ret < 0 && errno != EINTR)
1420 error("select: %.100s", strerror(errno));
1421 if (received_sigterm) {
1422 logit("Received signal %d; terminating.",
1423 (int) received_sigterm);
1424 close_listen_socks();
1425 unlink(options.pid_file);
1428 if (key_used && key_do_regen) {
1429 generate_ephemeral_server_key();
1436 for (i = 0; i < options.max_startups; i++)
1437 if (startup_pipes[i] != -1 &&
1438 FD_ISSET(startup_pipes[i], fdset)) {
1440 * the read end of the pipe is ready
1441 * if the child has closed the pipe
1442 * after successful authentication
1443 * or if the child has died
1445 close(startup_pipes[i]);
1446 startup_pipes[i] = -1;
1449 for (i = 0; i < num_listen_socks; i++) {
1450 if (!FD_ISSET(listen_socks[i], fdset))
1452 fromlen = sizeof(from);
1453 newsock = accept(listen_socks[i],
1454 (struct sockaddr *)&from, &fromlen);
1456 if (errno != EINTR && errno != EWOULDBLOCK)
1457 error("accept: %.100s", strerror(errno));
1460 if (unset_nonblock(newsock) == -1) {
1464 if (drop_connection(startups) == 1) {
1465 debug("drop connection #%d", startups);
1469 if (pipe(startup_p) == -1) {
1474 if (rexec_flag && socketpair(AF_UNIX,
1475 SOCK_STREAM, 0, config_s) == -1) {
1476 error("reexec socketpair: %s",
1479 close(startup_p[0]);
1480 close(startup_p[1]);
1484 for (j = 0; j < options.max_startups; j++)
1485 if (startup_pipes[j] == -1) {
1486 startup_pipes[j] = startup_p[0];
1487 if (maxfd < startup_p[0])
1488 maxfd = startup_p[0];
1494 * Got connection. Fork a child to handle it, unless
1495 * we are in debugging mode.
1499 * In debugging mode. Close the listening
1500 * socket, and start processing the
1501 * connection without forking.
1503 debug("Server will not fork when running in debugging mode.");
1504 close_listen_socks();
1507 close(startup_p[0]);
1508 close(startup_p[1]);
1512 send_rexec_state(config_s[0],
1519 * Normal production daemon. Fork, and have
1520 * the child process the connection. The
1521 * parent continues listening.
1523 if ((pid = fork()) == 0) {
1525 * Child. Close the listening and
1526 * max_startup sockets. Start using
1527 * the accepted socket. Reinitialize
1528 * logging (since our pid has changed).
1529 * We break out of the loop to handle
1532 startup_pipe = startup_p[1];
1533 close_startup_pipes();
1534 close_listen_socks();
1537 log_init(__progname,
1539 options.log_facility,
1547 /* Parent. Stay in the loop. */
1549 error("fork: %.100s", strerror(errno));
1551 debug("Forked child %ld.", (long)pid);
1553 close(startup_p[1]);
1556 send_rexec_state(config_s[0], &cfg);
1562 * Mark that the key has been used (it
1563 * was "given" to the child).
1565 if ((options.protocol & SSH_PROTO_1) &&
1567 /* Schedule server key regeneration alarm. */
1568 signal(SIGALRM, key_regeneration_alarm);
1569 alarm(options.key_regeneration_time);
1576 /* child process check (or debug mode) */
1577 if (num_listen_socks < 0)
1582 /* This is the child processing a new connection. */
1583 setproctitle("%s", "[accepted]");
1586 * Create a new session and process group since the 4.4BSD
1587 * setlogin() affects the entire process group. We don't
1588 * want the child to be able to affect the parent.
1590 #if !defined(SSHD_ACQUIRES_CTTY)
1592 * If setsid is called, on some platforms sshd will later acquire a
1593 * controlling terminal which will result in "could not set
1594 * controlling tty" errors.
1596 if (!debug_flag && !inetd_flag && setsid() < 0)
1597 error("setsid: %.100s", strerror(errno));
1603 debug("rexec start in %d out %d newsock %d pipe %d sock %d",
1604 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1605 dup2(newsock, STDIN_FILENO);
1606 dup2(STDIN_FILENO, STDOUT_FILENO);
1607 if (startup_pipe == -1)
1608 close(REEXEC_STARTUP_PIPE_FD);
1610 dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
1612 dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1614 if (startup_pipe != -1)
1615 close(startup_pipe);
1617 execv(rexec_argv[0], rexec_argv);
1619 /* Reexec has failed, fall back and continue */
1620 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1621 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1622 log_init(__progname, options.log_level,
1623 options.log_facility, log_stderr);
1626 startup_pipe = REEXEC_STARTUP_PIPE_FD;
1628 close(REEXEC_CONFIG_PASS_FD);
1629 newsock = sock_out = sock_in = dup(STDIN_FILENO);
1630 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1631 dup2(fd, STDIN_FILENO);
1632 dup2(fd, STDOUT_FILENO);
1633 if (fd > STDERR_FILENO)
1636 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
1637 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1641 * Disable the key regeneration alarm. We will not regenerate the
1642 * key since we are no longer in a position to give it to anyone. We
1643 * will not restart on SIGHUP since it no longer makes sense.
1646 signal(SIGALRM, SIG_DFL);
1647 signal(SIGHUP, SIG_DFL);
1648 signal(SIGTERM, SIG_DFL);
1649 signal(SIGQUIT, SIG_DFL);
1650 signal(SIGCHLD, SIG_DFL);
1651 signal(SIGINT, SIG_DFL);
1654 * Register our connection. This turns encryption off because we do
1657 packet_set_connection(sock_in, sock_out);
1658 packet_set_server();
1660 /* Set SO_KEEPALIVE if requested. */
1661 if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
1662 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
1663 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1665 if ((remote_port = get_remote_port()) < 0) {
1666 debug("get_remote_port failed");
1671 * We use get_canonical_hostname with usedns = 0 instead of
1672 * get_remote_ipaddr here so IP options will be checked.
1674 remote_ip = get_canonical_hostname(0);
1676 #ifdef SSH_AUDIT_EVENTS
1677 audit_connection_from(remote_ip, remote_port);
1680 /* Check whether logins are denied from this host. */
1681 if (packet_connection_is_on_socket()) {
1682 struct request_info req;
1684 request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1687 if (!hosts_access(&req)) {
1688 debug("Connection refused by tcp wrapper");
1691 fatal("libwrap refuse returns");
1694 #endif /* LIBWRAP */
1696 /* Log the connection. */
1697 verbose("Connection from %.500s port %d", remote_ip, remote_port);
1700 * We don't want to listen forever unless the other side
1701 * successfully authenticates itself. So we set up an alarm which is
1702 * cleared after successful authentication. A limit of zero
1703 * indicates no limit. Note that we don't set the alarm in debugging
1704 * mode; it is just annoying to have the server exit just when you
1705 * are about to discover the bug.
1707 signal(SIGALRM, grace_alarm_handler);
1709 alarm(options.login_grace_time);
1711 sshd_exchange_identification(sock_in, sock_out);
1713 packet_set_nonblocking();
1715 /* allocate authentication context */
1716 authctxt = xmalloc(sizeof(*authctxt));
1717 memset(authctxt, 0, sizeof(*authctxt));
1719 authctxt->loginmsg = &loginmsg;
1721 /* XXX global for cleanup, access from other modules */
1722 the_authctxt = authctxt;
1724 /* prepare buffer to collect messages to display to user after login */
1725 buffer_init(&loginmsg);
1728 if (privsep_preauth(authctxt) == 1)
1731 /* perform the key exchange */
1732 /* authenticate user and start session */
1735 do_authentication2(authctxt);
1738 do_authentication(authctxt);
1741 * If we use privilege separation, the unprivileged child transfers
1742 * the current keystate and exits
1745 mm_send_keystate(pmonitor);
1751 * Cancel the alarm we set to limit the time taken for
1755 signal(SIGALRM, SIG_DFL);
1756 if (startup_pipe != -1) {
1757 close(startup_pipe);
1761 #ifdef SSH_AUDIT_EVENTS
1762 audit_event(SSH_AUTH_SUCCESS);
1766 * In privilege separation, we fork another child and prepare
1767 * file descriptor passing.
1770 privsep_postauth(authctxt);
1771 /* the monitor process [priv] will not return */
1773 destroy_sensitive_data();
1776 /* Start session. */
1777 do_authenticated(authctxt);
1779 /* The connection has been terminated. */
1780 verbose("Closing connection to %.100s", remote_ip);
1783 if (options.use_pam)
1785 #endif /* USE_PAM */
1787 #ifdef SSH_AUDIT_EVENTS
1788 PRIVSEP(audit_event(SSH_CONNECTION_CLOSE));
1800 * Decrypt session_key_int using our private server key and private host key
1801 * (key with larger modulus first).
1804 ssh1_session_key(BIGNUM *session_key_int)
1808 if (BN_cmp(sensitive_data.server_key->rsa->n,
1809 sensitive_data.ssh1_host_key->rsa->n) > 0) {
1810 /* Server key has bigger modulus. */
1811 if (BN_num_bits(sensitive_data.server_key->rsa->n) <
1812 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1813 SSH_KEY_BITS_RESERVED) {
1814 fatal("do_connection: %s: "
1815 "server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1816 get_remote_ipaddr(),
1817 BN_num_bits(sensitive_data.server_key->rsa->n),
1818 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1819 SSH_KEY_BITS_RESERVED);
1821 if (rsa_private_decrypt(session_key_int, session_key_int,
1822 sensitive_data.server_key->rsa) <= 0)
1824 if (rsa_private_decrypt(session_key_int, session_key_int,
1825 sensitive_data.ssh1_host_key->rsa) <= 0)
1828 /* Host key has bigger modulus (or they are equal). */
1829 if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
1830 BN_num_bits(sensitive_data.server_key->rsa->n) +
1831 SSH_KEY_BITS_RESERVED) {
1832 fatal("do_connection: %s: "
1833 "host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
1834 get_remote_ipaddr(),
1835 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1836 BN_num_bits(sensitive_data.server_key->rsa->n),
1837 SSH_KEY_BITS_RESERVED);
1839 if (rsa_private_decrypt(session_key_int, session_key_int,
1840 sensitive_data.ssh1_host_key->rsa) < 0)
1842 if (rsa_private_decrypt(session_key_int, session_key_int,
1843 sensitive_data.server_key->rsa) < 0)
1856 BIGNUM *session_key_int;
1857 u_char session_key[SSH_SESSION_KEY_LENGTH];
1859 u_int cipher_type, auth_mask, protocol_flags;
1863 * Generate check bytes that the client must send back in the user
1864 * packet in order for it to be accepted; this is used to defy ip
1865 * spoofing attacks. Note that this only works against somebody
1866 * doing IP spoofing from a remote machine; any machine on the local
1867 * network can still see outgoing packets and catch the random
1868 * cookie. This only affects rhosts authentication, and this is one
1869 * of the reasons why it is inherently insecure.
1871 for (i = 0; i < 8; i++) {
1874 cookie[i] = rnd & 0xff;
1879 * Send our public key. We include in the packet 64 bits of random
1880 * data that must be matched in the reply in order to prevent IP
1883 packet_start(SSH_SMSG_PUBLIC_KEY);
1884 for (i = 0; i < 8; i++)
1885 packet_put_char(cookie[i]);
1887 /* Store our public server RSA key. */
1888 packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
1889 packet_put_bignum(sensitive_data.server_key->rsa->e);
1890 packet_put_bignum(sensitive_data.server_key->rsa->n);
1892 /* Store our public host RSA key. */
1893 packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1894 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
1895 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
1897 /* Put protocol flags. */
1898 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
1900 /* Declare which ciphers we support. */
1901 packet_put_int(cipher_mask_ssh1(0));
1903 /* Declare supported authentication types. */
1905 if (options.rhosts_rsa_authentication)
1906 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
1907 if (options.rsa_authentication)
1908 auth_mask |= 1 << SSH_AUTH_RSA;
1909 if (options.challenge_response_authentication == 1)
1910 auth_mask |= 1 << SSH_AUTH_TIS;
1911 if (options.password_authentication)
1912 auth_mask |= 1 << SSH_AUTH_PASSWORD;
1913 packet_put_int(auth_mask);
1915 /* Send the packet and wait for it to be sent. */
1917 packet_write_wait();
1919 debug("Sent %d bit server key and %d bit host key.",
1920 BN_num_bits(sensitive_data.server_key->rsa->n),
1921 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1923 /* Read clients reply (cipher type and session key). */
1924 packet_read_expect(SSH_CMSG_SESSION_KEY);
1926 /* Get cipher type and check whether we accept this. */
1927 cipher_type = packet_get_char();
1929 if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
1930 packet_disconnect("Warning: client selects unsupported cipher.");
1932 /* Get check bytes from the packet. These must match those we
1933 sent earlier with the public key packet. */
1934 for (i = 0; i < 8; i++)
1935 if (cookie[i] != packet_get_char())
1936 packet_disconnect("IP Spoofing check bytes do not match.");
1938 debug("Encryption type: %.200s", cipher_name(cipher_type));
1940 /* Get the encrypted integer. */
1941 if ((session_key_int = BN_new()) == NULL)
1942 fatal("do_ssh1_kex: BN_new failed");
1943 packet_get_bignum(session_key_int);
1945 protocol_flags = packet_get_int();
1946 packet_set_protocol_flags(protocol_flags);
1949 /* Decrypt session_key_int using host/server keys */
1950 rsafail = PRIVSEP(ssh1_session_key(session_key_int));
1953 * Extract session key from the decrypted integer. The key is in the
1954 * least significant 256 bits of the integer; the first byte of the
1955 * key is in the highest bits.
1958 BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1959 len = BN_num_bytes(session_key_int);
1960 if (len < 0 || (u_int)len > sizeof(session_key)) {
1961 error("do_connection: bad session key len from %s: "
1962 "session_key_int %d > sizeof(session_key) %lu",
1963 get_remote_ipaddr(), len, (u_long)sizeof(session_key));
1966 memset(session_key, 0, sizeof(session_key));
1967 BN_bn2bin(session_key_int,
1968 session_key + sizeof(session_key) - len);
1970 derive_ssh1_session_id(
1971 sensitive_data.ssh1_host_key->rsa->n,
1972 sensitive_data.server_key->rsa->n,
1973 cookie, session_id);
1975 * Xor the first 16 bytes of the session key with the
1978 for (i = 0; i < 16; i++)
1979 session_key[i] ^= session_id[i];
1983 int bytes = BN_num_bytes(session_key_int);
1984 u_char *buf = xmalloc(bytes);
1987 logit("do_connection: generating a fake encryption key");
1988 BN_bn2bin(session_key_int, buf);
1990 MD5_Update(&md, buf, bytes);
1991 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1992 MD5_Final(session_key, &md);
1994 MD5_Update(&md, session_key, 16);
1995 MD5_Update(&md, buf, bytes);
1996 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1997 MD5_Final(session_key + 16, &md);
1998 memset(buf, 0, bytes);
2000 for (i = 0; i < 16; i++)
2001 session_id[i] = session_key[i] ^ session_key[i + 16];
2003 /* Destroy the private and public keys. No longer. */
2004 destroy_sensitive_data();
2007 mm_ssh1_session_id(session_id);
2009 /* Destroy the decrypted integer. It is no longer needed. */
2010 BN_clear_free(session_key_int);
2012 /* Set the session key. From this on all communications will be encrypted. */
2013 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
2015 /* Destroy our copy of the session key. It is no longer needed. */
2016 memset(session_key, 0, sizeof(session_key));
2018 debug("Received session key; encryption turned on.");
2020 /* Send an acknowledgment packet. Note that this packet is sent encrypted. */
2021 packet_start(SSH_SMSG_SUCCESS);
2023 packet_write_wait();
2027 * SSH2 key exchange: diffie-hellman-group1-sha1
2034 if (options.ciphers != NULL) {
2035 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2036 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
2038 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2039 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
2040 myproposal[PROPOSAL_ENC_ALGS_STOC] =
2041 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
2043 if (options.macs != NULL) {
2044 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2045 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2047 if (options.compression == COMP_NONE) {
2048 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2049 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2050 } else if (options.compression == COMP_DELAYED) {
2051 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2052 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com";
2055 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
2057 /* start key exchange */
2058 kex = kex_setup(myproposal);
2059 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2060 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
2061 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2062 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2064 kex->client_version_string=client_version_string;
2065 kex->server_version_string=server_version_string;
2066 kex->load_host_key=&get_hostkey_by_type;
2067 kex->host_key_index=&get_hostkey_index;
2071 dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
2073 session_id2 = kex->session_id;
2074 session_id2_len = kex->session_id_len;
2077 /* send 1st encrypted/maced/compressed message */
2078 packet_start(SSH2_MSG_IGNORE);
2079 packet_put_cstring("markus");
2081 packet_write_wait();
2086 /* server specific fatal cleanup */
2091 do_cleanup(the_authctxt);
2092 #ifdef SSH_AUDIT_EVENTS
2093 /* done after do_cleanup so it can cancel the PAM auth 'thread' */
2094 if (!use_privsep || mm_is_monitor())
2095 audit_event(SSH_CONNECTION_ABANDON);