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