xref: /openssh-portable/sshd.c (revision e3c03233)
1 /* $OpenBSD: sshd.c,v 1.573 2021/05/07 03:09:38 djm Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
6  * This program is the ssh daemon.  It listens for connections from clients,
7  * and performs authentication, executes use commands or shell, and forwards
8  * information to/from the application to the user client over an encrypted
9  * connection.  This can also handle forwarding of X11, TCP/IP, and
10  * authentication agent connections.
11  *
12  * As far as I am concerned, the code I have written for this software
13  * can be used freely for any purpose.  Any derived versions of this
14  * software must be clearly marked as such, and if the derived work is
15  * incompatible with the protocol description in the RFC file, it must be
16  * called by a name other than "ssh" or "Secure Shell".
17  *
18  * SSH2 implementation:
19  * Privilege Separation:
20  *
21  * Copyright (c) 2000, 2001, 2002 Markus Friedl.  All rights reserved.
22  * Copyright (c) 2002 Niels Provos.  All rights reserved.
23  *
24  * Redistribution and use in source and binary forms, with or without
25  * modification, are permitted provided that the following conditions
26  * are met:
27  * 1. Redistributions of source code must retain the above copyright
28  *    notice, this list of conditions and the following disclaimer.
29  * 2. Redistributions in binary form must reproduce the above copyright
30  *    notice, this list of conditions and the following disclaimer in the
31  *    documentation and/or other materials provided with the distribution.
32  *
33  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
34  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
35  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
36  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
37  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
38  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
39  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
40  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
41  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
42  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43  */
44 
45 #include "includes.h"
46 
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
close_listen_socks(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
close_startup_pipes(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
sighup_handler(int sig)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
sighup_restart(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
sigterm_handler(int sig)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
main_sigchld_handler(int sig)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
grace_alarm_handler(int sig)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
destroy_sensitive_data(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
demote_sensitive_data(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
reseed_prngs(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
privsep_preauth_child(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
privsep_preauth(struct ssh * ssh)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
privsep_postauth(struct ssh * ssh,Authctxt * authctxt)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 
1145 	/* setup fd set for accept */
1146 	fdset = NULL;
1147 	maxfd = 0;
1148 	for (i = 0; i < num_listen_socks; i++)
1149 		if (listen_socks[i] > maxfd)
1150 			maxfd = listen_socks[i];
1151 	/* pipes connected to unauthenticated child sshd processes */
1152 	startup_pipes = xcalloc(options.max_startups, sizeof(int));
1153 	startup_flags = xcalloc(options.max_startups, sizeof(int));
1154 	for (i = 0; i < options.max_startups; i++)
1155 		startup_pipes[i] = -1;
1156 
1157 	/*
1158 	 * Stay listening for connections until the system crashes or
1159 	 * the daemon is killed with a signal.
1160 	 */
1161 	for (;;) {
1162 		if (ostartups != startups) {
1163 			setproctitle("%s [listener] %d of %d-%d startups",
1164 			    listener_proctitle, startups,
1165 			    options.max_startups_begin, options.max_startups);
1166 			ostartups = startups;
1167 		}
1168 		if (received_sighup) {
1169 			if (!lameduck) {
1170 				debug("Received SIGHUP; waiting for children");
1171 				close_listen_socks();
1172 				lameduck = 1;
1173 			}
1174 			if (listening <= 0)
1175 				sighup_restart();
1176 		}
1177 		free(fdset);
1178 		fdset = xcalloc(howmany(maxfd + 1, NFDBITS),
1179 		    sizeof(fd_mask));
1180 
1181 		for (i = 0; i < num_listen_socks; i++)
1182 			FD_SET(listen_socks[i], fdset);
1183 		for (i = 0; i < options.max_startups; i++)
1184 			if (startup_pipes[i] != -1)
1185 				FD_SET(startup_pipes[i], fdset);
1186 
1187 		/* Wait in select until there is a connection. */
1188 		ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1189 		if (ret == -1 && errno != EINTR)
1190 			error("select: %.100s", strerror(errno));
1191 		if (received_sigterm) {
1192 			logit("Received signal %d; terminating.",
1193 			    (int) received_sigterm);
1194 			close_listen_socks();
1195 			if (options.pid_file != NULL)
1196 				unlink(options.pid_file);
1197 			exit(received_sigterm == SIGTERM ? 0 : 255);
1198 		}
1199 		if (ret == -1)
1200 			continue;
1201 
1202 		for (i = 0; i < options.max_startups; i++) {
1203 			if (startup_pipes[i] == -1 ||
1204 			    !FD_ISSET(startup_pipes[i], fdset))
1205 				continue;
1206 			switch (read(startup_pipes[i], &c, sizeof(c))) {
1207 			case -1:
1208 				if (errno == EINTR || errno == EAGAIN)
1209 					continue;
1210 				if (errno != EPIPE) {
1211 					error_f("startup pipe %d (fd=%d): "
1212 					    "read %s", i, startup_pipes[i],
1213 					    strerror(errno));
1214 				}
1215 				/* FALLTHROUGH */
1216 			case 0:
1217 				/* child exited or completed auth */
1218 				close(startup_pipes[i]);
1219 				srclimit_done(startup_pipes[i]);
1220 				startup_pipes[i] = -1;
1221 				startups--;
1222 				if (startup_flags[i])
1223 					listening--;
1224 				break;
1225 			case 1:
1226 				/* child has finished preliminaries */
1227 				if (startup_flags[i]) {
1228 					listening--;
1229 					startup_flags[i] = 0;
1230 				}
1231 				break;
1232 			}
1233 		}
1234 		for (i = 0; i < num_listen_socks; i++) {
1235 			if (!FD_ISSET(listen_socks[i], fdset))
1236 				continue;
1237 			fromlen = sizeof(from);
1238 			*newsock = accept(listen_socks[i],
1239 			    (struct sockaddr *)&from, &fromlen);
1240 			if (*newsock == -1) {
1241 				if (errno != EINTR && errno != EWOULDBLOCK &&
1242 				    errno != ECONNABORTED && errno != EAGAIN)
1243 					error("accept: %.100s",
1244 					    strerror(errno));
1245 				if (errno == EMFILE || errno == ENFILE)
1246 					usleep(100 * 1000);
1247 				continue;
1248 			}
1249 			if (unset_nonblock(*newsock) == -1 ||
1250 			    pipe(startup_p) == -1)
1251 				continue;
1252 			if (drop_connection(*newsock, startups, startup_p[0])) {
1253 				close(*newsock);
1254 				close(startup_p[0]);
1255 				close(startup_p[1]);
1256 				continue;
1257 			}
1258 
1259 			if (rexec_flag && socketpair(AF_UNIX,
1260 			    SOCK_STREAM, 0, config_s) == -1) {
1261 				error("reexec socketpair: %s",
1262 				    strerror(errno));
1263 				close(*newsock);
1264 				close(startup_p[0]);
1265 				close(startup_p[1]);
1266 				continue;
1267 			}
1268 
1269 			for (j = 0; j < options.max_startups; j++)
1270 				if (startup_pipes[j] == -1) {
1271 					startup_pipes[j] = startup_p[0];
1272 					if (maxfd < startup_p[0])
1273 						maxfd = startup_p[0];
1274 					startups++;
1275 					startup_flags[j] = 1;
1276 					break;
1277 				}
1278 
1279 			/*
1280 			 * Got connection.  Fork a child to handle it, unless
1281 			 * we are in debugging mode.
1282 			 */
1283 			if (debug_flag) {
1284 				/*
1285 				 * In debugging mode.  Close the listening
1286 				 * socket, and start processing the
1287 				 * connection without forking.
1288 				 */
1289 				debug("Server will not fork when running in debugging mode.");
1290 				close_listen_socks();
1291 				*sock_in = *newsock;
1292 				*sock_out = *newsock;
1293 				close(startup_p[0]);
1294 				close(startup_p[1]);
1295 				startup_pipe = -1;
1296 				pid = getpid();
1297 				if (rexec_flag) {
1298 					send_rexec_state(config_s[0], cfg);
1299 					close(config_s[0]);
1300 				}
1301 				return;
1302 			}
1303 
1304 			/*
1305 			 * Normal production daemon.  Fork, and have
1306 			 * the child process the connection. The
1307 			 * parent continues listening.
1308 			 */
1309 			platform_pre_fork();
1310 			listening++;
1311 			if ((pid = fork()) == 0) {
1312 				/*
1313 				 * Child.  Close the listening and
1314 				 * max_startup sockets.  Start using
1315 				 * the accepted socket. Reinitialize
1316 				 * logging (since our pid has changed).
1317 				 * We return from this function to handle
1318 				 * the connection.
1319 				 */
1320 				platform_post_fork_child();
1321 				startup_pipe = startup_p[1];
1322 				close_startup_pipes();
1323 				close_listen_socks();
1324 				*sock_in = *newsock;
1325 				*sock_out = *newsock;
1326 				log_init(__progname,
1327 				    options.log_level,
1328 				    options.log_facility,
1329 				    log_stderr);
1330 				if (rexec_flag)
1331 					close(config_s[0]);
1332 				else {
1333 					/*
1334 					 * Signal parent that the preliminaries
1335 					 * for this child are complete. For the
1336 					 * re-exec case, this happens after the
1337 					 * child has received the rexec state
1338 					 * from the server.
1339 					 */
1340 					(void)atomicio(vwrite, startup_pipe,
1341 					    "\0", 1);
1342 				}
1343 				return;
1344 			}
1345 
1346 			/* Parent.  Stay in the loop. */
1347 			platform_post_fork_parent(pid);
1348 			if (pid == -1)
1349 				error("fork: %.100s", strerror(errno));
1350 			else
1351 				debug("Forked child %ld.", (long)pid);
1352 
1353 			close(startup_p[1]);
1354 
1355 			if (rexec_flag) {
1356 				close(config_s[1]);
1357 				send_rexec_state(config_s[0], cfg);
1358 				close(config_s[0]);
1359 			}
1360 			close(*newsock);
1361 
1362 			/*
1363 			 * Ensure that our random state differs
1364 			 * from that of the child
1365 			 */
1366 			arc4random_stir();
1367 			arc4random_buf(rnd, sizeof(rnd));
1368 #ifdef WITH_OPENSSL
1369 			RAND_seed(rnd, sizeof(rnd));
1370 			if ((RAND_bytes((u_char *)rnd, 1)) != 1)
1371 				fatal("%s: RAND_bytes failed", __func__);
1372 #endif
1373 			explicit_bzero(rnd, sizeof(rnd));
1374 		}
1375 	}
1376 }
1377 
1378 /*
1379  * If IP options are supported, make sure there are none (log and
1380  * return an error if any are found).  Basically we are worried about
1381  * source routing; it can be used to pretend you are somebody
1382  * (ip-address) you are not. That itself may be "almost acceptable"
1383  * under certain circumstances, but rhosts authentication is useless
1384  * if source routing is accepted. Notice also that if we just dropped
1385  * source routing here, the other side could use IP spoofing to do
1386  * rest of the interaction and could still bypass security.  So we
1387  * exit here if we detect any IP options.
1388  */
1389 static void
1390 check_ip_options(struct ssh *ssh)
1391 {
1392 #ifdef IP_OPTIONS
1393 	int sock_in = ssh_packet_get_connection_in(ssh);
1394 	struct sockaddr_storage from;
1395 	u_char opts[200];
1396 	socklen_t i, option_size = sizeof(opts), fromlen = sizeof(from);
1397 	char text[sizeof(opts) * 3 + 1];
1398 
1399 	memset(&from, 0, sizeof(from));
1400 	if (getpeername(sock_in, (struct sockaddr *)&from,
1401 	    &fromlen) == -1)
1402 		return;
1403 	if (from.ss_family != AF_INET)
1404 		return;
1405 	/* XXX IPv6 options? */
1406 
1407 	if (getsockopt(sock_in, IPPROTO_IP, IP_OPTIONS, opts,
1408 	    &option_size) >= 0 && option_size != 0) {
1409 		text[0] = '\0';
1410 		for (i = 0; i < option_size; i++)
1411 			snprintf(text + i*3, sizeof(text) - i*3,
1412 			    " %2.2x", opts[i]);
1413 		fatal("Connection from %.100s port %d with IP opts: %.800s",
1414 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), text);
1415 	}
1416 	return;
1417 #endif /* IP_OPTIONS */
1418 }
1419 
1420 /* Set the routing domain for this process */
1421 static void
1422 set_process_rdomain(struct ssh *ssh, const char *name)
1423 {
1424 #if defined(HAVE_SYS_SET_PROCESS_RDOMAIN)
1425 	if (name == NULL)
1426 		return; /* default */
1427 
1428 	if (strcmp(name, "%D") == 0) {
1429 		/* "expands" to routing domain of connection */
1430 		if ((name = ssh_packet_rdomain_in(ssh)) == NULL)
1431 			return;
1432 	}
1433 	/* NB. We don't pass 'ssh' to sys_set_process_rdomain() */
1434 	return sys_set_process_rdomain(name);
1435 #elif defined(__OpenBSD__)
1436 	int rtable, ortable = getrtable();
1437 	const char *errstr;
1438 
1439 	if (name == NULL)
1440 		return; /* default */
1441 
1442 	if (strcmp(name, "%D") == 0) {
1443 		/* "expands" to routing domain of connection */
1444 		if ((name = ssh_packet_rdomain_in(ssh)) == NULL)
1445 			return;
1446 	}
1447 
1448 	rtable = (int)strtonum(name, 0, 255, &errstr);
1449 	if (errstr != NULL) /* Shouldn't happen */
1450 		fatal("Invalid routing domain \"%s\": %s", name, errstr);
1451 	if (rtable != ortable && setrtable(rtable) != 0)
1452 		fatal("Unable to set routing domain %d: %s",
1453 		    rtable, strerror(errno));
1454 	debug_f("set routing domain %d (was %d)", rtable, ortable);
1455 #else /* defined(__OpenBSD__) */
1456 	fatal("Unable to set routing domain: not supported in this platform");
1457 #endif
1458 }
1459 
1460 static void
1461 accumulate_host_timing_secret(struct sshbuf *server_cfg,
1462     struct sshkey *key)
1463 {
1464 	static struct ssh_digest_ctx *ctx;
1465 	u_char *hash;
1466 	size_t len;
1467 	struct sshbuf *buf;
1468 	int r;
1469 
1470 	if (ctx == NULL && (ctx = ssh_digest_start(SSH_DIGEST_SHA512)) == NULL)
1471 		fatal_f("ssh_digest_start");
1472 	if (key == NULL) { /* finalize */
1473 		/* add server config in case we are using agent for host keys */
1474 		if (ssh_digest_update(ctx, sshbuf_ptr(server_cfg),
1475 		    sshbuf_len(server_cfg)) != 0)
1476 			fatal_f("ssh_digest_update");
1477 		len = ssh_digest_bytes(SSH_DIGEST_SHA512);
1478 		hash = xmalloc(len);
1479 		if (ssh_digest_final(ctx, hash, len) != 0)
1480 			fatal_f("ssh_digest_final");
1481 		options.timing_secret = PEEK_U64(hash);
1482 		freezero(hash, len);
1483 		ssh_digest_free(ctx);
1484 		ctx = NULL;
1485 		return;
1486 	}
1487 	if ((buf = sshbuf_new()) == NULL)
1488 		fatal_f("could not allocate buffer");
1489 	if ((r = sshkey_private_serialize(key, buf)) != 0)
1490 		fatal_fr(r, "decode key");
1491 	if (ssh_digest_update(ctx, sshbuf_ptr(buf), sshbuf_len(buf)) != 0)
1492 		fatal_f("ssh_digest_update");
1493 	sshbuf_reset(buf);
1494 	sshbuf_free(buf);
1495 }
1496 
1497 static char *
1498 prepare_proctitle(int ac, char **av)
1499 {
1500 	char *ret = NULL;
1501 	int i;
1502 
1503 	for (i = 0; i < ac; i++)
1504 		xextendf(&ret, " ", "%s", av[i]);
1505 	return ret;
1506 }
1507 
1508 /*
1509  * Main program for the daemon.
1510  */
1511 int
1512 main(int ac, char **av)
1513 {
1514 	struct ssh *ssh = NULL;
1515 	extern char *optarg;
1516 	extern int optind;
1517 	int r, opt, on = 1, already_daemon, remote_port;
1518 	int sock_in = -1, sock_out = -1, newsock = -1;
1519 	const char *remote_ip, *rdomain;
1520 	char *fp, *line, *laddr, *logfile = NULL;
1521 	int config_s[2] = { -1 , -1 };
1522 	u_int i, j;
1523 	u_int64_t ibytes, obytes;
1524 	mode_t new_umask;
1525 	struct sshkey *key;
1526 	struct sshkey *pubkey;
1527 	int keytype;
1528 	Authctxt *authctxt;
1529 	struct connection_info *connection_info = NULL;
1530 
1531 #ifdef HAVE_SECUREWARE
1532 	(void)set_auth_parameters(ac, av);
1533 #endif
1534 	__progname = ssh_get_progname(av[0]);
1535 
1536 	/* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1537 	saved_argc = ac;
1538 	rexec_argc = ac;
1539 	saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1540 	for (i = 0; (int)i < ac; i++)
1541 		saved_argv[i] = xstrdup(av[i]);
1542 	saved_argv[i] = NULL;
1543 
1544 #ifndef HAVE_SETPROCTITLE
1545 	/* Prepare for later setproctitle emulation */
1546 	compat_init_setproctitle(ac, av);
1547 	av = saved_argv;
1548 #endif
1549 
1550 	if (geteuid() == 0 && setgroups(0, NULL) == -1)
1551 		debug("setgroups(): %.200s", strerror(errno));
1552 
1553 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1554 	sanitise_stdfd();
1555 
1556 	seed_rng();
1557 
1558 	/* Initialize configuration options to their default values. */
1559 	initialize_server_options(&options);
1560 
1561 	/* Parse command-line arguments. */
1562 	while ((opt = getopt(ac, av,
1563 	    "C:E:b:c:f:g:h:k:o:p:u:46DQRTdeiqrt")) != -1) {
1564 		switch (opt) {
1565 		case '4':
1566 			options.address_family = AF_INET;
1567 			break;
1568 		case '6':
1569 			options.address_family = AF_INET6;
1570 			break;
1571 		case 'f':
1572 			config_file_name = optarg;
1573 			break;
1574 		case 'c':
1575 			servconf_add_hostcert("[command-line]", 0,
1576 			    &options, optarg);
1577 			break;
1578 		case 'd':
1579 			if (debug_flag == 0) {
1580 				debug_flag = 1;
1581 				options.log_level = SYSLOG_LEVEL_DEBUG1;
1582 			} else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1583 				options.log_level++;
1584 			break;
1585 		case 'D':
1586 			no_daemon_flag = 1;
1587 			break;
1588 		case 'E':
1589 			logfile = optarg;
1590 			/* FALLTHROUGH */
1591 		case 'e':
1592 			log_stderr = 1;
1593 			break;
1594 		case 'i':
1595 			inetd_flag = 1;
1596 			break;
1597 		case 'r':
1598 			rexec_flag = 0;
1599 			break;
1600 		case 'R':
1601 			rexeced_flag = 1;
1602 			inetd_flag = 1;
1603 			break;
1604 		case 'Q':
1605 			/* ignored */
1606 			break;
1607 		case 'q':
1608 			options.log_level = SYSLOG_LEVEL_QUIET;
1609 			break;
1610 		case 'b':
1611 			/* protocol 1, ignored */
1612 			break;
1613 		case 'p':
1614 			options.ports_from_cmdline = 1;
1615 			if (options.num_ports >= MAX_PORTS) {
1616 				fprintf(stderr, "too many ports.\n");
1617 				exit(1);
1618 			}
1619 			options.ports[options.num_ports++] = a2port(optarg);
1620 			if (options.ports[options.num_ports-1] <= 0) {
1621 				fprintf(stderr, "Bad port number.\n");
1622 				exit(1);
1623 			}
1624 			break;
1625 		case 'g':
1626 			if ((options.login_grace_time = convtime(optarg)) == -1) {
1627 				fprintf(stderr, "Invalid login grace time.\n");
1628 				exit(1);
1629 			}
1630 			break;
1631 		case 'k':
1632 			/* protocol 1, ignored */
1633 			break;
1634 		case 'h':
1635 			servconf_add_hostkey("[command-line]", 0,
1636 			    &options, optarg, 1);
1637 			break;
1638 		case 't':
1639 			test_flag = 1;
1640 			break;
1641 		case 'T':
1642 			test_flag = 2;
1643 			break;
1644 		case 'C':
1645 			connection_info = get_connection_info(ssh, 0, 0);
1646 			if (parse_server_match_testspec(connection_info,
1647 			    optarg) == -1)
1648 				exit(1);
1649 			break;
1650 		case 'u':
1651 			utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
1652 			if (utmp_len > HOST_NAME_MAX+1) {
1653 				fprintf(stderr, "Invalid utmp length.\n");
1654 				exit(1);
1655 			}
1656 			break;
1657 		case 'o':
1658 			line = xstrdup(optarg);
1659 			if (process_server_config_line(&options, line,
1660 			    "command-line", 0, NULL, NULL, &includes) != 0)
1661 				exit(1);
1662 			free(line);
1663 			break;
1664 		case '?':
1665 		default:
1666 			usage();
1667 			break;
1668 		}
1669 	}
1670 	if (rexeced_flag || inetd_flag)
1671 		rexec_flag = 0;
1672 	if (!test_flag && rexec_flag && !path_absolute(av[0]))
1673 		fatal("sshd re-exec requires execution with an absolute path");
1674 	if (rexeced_flag)
1675 		closefrom(REEXEC_MIN_FREE_FD);
1676 	else
1677 		closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1678 
1679 	/* If requested, redirect the logs to the specified logfile. */
1680 	if (logfile != NULL)
1681 		log_redirect_stderr_to(logfile);
1682 	/*
1683 	 * Force logging to stderr until we have loaded the private host
1684 	 * key (unless started from inetd)
1685 	 */
1686 	log_init(__progname,
1687 	    options.log_level == SYSLOG_LEVEL_NOT_SET ?
1688 	    SYSLOG_LEVEL_INFO : options.log_level,
1689 	    options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1690 	    SYSLOG_FACILITY_AUTH : options.log_facility,
1691 	    log_stderr || !inetd_flag || debug_flag);
1692 
1693 	/*
1694 	 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1695 	 * root's environment
1696 	 */
1697 	if (getenv("KRB5CCNAME") != NULL)
1698 		(void) unsetenv("KRB5CCNAME");
1699 
1700 	sensitive_data.have_ssh2_key = 0;
1701 
1702 	/*
1703 	 * If we're not doing an extended test do not silently ignore connection
1704 	 * test params.
1705 	 */
1706 	if (test_flag < 2 && connection_info != NULL)
1707 		fatal("Config test connection parameter (-C) provided without "
1708 		    "test mode (-T)");
1709 
1710 	/* Fetch our configuration */
1711 	if ((cfg = sshbuf_new()) == NULL)
1712 		fatal_f("sshbuf_new failed");
1713 	if (rexeced_flag) {
1714 		setproctitle("%s", "[rexeced]");
1715 		recv_rexec_state(REEXEC_CONFIG_PASS_FD, cfg);
1716 		if (!debug_flag) {
1717 			startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
1718 			close(REEXEC_STARTUP_PIPE_FD);
1719 			/*
1720 			 * Signal parent that this child is at a point where
1721 			 * they can go away if they have a SIGHUP pending.
1722 			 */
1723 			(void)atomicio(vwrite, startup_pipe, "\0", 1);
1724 		}
1725 	} else if (strcasecmp(config_file_name, "none") != 0)
1726 		load_server_config(config_file_name, cfg);
1727 
1728 	parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1729 	    cfg, &includes, NULL);
1730 
1731 #ifdef WITH_OPENSSL
1732 	if (options.moduli_file != NULL)
1733 		dh_set_moduli_file(options.moduli_file);
1734 #endif
1735 
1736 	/* Fill in default values for those options not explicitly set. */
1737 	fill_default_server_options(&options);
1738 
1739 	/* challenge-response is implemented via keyboard interactive */
1740 	if (options.challenge_response_authentication)
1741 		options.kbd_interactive_authentication = 1;
1742 
1743 	/* Check that options are sensible */
1744 	if (options.authorized_keys_command_user == NULL &&
1745 	    (options.authorized_keys_command != NULL &&
1746 	    strcasecmp(options.authorized_keys_command, "none") != 0))
1747 		fatal("AuthorizedKeysCommand set without "
1748 		    "AuthorizedKeysCommandUser");
1749 	if (options.authorized_principals_command_user == NULL &&
1750 	    (options.authorized_principals_command != NULL &&
1751 	    strcasecmp(options.authorized_principals_command, "none") != 0))
1752 		fatal("AuthorizedPrincipalsCommand set without "
1753 		    "AuthorizedPrincipalsCommandUser");
1754 
1755 	/*
1756 	 * Check whether there is any path through configured auth methods.
1757 	 * Unfortunately it is not possible to verify this generally before
1758 	 * daemonisation in the presence of Match block, but this catches
1759 	 * and warns for trivial misconfigurations that could break login.
1760 	 */
1761 	if (options.num_auth_methods != 0) {
1762 		for (i = 0; i < options.num_auth_methods; i++) {
1763 			if (auth2_methods_valid(options.auth_methods[i],
1764 			    1) == 0)
1765 				break;
1766 		}
1767 		if (i >= options.num_auth_methods)
1768 			fatal("AuthenticationMethods cannot be satisfied by "
1769 			    "enabled authentication methods");
1770 	}
1771 
1772 	/* Check that there are no remaining arguments. */
1773 	if (optind < ac) {
1774 		fprintf(stderr, "Extra argument %s.\n", av[optind]);
1775 		exit(1);
1776 	}
1777 
1778 	debug("sshd version %s, %s", SSH_VERSION, SSH_OPENSSL_VERSION);
1779 
1780 	/* Store privilege separation user for later use if required. */
1781 	privsep_chroot = use_privsep && (getuid() == 0 || geteuid() == 0);
1782 	if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1783 		if (privsep_chroot || options.kerberos_authentication)
1784 			fatal("Privilege separation user %s does not exist",
1785 			    SSH_PRIVSEP_USER);
1786 	} else {
1787 		privsep_pw = pwcopy(privsep_pw);
1788 		freezero(privsep_pw->pw_passwd, strlen(privsep_pw->pw_passwd));
1789 		privsep_pw->pw_passwd = xstrdup("*");
1790 	}
1791 	endpwent();
1792 
1793 	/* load host keys */
1794 	sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1795 	    sizeof(struct sshkey *));
1796 	sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
1797 	    sizeof(struct sshkey *));
1798 
1799 	if (options.host_key_agent) {
1800 		if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
1801 			setenv(SSH_AUTHSOCKET_ENV_NAME,
1802 			    options.host_key_agent, 1);
1803 		if ((r = ssh_get_authentication_socket(NULL)) == 0)
1804 			have_agent = 1;
1805 		else
1806 			error_r(r, "Could not connect to agent \"%s\"",
1807 			    options.host_key_agent);
1808 	}
1809 
1810 	for (i = 0; i < options.num_host_key_files; i++) {
1811 		int ll = options.host_key_file_userprovided[i] ?
1812 		    SYSLOG_LEVEL_ERROR : SYSLOG_LEVEL_DEBUG1;
1813 
1814 		if (options.host_key_files[i] == NULL)
1815 			continue;
1816 		if ((r = sshkey_load_private(options.host_key_files[i], "",
1817 		    &key, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR)
1818 			do_log2_r(r, ll, "Unable to load host key \"%s\"",
1819 			    options.host_key_files[i]);
1820 		if (sshkey_is_sk(key) &&
1821 		    key->sk_flags & SSH_SK_USER_PRESENCE_REQD) {
1822 			debug("host key %s requires user presence, ignoring",
1823 			    options.host_key_files[i]);
1824 			key->sk_flags &= ~SSH_SK_USER_PRESENCE_REQD;
1825 		}
1826 		if (r == 0 && key != NULL &&
1827 		    (r = sshkey_shield_private(key)) != 0) {
1828 			do_log2_r(r, ll, "Unable to shield host key \"%s\"",
1829 			    options.host_key_files[i]);
1830 			sshkey_free(key);
1831 			key = NULL;
1832 		}
1833 		if ((r = sshkey_load_public(options.host_key_files[i],
1834 		    &pubkey, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR)
1835 			do_log2_r(r, ll, "Unable to load host key \"%s\"",
1836 			    options.host_key_files[i]);
1837 		if (pubkey != NULL && key != NULL) {
1838 			if (!sshkey_equal(pubkey, key)) {
1839 				error("Public key for %s does not match "
1840 				    "private key", options.host_key_files[i]);
1841 				sshkey_free(pubkey);
1842 				pubkey = NULL;
1843 			}
1844 		}
1845 		if (pubkey == NULL && key != NULL) {
1846 			if ((r = sshkey_from_private(key, &pubkey)) != 0)
1847 				fatal_r(r, "Could not demote key: \"%s\"",
1848 				    options.host_key_files[i]);
1849 		}
1850 		sensitive_data.host_keys[i] = key;
1851 		sensitive_data.host_pubkeys[i] = pubkey;
1852 
1853 		if (key == NULL && pubkey != NULL && have_agent) {
1854 			debug("will rely on agent for hostkey %s",
1855 			    options.host_key_files[i]);
1856 			keytype = pubkey->type;
1857 		} else if (key != NULL) {
1858 			keytype = key->type;
1859 			accumulate_host_timing_secret(cfg, key);
1860 		} else {
1861 			do_log2(ll, "Unable to load host key: %s",
1862 			    options.host_key_files[i]);
1863 			sensitive_data.host_keys[i] = NULL;
1864 			sensitive_data.host_pubkeys[i] = NULL;
1865 			continue;
1866 		}
1867 
1868 		switch (keytype) {
1869 		case KEY_RSA:
1870 		case KEY_DSA:
1871 		case KEY_ECDSA:
1872 		case KEY_ED25519:
1873 		case KEY_ECDSA_SK:
1874 		case KEY_ED25519_SK:
1875 		case KEY_XMSS:
1876 			if (have_agent || key != NULL)
1877 				sensitive_data.have_ssh2_key = 1;
1878 			break;
1879 		}
1880 		if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash,
1881 		    SSH_FP_DEFAULT)) == NULL)
1882 			fatal("sshkey_fingerprint failed");
1883 		debug("%s host key #%d: %s %s",
1884 		    key ? "private" : "agent", i, sshkey_ssh_name(pubkey), fp);
1885 		free(fp);
1886 	}
1887 	accumulate_host_timing_secret(cfg, NULL);
1888 	if (!sensitive_data.have_ssh2_key) {
1889 		logit("sshd: no hostkeys available -- exiting.");
1890 		exit(1);
1891 	}
1892 
1893 	/*
1894 	 * Load certificates. They are stored in an array at identical
1895 	 * indices to the public keys that they relate to.
1896 	 */
1897 	sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
1898 	    sizeof(struct sshkey *));
1899 	for (i = 0; i < options.num_host_key_files; i++)
1900 		sensitive_data.host_certificates[i] = NULL;
1901 
1902 	for (i = 0; i < options.num_host_cert_files; i++) {
1903 		if (options.host_cert_files[i] == NULL)
1904 			continue;
1905 		if ((r = sshkey_load_public(options.host_cert_files[i],
1906 		    &key, NULL)) != 0) {
1907 			error_r(r, "Could not load host certificate \"%s\"",
1908 			    options.host_cert_files[i]);
1909 			continue;
1910 		}
1911 		if (!sshkey_is_cert(key)) {
1912 			error("Certificate file is not a certificate: %s",
1913 			    options.host_cert_files[i]);
1914 			sshkey_free(key);
1915 			continue;
1916 		}
1917 		/* Find matching private key */
1918 		for (j = 0; j < options.num_host_key_files; j++) {
1919 			if (sshkey_equal_public(key,
1920 			    sensitive_data.host_keys[j])) {
1921 				sensitive_data.host_certificates[j] = key;
1922 				break;
1923 			}
1924 		}
1925 		if (j >= options.num_host_key_files) {
1926 			error("No matching private key for certificate: %s",
1927 			    options.host_cert_files[i]);
1928 			sshkey_free(key);
1929 			continue;
1930 		}
1931 		sensitive_data.host_certificates[j] = key;
1932 		debug("host certificate: #%u type %d %s", j, key->type,
1933 		    sshkey_type(key));
1934 	}
1935 
1936 	if (privsep_chroot) {
1937 		struct stat st;
1938 
1939 		if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1940 		    (S_ISDIR(st.st_mode) == 0))
1941 			fatal("Missing privilege separation directory: %s",
1942 			    _PATH_PRIVSEP_CHROOT_DIR);
1943 
1944 #ifdef HAVE_CYGWIN
1945 		if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1946 		    (st.st_uid != getuid () ||
1947 		    (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1948 #else
1949 		if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1950 #endif
1951 			fatal("%s must be owned by root and not group or "
1952 			    "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1953 	}
1954 
1955 	if (test_flag > 1) {
1956 		/*
1957 		 * If no connection info was provided by -C then use
1958 		 * use a blank one that will cause no predicate to match.
1959 		 */
1960 		if (connection_info == NULL)
1961 			connection_info = get_connection_info(ssh, 0, 0);
1962 		connection_info->test = 1;
1963 		parse_server_match_config(&options, &includes, connection_info);
1964 		dump_config(&options);
1965 	}
1966 
1967 	/* Configuration looks good, so exit if in test mode. */
1968 	if (test_flag)
1969 		exit(0);
1970 
1971 	/*
1972 	 * Clear out any supplemental groups we may have inherited.  This
1973 	 * prevents inadvertent creation of files with bad modes (in the
1974 	 * portable version at least, it's certainly possible for PAM
1975 	 * to create a file, and we can't control the code in every
1976 	 * module which might be used).
1977 	 */
1978 	if (setgroups(0, NULL) < 0)
1979 		debug("setgroups() failed: %.200s", strerror(errno));
1980 
1981 	if (rexec_flag) {
1982 		if (rexec_argc < 0)
1983 			fatal("rexec_argc %d < 0", rexec_argc);
1984 		rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1985 		for (i = 0; i < (u_int)rexec_argc; i++) {
1986 			debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1987 			rexec_argv[i] = saved_argv[i];
1988 		}
1989 		rexec_argv[rexec_argc] = "-R";
1990 		rexec_argv[rexec_argc + 1] = NULL;
1991 	}
1992 	listener_proctitle = prepare_proctitle(ac, av);
1993 
1994 	/* Ensure that umask disallows at least group and world write */
1995 	new_umask = umask(0077) | 0022;
1996 	(void) umask(new_umask);
1997 
1998 	/* Initialize the log (it is reinitialized below in case we forked). */
1999 	if (debug_flag && (!inetd_flag || rexeced_flag))
2000 		log_stderr = 1;
2001 	log_init(__progname, options.log_level,
2002 	    options.log_facility, log_stderr);
2003 	for (i = 0; i < options.num_log_verbose; i++)
2004 		log_verbose_add(options.log_verbose[i]);
2005 
2006 	/*
2007 	 * If not in debugging mode, not started from inetd and not already
2008 	 * daemonized (eg re-exec via SIGHUP), disconnect from the controlling
2009 	 * terminal, and fork.  The original process exits.
2010 	 */
2011 	already_daemon = daemonized();
2012 	if (!(debug_flag || inetd_flag || no_daemon_flag || already_daemon)) {
2013 
2014 		if (daemon(0, 0) == -1)
2015 			fatal("daemon() failed: %.200s", strerror(errno));
2016 
2017 		disconnect_controlling_tty();
2018 	}
2019 	/* Reinitialize the log (because of the fork above). */
2020 	log_init(__progname, options.log_level, options.log_facility, log_stderr);
2021 
2022 	/*
2023 	 * Chdir to the root directory so that the current disk can be
2024 	 * unmounted if desired.
2025 	 */
2026 	if (chdir("/") == -1)
2027 		error("chdir(\"/\"): %s", strerror(errno));
2028 
2029 	/* ignore SIGPIPE */
2030 	ssh_signal(SIGPIPE, SIG_IGN);
2031 
2032 	/* Get a connection, either from inetd or a listening TCP socket */
2033 	if (inetd_flag) {
2034 		server_accept_inetd(&sock_in, &sock_out);
2035 	} else {
2036 		platform_pre_listen();
2037 		server_listen();
2038 
2039 		ssh_signal(SIGHUP, sighup_handler);
2040 		ssh_signal(SIGCHLD, main_sigchld_handler);
2041 		ssh_signal(SIGTERM, sigterm_handler);
2042 		ssh_signal(SIGQUIT, sigterm_handler);
2043 
2044 		/*
2045 		 * Write out the pid file after the sigterm handler
2046 		 * is setup and the listen sockets are bound
2047 		 */
2048 		if (options.pid_file != NULL && !debug_flag) {
2049 			FILE *f = fopen(options.pid_file, "w");
2050 
2051 			if (f == NULL) {
2052 				error("Couldn't create pid file \"%s\": %s",
2053 				    options.pid_file, strerror(errno));
2054 			} else {
2055 				fprintf(f, "%ld\n", (long) getpid());
2056 				fclose(f);
2057 			}
2058 		}
2059 
2060 		/* Accept a connection and return in a forked child */
2061 		server_accept_loop(&sock_in, &sock_out,
2062 		    &newsock, config_s);
2063 	}
2064 
2065 	/* This is the child processing a new connection. */
2066 	setproctitle("%s", "[accepted]");
2067 
2068 	/*
2069 	 * Create a new session and process group since the 4.4BSD
2070 	 * setlogin() affects the entire process group.  We don't
2071 	 * want the child to be able to affect the parent.
2072 	 */
2073 #if !defined(SSHD_ACQUIRES_CTTY)
2074 	/*
2075 	 * If setsid is called, on some platforms sshd will later acquire a
2076 	 * controlling terminal which will result in "could not set
2077 	 * controlling tty" errors.
2078 	 */
2079 	if (!debug_flag && !inetd_flag && setsid() == -1)
2080 		error("setsid: %.100s", strerror(errno));
2081 #endif
2082 
2083 	if (rexec_flag) {
2084 		debug("rexec start in %d out %d newsock %d pipe %d sock %d",
2085 		    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
2086 		dup2(newsock, STDIN_FILENO);
2087 		dup2(STDIN_FILENO, STDOUT_FILENO);
2088 		if (startup_pipe == -1)
2089 			close(REEXEC_STARTUP_PIPE_FD);
2090 		else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) {
2091 			dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
2092 			close(startup_pipe);
2093 			startup_pipe = REEXEC_STARTUP_PIPE_FD;
2094 		}
2095 
2096 		dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
2097 		close(config_s[1]);
2098 
2099 		ssh_signal(SIGHUP, SIG_IGN); /* avoid reset to SIG_DFL */
2100 		execv(rexec_argv[0], rexec_argv);
2101 
2102 		/* Reexec has failed, fall back and continue */
2103 		error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
2104 		recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
2105 		log_init(__progname, options.log_level,
2106 		    options.log_facility, log_stderr);
2107 
2108 		/* Clean up fds */
2109 		close(REEXEC_CONFIG_PASS_FD);
2110 		newsock = sock_out = sock_in = dup(STDIN_FILENO);
2111 		if (stdfd_devnull(1, 1, 0) == -1)
2112 			error_f("stdfd_devnull failed");
2113 		debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
2114 		    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
2115 	}
2116 
2117 	/* Executed child processes don't need these. */
2118 	fcntl(sock_out, F_SETFD, FD_CLOEXEC);
2119 	fcntl(sock_in, F_SETFD, FD_CLOEXEC);
2120 
2121 	/* We will not restart on SIGHUP since it no longer makes sense. */
2122 	ssh_signal(SIGALRM, SIG_DFL);
2123 	ssh_signal(SIGHUP, SIG_DFL);
2124 	ssh_signal(SIGTERM, SIG_DFL);
2125 	ssh_signal(SIGQUIT, SIG_DFL);
2126 	ssh_signal(SIGCHLD, SIG_DFL);
2127 	ssh_signal(SIGINT, SIG_DFL);
2128 
2129 	/*
2130 	 * Register our connection.  This turns encryption off because we do
2131 	 * not have a key.
2132 	 */
2133 	if ((ssh = ssh_packet_set_connection(NULL, sock_in, sock_out)) == NULL)
2134 		fatal("Unable to create connection");
2135 	the_active_state = ssh;
2136 	ssh_packet_set_server(ssh);
2137 
2138 	check_ip_options(ssh);
2139 
2140 	/* Prepare the channels layer */
2141 	channel_init_channels(ssh);
2142 	channel_set_af(ssh, options.address_family);
2143 	process_permitopen(ssh, &options);
2144 
2145 	/* Set SO_KEEPALIVE if requested. */
2146 	if (options.tcp_keep_alive && ssh_packet_connection_is_on_socket(ssh) &&
2147 	    setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) == -1)
2148 		error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
2149 
2150 	if ((remote_port = ssh_remote_port(ssh)) < 0) {
2151 		debug("ssh_remote_port failed");
2152 		cleanup_exit(255);
2153 	}
2154 
2155 	if (options.routing_domain != NULL)
2156 		set_process_rdomain(ssh, options.routing_domain);
2157 
2158 	/*
2159 	 * The rest of the code depends on the fact that
2160 	 * ssh_remote_ipaddr() caches the remote ip, even if
2161 	 * the socket goes away.
2162 	 */
2163 	remote_ip = ssh_remote_ipaddr(ssh);
2164 
2165 #ifdef SSH_AUDIT_EVENTS
2166 	audit_connection_from(remote_ip, remote_port);
2167 #endif
2168 
2169 	rdomain = ssh_packet_rdomain_in(ssh);
2170 
2171 	/* Log the connection. */
2172 	laddr = get_local_ipaddr(sock_in);
2173 	verbose("Connection from %s port %d on %s port %d%s%s%s",
2174 	    remote_ip, remote_port, laddr,  ssh_local_port(ssh),
2175 	    rdomain == NULL ? "" : " rdomain \"",
2176 	    rdomain == NULL ? "" : rdomain,
2177 	    rdomain == NULL ? "" : "\"");
2178 	free(laddr);
2179 
2180 	/*
2181 	 * We don't want to listen forever unless the other side
2182 	 * successfully authenticates itself.  So we set up an alarm which is
2183 	 * cleared after successful authentication.  A limit of zero
2184 	 * indicates no limit. Note that we don't set the alarm in debugging
2185 	 * mode; it is just annoying to have the server exit just when you
2186 	 * are about to discover the bug.
2187 	 */
2188 	ssh_signal(SIGALRM, grace_alarm_handler);
2189 	if (!debug_flag)
2190 		alarm(options.login_grace_time);
2191 
2192 	if ((r = kex_exchange_identification(ssh, -1,
2193 	    options.version_addendum)) != 0)
2194 		sshpkt_fatal(ssh, r, "banner exchange");
2195 
2196 	ssh_packet_set_nonblocking(ssh);
2197 
2198 	/* allocate authentication context */
2199 	authctxt = xcalloc(1, sizeof(*authctxt));
2200 	ssh->authctxt = authctxt;
2201 
2202 	authctxt->loginmsg = loginmsg;
2203 
2204 	/* XXX global for cleanup, access from other modules */
2205 	the_authctxt = authctxt;
2206 
2207 	/* Set default key authentication options */
2208 	if ((auth_opts = sshauthopt_new_with_keys_defaults()) == NULL)
2209 		fatal("allocation failed");
2210 
2211 	/* prepare buffer to collect messages to display to user after login */
2212 	if ((loginmsg = sshbuf_new()) == NULL)
2213 		fatal_f("sshbuf_new failed");
2214 	auth_debug_reset();
2215 
2216 	if (use_privsep) {
2217 		if (privsep_preauth(ssh) == 1)
2218 			goto authenticated;
2219 	} else if (have_agent) {
2220 		if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) {
2221 			error_r(r, "Unable to get agent socket");
2222 			have_agent = 0;
2223 		}
2224 	}
2225 
2226 	/* perform the key exchange */
2227 	/* authenticate user and start session */
2228 	do_ssh2_kex(ssh);
2229 	do_authentication2(ssh);
2230 
2231 	/*
2232 	 * If we use privilege separation, the unprivileged child transfers
2233 	 * the current keystate and exits
2234 	 */
2235 	if (use_privsep) {
2236 		mm_send_keystate(ssh, pmonitor);
2237 		ssh_packet_clear_keys(ssh);
2238 		exit(0);
2239 	}
2240 
2241  authenticated:
2242 	/*
2243 	 * Cancel the alarm we set to limit the time taken for
2244 	 * authentication.
2245 	 */
2246 	alarm(0);
2247 	ssh_signal(SIGALRM, SIG_DFL);
2248 	authctxt->authenticated = 1;
2249 	if (startup_pipe != -1) {
2250 		close(startup_pipe);
2251 		startup_pipe = -1;
2252 	}
2253 
2254 #ifdef SSH_AUDIT_EVENTS
2255 	audit_event(ssh, SSH_AUTH_SUCCESS);
2256 #endif
2257 
2258 #ifdef GSSAPI
2259 	if (options.gss_authentication) {
2260 		temporarily_use_uid(authctxt->pw);
2261 		ssh_gssapi_storecreds();
2262 		restore_uid();
2263 	}
2264 #endif
2265 #ifdef USE_PAM
2266 	if (options.use_pam) {
2267 		do_pam_setcred(1);
2268 		do_pam_session(ssh);
2269 	}
2270 #endif
2271 
2272 	/*
2273 	 * In privilege separation, we fork another child and prepare
2274 	 * file descriptor passing.
2275 	 */
2276 	if (use_privsep) {
2277 		privsep_postauth(ssh, authctxt);
2278 		/* the monitor process [priv] will not return */
2279 	}
2280 
2281 	ssh_packet_set_timeout(ssh, options.client_alive_interval,
2282 	    options.client_alive_count_max);
2283 
2284 	/* Try to send all our hostkeys to the client */
2285 	notify_hostkeys(ssh);
2286 
2287 	/* Start session. */
2288 	do_authenticated(ssh, authctxt);
2289 
2290 	/* The connection has been terminated. */
2291 	ssh_packet_get_bytes(ssh, &ibytes, &obytes);
2292 	verbose("Transferred: sent %llu, received %llu bytes",
2293 	    (unsigned long long)obytes, (unsigned long long)ibytes);
2294 
2295 	verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
2296 
2297 #ifdef USE_PAM
2298 	if (options.use_pam)
2299 		finish_pam();
2300 #endif /* USE_PAM */
2301 
2302 #ifdef SSH_AUDIT_EVENTS
2303 	PRIVSEP(audit_event(ssh, SSH_CONNECTION_CLOSE));
2304 #endif
2305 
2306 	ssh_packet_close(ssh);
2307 
2308 	if (use_privsep)
2309 		mm_terminate();
2310 
2311 	exit(0);
2312 }
2313 
2314 int
2315 sshd_hostkey_sign(struct ssh *ssh, struct sshkey *privkey,
2316     struct sshkey *pubkey, u_char **signature, size_t *slenp,
2317     const u_char *data, size_t dlen, const char *alg)
2318 {
2319 	int r;
2320 
2321 	if (use_privsep) {
2322 		if (privkey) {
2323 			if (mm_sshkey_sign(ssh, privkey, signature, slenp,
2324 			    data, dlen, alg, options.sk_provider, NULL,
2325 			    ssh->compat) < 0)
2326 				fatal_f("privkey sign failed");
2327 		} else {
2328 			if (mm_sshkey_sign(ssh, pubkey, signature, slenp,
2329 			    data, dlen, alg, options.sk_provider, NULL,
2330 			    ssh->compat) < 0)
2331 				fatal_f("pubkey sign failed");
2332 		}
2333 	} else {
2334 		if (privkey) {
2335 			if (sshkey_sign(privkey, signature, slenp, data, dlen,
2336 			    alg, options.sk_provider, NULL, ssh->compat) < 0)
2337 				fatal_f("privkey sign failed");
2338 		} else {
2339 			if ((r = ssh_agent_sign(auth_sock, pubkey,
2340 			    signature, slenp, data, dlen, alg,
2341 			    ssh->compat)) != 0) {
2342 				fatal_fr(r, "agent sign failed");
2343 			}
2344 		}
2345 	}
2346 	return 0;
2347 }
2348 
2349 /* SSH2 key exchange */
2350 static void
2351 do_ssh2_kex(struct ssh *ssh)
2352 {
2353 	char *myproposal[PROPOSAL_MAX] = { KEX_SERVER };
2354 	struct kex *kex;
2355 	int r;
2356 
2357 	myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(ssh,
2358 	    options.kex_algorithms);
2359 	myproposal[PROPOSAL_ENC_ALGS_CTOS] = compat_cipher_proposal(ssh,
2360 	    options.ciphers);
2361 	myproposal[PROPOSAL_ENC_ALGS_STOC] = compat_cipher_proposal(ssh,
2362 	    options.ciphers);
2363 	myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2364 	    myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2365 
2366 	if (options.compression == COMP_NONE) {
2367 		myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2368 		    myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2369 	}
2370 
2371 	if (options.rekey_limit || options.rekey_interval)
2372 		ssh_packet_set_rekey_limits(ssh, options.rekey_limit,
2373 		    options.rekey_interval);
2374 
2375 	myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal(
2376 	    ssh, list_hostkey_types());
2377 
2378 	/* start key exchange */
2379 	if ((r = kex_setup(ssh, myproposal)) != 0)
2380 		fatal_r(r, "kex_setup");
2381 	kex = ssh->kex;
2382 #ifdef WITH_OPENSSL
2383 	kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_server;
2384 	kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_server;
2385 	kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_server;
2386 	kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_server;
2387 	kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_server;
2388 	kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2389 	kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2390 # ifdef OPENSSL_HAS_ECC
2391 	kex->kex[KEX_ECDH_SHA2] = kex_gen_server;
2392 # endif
2393 #endif
2394 	kex->kex[KEX_C25519_SHA256] = kex_gen_server;
2395 	kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_server;
2396 	kex->load_host_public_key=&get_hostkey_public_by_type;
2397 	kex->load_host_private_key=&get_hostkey_private_by_type;
2398 	kex->host_key_index=&get_hostkey_index;
2399 	kex->sign = sshd_hostkey_sign;
2400 
2401 	ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &kex->done);
2402 
2403 #ifdef DEBUG_KEXDH
2404 	/* send 1st encrypted/maced/compressed message */
2405 	if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 ||
2406 	    (r = sshpkt_put_cstring(ssh, "markus")) != 0 ||
2407 	    (r = sshpkt_send(ssh)) != 0 ||
2408 	    (r = ssh_packet_write_wait(ssh)) != 0)
2409 		fatal_fr(r, "send test");
2410 #endif
2411 	debug("KEX done");
2412 }
2413 
2414 /* server specific fatal cleanup */
2415 void
2416 cleanup_exit(int i)
2417 {
2418 	if (the_active_state != NULL && the_authctxt != NULL) {
2419 		do_cleanup(the_active_state, the_authctxt);
2420 		if (use_privsep && privsep_is_preauth &&
2421 		    pmonitor != NULL && pmonitor->m_pid > 1) {
2422 			debug("Killing privsep child %d", pmonitor->m_pid);
2423 			if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
2424 			    errno != ESRCH) {
2425 				error_f("kill(%d): %s", pmonitor->m_pid,
2426 				    strerror(errno));
2427 			}
2428 		}
2429 	}
2430 #ifdef SSH_AUDIT_EVENTS
2431 	/* done after do_cleanup so it can cancel the PAM auth 'thread' */
2432 	if (the_active_state != NULL && (!use_privsep || mm_is_monitor()))
2433 		audit_event(the_active_state, SSH_CONNECTION_ABANDON);
2434 #endif
2435 	_exit(i);
2436 }
2437