1 /* $OpenBSD: sshd.c,v 1.331 2006/06/01 09:21:48 markus 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>
59 #include <openssl/dh.h>
60 #include <openssl/bn.h>
61 #include <openssl/md5.h>
62 #include <openssl/rand.h>
63 #ifdef HAVE_SECUREWARE
64 #include <sys/security.h>
85 #include "myproposal.h"
87 #include "pathnames.h"
96 #include "monitor_mm.h"
98 #include "monitor_wrap.h"
99 #include "monitor_fdpass.h"
104 int allow_severity = LOG_INFO;
105 int deny_severity = LOG_WARNING;
113 #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
114 #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
115 #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
116 #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
118 extern char *__progname;
120 /* Server configuration options. */
121 ServerOptions options;
123 /* Name of the server configuration file. */
124 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
127 * Debug mode flag. This can be set on the command line. If debug
128 * mode is enabled, extra debugging output will be sent to the system
129 * log, the daemon will not go to background, and will exit after processing
130 * the first connection.
134 /* Flag indicating that the daemon should only test the configuration and keys. */
137 /* Flag indicating that the daemon is being started from inetd. */
140 /* Flag indicating that sshd should not detach and become a daemon. */
141 int no_daemon_flag = 0;
143 /* debug goes to stderr unless inetd_flag is set */
146 /* Saved arguments to main(). */
151 int rexeced_flag = 0;
157 * The sockets that the server is listening; this is used in the SIGHUP
160 #define MAX_LISTEN_SOCKS 16
161 int listen_socks[MAX_LISTEN_SOCKS];
162 int num_listen_socks = 0;
165 * the client's version string, passed by sshd2 in compat mode. if != NULL,
166 * sshd will skip the version-number exchange
168 char *client_version_string = NULL;
169 char *server_version_string = NULL;
171 /* for rekeying XXX fixme */
175 * Any really sensitive data in the application is contained in this
176 * structure. The idea is that this structure could be locked into memory so
177 * that the pages do not get written into swap. However, there are some
178 * problems. The private key contains BIGNUMs, and we do not (in principle)
179 * have access to the internals of them, and locking just the structure is
180 * not very useful. Currently, memory locking is not implemented.
183 Key *server_key; /* ephemeral server key */
184 Key *ssh1_host_key; /* ssh1 host key */
185 Key **host_keys; /* all private host keys */
188 u_char ssh1_cookie[SSH_SESSION_KEY_LENGTH];
192 * Flag indicating whether the RSA server key needs to be regenerated.
193 * Is set in the SIGALRM handler and cleared when the key is regenerated.
195 static volatile sig_atomic_t key_do_regen = 0;
197 /* This is set to true when a signal is received. */
198 static volatile sig_atomic_t received_sighup = 0;
199 static volatile sig_atomic_t received_sigterm = 0;
201 /* session identifier, used by RSA-auth */
202 u_char session_id[16];
205 u_char *session_id2 = NULL;
206 u_int session_id2_len = 0;
208 /* record remote hostname or ip */
209 u_int utmp_len = MAXHOSTNAMELEN;
211 /* options.max_startup sized array of fd ints */
212 int *startup_pipes = NULL;
213 int startup_pipe; /* in child */
215 /* variables used for privilege separation */
217 struct monitor *pmonitor = NULL;
219 /* global authentication context */
220 Authctxt *the_authctxt = NULL;
222 /* message to be displayed after login */
225 /* Prototypes for various functions defined later in this file. */
226 void destroy_sensitive_data(void);
227 void demote_sensitive_data(void);
229 static void do_ssh1_kex(void);
230 static void do_ssh2_kex(void);
233 * Close all listening sockets
236 close_listen_socks(void)
240 for (i = 0; i < num_listen_socks; i++)
241 close(listen_socks[i]);
242 num_listen_socks = -1;
246 close_startup_pipes(void)
251 for (i = 0; i < options.max_startups; i++)
252 if (startup_pipes[i] != -1)
253 close(startup_pipes[i]);
257 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
258 * the effect is to reread the configuration file (and to regenerate
264 sighup_handler(int sig)
266 int save_errno = errno;
269 signal(SIGHUP, sighup_handler);
274 * Called from the main program after receiving SIGHUP.
275 * Restarts the server.
280 logit("Received SIGHUP; restarting.");
281 close_listen_socks();
282 close_startup_pipes();
283 execv(saved_argv[0], saved_argv);
284 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
290 * Generic signal handler for terminating signals in the master daemon.
294 sigterm_handler(int sig)
296 received_sigterm = sig;
300 * SIGCHLD handler. This is called whenever a child dies. This will then
301 * reap any zombies left by exited children.
305 main_sigchld_handler(int sig)
307 int save_errno = errno;
311 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
312 (pid < 0 && errno == EINTR))
315 signal(SIGCHLD, main_sigchld_handler);
320 * Signal handler for the alarm after the login grace period has expired.
324 grace_alarm_handler(int sig)
326 /* XXX no idea how fix this signal handler */
328 if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
329 kill(pmonitor->m_pid, SIGALRM);
331 /* Log error and exit. */
332 fatal("Timeout before authentication for %s", get_remote_ipaddr());
336 * Signal handler for the key regeneration alarm. Note that this
337 * alarm only occurs in the daemon waiting for connections, and it does not
338 * do anything with the private key or random state before forking.
339 * Thus there should be no concurrency control/asynchronous execution
343 generate_ephemeral_server_key(void)
348 verbose("Generating %s%d bit RSA key.",
349 sensitive_data.server_key ? "new " : "", options.server_key_bits);
350 if (sensitive_data.server_key != NULL)
351 key_free(sensitive_data.server_key);
352 sensitive_data.server_key = key_generate(KEY_RSA1,
353 options.server_key_bits);
354 verbose("RSA key generation complete.");
356 for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
359 sensitive_data.ssh1_cookie[i] = rnd & 0xff;
367 key_regeneration_alarm(int sig)
369 int save_errno = errno;
371 signal(SIGALRM, SIG_DFL);
377 sshd_exchange_identification(int sock_in, int sock_out)
381 int remote_major, remote_minor;
384 char buf[256]; /* Must not be larger than remote_version. */
385 char remote_version[256]; /* Must be at least as big as buf. */
387 if ((options.protocol & SSH_PROTO_1) &&
388 (options.protocol & SSH_PROTO_2)) {
389 major = PROTOCOL_MAJOR_1;
391 } else if (options.protocol & SSH_PROTO_2) {
392 major = PROTOCOL_MAJOR_2;
393 minor = PROTOCOL_MINOR_2;
395 major = PROTOCOL_MAJOR_1;
396 minor = PROTOCOL_MINOR_1;
398 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", major, minor, SSH_VERSION);
399 server_version_string = xstrdup(buf);
401 /* Send our protocol version identification. */
402 if (atomicio(vwrite, sock_out, server_version_string,
403 strlen(server_version_string))
404 != strlen(server_version_string)) {
405 logit("Could not write ident string to %s", get_remote_ipaddr());
409 /* Read other sides version identification. */
410 memset(buf, 0, sizeof(buf));
411 for (i = 0; i < sizeof(buf) - 1; i++) {
412 if (atomicio(read, sock_in, &buf[i], 1) != 1) {
413 logit("Did not receive identification string from %s",
414 get_remote_ipaddr());
417 if (buf[i] == '\r') {
419 /* Kludge for F-Secure Macintosh < 1.0.2 */
421 strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
425 if (buf[i] == '\n') {
430 buf[sizeof(buf) - 1] = 0;
431 client_version_string = xstrdup(buf);
434 * Check that the versions match. In future this might accept
435 * several versions and set appropriate flags to handle them.
437 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
438 &remote_major, &remote_minor, remote_version) != 3) {
439 s = "Protocol mismatch.\n";
440 (void) atomicio(vwrite, sock_out, s, strlen(s));
443 logit("Bad protocol version identification '%.100s' from %s",
444 client_version_string, get_remote_ipaddr());
447 debug("Client protocol version %d.%d; client software version %.100s",
448 remote_major, remote_minor, remote_version);
450 compat_datafellows(remote_version);
452 if (datafellows & SSH_BUG_PROBE) {
453 logit("probed from %s with %s. Don't panic.",
454 get_remote_ipaddr(), client_version_string);
458 if (datafellows & SSH_BUG_SCANNER) {
459 logit("scanned from %s with %s. Don't panic.",
460 get_remote_ipaddr(), client_version_string);
465 switch (remote_major) {
467 if (remote_minor == 99) {
468 if (options.protocol & SSH_PROTO_2)
474 if (!(options.protocol & SSH_PROTO_1)) {
478 if (remote_minor < 3) {
479 packet_disconnect("Your ssh version is too old and "
480 "is no longer supported. Please install a newer version.");
481 } else if (remote_minor == 3) {
482 /* note that this disables agent-forwarding */
487 if (options.protocol & SSH_PROTO_2) {
496 chop(server_version_string);
497 debug("Local version string %.200s", server_version_string);
500 s = "Protocol major versions differ.\n";
501 (void) atomicio(vwrite, sock_out, s, strlen(s));
504 logit("Protocol major versions differ for %s: %.200s vs. %.200s",
506 server_version_string, client_version_string);
511 /* Destroy the host and server keys. They will no longer be needed. */
513 destroy_sensitive_data(void)
517 if (sensitive_data.server_key) {
518 key_free(sensitive_data.server_key);
519 sensitive_data.server_key = NULL;
521 for (i = 0; i < options.num_host_key_files; i++) {
522 if (sensitive_data.host_keys[i]) {
523 key_free(sensitive_data.host_keys[i]);
524 sensitive_data.host_keys[i] = NULL;
527 sensitive_data.ssh1_host_key = NULL;
528 memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
531 /* Demote private to public keys for network child */
533 demote_sensitive_data(void)
538 if (sensitive_data.server_key) {
539 tmp = key_demote(sensitive_data.server_key);
540 key_free(sensitive_data.server_key);
541 sensitive_data.server_key = tmp;
544 for (i = 0; i < options.num_host_key_files; i++) {
545 if (sensitive_data.host_keys[i]) {
546 tmp = key_demote(sensitive_data.host_keys[i]);
547 key_free(sensitive_data.host_keys[i]);
548 sensitive_data.host_keys[i] = tmp;
549 if (tmp->type == KEY_RSA1)
550 sensitive_data.ssh1_host_key = tmp;
554 /* We do not clear ssh1_host key and cookie. XXX - Okay Niels? */
558 privsep_preauth_child(void)
565 /* Enable challenge-response authentication for privilege separation */
566 privsep_challenge_enable();
568 for (i = 0; i < 256; i++)
569 rnd[i] = arc4random();
570 RAND_seed(rnd, sizeof(rnd));
572 /* Demote the private keys to public keys. */
573 demote_sensitive_data();
575 if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL)
576 fatal("Privilege separation user %s does not exist",
578 memset(pw->pw_passwd, 0, strlen(pw->pw_passwd));
581 /* Change our root directory */
582 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
583 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
585 if (chdir("/") == -1)
586 fatal("chdir(\"/\"): %s", strerror(errno));
588 /* Drop our privileges */
589 debug3("privsep user:group %u:%u", (u_int)pw->pw_uid,
592 /* XXX not ready, too heavy after chroot */
593 do_setusercontext(pw);
595 gidset[0] = pw->pw_gid;
596 if (setgroups(1, gidset) < 0)
597 fatal("setgroups: %.100s", strerror(errno));
598 permanently_set_uid(pw);
603 privsep_preauth(Authctxt *authctxt)
608 /* Set up unprivileged child process to deal with network data */
609 pmonitor = monitor_init();
610 /* Store a pointer to the kex for later rekeying */
611 pmonitor->m_pkex = &xxx_kex;
615 fatal("fork of unprivileged child failed");
616 } else if (pid != 0) {
617 debug2("Network child is on pid %ld", (long)pid);
619 close(pmonitor->m_recvfd);
620 pmonitor->m_pid = pid;
621 monitor_child_preauth(authctxt, pmonitor);
622 close(pmonitor->m_sendfd);
625 monitor_sync(pmonitor);
627 /* Wait for the child's exit status */
628 while (waitpid(pid, &status, 0) < 0)
635 close(pmonitor->m_sendfd);
637 /* Demote the child */
638 if (getuid() == 0 || geteuid() == 0)
639 privsep_preauth_child();
640 setproctitle("%s", "[net]");
646 privsep_postauth(Authctxt *authctxt)
648 #ifdef DISABLE_FD_PASSING
651 if (authctxt->pw->pw_uid == 0 || options.use_login) {
653 /* File descriptor passing is broken or root login */
658 /* New socket pair */
659 monitor_reinit(pmonitor);
661 pmonitor->m_pid = fork();
662 if (pmonitor->m_pid == -1)
663 fatal("fork of unprivileged child failed");
664 else if (pmonitor->m_pid != 0) {
665 debug2("User child is on pid %ld", (long)pmonitor->m_pid);
666 close(pmonitor->m_recvfd);
667 buffer_clear(&loginmsg);
668 monitor_child_postauth(pmonitor);
674 close(pmonitor->m_sendfd);
676 /* Demote the private keys to public keys. */
677 demote_sensitive_data();
679 /* Drop privileges */
680 do_setusercontext(authctxt->pw);
683 /* It is safe now to apply the key state */
684 monitor_apply_keystate(pmonitor);
687 * Tell the packet layer that authentication was successful, since
688 * this information is not part of the key state.
690 packet_set_authenticated();
694 list_hostkey_types(void)
702 for (i = 0; i < options.num_host_key_files; i++) {
703 Key *key = sensitive_data.host_keys[i];
709 if (buffer_len(&b) > 0)
710 buffer_append(&b, ",", 1);
711 p = key_ssh_name(key);
712 buffer_append(&b, p, strlen(p));
716 buffer_append(&b, "\0", 1);
717 ret = xstrdup(buffer_ptr(&b));
719 debug("list_hostkey_types: %s", ret);
724 get_hostkey_by_type(int type)
728 for (i = 0; i < options.num_host_key_files; i++) {
729 Key *key = sensitive_data.host_keys[i];
730 if (key != NULL && key->type == type)
737 get_hostkey_by_index(int ind)
739 if (ind < 0 || ind >= options.num_host_key_files)
741 return (sensitive_data.host_keys[ind]);
745 get_hostkey_index(Key *key)
749 for (i = 0; i < options.num_host_key_files; i++) {
750 if (key == sensitive_data.host_keys[i])
757 * returns 1 if connection should be dropped, 0 otherwise.
758 * dropping starts at connection #max_startups_begin with a probability
759 * of (max_startups_rate/100). the probability increases linearly until
760 * all connections are dropped for startups > max_startups
763 drop_connection(int startups)
767 if (startups < options.max_startups_begin)
769 if (startups >= options.max_startups)
771 if (options.max_startups_rate == 100)
774 p = 100 - options.max_startups_rate;
775 p *= startups - options.max_startups_begin;
776 p /= options.max_startups - options.max_startups_begin;
777 p += options.max_startups_rate;
778 r = arc4random() % 100;
780 debug("drop_connection: p %d, r %d", p, r);
781 return (r < p) ? 1 : 0;
787 fprintf(stderr, "%s, %s\n",
788 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
790 "usage: sshd [-46Ddeiqt] [-b bits] [-f config_file] [-g login_grace_time]\n"
791 " [-h host_key_file] [-k key_gen_time] [-o option] [-p port] [-u len]\n"
797 send_rexec_state(int fd, Buffer *conf)
801 debug3("%s: entering fd = %d config len %d", __func__, fd,
805 * Protocol from reexec master to child:
806 * string configuration
807 * u_int ephemeral_key_follows
808 * bignum e (only if ephemeral_key_follows == 1)
814 * string rngseed (only if OpenSSL is not self-seeded)
817 buffer_put_cstring(&m, buffer_ptr(conf));
819 if (sensitive_data.server_key != NULL &&
820 sensitive_data.server_key->type == KEY_RSA1) {
821 buffer_put_int(&m, 1);
822 buffer_put_bignum(&m, sensitive_data.server_key->rsa->e);
823 buffer_put_bignum(&m, sensitive_data.server_key->rsa->n);
824 buffer_put_bignum(&m, sensitive_data.server_key->rsa->d);
825 buffer_put_bignum(&m, sensitive_data.server_key->rsa->iqmp);
826 buffer_put_bignum(&m, sensitive_data.server_key->rsa->p);
827 buffer_put_bignum(&m, sensitive_data.server_key->rsa->q);
829 buffer_put_int(&m, 0);
831 #ifndef OPENSSL_PRNG_ONLY
832 rexec_send_rng_seed(&m);
835 if (ssh_msg_send(fd, 0, &m) == -1)
836 fatal("%s: ssh_msg_send failed", __func__);
840 debug3("%s: done", __func__);
844 recv_rexec_state(int fd, Buffer *conf)
850 debug3("%s: entering fd = %d", __func__, fd);
854 if (ssh_msg_recv(fd, &m) == -1)
855 fatal("%s: ssh_msg_recv failed", __func__);
856 if (buffer_get_char(&m) != 0)
857 fatal("%s: rexec version mismatch", __func__);
859 cp = buffer_get_string(&m, &len);
861 buffer_append(conf, cp, len + 1);
864 if (buffer_get_int(&m)) {
865 if (sensitive_data.server_key != NULL)
866 key_free(sensitive_data.server_key);
867 sensitive_data.server_key = key_new_private(KEY_RSA1);
868 buffer_get_bignum(&m, sensitive_data.server_key->rsa->e);
869 buffer_get_bignum(&m, sensitive_data.server_key->rsa->n);
870 buffer_get_bignum(&m, sensitive_data.server_key->rsa->d);
871 buffer_get_bignum(&m, sensitive_data.server_key->rsa->iqmp);
872 buffer_get_bignum(&m, sensitive_data.server_key->rsa->p);
873 buffer_get_bignum(&m, sensitive_data.server_key->rsa->q);
874 rsa_generate_additional_parameters(
875 sensitive_data.server_key->rsa);
878 #ifndef OPENSSL_PRNG_ONLY
879 rexec_recv_rng_seed(&m);
884 debug3("%s: done", __func__);
888 * Main program for the daemon.
891 main(int ac, char **av)
895 int opt, j, i, on = 1;
896 int sock_in = -1, sock_out = -1, newsock = -1;
900 struct sockaddr_storage from;
901 const char *remote_ip;
905 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
907 int listen_sock, maxfd;
908 int startup_p[2] = { -1 , -1 }, config_s[2] = { -1 , -1 };
912 int ret, key_used = 0;
915 #ifdef HAVE_SECUREWARE
916 (void)set_auth_parameters(ac, av);
918 __progname = ssh_get_progname(av[0]);
921 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
924 saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
925 for (i = 0; i < ac; i++)
926 saved_argv[i] = xstrdup(av[i]);
927 saved_argv[i] = NULL;
929 #ifndef HAVE_SETPROCTITLE
930 /* Prepare for later setproctitle emulation */
931 compat_init_setproctitle(ac, av);
935 if (geteuid() == 0 && setgroups(0, NULL) == -1)
936 debug("setgroups(): %.200s", strerror(errno));
938 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
941 /* Initialize configuration options to their default values. */
942 initialize_server_options(&options);
944 /* Parse command-line arguments. */
945 while ((opt = getopt(ac, av, "f:p:b:k:h:g:u:o:dDeiqrtQR46")) != -1) {
948 options.address_family = AF_INET;
951 options.address_family = AF_INET6;
954 config_file_name = optarg;
957 if (debug_flag == 0) {
959 options.log_level = SYSLOG_LEVEL_DEBUG1;
960 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
983 options.log_level = SYSLOG_LEVEL_QUIET;
986 options.server_key_bits = (int)strtonum(optarg, 256,
990 options.ports_from_cmdline = 1;
991 if (options.num_ports >= MAX_PORTS) {
992 fprintf(stderr, "too many ports.\n");
995 options.ports[options.num_ports++] = a2port(optarg);
996 if (options.ports[options.num_ports-1] == 0) {
997 fprintf(stderr, "Bad port number.\n");
1002 if ((options.login_grace_time = convtime(optarg)) == -1) {
1003 fprintf(stderr, "Invalid login grace time.\n");
1008 if ((options.key_regeneration_time = convtime(optarg)) == -1) {
1009 fprintf(stderr, "Invalid key regeneration interval.\n");
1014 if (options.num_host_key_files >= MAX_HOSTKEYS) {
1015 fprintf(stderr, "too many host keys.\n");
1018 options.host_key_files[options.num_host_key_files++] = optarg;
1024 utmp_len = (u_int)strtonum(optarg, 0, MAXHOSTNAMELEN+1, NULL);
1025 if (utmp_len > MAXHOSTNAMELEN) {
1026 fprintf(stderr, "Invalid utmp length.\n");
1031 line = xstrdup(optarg);
1032 if (process_server_config_line(&options, line,
1033 "command-line", 0) != 0)
1043 if (rexeced_flag || inetd_flag)
1045 if (rexec_flag && (av[0] == NULL || *av[0] != '/'))
1046 fatal("sshd re-exec requires execution with an absolute path");
1048 closefrom(REEXEC_MIN_FREE_FD);
1050 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1052 SSLeay_add_all_algorithms();
1055 * Force logging to stderr until we have loaded the private host
1056 * key (unless started from inetd)
1058 log_init(__progname,
1059 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1060 SYSLOG_LEVEL_INFO : options.log_level,
1061 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1062 SYSLOG_FACILITY_AUTH : options.log_facility,
1063 log_stderr || !inetd_flag);
1066 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1067 * root's environment
1069 if (getenv("KRB5CCNAME") != NULL)
1070 unsetenv("KRB5CCNAME");
1073 /* Cray can define user privs drop all privs now!
1074 * Not needed on PRIV_SU systems!
1079 sensitive_data.server_key = NULL;
1080 sensitive_data.ssh1_host_key = NULL;
1081 sensitive_data.have_ssh1_key = 0;
1082 sensitive_data.have_ssh2_key = 0;
1084 /* Fetch our configuration */
1087 recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1089 load_server_config(config_file_name, &cfg);
1091 parse_server_config(&options,
1092 rexeced_flag ? "rexec" : config_file_name, &cfg);
1099 /* Fill in default values for those options not explicitly set. */
1100 fill_default_server_options(&options);
1102 /* set default channel AF */
1103 channel_set_af(options.address_family);
1105 /* Check that there are no remaining arguments. */
1107 fprintf(stderr, "Extra argument %s.\n", av[optind]);
1111 debug("sshd version %.100s", SSH_RELEASE);
1113 /* load private host keys */
1114 sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1116 for (i = 0; i < options.num_host_key_files; i++)
1117 sensitive_data.host_keys[i] = NULL;
1119 for (i = 0; i < options.num_host_key_files; i++) {
1120 key = key_load_private(options.host_key_files[i], "", NULL);
1121 sensitive_data.host_keys[i] = key;
1123 error("Could not load host key: %s",
1124 options.host_key_files[i]);
1125 sensitive_data.host_keys[i] = NULL;
1128 switch (key->type) {
1130 sensitive_data.ssh1_host_key = key;
1131 sensitive_data.have_ssh1_key = 1;
1135 sensitive_data.have_ssh2_key = 1;
1138 debug("private host key: #%d type %d %s", i, key->type,
1141 if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1142 logit("Disabling protocol version 1. Could not load host key");
1143 options.protocol &= ~SSH_PROTO_1;
1145 if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1146 logit("Disabling protocol version 2. Could not load host key");
1147 options.protocol &= ~SSH_PROTO_2;
1149 if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1150 logit("sshd: no hostkeys available -- exiting.");
1154 /* Check certain values for sanity. */
1155 if (options.protocol & SSH_PROTO_1) {
1156 if (options.server_key_bits < 512 ||
1157 options.server_key_bits > 32768) {
1158 fprintf(stderr, "Bad server key size.\n");
1162 * Check that server and host key lengths differ sufficiently. This
1163 * is necessary to make double encryption work with rsaref. Oh, I
1164 * hate software patents. I dont know if this can go? Niels
1166 if (options.server_key_bits >
1167 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
1168 SSH_KEY_BITS_RESERVED && options.server_key_bits <
1169 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1170 SSH_KEY_BITS_RESERVED) {
1171 options.server_key_bits =
1172 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1173 SSH_KEY_BITS_RESERVED;
1174 debug("Forcing server key to %d bits to make it differ from host key.",
1175 options.server_key_bits);
1182 if (getpwnam(SSH_PRIVSEP_USER) == NULL)
1183 fatal("Privilege separation user %s does not exist",
1185 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1186 (S_ISDIR(st.st_mode) == 0))
1187 fatal("Missing privilege separation directory: %s",
1188 _PATH_PRIVSEP_CHROOT_DIR);
1191 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1192 (st.st_uid != getuid () ||
1193 (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1195 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1197 fatal("%s must be owned by root and not group or "
1198 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1201 /* Configuration looks good, so exit if in test mode. */
1206 * Clear out any supplemental groups we may have inherited. This
1207 * prevents inadvertent creation of files with bad modes (in the
1208 * portable version at least, it's certainly possible for PAM
1209 * to create a file, and we can't control the code in every
1210 * module which might be used).
1212 if (setgroups(0, NULL) < 0)
1213 debug("setgroups() failed: %.200s", strerror(errno));
1216 rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1217 for (i = 0; i < rexec_argc; i++) {
1218 debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1219 rexec_argv[i] = saved_argv[i];
1221 rexec_argv[rexec_argc] = "-R";
1222 rexec_argv[rexec_argc + 1] = NULL;
1225 /* Initialize the log (it is reinitialized below in case we forked). */
1226 if (debug_flag && (!inetd_flag || rexeced_flag))
1228 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1231 * If not in debugging mode, and not started from inetd, disconnect
1232 * from the controlling terminal, and fork. The original process
1235 if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1238 #endif /* TIOCNOTTY */
1239 if (daemon(0, 0) < 0)
1240 fatal("daemon() failed: %.200s", strerror(errno));
1242 /* Disconnect from the controlling tty. */
1244 fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1246 (void) ioctl(fd, TIOCNOTTY, NULL);
1249 #endif /* TIOCNOTTY */
1251 /* Reinitialize the log (because of the fork above). */
1252 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1254 /* Initialize the random number generator. */
1257 /* Chdir to the root directory so that the current disk can be
1258 unmounted if desired. */
1261 /* ignore SIGPIPE */
1262 signal(SIGPIPE, SIG_IGN);
1264 /* Start listening for a socket, unless started from inetd. */
1270 close(REEXEC_CONFIG_PASS_FD);
1271 sock_in = sock_out = dup(STDIN_FILENO);
1273 startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
1274 close(REEXEC_STARTUP_PIPE_FD);
1277 sock_in = dup(STDIN_FILENO);
1278 sock_out = dup(STDOUT_FILENO);
1281 * We intentionally do not close the descriptors 0, 1, and 2
1282 * as our code for setting the descriptors won't work if
1283 * ttyfd happens to be one of those.
1285 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1286 dup2(fd, STDIN_FILENO);
1287 dup2(fd, STDOUT_FILENO);
1288 if (fd > STDOUT_FILENO)
1291 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
1292 if ((options.protocol & SSH_PROTO_1) &&
1293 sensitive_data.server_key == NULL)
1294 generate_ephemeral_server_key();
1296 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
1297 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1299 if (num_listen_socks >= MAX_LISTEN_SOCKS)
1300 fatal("Too many listen sockets. "
1301 "Enlarge MAX_LISTEN_SOCKS");
1302 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1303 ntop, sizeof(ntop), strport, sizeof(strport),
1304 NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1305 error("getnameinfo failed: %.100s",
1306 (ret != EAI_SYSTEM) ? gai_strerror(ret) :
1310 /* Create socket for listening. */
1311 listen_sock = socket(ai->ai_family, ai->ai_socktype,
1313 if (listen_sock < 0) {
1314 /* kernel may not support ipv6 */
1315 verbose("socket: %.100s", strerror(errno));
1318 if (set_nonblock(listen_sock) == -1) {
1323 * Set socket options.
1324 * Allow local port reuse in TIME_WAIT.
1326 if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
1327 &on, sizeof(on)) == -1)
1328 error("setsockopt SO_REUSEADDR: %s", strerror(errno));
1330 debug("Bind to port %s on %s.", strport, ntop);
1332 /* Bind the socket to the desired port. */
1333 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1335 error("Bind to port %s on %s failed: %.200s.",
1336 strport, ntop, strerror(errno));
1340 listen_socks[num_listen_socks] = listen_sock;
1343 /* Start listening on the port. */
1344 if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1345 fatal("listen on [%s]:%s: %.100s",
1346 ntop, strport, strerror(errno));
1347 logit("Server listening on %s port %s.", ntop, strport);
1349 freeaddrinfo(options.listen_addrs);
1351 if (!num_listen_socks)
1352 fatal("Cannot bind any address.");
1354 if (options.protocol & SSH_PROTO_1)
1355 generate_ephemeral_server_key();
1358 * Arrange to restart on SIGHUP. The handler needs
1361 signal(SIGHUP, sighup_handler);
1363 signal(SIGTERM, sigterm_handler);
1364 signal(SIGQUIT, sigterm_handler);
1366 /* Arrange SIGCHLD to be caught. */
1367 signal(SIGCHLD, main_sigchld_handler);
1369 /* Write out the pid file after the sigterm handler is setup */
1372 * Record our pid in /var/run/sshd.pid to make it
1373 * easier to kill the correct sshd. We don't want to
1374 * do this before the bind above because the bind will
1375 * fail if there already is a daemon, and this will
1376 * overwrite any old pid in the file.
1378 f = fopen(options.pid_file, "wb");
1380 error("Couldn't create pid file \"%s\": %s",
1381 options.pid_file, strerror(errno));
1383 fprintf(f, "%ld\n", (long) getpid());
1388 /* setup fd set for listen */
1391 for (i = 0; i < num_listen_socks; i++)
1392 if (listen_socks[i] > maxfd)
1393 maxfd = listen_socks[i];
1394 /* pipes connected to unauthenticated childs */
1395 startup_pipes = xcalloc(options.max_startups, sizeof(int));
1396 for (i = 0; i < options.max_startups; i++)
1397 startup_pipes[i] = -1;
1400 * Stay listening for connections until the system crashes or
1401 * the daemon is killed with a signal.
1404 if (received_sighup)
1408 fdset = (fd_set *)xcalloc(howmany(maxfd + 1, NFDBITS),
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 (void) get_canonical_hostname(0);
1676 * The rest of the code depends on the fact that
1677 * get_remote_ipaddr() caches the remote ip, even if
1678 * the socket goes away.
1680 remote_ip = get_remote_ipaddr();
1682 #ifdef SSH_AUDIT_EVENTS
1683 audit_connection_from(remote_ip, remote_port);
1686 /* Check whether logins are denied from this host. */
1687 if (packet_connection_is_on_socket()) {
1688 struct request_info req;
1690 request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1693 if (!hosts_access(&req)) {
1694 debug("Connection refused by tcp wrapper");
1697 fatal("libwrap refuse returns");
1700 #endif /* LIBWRAP */
1702 /* Log the connection. */
1703 verbose("Connection from %.500s port %d", remote_ip, remote_port);
1706 * We don't want to listen forever unless the other side
1707 * successfully authenticates itself. So we set up an alarm which is
1708 * cleared after successful authentication. A limit of zero
1709 * indicates no limit. Note that we don't set the alarm in debugging
1710 * mode; it is just annoying to have the server exit just when you
1711 * are about to discover the bug.
1713 signal(SIGALRM, grace_alarm_handler);
1715 alarm(options.login_grace_time);
1717 sshd_exchange_identification(sock_in, sock_out);
1719 packet_set_nonblocking();
1721 /* allocate authentication context */
1722 authctxt = xcalloc(1, sizeof(*authctxt));
1724 authctxt->loginmsg = &loginmsg;
1726 /* XXX global for cleanup, access from other modules */
1727 the_authctxt = authctxt;
1729 /* prepare buffer to collect messages to display to user after login */
1730 buffer_init(&loginmsg);
1733 if (privsep_preauth(authctxt) == 1)
1736 /* perform the key exchange */
1737 /* authenticate user and start session */
1740 do_authentication2(authctxt);
1743 do_authentication(authctxt);
1746 * If we use privilege separation, the unprivileged child transfers
1747 * the current keystate and exits
1750 mm_send_keystate(pmonitor);
1756 * Cancel the alarm we set to limit the time taken for
1760 signal(SIGALRM, SIG_DFL);
1761 if (startup_pipe != -1) {
1762 close(startup_pipe);
1766 #ifdef SSH_AUDIT_EVENTS
1767 audit_event(SSH_AUTH_SUCCESS);
1771 * In privilege separation, we fork another child and prepare
1772 * file descriptor passing.
1775 privsep_postauth(authctxt);
1776 /* the monitor process [priv] will not return */
1778 destroy_sensitive_data();
1781 /* Start session. */
1782 do_authenticated(authctxt);
1784 /* The connection has been terminated. */
1785 verbose("Closing connection to %.100s", remote_ip);
1788 if (options.use_pam)
1790 #endif /* USE_PAM */
1792 #ifdef SSH_AUDIT_EVENTS
1793 PRIVSEP(audit_event(SSH_CONNECTION_CLOSE));
1805 * Decrypt session_key_int using our private server key and private host key
1806 * (key with larger modulus first).
1809 ssh1_session_key(BIGNUM *session_key_int)
1813 if (BN_cmp(sensitive_data.server_key->rsa->n,
1814 sensitive_data.ssh1_host_key->rsa->n) > 0) {
1815 /* Server key has bigger modulus. */
1816 if (BN_num_bits(sensitive_data.server_key->rsa->n) <
1817 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1818 SSH_KEY_BITS_RESERVED) {
1819 fatal("do_connection: %s: "
1820 "server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1821 get_remote_ipaddr(),
1822 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);
1826 if (rsa_private_decrypt(session_key_int, session_key_int,
1827 sensitive_data.server_key->rsa) <= 0)
1829 if (rsa_private_decrypt(session_key_int, session_key_int,
1830 sensitive_data.ssh1_host_key->rsa) <= 0)
1833 /* Host key has bigger modulus (or they are equal). */
1834 if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
1835 BN_num_bits(sensitive_data.server_key->rsa->n) +
1836 SSH_KEY_BITS_RESERVED) {
1837 fatal("do_connection: %s: "
1838 "host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
1839 get_remote_ipaddr(),
1840 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);
1844 if (rsa_private_decrypt(session_key_int, session_key_int,
1845 sensitive_data.ssh1_host_key->rsa) < 0)
1847 if (rsa_private_decrypt(session_key_int, session_key_int,
1848 sensitive_data.server_key->rsa) < 0)
1861 BIGNUM *session_key_int;
1862 u_char session_key[SSH_SESSION_KEY_LENGTH];
1864 u_int cipher_type, auth_mask, protocol_flags;
1868 * Generate check bytes that the client must send back in the user
1869 * packet in order for it to be accepted; this is used to defy ip
1870 * spoofing attacks. Note that this only works against somebody
1871 * doing IP spoofing from a remote machine; any machine on the local
1872 * network can still see outgoing packets and catch the random
1873 * cookie. This only affects rhosts authentication, and this is one
1874 * of the reasons why it is inherently insecure.
1876 for (i = 0; i < 8; i++) {
1879 cookie[i] = rnd & 0xff;
1884 * Send our public key. We include in the packet 64 bits of random
1885 * data that must be matched in the reply in order to prevent IP
1888 packet_start(SSH_SMSG_PUBLIC_KEY);
1889 for (i = 0; i < 8; i++)
1890 packet_put_char(cookie[i]);
1892 /* Store our public server RSA key. */
1893 packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
1894 packet_put_bignum(sensitive_data.server_key->rsa->e);
1895 packet_put_bignum(sensitive_data.server_key->rsa->n);
1897 /* Store our public host RSA key. */
1898 packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1899 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
1900 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
1902 /* Put protocol flags. */
1903 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
1905 /* Declare which ciphers we support. */
1906 packet_put_int(cipher_mask_ssh1(0));
1908 /* Declare supported authentication types. */
1910 if (options.rhosts_rsa_authentication)
1911 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
1912 if (options.rsa_authentication)
1913 auth_mask |= 1 << SSH_AUTH_RSA;
1914 if (options.challenge_response_authentication == 1)
1915 auth_mask |= 1 << SSH_AUTH_TIS;
1916 if (options.password_authentication)
1917 auth_mask |= 1 << SSH_AUTH_PASSWORD;
1918 packet_put_int(auth_mask);
1920 /* Send the packet and wait for it to be sent. */
1922 packet_write_wait();
1924 debug("Sent %d bit server key and %d bit host key.",
1925 BN_num_bits(sensitive_data.server_key->rsa->n),
1926 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1928 /* Read clients reply (cipher type and session key). */
1929 packet_read_expect(SSH_CMSG_SESSION_KEY);
1931 /* Get cipher type and check whether we accept this. */
1932 cipher_type = packet_get_char();
1934 if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
1935 packet_disconnect("Warning: client selects unsupported cipher.");
1937 /* Get check bytes from the packet. These must match those we
1938 sent earlier with the public key packet. */
1939 for (i = 0; i < 8; i++)
1940 if (cookie[i] != packet_get_char())
1941 packet_disconnect("IP Spoofing check bytes do not match.");
1943 debug("Encryption type: %.200s", cipher_name(cipher_type));
1945 /* Get the encrypted integer. */
1946 if ((session_key_int = BN_new()) == NULL)
1947 fatal("do_ssh1_kex: BN_new failed");
1948 packet_get_bignum(session_key_int);
1950 protocol_flags = packet_get_int();
1951 packet_set_protocol_flags(protocol_flags);
1954 /* Decrypt session_key_int using host/server keys */
1955 rsafail = PRIVSEP(ssh1_session_key(session_key_int));
1958 * Extract session key from the decrypted integer. The key is in the
1959 * least significant 256 bits of the integer; the first byte of the
1960 * key is in the highest bits.
1963 BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1964 len = BN_num_bytes(session_key_int);
1965 if (len < 0 || (u_int)len > sizeof(session_key)) {
1966 error("do_connection: bad session key len from %s: "
1967 "session_key_int %d > sizeof(session_key) %lu",
1968 get_remote_ipaddr(), len, (u_long)sizeof(session_key));
1971 memset(session_key, 0, sizeof(session_key));
1972 BN_bn2bin(session_key_int,
1973 session_key + sizeof(session_key) - len);
1975 derive_ssh1_session_id(
1976 sensitive_data.ssh1_host_key->rsa->n,
1977 sensitive_data.server_key->rsa->n,
1978 cookie, session_id);
1980 * Xor the first 16 bytes of the session key with the
1983 for (i = 0; i < 16; i++)
1984 session_key[i] ^= session_id[i];
1988 int bytes = BN_num_bytes(session_key_int);
1989 u_char *buf = xmalloc(bytes);
1992 logit("do_connection: generating a fake encryption key");
1993 BN_bn2bin(session_key_int, buf);
1995 MD5_Update(&md, buf, bytes);
1996 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1997 MD5_Final(session_key, &md);
1999 MD5_Update(&md, session_key, 16);
2000 MD5_Update(&md, buf, bytes);
2001 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2002 MD5_Final(session_key + 16, &md);
2003 memset(buf, 0, bytes);
2005 for (i = 0; i < 16; i++)
2006 session_id[i] = session_key[i] ^ session_key[i + 16];
2008 /* Destroy the private and public keys. No longer. */
2009 destroy_sensitive_data();
2012 mm_ssh1_session_id(session_id);
2014 /* Destroy the decrypted integer. It is no longer needed. */
2015 BN_clear_free(session_key_int);
2017 /* Set the session key. From this on all communications will be encrypted. */
2018 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
2020 /* Destroy our copy of the session key. It is no longer needed. */
2021 memset(session_key, 0, sizeof(session_key));
2023 debug("Received session key; encryption turned on.");
2025 /* Send an acknowledgment packet. Note that this packet is sent encrypted. */
2026 packet_start(SSH_SMSG_SUCCESS);
2028 packet_write_wait();
2032 * SSH2 key exchange: diffie-hellman-group1-sha1
2039 if (options.ciphers != NULL) {
2040 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2041 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
2043 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2044 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
2045 myproposal[PROPOSAL_ENC_ALGS_STOC] =
2046 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
2048 if (options.macs != NULL) {
2049 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2050 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2052 if (options.compression == COMP_NONE) {
2053 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2054 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2055 } else if (options.compression == COMP_DELAYED) {
2056 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2057 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com";
2060 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
2062 /* start key exchange */
2063 kex = kex_setup(myproposal);
2064 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2065 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
2066 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2067 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2069 kex->client_version_string=client_version_string;
2070 kex->server_version_string=server_version_string;
2071 kex->load_host_key=&get_hostkey_by_type;
2072 kex->host_key_index=&get_hostkey_index;
2076 dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
2078 session_id2 = kex->session_id;
2079 session_id2_len = kex->session_id_len;
2082 /* send 1st encrypted/maced/compressed message */
2083 packet_start(SSH2_MSG_IGNORE);
2084 packet_put_cstring("markus");
2086 packet_write_wait();
2091 /* server specific fatal cleanup */
2096 do_cleanup(the_authctxt);
2097 #ifdef SSH_AUDIT_EVENTS
2098 /* done after do_cleanup so it can cancel the PAM auth 'thread' */
2099 if (!use_privsep || mm_is_monitor())
2100 audit_event(SSH_CONNECTION_ABANDON);