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