1 /* $OpenBSD: sshd.c,v 1.393 2012/07/10 02:19:15 djm Exp $ */
4 * Author: Tatu Ylonen <ylo@cs.hut.fi>
5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
7 * This program is the ssh daemon. It listens for connections from clients,
8 * and performs authentication, executes use commands or shell, and forwards
9 * information to/from the application to the user client over an encrypted
10 * connection. This can also handle forwarding of X11, TCP/IP, and
11 * authentication agent connections.
13 * As far as I am concerned, the code I have written for this software
14 * can be used freely for any purpose. Any derived versions of this
15 * software must be clearly marked as such, and if the derived work is
16 * incompatible with the protocol description in the RFC file, it must be
17 * called by a name other than "ssh" or "Secure Shell".
19 * SSH2 implementation:
20 * Privilege Separation:
22 * Copyright (c) 2000, 2001, 2002 Markus Friedl. All rights reserved.
23 * Copyright (c) 2002 Niels Provos. All rights reserved.
25 * Redistribution and use in source and binary forms, with or without
26 * modification, are permitted provided that the following conditions
28 * 1. Redistributions of source code must retain the above copyright
29 * notice, this list of conditions and the following disclaimer.
30 * 2. Redistributions in binary form must reproduce the above copyright
31 * notice, this list of conditions and the following disclaimer in the
32 * documentation and/or other materials provided with the distribution.
34 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
35 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
36 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
37 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
38 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
39 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
40 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
41 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
42 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
43 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
49 #include <sys/types.h>
50 #include <sys/ioctl.h>
52 #include <sys/socket.h>
53 #ifdef HAVE_SYS_STAT_H
54 # include <sys/stat.h>
56 #ifdef HAVE_SYS_TIME_H
57 # include <sys/time.h>
59 #include "openbsd-compat/sys-tree.h"
60 #include "openbsd-compat/sys-queue.h"
78 #include <openssl/dh.h>
79 #include <openssl/bn.h>
80 #include <openssl/md5.h>
81 #include <openssl/rand.h>
82 #include "openbsd-compat/openssl-compat.h"
84 #ifdef HAVE_SECUREWARE
85 #include <sys/security.h>
91 #if defined(GSSAPI) && defined(HAVE_GSSAPI_H)
93 #elif defined(GSSAPI) && defined(HAVE_GSSAPI_GSSAPI_H)
94 #include <gssapi/gssapi.h>
107 #include "servconf.h"
114 #include "myproposal.h"
115 #include "authfile.h"
116 #include "pathnames.h"
117 #include "atomicio.h"
118 #include "canohost.h"
119 #include "hostfile.h"
123 #include "dispatch.h"
124 #include "channels.h"
126 #include "monitor_mm.h"
131 #include "monitor_wrap.h"
133 #include "ssh-sandbox.h"
148 #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
149 #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
150 #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
151 #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
153 extern char *__progname;
155 /* Server configuration options. */
156 ServerOptions options;
158 /* Name of the server configuration file. */
159 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
162 * Debug mode flag. This can be set on the command line. If debug
163 * mode is enabled, extra debugging output will be sent to the system
164 * log, the daemon will not go to background, and will exit after processing
165 * the first connection.
169 /* Flag indicating that the daemon should only test the configuration and keys. */
172 /* Flag indicating that the daemon is being started from inetd. */
175 /* Flag indicating that sshd should not detach and become a daemon. */
176 int no_daemon_flag = 0;
178 /* debug goes to stderr unless inetd_flag is set */
181 /* Saved arguments to main(). */
186 int rexeced_flag = 0;
192 * The sockets that the server is listening; this is used in the SIGHUP
195 #define MAX_LISTEN_SOCKS 16
196 int listen_socks[MAX_LISTEN_SOCKS];
197 int num_listen_socks = 0;
200 * the client's version string, passed by sshd2 in compat mode. if != NULL,
201 * sshd will skip the version-number exchange
203 char *client_version_string = NULL;
204 char *server_version_string = NULL;
206 /* for rekeying XXX fixme */
210 * Any really sensitive data in the application is contained in this
211 * structure. The idea is that this structure could be locked into memory so
212 * that the pages do not get written into swap. However, there are some
213 * problems. The private key contains BIGNUMs, and we do not (in principle)
214 * have access to the internals of them, and locking just the structure is
215 * not very useful. Currently, memory locking is not implemented.
218 Key *server_key; /* ephemeral server key */
219 Key *ssh1_host_key; /* ssh1 host key */
220 Key **host_keys; /* all private host keys */
221 Key **host_certificates; /* all public host certificates */
224 u_char ssh1_cookie[SSH_SESSION_KEY_LENGTH];
228 * Flag indicating whether the RSA server key needs to be regenerated.
229 * Is set in the SIGALRM handler and cleared when the key is regenerated.
231 static volatile sig_atomic_t key_do_regen = 0;
233 /* This is set to true when a signal is received. */
234 static volatile sig_atomic_t received_sighup = 0;
235 static volatile sig_atomic_t received_sigterm = 0;
237 /* session identifier, used by RSA-auth */
238 u_char session_id[16];
241 u_char *session_id2 = NULL;
242 u_int session_id2_len = 0;
244 /* record remote hostname or ip */
245 u_int utmp_len = MAXHOSTNAMELEN;
247 /* options.max_startup sized array of fd ints */
248 int *startup_pipes = NULL;
249 int startup_pipe; /* in child */
251 /* variables used for privilege separation */
252 int use_privsep = -1;
253 struct monitor *pmonitor = NULL;
254 int privsep_is_preauth = 1;
256 /* global authentication context */
257 Authctxt *the_authctxt = NULL;
259 /* sshd_config buffer */
262 /* message to be displayed after login */
265 /* Unprivileged user */
266 struct passwd *privsep_pw = NULL;
268 /* Prototypes for various functions defined later in this file. */
269 void destroy_sensitive_data(void);
270 void demote_sensitive_data(void);
272 static void do_ssh1_kex(void);
273 static void do_ssh2_kex(void);
276 * Close all listening sockets
279 close_listen_socks(void)
283 for (i = 0; i < num_listen_socks; i++)
284 close(listen_socks[i]);
285 num_listen_socks = -1;
289 close_startup_pipes(void)
294 for (i = 0; i < options.max_startups; i++)
295 if (startup_pipes[i] != -1)
296 close(startup_pipes[i]);
300 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
301 * the effect is to reread the configuration file (and to regenerate
307 sighup_handler(int sig)
309 int save_errno = errno;
312 signal(SIGHUP, sighup_handler);
317 * Called from the main program after receiving SIGHUP.
318 * Restarts the server.
323 logit("Received SIGHUP; restarting.");
324 close_listen_socks();
325 close_startup_pipes();
326 alarm(0); /* alarm timer persists across exec */
327 signal(SIGHUP, SIG_IGN); /* will be restored after exec */
328 execv(saved_argv[0], saved_argv);
329 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
335 * Generic signal handler for terminating signals in the master daemon.
339 sigterm_handler(int sig)
341 received_sigterm = sig;
345 * SIGCHLD handler. This is called whenever a child dies. This will then
346 * reap any zombies left by exited children.
350 main_sigchld_handler(int sig)
352 int save_errno = errno;
356 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
357 (pid < 0 && errno == EINTR))
360 signal(SIGCHLD, main_sigchld_handler);
365 * Signal handler for the alarm after the login grace period has expired.
369 grace_alarm_handler(int sig)
371 if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
372 kill(pmonitor->m_pid, SIGALRM);
374 /* Log error and exit. */
375 sigdie("Timeout before authentication for %s", get_remote_ipaddr());
379 * Signal handler for the key regeneration alarm. Note that this
380 * alarm only occurs in the daemon waiting for connections, and it does not
381 * do anything with the private key or random state before forking.
382 * Thus there should be no concurrency control/asynchronous execution
386 generate_ephemeral_server_key(void)
388 verbose("Generating %s%d bit RSA key.",
389 sensitive_data.server_key ? "new " : "", options.server_key_bits);
390 if (sensitive_data.server_key != NULL)
391 key_free(sensitive_data.server_key);
392 sensitive_data.server_key = key_generate(KEY_RSA1,
393 options.server_key_bits);
394 verbose("RSA key generation complete.");
396 arc4random_buf(sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
402 key_regeneration_alarm(int sig)
404 int save_errno = errno;
406 signal(SIGALRM, SIG_DFL);
412 sshd_exchange_identification(int sock_in, int sock_out)
416 int remote_major, remote_minor;
418 char *s, *newline = "\n";
419 char buf[256]; /* Must not be larger than remote_version. */
420 char remote_version[256]; /* Must be at least as big as buf. */
422 if ((options.protocol & SSH_PROTO_1) &&
423 (options.protocol & SSH_PROTO_2)) {
424 major = PROTOCOL_MAJOR_1;
426 } else if (options.protocol & SSH_PROTO_2) {
427 major = PROTOCOL_MAJOR_2;
428 minor = PROTOCOL_MINOR_2;
431 major = PROTOCOL_MAJOR_1;
432 minor = PROTOCOL_MINOR_1;
435 xasprintf(&server_version_string, "SSH-%d.%d-%.100s%s%s%s%s",
436 major, minor, SSH_VERSION,
437 options.hpn_disabled ? "" : SSH_VERSION_HPN,
438 *options.version_addendum == '\0' ? "" : " ",
439 options.version_addendum, newline);
441 /* Send our protocol version identification. */
442 if (roaming_atomicio(vwrite, sock_out, server_version_string,
443 strlen(server_version_string))
444 != strlen(server_version_string)) {
445 logit("Could not write ident string to %s", get_remote_ipaddr());
449 /* Read other sides version identification. */
450 memset(buf, 0, sizeof(buf));
451 for (i = 0; i < sizeof(buf) - 1; i++) {
452 if (roaming_atomicio(read, sock_in, &buf[i], 1) != 1) {
453 logit("Did not receive identification string from %s",
454 get_remote_ipaddr());
457 if (buf[i] == '\r') {
459 /* Kludge for F-Secure Macintosh < 1.0.2 */
461 strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
465 if (buf[i] == '\n') {
470 buf[sizeof(buf) - 1] = 0;
471 client_version_string = xstrdup(buf);
474 * Check that the versions match. In future this might accept
475 * several versions and set appropriate flags to handle them.
477 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
478 &remote_major, &remote_minor, remote_version) != 3) {
479 s = "Protocol mismatch.\n";
480 (void) atomicio(vwrite, sock_out, s, strlen(s));
483 logit("Bad protocol version identification '%.100s' from %s",
484 client_version_string, get_remote_ipaddr());
487 debug("Client protocol version %d.%d; client software version %.100s",
488 remote_major, remote_minor, remote_version);
490 compat_datafellows(remote_version);
492 if (datafellows & SSH_BUG_PROBE) {
493 logit("probed from %s with %s. Don't panic.",
494 get_remote_ipaddr(), client_version_string);
498 if (datafellows & SSH_BUG_SCANNER) {
499 logit("scanned from %s with %s. Don't panic.",
500 get_remote_ipaddr(), client_version_string);
505 switch (remote_major) {
507 if (remote_minor == 99) {
508 if (options.protocol & SSH_PROTO_2)
514 if (!(options.protocol & SSH_PROTO_1)) {
518 if (remote_minor < 3) {
519 packet_disconnect("Your ssh version is too old and "
520 "is no longer supported. Please install a newer version.");
521 } else if (remote_minor == 3) {
522 /* note that this disables agent-forwarding */
527 if (options.protocol & SSH_PROTO_2) {
536 chop(server_version_string);
537 debug("Local version string %.200s", server_version_string);
540 s = "Protocol major versions differ.\n";
541 (void) atomicio(vwrite, sock_out, s, strlen(s));
544 logit("Protocol major versions differ for %s: %.200s vs. %.200s",
546 server_version_string, client_version_string);
551 /* Destroy the host and server keys. They will no longer be needed. */
553 destroy_sensitive_data(void)
557 if (sensitive_data.server_key) {
558 key_free(sensitive_data.server_key);
559 sensitive_data.server_key = NULL;
561 for (i = 0; i < options.num_host_key_files; i++) {
562 if (sensitive_data.host_keys[i]) {
563 key_free(sensitive_data.host_keys[i]);
564 sensitive_data.host_keys[i] = NULL;
566 if (sensitive_data.host_certificates[i]) {
567 key_free(sensitive_data.host_certificates[i]);
568 sensitive_data.host_certificates[i] = NULL;
571 sensitive_data.ssh1_host_key = NULL;
572 memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
575 /* Demote private to public keys for network child */
577 demote_sensitive_data(void)
582 if (sensitive_data.server_key) {
583 tmp = key_demote(sensitive_data.server_key);
584 key_free(sensitive_data.server_key);
585 sensitive_data.server_key = tmp;
588 for (i = 0; i < options.num_host_key_files; i++) {
589 if (sensitive_data.host_keys[i]) {
590 tmp = key_demote(sensitive_data.host_keys[i]);
591 key_free(sensitive_data.host_keys[i]);
592 sensitive_data.host_keys[i] = tmp;
593 if (tmp->type == KEY_RSA1)
594 sensitive_data.ssh1_host_key = tmp;
596 /* Certs do not need demotion */
599 /* We do not clear ssh1_host key and cookie. XXX - Okay Niels? */
603 privsep_preauth_child(void)
608 /* Enable challenge-response authentication for privilege separation */
609 privsep_challenge_enable();
612 arc4random_buf(rnd, sizeof(rnd));
613 RAND_seed(rnd, sizeof(rnd));
615 /* Demote the private keys to public keys. */
616 demote_sensitive_data();
618 /* Change our root directory */
619 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
620 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
622 if (chdir("/") == -1)
623 fatal("chdir(\"/\"): %s", strerror(errno));
625 /* Drop our privileges */
626 debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
627 (u_int)privsep_pw->pw_gid);
629 /* XXX not ready, too heavy after chroot */
630 do_setusercontext(privsep_pw);
632 gidset[0] = privsep_pw->pw_gid;
633 if (setgroups(1, gidset) < 0)
634 fatal("setgroups: %.100s", strerror(errno));
635 permanently_set_uid(privsep_pw);
640 privsep_preauth(Authctxt *authctxt)
644 struct ssh_sandbox *box = NULL;
646 /* Set up unprivileged child process to deal with network data */
647 pmonitor = monitor_init();
648 /* Store a pointer to the kex for later rekeying */
649 pmonitor->m_pkex = &xxx_kex;
651 if (use_privsep == PRIVSEP_ON)
652 box = ssh_sandbox_init();
655 fatal("fork of unprivileged child failed");
656 } else if (pid != 0) {
657 debug2("Network child is on pid %ld", (long)pid);
659 pmonitor->m_pid = pid;
661 ssh_sandbox_parent_preauth(box, pid);
662 monitor_child_preauth(authctxt, pmonitor);
665 monitor_sync(pmonitor);
667 /* Wait for the child's exit status */
668 while (waitpid(pid, &status, 0) < 0) {
671 pmonitor->m_pid = -1;
672 fatal("%s: waitpid: %s", __func__, strerror(errno));
674 privsep_is_preauth = 0;
675 pmonitor->m_pid = -1;
676 if (WIFEXITED(status)) {
677 if (WEXITSTATUS(status) != 0)
678 fatal("%s: preauth child exited with status %d",
679 __func__, WEXITSTATUS(status));
680 } else if (WIFSIGNALED(status))
681 fatal("%s: preauth child terminated by signal %d",
682 __func__, WTERMSIG(status));
684 ssh_sandbox_parent_finish(box);
688 close(pmonitor->m_sendfd);
689 close(pmonitor->m_log_recvfd);
691 /* Arrange for logging to be sent to the monitor */
692 set_log_handler(mm_log_handler, pmonitor);
694 /* Demote the child */
695 if (getuid() == 0 || geteuid() == 0)
696 privsep_preauth_child();
697 setproctitle("%s", "[net]");
699 ssh_sandbox_child(box);
706 privsep_postauth(Authctxt *authctxt)
710 #ifdef DISABLE_FD_PASSING
713 if (authctxt->pw->pw_uid == 0 || options.use_login) {
715 /* File descriptor passing is broken or root login */
720 /* New socket pair */
721 monitor_reinit(pmonitor);
723 pmonitor->m_pid = fork();
724 if (pmonitor->m_pid == -1)
725 fatal("fork of unprivileged child failed");
726 else if (pmonitor->m_pid != 0) {
727 verbose("User child is on pid %ld", (long)pmonitor->m_pid);
728 buffer_clear(&loginmsg);
729 monitor_child_postauth(pmonitor);
737 close(pmonitor->m_sendfd);
738 pmonitor->m_sendfd = -1;
740 /* Demote the private keys to public keys. */
741 demote_sensitive_data();
744 arc4random_buf(rnd, sizeof(rnd));
745 RAND_seed(rnd, sizeof(rnd));
747 /* Drop privileges */
748 do_setusercontext(authctxt->pw);
751 /* It is safe now to apply the key state */
752 monitor_apply_keystate(pmonitor);
755 * Tell the packet layer that authentication was successful, since
756 * this information is not part of the key state.
758 packet_set_authenticated();
762 list_hostkey_types(void)
771 for (i = 0; i < options.num_host_key_files; i++) {
772 key = sensitive_data.host_keys[i];
779 if (buffer_len(&b) > 0)
780 buffer_append(&b, ",", 1);
781 p = key_ssh_name(key);
782 buffer_append(&b, p, strlen(p));
785 /* If the private key has a cert peer, then list that too */
786 key = sensitive_data.host_certificates[i];
790 case KEY_RSA_CERT_V00:
791 case KEY_DSA_CERT_V00:
795 if (buffer_len(&b) > 0)
796 buffer_append(&b, ",", 1);
797 p = key_ssh_name(key);
798 buffer_append(&b, p, strlen(p));
802 buffer_append(&b, "\0", 1);
803 ret = xstrdup(buffer_ptr(&b));
805 debug("list_hostkey_types: %s", ret);
810 get_hostkey_by_type(int type, int need_private)
815 for (i = 0; i < options.num_host_key_files; i++) {
817 case KEY_RSA_CERT_V00:
818 case KEY_DSA_CERT_V00:
822 key = sensitive_data.host_certificates[i];
825 key = sensitive_data.host_keys[i];
828 if (key != NULL && key->type == type)
829 return need_private ?
830 sensitive_data.host_keys[i] : key;
836 get_hostkey_public_by_type(int type)
838 return get_hostkey_by_type(type, 0);
842 get_hostkey_private_by_type(int type)
844 return get_hostkey_by_type(type, 1);
848 get_hostkey_by_index(int ind)
850 if (ind < 0 || ind >= options.num_host_key_files)
852 return (sensitive_data.host_keys[ind]);
856 get_hostkey_index(Key *key)
860 for (i = 0; i < options.num_host_key_files; i++) {
861 if (key_is_cert(key)) {
862 if (key == sensitive_data.host_certificates[i])
865 if (key == sensitive_data.host_keys[i])
873 * returns 1 if connection should be dropped, 0 otherwise.
874 * dropping starts at connection #max_startups_begin with a probability
875 * of (max_startups_rate/100). the probability increases linearly until
876 * all connections are dropped for startups > max_startups
879 drop_connection(int startups)
883 if (startups < options.max_startups_begin)
885 if (startups >= options.max_startups)
887 if (options.max_startups_rate == 100)
890 p = 100 - options.max_startups_rate;
891 p *= startups - options.max_startups_begin;
892 p /= options.max_startups - options.max_startups_begin;
893 p += options.max_startups_rate;
894 r = arc4random_uniform(100);
896 debug("drop_connection: p %d, r %d", p, r);
897 return (r < p) ? 1 : 0;
903 if (options.version_addendum && *options.version_addendum != '\0')
904 fprintf(stderr, "%s%s %s, %s\n",
905 SSH_RELEASE, options.hpn_disabled ? "" : SSH_VERSION_HPN,
906 options.version_addendum, SSLeay_version(SSLEAY_VERSION));
908 fprintf(stderr, "%s%s, %s\n",
909 SSH_RELEASE, options.hpn_disabled ? "" : SSH_VERSION_HPN,
910 SSLeay_version(SSLEAY_VERSION));
912 "usage: sshd [-46DdeiqTt] [-b bits] [-C connection_spec] [-c host_cert_file]\n"
913 " [-f config_file] [-g login_grace_time] [-h host_key_file]\n"
914 " [-k key_gen_time] [-o option] [-p port] [-u len]\n"
920 send_rexec_state(int fd, Buffer *conf)
924 debug3("%s: entering fd = %d config len %d", __func__, fd,
928 * Protocol from reexec master to child:
929 * string configuration
930 * u_int ephemeral_key_follows
931 * bignum e (only if ephemeral_key_follows == 1)
937 * string rngseed (only if OpenSSL is not self-seeded)
940 buffer_put_cstring(&m, buffer_ptr(conf));
942 if (sensitive_data.server_key != NULL &&
943 sensitive_data.server_key->type == KEY_RSA1) {
944 buffer_put_int(&m, 1);
945 buffer_put_bignum(&m, sensitive_data.server_key->rsa->e);
946 buffer_put_bignum(&m, sensitive_data.server_key->rsa->n);
947 buffer_put_bignum(&m, sensitive_data.server_key->rsa->d);
948 buffer_put_bignum(&m, sensitive_data.server_key->rsa->iqmp);
949 buffer_put_bignum(&m, sensitive_data.server_key->rsa->p);
950 buffer_put_bignum(&m, sensitive_data.server_key->rsa->q);
952 buffer_put_int(&m, 0);
954 #ifndef OPENSSL_PRNG_ONLY
955 rexec_send_rng_seed(&m);
958 if (ssh_msg_send(fd, 0, &m) == -1)
959 fatal("%s: ssh_msg_send failed", __func__);
963 debug3("%s: done", __func__);
967 recv_rexec_state(int fd, Buffer *conf)
973 debug3("%s: entering fd = %d", __func__, fd);
977 if (ssh_msg_recv(fd, &m) == -1)
978 fatal("%s: ssh_msg_recv failed", __func__);
979 if (buffer_get_char(&m) != 0)
980 fatal("%s: rexec version mismatch", __func__);
982 cp = buffer_get_string(&m, &len);
984 buffer_append(conf, cp, len + 1);
987 if (buffer_get_int(&m)) {
988 if (sensitive_data.server_key != NULL)
989 key_free(sensitive_data.server_key);
990 sensitive_data.server_key = key_new_private(KEY_RSA1);
991 buffer_get_bignum(&m, sensitive_data.server_key->rsa->e);
992 buffer_get_bignum(&m, sensitive_data.server_key->rsa->n);
993 buffer_get_bignum(&m, sensitive_data.server_key->rsa->d);
994 buffer_get_bignum(&m, sensitive_data.server_key->rsa->iqmp);
995 buffer_get_bignum(&m, sensitive_data.server_key->rsa->p);
996 buffer_get_bignum(&m, sensitive_data.server_key->rsa->q);
997 rsa_generate_additional_parameters(
998 sensitive_data.server_key->rsa);
1001 #ifndef OPENSSL_PRNG_ONLY
1002 rexec_recv_rng_seed(&m);
1007 debug3("%s: done", __func__);
1010 /* Accept a connection from inetd */
1012 server_accept_inetd(int *sock_in, int *sock_out)
1018 close(REEXEC_CONFIG_PASS_FD);
1019 *sock_in = *sock_out = dup(STDIN_FILENO);
1021 startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
1022 close(REEXEC_STARTUP_PIPE_FD);
1025 *sock_in = dup(STDIN_FILENO);
1026 *sock_out = dup(STDOUT_FILENO);
1029 * We intentionally do not close the descriptors 0, 1, and 2
1030 * as our code for setting the descriptors won't work if
1031 * ttyfd happens to be one of those.
1033 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1034 dup2(fd, STDIN_FILENO);
1035 dup2(fd, STDOUT_FILENO);
1036 if (fd > STDOUT_FILENO)
1039 debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
1043 * Listen for TCP connections
1048 int ret, listen_sock, on = 1;
1049 struct addrinfo *ai;
1050 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1054 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
1055 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1057 if (num_listen_socks >= MAX_LISTEN_SOCKS)
1058 fatal("Too many listen sockets. "
1059 "Enlarge MAX_LISTEN_SOCKS");
1060 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1061 ntop, sizeof(ntop), strport, sizeof(strport),
1062 NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1063 error("getnameinfo failed: %.100s",
1064 ssh_gai_strerror(ret));
1067 /* Create socket for listening. */
1068 listen_sock = socket(ai->ai_family, ai->ai_socktype,
1070 if (listen_sock < 0) {
1071 /* kernel may not support ipv6 */
1072 verbose("socket: %.100s", strerror(errno));
1075 if (set_nonblock(listen_sock) == -1) {
1080 * Set socket options.
1081 * Allow local port reuse in TIME_WAIT.
1083 if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
1084 &on, sizeof(on)) == -1)
1085 error("setsockopt SO_REUSEADDR: %s", strerror(errno));
1087 /* Only communicate in IPv6 over AF_INET6 sockets. */
1088 if (ai->ai_family == AF_INET6)
1089 sock_set_v6only(listen_sock);
1091 debug("Bind to port %s on %s.", strport, ntop);
1093 len = sizeof(socksize);
1094 getsockopt(listen_sock, SOL_SOCKET, SO_RCVBUF, &socksize, &len);
1095 debug("Server TCP RWIN socket size: %d", socksize);
1096 debug("HPN Buffer Size: %d", options.hpn_buffer_size);
1098 /* Bind the socket to the desired port. */
1099 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1100 error("Bind to port %s on %s failed: %.200s.",
1101 strport, ntop, strerror(errno));
1105 listen_socks[num_listen_socks] = listen_sock;
1108 /* Start listening on the port. */
1109 if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1110 fatal("listen on [%s]:%s: %.100s",
1111 ntop, strport, strerror(errno));
1112 logit("Server listening on %s port %s.", ntop, strport);
1114 freeaddrinfo(options.listen_addrs);
1116 if (!num_listen_socks)
1117 fatal("Cannot bind any address.");
1121 * The main TCP accept loop. Note that, for the non-debug case, returns
1122 * from this function are in a forked subprocess.
1125 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1128 int i, j, ret, maxfd;
1129 int key_used = 0, startups = 0;
1130 int startup_p[2] = { -1 , -1 };
1131 struct sockaddr_storage from;
1135 /* setup fd set for accept */
1138 for (i = 0; i < num_listen_socks; i++)
1139 if (listen_socks[i] > maxfd)
1140 maxfd = listen_socks[i];
1141 /* pipes connected to unauthenticated childs */
1142 startup_pipes = xcalloc(options.max_startups, sizeof(int));
1143 for (i = 0; i < options.max_startups; i++)
1144 startup_pipes[i] = -1;
1147 * Stay listening for connections until the system crashes or
1148 * the daemon is killed with a signal.
1151 if (received_sighup)
1155 fdset = (fd_set *)xcalloc(howmany(maxfd + 1, NFDBITS),
1158 for (i = 0; i < num_listen_socks; i++)
1159 FD_SET(listen_socks[i], fdset);
1160 for (i = 0; i < options.max_startups; i++)
1161 if (startup_pipes[i] != -1)
1162 FD_SET(startup_pipes[i], fdset);
1164 /* Wait in select until there is a connection. */
1165 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1166 if (ret < 0 && errno != EINTR)
1167 error("select: %.100s", strerror(errno));
1168 if (received_sigterm) {
1169 logit("Received signal %d; terminating.",
1170 (int) received_sigterm);
1171 close_listen_socks();
1172 unlink(options.pid_file);
1173 exit(received_sigterm == SIGTERM ? 0 : 255);
1175 if (key_used && key_do_regen) {
1176 generate_ephemeral_server_key();
1183 for (i = 0; i < options.max_startups; i++)
1184 if (startup_pipes[i] != -1 &&
1185 FD_ISSET(startup_pipes[i], fdset)) {
1187 * the read end of the pipe is ready
1188 * if the child has closed the pipe
1189 * after successful authentication
1190 * or if the child has died
1192 close(startup_pipes[i]);
1193 startup_pipes[i] = -1;
1196 for (i = 0; i < num_listen_socks; i++) {
1197 if (!FD_ISSET(listen_socks[i], fdset))
1199 fromlen = sizeof(from);
1200 *newsock = accept(listen_socks[i],
1201 (struct sockaddr *)&from, &fromlen);
1203 if (errno != EINTR && errno != EAGAIN &&
1204 errno != EWOULDBLOCK)
1205 error("accept: %.100s",
1207 if (errno == EMFILE || errno == ENFILE)
1211 if (unset_nonblock(*newsock) == -1) {
1215 if (drop_connection(startups) == 1) {
1216 debug("drop connection #%d", startups);
1220 if (pipe(startup_p) == -1) {
1225 if (rexec_flag && socketpair(AF_UNIX,
1226 SOCK_STREAM, 0, config_s) == -1) {
1227 error("reexec socketpair: %s",
1230 close(startup_p[0]);
1231 close(startup_p[1]);
1235 for (j = 0; j < options.max_startups; j++)
1236 if (startup_pipes[j] == -1) {
1237 startup_pipes[j] = startup_p[0];
1238 if (maxfd < startup_p[0])
1239 maxfd = startup_p[0];
1245 * Got connection. Fork a child to handle it, unless
1246 * we are in debugging mode.
1250 * In debugging mode. Close the listening
1251 * socket, and start processing the
1252 * connection without forking.
1254 debug("Server will not fork when running in debugging mode.");
1255 close_listen_socks();
1256 *sock_in = *newsock;
1257 *sock_out = *newsock;
1258 close(startup_p[0]);
1259 close(startup_p[1]);
1263 send_rexec_state(config_s[0],
1271 * Normal production daemon. Fork, and have
1272 * the child process the connection. The
1273 * parent continues listening.
1275 platform_pre_fork();
1276 if ((pid = fork()) == 0) {
1278 * Child. Close the listening and
1279 * max_startup sockets. Start using
1280 * the accepted socket. Reinitialize
1281 * logging (since our pid has changed).
1282 * We break out of the loop to handle
1285 platform_post_fork_child();
1286 startup_pipe = startup_p[1];
1287 close_startup_pipes();
1288 close_listen_socks();
1289 *sock_in = *newsock;
1290 *sock_out = *newsock;
1291 log_init(__progname,
1293 options.log_facility,
1300 /* Parent. Stay in the loop. */
1301 platform_post_fork_parent(pid);
1303 error("fork: %.100s", strerror(errno));
1305 debug("Forked child %ld.", (long)pid);
1307 close(startup_p[1]);
1310 send_rexec_state(config_s[0], &cfg);
1316 * Mark that the key has been used (it
1317 * was "given" to the child).
1319 if ((options.protocol & SSH_PROTO_1) &&
1321 /* Schedule server key regeneration alarm. */
1322 signal(SIGALRM, key_regeneration_alarm);
1323 alarm(options.key_regeneration_time);
1330 * Ensure that our random state differs
1331 * from that of the child
1336 /* child process check (or debug mode) */
1337 if (num_listen_socks < 0)
1344 * Main program for the daemon.
1347 main(int ac, char **av)
1349 extern char *optarg;
1351 int opt, i, j, on = 1;
1352 int sock_in = -1, sock_out = -1, newsock = -1;
1353 const char *remote_ip;
1356 int config_s[2] = { -1 , -1 };
1357 u_int64_t ibytes, obytes;
1361 struct connection_info *connection_info = get_connection_info(0, 0);
1363 #ifdef HAVE_SECUREWARE
1364 (void)set_auth_parameters(ac, av);
1366 __progname = ssh_get_progname(av[0]);
1368 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1371 saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1372 for (i = 0; i < ac; i++)
1373 saved_argv[i] = xstrdup(av[i]);
1374 saved_argv[i] = NULL;
1376 #ifndef HAVE_SETPROCTITLE
1377 /* Prepare for later setproctitle emulation */
1378 compat_init_setproctitle(ac, av);
1382 if (geteuid() == 0 && setgroups(0, NULL) == -1)
1383 debug("setgroups(): %.200s", strerror(errno));
1385 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1388 /* Initialize configuration options to their default values. */
1389 initialize_server_options(&options);
1391 /* Parse command-line arguments. */
1392 while ((opt = getopt(ac, av, "f:p:b:k:h:g:u:o:C:dDeiqrtQRT46")) != -1) {
1395 options.address_family = AF_INET;
1398 options.address_family = AF_INET6;
1401 config_file_name = optarg;
1404 if (options.num_host_cert_files >= MAX_HOSTCERTS) {
1405 fprintf(stderr, "too many host certificates.\n");
1408 options.host_cert_files[options.num_host_cert_files++] =
1409 derelativise_path(optarg);
1412 if (debug_flag == 0) {
1414 options.log_level = SYSLOG_LEVEL_DEBUG1;
1415 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1416 options.log_level++;
1438 options.log_level = SYSLOG_LEVEL_QUIET;
1441 options.server_key_bits = (int)strtonum(optarg, 256,
1445 options.ports_from_cmdline = 1;
1446 if (options.num_ports >= MAX_PORTS) {
1447 fprintf(stderr, "too many ports.\n");
1450 options.ports[options.num_ports++] = a2port(optarg);
1451 if (options.ports[options.num_ports-1] <= 0) {
1452 fprintf(stderr, "Bad port number.\n");
1457 if ((options.login_grace_time = convtime(optarg)) == -1) {
1458 fprintf(stderr, "Invalid login grace time.\n");
1463 if ((options.key_regeneration_time = convtime(optarg)) == -1) {
1464 fprintf(stderr, "Invalid key regeneration interval.\n");
1469 if (options.num_host_key_files >= MAX_HOSTKEYS) {
1470 fprintf(stderr, "too many host keys.\n");
1473 options.host_key_files[options.num_host_key_files++] =
1474 derelativise_path(optarg);
1483 if (parse_server_match_testspec(connection_info,
1488 utmp_len = (u_int)strtonum(optarg, 0, MAXHOSTNAMELEN+1, NULL);
1489 if (utmp_len > MAXHOSTNAMELEN) {
1490 fprintf(stderr, "Invalid utmp length.\n");
1495 line = xstrdup(optarg);
1496 if (process_server_config_line(&options, line,
1497 "command-line", 0, NULL, NULL) != 0)
1507 if (rexeced_flag || inetd_flag)
1509 if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1510 fatal("sshd re-exec requires execution with an absolute path");
1512 closefrom(REEXEC_MIN_FREE_FD);
1514 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1516 OpenSSL_add_all_algorithms();
1519 * Force logging to stderr until we have loaded the private host
1520 * key (unless started from inetd)
1522 log_init(__progname,
1523 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1524 SYSLOG_LEVEL_INFO : options.log_level,
1525 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1526 SYSLOG_FACILITY_AUTH : options.log_facility,
1527 log_stderr || !inetd_flag);
1530 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1531 * root's environment
1533 if (getenv("KRB5CCNAME") != NULL)
1534 (void) unsetenv("KRB5CCNAME");
1537 /* Cray can define user privs drop all privs now!
1538 * Not needed on PRIV_SU systems!
1543 sensitive_data.server_key = NULL;
1544 sensitive_data.ssh1_host_key = NULL;
1545 sensitive_data.have_ssh1_key = 0;
1546 sensitive_data.have_ssh2_key = 0;
1549 * If we're doing an extended config test, make sure we have all of
1550 * the parameters we need. If we're not doing an extended test,
1551 * do not silently ignore connection test params.
1553 if (test_flag >= 2 && server_match_spec_complete(connection_info) == 0)
1554 fatal("user, host and addr are all required when testing "
1556 if (test_flag < 2 && server_match_spec_complete(connection_info) >= 0)
1557 fatal("Config test connection parameter (-C) provided without "
1560 /* Fetch our configuration */
1563 recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1565 load_server_config(config_file_name, &cfg);
1567 parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1572 /* Fill in default values for those options not explicitly set. */
1573 fill_default_server_options(&options);
1575 /* challenge-response is implemented via keyboard interactive */
1576 if (options.challenge_response_authentication)
1577 options.kbd_interactive_authentication = 1;
1579 /* set default channel AF */
1580 channel_set_af(options.address_family);
1582 /* Check that there are no remaining arguments. */
1584 fprintf(stderr, "Extra argument %s.\n", av[optind]);
1588 debug("sshd version %.100s%.100s%s%.100s",
1590 options.hpn_disabled ? "" : SSH_VERSION_HPN,
1591 *options.version_addendum == '\0' ? "" : " ",
1592 options.version_addendum);
1594 /* Store privilege separation user for later use if required. */
1595 if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1596 if (use_privsep || options.kerberos_authentication)
1597 fatal("Privilege separation user %s does not exist",
1600 memset(privsep_pw->pw_passwd, 0, strlen(privsep_pw->pw_passwd));
1601 privsep_pw = pwcopy(privsep_pw);
1602 xfree(privsep_pw->pw_passwd);
1603 privsep_pw->pw_passwd = xstrdup("*");
1607 /* load private host keys */
1608 sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1610 for (i = 0; i < options.num_host_key_files; i++)
1611 sensitive_data.host_keys[i] = NULL;
1613 for (i = 0; i < options.num_host_key_files; i++) {
1614 key = key_load_private(options.host_key_files[i], "", NULL);
1615 sensitive_data.host_keys[i] = key;
1617 error("Could not load host key: %s",
1618 options.host_key_files[i]);
1619 sensitive_data.host_keys[i] = NULL;
1622 switch (key->type) {
1624 sensitive_data.ssh1_host_key = key;
1625 sensitive_data.have_ssh1_key = 1;
1630 sensitive_data.have_ssh2_key = 1;
1633 debug("private host key: #%d type %d %s", i, key->type,
1636 if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1637 logit("Disabling protocol version 1. Could not load host key");
1638 options.protocol &= ~SSH_PROTO_1;
1640 if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1641 logit("Disabling protocol version 2. Could not load host key");
1642 options.protocol &= ~SSH_PROTO_2;
1644 if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1645 logit("sshd: no hostkeys available -- exiting.");
1650 * Load certificates. They are stored in an array at identical
1651 * indices to the public keys that they relate to.
1653 sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
1655 for (i = 0; i < options.num_host_key_files; i++)
1656 sensitive_data.host_certificates[i] = NULL;
1658 for (i = 0; i < options.num_host_cert_files; i++) {
1659 key = key_load_public(options.host_cert_files[i], NULL);
1661 error("Could not load host certificate: %s",
1662 options.host_cert_files[i]);
1665 if (!key_is_cert(key)) {
1666 error("Certificate file is not a certificate: %s",
1667 options.host_cert_files[i]);
1671 /* Find matching private key */
1672 for (j = 0; j < options.num_host_key_files; j++) {
1673 if (key_equal_public(key,
1674 sensitive_data.host_keys[j])) {
1675 sensitive_data.host_certificates[j] = key;
1679 if (j >= options.num_host_key_files) {
1680 error("No matching private key for certificate: %s",
1681 options.host_cert_files[i]);
1685 sensitive_data.host_certificates[j] = key;
1686 debug("host certificate: #%d type %d %s", j, key->type,
1689 /* Check certain values for sanity. */
1690 if (options.protocol & SSH_PROTO_1) {
1691 if (options.server_key_bits < 512 ||
1692 options.server_key_bits > 32768) {
1693 fprintf(stderr, "Bad server key size.\n");
1697 * Check that server and host key lengths differ sufficiently. This
1698 * is necessary to make double encryption work with rsaref. Oh, I
1699 * hate software patents. I dont know if this can go? Niels
1701 if (options.server_key_bits >
1702 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
1703 SSH_KEY_BITS_RESERVED && options.server_key_bits <
1704 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1705 SSH_KEY_BITS_RESERVED) {
1706 options.server_key_bits =
1707 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1708 SSH_KEY_BITS_RESERVED;
1709 debug("Forcing server key to %d bits to make it differ from host key.",
1710 options.server_key_bits);
1717 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1718 (S_ISDIR(st.st_mode) == 0))
1719 fatal("Missing privilege separation directory: %s",
1720 _PATH_PRIVSEP_CHROOT_DIR);
1723 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1724 (st.st_uid != getuid () ||
1725 (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1727 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1729 fatal("%s must be owned by root and not group or "
1730 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1733 if (test_flag > 1) {
1734 if (server_match_spec_complete(connection_info) == 1)
1735 parse_server_match_config(&options, connection_info);
1736 dump_config(&options);
1739 /* Configuration looks good, so exit if in test mode. */
1744 * Clear out any supplemental groups we may have inherited. This
1745 * prevents inadvertent creation of files with bad modes (in the
1746 * portable version at least, it's certainly possible for PAM
1747 * to create a file, and we can't control the code in every
1748 * module which might be used).
1750 if (setgroups(0, NULL) < 0)
1751 debug("setgroups() failed: %.200s", strerror(errno));
1754 rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1755 for (i = 0; i < rexec_argc; i++) {
1756 debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1757 rexec_argv[i] = saved_argv[i];
1759 rexec_argv[rexec_argc] = "-R";
1760 rexec_argv[rexec_argc + 1] = NULL;
1763 /* Ensure that umask disallows at least group and world write */
1764 new_umask = umask(0077) | 0022;
1765 (void) umask(new_umask);
1767 /* Initialize the log (it is reinitialized below in case we forked). */
1768 if (debug_flag && (!inetd_flag || rexeced_flag))
1770 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1773 * If not in debugging mode, and not started from inetd, disconnect
1774 * from the controlling terminal, and fork. The original process
1777 if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1780 #endif /* TIOCNOTTY */
1781 if (daemon(0, 0) < 0)
1782 fatal("daemon() failed: %.200s", strerror(errno));
1784 /* Disconnect from the controlling tty. */
1786 fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1788 (void) ioctl(fd, TIOCNOTTY, NULL);
1791 #endif /* TIOCNOTTY */
1793 /* Reinitialize the log (because of the fork above). */
1794 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1796 /* Avoid killing the process in high-pressure swapping environments. */
1797 if (!inetd_flag && madvise(NULL, 0, MADV_PROTECT) != 0)
1798 debug("madvise(): %.200s", strerror(errno));
1800 /* Initialize the random number generator. */
1803 /* Chdir to the root directory so that the current disk can be
1804 unmounted if desired. */
1807 /* ignore SIGPIPE */
1808 signal(SIGPIPE, SIG_IGN);
1810 /* Get a connection, either from inetd or a listening TCP socket */
1812 server_accept_inetd(&sock_in, &sock_out);
1814 platform_pre_listen();
1817 if (options.protocol & SSH_PROTO_1)
1818 generate_ephemeral_server_key();
1820 signal(SIGHUP, sighup_handler);
1821 signal(SIGCHLD, main_sigchld_handler);
1822 signal(SIGTERM, sigterm_handler);
1823 signal(SIGQUIT, sigterm_handler);
1826 * Write out the pid file after the sigterm handler
1827 * is setup and the listen sockets are bound
1830 FILE *f = fopen(options.pid_file, "w");
1833 error("Couldn't create pid file \"%s\": %s",
1834 options.pid_file, strerror(errno));
1836 fprintf(f, "%ld\n", (long) getpid());
1841 /* Accept a connection and return in a forked child */
1842 server_accept_loop(&sock_in, &sock_out,
1843 &newsock, config_s);
1846 /* This is the child processing a new connection. */
1847 setproctitle("%s", "[accepted]");
1850 * Create a new session and process group since the 4.4BSD
1851 * setlogin() affects the entire process group. We don't
1852 * want the child to be able to affect the parent.
1854 #if !defined(SSHD_ACQUIRES_CTTY)
1856 * If setsid is called, on some platforms sshd will later acquire a
1857 * controlling terminal which will result in "could not set
1858 * controlling tty" errors.
1860 if (!debug_flag && !inetd_flag && setsid() < 0)
1861 error("setsid: %.100s", strerror(errno));
1867 debug("rexec start in %d out %d newsock %d pipe %d sock %d",
1868 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1869 dup2(newsock, STDIN_FILENO);
1870 dup2(STDIN_FILENO, STDOUT_FILENO);
1871 if (startup_pipe == -1)
1872 close(REEXEC_STARTUP_PIPE_FD);
1874 dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
1876 dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1878 if (startup_pipe != -1)
1879 close(startup_pipe);
1881 execv(rexec_argv[0], rexec_argv);
1883 /* Reexec has failed, fall back and continue */
1884 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1885 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1886 log_init(__progname, options.log_level,
1887 options.log_facility, log_stderr);
1890 startup_pipe = REEXEC_STARTUP_PIPE_FD;
1892 close(REEXEC_CONFIG_PASS_FD);
1893 newsock = sock_out = sock_in = dup(STDIN_FILENO);
1894 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1895 dup2(fd, STDIN_FILENO);
1896 dup2(fd, STDOUT_FILENO);
1897 if (fd > STDERR_FILENO)
1900 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
1901 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1904 /* Executed child processes don't need these. */
1905 fcntl(sock_out, F_SETFD, FD_CLOEXEC);
1906 fcntl(sock_in, F_SETFD, FD_CLOEXEC);
1909 * Disable the key regeneration alarm. We will not regenerate the
1910 * key since we are no longer in a position to give it to anyone. We
1911 * will not restart on SIGHUP since it no longer makes sense.
1914 signal(SIGALRM, SIG_DFL);
1915 signal(SIGHUP, SIG_DFL);
1916 signal(SIGTERM, SIG_DFL);
1917 signal(SIGQUIT, SIG_DFL);
1918 signal(SIGCHLD, SIG_DFL);
1919 signal(SIGINT, SIG_DFL);
1923 * Initialize the resolver. This may not happen automatically
1924 * before privsep chroot().
1926 if ((_res.options & RES_INIT) == 0) {
1927 debug("res_init()");
1932 * Force GSS-API to parse its configuration and load any
1933 * mechanism plugins.
1937 OM_uint32 minor_status;
1938 gss_indicate_mechs(&minor_status, &mechs);
1939 gss_release_oid_set(&minor_status, &mechs);
1945 * Register our connection. This turns encryption off because we do
1948 packet_set_connection(sock_in, sock_out);
1949 packet_set_server();
1951 /* Set SO_KEEPALIVE if requested. */
1952 if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
1953 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
1954 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1956 if ((remote_port = get_remote_port()) < 0) {
1957 debug("get_remote_port failed");
1962 * We use get_canonical_hostname with usedns = 0 instead of
1963 * get_remote_ipaddr here so IP options will be checked.
1965 (void) get_canonical_hostname(0);
1967 * The rest of the code depends on the fact that
1968 * get_remote_ipaddr() caches the remote ip, even if
1969 * the socket goes away.
1971 remote_ip = get_remote_ipaddr();
1973 #ifdef SSH_AUDIT_EVENTS
1974 audit_connection_from(remote_ip, remote_port);
1977 allow_severity = options.log_facility|LOG_INFO;
1978 deny_severity = options.log_facility|LOG_WARNING;
1979 /* Check whether logins are denied from this host. */
1980 if (packet_connection_is_on_socket()) {
1981 struct request_info req;
1983 request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1986 if (!hosts_access(&req)) {
1987 debug("Connection refused by tcp wrapper");
1990 fatal("libwrap refuse returns");
1993 #endif /* LIBWRAP */
1995 /* Log the connection. */
1996 verbose("Connection from %.500s port %d", remote_ip, remote_port);
1998 /* Set HPN options for the child. */
1999 channel_set_hpn(options.hpn_disabled, options.hpn_buffer_size);
2002 * We don't want to listen forever unless the other side
2003 * successfully authenticates itself. So we set up an alarm which is
2004 * cleared after successful authentication. A limit of zero
2005 * indicates no limit. Note that we don't set the alarm in debugging
2006 * mode; it is just annoying to have the server exit just when you
2007 * are about to discover the bug.
2009 signal(SIGALRM, grace_alarm_handler);
2011 alarm(options.login_grace_time);
2013 sshd_exchange_identification(sock_in, sock_out);
2015 /* In inetd mode, generate ephemeral key only for proto 1 connections */
2016 if (!compat20 && inetd_flag && sensitive_data.server_key == NULL)
2017 generate_ephemeral_server_key();
2019 packet_set_nonblocking();
2021 /* allocate authentication context */
2022 authctxt = xcalloc(1, sizeof(*authctxt));
2024 authctxt->loginmsg = &loginmsg;
2026 /* XXX global for cleanup, access from other modules */
2027 the_authctxt = authctxt;
2029 /* prepare buffer to collect messages to display to user after login */
2030 buffer_init(&loginmsg);
2034 if (privsep_preauth(authctxt) == 1)
2037 /* perform the key exchange */
2038 /* authenticate user and start session */
2041 do_authentication2(authctxt);
2044 do_authentication(authctxt);
2047 * If we use privilege separation, the unprivileged child transfers
2048 * the current keystate and exits
2051 mm_send_keystate(pmonitor);
2057 * Cancel the alarm we set to limit the time taken for
2061 signal(SIGALRM, SIG_DFL);
2062 authctxt->authenticated = 1;
2063 if (startup_pipe != -1) {
2064 close(startup_pipe);
2068 #ifdef SSH_AUDIT_EVENTS
2069 audit_event(SSH_AUTH_SUCCESS);
2073 if (options.gss_authentication) {
2074 temporarily_use_uid(authctxt->pw);
2075 ssh_gssapi_storecreds();
2080 if (options.use_pam) {
2087 * In privilege separation, we fork another child and prepare
2088 * file descriptor passing.
2091 privsep_postauth(authctxt);
2092 /* the monitor process [priv] will not return */
2094 destroy_sensitive_data();
2097 packet_set_timeout(options.client_alive_interval,
2098 options.client_alive_count_max);
2100 /* Start session. */
2101 do_authenticated(authctxt);
2103 /* The connection has been terminated. */
2104 packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
2105 packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
2106 verbose("Transferred: sent %llu, received %llu bytes",
2107 (unsigned long long)obytes, (unsigned long long)ibytes);
2109 verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
2112 if (options.use_pam)
2114 #endif /* USE_PAM */
2116 #ifdef SSH_AUDIT_EVENTS
2117 PRIVSEP(audit_event(SSH_CONNECTION_CLOSE));
2129 * Decrypt session_key_int using our private server key and private host key
2130 * (key with larger modulus first).
2133 ssh1_session_key(BIGNUM *session_key_int)
2137 if (BN_cmp(sensitive_data.server_key->rsa->n,
2138 sensitive_data.ssh1_host_key->rsa->n) > 0) {
2139 /* Server key has bigger modulus. */
2140 if (BN_num_bits(sensitive_data.server_key->rsa->n) <
2141 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
2142 SSH_KEY_BITS_RESERVED) {
2143 fatal("do_connection: %s: "
2144 "server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
2145 get_remote_ipaddr(),
2146 BN_num_bits(sensitive_data.server_key->rsa->n),
2147 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2148 SSH_KEY_BITS_RESERVED);
2150 if (rsa_private_decrypt(session_key_int, session_key_int,
2151 sensitive_data.server_key->rsa) <= 0)
2153 if (rsa_private_decrypt(session_key_int, session_key_int,
2154 sensitive_data.ssh1_host_key->rsa) <= 0)
2157 /* Host key has bigger modulus (or they are equal). */
2158 if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
2159 BN_num_bits(sensitive_data.server_key->rsa->n) +
2160 SSH_KEY_BITS_RESERVED) {
2161 fatal("do_connection: %s: "
2162 "host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
2163 get_remote_ipaddr(),
2164 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2165 BN_num_bits(sensitive_data.server_key->rsa->n),
2166 SSH_KEY_BITS_RESERVED);
2168 if (rsa_private_decrypt(session_key_int, session_key_int,
2169 sensitive_data.ssh1_host_key->rsa) < 0)
2171 if (rsa_private_decrypt(session_key_int, session_key_int,
2172 sensitive_data.server_key->rsa) < 0)
2185 BIGNUM *session_key_int;
2186 u_char session_key[SSH_SESSION_KEY_LENGTH];
2188 u_int cipher_type, auth_mask, protocol_flags;
2191 * Generate check bytes that the client must send back in the user
2192 * packet in order for it to be accepted; this is used to defy ip
2193 * spoofing attacks. Note that this only works against somebody
2194 * doing IP spoofing from a remote machine; any machine on the local
2195 * network can still see outgoing packets and catch the random
2196 * cookie. This only affects rhosts authentication, and this is one
2197 * of the reasons why it is inherently insecure.
2199 arc4random_buf(cookie, sizeof(cookie));
2202 * Send our public key. We include in the packet 64 bits of random
2203 * data that must be matched in the reply in order to prevent IP
2206 packet_start(SSH_SMSG_PUBLIC_KEY);
2207 for (i = 0; i < 8; i++)
2208 packet_put_char(cookie[i]);
2210 /* Store our public server RSA key. */
2211 packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
2212 packet_put_bignum(sensitive_data.server_key->rsa->e);
2213 packet_put_bignum(sensitive_data.server_key->rsa->n);
2215 /* Store our public host RSA key. */
2216 packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2217 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
2218 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
2220 /* Put protocol flags. */
2221 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
2223 /* Declare which ciphers we support. */
2224 packet_put_int(cipher_mask_ssh1(0));
2226 /* Declare supported authentication types. */
2228 if (options.rhosts_rsa_authentication)
2229 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
2230 if (options.rsa_authentication)
2231 auth_mask |= 1 << SSH_AUTH_RSA;
2232 if (options.challenge_response_authentication == 1)
2233 auth_mask |= 1 << SSH_AUTH_TIS;
2234 if (options.password_authentication)
2235 auth_mask |= 1 << SSH_AUTH_PASSWORD;
2236 packet_put_int(auth_mask);
2238 /* Send the packet and wait for it to be sent. */
2240 packet_write_wait();
2242 debug("Sent %d bit server key and %d bit host key.",
2243 BN_num_bits(sensitive_data.server_key->rsa->n),
2244 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2246 /* Read clients reply (cipher type and session key). */
2247 packet_read_expect(SSH_CMSG_SESSION_KEY);
2249 /* Get cipher type and check whether we accept this. */
2250 cipher_type = packet_get_char();
2252 if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
2253 packet_disconnect("Warning: client selects unsupported cipher.");
2255 /* Get check bytes from the packet. These must match those we
2256 sent earlier with the public key packet. */
2257 for (i = 0; i < 8; i++)
2258 if (cookie[i] != packet_get_char())
2259 packet_disconnect("IP Spoofing check bytes do not match.");
2261 debug("Encryption type: %.200s", cipher_name(cipher_type));
2263 /* Get the encrypted integer. */
2264 if ((session_key_int = BN_new()) == NULL)
2265 fatal("do_ssh1_kex: BN_new failed");
2266 packet_get_bignum(session_key_int);
2268 protocol_flags = packet_get_int();
2269 packet_set_protocol_flags(protocol_flags);
2272 /* Decrypt session_key_int using host/server keys */
2273 rsafail = PRIVSEP(ssh1_session_key(session_key_int));
2276 * Extract session key from the decrypted integer. The key is in the
2277 * least significant 256 bits of the integer; the first byte of the
2278 * key is in the highest bits.
2281 (void) BN_mask_bits(session_key_int, sizeof(session_key) * 8);
2282 len = BN_num_bytes(session_key_int);
2283 if (len < 0 || (u_int)len > sizeof(session_key)) {
2284 error("do_ssh1_kex: bad session key len from %s: "
2285 "session_key_int %d > sizeof(session_key) %lu",
2286 get_remote_ipaddr(), len, (u_long)sizeof(session_key));
2289 memset(session_key, 0, sizeof(session_key));
2290 BN_bn2bin(session_key_int,
2291 session_key + sizeof(session_key) - len);
2293 derive_ssh1_session_id(
2294 sensitive_data.ssh1_host_key->rsa->n,
2295 sensitive_data.server_key->rsa->n,
2296 cookie, session_id);
2298 * Xor the first 16 bytes of the session key with the
2301 for (i = 0; i < 16; i++)
2302 session_key[i] ^= session_id[i];
2306 int bytes = BN_num_bytes(session_key_int);
2307 u_char *buf = xmalloc(bytes);
2310 logit("do_connection: generating a fake encryption key");
2311 BN_bn2bin(session_key_int, buf);
2313 MD5_Update(&md, buf, bytes);
2314 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2315 MD5_Final(session_key, &md);
2317 MD5_Update(&md, session_key, 16);
2318 MD5_Update(&md, buf, bytes);
2319 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2320 MD5_Final(session_key + 16, &md);
2321 memset(buf, 0, bytes);
2323 for (i = 0; i < 16; i++)
2324 session_id[i] = session_key[i] ^ session_key[i + 16];
2326 /* Destroy the private and public keys. No longer. */
2327 destroy_sensitive_data();
2330 mm_ssh1_session_id(session_id);
2332 /* Destroy the decrypted integer. It is no longer needed. */
2333 BN_clear_free(session_key_int);
2335 /* Set the session key. From this on all communications will be encrypted. */
2336 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
2338 /* Destroy our copy of the session key. It is no longer needed. */
2339 memset(session_key, 0, sizeof(session_key));
2341 debug("Received session key; encryption turned on.");
2343 /* Send an acknowledgment packet. Note that this packet is sent encrypted. */
2344 packet_start(SSH_SMSG_SUCCESS);
2346 packet_write_wait();
2350 * SSH2 key exchange: diffie-hellman-group1-sha1
2357 if (options.ciphers != NULL) {
2358 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2359 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
2360 #ifdef NONE_CIPHER_ENABLED
2361 } else if (options.none_enabled == 1) {
2362 debug ("WARNING: None cipher enabled");
2363 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2364 myproposal[PROPOSAL_ENC_ALGS_STOC] = KEX_ENCRYPT_INCLUDE_NONE;
2367 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2368 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
2369 myproposal[PROPOSAL_ENC_ALGS_STOC] =
2370 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
2372 if (options.macs != NULL) {
2373 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2374 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2376 if (options.compression == COMP_NONE) {
2377 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2378 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2379 } else if (options.compression == COMP_DELAYED) {
2380 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2381 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com";
2383 if (options.kex_algorithms != NULL)
2384 myproposal[PROPOSAL_KEX_ALGS] = options.kex_algorithms;
2386 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
2388 /* start key exchange */
2389 kex = kex_setup(myproposal);
2390 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2391 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
2392 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2393 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2394 kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
2396 kex->client_version_string=client_version_string;
2397 kex->server_version_string=server_version_string;
2398 kex->load_host_public_key=&get_hostkey_public_by_type;
2399 kex->load_host_private_key=&get_hostkey_private_by_type;
2400 kex->host_key_index=&get_hostkey_index;
2404 dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
2406 session_id2 = kex->session_id;
2407 session_id2_len = kex->session_id_len;
2410 /* send 1st encrypted/maced/compressed message */
2411 packet_start(SSH2_MSG_IGNORE);
2412 packet_put_cstring("markus");
2414 packet_write_wait();
2419 /* server specific fatal cleanup */
2424 do_cleanup(the_authctxt);
2425 if (use_privsep && privsep_is_preauth && pmonitor->m_pid > 1) {
2426 debug("Killing privsep child %d", pmonitor->m_pid);
2427 if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
2429 error("%s: kill(%d): %s", __func__,
2430 pmonitor->m_pid, strerror(errno));
2433 #ifdef SSH_AUDIT_EVENTS
2434 /* done after do_cleanup so it can cancel the PAM auth 'thread' */
2435 if (!use_privsep || mm_is_monitor())
2436 audit_event(SSH_CONNECTION_ABANDON);