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