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