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