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.
47 #include <sys/types.h>
48 #include <sys/ioctl.h>
49 #include <sys/socket.h>
50 #ifdef HAVE_SYS_STAT_H
51 # include <sys/stat.h>
53 #ifdef HAVE_SYS_TIME_H
54 # include <sys/time.h>
56 #include "openbsd-compat/sys-tree.h"
57 #include "openbsd-compat/sys-queue.h"
75 #include <openssl/dh.h>
76 #include <openssl/bn.h>
77 #include <openssl/rand.h>
78 #include "openbsd-compat/openssl-compat.h"
79 #include <openssl/engine.h>
81 #ifdef HAVE_SECUREWARE
82 #include <sys/security.h>
103 #include "myproposal.h"
104 #include "authfile.h"
105 #include "pathnames.h"
106 #include "atomicio.h"
107 #include "canohost.h"
108 #include "hostfile.h"
113 #include "dispatch.h"
114 #include "channels.h"
116 #include "monitor_mm.h"
121 #include "monitor_wrap.h"
123 #include "ssh-sandbox.h"
138 #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
139 #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
140 #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
141 #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
143 extern char *__progname;
145 /* Server configuration options. */
146 ServerOptions options;
148 /* Name of the server configuration file. */
149 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
152 * Debug mode flag. This can be set on the command line. If debug
153 * mode is enabled, extra debugging output will be sent to the system
154 * log, the daemon will not go to background, and will exit after processing
155 * the first connection.
159 /* Flag indicating that the daemon should only test the configuration and keys. */
162 /* Flag indicating that the daemon is being started from inetd. */
165 /* Flag indicating that sshd should not detach and become a daemon. */
166 int no_daemon_flag = 0;
168 /* debug goes to stderr unless inetd_flag is set */
171 /* Saved arguments to main(). */
176 int rexeced_flag = 0;
182 * The sockets that the server is listening; this is used in the SIGHUP
185 #define MAX_LISTEN_SOCKS 16
186 int listen_socks[MAX_LISTEN_SOCKS];
187 int num_listen_socks = 0;
190 * the client's version string, passed by sshd2 in compat mode. if != NULL,
191 * sshd will skip the version-number exchange
193 char *client_version_string = NULL;
194 char *server_version_string = NULL;
196 /* for rekeying XXX fixme */
199 /* Daemon's agent connection */
200 AuthenticationConnection *auth_conn = NULL;
204 * Any really sensitive data in the application is contained in this
205 * structure. The idea is that this structure could be locked into memory so
206 * that the pages do not get written into swap. However, there are some
207 * problems. The private key contains BIGNUMs, and we do not (in principle)
208 * have access to the internals of them, and locking just the structure is
209 * not very useful. Currently, memory locking is not implemented.
212 Key *server_key; /* ephemeral server key */
213 Key *ssh1_host_key; /* ssh1 host key */
214 Key **host_keys; /* all private host keys */
215 Key **host_pubkeys; /* all public host keys */
216 Key **host_certificates; /* all public host certificates */
219 u_char ssh1_cookie[SSH_SESSION_KEY_LENGTH];
223 * Flag indicating whether the RSA server key needs to be regenerated.
224 * Is set in the SIGALRM handler and cleared when the key is regenerated.
226 static volatile sig_atomic_t key_do_regen = 0;
228 /* This is set to true when a signal is received. */
229 static volatile sig_atomic_t received_sighup = 0;
230 static volatile sig_atomic_t received_sigterm = 0;
232 /* session identifier, used by RSA-auth */
233 u_char session_id[16];
236 u_char *session_id2 = NULL;
237 u_int session_id2_len = 0;
239 /* record remote hostname or ip */
240 u_int utmp_len = MAXHOSTNAMELEN;
242 /* options.max_startup sized array of fd ints */
243 int *startup_pipes = NULL;
244 int startup_pipe; /* in child */
246 /* variables used for privilege separation */
247 int use_privsep = -1;
248 struct monitor *pmonitor = NULL;
249 int privsep_is_preauth = 1;
251 /* global authentication context */
252 Authctxt *the_authctxt = NULL;
254 /* sshd_config buffer */
257 /* message to be displayed after login */
260 /* Unprivileged user */
261 struct passwd *privsep_pw = NULL;
263 /* Prototypes for various functions defined later in this file. */
264 void destroy_sensitive_data(void);
265 void demote_sensitive_data(void);
267 static void do_ssh1_kex(void);
268 static void do_ssh2_kex(void);
271 * Close all listening sockets
274 close_listen_socks(void)
278 for (i = 0; i < num_listen_socks; i++)
279 close(listen_socks[i]);
280 num_listen_socks = -1;
284 close_startup_pipes(void)
289 for (i = 0; i < options.max_startups; i++)
290 if (startup_pipes[i] != -1)
291 close(startup_pipes[i]);
295 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
296 * the effect is to reread the configuration file (and to regenerate
302 sighup_handler(int sig)
304 int save_errno = errno;
307 signal(SIGHUP, sighup_handler);
312 * Called from the main program after receiving SIGHUP.
313 * Restarts the server.
319 logit("Received SIGHUP; restarting.");
320 platform_pre_restart();
321 close_listen_socks();
322 close_startup_pipes();
323 alarm(0); /* alarm timer persists across exec */
324 signal(SIGHUP, SIG_IGN); /* will be restored after exec */
325 execv(saved_argv[0], saved_argv);
326 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
332 * Generic signal handler for terminating signals in the master daemon.
336 sigterm_handler(int sig)
338 received_sigterm = sig;
342 * SIGCHLD handler. This is called whenever a child dies. This will then
343 * reap any zombies left by exited children.
347 main_sigchld_handler(int sig)
349 int save_errno = errno;
353 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
354 (pid < 0 && errno == EINTR))
357 signal(SIGCHLD, main_sigchld_handler);
362 * Signal handler for the alarm after the login grace period has expired.
366 grace_alarm_handler(int sig)
368 if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
369 kill(pmonitor->m_pid, SIGALRM);
372 * Try to kill any processes that we have spawned, E.g. authorized
373 * keys command helpers.
375 if (getpgid(0) == getpid()) {
376 signal(SIGTERM, SIG_IGN);
380 /* Log error and exit. */
381 sigdie("Timeout before authentication for %s", get_remote_ipaddr());
385 * Signal handler for the key regeneration alarm. Note that this
386 * alarm only occurs in the daemon waiting for connections, and it does not
387 * do anything with the private key or random state before forking.
388 * Thus there should be no concurrency control/asynchronous execution
392 generate_ephemeral_server_key(void)
394 verbose("Generating %s%d bit RSA key.",
395 sensitive_data.server_key ? "new " : "", options.server_key_bits);
396 if (sensitive_data.server_key != NULL)
397 key_free(sensitive_data.server_key);
398 sensitive_data.server_key = key_generate(KEY_RSA1,
399 options.server_key_bits);
400 verbose("RSA key generation complete.");
402 arc4random_buf(sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
407 key_regeneration_alarm(int sig)
409 int save_errno = errno;
411 signal(SIGALRM, SIG_DFL);
417 sshd_exchange_identification(int sock_in, int sock_out)
421 int remote_major, remote_minor;
423 char *s, *newline = "\n";
424 char buf[256]; /* Must not be larger than remote_version. */
425 char remote_version[256]; /* Must be at least as big as buf. */
427 if ((options.protocol & SSH_PROTO_1) &&
428 (options.protocol & SSH_PROTO_2)) {
429 major = PROTOCOL_MAJOR_1;
431 } else if (options.protocol & SSH_PROTO_2) {
432 major = PROTOCOL_MAJOR_2;
433 minor = PROTOCOL_MINOR_2;
436 major = PROTOCOL_MAJOR_1;
437 minor = PROTOCOL_MINOR_1;
440 xasprintf(&server_version_string, "SSH-%d.%d-%.100s%s%s%s",
441 major, minor, SSH_VERSION,
442 *options.version_addendum == '\0' ? "" : " ",
443 options.version_addendum, newline);
445 /* Send our protocol version identification. */
446 if (roaming_atomicio(vwrite, sock_out, server_version_string,
447 strlen(server_version_string))
448 != strlen(server_version_string)) {
449 logit("Could not write ident string to %s", get_remote_ipaddr());
453 /* Read other sides version identification. */
454 memset(buf, 0, sizeof(buf));
455 for (i = 0; i < sizeof(buf) - 1; i++) {
456 if (roaming_atomicio(read, sock_in, &buf[i], 1) != 1) {
457 logit("Did not receive identification string from %s",
458 get_remote_ipaddr());
461 if (buf[i] == '\r') {
463 /* Kludge for F-Secure Macintosh < 1.0.2 */
465 strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
469 if (buf[i] == '\n') {
474 buf[sizeof(buf) - 1] = 0;
475 client_version_string = xstrdup(buf);
478 * Check that the versions match. In future this might accept
479 * several versions and set appropriate flags to handle them.
481 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
482 &remote_major, &remote_minor, remote_version) != 3) {
483 s = "Protocol mismatch.\n";
484 (void) atomicio(vwrite, sock_out, s, strlen(s));
485 logit("Bad protocol version identification '%.100s' "
486 "from %s port %d", client_version_string,
487 get_remote_ipaddr(), get_remote_port());
492 debug("Client protocol version %d.%d; client software version %.100s",
493 remote_major, remote_minor, remote_version);
495 compat_datafellows(remote_version);
497 if ((datafellows & SSH_BUG_PROBE) != 0) {
498 logit("probed from %s with %s. Don't panic.",
499 get_remote_ipaddr(), client_version_string);
502 if ((datafellows & SSH_BUG_SCANNER) != 0) {
503 logit("scanned from %s with %s. Don't panic.",
504 get_remote_ipaddr(), client_version_string);
507 if ((datafellows & SSH_BUG_RSASIGMD5) != 0) {
508 logit("Client version \"%.100s\" uses unsafe RSA signature "
509 "scheme; disabling use of RSA keys", remote_version);
511 if ((datafellows & SSH_BUG_DERIVEKEY) != 0) {
512 fatal("Client version \"%.100s\" uses unsafe key agreement; "
513 "refusing connection", remote_version);
517 switch (remote_major) {
519 if (remote_minor == 99) {
520 if (options.protocol & SSH_PROTO_2)
526 if (!(options.protocol & SSH_PROTO_1)) {
530 if (remote_minor < 3) {
531 packet_disconnect("Your ssh version is too old and "
532 "is no longer supported. Please install a newer version.");
533 } else if (remote_minor == 3) {
534 /* note that this disables agent-forwarding */
539 if (options.protocol & SSH_PROTO_2) {
548 chop(server_version_string);
549 debug("Local version string %.200s", server_version_string);
552 s = "Protocol major versions differ.\n";
553 (void) atomicio(vwrite, sock_out, s, strlen(s));
556 logit("Protocol major versions differ for %s: %.200s vs. %.200s",
558 server_version_string, client_version_string);
563 /* Destroy the host and server keys. They will no longer be needed. */
565 destroy_sensitive_data(void)
569 if (sensitive_data.server_key) {
570 key_free(sensitive_data.server_key);
571 sensitive_data.server_key = NULL;
573 for (i = 0; i < options.num_host_key_files; i++) {
574 if (sensitive_data.host_keys[i]) {
575 key_free(sensitive_data.host_keys[i]);
576 sensitive_data.host_keys[i] = NULL;
578 if (sensitive_data.host_certificates[i]) {
579 key_free(sensitive_data.host_certificates[i]);
580 sensitive_data.host_certificates[i] = NULL;
583 sensitive_data.ssh1_host_key = NULL;
584 explicit_bzero(sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
587 /* Demote private to public keys for network child */
589 demote_sensitive_data(void)
594 if (sensitive_data.server_key) {
595 tmp = key_demote(sensitive_data.server_key);
596 key_free(sensitive_data.server_key);
597 sensitive_data.server_key = tmp;
600 for (i = 0; i < options.num_host_key_files; i++) {
601 if (sensitive_data.host_keys[i]) {
602 tmp = key_demote(sensitive_data.host_keys[i]);
603 key_free(sensitive_data.host_keys[i]);
604 sensitive_data.host_keys[i] = tmp;
605 if (tmp->type == KEY_RSA1)
606 sensitive_data.ssh1_host_key = tmp;
608 /* Certs do not need demotion */
611 /* We do not clear ssh1_host key and cookie. XXX - Okay Niels? */
615 privsep_preauth_child(void)
620 /* Enable challenge-response authentication for privilege separation */
621 privsep_challenge_enable();
624 /* Cache supported mechanism OIDs for later use */
625 if (options.gss_authentication)
626 ssh_gssapi_prepare_supported_oids();
630 arc4random_buf(rnd, sizeof(rnd));
631 RAND_seed(rnd, sizeof(rnd));
632 explicit_bzero(rnd, sizeof(rnd));
634 /* Demote the private keys to public keys. */
635 demote_sensitive_data();
637 /* Change our root directory */
638 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
639 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
641 if (chdir("/") == -1)
642 fatal("chdir(\"/\"): %s", strerror(errno));
644 /* Drop our privileges */
645 debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
646 (u_int)privsep_pw->pw_gid);
648 /* XXX not ready, too heavy after chroot */
649 do_setusercontext(privsep_pw);
651 gidset[0] = privsep_pw->pw_gid;
652 if (setgroups(1, gidset) < 0)
653 fatal("setgroups: %.100s", strerror(errno));
654 permanently_set_uid(privsep_pw);
659 privsep_preauth(Authctxt *authctxt)
663 struct ssh_sandbox *box = NULL;
665 /* Set up unprivileged child process to deal with network data */
666 pmonitor = monitor_init();
667 /* Store a pointer to the kex for later rekeying */
668 pmonitor->m_pkex = &xxx_kex;
670 if (use_privsep == PRIVSEP_ON)
671 box = ssh_sandbox_init(pmonitor);
674 fatal("fork of unprivileged child failed");
675 } else if (pid != 0) {
676 debug2("Network child is on pid %ld", (long)pid);
678 pmonitor->m_pid = pid;
680 auth_conn = ssh_get_authentication_connection();
682 ssh_sandbox_parent_preauth(box, pid);
683 monitor_child_preauth(authctxt, pmonitor);
686 monitor_sync(pmonitor);
688 /* Wait for the child's exit status */
689 while (waitpid(pid, &status, 0) < 0) {
692 pmonitor->m_pid = -1;
693 fatal("%s: waitpid: %s", __func__, strerror(errno));
695 privsep_is_preauth = 0;
696 pmonitor->m_pid = -1;
697 if (WIFEXITED(status)) {
698 if (WEXITSTATUS(status) != 0)
699 fatal("%s: preauth child exited with status %d",
700 __func__, WEXITSTATUS(status));
701 } else if (WIFSIGNALED(status))
702 fatal("%s: preauth child terminated by signal %d",
703 __func__, WTERMSIG(status));
705 ssh_sandbox_parent_finish(box);
709 close(pmonitor->m_sendfd);
710 close(pmonitor->m_log_recvfd);
712 /* Arrange for logging to be sent to the monitor */
713 set_log_handler(mm_log_handler, pmonitor);
715 /* Demote the child */
716 if (getuid() == 0 || geteuid() == 0)
717 privsep_preauth_child();
718 setproctitle("%s", "[net]");
720 ssh_sandbox_child(box);
727 privsep_postauth(Authctxt *authctxt)
731 #ifdef DISABLE_FD_PASSING
734 if (authctxt->pw->pw_uid == 0 || options.use_login) {
736 /* File descriptor passing is broken or root login */
741 /* New socket pair */
742 monitor_reinit(pmonitor);
744 pmonitor->m_pid = fork();
745 if (pmonitor->m_pid == -1)
746 fatal("fork of unprivileged child failed");
747 else if (pmonitor->m_pid != 0) {
748 verbose("User child is on pid %ld", (long)pmonitor->m_pid);
749 buffer_clear(&loginmsg);
750 monitor_child_postauth(pmonitor);
758 close(pmonitor->m_sendfd);
759 pmonitor->m_sendfd = -1;
761 /* Demote the private keys to public keys. */
762 demote_sensitive_data();
765 arc4random_buf(rnd, sizeof(rnd));
766 RAND_seed(rnd, sizeof(rnd));
767 explicit_bzero(rnd, sizeof(rnd));
769 /* Drop privileges */
770 do_setusercontext(authctxt->pw);
773 /* It is safe now to apply the key state */
774 monitor_apply_keystate(pmonitor);
777 * Tell the packet layer that authentication was successful, since
778 * this information is not part of the key state.
780 packet_set_authenticated();
784 list_hostkey_types(void)
793 for (i = 0; i < options.num_host_key_files; i++) {
794 key = sensitive_data.host_keys[i];
796 key = sensitive_data.host_pubkeys[i];
804 if (buffer_len(&b) > 0)
805 buffer_append(&b, ",", 1);
806 p = key_ssh_name(key);
807 buffer_append(&b, p, strlen(p));
810 /* If the private key has a cert peer, then list that too */
811 key = sensitive_data.host_certificates[i];
815 case KEY_RSA_CERT_V00:
816 case KEY_DSA_CERT_V00:
820 case KEY_ED25519_CERT:
821 if (buffer_len(&b) > 0)
822 buffer_append(&b, ",", 1);
823 p = key_ssh_name(key);
824 buffer_append(&b, p, strlen(p));
828 buffer_append(&b, "\0", 1);
829 ret = xstrdup(buffer_ptr(&b));
831 debug("list_hostkey_types: %s", ret);
836 get_hostkey_by_type(int type, int need_private)
841 for (i = 0; i < options.num_host_key_files; i++) {
843 case KEY_RSA_CERT_V00:
844 case KEY_DSA_CERT_V00:
848 case KEY_ED25519_CERT:
849 key = sensitive_data.host_certificates[i];
852 key = sensitive_data.host_keys[i];
853 if (key == NULL && !need_private)
854 key = sensitive_data.host_pubkeys[i];
857 if (key != NULL && key->type == type)
858 return need_private ?
859 sensitive_data.host_keys[i] : key;
865 get_hostkey_public_by_type(int type)
867 return get_hostkey_by_type(type, 0);
871 get_hostkey_private_by_type(int type)
873 return get_hostkey_by_type(type, 1);
877 get_hostkey_by_index(int ind)
879 if (ind < 0 || ind >= options.num_host_key_files)
881 return (sensitive_data.host_keys[ind]);
885 get_hostkey_public_by_index(int ind)
887 if (ind < 0 || ind >= options.num_host_key_files)
889 return (sensitive_data.host_pubkeys[ind]);
893 get_hostkey_index(Key *key)
897 for (i = 0; i < options.num_host_key_files; i++) {
898 if (key_is_cert(key)) {
899 if (key == sensitive_data.host_certificates[i])
902 if (key == sensitive_data.host_keys[i])
904 if (key == sensitive_data.host_pubkeys[i])
912 * returns 1 if connection should be dropped, 0 otherwise.
913 * dropping starts at connection #max_startups_begin with a probability
914 * of (max_startups_rate/100). the probability increases linearly until
915 * all connections are dropped for startups > max_startups
918 drop_connection(int startups)
922 if (startups < options.max_startups_begin)
924 if (startups >= options.max_startups)
926 if (options.max_startups_rate == 100)
929 p = 100 - options.max_startups_rate;
930 p *= startups - options.max_startups_begin;
931 p /= options.max_startups - options.max_startups_begin;
932 p += options.max_startups_rate;
933 r = arc4random_uniform(100);
935 debug("drop_connection: p %d, r %d", p, r);
936 return (r < p) ? 1 : 0;
942 fprintf(stderr, "%s, %s\n",
943 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
945 "usage: sshd [-46DdeiqTt] [-b bits] [-C connection_spec] [-c host_cert_file]\n"
946 " [-E log_file] [-f config_file] [-g login_grace_time]\n"
947 " [-h host_key_file] [-k key_gen_time] [-o option] [-p port]\n"
954 send_rexec_state(int fd, Buffer *conf)
958 debug3("%s: entering fd = %d config len %d", __func__, fd,
962 * Protocol from reexec master to child:
963 * string configuration
964 * u_int ephemeral_key_follows
965 * bignum e (only if ephemeral_key_follows == 1)
971 * string rngseed (only if OpenSSL is not self-seeded)
974 buffer_put_cstring(&m, buffer_ptr(conf));
976 if (sensitive_data.server_key != NULL &&
977 sensitive_data.server_key->type == KEY_RSA1) {
978 buffer_put_int(&m, 1);
979 buffer_put_bignum(&m, sensitive_data.server_key->rsa->e);
980 buffer_put_bignum(&m, sensitive_data.server_key->rsa->n);
981 buffer_put_bignum(&m, sensitive_data.server_key->rsa->d);
982 buffer_put_bignum(&m, sensitive_data.server_key->rsa->iqmp);
983 buffer_put_bignum(&m, sensitive_data.server_key->rsa->p);
984 buffer_put_bignum(&m, sensitive_data.server_key->rsa->q);
986 buffer_put_int(&m, 0);
988 #ifndef OPENSSL_PRNG_ONLY
989 rexec_send_rng_seed(&m);
992 if (ssh_msg_send(fd, 0, &m) == -1)
993 fatal("%s: ssh_msg_send failed", __func__);
997 debug3("%s: done", __func__);
1001 recv_rexec_state(int fd, Buffer *conf)
1007 debug3("%s: entering fd = %d", __func__, fd);
1011 if (ssh_msg_recv(fd, &m) == -1)
1012 fatal("%s: ssh_msg_recv failed", __func__);
1013 if (buffer_get_char(&m) != 0)
1014 fatal("%s: rexec version mismatch", __func__);
1016 cp = buffer_get_string(&m, &len);
1018 buffer_append(conf, cp, len + 1);
1021 if (buffer_get_int(&m)) {
1022 if (sensitive_data.server_key != NULL)
1023 key_free(sensitive_data.server_key);
1024 sensitive_data.server_key = key_new_private(KEY_RSA1);
1025 buffer_get_bignum(&m, sensitive_data.server_key->rsa->e);
1026 buffer_get_bignum(&m, sensitive_data.server_key->rsa->n);
1027 buffer_get_bignum(&m, sensitive_data.server_key->rsa->d);
1028 buffer_get_bignum(&m, sensitive_data.server_key->rsa->iqmp);
1029 buffer_get_bignum(&m, sensitive_data.server_key->rsa->p);
1030 buffer_get_bignum(&m, sensitive_data.server_key->rsa->q);
1031 rsa_generate_additional_parameters(
1032 sensitive_data.server_key->rsa);
1035 #ifndef OPENSSL_PRNG_ONLY
1036 rexec_recv_rng_seed(&m);
1041 debug3("%s: done", __func__);
1044 /* Accept a connection from inetd */
1046 server_accept_inetd(int *sock_in, int *sock_out)
1052 close(REEXEC_CONFIG_PASS_FD);
1053 *sock_in = *sock_out = dup(STDIN_FILENO);
1055 startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
1056 close(REEXEC_STARTUP_PIPE_FD);
1059 *sock_in = dup(STDIN_FILENO);
1060 *sock_out = dup(STDOUT_FILENO);
1063 * We intentionally do not close the descriptors 0, 1, and 2
1064 * as our code for setting the descriptors won't work if
1065 * ttyfd happens to be one of those.
1067 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1068 dup2(fd, STDIN_FILENO);
1069 dup2(fd, STDOUT_FILENO);
1071 dup2(fd, STDERR_FILENO);
1072 if (fd > (log_stderr ? STDERR_FILENO : STDOUT_FILENO))
1075 debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
1079 * Listen for TCP connections
1084 int ret, listen_sock, on = 1;
1085 struct addrinfo *ai;
1086 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1088 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
1089 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1091 if (num_listen_socks >= MAX_LISTEN_SOCKS)
1092 fatal("Too many listen sockets. "
1093 "Enlarge MAX_LISTEN_SOCKS");
1094 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1095 ntop, sizeof(ntop), strport, sizeof(strport),
1096 NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1097 error("getnameinfo failed: %.100s",
1098 ssh_gai_strerror(ret));
1101 /* Create socket for listening. */
1102 listen_sock = socket(ai->ai_family, ai->ai_socktype,
1104 if (listen_sock < 0) {
1105 /* kernel may not support ipv6 */
1106 verbose("socket: %.100s", strerror(errno));
1109 if (set_nonblock(listen_sock) == -1) {
1114 * Set socket options.
1115 * Allow local port reuse in TIME_WAIT.
1117 if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
1118 &on, sizeof(on)) == -1)
1119 error("setsockopt SO_REUSEADDR: %s", strerror(errno));
1121 /* Only communicate in IPv6 over AF_INET6 sockets. */
1122 if (ai->ai_family == AF_INET6)
1123 sock_set_v6only(listen_sock);
1125 debug("Bind to port %s on %s.", strport, ntop);
1127 /* Bind the socket to the desired port. */
1128 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1129 error("Bind to port %s on %s failed: %.200s.",
1130 strport, ntop, strerror(errno));
1134 listen_socks[num_listen_socks] = listen_sock;
1137 /* Start listening on the port. */
1138 if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1139 fatal("listen on [%s]:%s: %.100s",
1140 ntop, strport, strerror(errno));
1141 logit("Server listening on %s port %s.", ntop, strport);
1143 freeaddrinfo(options.listen_addrs);
1145 if (!num_listen_socks)
1146 fatal("Cannot bind any address.");
1150 * The main TCP accept loop. Note that, for the non-debug case, returns
1151 * from this function are in a forked subprocess.
1154 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1157 int i, j, ret, maxfd;
1158 int key_used = 0, startups = 0;
1159 int startup_p[2] = { -1 , -1 };
1160 struct sockaddr_storage from;
1165 /* setup fd set for accept */
1168 for (i = 0; i < num_listen_socks; i++)
1169 if (listen_socks[i] > maxfd)
1170 maxfd = listen_socks[i];
1171 /* pipes connected to unauthenticated childs */
1172 startup_pipes = xcalloc(options.max_startups, sizeof(int));
1173 for (i = 0; i < options.max_startups; i++)
1174 startup_pipes[i] = -1;
1177 * Stay listening for connections until the system crashes or
1178 * the daemon is killed with a signal.
1181 if (received_sighup)
1185 fdset = (fd_set *)xcalloc(howmany(maxfd + 1, NFDBITS),
1188 for (i = 0; i < num_listen_socks; i++)
1189 FD_SET(listen_socks[i], fdset);
1190 for (i = 0; i < options.max_startups; i++)
1191 if (startup_pipes[i] != -1)
1192 FD_SET(startup_pipes[i], fdset);
1194 /* Wait in select until there is a connection. */
1195 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1196 if (ret < 0 && errno != EINTR)
1197 error("select: %.100s", strerror(errno));
1198 if (received_sigterm) {
1199 logit("Received signal %d; terminating.",
1200 (int) received_sigterm);
1201 close_listen_socks();
1202 unlink(options.pid_file);
1203 exit(received_sigterm == SIGTERM ? 0 : 255);
1205 if (key_used && key_do_regen) {
1206 generate_ephemeral_server_key();
1213 for (i = 0; i < options.max_startups; i++)
1214 if (startup_pipes[i] != -1 &&
1215 FD_ISSET(startup_pipes[i], fdset)) {
1217 * the read end of the pipe is ready
1218 * if the child has closed the pipe
1219 * after successful authentication
1220 * or if the child has died
1222 close(startup_pipes[i]);
1223 startup_pipes[i] = -1;
1226 for (i = 0; i < num_listen_socks; i++) {
1227 if (!FD_ISSET(listen_socks[i], fdset))
1229 fromlen = sizeof(from);
1230 *newsock = accept(listen_socks[i],
1231 (struct sockaddr *)&from, &fromlen);
1233 if (errno != EINTR && errno != EWOULDBLOCK &&
1234 errno != ECONNABORTED && errno != EAGAIN)
1235 error("accept: %.100s",
1237 if (errno == EMFILE || errno == ENFILE)
1241 if (unset_nonblock(*newsock) == -1) {
1245 if (drop_connection(startups) == 1) {
1246 debug("drop connection #%d", startups);
1250 if (pipe(startup_p) == -1) {
1255 if (rexec_flag && socketpair(AF_UNIX,
1256 SOCK_STREAM, 0, config_s) == -1) {
1257 error("reexec socketpair: %s",
1260 close(startup_p[0]);
1261 close(startup_p[1]);
1265 for (j = 0; j < options.max_startups; j++)
1266 if (startup_pipes[j] == -1) {
1267 startup_pipes[j] = startup_p[0];
1268 if (maxfd < startup_p[0])
1269 maxfd = startup_p[0];
1275 * Got connection. Fork a child to handle it, unless
1276 * we are in debugging mode.
1280 * In debugging mode. Close the listening
1281 * socket, and start processing the
1282 * connection without forking.
1284 debug("Server will not fork when running in debugging mode.");
1285 close_listen_socks();
1286 *sock_in = *newsock;
1287 *sock_out = *newsock;
1288 close(startup_p[0]);
1289 close(startup_p[1]);
1293 send_rexec_state(config_s[0],
1301 * Normal production daemon. Fork, and have
1302 * the child process the connection. The
1303 * parent continues listening.
1305 platform_pre_fork();
1306 if ((pid = fork()) == 0) {
1308 * Child. Close the listening and
1309 * max_startup sockets. Start using
1310 * the accepted socket. Reinitialize
1311 * logging (since our pid has changed).
1312 * We break out of the loop to handle
1315 platform_post_fork_child();
1316 startup_pipe = startup_p[1];
1317 close_startup_pipes();
1318 close_listen_socks();
1319 *sock_in = *newsock;
1320 *sock_out = *newsock;
1321 log_init(__progname,
1323 options.log_facility,
1330 /* Parent. Stay in the loop. */
1331 platform_post_fork_parent(pid);
1333 error("fork: %.100s", strerror(errno));
1335 debug("Forked child %ld.", (long)pid);
1337 close(startup_p[1]);
1340 send_rexec_state(config_s[0], &cfg);
1346 * Mark that the key has been used (it
1347 * was "given" to the child).
1349 if ((options.protocol & SSH_PROTO_1) &&
1351 /* Schedule server key regeneration alarm. */
1352 signal(SIGALRM, key_regeneration_alarm);
1353 alarm(options.key_regeneration_time);
1360 * Ensure that our random state differs
1361 * from that of the child
1364 arc4random_buf(rnd, sizeof(rnd));
1365 RAND_seed(rnd, sizeof(rnd));
1366 explicit_bzero(rnd, sizeof(rnd));
1369 /* child process check (or debug mode) */
1370 if (num_listen_socks < 0)
1377 * Main program for the daemon.
1380 main(int ac, char **av)
1382 extern char *optarg;
1384 int opt, i, j, on = 1;
1385 int sock_in = -1, sock_out = -1, newsock = -1;
1386 const char *remote_ip;
1388 char *line, *logfile = NULL;
1389 int config_s[2] = { -1 , -1 };
1391 u_int64_t ibytes, obytes;
1397 struct connection_info *connection_info = get_connection_info(0, 0);
1399 #ifdef HAVE_SECUREWARE
1400 (void)set_auth_parameters(ac, av);
1402 __progname = ssh_get_progname(av[0]);
1404 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1407 saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1408 for (i = 0; i < ac; i++)
1409 saved_argv[i] = xstrdup(av[i]);
1410 saved_argv[i] = NULL;
1412 #ifndef HAVE_SETPROCTITLE
1413 /* Prepare for later setproctitle emulation */
1414 compat_init_setproctitle(ac, av);
1416 av = xmalloc(sizeof(*saved_argv) * (saved_argc + 1));
1417 for (i = 0; i < saved_argc; i++)
1418 av[i] = xstrdup(saved_argv[i]);
1422 if (geteuid() == 0 && setgroups(0, NULL) == -1)
1423 debug("setgroups(): %.200s", strerror(errno));
1425 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1428 /* Initialize configuration options to their default values. */
1429 initialize_server_options(&options);
1431 /* Parse command-line arguments. */
1432 while ((opt = getopt(ac, av, "f:p:b:k:h:g:u:o:C:dDeE:iqrtQRT46")) != -1) {
1435 options.address_family = AF_INET;
1438 options.address_family = AF_INET6;
1441 config_file_name = optarg;
1444 if (options.num_host_cert_files >= MAX_HOSTCERTS) {
1445 fprintf(stderr, "too many host certificates.\n");
1448 options.host_cert_files[options.num_host_cert_files++] =
1449 derelativise_path(optarg);
1452 if (debug_flag == 0) {
1454 options.log_level = SYSLOG_LEVEL_DEBUG1;
1455 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1456 options.log_level++;
1462 logfile = xstrdup(optarg);
1481 options.log_level = SYSLOG_LEVEL_QUIET;
1484 options.server_key_bits = (int)strtonum(optarg, 256,
1488 options.ports_from_cmdline = 1;
1489 if (options.num_ports >= MAX_PORTS) {
1490 fprintf(stderr, "too many ports.\n");
1493 options.ports[options.num_ports++] = a2port(optarg);
1494 if (options.ports[options.num_ports-1] <= 0) {
1495 fprintf(stderr, "Bad port number.\n");
1500 if ((options.login_grace_time = convtime(optarg)) == -1) {
1501 fprintf(stderr, "Invalid login grace time.\n");
1506 if ((options.key_regeneration_time = convtime(optarg)) == -1) {
1507 fprintf(stderr, "Invalid key regeneration interval.\n");
1512 if (options.num_host_key_files >= MAX_HOSTKEYS) {
1513 fprintf(stderr, "too many host keys.\n");
1516 options.host_key_files[options.num_host_key_files++] =
1517 derelativise_path(optarg);
1526 if (parse_server_match_testspec(connection_info,
1531 utmp_len = (u_int)strtonum(optarg, 0, MAXHOSTNAMELEN+1, NULL);
1532 if (utmp_len > MAXHOSTNAMELEN) {
1533 fprintf(stderr, "Invalid utmp length.\n");
1538 line = xstrdup(optarg);
1539 if (process_server_config_line(&options, line,
1540 "command-line", 0, NULL, NULL) != 0)
1550 if (rexeced_flag || inetd_flag)
1552 if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1553 fatal("sshd re-exec requires execution with an absolute path");
1555 closefrom(REEXEC_MIN_FREE_FD);
1557 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1559 OpenSSL_add_all_algorithms();
1561 /* If requested, redirect the logs to the specified logfile. */
1562 if (logfile != NULL) {
1563 log_redirect_stderr_to(logfile);
1566 /* Init available hardware crypto engines. */
1567 ENGINE_load_builtin_engines();
1568 ENGINE_register_all_complete();
1571 * Force logging to stderr until we have loaded the private host
1572 * key (unless started from inetd)
1574 log_init(__progname,
1575 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1576 SYSLOG_LEVEL_INFO : options.log_level,
1577 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1578 SYSLOG_FACILITY_AUTH : options.log_facility,
1579 log_stderr || !inetd_flag);
1582 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1583 * root's environment
1585 if (getenv("KRB5CCNAME") != NULL)
1586 (void) unsetenv("KRB5CCNAME");
1589 /* Cray can define user privs drop all privs now!
1590 * Not needed on PRIV_SU systems!
1595 sensitive_data.server_key = NULL;
1596 sensitive_data.ssh1_host_key = NULL;
1597 sensitive_data.have_ssh1_key = 0;
1598 sensitive_data.have_ssh2_key = 0;
1601 * If we're doing an extended config test, make sure we have all of
1602 * the parameters we need. If we're not doing an extended test,
1603 * do not silently ignore connection test params.
1605 if (test_flag >= 2 && server_match_spec_complete(connection_info) == 0)
1606 fatal("user, host and addr are all required when testing "
1608 if (test_flag < 2 && server_match_spec_complete(connection_info) >= 0)
1609 fatal("Config test connection parameter (-C) provided without "
1612 /* Fetch our configuration */
1615 recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1617 load_server_config(config_file_name, &cfg);
1619 parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1624 /* Fill in default values for those options not explicitly set. */
1625 fill_default_server_options(&options);
1627 /* challenge-response is implemented via keyboard interactive */
1628 if (options.challenge_response_authentication)
1629 options.kbd_interactive_authentication = 1;
1631 /* Check that options are sensible */
1632 if (options.authorized_keys_command_user == NULL &&
1633 (options.authorized_keys_command != NULL &&
1634 strcasecmp(options.authorized_keys_command, "none") != 0))
1635 fatal("AuthorizedKeysCommand set without "
1636 "AuthorizedKeysCommandUser");
1639 * Check whether there is any path through configured auth methods.
1640 * Unfortunately it is not possible to verify this generally before
1641 * daemonisation in the presence of Match block, but this catches
1642 * and warns for trivial misconfigurations that could break login.
1644 if (options.num_auth_methods != 0) {
1645 if ((options.protocol & SSH_PROTO_1))
1646 fatal("AuthenticationMethods is not supported with "
1648 for (n = 0; n < options.num_auth_methods; n++) {
1649 if (auth2_methods_valid(options.auth_methods[n],
1653 if (n >= options.num_auth_methods)
1654 fatal("AuthenticationMethods cannot be satisfied by "
1655 "enabled authentication methods");
1658 /* set default channel AF */
1659 channel_set_af(options.address_family);
1661 /* Check that there are no remaining arguments. */
1663 fprintf(stderr, "Extra argument %s.\n", av[optind]);
1667 debug("sshd version %s, %s", SSH_VERSION,
1668 SSLeay_version(SSLEAY_VERSION));
1670 /* Store privilege separation user for later use if required. */
1671 if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1672 if (use_privsep || options.kerberos_authentication)
1673 fatal("Privilege separation user %s does not exist",
1676 explicit_bzero(privsep_pw->pw_passwd,
1677 strlen(privsep_pw->pw_passwd));
1678 privsep_pw = pwcopy(privsep_pw);
1679 free(privsep_pw->pw_passwd);
1680 privsep_pw->pw_passwd = xstrdup("*");
1684 /* load host keys */
1685 sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1687 sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
1689 for (i = 0; i < options.num_host_key_files; i++) {
1690 sensitive_data.host_keys[i] = NULL;
1691 sensitive_data.host_pubkeys[i] = NULL;
1694 if (options.host_key_agent) {
1695 if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
1696 setenv(SSH_AUTHSOCKET_ENV_NAME,
1697 options.host_key_agent, 1);
1698 have_agent = ssh_agent_present();
1701 for (i = 0; i < options.num_host_key_files; i++) {
1702 key = key_load_private(options.host_key_files[i], "", NULL);
1703 pubkey = key_load_public(options.host_key_files[i], NULL);
1704 sensitive_data.host_keys[i] = key;
1705 sensitive_data.host_pubkeys[i] = pubkey;
1707 if (key == NULL && pubkey != NULL && pubkey->type != KEY_RSA1 &&
1709 debug("will rely on agent for hostkey %s",
1710 options.host_key_files[i]);
1711 keytype = pubkey->type;
1712 } else if (key != NULL) {
1713 keytype = key->type;
1715 error("Could not load host key: %s",
1716 options.host_key_files[i]);
1717 sensitive_data.host_keys[i] = NULL;
1718 sensitive_data.host_pubkeys[i] = NULL;
1724 sensitive_data.ssh1_host_key = key;
1725 sensitive_data.have_ssh1_key = 1;
1731 sensitive_data.have_ssh2_key = 1;
1734 debug("private host key: #%d type %d %s", i, keytype,
1735 key_type(key ? key : pubkey));
1737 if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1738 logit("Disabling protocol version 1. Could not load host key");
1739 options.protocol &= ~SSH_PROTO_1;
1741 if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1742 logit("Disabling protocol version 2. Could not load host key");
1743 options.protocol &= ~SSH_PROTO_2;
1745 if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1746 logit("sshd: no hostkeys available -- exiting.");
1751 * Load certificates. They are stored in an array at identical
1752 * indices to the public keys that they relate to.
1754 sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
1756 for (i = 0; i < options.num_host_key_files; i++)
1757 sensitive_data.host_certificates[i] = NULL;
1759 for (i = 0; i < options.num_host_cert_files; i++) {
1760 key = key_load_public(options.host_cert_files[i], NULL);
1762 error("Could not load host certificate: %s",
1763 options.host_cert_files[i]);
1766 if (!key_is_cert(key)) {
1767 error("Certificate file is not a certificate: %s",
1768 options.host_cert_files[i]);
1772 /* Find matching private key */
1773 for (j = 0; j < options.num_host_key_files; j++) {
1774 if (key_equal_public(key,
1775 sensitive_data.host_keys[j])) {
1776 sensitive_data.host_certificates[j] = key;
1780 if (j >= options.num_host_key_files) {
1781 error("No matching private key for certificate: %s",
1782 options.host_cert_files[i]);
1786 sensitive_data.host_certificates[j] = key;
1787 debug("host certificate: #%d type %d %s", j, key->type,
1790 /* Check certain values for sanity. */
1791 if (options.protocol & SSH_PROTO_1) {
1792 if (options.server_key_bits < 512 ||
1793 options.server_key_bits > 32768) {
1794 fprintf(stderr, "Bad server key size.\n");
1798 * Check that server and host key lengths differ sufficiently. This
1799 * is necessary to make double encryption work with rsaref. Oh, I
1800 * hate software patents. I dont know if this can go? Niels
1802 if (options.server_key_bits >
1803 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
1804 SSH_KEY_BITS_RESERVED && options.server_key_bits <
1805 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1806 SSH_KEY_BITS_RESERVED) {
1807 options.server_key_bits =
1808 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1809 SSH_KEY_BITS_RESERVED;
1810 debug("Forcing server key to %d bits to make it differ from host key.",
1811 options.server_key_bits);
1818 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1819 (S_ISDIR(st.st_mode) == 0))
1820 fatal("Missing privilege separation directory: %s",
1821 _PATH_PRIVSEP_CHROOT_DIR);
1824 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1825 (st.st_uid != getuid () ||
1826 (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1828 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1830 fatal("%s must be owned by root and not group or "
1831 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1834 if (test_flag > 1) {
1835 if (server_match_spec_complete(connection_info) == 1)
1836 parse_server_match_config(&options, connection_info);
1837 dump_config(&options);
1840 /* Configuration looks good, so exit if in test mode. */
1845 * Clear out any supplemental groups we may have inherited. This
1846 * prevents inadvertent creation of files with bad modes (in the
1847 * portable version at least, it's certainly possible for PAM
1848 * to create a file, and we can't control the code in every
1849 * module which might be used).
1851 if (setgroups(0, NULL) < 0)
1852 debug("setgroups() failed: %.200s", strerror(errno));
1855 rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1856 for (i = 0; i < rexec_argc; i++) {
1857 debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1858 rexec_argv[i] = saved_argv[i];
1860 rexec_argv[rexec_argc] = "-R";
1861 rexec_argv[rexec_argc + 1] = NULL;
1864 /* Ensure that umask disallows at least group and world write */
1865 new_umask = umask(0077) | 0022;
1866 (void) umask(new_umask);
1868 /* Initialize the log (it is reinitialized below in case we forked). */
1869 if (debug_flag && (!inetd_flag || rexeced_flag))
1871 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1874 * If not in debugging mode, and not started from inetd, disconnect
1875 * from the controlling terminal, and fork. The original process
1878 if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1881 #endif /* TIOCNOTTY */
1882 if (daemon(0, 0) < 0)
1883 fatal("daemon() failed: %.200s", strerror(errno));
1885 /* Disconnect from the controlling tty. */
1887 fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1889 (void) ioctl(fd, TIOCNOTTY, NULL);
1892 #endif /* TIOCNOTTY */
1894 /* Reinitialize the log (because of the fork above). */
1895 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1897 /* Chdir to the root directory so that the current disk can be
1898 unmounted if desired. */
1899 if (chdir("/") == -1)
1900 error("chdir(\"/\"): %s", strerror(errno));
1902 /* ignore SIGPIPE */
1903 signal(SIGPIPE, SIG_IGN);
1905 /* Get a connection, either from inetd or a listening TCP socket */
1907 server_accept_inetd(&sock_in, &sock_out);
1909 platform_pre_listen();
1912 if (options.protocol & SSH_PROTO_1)
1913 generate_ephemeral_server_key();
1915 signal(SIGHUP, sighup_handler);
1916 signal(SIGCHLD, main_sigchld_handler);
1917 signal(SIGTERM, sigterm_handler);
1918 signal(SIGQUIT, sigterm_handler);
1921 * Write out the pid file after the sigterm handler
1922 * is setup and the listen sockets are bound
1925 FILE *f = fopen(options.pid_file, "w");
1928 error("Couldn't create pid file \"%s\": %s",
1929 options.pid_file, strerror(errno));
1931 fprintf(f, "%ld\n", (long) getpid());
1936 /* Accept a connection and return in a forked child */
1937 server_accept_loop(&sock_in, &sock_out,
1938 &newsock, config_s);
1941 /* This is the child processing a new connection. */
1942 setproctitle("%s", "[accepted]");
1945 * Create a new session and process group since the 4.4BSD
1946 * setlogin() affects the entire process group. We don't
1947 * want the child to be able to affect the parent.
1949 #if !defined(SSHD_ACQUIRES_CTTY)
1951 * If setsid is called, on some platforms sshd will later acquire a
1952 * controlling terminal which will result in "could not set
1953 * controlling tty" errors.
1955 if (!debug_flag && !inetd_flag && setsid() < 0)
1956 error("setsid: %.100s", strerror(errno));
1962 debug("rexec start in %d out %d newsock %d pipe %d sock %d",
1963 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1964 dup2(newsock, STDIN_FILENO);
1965 dup2(STDIN_FILENO, STDOUT_FILENO);
1966 if (startup_pipe == -1)
1967 close(REEXEC_STARTUP_PIPE_FD);
1968 else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) {
1969 dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
1970 close(startup_pipe);
1971 startup_pipe = REEXEC_STARTUP_PIPE_FD;
1974 dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1977 execv(rexec_argv[0], rexec_argv);
1979 /* Reexec has failed, fall back and continue */
1980 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1981 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1982 log_init(__progname, options.log_level,
1983 options.log_facility, log_stderr);
1986 close(REEXEC_CONFIG_PASS_FD);
1987 newsock = sock_out = sock_in = dup(STDIN_FILENO);
1988 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1989 dup2(fd, STDIN_FILENO);
1990 dup2(fd, STDOUT_FILENO);
1991 if (fd > STDERR_FILENO)
1994 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
1995 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1998 /* Executed child processes don't need these. */
1999 fcntl(sock_out, F_SETFD, FD_CLOEXEC);
2000 fcntl(sock_in, F_SETFD, FD_CLOEXEC);
2003 * Disable the key regeneration alarm. We will not regenerate the
2004 * key since we are no longer in a position to give it to anyone. We
2005 * will not restart on SIGHUP since it no longer makes sense.
2008 signal(SIGALRM, SIG_DFL);
2009 signal(SIGHUP, SIG_DFL);
2010 signal(SIGTERM, SIG_DFL);
2011 signal(SIGQUIT, SIG_DFL);
2012 signal(SIGCHLD, SIG_DFL);
2013 signal(SIGINT, SIG_DFL);
2016 * Register our connection. This turns encryption off because we do
2019 packet_set_connection(sock_in, sock_out);
2020 packet_set_server();
2022 /* Set SO_KEEPALIVE if requested. */
2023 if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
2024 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
2025 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
2027 if ((remote_port = get_remote_port()) < 0) {
2028 debug("get_remote_port failed");
2033 * We use get_canonical_hostname with usedns = 0 instead of
2034 * get_remote_ipaddr here so IP options will be checked.
2036 (void) get_canonical_hostname(0);
2038 * The rest of the code depends on the fact that
2039 * get_remote_ipaddr() caches the remote ip, even if
2040 * the socket goes away.
2042 remote_ip = get_remote_ipaddr();
2044 #ifdef SSH_AUDIT_EVENTS
2045 audit_connection_from(remote_ip, remote_port);
2048 allow_severity = options.log_facility|LOG_INFO;
2049 deny_severity = options.log_facility|LOG_WARNING;
2050 /* Check whether logins are denied from this host. */
2051 if (packet_connection_is_on_socket()) {
2052 struct request_info req;
2054 request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
2057 if (!hosts_access(&req)) {
2058 debug("Connection refused by tcp wrapper");
2061 fatal("libwrap refuse returns");
2064 #endif /* LIBWRAP */
2066 /* Log the connection. */
2067 verbose("Connection from %s port %d on %s port %d",
2068 remote_ip, remote_port,
2069 get_local_ipaddr(sock_in), get_local_port());
2072 * We don't want to listen forever unless the other side
2073 * successfully authenticates itself. So we set up an alarm which is
2074 * cleared after successful authentication. A limit of zero
2075 * indicates no limit. Note that we don't set the alarm in debugging
2076 * mode; it is just annoying to have the server exit just when you
2077 * are about to discover the bug.
2079 signal(SIGALRM, grace_alarm_handler);
2081 alarm(options.login_grace_time);
2083 sshd_exchange_identification(sock_in, sock_out);
2085 /* In inetd mode, generate ephemeral key only for proto 1 connections */
2086 if (!compat20 && inetd_flag && sensitive_data.server_key == NULL)
2087 generate_ephemeral_server_key();
2089 packet_set_nonblocking();
2091 /* allocate authentication context */
2092 authctxt = xcalloc(1, sizeof(*authctxt));
2094 authctxt->loginmsg = &loginmsg;
2096 /* XXX global for cleanup, access from other modules */
2097 the_authctxt = authctxt;
2099 /* prepare buffer to collect messages to display to user after login */
2100 buffer_init(&loginmsg);
2104 if (privsep_preauth(authctxt) == 1)
2106 } else if (compat20 && have_agent)
2107 auth_conn = ssh_get_authentication_connection();
2109 /* perform the key exchange */
2110 /* authenticate user and start session */
2113 do_authentication2(authctxt);
2116 do_authentication(authctxt);
2119 * If we use privilege separation, the unprivileged child transfers
2120 * the current keystate and exits
2123 mm_send_keystate(pmonitor);
2129 * Cancel the alarm we set to limit the time taken for
2133 signal(SIGALRM, SIG_DFL);
2134 authctxt->authenticated = 1;
2135 if (startup_pipe != -1) {
2136 close(startup_pipe);
2140 #ifdef SSH_AUDIT_EVENTS
2141 audit_event(SSH_AUTH_SUCCESS);
2145 if (options.gss_authentication) {
2146 temporarily_use_uid(authctxt->pw);
2147 ssh_gssapi_storecreds();
2152 if (options.use_pam) {
2159 * In privilege separation, we fork another child and prepare
2160 * file descriptor passing.
2163 privsep_postauth(authctxt);
2164 /* the monitor process [priv] will not return */
2166 destroy_sensitive_data();
2169 packet_set_timeout(options.client_alive_interval,
2170 options.client_alive_count_max);
2172 /* Start session. */
2173 do_authenticated(authctxt);
2175 /* The connection has been terminated. */
2176 packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
2177 packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
2178 verbose("Transferred: sent %llu, received %llu bytes",
2179 (unsigned long long)obytes, (unsigned long long)ibytes);
2181 verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
2184 if (options.use_pam)
2186 #endif /* USE_PAM */
2188 #ifdef SSH_AUDIT_EVENTS
2189 PRIVSEP(audit_event(SSH_CONNECTION_CLOSE));
2201 * Decrypt session_key_int using our private server key and private host key
2202 * (key with larger modulus first).
2205 ssh1_session_key(BIGNUM *session_key_int)
2209 if (BN_cmp(sensitive_data.server_key->rsa->n,
2210 sensitive_data.ssh1_host_key->rsa->n) > 0) {
2211 /* Server key has bigger modulus. */
2212 if (BN_num_bits(sensitive_data.server_key->rsa->n) <
2213 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
2214 SSH_KEY_BITS_RESERVED) {
2215 fatal("do_connection: %s: "
2216 "server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
2217 get_remote_ipaddr(),
2218 BN_num_bits(sensitive_data.server_key->rsa->n),
2219 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2220 SSH_KEY_BITS_RESERVED);
2222 if (rsa_private_decrypt(session_key_int, session_key_int,
2223 sensitive_data.server_key->rsa) <= 0)
2225 if (rsa_private_decrypt(session_key_int, session_key_int,
2226 sensitive_data.ssh1_host_key->rsa) <= 0)
2229 /* Host key has bigger modulus (or they are equal). */
2230 if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
2231 BN_num_bits(sensitive_data.server_key->rsa->n) +
2232 SSH_KEY_BITS_RESERVED) {
2233 fatal("do_connection: %s: "
2234 "host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
2235 get_remote_ipaddr(),
2236 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2237 BN_num_bits(sensitive_data.server_key->rsa->n),
2238 SSH_KEY_BITS_RESERVED);
2240 if (rsa_private_decrypt(session_key_int, session_key_int,
2241 sensitive_data.ssh1_host_key->rsa) < 0)
2243 if (rsa_private_decrypt(session_key_int, session_key_int,
2244 sensitive_data.server_key->rsa) < 0)
2257 BIGNUM *session_key_int;
2258 u_char session_key[SSH_SESSION_KEY_LENGTH];
2260 u_int cipher_type, auth_mask, protocol_flags;
2263 * Generate check bytes that the client must send back in the user
2264 * packet in order for it to be accepted; this is used to defy ip
2265 * spoofing attacks. Note that this only works against somebody
2266 * doing IP spoofing from a remote machine; any machine on the local
2267 * network can still see outgoing packets and catch the random
2268 * cookie. This only affects rhosts authentication, and this is one
2269 * of the reasons why it is inherently insecure.
2271 arc4random_buf(cookie, sizeof(cookie));
2274 * Send our public key. We include in the packet 64 bits of random
2275 * data that must be matched in the reply in order to prevent IP
2278 packet_start(SSH_SMSG_PUBLIC_KEY);
2279 for (i = 0; i < 8; i++)
2280 packet_put_char(cookie[i]);
2282 /* Store our public server RSA key. */
2283 packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
2284 packet_put_bignum(sensitive_data.server_key->rsa->e);
2285 packet_put_bignum(sensitive_data.server_key->rsa->n);
2287 /* Store our public host RSA key. */
2288 packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2289 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
2290 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
2292 /* Put protocol flags. */
2293 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
2295 /* Declare which ciphers we support. */
2296 packet_put_int(cipher_mask_ssh1(0));
2298 /* Declare supported authentication types. */
2300 if (options.rhosts_rsa_authentication)
2301 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
2302 if (options.rsa_authentication)
2303 auth_mask |= 1 << SSH_AUTH_RSA;
2304 if (options.challenge_response_authentication == 1)
2305 auth_mask |= 1 << SSH_AUTH_TIS;
2306 if (options.password_authentication)
2307 auth_mask |= 1 << SSH_AUTH_PASSWORD;
2308 packet_put_int(auth_mask);
2310 /* Send the packet and wait for it to be sent. */
2312 packet_write_wait();
2314 debug("Sent %d bit server key and %d bit host key.",
2315 BN_num_bits(sensitive_data.server_key->rsa->n),
2316 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2318 /* Read clients reply (cipher type and session key). */
2319 packet_read_expect(SSH_CMSG_SESSION_KEY);
2321 /* Get cipher type and check whether we accept this. */
2322 cipher_type = packet_get_char();
2324 if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
2325 packet_disconnect("Warning: client selects unsupported cipher.");
2327 /* Get check bytes from the packet. These must match those we
2328 sent earlier with the public key packet. */
2329 for (i = 0; i < 8; i++)
2330 if (cookie[i] != packet_get_char())
2331 packet_disconnect("IP Spoofing check bytes do not match.");
2333 debug("Encryption type: %.200s", cipher_name(cipher_type));
2335 /* Get the encrypted integer. */
2336 if ((session_key_int = BN_new()) == NULL)
2337 fatal("do_ssh1_kex: BN_new failed");
2338 packet_get_bignum(session_key_int);
2340 protocol_flags = packet_get_int();
2341 packet_set_protocol_flags(protocol_flags);
2344 /* Decrypt session_key_int using host/server keys */
2345 rsafail = PRIVSEP(ssh1_session_key(session_key_int));
2348 * Extract session key from the decrypted integer. The key is in the
2349 * least significant 256 bits of the integer; the first byte of the
2350 * key is in the highest bits.
2353 (void) BN_mask_bits(session_key_int, sizeof(session_key) * 8);
2354 len = BN_num_bytes(session_key_int);
2355 if (len < 0 || (u_int)len > sizeof(session_key)) {
2356 error("do_ssh1_kex: bad session key len from %s: "
2357 "session_key_int %d > sizeof(session_key) %lu",
2358 get_remote_ipaddr(), len, (u_long)sizeof(session_key));
2361 explicit_bzero(session_key, sizeof(session_key));
2362 BN_bn2bin(session_key_int,
2363 session_key + sizeof(session_key) - len);
2365 derive_ssh1_session_id(
2366 sensitive_data.ssh1_host_key->rsa->n,
2367 sensitive_data.server_key->rsa->n,
2368 cookie, session_id);
2370 * Xor the first 16 bytes of the session key with the
2373 for (i = 0; i < 16; i++)
2374 session_key[i] ^= session_id[i];
2378 int bytes = BN_num_bytes(session_key_int);
2379 u_char *buf = xmalloc(bytes);
2380 struct ssh_digest_ctx *md;
2382 logit("do_connection: generating a fake encryption key");
2383 BN_bn2bin(session_key_int, buf);
2384 if ((md = ssh_digest_start(SSH_DIGEST_MD5)) == NULL ||
2385 ssh_digest_update(md, buf, bytes) < 0 ||
2386 ssh_digest_update(md, sensitive_data.ssh1_cookie,
2387 SSH_SESSION_KEY_LENGTH) < 0 ||
2388 ssh_digest_final(md, session_key, sizeof(session_key)) < 0)
2389 fatal("%s: md5 failed", __func__);
2390 ssh_digest_free(md);
2391 if ((md = ssh_digest_start(SSH_DIGEST_MD5)) == NULL ||
2392 ssh_digest_update(md, session_key, 16) < 0 ||
2393 ssh_digest_update(md, sensitive_data.ssh1_cookie,
2394 SSH_SESSION_KEY_LENGTH) < 0 ||
2395 ssh_digest_final(md, session_key + 16,
2396 sizeof(session_key) - 16) < 0)
2397 fatal("%s: md5 failed", __func__);
2398 ssh_digest_free(md);
2399 explicit_bzero(buf, bytes);
2401 for (i = 0; i < 16; i++)
2402 session_id[i] = session_key[i] ^ session_key[i + 16];
2404 /* Destroy the private and public keys. No longer. */
2405 destroy_sensitive_data();
2408 mm_ssh1_session_id(session_id);
2410 /* Destroy the decrypted integer. It is no longer needed. */
2411 BN_clear_free(session_key_int);
2413 /* Set the session key. From this on all communications will be encrypted. */
2414 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
2416 /* Destroy our copy of the session key. It is no longer needed. */
2417 explicit_bzero(session_key, sizeof(session_key));
2419 debug("Received session key; encryption turned on.");
2421 /* Send an acknowledgment packet. Note that this packet is sent encrypted. */
2422 packet_start(SSH_SMSG_SUCCESS);
2424 packet_write_wait();
2428 sshd_hostkey_sign(Key *privkey, Key *pubkey, u_char **signature, u_int *slen,
2429 u_char *data, u_int dlen)
2432 if (PRIVSEP(key_sign(privkey, signature, slen, data, dlen) < 0))
2433 fatal("%s: key_sign failed", __func__);
2434 } else if (use_privsep) {
2435 if (mm_key_sign(pubkey, signature, slen, data, dlen) < 0)
2436 fatal("%s: pubkey_sign failed", __func__);
2438 if (ssh_agent_sign(auth_conn, pubkey, signature, slen, data,
2440 fatal("%s: ssh_agent_sign failed", __func__);
2445 * SSH2 key exchange: diffie-hellman-group1-sha1
2452 if (options.ciphers != NULL) {
2453 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2454 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
2456 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2457 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
2458 myproposal[PROPOSAL_ENC_ALGS_STOC] =
2459 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
2461 if (options.macs != NULL) {
2462 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2463 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2465 if (options.compression == COMP_NONE) {
2466 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2467 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2468 } else if (options.compression == COMP_DELAYED) {
2469 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2470 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com";
2472 if (options.kex_algorithms != NULL)
2473 myproposal[PROPOSAL_KEX_ALGS] = options.kex_algorithms;
2475 if (options.rekey_limit || options.rekey_interval)
2476 packet_set_rekey_limits((u_int32_t)options.rekey_limit,
2477 (time_t)options.rekey_interval);
2479 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal(
2480 list_hostkey_types());
2482 /* start key exchange */
2483 kex = kex_setup(myproposal);
2484 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2485 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
2486 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2487 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2488 kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
2489 kex->kex[KEX_C25519_SHA256] = kexc25519_server;
2491 kex->client_version_string=client_version_string;
2492 kex->server_version_string=server_version_string;
2493 kex->load_host_public_key=&get_hostkey_public_by_type;
2494 kex->load_host_private_key=&get_hostkey_private_by_type;
2495 kex->host_key_index=&get_hostkey_index;
2496 kex->sign = sshd_hostkey_sign;
2500 dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
2502 session_id2 = kex->session_id;
2503 session_id2_len = kex->session_id_len;
2506 /* send 1st encrypted/maced/compressed message */
2507 packet_start(SSH2_MSG_IGNORE);
2508 packet_put_cstring("markus");
2510 packet_write_wait();
2515 /* server specific fatal cleanup */
2520 do_cleanup(the_authctxt);
2521 if (use_privsep && privsep_is_preauth && pmonitor->m_pid > 1) {
2522 debug("Killing privsep child %d", pmonitor->m_pid);
2523 if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
2525 error("%s: kill(%d): %s", __func__,
2526 pmonitor->m_pid, strerror(errno));
2529 #ifdef SSH_AUDIT_EVENTS
2530 /* done after do_cleanup so it can cancel the PAM auth 'thread' */
2531 if (!use_privsep || mm_is_monitor())
2532 audit_event(SSH_CONNECTION_ABANDON);