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