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