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