xref: /freebsd/crypto/openssh/sshd.c (revision 0b3105a37d7adcadcb720112fed4dc4e8040be99)
1 /* $OpenBSD: sshd.c,v 1.458 2015/08/20 22:32:42 deraadt Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
6  * This program is the ssh daemon.  It listens for connections from clients,
7  * and performs authentication, executes use commands or shell, and forwards
8  * information to/from the application to the user client over an encrypted
9  * connection.  This can also handle forwarding of X11, TCP/IP, and
10  * authentication agent connections.
11  *
12  * As far as I am concerned, the code I have written for this software
13  * can be used freely for any purpose.  Any derived versions of this
14  * software must be clearly marked as such, and if the derived work is
15  * incompatible with the protocol description in the RFC file, it must be
16  * called by a name other than "ssh" or "Secure Shell".
17  *
18  * SSH2 implementation:
19  * Privilege Separation:
20  *
21  * Copyright (c) 2000, 2001, 2002 Markus Friedl.  All rights reserved.
22  * Copyright (c) 2002 Niels Provos.  All rights reserved.
23  *
24  * Redistribution and use in source and binary forms, with or without
25  * modification, are permitted provided that the following conditions
26  * are met:
27  * 1. Redistributions of source code must retain the above copyright
28  *    notice, this list of conditions and the following disclaimer.
29  * 2. Redistributions in binary form must reproduce the above copyright
30  *    notice, this list of conditions and the following disclaimer in the
31  *    documentation and/or other materials provided with the distribution.
32  *
33  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
34  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
35  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
36  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
37  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
38  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
39  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
40  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
41  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
42  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43  */
44 
45 #include "includes.h"
46 __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 	if ((RAND_bytes((u_char *)rnd, 1)) != 1)
646 		fatal("%s: RAND_bytes failed", __func__);
647 #endif
648 	explicit_bzero(rnd, sizeof(rnd));
649 
650 	/* Demote the private keys to public keys. */
651 	demote_sensitive_data();
652 
653 	/* Change our root directory */
654 	if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
655 		fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
656 		    strerror(errno));
657 	if (chdir("/") == -1)
658 		fatal("chdir(\"/\"): %s", strerror(errno));
659 
660 	/* Drop our privileges */
661 	debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
662 	    (u_int)privsep_pw->pw_gid);
663 #if 0
664 	/* XXX not ready, too heavy after chroot */
665 	do_setusercontext(privsep_pw);
666 #else
667 	gidset[0] = privsep_pw->pw_gid;
668 	if (setgroups(1, gidset) < 0)
669 		fatal("setgroups: %.100s", strerror(errno));
670 	permanently_set_uid(privsep_pw);
671 #endif
672 }
673 
674 static int
675 privsep_preauth(Authctxt *authctxt)
676 {
677 	int status, r;
678 	pid_t pid;
679 	struct ssh_sandbox *box = NULL;
680 
681 	/* Set up unprivileged child process to deal with network data */
682 	pmonitor = monitor_init();
683 	/* Store a pointer to the kex for later rekeying */
684 	pmonitor->m_pkex = &active_state->kex;
685 
686 	if (use_privsep == PRIVSEP_ON)
687 		box = ssh_sandbox_init(pmonitor);
688 	pid = fork();
689 	if (pid == -1) {
690 		fatal("fork of unprivileged child failed");
691 	} else if (pid != 0) {
692 		debug2("Network child is on pid %ld", (long)pid);
693 
694 		pmonitor->m_pid = pid;
695 		if (have_agent) {
696 			r = ssh_get_authentication_socket(&auth_sock);
697 			if (r != 0) {
698 				error("Could not get agent socket: %s",
699 				    ssh_err(r));
700 				have_agent = 0;
701 			}
702 		}
703 		if (box != NULL)
704 			ssh_sandbox_parent_preauth(box, pid);
705 		monitor_child_preauth(authctxt, pmonitor);
706 
707 		/* Sync memory */
708 		monitor_sync(pmonitor);
709 
710 		/* Wait for the child's exit status */
711 		while (waitpid(pid, &status, 0) < 0) {
712 			if (errno == EINTR)
713 				continue;
714 			pmonitor->m_pid = -1;
715 			fatal("%s: waitpid: %s", __func__, strerror(errno));
716 		}
717 		privsep_is_preauth = 0;
718 		pmonitor->m_pid = -1;
719 		if (WIFEXITED(status)) {
720 			if (WEXITSTATUS(status) != 0)
721 				fatal("%s: preauth child exited with status %d",
722 				    __func__, WEXITSTATUS(status));
723 		} else if (WIFSIGNALED(status))
724 			fatal("%s: preauth child terminated by signal %d",
725 			    __func__, WTERMSIG(status));
726 		if (box != NULL)
727 			ssh_sandbox_parent_finish(box);
728 		return 1;
729 	} else {
730 		/* child */
731 		close(pmonitor->m_sendfd);
732 		close(pmonitor->m_log_recvfd);
733 
734 		/* Arrange for logging to be sent to the monitor */
735 		set_log_handler(mm_log_handler, pmonitor);
736 
737 		/* Demote the child */
738 		if (getuid() == 0 || geteuid() == 0)
739 			privsep_preauth_child();
740 		setproctitle("%s", "[net]");
741 		if (box != NULL)
742 			ssh_sandbox_child(box);
743 
744 		return 0;
745 	}
746 }
747 
748 static void
749 privsep_postauth(Authctxt *authctxt)
750 {
751 	u_int32_t rnd[256];
752 
753 #ifdef DISABLE_FD_PASSING
754 	if (1) {
755 #else
756 	if (authctxt->pw->pw_uid == 0 || options.use_login) {
757 #endif
758 		/* File descriptor passing is broken or root login */
759 		use_privsep = 0;
760 		goto skip;
761 	}
762 
763 	/* New socket pair */
764 	monitor_reinit(pmonitor);
765 
766 	pmonitor->m_pid = fork();
767 	if (pmonitor->m_pid == -1)
768 		fatal("fork of unprivileged child failed");
769 	else if (pmonitor->m_pid != 0) {
770 		verbose("User child is on pid %ld", (long)pmonitor->m_pid);
771 		buffer_clear(&loginmsg);
772 		monitor_child_postauth(pmonitor);
773 
774 		/* NEVERREACHED */
775 		exit(0);
776 	}
777 
778 	/* child */
779 
780 	close(pmonitor->m_sendfd);
781 	pmonitor->m_sendfd = -1;
782 
783 	/* Demote the private keys to public keys. */
784 	demote_sensitive_data();
785 
786 	arc4random_stir();
787 	arc4random_buf(rnd, sizeof(rnd));
788 #ifdef WITH_OPENSSL
789 	RAND_seed(rnd, sizeof(rnd));
790 	if ((RAND_bytes((u_char *)rnd, 1)) != 1)
791 		fatal("%s: RAND_bytes failed", __func__);
792 #endif
793 	explicit_bzero(rnd, sizeof(rnd));
794 
795 	/* Drop privileges */
796 	do_setusercontext(authctxt->pw);
797 
798  skip:
799 	/* It is safe now to apply the key state */
800 	monitor_apply_keystate(pmonitor);
801 
802 	/*
803 	 * Tell the packet layer that authentication was successful, since
804 	 * this information is not part of the key state.
805 	 */
806 	packet_set_authenticated();
807 }
808 
809 static char *
810 list_hostkey_types(void)
811 {
812 	Buffer b;
813 	const char *p;
814 	char *ret;
815 	int i;
816 	Key *key;
817 
818 	buffer_init(&b);
819 	for (i = 0; i < options.num_host_key_files; i++) {
820 		key = sensitive_data.host_keys[i];
821 		if (key == NULL)
822 			key = sensitive_data.host_pubkeys[i];
823 		if (key == NULL || key->type == KEY_RSA1)
824 			continue;
825 		/* Check that the key is accepted in HostkeyAlgorithms */
826 		if (match_pattern_list(sshkey_ssh_name(key),
827 		    options.hostkeyalgorithms, 0) != 1) {
828 			debug3("%s: %s key not permitted by HostkeyAlgorithms",
829 			    __func__, sshkey_ssh_name(key));
830 			continue;
831 		}
832 		switch (key->type) {
833 		case KEY_RSA:
834 		case KEY_DSA:
835 		case KEY_ECDSA:
836 		case KEY_ED25519:
837 			if (buffer_len(&b) > 0)
838 				buffer_append(&b, ",", 1);
839 			p = key_ssh_name(key);
840 			buffer_append(&b, p, strlen(p));
841 			break;
842 		}
843 		/* If the private key has a cert peer, then list that too */
844 		key = sensitive_data.host_certificates[i];
845 		if (key == NULL)
846 			continue;
847 		switch (key->type) {
848 		case KEY_RSA_CERT:
849 		case KEY_DSA_CERT:
850 		case KEY_ECDSA_CERT:
851 		case KEY_ED25519_CERT:
852 			if (buffer_len(&b) > 0)
853 				buffer_append(&b, ",", 1);
854 			p = key_ssh_name(key);
855 			buffer_append(&b, p, strlen(p));
856 			break;
857 		}
858 	}
859 	buffer_append(&b, "\0", 1);
860 	ret = xstrdup(buffer_ptr(&b));
861 	buffer_free(&b);
862 	debug("list_hostkey_types: %s", ret);
863 	return ret;
864 }
865 
866 static Key *
867 get_hostkey_by_type(int type, int nid, int need_private, struct ssh *ssh)
868 {
869 	int i;
870 	Key *key;
871 
872 	for (i = 0; i < options.num_host_key_files; i++) {
873 		switch (type) {
874 		case KEY_RSA_CERT:
875 		case KEY_DSA_CERT:
876 		case KEY_ECDSA_CERT:
877 		case KEY_ED25519_CERT:
878 			key = sensitive_data.host_certificates[i];
879 			break;
880 		default:
881 			key = sensitive_data.host_keys[i];
882 			if (key == NULL && !need_private)
883 				key = sensitive_data.host_pubkeys[i];
884 			break;
885 		}
886 		if (key != NULL && key->type == type &&
887 		    (key->type != KEY_ECDSA || key->ecdsa_nid == nid))
888 			return need_private ?
889 			    sensitive_data.host_keys[i] : key;
890 	}
891 	return NULL;
892 }
893 
894 Key *
895 get_hostkey_public_by_type(int type, int nid, struct ssh *ssh)
896 {
897 	return get_hostkey_by_type(type, nid, 0, ssh);
898 }
899 
900 Key *
901 get_hostkey_private_by_type(int type, int nid, struct ssh *ssh)
902 {
903 	return get_hostkey_by_type(type, nid, 1, ssh);
904 }
905 
906 Key *
907 get_hostkey_by_index(int ind)
908 {
909 	if (ind < 0 || ind >= options.num_host_key_files)
910 		return (NULL);
911 	return (sensitive_data.host_keys[ind]);
912 }
913 
914 Key *
915 get_hostkey_public_by_index(int ind, struct ssh *ssh)
916 {
917 	if (ind < 0 || ind >= options.num_host_key_files)
918 		return (NULL);
919 	return (sensitive_data.host_pubkeys[ind]);
920 }
921 
922 int
923 get_hostkey_index(Key *key, int compare, struct ssh *ssh)
924 {
925 	int i;
926 
927 	for (i = 0; i < options.num_host_key_files; i++) {
928 		if (key_is_cert(key)) {
929 			if (key == sensitive_data.host_certificates[i] ||
930 			    (compare && sensitive_data.host_certificates[i] &&
931 			    sshkey_equal(key,
932 			    sensitive_data.host_certificates[i])))
933 				return (i);
934 		} else {
935 			if (key == sensitive_data.host_keys[i] ||
936 			    (compare && sensitive_data.host_keys[i] &&
937 			    sshkey_equal(key, sensitive_data.host_keys[i])))
938 				return (i);
939 			if (key == sensitive_data.host_pubkeys[i] ||
940 			    (compare && sensitive_data.host_pubkeys[i] &&
941 			    sshkey_equal(key, sensitive_data.host_pubkeys[i])))
942 				return (i);
943 		}
944 	}
945 	return (-1);
946 }
947 
948 /* Inform the client of all hostkeys */
949 static void
950 notify_hostkeys(struct ssh *ssh)
951 {
952 	struct sshbuf *buf;
953 	struct sshkey *key;
954 	int i, nkeys, r;
955 	char *fp;
956 
957 	/* Some clients cannot cope with the hostkeys message, skip those. */
958 	if (datafellows & SSH_BUG_HOSTKEYS)
959 		return;
960 
961 	if ((buf = sshbuf_new()) == NULL)
962 		fatal("%s: sshbuf_new", __func__);
963 	for (i = nkeys = 0; i < options.num_host_key_files; i++) {
964 		key = get_hostkey_public_by_index(i, ssh);
965 		if (key == NULL || key->type == KEY_UNSPEC ||
966 		    key->type == KEY_RSA1 || sshkey_is_cert(key))
967 			continue;
968 		fp = sshkey_fingerprint(key, options.fingerprint_hash,
969 		    SSH_FP_DEFAULT);
970 		debug3("%s: key %d: %s %s", __func__, i,
971 		    sshkey_ssh_name(key), fp);
972 		free(fp);
973 		if (nkeys == 0) {
974 			packet_start(SSH2_MSG_GLOBAL_REQUEST);
975 			packet_put_cstring("hostkeys-00@openssh.com");
976 			packet_put_char(0); /* want-reply */
977 		}
978 		sshbuf_reset(buf);
979 		if ((r = sshkey_putb(key, buf)) != 0)
980 			fatal("%s: couldn't put hostkey %d: %s",
981 			    __func__, i, ssh_err(r));
982 		packet_put_string(sshbuf_ptr(buf), sshbuf_len(buf));
983 		nkeys++;
984 	}
985 	debug3("%s: sent %d hostkeys", __func__, nkeys);
986 	if (nkeys == 0)
987 		fatal("%s: no hostkeys", __func__);
988 	packet_send();
989 	sshbuf_free(buf);
990 }
991 
992 /*
993  * returns 1 if connection should be dropped, 0 otherwise.
994  * dropping starts at connection #max_startups_begin with a probability
995  * of (max_startups_rate/100). the probability increases linearly until
996  * all connections are dropped for startups > max_startups
997  */
998 static int
999 drop_connection(int startups)
1000 {
1001 	int p, r;
1002 
1003 	if (startups < options.max_startups_begin)
1004 		return 0;
1005 	if (startups >= options.max_startups)
1006 		return 1;
1007 	if (options.max_startups_rate == 100)
1008 		return 1;
1009 
1010 	p  = 100 - options.max_startups_rate;
1011 	p *= startups - options.max_startups_begin;
1012 	p /= options.max_startups - options.max_startups_begin;
1013 	p += options.max_startups_rate;
1014 	r = arc4random_uniform(100);
1015 
1016 	debug("drop_connection: p %d, r %d", p, r);
1017 	return (r < p) ? 1 : 0;
1018 }
1019 
1020 static void
1021 usage(void)
1022 {
1023 	if (options.version_addendum && *options.version_addendum != '\0')
1024 		fprintf(stderr, "%s %s, %s\n",
1025 		    SSH_RELEASE,
1026 		    options.version_addendum, OPENSSL_VERSION);
1027 	else
1028 		fprintf(stderr, "%s, %s\n",
1029 		    SSH_RELEASE, OPENSSL_VERSION);
1030 	fprintf(stderr,
1031 "usage: sshd [-46DdeiqTt] [-b bits] [-C connection_spec] [-c host_cert_file]\n"
1032 "            [-E log_file] [-f config_file] [-g login_grace_time]\n"
1033 "            [-h host_key_file] [-k key_gen_time] [-o option] [-p port]\n"
1034 "            [-u len]\n"
1035 	);
1036 	exit(1);
1037 }
1038 
1039 static void
1040 send_rexec_state(int fd, Buffer *conf)
1041 {
1042 	Buffer m;
1043 
1044 	debug3("%s: entering fd = %d config len %d", __func__, fd,
1045 	    buffer_len(conf));
1046 
1047 	/*
1048 	 * Protocol from reexec master to child:
1049 	 *	string	configuration
1050 	 *	u_int	ephemeral_key_follows
1051 	 *	bignum	e		(only if ephemeral_key_follows == 1)
1052 	 *	bignum	n			"
1053 	 *	bignum	d			"
1054 	 *	bignum	iqmp			"
1055 	 *	bignum	p			"
1056 	 *	bignum	q			"
1057 	 *	string rngseed		(only if OpenSSL is not self-seeded)
1058 	 */
1059 	buffer_init(&m);
1060 	buffer_put_cstring(&m, buffer_ptr(conf));
1061 
1062 #ifdef WITH_SSH1
1063 	if (sensitive_data.server_key != NULL &&
1064 	    sensitive_data.server_key->type == KEY_RSA1) {
1065 		buffer_put_int(&m, 1);
1066 		buffer_put_bignum(&m, sensitive_data.server_key->rsa->e);
1067 		buffer_put_bignum(&m, sensitive_data.server_key->rsa->n);
1068 		buffer_put_bignum(&m, sensitive_data.server_key->rsa->d);
1069 		buffer_put_bignum(&m, sensitive_data.server_key->rsa->iqmp);
1070 		buffer_put_bignum(&m, sensitive_data.server_key->rsa->p);
1071 		buffer_put_bignum(&m, sensitive_data.server_key->rsa->q);
1072 	} else
1073 #endif
1074 		buffer_put_int(&m, 0);
1075 
1076 #if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
1077 	rexec_send_rng_seed(&m);
1078 #endif
1079 
1080 	if (ssh_msg_send(fd, 0, &m) == -1)
1081 		fatal("%s: ssh_msg_send failed", __func__);
1082 
1083 	buffer_free(&m);
1084 
1085 	debug3("%s: done", __func__);
1086 }
1087 
1088 static void
1089 recv_rexec_state(int fd, Buffer *conf)
1090 {
1091 	Buffer m;
1092 	char *cp;
1093 	u_int len;
1094 
1095 	debug3("%s: entering fd = %d", __func__, fd);
1096 
1097 	buffer_init(&m);
1098 
1099 	if (ssh_msg_recv(fd, &m) == -1)
1100 		fatal("%s: ssh_msg_recv failed", __func__);
1101 	if (buffer_get_char(&m) != 0)
1102 		fatal("%s: rexec version mismatch", __func__);
1103 
1104 	cp = buffer_get_string(&m, &len);
1105 	if (conf != NULL)
1106 		buffer_append(conf, cp, len + 1);
1107 	free(cp);
1108 
1109 	if (buffer_get_int(&m)) {
1110 #ifdef WITH_SSH1
1111 		if (sensitive_data.server_key != NULL)
1112 			key_free(sensitive_data.server_key);
1113 		sensitive_data.server_key = key_new_private(KEY_RSA1);
1114 		buffer_get_bignum(&m, sensitive_data.server_key->rsa->e);
1115 		buffer_get_bignum(&m, sensitive_data.server_key->rsa->n);
1116 		buffer_get_bignum(&m, sensitive_data.server_key->rsa->d);
1117 		buffer_get_bignum(&m, sensitive_data.server_key->rsa->iqmp);
1118 		buffer_get_bignum(&m, sensitive_data.server_key->rsa->p);
1119 		buffer_get_bignum(&m, sensitive_data.server_key->rsa->q);
1120 		if (rsa_generate_additional_parameters(
1121 		    sensitive_data.server_key->rsa) != 0)
1122 			fatal("%s: rsa_generate_additional_parameters "
1123 			    "error", __func__);
1124 #endif
1125 	}
1126 
1127 #if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
1128 	rexec_recv_rng_seed(&m);
1129 #endif
1130 
1131 	buffer_free(&m);
1132 
1133 	debug3("%s: done", __func__);
1134 }
1135 
1136 /* Accept a connection from inetd */
1137 static void
1138 server_accept_inetd(int *sock_in, int *sock_out)
1139 {
1140 	int fd;
1141 
1142 	startup_pipe = -1;
1143 	if (rexeced_flag) {
1144 		close(REEXEC_CONFIG_PASS_FD);
1145 		*sock_in = *sock_out = dup(STDIN_FILENO);
1146 		if (!debug_flag) {
1147 			startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
1148 			close(REEXEC_STARTUP_PIPE_FD);
1149 		}
1150 	} else {
1151 		*sock_in = dup(STDIN_FILENO);
1152 		*sock_out = dup(STDOUT_FILENO);
1153 	}
1154 	/*
1155 	 * We intentionally do not close the descriptors 0, 1, and 2
1156 	 * as our code for setting the descriptors won't work if
1157 	 * ttyfd happens to be one of those.
1158 	 */
1159 	if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1160 		dup2(fd, STDIN_FILENO);
1161 		dup2(fd, STDOUT_FILENO);
1162 		if (!log_stderr)
1163 			dup2(fd, STDERR_FILENO);
1164 		if (fd > (log_stderr ? STDERR_FILENO : STDOUT_FILENO))
1165 			close(fd);
1166 	}
1167 	debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
1168 }
1169 
1170 /*
1171  * Listen for TCP connections
1172  */
1173 static void
1174 server_listen(void)
1175 {
1176 	int ret, listen_sock, on = 1;
1177 	struct addrinfo *ai;
1178 	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1179 	int socksize;
1180 	socklen_t len;
1181 
1182 	for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
1183 		if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1184 			continue;
1185 		if (num_listen_socks >= MAX_LISTEN_SOCKS)
1186 			fatal("Too many listen sockets. "
1187 			    "Enlarge MAX_LISTEN_SOCKS");
1188 		if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1189 		    ntop, sizeof(ntop), strport, sizeof(strport),
1190 		    NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1191 			error("getnameinfo failed: %.100s",
1192 			    ssh_gai_strerror(ret));
1193 			continue;
1194 		}
1195 		/* Create socket for listening. */
1196 		listen_sock = socket(ai->ai_family, ai->ai_socktype,
1197 		    ai->ai_protocol);
1198 		if (listen_sock < 0) {
1199 			/* kernel may not support ipv6 */
1200 			verbose("socket: %.100s", strerror(errno));
1201 			continue;
1202 		}
1203 		if (set_nonblock(listen_sock) == -1) {
1204 			close(listen_sock);
1205 			continue;
1206 		}
1207 		/*
1208 		 * Set socket options.
1209 		 * Allow local port reuse in TIME_WAIT.
1210 		 */
1211 		if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
1212 		    &on, sizeof(on)) == -1)
1213 			error("setsockopt SO_REUSEADDR: %s", strerror(errno));
1214 
1215 		/* Only communicate in IPv6 over AF_INET6 sockets. */
1216 		if (ai->ai_family == AF_INET6)
1217 			sock_set_v6only(listen_sock);
1218 
1219 		debug("Bind to port %s on %s.", strport, ntop);
1220 
1221 		len = sizeof(socksize);
1222 		getsockopt(listen_sock, SOL_SOCKET, SO_RCVBUF, &socksize, &len);
1223 		debug("Server TCP RWIN socket size: %d", socksize);
1224 
1225 		/* Bind the socket to the desired port. */
1226 		if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1227 			error("Bind to port %s on %s failed: %.200s.",
1228 			    strport, ntop, strerror(errno));
1229 			close(listen_sock);
1230 			continue;
1231 		}
1232 		listen_socks[num_listen_socks] = listen_sock;
1233 		num_listen_socks++;
1234 
1235 		/* Start listening on the port. */
1236 		if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1237 			fatal("listen on [%s]:%s: %.100s",
1238 			    ntop, strport, strerror(errno));
1239 		logit("Server listening on %s port %s.", ntop, strport);
1240 	}
1241 	freeaddrinfo(options.listen_addrs);
1242 
1243 	if (!num_listen_socks)
1244 		fatal("Cannot bind any address.");
1245 }
1246 
1247 /*
1248  * The main TCP accept loop. Note that, for the non-debug case, returns
1249  * from this function are in a forked subprocess.
1250  */
1251 static void
1252 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1253 {
1254 	fd_set *fdset;
1255 	int i, j, ret, maxfd;
1256 	int key_used = 0, startups = 0;
1257 	int startup_p[2] = { -1 , -1 };
1258 	struct sockaddr_storage from;
1259 	socklen_t fromlen;
1260 	pid_t pid;
1261 	u_char rnd[256];
1262 
1263 	/* setup fd set for accept */
1264 	fdset = NULL;
1265 	maxfd = 0;
1266 	for (i = 0; i < num_listen_socks; i++)
1267 		if (listen_socks[i] > maxfd)
1268 			maxfd = listen_socks[i];
1269 	/* pipes connected to unauthenticated childs */
1270 	startup_pipes = xcalloc(options.max_startups, sizeof(int));
1271 	for (i = 0; i < options.max_startups; i++)
1272 		startup_pipes[i] = -1;
1273 
1274 	/*
1275 	 * Stay listening for connections until the system crashes or
1276 	 * the daemon is killed with a signal.
1277 	 */
1278 	for (;;) {
1279 		if (received_sighup)
1280 			sighup_restart();
1281 		if (fdset != NULL)
1282 			free(fdset);
1283 		fdset = xcalloc(howmany(maxfd + 1, NFDBITS),
1284 		    sizeof(fd_mask));
1285 
1286 		for (i = 0; i < num_listen_socks; i++)
1287 			FD_SET(listen_socks[i], fdset);
1288 		for (i = 0; i < options.max_startups; i++)
1289 			if (startup_pipes[i] != -1)
1290 				FD_SET(startup_pipes[i], fdset);
1291 
1292 		/* Wait in select until there is a connection. */
1293 		ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1294 		if (ret < 0 && errno != EINTR)
1295 			error("select: %.100s", strerror(errno));
1296 		if (received_sigterm) {
1297 			logit("Received signal %d; terminating.",
1298 			    (int) received_sigterm);
1299 			close_listen_socks();
1300 			if (options.pid_file != NULL)
1301 				unlink(options.pid_file);
1302 			exit(received_sigterm == SIGTERM ? 0 : 255);
1303 		}
1304 		if (key_used && key_do_regen) {
1305 			generate_ephemeral_server_key();
1306 			key_used = 0;
1307 			key_do_regen = 0;
1308 		}
1309 		if (ret < 0)
1310 			continue;
1311 
1312 		for (i = 0; i < options.max_startups; i++)
1313 			if (startup_pipes[i] != -1 &&
1314 			    FD_ISSET(startup_pipes[i], fdset)) {
1315 				/*
1316 				 * the read end of the pipe is ready
1317 				 * if the child has closed the pipe
1318 				 * after successful authentication
1319 				 * or if the child has died
1320 				 */
1321 				close(startup_pipes[i]);
1322 				startup_pipes[i] = -1;
1323 				startups--;
1324 			}
1325 		for (i = 0; i < num_listen_socks; i++) {
1326 			if (!FD_ISSET(listen_socks[i], fdset))
1327 				continue;
1328 			fromlen = sizeof(from);
1329 			*newsock = accept(listen_socks[i],
1330 			    (struct sockaddr *)&from, &fromlen);
1331 			if (*newsock < 0) {
1332 				if (errno != EINTR && errno != EWOULDBLOCK &&
1333 				    errno != ECONNABORTED && errno != EAGAIN)
1334 					error("accept: %.100s",
1335 					    strerror(errno));
1336 				if (errno == EMFILE || errno == ENFILE)
1337 					usleep(100 * 1000);
1338 				continue;
1339 			}
1340 			if (unset_nonblock(*newsock) == -1) {
1341 				close(*newsock);
1342 				continue;
1343 			}
1344 			if (drop_connection(startups) == 1) {
1345 				debug("drop connection #%d", startups);
1346 				close(*newsock);
1347 				continue;
1348 			}
1349 			if (pipe(startup_p) == -1) {
1350 				close(*newsock);
1351 				continue;
1352 			}
1353 
1354 			if (rexec_flag && socketpair(AF_UNIX,
1355 			    SOCK_STREAM, 0, config_s) == -1) {
1356 				error("reexec socketpair: %s",
1357 				    strerror(errno));
1358 				close(*newsock);
1359 				close(startup_p[0]);
1360 				close(startup_p[1]);
1361 				continue;
1362 			}
1363 
1364 			for (j = 0; j < options.max_startups; j++)
1365 				if (startup_pipes[j] == -1) {
1366 					startup_pipes[j] = startup_p[0];
1367 					if (maxfd < startup_p[0])
1368 						maxfd = startup_p[0];
1369 					startups++;
1370 					break;
1371 				}
1372 
1373 			/*
1374 			 * Got connection.  Fork a child to handle it, unless
1375 			 * we are in debugging mode.
1376 			 */
1377 			if (debug_flag) {
1378 				/*
1379 				 * In debugging mode.  Close the listening
1380 				 * socket, and start processing the
1381 				 * connection without forking.
1382 				 */
1383 				debug("Server will not fork when running in debugging mode.");
1384 				close_listen_socks();
1385 				*sock_in = *newsock;
1386 				*sock_out = *newsock;
1387 				close(startup_p[0]);
1388 				close(startup_p[1]);
1389 				startup_pipe = -1;
1390 				pid = getpid();
1391 				if (rexec_flag) {
1392 					send_rexec_state(config_s[0],
1393 					    &cfg);
1394 					close(config_s[0]);
1395 				}
1396 				break;
1397 			}
1398 
1399 			/*
1400 			 * Normal production daemon.  Fork, and have
1401 			 * the child process the connection. The
1402 			 * parent continues listening.
1403 			 */
1404 			platform_pre_fork();
1405 			if ((pid = fork()) == 0) {
1406 				/*
1407 				 * Child.  Close the listening and
1408 				 * max_startup sockets.  Start using
1409 				 * the accepted socket. Reinitialize
1410 				 * logging (since our pid has changed).
1411 				 * We break out of the loop to handle
1412 				 * the connection.
1413 				 */
1414 				platform_post_fork_child();
1415 				startup_pipe = startup_p[1];
1416 				close_startup_pipes();
1417 				close_listen_socks();
1418 				*sock_in = *newsock;
1419 				*sock_out = *newsock;
1420 				log_init(__progname,
1421 				    options.log_level,
1422 				    options.log_facility,
1423 				    log_stderr);
1424 				if (rexec_flag)
1425 					close(config_s[0]);
1426 				break;
1427 			}
1428 
1429 			/* Parent.  Stay in the loop. */
1430 			platform_post_fork_parent(pid);
1431 			if (pid < 0)
1432 				error("fork: %.100s", strerror(errno));
1433 			else
1434 				debug("Forked child %ld.", (long)pid);
1435 
1436 			close(startup_p[1]);
1437 
1438 			if (rexec_flag) {
1439 				send_rexec_state(config_s[0], &cfg);
1440 				close(config_s[0]);
1441 				close(config_s[1]);
1442 			}
1443 
1444 			/*
1445 			 * Mark that the key has been used (it
1446 			 * was "given" to the child).
1447 			 */
1448 			if ((options.protocol & SSH_PROTO_1) &&
1449 			    key_used == 0) {
1450 				/* Schedule server key regeneration alarm. */
1451 				signal(SIGALRM, key_regeneration_alarm);
1452 				alarm(options.key_regeneration_time);
1453 				key_used = 1;
1454 			}
1455 
1456 			close(*newsock);
1457 
1458 			/*
1459 			 * Ensure that our random state differs
1460 			 * from that of the child
1461 			 */
1462 			arc4random_stir();
1463 			arc4random_buf(rnd, sizeof(rnd));
1464 #ifdef WITH_OPENSSL
1465 			RAND_seed(rnd, sizeof(rnd));
1466 			if ((RAND_bytes((u_char *)rnd, 1)) != 1)
1467 				fatal("%s: RAND_bytes failed", __func__);
1468 #endif
1469 			explicit_bzero(rnd, sizeof(rnd));
1470 		}
1471 
1472 		/* child process check (or debug mode) */
1473 		if (num_listen_socks < 0)
1474 			break;
1475 	}
1476 }
1477 
1478 
1479 /*
1480  * Main program for the daemon.
1481  */
1482 int
1483 main(int ac, char **av)
1484 {
1485 	extern char *optarg;
1486 	extern int optind;
1487 	int r, opt, i, j, on = 1;
1488 	int sock_in = -1, sock_out = -1, newsock = -1;
1489 	const char *remote_ip;
1490 	int remote_port;
1491 	char *fp, *line, *laddr, *logfile = NULL;
1492 	int config_s[2] = { -1 , -1 };
1493 	u_int n;
1494 	u_int64_t ibytes, obytes;
1495 	mode_t new_umask;
1496 	Key *key;
1497 	Key *pubkey;
1498 	int keytype;
1499 	Authctxt *authctxt;
1500 	struct connection_info *connection_info = get_connection_info(0, 0);
1501 
1502 #ifdef HAVE_SECUREWARE
1503 	(void)set_auth_parameters(ac, av);
1504 #endif
1505 	__progname = ssh_get_progname(av[0]);
1506 
1507 	/* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1508 	saved_argc = ac;
1509 	rexec_argc = ac;
1510 	saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1511 	for (i = 0; i < ac; i++)
1512 		saved_argv[i] = xstrdup(av[i]);
1513 	saved_argv[i] = NULL;
1514 
1515 #ifndef HAVE_SETPROCTITLE
1516 	/* Prepare for later setproctitle emulation */
1517 	compat_init_setproctitle(ac, av);
1518 	av = saved_argv;
1519 #endif
1520 
1521 	if (geteuid() == 0 && setgroups(0, NULL) == -1)
1522 		debug("setgroups(): %.200s", strerror(errno));
1523 
1524 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1525 	sanitise_stdfd();
1526 
1527 	/* Initialize configuration options to their default values. */
1528 	initialize_server_options(&options);
1529 
1530 	/* Parse command-line arguments. */
1531 	while ((opt = getopt(ac, av,
1532 	    "C:E:b:c:f:g:h:k:o:p:u:46DQRTdeiqrt")) != -1) {
1533 		switch (opt) {
1534 		case '4':
1535 			options.address_family = AF_INET;
1536 			break;
1537 		case '6':
1538 			options.address_family = AF_INET6;
1539 			break;
1540 		case 'f':
1541 			config_file_name = optarg;
1542 			break;
1543 		case 'c':
1544 			if (options.num_host_cert_files >= MAX_HOSTCERTS) {
1545 				fprintf(stderr, "too many host certificates.\n");
1546 				exit(1);
1547 			}
1548 			options.host_cert_files[options.num_host_cert_files++] =
1549 			   derelativise_path(optarg);
1550 			break;
1551 		case 'd':
1552 			if (debug_flag == 0) {
1553 				debug_flag = 1;
1554 				options.log_level = SYSLOG_LEVEL_DEBUG1;
1555 			} else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1556 				options.log_level++;
1557 			break;
1558 		case 'D':
1559 			no_daemon_flag = 1;
1560 			break;
1561 		case 'E':
1562 			logfile = xstrdup(optarg);
1563 			/* FALLTHROUGH */
1564 		case 'e':
1565 			log_stderr = 1;
1566 			break;
1567 		case 'i':
1568 			inetd_flag = 1;
1569 			break;
1570 		case 'r':
1571 			rexec_flag = 0;
1572 			break;
1573 		case 'R':
1574 			rexeced_flag = 1;
1575 			inetd_flag = 1;
1576 			break;
1577 		case 'Q':
1578 			/* ignored */
1579 			break;
1580 		case 'q':
1581 			options.log_level = SYSLOG_LEVEL_QUIET;
1582 			break;
1583 		case 'b':
1584 			options.server_key_bits = (int)strtonum(optarg, 256,
1585 			    32768, NULL);
1586 			break;
1587 		case 'p':
1588 			options.ports_from_cmdline = 1;
1589 			if (options.num_ports >= MAX_PORTS) {
1590 				fprintf(stderr, "too many ports.\n");
1591 				exit(1);
1592 			}
1593 			options.ports[options.num_ports++] = a2port(optarg);
1594 			if (options.ports[options.num_ports-1] <= 0) {
1595 				fprintf(stderr, "Bad port number.\n");
1596 				exit(1);
1597 			}
1598 			break;
1599 		case 'g':
1600 			if ((options.login_grace_time = convtime(optarg)) == -1) {
1601 				fprintf(stderr, "Invalid login grace time.\n");
1602 				exit(1);
1603 			}
1604 			break;
1605 		case 'k':
1606 			if ((options.key_regeneration_time = convtime(optarg)) == -1) {
1607 				fprintf(stderr, "Invalid key regeneration interval.\n");
1608 				exit(1);
1609 			}
1610 			break;
1611 		case 'h':
1612 			if (options.num_host_key_files >= MAX_HOSTKEYS) {
1613 				fprintf(stderr, "too many host keys.\n");
1614 				exit(1);
1615 			}
1616 			options.host_key_files[options.num_host_key_files++] =
1617 			   derelativise_path(optarg);
1618 			break;
1619 		case 't':
1620 			test_flag = 1;
1621 			break;
1622 		case 'T':
1623 			test_flag = 2;
1624 			break;
1625 		case 'C':
1626 			if (parse_server_match_testspec(connection_info,
1627 			    optarg) == -1)
1628 				exit(1);
1629 			break;
1630 		case 'u':
1631 			utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
1632 			if (utmp_len > HOST_NAME_MAX+1) {
1633 				fprintf(stderr, "Invalid utmp length.\n");
1634 				exit(1);
1635 			}
1636 			break;
1637 		case 'o':
1638 			line = xstrdup(optarg);
1639 			if (process_server_config_line(&options, line,
1640 			    "command-line", 0, NULL, NULL) != 0)
1641 				exit(1);
1642 			free(line);
1643 			break;
1644 		case '?':
1645 		default:
1646 			usage();
1647 			break;
1648 		}
1649 	}
1650 	if (rexeced_flag || inetd_flag)
1651 		rexec_flag = 0;
1652 	if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1653 		fatal("sshd re-exec requires execution with an absolute path");
1654 	if (rexeced_flag)
1655 		closefrom(REEXEC_MIN_FREE_FD);
1656 	else
1657 		closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1658 
1659 #ifdef WITH_OPENSSL
1660 	OpenSSL_add_all_algorithms();
1661 #endif
1662 
1663 	/* If requested, redirect the logs to the specified logfile. */
1664 	if (logfile != NULL) {
1665 		log_redirect_stderr_to(logfile);
1666 		free(logfile);
1667 	}
1668 	/*
1669 	 * Force logging to stderr until we have loaded the private host
1670 	 * key (unless started from inetd)
1671 	 */
1672 	log_init(__progname,
1673 	    options.log_level == SYSLOG_LEVEL_NOT_SET ?
1674 	    SYSLOG_LEVEL_INFO : options.log_level,
1675 	    options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1676 	    SYSLOG_FACILITY_AUTH : options.log_facility,
1677 	    log_stderr || !inetd_flag);
1678 
1679 	/*
1680 	 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1681 	 * root's environment
1682 	 */
1683 	if (getenv("KRB5CCNAME") != NULL)
1684 		(void) unsetenv("KRB5CCNAME");
1685 
1686 #ifdef _UNICOS
1687 	/* Cray can define user privs drop all privs now!
1688 	 * Not needed on PRIV_SU systems!
1689 	 */
1690 	drop_cray_privs();
1691 #endif
1692 
1693 	sensitive_data.server_key = NULL;
1694 	sensitive_data.ssh1_host_key = NULL;
1695 	sensitive_data.have_ssh1_key = 0;
1696 	sensitive_data.have_ssh2_key = 0;
1697 
1698 	/*
1699 	 * If we're doing an extended config test, make sure we have all of
1700 	 * the parameters we need.  If we're not doing an extended test,
1701 	 * do not silently ignore connection test params.
1702 	 */
1703 	if (test_flag >= 2 && server_match_spec_complete(connection_info) == 0)
1704 		fatal("user, host and addr are all required when testing "
1705 		   "Match configs");
1706 	if (test_flag < 2 && server_match_spec_complete(connection_info) >= 0)
1707 		fatal("Config test connection parameter (-C) provided without "
1708 		   "test mode (-T)");
1709 
1710 	/* Fetch our configuration */
1711 	buffer_init(&cfg);
1712 	if (rexeced_flag)
1713 		recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1714 	else if (strcasecmp(config_file_name, "none") != 0)
1715 		load_server_config(config_file_name, &cfg);
1716 
1717 	parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1718 	    &cfg, NULL);
1719 
1720 	seed_rng();
1721 
1722 	/* Fill in default values for those options not explicitly set. */
1723 	fill_default_server_options(&options);
1724 
1725 	/* challenge-response is implemented via keyboard interactive */
1726 	if (options.challenge_response_authentication)
1727 		options.kbd_interactive_authentication = 1;
1728 
1729 	/* Check that options are sensible */
1730 	if (options.authorized_keys_command_user == NULL &&
1731 	    (options.authorized_keys_command != NULL &&
1732 	    strcasecmp(options.authorized_keys_command, "none") != 0))
1733 		fatal("AuthorizedKeysCommand set without "
1734 		    "AuthorizedKeysCommandUser");
1735 	if (options.authorized_principals_command_user == NULL &&
1736 	    (options.authorized_principals_command != NULL &&
1737 	    strcasecmp(options.authorized_principals_command, "none") != 0))
1738 		fatal("AuthorizedPrincipalsCommand set without "
1739 		    "AuthorizedPrincipalsCommandUser");
1740 
1741 	/*
1742 	 * Check whether there is any path through configured auth methods.
1743 	 * Unfortunately it is not possible to verify this generally before
1744 	 * daemonisation in the presence of Match block, but this catches
1745 	 * and warns for trivial misconfigurations that could break login.
1746 	 */
1747 	if (options.num_auth_methods != 0) {
1748 		if ((options.protocol & SSH_PROTO_1))
1749 			fatal("AuthenticationMethods is not supported with "
1750 			    "SSH protocol 1");
1751 		for (n = 0; n < options.num_auth_methods; n++) {
1752 			if (auth2_methods_valid(options.auth_methods[n],
1753 			    1) == 0)
1754 				break;
1755 		}
1756 		if (n >= options.num_auth_methods)
1757 			fatal("AuthenticationMethods cannot be satisfied by "
1758 			    "enabled authentication methods");
1759 	}
1760 
1761 	/* set default channel AF */
1762 	channel_set_af(options.address_family);
1763 
1764 	/* Check that there are no remaining arguments. */
1765 	if (optind < ac) {
1766 		fprintf(stderr, "Extra argument %s.\n", av[optind]);
1767 		exit(1);
1768 	}
1769 
1770 	debug("sshd version %s, %s", SSH_VERSION,
1771 #ifdef WITH_OPENSSL
1772 	    SSLeay_version(SSLEAY_VERSION)
1773 #else
1774 	    "without OpenSSL"
1775 #endif
1776 	);
1777 
1778 	/* Store privilege separation user for later use if required. */
1779 	if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1780 		if (use_privsep || options.kerberos_authentication)
1781 			fatal("Privilege separation user %s does not exist",
1782 			    SSH_PRIVSEP_USER);
1783 	} else {
1784 		explicit_bzero(privsep_pw->pw_passwd,
1785 		    strlen(privsep_pw->pw_passwd));
1786 		privsep_pw = pwcopy(privsep_pw);
1787 		free(privsep_pw->pw_passwd);
1788 		privsep_pw->pw_passwd = xstrdup("*");
1789 	}
1790 	endpwent();
1791 
1792 	/* load host keys */
1793 	sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1794 	    sizeof(Key *));
1795 	sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
1796 	    sizeof(Key *));
1797 
1798 	if (options.host_key_agent) {
1799 		if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
1800 			setenv(SSH_AUTHSOCKET_ENV_NAME,
1801 			    options.host_key_agent, 1);
1802 		if ((r = ssh_get_authentication_socket(NULL)) == 0)
1803 			have_agent = 1;
1804 		else
1805 			error("Could not connect to agent \"%s\": %s",
1806 			    options.host_key_agent, ssh_err(r));
1807 	}
1808 
1809 	for (i = 0; i < options.num_host_key_files; i++) {
1810 		if (options.host_key_files[i] == NULL)
1811 			continue;
1812 		key = key_load_private(options.host_key_files[i], "", NULL);
1813 		pubkey = key_load_public(options.host_key_files[i], NULL);
1814 		if (pubkey == NULL && key != NULL)
1815 			pubkey = key_demote(key);
1816 		sensitive_data.host_keys[i] = key;
1817 		sensitive_data.host_pubkeys[i] = pubkey;
1818 
1819 		if (key == NULL && pubkey != NULL && pubkey->type != KEY_RSA1 &&
1820 		    have_agent) {
1821 			debug("will rely on agent for hostkey %s",
1822 			    options.host_key_files[i]);
1823 			keytype = pubkey->type;
1824 		} else if (key != NULL) {
1825 			keytype = key->type;
1826 		} else {
1827 			error("Could not load host key: %s",
1828 			    options.host_key_files[i]);
1829 			sensitive_data.host_keys[i] = NULL;
1830 			sensitive_data.host_pubkeys[i] = NULL;
1831 			continue;
1832 		}
1833 
1834 		switch (keytype) {
1835 		case KEY_RSA1:
1836 			sensitive_data.ssh1_host_key = key;
1837 			sensitive_data.have_ssh1_key = 1;
1838 			break;
1839 		case KEY_RSA:
1840 		case KEY_DSA:
1841 		case KEY_ECDSA:
1842 		case KEY_ED25519:
1843 			if (have_agent || key != NULL)
1844 				sensitive_data.have_ssh2_key = 1;
1845 			break;
1846 		}
1847 		if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash,
1848 		    SSH_FP_DEFAULT)) == NULL)
1849 			fatal("sshkey_fingerprint failed");
1850 		debug("%s host key #%d: %s %s",
1851 		    key ? "private" : "agent", i, keytype == KEY_RSA1 ?
1852 		    sshkey_type(pubkey) : sshkey_ssh_name(pubkey), fp);
1853 		free(fp);
1854 	}
1855 	if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1856 		logit("Disabling protocol version 1. Could not load host key");
1857 		options.protocol &= ~SSH_PROTO_1;
1858 	}
1859 	if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1860 		logit("Disabling protocol version 2. Could not load host key");
1861 		options.protocol &= ~SSH_PROTO_2;
1862 	}
1863 	if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1864 		logit("sshd: no hostkeys available -- exiting.");
1865 		exit(1);
1866 	}
1867 
1868 	/*
1869 	 * Load certificates. They are stored in an array at identical
1870 	 * indices to the public keys that they relate to.
1871 	 */
1872 	sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
1873 	    sizeof(Key *));
1874 	for (i = 0; i < options.num_host_key_files; i++)
1875 		sensitive_data.host_certificates[i] = NULL;
1876 
1877 	for (i = 0; i < options.num_host_cert_files; i++) {
1878 		if (options.host_cert_files[i] == NULL)
1879 			continue;
1880 		key = key_load_public(options.host_cert_files[i], NULL);
1881 		if (key == NULL) {
1882 			error("Could not load host certificate: %s",
1883 			    options.host_cert_files[i]);
1884 			continue;
1885 		}
1886 		if (!key_is_cert(key)) {
1887 			error("Certificate file is not a certificate: %s",
1888 			    options.host_cert_files[i]);
1889 			key_free(key);
1890 			continue;
1891 		}
1892 		/* Find matching private key */
1893 		for (j = 0; j < options.num_host_key_files; j++) {
1894 			if (key_equal_public(key,
1895 			    sensitive_data.host_keys[j])) {
1896 				sensitive_data.host_certificates[j] = key;
1897 				break;
1898 			}
1899 		}
1900 		if (j >= options.num_host_key_files) {
1901 			error("No matching private key for certificate: %s",
1902 			    options.host_cert_files[i]);
1903 			key_free(key);
1904 			continue;
1905 		}
1906 		sensitive_data.host_certificates[j] = key;
1907 		debug("host certificate: #%d type %d %s", j, key->type,
1908 		    key_type(key));
1909 	}
1910 
1911 #ifdef WITH_SSH1
1912 	/* Check certain values for sanity. */
1913 	if (options.protocol & SSH_PROTO_1) {
1914 		if (options.server_key_bits < SSH_RSA_MINIMUM_MODULUS_SIZE ||
1915 		    options.server_key_bits > OPENSSL_RSA_MAX_MODULUS_BITS) {
1916 			fprintf(stderr, "Bad server key size.\n");
1917 			exit(1);
1918 		}
1919 		/*
1920 		 * Check that server and host key lengths differ sufficiently. This
1921 		 * is necessary to make double encryption work with rsaref. Oh, I
1922 		 * hate software patents. I dont know if this can go? Niels
1923 		 */
1924 		if (options.server_key_bits >
1925 		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
1926 		    SSH_KEY_BITS_RESERVED && options.server_key_bits <
1927 		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1928 		    SSH_KEY_BITS_RESERVED) {
1929 			options.server_key_bits =
1930 			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1931 			    SSH_KEY_BITS_RESERVED;
1932 			debug("Forcing server key to %d bits to make it differ from host key.",
1933 			    options.server_key_bits);
1934 		}
1935 	}
1936 #endif
1937 
1938 	if (use_privsep) {
1939 		struct stat st;
1940 
1941 		if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1942 		    (S_ISDIR(st.st_mode) == 0))
1943 			fatal("Missing privilege separation directory: %s",
1944 			    _PATH_PRIVSEP_CHROOT_DIR);
1945 
1946 #ifdef HAVE_CYGWIN
1947 		if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1948 		    (st.st_uid != getuid () ||
1949 		    (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1950 #else
1951 		if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1952 #endif
1953 			fatal("%s must be owned by root and not group or "
1954 			    "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1955 	}
1956 
1957 	if (test_flag > 1) {
1958 		if (server_match_spec_complete(connection_info) == 1)
1959 			parse_server_match_config(&options, connection_info);
1960 		dump_config(&options);
1961 	}
1962 
1963 	/* Configuration looks good, so exit if in test mode. */
1964 	if (test_flag)
1965 		exit(0);
1966 
1967 	/*
1968 	 * Clear out any supplemental groups we may have inherited.  This
1969 	 * prevents inadvertent creation of files with bad modes (in the
1970 	 * portable version at least, it's certainly possible for PAM
1971 	 * to create a file, and we can't control the code in every
1972 	 * module which might be used).
1973 	 */
1974 	if (setgroups(0, NULL) < 0)
1975 		debug("setgroups() failed: %.200s", strerror(errno));
1976 
1977 	if (rexec_flag) {
1978 		rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1979 		for (i = 0; i < rexec_argc; i++) {
1980 			debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1981 			rexec_argv[i] = saved_argv[i];
1982 		}
1983 		rexec_argv[rexec_argc] = "-R";
1984 		rexec_argv[rexec_argc + 1] = NULL;
1985 	}
1986 
1987 	/* Ensure that umask disallows at least group and world write */
1988 	new_umask = umask(0077) | 0022;
1989 	(void) umask(new_umask);
1990 
1991 	/* Initialize the log (it is reinitialized below in case we forked). */
1992 	if (debug_flag && (!inetd_flag || rexeced_flag))
1993 		log_stderr = 1;
1994 	log_init(__progname, options.log_level, options.log_facility, log_stderr);
1995 
1996 	/*
1997 	 * If not in debugging mode, and not started from inetd, disconnect
1998 	 * from the controlling terminal, and fork.  The original process
1999 	 * exits.
2000 	 */
2001 	if (!(debug_flag || inetd_flag || no_daemon_flag)) {
2002 #ifdef TIOCNOTTY
2003 		int fd;
2004 #endif /* TIOCNOTTY */
2005 		if (daemon(0, 0) < 0)
2006 			fatal("daemon() failed: %.200s", strerror(errno));
2007 
2008 		/* Disconnect from the controlling tty. */
2009 #ifdef TIOCNOTTY
2010 		fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
2011 		if (fd >= 0) {
2012 			(void) ioctl(fd, TIOCNOTTY, NULL);
2013 			close(fd);
2014 		}
2015 #endif /* TIOCNOTTY */
2016 	}
2017 	/* Reinitialize the log (because of the fork above). */
2018 	log_init(__progname, options.log_level, options.log_facility, log_stderr);
2019 
2020 	/* Avoid killing the process in high-pressure swapping environments. */
2021 	if (!inetd_flag && madvise(NULL, 0, MADV_PROTECT) != 0)
2022 		debug("madvise(): %.200s", strerror(errno));
2023 
2024 	/* Chdir to the root directory so that the current disk can be
2025 	   unmounted if desired. */
2026 	if (chdir("/") == -1)
2027 		error("chdir(\"/\"): %s", strerror(errno));
2028 
2029 	/* ignore SIGPIPE */
2030 	signal(SIGPIPE, SIG_IGN);
2031 
2032 	/* Get a connection, either from inetd or a listening TCP socket */
2033 	if (inetd_flag) {
2034 		server_accept_inetd(&sock_in, &sock_out);
2035 	} else {
2036 		platform_pre_listen();
2037 		server_listen();
2038 
2039 		if (options.protocol & SSH_PROTO_1)
2040 			generate_ephemeral_server_key();
2041 
2042 		signal(SIGHUP, sighup_handler);
2043 		signal(SIGCHLD, main_sigchld_handler);
2044 		signal(SIGTERM, sigterm_handler);
2045 		signal(SIGQUIT, sigterm_handler);
2046 
2047 		/*
2048 		 * Write out the pid file after the sigterm handler
2049 		 * is setup and the listen sockets are bound
2050 		 */
2051 		if (options.pid_file != NULL && !debug_flag) {
2052 			FILE *f = fopen(options.pid_file, "w");
2053 
2054 			if (f == NULL) {
2055 				error("Couldn't create pid file \"%s\": %s",
2056 				    options.pid_file, strerror(errno));
2057 			} else {
2058 				fprintf(f, "%ld\n", (long) getpid());
2059 				fclose(f);
2060 			}
2061 		}
2062 
2063 		/* Accept a connection and return in a forked child */
2064 		server_accept_loop(&sock_in, &sock_out,
2065 		    &newsock, config_s);
2066 	}
2067 
2068 	/* This is the child processing a new connection. */
2069 	setproctitle("%s", "[accepted]");
2070 
2071 	/*
2072 	 * Create a new session and process group since the 4.4BSD
2073 	 * setlogin() affects the entire process group.  We don't
2074 	 * want the child to be able to affect the parent.
2075 	 */
2076 #if !defined(SSHD_ACQUIRES_CTTY)
2077 	/*
2078 	 * If setsid is called, on some platforms sshd will later acquire a
2079 	 * controlling terminal which will result in "could not set
2080 	 * controlling tty" errors.
2081 	 */
2082 	if (!debug_flag && !inetd_flag && setsid() < 0)
2083 		error("setsid: %.100s", strerror(errno));
2084 #endif
2085 
2086 	if (rexec_flag) {
2087 		int fd;
2088 
2089 		debug("rexec start in %d out %d newsock %d pipe %d sock %d",
2090 		    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
2091 		dup2(newsock, STDIN_FILENO);
2092 		dup2(STDIN_FILENO, STDOUT_FILENO);
2093 		if (startup_pipe == -1)
2094 			close(REEXEC_STARTUP_PIPE_FD);
2095 		else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) {
2096 			dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
2097 			close(startup_pipe);
2098 			startup_pipe = REEXEC_STARTUP_PIPE_FD;
2099 		}
2100 
2101 		dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
2102 		close(config_s[1]);
2103 
2104 		execv(rexec_argv[0], rexec_argv);
2105 
2106 		/* Reexec has failed, fall back and continue */
2107 		error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
2108 		recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
2109 		log_init(__progname, options.log_level,
2110 		    options.log_facility, log_stderr);
2111 
2112 		/* Clean up fds */
2113 		close(REEXEC_CONFIG_PASS_FD);
2114 		newsock = sock_out = sock_in = dup(STDIN_FILENO);
2115 		if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
2116 			dup2(fd, STDIN_FILENO);
2117 			dup2(fd, STDOUT_FILENO);
2118 			if (fd > STDERR_FILENO)
2119 				close(fd);
2120 		}
2121 		debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
2122 		    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
2123 	}
2124 
2125 	/* Executed child processes don't need these. */
2126 	fcntl(sock_out, F_SETFD, FD_CLOEXEC);
2127 	fcntl(sock_in, F_SETFD, FD_CLOEXEC);
2128 
2129 	/*
2130 	 * Disable the key regeneration alarm.  We will not regenerate the
2131 	 * key since we are no longer in a position to give it to anyone. We
2132 	 * will not restart on SIGHUP since it no longer makes sense.
2133 	 */
2134 	alarm(0);
2135 	signal(SIGALRM, SIG_DFL);
2136 	signal(SIGHUP, SIG_DFL);
2137 	signal(SIGTERM, SIG_DFL);
2138 	signal(SIGQUIT, SIG_DFL);
2139 	signal(SIGCHLD, SIG_DFL);
2140 	signal(SIGINT, SIG_DFL);
2141 
2142 #ifdef __FreeBSD__
2143 	/*
2144 	 * Initialize the resolver.  This may not happen automatically
2145 	 * before privsep chroot().
2146 	 */
2147 	if ((_res.options & RES_INIT) == 0) {
2148 		debug("res_init()");
2149 		res_init();
2150 	}
2151 #ifdef GSSAPI
2152 	/*
2153 	 * Force GSS-API to parse its configuration and load any
2154 	 * mechanism plugins.
2155 	 */
2156 	{
2157 		gss_OID_set mechs;
2158 		OM_uint32 minor_status;
2159 		gss_indicate_mechs(&minor_status, &mechs);
2160 		gss_release_oid_set(&minor_status, &mechs);
2161 	}
2162 #endif
2163 #endif
2164 
2165 	/*
2166 	 * Register our connection.  This turns encryption off because we do
2167 	 * not have a key.
2168 	 */
2169 	packet_set_connection(sock_in, sock_out);
2170 	packet_set_server();
2171 
2172 	/* Set SO_KEEPALIVE if requested. */
2173 	if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
2174 	    setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
2175 		error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
2176 
2177 	if ((remote_port = get_remote_port()) < 0) {
2178 		debug("get_remote_port failed");
2179 		cleanup_exit(255);
2180 	}
2181 
2182 	/*
2183 	 * We use get_canonical_hostname with usedns = 0 instead of
2184 	 * get_remote_ipaddr here so IP options will be checked.
2185 	 */
2186 	(void) get_canonical_hostname(0);
2187 	/*
2188 	 * The rest of the code depends on the fact that
2189 	 * get_remote_ipaddr() caches the remote ip, even if
2190 	 * the socket goes away.
2191 	 */
2192 	remote_ip = get_remote_ipaddr();
2193 
2194 #ifdef SSH_AUDIT_EVENTS
2195 	audit_connection_from(remote_ip, remote_port);
2196 #endif
2197 #ifdef LIBWRAP
2198 	allow_severity = options.log_facility|LOG_INFO;
2199 	deny_severity = options.log_facility|LOG_WARNING;
2200 	/* Check whether logins are denied from this host. */
2201 	if (packet_connection_is_on_socket()) {
2202 		struct request_info req;
2203 
2204 		request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
2205 		fromhost(&req);
2206 
2207 		if (!hosts_access(&req)) {
2208 			debug("Connection refused by tcp wrapper");
2209 			refuse(&req);
2210 			/* NOTREACHED */
2211 			fatal("libwrap refuse returns");
2212 		}
2213 	}
2214 #endif /* LIBWRAP */
2215 
2216 	/* Log the connection. */
2217 	laddr = get_local_ipaddr(sock_in);
2218 	verbose("Connection from %s port %d on %s port %d",
2219 	    remote_ip, remote_port, laddr,  get_local_port());
2220 	free(laddr);
2221 
2222 	/*
2223 	 * We don't want to listen forever unless the other side
2224 	 * successfully authenticates itself.  So we set up an alarm which is
2225 	 * cleared after successful authentication.  A limit of zero
2226 	 * indicates no limit. Note that we don't set the alarm in debugging
2227 	 * mode; it is just annoying to have the server exit just when you
2228 	 * are about to discover the bug.
2229 	 */
2230 	signal(SIGALRM, grace_alarm_handler);
2231 	if (!debug_flag)
2232 		alarm(options.login_grace_time);
2233 
2234 	sshd_exchange_identification(sock_in, sock_out);
2235 
2236 	/* In inetd mode, generate ephemeral key only for proto 1 connections */
2237 	if (!compat20 && inetd_flag && sensitive_data.server_key == NULL)
2238 		generate_ephemeral_server_key();
2239 
2240 	packet_set_nonblocking();
2241 
2242 	/* allocate authentication context */
2243 	authctxt = xcalloc(1, sizeof(*authctxt));
2244 
2245 	authctxt->loginmsg = &loginmsg;
2246 
2247 	/* XXX global for cleanup, access from other modules */
2248 	the_authctxt = authctxt;
2249 
2250 	/* prepare buffer to collect messages to display to user after login */
2251 	buffer_init(&loginmsg);
2252 	auth_debug_reset();
2253 
2254 	if (use_privsep) {
2255 		if (privsep_preauth(authctxt) == 1)
2256 			goto authenticated;
2257 	} else if (compat20 && have_agent) {
2258 		if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) {
2259 			error("Unable to get agent socket: %s", ssh_err(r));
2260 			have_agent = 0;
2261 		}
2262 	}
2263 
2264 	/* perform the key exchange */
2265 	/* authenticate user and start session */
2266 	if (compat20) {
2267 		do_ssh2_kex();
2268 		do_authentication2(authctxt);
2269 	} else {
2270 #ifdef WITH_SSH1
2271 		do_ssh1_kex();
2272 		do_authentication(authctxt);
2273 #else
2274 		fatal("ssh1 not supported");
2275 #endif
2276 	}
2277 	/*
2278 	 * If we use privilege separation, the unprivileged child transfers
2279 	 * the current keystate and exits
2280 	 */
2281 	if (use_privsep) {
2282 		mm_send_keystate(pmonitor);
2283 		exit(0);
2284 	}
2285 
2286  authenticated:
2287 	/*
2288 	 * Cancel the alarm we set to limit the time taken for
2289 	 * authentication.
2290 	 */
2291 	alarm(0);
2292 	signal(SIGALRM, SIG_DFL);
2293 	authctxt->authenticated = 1;
2294 	if (startup_pipe != -1) {
2295 		close(startup_pipe);
2296 		startup_pipe = -1;
2297 	}
2298 
2299 #ifdef SSH_AUDIT_EVENTS
2300 	audit_event(SSH_AUTH_SUCCESS);
2301 #endif
2302 
2303 #ifdef GSSAPI
2304 	if (options.gss_authentication) {
2305 		temporarily_use_uid(authctxt->pw);
2306 		ssh_gssapi_storecreds();
2307 		restore_uid();
2308 	}
2309 #endif
2310 #ifdef USE_PAM
2311 	if (options.use_pam) {
2312 		do_pam_setcred(1);
2313 		do_pam_session();
2314 	}
2315 #endif
2316 
2317 	/*
2318 	 * In privilege separation, we fork another child and prepare
2319 	 * file descriptor passing.
2320 	 */
2321 	if (use_privsep) {
2322 		privsep_postauth(authctxt);
2323 		/* the monitor process [priv] will not return */
2324 		if (!compat20)
2325 			destroy_sensitive_data();
2326 	}
2327 
2328 	packet_set_timeout(options.client_alive_interval,
2329 	    options.client_alive_count_max);
2330 
2331 	/* Try to send all our hostkeys to the client */
2332 	if (compat20)
2333 		notify_hostkeys(active_state);
2334 
2335 	/* Start session. */
2336 	do_authenticated(authctxt);
2337 
2338 	/* The connection has been terminated. */
2339 	packet_get_bytes(&ibytes, &obytes);
2340 	verbose("Transferred: sent %llu, received %llu bytes",
2341 	    (unsigned long long)obytes, (unsigned long long)ibytes);
2342 
2343 	verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
2344 
2345 #ifdef USE_PAM
2346 	if (options.use_pam)
2347 		finish_pam();
2348 #endif /* USE_PAM */
2349 
2350 #ifdef SSH_AUDIT_EVENTS
2351 	PRIVSEP(audit_event(SSH_CONNECTION_CLOSE));
2352 #endif
2353 
2354 	packet_close();
2355 
2356 	if (use_privsep)
2357 		mm_terminate();
2358 
2359 	exit(0);
2360 }
2361 
2362 #ifdef WITH_SSH1
2363 /*
2364  * Decrypt session_key_int using our private server key and private host key
2365  * (key with larger modulus first).
2366  */
2367 int
2368 ssh1_session_key(BIGNUM *session_key_int)
2369 {
2370 	int rsafail = 0;
2371 
2372 	if (BN_cmp(sensitive_data.server_key->rsa->n,
2373 	    sensitive_data.ssh1_host_key->rsa->n) > 0) {
2374 		/* Server key has bigger modulus. */
2375 		if (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 			fatal("do_connection: %s: "
2379 			    "server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
2380 			    get_remote_ipaddr(),
2381 			    BN_num_bits(sensitive_data.server_key->rsa->n),
2382 			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2383 			    SSH_KEY_BITS_RESERVED);
2384 		}
2385 		if (rsa_private_decrypt(session_key_int, session_key_int,
2386 		    sensitive_data.server_key->rsa) != 0)
2387 			rsafail++;
2388 		if (rsa_private_decrypt(session_key_int, session_key_int,
2389 		    sensitive_data.ssh1_host_key->rsa) != 0)
2390 			rsafail++;
2391 	} else {
2392 		/* Host key has bigger modulus (or they are equal). */
2393 		if (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 			fatal("do_connection: %s: "
2397 			    "host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
2398 			    get_remote_ipaddr(),
2399 			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2400 			    BN_num_bits(sensitive_data.server_key->rsa->n),
2401 			    SSH_KEY_BITS_RESERVED);
2402 		}
2403 		if (rsa_private_decrypt(session_key_int, session_key_int,
2404 		    sensitive_data.ssh1_host_key->rsa) != 0)
2405 			rsafail++;
2406 		if (rsa_private_decrypt(session_key_int, session_key_int,
2407 		    sensitive_data.server_key->rsa) != 0)
2408 			rsafail++;
2409 	}
2410 	return (rsafail);
2411 }
2412 
2413 /*
2414  * SSH1 key exchange
2415  */
2416 static void
2417 do_ssh1_kex(void)
2418 {
2419 	int i, len;
2420 	int rsafail = 0;
2421 	BIGNUM *session_key_int, *fake_key_int, *real_key_int;
2422 	u_char session_key[SSH_SESSION_KEY_LENGTH];
2423 	u_char fake_key_bytes[4096 / 8];
2424 	size_t fake_key_len;
2425 	u_char cookie[8];
2426 	u_int cipher_type, auth_mask, protocol_flags;
2427 
2428 	/*
2429 	 * Generate check bytes that the client must send back in the user
2430 	 * packet in order for it to be accepted; this is used to defy ip
2431 	 * spoofing attacks.  Note that this only works against somebody
2432 	 * doing IP spoofing from a remote machine; any machine on the local
2433 	 * network can still see outgoing packets and catch the random
2434 	 * cookie.  This only affects rhosts authentication, and this is one
2435 	 * of the reasons why it is inherently insecure.
2436 	 */
2437 	arc4random_buf(cookie, sizeof(cookie));
2438 
2439 	/*
2440 	 * Send our public key.  We include in the packet 64 bits of random
2441 	 * data that must be matched in the reply in order to prevent IP
2442 	 * spoofing.
2443 	 */
2444 	packet_start(SSH_SMSG_PUBLIC_KEY);
2445 	for (i = 0; i < 8; i++)
2446 		packet_put_char(cookie[i]);
2447 
2448 	/* Store our public server RSA key. */
2449 	packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
2450 	packet_put_bignum(sensitive_data.server_key->rsa->e);
2451 	packet_put_bignum(sensitive_data.server_key->rsa->n);
2452 
2453 	/* Store our public host RSA key. */
2454 	packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2455 	packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
2456 	packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
2457 
2458 	/* Put protocol flags. */
2459 	packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
2460 
2461 	/* Declare which ciphers we support. */
2462 	packet_put_int(cipher_mask_ssh1(0));
2463 
2464 	/* Declare supported authentication types. */
2465 	auth_mask = 0;
2466 	if (options.rhosts_rsa_authentication)
2467 		auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
2468 	if (options.rsa_authentication)
2469 		auth_mask |= 1 << SSH_AUTH_RSA;
2470 	if (options.challenge_response_authentication == 1)
2471 		auth_mask |= 1 << SSH_AUTH_TIS;
2472 	if (options.password_authentication)
2473 		auth_mask |= 1 << SSH_AUTH_PASSWORD;
2474 	packet_put_int(auth_mask);
2475 
2476 	/* Send the packet and wait for it to be sent. */
2477 	packet_send();
2478 	packet_write_wait();
2479 
2480 	debug("Sent %d bit server key and %d bit host key.",
2481 	    BN_num_bits(sensitive_data.server_key->rsa->n),
2482 	    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2483 
2484 	/* Read clients reply (cipher type and session key). */
2485 	packet_read_expect(SSH_CMSG_SESSION_KEY);
2486 
2487 	/* Get cipher type and check whether we accept this. */
2488 	cipher_type = packet_get_char();
2489 
2490 	if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
2491 		packet_disconnect("Warning: client selects unsupported cipher.");
2492 
2493 	/* Get check bytes from the packet.  These must match those we
2494 	   sent earlier with the public key packet. */
2495 	for (i = 0; i < 8; i++)
2496 		if (cookie[i] != packet_get_char())
2497 			packet_disconnect("IP Spoofing check bytes do not match.");
2498 
2499 	debug("Encryption type: %.200s", cipher_name(cipher_type));
2500 
2501 	/* Get the encrypted integer. */
2502 	if ((real_key_int = BN_new()) == NULL)
2503 		fatal("do_ssh1_kex: BN_new failed");
2504 	packet_get_bignum(real_key_int);
2505 
2506 	protocol_flags = packet_get_int();
2507 	packet_set_protocol_flags(protocol_flags);
2508 	packet_check_eom();
2509 
2510 	/* Setup a fake key in case RSA decryption fails */
2511 	if ((fake_key_int = BN_new()) == NULL)
2512 		fatal("do_ssh1_kex: BN_new failed");
2513 	fake_key_len = BN_num_bytes(real_key_int);
2514 	if (fake_key_len > sizeof(fake_key_bytes))
2515 		fake_key_len = sizeof(fake_key_bytes);
2516 	arc4random_buf(fake_key_bytes, fake_key_len);
2517 	if (BN_bin2bn(fake_key_bytes, fake_key_len, fake_key_int) == NULL)
2518 		fatal("do_ssh1_kex: BN_bin2bn failed");
2519 
2520 	/* Decrypt real_key_int using host/server keys */
2521 	rsafail = PRIVSEP(ssh1_session_key(real_key_int));
2522 	/* If decryption failed, use the fake key. Else, the real key. */
2523 	if (rsafail)
2524 		session_key_int = fake_key_int;
2525 	else
2526 		session_key_int = real_key_int;
2527 
2528 	/*
2529 	 * Extract session key from the decrypted integer.  The key is in the
2530 	 * least significant 256 bits of the integer; the first byte of the
2531 	 * key is in the highest bits.
2532 	 */
2533 	(void) BN_mask_bits(session_key_int, sizeof(session_key) * 8);
2534 	len = BN_num_bytes(session_key_int);
2535 	if (len < 0 || (u_int)len > sizeof(session_key)) {
2536 		error("do_ssh1_kex: bad session key len from %s: "
2537 		    "session_key_int %d > sizeof(session_key) %lu",
2538 		    get_remote_ipaddr(), len, (u_long)sizeof(session_key));
2539 		rsafail++;
2540 	} else {
2541 		explicit_bzero(session_key, sizeof(session_key));
2542 		BN_bn2bin(session_key_int,
2543 		    session_key + sizeof(session_key) - len);
2544 
2545 		derive_ssh1_session_id(
2546 		    sensitive_data.ssh1_host_key->rsa->n,
2547 		    sensitive_data.server_key->rsa->n,
2548 		    cookie, session_id);
2549 		/*
2550 		 * Xor the first 16 bytes of the session key with the
2551 		 * session id.
2552 		 */
2553 		for (i = 0; i < 16; i++)
2554 			session_key[i] ^= session_id[i];
2555 	}
2556 
2557 	/* Destroy the private and public keys. No longer. */
2558 	destroy_sensitive_data();
2559 
2560 	if (use_privsep)
2561 		mm_ssh1_session_id(session_id);
2562 
2563 	/* Destroy the decrypted integer.  It is no longer needed. */
2564 	BN_clear_free(real_key_int);
2565 	BN_clear_free(fake_key_int);
2566 
2567 	/* Set the session key.  From this on all communications will be encrypted. */
2568 	packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
2569 
2570 	/* Destroy our copy of the session key.  It is no longer needed. */
2571 	explicit_bzero(session_key, sizeof(session_key));
2572 
2573 	debug("Received session key; encryption turned on.");
2574 
2575 	/* Send an acknowledgment packet.  Note that this packet is sent encrypted. */
2576 	packet_start(SSH_SMSG_SUCCESS);
2577 	packet_send();
2578 	packet_write_wait();
2579 }
2580 #endif
2581 
2582 int
2583 sshd_hostkey_sign(Key *privkey, Key *pubkey, u_char **signature, size_t *slen,
2584     const u_char *data, size_t dlen, u_int flag)
2585 {
2586 	int r;
2587 	u_int xxx_slen, xxx_dlen = dlen;
2588 
2589 	if (privkey) {
2590 		if (PRIVSEP(key_sign(privkey, signature, &xxx_slen, data, xxx_dlen) < 0))
2591 			fatal("%s: key_sign failed", __func__);
2592 		if (slen)
2593 			*slen = xxx_slen;
2594 	} else if (use_privsep) {
2595 		if (mm_key_sign(pubkey, signature, &xxx_slen, data, xxx_dlen) < 0)
2596 			fatal("%s: pubkey_sign failed", __func__);
2597 		if (slen)
2598 			*slen = xxx_slen;
2599 	} else {
2600 		if ((r = ssh_agent_sign(auth_sock, pubkey, signature, slen,
2601 		    data, dlen, datafellows)) != 0)
2602 			fatal("%s: ssh_agent_sign failed: %s",
2603 			    __func__, ssh_err(r));
2604 	}
2605 	return 0;
2606 }
2607 
2608 /* SSH2 key exchange */
2609 static void
2610 do_ssh2_kex(void)
2611 {
2612 	char *myproposal[PROPOSAL_MAX] = { KEX_SERVER };
2613 	struct kex *kex;
2614 	int r;
2615 
2616 	myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(
2617 	    options.kex_algorithms);
2618 	myproposal[PROPOSAL_ENC_ALGS_CTOS] = compat_cipher_proposal(
2619 	    options.ciphers);
2620 	myproposal[PROPOSAL_ENC_ALGS_STOC] = compat_cipher_proposal(
2621 	    options.ciphers);
2622 	myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2623 	    myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2624 
2625 	if (options.compression == COMP_NONE) {
2626 		myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2627 		myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2628 	} else if (options.compression == COMP_DELAYED) {
2629 		myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2630 		myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com";
2631 	}
2632 
2633 	if (options.rekey_limit || options.rekey_interval)
2634 		packet_set_rekey_limits((u_int32_t)options.rekey_limit,
2635 		    (time_t)options.rekey_interval);
2636 
2637 	myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal(
2638 	    list_hostkey_types());
2639 
2640 	/* start key exchange */
2641 	if ((r = kex_setup(active_state, myproposal)) != 0)
2642 		fatal("kex_setup: %s", ssh_err(r));
2643 	kex = active_state->kex;
2644 #ifdef WITH_OPENSSL
2645 	kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2646 	kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
2647 	kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2648 	kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2649 # ifdef OPENSSL_HAS_ECC
2650 	kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
2651 # endif
2652 #endif
2653 	kex->kex[KEX_C25519_SHA256] = kexc25519_server;
2654 	kex->server = 1;
2655 	kex->client_version_string=client_version_string;
2656 	kex->server_version_string=server_version_string;
2657 	kex->load_host_public_key=&get_hostkey_public_by_type;
2658 	kex->load_host_private_key=&get_hostkey_private_by_type;
2659 	kex->host_key_index=&get_hostkey_index;
2660 	kex->sign = sshd_hostkey_sign;
2661 
2662 	dispatch_run(DISPATCH_BLOCK, &kex->done, active_state);
2663 
2664 	session_id2 = kex->session_id;
2665 	session_id2_len = kex->session_id_len;
2666 
2667 #ifdef DEBUG_KEXDH
2668 	/* send 1st encrypted/maced/compressed message */
2669 	packet_start(SSH2_MSG_IGNORE);
2670 	packet_put_cstring("markus");
2671 	packet_send();
2672 	packet_write_wait();
2673 #endif
2674 	debug("KEX done");
2675 }
2676 
2677 /* server specific fatal cleanup */
2678 void
2679 cleanup_exit(int i)
2680 {
2681 	if (the_authctxt) {
2682 		do_cleanup(the_authctxt);
2683 		if (use_privsep && privsep_is_preauth &&
2684 		    pmonitor != NULL && pmonitor->m_pid > 1) {
2685 			debug("Killing privsep child %d", pmonitor->m_pid);
2686 			if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
2687 			    errno != ESRCH)
2688 				error("%s: kill(%d): %s", __func__,
2689 				    pmonitor->m_pid, strerror(errno));
2690 		}
2691 	}
2692 #ifdef SSH_AUDIT_EVENTS
2693 	/* done after do_cleanup so it can cancel the PAM auth 'thread' */
2694 	if (!use_privsep || mm_is_monitor())
2695 		audit_event(SSH_CONNECTION_ABANDON);
2696 #endif
2697 	_exit(i);
2698 }
2699