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