Home | History | Annotate | Line # | Download | only in dist
      1 /*	$NetBSD: sshd.c,v 1.57 2026/04/08 18:58:41 christos Exp $	*/
      2 /* $OpenBSD: sshd.c,v 1.626 2026/02/09 21:21:39 dtucker Exp $ */
      3 
      4 /*
      5  * Copyright (c) 2000, 2001, 2002 Markus Friedl.  All rights reserved.
      6  * Copyright (c) 2002 Niels Provos.  All rights reserved.
      7  *
      8  * Redistribution and use in source and binary forms, with or without
      9  * modification, are permitted provided that the following conditions
     10  * are met:
     11  * 1. Redistributions of source code must retain the above copyright
     12  *    notice, this list of conditions and the following disclaimer.
     13  * 2. Redistributions in binary form must reproduce the above copyright
     14  *    notice, this list of conditions and the following disclaimer in the
     15  *    documentation and/or other materials provided with the distribution.
     16  *
     17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     27  */
     28 
     29 #include "includes.h"
     30 __RCSID("$NetBSD: sshd.c,v 1.57 2026/04/08 18:58:41 christos Exp $");
     31 #include <sys/types.h>
     32 #include <sys/param.h>
     33 #include <sys/ioctl.h>
     34 #include <sys/wait.h>
     35 #include <sys/tree.h>
     36 #include <sys/stat.h>
     37 #include <sys/socket.h>
     38 #include <sys/time.h>
     39 #include <sys/queue.h>
     40 #include <sys/utsname.h>
     41 
     42 #include <errno.h>
     43 #include <fcntl.h>
     44 #include <netdb.h>
     45 #include <paths.h>
     46 #include <poll.h>
     47 #include <pwd.h>
     48 #include <signal.h>
     49 #include <stdio.h>
     50 #include <stdlib.h>
     51 #include <string.h>
     52 #include <stdarg.h>
     53 #include <time.h>
     54 #include <unistd.h>
     55 #include <limits.h>
     56 
     57 #include "xmalloc.h"
     58 #include "ssh.h"
     59 #include "sshpty.h"
     60 #include "log.h"
     61 #include "sshbuf.h"
     62 #include "misc.h"
     63 #include "servconf.h"
     64 #include "compat.h"
     65 #include "digest.h"
     66 #include "sshkey.h"
     67 #include "authfile.h"
     68 #include "pathnames.h"
     69 #include "canohost.h"
     70 #include "hostfile.h"
     71 #include "auth.h"
     72 #include "authfd.h"
     73 #include "misc.h"
     74 #include "msg.h"
     75 #include "version.h"
     76 #include "ssherr.h"
     77 #include "sk-api.h"
     78 #include "addr.h"
     79 #include "srclimit.h"
     80 #include "atomicio.h"
     81 #ifdef GSSAPI
     82 #include "ssh-gss.h"
     83 #endif
     84 #include "monitor_wrap.h"
     85 
     86 #ifdef LIBWRAP
     87 #include <tcpd.h>
     88 #include <syslog.h>
     89 int allow_severity = LOG_INFO;
     90 int deny_severity = LOG_WARNING;
     91 #endif /* LIBWRAP */
     92 
     93 #ifdef WITH_LDAP_PUBKEY
     94 #include "ldapauth.h"
     95 #endif
     96 
     97 #ifndef HOST_NAME_MAX
     98 #define HOST_NAME_MAX MAXHOSTNAMELEN
     99 #endif
    100 
    101 /* Re-exec fds */
    102 #define REEXEC_DEVCRYPTO_RESERVED_FD	(STDERR_FILENO + 1)
    103 #define REEXEC_CONFIG_PASS_FD		(STDERR_FILENO + 2)
    104 #define REEXEC_MIN_FREE_FD		(STDERR_FILENO + 3)
    105 
    106 extern char *__progname;
    107 
    108 /* Server configuration options. */
    109 ServerOptions options;
    110 
    111 /*
    112  * Debug mode flag.  This can be set on the command line.  If debug
    113  * mode is enabled, extra debugging output will be sent to the system
    114  * log, the daemon will not go to background, and will exit after processing
    115  * the first connection.
    116  */
    117 int debug_flag = 0;
    118 
    119 /* Saved arguments to main(). */
    120 static char **saved_argv;
    121 
    122 /*
    123  * The sockets that the server is listening; this is used in the SIGHUP
    124  * signal handler.
    125  */
    126 #define	MAX_LISTEN_SOCKS	16
    127 static int listen_socks[MAX_LISTEN_SOCKS];
    128 static int num_listen_socks = 0;
    129 
    130 /*
    131  * Any really sensitive data in the application is contained in this
    132  * structure. The idea is that this structure could be locked into memory so
    133  * that the pages do not get written into swap.  However, there are some
    134  * problems. The private key contains BIGNUMs, and we do not (in principle)
    135  * have access to the internals of them, and locking just the structure is
    136  * not very useful.  Currently, memory locking is not implemented.
    137  */
    138 struct {
    139 	struct sshkey	**host_keys;		/* all private host keys */
    140 	struct sshkey	**host_pubkeys;		/* all public host keys */
    141 	struct sshkey	**host_certificates;	/* all public host certificates */
    142 	int		have_ssh2_key;
    143 } sensitive_data;
    144 
    145 /* This is set to true when a signal is received. */
    146 static volatile sig_atomic_t received_siginfo = 0;
    147 static volatile sig_atomic_t received_sigchld = 0;
    148 static volatile sig_atomic_t received_sighup = 0;
    149 static volatile sig_atomic_t received_sigterm = 0;
    150 
    151 /* record remote hostname or ip */
    152 u_int utmp_len = HOST_NAME_MAX+1;
    153 
    154 /*
    155  * The early_child/children array below is used for tracking children of the
    156  * listening sshd process early in their lifespans, before they have
    157  * completed authentication. This tracking is needed for four things:
    158  *
    159  * 1) Implementing the MaxStartups limit of concurrent unauthenticated
    160  *    connections.
    161  * 2) Avoiding a race condition for SIGHUP processing, where child processes
    162  *    may have listen_socks open that could collide with main listener process
    163  *    after it restarts.
    164  * 3) Ensuring that rexec'd sshd processes have received their initial state
    165  *    from the parent listen process before handling SIGHUP.
    166  * 4) Tracking and logging unsuccessful exits from the preauth sshd monitor,
    167  *    including and especially those for LoginGraceTime timeouts.
    168  *
    169  * Child processes signal that they have completed closure of the listen_socks
    170  * and (if applicable) received their rexec state by sending a char over their
    171  * sock.
    172  *
    173  * Child processes signal that authentication has completed by sending a
    174  * second char over the socket before closing it, otherwise the listener will
    175  * continue tracking the child (and using up a MaxStartups slot) until the
    176  * preauth subprocess exits, whereupon the listener will log its exit status.
    177  * preauth processes will exit with a status of EXIT_LOGIN_GRACE to indicate
    178  * they did not authenticate before the LoginGraceTime alarm fired.
    179  */
    180 struct early_child {
    181 	int pipefd;
    182 	int early;		/* Indicates child closed listener */
    183 	char *id;		/* human readable connection identifier */
    184 	pid_t pid;
    185 	struct xaddr addr;
    186 	int have_addr;
    187 	int status, have_status;
    188 	struct sshbuf *config;
    189 	struct sshbuf *keys;
    190 };
    191 static struct early_child *children;
    192 static int children_active;
    193 
    194 /* sshd_config buffer */
    195 struct sshbuf *cfg;
    196 struct sshbuf *config;	/* packed */
    197 
    198 /* Included files from the configuration file */
    199 struct include_list includes = TAILQ_HEAD_INITIALIZER(includes);
    200 
    201 /* message to be displayed after login */
    202 struct sshbuf *loginmsg;
    203 
    204 static char *listener_proctitle;
    205 
    206 /*
    207  * Close all listening sockets
    208  */
    209 static void
    210 close_listen_socks(void)
    211 {
    212 	int i;
    213 
    214 	for (i = 0; i < num_listen_socks; i++)
    215 		close(listen_socks[i]);
    216 	num_listen_socks = 0;
    217 }
    218 
    219 /* Allocate and initialise the children array */
    220 static void
    221 child_alloc(void)
    222 {
    223 	int i;
    224 
    225 	children = xcalloc(options.max_startups, sizeof(*children));
    226 	for (i = 0; i < options.max_startups; i++) {
    227 		children[i].pipefd = -1;
    228 		children[i].pid = -1;
    229 	}
    230 }
    231 
    232 /* Register a new connection in the children array; child pid comes later */
    233 static struct early_child *
    234 child_register(int pipefd, int sockfd)
    235 {
    236 	int i, lport, rport;
    237 	char *laddr = NULL, *raddr = NULL;
    238 	struct early_child *child = NULL;
    239 	struct sockaddr_storage addr;
    240 	socklen_t addrlen = sizeof(addr);
    241 	struct sockaddr *sa = (struct sockaddr *)&addr;
    242 
    243 	for (i = 0; i < options.max_startups; i++) {
    244 		if (children[i].pipefd != -1 ||
    245 		    children[i].config != NULL ||
    246 		    children[i].keys != NULL ||
    247 		    children[i].pid > 0)
    248 			continue;
    249 		child = &(children[i]);
    250 		break;
    251 	}
    252 	if (child == NULL) {
    253 		fatal_f("error: accepted connection when all %d child "
    254 		    " slots full", options.max_startups);
    255 	}
    256 	child->pipefd = pipefd;
    257 	child->early = 1;
    258 	if ((child->config = sshbuf_fromb(config)) == NULL)
    259 		fatal_f("sshbuf_fromb failed");
    260 	/* record peer address, if available */
    261 	if (getpeername(sockfd, sa, &addrlen) == 0 &&
    262 	   addr_sa_to_xaddr(sa, addrlen, &child->addr) == 0)
    263 		child->have_addr = 1;
    264 	/* format peer address string for logs */
    265 	if ((lport = get_local_port(sockfd)) == 0 ||
    266 	    (rport = get_peer_port(sockfd)) == 0) {
    267 		/* Not a TCP socket */
    268 		raddr = get_peer_ipaddr(sockfd);
    269 		xasprintf(&child->id, "connection from %s", raddr);
    270 	} else {
    271 		laddr = get_local_ipaddr(sockfd);
    272 		raddr = get_peer_ipaddr(sockfd);
    273 		xasprintf(&child->id, "connection from %s to %s", raddr, laddr);
    274 	}
    275 	free(laddr);
    276 	free(raddr);
    277 	if (++children_active > options.max_startups)
    278 		fatal_f("internal error: more children than max_startups");
    279 
    280 	return child;
    281 }
    282 
    283 /*
    284  * Finally free a child entry. Don't call this directly.
    285  */
    286 static void
    287 child_finish(struct early_child *child)
    288 {
    289 	if (children_active == 0)
    290 		fatal_f("internal error: children_active underflow");
    291 	if (child->pipefd != -1) {
    292 		srclimit_done(child->pipefd);
    293 		close(child->pipefd);
    294 	}
    295 	sshbuf_free(child->config);
    296 	sshbuf_free(child->keys);
    297 	free(child->id);
    298 	memset(child, '\0', sizeof(*child));
    299 	child->pipefd = -1;
    300 	child->pid = -1;
    301 	children_active--;
    302 }
    303 
    304 /*
    305  * Close a child's pipe. This will not stop tracking the child immediately
    306  * (it will still be tracked for waitpid()) unless force_final is set, or
    307  * child has already exited.
    308  */
    309 static void
    310 child_close(struct early_child *child, int force_final, int quiet)
    311 {
    312 	if (!quiet)
    313 		debug_f("enter%s", force_final ? " (forcing)" : "");
    314 	if (child->pipefd != -1) {
    315 		srclimit_done(child->pipefd);
    316 		close(child->pipefd);
    317 		child->pipefd = -1;
    318 	}
    319 	if (child->pid == -1 || force_final)
    320 		child_finish(child);
    321 }
    322 
    323 /* Record a child exit. Safe to call from signal handlers */
    324 static void
    325 child_exit(pid_t pid, int status)
    326 {
    327 	int i;
    328 
    329 	if (children == NULL || pid <= 0)
    330 		return;
    331 	for (i = 0; i < options.max_startups; i++) {
    332 		if (children[i].pid == pid) {
    333 			children[i].have_status = 1;
    334 			children[i].status = status;
    335 			break;
    336 		}
    337 	}
    338 }
    339 
    340 /*
    341  * Reap a child entry that has exited, as previously flagged
    342  * using child_exit().
    343  * Handles logging of exit condition and will finalise the child if its pipe
    344  * had already been closed.
    345  */
    346 static void
    347 child_reap(struct early_child *child)
    348 {
    349 	LogLevel level = SYSLOG_LEVEL_DEBUG1;
    350 	int was_crash, penalty_type = SRCLIMIT_PENALTY_NONE;
    351 	const char *child_status;
    352 
    353 	if (child->config)
    354 		child_status = " (sending config)";
    355 	else if (child->keys)
    356 		child_status = " (sending keys)";
    357 	else if (child->early)
    358 		child_status = " (early)";
    359 	else
    360 		child_status = "";
    361 
    362 	/* Log exit information */
    363 	if (WIFSIGNALED(child->status)) {
    364 		/*
    365 		 * Increase logging for signals potentially associated
    366 		 * with serious conditions.
    367 		 */
    368 		if ((was_crash = signal_is_crash(WTERMSIG(child->status))))
    369 			level = SYSLOG_LEVEL_ERROR;
    370 		do_log2(level, "session process %ld for %s killed by "
    371 		    "signal %d%s", (long)child->pid, child->id,
    372 		    WTERMSIG(child->status), child_status);
    373 		if (was_crash)
    374 			penalty_type = SRCLIMIT_PENALTY_CRASH;
    375 	} else if (!WIFEXITED(child->status)) {
    376 		penalty_type = SRCLIMIT_PENALTY_CRASH;
    377 		error("session process %ld for %s terminated abnormally, "
    378 		    "status=0x%x%s", (long)child->pid, child->id, child->status,
    379 		    child_status);
    380 	} else {
    381 		/* Normal exit. We care about the status */
    382 		switch (WEXITSTATUS(child->status)) {
    383 		case 0:
    384 			debug3_f("preauth child %ld for %s completed "
    385 			    "normally%s", (long)child->pid, child->id,
    386 			    child_status);
    387 			break;
    388 		case EXIT_LOGIN_GRACE:
    389 			penalty_type = SRCLIMIT_PENALTY_GRACE_EXCEEDED;
    390 			logit("Timeout before authentication for %s, "
    391 			    "pid = %ld%s", child->id, (long)child->pid,
    392 			    child_status);
    393 			break;
    394 		case EXIT_CHILD_CRASH:
    395 			penalty_type = SRCLIMIT_PENALTY_CRASH;
    396 			logit("Session process %ld unpriv child crash for %s%s",
    397 			    (long)child->pid, child->id, child_status);
    398 			break;
    399 		case EXIT_AUTH_ATTEMPTED:
    400 			penalty_type = SRCLIMIT_PENALTY_AUTHFAIL;
    401 			debug_f("preauth child %ld for %s exited "
    402 			    "after unsuccessful auth attempt%s",
    403 			    (long)child->pid, child->id, child_status);
    404 			break;
    405 		case EXIT_INVALID_USER:
    406 			penalty_type = SRCLIMIT_PENALTY_INVALIDUSER;
    407 			debug_f("preauth child %ld for %s exited "
    408 			    "after auth attempt by invalid user%s",
    409 			    (long)child->pid, child->id, child_status);
    410 			break;
    411 		case EXIT_CONFIG_REFUSED:
    412 			penalty_type = SRCLIMIT_PENALTY_REFUSECONNECTION;
    413 			debug_f("preauth child %ld for %s prohibited by"
    414 			    "RefuseConnection%s",
    415 			    (long)child->pid, child->id, child_status);
    416 			break;
    417 		default:
    418 			penalty_type = SRCLIMIT_PENALTY_NOAUTH;
    419 			debug_f("preauth child %ld for %s exited "
    420 			    "with status %d%s", (long)child->pid, child->id,
    421 			    WEXITSTATUS(child->status), child_status);
    422 			break;
    423 		}
    424 	}
    425 
    426 	if (child->have_addr)
    427 		srclimit_penalise(&child->addr, penalty_type);
    428 
    429 	child->pid = -1;
    430 	child->have_status = 0;
    431 	if (child->pipefd == -1)
    432 		child_finish(child);
    433 }
    434 
    435 /* Reap all children that have exited; called after SIGCHLD */
    436 static void
    437 child_reap_all_exited(void)
    438 {
    439 	int i;
    440 	pid_t pid;
    441 	int status;
    442 
    443 	if (children == NULL)
    444 		return;
    445 
    446 	for (;;) {
    447 		if ((pid = waitpid(-1, &status, WNOHANG)) == 0)
    448 			break;
    449 		else if (pid == -1) {
    450 			if (errno == EINTR || errno == EAGAIN)
    451 				continue;
    452 			if (errno != ECHILD)
    453 				error_f("waitpid: %s", strerror(errno));
    454 			break;
    455 		}
    456 		child_exit(pid, status);
    457 	}
    458 
    459 	for (i = 0; i < options.max_startups; i++) {
    460 		if (!children[i].have_status)
    461 			continue;
    462 		child_reap(&(children[i]));
    463 	}
    464 }
    465 
    466 static void
    467 close_startup_pipes(void)
    468 {
    469 	int i;
    470 
    471 	if (children == NULL)
    472 		return;
    473 	for (i = 0; i < options.max_startups; i++) {
    474 		if (children[i].pipefd != -1)
    475 			child_close(&(children[i]), 1, 1);
    476 	}
    477 }
    478 
    479 /* Called after SIGINFO */
    480 static void
    481 show_info(void)
    482 {
    483 	int i;
    484 	const char *child_status;
    485 
    486 	/* XXX print listening sockets here too */
    487 	if (children == NULL)
    488 		return;
    489 	logit("%d active startups", children_active);
    490 	for (i = 0; i < options.max_startups; i++) {
    491 		if (children[i].pipefd == -1 && children[i].pid <= 0)
    492 			continue;
    493 		if (children[i].config)
    494 			child_status = " (sending config)";
    495 		else if (children[i].keys)
    496 			child_status = " (sending keys)";
    497 		else if (children[i].early)
    498 			child_status = " (early)";
    499 		else
    500 			child_status = "";
    501 		logit("child %d: fd=%d pid=%ld %s%s", i, children[i].pipefd,
    502 		    (long)children[i].pid, children[i].id, child_status);
    503 	}
    504 	srclimit_penalty_info();
    505 }
    506 
    507 /*
    508  * Signal handler for SIGHUP.  Sshd execs itself when it receives SIGHUP;
    509  * the effect is to reread the configuration file (and to regenerate
    510  * the server key).
    511  */
    512 
    513 static void
    514 sighup_handler(int sig)
    515 {
    516 	received_sighup = 1;
    517 }
    518 
    519 /*
    520  * Called from the main program after receiving SIGHUP.
    521  * Restarts the server.
    522  */
    523 __dead
    524 static void
    525 sighup_restart(void)
    526 {
    527 	logit("Received SIGHUP; restarting.");
    528 	if (options.pid_file != NULL)
    529 		unlink(options.pid_file);
    530 	close_listen_socks();
    531 	close_startup_pipes();
    532 	ssh_signal(SIGHUP, SIG_IGN); /* will be restored after exec */
    533 	execv(saved_argv[0], saved_argv);
    534 	logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
    535 	    strerror(errno));
    536 	exit(1);
    537 }
    538 
    539 /*
    540  * Generic signal handler for terminating signals in the master daemon.
    541  */
    542 static void
    543 sigterm_handler(int sig)
    544 {
    545 	received_sigterm = sig;
    546 }
    547 
    548 static void
    549 siginfo_handler(int sig)
    550 {
    551 	received_siginfo = 1;
    552 }
    553 
    554 static void
    555 main_sigchld_handler(int sig)
    556 {
    557 	received_sigchld = 1;
    558 }
    559 
    560 /*
    561  * returns 1 if connection should be dropped, 0 otherwise.
    562  * dropping starts at connection #max_startups_begin with a probability
    563  * of (max_startups_rate/100). the probability increases linearly until
    564  * all connections are dropped for startups > max_startups
    565  */
    566 static int
    567 should_drop_connection(int startups)
    568 {
    569 	int p, r;
    570 
    571 	if (startups < options.max_startups_begin)
    572 		return 0;
    573 	if (startups >= options.max_startups)
    574 		return 1;
    575 	if (options.max_startups_rate == 100)
    576 		return 1;
    577 
    578 	p  = 100 - options.max_startups_rate;
    579 	p *= startups - options.max_startups_begin;
    580 	p /= options.max_startups - options.max_startups_begin;
    581 	p += options.max_startups_rate;
    582 	r = arc4random_uniform(100);
    583 
    584 	debug_f("p %d, r %d", p, r);
    585 	return (r < p) ? 1 : 0;
    586 }
    587 
    588 /*
    589  * Check whether connection should be accepted by MaxStartups or for penalty.
    590  * Returns 0 if the connection is accepted. If the connection is refused,
    591  * returns 1 and attempts to send notification to client.
    592  * Logs when the MaxStartups condition is entered or exited, and periodically
    593  * while in that state.
    594  */
    595 static int
    596 drop_connection(int sock, int startups, int notify_pipe)
    597 {
    598 	static struct log_ratelimit_ctx ratelimit_maxstartups;
    599 	static struct log_ratelimit_ctx ratelimit_penalty;
    600 	static int init_done;
    601 	char *laddr, *raddr;
    602 	const char *reason = NULL, *subreason = NULL;
    603 	const char msg[] = "Not allowed at this time\r\n";
    604 	struct log_ratelimit_ctx *rl = NULL;
    605 	int ratelimited;
    606 	u_int ndropped;
    607 
    608 	if (!init_done) {
    609 		init_done = 1;
    610 		log_ratelimit_init(&ratelimit_maxstartups, 4, 60, 20, 5*60);
    611 		log_ratelimit_init(&ratelimit_penalty, 8, 60, 30, 2*60);
    612 	}
    613 
    614 	/* PerSourcePenalties */
    615 	if (!srclimit_penalty_check_allow(sock, &subreason)) {
    616 		reason = "PerSourcePenalties";
    617 		rl = &ratelimit_penalty;
    618 	} else {
    619 		/* MaxStartups */
    620 		if (!should_drop_connection(startups) &&
    621 		    srclimit_check_allow(sock, notify_pipe) == 1)
    622 			return 0;
    623 		reason = "Maxstartups";
    624 		rl = &ratelimit_maxstartups;
    625 	}
    626 
    627 	laddr = get_local_ipaddr(sock);
    628 	raddr = get_peer_ipaddr(sock);
    629 	ratelimited = log_ratelimit(rl, time(NULL), NULL, &ndropped);
    630 	do_log2(ratelimited ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
    631 	    "drop connection #%d from [%s]:%d on [%s]:%d %s",
    632 	    startups,
    633 	    raddr, get_peer_port(sock),
    634 	    laddr, get_local_port(sock),
    635 	    subreason != NULL ? subreason : reason);
    636 	free(laddr);
    637 	free(raddr);
    638 	if (ndropped != 0) {
    639 		logit("%s logging rate-limited: additional %u connections "
    640 		    "dropped", reason, ndropped);
    641 	}
    642 
    643 	/* best-effort notification to client */
    644 	(void)write(sock, msg, sizeof(msg) - 1);
    645 	return 1;
    646 }
    647 
    648 __dead static void
    649 usage(void)
    650 {
    651 	fprintf(stderr, "%s, %s\n", SSH_VERSION, SSH_OPENSSL_VERSION);
    652 	fprintf(stderr,
    653 "usage: sshd [-46DdeGiqTtV] [-C connection_spec] [-c host_cert_file]\n"
    654 "            [-E log_file] [-f config_file] [-g login_grace_time]\n"
    655 "            [-h host_key_file] [-o option] [-p port] [-u len]\n"
    656 	);
    657 	exit(1);
    658 }
    659 
    660 static struct sshbuf *
    661 pack_hostkeys(void)
    662 {
    663 	struct sshbuf *m = NULL, *keybuf = NULL, *hostkeys = NULL;
    664 	int r;
    665 	u_int i;
    666 	size_t len;
    667 
    668 	if ((m = sshbuf_new()) == NULL ||
    669 	    (keybuf = sshbuf_new()) == NULL ||
    670 	    (hostkeys = sshbuf_new()) == NULL)
    671 		fatal_f("sshbuf_new failed");
    672 
    673 	/* pack hostkeys into a string. Empty key slots get empty strings */
    674 	for (i = 0; i < options.num_host_key_files; i++) {
    675 		/* private key */
    676 		sshbuf_reset(keybuf);
    677 		if (sensitive_data.host_keys[i] != NULL &&
    678 		    (r = sshkey_private_serialize(sensitive_data.host_keys[i],
    679 		    keybuf)) != 0)
    680 			fatal_fr(r, "serialize hostkey private");
    681 		if ((r = sshbuf_put_stringb(hostkeys, keybuf)) != 0)
    682 			fatal_fr(r, "compose hostkey private");
    683 		/* public key */
    684 		if (sensitive_data.host_pubkeys[i] != NULL) {
    685 			if ((r = sshkey_puts(sensitive_data.host_pubkeys[i],
    686 			    hostkeys)) != 0)
    687 				fatal_fr(r, "compose hostkey public");
    688 		} else {
    689 			if ((r = sshbuf_put_string(hostkeys, NULL, 0)) != 0)
    690 				fatal_fr(r, "compose hostkey empty public");
    691 		}
    692 		/* cert */
    693 		if (sensitive_data.host_certificates[i] != NULL) {
    694 			if ((r = sshkey_puts(
    695 			    sensitive_data.host_certificates[i],
    696 			    hostkeys)) != 0)
    697 				fatal_fr(r, "compose host cert");
    698 		} else {
    699 			if ((r = sshbuf_put_string(hostkeys, NULL, 0)) != 0)
    700 				fatal_fr(r, "compose host cert empty");
    701 		}
    702 	}
    703 
    704 	if ((r = sshbuf_put_u32(m, 0)) != 0 ||
    705 	    (r = sshbuf_put_u8(m, 0)) != 0 ||
    706 	    (r = sshbuf_put_stringb(m, hostkeys)) != 0)
    707 		fatal_fr(r, "compose message");
    708 	if ((len = sshbuf_len(m)) < 5 || len > 0xffffffff)
    709 		fatal_f("bad length %zu", len);
    710 	POKE_U32(sshbuf_mutable_ptr(m), len - 4);
    711 
    712 	sshbuf_free(keybuf);
    713 	sshbuf_free(hostkeys);
    714 	return m;
    715 }
    716 
    717 static struct sshbuf *
    718 pack_config(struct sshbuf *conf)
    719 {
    720 	struct sshbuf *m = NULL, *inc = NULL;
    721 	struct include_item *item = NULL;
    722 	size_t len;
    723 	int r;
    724 
    725 	debug3_f("d config len %zu", sshbuf_len(conf));
    726 
    727 	if ((m = sshbuf_new()) == NULL ||
    728 	    (inc = sshbuf_new()) == NULL)
    729 		fatal_f("sshbuf_new failed");
    730 
    731 	/* pack includes into a string */
    732 	TAILQ_FOREACH(item, &includes, entry) {
    733 		if ((r = sshbuf_put_cstring(inc, item->selector)) != 0 ||
    734 		    (r = sshbuf_put_cstring(inc, item->filename)) != 0 ||
    735 		    (r = sshbuf_put_stringb(inc, item->contents)) != 0)
    736 			fatal_fr(r, "compose includes");
    737 	}
    738 
    739 	if ((r = sshbuf_put_u32(m, 0)) != 0 ||
    740 	    (r = sshbuf_put_u8(m, 0)) != 0 ||
    741 	    (r = sshbuf_put_stringb(m, conf)) != 0 ||
    742 	    (r = sshbuf_put_u64(m, options.timing_secret)) != 0 ||
    743 	    (r = sshbuf_put_stringb(m, inc)) != 0)
    744 		fatal_fr(r, "compose config");
    745 
    746 	if ((len = sshbuf_len(m)) < 5 || len > 0xffffffff)
    747 		fatal_f("bad length %zu", len);
    748 	POKE_U32(sshbuf_mutable_ptr(m), len - 4);
    749 
    750 	sshbuf_free(inc);
    751 
    752 	debug3_f("done");
    753 	return m;
    754 }
    755 
    756 /*
    757  * Protocol from reexec master to child:
    758  *	uint32  size
    759  *	uint8   type (ignored)
    760  *	string	configuration
    761  *	uint64	timing_secret
    762  *	string	included_files[] {
    763  *		string	selector
    764  *		string	filename
    765  *		string	contents
    766  *	}
    767  * Second message
    768  *	uint32  size
    769  *	uint8   type (ignored)
    770  *	string	host_keys[] {
    771  *		string private_key
    772  *		string public_key
    773  *		string certificate
    774  *	}
    775  */
    776 /*
    777  * This function is used only if inet_flag or debug_flag is set,
    778  * otherwise the data is sent from the main poll loop.
    779  * It sends the config from a child process back to the parent.
    780  * The parent will read the config after exec.
    781  */
    782 static void
    783 send_rexec_state(int fd)
    784 {
    785 	struct sshbuf *keys;
    786 	u_int mlen;
    787 	pid_t pid;
    788 
    789 	if ((pid = fork()) == -1)
    790 		fatal_f("fork failed: %s", strerror(errno));
    791 	if (pid != 0)
    792 		return;
    793 
    794 	debug3_f("entering fd = %d config len %zu", fd,
    795 	    sshbuf_len(config));
    796 
    797 	mlen = sshbuf_len(config);
    798 	if (atomicio(vwrite, fd, sshbuf_mutable_ptr(config), mlen) != mlen)
    799 		error_f("write: %s", strerror(errno));
    800 
    801 	keys = pack_hostkeys();
    802 	mlen = sshbuf_len(keys);
    803 	if (atomicio(vwrite, fd, sshbuf_mutable_ptr(keys), mlen) != mlen)
    804 		error_f("write: %s", strerror(errno));
    805 
    806 	sshbuf_free(keys);
    807 	debug3_f("done");
    808 	exit(0);
    809 }
    810 
    811 /*
    812  * Listen for TCP connections
    813  */
    814 static void
    815 listen_on_addrs(struct listenaddr *la)
    816 {
    817 	int ret, listen_sock;
    818 	struct addrinfo *ai;
    819 	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
    820 	int socksize;
    821 	socklen_t socksizelen = sizeof(int);
    822 
    823 	for (ai = la->addrs; ai; ai = ai->ai_next) {
    824 		if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
    825 			continue;
    826 		if (num_listen_socks >= MAX_LISTEN_SOCKS)
    827 			fatal("Too many listen sockets. "
    828 			    "Enlarge MAX_LISTEN_SOCKS");
    829 		if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
    830 		    ntop, sizeof(ntop), strport, sizeof(strport),
    831 		    NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
    832 			error("getnameinfo failed: %.100s",
    833 			    ssh_gai_strerror(ret));
    834 			continue;
    835 		}
    836 		/* Create socket for listening. */
    837 		listen_sock = socket(ai->ai_family, ai->ai_socktype,
    838 		    ai->ai_protocol);
    839 		if (listen_sock == -1) {
    840 			/* kernel may not support ipv6 */
    841 			verbose("socket: %.100s", strerror(errno));
    842 			continue;
    843 		}
    844 		if (set_nonblock(listen_sock) == -1) {
    845 			close(listen_sock);
    846 			continue;
    847 		}
    848 		if (fcntl(listen_sock, F_SETFD, FD_CLOEXEC) == -1) {
    849 			verbose("socket: CLOEXEC: %s", strerror(errno));
    850 			close(listen_sock);
    851 			continue;
    852 		}
    853 		/* Socket options */
    854 		set_reuseaddr(listen_sock);
    855 		if (la->rdomain != NULL &&
    856 		    set_rdomain(listen_sock, la->rdomain) == -1) {
    857 			close(listen_sock);
    858 			continue;
    859 		}
    860 
    861 		debug("Bind to port %s on %s.", strport, ntop);
    862 
    863 		getsockopt(listen_sock, SOL_SOCKET, SO_RCVBUF,
    864 				   &socksize, &socksizelen);
    865 		debug("Server TCP RWIN socket size: %d", socksize);
    866 		debug("HPN Buffer Size: %d", options.hpn_buffer_size);
    867 
    868 		/* Bind the socket to the desired port. */
    869 		if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) == -1) {
    870 			error("Bind to port %s on %s failed: %.200s.",
    871 			    strport, ntop, strerror(errno));
    872 			close(listen_sock);
    873 			continue;
    874 		}
    875 		listen_socks[num_listen_socks] = listen_sock;
    876 		num_listen_socks++;
    877 
    878 		/* Start listening on the port. */
    879 		if (listen(listen_sock, SSH_LISTEN_BACKLOG) == -1)
    880 			fatal("listen on [%s]:%s: %.100s",
    881 			    ntop, strport, strerror(errno));
    882 		logit("Server listening on %s port %s%s%s.",
    883 		    ntop, strport,
    884 		    la->rdomain == NULL ? "" : " rdomain ",
    885 		    la->rdomain == NULL ? "" : la->rdomain);
    886 	}
    887 }
    888 
    889 static void
    890 server_listen(void)
    891 {
    892 	u_int i;
    893 
    894 	/* Initialise per-source limit tracking. */
    895 	srclimit_init(options.max_startups,
    896 	    options.per_source_max_startups,
    897 	    options.per_source_masklen_ipv4,
    898 	    options.per_source_masklen_ipv6,
    899 	    &options.per_source_penalty,
    900 	    options.per_source_penalty_exempt);
    901 
    902 	for (i = 0; i < options.num_listen_addrs; i++) {
    903 		listen_on_addrs(&options.listen_addrs[i]);
    904 		freeaddrinfo(options.listen_addrs[i].addrs);
    905 		free(options.listen_addrs[i].rdomain);
    906 		memset(&options.listen_addrs[i], 0,
    907 		    sizeof(options.listen_addrs[i]));
    908 	}
    909 	free(options.listen_addrs);
    910 	options.listen_addrs = NULL;
    911 	options.num_listen_addrs = 0;
    912 
    913 	if (!num_listen_socks)
    914 		fatal("Cannot bind any address.");
    915 }
    916 
    917 /*
    918  * The main TCP accept loop. Note that, for the non-debug case, returns
    919  * from this function are in a forked subprocess.
    920  */
    921 static void
    922 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s,
    923     int log_stderr)
    924 {
    925 	struct pollfd *pfd = NULL;
    926 	int i, ret, npfd, r;
    927 	int oactive = -1, listening = 0, lameduck = 0;
    928 	int *startup_pollfd;
    929 	ssize_t len;
    930 	const u_char *ptr;
    931 	char c = 0;
    932 	struct sockaddr_storage from;
    933 	struct early_child *child;
    934 	struct sshbuf *buf;
    935 	socklen_t fromlen;
    936 	sigset_t nsigset, osigset;
    937 
    938 	/* setup fd set for accept */
    939 	/* pipes connected to unauthenticated child sshd processes */
    940 	child_alloc();
    941 	startup_pollfd = xcalloc(options.max_startups, sizeof(int));
    942 
    943 	/*
    944 	 * Prepare signal mask that we use to block signals that might set
    945 	 * received_sigterm/hup/chld/info, so that we are guaranteed
    946 	 * to immediately wake up the ppoll if a signal is received after
    947 	 * the flag is checked.
    948 	 */
    949 	sigemptyset(&nsigset);
    950 	sigaddset(&nsigset, SIGHUP);
    951 	sigaddset(&nsigset, SIGCHLD);
    952 	sigaddset(&nsigset, SIGINFO);
    953 	sigaddset(&nsigset, SIGTERM);
    954 	sigaddset(&nsigset, SIGQUIT);
    955 
    956 	/* sized for worst-case */
    957 	pfd = xcalloc(num_listen_socks + options.max_startups,
    958 	    sizeof(struct pollfd));
    959 
    960 	/*
    961 	 * Stay listening for connections until the system crashes or
    962 	 * the daemon is killed with a signal.
    963 	 */
    964 	for (;;) {
    965 		sigprocmask(SIG_BLOCK, &nsigset, &osigset);
    966 		if (received_sigterm) {
    967 			logit("Received signal %d; terminating.",
    968 			    (int) received_sigterm);
    969 			close_listen_socks();
    970 			if (options.pid_file != NULL)
    971 				unlink(options.pid_file);
    972 			exit(received_sigterm == SIGTERM ? 0 : 255);
    973 		}
    974 		if (received_sigchld) {
    975 			child_reap_all_exited();
    976 			received_sigchld = 0;
    977 		}
    978 		if (received_siginfo) {
    979 			show_info();
    980 			received_siginfo = 0;
    981 		}
    982 		if (oactive != children_active) {
    983 			setproctitle("%s [listener] %d of %d-%d startups",
    984 			    listener_proctitle, children_active,
    985 			    options.max_startups_begin, options.max_startups);
    986 			oactive = children_active;
    987 		}
    988 		if (received_sighup) {
    989 			if (!lameduck) {
    990 				debug("Received SIGHUP; waiting for children");
    991 				close_listen_socks();
    992 				lameduck = 1;
    993 			}
    994 			if (listening <= 0) {
    995 				sigprocmask(SIG_SETMASK, &osigset, NULL);
    996 				sighup_restart();
    997 			}
    998 		}
    999 
   1000 		for (i = 0; i < num_listen_socks; i++) {
   1001 			pfd[i].fd = listen_socks[i];
   1002 			pfd[i].events = POLLIN;
   1003 		}
   1004 		npfd = num_listen_socks;
   1005 		for (i = 0; i < options.max_startups; i++) {
   1006 			startup_pollfd[i] = -1;
   1007 			if (children[i].pipefd != -1) {
   1008 				pfd[npfd].fd = children[i].pipefd;
   1009 				pfd[npfd].events = POLLIN;
   1010 				if (children[i].config != NULL ||
   1011 				    children[i].keys != NULL)
   1012 					pfd[npfd].events |= POLLOUT;
   1013 				startup_pollfd[i] = npfd++;
   1014 			}
   1015 		}
   1016 
   1017 		/* Wait until a connection arrives or a child exits. */
   1018 		ret = ppoll(pfd, npfd, NULL, &osigset);
   1019 		if (ret == -1 && errno != EINTR) {
   1020 			error("ppoll: %.100s", strerror(errno));
   1021 			if (errno == EINVAL)
   1022 				cleanup_exit(1); /* can't recover */
   1023 		}
   1024 		sigprocmask(SIG_SETMASK, &osigset, NULL);
   1025 		if (ret == -1)
   1026 			continue;
   1027 
   1028 		for (i = 0; i < options.max_startups; i++) {
   1029 			if (children[i].pipefd == -1 ||
   1030 			    startup_pollfd[i] == -1 ||
   1031 			    !(pfd[startup_pollfd[i]].revents & POLLOUT))
   1032 				continue;
   1033 			if (children[i].config)
   1034 				buf = children[i].config;
   1035 			else if (children[i].keys)
   1036 				buf = children[i].keys;
   1037 			else {
   1038 				error_f("no buffer to send");
   1039 				continue;
   1040 			}
   1041 			ptr = sshbuf_ptr(buf);
   1042 			len = sshbuf_len(buf);
   1043 			ret = write(children[i].pipefd, ptr, len);
   1044 			if (ret == -1 && (errno == EINTR || errno == EAGAIN))
   1045 				continue;
   1046 			if (ret <= 0) {
   1047 				if (children[i].early)
   1048 					listening--;
   1049 				child_close(&(children[i]), 0, 0);
   1050 				continue;
   1051 			}
   1052 			if (ret == len) {
   1053 				/* finished sending buffer */
   1054 				sshbuf_free(buf);
   1055 				if (children[i].config == buf) {
   1056 					/* sent config, now send keys */
   1057 					children[i].config = NULL;
   1058 					children[i].keys = pack_hostkeys();
   1059 				} else if (children[i].keys == buf) {
   1060 					/* sent both config and keys */
   1061 					children[i].keys = NULL;
   1062 				} else {
   1063 					fatal("config buf not set");
   1064 				}
   1065 
   1066 			} else {
   1067 				if ((r = sshbuf_consume(buf, ret)) != 0)
   1068 					fatal_fr(r, "config buf inconsistent");
   1069 			}
   1070 		}
   1071 		for (i = 0; i < options.max_startups; i++) {
   1072 			if (children[i].pipefd == -1 ||
   1073 			    startup_pollfd[i] == -1 ||
   1074 			    !(pfd[startup_pollfd[i]].revents & (POLLIN|POLLHUP)))
   1075 				continue;
   1076 			switch (read(children[i].pipefd, &c, sizeof(c))) {
   1077 			case -1:
   1078 				if (errno == EINTR || errno == EAGAIN)
   1079 					continue;
   1080 				if (errno != EPIPE) {
   1081 					error_f("startup pipe %d (fd=%d): "
   1082 					    "read %s", i, children[i].pipefd,
   1083 					    strerror(errno));
   1084 				}
   1085 				/* FALLTHROUGH */
   1086 			case 0:
   1087 				/* child closed pipe */
   1088 				if (children[i].early)
   1089 					listening--;
   1090 				debug3_f("child %lu for %s closed pipe",
   1091 				    (long)children[i].pid, children[i].id);
   1092 				child_close(&(children[i]), 0, 0);
   1093 				break;
   1094 			case 1:
   1095 				if (children[i].config) {
   1096 					error_f("startup pipe %d (fd=%d)"
   1097 					    " early read",
   1098 					    i, children[i].pipefd);
   1099 					goto problem_child;
   1100 				}
   1101 				if (children[i].early && c == '\0') {
   1102 					/* child has finished preliminaries */
   1103 					listening--;
   1104 					children[i].early = 0;
   1105 					debug2_f("child %lu for %s received "
   1106 					    "config", (long)children[i].pid,
   1107 					    children[i].id);
   1108 				} else if (!children[i].early && c == '\001') {
   1109 					/* child has completed auth */
   1110 					debug2_f("child %lu for %s auth done",
   1111 					    (long)children[i].pid,
   1112 					    children[i].id);
   1113 					child_close(&(children[i]), 1, 0);
   1114 				} else {
   1115 					error_f("unexpected message 0x%02x "
   1116 					    "child %ld for %s in state %d",
   1117 					    (int)c, (long)children[i].pid,
   1118 					    children[i].id, children[i].early);
   1119  problem_child:
   1120 					if (children[i].early)
   1121 						listening--;
   1122 					if (children[i].pid > 0)
   1123 						kill(children[i].pid, SIGTERM);
   1124 					child_close(&(children[i]), 0, 0);
   1125 				}
   1126 				break;
   1127 			}
   1128 		}
   1129 		for (i = 0; i < num_listen_socks; i++) {
   1130 			if (!(pfd[i].revents & POLLIN))
   1131 				continue;
   1132 			fromlen = sizeof(from);
   1133 			*newsock = accept(listen_socks[i],
   1134 			    (struct sockaddr *)&from, &fromlen);
   1135 			if (*newsock == -1) {
   1136 				if (errno != EINTR && errno != EWOULDBLOCK &&
   1137 				    errno != ECONNABORTED)
   1138 					error("accept: %.100s",
   1139 					    strerror(errno));
   1140 				if (errno == EMFILE || errno == ENFILE)
   1141 					usleep(100 * 1000);
   1142 				continue;
   1143 			}
   1144 			if (unset_nonblock(*newsock) == -1) {
   1145 				close(*newsock);
   1146 				continue;
   1147 			}
   1148 			if (socketpair(AF_UNIX,
   1149 			    SOCK_STREAM, 0, config_s) == -1) {
   1150 				error("reexec socketpair: %s",
   1151 				    strerror(errno));
   1152 				close(*newsock);
   1153 				continue;
   1154 			}
   1155 			if (drop_connection(*newsock,
   1156 			    children_active, config_s[0])) {
   1157 				close(*newsock);
   1158 				close(config_s[0]);
   1159 				close(config_s[1]);
   1160 				continue;
   1161 			}
   1162 
   1163 			/*
   1164 			 * Got connection.  Fork a child to handle it, unless
   1165 			 * we are in debugging mode.
   1166 			 */
   1167 			if (debug_flag) {
   1168 				/*
   1169 				 * In debugging mode.  Close the listening
   1170 				 * socket, and start processing the
   1171 				 * connection without forking.
   1172 				 */
   1173 				debug("Server will not fork when running in debugging mode.");
   1174 				close_listen_socks();
   1175 				*sock_in = *newsock;
   1176 				*sock_out = *newsock;
   1177 				send_rexec_state(config_s[0]);
   1178 				close(config_s[0]);
   1179 				free(pfd);
   1180 				free(startup_pollfd);
   1181 				return;
   1182 			}
   1183 
   1184 			/*
   1185 			 * Normal production daemon.  Fork, and have
   1186 			 * the child process the connection. The
   1187 			 * parent continues listening.
   1188 			 */
   1189 			set_nonblock(config_s[0]);
   1190 			listening++;
   1191 			child = child_register(config_s[0], *newsock);
   1192 			if ((child->pid = fork()) == 0) {
   1193 				/*
   1194 				 * Child.  Close the listening and
   1195 				 * max_startup sockets.  Start using
   1196 				 * the accepted socket. Reinitialize
   1197 				 * logging (since our pid has changed).
   1198 				 * We return from this function to handle
   1199 				 * the connection.
   1200 				 */
   1201 				close_startup_pipes();
   1202 				close_listen_socks();
   1203 				*sock_in = *newsock;
   1204 				*sock_out = *newsock;
   1205 				log_init(__progname,
   1206 				    options.log_level,
   1207 				    options.log_facility,
   1208 				    log_stderr);
   1209 				close(config_s[0]);
   1210 				free(pfd);
   1211 				free(startup_pollfd);
   1212 				return;
   1213 			}
   1214 
   1215 			/* Parent.  Stay in the loop. */
   1216 			if (child->pid == -1)
   1217 				error("fork: %.100s", strerror(errno));
   1218 			else
   1219 				debug("Forked child %ld.", (long)child->pid);
   1220 
   1221 			close(config_s[1]);
   1222 			close(*newsock);
   1223 		}
   1224 	}
   1225 }
   1226 
   1227 static void
   1228 accumulate_host_timing_secret(struct sshbuf *server_cfg,
   1229     struct sshkey *key)
   1230 {
   1231 	static struct ssh_digest_ctx *ctx;
   1232 	u_char *hash;
   1233 	size_t len;
   1234 	struct sshbuf *buf;
   1235 	int r;
   1236 
   1237 	if (ctx == NULL && (ctx = ssh_digest_start(SSH_DIGEST_SHA512)) == NULL)
   1238 		fatal_f("ssh_digest_start");
   1239 	if (key == NULL) { /* finalize */
   1240 		/* add server config in case we are using agent for host keys */
   1241 		if (ssh_digest_update(ctx, sshbuf_ptr(server_cfg),
   1242 		    sshbuf_len(server_cfg)) != 0)
   1243 			fatal_f("ssh_digest_update");
   1244 		len = ssh_digest_bytes(SSH_DIGEST_SHA512);
   1245 		hash = xmalloc(len);
   1246 		if (ssh_digest_final(ctx, hash, len) != 0)
   1247 			fatal_f("ssh_digest_final");
   1248 		options.timing_secret = PEEK_U64(hash);
   1249 		freezero(hash, len);
   1250 		ssh_digest_free(ctx);
   1251 		ctx = NULL;
   1252 		return;
   1253 	}
   1254 	if ((buf = sshbuf_new()) == NULL)
   1255 		fatal_f("could not allocate buffer");
   1256 	if ((r = sshkey_private_serialize(key, buf)) != 0)
   1257 		fatal_fr(r, "encode %s key", sshkey_ssh_name(key));
   1258 	if (ssh_digest_update(ctx, sshbuf_ptr(buf), sshbuf_len(buf)) != 0)
   1259 		fatal_f("ssh_digest_update");
   1260 	sshbuf_reset(buf);
   1261 	sshbuf_free(buf);
   1262 }
   1263 
   1264 static char *
   1265 prepare_proctitle(int ac, char **av)
   1266 {
   1267 	char *ret = NULL;
   1268 	int i;
   1269 
   1270 	for (i = 0; i < ac; i++)
   1271 		xextendf(&ret, " ", "%s", av[i]);
   1272 	return ret;
   1273 }
   1274 
   1275 __dead static void
   1276 print_config(struct connection_info *connection_info)
   1277 {
   1278 	connection_info->test = 1;
   1279 	parse_server_match_config(&options, &includes, connection_info);
   1280 	dump_config(&options);
   1281 	exit(0);
   1282 }
   1283 
   1284 /*
   1285  * Main program for the daemon.
   1286  */
   1287 int
   1288 main(int ac, char **av)
   1289 {
   1290 	extern char *optarg;
   1291 	extern int optind;
   1292 	int log_stderr = 0, inetd_flag = 0, test_flag = 0, no_daemon_flag = 0;
   1293 	const char *config_file_name = _PATH_SERVER_CONFIG_FILE;
   1294 	int r, opt, do_dump_cfg = 0, keytype, already_daemon, have_agent = 0;
   1295 	int sock_in = -1, sock_out = -1, newsock = -1, rexec_argc = 0;
   1296 	int devnull, config_s[2] = { -1 , -1 }, have_connection_info = 0;
   1297 	char *args, *fp, *line, *logfile = NULL, **rexec_argv = NULL;
   1298 	struct stat sb;
   1299 	u_int i, j;
   1300 	mode_t new_umask;
   1301 	struct sshkey *key;
   1302 	struct sshkey *pubkey;
   1303 	struct utsname utsname;
   1304 	struct connection_info connection_info;
   1305 	sigset_t sigmask;
   1306 
   1307 	memset(&connection_info, 0, sizeof(connection_info));
   1308 
   1309 	sigemptyset(&sigmask);
   1310 	sigprocmask(SIG_SETMASK, &sigmask, NULL);
   1311 
   1312 	/* Save argv. */
   1313 	saved_argv = av;
   1314 	rexec_argc = ac;
   1315 
   1316 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
   1317 	sanitise_stdfd();
   1318 
   1319 	/* Initialize configuration options to their default values. */
   1320 	initialize_server_options(&options);
   1321 
   1322 	/* Parse command-line arguments. */
   1323 	args = argv_assemble(ac, av); /* logged later */
   1324 	while ((opt = getopt(ac, av,
   1325 	    "C:E:b:c:f:g:h:k:o:p:u:46DGQRTdeiqrtV")) != -1) {
   1326 		switch (opt) {
   1327 		case '4':
   1328 			options.address_family = AF_INET;
   1329 			break;
   1330 		case '6':
   1331 			options.address_family = AF_INET6;
   1332 			break;
   1333 		case 'f':
   1334 			config_file_name = optarg;
   1335 			break;
   1336 		case 'c':
   1337 			servconf_add_hostcert("[command-line]", 0,
   1338 			    &options, optarg);
   1339 			break;
   1340 		case 'd':
   1341 			if (debug_flag == 0) {
   1342 				debug_flag = 1;
   1343 				options.log_level = SYSLOG_LEVEL_DEBUG1;
   1344 			} else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
   1345 				options.log_level++;
   1346 			break;
   1347 		case 'D':
   1348 			no_daemon_flag = 1;
   1349 			break;
   1350 		case 'G':
   1351 			do_dump_cfg = 1;
   1352 			break;
   1353 		case 'E':
   1354 			logfile = optarg;
   1355 			/* FALLTHROUGH */
   1356 		case 'e':
   1357 			log_stderr = 1;
   1358 			break;
   1359 		case 'i':
   1360 			inetd_flag = 1;
   1361 			break;
   1362 		case 'r':
   1363 			logit("-r option is deprecated");
   1364 			break;
   1365 		case 'R':
   1366 			fatal("-R not supported here");
   1367 			break;
   1368 		case 'Q':
   1369 			/* ignored */
   1370 			break;
   1371 		case 'q':
   1372 			options.log_level = SYSLOG_LEVEL_QUIET;
   1373 			break;
   1374 		case 'b':
   1375 			/* protocol 1, ignored */
   1376 			break;
   1377 		case 'p':
   1378 			options.ports_from_cmdline = 1;
   1379 			if (options.num_ports >= MAX_PORTS) {
   1380 				fprintf(stderr, "too many ports.\n");
   1381 				exit(1);
   1382 			}
   1383 			options.ports[options.num_ports++] = a2port(optarg);
   1384 			if (options.ports[options.num_ports-1] <= 0) {
   1385 				fprintf(stderr, "Bad port number.\n");
   1386 				exit(1);
   1387 			}
   1388 			break;
   1389 		case 'g':
   1390 			if ((options.login_grace_time = convtime(optarg)) == -1) {
   1391 				fprintf(stderr, "Invalid login grace time.\n");
   1392 				exit(1);
   1393 			}
   1394 			break;
   1395 		case 'k':
   1396 			/* protocol 1, ignored */
   1397 			break;
   1398 		case 'h':
   1399 			servconf_add_hostkey("[command-line]", 0,
   1400 			    &options, optarg, 1);
   1401 			break;
   1402 		case 't':
   1403 			test_flag = 1;
   1404 			break;
   1405 		case 'T':
   1406 			test_flag = 2;
   1407 			break;
   1408 		case 'C':
   1409 			if (parse_server_match_testspec(&connection_info,
   1410 			    optarg) == -1)
   1411 				exit(1);
   1412 			have_connection_info = 1;
   1413 			break;
   1414 		case 'u':
   1415 			utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
   1416 			if (utmp_len > HOST_NAME_MAX+1) {
   1417 				fprintf(stderr, "Invalid utmp length.\n");
   1418 				exit(1);
   1419 			}
   1420 			break;
   1421 		case 'o':
   1422 			line = xstrdup(optarg);
   1423 			if (process_server_config_line(&options, line,
   1424 			    "command-line", 0, NULL, NULL, &includes) != 0)
   1425 				exit(1);
   1426 			free(line);
   1427 			break;
   1428 		case 'V':
   1429 			fprintf(stderr, "%s, %s\n",
   1430 			    SSH_VERSION, SSH_OPENSSL_VERSION);
   1431 			exit(0);
   1432 		default:
   1433 			usage();
   1434 			break;
   1435 		}
   1436 	}
   1437 	if (!test_flag && !inetd_flag && !do_dump_cfg && !path_absolute(av[0]))
   1438 		fatal("sshd requires execution with an absolute path");
   1439 
   1440 	closefrom(STDERR_FILENO + 1);
   1441 
   1442 	/* Reserve fds we'll need later for reexec things */
   1443 	if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1)
   1444 		fatal("open %s: %s", _PATH_DEVNULL, strerror(errno));
   1445 	while (devnull < REEXEC_MIN_FREE_FD) {
   1446 		if ((devnull = dup(devnull)) == -1)
   1447 			fatal("dup %s: %s", _PATH_DEVNULL, strerror(errno));
   1448 	}
   1449 
   1450 	/* If requested, redirect the logs to the specified logfile. */
   1451 	if (logfile != NULL) {
   1452 		char *cp, pid_s[32];
   1453 
   1454 		snprintf(pid_s, sizeof(pid_s), "%ld", (unsigned long)getpid());
   1455 		cp = percent_expand(logfile,
   1456 		    "p", pid_s,
   1457 		    "P", "sshd",
   1458 		    (char *)NULL);
   1459 		log_redirect_stderr_to(cp);
   1460 		free(cp);
   1461 	}
   1462 
   1463 	/*
   1464 	 * Force logging to stderr until we have loaded the private host
   1465 	 * key (unless started from inetd)
   1466 	 */
   1467 	log_init(__progname,
   1468 	    options.log_level == SYSLOG_LEVEL_NOT_SET ?
   1469 	    SYSLOG_LEVEL_INFO : options.log_level,
   1470 	    options.log_facility == SYSLOG_FACILITY_NOT_SET ?
   1471 	    SYSLOG_FACILITY_AUTH : options.log_facility,
   1472 	    log_stderr || !inetd_flag || debug_flag);
   1473 
   1474 	sensitive_data.have_ssh2_key = 0;
   1475 
   1476 	/*
   1477 	 * If we're not doing an extended test do not silently ignore connection
   1478 	 * test params.
   1479 	 */
   1480 	if (test_flag < 2 && have_connection_info)
   1481 		fatal("Config test connection parameter (-C) provided without "
   1482 		    "test mode (-T)");
   1483 
   1484 	debug("sshd version %s, %s", SSH_VERSION, SSH_OPENSSL_VERSION);
   1485 	if (uname(&utsname) != 0) {
   1486 		memset(&utsname, 0, sizeof(utsname));
   1487 		strlcpy(utsname.sysname, "UNKNOWN", sizeof(utsname.sysname));
   1488 	}
   1489 	debug3("Running on %s %s %s %s", utsname.sysname, utsname.release,
   1490 	    utsname.version, utsname.machine);
   1491 	debug3("Started with: %s", args);
   1492 	free(args);
   1493 
   1494 	/* Fetch our configuration */
   1495 	if ((cfg = sshbuf_new()) == NULL)
   1496 		fatal("sshbuf_new config failed");
   1497 	if (strcasecmp(config_file_name, "none") != 0)
   1498 		load_server_config(config_file_name, cfg);
   1499 
   1500 	parse_server_config(&options, config_file_name, cfg,
   1501 	    &includes, NULL, 0);
   1502 
   1503 	/* Fill in default values for those options not explicitly set. */
   1504 	fill_default_server_options(&options);
   1505 
   1506 	/* Check that options are sensible */
   1507 	if (options.authorized_keys_command_user == NULL &&
   1508 	    (options.authorized_keys_command != NULL &&
   1509 	    strcasecmp(options.authorized_keys_command, "none") != 0))
   1510 		fatal("AuthorizedKeysCommand set without "
   1511 		    "AuthorizedKeysCommandUser");
   1512 	if (options.authorized_principals_command_user == NULL &&
   1513 	    (options.authorized_principals_command != NULL &&
   1514 	    strcasecmp(options.authorized_principals_command, "none") != 0))
   1515 		fatal("AuthorizedPrincipalsCommand set without "
   1516 		    "AuthorizedPrincipalsCommandUser");
   1517 
   1518 	/*
   1519 	 * Check whether there is any path through configured auth methods.
   1520 	 * Unfortunately it is not possible to verify this generally before
   1521 	 * daemonisation in the presence of Match blocks, but this catches
   1522 	 * and warns for trivial misconfigurations that could break login.
   1523 	 */
   1524 	if (options.num_auth_methods != 0) {
   1525 		for (i = 0; i < options.num_auth_methods; i++) {
   1526 			if (auth2_methods_valid(options.auth_methods[i],
   1527 			    1) == 0)
   1528 				break;
   1529 		}
   1530 		if (i >= options.num_auth_methods)
   1531 			fatal("AuthenticationMethods cannot be satisfied by "
   1532 			    "enabled authentication methods");
   1533 	}
   1534 
   1535 	/* Check that there are no remaining arguments. */
   1536 	if (optind < ac) {
   1537 		fprintf(stderr, "Extra argument %s.\n", av[optind]);
   1538 		exit(1);
   1539 	}
   1540 
   1541 	if (do_dump_cfg)
   1542 		print_config(&connection_info);
   1543 
   1544 	/* load host keys */
   1545 	sensitive_data.host_keys = xcalloc(options.num_host_key_files,
   1546 	    sizeof(struct sshkey *));
   1547 	sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
   1548 	    sizeof(struct sshkey *));
   1549 
   1550 	if (options.host_key_agent) {
   1551 		if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
   1552 			setenv(SSH_AUTHSOCKET_ENV_NAME,
   1553 			    options.host_key_agent, 1);
   1554 		if ((r = ssh_get_authentication_socket(NULL)) == 0)
   1555 			have_agent = 1;
   1556 		else
   1557 			error_r(r, "Could not connect to agent \"%s\"",
   1558 			    options.host_key_agent);
   1559 	}
   1560 
   1561 	for (i = 0; i < options.num_host_key_files; i++) {
   1562 		int ll = options.host_key_file_userprovided[i] ?
   1563 		    SYSLOG_LEVEL_ERROR : SYSLOG_LEVEL_DEBUG1;
   1564 
   1565 		if (options.host_key_files[i] == NULL)
   1566 			continue;
   1567 		if ((r = sshkey_load_private(options.host_key_files[i], "",
   1568 		    &key, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR)
   1569 			do_log2_r(r, ll, "Unable to load host key \"%s\"",
   1570 			    options.host_key_files[i]);
   1571 		if (sshkey_is_sk(key) &&
   1572 		    key->sk_flags & SSH_SK_USER_PRESENCE_REQD) {
   1573 			debug("host key %s requires user presence, ignoring",
   1574 			    options.host_key_files[i]);
   1575 			key->sk_flags &= ~SSH_SK_USER_PRESENCE_REQD;
   1576 		}
   1577 		if (r == 0 && key != NULL &&
   1578 		    (r = sshkey_shield_private(key)) != 0) {
   1579 			do_log2_r(r, ll, "Unable to shield host key \"%s\"",
   1580 			    options.host_key_files[i]);
   1581 			sshkey_free(key);
   1582 			key = NULL;
   1583 		}
   1584 		if ((r = sshkey_load_public(options.host_key_files[i],
   1585 		    &pubkey, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR)
   1586 			do_log2_r(r, ll, "Unable to load host key \"%s\"",
   1587 			    options.host_key_files[i]);
   1588 		if (pubkey != NULL && key != NULL) {
   1589 			if (!sshkey_equal(pubkey, key)) {
   1590 				error("Public key for %s does not match "
   1591 				    "private key", options.host_key_files[i]);
   1592 				sshkey_free(pubkey);
   1593 				pubkey = NULL;
   1594 			}
   1595 		}
   1596 		if (pubkey == NULL && key != NULL) {
   1597 			if ((r = sshkey_from_private(key, &pubkey)) != 0)
   1598 				fatal_r(r, "Could not demote key: \"%s\"",
   1599 				    options.host_key_files[i]);
   1600 		}
   1601 		if (pubkey != NULL && (r = sshkey_check_rsa_length(pubkey,
   1602 		    options.required_rsa_size)) != 0) {
   1603 			error_fr(r, "Host key %s", options.host_key_files[i]);
   1604 			sshkey_free(pubkey);
   1605 			sshkey_free(key);
   1606 			continue;
   1607 		}
   1608 		sensitive_data.host_keys[i] = key;
   1609 		sensitive_data.host_pubkeys[i] = pubkey;
   1610 
   1611 		if (key == NULL && pubkey != NULL && have_agent) {
   1612 			debug("will rely on agent for hostkey %s",
   1613 			    options.host_key_files[i]);
   1614 			keytype = pubkey->type;
   1615 		} else if (key != NULL) {
   1616 			keytype = key->type;
   1617 			accumulate_host_timing_secret(cfg, key);
   1618 		} else {
   1619 			do_log2(ll, "Unable to load host key: %s",
   1620 			    options.host_key_files[i]);
   1621 			sensitive_data.host_keys[i] = NULL;
   1622 			sensitive_data.host_pubkeys[i] = NULL;
   1623 			continue;
   1624 		}
   1625 
   1626 		switch (keytype) {
   1627 		case KEY_RSA:
   1628 		case KEY_ECDSA:
   1629 		case KEY_ED25519:
   1630 		case KEY_ECDSA_SK:
   1631 		case KEY_ED25519_SK:
   1632 			if (have_agent || key != NULL)
   1633 				sensitive_data.have_ssh2_key = 1;
   1634 			break;
   1635 		}
   1636 		if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash,
   1637 		    SSH_FP_DEFAULT)) == NULL)
   1638 			fatal("sshkey_fingerprint failed");
   1639 		debug("%s host key #%d: %s %s",
   1640 		    key ? "private" : "agent", i, sshkey_ssh_name(pubkey), fp);
   1641 		free(fp);
   1642 	}
   1643 	accumulate_host_timing_secret(cfg, NULL);
   1644 	if (!sensitive_data.have_ssh2_key) {
   1645 		logit("sshd: no hostkeys available -- exiting.");
   1646 		exit(1);
   1647 	}
   1648 
   1649 	/*
   1650 	 * Load certificates. They are stored in an array at identical
   1651 	 * indices to the public keys that they relate to.
   1652 	 */
   1653 	sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
   1654 	    sizeof(struct sshkey *));
   1655 	for (i = 0; i < options.num_host_key_files; i++)
   1656 		sensitive_data.host_certificates[i] = NULL;
   1657 
   1658 	for (i = 0; i < options.num_host_cert_files; i++) {
   1659 		if (options.host_cert_files[i] == NULL)
   1660 			continue;
   1661 		if ((r = sshkey_load_public(options.host_cert_files[i],
   1662 		    &key, NULL)) != 0) {
   1663 			error_r(r, "Could not load host certificate \"%s\"",
   1664 			    options.host_cert_files[i]);
   1665 			continue;
   1666 		}
   1667 		if (!sshkey_is_cert(key)) {
   1668 			error("Certificate file is not a certificate: %s",
   1669 			    options.host_cert_files[i]);
   1670 			sshkey_free(key);
   1671 			continue;
   1672 		}
   1673 		/* Find matching private key */
   1674 		for (j = 0; j < options.num_host_key_files; j++) {
   1675 			if (sshkey_equal_public(key,
   1676 			    sensitive_data.host_pubkeys[j])) {
   1677 				sensitive_data.host_certificates[j] = key;
   1678 				break;
   1679 			}
   1680 		}
   1681 		if (j >= options.num_host_key_files) {
   1682 			error("No matching private key for certificate: %s",
   1683 			    options.host_cert_files[i]);
   1684 			sshkey_free(key);
   1685 			continue;
   1686 		}
   1687 		sensitive_data.host_certificates[j] = key;
   1688 		debug("host certificate: #%u type %d %s", j, key->type,
   1689 		    sshkey_type(key));
   1690 	}
   1691 
   1692 	/* Ensure privsep directory is correctly configured. */
   1693 	if (getpwnam(SSH_PRIVSEP_USER) == NULL)
   1694 		fatal("Privilege separation user %s does not exist",
   1695 		    SSH_PRIVSEP_USER);
   1696 	endpwent();
   1697 	if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &sb) == -1) ||
   1698 	    (S_ISDIR(sb.st_mode) == 0))
   1699 		fatal("Missing privilege separation directory: %s",
   1700 		    _PATH_PRIVSEP_CHROOT_DIR);
   1701 	if (sb.st_uid != 0 || (sb.st_mode & (S_IWGRP|S_IWOTH)) != 0)
   1702 		fatal("%s must be owned by root and not group or "
   1703 		    "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
   1704 
   1705 	if (test_flag > 1)
   1706 		print_config(&connection_info);
   1707 
   1708 	config = pack_config(cfg);
   1709 	if (sshbuf_len(config) > MONITOR_MAX_CFGLEN) {
   1710 		fatal("Configuration file is too large (have %zu, max %d)",
   1711 		    sshbuf_len(config), MONITOR_MAX_CFGLEN);
   1712 	}
   1713 
   1714 	/* Configuration looks good, so exit if in test mode. */
   1715 	if (test_flag)
   1716 		exit(0);
   1717 
   1718 	/* Prepare arguments for sshd-session */
   1719 	if (rexec_argc < 0)
   1720 		fatal("rexec_argc %d < 0", rexec_argc);
   1721 	rexec_argv = xcalloc(rexec_argc + 3, sizeof(char *));
   1722 	/* Point to the sshd-session binary instead of sshd */
   1723 	rexec_argv[0] = options.sshd_session_path;
   1724 	for (i = 1; i < (u_int)rexec_argc; i++) {
   1725 		debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
   1726 		rexec_argv[i] = saved_argv[i];
   1727 	}
   1728 	rexec_argv[rexec_argc++] = __UNCONST("-R");
   1729 	rexec_argv[rexec_argc] = NULL;
   1730 	if (stat(rexec_argv[0], &sb) != 0 || !(sb.st_mode & (S_IXOTH|S_IXUSR)))
   1731 		fatal("%s does not exist or is not executable", rexec_argv[0]);
   1732 	debug3("using %s for re-exec", rexec_argv[0]);
   1733 
   1734 	/* Ensure that the privsep binary exists now too. */
   1735 	if (stat(options.sshd_auth_path, &sb) != 0 ||
   1736 	    !(sb.st_mode & (S_IXOTH|S_IXUSR))) {
   1737 		fatal("%s does not exist or is not executable",
   1738 		    options.sshd_auth_path);
   1739 	}
   1740 
   1741 	listener_proctitle = prepare_proctitle(ac, av);
   1742 
   1743 	/* Ensure that umask disallows at least group and world write */
   1744 	new_umask = umask(0077) | 0022;
   1745 	(void) umask(new_umask);
   1746 
   1747 	/* Initialize the log (it is reinitialized below in case we forked). */
   1748 	if (debug_flag && !inetd_flag)
   1749 		log_stderr = 1;
   1750 	log_init(__progname, options.log_level,
   1751 	    options.log_facility, log_stderr);
   1752 	for (i = 0; i < options.num_log_verbose; i++)
   1753 		log_verbose_add(options.log_verbose[i]);
   1754 
   1755 	/*
   1756 	 * If not in debugging mode, not started from inetd and not already
   1757 	 * daemonized (eg re-exec via SIGHUP), disconnect from the controlling
   1758 	 * terminal, and fork.  The original process exits.
   1759 	 */
   1760 	already_daemon = daemonized();
   1761 	if (!(debug_flag || inetd_flag || no_daemon_flag || already_daemon)) {
   1762 
   1763 		if (daemon(0, 0) == -1)
   1764 			fatal("daemon() failed: %.200s", strerror(errno));
   1765 
   1766 		disconnect_controlling_tty();
   1767 	}
   1768 	/* Reinitialize the log (because of the fork above). */
   1769 	log_init(__progname, options.log_level, options.log_facility, log_stderr);
   1770 
   1771 	/*
   1772 	 * Chdir to the root directory so that the current disk can be
   1773 	 * unmounted if desired.
   1774 	 */
   1775 	if (chdir("/") == -1)
   1776 		error("chdir(\"/\"): %s", strerror(errno));
   1777 
   1778 	/* ignore SIGPIPE */
   1779 	ssh_signal(SIGPIPE, SIG_IGN);
   1780 
   1781 	/* Get a connection, either from inetd or a listening TCP socket */
   1782 	if (inetd_flag) {
   1783 		/* Send configuration to ancestor sshd-session process */
   1784 		if (socketpair(AF_UNIX, SOCK_STREAM, 0, config_s) == -1)
   1785 			fatal("socketpair: %s", strerror(errno));
   1786 		send_rexec_state(config_s[0]);
   1787 		close(config_s[0]);
   1788 	} else {
   1789 		server_listen();
   1790 
   1791 		ssh_signal(SIGHUP, sighup_handler);
   1792 		ssh_signal(SIGCHLD, main_sigchld_handler);
   1793 		ssh_signal(SIGTERM, sigterm_handler);
   1794 		ssh_signal(SIGQUIT, sigterm_handler);
   1795 		ssh_signal(SIGINFO, siginfo_handler);
   1796 
   1797 		/*
   1798 		 * Write out the pid file after the sigterm handler
   1799 		 * is setup and the listen sockets are bound
   1800 		 */
   1801 		if (options.pid_file != NULL && !debug_flag) {
   1802 			FILE *f = fopen(options.pid_file, "w");
   1803 
   1804 			if (f == NULL) {
   1805 				error("Couldn't create pid file \"%s\": %s",
   1806 				    options.pid_file, strerror(errno));
   1807 			} else {
   1808 				fprintf(f, "%ld\n", (long) getpid());
   1809 				fclose(f);
   1810 			}
   1811 		}
   1812 
   1813 		/* Accept a connection and return in a forked child */
   1814 		server_accept_loop(&sock_in, &sock_out,
   1815 		    &newsock, config_s, log_stderr);
   1816 	}
   1817 
   1818 	/* This is the child processing a new connection. */
   1819 	setproctitle("%s", "[accepted]");
   1820 
   1821 	/*
   1822 	 * Create a new session and process group since the 4.4BSD
   1823 	 * setlogin() affects the entire process group.  We don't
   1824 	 * want the child to be able to affect the parent.
   1825 	 */
   1826 	if (!debug_flag && !inetd_flag && setsid() == -1)
   1827 		error("setsid: %.100s", strerror(errno));
   1828 
   1829 	debug("rexec start in %d out %d newsock %d config_s %d/%d",
   1830 	    sock_in, sock_out, newsock, config_s[0], config_s[1]);
   1831 	if (!inetd_flag) {
   1832 		if (dup2(newsock, STDIN_FILENO) == -1)
   1833 			fatal("dup2 stdin: %s", strerror(errno));
   1834 		if (dup2(STDIN_FILENO, STDOUT_FILENO) == -1)
   1835 			fatal("dup2 stdout: %s", strerror(errno));
   1836 		if (newsock > STDOUT_FILENO)
   1837 			close(newsock);
   1838 	}
   1839 	if (config_s[1] != REEXEC_CONFIG_PASS_FD) {
   1840 		if (dup2(config_s[1], REEXEC_CONFIG_PASS_FD) == -1)
   1841 			fatal("dup2 config_s: %s", strerror(errno));
   1842 		close(config_s[1]);
   1843 	}
   1844 	log_redirect_stderr_to(NULL);
   1845 	closefrom(REEXEC_MIN_FREE_FD);
   1846 
   1847 	ssh_signal(SIGHUP, SIG_IGN); /* avoid reset to SIG_DFL */
   1848 	execv(rexec_argv[0], rexec_argv);
   1849 
   1850 	fatal("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
   1851 }
   1852 
   1853 /* server specific fatal cleanup */
   1854 void
   1855 cleanup_exit(int i)
   1856 {
   1857 	_exit(i);
   1858 }
   1859