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