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