xref: /freebsd/crypto/openssh/sshd.c (revision bc5531debefeb54993d01d4f3c8b33ccbe0b4d95)
1 /* $OpenBSD: sshd.c,v 1.444 2015/02/20 22:17:21 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 "ssh1.h"
102 #include "ssh2.h"
103 #include "rsa.h"
104 #include "sshpty.h"
105 #include "packet.h"
106 #include "log.h"
107 #include "buffer.h"
108 #include "misc.h"
109 #include "servconf.h"
110 #include "uidswap.h"
111 #include "compat.h"
112 #include "cipher.h"
113 #include "digest.h"
114 #include "key.h"
115 #include "kex.h"
116 #include "myproposal.h"
117 #include "authfile.h"
118 #include "pathnames.h"
119 #include "atomicio.h"
120 #include "canohost.h"
121 #include "hostfile.h"
122 #include "auth.h"
123 #include "authfd.h"
124 #include "msg.h"
125 #include "dispatch.h"
126 #include "channels.h"
127 #include "session.h"
128 #include "monitor_mm.h"
129 #include "monitor.h"
130 #ifdef GSSAPI
131 #include "ssh-gss.h"
132 #endif
133 #include "monitor_wrap.h"
134 #include "roaming.h"
135 #include "ssh-sandbox.h"
136 #include "version.h"
137 #include "ssherr.h"
138 
139 #ifdef LIBWRAP
140 #include <tcpd.h>
141 #include <syslog.h>
142 int allow_severity;
143 int deny_severity;
144 #endif /* LIBWRAP */
145 
146 #ifndef O_NOCTTY
147 #define O_NOCTTY	0
148 #endif
149 
150 /* Re-exec fds */
151 #define REEXEC_DEVCRYPTO_RESERVED_FD	(STDERR_FILENO + 1)
152 #define REEXEC_STARTUP_PIPE_FD		(STDERR_FILENO + 2)
153 #define REEXEC_CONFIG_PASS_FD		(STDERR_FILENO + 3)
154 #define REEXEC_MIN_FREE_FD		(STDERR_FILENO + 4)
155 
156 extern char *__progname;
157 
158 /* Server configuration options. */
159 ServerOptions options;
160 
161 /* Name of the server configuration file. */
162 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
163 
164 /*
165  * Debug mode flag.  This can be set on the command line.  If debug
166  * mode is enabled, extra debugging output will be sent to the system
167  * log, the daemon will not go to background, and will exit after processing
168  * the first connection.
169  */
170 int debug_flag = 0;
171 
172 /* Flag indicating that the daemon should only test the configuration and keys. */
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 	Key	*server_key;		/* ephemeral server key */
223 	Key	*ssh1_host_key;		/* ssh1 host key */
224 	Key	**host_keys;		/* all private host keys */
225 	Key	**host_pubkeys;		/* all public host keys */
226 	Key	**host_certificates;	/* all public host certificates */
227 	int	have_ssh1_key;
228 	int	have_ssh2_key;
229 	u_char	ssh1_cookie[SSH_SESSION_KEY_LENGTH];
230 } sensitive_data;
231 
232 /*
233  * Flag indicating whether the RSA server key needs to be regenerated.
234  * Is set in the SIGALRM handler and cleared when the key is regenerated.
235  */
236 static volatile sig_atomic_t key_do_regen = 0;
237 
238 /* This is set to true when a signal is received. */
239 static volatile sig_atomic_t received_sighup = 0;
240 static volatile sig_atomic_t received_sigterm = 0;
241 
242 /* session identifier, used by RSA-auth */
243 u_char session_id[16];
244 
245 /* same for ssh2 */
246 u_char *session_id2 = NULL;
247 u_int session_id2_len = 0;
248 
249 /* record remote hostname or ip */
250 u_int utmp_len = HOST_NAME_MAX+1;
251 
252 /* options.max_startup sized array of fd ints */
253 int *startup_pipes = NULL;
254 int startup_pipe;		/* in child */
255 
256 /* variables used for privilege separation */
257 int use_privsep = -1;
258 struct monitor *pmonitor = NULL;
259 int privsep_is_preauth = 1;
260 
261 /* global authentication context */
262 Authctxt *the_authctxt = NULL;
263 
264 /* sshd_config buffer */
265 Buffer cfg;
266 
267 /* message to be displayed after login */
268 Buffer loginmsg;
269 
270 /* Unprivileged user */
271 struct passwd *privsep_pw = NULL;
272 
273 /* Prototypes for various functions defined later in this file. */
274 void destroy_sensitive_data(void);
275 void demote_sensitive_data(void);
276 
277 #ifdef WITH_SSH1
278 static void do_ssh1_kex(void);
279 #endif
280 static void do_ssh2_kex(void);
281 
282 /*
283  * Close all listening sockets
284  */
285 static void
286 close_listen_socks(void)
287 {
288 	int i;
289 
290 	for (i = 0; i < num_listen_socks; i++)
291 		close(listen_socks[i]);
292 	num_listen_socks = -1;
293 }
294 
295 static void
296 close_startup_pipes(void)
297 {
298 	int i;
299 
300 	if (startup_pipes)
301 		for (i = 0; i < options.max_startups; i++)
302 			if (startup_pipes[i] != -1)
303 				close(startup_pipes[i]);
304 }
305 
306 /*
307  * Signal handler for SIGHUP.  Sshd execs itself when it receives SIGHUP;
308  * the effect is to reread the configuration file (and to regenerate
309  * the server key).
310  */
311 
312 /*ARGSUSED*/
313 static void
314 sighup_handler(int sig)
315 {
316 	int save_errno = errno;
317 
318 	received_sighup = 1;
319 	signal(SIGHUP, sighup_handler);
320 	errno = save_errno;
321 }
322 
323 /*
324  * Called from the main program after receiving SIGHUP.
325  * Restarts the server.
326  */
327 static void
328 sighup_restart(void)
329 {
330 	logit("Received SIGHUP; restarting.");
331 	platform_pre_restart();
332 	close_listen_socks();
333 	close_startup_pipes();
334 	alarm(0);  /* alarm timer persists across exec */
335 	signal(SIGHUP, SIG_IGN); /* will be restored after exec */
336 	execv(saved_argv[0], saved_argv);
337 	logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
338 	    strerror(errno));
339 	exit(1);
340 }
341 
342 /*
343  * Generic signal handler for terminating signals in the master daemon.
344  */
345 /*ARGSUSED*/
346 static void
347 sigterm_handler(int sig)
348 {
349 	received_sigterm = sig;
350 }
351 
352 /*
353  * SIGCHLD handler.  This is called whenever a child dies.  This will then
354  * reap any zombies left by exited children.
355  */
356 /*ARGSUSED*/
357 static void
358 main_sigchld_handler(int sig)
359 {
360 	int save_errno = errno;
361 	pid_t pid;
362 	int status;
363 
364 	while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
365 	    (pid < 0 && errno == EINTR))
366 		;
367 
368 	signal(SIGCHLD, main_sigchld_handler);
369 	errno = save_errno;
370 }
371 
372 /*
373  * Signal handler for the alarm after the login grace period has expired.
374  */
375 /*ARGSUSED*/
376 static void
377 grace_alarm_handler(int sig)
378 {
379 	if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
380 		kill(pmonitor->m_pid, SIGALRM);
381 
382 	/*
383 	 * Try to kill any processes that we have spawned, E.g. authorized
384 	 * keys command helpers.
385 	 */
386 	if (getpgid(0) == getpid()) {
387 		signal(SIGTERM, SIG_IGN);
388 		kill(0, SIGTERM);
389 	}
390 
391 	/* Log error and exit. */
392 	sigdie("Timeout before authentication for %s", get_remote_ipaddr());
393 }
394 
395 /*
396  * Signal handler for the key regeneration alarm.  Note that this
397  * alarm only occurs in the daemon waiting for connections, and it does not
398  * do anything with the private key or random state before forking.
399  * Thus there should be no concurrency control/asynchronous execution
400  * problems.
401  */
402 static void
403 generate_ephemeral_server_key(void)
404 {
405 	verbose("Generating %s%d bit RSA key.",
406 	    sensitive_data.server_key ? "new " : "", options.server_key_bits);
407 	if (sensitive_data.server_key != NULL)
408 		key_free(sensitive_data.server_key);
409 	sensitive_data.server_key = key_generate(KEY_RSA1,
410 	    options.server_key_bits);
411 	verbose("RSA key generation complete.");
412 
413 	arc4random_buf(sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
414 }
415 
416 /*ARGSUSED*/
417 static void
418 key_regeneration_alarm(int sig)
419 {
420 	int save_errno = errno;
421 
422 	signal(SIGALRM, SIG_DFL);
423 	errno = save_errno;
424 	key_do_regen = 1;
425 }
426 
427 static void
428 sshd_exchange_identification(int sock_in, int sock_out)
429 {
430 	u_int i;
431 	int mismatch;
432 	int remote_major, remote_minor;
433 	int major, minor;
434 	char *s, *newline = "\n";
435 	char buf[256];			/* Must not be larger than remote_version. */
436 	char remote_version[256];	/* Must be at least as big as buf. */
437 
438 	if ((options.protocol & SSH_PROTO_1) &&
439 	    (options.protocol & SSH_PROTO_2)) {
440 		major = PROTOCOL_MAJOR_1;
441 		minor = 99;
442 	} else if (options.protocol & SSH_PROTO_2) {
443 		major = PROTOCOL_MAJOR_2;
444 		minor = PROTOCOL_MINOR_2;
445 		newline = "\r\n";
446 	} else {
447 		major = PROTOCOL_MAJOR_1;
448 		minor = PROTOCOL_MINOR_1;
449 	}
450 
451 	xasprintf(&server_version_string, "SSH-%d.%d-%.100s%s%s%s",
452 	    major, minor, SSH_VERSION,
453 	    *options.version_addendum == '\0' ? "" : " ",
454 	    options.version_addendum, newline);
455 
456 	/* Send our protocol version identification. */
457 	if (roaming_atomicio(vwrite, sock_out, server_version_string,
458 	    strlen(server_version_string))
459 	    != strlen(server_version_string)) {
460 		logit("Could not write ident string to %s", get_remote_ipaddr());
461 		cleanup_exit(255);
462 	}
463 
464 	/* Read other sides version identification. */
465 	memset(buf, 0, sizeof(buf));
466 	for (i = 0; i < sizeof(buf) - 1; i++) {
467 		if (roaming_atomicio(read, sock_in, &buf[i], 1) != 1) {
468 			logit("Did not receive identification string from %s",
469 			    get_remote_ipaddr());
470 			cleanup_exit(255);
471 		}
472 		if (buf[i] == '\r') {
473 			buf[i] = 0;
474 			/* Kludge for F-Secure Macintosh < 1.0.2 */
475 			if (i == 12 &&
476 			    strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
477 				break;
478 			continue;
479 		}
480 		if (buf[i] == '\n') {
481 			buf[i] = 0;
482 			break;
483 		}
484 	}
485 	buf[sizeof(buf) - 1] = 0;
486 	client_version_string = xstrdup(buf);
487 
488 	/*
489 	 * Check that the versions match.  In future this might accept
490 	 * several versions and set appropriate flags to handle them.
491 	 */
492 	if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
493 	    &remote_major, &remote_minor, remote_version) != 3) {
494 		s = "Protocol mismatch.\n";
495 		(void) atomicio(vwrite, sock_out, s, strlen(s));
496 		logit("Bad protocol version identification '%.100s' "
497 		    "from %s port %d", client_version_string,
498 		    get_remote_ipaddr(), get_remote_port());
499 		close(sock_in);
500 		close(sock_out);
501 		cleanup_exit(255);
502 	}
503 	debug("Client protocol version %d.%d; client software version %.100s",
504 	    remote_major, remote_minor, remote_version);
505 
506 	active_state->compat = compat_datafellows(remote_version);
507 
508 	if ((datafellows & SSH_BUG_PROBE) != 0) {
509 		logit("probed from %s with %s.  Don't panic.",
510 		    get_remote_ipaddr(), client_version_string);
511 		cleanup_exit(255);
512 	}
513 	if ((datafellows & SSH_BUG_SCANNER) != 0) {
514 		logit("scanned from %s with %s.  Don't panic.",
515 		    get_remote_ipaddr(), client_version_string);
516 		cleanup_exit(255);
517 	}
518 	if ((datafellows & SSH_BUG_RSASIGMD5) != 0) {
519 		logit("Client version \"%.100s\" uses unsafe RSA signature "
520 		    "scheme; disabling use of RSA keys", remote_version);
521 	}
522 	if ((datafellows & SSH_BUG_DERIVEKEY) != 0) {
523 		fatal("Client version \"%.100s\" uses unsafe key agreement; "
524 		    "refusing connection", remote_version);
525 	}
526 
527 	mismatch = 0;
528 	switch (remote_major) {
529 	case 1:
530 		if (remote_minor == 99) {
531 			if (options.protocol & SSH_PROTO_2)
532 				enable_compat20();
533 			else
534 				mismatch = 1;
535 			break;
536 		}
537 		if (!(options.protocol & SSH_PROTO_1)) {
538 			mismatch = 1;
539 			break;
540 		}
541 		if (remote_minor < 3) {
542 			packet_disconnect("Your ssh version is too old and "
543 			    "is no longer supported.  Please install a newer version.");
544 		} else if (remote_minor == 3) {
545 			/* note that this disables agent-forwarding */
546 			enable_compat13();
547 		}
548 		break;
549 	case 2:
550 		if (options.protocol & SSH_PROTO_2) {
551 			enable_compat20();
552 			break;
553 		}
554 		/* FALLTHROUGH */
555 	default:
556 		mismatch = 1;
557 		break;
558 	}
559 	chop(server_version_string);
560 	debug("Local version string %.200s", server_version_string);
561 
562 	if (mismatch) {
563 		s = "Protocol major versions differ.\n";
564 		(void) atomicio(vwrite, sock_out, s, strlen(s));
565 		close(sock_in);
566 		close(sock_out);
567 		logit("Protocol major versions differ for %s: %.200s vs. %.200s",
568 		    get_remote_ipaddr(),
569 		    server_version_string, client_version_string);
570 		cleanup_exit(255);
571 	}
572 }
573 
574 /* Destroy the host and server keys.  They will no longer be needed. */
575 void
576 destroy_sensitive_data(void)
577 {
578 	int i;
579 
580 	if (sensitive_data.server_key) {
581 		key_free(sensitive_data.server_key);
582 		sensitive_data.server_key = NULL;
583 	}
584 	for (i = 0; i < options.num_host_key_files; i++) {
585 		if (sensitive_data.host_keys[i]) {
586 			key_free(sensitive_data.host_keys[i]);
587 			sensitive_data.host_keys[i] = NULL;
588 		}
589 		if (sensitive_data.host_certificates[i]) {
590 			key_free(sensitive_data.host_certificates[i]);
591 			sensitive_data.host_certificates[i] = NULL;
592 		}
593 	}
594 	sensitive_data.ssh1_host_key = NULL;
595 	explicit_bzero(sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
596 }
597 
598 /* Demote private to public keys for network child */
599 void
600 demote_sensitive_data(void)
601 {
602 	Key *tmp;
603 	int i;
604 
605 	if (sensitive_data.server_key) {
606 		tmp = key_demote(sensitive_data.server_key);
607 		key_free(sensitive_data.server_key);
608 		sensitive_data.server_key = tmp;
609 	}
610 
611 	for (i = 0; i < options.num_host_key_files; i++) {
612 		if (sensitive_data.host_keys[i]) {
613 			tmp = key_demote(sensitive_data.host_keys[i]);
614 			key_free(sensitive_data.host_keys[i]);
615 			sensitive_data.host_keys[i] = tmp;
616 			if (tmp->type == KEY_RSA1)
617 				sensitive_data.ssh1_host_key = tmp;
618 		}
619 		/* Certs do not need demotion */
620 	}
621 
622 	/* We do not clear ssh1_host key and cookie.  XXX - Okay Niels? */
623 }
624 
625 static void
626 privsep_preauth_child(void)
627 {
628 	u_int32_t rnd[256];
629 	gid_t gidset[1];
630 
631 	/* Enable challenge-response authentication for privilege separation */
632 	privsep_challenge_enable();
633 
634 #ifdef GSSAPI
635 	/* Cache supported mechanism OIDs for later use */
636 	if (options.gss_authentication)
637 		ssh_gssapi_prepare_supported_oids();
638 #endif
639 
640 	arc4random_stir();
641 	arc4random_buf(rnd, sizeof(rnd));
642 #ifdef WITH_OPENSSL
643 	RAND_seed(rnd, sizeof(rnd));
644 #endif
645 	explicit_bzero(rnd, sizeof(rnd));
646 
647 	/* Demote the private keys to public keys. */
648 	demote_sensitive_data();
649 
650 	/* Change our root directory */
651 	if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
652 		fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
653 		    strerror(errno));
654 	if (chdir("/") == -1)
655 		fatal("chdir(\"/\"): %s", strerror(errno));
656 
657 	/* Drop our privileges */
658 	debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
659 	    (u_int)privsep_pw->pw_gid);
660 #if 0
661 	/* XXX not ready, too heavy after chroot */
662 	do_setusercontext(privsep_pw);
663 #else
664 	gidset[0] = privsep_pw->pw_gid;
665 	if (setgroups(1, gidset) < 0)
666 		fatal("setgroups: %.100s", strerror(errno));
667 	permanently_set_uid(privsep_pw);
668 #endif
669 }
670 
671 static int
672 privsep_preauth(Authctxt *authctxt)
673 {
674 	int status, r;
675 	pid_t pid;
676 	struct ssh_sandbox *box = NULL;
677 
678 	/* Set up unprivileged child process to deal with network data */
679 	pmonitor = monitor_init();
680 	/* Store a pointer to the kex for later rekeying */
681 	pmonitor->m_pkex = &active_state->kex;
682 
683 	if (use_privsep == PRIVSEP_ON)
684 		box = ssh_sandbox_init(pmonitor);
685 	pid = fork();
686 	if (pid == -1) {
687 		fatal("fork of unprivileged child failed");
688 	} else if (pid != 0) {
689 		debug2("Network child is on pid %ld", (long)pid);
690 
691 		pmonitor->m_pid = pid;
692 		if (have_agent) {
693 			r = ssh_get_authentication_socket(&auth_sock);
694 			if (r != 0) {
695 				error("Could not get agent socket: %s",
696 				    ssh_err(r));
697 				have_agent = 0;
698 			}
699 		}
700 		if (box != NULL)
701 			ssh_sandbox_parent_preauth(box, pid);
702 		monitor_child_preauth(authctxt, pmonitor);
703 
704 		/* Sync memory */
705 		monitor_sync(pmonitor);
706 
707 		/* Wait for the child's exit status */
708 		while (waitpid(pid, &status, 0) < 0) {
709 			if (errno == EINTR)
710 				continue;
711 			pmonitor->m_pid = -1;
712 			fatal("%s: waitpid: %s", __func__, strerror(errno));
713 		}
714 		privsep_is_preauth = 0;
715 		pmonitor->m_pid = -1;
716 		if (WIFEXITED(status)) {
717 			if (WEXITSTATUS(status) != 0)
718 				fatal("%s: preauth child exited with status %d",
719 				    __func__, WEXITSTATUS(status));
720 		} else if (WIFSIGNALED(status))
721 			fatal("%s: preauth child terminated by signal %d",
722 			    __func__, WTERMSIG(status));
723 		if (box != NULL)
724 			ssh_sandbox_parent_finish(box);
725 		return 1;
726 	} else {
727 		/* child */
728 		close(pmonitor->m_sendfd);
729 		close(pmonitor->m_log_recvfd);
730 
731 		/* Arrange for logging to be sent to the monitor */
732 		set_log_handler(mm_log_handler, pmonitor);
733 
734 		/* Demote the child */
735 		if (getuid() == 0 || geteuid() == 0)
736 			privsep_preauth_child();
737 		setproctitle("%s", "[net]");
738 		if (box != NULL)
739 			ssh_sandbox_child(box);
740 
741 		return 0;
742 	}
743 }
744 
745 static void
746 privsep_postauth(Authctxt *authctxt)
747 {
748 	u_int32_t rnd[256];
749 
750 #ifdef DISABLE_FD_PASSING
751 	if (1) {
752 #else
753 	if (authctxt->pw->pw_uid == 0 || options.use_login) {
754 #endif
755 		/* File descriptor passing is broken or root login */
756 		use_privsep = 0;
757 		goto skip;
758 	}
759 
760 	/* New socket pair */
761 	monitor_reinit(pmonitor);
762 
763 	pmonitor->m_pid = fork();
764 	if (pmonitor->m_pid == -1)
765 		fatal("fork of unprivileged child failed");
766 	else if (pmonitor->m_pid != 0) {
767 		verbose("User child is on pid %ld", (long)pmonitor->m_pid);
768 		buffer_clear(&loginmsg);
769 		monitor_child_postauth(pmonitor);
770 
771 		/* NEVERREACHED */
772 		exit(0);
773 	}
774 
775 	/* child */
776 
777 	close(pmonitor->m_sendfd);
778 	pmonitor->m_sendfd = -1;
779 
780 	/* Demote the private keys to public keys. */
781 	demote_sensitive_data();
782 
783 	arc4random_stir();
784 	arc4random_buf(rnd, sizeof(rnd));
785 #ifdef WITH_OPENSSL
786 	RAND_seed(rnd, sizeof(rnd));
787 #endif
788 	explicit_bzero(rnd, sizeof(rnd));
789 
790 	/* Drop privileges */
791 	do_setusercontext(authctxt->pw);
792 
793  skip:
794 	/* It is safe now to apply the key state */
795 	monitor_apply_keystate(pmonitor);
796 
797 	/*
798 	 * Tell the packet layer that authentication was successful, since
799 	 * this information is not part of the key state.
800 	 */
801 	packet_set_authenticated();
802 }
803 
804 static char *
805 list_hostkey_types(void)
806 {
807 	Buffer b;
808 	const char *p;
809 	char *ret;
810 	int i;
811 	Key *key;
812 
813 	buffer_init(&b);
814 	for (i = 0; i < options.num_host_key_files; i++) {
815 		key = sensitive_data.host_keys[i];
816 		if (key == NULL)
817 			key = sensitive_data.host_pubkeys[i];
818 		if (key == NULL)
819 			continue;
820 		switch (key->type) {
821 		case KEY_RSA:
822 		case KEY_DSA:
823 		case KEY_ECDSA:
824 		case KEY_ED25519:
825 			if (buffer_len(&b) > 0)
826 				buffer_append(&b, ",", 1);
827 			p = key_ssh_name(key);
828 			buffer_append(&b, p, strlen(p));
829 			break;
830 		}
831 		/* If the private key has a cert peer, then list that too */
832 		key = sensitive_data.host_certificates[i];
833 		if (key == NULL)
834 			continue;
835 		switch (key->type) {
836 		case KEY_RSA_CERT_V00:
837 		case KEY_DSA_CERT_V00:
838 		case KEY_RSA_CERT:
839 		case KEY_DSA_CERT:
840 		case KEY_ECDSA_CERT:
841 		case KEY_ED25519_CERT:
842 			if (buffer_len(&b) > 0)
843 				buffer_append(&b, ",", 1);
844 			p = key_ssh_name(key);
845 			buffer_append(&b, p, strlen(p));
846 			break;
847 		}
848 	}
849 	buffer_append(&b, "\0", 1);
850 	ret = xstrdup(buffer_ptr(&b));
851 	buffer_free(&b);
852 	debug("list_hostkey_types: %s", ret);
853 	return ret;
854 }
855 
856 static Key *
857 get_hostkey_by_type(int type, int nid, int need_private, struct ssh *ssh)
858 {
859 	int i;
860 	Key *key;
861 
862 	for (i = 0; i < options.num_host_key_files; i++) {
863 		switch (type) {
864 		case KEY_RSA_CERT_V00:
865 		case KEY_DSA_CERT_V00:
866 		case KEY_RSA_CERT:
867 		case KEY_DSA_CERT:
868 		case KEY_ECDSA_CERT:
869 		case KEY_ED25519_CERT:
870 			key = sensitive_data.host_certificates[i];
871 			break;
872 		default:
873 			key = sensitive_data.host_keys[i];
874 			if (key == NULL && !need_private)
875 				key = sensitive_data.host_pubkeys[i];
876 			break;
877 		}
878 		if (key != NULL && key->type == type &&
879 		    (key->type != KEY_ECDSA || key->ecdsa_nid == nid))
880 			return need_private ?
881 			    sensitive_data.host_keys[i] : key;
882 	}
883 	return NULL;
884 }
885 
886 Key *
887 get_hostkey_public_by_type(int type, int nid, struct ssh *ssh)
888 {
889 	return get_hostkey_by_type(type, nid, 0, ssh);
890 }
891 
892 Key *
893 get_hostkey_private_by_type(int type, int nid, struct ssh *ssh)
894 {
895 	return get_hostkey_by_type(type, nid, 1, ssh);
896 }
897 
898 Key *
899 get_hostkey_by_index(int ind)
900 {
901 	if (ind < 0 || ind >= options.num_host_key_files)
902 		return (NULL);
903 	return (sensitive_data.host_keys[ind]);
904 }
905 
906 Key *
907 get_hostkey_public_by_index(int ind, struct ssh *ssh)
908 {
909 	if (ind < 0 || ind >= options.num_host_key_files)
910 		return (NULL);
911 	return (sensitive_data.host_pubkeys[ind]);
912 }
913 
914 int
915 get_hostkey_index(Key *key, int compare, struct ssh *ssh)
916 {
917 	int i;
918 
919 	for (i = 0; i < options.num_host_key_files; i++) {
920 		if (key_is_cert(key)) {
921 			if (key == sensitive_data.host_certificates[i] ||
922 			    (compare && sensitive_data.host_certificates[i] &&
923 			    sshkey_equal(key,
924 			    sensitive_data.host_certificates[i])))
925 				return (i);
926 		} else {
927 			if (key == sensitive_data.host_keys[i] ||
928 			    (compare && sensitive_data.host_keys[i] &&
929 			    sshkey_equal(key, sensitive_data.host_keys[i])))
930 				return (i);
931 			if (key == sensitive_data.host_pubkeys[i] ||
932 			    (compare && sensitive_data.host_pubkeys[i] &&
933 			    sshkey_equal(key, sensitive_data.host_pubkeys[i])))
934 				return (i);
935 		}
936 	}
937 	return (-1);
938 }
939 
940 /* Inform the client of all hostkeys */
941 static void
942 notify_hostkeys(struct ssh *ssh)
943 {
944 	struct sshbuf *buf;
945 	struct sshkey *key;
946 	int i, nkeys, r;
947 	char *fp;
948 
949 	if ((buf = sshbuf_new()) == NULL)
950 		fatal("%s: sshbuf_new", __func__);
951 	for (i = nkeys = 0; i < options.num_host_key_files; i++) {
952 		key = get_hostkey_public_by_index(i, ssh);
953 		if (key == NULL || key->type == KEY_UNSPEC ||
954 		    key->type == KEY_RSA1 || sshkey_is_cert(key))
955 			continue;
956 		fp = sshkey_fingerprint(key, options.fingerprint_hash,
957 		    SSH_FP_DEFAULT);
958 		debug3("%s: key %d: %s %s", __func__, i,
959 		    sshkey_ssh_name(key), fp);
960 		free(fp);
961 		if (nkeys == 0) {
962 			packet_start(SSH2_MSG_GLOBAL_REQUEST);
963 			packet_put_cstring("hostkeys-00@openssh.com");
964 			packet_put_char(0); /* want-reply */
965 		}
966 		sshbuf_reset(buf);
967 		if ((r = sshkey_putb(key, buf)) != 0)
968 			fatal("%s: couldn't put hostkey %d: %s",
969 			    __func__, i, ssh_err(r));
970 		packet_put_string(sshbuf_ptr(buf), sshbuf_len(buf));
971 		nkeys++;
972 	}
973 	debug3("%s: sent %d hostkeys", __func__, nkeys);
974 	if (nkeys == 0)
975 		fatal("%s: no hostkeys", __func__);
976 	packet_send();
977 	sshbuf_free(buf);
978 }
979 
980 /*
981  * returns 1 if connection should be dropped, 0 otherwise.
982  * dropping starts at connection #max_startups_begin with a probability
983  * of (max_startups_rate/100). the probability increases linearly until
984  * all connections are dropped for startups > max_startups
985  */
986 static int
987 drop_connection(int startups)
988 {
989 	int p, r;
990 
991 	if (startups < options.max_startups_begin)
992 		return 0;
993 	if (startups >= options.max_startups)
994 		return 1;
995 	if (options.max_startups_rate == 100)
996 		return 1;
997 
998 	p  = 100 - options.max_startups_rate;
999 	p *= startups - options.max_startups_begin;
1000 	p /= options.max_startups - options.max_startups_begin;
1001 	p += options.max_startups_rate;
1002 	r = arc4random_uniform(100);
1003 
1004 	debug("drop_connection: p %d, r %d", p, r);
1005 	return (r < p) ? 1 : 0;
1006 }
1007 
1008 static void
1009 usage(void)
1010 {
1011 	if (options.version_addendum && *options.version_addendum != '\0')
1012 		fprintf(stderr, "%s %s, %s\n",
1013 		    SSH_RELEASE,
1014 		    options.version_addendum, OPENSSL_VERSION);
1015 	else
1016 		fprintf(stderr, "%s, %s\n",
1017 		    SSH_RELEASE, OPENSSL_VERSION);
1018 	fprintf(stderr,
1019 "usage: sshd [-46DdeiqTt] [-b bits] [-C connection_spec] [-c host_cert_file]\n"
1020 "            [-E log_file] [-f config_file] [-g login_grace_time]\n"
1021 "            [-h host_key_file] [-k key_gen_time] [-o option] [-p port]\n"
1022 "            [-u len]\n"
1023 	);
1024 	exit(1);
1025 }
1026 
1027 static void
1028 send_rexec_state(int fd, Buffer *conf)
1029 {
1030 	Buffer m;
1031 
1032 	debug3("%s: entering fd = %d config len %d", __func__, fd,
1033 	    buffer_len(conf));
1034 
1035 	/*
1036 	 * Protocol from reexec master to child:
1037 	 *	string	configuration
1038 	 *	u_int	ephemeral_key_follows
1039 	 *	bignum	e		(only if ephemeral_key_follows == 1)
1040 	 *	bignum	n			"
1041 	 *	bignum	d			"
1042 	 *	bignum	iqmp			"
1043 	 *	bignum	p			"
1044 	 *	bignum	q			"
1045 	 *	string rngseed		(only if OpenSSL is not self-seeded)
1046 	 */
1047 	buffer_init(&m);
1048 	buffer_put_cstring(&m, buffer_ptr(conf));
1049 
1050 #ifdef WITH_SSH1
1051 	if (sensitive_data.server_key != NULL &&
1052 	    sensitive_data.server_key->type == KEY_RSA1) {
1053 		buffer_put_int(&m, 1);
1054 		buffer_put_bignum(&m, sensitive_data.server_key->rsa->e);
1055 		buffer_put_bignum(&m, sensitive_data.server_key->rsa->n);
1056 		buffer_put_bignum(&m, sensitive_data.server_key->rsa->d);
1057 		buffer_put_bignum(&m, sensitive_data.server_key->rsa->iqmp);
1058 		buffer_put_bignum(&m, sensitive_data.server_key->rsa->p);
1059 		buffer_put_bignum(&m, sensitive_data.server_key->rsa->q);
1060 	} else
1061 #endif
1062 		buffer_put_int(&m, 0);
1063 
1064 #if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
1065 	rexec_send_rng_seed(&m);
1066 #endif
1067 
1068 	if (ssh_msg_send(fd, 0, &m) == -1)
1069 		fatal("%s: ssh_msg_send failed", __func__);
1070 
1071 	buffer_free(&m);
1072 
1073 	debug3("%s: done", __func__);
1074 }
1075 
1076 static void
1077 recv_rexec_state(int fd, Buffer *conf)
1078 {
1079 	Buffer m;
1080 	char *cp;
1081 	u_int len;
1082 
1083 	debug3("%s: entering fd = %d", __func__, fd);
1084 
1085 	buffer_init(&m);
1086 
1087 	if (ssh_msg_recv(fd, &m) == -1)
1088 		fatal("%s: ssh_msg_recv failed", __func__);
1089 	if (buffer_get_char(&m) != 0)
1090 		fatal("%s: rexec version mismatch", __func__);
1091 
1092 	cp = buffer_get_string(&m, &len);
1093 	if (conf != NULL)
1094 		buffer_append(conf, cp, len + 1);
1095 	free(cp);
1096 
1097 	if (buffer_get_int(&m)) {
1098 #ifdef WITH_SSH1
1099 		if (sensitive_data.server_key != NULL)
1100 			key_free(sensitive_data.server_key);
1101 		sensitive_data.server_key = key_new_private(KEY_RSA1);
1102 		buffer_get_bignum(&m, sensitive_data.server_key->rsa->e);
1103 		buffer_get_bignum(&m, sensitive_data.server_key->rsa->n);
1104 		buffer_get_bignum(&m, sensitive_data.server_key->rsa->d);
1105 		buffer_get_bignum(&m, sensitive_data.server_key->rsa->iqmp);
1106 		buffer_get_bignum(&m, sensitive_data.server_key->rsa->p);
1107 		buffer_get_bignum(&m, sensitive_data.server_key->rsa->q);
1108 		if (rsa_generate_additional_parameters(
1109 		    sensitive_data.server_key->rsa) != 0)
1110 			fatal("%s: rsa_generate_additional_parameters "
1111 			    "error", __func__);
1112 #else
1113 		fatal("ssh1 not supported");
1114 #endif
1115 	}
1116 
1117 #if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
1118 	rexec_recv_rng_seed(&m);
1119 #endif
1120 
1121 	buffer_free(&m);
1122 
1123 	debug3("%s: done", __func__);
1124 }
1125 
1126 /* Accept a connection from inetd */
1127 static void
1128 server_accept_inetd(int *sock_in, int *sock_out)
1129 {
1130 	int fd;
1131 
1132 	startup_pipe = -1;
1133 	if (rexeced_flag) {
1134 		close(REEXEC_CONFIG_PASS_FD);
1135 		*sock_in = *sock_out = dup(STDIN_FILENO);
1136 		if (!debug_flag) {
1137 			startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
1138 			close(REEXEC_STARTUP_PIPE_FD);
1139 		}
1140 	} else {
1141 		*sock_in = dup(STDIN_FILENO);
1142 		*sock_out = dup(STDOUT_FILENO);
1143 	}
1144 	/*
1145 	 * We intentionally do not close the descriptors 0, 1, and 2
1146 	 * as our code for setting the descriptors won't work if
1147 	 * ttyfd happens to be one of those.
1148 	 */
1149 	if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1150 		dup2(fd, STDIN_FILENO);
1151 		dup2(fd, STDOUT_FILENO);
1152 		if (!log_stderr)
1153 			dup2(fd, STDERR_FILENO);
1154 		if (fd > (log_stderr ? STDERR_FILENO : STDOUT_FILENO))
1155 			close(fd);
1156 	}
1157 	debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
1158 }
1159 
1160 /*
1161  * Listen for TCP connections
1162  */
1163 static void
1164 server_listen(void)
1165 {
1166 	int ret, listen_sock, on = 1;
1167 	struct addrinfo *ai;
1168 	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1169 	int socksize;
1170 	socklen_t len;
1171 
1172 	for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
1173 		if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1174 			continue;
1175 		if (num_listen_socks >= MAX_LISTEN_SOCKS)
1176 			fatal("Too many listen sockets. "
1177 			    "Enlarge MAX_LISTEN_SOCKS");
1178 		if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1179 		    ntop, sizeof(ntop), strport, sizeof(strport),
1180 		    NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1181 			error("getnameinfo failed: %.100s",
1182 			    ssh_gai_strerror(ret));
1183 			continue;
1184 		}
1185 		/* Create socket for listening. */
1186 		listen_sock = socket(ai->ai_family, ai->ai_socktype,
1187 		    ai->ai_protocol);
1188 		if (listen_sock < 0) {
1189 			/* kernel may not support ipv6 */
1190 			verbose("socket: %.100s", strerror(errno));
1191 			continue;
1192 		}
1193 		if (set_nonblock(listen_sock) == -1) {
1194 			close(listen_sock);
1195 			continue;
1196 		}
1197 		/*
1198 		 * Set socket options.
1199 		 * Allow local port reuse in TIME_WAIT.
1200 		 */
1201 		if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
1202 		    &on, sizeof(on)) == -1)
1203 			error("setsockopt SO_REUSEADDR: %s", strerror(errno));
1204 
1205 		/* Only communicate in IPv6 over AF_INET6 sockets. */
1206 		if (ai->ai_family == AF_INET6)
1207 			sock_set_v6only(listen_sock);
1208 
1209 		debug("Bind to port %s on %s.", strport, ntop);
1210 
1211 		len = sizeof(socksize);
1212 		getsockopt(listen_sock, SOL_SOCKET, SO_RCVBUF, &socksize, &len);
1213 		debug("Server TCP RWIN socket size: %d", socksize);
1214 
1215 		/* Bind the socket to the desired port. */
1216 		if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1217 			error("Bind to port %s on %s failed: %.200s.",
1218 			    strport, ntop, strerror(errno));
1219 			close(listen_sock);
1220 			continue;
1221 		}
1222 		listen_socks[num_listen_socks] = listen_sock;
1223 		num_listen_socks++;
1224 
1225 		/* Start listening on the port. */
1226 		if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1227 			fatal("listen on [%s]:%s: %.100s",
1228 			    ntop, strport, strerror(errno));
1229 		logit("Server listening on %s port %s.", ntop, strport);
1230 	}
1231 	freeaddrinfo(options.listen_addrs);
1232 
1233 	if (!num_listen_socks)
1234 		fatal("Cannot bind any address.");
1235 }
1236 
1237 /*
1238  * The main TCP accept loop. Note that, for the non-debug case, returns
1239  * from this function are in a forked subprocess.
1240  */
1241 static void
1242 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1243 {
1244 	fd_set *fdset;
1245 	int i, j, ret, maxfd;
1246 	int key_used = 0, startups = 0;
1247 	int startup_p[2] = { -1 , -1 };
1248 	struct sockaddr_storage from;
1249 	socklen_t fromlen;
1250 	pid_t pid;
1251 	u_char rnd[256];
1252 
1253 	/* setup fd set for accept */
1254 	fdset = NULL;
1255 	maxfd = 0;
1256 	for (i = 0; i < num_listen_socks; i++)
1257 		if (listen_socks[i] > maxfd)
1258 			maxfd = listen_socks[i];
1259 	/* pipes connected to unauthenticated childs */
1260 	startup_pipes = xcalloc(options.max_startups, sizeof(int));
1261 	for (i = 0; i < options.max_startups; i++)
1262 		startup_pipes[i] = -1;
1263 
1264 	/*
1265 	 * Stay listening for connections until the system crashes or
1266 	 * the daemon is killed with a signal.
1267 	 */
1268 	for (;;) {
1269 		if (received_sighup)
1270 			sighup_restart();
1271 		if (fdset != NULL)
1272 			free(fdset);
1273 		fdset = (fd_set *)xcalloc(howmany(maxfd + 1, NFDBITS),
1274 		    sizeof(fd_mask));
1275 
1276 		for (i = 0; i < num_listen_socks; i++)
1277 			FD_SET(listen_socks[i], fdset);
1278 		for (i = 0; i < options.max_startups; i++)
1279 			if (startup_pipes[i] != -1)
1280 				FD_SET(startup_pipes[i], fdset);
1281 
1282 		/* Wait in select until there is a connection. */
1283 		ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1284 		if (ret < 0 && errno != EINTR)
1285 			error("select: %.100s", strerror(errno));
1286 		if (received_sigterm) {
1287 			logit("Received signal %d; terminating.",
1288 			    (int) received_sigterm);
1289 			close_listen_socks();
1290 			if (options.pid_file != NULL)
1291 				unlink(options.pid_file);
1292 			exit(received_sigterm == SIGTERM ? 0 : 255);
1293 		}
1294 		if (key_used && key_do_regen) {
1295 			generate_ephemeral_server_key();
1296 			key_used = 0;
1297 			key_do_regen = 0;
1298 		}
1299 		if (ret < 0)
1300 			continue;
1301 
1302 		for (i = 0; i < options.max_startups; i++)
1303 			if (startup_pipes[i] != -1 &&
1304 			    FD_ISSET(startup_pipes[i], fdset)) {
1305 				/*
1306 				 * the read end of the pipe is ready
1307 				 * if the child has closed the pipe
1308 				 * after successful authentication
1309 				 * or if the child has died
1310 				 */
1311 				close(startup_pipes[i]);
1312 				startup_pipes[i] = -1;
1313 				startups--;
1314 			}
1315 		for (i = 0; i < num_listen_socks; i++) {
1316 			if (!FD_ISSET(listen_socks[i], fdset))
1317 				continue;
1318 			fromlen = sizeof(from);
1319 			*newsock = accept(listen_socks[i],
1320 			    (struct sockaddr *)&from, &fromlen);
1321 			if (*newsock < 0) {
1322 				if (errno != EINTR && errno != EWOULDBLOCK &&
1323 				    errno != ECONNABORTED && errno != EAGAIN)
1324 					error("accept: %.100s",
1325 					    strerror(errno));
1326 				if (errno == EMFILE || errno == ENFILE)
1327 					usleep(100 * 1000);
1328 				continue;
1329 			}
1330 			if (unset_nonblock(*newsock) == -1) {
1331 				close(*newsock);
1332 				continue;
1333 			}
1334 			if (drop_connection(startups) == 1) {
1335 				debug("drop connection #%d", startups);
1336 				close(*newsock);
1337 				continue;
1338 			}
1339 			if (pipe(startup_p) == -1) {
1340 				close(*newsock);
1341 				continue;
1342 			}
1343 
1344 			if (rexec_flag && socketpair(AF_UNIX,
1345 			    SOCK_STREAM, 0, config_s) == -1) {
1346 				error("reexec socketpair: %s",
1347 				    strerror(errno));
1348 				close(*newsock);
1349 				close(startup_p[0]);
1350 				close(startup_p[1]);
1351 				continue;
1352 			}
1353 
1354 			for (j = 0; j < options.max_startups; j++)
1355 				if (startup_pipes[j] == -1) {
1356 					startup_pipes[j] = startup_p[0];
1357 					if (maxfd < startup_p[0])
1358 						maxfd = startup_p[0];
1359 					startups++;
1360 					break;
1361 				}
1362 
1363 			/*
1364 			 * Got connection.  Fork a child to handle it, unless
1365 			 * we are in debugging mode.
1366 			 */
1367 			if (debug_flag) {
1368 				/*
1369 				 * In debugging mode.  Close the listening
1370 				 * socket, and start processing the
1371 				 * connection without forking.
1372 				 */
1373 				debug("Server will not fork when running in debugging mode.");
1374 				close_listen_socks();
1375 				*sock_in = *newsock;
1376 				*sock_out = *newsock;
1377 				close(startup_p[0]);
1378 				close(startup_p[1]);
1379 				startup_pipe = -1;
1380 				pid = getpid();
1381 				if (rexec_flag) {
1382 					send_rexec_state(config_s[0],
1383 					    &cfg);
1384 					close(config_s[0]);
1385 				}
1386 				break;
1387 			}
1388 
1389 			/*
1390 			 * Normal production daemon.  Fork, and have
1391 			 * the child process the connection. The
1392 			 * parent continues listening.
1393 			 */
1394 			platform_pre_fork();
1395 			if ((pid = fork()) == 0) {
1396 				/*
1397 				 * Child.  Close the listening and
1398 				 * max_startup sockets.  Start using
1399 				 * the accepted socket. Reinitialize
1400 				 * logging (since our pid has changed).
1401 				 * We break out of the loop to handle
1402 				 * the connection.
1403 				 */
1404 				platform_post_fork_child();
1405 				startup_pipe = startup_p[1];
1406 				close_startup_pipes();
1407 				close_listen_socks();
1408 				*sock_in = *newsock;
1409 				*sock_out = *newsock;
1410 				log_init(__progname,
1411 				    options.log_level,
1412 				    options.log_facility,
1413 				    log_stderr);
1414 				if (rexec_flag)
1415 					close(config_s[0]);
1416 				break;
1417 			}
1418 
1419 			/* Parent.  Stay in the loop. */
1420 			platform_post_fork_parent(pid);
1421 			if (pid < 0)
1422 				error("fork: %.100s", strerror(errno));
1423 			else
1424 				debug("Forked child %ld.", (long)pid);
1425 
1426 			close(startup_p[1]);
1427 
1428 			if (rexec_flag) {
1429 				send_rexec_state(config_s[0], &cfg);
1430 				close(config_s[0]);
1431 				close(config_s[1]);
1432 			}
1433 
1434 			/*
1435 			 * Mark that the key has been used (it
1436 			 * was "given" to the child).
1437 			 */
1438 			if ((options.protocol & SSH_PROTO_1) &&
1439 			    key_used == 0) {
1440 				/* Schedule server key regeneration alarm. */
1441 				signal(SIGALRM, key_regeneration_alarm);
1442 				alarm(options.key_regeneration_time);
1443 				key_used = 1;
1444 			}
1445 
1446 			close(*newsock);
1447 
1448 			/*
1449 			 * Ensure that our random state differs
1450 			 * from that of the child
1451 			 */
1452 			arc4random_stir();
1453 			arc4random_buf(rnd, sizeof(rnd));
1454 #ifdef WITH_OPENSSL
1455 			RAND_seed(rnd, sizeof(rnd));
1456 #endif
1457 			explicit_bzero(rnd, sizeof(rnd));
1458 		}
1459 
1460 		/* child process check (or debug mode) */
1461 		if (num_listen_socks < 0)
1462 			break;
1463 	}
1464 }
1465 
1466 
1467 /*
1468  * Main program for the daemon.
1469  */
1470 int
1471 main(int ac, char **av)
1472 {
1473 	extern char *optarg;
1474 	extern int optind;
1475 	int r, opt, i, j, on = 1;
1476 	int sock_in = -1, sock_out = -1, newsock = -1;
1477 	const char *remote_ip;
1478 	int remote_port;
1479 	char *fp, *line, *logfile = NULL;
1480 	int config_s[2] = { -1 , -1 };
1481 	u_int n;
1482 	u_int64_t ibytes, obytes;
1483 	mode_t new_umask;
1484 	Key *key;
1485 	Key *pubkey;
1486 	int keytype;
1487 	Authctxt *authctxt;
1488 	struct connection_info *connection_info = get_connection_info(0, 0);
1489 
1490 #ifdef HAVE_SECUREWARE
1491 	(void)set_auth_parameters(ac, av);
1492 #endif
1493 	__progname = ssh_get_progname(av[0]);
1494 
1495 	/* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1496 	saved_argc = ac;
1497 	rexec_argc = ac;
1498 	saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1499 	for (i = 0; i < ac; i++)
1500 		saved_argv[i] = xstrdup(av[i]);
1501 	saved_argv[i] = NULL;
1502 
1503 #ifndef HAVE_SETPROCTITLE
1504 	/* Prepare for later setproctitle emulation */
1505 	compat_init_setproctitle(ac, av);
1506 	av = saved_argv;
1507 #endif
1508 
1509 	if (geteuid() == 0 && setgroups(0, NULL) == -1)
1510 		debug("setgroups(): %.200s", strerror(errno));
1511 
1512 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1513 	sanitise_stdfd();
1514 
1515 	/* Initialize configuration options to their default values. */
1516 	initialize_server_options(&options);
1517 
1518 	/* Parse command-line arguments. */
1519 	while ((opt = getopt(ac, av, "f:p:b:k:h:g:u:o:C:dDeE:iqrtQRT46")) != -1) {
1520 		switch (opt) {
1521 		case '4':
1522 			options.address_family = AF_INET;
1523 			break;
1524 		case '6':
1525 			options.address_family = AF_INET6;
1526 			break;
1527 		case 'f':
1528 			config_file_name = optarg;
1529 			break;
1530 		case 'c':
1531 			if (options.num_host_cert_files >= MAX_HOSTCERTS) {
1532 				fprintf(stderr, "too many host certificates.\n");
1533 				exit(1);
1534 			}
1535 			options.host_cert_files[options.num_host_cert_files++] =
1536 			   derelativise_path(optarg);
1537 			break;
1538 		case 'd':
1539 			if (debug_flag == 0) {
1540 				debug_flag = 1;
1541 				options.log_level = SYSLOG_LEVEL_DEBUG1;
1542 			} else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1543 				options.log_level++;
1544 			break;
1545 		case 'D':
1546 			no_daemon_flag = 1;
1547 			break;
1548 		case 'E':
1549 			logfile = xstrdup(optarg);
1550 			/* FALLTHROUGH */
1551 		case 'e':
1552 			log_stderr = 1;
1553 			break;
1554 		case 'i':
1555 			inetd_flag = 1;
1556 			break;
1557 		case 'r':
1558 			rexec_flag = 0;
1559 			break;
1560 		case 'R':
1561 			rexeced_flag = 1;
1562 			inetd_flag = 1;
1563 			break;
1564 		case 'Q':
1565 			/* ignored */
1566 			break;
1567 		case 'q':
1568 			options.log_level = SYSLOG_LEVEL_QUIET;
1569 			break;
1570 		case 'b':
1571 			options.server_key_bits = (int)strtonum(optarg, 256,
1572 			    32768, NULL);
1573 			break;
1574 		case 'p':
1575 			options.ports_from_cmdline = 1;
1576 			if (options.num_ports >= MAX_PORTS) {
1577 				fprintf(stderr, "too many ports.\n");
1578 				exit(1);
1579 			}
1580 			options.ports[options.num_ports++] = a2port(optarg);
1581 			if (options.ports[options.num_ports-1] <= 0) {
1582 				fprintf(stderr, "Bad port number.\n");
1583 				exit(1);
1584 			}
1585 			break;
1586 		case 'g':
1587 			if ((options.login_grace_time = convtime(optarg)) == -1) {
1588 				fprintf(stderr, "Invalid login grace time.\n");
1589 				exit(1);
1590 			}
1591 			break;
1592 		case 'k':
1593 			if ((options.key_regeneration_time = convtime(optarg)) == -1) {
1594 				fprintf(stderr, "Invalid key regeneration interval.\n");
1595 				exit(1);
1596 			}
1597 			break;
1598 		case 'h':
1599 			if (options.num_host_key_files >= MAX_HOSTKEYS) {
1600 				fprintf(stderr, "too many host keys.\n");
1601 				exit(1);
1602 			}
1603 			options.host_key_files[options.num_host_key_files++] =
1604 			   derelativise_path(optarg);
1605 			break;
1606 		case 't':
1607 			test_flag = 1;
1608 			break;
1609 		case 'T':
1610 			test_flag = 2;
1611 			break;
1612 		case 'C':
1613 			if (parse_server_match_testspec(connection_info,
1614 			    optarg) == -1)
1615 				exit(1);
1616 			break;
1617 		case 'u':
1618 			utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
1619 			if (utmp_len > HOST_NAME_MAX+1) {
1620 				fprintf(stderr, "Invalid utmp length.\n");
1621 				exit(1);
1622 			}
1623 			break;
1624 		case 'o':
1625 			line = xstrdup(optarg);
1626 			if (process_server_config_line(&options, line,
1627 			    "command-line", 0, NULL, NULL) != 0)
1628 				exit(1);
1629 			free(line);
1630 			break;
1631 		case '?':
1632 		default:
1633 			usage();
1634 			break;
1635 		}
1636 	}
1637 	if (rexeced_flag || inetd_flag)
1638 		rexec_flag = 0;
1639 	if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1640 		fatal("sshd re-exec requires execution with an absolute path");
1641 	if (rexeced_flag)
1642 		closefrom(REEXEC_MIN_FREE_FD);
1643 	else
1644 		closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1645 
1646 #ifdef WITH_OPENSSL
1647 	OpenSSL_add_all_algorithms();
1648 #endif
1649 
1650 	/* If requested, redirect the logs to the specified logfile. */
1651 	if (logfile != NULL) {
1652 		log_redirect_stderr_to(logfile);
1653 		free(logfile);
1654 	}
1655 	/*
1656 	 * Force logging to stderr until we have loaded the private host
1657 	 * key (unless started from inetd)
1658 	 */
1659 	log_init(__progname,
1660 	    options.log_level == SYSLOG_LEVEL_NOT_SET ?
1661 	    SYSLOG_LEVEL_INFO : options.log_level,
1662 	    options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1663 	    SYSLOG_FACILITY_AUTH : options.log_facility,
1664 	    log_stderr || !inetd_flag);
1665 
1666 	/*
1667 	 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1668 	 * root's environment
1669 	 */
1670 	if (getenv("KRB5CCNAME") != NULL)
1671 		(void) unsetenv("KRB5CCNAME");
1672 
1673 #ifdef _UNICOS
1674 	/* Cray can define user privs drop all privs now!
1675 	 * Not needed on PRIV_SU systems!
1676 	 */
1677 	drop_cray_privs();
1678 #endif
1679 
1680 	sensitive_data.server_key = NULL;
1681 	sensitive_data.ssh1_host_key = NULL;
1682 	sensitive_data.have_ssh1_key = 0;
1683 	sensitive_data.have_ssh2_key = 0;
1684 
1685 	/*
1686 	 * If we're doing an extended config test, make sure we have all of
1687 	 * the parameters we need.  If we're not doing an extended test,
1688 	 * do not silently ignore connection test params.
1689 	 */
1690 	if (test_flag >= 2 && server_match_spec_complete(connection_info) == 0)
1691 		fatal("user, host and addr are all required when testing "
1692 		   "Match configs");
1693 	if (test_flag < 2 && server_match_spec_complete(connection_info) >= 0)
1694 		fatal("Config test connection parameter (-C) provided without "
1695 		   "test mode (-T)");
1696 
1697 	/* Fetch our configuration */
1698 	buffer_init(&cfg);
1699 	if (rexeced_flag)
1700 		recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1701 	else
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 
1723 	/*
1724 	 * Check whether there is any path through configured auth methods.
1725 	 * Unfortunately it is not possible to verify this generally before
1726 	 * daemonisation in the presence of Match block, but this catches
1727 	 * and warns for trivial misconfigurations that could break login.
1728 	 */
1729 	if (options.num_auth_methods != 0) {
1730 		if ((options.protocol & SSH_PROTO_1))
1731 			fatal("AuthenticationMethods is not supported with "
1732 			    "SSH protocol 1");
1733 		for (n = 0; n < options.num_auth_methods; n++) {
1734 			if (auth2_methods_valid(options.auth_methods[n],
1735 			    1) == 0)
1736 				break;
1737 		}
1738 		if (n >= options.num_auth_methods)
1739 			fatal("AuthenticationMethods cannot be satisfied by "
1740 			    "enabled authentication methods");
1741 	}
1742 
1743 	/* set default channel AF */
1744 	channel_set_af(options.address_family);
1745 
1746 	/* Check that there are no remaining arguments. */
1747 	if (optind < ac) {
1748 		fprintf(stderr, "Extra argument %s.\n", av[optind]);
1749 		exit(1);
1750 	}
1751 
1752 	debug("sshd version %s, %s", SSH_VERSION,
1753 #ifdef WITH_OPENSSL
1754 	    SSLeay_version(SSLEAY_VERSION)
1755 #else
1756 	    "without OpenSSL"
1757 #endif
1758 	);
1759 
1760 	/* Store privilege separation user for later use if required. */
1761 	if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1762 		if (use_privsep || options.kerberos_authentication)
1763 			fatal("Privilege separation user %s does not exist",
1764 			    SSH_PRIVSEP_USER);
1765 	} else {
1766 		explicit_bzero(privsep_pw->pw_passwd,
1767 		    strlen(privsep_pw->pw_passwd));
1768 		privsep_pw = pwcopy(privsep_pw);
1769 		free(privsep_pw->pw_passwd);
1770 		privsep_pw->pw_passwd = xstrdup("*");
1771 	}
1772 	endpwent();
1773 
1774 	/* load host keys */
1775 	sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1776 	    sizeof(Key *));
1777 	sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
1778 	    sizeof(Key *));
1779 
1780 	if (options.host_key_agent) {
1781 		if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
1782 			setenv(SSH_AUTHSOCKET_ENV_NAME,
1783 			    options.host_key_agent, 1);
1784 		if ((r = ssh_get_authentication_socket(NULL)) == 0)
1785 			have_agent = 1;
1786 		else
1787 			error("Could not connect to agent \"%s\": %s",
1788 			    options.host_key_agent, ssh_err(r));
1789 	}
1790 
1791 	for (i = 0; i < options.num_host_key_files; i++) {
1792 		if (options.host_key_files[i] == NULL)
1793 			continue;
1794 		key = key_load_private(options.host_key_files[i], "", NULL);
1795 		pubkey = key_load_public(options.host_key_files[i], NULL);
1796 		if (pubkey == NULL && key != NULL)
1797 			pubkey = key_demote(key);
1798 		sensitive_data.host_keys[i] = key;
1799 		sensitive_data.host_pubkeys[i] = pubkey;
1800 
1801 		if (key == NULL && pubkey != NULL && pubkey->type != KEY_RSA1 &&
1802 		    have_agent) {
1803 			debug("will rely on agent for hostkey %s",
1804 			    options.host_key_files[i]);
1805 			keytype = pubkey->type;
1806 		} else if (key != NULL) {
1807 			keytype = key->type;
1808 		} else {
1809 			error("Could not load host key: %s",
1810 			    options.host_key_files[i]);
1811 			sensitive_data.host_keys[i] = NULL;
1812 			sensitive_data.host_pubkeys[i] = NULL;
1813 			continue;
1814 		}
1815 
1816 		switch (keytype) {
1817 		case KEY_RSA1:
1818 			sensitive_data.ssh1_host_key = key;
1819 			sensitive_data.have_ssh1_key = 1;
1820 			break;
1821 		case KEY_RSA:
1822 		case KEY_DSA:
1823 		case KEY_ECDSA:
1824 		case KEY_ED25519:
1825 			if (have_agent || key != NULL)
1826 				sensitive_data.have_ssh2_key = 1;
1827 			break;
1828 		}
1829 		if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash,
1830 		    SSH_FP_DEFAULT)) == NULL)
1831 			fatal("sshkey_fingerprint failed");
1832 		debug("%s host key #%d: %s %s",
1833 		    key ? "private" : "agent", i, keytype == KEY_RSA1 ?
1834 		    sshkey_type(pubkey) : sshkey_ssh_name(pubkey), fp);
1835 		free(fp);
1836 	}
1837 	if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1838 		logit("Disabling protocol version 1. Could not load host key");
1839 		options.protocol &= ~SSH_PROTO_1;
1840 	}
1841 	if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1842 		logit("Disabling protocol version 2. Could not load host key");
1843 		options.protocol &= ~SSH_PROTO_2;
1844 	}
1845 	if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1846 		logit("sshd: no hostkeys available -- exiting.");
1847 		exit(1);
1848 	}
1849 
1850 	/*
1851 	 * Load certificates. They are stored in an array at identical
1852 	 * indices to the public keys that they relate to.
1853 	 */
1854 	sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
1855 	    sizeof(Key *));
1856 	for (i = 0; i < options.num_host_key_files; i++)
1857 		sensitive_data.host_certificates[i] = NULL;
1858 
1859 	for (i = 0; i < options.num_host_cert_files; i++) {
1860 		if (options.host_cert_files[i] == NULL)
1861 			continue;
1862 		key = key_load_public(options.host_cert_files[i], NULL);
1863 		if (key == NULL) {
1864 			error("Could not load host certificate: %s",
1865 			    options.host_cert_files[i]);
1866 			continue;
1867 		}
1868 		if (!key_is_cert(key)) {
1869 			error("Certificate file is not a certificate: %s",
1870 			    options.host_cert_files[i]);
1871 			key_free(key);
1872 			continue;
1873 		}
1874 		/* Find matching private key */
1875 		for (j = 0; j < options.num_host_key_files; j++) {
1876 			if (key_equal_public(key,
1877 			    sensitive_data.host_keys[j])) {
1878 				sensitive_data.host_certificates[j] = key;
1879 				break;
1880 			}
1881 		}
1882 		if (j >= options.num_host_key_files) {
1883 			error("No matching private key for certificate: %s",
1884 			    options.host_cert_files[i]);
1885 			key_free(key);
1886 			continue;
1887 		}
1888 		sensitive_data.host_certificates[j] = key;
1889 		debug("host certificate: #%d type %d %s", j, key->type,
1890 		    key_type(key));
1891 	}
1892 
1893 #ifdef WITH_SSH1
1894 	/* Check certain values for sanity. */
1895 	if (options.protocol & SSH_PROTO_1) {
1896 		if (options.server_key_bits < 512 ||
1897 		    options.server_key_bits > 32768) {
1898 			fprintf(stderr, "Bad server key size.\n");
1899 			exit(1);
1900 		}
1901 		/*
1902 		 * Check that server and host key lengths differ sufficiently. This
1903 		 * is necessary to make double encryption work with rsaref. Oh, I
1904 		 * hate software patents. I dont know if this can go? Niels
1905 		 */
1906 		if (options.server_key_bits >
1907 		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
1908 		    SSH_KEY_BITS_RESERVED && options.server_key_bits <
1909 		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1910 		    SSH_KEY_BITS_RESERVED) {
1911 			options.server_key_bits =
1912 			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1913 			    SSH_KEY_BITS_RESERVED;
1914 			debug("Forcing server key to %d bits to make it differ from host key.",
1915 			    options.server_key_bits);
1916 		}
1917 	}
1918 #endif
1919 
1920 	if (use_privsep) {
1921 		struct stat st;
1922 
1923 		if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1924 		    (S_ISDIR(st.st_mode) == 0))
1925 			fatal("Missing privilege separation directory: %s",
1926 			    _PATH_PRIVSEP_CHROOT_DIR);
1927 
1928 #ifdef HAVE_CYGWIN
1929 		if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1930 		    (st.st_uid != getuid () ||
1931 		    (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1932 #else
1933 		if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1934 #endif
1935 			fatal("%s must be owned by root and not group or "
1936 			    "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1937 	}
1938 
1939 	if (test_flag > 1) {
1940 		if (server_match_spec_complete(connection_info) == 1)
1941 			parse_server_match_config(&options, connection_info);
1942 		dump_config(&options);
1943 	}
1944 
1945 	/* Configuration looks good, so exit if in test mode. */
1946 	if (test_flag)
1947 		exit(0);
1948 
1949 	/*
1950 	 * Clear out any supplemental groups we may have inherited.  This
1951 	 * prevents inadvertent creation of files with bad modes (in the
1952 	 * portable version at least, it's certainly possible for PAM
1953 	 * to create a file, and we can't control the code in every
1954 	 * module which might be used).
1955 	 */
1956 	if (setgroups(0, NULL) < 0)
1957 		debug("setgroups() failed: %.200s", strerror(errno));
1958 
1959 	if (rexec_flag) {
1960 		rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1961 		for (i = 0; i < rexec_argc; i++) {
1962 			debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1963 			rexec_argv[i] = saved_argv[i];
1964 		}
1965 		rexec_argv[rexec_argc] = "-R";
1966 		rexec_argv[rexec_argc + 1] = NULL;
1967 	}
1968 
1969 	/* Ensure that umask disallows at least group and world write */
1970 	new_umask = umask(0077) | 0022;
1971 	(void) umask(new_umask);
1972 
1973 	/* Initialize the log (it is reinitialized below in case we forked). */
1974 	if (debug_flag && (!inetd_flag || rexeced_flag))
1975 		log_stderr = 1;
1976 	log_init(__progname, options.log_level, options.log_facility, log_stderr);
1977 
1978 	/*
1979 	 * If not in debugging mode, and not started from inetd, disconnect
1980 	 * from the controlling terminal, and fork.  The original process
1981 	 * exits.
1982 	 */
1983 	if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1984 #ifdef TIOCNOTTY
1985 		int fd;
1986 #endif /* TIOCNOTTY */
1987 		if (daemon(0, 0) < 0)
1988 			fatal("daemon() failed: %.200s", strerror(errno));
1989 
1990 		/* Disconnect from the controlling tty. */
1991 #ifdef TIOCNOTTY
1992 		fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1993 		if (fd >= 0) {
1994 			(void) ioctl(fd, TIOCNOTTY, NULL);
1995 			close(fd);
1996 		}
1997 #endif /* TIOCNOTTY */
1998 	}
1999 	/* Reinitialize the log (because of the fork above). */
2000 	log_init(__progname, options.log_level, options.log_facility, log_stderr);
2001 
2002 	/* Avoid killing the process in high-pressure swapping environments. */
2003 	if (!inetd_flag && madvise(NULL, 0, MADV_PROTECT) != 0)
2004 		debug("madvise(): %.200s", strerror(errno));
2005 
2006 	/* Chdir to the root directory so that the current disk can be
2007 	   unmounted if desired. */
2008 	if (chdir("/") == -1)
2009 		error("chdir(\"/\"): %s", strerror(errno));
2010 
2011 	/* ignore SIGPIPE */
2012 	signal(SIGPIPE, SIG_IGN);
2013 
2014 	/* Get a connection, either from inetd or a listening TCP socket */
2015 	if (inetd_flag) {
2016 		server_accept_inetd(&sock_in, &sock_out);
2017 	} else {
2018 		platform_pre_listen();
2019 		server_listen();
2020 
2021 		if (options.protocol & SSH_PROTO_1)
2022 			generate_ephemeral_server_key();
2023 
2024 		signal(SIGHUP, sighup_handler);
2025 		signal(SIGCHLD, main_sigchld_handler);
2026 		signal(SIGTERM, sigterm_handler);
2027 		signal(SIGQUIT, sigterm_handler);
2028 
2029 		/*
2030 		 * Write out the pid file after the sigterm handler
2031 		 * is setup and the listen sockets are bound
2032 		 */
2033 		if (options.pid_file != NULL && !debug_flag) {
2034 			FILE *f = fopen(options.pid_file, "w");
2035 
2036 			if (f == NULL) {
2037 				error("Couldn't create pid file \"%s\": %s",
2038 				    options.pid_file, strerror(errno));
2039 			} else {
2040 				fprintf(f, "%ld\n", (long) getpid());
2041 				fclose(f);
2042 			}
2043 		}
2044 
2045 		/* Accept a connection and return in a forked child */
2046 		server_accept_loop(&sock_in, &sock_out,
2047 		    &newsock, config_s);
2048 	}
2049 
2050 	/* This is the child processing a new connection. */
2051 	setproctitle("%s", "[accepted]");
2052 
2053 	/*
2054 	 * Create a new session and process group since the 4.4BSD
2055 	 * setlogin() affects the entire process group.  We don't
2056 	 * want the child to be able to affect the parent.
2057 	 */
2058 #if !defined(SSHD_ACQUIRES_CTTY)
2059 	/*
2060 	 * If setsid is called, on some platforms sshd will later acquire a
2061 	 * controlling terminal which will result in "could not set
2062 	 * controlling tty" errors.
2063 	 */
2064 	if (!debug_flag && !inetd_flag && setsid() < 0)
2065 		error("setsid: %.100s", strerror(errno));
2066 #endif
2067 
2068 	if (rexec_flag) {
2069 		int fd;
2070 
2071 		debug("rexec start in %d out %d newsock %d pipe %d sock %d",
2072 		    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
2073 		dup2(newsock, STDIN_FILENO);
2074 		dup2(STDIN_FILENO, STDOUT_FILENO);
2075 		if (startup_pipe == -1)
2076 			close(REEXEC_STARTUP_PIPE_FD);
2077 		else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) {
2078 			dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
2079 			close(startup_pipe);
2080 			startup_pipe = REEXEC_STARTUP_PIPE_FD;
2081 		}
2082 
2083 		dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
2084 		close(config_s[1]);
2085 
2086 		execv(rexec_argv[0], rexec_argv);
2087 
2088 		/* Reexec has failed, fall back and continue */
2089 		error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
2090 		recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
2091 		log_init(__progname, options.log_level,
2092 		    options.log_facility, log_stderr);
2093 
2094 		/* Clean up fds */
2095 		close(REEXEC_CONFIG_PASS_FD);
2096 		newsock = sock_out = sock_in = dup(STDIN_FILENO);
2097 		if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
2098 			dup2(fd, STDIN_FILENO);
2099 			dup2(fd, STDOUT_FILENO);
2100 			if (fd > STDERR_FILENO)
2101 				close(fd);
2102 		}
2103 		debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
2104 		    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
2105 	}
2106 
2107 	/* Executed child processes don't need these. */
2108 	fcntl(sock_out, F_SETFD, FD_CLOEXEC);
2109 	fcntl(sock_in, F_SETFD, FD_CLOEXEC);
2110 
2111 	/*
2112 	 * Disable the key regeneration alarm.  We will not regenerate the
2113 	 * key since we are no longer in a position to give it to anyone. We
2114 	 * will not restart on SIGHUP since it no longer makes sense.
2115 	 */
2116 	alarm(0);
2117 	signal(SIGALRM, SIG_DFL);
2118 	signal(SIGHUP, SIG_DFL);
2119 	signal(SIGTERM, SIG_DFL);
2120 	signal(SIGQUIT, SIG_DFL);
2121 	signal(SIGCHLD, SIG_DFL);
2122 	signal(SIGINT, SIG_DFL);
2123 
2124 #ifdef __FreeBSD__
2125 	/*
2126 	 * Initialize the resolver.  This may not happen automatically
2127 	 * before privsep chroot().
2128 	 */
2129 	if ((_res.options & RES_INIT) == 0) {
2130 		debug("res_init()");
2131 		res_init();
2132 	}
2133 #ifdef GSSAPI
2134 	/*
2135 	 * Force GSS-API to parse its configuration and load any
2136 	 * mechanism plugins.
2137 	 */
2138 	{
2139 		gss_OID_set mechs;
2140 		OM_uint32 minor_status;
2141 		gss_indicate_mechs(&minor_status, &mechs);
2142 		gss_release_oid_set(&minor_status, &mechs);
2143 	}
2144 #endif
2145 #endif
2146 
2147 	/*
2148 	 * Register our connection.  This turns encryption off because we do
2149 	 * not have a key.
2150 	 */
2151 	packet_set_connection(sock_in, sock_out);
2152 	packet_set_server();
2153 
2154 	/* Set SO_KEEPALIVE if requested. */
2155 	if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
2156 	    setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
2157 		error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
2158 
2159 	if ((remote_port = get_remote_port()) < 0) {
2160 		debug("get_remote_port failed");
2161 		cleanup_exit(255);
2162 	}
2163 
2164 	/*
2165 	 * We use get_canonical_hostname with usedns = 0 instead of
2166 	 * get_remote_ipaddr here so IP options will be checked.
2167 	 */
2168 	(void) get_canonical_hostname(0);
2169 	/*
2170 	 * The rest of the code depends on the fact that
2171 	 * get_remote_ipaddr() caches the remote ip, even if
2172 	 * the socket goes away.
2173 	 */
2174 	remote_ip = get_remote_ipaddr();
2175 
2176 #ifdef SSH_AUDIT_EVENTS
2177 	audit_connection_from(remote_ip, remote_port);
2178 #endif
2179 #ifdef LIBWRAP
2180 	allow_severity = options.log_facility|LOG_INFO;
2181 	deny_severity = options.log_facility|LOG_WARNING;
2182 	/* Check whether logins are denied from this host. */
2183 	if (packet_connection_is_on_socket()) {
2184 		struct request_info req;
2185 
2186 		request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
2187 		fromhost(&req);
2188 
2189 		if (!hosts_access(&req)) {
2190 			debug("Connection refused by tcp wrapper");
2191 			refuse(&req);
2192 			/* NOTREACHED */
2193 			fatal("libwrap refuse returns");
2194 		}
2195 	}
2196 #endif /* LIBWRAP */
2197 
2198 	/* Log the connection. */
2199 	verbose("Connection from %s port %d on %s port %d",
2200 	    remote_ip, remote_port,
2201 	    get_local_ipaddr(sock_in), get_local_port());
2202 
2203 	/*
2204 	 * We don't want to listen forever unless the other side
2205 	 * successfully authenticates itself.  So we set up an alarm which is
2206 	 * cleared after successful authentication.  A limit of zero
2207 	 * indicates no limit. Note that we don't set the alarm in debugging
2208 	 * mode; it is just annoying to have the server exit just when you
2209 	 * are about to discover the bug.
2210 	 */
2211 	signal(SIGALRM, grace_alarm_handler);
2212 	if (!debug_flag)
2213 		alarm(options.login_grace_time);
2214 
2215 	sshd_exchange_identification(sock_in, sock_out);
2216 
2217 	/* In inetd mode, generate ephemeral key only for proto 1 connections */
2218 	if (!compat20 && inetd_flag && sensitive_data.server_key == NULL)
2219 		generate_ephemeral_server_key();
2220 
2221 	packet_set_nonblocking();
2222 
2223 	/* allocate authentication context */
2224 	authctxt = xcalloc(1, sizeof(*authctxt));
2225 
2226 	authctxt->loginmsg = &loginmsg;
2227 
2228 	/* XXX global for cleanup, access from other modules */
2229 	the_authctxt = authctxt;
2230 
2231 	/* prepare buffer to collect messages to display to user after login */
2232 	buffer_init(&loginmsg);
2233 	auth_debug_reset();
2234 
2235 	if (use_privsep) {
2236 		if (privsep_preauth(authctxt) == 1)
2237 			goto authenticated;
2238 	} else if (compat20 && have_agent) {
2239 		if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) {
2240 			error("Unable to get agent socket: %s", ssh_err(r));
2241 			have_agent = 0;
2242 		}
2243 	}
2244 
2245 	/* perform the key exchange */
2246 	/* authenticate user and start session */
2247 	if (compat20) {
2248 		do_ssh2_kex();
2249 		do_authentication2(authctxt);
2250 	} else {
2251 #ifdef WITH_SSH1
2252 		do_ssh1_kex();
2253 		do_authentication(authctxt);
2254 #else
2255 		fatal("ssh1 not supported");
2256 #endif
2257 	}
2258 	/*
2259 	 * If we use privilege separation, the unprivileged child transfers
2260 	 * the current keystate and exits
2261 	 */
2262 	if (use_privsep) {
2263 		mm_send_keystate(pmonitor);
2264 		exit(0);
2265 	}
2266 
2267  authenticated:
2268 	/*
2269 	 * Cancel the alarm we set to limit the time taken for
2270 	 * authentication.
2271 	 */
2272 	alarm(0);
2273 	signal(SIGALRM, SIG_DFL);
2274 	authctxt->authenticated = 1;
2275 	if (startup_pipe != -1) {
2276 		close(startup_pipe);
2277 		startup_pipe = -1;
2278 	}
2279 
2280 #ifdef SSH_AUDIT_EVENTS
2281 	audit_event(SSH_AUTH_SUCCESS);
2282 #endif
2283 
2284 #ifdef GSSAPI
2285 	if (options.gss_authentication) {
2286 		temporarily_use_uid(authctxt->pw);
2287 		ssh_gssapi_storecreds();
2288 		restore_uid();
2289 	}
2290 #endif
2291 #ifdef USE_PAM
2292 	if (options.use_pam) {
2293 		do_pam_setcred(1);
2294 		do_pam_session();
2295 	}
2296 #endif
2297 
2298 	/*
2299 	 * In privilege separation, we fork another child and prepare
2300 	 * file descriptor passing.
2301 	 */
2302 	if (use_privsep) {
2303 		privsep_postauth(authctxt);
2304 		/* the monitor process [priv] will not return */
2305 		if (!compat20)
2306 			destroy_sensitive_data();
2307 	}
2308 
2309 	packet_set_timeout(options.client_alive_interval,
2310 	    options.client_alive_count_max);
2311 
2312 	/* Try to send all our hostkeys to the client */
2313 	if (compat20)
2314 		notify_hostkeys(active_state);
2315 
2316 	/* Start session. */
2317 	do_authenticated(authctxt);
2318 
2319 	/* The connection has been terminated. */
2320 	packet_get_bytes(&ibytes, &obytes);
2321 	verbose("Transferred: sent %llu, received %llu bytes",
2322 	    (unsigned long long)obytes, (unsigned long long)ibytes);
2323 
2324 	verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
2325 
2326 #ifdef USE_PAM
2327 	if (options.use_pam)
2328 		finish_pam();
2329 #endif /* USE_PAM */
2330 
2331 #ifdef SSH_AUDIT_EVENTS
2332 	PRIVSEP(audit_event(SSH_CONNECTION_CLOSE));
2333 #endif
2334 
2335 	packet_close();
2336 
2337 	if (use_privsep)
2338 		mm_terminate();
2339 
2340 	exit(0);
2341 }
2342 
2343 #ifdef WITH_SSH1
2344 /*
2345  * Decrypt session_key_int using our private server key and private host key
2346  * (key with larger modulus first).
2347  */
2348 int
2349 ssh1_session_key(BIGNUM *session_key_int)
2350 {
2351 	int rsafail = 0;
2352 
2353 	if (BN_cmp(sensitive_data.server_key->rsa->n,
2354 	    sensitive_data.ssh1_host_key->rsa->n) > 0) {
2355 		/* Server key has bigger modulus. */
2356 		if (BN_num_bits(sensitive_data.server_key->rsa->n) <
2357 		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
2358 		    SSH_KEY_BITS_RESERVED) {
2359 			fatal("do_connection: %s: "
2360 			    "server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
2361 			    get_remote_ipaddr(),
2362 			    BN_num_bits(sensitive_data.server_key->rsa->n),
2363 			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2364 			    SSH_KEY_BITS_RESERVED);
2365 		}
2366 		if (rsa_private_decrypt(session_key_int, session_key_int,
2367 		    sensitive_data.server_key->rsa) != 0)
2368 			rsafail++;
2369 		if (rsa_private_decrypt(session_key_int, session_key_int,
2370 		    sensitive_data.ssh1_host_key->rsa) != 0)
2371 			rsafail++;
2372 	} else {
2373 		/* Host key has bigger modulus (or they are equal). */
2374 		if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
2375 		    BN_num_bits(sensitive_data.server_key->rsa->n) +
2376 		    SSH_KEY_BITS_RESERVED) {
2377 			fatal("do_connection: %s: "
2378 			    "host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
2379 			    get_remote_ipaddr(),
2380 			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2381 			    BN_num_bits(sensitive_data.server_key->rsa->n),
2382 			    SSH_KEY_BITS_RESERVED);
2383 		}
2384 		if (rsa_private_decrypt(session_key_int, session_key_int,
2385 		    sensitive_data.ssh1_host_key->rsa) != 0)
2386 			rsafail++;
2387 		if (rsa_private_decrypt(session_key_int, session_key_int,
2388 		    sensitive_data.server_key->rsa) != 0)
2389 			rsafail++;
2390 	}
2391 	return (rsafail);
2392 }
2393 
2394 /*
2395  * SSH1 key exchange
2396  */
2397 static void
2398 do_ssh1_kex(void)
2399 {
2400 	int i, len;
2401 	int rsafail = 0;
2402 	BIGNUM *session_key_int, *fake_key_int, *real_key_int;
2403 	u_char session_key[SSH_SESSION_KEY_LENGTH];
2404 	u_char fake_key_bytes[4096 / 8];
2405 	size_t fake_key_len;
2406 	u_char cookie[8];
2407 	u_int cipher_type, auth_mask, protocol_flags;
2408 
2409 	/*
2410 	 * Generate check bytes that the client must send back in the user
2411 	 * packet in order for it to be accepted; this is used to defy ip
2412 	 * spoofing attacks.  Note that this only works against somebody
2413 	 * doing IP spoofing from a remote machine; any machine on the local
2414 	 * network can still see outgoing packets and catch the random
2415 	 * cookie.  This only affects rhosts authentication, and this is one
2416 	 * of the reasons why it is inherently insecure.
2417 	 */
2418 	arc4random_buf(cookie, sizeof(cookie));
2419 
2420 	/*
2421 	 * Send our public key.  We include in the packet 64 bits of random
2422 	 * data that must be matched in the reply in order to prevent IP
2423 	 * spoofing.
2424 	 */
2425 	packet_start(SSH_SMSG_PUBLIC_KEY);
2426 	for (i = 0; i < 8; i++)
2427 		packet_put_char(cookie[i]);
2428 
2429 	/* Store our public server RSA key. */
2430 	packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
2431 	packet_put_bignum(sensitive_data.server_key->rsa->e);
2432 	packet_put_bignum(sensitive_data.server_key->rsa->n);
2433 
2434 	/* Store our public host RSA key. */
2435 	packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2436 	packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
2437 	packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
2438 
2439 	/* Put protocol flags. */
2440 	packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
2441 
2442 	/* Declare which ciphers we support. */
2443 	packet_put_int(cipher_mask_ssh1(0));
2444 
2445 	/* Declare supported authentication types. */
2446 	auth_mask = 0;
2447 	if (options.rhosts_rsa_authentication)
2448 		auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
2449 	if (options.rsa_authentication)
2450 		auth_mask |= 1 << SSH_AUTH_RSA;
2451 	if (options.challenge_response_authentication == 1)
2452 		auth_mask |= 1 << SSH_AUTH_TIS;
2453 	if (options.password_authentication)
2454 		auth_mask |= 1 << SSH_AUTH_PASSWORD;
2455 	packet_put_int(auth_mask);
2456 
2457 	/* Send the packet and wait for it to be sent. */
2458 	packet_send();
2459 	packet_write_wait();
2460 
2461 	debug("Sent %d bit server key and %d bit host key.",
2462 	    BN_num_bits(sensitive_data.server_key->rsa->n),
2463 	    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2464 
2465 	/* Read clients reply (cipher type and session key). */
2466 	packet_read_expect(SSH_CMSG_SESSION_KEY);
2467 
2468 	/* Get cipher type and check whether we accept this. */
2469 	cipher_type = packet_get_char();
2470 
2471 	if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
2472 		packet_disconnect("Warning: client selects unsupported cipher.");
2473 
2474 	/* Get check bytes from the packet.  These must match those we
2475 	   sent earlier with the public key packet. */
2476 	for (i = 0; i < 8; i++)
2477 		if (cookie[i] != packet_get_char())
2478 			packet_disconnect("IP Spoofing check bytes do not match.");
2479 
2480 	debug("Encryption type: %.200s", cipher_name(cipher_type));
2481 
2482 	/* Get the encrypted integer. */
2483 	if ((real_key_int = BN_new()) == NULL)
2484 		fatal("do_ssh1_kex: BN_new failed");
2485 	packet_get_bignum(real_key_int);
2486 
2487 	protocol_flags = packet_get_int();
2488 	packet_set_protocol_flags(protocol_flags);
2489 	packet_check_eom();
2490 
2491 	/* Setup a fake key in case RSA decryption fails */
2492 	if ((fake_key_int = BN_new()) == NULL)
2493 		fatal("do_ssh1_kex: BN_new failed");
2494 	fake_key_len = BN_num_bytes(real_key_int);
2495 	if (fake_key_len > sizeof(fake_key_bytes))
2496 		fake_key_len = sizeof(fake_key_bytes);
2497 	arc4random_buf(fake_key_bytes, fake_key_len);
2498 	if (BN_bin2bn(fake_key_bytes, fake_key_len, fake_key_int) == NULL)
2499 		fatal("do_ssh1_kex: BN_bin2bn failed");
2500 
2501 	/* Decrypt real_key_int using host/server keys */
2502 	rsafail = PRIVSEP(ssh1_session_key(real_key_int));
2503 	/* If decryption failed, use the fake key. Else, the real key. */
2504 	if (rsafail)
2505 		session_key_int = fake_key_int;
2506 	else
2507 		session_key_int = real_key_int;
2508 
2509 	/*
2510 	 * Extract session key from the decrypted integer.  The key is in the
2511 	 * least significant 256 bits of the integer; the first byte of the
2512 	 * key is in the highest bits.
2513 	 */
2514 	(void) BN_mask_bits(session_key_int, sizeof(session_key) * 8);
2515 	len = BN_num_bytes(session_key_int);
2516 	if (len < 0 || (u_int)len > sizeof(session_key)) {
2517 		error("do_ssh1_kex: bad session key len from %s: "
2518 		    "session_key_int %d > sizeof(session_key) %lu",
2519 		    get_remote_ipaddr(), len, (u_long)sizeof(session_key));
2520 		rsafail++;
2521 	} else {
2522 		explicit_bzero(session_key, sizeof(session_key));
2523 		BN_bn2bin(session_key_int,
2524 		    session_key + sizeof(session_key) - len);
2525 
2526 		derive_ssh1_session_id(
2527 		    sensitive_data.ssh1_host_key->rsa->n,
2528 		    sensitive_data.server_key->rsa->n,
2529 		    cookie, session_id);
2530 		/*
2531 		 * Xor the first 16 bytes of the session key with the
2532 		 * session id.
2533 		 */
2534 		for (i = 0; i < 16; i++)
2535 			session_key[i] ^= session_id[i];
2536 	}
2537 
2538 	/* Destroy the private and public keys. No longer. */
2539 	destroy_sensitive_data();
2540 
2541 	if (use_privsep)
2542 		mm_ssh1_session_id(session_id);
2543 
2544 	/* Destroy the decrypted integer.  It is no longer needed. */
2545 	BN_clear_free(real_key_int);
2546 	BN_clear_free(fake_key_int);
2547 
2548 	/* Set the session key.  From this on all communications will be encrypted. */
2549 	packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
2550 
2551 	/* Destroy our copy of the session key.  It is no longer needed. */
2552 	explicit_bzero(session_key, sizeof(session_key));
2553 
2554 	debug("Received session key; encryption turned on.");
2555 
2556 	/* Send an acknowledgment packet.  Note that this packet is sent encrypted. */
2557 	packet_start(SSH_SMSG_SUCCESS);
2558 	packet_send();
2559 	packet_write_wait();
2560 }
2561 #endif
2562 
2563 int
2564 sshd_hostkey_sign(Key *privkey, Key *pubkey, u_char **signature, size_t *slen,
2565     const u_char *data, size_t dlen, u_int flag)
2566 {
2567 	int r;
2568 	u_int xxx_slen, xxx_dlen = dlen;
2569 
2570 	if (privkey) {
2571 		if (PRIVSEP(key_sign(privkey, signature, &xxx_slen, data, xxx_dlen) < 0))
2572 			fatal("%s: key_sign failed", __func__);
2573 		if (slen)
2574 			*slen = xxx_slen;
2575 	} else if (use_privsep) {
2576 		if (mm_key_sign(pubkey, signature, &xxx_slen, data, xxx_dlen) < 0)
2577 			fatal("%s: pubkey_sign failed", __func__);
2578 		if (slen)
2579 			*slen = xxx_slen;
2580 	} else {
2581 		if ((r = ssh_agent_sign(auth_sock, pubkey, signature, slen,
2582 		    data, dlen, datafellows)) != 0)
2583 			fatal("%s: ssh_agent_sign failed: %s",
2584 			    __func__, ssh_err(r));
2585 	}
2586 	return 0;
2587 }
2588 
2589 /*
2590  * SSH2 key exchange: diffie-hellman-group1-sha1
2591  */
2592 static void
2593 do_ssh2_kex(void)
2594 {
2595 	char *myproposal[PROPOSAL_MAX] = { KEX_SERVER };
2596 	struct kex *kex;
2597 	int r;
2598 
2599 	if (options.ciphers != NULL) {
2600 		myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2601 		myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
2602 	}
2603 	myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2604 	    compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
2605 	myproposal[PROPOSAL_ENC_ALGS_STOC] =
2606 	    compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
2607 
2608 	if (options.macs != NULL) {
2609 		myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2610 		myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2611 	}
2612 	if (options.compression == COMP_NONE) {
2613 		myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2614 		myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2615 	} else if (options.compression == COMP_DELAYED) {
2616 		myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2617 		myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com";
2618 	}
2619 	if (options.kex_algorithms != NULL)
2620 		myproposal[PROPOSAL_KEX_ALGS] = options.kex_algorithms;
2621 
2622 	myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(
2623 	    myproposal[PROPOSAL_KEX_ALGS]);
2624 
2625 	if (options.rekey_limit || options.rekey_interval)
2626 		packet_set_rekey_limits((u_int32_t)options.rekey_limit,
2627 		    (time_t)options.rekey_interval);
2628 
2629 	myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal(
2630 	    list_hostkey_types());
2631 
2632 	/* start key exchange */
2633 	if ((r = kex_setup(active_state, myproposal)) != 0)
2634 		fatal("kex_setup: %s", ssh_err(r));
2635 	kex = active_state->kex;
2636 #ifdef WITH_OPENSSL
2637 	kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2638 	kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
2639 	kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2640 	kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2641 # ifdef OPENSSL_HAS_ECC
2642 	kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
2643 # endif
2644 #endif
2645 	kex->kex[KEX_C25519_SHA256] = kexc25519_server;
2646 	kex->server = 1;
2647 	kex->client_version_string=client_version_string;
2648 	kex->server_version_string=server_version_string;
2649 	kex->load_host_public_key=&get_hostkey_public_by_type;
2650 	kex->load_host_private_key=&get_hostkey_private_by_type;
2651 	kex->host_key_index=&get_hostkey_index;
2652 	kex->sign = sshd_hostkey_sign;
2653 
2654 	dispatch_run(DISPATCH_BLOCK, &kex->done, active_state);
2655 
2656 	session_id2 = kex->session_id;
2657 	session_id2_len = kex->session_id_len;
2658 
2659 #ifdef DEBUG_KEXDH
2660 	/* send 1st encrypted/maced/compressed message */
2661 	packet_start(SSH2_MSG_IGNORE);
2662 	packet_put_cstring("markus");
2663 	packet_send();
2664 	packet_write_wait();
2665 #endif
2666 	debug("KEX done");
2667 }
2668 
2669 /* server specific fatal cleanup */
2670 void
2671 cleanup_exit(int i)
2672 {
2673 	if (the_authctxt) {
2674 		do_cleanup(the_authctxt);
2675 		if (use_privsep && privsep_is_preauth &&
2676 		    pmonitor != NULL && pmonitor->m_pid > 1) {
2677 			debug("Killing privsep child %d", pmonitor->m_pid);
2678 			if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
2679 			    errno != ESRCH)
2680 				error("%s: kill(%d): %s", __func__,
2681 				    pmonitor->m_pid, strerror(errno));
2682 		}
2683 	}
2684 #ifdef SSH_AUDIT_EVENTS
2685 	/* done after do_cleanup so it can cancel the PAM auth 'thread' */
2686 	if (!use_privsep || mm_is_monitor())
2687 		audit_event(SSH_CONNECTION_ABANDON);
2688 #endif
2689 	_exit(i);
2690 }
2691