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