1 /* $OpenBSD: sshd.c,v 1.533 2019/03/01 02:32:39 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.
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"
77 #include <openssl/dh.h>
78 #include <openssl/bn.h>
79 #include <openssl/rand.h>
80 #include "openbsd-compat/openssl-compat.h"
83 #ifdef HAVE_SECUREWARE
84 #include <sys/security.h>
104 #include "myproposal.h"
105 #include "authfile.h"
106 #include "pathnames.h"
107 #include "atomicio.h"
108 #include "canohost.h"
109 #include "hostfile.h"
113 #include "dispatch.h"
114 #include "channels.h"
120 #include "monitor_wrap.h"
121 #include "ssh-sandbox.h"
122 #include "auth-options.h"
127 #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
128 #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
129 #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
130 #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
132 extern char *__progname;
134 /* Server configuration options. */
135 ServerOptions options;
137 /* Name of the server configuration file. */
138 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
141 * Debug mode flag. This can be set on the command line. If debug
142 * mode is enabled, extra debugging output will be sent to the system
143 * log, the daemon will not go to background, and will exit after processing
144 * the first connection.
149 * Indicating that the daemon should only test the configuration and keys.
150 * If test_flag > 1 ("-T" flag), then sshd will also dump the effective
151 * configuration, optionally using connection information provided by the
154 static int test_flag = 0;
156 /* Flag indicating that the daemon is being started from inetd. */
157 static int inetd_flag = 0;
159 /* Flag indicating that sshd should not detach and become a daemon. */
160 static int no_daemon_flag = 0;
162 /* debug goes to stderr unless inetd_flag is set */
163 static int log_stderr = 0;
165 /* Saved arguments to main(). */
166 static char **saved_argv;
167 static int saved_argc;
170 static int rexeced_flag = 0;
171 static int rexec_flag = 1;
172 static int rexec_argc = 0;
173 static char **rexec_argv;
176 * The sockets that the server is listening; this is used in the SIGHUP
179 #define MAX_LISTEN_SOCKS 16
180 static int listen_socks[MAX_LISTEN_SOCKS];
181 static int num_listen_socks = 0;
183 /* Daemon's agent connection */
185 static int have_agent = 0;
188 * Any really sensitive data in the application is contained in this
189 * structure. The idea is that this structure could be locked into memory so
190 * that the pages do not get written into swap. However, there are some
191 * problems. The private key contains BIGNUMs, and we do not (in principle)
192 * have access to the internals of them, and locking just the structure is
193 * not very useful. Currently, memory locking is not implemented.
196 struct sshkey **host_keys; /* all private host keys */
197 struct sshkey **host_pubkeys; /* all public host keys */
198 struct sshkey **host_certificates; /* all public host certificates */
202 /* This is set to true when a signal is received. */
203 static volatile sig_atomic_t received_sighup = 0;
204 static volatile sig_atomic_t received_sigterm = 0;
206 /* session identifier, used by RSA-auth */
207 u_char session_id[16];
210 u_char *session_id2 = NULL;
211 u_int session_id2_len = 0;
213 /* record remote hostname or ip */
214 u_int utmp_len = HOST_NAME_MAX+1;
217 * startup_pipes/flags are used for tracking children of the listening sshd
218 * process early in their lifespans. This tracking is needed for three things:
220 * 1) Implementing the MaxStartups limit of concurrent unauthenticated
222 * 2) Avoiding a race condition for SIGHUP processing, where child processes
223 * may have listen_socks open that could collide with main listener process
225 * 3) Ensuring that rexec'd sshd processes have received their initial state
226 * from the parent listen process before handling SIGHUP.
228 * Child processes signal that they have completed closure of the listen_socks
229 * and (if applicable) received their rexec state by sending a char over their
230 * sock. Child processes signal that authentication has completed by closing
231 * the sock (or by exiting).
233 static int *startup_pipes = NULL;
234 static int *startup_flags = NULL; /* Indicates child closed listener */
235 static int startup_pipe = -1; /* in child */
237 /* variables used for privilege separation */
238 int use_privsep = -1;
239 struct monitor *pmonitor = NULL;
240 int privsep_is_preauth = 1;
241 static int privsep_chroot = 1;
243 /* global connection state and authentication contexts */
244 Authctxt *the_authctxt = NULL;
245 struct ssh *the_active_state;
247 /* global key/cert auth options. XXX move to permanent ssh->authctxt? */
248 struct sshauthopt *auth_opts = NULL;
250 /* sshd_config buffer */
253 /* message to be displayed after login */
254 struct sshbuf *loginmsg;
256 /* Unprivileged user */
257 struct passwd *privsep_pw = NULL;
259 /* Prototypes for various functions defined later in this file. */
260 void destroy_sensitive_data(void);
261 void demote_sensitive_data(void);
262 static void do_ssh2_kex(struct ssh *);
265 * Close all listening sockets
268 close_listen_socks(void)
272 for (i = 0; i < num_listen_socks; i++)
273 close(listen_socks[i]);
274 num_listen_socks = -1;
278 close_startup_pipes(void)
283 for (i = 0; i < options.max_startups; i++)
284 if (startup_pipes[i] != -1)
285 close(startup_pipes[i]);
289 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
290 * the effect is to reread the configuration file (and to regenerate
296 sighup_handler(int sig)
298 int save_errno = errno;
305 * Called from the main program after receiving SIGHUP.
306 * Restarts the server.
311 logit("Received SIGHUP; restarting.");
312 if (options.pid_file != NULL)
313 unlink(options.pid_file);
314 platform_pre_restart();
315 close_listen_socks();
316 close_startup_pipes();
317 alarm(0); /* alarm timer persists across exec */
318 signal(SIGHUP, SIG_IGN); /* will be restored after exec */
319 execv(saved_argv[0], saved_argv);
320 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
326 * Generic signal handler for terminating signals in the master daemon.
330 sigterm_handler(int sig)
332 received_sigterm = sig;
336 * SIGCHLD handler. This is called whenever a child dies. This will then
337 * reap any zombies left by exited children.
341 main_sigchld_handler(int sig)
343 int save_errno = errno;
347 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
348 (pid < 0 && errno == EINTR))
354 * Signal handler for the alarm after the login grace period has expired.
358 grace_alarm_handler(int sig)
360 if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
361 kill(pmonitor->m_pid, SIGALRM);
364 * Try to kill any processes that we have spawned, E.g. authorized
365 * keys command helpers.
367 if (getpgid(0) == getpid()) {
368 signal(SIGTERM, SIG_IGN);
372 /* XXX pre-format ipaddr/port so we don't need to access active_state */
373 /* Log error and exit. */
374 sigdie("Timeout before authentication for %s port %d",
375 ssh_remote_ipaddr(the_active_state),
376 ssh_remote_port(the_active_state));
379 /* Destroy the host and server keys. They will no longer be needed. */
381 destroy_sensitive_data(void)
385 for (i = 0; i < options.num_host_key_files; i++) {
386 if (sensitive_data.host_keys[i]) {
387 sshkey_free(sensitive_data.host_keys[i]);
388 sensitive_data.host_keys[i] = NULL;
390 if (sensitive_data.host_certificates[i]) {
391 sshkey_free(sensitive_data.host_certificates[i]);
392 sensitive_data.host_certificates[i] = NULL;
397 /* Demote private to public keys for network child */
399 demote_sensitive_data(void)
405 for (i = 0; i < options.num_host_key_files; i++) {
406 if (sensitive_data.host_keys[i]) {
407 if ((r = sshkey_from_private(
408 sensitive_data.host_keys[i], &tmp)) != 0)
409 fatal("could not demote host %s key: %s",
410 sshkey_type(sensitive_data.host_keys[i]),
412 sshkey_free(sensitive_data.host_keys[i]);
413 sensitive_data.host_keys[i] = tmp;
415 /* Certs do not need demotion */
427 arc4random_stir(); /* noop on recent arc4random() implementations */
428 arc4random_buf(rnd, sizeof(rnd)); /* let arc4random notice PID change */
431 RAND_seed(rnd, sizeof(rnd));
432 /* give libcrypto a chance to notice the PID change */
433 if ((RAND_bytes((u_char *)rnd, 1)) != 1)
434 fatal("%s: RAND_bytes failed", __func__);
437 explicit_bzero(rnd, sizeof(rnd));
441 privsep_preauth_child(void)
445 /* Enable challenge-response authentication for privilege separation */
446 privsep_challenge_enable();
449 /* Cache supported mechanism OIDs for later use */
450 ssh_gssapi_prepare_supported_oids();
455 /* Demote the private keys to public keys. */
456 demote_sensitive_data();
458 /* Demote the child */
459 if (privsep_chroot) {
460 /* Change our root directory */
461 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
462 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
464 if (chdir("/") == -1)
465 fatal("chdir(\"/\"): %s", strerror(errno));
467 /* Drop our privileges */
468 debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
469 (u_int)privsep_pw->pw_gid);
470 gidset[0] = privsep_pw->pw_gid;
471 if (setgroups(1, gidset) < 0)
472 fatal("setgroups: %.100s", strerror(errno));
473 permanently_set_uid(privsep_pw);
478 privsep_preauth(struct ssh *ssh)
482 struct ssh_sandbox *box = NULL;
484 /* Set up unprivileged child process to deal with network data */
485 pmonitor = monitor_init();
486 /* Store a pointer to the kex for later rekeying */
487 pmonitor->m_pkex = &ssh->kex;
489 if (use_privsep == PRIVSEP_ON)
490 box = ssh_sandbox_init(pmonitor);
493 fatal("fork of unprivileged child failed");
494 } else if (pid != 0) {
495 debug2("Network child is on pid %ld", (long)pid);
497 pmonitor->m_pid = pid;
499 r = ssh_get_authentication_socket(&auth_sock);
501 error("Could not get agent socket: %s",
507 ssh_sandbox_parent_preauth(box, pid);
508 monitor_child_preauth(ssh, pmonitor);
510 /* Wait for the child's exit status */
511 while (waitpid(pid, &status, 0) < 0) {
514 pmonitor->m_pid = -1;
515 fatal("%s: waitpid: %s", __func__, strerror(errno));
517 privsep_is_preauth = 0;
518 pmonitor->m_pid = -1;
519 if (WIFEXITED(status)) {
520 if (WEXITSTATUS(status) != 0)
521 fatal("%s: preauth child exited with status %d",
522 __func__, WEXITSTATUS(status));
523 } else if (WIFSIGNALED(status))
524 fatal("%s: preauth child terminated by signal %d",
525 __func__, WTERMSIG(status));
527 ssh_sandbox_parent_finish(box);
531 close(pmonitor->m_sendfd);
532 close(pmonitor->m_log_recvfd);
534 /* Arrange for logging to be sent to the monitor */
535 set_log_handler(mm_log_handler, pmonitor);
537 privsep_preauth_child();
538 setproctitle("%s", "[net]");
540 ssh_sandbox_child(box);
547 privsep_postauth(struct ssh *ssh, Authctxt *authctxt)
549 #ifdef DISABLE_FD_PASSING
552 if (authctxt->pw->pw_uid == 0) {
554 /* File descriptor passing is broken or root login */
559 /* New socket pair */
560 monitor_reinit(pmonitor);
562 pmonitor->m_pid = fork();
563 if (pmonitor->m_pid == -1)
564 fatal("fork of unprivileged child failed");
565 else if (pmonitor->m_pid != 0) {
566 verbose("User child is on pid %ld", (long)pmonitor->m_pid);
567 sshbuf_reset(loginmsg);
568 monitor_clear_keystate(ssh, pmonitor);
569 monitor_child_postauth(ssh, pmonitor);
577 close(pmonitor->m_sendfd);
578 pmonitor->m_sendfd = -1;
580 /* Demote the private keys to public keys. */
581 demote_sensitive_data();
585 /* Drop privileges */
586 do_setusercontext(authctxt->pw);
589 /* It is safe now to apply the key state */
590 monitor_apply_keystate(ssh, pmonitor);
593 * Tell the packet layer that authentication was successful, since
594 * this information is not part of the key state.
596 ssh_packet_set_authenticated(ssh);
600 append_hostkey_type(struct sshbuf *b, const char *s)
604 if (match_pattern_list(s, options.hostkeyalgorithms, 0) != 1) {
605 debug3("%s: %s key not permitted by HostkeyAlgorithms",
609 if ((r = sshbuf_putf(b, "%s%s", sshbuf_len(b) > 0 ? "," : "", s)) != 0)
610 fatal("%s: sshbuf_putf: %s", __func__, ssh_err(r));
614 list_hostkey_types(void)
621 if ((b = sshbuf_new()) == NULL)
622 fatal("%s: sshbuf_new failed", __func__);
623 for (i = 0; i < options.num_host_key_files; i++) {
624 key = sensitive_data.host_keys[i];
626 key = sensitive_data.host_pubkeys[i];
631 /* for RSA we also support SHA2 signatures */
632 append_hostkey_type(b, "rsa-sha2-512");
633 append_hostkey_type(b, "rsa-sha2-256");
639 append_hostkey_type(b, sshkey_ssh_name(key));
642 /* If the private key has a cert peer, then list that too */
643 key = sensitive_data.host_certificates[i];
648 /* for RSA we also support SHA2 signatures */
649 append_hostkey_type(b,
650 "rsa-sha2-512-cert-v01@openssh.com");
651 append_hostkey_type(b,
652 "rsa-sha2-256-cert-v01@openssh.com");
656 case KEY_ED25519_CERT:
658 append_hostkey_type(b, sshkey_ssh_name(key));
662 if ((ret = sshbuf_dup_string(b)) == NULL)
663 fatal("%s: sshbuf_dup_string failed", __func__);
665 debug("%s: %s", __func__, ret);
669 static struct sshkey *
670 get_hostkey_by_type(int type, int nid, int need_private, struct ssh *ssh)
675 for (i = 0; i < options.num_host_key_files; i++) {
680 case KEY_ED25519_CERT:
682 key = sensitive_data.host_certificates[i];
685 key = sensitive_data.host_keys[i];
686 if (key == NULL && !need_private)
687 key = sensitive_data.host_pubkeys[i];
690 if (key != NULL && key->type == type &&
691 (key->type != KEY_ECDSA || key->ecdsa_nid == nid))
692 return need_private ?
693 sensitive_data.host_keys[i] : key;
699 get_hostkey_public_by_type(int type, int nid, struct ssh *ssh)
701 return get_hostkey_by_type(type, nid, 0, ssh);
705 get_hostkey_private_by_type(int type, int nid, struct ssh *ssh)
707 return get_hostkey_by_type(type, nid, 1, ssh);
711 get_hostkey_by_index(int ind)
713 if (ind < 0 || (u_int)ind >= options.num_host_key_files)
715 return (sensitive_data.host_keys[ind]);
719 get_hostkey_public_by_index(int ind, struct ssh *ssh)
721 if (ind < 0 || (u_int)ind >= options.num_host_key_files)
723 return (sensitive_data.host_pubkeys[ind]);
727 get_hostkey_index(struct sshkey *key, int compare, struct ssh *ssh)
731 for (i = 0; i < options.num_host_key_files; i++) {
732 if (sshkey_is_cert(key)) {
733 if (key == sensitive_data.host_certificates[i] ||
734 (compare && sensitive_data.host_certificates[i] &&
736 sensitive_data.host_certificates[i])))
739 if (key == sensitive_data.host_keys[i] ||
740 (compare && sensitive_data.host_keys[i] &&
741 sshkey_equal(key, sensitive_data.host_keys[i])))
743 if (key == sensitive_data.host_pubkeys[i] ||
744 (compare && sensitive_data.host_pubkeys[i] &&
745 sshkey_equal(key, sensitive_data.host_pubkeys[i])))
752 /* Inform the client of all hostkeys */
754 notify_hostkeys(struct ssh *ssh)
762 /* Some clients cannot cope with the hostkeys message, skip those. */
763 if (ssh->compat & SSH_BUG_HOSTKEYS)
766 if ((buf = sshbuf_new()) == NULL)
767 fatal("%s: sshbuf_new", __func__);
768 for (i = nkeys = 0; i < options.num_host_key_files; i++) {
769 key = get_hostkey_public_by_index(i, ssh);
770 if (key == NULL || key->type == KEY_UNSPEC ||
773 fp = sshkey_fingerprint(key, options.fingerprint_hash,
775 debug3("%s: key %d: %s %s", __func__, i,
776 sshkey_ssh_name(key), fp);
780 * Start building the request when we find the
783 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
784 (r = sshpkt_put_cstring(ssh, "hostkeys-00@openssh.com")) != 0 ||
785 (r = sshpkt_put_u8(ssh, 0)) != 0) /* want reply */
786 sshpkt_fatal(ssh, r, "%s: start request", __func__);
788 /* Append the key to the request */
790 if ((r = sshkey_putb(key, buf)) != 0)
791 fatal("%s: couldn't put hostkey %d: %s",
792 __func__, i, ssh_err(r));
793 if ((r = sshpkt_put_stringb(ssh, buf)) != 0)
794 sshpkt_fatal(ssh, r, "%s: append key", __func__);
797 debug3("%s: sent %u hostkeys", __func__, nkeys);
799 fatal("%s: no hostkeys", __func__);
800 if ((r = sshpkt_send(ssh)) != 0)
801 sshpkt_fatal(ssh, r, "%s: send", __func__);
806 * returns 1 if connection should be dropped, 0 otherwise.
807 * dropping starts at connection #max_startups_begin with a probability
808 * of (max_startups_rate/100). the probability increases linearly until
809 * all connections are dropped for startups > max_startups
812 drop_connection(int startups)
816 if (startups < options.max_startups_begin)
818 if (startups >= options.max_startups)
820 if (options.max_startups_rate == 100)
823 p = 100 - options.max_startups_rate;
824 p *= startups - options.max_startups_begin;
825 p /= options.max_startups - options.max_startups_begin;
826 p += options.max_startups_rate;
827 r = arc4random_uniform(100);
829 debug("drop_connection: p %d, r %d", p, r);
830 return (r < p) ? 1 : 0;
836 fprintf(stderr, "%s, %s\n",
839 OpenSSL_version(OPENSSL_VERSION)
845 "usage: sshd [-46DdeiqTt] [-C connection_spec] [-c host_cert_file]\n"
846 " [-E log_file] [-f config_file] [-g login_grace_time]\n"
847 " [-h host_key_file] [-o option] [-p port] [-u len]\n"
853 send_rexec_state(int fd, struct sshbuf *conf)
858 debug3("%s: entering fd = %d config len %zu", __func__, fd,
862 * Protocol from reexec master to child:
863 * string configuration
864 * string rngseed (only if OpenSSL is not self-seeded)
866 if ((m = sshbuf_new()) == NULL)
867 fatal("%s: sshbuf_new failed", __func__);
868 if ((r = sshbuf_put_stringb(m, conf)) != 0)
869 fatal("%s: buffer error: %s", __func__, ssh_err(r));
871 #if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
872 rexec_send_rng_seed(m);
875 if (ssh_msg_send(fd, 0, m) == -1)
876 fatal("%s: ssh_msg_send failed", __func__);
880 debug3("%s: done", __func__);
884 recv_rexec_state(int fd, struct sshbuf *conf)
891 debug3("%s: entering fd = %d", __func__, fd);
893 if ((m = sshbuf_new()) == NULL)
894 fatal("%s: sshbuf_new failed", __func__);
895 if (ssh_msg_recv(fd, m) == -1)
896 fatal("%s: ssh_msg_recv failed", __func__);
897 if ((r = sshbuf_get_u8(m, &ver)) != 0)
898 fatal("%s: buffer error: %s", __func__, ssh_err(r));
900 fatal("%s: rexec version mismatch", __func__);
901 if ((r = sshbuf_get_string(m, &cp, &len)) != 0)
902 fatal("%s: buffer error: %s", __func__, ssh_err(r));
903 if (conf != NULL && (r = sshbuf_put(conf, cp, len)))
904 fatal("%s: buffer error: %s", __func__, ssh_err(r));
905 #if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
906 rexec_recv_rng_seed(m);
912 debug3("%s: done", __func__);
915 /* Accept a connection from inetd */
917 server_accept_inetd(int *sock_in, int *sock_out)
922 close(REEXEC_CONFIG_PASS_FD);
923 *sock_in = *sock_out = dup(STDIN_FILENO);
925 *sock_in = dup(STDIN_FILENO);
926 *sock_out = dup(STDOUT_FILENO);
929 * We intentionally do not close the descriptors 0, 1, and 2
930 * as our code for setting the descriptors won't work if
931 * ttyfd happens to be one of those.
933 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
934 dup2(fd, STDIN_FILENO);
935 dup2(fd, STDOUT_FILENO);
937 dup2(fd, STDERR_FILENO);
938 if (fd > (log_stderr ? STDERR_FILENO : STDOUT_FILENO))
941 debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
945 * Listen for TCP connections
948 listen_on_addrs(struct listenaddr *la)
950 int ret, listen_sock;
952 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
954 for (ai = la->addrs; ai; ai = ai->ai_next) {
955 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
957 if (num_listen_socks >= MAX_LISTEN_SOCKS)
958 fatal("Too many listen sockets. "
959 "Enlarge MAX_LISTEN_SOCKS");
960 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
961 ntop, sizeof(ntop), strport, sizeof(strport),
962 NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
963 error("getnameinfo failed: %.100s",
964 ssh_gai_strerror(ret));
967 /* Create socket for listening. */
968 listen_sock = socket(ai->ai_family, ai->ai_socktype,
970 if (listen_sock < 0) {
971 /* kernel may not support ipv6 */
972 verbose("socket: %.100s", strerror(errno));
975 if (set_nonblock(listen_sock) == -1) {
979 if (fcntl(listen_sock, F_SETFD, FD_CLOEXEC) == -1) {
980 verbose("socket: CLOEXEC: %s", strerror(errno));
985 set_reuseaddr(listen_sock);
986 if (la->rdomain != NULL &&
987 set_rdomain(listen_sock, la->rdomain) == -1) {
992 /* Only communicate in IPv6 over AF_INET6 sockets. */
993 if (ai->ai_family == AF_INET6)
994 sock_set_v6only(listen_sock);
996 debug("Bind to port %s on %s.", strport, ntop);
998 /* Bind the socket to the desired port. */
999 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1000 error("Bind to port %s on %s failed: %.200s.",
1001 strport, ntop, strerror(errno));
1005 listen_socks[num_listen_socks] = listen_sock;
1008 /* Start listening on the port. */
1009 if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1010 fatal("listen on [%s]:%s: %.100s",
1011 ntop, strport, strerror(errno));
1012 logit("Server listening on %s port %s%s%s.",
1014 la->rdomain == NULL ? "" : " rdomain ",
1015 la->rdomain == NULL ? "" : la->rdomain);
1024 for (i = 0; i < options.num_listen_addrs; i++) {
1025 listen_on_addrs(&options.listen_addrs[i]);
1026 freeaddrinfo(options.listen_addrs[i].addrs);
1027 free(options.listen_addrs[i].rdomain);
1028 memset(&options.listen_addrs[i], 0,
1029 sizeof(options.listen_addrs[i]));
1031 free(options.listen_addrs);
1032 options.listen_addrs = NULL;
1033 options.num_listen_addrs = 0;
1035 if (!num_listen_socks)
1036 fatal("Cannot bind any address.");
1040 * The main TCP accept loop. Note that, for the non-debug case, returns
1041 * from this function are in a forked subprocess.
1044 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1047 int i, j, ret, maxfd;
1048 int startups = 0, listening = 0, lameduck = 0;
1049 int startup_p[2] = { -1 , -1 };
1051 struct sockaddr_storage from;
1056 /* setup fd set for accept */
1059 for (i = 0; i < num_listen_socks; i++)
1060 if (listen_socks[i] > maxfd)
1061 maxfd = listen_socks[i];
1062 /* pipes connected to unauthenticated childs */
1063 startup_pipes = xcalloc(options.max_startups, sizeof(int));
1064 startup_flags = xcalloc(options.max_startups, sizeof(int));
1065 for (i = 0; i < options.max_startups; i++)
1066 startup_pipes[i] = -1;
1069 * Stay listening for connections until the system crashes or
1070 * the daemon is killed with a signal.
1073 if (received_sighup) {
1075 debug("Received SIGHUP; waiting for children");
1076 close_listen_socks();
1083 fdset = xcalloc(howmany(maxfd + 1, NFDBITS),
1086 for (i = 0; i < num_listen_socks; i++)
1087 FD_SET(listen_socks[i], fdset);
1088 for (i = 0; i < options.max_startups; i++)
1089 if (startup_pipes[i] != -1)
1090 FD_SET(startup_pipes[i], fdset);
1092 /* Wait in select until there is a connection. */
1093 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1094 if (ret < 0 && errno != EINTR)
1095 error("select: %.100s", strerror(errno));
1096 if (received_sigterm) {
1097 logit("Received signal %d; terminating.",
1098 (int) received_sigterm);
1099 close_listen_socks();
1100 if (options.pid_file != NULL)
1101 unlink(options.pid_file);
1102 exit(received_sigterm == SIGTERM ? 0 : 255);
1107 for (i = 0; i < options.max_startups; i++) {
1108 if (startup_pipes[i] == -1 ||
1109 !FD_ISSET(startup_pipes[i], fdset))
1111 switch (read(startup_pipes[i], &c, sizeof(c))) {
1113 if (errno == EINTR || errno == EAGAIN)
1115 if (errno != EPIPE) {
1116 error("%s: startup pipe %d (fd=%d): "
1117 "read %s", __func__, i,
1118 startup_pipes[i], strerror(errno));
1122 /* child exited or completed auth */
1123 close(startup_pipes[i]);
1124 startup_pipes[i] = -1;
1126 if (startup_flags[i])
1130 /* child has finished preliminaries */
1131 if (startup_flags[i]) {
1133 startup_flags[i] = 0;
1138 for (i = 0; i < num_listen_socks; i++) {
1139 if (!FD_ISSET(listen_socks[i], fdset))
1141 fromlen = sizeof(from);
1142 *newsock = accept(listen_socks[i],
1143 (struct sockaddr *)&from, &fromlen);
1145 if (errno != EINTR && errno != EWOULDBLOCK &&
1146 errno != ECONNABORTED && errno != EAGAIN)
1147 error("accept: %.100s",
1149 if (errno == EMFILE || errno == ENFILE)
1153 if (unset_nonblock(*newsock) == -1) {
1157 if (drop_connection(startups) == 1) {
1158 char *laddr = get_local_ipaddr(*newsock);
1159 char *raddr = get_peer_ipaddr(*newsock);
1161 verbose("drop connection #%d from [%s]:%d "
1162 "on [%s]:%d past MaxStartups", startups,
1163 raddr, get_peer_port(*newsock),
1164 laddr, get_local_port(*newsock));
1170 if (pipe(startup_p) == -1) {
1175 if (rexec_flag && socketpair(AF_UNIX,
1176 SOCK_STREAM, 0, config_s) == -1) {
1177 error("reexec socketpair: %s",
1180 close(startup_p[0]);
1181 close(startup_p[1]);
1185 for (j = 0; j < options.max_startups; j++)
1186 if (startup_pipes[j] == -1) {
1187 startup_pipes[j] = startup_p[0];
1188 if (maxfd < startup_p[0])
1189 maxfd = startup_p[0];
1191 startup_flags[j] = 1;
1196 * Got connection. Fork a child to handle it, unless
1197 * we are in debugging mode.
1201 * In debugging mode. Close the listening
1202 * socket, and start processing the
1203 * connection without forking.
1205 debug("Server will not fork when running in debugging mode.");
1206 close_listen_socks();
1207 *sock_in = *newsock;
1208 *sock_out = *newsock;
1209 close(startup_p[0]);
1210 close(startup_p[1]);
1214 send_rexec_state(config_s[0], cfg);
1221 * Normal production daemon. Fork, and have
1222 * the child process the connection. The
1223 * parent continues listening.
1225 platform_pre_fork();
1227 if ((pid = fork()) == 0) {
1229 * Child. Close the listening and
1230 * max_startup sockets. Start using
1231 * the accepted socket. Reinitialize
1232 * logging (since our pid has changed).
1233 * We return from this function to handle
1236 platform_post_fork_child();
1237 startup_pipe = startup_p[1];
1238 close_startup_pipes();
1239 close_listen_socks();
1240 *sock_in = *newsock;
1241 *sock_out = *newsock;
1242 log_init(__progname,
1244 options.log_facility,
1250 * Signal parent that the preliminaries
1251 * for this child are complete. For the
1252 * re-exec case, this happens after the
1253 * child has received the rexec state
1256 (void)atomicio(vwrite, startup_pipe,
1262 /* Parent. Stay in the loop. */
1263 platform_post_fork_parent(pid);
1265 error("fork: %.100s", strerror(errno));
1267 debug("Forked child %ld.", (long)pid);
1269 close(startup_p[1]);
1272 send_rexec_state(config_s[0], cfg);
1279 * Ensure that our random state differs
1280 * from that of the child
1283 arc4random_buf(rnd, sizeof(rnd));
1285 RAND_seed(rnd, sizeof(rnd));
1286 if ((RAND_bytes((u_char *)rnd, 1)) != 1)
1287 fatal("%s: RAND_bytes failed", __func__);
1289 explicit_bzero(rnd, sizeof(rnd));
1295 * If IP options are supported, make sure there are none (log and
1296 * return an error if any are found). Basically we are worried about
1297 * source routing; it can be used to pretend you are somebody
1298 * (ip-address) you are not. That itself may be "almost acceptable"
1299 * under certain circumstances, but rhosts authentication is useless
1300 * if source routing is accepted. Notice also that if we just dropped
1301 * source routing here, the other side could use IP spoofing to do
1302 * rest of the interaction and could still bypass security. So we
1303 * exit here if we detect any IP options.
1306 check_ip_options(struct ssh *ssh)
1309 int sock_in = ssh_packet_get_connection_in(ssh);
1310 struct sockaddr_storage from;
1312 socklen_t i, option_size = sizeof(opts), fromlen = sizeof(from);
1313 char text[sizeof(opts) * 3 + 1];
1315 memset(&from, 0, sizeof(from));
1316 if (getpeername(sock_in, (struct sockaddr *)&from,
1319 if (from.ss_family != AF_INET)
1321 /* XXX IPv6 options? */
1323 if (getsockopt(sock_in, IPPROTO_IP, IP_OPTIONS, opts,
1324 &option_size) >= 0 && option_size != 0) {
1326 for (i = 0; i < option_size; i++)
1327 snprintf(text + i*3, sizeof(text) - i*3,
1329 fatal("Connection from %.100s port %d with IP opts: %.800s",
1330 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), text);
1333 #endif /* IP_OPTIONS */
1336 /* Set the routing domain for this process */
1338 set_process_rdomain(struct ssh *ssh, const char *name)
1340 #if defined(HAVE_SYS_SET_PROCESS_RDOMAIN)
1342 return; /* default */
1344 if (strcmp(name, "%D") == 0) {
1345 /* "expands" to routing domain of connection */
1346 if ((name = ssh_packet_rdomain_in(ssh)) == NULL)
1349 /* NB. We don't pass 'ssh' to sys_set_process_rdomain() */
1350 return sys_set_process_rdomain(name);
1351 #elif defined(__OpenBSD__)
1352 int rtable, ortable = getrtable();
1356 return; /* default */
1358 if (strcmp(name, "%D") == 0) {
1359 /* "expands" to routing domain of connection */
1360 if ((name = ssh_packet_rdomain_in(ssh)) == NULL)
1364 rtable = (int)strtonum(name, 0, 255, &errstr);
1365 if (errstr != NULL) /* Shouldn't happen */
1366 fatal("Invalid routing domain \"%s\": %s", name, errstr);
1367 if (rtable != ortable && setrtable(rtable) != 0)
1368 fatal("Unable to set routing domain %d: %s",
1369 rtable, strerror(errno));
1370 debug("%s: set routing domain %d (was %d)", __func__, rtable, ortable);
1371 #else /* defined(__OpenBSD__) */
1372 fatal("Unable to set routing domain: not supported in this platform");
1377 accumulate_host_timing_secret(struct sshbuf *server_cfg,
1378 const struct sshkey *key)
1380 static struct ssh_digest_ctx *ctx;
1386 if (ctx == NULL && (ctx = ssh_digest_start(SSH_DIGEST_SHA512)) == NULL)
1387 fatal("%s: ssh_digest_start", __func__);
1388 if (key == NULL) { /* finalize */
1389 /* add server config in case we are using agent for host keys */
1390 if (ssh_digest_update(ctx, sshbuf_ptr(server_cfg),
1391 sshbuf_len(server_cfg)) != 0)
1392 fatal("%s: ssh_digest_update", __func__);
1393 len = ssh_digest_bytes(SSH_DIGEST_SHA512);
1394 hash = xmalloc(len);
1395 if (ssh_digest_final(ctx, hash, len) != 0)
1396 fatal("%s: ssh_digest_final", __func__);
1397 options.timing_secret = PEEK_U64(hash);
1398 freezero(hash, len);
1399 ssh_digest_free(ctx);
1403 if ((buf = sshbuf_new()) == NULL)
1404 fatal("%s could not allocate buffer", __func__);
1405 if ((r = sshkey_private_serialize(key, buf)) != 0)
1406 fatal("sshkey_private_serialize: %s", ssh_err(r));
1407 if (ssh_digest_update(ctx, sshbuf_ptr(buf), sshbuf_len(buf)) != 0)
1408 fatal("%s: ssh_digest_update", __func__);
1414 * Main program for the daemon.
1417 main(int ac, char **av)
1419 struct ssh *ssh = NULL;
1420 extern char *optarg;
1422 int r, opt, on = 1, already_daemon, remote_port;
1423 int sock_in = -1, sock_out = -1, newsock = -1;
1424 const char *remote_ip, *rdomain;
1425 char *fp, *line, *laddr, *logfile = NULL;
1426 int config_s[2] = { -1 , -1 };
1428 u_int64_t ibytes, obytes;
1431 struct sshkey *pubkey;
1434 struct connection_info *connection_info = NULL;
1436 ssh_malloc_init(); /* must be called before any mallocs */
1438 #ifdef HAVE_SECUREWARE
1439 (void)set_auth_parameters(ac, av);
1441 __progname = ssh_get_progname(av[0]);
1443 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1446 saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1447 for (i = 0; (int)i < ac; i++)
1448 saved_argv[i] = xstrdup(av[i]);
1449 saved_argv[i] = NULL;
1451 #ifndef HAVE_SETPROCTITLE
1452 /* Prepare for later setproctitle emulation */
1453 compat_init_setproctitle(ac, av);
1457 if (geteuid() == 0 && setgroups(0, NULL) == -1)
1458 debug("setgroups(): %.200s", strerror(errno));
1460 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1465 /* Initialize configuration options to their default values. */
1466 initialize_server_options(&options);
1468 /* Parse command-line arguments. */
1469 while ((opt = getopt(ac, av,
1470 "C:E:b:c:f:g:h:k:o:p:u:46DQRTdeiqrt")) != -1) {
1473 options.address_family = AF_INET;
1476 options.address_family = AF_INET6;
1479 config_file_name = optarg;
1482 servconf_add_hostcert("[command-line]", 0,
1486 if (debug_flag == 0) {
1488 options.log_level = SYSLOG_LEVEL_DEBUG1;
1489 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1490 options.log_level++;
1515 options.log_level = SYSLOG_LEVEL_QUIET;
1518 /* protocol 1, ignored */
1521 options.ports_from_cmdline = 1;
1522 if (options.num_ports >= MAX_PORTS) {
1523 fprintf(stderr, "too many ports.\n");
1526 options.ports[options.num_ports++] = a2port(optarg);
1527 if (options.ports[options.num_ports-1] <= 0) {
1528 fprintf(stderr, "Bad port number.\n");
1533 if ((options.login_grace_time = convtime(optarg)) == -1) {
1534 fprintf(stderr, "Invalid login grace time.\n");
1539 /* protocol 1, ignored */
1542 servconf_add_hostkey("[command-line]", 0,
1543 &options, optarg, 1);
1552 connection_info = get_connection_info(ssh, 0, 0);
1553 if (parse_server_match_testspec(connection_info,
1558 utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
1559 if (utmp_len > HOST_NAME_MAX+1) {
1560 fprintf(stderr, "Invalid utmp length.\n");
1565 line = xstrdup(optarg);
1566 if (process_server_config_line(&options, line,
1567 "command-line", 0, NULL, NULL) != 0)
1577 if (rexeced_flag || inetd_flag)
1579 if (!test_flag && rexec_flag && !path_absolute(av[0]))
1580 fatal("sshd re-exec requires execution with an absolute path");
1582 closefrom(REEXEC_MIN_FREE_FD);
1584 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1586 /* If requested, redirect the logs to the specified logfile. */
1587 if (logfile != NULL)
1588 log_redirect_stderr_to(logfile);
1590 * Force logging to stderr until we have loaded the private host
1591 * key (unless started from inetd)
1593 log_init(__progname,
1594 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1595 SYSLOG_LEVEL_INFO : options.log_level,
1596 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1597 SYSLOG_FACILITY_AUTH : options.log_facility,
1598 log_stderr || !inetd_flag);
1601 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1602 * root's environment
1604 if (getenv("KRB5CCNAME") != NULL)
1605 (void) unsetenv("KRB5CCNAME");
1607 sensitive_data.have_ssh2_key = 0;
1610 * If we're not doing an extended test do not silently ignore connection
1613 if (test_flag < 2 && connection_info != NULL)
1614 fatal("Config test connection parameter (-C) provided without "
1617 /* Fetch our configuration */
1618 if ((cfg = sshbuf_new()) == NULL)
1619 fatal("%s: sshbuf_new failed", __func__);
1621 recv_rexec_state(REEXEC_CONFIG_PASS_FD, cfg);
1623 startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
1624 close(REEXEC_STARTUP_PIPE_FD);
1626 * Signal parent that this child is at a point where
1627 * they can go away if they have a SIGHUP pending.
1629 (void)atomicio(vwrite, startup_pipe, "\0", 1);
1632 else if (strcasecmp(config_file_name, "none") != 0)
1633 load_server_config(config_file_name, cfg);
1635 parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1638 /* Fill in default values for those options not explicitly set. */
1639 fill_default_server_options(&options);
1641 /* challenge-response is implemented via keyboard interactive */
1642 if (options.challenge_response_authentication)
1643 options.kbd_interactive_authentication = 1;
1645 /* Check that options are sensible */
1646 if (options.authorized_keys_command_user == NULL &&
1647 (options.authorized_keys_command != NULL &&
1648 strcasecmp(options.authorized_keys_command, "none") != 0))
1649 fatal("AuthorizedKeysCommand set without "
1650 "AuthorizedKeysCommandUser");
1651 if (options.authorized_principals_command_user == NULL &&
1652 (options.authorized_principals_command != NULL &&
1653 strcasecmp(options.authorized_principals_command, "none") != 0))
1654 fatal("AuthorizedPrincipalsCommand set without "
1655 "AuthorizedPrincipalsCommandUser");
1658 * Check whether there is any path through configured auth methods.
1659 * Unfortunately it is not possible to verify this generally before
1660 * daemonisation in the presence of Match block, but this catches
1661 * and warns for trivial misconfigurations that could break login.
1663 if (options.num_auth_methods != 0) {
1664 for (i = 0; i < options.num_auth_methods; i++) {
1665 if (auth2_methods_valid(options.auth_methods[i],
1669 if (i >= options.num_auth_methods)
1670 fatal("AuthenticationMethods cannot be satisfied by "
1671 "enabled authentication methods");
1674 /* Check that there are no remaining arguments. */
1676 fprintf(stderr, "Extra argument %s.\n", av[optind]);
1680 debug("sshd version %s, %s", SSH_VERSION,
1682 OpenSSL_version(OPENSSL_VERSION)
1688 /* Store privilege separation user for later use if required. */
1689 privsep_chroot = use_privsep && (getuid() == 0 || geteuid() == 0);
1690 if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1691 if (privsep_chroot || options.kerberos_authentication)
1692 fatal("Privilege separation user %s does not exist",
1695 privsep_pw = pwcopy(privsep_pw);
1696 freezero(privsep_pw->pw_passwd, strlen(privsep_pw->pw_passwd));
1697 privsep_pw->pw_passwd = xstrdup("*");
1701 /* load host keys */
1702 sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1703 sizeof(struct sshkey *));
1704 sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
1705 sizeof(struct sshkey *));
1707 if (options.host_key_agent) {
1708 if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
1709 setenv(SSH_AUTHSOCKET_ENV_NAME,
1710 options.host_key_agent, 1);
1711 if ((r = ssh_get_authentication_socket(NULL)) == 0)
1714 error("Could not connect to agent \"%s\": %s",
1715 options.host_key_agent, ssh_err(r));
1718 for (i = 0; i < options.num_host_key_files; i++) {
1719 int ll = options.host_key_file_userprovided[i] ?
1720 SYSLOG_LEVEL_ERROR : SYSLOG_LEVEL_DEBUG1;
1722 if (options.host_key_files[i] == NULL)
1724 if ((r = sshkey_load_private(options.host_key_files[i], "",
1725 &key, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR)
1726 do_log2(ll, "Unable to load host key \"%s\": %s",
1727 options.host_key_files[i], ssh_err(r));
1728 if ((r = sshkey_load_public(options.host_key_files[i],
1729 &pubkey, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR)
1730 do_log2(ll, "Unable to load host key \"%s\": %s",
1731 options.host_key_files[i], ssh_err(r));
1732 if (pubkey == NULL && key != NULL)
1733 if ((r = sshkey_from_private(key, &pubkey)) != 0)
1734 fatal("Could not demote key: \"%s\": %s",
1735 options.host_key_files[i], ssh_err(r));
1736 sensitive_data.host_keys[i] = key;
1737 sensitive_data.host_pubkeys[i] = pubkey;
1739 if (key == NULL && pubkey != NULL && have_agent) {
1740 debug("will rely on agent for hostkey %s",
1741 options.host_key_files[i]);
1742 keytype = pubkey->type;
1743 } else if (key != NULL) {
1744 keytype = key->type;
1745 accumulate_host_timing_secret(cfg, key);
1747 do_log2(ll, "Unable to load host key: %s",
1748 options.host_key_files[i]);
1749 sensitive_data.host_keys[i] = NULL;
1750 sensitive_data.host_pubkeys[i] = NULL;
1760 if (have_agent || key != NULL)
1761 sensitive_data.have_ssh2_key = 1;
1764 if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash,
1765 SSH_FP_DEFAULT)) == NULL)
1766 fatal("sshkey_fingerprint failed");
1767 debug("%s host key #%d: %s %s",
1768 key ? "private" : "agent", i, sshkey_ssh_name(pubkey), fp);
1771 accumulate_host_timing_secret(cfg, NULL);
1772 if (!sensitive_data.have_ssh2_key) {
1773 logit("sshd: no hostkeys available -- exiting.");
1778 * Load certificates. They are stored in an array at identical
1779 * indices to the public keys that they relate to.
1781 sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
1782 sizeof(struct sshkey *));
1783 for (i = 0; i < options.num_host_key_files; i++)
1784 sensitive_data.host_certificates[i] = NULL;
1786 for (i = 0; i < options.num_host_cert_files; i++) {
1787 if (options.host_cert_files[i] == NULL)
1789 if ((r = sshkey_load_public(options.host_cert_files[i],
1790 &key, NULL)) != 0) {
1791 error("Could not load host certificate \"%s\": %s",
1792 options.host_cert_files[i], ssh_err(r));
1795 if (!sshkey_is_cert(key)) {
1796 error("Certificate file is not a certificate: %s",
1797 options.host_cert_files[i]);
1801 /* Find matching private key */
1802 for (j = 0; j < options.num_host_key_files; j++) {
1803 if (sshkey_equal_public(key,
1804 sensitive_data.host_keys[j])) {
1805 sensitive_data.host_certificates[j] = key;
1809 if (j >= options.num_host_key_files) {
1810 error("No matching private key for certificate: %s",
1811 options.host_cert_files[i]);
1815 sensitive_data.host_certificates[j] = key;
1816 debug("host certificate: #%u type %d %s", j, key->type,
1820 if (privsep_chroot) {
1823 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1824 (S_ISDIR(st.st_mode) == 0))
1825 fatal("Missing privilege separation directory: %s",
1826 _PATH_PRIVSEP_CHROOT_DIR);
1829 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1830 (st.st_uid != getuid () ||
1831 (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1833 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1835 fatal("%s must be owned by root and not group or "
1836 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1839 if (test_flag > 1) {
1841 * If no connection info was provided by -C then use
1842 * use a blank one that will cause no predicate to match.
1844 if (connection_info == NULL)
1845 connection_info = get_connection_info(ssh, 0, 0);
1846 parse_server_match_config(&options, connection_info);
1847 dump_config(&options);
1850 /* Configuration looks good, so exit if in test mode. */
1855 * Clear out any supplemental groups we may have inherited. This
1856 * prevents inadvertent creation of files with bad modes (in the
1857 * portable version at least, it's certainly possible for PAM
1858 * to create a file, and we can't control the code in every
1859 * module which might be used).
1861 if (setgroups(0, NULL) < 0)
1862 debug("setgroups() failed: %.200s", strerror(errno));
1866 fatal("rexec_argc %d < 0", rexec_argc);
1867 rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1868 for (i = 0; i < (u_int)rexec_argc; i++) {
1869 debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1870 rexec_argv[i] = saved_argv[i];
1872 rexec_argv[rexec_argc] = "-R";
1873 rexec_argv[rexec_argc + 1] = NULL;
1876 /* Ensure that umask disallows at least group and world write */
1877 new_umask = umask(0077) | 0022;
1878 (void) umask(new_umask);
1880 /* Initialize the log (it is reinitialized below in case we forked). */
1881 if (debug_flag && (!inetd_flag || rexeced_flag))
1883 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1886 * If not in debugging mode, not started from inetd and not already
1887 * daemonized (eg re-exec via SIGHUP), disconnect from the controlling
1888 * terminal, and fork. The original process exits.
1890 already_daemon = daemonized();
1891 if (!(debug_flag || inetd_flag || no_daemon_flag || already_daemon)) {
1893 if (daemon(0, 0) < 0)
1894 fatal("daemon() failed: %.200s", strerror(errno));
1896 disconnect_controlling_tty();
1898 /* Reinitialize the log (because of the fork above). */
1899 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1901 /* Chdir to the root directory so that the current disk can be
1902 unmounted if desired. */
1903 if (chdir("/") == -1)
1904 error("chdir(\"/\"): %s", strerror(errno));
1906 /* ignore SIGPIPE */
1907 signal(SIGPIPE, SIG_IGN);
1909 /* Get a connection, either from inetd or a listening TCP socket */
1911 server_accept_inetd(&sock_in, &sock_out);
1913 platform_pre_listen();
1916 signal(SIGHUP, sighup_handler);
1917 signal(SIGCHLD, main_sigchld_handler);
1918 signal(SIGTERM, sigterm_handler);
1919 signal(SIGQUIT, sigterm_handler);
1922 * Write out the pid file after the sigterm handler
1923 * is setup and the listen sockets are bound
1925 if (options.pid_file != NULL && !debug_flag) {
1926 FILE *f = fopen(options.pid_file, "w");
1929 error("Couldn't create pid file \"%s\": %s",
1930 options.pid_file, strerror(errno));
1932 fprintf(f, "%ld\n", (long) getpid());
1937 /* Accept a connection and return in a forked child */
1938 server_accept_loop(&sock_in, &sock_out,
1939 &newsock, config_s);
1942 /* This is the child processing a new connection. */
1943 setproctitle("%s", "[accepted]");
1946 * Create a new session and process group since the 4.4BSD
1947 * setlogin() affects the entire process group. We don't
1948 * want the child to be able to affect the parent.
1950 #if !defined(SSHD_ACQUIRES_CTTY)
1952 * If setsid is called, on some platforms sshd will later acquire a
1953 * controlling terminal which will result in "could not set
1954 * controlling tty" errors.
1956 if (!debug_flag && !inetd_flag && setsid() < 0)
1957 error("setsid: %.100s", strerror(errno));
1963 debug("rexec start in %d out %d newsock %d pipe %d sock %d",
1964 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1965 dup2(newsock, STDIN_FILENO);
1966 dup2(STDIN_FILENO, STDOUT_FILENO);
1967 if (startup_pipe == -1)
1968 close(REEXEC_STARTUP_PIPE_FD);
1969 else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) {
1970 dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
1971 close(startup_pipe);
1972 startup_pipe = REEXEC_STARTUP_PIPE_FD;
1975 dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1978 execv(rexec_argv[0], rexec_argv);
1980 /* Reexec has failed, fall back and continue */
1981 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1982 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1983 log_init(__progname, options.log_level,
1984 options.log_facility, log_stderr);
1987 close(REEXEC_CONFIG_PASS_FD);
1988 newsock = sock_out = sock_in = dup(STDIN_FILENO);
1989 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1990 dup2(fd, STDIN_FILENO);
1991 dup2(fd, STDOUT_FILENO);
1992 if (fd > STDERR_FILENO)
1995 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
1996 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1999 /* Executed child processes don't need these. */
2000 fcntl(sock_out, F_SETFD, FD_CLOEXEC);
2001 fcntl(sock_in, F_SETFD, FD_CLOEXEC);
2004 * Disable the key regeneration alarm. We will not regenerate the
2005 * key since we are no longer in a position to give it to anyone. We
2006 * will not restart on SIGHUP since it no longer makes sense.
2009 signal(SIGALRM, SIG_DFL);
2010 signal(SIGHUP, SIG_DFL);
2011 signal(SIGTERM, SIG_DFL);
2012 signal(SIGQUIT, SIG_DFL);
2013 signal(SIGCHLD, SIG_DFL);
2014 signal(SIGINT, SIG_DFL);
2017 * Register our connection. This turns encryption off because we do
2020 if ((ssh = ssh_packet_set_connection(NULL, sock_in, sock_out)) == NULL)
2021 fatal("Unable to create connection");
2022 the_active_state = ssh;
2023 ssh_packet_set_server(ssh);
2025 check_ip_options(ssh);
2027 /* Prepare the channels layer */
2028 channel_init_channels(ssh);
2029 channel_set_af(ssh, options.address_family);
2030 process_permitopen(ssh, &options);
2032 /* Set SO_KEEPALIVE if requested. */
2033 if (options.tcp_keep_alive && ssh_packet_connection_is_on_socket(ssh) &&
2034 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
2035 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
2037 if ((remote_port = ssh_remote_port(ssh)) < 0) {
2038 debug("ssh_remote_port failed");
2042 if (options.routing_domain != NULL)
2043 set_process_rdomain(ssh, options.routing_domain);
2046 * The rest of the code depends on the fact that
2047 * ssh_remote_ipaddr() caches the remote ip, even if
2048 * the socket goes away.
2050 remote_ip = ssh_remote_ipaddr(ssh);
2052 #ifdef SSH_AUDIT_EVENTS
2053 audit_connection_from(remote_ip, remote_port);
2056 rdomain = ssh_packet_rdomain_in(ssh);
2058 /* Log the connection. */
2059 laddr = get_local_ipaddr(sock_in);
2060 verbose("Connection from %s port %d on %s port %d%s%s%s",
2061 remote_ip, remote_port, laddr, ssh_local_port(ssh),
2062 rdomain == NULL ? "" : " rdomain \"",
2063 rdomain == NULL ? "" : rdomain,
2064 rdomain == NULL ? "" : "\"");
2068 * We don't want to listen forever unless the other side
2069 * successfully authenticates itself. So we set up an alarm which is
2070 * cleared after successful authentication. A limit of zero
2071 * indicates no limit. Note that we don't set the alarm in debugging
2072 * mode; it is just annoying to have the server exit just when you
2073 * are about to discover the bug.
2075 signal(SIGALRM, grace_alarm_handler);
2077 alarm(options.login_grace_time);
2079 if (kex_exchange_identification(ssh, -1, options.version_addendum) != 0)
2080 cleanup_exit(255); /* error already logged */
2082 ssh_packet_set_nonblocking(ssh);
2084 /* allocate authentication context */
2085 authctxt = xcalloc(1, sizeof(*authctxt));
2086 ssh->authctxt = authctxt;
2088 authctxt->loginmsg = loginmsg;
2090 /* XXX global for cleanup, access from other modules */
2091 the_authctxt = authctxt;
2093 /* Set default key authentication options */
2094 if ((auth_opts = sshauthopt_new_with_keys_defaults()) == NULL)
2095 fatal("allocation failed");
2097 /* prepare buffer to collect messages to display to user after login */
2098 if ((loginmsg = sshbuf_new()) == NULL)
2099 fatal("%s: sshbuf_new failed", __func__);
2103 if (privsep_preauth(ssh) == 1)
2105 } else if (have_agent) {
2106 if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) {
2107 error("Unable to get agent socket: %s", ssh_err(r));
2112 /* perform the key exchange */
2113 /* authenticate user and start session */
2115 do_authentication2(ssh);
2118 * If we use privilege separation, the unprivileged child transfers
2119 * the current keystate and exits
2122 mm_send_keystate(ssh, pmonitor);
2123 ssh_packet_clear_keys(ssh);
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, SSH_AUTH_SUCCESS);
2145 if (options.gss_authentication) {
2146 temporarily_use_uid(authctxt->pw);
2147 ssh_gssapi_storecreds();
2152 if (options.use_pam) {
2154 do_pam_session(ssh);
2159 * In privilege separation, we fork another child and prepare
2160 * file descriptor passing.
2163 privsep_postauth(ssh, authctxt);
2164 /* the monitor process [priv] will not return */
2167 ssh_packet_set_timeout(ssh, options.client_alive_interval,
2168 options.client_alive_count_max);
2170 /* Try to send all our hostkeys to the client */
2171 notify_hostkeys(ssh);
2173 /* Start session. */
2174 do_authenticated(ssh, authctxt);
2176 /* The connection has been terminated. */
2177 ssh_packet_get_bytes(ssh, &ibytes, &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, SSH_CONNECTION_CLOSE));
2192 ssh_packet_close(ssh);
2201 sshd_hostkey_sign(struct ssh *ssh, struct sshkey *privkey,
2202 struct sshkey *pubkey, u_char **signature, size_t *slenp,
2203 const u_char *data, size_t dlen, const char *alg)
2209 if (mm_sshkey_sign(ssh, privkey, signature, slenp,
2210 data, dlen, alg, ssh->compat) < 0)
2211 fatal("%s: privkey sign failed", __func__);
2213 if (mm_sshkey_sign(ssh, pubkey, signature, slenp,
2214 data, dlen, alg, ssh->compat) < 0)
2215 fatal("%s: pubkey sign failed", __func__);
2219 if (sshkey_sign(privkey, signature, slenp, data, dlen,
2220 alg, ssh->compat) < 0)
2221 fatal("%s: privkey sign failed", __func__);
2223 if ((r = ssh_agent_sign(auth_sock, pubkey,
2224 signature, slenp, data, dlen, alg,
2225 ssh->compat)) != 0) {
2226 fatal("%s: agent sign failed: %s",
2227 __func__, ssh_err(r));
2234 /* SSH2 key exchange */
2236 do_ssh2_kex(struct ssh *ssh)
2238 char *myproposal[PROPOSAL_MAX] = { KEX_SERVER };
2242 myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(
2243 options.kex_algorithms);
2244 myproposal[PROPOSAL_ENC_ALGS_CTOS] = compat_cipher_proposal(
2246 myproposal[PROPOSAL_ENC_ALGS_STOC] = compat_cipher_proposal(
2248 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2249 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2251 if (options.compression == COMP_NONE) {
2252 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2253 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2256 if (options.rekey_limit || options.rekey_interval)
2257 ssh_packet_set_rekey_limits(ssh, options.rekey_limit,
2258 options.rekey_interval);
2260 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal(
2261 list_hostkey_types());
2263 /* start key exchange */
2264 if ((r = kex_setup(ssh, myproposal)) != 0)
2265 fatal("kex_setup: %s", ssh_err(r));
2268 kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_server;
2269 kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_server;
2270 kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_server;
2271 kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_server;
2272 kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_server;
2273 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2274 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2275 # ifdef OPENSSL_HAS_ECC
2276 kex->kex[KEX_ECDH_SHA2] = kex_gen_server;
2279 kex->kex[KEX_C25519_SHA256] = kex_gen_server;
2280 kex->kex[KEX_KEM_SNTRUP4591761X25519_SHA512] = kex_gen_server;
2281 kex->load_host_public_key=&get_hostkey_public_by_type;
2282 kex->load_host_private_key=&get_hostkey_private_by_type;
2283 kex->host_key_index=&get_hostkey_index;
2284 kex->sign = sshd_hostkey_sign;
2286 ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &kex->done);
2288 session_id2 = kex->session_id;
2289 session_id2_len = kex->session_id_len;
2292 /* send 1st encrypted/maced/compressed message */
2293 packet_start(SSH2_MSG_IGNORE);
2294 packet_put_cstring("markus");
2296 packet_write_wait();
2301 /* server specific fatal cleanup */
2305 if (the_active_state != NULL && the_authctxt != NULL) {
2306 do_cleanup(the_active_state, the_authctxt);
2307 if (use_privsep && privsep_is_preauth &&
2308 pmonitor != NULL && pmonitor->m_pid > 1) {
2309 debug("Killing privsep child %d", pmonitor->m_pid);
2310 if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
2312 error("%s: kill(%d): %s", __func__,
2313 pmonitor->m_pid, strerror(errno));
2316 #ifdef SSH_AUDIT_EVENTS
2317 /* done after do_cleanup so it can cancel the PAM auth 'thread' */
2318 if (the_active_state != NULL && (!use_privsep || mm_is_monitor()))
2319 audit_event(the_active_state, SSH_CONNECTION_ABANDON);