1 /* $OpenBSD: sshd.c,v 1.420 2014/02/26 21:53:37 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.
48 #include <sys/types.h>
49 #include <sys/ioctl.h>
51 #include <sys/socket.h>
52 #ifdef HAVE_SYS_STAT_H
53 # include <sys/stat.h>
55 #ifdef HAVE_SYS_TIME_H
56 # include <sys/time.h>
58 #include "openbsd-compat/sys-tree.h"
59 #include "openbsd-compat/sys-queue.h"
77 #include <openssl/dh.h>
78 #include <openssl/bn.h>
79 #include <openssl/rand.h>
80 #include "openbsd-compat/openssl-compat.h"
82 #ifdef HAVE_SECUREWARE
83 #include <sys/security.h>
89 #if defined(GSSAPI) && defined(HAVE_GSSAPI_GSSAPI_H)
90 #include <gssapi/gssapi.h>
91 #elif defined(GSSAPI) && defined(HAVE_GSSAPI_H)
105 #include "servconf.h"
113 #include "myproposal.h"
114 #include "authfile.h"
115 #include "pathnames.h"
116 #include "atomicio.h"
117 #include "canohost.h"
118 #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 */
209 /* Daemon's agent connection */
210 AuthenticationConnection *auth_conn = NULL;
214 * Any really sensitive data in the application is contained in this
215 * structure. The idea is that this structure could be locked into memory so
216 * that the pages do not get written into swap. However, there are some
217 * problems. The private key contains BIGNUMs, and we do not (in principle)
218 * have access to the internals of them, and locking just the structure is
219 * not very useful. Currently, memory locking is not implemented.
222 Key *server_key; /* ephemeral server key */
223 Key *ssh1_host_key; /* ssh1 host key */
224 Key **host_keys; /* all private host keys */
225 Key **host_pubkeys; /* all public host keys */
226 Key **host_certificates; /* all public host certificates */
229 u_char ssh1_cookie[SSH_SESSION_KEY_LENGTH];
233 * Flag indicating whether the RSA server key needs to be regenerated.
234 * Is set in the SIGALRM handler and cleared when the key is regenerated.
236 static volatile sig_atomic_t key_do_regen = 0;
238 /* This is set to true when a signal is received. */
239 static volatile sig_atomic_t received_sighup = 0;
240 static volatile sig_atomic_t received_sigterm = 0;
242 /* session identifier, used by RSA-auth */
243 u_char session_id[16];
246 u_char *session_id2 = NULL;
247 u_int session_id2_len = 0;
249 /* record remote hostname or ip */
250 u_int utmp_len = MAXHOSTNAMELEN;
252 /* options.max_startup sized array of fd ints */
253 int *startup_pipes = NULL;
254 int startup_pipe; /* in child */
256 /* variables used for privilege separation */
257 int use_privsep = -1;
258 struct monitor *pmonitor = NULL;
259 int privsep_is_preauth = 1;
261 /* global authentication context */
262 Authctxt *the_authctxt = NULL;
264 /* sshd_config buffer */
267 /* message to be displayed after login */
270 /* Unprivileged user */
271 struct passwd *privsep_pw = NULL;
273 /* Prototypes for various functions defined later in this file. */
274 void destroy_sensitive_data(void);
275 void demote_sensitive_data(void);
277 static void do_ssh1_kex(void);
278 static void do_ssh2_kex(void);
281 * Close all listening sockets
284 close_listen_socks(void)
288 for (i = 0; i < num_listen_socks; i++)
289 close(listen_socks[i]);
290 num_listen_socks = -1;
294 close_startup_pipes(void)
299 for (i = 0; i < options.max_startups; i++)
300 if (startup_pipes[i] != -1)
301 close(startup_pipes[i]);
305 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
306 * the effect is to reread the configuration file (and to regenerate
312 sighup_handler(int sig)
314 int save_errno = errno;
317 signal(SIGHUP, sighup_handler);
322 * Called from the main program after receiving SIGHUP.
323 * Restarts the server.
328 logit("Received SIGHUP; restarting.");
329 platform_pre_restart();
330 close_listen_socks();
331 close_startup_pipes();
332 alarm(0); /* alarm timer persists across exec */
333 signal(SIGHUP, SIG_IGN); /* will be restored after exec */
334 execv(saved_argv[0], saved_argv);
335 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
341 * Generic signal handler for terminating signals in the master daemon.
345 sigterm_handler(int sig)
347 received_sigterm = sig;
351 * SIGCHLD handler. This is called whenever a child dies. This will then
352 * reap any zombies left by exited children.
356 main_sigchld_handler(int sig)
358 int save_errno = errno;
362 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
363 (pid < 0 && errno == EINTR))
366 signal(SIGCHLD, main_sigchld_handler);
371 * Signal handler for the alarm after the login grace period has expired.
375 grace_alarm_handler(int sig)
377 if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
378 kill(pmonitor->m_pid, SIGALRM);
381 * Try to kill any processes that we have spawned, E.g. authorized
382 * keys command helpers.
384 if (getpgid(0) == getpid()) {
385 signal(SIGTERM, SIG_IGN);
389 /* Log error and exit. */
390 sigdie("Timeout before authentication for %s", get_remote_ipaddr());
394 * Signal handler for the key regeneration alarm. Note that this
395 * alarm only occurs in the daemon waiting for connections, and it does not
396 * do anything with the private key or random state before forking.
397 * Thus there should be no concurrency control/asynchronous execution
401 generate_ephemeral_server_key(void)
403 verbose("Generating %s%d bit RSA key.",
404 sensitive_data.server_key ? "new " : "", options.server_key_bits);
405 if (sensitive_data.server_key != NULL)
406 key_free(sensitive_data.server_key);
407 sensitive_data.server_key = key_generate(KEY_RSA1,
408 options.server_key_bits);
409 verbose("RSA key generation complete.");
411 arc4random_buf(sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
416 key_regeneration_alarm(int sig)
418 int save_errno = errno;
420 signal(SIGALRM, SIG_DFL);
426 sshd_exchange_identification(int sock_in, int sock_out)
430 int remote_major, remote_minor;
432 char *s, *newline = "\n";
433 char buf[256]; /* Must not be larger than remote_version. */
434 char remote_version[256]; /* Must be at least as big as buf. */
436 if ((options.protocol & SSH_PROTO_1) &&
437 (options.protocol & SSH_PROTO_2)) {
438 major = PROTOCOL_MAJOR_1;
440 } else if (options.protocol & SSH_PROTO_2) {
441 major = PROTOCOL_MAJOR_2;
442 minor = PROTOCOL_MINOR_2;
445 major = PROTOCOL_MAJOR_1;
446 minor = PROTOCOL_MINOR_1;
449 xasprintf(&server_version_string, "SSH-%d.%d-%.100s%s%s%s",
450 major, minor, SSH_VERSION,
451 *options.version_addendum == '\0' ? "" : " ",
452 options.version_addendum, newline);
454 /* Send our protocol version identification. */
455 if (roaming_atomicio(vwrite, sock_out, server_version_string,
456 strlen(server_version_string))
457 != strlen(server_version_string)) {
458 logit("Could not write ident string to %s", get_remote_ipaddr());
462 /* Read other sides version identification. */
463 memset(buf, 0, sizeof(buf));
464 for (i = 0; i < sizeof(buf) - 1; i++) {
465 if (roaming_atomicio(read, sock_in, &buf[i], 1) != 1) {
466 logit("Did not receive identification string from %s",
467 get_remote_ipaddr());
470 if (buf[i] == '\r') {
472 /* Kludge for F-Secure Macintosh < 1.0.2 */
474 strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
478 if (buf[i] == '\n') {
483 buf[sizeof(buf) - 1] = 0;
484 client_version_string = xstrdup(buf);
487 * Check that the versions match. In future this might accept
488 * several versions and set appropriate flags to handle them.
490 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
491 &remote_major, &remote_minor, remote_version) != 3) {
492 s = "Protocol mismatch.\n";
493 (void) atomicio(vwrite, sock_out, s, strlen(s));
494 logit("Bad protocol version identification '%.100s' "
495 "from %s port %d", client_version_string,
496 get_remote_ipaddr(), get_remote_port());
501 debug("Client protocol version %d.%d; client software version %.100s",
502 remote_major, remote_minor, remote_version);
504 compat_datafellows(remote_version);
506 if ((datafellows & SSH_BUG_PROBE) != 0) {
507 logit("probed from %s with %s. Don't panic.",
508 get_remote_ipaddr(), client_version_string);
511 if ((datafellows & SSH_BUG_SCANNER) != 0) {
512 logit("scanned from %s with %s. Don't panic.",
513 get_remote_ipaddr(), client_version_string);
516 if ((datafellows & SSH_BUG_RSASIGMD5) != 0) {
517 logit("Client version \"%.100s\" uses unsafe RSA signature "
518 "scheme; disabling use of RSA keys", remote_version);
520 if ((datafellows & SSH_BUG_DERIVEKEY) != 0) {
521 fatal("Client version \"%.100s\" uses unsafe key agreement; "
522 "refusing connection", remote_version);
526 switch (remote_major) {
528 if (remote_minor == 99) {
529 if (options.protocol & SSH_PROTO_2)
535 if (!(options.protocol & SSH_PROTO_1)) {
539 if (remote_minor < 3) {
540 packet_disconnect("Your ssh version is too old and "
541 "is no longer supported. Please install a newer version.");
542 } else if (remote_minor == 3) {
543 /* note that this disables agent-forwarding */
548 if (options.protocol & SSH_PROTO_2) {
557 chop(server_version_string);
558 debug("Local version string %.200s", server_version_string);
561 s = "Protocol major versions differ.\n";
562 (void) atomicio(vwrite, sock_out, s, strlen(s));
565 logit("Protocol major versions differ for %s: %.200s vs. %.200s",
567 server_version_string, client_version_string);
572 /* Destroy the host and server keys. They will no longer be needed. */
574 destroy_sensitive_data(void)
578 if (sensitive_data.server_key) {
579 key_free(sensitive_data.server_key);
580 sensitive_data.server_key = NULL;
582 for (i = 0; i < options.num_host_key_files; i++) {
583 if (sensitive_data.host_keys[i]) {
584 key_free(sensitive_data.host_keys[i]);
585 sensitive_data.host_keys[i] = NULL;
587 if (sensitive_data.host_certificates[i]) {
588 key_free(sensitive_data.host_certificates[i]);
589 sensitive_data.host_certificates[i] = NULL;
592 sensitive_data.ssh1_host_key = NULL;
593 explicit_bzero(sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
596 /* Demote private to public keys for network child */
598 demote_sensitive_data(void)
603 if (sensitive_data.server_key) {
604 tmp = key_demote(sensitive_data.server_key);
605 key_free(sensitive_data.server_key);
606 sensitive_data.server_key = tmp;
609 for (i = 0; i < options.num_host_key_files; i++) {
610 if (sensitive_data.host_keys[i]) {
611 tmp = key_demote(sensitive_data.host_keys[i]);
612 key_free(sensitive_data.host_keys[i]);
613 sensitive_data.host_keys[i] = tmp;
614 if (tmp->type == KEY_RSA1)
615 sensitive_data.ssh1_host_key = tmp;
617 /* Certs do not need demotion */
620 /* We do not clear ssh1_host key and cookie. XXX - Okay Niels? */
624 privsep_preauth_child(void)
629 /* Enable challenge-response authentication for privilege separation */
630 privsep_challenge_enable();
633 /* Cache supported mechanism OIDs for later use */
634 if (options.gss_authentication)
635 ssh_gssapi_prepare_supported_oids();
639 arc4random_buf(rnd, sizeof(rnd));
640 RAND_seed(rnd, sizeof(rnd));
641 explicit_bzero(rnd, sizeof(rnd));
643 /* Demote the private keys to public keys. */
644 demote_sensitive_data();
646 /* Change our root directory */
647 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
648 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
650 if (chdir("/") == -1)
651 fatal("chdir(\"/\"): %s", strerror(errno));
653 /* Drop our privileges */
654 debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
655 (u_int)privsep_pw->pw_gid);
657 /* XXX not ready, too heavy after chroot */
658 do_setusercontext(privsep_pw);
660 gidset[0] = privsep_pw->pw_gid;
661 if (setgroups(1, gidset) < 0)
662 fatal("setgroups: %.100s", strerror(errno));
663 permanently_set_uid(privsep_pw);
668 privsep_preauth(Authctxt *authctxt)
672 struct ssh_sandbox *box = NULL;
674 /* Set up unprivileged child process to deal with network data */
675 pmonitor = monitor_init();
676 /* Store a pointer to the kex for later rekeying */
677 pmonitor->m_pkex = &xxx_kex;
679 if (use_privsep == PRIVSEP_ON)
680 box = ssh_sandbox_init(pmonitor);
683 fatal("fork of unprivileged child failed");
684 } else if (pid != 0) {
685 debug2("Network child is on pid %ld", (long)pid);
687 pmonitor->m_pid = pid;
689 auth_conn = ssh_get_authentication_connection();
691 ssh_sandbox_parent_preauth(box, pid);
692 monitor_child_preauth(authctxt, pmonitor);
695 monitor_sync(pmonitor);
697 /* Wait for the child's exit status */
698 while (waitpid(pid, &status, 0) < 0) {
701 pmonitor->m_pid = -1;
702 fatal("%s: waitpid: %s", __func__, strerror(errno));
704 privsep_is_preauth = 0;
705 pmonitor->m_pid = -1;
706 if (WIFEXITED(status)) {
707 if (WEXITSTATUS(status) != 0)
708 fatal("%s: preauth child exited with status %d",
709 __func__, WEXITSTATUS(status));
710 } else if (WIFSIGNALED(status))
711 fatal("%s: preauth child terminated by signal %d",
712 __func__, WTERMSIG(status));
714 ssh_sandbox_parent_finish(box);
718 close(pmonitor->m_sendfd);
719 close(pmonitor->m_log_recvfd);
721 /* Arrange for logging to be sent to the monitor */
722 set_log_handler(mm_log_handler, pmonitor);
724 /* Demote the child */
725 if (getuid() == 0 || geteuid() == 0)
726 privsep_preauth_child();
727 setproctitle("%s", "[net]");
729 ssh_sandbox_child(box);
736 privsep_postauth(Authctxt *authctxt)
740 #ifdef DISABLE_FD_PASSING
743 if (authctxt->pw->pw_uid == 0 || options.use_login) {
745 /* File descriptor passing is broken or root login */
750 /* New socket pair */
751 monitor_reinit(pmonitor);
753 pmonitor->m_pid = fork();
754 if (pmonitor->m_pid == -1)
755 fatal("fork of unprivileged child failed");
756 else if (pmonitor->m_pid != 0) {
757 verbose("User child is on pid %ld", (long)pmonitor->m_pid);
758 buffer_clear(&loginmsg);
759 monitor_child_postauth(pmonitor);
767 close(pmonitor->m_sendfd);
768 pmonitor->m_sendfd = -1;
770 /* Demote the private keys to public keys. */
771 demote_sensitive_data();
774 arc4random_buf(rnd, sizeof(rnd));
775 RAND_seed(rnd, sizeof(rnd));
776 explicit_bzero(rnd, sizeof(rnd));
778 /* Drop privileges */
779 do_setusercontext(authctxt->pw);
782 /* It is safe now to apply the key state */
783 monitor_apply_keystate(pmonitor);
786 * Tell the packet layer that authentication was successful, since
787 * this information is not part of the key state.
789 packet_set_authenticated();
793 list_hostkey_types(void)
802 for (i = 0; i < options.num_host_key_files; i++) {
803 key = sensitive_data.host_keys[i];
805 key = sensitive_data.host_pubkeys[i];
813 if (buffer_len(&b) > 0)
814 buffer_append(&b, ",", 1);
815 p = key_ssh_name(key);
816 buffer_append(&b, p, strlen(p));
819 /* If the private key has a cert peer, then list that too */
820 key = sensitive_data.host_certificates[i];
824 case KEY_RSA_CERT_V00:
825 case KEY_DSA_CERT_V00:
829 case KEY_ED25519_CERT:
830 if (buffer_len(&b) > 0)
831 buffer_append(&b, ",", 1);
832 p = key_ssh_name(key);
833 buffer_append(&b, p, strlen(p));
837 buffer_append(&b, "\0", 1);
838 ret = xstrdup(buffer_ptr(&b));
840 debug("list_hostkey_types: %s", ret);
845 get_hostkey_by_type(int type, int need_private)
850 for (i = 0; i < options.num_host_key_files; i++) {
852 case KEY_RSA_CERT_V00:
853 case KEY_DSA_CERT_V00:
857 case KEY_ED25519_CERT:
858 key = sensitive_data.host_certificates[i];
861 key = sensitive_data.host_keys[i];
862 if (key == NULL && !need_private)
863 key = sensitive_data.host_pubkeys[i];
866 if (key != NULL && key->type == type)
867 return need_private ?
868 sensitive_data.host_keys[i] : key;
874 get_hostkey_public_by_type(int type)
876 return get_hostkey_by_type(type, 0);
880 get_hostkey_private_by_type(int type)
882 return get_hostkey_by_type(type, 1);
886 get_hostkey_by_index(int ind)
888 if (ind < 0 || ind >= options.num_host_key_files)
890 return (sensitive_data.host_keys[ind]);
894 get_hostkey_public_by_index(int ind)
896 if (ind < 0 || ind >= options.num_host_key_files)
898 return (sensitive_data.host_pubkeys[ind]);
902 get_hostkey_index(Key *key)
906 for (i = 0; i < options.num_host_key_files; i++) {
907 if (key_is_cert(key)) {
908 if (key == sensitive_data.host_certificates[i])
911 if (key == sensitive_data.host_keys[i])
913 if (key == sensitive_data.host_pubkeys[i])
921 * returns 1 if connection should be dropped, 0 otherwise.
922 * dropping starts at connection #max_startups_begin with a probability
923 * of (max_startups_rate/100). the probability increases linearly until
924 * all connections are dropped for startups > max_startups
927 drop_connection(int startups)
931 if (startups < options.max_startups_begin)
933 if (startups >= options.max_startups)
935 if (options.max_startups_rate == 100)
938 p = 100 - options.max_startups_rate;
939 p *= startups - options.max_startups_begin;
940 p /= options.max_startups - options.max_startups_begin;
941 p += options.max_startups_rate;
942 r = arc4random_uniform(100);
944 debug("drop_connection: p %d, r %d", p, r);
945 return (r < p) ? 1 : 0;
951 if (options.version_addendum && *options.version_addendum != '\0')
952 fprintf(stderr, "%s %s, %s\n",
954 options.version_addendum, SSLeay_version(SSLEAY_VERSION));
956 fprintf(stderr, "%s, %s\n",
957 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
959 "usage: sshd [-46DdeiqTt] [-b bits] [-C connection_spec] [-c host_cert_file]\n"
960 " [-E log_file] [-f config_file] [-g login_grace_time]\n"
961 " [-h host_key_file] [-k key_gen_time] [-o option] [-p port]\n"
968 send_rexec_state(int fd, Buffer *conf)
972 debug3("%s: entering fd = %d config len %d", __func__, fd,
976 * Protocol from reexec master to child:
977 * string configuration
978 * u_int ephemeral_key_follows
979 * bignum e (only if ephemeral_key_follows == 1)
985 * string rngseed (only if OpenSSL is not self-seeded)
988 buffer_put_cstring(&m, buffer_ptr(conf));
990 if (sensitive_data.server_key != NULL &&
991 sensitive_data.server_key->type == KEY_RSA1) {
992 buffer_put_int(&m, 1);
993 buffer_put_bignum(&m, sensitive_data.server_key->rsa->e);
994 buffer_put_bignum(&m, sensitive_data.server_key->rsa->n);
995 buffer_put_bignum(&m, sensitive_data.server_key->rsa->d);
996 buffer_put_bignum(&m, sensitive_data.server_key->rsa->iqmp);
997 buffer_put_bignum(&m, sensitive_data.server_key->rsa->p);
998 buffer_put_bignum(&m, sensitive_data.server_key->rsa->q);
1000 buffer_put_int(&m, 0);
1002 #ifndef OPENSSL_PRNG_ONLY
1003 rexec_send_rng_seed(&m);
1006 if (ssh_msg_send(fd, 0, &m) == -1)
1007 fatal("%s: ssh_msg_send failed", __func__);
1011 debug3("%s: done", __func__);
1015 recv_rexec_state(int fd, Buffer *conf)
1021 debug3("%s: entering fd = %d", __func__, fd);
1025 if (ssh_msg_recv(fd, &m) == -1)
1026 fatal("%s: ssh_msg_recv failed", __func__);
1027 if (buffer_get_char(&m) != 0)
1028 fatal("%s: rexec version mismatch", __func__);
1030 cp = buffer_get_string(&m, &len);
1032 buffer_append(conf, cp, len + 1);
1035 if (buffer_get_int(&m)) {
1036 if (sensitive_data.server_key != NULL)
1037 key_free(sensitive_data.server_key);
1038 sensitive_data.server_key = key_new_private(KEY_RSA1);
1039 buffer_get_bignum(&m, sensitive_data.server_key->rsa->e);
1040 buffer_get_bignum(&m, sensitive_data.server_key->rsa->n);
1041 buffer_get_bignum(&m, sensitive_data.server_key->rsa->d);
1042 buffer_get_bignum(&m, sensitive_data.server_key->rsa->iqmp);
1043 buffer_get_bignum(&m, sensitive_data.server_key->rsa->p);
1044 buffer_get_bignum(&m, sensitive_data.server_key->rsa->q);
1045 rsa_generate_additional_parameters(
1046 sensitive_data.server_key->rsa);
1049 #ifndef OPENSSL_PRNG_ONLY
1050 rexec_recv_rng_seed(&m);
1055 debug3("%s: done", __func__);
1058 /* Accept a connection from inetd */
1060 server_accept_inetd(int *sock_in, int *sock_out)
1066 close(REEXEC_CONFIG_PASS_FD);
1067 *sock_in = *sock_out = dup(STDIN_FILENO);
1069 startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
1070 close(REEXEC_STARTUP_PIPE_FD);
1073 *sock_in = dup(STDIN_FILENO);
1074 *sock_out = dup(STDOUT_FILENO);
1077 * We intentionally do not close the descriptors 0, 1, and 2
1078 * as our code for setting the descriptors won't work if
1079 * ttyfd happens to be one of those.
1081 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1082 dup2(fd, STDIN_FILENO);
1083 dup2(fd, STDOUT_FILENO);
1085 dup2(fd, STDERR_FILENO);
1086 if (fd > (log_stderr ? STDERR_FILENO : STDOUT_FILENO))
1089 debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
1093 * Listen for TCP connections
1098 int ret, listen_sock, on = 1;
1099 struct addrinfo *ai;
1100 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1104 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
1105 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1107 if (num_listen_socks >= MAX_LISTEN_SOCKS)
1108 fatal("Too many listen sockets. "
1109 "Enlarge MAX_LISTEN_SOCKS");
1110 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1111 ntop, sizeof(ntop), strport, sizeof(strport),
1112 NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1113 error("getnameinfo failed: %.100s",
1114 ssh_gai_strerror(ret));
1117 /* Create socket for listening. */
1118 listen_sock = socket(ai->ai_family, ai->ai_socktype,
1120 if (listen_sock < 0) {
1121 /* kernel may not support ipv6 */
1122 verbose("socket: %.100s", strerror(errno));
1125 if (set_nonblock(listen_sock) == -1) {
1130 * Set socket options.
1131 * Allow local port reuse in TIME_WAIT.
1133 if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
1134 &on, sizeof(on)) == -1)
1135 error("setsockopt SO_REUSEADDR: %s", strerror(errno));
1137 /* Only communicate in IPv6 over AF_INET6 sockets. */
1138 if (ai->ai_family == AF_INET6)
1139 sock_set_v6only(listen_sock);
1141 debug("Bind to port %s on %s.", strport, ntop);
1143 len = sizeof(socksize);
1144 getsockopt(listen_sock, SOL_SOCKET, SO_RCVBUF, &socksize, &len);
1145 debug("Server TCP RWIN socket size: %d", socksize);
1147 /* Bind the socket to the desired port. */
1148 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1149 error("Bind to port %s on %s failed: %.200s.",
1150 strport, ntop, strerror(errno));
1154 listen_socks[num_listen_socks] = listen_sock;
1157 /* Start listening on the port. */
1158 if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1159 fatal("listen on [%s]:%s: %.100s",
1160 ntop, strport, strerror(errno));
1161 logit("Server listening on %s port %s.", ntop, strport);
1163 freeaddrinfo(options.listen_addrs);
1165 if (!num_listen_socks)
1166 fatal("Cannot bind any address.");
1170 * The main TCP accept loop. Note that, for the non-debug case, returns
1171 * from this function are in a forked subprocess.
1174 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1177 int i, j, ret, maxfd;
1178 int key_used = 0, startups = 0;
1179 int startup_p[2] = { -1 , -1 };
1180 struct sockaddr_storage from;
1185 /* setup fd set for accept */
1188 for (i = 0; i < num_listen_socks; i++)
1189 if (listen_socks[i] > maxfd)
1190 maxfd = listen_socks[i];
1191 /* pipes connected to unauthenticated childs */
1192 startup_pipes = xcalloc(options.max_startups, sizeof(int));
1193 for (i = 0; i < options.max_startups; i++)
1194 startup_pipes[i] = -1;
1197 * Stay listening for connections until the system crashes or
1198 * the daemon is killed with a signal.
1201 if (received_sighup)
1205 fdset = (fd_set *)xcalloc(howmany(maxfd + 1, NFDBITS),
1208 for (i = 0; i < num_listen_socks; i++)
1209 FD_SET(listen_socks[i], fdset);
1210 for (i = 0; i < options.max_startups; i++)
1211 if (startup_pipes[i] != -1)
1212 FD_SET(startup_pipes[i], fdset);
1214 /* Wait in select until there is a connection. */
1215 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1216 if (ret < 0 && errno != EINTR)
1217 error("select: %.100s", strerror(errno));
1218 if (received_sigterm) {
1219 logit("Received signal %d; terminating.",
1220 (int) received_sigterm);
1221 close_listen_socks();
1222 unlink(options.pid_file);
1223 exit(received_sigterm == SIGTERM ? 0 : 255);
1225 if (key_used && key_do_regen) {
1226 generate_ephemeral_server_key();
1233 for (i = 0; i < options.max_startups; i++)
1234 if (startup_pipes[i] != -1 &&
1235 FD_ISSET(startup_pipes[i], fdset)) {
1237 * the read end of the pipe is ready
1238 * if the child has closed the pipe
1239 * after successful authentication
1240 * or if the child has died
1242 close(startup_pipes[i]);
1243 startup_pipes[i] = -1;
1246 for (i = 0; i < num_listen_socks; i++) {
1247 if (!FD_ISSET(listen_socks[i], fdset))
1249 fromlen = sizeof(from);
1250 *newsock = accept(listen_socks[i],
1251 (struct sockaddr *)&from, &fromlen);
1253 if (errno != EINTR && errno != EWOULDBLOCK &&
1254 errno != ECONNABORTED && errno != EAGAIN)
1255 error("accept: %.100s",
1257 if (errno == EMFILE || errno == ENFILE)
1261 if (unset_nonblock(*newsock) == -1) {
1265 if (drop_connection(startups) == 1) {
1266 debug("drop connection #%d", startups);
1270 if (pipe(startup_p) == -1) {
1275 if (rexec_flag && socketpair(AF_UNIX,
1276 SOCK_STREAM, 0, config_s) == -1) {
1277 error("reexec socketpair: %s",
1280 close(startup_p[0]);
1281 close(startup_p[1]);
1285 for (j = 0; j < options.max_startups; j++)
1286 if (startup_pipes[j] == -1) {
1287 startup_pipes[j] = startup_p[0];
1288 if (maxfd < startup_p[0])
1289 maxfd = startup_p[0];
1295 * Got connection. Fork a child to handle it, unless
1296 * we are in debugging mode.
1300 * In debugging mode. Close the listening
1301 * socket, and start processing the
1302 * connection without forking.
1304 debug("Server will not fork when running in debugging mode.");
1305 close_listen_socks();
1306 *sock_in = *newsock;
1307 *sock_out = *newsock;
1308 close(startup_p[0]);
1309 close(startup_p[1]);
1313 send_rexec_state(config_s[0],
1321 * Normal production daemon. Fork, and have
1322 * the child process the connection. The
1323 * parent continues listening.
1325 platform_pre_fork();
1326 if ((pid = fork()) == 0) {
1328 * Child. Close the listening and
1329 * max_startup sockets. Start using
1330 * the accepted socket. Reinitialize
1331 * logging (since our pid has changed).
1332 * We break out of the loop to handle
1335 platform_post_fork_child();
1336 startup_pipe = startup_p[1];
1337 close_startup_pipes();
1338 close_listen_socks();
1339 *sock_in = *newsock;
1340 *sock_out = *newsock;
1341 log_init(__progname,
1343 options.log_facility,
1350 /* Parent. Stay in the loop. */
1351 platform_post_fork_parent(pid);
1353 error("fork: %.100s", strerror(errno));
1355 debug("Forked child %ld.", (long)pid);
1357 close(startup_p[1]);
1360 send_rexec_state(config_s[0], &cfg);
1366 * Mark that the key has been used (it
1367 * was "given" to the child).
1369 if ((options.protocol & SSH_PROTO_1) &&
1371 /* Schedule server key regeneration alarm. */
1372 signal(SIGALRM, key_regeneration_alarm);
1373 alarm(options.key_regeneration_time);
1380 * Ensure that our random state differs
1381 * from that of the child
1384 arc4random_buf(rnd, sizeof(rnd));
1385 RAND_seed(rnd, sizeof(rnd));
1386 explicit_bzero(rnd, sizeof(rnd));
1389 /* child process check (or debug mode) */
1390 if (num_listen_socks < 0)
1397 * Main program for the daemon.
1400 main(int ac, char **av)
1402 extern char *optarg;
1404 int opt, i, j, on = 1;
1405 int sock_in = -1, sock_out = -1, newsock = -1;
1406 const char *remote_ip;
1408 char *line, *logfile = NULL;
1409 int config_s[2] = { -1 , -1 };
1411 u_int64_t ibytes, obytes;
1417 struct connection_info *connection_info = get_connection_info(0, 0);
1419 #ifdef HAVE_SECUREWARE
1420 (void)set_auth_parameters(ac, av);
1422 __progname = ssh_get_progname(av[0]);
1424 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1427 saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1428 for (i = 0; i < ac; i++)
1429 saved_argv[i] = xstrdup(av[i]);
1430 saved_argv[i] = NULL;
1432 #ifndef HAVE_SETPROCTITLE
1433 /* Prepare for later setproctitle emulation */
1434 compat_init_setproctitle(ac, av);
1438 if (geteuid() == 0 && setgroups(0, NULL) == -1)
1439 debug("setgroups(): %.200s", strerror(errno));
1441 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1444 /* Initialize configuration options to their default values. */
1445 initialize_server_options(&options);
1447 /* Parse command-line arguments. */
1448 while ((opt = getopt(ac, av, "f:p:b:k:h:g:u:o:C:dDeE:iqrtQRT46")) != -1) {
1451 options.address_family = AF_INET;
1454 options.address_family = AF_INET6;
1457 config_file_name = optarg;
1460 if (options.num_host_cert_files >= MAX_HOSTCERTS) {
1461 fprintf(stderr, "too many host certificates.\n");
1464 options.host_cert_files[options.num_host_cert_files++] =
1465 derelativise_path(optarg);
1468 if (debug_flag == 0) {
1470 options.log_level = SYSLOG_LEVEL_DEBUG1;
1471 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1472 options.log_level++;
1478 logfile = xstrdup(optarg);
1497 options.log_level = SYSLOG_LEVEL_QUIET;
1500 options.server_key_bits = (int)strtonum(optarg, 256,
1504 options.ports_from_cmdline = 1;
1505 if (options.num_ports >= MAX_PORTS) {
1506 fprintf(stderr, "too many ports.\n");
1509 options.ports[options.num_ports++] = a2port(optarg);
1510 if (options.ports[options.num_ports-1] <= 0) {
1511 fprintf(stderr, "Bad port number.\n");
1516 if ((options.login_grace_time = convtime(optarg)) == -1) {
1517 fprintf(stderr, "Invalid login grace time.\n");
1522 if ((options.key_regeneration_time = convtime(optarg)) == -1) {
1523 fprintf(stderr, "Invalid key regeneration interval.\n");
1528 if (options.num_host_key_files >= MAX_HOSTKEYS) {
1529 fprintf(stderr, "too many host keys.\n");
1532 options.host_key_files[options.num_host_key_files++] =
1533 derelativise_path(optarg);
1542 if (parse_server_match_testspec(connection_info,
1547 utmp_len = (u_int)strtonum(optarg, 0, MAXHOSTNAMELEN+1, NULL);
1548 if (utmp_len > MAXHOSTNAMELEN) {
1549 fprintf(stderr, "Invalid utmp length.\n");
1554 line = xstrdup(optarg);
1555 if (process_server_config_line(&options, line,
1556 "command-line", 0, NULL, NULL) != 0)
1566 if (rexeced_flag || inetd_flag)
1568 if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1569 fatal("sshd re-exec requires execution with an absolute path");
1571 closefrom(REEXEC_MIN_FREE_FD);
1573 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1575 OpenSSL_add_all_algorithms();
1577 /* If requested, redirect the logs to the specified logfile. */
1578 if (logfile != NULL) {
1579 log_redirect_stderr_to(logfile);
1583 * Force logging to stderr until we have loaded the private host
1584 * key (unless started from inetd)
1586 log_init(__progname,
1587 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1588 SYSLOG_LEVEL_INFO : options.log_level,
1589 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1590 SYSLOG_FACILITY_AUTH : options.log_facility,
1591 log_stderr || !inetd_flag);
1594 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1595 * root's environment
1597 if (getenv("KRB5CCNAME") != NULL)
1598 (void) unsetenv("KRB5CCNAME");
1601 /* Cray can define user privs drop all privs now!
1602 * Not needed on PRIV_SU systems!
1607 sensitive_data.server_key = NULL;
1608 sensitive_data.ssh1_host_key = NULL;
1609 sensitive_data.have_ssh1_key = 0;
1610 sensitive_data.have_ssh2_key = 0;
1613 * If we're doing an extended config test, make sure we have all of
1614 * the parameters we need. If we're not doing an extended test,
1615 * do not silently ignore connection test params.
1617 if (test_flag >= 2 && server_match_spec_complete(connection_info) == 0)
1618 fatal("user, host and addr are all required when testing "
1620 if (test_flag < 2 && server_match_spec_complete(connection_info) >= 0)
1621 fatal("Config test connection parameter (-C) provided without "
1624 /* Fetch our configuration */
1627 recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1629 load_server_config(config_file_name, &cfg);
1631 parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1636 /* Fill in default values for those options not explicitly set. */
1637 fill_default_server_options(&options);
1639 /* challenge-response is implemented via keyboard interactive */
1640 if (options.challenge_response_authentication)
1641 options.kbd_interactive_authentication = 1;
1643 /* Check that options are sensible */
1644 if (options.authorized_keys_command_user == NULL &&
1645 (options.authorized_keys_command != NULL &&
1646 strcasecmp(options.authorized_keys_command, "none") != 0))
1647 fatal("AuthorizedKeysCommand set without "
1648 "AuthorizedKeysCommandUser");
1651 * Check whether there is any path through configured auth methods.
1652 * Unfortunately it is not possible to verify this generally before
1653 * daemonisation in the presence of Match block, but this catches
1654 * and warns for trivial misconfigurations that could break login.
1656 if (options.num_auth_methods != 0) {
1657 if ((options.protocol & SSH_PROTO_1))
1658 fatal("AuthenticationMethods is not supported with "
1660 for (n = 0; n < options.num_auth_methods; n++) {
1661 if (auth2_methods_valid(options.auth_methods[n],
1665 if (n >= options.num_auth_methods)
1666 fatal("AuthenticationMethods cannot be satisfied by "
1667 "enabled authentication methods");
1670 /* set default channel AF */
1671 channel_set_af(options.address_family);
1673 /* Check that there are no remaining arguments. */
1675 fprintf(stderr, "Extra argument %s.\n", av[optind]);
1679 debug("sshd version %s, %s", SSH_VERSION,
1680 SSLeay_version(SSLEAY_VERSION));
1682 /* Store privilege separation user for later use if required. */
1683 if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1684 if (use_privsep || options.kerberos_authentication)
1685 fatal("Privilege separation user %s does not exist",
1688 explicit_bzero(privsep_pw->pw_passwd,
1689 strlen(privsep_pw->pw_passwd));
1690 privsep_pw = pwcopy(privsep_pw);
1691 free(privsep_pw->pw_passwd);
1692 privsep_pw->pw_passwd = xstrdup("*");
1696 /* load host keys */
1697 sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1699 sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
1701 for (i = 0; i < options.num_host_key_files; i++) {
1702 sensitive_data.host_keys[i] = NULL;
1703 sensitive_data.host_pubkeys[i] = NULL;
1706 if (options.host_key_agent) {
1707 if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
1708 setenv(SSH_AUTHSOCKET_ENV_NAME,
1709 options.host_key_agent, 1);
1710 have_agent = ssh_agent_present();
1713 for (i = 0; i < options.num_host_key_files; i++) {
1714 key = key_load_private(options.host_key_files[i], "", NULL);
1715 pubkey = key_load_public(options.host_key_files[i], NULL);
1716 sensitive_data.host_keys[i] = key;
1717 sensitive_data.host_pubkeys[i] = pubkey;
1719 if (key == NULL && pubkey != NULL && pubkey->type != KEY_RSA1 &&
1721 debug("will rely on agent for hostkey %s",
1722 options.host_key_files[i]);
1723 keytype = pubkey->type;
1724 } else if (key != NULL) {
1725 keytype = key->type;
1727 error("Could not load host key: %s",
1728 options.host_key_files[i]);
1729 sensitive_data.host_keys[i] = NULL;
1730 sensitive_data.host_pubkeys[i] = NULL;
1736 sensitive_data.ssh1_host_key = key;
1737 sensitive_data.have_ssh1_key = 1;
1743 sensitive_data.have_ssh2_key = 1;
1746 debug("private host key: #%d type %d %s", i, keytype,
1747 key_type(key ? key : pubkey));
1749 if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1750 logit("Disabling protocol version 1. Could not load host key");
1751 options.protocol &= ~SSH_PROTO_1;
1753 if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1754 logit("Disabling protocol version 2. Could not load host key");
1755 options.protocol &= ~SSH_PROTO_2;
1757 if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1758 logit("sshd: no hostkeys available -- exiting.");
1763 * Load certificates. They are stored in an array at identical
1764 * indices to the public keys that they relate to.
1766 sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
1768 for (i = 0; i < options.num_host_key_files; i++)
1769 sensitive_data.host_certificates[i] = NULL;
1771 for (i = 0; i < options.num_host_cert_files; i++) {
1772 key = key_load_public(options.host_cert_files[i], NULL);
1774 error("Could not load host certificate: %s",
1775 options.host_cert_files[i]);
1778 if (!key_is_cert(key)) {
1779 error("Certificate file is not a certificate: %s",
1780 options.host_cert_files[i]);
1784 /* Find matching private key */
1785 for (j = 0; j < options.num_host_key_files; j++) {
1786 if (key_equal_public(key,
1787 sensitive_data.host_keys[j])) {
1788 sensitive_data.host_certificates[j] = key;
1792 if (j >= options.num_host_key_files) {
1793 error("No matching private key for certificate: %s",
1794 options.host_cert_files[i]);
1798 sensitive_data.host_certificates[j] = key;
1799 debug("host certificate: #%d type %d %s", j, key->type,
1802 /* Check certain values for sanity. */
1803 if (options.protocol & SSH_PROTO_1) {
1804 if (options.server_key_bits < 512 ||
1805 options.server_key_bits > 32768) {
1806 fprintf(stderr, "Bad server key size.\n");
1810 * Check that server and host key lengths differ sufficiently. This
1811 * is necessary to make double encryption work with rsaref. Oh, I
1812 * hate software patents. I dont know if this can go? Niels
1814 if (options.server_key_bits >
1815 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
1816 SSH_KEY_BITS_RESERVED && options.server_key_bits <
1817 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1818 SSH_KEY_BITS_RESERVED) {
1819 options.server_key_bits =
1820 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1821 SSH_KEY_BITS_RESERVED;
1822 debug("Forcing server key to %d bits to make it differ from host key.",
1823 options.server_key_bits);
1830 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1831 (S_ISDIR(st.st_mode) == 0))
1832 fatal("Missing privilege separation directory: %s",
1833 _PATH_PRIVSEP_CHROOT_DIR);
1836 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1837 (st.st_uid != getuid () ||
1838 (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1840 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1842 fatal("%s must be owned by root and not group or "
1843 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1846 if (test_flag > 1) {
1847 if (server_match_spec_complete(connection_info) == 1)
1848 parse_server_match_config(&options, connection_info);
1849 dump_config(&options);
1852 /* Configuration looks good, so exit if in test mode. */
1857 * Clear out any supplemental groups we may have inherited. This
1858 * prevents inadvertent creation of files with bad modes (in the
1859 * portable version at least, it's certainly possible for PAM
1860 * to create a file, and we can't control the code in every
1861 * module which might be used).
1863 if (setgroups(0, NULL) < 0)
1864 debug("setgroups() failed: %.200s", strerror(errno));
1867 rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1868 for (i = 0; i < rexec_argc; i++) {
1869 debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1870 rexec_argv[i] = saved_argv[i];
1872 rexec_argv[rexec_argc] = "-R";
1873 rexec_argv[rexec_argc + 1] = NULL;
1876 /* Ensure that umask disallows at least group and world write */
1877 new_umask = umask(0077) | 0022;
1878 (void) umask(new_umask);
1880 /* Initialize the log (it is reinitialized below in case we forked). */
1881 if (debug_flag && (!inetd_flag || rexeced_flag))
1883 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1886 * If not in debugging mode, and not started from inetd, disconnect
1887 * from the controlling terminal, and fork. The original process
1890 if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1893 #endif /* TIOCNOTTY */
1894 if (daemon(0, 0) < 0)
1895 fatal("daemon() failed: %.200s", strerror(errno));
1897 /* Disconnect from the controlling tty. */
1899 fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1901 (void) ioctl(fd, TIOCNOTTY, NULL);
1904 #endif /* TIOCNOTTY */
1906 /* Reinitialize the log (because of the fork above). */
1907 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1909 /* Avoid killing the process in high-pressure swapping environments. */
1910 if (!inetd_flag && madvise(NULL, 0, MADV_PROTECT) != 0)
1911 debug("madvise(): %.200s", strerror(errno));
1913 /* Chdir to the root directory so that the current disk can be
1914 unmounted if desired. */
1915 if (chdir("/") == -1)
1916 error("chdir(\"/\"): %s", strerror(errno));
1918 /* ignore SIGPIPE */
1919 signal(SIGPIPE, SIG_IGN);
1921 /* Get a connection, either from inetd or a listening TCP socket */
1923 server_accept_inetd(&sock_in, &sock_out);
1925 platform_pre_listen();
1928 if (options.protocol & SSH_PROTO_1)
1929 generate_ephemeral_server_key();
1931 signal(SIGHUP, sighup_handler);
1932 signal(SIGCHLD, main_sigchld_handler);
1933 signal(SIGTERM, sigterm_handler);
1934 signal(SIGQUIT, sigterm_handler);
1937 * Write out the pid file after the sigterm handler
1938 * is setup and the listen sockets are bound
1941 FILE *f = fopen(options.pid_file, "w");
1944 error("Couldn't create pid file \"%s\": %s",
1945 options.pid_file, strerror(errno));
1947 fprintf(f, "%ld\n", (long) getpid());
1952 /* Accept a connection and return in a forked child */
1953 server_accept_loop(&sock_in, &sock_out,
1954 &newsock, config_s);
1957 /* This is the child processing a new connection. */
1958 setproctitle("%s", "[accepted]");
1961 * Create a new session and process group since the 4.4BSD
1962 * setlogin() affects the entire process group. We don't
1963 * want the child to be able to affect the parent.
1965 #if !defined(SSHD_ACQUIRES_CTTY)
1967 * If setsid is called, on some platforms sshd will later acquire a
1968 * controlling terminal which will result in "could not set
1969 * controlling tty" errors.
1971 if (!debug_flag && !inetd_flag && setsid() < 0)
1972 error("setsid: %.100s", strerror(errno));
1978 debug("rexec start in %d out %d newsock %d pipe %d sock %d",
1979 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1980 dup2(newsock, STDIN_FILENO);
1981 dup2(STDIN_FILENO, STDOUT_FILENO);
1982 if (startup_pipe == -1)
1983 close(REEXEC_STARTUP_PIPE_FD);
1984 else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) {
1985 dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
1986 close(startup_pipe);
1987 startup_pipe = REEXEC_STARTUP_PIPE_FD;
1990 dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1993 execv(rexec_argv[0], rexec_argv);
1995 /* Reexec has failed, fall back and continue */
1996 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1997 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1998 log_init(__progname, options.log_level,
1999 options.log_facility, log_stderr);
2002 close(REEXEC_CONFIG_PASS_FD);
2003 newsock = sock_out = sock_in = dup(STDIN_FILENO);
2004 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
2005 dup2(fd, STDIN_FILENO);
2006 dup2(fd, STDOUT_FILENO);
2007 if (fd > STDERR_FILENO)
2010 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
2011 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
2014 /* Executed child processes don't need these. */
2015 fcntl(sock_out, F_SETFD, FD_CLOEXEC);
2016 fcntl(sock_in, F_SETFD, FD_CLOEXEC);
2019 * Disable the key regeneration alarm. We will not regenerate the
2020 * key since we are no longer in a position to give it to anyone. We
2021 * will not restart on SIGHUP since it no longer makes sense.
2024 signal(SIGALRM, SIG_DFL);
2025 signal(SIGHUP, SIG_DFL);
2026 signal(SIGTERM, SIG_DFL);
2027 signal(SIGQUIT, SIG_DFL);
2028 signal(SIGCHLD, SIG_DFL);
2029 signal(SIGINT, SIG_DFL);
2033 * Initialize the resolver. This may not happen automatically
2034 * before privsep chroot().
2036 if ((_res.options & RES_INIT) == 0) {
2037 debug("res_init()");
2042 * Force GSS-API to parse its configuration and load any
2043 * mechanism plugins.
2047 OM_uint32 minor_status;
2048 gss_indicate_mechs(&minor_status, &mechs);
2049 gss_release_oid_set(&minor_status, &mechs);
2055 * Register our connection. This turns encryption off because we do
2058 packet_set_connection(sock_in, sock_out);
2059 packet_set_server();
2061 /* Set SO_KEEPALIVE if requested. */
2062 if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
2063 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
2064 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
2066 if ((remote_port = get_remote_port()) < 0) {
2067 debug("get_remote_port failed");
2072 * We use get_canonical_hostname with usedns = 0 instead of
2073 * get_remote_ipaddr here so IP options will be checked.
2075 (void) get_canonical_hostname(0);
2077 * The rest of the code depends on the fact that
2078 * get_remote_ipaddr() caches the remote ip, even if
2079 * the socket goes away.
2081 remote_ip = get_remote_ipaddr();
2083 #ifdef SSH_AUDIT_EVENTS
2084 audit_connection_from(remote_ip, remote_port);
2087 allow_severity = options.log_facility|LOG_INFO;
2088 deny_severity = options.log_facility|LOG_WARNING;
2089 /* Check whether logins are denied from this host. */
2090 if (packet_connection_is_on_socket()) {
2091 struct request_info req;
2093 request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
2096 if (!hosts_access(&req)) {
2097 debug("Connection refused by tcp wrapper");
2100 fatal("libwrap refuse returns");
2103 #endif /* LIBWRAP */
2105 /* Log the connection. */
2106 verbose("Connection from %s port %d on %s port %d",
2107 remote_ip, remote_port,
2108 get_local_ipaddr(sock_in), get_local_port());
2111 * We don't want to listen forever unless the other side
2112 * successfully authenticates itself. So we set up an alarm which is
2113 * cleared after successful authentication. A limit of zero
2114 * indicates no limit. Note that we don't set the alarm in debugging
2115 * mode; it is just annoying to have the server exit just when you
2116 * are about to discover the bug.
2118 signal(SIGALRM, grace_alarm_handler);
2120 alarm(options.login_grace_time);
2122 sshd_exchange_identification(sock_in, sock_out);
2124 /* In inetd mode, generate ephemeral key only for proto 1 connections */
2125 if (!compat20 && inetd_flag && sensitive_data.server_key == NULL)
2126 generate_ephemeral_server_key();
2128 packet_set_nonblocking();
2130 /* allocate authentication context */
2131 authctxt = xcalloc(1, sizeof(*authctxt));
2133 authctxt->loginmsg = &loginmsg;
2135 /* XXX global for cleanup, access from other modules */
2136 the_authctxt = authctxt;
2138 /* prepare buffer to collect messages to display to user after login */
2139 buffer_init(&loginmsg);
2143 if (privsep_preauth(authctxt) == 1)
2145 } else if (compat20 && have_agent)
2146 auth_conn = ssh_get_authentication_connection();
2148 /* perform the key exchange */
2149 /* authenticate user and start session */
2152 do_authentication2(authctxt);
2155 do_authentication(authctxt);
2158 * If we use privilege separation, the unprivileged child transfers
2159 * the current keystate and exits
2162 mm_send_keystate(pmonitor);
2168 * Cancel the alarm we set to limit the time taken for
2172 signal(SIGALRM, SIG_DFL);
2173 authctxt->authenticated = 1;
2174 if (startup_pipe != -1) {
2175 close(startup_pipe);
2179 #ifdef SSH_AUDIT_EVENTS
2180 audit_event(SSH_AUTH_SUCCESS);
2184 if (options.gss_authentication) {
2185 temporarily_use_uid(authctxt->pw);
2186 ssh_gssapi_storecreds();
2191 if (options.use_pam) {
2198 * In privilege separation, we fork another child and prepare
2199 * file descriptor passing.
2202 privsep_postauth(authctxt);
2203 /* the monitor process [priv] will not return */
2205 destroy_sensitive_data();
2208 packet_set_timeout(options.client_alive_interval,
2209 options.client_alive_count_max);
2211 /* Start session. */
2212 do_authenticated(authctxt);
2214 /* The connection has been terminated. */
2215 packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
2216 packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
2217 verbose("Transferred: sent %llu, received %llu bytes",
2218 (unsigned long long)obytes, (unsigned long long)ibytes);
2220 verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
2223 if (options.use_pam)
2225 #endif /* USE_PAM */
2227 #ifdef SSH_AUDIT_EVENTS
2228 PRIVSEP(audit_event(SSH_CONNECTION_CLOSE));
2240 * Decrypt session_key_int using our private server key and private host key
2241 * (key with larger modulus first).
2244 ssh1_session_key(BIGNUM *session_key_int)
2248 if (BN_cmp(sensitive_data.server_key->rsa->n,
2249 sensitive_data.ssh1_host_key->rsa->n) > 0) {
2250 /* Server key has bigger modulus. */
2251 if (BN_num_bits(sensitive_data.server_key->rsa->n) <
2252 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
2253 SSH_KEY_BITS_RESERVED) {
2254 fatal("do_connection: %s: "
2255 "server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
2256 get_remote_ipaddr(),
2257 BN_num_bits(sensitive_data.server_key->rsa->n),
2258 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2259 SSH_KEY_BITS_RESERVED);
2261 if (rsa_private_decrypt(session_key_int, session_key_int,
2262 sensitive_data.server_key->rsa) <= 0)
2264 if (rsa_private_decrypt(session_key_int, session_key_int,
2265 sensitive_data.ssh1_host_key->rsa) <= 0)
2268 /* Host key has bigger modulus (or they are equal). */
2269 if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
2270 BN_num_bits(sensitive_data.server_key->rsa->n) +
2271 SSH_KEY_BITS_RESERVED) {
2272 fatal("do_connection: %s: "
2273 "host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
2274 get_remote_ipaddr(),
2275 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2276 BN_num_bits(sensitive_data.server_key->rsa->n),
2277 SSH_KEY_BITS_RESERVED);
2279 if (rsa_private_decrypt(session_key_int, session_key_int,
2280 sensitive_data.ssh1_host_key->rsa) < 0)
2282 if (rsa_private_decrypt(session_key_int, session_key_int,
2283 sensitive_data.server_key->rsa) < 0)
2296 BIGNUM *session_key_int;
2297 u_char session_key[SSH_SESSION_KEY_LENGTH];
2299 u_int cipher_type, auth_mask, protocol_flags;
2302 * Generate check bytes that the client must send back in the user
2303 * packet in order for it to be accepted; this is used to defy ip
2304 * spoofing attacks. Note that this only works against somebody
2305 * doing IP spoofing from a remote machine; any machine on the local
2306 * network can still see outgoing packets and catch the random
2307 * cookie. This only affects rhosts authentication, and this is one
2308 * of the reasons why it is inherently insecure.
2310 arc4random_buf(cookie, sizeof(cookie));
2313 * Send our public key. We include in the packet 64 bits of random
2314 * data that must be matched in the reply in order to prevent IP
2317 packet_start(SSH_SMSG_PUBLIC_KEY);
2318 for (i = 0; i < 8; i++)
2319 packet_put_char(cookie[i]);
2321 /* Store our public server RSA key. */
2322 packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
2323 packet_put_bignum(sensitive_data.server_key->rsa->e);
2324 packet_put_bignum(sensitive_data.server_key->rsa->n);
2326 /* Store our public host RSA key. */
2327 packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2328 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
2329 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
2331 /* Put protocol flags. */
2332 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
2334 /* Declare which ciphers we support. */
2335 packet_put_int(cipher_mask_ssh1(0));
2337 /* Declare supported authentication types. */
2339 if (options.rhosts_rsa_authentication)
2340 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
2341 if (options.rsa_authentication)
2342 auth_mask |= 1 << SSH_AUTH_RSA;
2343 if (options.challenge_response_authentication == 1)
2344 auth_mask |= 1 << SSH_AUTH_TIS;
2345 if (options.password_authentication)
2346 auth_mask |= 1 << SSH_AUTH_PASSWORD;
2347 packet_put_int(auth_mask);
2349 /* Send the packet and wait for it to be sent. */
2351 packet_write_wait();
2353 debug("Sent %d bit server key and %d bit host key.",
2354 BN_num_bits(sensitive_data.server_key->rsa->n),
2355 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2357 /* Read clients reply (cipher type and session key). */
2358 packet_read_expect(SSH_CMSG_SESSION_KEY);
2360 /* Get cipher type and check whether we accept this. */
2361 cipher_type = packet_get_char();
2363 if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
2364 packet_disconnect("Warning: client selects unsupported cipher.");
2366 /* Get check bytes from the packet. These must match those we
2367 sent earlier with the public key packet. */
2368 for (i = 0; i < 8; i++)
2369 if (cookie[i] != packet_get_char())
2370 packet_disconnect("IP Spoofing check bytes do not match.");
2372 debug("Encryption type: %.200s", cipher_name(cipher_type));
2374 /* Get the encrypted integer. */
2375 if ((session_key_int = BN_new()) == NULL)
2376 fatal("do_ssh1_kex: BN_new failed");
2377 packet_get_bignum(session_key_int);
2379 protocol_flags = packet_get_int();
2380 packet_set_protocol_flags(protocol_flags);
2383 /* Decrypt session_key_int using host/server keys */
2384 rsafail = PRIVSEP(ssh1_session_key(session_key_int));
2387 * Extract session key from the decrypted integer. The key is in the
2388 * least significant 256 bits of the integer; the first byte of the
2389 * key is in the highest bits.
2392 (void) BN_mask_bits(session_key_int, sizeof(session_key) * 8);
2393 len = BN_num_bytes(session_key_int);
2394 if (len < 0 || (u_int)len > sizeof(session_key)) {
2395 error("do_ssh1_kex: bad session key len from %s: "
2396 "session_key_int %d > sizeof(session_key) %lu",
2397 get_remote_ipaddr(), len, (u_long)sizeof(session_key));
2400 explicit_bzero(session_key, sizeof(session_key));
2401 BN_bn2bin(session_key_int,
2402 session_key + sizeof(session_key) - len);
2404 derive_ssh1_session_id(
2405 sensitive_data.ssh1_host_key->rsa->n,
2406 sensitive_data.server_key->rsa->n,
2407 cookie, session_id);
2409 * Xor the first 16 bytes of the session key with the
2412 for (i = 0; i < 16; i++)
2413 session_key[i] ^= session_id[i];
2417 int bytes = BN_num_bytes(session_key_int);
2418 u_char *buf = xmalloc(bytes);
2419 struct ssh_digest_ctx *md;
2421 logit("do_connection: generating a fake encryption key");
2422 BN_bn2bin(session_key_int, buf);
2423 if ((md = ssh_digest_start(SSH_DIGEST_MD5)) == NULL ||
2424 ssh_digest_update(md, buf, bytes) < 0 ||
2425 ssh_digest_update(md, sensitive_data.ssh1_cookie,
2426 SSH_SESSION_KEY_LENGTH) < 0 ||
2427 ssh_digest_final(md, session_key, sizeof(session_key)) < 0)
2428 fatal("%s: md5 failed", __func__);
2429 ssh_digest_free(md);
2430 if ((md = ssh_digest_start(SSH_DIGEST_MD5)) == NULL ||
2431 ssh_digest_update(md, session_key, 16) < 0 ||
2432 ssh_digest_update(md, sensitive_data.ssh1_cookie,
2433 SSH_SESSION_KEY_LENGTH) < 0 ||
2434 ssh_digest_final(md, session_key + 16,
2435 sizeof(session_key) - 16) < 0)
2436 fatal("%s: md5 failed", __func__);
2437 ssh_digest_free(md);
2438 explicit_bzero(buf, bytes);
2440 for (i = 0; i < 16; i++)
2441 session_id[i] = session_key[i] ^ session_key[i + 16];
2443 /* Destroy the private and public keys. No longer. */
2444 destroy_sensitive_data();
2447 mm_ssh1_session_id(session_id);
2449 /* Destroy the decrypted integer. It is no longer needed. */
2450 BN_clear_free(session_key_int);
2452 /* Set the session key. From this on all communications will be encrypted. */
2453 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
2455 /* Destroy our copy of the session key. It is no longer needed. */
2456 explicit_bzero(session_key, sizeof(session_key));
2458 debug("Received session key; encryption turned on.");
2460 /* Send an acknowledgment packet. Note that this packet is sent encrypted. */
2461 packet_start(SSH_SMSG_SUCCESS);
2463 packet_write_wait();
2467 sshd_hostkey_sign(Key *privkey, Key *pubkey, u_char **signature, u_int *slen,
2468 u_char *data, u_int dlen)
2471 if (PRIVSEP(key_sign(privkey, signature, slen, data, dlen) < 0))
2472 fatal("%s: key_sign failed", __func__);
2473 } else if (use_privsep) {
2474 if (mm_key_sign(pubkey, signature, slen, data, dlen) < 0)
2475 fatal("%s: pubkey_sign failed", __func__);
2477 if (ssh_agent_sign(auth_conn, pubkey, signature, slen, data,
2479 fatal("%s: ssh_agent_sign failed", __func__);
2484 * SSH2 key exchange: diffie-hellman-group1-sha1
2491 if (options.ciphers != NULL) {
2492 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2493 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
2495 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2496 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
2497 myproposal[PROPOSAL_ENC_ALGS_STOC] =
2498 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
2500 if (options.macs != NULL) {
2501 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2502 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2504 if (options.compression == COMP_NONE) {
2505 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2506 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2507 } else if (options.compression == COMP_DELAYED) {
2508 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2509 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com";
2511 if (options.kex_algorithms != NULL)
2512 myproposal[PROPOSAL_KEX_ALGS] = options.kex_algorithms;
2514 myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(
2515 myproposal[PROPOSAL_KEX_ALGS]);
2517 if (options.rekey_limit || options.rekey_interval)
2518 packet_set_rekey_limits((u_int32_t)options.rekey_limit,
2519 (time_t)options.rekey_interval);
2521 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal(
2522 list_hostkey_types());
2524 /* start key exchange */
2525 kex = kex_setup(myproposal);
2526 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2527 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
2528 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2529 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2530 kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
2531 kex->kex[KEX_C25519_SHA256] = kexc25519_server;
2533 kex->client_version_string=client_version_string;
2534 kex->server_version_string=server_version_string;
2535 kex->load_host_public_key=&get_hostkey_public_by_type;
2536 kex->load_host_private_key=&get_hostkey_private_by_type;
2537 kex->host_key_index=&get_hostkey_index;
2538 kex->sign = sshd_hostkey_sign;
2542 dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
2544 session_id2 = kex->session_id;
2545 session_id2_len = kex->session_id_len;
2548 /* send 1st encrypted/maced/compressed message */
2549 packet_start(SSH2_MSG_IGNORE);
2550 packet_put_cstring("markus");
2552 packet_write_wait();
2557 /* server specific fatal cleanup */
2562 do_cleanup(the_authctxt);
2563 if (use_privsep && privsep_is_preauth && pmonitor->m_pid > 1) {
2564 debug("Killing privsep child %d", pmonitor->m_pid);
2565 if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
2567 error("%s: kill(%d): %s", __func__,
2568 pmonitor->m_pid, strerror(errno));
2571 #ifdef SSH_AUDIT_EVENTS
2572 /* done after do_cleanup so it can cancel the PAM auth 'thread' */
2573 if (!use_privsep || mm_is_monitor())
2574 audit_event(SSH_CONNECTION_ABANDON);