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