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