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