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