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