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