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