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