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