1 /* $OpenBSD: sshd.c,v 1.516 2018/09/21 12:23:17 djm 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"
79 #include <openssl/dh.h>
80 #include <openssl/bn.h>
81 #include <openssl/rand.h>
82 #include "openbsd-compat/openssl-compat.h"
85 #ifdef HAVE_SECUREWARE
86 #include <sys/security.h>
92 #if defined(GSSAPI) && defined(HAVE_GSSAPI_GSSAPI_H)
93 #include <gssapi/gssapi.h>
94 #elif defined(GSSAPI) && defined(HAVE_GSSAPI_H)
108 #include "servconf.h"
115 #include "myproposal.h"
116 #include "authfile.h"
117 #include "pathnames.h"
118 #include "atomicio.h"
119 #include "canohost.h"
120 #include "hostfile.h"
124 #include "dispatch.h"
125 #include "channels.h"
131 #include "monitor_wrap.h"
132 #include "ssh-sandbox.h"
133 #include "auth-options.h"
136 #include "blacklist_client.h"
146 #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
147 #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
148 #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
149 #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
151 extern char *__progname;
153 /* Server configuration options. */
154 ServerOptions options;
156 /* Name of the server configuration file. */
157 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
160 * Debug mode flag. This can be set on the command line. If debug
161 * mode is enabled, extra debugging output will be sent to the system
162 * log, the daemon will not go to background, and will exit after processing
163 * the first connection.
168 * Indicating that the daemon should only test the configuration and keys.
169 * If test_flag > 1 ("-T" flag), then sshd will also dump the effective
170 * configuration, optionally using connection information provided by the
175 /* Flag indicating that the daemon is being started from inetd. */
178 /* Flag indicating that sshd should not detach and become a daemon. */
179 int no_daemon_flag = 0;
181 /* debug goes to stderr unless inetd_flag is set */
184 /* Saved arguments to main(). */
189 int rexeced_flag = 0;
195 * The sockets that the server is listening; this is used in the SIGHUP
198 #define MAX_LISTEN_SOCKS 16
199 int listen_socks[MAX_LISTEN_SOCKS];
200 int num_listen_socks = 0;
203 * the client's version string, passed by sshd2 in compat mode. if != NULL,
204 * sshd will skip the version-number exchange
206 char *client_version_string = NULL;
207 char *server_version_string = NULL;
209 /* Daemon's agent connection */
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 struct sshkey **host_keys; /* all private host keys */
223 struct sshkey **host_pubkeys; /* all public host keys */
224 struct sshkey **host_certificates; /* all public host certificates */
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 = HOST_NAME_MAX+1;
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;
250 static int privsep_chroot = 1;
252 /* global authentication context */
253 Authctxt *the_authctxt = NULL;
255 /* global key/cert auth options. XXX move to permanent ssh->authctxt? */
256 struct sshauthopt *auth_opts = NULL;
258 /* sshd_config buffer */
261 /* message to be displayed after login */
262 struct sshbuf *loginmsg;
264 /* Unprivileged user */
265 struct passwd *privsep_pw = NULL;
267 /* Prototypes for various functions defined later in this file. */
268 void destroy_sensitive_data(void);
269 void demote_sensitive_data(void);
270 static void do_ssh2_kex(void);
273 * Close all listening sockets
276 close_listen_socks(void)
280 for (i = 0; i < num_listen_socks; i++)
281 close(listen_socks[i]);
282 num_listen_socks = -1;
286 close_startup_pipes(void)
291 for (i = 0; i < options.max_startups; i++)
292 if (startup_pipes[i] != -1)
293 close(startup_pipes[i]);
297 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
298 * the effect is to reread the configuration file (and to regenerate
304 sighup_handler(int sig)
306 int save_errno = errno;
313 * Called from the main program after receiving SIGHUP.
314 * Restarts the server.
319 logit("Received SIGHUP; restarting.");
320 if (options.pid_file != NULL)
321 unlink(options.pid_file);
322 platform_pre_restart();
323 close_listen_socks();
324 close_startup_pipes();
325 alarm(0); /* alarm timer persists across exec */
326 signal(SIGHUP, SIG_IGN); /* will be restored after exec */
327 execv(saved_argv[0], saved_argv);
328 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
334 * Generic signal handler for terminating signals in the master daemon.
338 sigterm_handler(int sig)
340 received_sigterm = sig;
344 * SIGCHLD handler. This is called whenever a child dies. This will then
345 * reap any zombies left by exited children.
349 main_sigchld_handler(int sig)
351 int save_errno = errno;
355 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
356 (pid < 0 && errno == EINTR))
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 BLACKLIST_NOTIFY(BLACKLIST_AUTH_FAIL, "ssh");
382 /* Log error and exit. */
383 sigdie("Timeout before authentication for %s port %d",
384 ssh_remote_ipaddr(active_state), ssh_remote_port(active_state));
388 sshd_exchange_identification(struct ssh *ssh, int sock_in, int sock_out)
391 int remote_major, remote_minor;
393 char buf[256]; /* Must not be larger than remote_version. */
394 char remote_version[256]; /* Must be at least as big as buf. */
396 xasprintf(&server_version_string, "SSH-%d.%d-%.100s%s%s\r\n",
397 PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2, SSH_VERSION,
398 *options.version_addendum == '\0' ? "" : " ",
399 options.version_addendum);
401 /* Send our protocol version identification. */
402 if (atomicio(vwrite, sock_out, server_version_string,
403 strlen(server_version_string))
404 != strlen(server_version_string)) {
405 logit("Could not write ident string to %s port %d",
406 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
410 /* Read other sides version identification. */
411 memset(buf, 0, sizeof(buf));
412 for (i = 0; i < sizeof(buf) - 1; i++) {
413 if (atomicio(read, sock_in, &buf[i], 1) != 1) {
414 logit("Did not receive identification string "
416 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
419 if (buf[i] == '\r') {
421 /* Kludge for F-Secure Macintosh < 1.0.2 */
423 strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
427 if (buf[i] == '\n') {
432 buf[sizeof(buf) - 1] = 0;
433 client_version_string = xstrdup(buf);
436 * Check that the versions match. In future this might accept
437 * several versions and set appropriate flags to handle them.
439 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
440 &remote_major, &remote_minor, remote_version) != 3) {
441 s = "Protocol mismatch.\n";
442 (void) atomicio(vwrite, sock_out, s, strlen(s));
443 logit("Bad protocol version identification '%.100s' "
444 "from %s port %d", client_version_string,
445 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
450 debug("Client protocol version %d.%d; client software version %.100s",
451 remote_major, remote_minor, remote_version);
453 ssh->compat = compat_datafellows(remote_version);
455 if ((ssh->compat & SSH_BUG_PROBE) != 0) {
456 logit("probed from %s port %d with %s. Don't panic.",
457 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
458 client_version_string);
461 if ((ssh->compat & SSH_BUG_SCANNER) != 0) {
462 logit("scanned from %s port %d with %s. Don't panic.",
463 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
464 client_version_string);
467 if ((ssh->compat & SSH_BUG_RSASIGMD5) != 0) {
468 logit("Client version \"%.100s\" uses unsafe RSA signature "
469 "scheme; disabling use of RSA keys", remote_version);
472 chop(server_version_string);
473 debug("Local version string %.200s", server_version_string);
475 if (remote_major != 2 &&
476 !(remote_major == 1 && remote_minor == 99)) {
477 s = "Protocol major versions differ.\n";
478 (void) atomicio(vwrite, sock_out, s, strlen(s));
481 logit("Protocol major versions differ for %s port %d: "
483 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
484 server_version_string, client_version_string);
489 /* Destroy the host and server keys. They will no longer be needed. */
491 destroy_sensitive_data(void)
495 for (i = 0; i < options.num_host_key_files; i++) {
496 if (sensitive_data.host_keys[i]) {
497 sshkey_free(sensitive_data.host_keys[i]);
498 sensitive_data.host_keys[i] = NULL;
500 if (sensitive_data.host_certificates[i]) {
501 sshkey_free(sensitive_data.host_certificates[i]);
502 sensitive_data.host_certificates[i] = NULL;
507 /* Demote private to public keys for network child */
509 demote_sensitive_data(void)
515 for (i = 0; i < options.num_host_key_files; i++) {
516 if (sensitive_data.host_keys[i]) {
517 if ((r = sshkey_from_private(
518 sensitive_data.host_keys[i], &tmp)) != 0)
519 fatal("could not demote host %s key: %s",
520 sshkey_type(sensitive_data.host_keys[i]),
522 sshkey_free(sensitive_data.host_keys[i]);
523 sensitive_data.host_keys[i] = tmp;
525 /* Certs do not need demotion */
537 arc4random_stir(); /* noop on recent arc4random() implementations */
538 arc4random_buf(rnd, sizeof(rnd)); /* let arc4random notice PID change */
541 RAND_seed(rnd, sizeof(rnd));
542 /* give libcrypto a chance to notice the PID change */
543 if ((RAND_bytes((u_char *)rnd, 1)) != 1)
544 fatal("%s: RAND_bytes failed", __func__);
547 explicit_bzero(rnd, sizeof(rnd));
551 privsep_preauth_child(void)
555 /* Enable challenge-response authentication for privilege separation */
556 privsep_challenge_enable();
559 /* Cache supported mechanism OIDs for later use */
560 ssh_gssapi_prepare_supported_oids();
565 /* Demote the private keys to public keys. */
566 demote_sensitive_data();
568 /* Demote the child */
569 if (privsep_chroot) {
570 /* Change our root directory */
571 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
572 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
574 if (chdir("/") == -1)
575 fatal("chdir(\"/\"): %s", strerror(errno));
577 /* Drop our privileges */
578 debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
579 (u_int)privsep_pw->pw_gid);
580 gidset[0] = privsep_pw->pw_gid;
581 if (setgroups(1, gidset) < 0)
582 fatal("setgroups: %.100s", strerror(errno));
583 permanently_set_uid(privsep_pw);
588 privsep_preauth(Authctxt *authctxt)
592 struct ssh_sandbox *box = NULL;
594 /* Set up unprivileged child process to deal with network data */
595 pmonitor = monitor_init();
596 /* Store a pointer to the kex for later rekeying */
597 pmonitor->m_pkex = &active_state->kex;
599 if (use_privsep == PRIVSEP_ON)
600 box = ssh_sandbox_init(pmonitor);
603 fatal("fork of unprivileged child failed");
604 } else if (pid != 0) {
605 debug2("Network child is on pid %ld", (long)pid);
607 pmonitor->m_pid = pid;
609 r = ssh_get_authentication_socket(&auth_sock);
611 error("Could not get agent socket: %s",
617 ssh_sandbox_parent_preauth(box, pid);
618 monitor_child_preauth(authctxt, pmonitor);
620 /* Wait for the child's exit status */
621 while (waitpid(pid, &status, 0) < 0) {
624 pmonitor->m_pid = -1;
625 fatal("%s: waitpid: %s", __func__, strerror(errno));
627 privsep_is_preauth = 0;
628 pmonitor->m_pid = -1;
629 if (WIFEXITED(status)) {
630 if (WEXITSTATUS(status) != 0)
631 fatal("%s: preauth child exited with status %d",
632 __func__, WEXITSTATUS(status));
633 } else if (WIFSIGNALED(status))
634 fatal("%s: preauth child terminated by signal %d",
635 __func__, WTERMSIG(status));
637 ssh_sandbox_parent_finish(box);
641 close(pmonitor->m_sendfd);
642 close(pmonitor->m_log_recvfd);
644 /* Arrange for logging to be sent to the monitor */
645 set_log_handler(mm_log_handler, pmonitor);
647 privsep_preauth_child();
648 setproctitle("%s", "[net]");
650 ssh_sandbox_child(box);
657 privsep_postauth(Authctxt *authctxt)
659 #ifdef DISABLE_FD_PASSING
662 if (authctxt->pw->pw_uid == 0) {
664 /* File descriptor passing is broken or root login */
669 /* New socket pair */
670 monitor_reinit(pmonitor);
672 pmonitor->m_pid = fork();
673 if (pmonitor->m_pid == -1)
674 fatal("fork of unprivileged child failed");
675 else if (pmonitor->m_pid != 0) {
676 verbose("User child is on pid %ld", (long)pmonitor->m_pid);
677 sshbuf_reset(loginmsg);
678 monitor_clear_keystate(pmonitor);
679 monitor_child_postauth(pmonitor);
687 close(pmonitor->m_sendfd);
688 pmonitor->m_sendfd = -1;
690 /* Demote the private keys to public keys. */
691 demote_sensitive_data();
695 /* Drop privileges */
696 do_setusercontext(authctxt->pw);
699 /* It is safe now to apply the key state */
700 monitor_apply_keystate(pmonitor);
703 * Tell the packet layer that authentication was successful, since
704 * this information is not part of the key state.
706 packet_set_authenticated();
710 append_hostkey_type(struct sshbuf *b, const char *s)
714 if (match_pattern_list(s, options.hostkeyalgorithms, 0) != 1) {
715 debug3("%s: %s key not permitted by HostkeyAlgorithms",
719 if ((r = sshbuf_putf(b, "%s%s", sshbuf_len(b) > 0 ? "," : "", s)) != 0)
720 fatal("%s: sshbuf_putf: %s", __func__, ssh_err(r));
724 list_hostkey_types(void)
731 if ((b = sshbuf_new()) == NULL)
732 fatal("%s: sshbuf_new failed", __func__);
733 for (i = 0; i < options.num_host_key_files; i++) {
734 key = sensitive_data.host_keys[i];
736 key = sensitive_data.host_pubkeys[i];
741 /* for RSA we also support SHA2 signatures */
742 append_hostkey_type(b, "rsa-sha2-512");
743 append_hostkey_type(b, "rsa-sha2-256");
749 append_hostkey_type(b, sshkey_ssh_name(key));
752 /* If the private key has a cert peer, then list that too */
753 key = sensitive_data.host_certificates[i];
758 /* for RSA we also support SHA2 signatures */
759 append_hostkey_type(b,
760 "rsa-sha2-512-cert-v01@openssh.com");
761 append_hostkey_type(b,
762 "rsa-sha2-256-cert-v01@openssh.com");
766 case KEY_ED25519_CERT:
768 append_hostkey_type(b, sshkey_ssh_name(key));
772 if ((ret = sshbuf_dup_string(b)) == NULL)
773 fatal("%s: sshbuf_dup_string failed", __func__);
775 debug("%s: %s", __func__, ret);
779 static struct sshkey *
780 get_hostkey_by_type(int type, int nid, int need_private, struct ssh *ssh)
785 for (i = 0; i < options.num_host_key_files; i++) {
790 case KEY_ED25519_CERT:
792 key = sensitive_data.host_certificates[i];
795 key = sensitive_data.host_keys[i];
796 if (key == NULL && !need_private)
797 key = sensitive_data.host_pubkeys[i];
800 if (key != NULL && key->type == type &&
801 (key->type != KEY_ECDSA || key->ecdsa_nid == nid))
802 return need_private ?
803 sensitive_data.host_keys[i] : key;
809 get_hostkey_public_by_type(int type, int nid, struct ssh *ssh)
811 return get_hostkey_by_type(type, nid, 0, ssh);
815 get_hostkey_private_by_type(int type, int nid, struct ssh *ssh)
817 return get_hostkey_by_type(type, nid, 1, ssh);
821 get_hostkey_by_index(int ind)
823 if (ind < 0 || (u_int)ind >= options.num_host_key_files)
825 return (sensitive_data.host_keys[ind]);
829 get_hostkey_public_by_index(int ind, struct ssh *ssh)
831 if (ind < 0 || (u_int)ind >= options.num_host_key_files)
833 return (sensitive_data.host_pubkeys[ind]);
837 get_hostkey_index(struct sshkey *key, int compare, struct ssh *ssh)
841 for (i = 0; i < options.num_host_key_files; i++) {
842 if (sshkey_is_cert(key)) {
843 if (key == sensitive_data.host_certificates[i] ||
844 (compare && sensitive_data.host_certificates[i] &&
846 sensitive_data.host_certificates[i])))
849 if (key == sensitive_data.host_keys[i] ||
850 (compare && sensitive_data.host_keys[i] &&
851 sshkey_equal(key, sensitive_data.host_keys[i])))
853 if (key == sensitive_data.host_pubkeys[i] ||
854 (compare && sensitive_data.host_pubkeys[i] &&
855 sshkey_equal(key, sensitive_data.host_pubkeys[i])))
862 /* Inform the client of all hostkeys */
864 notify_hostkeys(struct ssh *ssh)
872 /* Some clients cannot cope with the hostkeys message, skip those. */
873 if (datafellows & SSH_BUG_HOSTKEYS)
876 if ((buf = sshbuf_new()) == NULL)
877 fatal("%s: sshbuf_new", __func__);
878 for (i = nkeys = 0; i < options.num_host_key_files; i++) {
879 key = get_hostkey_public_by_index(i, ssh);
880 if (key == NULL || key->type == KEY_UNSPEC ||
883 fp = sshkey_fingerprint(key, options.fingerprint_hash,
885 debug3("%s: key %d: %s %s", __func__, i,
886 sshkey_ssh_name(key), fp);
889 packet_start(SSH2_MSG_GLOBAL_REQUEST);
890 packet_put_cstring("hostkeys-00@openssh.com");
891 packet_put_char(0); /* want-reply */
894 if ((r = sshkey_putb(key, buf)) != 0)
895 fatal("%s: couldn't put hostkey %d: %s",
896 __func__, i, ssh_err(r));
897 packet_put_string(sshbuf_ptr(buf), sshbuf_len(buf));
900 debug3("%s: sent %u hostkeys", __func__, nkeys);
902 fatal("%s: no hostkeys", __func__);
908 * returns 1 if connection should be dropped, 0 otherwise.
909 * dropping starts at connection #max_startups_begin with a probability
910 * of (max_startups_rate/100). the probability increases linearly until
911 * all connections are dropped for startups > max_startups
914 drop_connection(int startups)
918 if (startups < options.max_startups_begin)
920 if (startups >= options.max_startups)
922 if (options.max_startups_rate == 100)
925 p = 100 - options.max_startups_rate;
926 p *= startups - options.max_startups_begin;
927 p /= options.max_startups - options.max_startups_begin;
928 p += options.max_startups_rate;
929 r = arc4random_uniform(100);
931 debug("drop_connection: p %d, r %d", p, r);
932 return (r < p) ? 1 : 0;
938 if (options.version_addendum && *options.version_addendum != '\0')
939 fprintf(stderr, "%s %s, %s\n",
941 options.version_addendum, OPENSSL_VERSION_STRING);
943 fprintf(stderr, "%s, %s\n",
944 SSH_RELEASE, OPENSSL_VERSION_STRING);
946 "usage: sshd [-46DdeiqTt] [-C connection_spec] [-c host_cert_file]\n"
947 " [-E log_file] [-f config_file] [-g login_grace_time]\n"
948 " [-h host_key_file] [-o option] [-p port] [-u len]\n"
954 send_rexec_state(int fd, struct sshbuf *conf)
959 debug3("%s: entering fd = %d config len %zu", __func__, fd,
963 * Protocol from reexec master to child:
964 * string configuration
965 * string rngseed (only if OpenSSL is not self-seeded)
967 if ((m = sshbuf_new()) == NULL)
968 fatal("%s: sshbuf_new failed", __func__);
969 if ((r = sshbuf_put_stringb(m, conf)) != 0)
970 fatal("%s: buffer error: %s", __func__, ssh_err(r));
972 #if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
973 rexec_send_rng_seed(m);
976 if (ssh_msg_send(fd, 0, m) == -1)
977 fatal("%s: ssh_msg_send failed", __func__);
981 debug3("%s: done", __func__);
985 recv_rexec_state(int fd, struct sshbuf *conf)
992 debug3("%s: entering fd = %d", __func__, fd);
994 if ((m = sshbuf_new()) == NULL)
995 fatal("%s: sshbuf_new failed", __func__);
996 if (ssh_msg_recv(fd, m) == -1)
997 fatal("%s: ssh_msg_recv failed", __func__);
998 if ((r = sshbuf_get_u8(m, &ver)) != 0)
999 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1001 fatal("%s: rexec version mismatch", __func__);
1002 if ((r = sshbuf_get_string(m, &cp, &len)) != 0)
1003 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1004 if (conf != NULL && (r = sshbuf_put(conf, cp, len)))
1005 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1006 #if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
1007 rexec_recv_rng_seed(m);
1013 debug3("%s: done", __func__);
1016 /* Accept a connection from inetd */
1018 server_accept_inetd(int *sock_in, int *sock_out)
1024 close(REEXEC_CONFIG_PASS_FD);
1025 *sock_in = *sock_out = dup(STDIN_FILENO);
1027 startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
1028 close(REEXEC_STARTUP_PIPE_FD);
1031 *sock_in = dup(STDIN_FILENO);
1032 *sock_out = dup(STDOUT_FILENO);
1035 * We intentionally do not close the descriptors 0, 1, and 2
1036 * as our code for setting the descriptors won't work if
1037 * ttyfd happens to be one of those.
1039 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1040 dup2(fd, STDIN_FILENO);
1041 dup2(fd, STDOUT_FILENO);
1043 dup2(fd, STDERR_FILENO);
1044 if (fd > (log_stderr ? STDERR_FILENO : STDOUT_FILENO))
1047 debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
1051 * Listen for TCP connections
1054 listen_on_addrs(struct listenaddr *la)
1056 int ret, listen_sock;
1057 struct addrinfo *ai;
1058 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1062 for (ai = la->addrs; ai; ai = ai->ai_next) {
1063 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1065 if (num_listen_socks >= MAX_LISTEN_SOCKS)
1066 fatal("Too many listen sockets. "
1067 "Enlarge MAX_LISTEN_SOCKS");
1068 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1069 ntop, sizeof(ntop), strport, sizeof(strport),
1070 NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1071 error("getnameinfo failed: %.100s",
1072 ssh_gai_strerror(ret));
1075 /* Create socket for listening. */
1076 listen_sock = socket(ai->ai_family, ai->ai_socktype,
1078 if (listen_sock < 0) {
1079 /* kernel may not support ipv6 */
1080 verbose("socket: %.100s", strerror(errno));
1083 if (set_nonblock(listen_sock) == -1) {
1087 if (fcntl(listen_sock, F_SETFD, FD_CLOEXEC) == -1) {
1088 verbose("socket: CLOEXEC: %s", strerror(errno));
1092 /* Socket options */
1093 set_reuseaddr(listen_sock);
1094 if (la->rdomain != NULL &&
1095 set_rdomain(listen_sock, la->rdomain) == -1) {
1100 /* Only communicate in IPv6 over AF_INET6 sockets. */
1101 if (ai->ai_family == AF_INET6)
1102 sock_set_v6only(listen_sock);
1104 debug("Bind to port %s on %s.", strport, ntop);
1106 len = sizeof(socksize);
1107 getsockopt(listen_sock, SOL_SOCKET, SO_RCVBUF, &socksize, &len);
1108 debug("Server TCP RWIN socket size: %d", socksize);
1110 /* Bind the socket to the desired port. */
1111 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1112 error("Bind to port %s on %s failed: %.200s.",
1113 strport, ntop, strerror(errno));
1117 listen_socks[num_listen_socks] = listen_sock;
1120 /* Start listening on the port. */
1121 if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1122 fatal("listen on [%s]:%s: %.100s",
1123 ntop, strport, strerror(errno));
1124 logit("Server listening on %s port %s%s%s.",
1126 la->rdomain == NULL ? "" : " rdomain ",
1127 la->rdomain == NULL ? "" : la->rdomain);
1136 for (i = 0; i < options.num_listen_addrs; i++) {
1137 listen_on_addrs(&options.listen_addrs[i]);
1138 freeaddrinfo(options.listen_addrs[i].addrs);
1139 free(options.listen_addrs[i].rdomain);
1140 memset(&options.listen_addrs[i], 0,
1141 sizeof(options.listen_addrs[i]));
1143 free(options.listen_addrs);
1144 options.listen_addrs = NULL;
1145 options.num_listen_addrs = 0;
1147 if (!num_listen_socks)
1148 fatal("Cannot bind any address.");
1152 * The main TCP accept loop. Note that, for the non-debug case, returns
1153 * from this function are in a forked subprocess.
1156 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1159 int i, j, ret, maxfd;
1161 int startup_p[2] = { -1 , -1 };
1162 struct sockaddr_storage from;
1167 /* setup fd set for accept */
1170 for (i = 0; i < num_listen_socks; i++)
1171 if (listen_socks[i] > maxfd)
1172 maxfd = listen_socks[i];
1173 /* pipes connected to unauthenticated childs */
1174 startup_pipes = xcalloc(options.max_startups, sizeof(int));
1175 for (i = 0; i < options.max_startups; i++)
1176 startup_pipes[i] = -1;
1179 * Stay listening for connections until the system crashes or
1180 * the daemon is killed with a signal.
1183 if (received_sighup)
1186 fdset = xcalloc(howmany(maxfd + 1, NFDBITS),
1189 for (i = 0; i < num_listen_socks; i++)
1190 FD_SET(listen_socks[i], fdset);
1191 for (i = 0; i < options.max_startups; i++)
1192 if (startup_pipes[i] != -1)
1193 FD_SET(startup_pipes[i], fdset);
1195 /* Wait in select until there is a connection. */
1196 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1197 if (ret < 0 && errno != EINTR)
1198 error("select: %.100s", strerror(errno));
1199 if (received_sigterm) {
1200 logit("Received signal %d; terminating.",
1201 (int) received_sigterm);
1202 close_listen_socks();
1203 if (options.pid_file != NULL)
1204 unlink(options.pid_file);
1205 exit(received_sigterm == SIGTERM ? 0 : 255);
1210 for (i = 0; i < options.max_startups; i++)
1211 if (startup_pipes[i] != -1 &&
1212 FD_ISSET(startup_pipes[i], fdset)) {
1214 * the read end of the pipe is ready
1215 * if the child has closed the pipe
1216 * after successful authentication
1217 * or if the child has died
1219 close(startup_pipes[i]);
1220 startup_pipes[i] = -1;
1223 for (i = 0; i < num_listen_socks; i++) {
1224 if (!FD_ISSET(listen_socks[i], fdset))
1226 fromlen = sizeof(from);
1227 *newsock = accept(listen_socks[i],
1228 (struct sockaddr *)&from, &fromlen);
1230 if (errno != EINTR && errno != EWOULDBLOCK &&
1231 errno != ECONNABORTED && errno != EAGAIN)
1232 error("accept: %.100s",
1234 if (errno == EMFILE || errno == ENFILE)
1238 if (unset_nonblock(*newsock) == -1) {
1242 if (drop_connection(startups) == 1) {
1243 char *laddr = get_local_ipaddr(*newsock);
1244 char *raddr = get_peer_ipaddr(*newsock);
1246 verbose("drop connection #%d from [%s]:%d "
1247 "on [%s]:%d past MaxStartups", startups,
1248 raddr, get_peer_port(*newsock),
1249 laddr, get_local_port(*newsock));
1255 if (pipe(startup_p) == -1) {
1260 if (rexec_flag && socketpair(AF_UNIX,
1261 SOCK_STREAM, 0, config_s) == -1) {
1262 error("reexec socketpair: %s",
1265 close(startup_p[0]);
1266 close(startup_p[1]);
1270 for (j = 0; j < options.max_startups; j++)
1271 if (startup_pipes[j] == -1) {
1272 startup_pipes[j] = startup_p[0];
1273 if (maxfd < startup_p[0])
1274 maxfd = startup_p[0];
1280 * Got connection. Fork a child to handle it, unless
1281 * we are in debugging mode.
1285 * In debugging mode. Close the listening
1286 * socket, and start processing the
1287 * connection without forking.
1289 debug("Server will not fork when running in debugging mode.");
1290 close_listen_socks();
1291 *sock_in = *newsock;
1292 *sock_out = *newsock;
1293 close(startup_p[0]);
1294 close(startup_p[1]);
1298 send_rexec_state(config_s[0], cfg);
1305 * Normal production daemon. Fork, and have
1306 * the child process the connection. The
1307 * parent continues listening.
1309 platform_pre_fork();
1310 if ((pid = fork()) == 0) {
1312 * Child. Close the listening and
1313 * max_startup sockets. Start using
1314 * the accepted socket. Reinitialize
1315 * logging (since our pid has changed).
1316 * We break out of the loop to handle
1319 platform_post_fork_child();
1320 startup_pipe = startup_p[1];
1321 close_startup_pipes();
1322 close_listen_socks();
1323 *sock_in = *newsock;
1324 *sock_out = *newsock;
1325 log_init(__progname,
1327 options.log_facility,
1334 /* Parent. Stay in the loop. */
1335 platform_post_fork_parent(pid);
1337 error("fork: %.100s", strerror(errno));
1339 debug("Forked child %ld.", (long)pid);
1341 close(startup_p[1]);
1344 send_rexec_state(config_s[0], cfg);
1351 * Ensure that our random state differs
1352 * from that of the child
1355 arc4random_buf(rnd, sizeof(rnd));
1357 RAND_seed(rnd, sizeof(rnd));
1358 if ((RAND_bytes((u_char *)rnd, 1)) != 1)
1359 fatal("%s: RAND_bytes failed", __func__);
1361 explicit_bzero(rnd, sizeof(rnd));
1364 /* child process check (or debug mode) */
1365 if (num_listen_socks < 0)
1371 * If IP options are supported, make sure there are none (log and
1372 * return an error if any are found). Basically we are worried about
1373 * source routing; it can be used to pretend you are somebody
1374 * (ip-address) you are not. That itself may be "almost acceptable"
1375 * under certain circumstances, but rhosts authentication is useless
1376 * if source routing is accepted. Notice also that if we just dropped
1377 * source routing here, the other side could use IP spoofing to do
1378 * rest of the interaction and could still bypass security. So we
1379 * exit here if we detect any IP options.
1382 check_ip_options(struct ssh *ssh)
1385 int sock_in = ssh_packet_get_connection_in(ssh);
1386 struct sockaddr_storage from;
1388 socklen_t i, option_size = sizeof(opts), fromlen = sizeof(from);
1389 char text[sizeof(opts) * 3 + 1];
1391 memset(&from, 0, sizeof(from));
1392 if (getpeername(sock_in, (struct sockaddr *)&from,
1395 if (from.ss_family != AF_INET)
1397 /* XXX IPv6 options? */
1399 if (getsockopt(sock_in, IPPROTO_IP, IP_OPTIONS, opts,
1400 &option_size) >= 0 && option_size != 0) {
1402 for (i = 0; i < option_size; i++)
1403 snprintf(text + i*3, sizeof(text) - i*3,
1405 fatal("Connection from %.100s port %d with IP opts: %.800s",
1406 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), text);
1409 #endif /* IP_OPTIONS */
1412 /* Set the routing domain for this process */
1414 set_process_rdomain(struct ssh *ssh, const char *name)
1416 #if defined(HAVE_SYS_SET_PROCESS_RDOMAIN)
1418 return; /* default */
1420 if (strcmp(name, "%D") == 0) {
1421 /* "expands" to routing domain of connection */
1422 if ((name = ssh_packet_rdomain_in(ssh)) == NULL)
1425 /* NB. We don't pass 'ssh' to sys_set_process_rdomain() */
1426 return sys_set_process_rdomain(name);
1427 #elif defined(__OpenBSD__)
1428 int rtable, ortable = getrtable();
1432 return; /* default */
1434 if (strcmp(name, "%D") == 0) {
1435 /* "expands" to routing domain of connection */
1436 if ((name = ssh_packet_rdomain_in(ssh)) == NULL)
1440 rtable = (int)strtonum(name, 0, 255, &errstr);
1441 if (errstr != NULL) /* Shouldn't happen */
1442 fatal("Invalid routing domain \"%s\": %s", name, errstr);
1443 if (rtable != ortable && setrtable(rtable) != 0)
1444 fatal("Unable to set routing domain %d: %s",
1445 rtable, strerror(errno));
1446 debug("%s: set routing domain %d (was %d)", __func__, rtable, ortable);
1447 #else /* defined(__OpenBSD__) */
1448 fatal("Unable to set routing domain: not supported in this platform");
1453 accumulate_host_timing_secret(struct sshbuf *server_cfg,
1454 const struct sshkey *key)
1456 static struct ssh_digest_ctx *ctx;
1462 if (ctx == NULL && (ctx = ssh_digest_start(SSH_DIGEST_SHA512)) == NULL)
1463 fatal("%s: ssh_digest_start", __func__);
1464 if (key == NULL) { /* finalize */
1465 /* add server config in case we are using agent for host keys */
1466 if (ssh_digest_update(ctx, sshbuf_ptr(server_cfg),
1467 sshbuf_len(server_cfg)) != 0)
1468 fatal("%s: ssh_digest_update", __func__);
1469 len = ssh_digest_bytes(SSH_DIGEST_SHA512);
1470 hash = xmalloc(len);
1471 if (ssh_digest_final(ctx, hash, len) != 0)
1472 fatal("%s: ssh_digest_final", __func__);
1473 options.timing_secret = PEEK_U64(hash);
1474 freezero(hash, len);
1475 ssh_digest_free(ctx);
1479 if ((buf = sshbuf_new()) == NULL)
1480 fatal("%s could not allocate buffer", __func__);
1481 if ((r = sshkey_private_serialize(key, buf)) != 0)
1482 fatal("sshkey_private_serialize: %s", ssh_err(r));
1483 if (ssh_digest_update(ctx, sshbuf_ptr(buf), sshbuf_len(buf)) != 0)
1484 fatal("%s: ssh_digest_update", __func__);
1490 * Main program for the daemon.
1493 main(int ac, char **av)
1495 struct ssh *ssh = NULL;
1496 extern char *optarg;
1498 int r, opt, on = 1, already_daemon, remote_port;
1499 int sock_in = -1, sock_out = -1, newsock = -1;
1500 const char *remote_ip, *rdomain;
1501 char *fp, *line, *laddr, *logfile = NULL;
1502 int config_s[2] = { -1 , -1 };
1504 u_int64_t ibytes, obytes;
1507 struct sshkey *pubkey;
1510 struct connection_info *connection_info = NULL;
1512 ssh_malloc_init(); /* must be called before any mallocs */
1514 #ifdef HAVE_SECUREWARE
1515 (void)set_auth_parameters(ac, av);
1517 __progname = ssh_get_progname(av[0]);
1519 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1522 saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1523 for (i = 0; (int)i < ac; i++)
1524 saved_argv[i] = xstrdup(av[i]);
1525 saved_argv[i] = NULL;
1527 #ifndef HAVE_SETPROCTITLE
1528 /* Prepare for later setproctitle emulation */
1529 compat_init_setproctitle(ac, av);
1533 if (geteuid() == 0 && setgroups(0, NULL) == -1)
1534 debug("setgroups(): %.200s", strerror(errno));
1536 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1539 /* Initialize configuration options to their default values. */
1540 initialize_server_options(&options);
1542 /* Parse command-line arguments. */
1543 while ((opt = getopt(ac, av,
1544 "C:E:b:c:f:g:h:k:o:p:u:46DQRTdeiqrt")) != -1) {
1547 options.address_family = AF_INET;
1550 options.address_family = AF_INET6;
1553 config_file_name = optarg;
1556 servconf_add_hostcert("[command-line]", 0,
1560 if (debug_flag == 0) {
1562 options.log_level = SYSLOG_LEVEL_DEBUG1;
1563 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1564 options.log_level++;
1589 options.log_level = SYSLOG_LEVEL_QUIET;
1592 /* protocol 1, ignored */
1595 options.ports_from_cmdline = 1;
1596 if (options.num_ports >= MAX_PORTS) {
1597 fprintf(stderr, "too many ports.\n");
1600 options.ports[options.num_ports++] = a2port(optarg);
1601 if (options.ports[options.num_ports-1] <= 0) {
1602 fprintf(stderr, "Bad port number.\n");
1607 if ((options.login_grace_time = convtime(optarg)) == -1) {
1608 fprintf(stderr, "Invalid login grace time.\n");
1613 /* protocol 1, ignored */
1616 servconf_add_hostkey("[command-line]", 0,
1626 connection_info = get_connection_info(0, 0);
1627 if (parse_server_match_testspec(connection_info,
1632 utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
1633 if (utmp_len > HOST_NAME_MAX+1) {
1634 fprintf(stderr, "Invalid utmp length.\n");
1639 line = xstrdup(optarg);
1640 if (process_server_config_line(&options, line,
1641 "command-line", 0, NULL, NULL) != 0)
1651 if (rexeced_flag || inetd_flag)
1653 if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1654 fatal("sshd re-exec requires execution with an absolute path");
1656 closefrom(REEXEC_MIN_FREE_FD);
1658 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1661 OpenSSL_add_all_algorithms();
1664 /* If requested, redirect the logs to the specified logfile. */
1665 if (logfile != NULL)
1666 log_redirect_stderr_to(logfile);
1668 * Force logging to stderr until we have loaded the private host
1669 * key (unless started from inetd)
1671 log_init(__progname,
1672 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1673 SYSLOG_LEVEL_INFO : options.log_level,
1674 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1675 SYSLOG_FACILITY_AUTH : options.log_facility,
1676 log_stderr || !inetd_flag);
1679 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1680 * root's environment
1682 if (getenv("KRB5CCNAME") != NULL)
1683 (void) unsetenv("KRB5CCNAME");
1685 sensitive_data.have_ssh2_key = 0;
1688 * If we're not doing an extended test do not silently ignore connection
1691 if (test_flag < 2 && connection_info != NULL)
1692 fatal("Config test connection parameter (-C) provided without "
1695 /* Fetch our configuration */
1696 if ((cfg = sshbuf_new()) == NULL)
1697 fatal("%s: sshbuf_new failed", __func__);
1699 recv_rexec_state(REEXEC_CONFIG_PASS_FD, cfg);
1700 else if (strcasecmp(config_file_name, "none") != 0)
1701 load_server_config(config_file_name, cfg);
1703 parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1708 /* Fill in default values for those options not explicitly set. */
1709 fill_default_server_options(&options);
1711 /* challenge-response is implemented via keyboard interactive */
1712 if (options.challenge_response_authentication)
1713 options.kbd_interactive_authentication = 1;
1715 /* Check that options are sensible */
1716 if (options.authorized_keys_command_user == NULL &&
1717 (options.authorized_keys_command != NULL &&
1718 strcasecmp(options.authorized_keys_command, "none") != 0))
1719 fatal("AuthorizedKeysCommand set without "
1720 "AuthorizedKeysCommandUser");
1721 if (options.authorized_principals_command_user == NULL &&
1722 (options.authorized_principals_command != NULL &&
1723 strcasecmp(options.authorized_principals_command, "none") != 0))
1724 fatal("AuthorizedPrincipalsCommand set without "
1725 "AuthorizedPrincipalsCommandUser");
1728 * Check whether there is any path through configured auth methods.
1729 * Unfortunately it is not possible to verify this generally before
1730 * daemonisation in the presence of Match block, but this catches
1731 * and warns for trivial misconfigurations that could break login.
1733 if (options.num_auth_methods != 0) {
1734 for (i = 0; i < options.num_auth_methods; i++) {
1735 if (auth2_methods_valid(options.auth_methods[i],
1739 if (i >= options.num_auth_methods)
1740 fatal("AuthenticationMethods cannot be satisfied by "
1741 "enabled authentication methods");
1744 /* Check that there are no remaining arguments. */
1746 fprintf(stderr, "Extra argument %s.\n", av[optind]);
1750 debug("sshd version %s, %s", SSH_VERSION,
1752 OpenSSL_version(OPENSSL_VERSION)
1758 /* Store privilege separation user for later use if required. */
1759 privsep_chroot = use_privsep && (getuid() == 0 || geteuid() == 0);
1760 if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1761 if (privsep_chroot || options.kerberos_authentication)
1762 fatal("Privilege separation user %s does not exist",
1765 privsep_pw = pwcopy(privsep_pw);
1766 freezero(privsep_pw->pw_passwd, strlen(privsep_pw->pw_passwd));
1767 privsep_pw->pw_passwd = xstrdup("*");
1771 /* load host keys */
1772 sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1773 sizeof(struct sshkey *));
1774 sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
1775 sizeof(struct sshkey *));
1777 if (options.host_key_agent) {
1778 if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
1779 setenv(SSH_AUTHSOCKET_ENV_NAME,
1780 options.host_key_agent, 1);
1781 if ((r = ssh_get_authentication_socket(NULL)) == 0)
1784 error("Could not connect to agent \"%s\": %s",
1785 options.host_key_agent, ssh_err(r));
1788 for (i = 0; i < options.num_host_key_files; i++) {
1789 if (options.host_key_files[i] == NULL)
1791 if ((r = sshkey_load_private(options.host_key_files[i], "",
1792 &key, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR)
1793 error("Error loading host key \"%s\": %s",
1794 options.host_key_files[i], ssh_err(r));
1795 if ((r = sshkey_load_public(options.host_key_files[i],
1796 &pubkey, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR)
1797 error("Error loading host key \"%s\": %s",
1798 options.host_key_files[i], ssh_err(r));
1799 if (pubkey == NULL && key != NULL)
1800 if ((r = sshkey_from_private(key, &pubkey)) != 0)
1801 fatal("Could not demote key: \"%s\": %s",
1802 options.host_key_files[i], ssh_err(r));
1803 sensitive_data.host_keys[i] = key;
1804 sensitive_data.host_pubkeys[i] = pubkey;
1806 if (key == NULL && pubkey != NULL && have_agent) {
1807 debug("will rely on agent for hostkey %s",
1808 options.host_key_files[i]);
1809 keytype = pubkey->type;
1810 } else if (key != NULL) {
1811 keytype = key->type;
1812 accumulate_host_timing_secret(cfg, key);
1814 error("Could not load host key: %s",
1815 options.host_key_files[i]);
1816 sensitive_data.host_keys[i] = NULL;
1817 sensitive_data.host_pubkeys[i] = NULL;
1827 if (have_agent || key != NULL)
1828 sensitive_data.have_ssh2_key = 1;
1831 if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash,
1832 SSH_FP_DEFAULT)) == NULL)
1833 fatal("sshkey_fingerprint failed");
1834 debug("%s host key #%d: %s %s",
1835 key ? "private" : "agent", i, sshkey_ssh_name(pubkey), fp);
1838 accumulate_host_timing_secret(cfg, NULL);
1839 if (!sensitive_data.have_ssh2_key) {
1840 logit("sshd: no hostkeys available -- exiting.");
1845 * Load certificates. They are stored in an array at identical
1846 * indices to the public keys that they relate to.
1848 sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
1849 sizeof(struct sshkey *));
1850 for (i = 0; i < options.num_host_key_files; i++)
1851 sensitive_data.host_certificates[i] = NULL;
1853 for (i = 0; i < options.num_host_cert_files; i++) {
1854 if (options.host_cert_files[i] == NULL)
1856 if ((r = sshkey_load_public(options.host_cert_files[i],
1857 &key, NULL)) != 0) {
1858 error("Could not load host certificate \"%s\": %s",
1859 options.host_cert_files[i], ssh_err(r));
1862 if (!sshkey_is_cert(key)) {
1863 error("Certificate file is not a certificate: %s",
1864 options.host_cert_files[i]);
1868 /* Find matching private key */
1869 for (j = 0; j < options.num_host_key_files; j++) {
1870 if (sshkey_equal_public(key,
1871 sensitive_data.host_keys[j])) {
1872 sensitive_data.host_certificates[j] = key;
1876 if (j >= options.num_host_key_files) {
1877 error("No matching private key for certificate: %s",
1878 options.host_cert_files[i]);
1882 sensitive_data.host_certificates[j] = key;
1883 debug("host certificate: #%u type %d %s", j, key->type,
1887 if (privsep_chroot) {
1890 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1891 (S_ISDIR(st.st_mode) == 0))
1892 fatal("Missing privilege separation directory: %s",
1893 _PATH_PRIVSEP_CHROOT_DIR);
1896 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1897 (st.st_uid != getuid () ||
1898 (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1900 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1902 fatal("%s must be owned by root and not group or "
1903 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1906 if (test_flag > 1) {
1908 * If no connection info was provided by -C then use
1909 * use a blank one that will cause no predicate to match.
1911 if (connection_info == NULL)
1912 connection_info = get_connection_info(0, 0);
1913 parse_server_match_config(&options, connection_info);
1914 dump_config(&options);
1917 /* Configuration looks good, so exit if in test mode. */
1922 * Clear out any supplemental groups we may have inherited. This
1923 * prevents inadvertent creation of files with bad modes (in the
1924 * portable version at least, it's certainly possible for PAM
1925 * to create a file, and we can't control the code in every
1926 * module which might be used).
1928 if (setgroups(0, NULL) < 0)
1929 debug("setgroups() failed: %.200s", strerror(errno));
1933 fatal("rexec_argc %d < 0", rexec_argc);
1934 rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1935 for (i = 0; i < (u_int)rexec_argc; i++) {
1936 debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1937 rexec_argv[i] = saved_argv[i];
1939 rexec_argv[rexec_argc] = "-R";
1940 rexec_argv[rexec_argc + 1] = NULL;
1943 /* Ensure that umask disallows at least group and world write */
1944 new_umask = umask(0077) | 0022;
1945 (void) umask(new_umask);
1947 /* Initialize the log (it is reinitialized below in case we forked). */
1948 if (debug_flag && (!inetd_flag || rexeced_flag))
1950 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1953 * If not in debugging mode, not started from inetd and not already
1954 * daemonized (eg re-exec via SIGHUP), disconnect from the controlling
1955 * terminal, and fork. The original process exits.
1957 already_daemon = daemonized();
1958 if (!(debug_flag || inetd_flag || no_daemon_flag || already_daemon)) {
1960 if (daemon(0, 0) < 0)
1961 fatal("daemon() failed: %.200s", strerror(errno));
1963 disconnect_controlling_tty();
1965 /* Reinitialize the log (because of the fork above). */
1966 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1968 /* Avoid killing the process in high-pressure swapping environments. */
1969 if (!inetd_flag && madvise(NULL, 0, MADV_PROTECT) != 0)
1970 debug("madvise(): %.200s", strerror(errno));
1972 /* Chdir to the root directory so that the current disk can be
1973 unmounted if desired. */
1974 if (chdir("/") == -1)
1975 error("chdir(\"/\"): %s", strerror(errno));
1977 /* ignore SIGPIPE */
1978 signal(SIGPIPE, SIG_IGN);
1980 /* Get a connection, either from inetd or a listening TCP socket */
1982 server_accept_inetd(&sock_in, &sock_out);
1984 platform_pre_listen();
1987 signal(SIGHUP, sighup_handler);
1988 signal(SIGCHLD, main_sigchld_handler);
1989 signal(SIGTERM, sigterm_handler);
1990 signal(SIGQUIT, sigterm_handler);
1993 * Write out the pid file after the sigterm handler
1994 * is setup and the listen sockets are bound
1996 if (options.pid_file != NULL && !debug_flag) {
1997 FILE *f = fopen(options.pid_file, "w");
2000 error("Couldn't create pid file \"%s\": %s",
2001 options.pid_file, strerror(errno));
2003 fprintf(f, "%ld\n", (long) getpid());
2008 /* Accept a connection and return in a forked child */
2009 server_accept_loop(&sock_in, &sock_out,
2010 &newsock, config_s);
2013 /* This is the child processing a new connection. */
2014 setproctitle("%s", "[accepted]");
2017 * Create a new session and process group since the 4.4BSD
2018 * setlogin() affects the entire process group. We don't
2019 * want the child to be able to affect the parent.
2021 #if !defined(SSHD_ACQUIRES_CTTY)
2023 * If setsid is called, on some platforms sshd will later acquire a
2024 * controlling terminal which will result in "could not set
2025 * controlling tty" errors.
2027 if (!debug_flag && !inetd_flag && setsid() < 0)
2028 error("setsid: %.100s", strerror(errno));
2034 debug("rexec start in %d out %d newsock %d pipe %d sock %d",
2035 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
2036 dup2(newsock, STDIN_FILENO);
2037 dup2(STDIN_FILENO, STDOUT_FILENO);
2038 if (startup_pipe == -1)
2039 close(REEXEC_STARTUP_PIPE_FD);
2040 else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) {
2041 dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
2042 close(startup_pipe);
2043 startup_pipe = REEXEC_STARTUP_PIPE_FD;
2046 dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
2049 execv(rexec_argv[0], rexec_argv);
2051 /* Reexec has failed, fall back and continue */
2052 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
2053 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
2054 log_init(__progname, options.log_level,
2055 options.log_facility, log_stderr);
2058 close(REEXEC_CONFIG_PASS_FD);
2059 newsock = sock_out = sock_in = dup(STDIN_FILENO);
2060 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
2061 dup2(fd, STDIN_FILENO);
2062 dup2(fd, STDOUT_FILENO);
2063 if (fd > STDERR_FILENO)
2066 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
2067 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
2070 /* Executed child processes don't need these. */
2071 fcntl(sock_out, F_SETFD, FD_CLOEXEC);
2072 fcntl(sock_in, F_SETFD, FD_CLOEXEC);
2075 * Disable the key regeneration alarm. We will not regenerate the
2076 * key since we are no longer in a position to give it to anyone. We
2077 * will not restart on SIGHUP since it no longer makes sense.
2080 signal(SIGALRM, SIG_DFL);
2081 signal(SIGHUP, SIG_DFL);
2082 signal(SIGTERM, SIG_DFL);
2083 signal(SIGQUIT, SIG_DFL);
2084 signal(SIGCHLD, SIG_DFL);
2085 signal(SIGINT, SIG_DFL);
2089 * Initialize the resolver. This may not happen automatically
2090 * before privsep chroot().
2092 if ((_res.options & RES_INIT) == 0) {
2093 debug("res_init()");
2098 * Force GSS-API to parse its configuration and load any
2099 * mechanism plugins.
2103 OM_uint32 minor_status;
2104 gss_indicate_mechs(&minor_status, &mechs);
2105 gss_release_oid_set(&minor_status, &mechs);
2111 * Register our connection. This turns encryption off because we do
2114 packet_set_connection(sock_in, sock_out);
2115 packet_set_server();
2116 ssh = active_state; /* XXX */
2118 check_ip_options(ssh);
2120 /* Prepare the channels layer */
2121 channel_init_channels(ssh);
2122 channel_set_af(ssh, options.address_family);
2123 process_permitopen(ssh, &options);
2125 /* Set SO_KEEPALIVE if requested. */
2126 if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
2127 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
2128 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
2130 if ((remote_port = ssh_remote_port(ssh)) < 0) {
2131 debug("ssh_remote_port failed");
2135 if (options.routing_domain != NULL)
2136 set_process_rdomain(ssh, options.routing_domain);
2139 * The rest of the code depends on the fact that
2140 * ssh_remote_ipaddr() caches the remote ip, even if
2141 * the socket goes away.
2143 remote_ip = ssh_remote_ipaddr(ssh);
2145 #ifdef HAVE_LOGIN_CAP
2146 /* Also caches remote hostname for sandboxed child. */
2147 auth_get_canonical_hostname(ssh, options.use_dns);
2150 #ifdef SSH_AUDIT_EVENTS
2151 audit_connection_from(remote_ip, remote_port);
2154 allow_severity = options.log_facility|LOG_INFO;
2155 deny_severity = options.log_facility|LOG_WARNING;
2156 /* Check whether logins are denied from this host. */
2157 if (packet_connection_is_on_socket()) {
2158 struct request_info req;
2160 request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
2163 if (!hosts_access(&req)) {
2164 debug("Connection refused by tcp wrapper");
2167 fatal("libwrap refuse returns");
2170 #endif /* LIBWRAP */
2172 rdomain = ssh_packet_rdomain_in(ssh);
2174 /* Log the connection. */
2175 laddr = get_local_ipaddr(sock_in);
2176 verbose("Connection from %s port %d on %s port %d%s%s%s",
2177 remote_ip, remote_port, laddr, ssh_local_port(ssh),
2178 rdomain == NULL ? "" : " rdomain \"",
2179 rdomain == NULL ? "" : rdomain,
2180 rdomain == NULL ? "" : "\"");
2184 * We don't want to listen forever unless the other side
2185 * successfully authenticates itself. So we set up an alarm which is
2186 * cleared after successful authentication. A limit of zero
2187 * indicates no limit. Note that we don't set the alarm in debugging
2188 * mode; it is just annoying to have the server exit just when you
2189 * are about to discover the bug.
2191 signal(SIGALRM, grace_alarm_handler);
2193 alarm(options.login_grace_time);
2195 sshd_exchange_identification(ssh, sock_in, sock_out);
2196 packet_set_nonblocking();
2198 /* allocate authentication context */
2199 authctxt = xcalloc(1, sizeof(*authctxt));
2201 authctxt->loginmsg = loginmsg;
2203 /* XXX global for cleanup, access from other modules */
2204 the_authctxt = authctxt;
2206 /* Set default key authentication options */
2207 if ((auth_opts = sshauthopt_new_with_keys_defaults()) == NULL)
2208 fatal("allocation failed");
2210 /* prepare buffer to collect messages to display to user after login */
2211 if ((loginmsg = sshbuf_new()) == NULL)
2212 fatal("%s: sshbuf_new failed", __func__);
2218 if (privsep_preauth(authctxt) == 1)
2220 } else if (have_agent) {
2221 if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) {
2222 error("Unable to get agent socket: %s", ssh_err(r));
2227 /* perform the key exchange */
2228 /* authenticate user and start session */
2230 do_authentication2(authctxt);
2233 * If we use privilege separation, the unprivileged child transfers
2234 * the current keystate and exits
2237 mm_send_keystate(pmonitor);
2238 packet_clear_keys();
2244 * Cancel the alarm we set to limit the time taken for
2248 signal(SIGALRM, SIG_DFL);
2249 authctxt->authenticated = 1;
2250 if (startup_pipe != -1) {
2251 close(startup_pipe);
2255 #ifdef SSH_AUDIT_EVENTS
2256 audit_event(SSH_AUTH_SUCCESS);
2260 if (options.gss_authentication) {
2261 temporarily_use_uid(authctxt->pw);
2262 ssh_gssapi_storecreds();
2267 if (options.use_pam) {
2269 do_pam_session(ssh);
2274 * In privilege separation, we fork another child and prepare
2275 * file descriptor passing.
2278 privsep_postauth(authctxt);
2279 /* the monitor process [priv] will not return */
2282 packet_set_timeout(options.client_alive_interval,
2283 options.client_alive_count_max);
2285 /* Try to send all our hostkeys to the client */
2286 notify_hostkeys(ssh);
2288 /* Start session. */
2289 do_authenticated(ssh, authctxt);
2291 /* The connection has been terminated. */
2292 packet_get_bytes(&ibytes, &obytes);
2293 verbose("Transferred: sent %llu, received %llu bytes",
2294 (unsigned long long)obytes, (unsigned long long)ibytes);
2296 verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
2299 if (options.use_pam)
2301 #endif /* USE_PAM */
2303 #ifdef SSH_AUDIT_EVENTS
2304 PRIVSEP(audit_event(SSH_CONNECTION_CLOSE));
2316 sshd_hostkey_sign(struct sshkey *privkey, struct sshkey *pubkey,
2317 u_char **signature, size_t *slenp, const u_char *data, size_t dlen,
2318 const char *alg, u_int flag)
2323 if (PRIVSEP(sshkey_sign(privkey, signature, slenp, data, dlen,
2324 alg, datafellows)) < 0)
2325 fatal("%s: key_sign failed", __func__);
2326 } else if (use_privsep) {
2327 if (mm_sshkey_sign(pubkey, signature, slenp, data, dlen,
2328 alg, datafellows) < 0)
2329 fatal("%s: pubkey_sign failed", __func__);
2331 if ((r = ssh_agent_sign(auth_sock, pubkey, signature, slenp,
2332 data, dlen, alg, datafellows)) != 0)
2333 fatal("%s: ssh_agent_sign failed: %s",
2334 __func__, ssh_err(r));
2339 /* SSH2 key exchange */
2343 char *myproposal[PROPOSAL_MAX] = { KEX_SERVER };
2347 myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(
2348 options.kex_algorithms);
2349 myproposal[PROPOSAL_ENC_ALGS_CTOS] = compat_cipher_proposal(
2351 myproposal[PROPOSAL_ENC_ALGS_STOC] = compat_cipher_proposal(
2353 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2354 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2356 if (options.compression == COMP_NONE) {
2357 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2358 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2361 if (options.rekey_limit || options.rekey_interval)
2362 packet_set_rekey_limits(options.rekey_limit,
2363 options.rekey_interval);
2365 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal(
2366 list_hostkey_types());
2368 /* start key exchange */
2369 if ((r = kex_setup(active_state, myproposal)) != 0)
2370 fatal("kex_setup: %s", ssh_err(r));
2371 kex = active_state->kex;
2373 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2374 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
2375 kex->kex[KEX_DH_GRP14_SHA256] = kexdh_server;
2376 kex->kex[KEX_DH_GRP16_SHA512] = kexdh_server;
2377 kex->kex[KEX_DH_GRP18_SHA512] = kexdh_server;
2378 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2379 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2380 # ifdef OPENSSL_HAS_ECC
2381 kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
2384 kex->kex[KEX_C25519_SHA256] = kexc25519_server;
2386 kex->client_version_string=client_version_string;
2387 kex->server_version_string=server_version_string;
2388 kex->load_host_public_key=&get_hostkey_public_by_type;
2389 kex->load_host_private_key=&get_hostkey_private_by_type;
2390 kex->host_key_index=&get_hostkey_index;
2391 kex->sign = sshd_hostkey_sign;
2393 ssh_dispatch_run_fatal(active_state, DISPATCH_BLOCK, &kex->done);
2395 session_id2 = kex->session_id;
2396 session_id2_len = kex->session_id_len;
2399 /* send 1st encrypted/maced/compressed message */
2400 packet_start(SSH2_MSG_IGNORE);
2401 packet_put_cstring("markus");
2403 packet_write_wait();
2408 /* server specific fatal cleanup */
2412 struct ssh *ssh = active_state; /* XXX */
2415 do_cleanup(ssh, the_authctxt);
2416 if (use_privsep && privsep_is_preauth &&
2417 pmonitor != NULL && pmonitor->m_pid > 1) {
2418 debug("Killing privsep child %d", pmonitor->m_pid);
2419 if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
2421 error("%s: kill(%d): %s", __func__,
2422 pmonitor->m_pid, strerror(errno));
2425 #ifdef SSH_AUDIT_EVENTS
2426 /* done after do_cleanup so it can cancel the PAM auth 'thread' */
2427 if (!use_privsep || mm_is_monitor())
2428 audit_event(SSH_CONNECTION_ABANDON);