Home | History | Annotate | Download | only in openssh
      1 /* $OpenBSD: sshd.c,v 1.485 2017/03/15 03:52:30 deraadt Exp $ */
      2 /*
      3  * Author: Tatu Ylonen <ylo (at) cs.hut.fi>
      4  * Copyright (c) 1995 Tatu Ylonen <ylo (at) cs.hut.fi>, Espoo, Finland
      5  *                    All rights reserved
      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.
     11  *
     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".
     17  *
     18  * SSH2 implementation:
     19  * Privilege Separation:
     20  *
     21  * Copyright (c) 2000, 2001, 2002 Markus Friedl.  All rights reserved.
     22  * Copyright (c) 2002 Niels Provos.  All rights reserved.
     23  *
     24  * Redistribution and use in source and binary forms, with or without
     25  * modification, are permitted provided that the following conditions
     26  * are met:
     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.
     32  *
     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.
     43  */
     44 
     45 #include "includes.h"
     46 
     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>
     52 #endif
     53 #ifdef HAVE_SYS_TIME_H
     54 # include <sys/time.h>
     55 #endif
     56 #include "openbsd-compat/sys-tree.h"
     57 #include "openbsd-compat/sys-queue.h"
     58 #include <sys/wait.h>
     59 
     60 #include <errno.h>
     61 #include <fcntl.h>
     62 #include <netdb.h>
     63 #ifdef HAVE_PATHS_H
     64 #include <paths.h>
     65 #endif
     66 #include <grp.h>
     67 #include <pwd.h>
     68 #include <signal.h>
     69 #include <stdarg.h>
     70 #include <stdio.h>
     71 #include <stdlib.h>
     72 #include <string.h>
     73 #include <unistd.h>
     74 #include <limits.h>
     75 
     76 #ifdef WITH_OPENSSL
     77 #include <openssl/dh.h>
     78 #include <openssl/bn.h>
     79 #include <openssl/rand.h>
     80 #include "openbsd-compat/openssl-compat.h"
     81 #endif
     82 
     83 #ifdef HAVE_SECUREWARE
     84 #include <sys/security.h>
     85 #include <prot.h>
     86 #endif
     87 
     88 #include "xmalloc.h"
     89 #include "ssh.h"
     90 #include "ssh2.h"
     91 #include "rsa.h"
     92 #include "sshpty.h"
     93 #include "packet.h"
     94 #include "log.h"
     95 #include "buffer.h"
     96 #include "misc.h"
     97 #include "match.h"
     98 #include "servconf.h"
     99 #include "uidswap.h"
    100 #include "compat.h"
    101 #include "cipher.h"
    102 #include "digest.h"
    103 #include "key.h"
    104 #include "kex.h"
    105 #include "myproposal.h"
    106 #include "authfile.h"
    107 #include "pathnames.h"
    108 #include "atomicio.h"
    109 #include "canohost.h"
    110 #include "hostfile.h"
    111 #include "auth.h"
    112 #include "authfd.h"
    113 #include "msg.h"
    114 #include "dispatch.h"
    115 #include "channels.h"
    116 #include "session.h"
    117 #include "monitor.h"
    118 #ifdef GSSAPI
    119 #include "ssh-gss.h"
    120 #endif
    121 #include "monitor_wrap.h"
    122 #include "ssh-sandbox.h"
    123 #include "version.h"
    124 #include "ssherr.h"
    125 
    126 /* Re-exec fds */
    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)
    131 
    132 extern char *__progname;
    133 
    134 /* Server configuration options. */
    135 ServerOptions options;
    136 
    137 /* Name of the server configuration file. */
    138 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
    139 
    140 /*
    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.
    145  */
    146 int debug_flag = 0;
    147 
    148 /* Flag indicating that the daemon should only test the configuration and keys. */
    149 int test_flag = 0;
    150 
    151 /* Flag indicating that the daemon is being started from inetd. */
    152 int inetd_flag = 0;
    153 
    154 /* Flag indicating that sshd should not detach and become a daemon. */
    155 int no_daemon_flag = 0;
    156 
    157 /* debug goes to stderr unless inetd_flag is set */
    158 int log_stderr = 0;
    159 
    160 /* Saved arguments to main(). */
    161 char **saved_argv;
    162 int saved_argc;
    163 
    164 /* re-exec */
    165 int rexeced_flag = 0;
    166 int rexec_flag = 1;
    167 int rexec_argc = 0;
    168 char **rexec_argv;
    169 
    170 /*
    171  * The sockets that the server is listening; this is used in the SIGHUP
    172  * signal handler.
    173  */
    174 #define	MAX_LISTEN_SOCKS	16
    175 int listen_socks[MAX_LISTEN_SOCKS];
    176 int num_listen_socks = 0;
    177 
    178 /*
    179  * the client's version string, passed by sshd2 in compat mode. if != NULL,
    180  * sshd will skip the version-number exchange
    181  */
    182 char *client_version_string = NULL;
    183 char *server_version_string = NULL;
    184 
    185 /* Daemon's agent connection */
    186 int auth_sock = -1;
    187 int have_agent = 0;
    188 
    189 /*
    190  * Any really sensitive data in the application is contained in this
    191  * structure. The idea is that this structure could be locked into memory so
    192  * that the pages do not get written into swap.  However, there are some
    193  * problems. The private key contains BIGNUMs, and we do not (in principle)
    194  * have access to the internals of them, and locking just the structure is
    195  * not very useful.  Currently, memory locking is not implemented.
    196  */
    197 struct {
    198 	Key	**host_keys;		/* all private host keys */
    199 	Key	**host_pubkeys;		/* all public host keys */
    200 	Key	**host_certificates;	/* all public host certificates */
    201 	int	have_ssh2_key;
    202 } sensitive_data;
    203 
    204 /* This is set to true when a signal is received. */
    205 static volatile sig_atomic_t received_sighup = 0;
    206 static volatile sig_atomic_t received_sigterm = 0;
    207 
    208 /* session identifier, used by RSA-auth */
    209 u_char session_id[16];
    210 
    211 /* same for ssh2 */
    212 u_char *session_id2 = NULL;
    213 u_int session_id2_len = 0;
    214 
    215 /* record remote hostname or ip */
    216 u_int utmp_len = HOST_NAME_MAX+1;
    217 
    218 /* options.max_startup sized array of fd ints */
    219 int *startup_pipes = NULL;
    220 int startup_pipe;		/* in child */
    221 
    222 /* variables used for privilege separation */
    223 int use_privsep = -1;
    224 struct monitor *pmonitor = NULL;
    225 int privsep_is_preauth = 1;
    226 
    227 /* global authentication context */
    228 Authctxt *the_authctxt = NULL;
    229 
    230 /* sshd_config buffer */
    231 Buffer cfg;
    232 
    233 /* message to be displayed after login */
    234 Buffer loginmsg;
    235 
    236 /* Unprivileged user */
    237 struct passwd *privsep_pw = NULL;
    238 
    239 /* Prototypes for various functions defined later in this file. */
    240 void destroy_sensitive_data(void);
    241 void demote_sensitive_data(void);
    242 static void do_ssh2_kex(void);
    243 
    244 /*
    245  * Close all listening sockets
    246  */
    247 static void
    248 close_listen_socks(void)
    249 {
    250 	int i;
    251 
    252 	for (i = 0; i < num_listen_socks; i++)
    253 		close(listen_socks[i]);
    254 	num_listen_socks = -1;
    255 }
    256 
    257 static void
    258 close_startup_pipes(void)
    259 {
    260 	int i;
    261 
    262 	if (startup_pipes)
    263 		for (i = 0; i < options.max_startups; i++)
    264 			if (startup_pipes[i] != -1)
    265 				close(startup_pipes[i]);
    266 }
    267 
    268 /*
    269  * Signal handler for SIGHUP.  Sshd execs itself when it receives SIGHUP;
    270  * the effect is to reread the configuration file (and to regenerate
    271  * the server key).
    272  */
    273 
    274 /*ARGSUSED*/
    275 static void
    276 sighup_handler(int sig)
    277 {
    278 	int save_errno = errno;
    279 
    280 	received_sighup = 1;
    281 	signal(SIGHUP, sighup_handler);
    282 	errno = save_errno;
    283 }
    284 
    285 /*
    286  * Called from the main program after receiving SIGHUP.
    287  * Restarts the server.
    288  */
    289 static void
    290 sighup_restart(void)
    291 {
    292 	logit("Received SIGHUP; restarting.");
    293 	if (options.pid_file != NULL)
    294 		unlink(options.pid_file);
    295 	platform_pre_restart();
    296 	close_listen_socks();
    297 	close_startup_pipes();
    298 	alarm(0);  /* alarm timer persists across exec */
    299 	signal(SIGHUP, SIG_IGN); /* will be restored after exec */
    300 	execv(saved_argv[0], saved_argv);
    301 	logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
    302 	    strerror(errno));
    303 	exit(1);
    304 }
    305 
    306 /*
    307  * Generic signal handler for terminating signals in the master daemon.
    308  */
    309 /*ARGSUSED*/
    310 static void
    311 sigterm_handler(int sig)
    312 {
    313 	received_sigterm = sig;
    314 }
    315 
    316 /*
    317  * SIGCHLD handler.  This is called whenever a child dies.  This will then
    318  * reap any zombies left by exited children.
    319  */
    320 /*ARGSUSED*/
    321 static void
    322 main_sigchld_handler(int sig)
    323 {
    324 	int save_errno = errno;
    325 	pid_t pid;
    326 	int status;
    327 
    328 	while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
    329 	    (pid < 0 && errno == EINTR))
    330 		;
    331 
    332 	signal(SIGCHLD, main_sigchld_handler);
    333 	errno = save_errno;
    334 }
    335 
    336 /*
    337  * Signal handler for the alarm after the login grace period has expired.
    338  */
    339 /*ARGSUSED*/
    340 static void
    341 grace_alarm_handler(int sig)
    342 {
    343 	if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
    344 		kill(pmonitor->m_pid, SIGALRM);
    345 
    346 	/*
    347 	 * Try to kill any processes that we have spawned, E.g. authorized
    348 	 * keys command helpers.
    349 	 */
    350 	if (getpgid(0) == getpid()) {
    351 		signal(SIGTERM, SIG_IGN);
    352 		kill(0, SIGTERM);
    353 	}
    354 
    355 	/* Log error and exit. */
    356 	sigdie("Timeout before authentication for %s port %d",
    357 	    ssh_remote_ipaddr(active_state), ssh_remote_port(active_state));
    358 }
    359 
    360 static void
    361 sshd_exchange_identification(struct ssh *ssh, int sock_in, int sock_out)
    362 {
    363 	u_int i;
    364 	int remote_major, remote_minor;
    365 	char *s;
    366 	char buf[256];			/* Must not be larger than remote_version. */
    367 	char remote_version[256];	/* Must be at least as big as buf. */
    368 
    369 	xasprintf(&server_version_string, "SSH-%d.%d-%.100s%s%s\r\n",
    370 	    PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2, SSH_VERSION,
    371 	    *options.version_addendum == '\0' ? "" : " ",
    372 	    options.version_addendum);
    373 
    374 	/* Send our protocol version identification. */
    375 	if (atomicio(vwrite, sock_out, server_version_string,
    376 	    strlen(server_version_string))
    377 	    != strlen(server_version_string)) {
    378 		logit("Could not write ident string to %s port %d",
    379 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
    380 		cleanup_exit(255);
    381 	}
    382 
    383 	/* Read other sides version identification. */
    384 	memset(buf, 0, sizeof(buf));
    385 	for (i = 0; i < sizeof(buf) - 1; i++) {
    386 		if (atomicio(read, sock_in, &buf[i], 1) != 1) {
    387 			logit("Did not receive identification string "
    388 			    "from %s port %d",
    389 			    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
    390 			cleanup_exit(255);
    391 		}
    392 		if (buf[i] == '\r') {
    393 			buf[i] = 0;
    394 			/* Kludge for F-Secure Macintosh < 1.0.2 */
    395 			if (i == 12 &&
    396 			    strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
    397 				break;
    398 			continue;
    399 		}
    400 		if (buf[i] == '\n') {
    401 			buf[i] = 0;
    402 			break;
    403 		}
    404 	}
    405 	buf[sizeof(buf) - 1] = 0;
    406 	client_version_string = xstrdup(buf);
    407 
    408 	/*
    409 	 * Check that the versions match.  In future this might accept
    410 	 * several versions and set appropriate flags to handle them.
    411 	 */
    412 	if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
    413 	    &remote_major, &remote_minor, remote_version) != 3) {
    414 		s = "Protocol mismatch.\n";
    415 		(void) atomicio(vwrite, sock_out, s, strlen(s));
    416 		logit("Bad protocol version identification '%.100s' "
    417 		    "from %s port %d", client_version_string,
    418 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
    419 		close(sock_in);
    420 		close(sock_out);
    421 		cleanup_exit(255);
    422 	}
    423 	debug("Client protocol version %d.%d; client software version %.100s",
    424 	    remote_major, remote_minor, remote_version);
    425 
    426 	ssh->compat = compat_datafellows(remote_version);
    427 
    428 	if ((ssh->compat & SSH_BUG_PROBE) != 0) {
    429 		logit("probed from %s port %d with %s.  Don't panic.",
    430 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
    431 		    client_version_string);
    432 		cleanup_exit(255);
    433 	}
    434 	if ((ssh->compat & SSH_BUG_SCANNER) != 0) {
    435 		logit("scanned from %s port %d with %s.  Don't panic.",
    436 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
    437 		    client_version_string);
    438 		cleanup_exit(255);
    439 	}
    440 	if ((ssh->compat & SSH_BUG_RSASIGMD5) != 0) {
    441 		logit("Client version \"%.100s\" uses unsafe RSA signature "
    442 		    "scheme; disabling use of RSA keys", remote_version);
    443 	}
    444 	if ((ssh->compat & SSH_BUG_DERIVEKEY) != 0) {
    445 		fatal("Client version \"%.100s\" uses unsafe key agreement; "
    446 		    "refusing connection", remote_version);
    447 	}
    448 
    449 	chop(server_version_string);
    450 	debug("Local version string %.200s", server_version_string);
    451 
    452 	if (remote_major == 2 ||
    453 	    (remote_major == 1 && remote_minor == 99)) {
    454 		enable_compat20();
    455 	} else {
    456 		s = "Protocol major versions differ.\n";
    457 		(void) atomicio(vwrite, sock_out, s, strlen(s));
    458 		close(sock_in);
    459 		close(sock_out);
    460 		logit("Protocol major versions differ for %s port %d: "
    461 		    "%.200s vs. %.200s",
    462 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
    463 		    server_version_string, client_version_string);
    464 		cleanup_exit(255);
    465 	}
    466 }
    467 
    468 /* Destroy the host and server keys.  They will no longer be needed. */
    469 void
    470 destroy_sensitive_data(void)
    471 {
    472 	int i;
    473 
    474 	for (i = 0; i < options.num_host_key_files; i++) {
    475 		if (sensitive_data.host_keys[i]) {
    476 			key_free(sensitive_data.host_keys[i]);
    477 			sensitive_data.host_keys[i] = NULL;
    478 		}
    479 		if (sensitive_data.host_certificates[i]) {
    480 			key_free(sensitive_data.host_certificates[i]);
    481 			sensitive_data.host_certificates[i] = NULL;
    482 		}
    483 	}
    484 }
    485 
    486 /* Demote private to public keys for network child */
    487 void
    488 demote_sensitive_data(void)
    489 {
    490 	Key *tmp;
    491 	int i;
    492 
    493 	for (i = 0; i < options.num_host_key_files; i++) {
    494 		if (sensitive_data.host_keys[i]) {
    495 			tmp = key_demote(sensitive_data.host_keys[i]);
    496 			key_free(sensitive_data.host_keys[i]);
    497 			sensitive_data.host_keys[i] = tmp;
    498 		}
    499 		/* Certs do not need demotion */
    500 	}
    501 }
    502 
    503 static void
    504 reseed_prngs(void)
    505 {
    506 	u_int32_t rnd[256];
    507 
    508 #ifdef WITH_OPENSSL
    509 	RAND_poll();
    510 #endif
    511 	arc4random_stir(); /* noop on recent arc4random() implementations */
    512 	arc4random_buf(rnd, sizeof(rnd)); /* let arc4random notice PID change */
    513 
    514 #ifdef WITH_OPENSSL
    515 	RAND_seed(rnd, sizeof(rnd));
    516 	/* give libcrypto a chance to notice the PID change */
    517 	if ((RAND_bytes((u_char *)rnd, 1)) != 1)
    518 		fatal("%s: RAND_bytes failed", __func__);
    519 #endif
    520 
    521 	explicit_bzero(rnd, sizeof(rnd));
    522 }
    523 
    524 static void
    525 privsep_preauth_child(void)
    526 {
    527 	gid_t gidset[1];
    528 
    529 	/* Enable challenge-response authentication for privilege separation */
    530 	privsep_challenge_enable();
    531 
    532 #ifdef GSSAPI
    533 	/* Cache supported mechanism OIDs for later use */
    534 	if (options.gss_authentication)
    535 		ssh_gssapi_prepare_supported_oids();
    536 #endif
    537 
    538 	reseed_prngs();
    539 
    540 	/* Demote the private keys to public keys. */
    541 	demote_sensitive_data();
    542 
    543 	/* Demote the child */
    544 	if (getuid() == 0 || geteuid() == 0) {
    545 		/* Change our root directory */
    546 		if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
    547 			fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
    548 			    strerror(errno));
    549 		if (chdir("/") == -1)
    550 			fatal("chdir(\"/\"): %s", strerror(errno));
    551 
    552 		/* Drop our privileges */
    553 		debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
    554 		    (u_int)privsep_pw->pw_gid);
    555 		gidset[0] = privsep_pw->pw_gid;
    556 		if (setgroups(1, gidset) < 0)
    557 			fatal("setgroups: %.100s", strerror(errno));
    558 		permanently_set_uid(privsep_pw);
    559 	}
    560 }
    561 
    562 static int
    563 privsep_preauth(Authctxt *authctxt)
    564 {
    565 	int status, r;
    566 	pid_t pid;
    567 	struct ssh_sandbox *box = NULL;
    568 
    569 	/* Set up unprivileged child process to deal with network data */
    570 	pmonitor = monitor_init();
    571 	/* Store a pointer to the kex for later rekeying */
    572 	pmonitor->m_pkex = &active_state->kex;
    573 
    574 	if (use_privsep == PRIVSEP_ON)
    575 		box = ssh_sandbox_init(pmonitor);
    576 	pid = fork();
    577 	if (pid == -1) {
    578 		fatal("fork of unprivileged child failed");
    579 	} else if (pid != 0) {
    580 		debug2("Network child is on pid %ld", (long)pid);
    581 
    582 		pmonitor->m_pid = pid;
    583 		if (have_agent) {
    584 			r = ssh_get_authentication_socket(&auth_sock);
    585 			if (r != 0) {
    586 				error("Could not get agent socket: %s",
    587 				    ssh_err(r));
    588 				have_agent = 0;
    589 			}
    590 		}
    591 		if (box != NULL)
    592 			ssh_sandbox_parent_preauth(box, pid);
    593 		monitor_child_preauth(authctxt, pmonitor);
    594 
    595 		/* Wait for the child's exit status */
    596 		while (waitpid(pid, &status, 0) < 0) {
    597 			if (errno == EINTR)
    598 				continue;
    599 			pmonitor->m_pid = -1;
    600 			fatal("%s: waitpid: %s", __func__, strerror(errno));
    601 		}
    602 		privsep_is_preauth = 0;
    603 		pmonitor->m_pid = -1;
    604 		if (WIFEXITED(status)) {
    605 			if (WEXITSTATUS(status) != 0)
    606 				fatal("%s: preauth child exited with status %d",
    607 				    __func__, WEXITSTATUS(status));
    608 		} else if (WIFSIGNALED(status))
    609 			fatal("%s: preauth child terminated by signal %d",
    610 			    __func__, WTERMSIG(status));
    611 		if (box != NULL)
    612 			ssh_sandbox_parent_finish(box);
    613 		return 1;
    614 	} else {
    615 		/* child */
    616 		close(pmonitor->m_sendfd);
    617 		close(pmonitor->m_log_recvfd);
    618 
    619 		/* Arrange for logging to be sent to the monitor */
    620 		set_log_handler(mm_log_handler, pmonitor);
    621 
    622 		privsep_preauth_child();
    623 		setproctitle("%s", "[net]");
    624 		if (box != NULL)
    625 			ssh_sandbox_child(box);
    626 
    627 		return 0;
    628 	}
    629 }
    630 
    631 static void
    632 privsep_postauth(Authctxt *authctxt)
    633 {
    634 #ifdef DISABLE_FD_PASSING
    635 	if (1) {
    636 #else
    637 	if (authctxt->pw->pw_uid == 0) {
    638 #endif
    639 		/* File descriptor passing is broken or root login */
    640 		use_privsep = 0;
    641 		goto skip;
    642 	}
    643 
    644 	/* New socket pair */
    645 	monitor_reinit(pmonitor);
    646 
    647 	pmonitor->m_pid = fork();
    648 	if (pmonitor->m_pid == -1)
    649 		fatal("fork of unprivileged child failed");
    650 	else if (pmonitor->m_pid != 0) {
    651 		verbose("User child is on pid %ld", (long)pmonitor->m_pid);
    652 		buffer_clear(&loginmsg);
    653 		monitor_child_postauth(pmonitor);
    654 
    655 		/* NEVERREACHED */
    656 		exit(0);
    657 	}
    658 
    659 	/* child */
    660 
    661 	close(pmonitor->m_sendfd);
    662 	pmonitor->m_sendfd = -1;
    663 
    664 	/* Demote the private keys to public keys. */
    665 	demote_sensitive_data();
    666 
    667 	reseed_prngs();
    668 
    669 	/* Drop privileges */
    670 	do_setusercontext(authctxt->pw);
    671 
    672  skip:
    673 	/* It is safe now to apply the key state */
    674 	monitor_apply_keystate(pmonitor);
    675 
    676 	/*
    677 	 * Tell the packet layer that authentication was successful, since
    678 	 * this information is not part of the key state.
    679 	 */
    680 	packet_set_authenticated();
    681 }
    682 
    683 static char *
    684 list_hostkey_types(void)
    685 {
    686 	Buffer b;
    687 	const char *p;
    688 	char *ret;
    689 	int i;
    690 	Key *key;
    691 
    692 	buffer_init(&b);
    693 	for (i = 0; i < options.num_host_key_files; i++) {
    694 		key = sensitive_data.host_keys[i];
    695 		if (key == NULL)
    696 			key = sensitive_data.host_pubkeys[i];
    697 		if (key == NULL)
    698 			continue;
    699 		/* Check that the key is accepted in HostkeyAlgorithms */
    700 		if (match_pattern_list(sshkey_ssh_name(key),
    701 		    options.hostkeyalgorithms, 0) != 1) {
    702 			debug3("%s: %s key not permitted by HostkeyAlgorithms",
    703 			    __func__, sshkey_ssh_name(key));
    704 			continue;
    705 		}
    706 		switch (key->type) {
    707 		case KEY_RSA:
    708 		case KEY_DSA:
    709 		case KEY_ECDSA:
    710 		case KEY_ED25519:
    711 			if (buffer_len(&b) > 0)
    712 				buffer_append(&b, ",", 1);
    713 			p = key_ssh_name(key);
    714 			buffer_append(&b, p, strlen(p));
    715 
    716 			/* for RSA we also support SHA2 signatures */
    717 			if (key->type == KEY_RSA) {
    718 				p = ",rsa-sha2-512,rsa-sha2-256";
    719 				buffer_append(&b, p, strlen(p));
    720 			}
    721 			break;
    722 		}
    723 		/* If the private key has a cert peer, then list that too */
    724 		key = sensitive_data.host_certificates[i];
    725 		if (key == NULL)
    726 			continue;
    727 		switch (key->type) {
    728 		case KEY_RSA_CERT:
    729 		case KEY_DSA_CERT:
    730 		case KEY_ECDSA_CERT:
    731 		case KEY_ED25519_CERT:
    732 			if (buffer_len(&b) > 0)
    733 				buffer_append(&b, ",", 1);
    734 			p = key_ssh_name(key);
    735 			buffer_append(&b, p, strlen(p));
    736 			break;
    737 		}
    738 	}
    739 	if ((ret = sshbuf_dup_string(&b)) == NULL)
    740 		fatal("%s: sshbuf_dup_string failed", __func__);
    741 	buffer_free(&b);
    742 	debug("list_hostkey_types: %s", ret);
    743 	return ret;
    744 }
    745 
    746 static Key *
    747 get_hostkey_by_type(int type, int nid, int need_private, struct ssh *ssh)
    748 {
    749 	int i;
    750 	Key *key;
    751 
    752 	for (i = 0; i < options.num_host_key_files; i++) {
    753 		switch (type) {
    754 		case KEY_RSA_CERT:
    755 		case KEY_DSA_CERT:
    756 		case KEY_ECDSA_CERT:
    757 		case KEY_ED25519_CERT:
    758 			key = sensitive_data.host_certificates[i];
    759 			break;
    760 		default:
    761 			key = sensitive_data.host_keys[i];
    762 			if (key == NULL && !need_private)
    763 				key = sensitive_data.host_pubkeys[i];
    764 			break;
    765 		}
    766 		if (key != NULL && key->type == type &&
    767 		    (key->type != KEY_ECDSA || key->ecdsa_nid == nid))
    768 			return need_private ?
    769 			    sensitive_data.host_keys[i] : key;
    770 	}
    771 	return NULL;
    772 }
    773 
    774 Key *
    775 get_hostkey_public_by_type(int type, int nid, struct ssh *ssh)
    776 {
    777 	return get_hostkey_by_type(type, nid, 0, ssh);
    778 }
    779 
    780 Key *
    781 get_hostkey_private_by_type(int type, int nid, struct ssh *ssh)
    782 {
    783 	return get_hostkey_by_type(type, nid, 1, ssh);
    784 }
    785 
    786 Key *
    787 get_hostkey_by_index(int ind)
    788 {
    789 	if (ind < 0 || ind >= options.num_host_key_files)
    790 		return (NULL);
    791 	return (sensitive_data.host_keys[ind]);
    792 }
    793 
    794 Key *
    795 get_hostkey_public_by_index(int ind, struct ssh *ssh)
    796 {
    797 	if (ind < 0 || ind >= options.num_host_key_files)
    798 		return (NULL);
    799 	return (sensitive_data.host_pubkeys[ind]);
    800 }
    801 
    802 int
    803 get_hostkey_index(Key *key, int compare, struct ssh *ssh)
    804 {
    805 	int i;
    806 
    807 	for (i = 0; i < options.num_host_key_files; i++) {
    808 		if (key_is_cert(key)) {
    809 			if (key == sensitive_data.host_certificates[i] ||
    810 			    (compare && sensitive_data.host_certificates[i] &&
    811 			    sshkey_equal(key,
    812 			    sensitive_data.host_certificates[i])))
    813 				return (i);
    814 		} else {
    815 			if (key == sensitive_data.host_keys[i] ||
    816 			    (compare && sensitive_data.host_keys[i] &&
    817 			    sshkey_equal(key, sensitive_data.host_keys[i])))
    818 				return (i);
    819 			if (key == sensitive_data.host_pubkeys[i] ||
    820 			    (compare && sensitive_data.host_pubkeys[i] &&
    821 			    sshkey_equal(key, sensitive_data.host_pubkeys[i])))
    822 				return (i);
    823 		}
    824 	}
    825 	return (-1);
    826 }
    827 
    828 /* Inform the client of all hostkeys */
    829 static void
    830 notify_hostkeys(struct ssh *ssh)
    831 {
    832 	struct sshbuf *buf;
    833 	struct sshkey *key;
    834 	int i, nkeys, r;
    835 	char *fp;
    836 
    837 	/* Some clients cannot cope with the hostkeys message, skip those. */
    838 	if (datafellows & SSH_BUG_HOSTKEYS)
    839 		return;
    840 
    841 	if ((buf = sshbuf_new()) == NULL)
    842 		fatal("%s: sshbuf_new", __func__);
    843 	for (i = nkeys = 0; i < options.num_host_key_files; i++) {
    844 		key = get_hostkey_public_by_index(i, ssh);
    845 		if (key == NULL || key->type == KEY_UNSPEC ||
    846 		    sshkey_is_cert(key))
    847 			continue;
    848 		fp = sshkey_fingerprint(key, options.fingerprint_hash,
    849 		    SSH_FP_DEFAULT);
    850 		debug3("%s: key %d: %s %s", __func__, i,
    851 		    sshkey_ssh_name(key), fp);
    852 		free(fp);
    853 		if (nkeys == 0) {
    854 			packet_start(SSH2_MSG_GLOBAL_REQUEST);
    855 			packet_put_cstring("hostkeys-00 (at) openssh.com");
    856 			packet_put_char(0); /* want-reply */
    857 		}
    858 		sshbuf_reset(buf);
    859 		if ((r = sshkey_putb(key, buf)) != 0)
    860 			fatal("%s: couldn't put hostkey %d: %s",
    861 			    __func__, i, ssh_err(r));
    862 		packet_put_string(sshbuf_ptr(buf), sshbuf_len(buf));
    863 		nkeys++;
    864 	}
    865 	debug3("%s: sent %d hostkeys", __func__, nkeys);
    866 	if (nkeys == 0)
    867 		fatal("%s: no hostkeys", __func__);
    868 	packet_send();
    869 	sshbuf_free(buf);
    870 }
    871 
    872 /*
    873  * returns 1 if connection should be dropped, 0 otherwise.
    874  * dropping starts at connection #max_startups_begin with a probability
    875  * of (max_startups_rate/100). the probability increases linearly until
    876  * all connections are dropped for startups > max_startups
    877  */
    878 static int
    879 drop_connection(int startups)
    880 {
    881 	int p, r;
    882 
    883 	if (startups < options.max_startups_begin)
    884 		return 0;
    885 	if (startups >= options.max_startups)
    886 		return 1;
    887 	if (options.max_startups_rate == 100)
    888 		return 1;
    889 
    890 	p  = 100 - options.max_startups_rate;
    891 	p *= startups - options.max_startups_begin;
    892 	p /= options.max_startups - options.max_startups_begin;
    893 	p += options.max_startups_rate;
    894 	r = arc4random_uniform(100);
    895 
    896 	debug("drop_connection: p %d, r %d", p, r);
    897 	return (r < p) ? 1 : 0;
    898 }
    899 
    900 static void
    901 usage(void)
    902 {
    903 	fprintf(stderr, "%s, %s\n",
    904 	    SSH_RELEASE,
    905 #ifdef WITH_OPENSSL
    906 	    SSLeay_version(SSLEAY_VERSION)
    907 #else
    908 	    "without OpenSSL"
    909 #endif
    910 	);
    911 	fprintf(stderr,
    912 "usage: sshd [-46DdeiqTt] [-C connection_spec] [-c host_cert_file]\n"
    913 "            [-E log_file] [-f config_file] [-g login_grace_time]\n"
    914 "            [-h host_key_file] [-o option] [-p port] [-u len]\n"
    915 	);
    916 	exit(1);
    917 }
    918 
    919 static void
    920 send_rexec_state(int fd, struct sshbuf *conf)
    921 {
    922 	struct sshbuf *m;
    923 	int r;
    924 
    925 	debug3("%s: entering fd = %d config len %zu", __func__, fd,
    926 	    sshbuf_len(conf));
    927 
    928 	/*
    929 	 * Protocol from reexec master to child:
    930 	 *	string	configuration
    931 	 *	string rngseed		(only if OpenSSL is not self-seeded)
    932 	 */
    933 	if ((m = sshbuf_new()) == NULL)
    934 		fatal("%s: sshbuf_new failed", __func__);
    935 	if ((r = sshbuf_put_stringb(m, conf)) != 0)
    936 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
    937 
    938 #if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
    939 	rexec_send_rng_seed(m);
    940 #endif
    941 
    942 	if (ssh_msg_send(fd, 0, m) == -1)
    943 		fatal("%s: ssh_msg_send failed", __func__);
    944 
    945 	sshbuf_free(m);
    946 
    947 	debug3("%s: done", __func__);
    948 }
    949 
    950 static void
    951 recv_rexec_state(int fd, Buffer *conf)
    952 {
    953 	Buffer m;
    954 	char *cp;
    955 	u_int len;
    956 
    957 	debug3("%s: entering fd = %d", __func__, fd);
    958 
    959 	buffer_init(&m);
    960 
    961 	if (ssh_msg_recv(fd, &m) == -1)
    962 		fatal("%s: ssh_msg_recv failed", __func__);
    963 	if (buffer_get_char(&m) != 0)
    964 		fatal("%s: rexec version mismatch", __func__);
    965 
    966 	cp = buffer_get_string(&m, &len);
    967 	if (conf != NULL)
    968 		buffer_append(conf, cp, len);
    969 	free(cp);
    970 
    971 #if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
    972 	rexec_recv_rng_seed(&m);
    973 #endif
    974 
    975 	buffer_free(&m);
    976 
    977 	debug3("%s: done", __func__);
    978 }
    979 
    980 /* Accept a connection from inetd */
    981 static void
    982 server_accept_inetd(int *sock_in, int *sock_out)
    983 {
    984 	int fd;
    985 
    986 	startup_pipe = -1;
    987 	if (rexeced_flag) {
    988 		close(REEXEC_CONFIG_PASS_FD);
    989 		*sock_in = *sock_out = dup(STDIN_FILENO);
    990 		if (!debug_flag) {
    991 			startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
    992 			close(REEXEC_STARTUP_PIPE_FD);
    993 		}
    994 	} else {
    995 		*sock_in = dup(STDIN_FILENO);
    996 		*sock_out = dup(STDOUT_FILENO);
    997 	}
    998 	/*
    999 	 * We intentionally do not close the descriptors 0, 1, and 2
   1000 	 * as our code for setting the descriptors won't work if
   1001 	 * ttyfd happens to be one of those.
   1002 	 */
   1003 	if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
   1004 		dup2(fd, STDIN_FILENO);
   1005 		dup2(fd, STDOUT_FILENO);
   1006 		if (!log_stderr)
   1007 			dup2(fd, STDERR_FILENO);
   1008 		if (fd > (log_stderr ? STDERR_FILENO : STDOUT_FILENO))
   1009 			close(fd);
   1010 	}
   1011 	debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
   1012 }
   1013 
   1014 /*
   1015  * Listen for TCP connections
   1016  */
   1017 static void
   1018 server_listen(void)
   1019 {
   1020 	int ret, listen_sock, on = 1;
   1021 	struct addrinfo *ai;
   1022 	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
   1023 
   1024 	for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
   1025 		if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
   1026 			continue;
   1027 		if (num_listen_socks >= MAX_LISTEN_SOCKS)
   1028 			fatal("Too many listen sockets. "
   1029 			    "Enlarge MAX_LISTEN_SOCKS");
   1030 		if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
   1031 		    ntop, sizeof(ntop), strport, sizeof(strport),
   1032 		    NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
   1033 			error("getnameinfo failed: %.100s",
   1034 			    ssh_gai_strerror(ret));
   1035 			continue;
   1036 		}
   1037 		/* Create socket for listening. */
   1038 		listen_sock = socket(ai->ai_family, ai->ai_socktype,
   1039 		    ai->ai_protocol);
   1040 		if (listen_sock < 0) {
   1041 			/* kernel may not support ipv6 */
   1042 			verbose("socket: %.100s", strerror(errno));
   1043 			continue;
   1044 		}
   1045 		if (set_nonblock(listen_sock) == -1) {
   1046 			close(listen_sock);
   1047 			continue;
   1048 		}
   1049 		if (fcntl(listen_sock, F_SETFD, FD_CLOEXEC) == -1) {
   1050 			verbose("socket: CLOEXEC: %s", strerror(errno));
   1051 			close(listen_sock);
   1052 			continue;
   1053 		}
   1054 		/*
   1055 		 * Set socket options.
   1056 		 * Allow local port reuse in TIME_WAIT.
   1057 		 */
   1058 		if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
   1059 		    &on, sizeof(on)) == -1)
   1060 			error("setsockopt SO_REUSEADDR: %s", strerror(errno));
   1061 
   1062 		/* Only communicate in IPv6 over AF_INET6 sockets. */
   1063 		if (ai->ai_family == AF_INET6)
   1064 			sock_set_v6only(listen_sock);
   1065 
   1066 		debug("Bind to port %s on %s.", strport, ntop);
   1067 
   1068 		/* Bind the socket to the desired port. */
   1069 		if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
   1070 			error("Bind to port %s on %s failed: %.200s.",
   1071 			    strport, ntop, strerror(errno));
   1072 			close(listen_sock);
   1073 			continue;
   1074 		}
   1075 		listen_socks[num_listen_socks] = listen_sock;
   1076 		num_listen_socks++;
   1077 
   1078 		/* Start listening on the port. */
   1079 		if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
   1080 			fatal("listen on [%s]:%s: %.100s",
   1081 			    ntop, strport, strerror(errno));
   1082 		logit("Server listening on %s port %s.", ntop, strport);
   1083 	}
   1084 	freeaddrinfo(options.listen_addrs);
   1085 
   1086 	if (!num_listen_socks)
   1087 		fatal("Cannot bind any address.");
   1088 }
   1089 
   1090 /*
   1091  * The main TCP accept loop. Note that, for the non-debug case, returns
   1092  * from this function are in a forked subprocess.
   1093  */
   1094 static void
   1095 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
   1096 {
   1097 	fd_set *fdset;
   1098 	int i, j, ret, maxfd;
   1099 	int startups = 0;
   1100 	int startup_p[2] = { -1 , -1 };
   1101 	struct sockaddr_storage from;
   1102 	socklen_t fromlen;
   1103 	pid_t pid;
   1104 	u_char rnd[256];
   1105 
   1106 	/* setup fd set for accept */
   1107 	fdset = NULL;
   1108 	maxfd = 0;
   1109 	for (i = 0; i < num_listen_socks; i++)
   1110 		if (listen_socks[i] > maxfd)
   1111 			maxfd = listen_socks[i];
   1112 	/* pipes connected to unauthenticated childs */
   1113 	startup_pipes = xcalloc(options.max_startups, sizeof(int));
   1114 	for (i = 0; i < options.max_startups; i++)
   1115 		startup_pipes[i] = -1;
   1116 
   1117 	/*
   1118 	 * Stay listening for connections until the system crashes or
   1119 	 * the daemon is killed with a signal.
   1120 	 */
   1121 	for (;;) {
   1122 		if (received_sighup)
   1123 			sighup_restart();
   1124 		free(fdset);
   1125 		fdset = xcalloc(howmany(maxfd + 1, NFDBITS),
   1126 		    sizeof(fd_mask));
   1127 
   1128 		for (i = 0; i < num_listen_socks; i++)
   1129 			FD_SET(listen_socks[i], fdset);
   1130 		for (i = 0; i < options.max_startups; i++)
   1131 			if (startup_pipes[i] != -1)
   1132 				FD_SET(startup_pipes[i], fdset);
   1133 
   1134 		/* Wait in select until there is a connection. */
   1135 		ret = select(maxfd+1, fdset, NULL, NULL, NULL);
   1136 		if (ret < 0 && errno != EINTR)
   1137 			error("select: %.100s", strerror(errno));
   1138 		if (received_sigterm) {
   1139 			logit("Received signal %d; terminating.",
   1140 			    (int) received_sigterm);
   1141 			close_listen_socks();
   1142 			if (options.pid_file != NULL)
   1143 				unlink(options.pid_file);
   1144 			exit(received_sigterm == SIGTERM ? 0 : 255);
   1145 		}
   1146 		if (ret < 0)
   1147 			continue;
   1148 
   1149 		for (i = 0; i < options.max_startups; i++)
   1150 			if (startup_pipes[i] != -1 &&
   1151 			    FD_ISSET(startup_pipes[i], fdset)) {
   1152 				/*
   1153 				 * the read end of the pipe is ready
   1154 				 * if the child has closed the pipe
   1155 				 * after successful authentication
   1156 				 * or if the child has died
   1157 				 */
   1158 				close(startup_pipes[i]);
   1159 				startup_pipes[i] = -1;
   1160 				startups--;
   1161 			}
   1162 		for (i = 0; i < num_listen_socks; i++) {
   1163 			if (!FD_ISSET(listen_socks[i], fdset))
   1164 				continue;
   1165 			fromlen = sizeof(from);
   1166 			*newsock = accept(listen_socks[i],
   1167 			    (struct sockaddr *)&from, &fromlen);
   1168 			if (*newsock < 0) {
   1169 				if (errno != EINTR && errno != EWOULDBLOCK &&
   1170 				    errno != ECONNABORTED && errno != EAGAIN)
   1171 					error("accept: %.100s",
   1172 					    strerror(errno));
   1173 				if (errno == EMFILE || errno == ENFILE)
   1174 					usleep(100 * 1000);
   1175 				continue;
   1176 			}
   1177 			if (unset_nonblock(*newsock) == -1) {
   1178 				close(*newsock);
   1179 				continue;
   1180 			}
   1181 			if (drop_connection(startups) == 1) {
   1182 				char *laddr = get_local_ipaddr(*newsock);
   1183 				char *raddr = get_peer_ipaddr(*newsock);
   1184 
   1185 				verbose("drop connection #%d from [%s]:%d "
   1186 				    "on [%s]:%d past MaxStartups", startups,
   1187 				    raddr, get_peer_port(*newsock),
   1188 				    laddr, get_local_port(*newsock));
   1189 				free(laddr);
   1190 				free(raddr);
   1191 				close(*newsock);
   1192 				continue;
   1193 			}
   1194 			if (pipe(startup_p) == -1) {
   1195 				close(*newsock);
   1196 				continue;
   1197 			}
   1198 
   1199 			if (rexec_flag && socketpair(AF_UNIX,
   1200 			    SOCK_STREAM, 0, config_s) == -1) {
   1201 				error("reexec socketpair: %s",
   1202 				    strerror(errno));
   1203 				close(*newsock);
   1204 				close(startup_p[0]);
   1205 				close(startup_p[1]);
   1206 				continue;
   1207 			}
   1208 
   1209 			for (j = 0; j < options.max_startups; j++)
   1210 				if (startup_pipes[j] == -1) {
   1211 					startup_pipes[j] = startup_p[0];
   1212 					if (maxfd < startup_p[0])
   1213 						maxfd = startup_p[0];
   1214 					startups++;
   1215 					break;
   1216 				}
   1217 
   1218 			/*
   1219 			 * Got connection.  Fork a child to handle it, unless
   1220 			 * we are in debugging mode.
   1221 			 */
   1222 			if (debug_flag) {
   1223 				/*
   1224 				 * In debugging mode.  Close the listening
   1225 				 * socket, and start processing the
   1226 				 * connection without forking.
   1227 				 */
   1228 				debug("Server will not fork when running in debugging mode.");
   1229 				close_listen_socks();
   1230 				*sock_in = *newsock;
   1231 				*sock_out = *newsock;
   1232 				close(startup_p[0]);
   1233 				close(startup_p[1]);
   1234 				startup_pipe = -1;
   1235 				pid = getpid();
   1236 				if (rexec_flag) {
   1237 					send_rexec_state(config_s[0],
   1238 					    &cfg);
   1239 					close(config_s[0]);
   1240 				}
   1241 				break;
   1242 			}
   1243 
   1244 			/*
   1245 			 * Normal production daemon.  Fork, and have
   1246 			 * the child process the connection. The
   1247 			 * parent continues listening.
   1248 			 */
   1249 			platform_pre_fork();
   1250 			if ((pid = fork()) == 0) {
   1251 				/*
   1252 				 * Child.  Close the listening and
   1253 				 * max_startup sockets.  Start using
   1254 				 * the accepted socket. Reinitialize
   1255 				 * logging (since our pid has changed).
   1256 				 * We break out of the loop to handle
   1257 				 * the connection.
   1258 				 */
   1259 				platform_post_fork_child();
   1260 				startup_pipe = startup_p[1];
   1261 				close_startup_pipes();
   1262 				close_listen_socks();
   1263 				*sock_in = *newsock;
   1264 				*sock_out = *newsock;
   1265 				log_init(__progname,
   1266 				    options.log_level,
   1267 				    options.log_facility,
   1268 				    log_stderr);
   1269 				if (rexec_flag)
   1270 					close(config_s[0]);
   1271 				break;
   1272 			}
   1273 
   1274 			/* Parent.  Stay in the loop. */
   1275 			platform_post_fork_parent(pid);
   1276 			if (pid < 0)
   1277 				error("fork: %.100s", strerror(errno));
   1278 			else
   1279 				debug("Forked child %ld.", (long)pid);
   1280 
   1281 			close(startup_p[1]);
   1282 
   1283 			if (rexec_flag) {
   1284 				send_rexec_state(config_s[0], &cfg);
   1285 				close(config_s[0]);
   1286 				close(config_s[1]);
   1287 			}
   1288 			close(*newsock);
   1289 
   1290 			/*
   1291 			 * Ensure that our random state differs
   1292 			 * from that of the child
   1293 			 */
   1294 			arc4random_stir();
   1295 			arc4random_buf(rnd, sizeof(rnd));
   1296 #ifdef WITH_OPENSSL
   1297 			RAND_seed(rnd, sizeof(rnd));
   1298 			if ((RAND_bytes((u_char *)rnd, 1)) != 1)
   1299 				fatal("%s: RAND_bytes failed", __func__);
   1300 #endif
   1301 			explicit_bzero(rnd, sizeof(rnd));
   1302 		}
   1303 
   1304 		/* child process check (or debug mode) */
   1305 		if (num_listen_socks < 0)
   1306 			break;
   1307 	}
   1308 }
   1309 
   1310 /*
   1311  * If IP options are supported, make sure there are none (log and
   1312  * return an error if any are found).  Basically we are worried about
   1313  * source routing; it can be used to pretend you are somebody
   1314  * (ip-address) you are not. That itself may be "almost acceptable"
   1315  * under certain circumstances, but rhosts autentication is useless
   1316  * if source routing is accepted. Notice also that if we just dropped
   1317  * source routing here, the other side could use IP spoofing to do
   1318  * rest of the interaction and could still bypass security.  So we
   1319  * exit here if we detect any IP options.
   1320  */
   1321 static void
   1322 check_ip_options(struct ssh *ssh)
   1323 {
   1324 #ifdef IP_OPTIONS
   1325 	int sock_in = ssh_packet_get_connection_in(ssh);
   1326 	struct sockaddr_storage from;
   1327 	u_char opts[200];
   1328 	socklen_t i, option_size = sizeof(opts), fromlen = sizeof(from);
   1329 	char text[sizeof(opts) * 3 + 1];
   1330 
   1331 	memset(&from, 0, sizeof(from));
   1332 	if (getpeername(sock_in, (struct sockaddr *)&from,
   1333 	    &fromlen) < 0)
   1334 		return;
   1335 	if (from.ss_family != AF_INET)
   1336 		return;
   1337 	/* XXX IPv6 options? */
   1338 
   1339 	if (getsockopt(sock_in, IPPROTO_IP, IP_OPTIONS, opts,
   1340 	    &option_size) >= 0 && option_size != 0) {
   1341 		text[0] = '\0';
   1342 		for (i = 0; i < option_size; i++)
   1343 			snprintf(text + i*3, sizeof(text) - i*3,
   1344 			    " %2.2x", opts[i]);
   1345 		fatal("Connection from %.100s port %d with IP opts: %.800s",
   1346 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), text);
   1347 	}
   1348 	return;
   1349 #endif /* IP_OPTIONS */
   1350 }
   1351 
   1352 /*
   1353  * Main program for the daemon.
   1354  */
   1355 int
   1356 main(int ac, char **av)
   1357 {
   1358 	struct ssh *ssh = NULL;
   1359 	extern char *optarg;
   1360 	extern int optind;
   1361 	int r, opt, i, j, on = 1, already_daemon;
   1362 	int sock_in = -1, sock_out = -1, newsock = -1;
   1363 	const char *remote_ip;
   1364 	int remote_port;
   1365 	char *fp, *line, *laddr, *logfile = NULL;
   1366 	int config_s[2] = { -1 , -1 };
   1367 	u_int n;
   1368 	u_int64_t ibytes, obytes;
   1369 	mode_t new_umask;
   1370 	Key *key;
   1371 	Key *pubkey;
   1372 	int keytype;
   1373 	Authctxt *authctxt;
   1374 	struct connection_info *connection_info = get_connection_info(0, 0);
   1375 
   1376 	ssh_malloc_init();	/* must be called before any mallocs */
   1377 
   1378 #ifdef HAVE_SECUREWARE
   1379 	(void)set_auth_parameters(ac, av);
   1380 #endif
   1381 	__progname = ssh_get_progname(av[0]);
   1382 
   1383 	/* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
   1384 	saved_argc = ac;
   1385 	rexec_argc = ac;
   1386 	saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
   1387 	for (i = 0; i < ac; i++)
   1388 		saved_argv[i] = xstrdup(av[i]);
   1389 	saved_argv[i] = NULL;
   1390 
   1391 #ifndef HAVE_SETPROCTITLE
   1392 	/* Prepare for later setproctitle emulation */
   1393 	compat_init_setproctitle(ac, av);
   1394 	av = saved_argv;
   1395 #endif
   1396 
   1397 	if (geteuid() == 0 && setgroups(0, NULL) == -1)
   1398 		debug("setgroups(): %.200s", strerror(errno));
   1399 
   1400 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
   1401 	sanitise_stdfd();
   1402 
   1403 	/* Initialize configuration options to their default values. */
   1404 	initialize_server_options(&options);
   1405 
   1406 	/* Parse command-line arguments. */
   1407 	while ((opt = getopt(ac, av,
   1408 	    "C:E:b:c:f:g:h:k:o:p:u:46DQRTdeiqrt")) != -1) {
   1409 		switch (opt) {
   1410 		case '4':
   1411 			options.address_family = AF_INET;
   1412 			break;
   1413 		case '6':
   1414 			options.address_family = AF_INET6;
   1415 			break;
   1416 		case 'f':
   1417 			config_file_name = optarg;
   1418 			break;
   1419 		case 'c':
   1420 			if (options.num_host_cert_files >= MAX_HOSTCERTS) {
   1421 				fprintf(stderr, "too many host certificates.\n");
   1422 				exit(1);
   1423 			}
   1424 			options.host_cert_files[options.num_host_cert_files++] =
   1425 			   derelativise_path(optarg);
   1426 			break;
   1427 		case 'd':
   1428 			if (debug_flag == 0) {
   1429 				debug_flag = 1;
   1430 				options.log_level = SYSLOG_LEVEL_DEBUG1;
   1431 			} else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
   1432 				options.log_level++;
   1433 			break;
   1434 		case 'D':
   1435 			no_daemon_flag = 1;
   1436 			break;
   1437 		case 'E':
   1438 			logfile = optarg;
   1439 			/* FALLTHROUGH */
   1440 		case 'e':
   1441 			log_stderr = 1;
   1442 			break;
   1443 		case 'i':
   1444 			inetd_flag = 1;
   1445 			break;
   1446 		case 'r':
   1447 			rexec_flag = 0;
   1448 			break;
   1449 		case 'R':
   1450 			rexeced_flag = 1;
   1451 			inetd_flag = 1;
   1452 			break;
   1453 		case 'Q':
   1454 			/* ignored */
   1455 			break;
   1456 		case 'q':
   1457 			options.log_level = SYSLOG_LEVEL_QUIET;
   1458 			break;
   1459 		case 'b':
   1460 			/* protocol 1, ignored */
   1461 			break;
   1462 		case 'p':
   1463 			options.ports_from_cmdline = 1;
   1464 			if (options.num_ports >= MAX_PORTS) {
   1465 				fprintf(stderr, "too many ports.\n");
   1466 				exit(1);
   1467 			}
   1468 			options.ports[options.num_ports++] = a2port(optarg);
   1469 			if (options.ports[options.num_ports-1] <= 0) {
   1470 				fprintf(stderr, "Bad port number.\n");
   1471 				exit(1);
   1472 			}
   1473 			break;
   1474 		case 'g':
   1475 			if ((options.login_grace_time = convtime(optarg)) == -1) {
   1476 				fprintf(stderr, "Invalid login grace time.\n");
   1477 				exit(1);
   1478 			}
   1479 			break;
   1480 		case 'k':
   1481 			/* protocol 1, ignored */
   1482 			break;
   1483 		case 'h':
   1484 			if (options.num_host_key_files >= MAX_HOSTKEYS) {
   1485 				fprintf(stderr, "too many host keys.\n");
   1486 				exit(1);
   1487 			}
   1488 			options.host_key_files[options.num_host_key_files++] =
   1489 			   derelativise_path(optarg);
   1490 			break;
   1491 		case 't':
   1492 			test_flag = 1;
   1493 			break;
   1494 		case 'T':
   1495 			test_flag = 2;
   1496 			break;
   1497 		case 'C':
   1498 			if (parse_server_match_testspec(connection_info,
   1499 			    optarg) == -1)
   1500 				exit(1);
   1501 			break;
   1502 		case 'u':
   1503 			utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
   1504 			if (utmp_len > HOST_NAME_MAX+1) {
   1505 				fprintf(stderr, "Invalid utmp length.\n");
   1506 				exit(1);
   1507 			}
   1508 			break;
   1509 		case 'o':
   1510 			line = xstrdup(optarg);
   1511 			if (process_server_config_line(&options, line,
   1512 			    "command-line", 0, NULL, NULL) != 0)
   1513 				exit(1);
   1514 			free(line);
   1515 			break;
   1516 		case '?':
   1517 		default:
   1518 			usage();
   1519 			break;
   1520 		}
   1521 	}
   1522 	if (rexeced_flag || inetd_flag)
   1523 		rexec_flag = 0;
   1524 	if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
   1525 		fatal("sshd re-exec requires execution with an absolute path");
   1526 	if (rexeced_flag)
   1527 		closefrom(REEXEC_MIN_FREE_FD);
   1528 	else
   1529 		closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
   1530 
   1531 #ifdef WITH_OPENSSL
   1532 	OpenSSL_add_all_algorithms();
   1533 #endif
   1534 
   1535 	/* If requested, redirect the logs to the specified logfile. */
   1536 	if (logfile != NULL)
   1537 		log_redirect_stderr_to(logfile);
   1538 	/*
   1539 	 * Force logging to stderr until we have loaded the private host
   1540 	 * key (unless started from inetd)
   1541 	 */
   1542 	log_init(__progname,
   1543 	    options.log_level == SYSLOG_LEVEL_NOT_SET ?
   1544 	    SYSLOG_LEVEL_INFO : options.log_level,
   1545 	    options.log_facility == SYSLOG_FACILITY_NOT_SET ?
   1546 	    SYSLOG_FACILITY_AUTH : options.log_facility,
   1547 	    log_stderr || !inetd_flag);
   1548 
   1549 	/*
   1550 	 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
   1551 	 * root's environment
   1552 	 */
   1553 	if (getenv("KRB5CCNAME") != NULL)
   1554 		(void) unsetenv("KRB5CCNAME");
   1555 
   1556 #ifdef _UNICOS
   1557 	/* Cray can define user privs drop all privs now!
   1558 	 * Not needed on PRIV_SU systems!
   1559 	 */
   1560 	drop_cray_privs();
   1561 #endif
   1562 
   1563 	sensitive_data.have_ssh2_key = 0;
   1564 
   1565 	/*
   1566 	 * If we're doing an extended config test, make sure we have all of
   1567 	 * the parameters we need.  If we're not doing an extended test,
   1568 	 * do not silently ignore connection test params.
   1569 	 */
   1570 	if (test_flag >= 2 && server_match_spec_complete(connection_info) == 0)
   1571 		fatal("user, host and addr are all required when testing "
   1572 		   "Match configs");
   1573 	if (test_flag < 2 && server_match_spec_complete(connection_info) >= 0)
   1574 		fatal("Config test connection parameter (-C) provided without "
   1575 		   "test mode (-T)");
   1576 
   1577 	/* Fetch our configuration */
   1578 	buffer_init(&cfg);
   1579 	if (rexeced_flag)
   1580 		recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
   1581 	else if (strcasecmp(config_file_name, "none") != 0)
   1582 		load_server_config(config_file_name, &cfg);
   1583 
   1584 	parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
   1585 	    &cfg, NULL);
   1586 
   1587 	seed_rng();
   1588 
   1589 	/* Fill in default values for those options not explicitly set. */
   1590 	fill_default_server_options(&options);
   1591 
   1592 	/* challenge-response is implemented via keyboard interactive */
   1593 	if (options.challenge_response_authentication)
   1594 		options.kbd_interactive_authentication = 1;
   1595 
   1596 	/* Check that options are sensible */
   1597 	if (options.authorized_keys_command_user == NULL &&
   1598 	    (options.authorized_keys_command != NULL &&
   1599 	    strcasecmp(options.authorized_keys_command, "none") != 0))
   1600 		fatal("AuthorizedKeysCommand set without "
   1601 		    "AuthorizedKeysCommandUser");
   1602 	if (options.authorized_principals_command_user == NULL &&
   1603 	    (options.authorized_principals_command != NULL &&
   1604 	    strcasecmp(options.authorized_principals_command, "none") != 0))
   1605 		fatal("AuthorizedPrincipalsCommand set without "
   1606 		    "AuthorizedPrincipalsCommandUser");
   1607 
   1608 	/*
   1609 	 * Check whether there is any path through configured auth methods.
   1610 	 * Unfortunately it is not possible to verify this generally before
   1611 	 * daemonisation in the presence of Match block, but this catches
   1612 	 * and warns for trivial misconfigurations that could break login.
   1613 	 */
   1614 	if (options.num_auth_methods != 0) {
   1615 		for (n = 0; n < options.num_auth_methods; n++) {
   1616 			if (auth2_methods_valid(options.auth_methods[n],
   1617 			    1) == 0)
   1618 				break;
   1619 		}
   1620 		if (n >= options.num_auth_methods)
   1621 			fatal("AuthenticationMethods cannot be satisfied by "
   1622 			    "enabled authentication methods");
   1623 	}
   1624 
   1625 	/* set default channel AF */
   1626 	channel_set_af(options.address_family);
   1627 
   1628 	/* Check that there are no remaining arguments. */
   1629 	if (optind < ac) {
   1630 		fprintf(stderr, "Extra argument %s.\n", av[optind]);
   1631 		exit(1);
   1632 	}
   1633 
   1634 	debug("sshd version %s, %s", SSH_VERSION,
   1635 #ifdef WITH_OPENSSL
   1636 	    SSLeay_version(SSLEAY_VERSION)
   1637 #else
   1638 	    "without OpenSSL"
   1639 #endif
   1640 	);
   1641 
   1642 	/* Store privilege separation user for later use if required. */
   1643 	if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
   1644 		if (use_privsep || options.kerberos_authentication)
   1645 			fatal("Privilege separation user %s does not exist",
   1646 			    SSH_PRIVSEP_USER);
   1647 	} else {
   1648 #if defined(ANDROID)
   1649 /* Android does not do passwords and passes NULL for them. This breaks strlen */
   1650           if (privsep_pw->pw_passwd) {
   1651 #endif
   1652 		explicit_bzero(privsep_pw->pw_passwd,
   1653 		    strlen(privsep_pw->pw_passwd));
   1654 		privsep_pw = pwcopy(privsep_pw);
   1655 		free(privsep_pw->pw_passwd);
   1656 #if defined(ANDROID)
   1657           }
   1658 #endif
   1659 		privsep_pw->pw_passwd = xstrdup("*");
   1660 	}
   1661 #if !defined(ANDROID)
   1662 	endpwent();
   1663 #endif
   1664 
   1665 	/* load host keys */
   1666 	sensitive_data.host_keys = xcalloc(options.num_host_key_files,
   1667 	    sizeof(Key *));
   1668 	sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
   1669 	    sizeof(Key *));
   1670 
   1671 	if (options.host_key_agent) {
   1672 		if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
   1673 			setenv(SSH_AUTHSOCKET_ENV_NAME,
   1674 			    options.host_key_agent, 1);
   1675 		if ((r = ssh_get_authentication_socket(NULL)) == 0)
   1676 			have_agent = 1;
   1677 		else
   1678 			error("Could not connect to agent \"%s\": %s",
   1679 			    options.host_key_agent, ssh_err(r));
   1680 	}
   1681 
   1682 	for (i = 0; i < options.num_host_key_files; i++) {
   1683 		if (options.host_key_files[i] == NULL)
   1684 			continue;
   1685 		key = key_load_private(options.host_key_files[i], "", NULL);
   1686 		pubkey = key_load_public(options.host_key_files[i], NULL);
   1687 
   1688 		if ((pubkey != NULL && pubkey->type == KEY_RSA1) ||
   1689 		    (key != NULL && key->type == KEY_RSA1)) {
   1690 			verbose("Ignoring RSA1 key %s",
   1691 			    options.host_key_files[i]);
   1692 			key_free(key);
   1693 			key_free(pubkey);
   1694 			continue;
   1695 		}
   1696 		if (pubkey == NULL && key != NULL)
   1697 			pubkey = key_demote(key);
   1698 		sensitive_data.host_keys[i] = key;
   1699 		sensitive_data.host_pubkeys[i] = pubkey;
   1700 
   1701 		if (key == NULL && pubkey != NULL && have_agent) {
   1702 			debug("will rely on agent for hostkey %s",
   1703 			    options.host_key_files[i]);
   1704 			keytype = pubkey->type;
   1705 		} else if (key != NULL) {
   1706 			keytype = key->type;
   1707 		} else {
   1708 			error("Could not load host key: %s",
   1709 			    options.host_key_files[i]);
   1710 			sensitive_data.host_keys[i] = NULL;
   1711 			sensitive_data.host_pubkeys[i] = NULL;
   1712 			continue;
   1713 		}
   1714 
   1715 		switch (keytype) {
   1716 		case KEY_RSA:
   1717 		case KEY_DSA:
   1718 		case KEY_ECDSA:
   1719 		case KEY_ED25519:
   1720 			if (have_agent || key != NULL)
   1721 				sensitive_data.have_ssh2_key = 1;
   1722 			break;
   1723 		}
   1724 		if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash,
   1725 		    SSH_FP_DEFAULT)) == NULL)
   1726 			fatal("sshkey_fingerprint failed");
   1727 		debug("%s host key #%d: %s %s",
   1728 		    key ? "private" : "agent", i, sshkey_ssh_name(pubkey), fp);
   1729 		free(fp);
   1730 	}
   1731 	if (!sensitive_data.have_ssh2_key) {
   1732 		logit("sshd: no hostkeys available -- exiting.");
   1733 		exit(1);
   1734 	}
   1735 
   1736 	/*
   1737 	 * Load certificates. They are stored in an array at identical
   1738 	 * indices to the public keys that they relate to.
   1739 	 */
   1740 	sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
   1741 	    sizeof(Key *));
   1742 	for (i = 0; i < options.num_host_key_files; i++)
   1743 		sensitive_data.host_certificates[i] = NULL;
   1744 
   1745 	for (i = 0; i < options.num_host_cert_files; i++) {
   1746 		if (options.host_cert_files[i] == NULL)
   1747 			continue;
   1748 		key = key_load_public(options.host_cert_files[i], NULL);
   1749 		if (key == NULL) {
   1750 			error("Could not load host certificate: %s",
   1751 			    options.host_cert_files[i]);
   1752 			continue;
   1753 		}
   1754 		if (!key_is_cert(key)) {
   1755 			error("Certificate file is not a certificate: %s",
   1756 			    options.host_cert_files[i]);
   1757 			key_free(key);
   1758 			continue;
   1759 		}
   1760 		/* Find matching private key */
   1761 		for (j = 0; j < options.num_host_key_files; j++) {
   1762 			if (key_equal_public(key,
   1763 			    sensitive_data.host_keys[j])) {
   1764 				sensitive_data.host_certificates[j] = key;
   1765 				break;
   1766 			}
   1767 		}
   1768 		if (j >= options.num_host_key_files) {
   1769 			error("No matching private key for certificate: %s",
   1770 			    options.host_cert_files[i]);
   1771 			key_free(key);
   1772 			continue;
   1773 		}
   1774 		sensitive_data.host_certificates[j] = key;
   1775 		debug("host certificate: #%d type %d %s", j, key->type,
   1776 		    key_type(key));
   1777 	}
   1778 
   1779 	if (use_privsep) {
   1780 		struct stat st;
   1781 
   1782 		if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
   1783 		    (S_ISDIR(st.st_mode) == 0))
   1784 			fatal("Missing privilege separation directory: %s",
   1785 			    _PATH_PRIVSEP_CHROOT_DIR);
   1786 
   1787 #ifdef HAVE_CYGWIN
   1788 		if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
   1789 		    (st.st_uid != getuid () ||
   1790 		    (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
   1791 #else
   1792 		if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
   1793 #endif
   1794 			fatal("%s must be owned by root and not group or "
   1795 			    "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
   1796 	}
   1797 
   1798 	if (test_flag > 1) {
   1799 		if (server_match_spec_complete(connection_info) == 1)
   1800 			parse_server_match_config(&options, connection_info);
   1801 		dump_config(&options);
   1802 	}
   1803 
   1804 	/* Configuration looks good, so exit if in test mode. */
   1805 	if (test_flag)
   1806 		exit(0);
   1807 
   1808 	/*
   1809 	 * Clear out any supplemental groups we may have inherited.  This
   1810 	 * prevents inadvertent creation of files with bad modes (in the
   1811 	 * portable version at least, it's certainly possible for PAM
   1812 	 * to create a file, and we can't control the code in every
   1813 	 * module which might be used).
   1814 	 */
   1815 	if (setgroups(0, NULL) < 0)
   1816 		debug("setgroups() failed: %.200s", strerror(errno));
   1817 
   1818 	if (rexec_flag) {
   1819 		rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
   1820 		for (i = 0; i < rexec_argc; i++) {
   1821 			debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
   1822 			rexec_argv[i] = saved_argv[i];
   1823 		}
   1824 		rexec_argv[rexec_argc] = "-R";
   1825 		rexec_argv[rexec_argc + 1] = NULL;
   1826 	}
   1827 
   1828 	/* Ensure that umask disallows at least group and world write */
   1829 	new_umask = umask(0077) | 0022;
   1830 	(void) umask(new_umask);
   1831 
   1832 	/* Initialize the log (it is reinitialized below in case we forked). */
   1833 	if (debug_flag && (!inetd_flag || rexeced_flag))
   1834 		log_stderr = 1;
   1835 	log_init(__progname, options.log_level, options.log_facility, log_stderr);
   1836 
   1837 	/*
   1838 	 * If not in debugging mode, not started from inetd and not already
   1839 	 * daemonized (eg re-exec via SIGHUP), disconnect from the controlling
   1840 	 * terminal, and fork.  The original process exits.
   1841 	 */
   1842 	already_daemon = daemonized();
   1843 	if (!(debug_flag || inetd_flag || no_daemon_flag || already_daemon)) {
   1844 
   1845 		if (daemon(0, 0) < 0)
   1846 			fatal("daemon() failed: %.200s", strerror(errno));
   1847 
   1848 		disconnect_controlling_tty();
   1849 	}
   1850 	/* Reinitialize the log (because of the fork above). */
   1851 	log_init(__progname, options.log_level, options.log_facility, log_stderr);
   1852 
   1853 	/* Chdir to the root directory so that the current disk can be
   1854 	   unmounted if desired. */
   1855 	if (chdir("/") == -1)
   1856 		error("chdir(\"/\"): %s", strerror(errno));
   1857 
   1858 	/* ignore SIGPIPE */
   1859 	signal(SIGPIPE, SIG_IGN);
   1860 
   1861 	/* Get a connection, either from inetd or a listening TCP socket */
   1862 	if (inetd_flag) {
   1863 		server_accept_inetd(&sock_in, &sock_out);
   1864 	} else {
   1865 		platform_pre_listen();
   1866 		server_listen();
   1867 
   1868 		signal(SIGHUP, sighup_handler);
   1869 		signal(SIGCHLD, main_sigchld_handler);
   1870 		signal(SIGTERM, sigterm_handler);
   1871 		signal(SIGQUIT, sigterm_handler);
   1872 
   1873 		/*
   1874 		 * Write out the pid file after the sigterm handler
   1875 		 * is setup and the listen sockets are bound
   1876 		 */
   1877 		if (options.pid_file != NULL && !debug_flag) {
   1878 			FILE *f = fopen(options.pid_file, "w");
   1879 
   1880 			if (f == NULL) {
   1881 				error("Couldn't create pid file \"%s\": %s",
   1882 				    options.pid_file, strerror(errno));
   1883 			} else {
   1884 				fprintf(f, "%ld\n", (long) getpid());
   1885 				fclose(f);
   1886 			}
   1887 		}
   1888 
   1889 		/* Accept a connection and return in a forked child */
   1890 		server_accept_loop(&sock_in, &sock_out,
   1891 		    &newsock, config_s);
   1892 	}
   1893 
   1894 	/* This is the child processing a new connection. */
   1895 	setproctitle("%s", "[accepted]");
   1896 
   1897 	/*
   1898 	 * Create a new session and process group since the 4.4BSD
   1899 	 * setlogin() affects the entire process group.  We don't
   1900 	 * want the child to be able to affect the parent.
   1901 	 */
   1902 #if !defined(SSHD_ACQUIRES_CTTY)
   1903 	/*
   1904 	 * If setsid is called, on some platforms sshd will later acquire a
   1905 	 * controlling terminal which will result in "could not set
   1906 	 * controlling tty" errors.
   1907 	 */
   1908 	if (!debug_flag && !inetd_flag && setsid() < 0)
   1909 		error("setsid: %.100s", strerror(errno));
   1910 #endif
   1911 
   1912 	if (rexec_flag) {
   1913 		int fd;
   1914 
   1915 		debug("rexec start in %d out %d newsock %d pipe %d sock %d",
   1916 		    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
   1917 		dup2(newsock, STDIN_FILENO);
   1918 		dup2(STDIN_FILENO, STDOUT_FILENO);
   1919 		if (startup_pipe == -1)
   1920 			close(REEXEC_STARTUP_PIPE_FD);
   1921 		else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) {
   1922 			dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
   1923 			close(startup_pipe);
   1924 			startup_pipe = REEXEC_STARTUP_PIPE_FD;
   1925 		}
   1926 
   1927 		dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
   1928 		close(config_s[1]);
   1929 
   1930 		execv(rexec_argv[0], rexec_argv);
   1931 
   1932 		/* Reexec has failed, fall back and continue */
   1933 		error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
   1934 		recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
   1935 		log_init(__progname, options.log_level,
   1936 		    options.log_facility, log_stderr);
   1937 
   1938 		/* Clean up fds */
   1939 		close(REEXEC_CONFIG_PASS_FD);
   1940 		newsock = sock_out = sock_in = dup(STDIN_FILENO);
   1941 		if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
   1942 			dup2(fd, STDIN_FILENO);
   1943 			dup2(fd, STDOUT_FILENO);
   1944 			if (fd > STDERR_FILENO)
   1945 				close(fd);
   1946 		}
   1947 		debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
   1948 		    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
   1949 	}
   1950 
   1951 	/* Executed child processes don't need these. */
   1952 	fcntl(sock_out, F_SETFD, FD_CLOEXEC);
   1953 	fcntl(sock_in, F_SETFD, FD_CLOEXEC);
   1954 
   1955 	/*
   1956 	 * Disable the key regeneration alarm.  We will not regenerate the
   1957 	 * key since we are no longer in a position to give it to anyone. We
   1958 	 * will not restart on SIGHUP since it no longer makes sense.
   1959 	 */
   1960 	alarm(0);
   1961 	signal(SIGALRM, SIG_DFL);
   1962 	signal(SIGHUP, SIG_DFL);
   1963 	signal(SIGTERM, SIG_DFL);
   1964 	signal(SIGQUIT, SIG_DFL);
   1965 	signal(SIGCHLD, SIG_DFL);
   1966 	signal(SIGINT, SIG_DFL);
   1967 
   1968 	/*
   1969 	 * Register our connection.  This turns encryption off because we do
   1970 	 * not have a key.
   1971 	 */
   1972 	packet_set_connection(sock_in, sock_out);
   1973 	packet_set_server();
   1974 	ssh = active_state; /* XXX */
   1975 	check_ip_options(ssh);
   1976 
   1977 	/* Set SO_KEEPALIVE if requested. */
   1978 	if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
   1979 	    setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
   1980 		error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
   1981 
   1982 	if ((remote_port = ssh_remote_port(ssh)) < 0) {
   1983 		debug("ssh_remote_port failed");
   1984 		cleanup_exit(255);
   1985 	}
   1986 
   1987 	/*
   1988 	 * The rest of the code depends on the fact that
   1989 	 * ssh_remote_ipaddr() caches the remote ip, even if
   1990 	 * the socket goes away.
   1991 	 */
   1992 	remote_ip = ssh_remote_ipaddr(ssh);
   1993 
   1994 #ifdef SSH_AUDIT_EVENTS
   1995 	audit_connection_from(remote_ip, remote_port);
   1996 #endif
   1997 
   1998 	/* Log the connection. */
   1999 	laddr = get_local_ipaddr(sock_in);
   2000 	verbose("Connection from %s port %d on %s port %d",
   2001 	    remote_ip, remote_port, laddr,  ssh_local_port(ssh));
   2002 	free(laddr);
   2003 
   2004 	/*
   2005 	 * We don't want to listen forever unless the other side
   2006 	 * successfully authenticates itself.  So we set up an alarm which is
   2007 	 * cleared after successful authentication.  A limit of zero
   2008 	 * indicates no limit. Note that we don't set the alarm in debugging
   2009 	 * mode; it is just annoying to have the server exit just when you
   2010 	 * are about to discover the bug.
   2011 	 */
   2012 	signal(SIGALRM, grace_alarm_handler);
   2013 	if (!debug_flag)
   2014 		alarm(options.login_grace_time);
   2015 
   2016 	sshd_exchange_identification(ssh, sock_in, sock_out);
   2017 	packet_set_nonblocking();
   2018 
   2019 	/* allocate authentication context */
   2020 	authctxt = xcalloc(1, sizeof(*authctxt));
   2021 
   2022 	authctxt->loginmsg = &loginmsg;
   2023 
   2024 	/* XXX global for cleanup, access from other modules */
   2025 	the_authctxt = authctxt;
   2026 
   2027 	/* prepare buffer to collect messages to display to user after login */
   2028 	buffer_init(&loginmsg);
   2029 	auth_debug_reset();
   2030 
   2031 	if (use_privsep) {
   2032 		if (privsep_preauth(authctxt) == 1)
   2033 			goto authenticated;
   2034 	} else if (have_agent) {
   2035 		if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) {
   2036 			error("Unable to get agent socket: %s", ssh_err(r));
   2037 			have_agent = 0;
   2038 		}
   2039 	}
   2040 
   2041 	/* perform the key exchange */
   2042 	/* authenticate user and start session */
   2043 	do_ssh2_kex();
   2044 	do_authentication2(authctxt);
   2045 
   2046 	/*
   2047 	 * If we use privilege separation, the unprivileged child transfers
   2048 	 * the current keystate and exits
   2049 	 */
   2050 	if (use_privsep) {
   2051 		mm_send_keystate(pmonitor);
   2052 		exit(0);
   2053 	}
   2054 
   2055  authenticated:
   2056 	/*
   2057 	 * Cancel the alarm we set to limit the time taken for
   2058 	 * authentication.
   2059 	 */
   2060 	alarm(0);
   2061 	signal(SIGALRM, SIG_DFL);
   2062 	authctxt->authenticated = 1;
   2063 	if (startup_pipe != -1) {
   2064 		close(startup_pipe);
   2065 		startup_pipe = -1;
   2066 	}
   2067 
   2068 #ifdef SSH_AUDIT_EVENTS
   2069 	audit_event(SSH_AUTH_SUCCESS);
   2070 #endif
   2071 
   2072 #ifdef GSSAPI
   2073 	if (options.gss_authentication) {
   2074 		temporarily_use_uid(authctxt->pw);
   2075 		ssh_gssapi_storecreds();
   2076 		restore_uid();
   2077 	}
   2078 #endif
   2079 #ifdef USE_PAM
   2080 	if (options.use_pam) {
   2081 		do_pam_setcred(1);
   2082 		do_pam_session();
   2083 	}
   2084 #endif
   2085 
   2086 	/*
   2087 	 * In privilege separation, we fork another child and prepare
   2088 	 * file descriptor passing.
   2089 	 */
   2090 	if (use_privsep) {
   2091 		privsep_postauth(authctxt);
   2092 		/* the monitor process [priv] will not return */
   2093 	}
   2094 
   2095 	packet_set_timeout(options.client_alive_interval,
   2096 	    options.client_alive_count_max);
   2097 
   2098 	/* Try to send all our hostkeys to the client */
   2099 	notify_hostkeys(active_state);
   2100 
   2101 	/* Start session. */
   2102 	do_authenticated(authctxt);
   2103 
   2104 	/* The connection has been terminated. */
   2105 	packet_get_bytes(&ibytes, &obytes);
   2106 	verbose("Transferred: sent %llu, received %llu bytes",
   2107 	    (unsigned long long)obytes, (unsigned long long)ibytes);
   2108 
   2109 	verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
   2110 
   2111 #ifdef USE_PAM
   2112 	if (options.use_pam)
   2113 		finish_pam();
   2114 #endif /* USE_PAM */
   2115 
   2116 #ifdef SSH_AUDIT_EVENTS
   2117 	PRIVSEP(audit_event(SSH_CONNECTION_CLOSE));
   2118 #endif
   2119 
   2120 	packet_close();
   2121 
   2122 	if (use_privsep)
   2123 		mm_terminate();
   2124 
   2125 	exit(0);
   2126 }
   2127 
   2128 int
   2129 sshd_hostkey_sign(Key *privkey, Key *pubkey, u_char **signature, size_t *slen,
   2130     const u_char *data, size_t dlen, const char *alg, u_int flag)
   2131 {
   2132 	int r;
   2133 	u_int xxx_slen, xxx_dlen = dlen;
   2134 
   2135 	if (privkey) {
   2136 		if (PRIVSEP(key_sign(privkey, signature, &xxx_slen, data, xxx_dlen,
   2137 		    alg) < 0))
   2138 			fatal("%s: key_sign failed", __func__);
   2139 		if (slen)
   2140 			*slen = xxx_slen;
   2141 	} else if (use_privsep) {
   2142 		if (mm_key_sign(pubkey, signature, &xxx_slen, data, xxx_dlen,
   2143 		    alg) < 0)
   2144 			fatal("%s: pubkey_sign failed", __func__);
   2145 		if (slen)
   2146 			*slen = xxx_slen;
   2147 	} else {
   2148 		if ((r = ssh_agent_sign(auth_sock, pubkey, signature, slen,
   2149 		    data, dlen, alg, datafellows)) != 0)
   2150 			fatal("%s: ssh_agent_sign failed: %s",
   2151 			    __func__, ssh_err(r));
   2152 	}
   2153 	return 0;
   2154 }
   2155 
   2156 /* SSH2 key exchange */
   2157 static void
   2158 do_ssh2_kex(void)
   2159 {
   2160 	char *myproposal[PROPOSAL_MAX] = { KEX_SERVER };
   2161 	struct kex *kex;
   2162 	int r;
   2163 
   2164 	myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(
   2165 	    options.kex_algorithms);
   2166 	myproposal[PROPOSAL_ENC_ALGS_CTOS] = compat_cipher_proposal(
   2167 	    options.ciphers);
   2168 	myproposal[PROPOSAL_ENC_ALGS_STOC] = compat_cipher_proposal(
   2169 	    options.ciphers);
   2170 	myproposal[PROPOSAL_MAC_ALGS_CTOS] =
   2171 	    myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
   2172 
   2173 	if (options.compression == COMP_NONE) {
   2174 		myproposal[PROPOSAL_COMP_ALGS_CTOS] =
   2175 		    myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
   2176 	}
   2177 
   2178 	if (options.rekey_limit || options.rekey_interval)
   2179 		packet_set_rekey_limits(options.rekey_limit,
   2180 		    options.rekey_interval);
   2181 
   2182 	myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal(
   2183 	    list_hostkey_types());
   2184 
   2185 	/* start key exchange */
   2186 	if ((r = kex_setup(active_state, myproposal)) != 0)
   2187 		fatal("kex_setup: %s", ssh_err(r));
   2188 	kex = active_state->kex;
   2189 #ifdef WITH_OPENSSL
   2190 	kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
   2191 	kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
   2192 	kex->kex[KEX_DH_GRP14_SHA256] = kexdh_server;
   2193 	kex->kex[KEX_DH_GRP16_SHA512] = kexdh_server;
   2194 	kex->kex[KEX_DH_GRP18_SHA512] = kexdh_server;
   2195 	kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
   2196 	kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
   2197 # ifdef OPENSSL_HAS_ECC
   2198 	kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
   2199 # endif
   2200 #endif
   2201 	kex->kex[KEX_C25519_SHA256] = kexc25519_server;
   2202 	kex->server = 1;
   2203 	kex->client_version_string=client_version_string;
   2204 	kex->server_version_string=server_version_string;
   2205 	kex->load_host_public_key=&get_hostkey_public_by_type;
   2206 	kex->load_host_private_key=&get_hostkey_private_by_type;
   2207 	kex->host_key_index=&get_hostkey_index;
   2208 	kex->sign = sshd_hostkey_sign;
   2209 
   2210 	dispatch_run(DISPATCH_BLOCK, &kex->done, active_state);
   2211 
   2212 	session_id2 = kex->session_id;
   2213 	session_id2_len = kex->session_id_len;
   2214 
   2215 #ifdef DEBUG_KEXDH
   2216 	/* send 1st encrypted/maced/compressed message */
   2217 	packet_start(SSH2_MSG_IGNORE);
   2218 	packet_put_cstring("markus");
   2219 	packet_send();
   2220 	packet_write_wait();
   2221 #endif
   2222 	debug("KEX done");
   2223 }
   2224 
   2225 /* server specific fatal cleanup */
   2226 void
   2227 cleanup_exit(int i)
   2228 {
   2229 	if (the_authctxt) {
   2230 		do_cleanup(the_authctxt);
   2231 		if (use_privsep && privsep_is_preauth &&
   2232 		    pmonitor != NULL && pmonitor->m_pid > 1) {
   2233 			debug("Killing privsep child %d", pmonitor->m_pid);
   2234 			if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
   2235 			    errno != ESRCH)
   2236 				error("%s: kill(%d): %s", __func__,
   2237 				    pmonitor->m_pid, strerror(errno));
   2238 		}
   2239 	}
   2240 #ifdef SSH_AUDIT_EVENTS
   2241 	/* done after do_cleanup so it can cancel the PAM auth 'thread' */
   2242 	if (!use_privsep || mm_is_monitor())
   2243 		audit_event(SSH_CONNECTION_ABANDON);
   2244 #endif
   2245 	_exit(i);
   2246 }
   2247