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