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