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