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