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