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