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