xref: /freebsd/crypto/openssh/sshd.c (revision 9207b4cff7b8d483f4dd3c62266c2b58819eb7f9)
1 /*
2  * Author: Tatu Ylonen <ylo@cs.hut.fi>
3  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4  *                    All rights reserved
5  * This program is the ssh daemon.  It listens for connections from clients,
6  * and performs authentication, executes use commands or shell, and forwards
7  * information to/from the application to the user client over an encrypted
8  * connection.  This can also handle forwarding of X11, TCP/IP, and
9  * authentication agent connections.
10  *
11  * As far as I am concerned, the code I have written for this software
12  * can be used freely for any purpose.  Any derived versions of this
13  * software must be clearly marked as such, and if the derived work is
14  * incompatible with the protocol description in the RFC file, it must be
15  * called by a name other than "ssh" or "Secure Shell".
16  *
17  * SSH2 implementation:
18  *
19  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
20  *
21  * Redistribution and use in source and binary forms, with or without
22  * modification, are permitted provided that the following conditions
23  * are met:
24  * 1. Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  * 2. Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in the
28  *    documentation and/or other materials provided with the distribution.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40  */
41 
42 #include "includes.h"
43 RCSID("$OpenBSD: sshd.c,v 1.195 2001/04/15 16:58:03 markus Exp $");
44 RCSID("$FreeBSD$");
45 
46 #include <openssl/dh.h>
47 #include <openssl/bn.h>
48 #include <openssl/hmac.h>
49 
50 #include "ssh.h"
51 #include "ssh1.h"
52 #include "ssh2.h"
53 #include "xmalloc.h"
54 #include "rsa.h"
55 #include "sshpty.h"
56 #include "packet.h"
57 #include "mpaux.h"
58 #include "log.h"
59 #include "servconf.h"
60 #include "uidswap.h"
61 #include "compat.h"
62 #include "buffer.h"
63 #include <poll.h>
64 #include <time.h>
65 
66 #include "cipher.h"
67 #include "kex.h"
68 #include "key.h"
69 #include "dh.h"
70 #include "myproposal.h"
71 #include "authfile.h"
72 #include "pathnames.h"
73 #include "atomicio.h"
74 #include "canohost.h"
75 #include "auth.h"
76 #include "misc.h"
77 #include "dispatch.h"
78 
79 #ifdef LIBWRAP
80 #include <tcpd.h>
81 #include <syslog.h>
82 int allow_severity = LOG_INFO;
83 int deny_severity = LOG_WARNING;
84 #endif /* LIBWRAP */
85 
86 #ifndef O_NOCTTY
87 #define O_NOCTTY	0
88 #endif
89 
90 #ifdef KRB5
91 #include <krb5.h>
92 #endif /* KRB5 */
93 
94 extern char *__progname;
95 
96 /* Server configuration options. */
97 ServerOptions options;
98 
99 /* Name of the server configuration file. */
100 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
101 
102 /*
103  * Flag indicating whether IPv4 or IPv6.  This can be set on the command line.
104  * Default value is AF_UNSPEC means both IPv4 and IPv6.
105  */
106 int IPv4or6 = AF_UNSPEC;
107 
108 /*
109  * Debug mode flag.  This can be set on the command line.  If debug
110  * mode is enabled, extra debugging output will be sent to the system
111  * log, the daemon will not go to background, and will exit after processing
112  * the first connection.
113  */
114 int debug_flag = 0;
115 
116 /* Flag indicating that the daemon is being started from inetd. */
117 int inetd_flag = 0;
118 
119 /* Flag indicating that sshd should not detach and become a daemon. */
120 int no_daemon_flag = 0;
121 
122 /* debug goes to stderr unless inetd_flag is set */
123 int log_stderr = 0;
124 
125 /* Saved arguments to main(). */
126 char **saved_argv;
127 
128 /*
129  * The sockets that the server is listening; this is used in the SIGHUP
130  * signal handler.
131  */
132 #define	MAX_LISTEN_SOCKS	16
133 int listen_socks[MAX_LISTEN_SOCKS];
134 int num_listen_socks = 0;
135 
136 /*
137  * the client's version string, passed by sshd2 in compat mode. if != NULL,
138  * sshd will skip the version-number exchange
139  */
140 char *client_version_string = NULL;
141 char *server_version_string = NULL;
142 
143 /* for rekeying XXX fixme */
144 Kex *xxx_kex;
145 
146 /*
147  * Any really sensitive data in the application is contained in this
148  * structure. The idea is that this structure could be locked into memory so
149  * that the pages do not get written into swap.  However, there are some
150  * problems. The private key contains BIGNUMs, and we do not (in principle)
151  * have access to the internals of them, and locking just the structure is
152  * not very useful.  Currently, memory locking is not implemented.
153  */
154 struct {
155 	Key	*server_key;		/* ephemeral server key */
156 	Key	*ssh1_host_key;		/* ssh1 host key */
157 	Key	**host_keys;		/* all private host keys */
158 	int	have_ssh1_key;
159 	int	have_ssh2_key;
160 	u_char	ssh1_cookie[SSH_SESSION_KEY_LENGTH];
161 } sensitive_data;
162 
163 /*
164  * Flag indicating whether the RSA server key needs to be regenerated.
165  * Is set in the SIGALRM handler and cleared when the key is regenerated.
166  */
167 int key_do_regen = 0;
168 
169 /* This is set to true when SIGHUP is received. */
170 int received_sighup = 0;
171 
172 /* session identifier, used by RSA-auth */
173 u_char session_id[16];
174 
175 /* same for ssh2 */
176 u_char *session_id2 = NULL;
177 int session_id2_len = 0;
178 
179 /* record remote hostname or ip */
180 u_int utmp_len = MAXHOSTNAMELEN;
181 
182 /* Prototypes for various functions defined later in this file. */
183 void do_ssh1_kex(void);
184 void do_ssh2_kex(void);
185 
186 void ssh_dh1_server(Kex *, Buffer *_kexinit, Buffer *);
187 void ssh_dhgex_server(Kex *, Buffer *_kexinit, Buffer *);
188 
189 /*
190  * Close all listening sockets
191  */
192 void
193 close_listen_socks(void)
194 {
195 	int i;
196 	for (i = 0; i < num_listen_socks; i++)
197 		close(listen_socks[i]);
198 	num_listen_socks = -1;
199 }
200 
201 /*
202  * Signal handler for SIGHUP.  Sshd execs itself when it receives SIGHUP;
203  * the effect is to reread the configuration file (and to regenerate
204  * the server key).
205  */
206 void
207 sighup_handler(int sig)
208 {
209 	received_sighup = 1;
210 	signal(SIGHUP, sighup_handler);
211 }
212 
213 /*
214  * Called from the main program after receiving SIGHUP.
215  * Restarts the server.
216  */
217 void
218 sighup_restart(void)
219 {
220 	log("Received SIGHUP; restarting.");
221 	close_listen_socks();
222 	execv(saved_argv[0], saved_argv);
223 	log("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0], strerror(errno));
224 	exit(1);
225 }
226 
227 /*
228  * Generic signal handler for terminating signals in the master daemon.
229  * These close the listen socket; not closing it seems to cause "Address
230  * already in use" problems on some machines, which is inconvenient.
231  */
232 void
233 sigterm_handler(int sig)
234 {
235 	log("Received signal %d; terminating.", sig);
236 	close_listen_socks();
237 	unlink(options.pid_file);
238 	exit(255);
239 }
240 
241 /*
242  * SIGCHLD handler.  This is called whenever a child dies.  This will then
243  * reap any zombies left by exited c.
244  */
245 void
246 main_sigchld_handler(int sig)
247 {
248 	int save_errno = errno;
249 	int status;
250 
251 	while (waitpid(-1, &status, WNOHANG) > 0)
252 		;
253 
254 	signal(SIGCHLD, main_sigchld_handler);
255 	errno = save_errno;
256 }
257 
258 /*
259  * Signal handler for the alarm after the login grace period has expired.
260  */
261 void
262 grace_alarm_handler(int sig)
263 {
264 	/* Close the connection. */
265 	packet_close();
266 
267 	/* Log error and exit. */
268 	fatal("Timeout before authentication for %s.", get_remote_ipaddr());
269 }
270 
271 /*
272  * Signal handler for the key regeneration alarm.  Note that this
273  * alarm only occurs in the daemon waiting for connections, and it does not
274  * do anything with the private key or random state before forking.
275  * Thus there should be no concurrency control/asynchronous execution
276  * problems.
277  */
278 void
279 generate_ephemeral_server_key(void)
280 {
281 	u_int32_t rand = 0;
282 	int i;
283 
284 	verbose("Generating %s%d bit RSA key.",
285 	    sensitive_data.server_key ? "new " : "", options.server_key_bits);
286 	if (sensitive_data.server_key != NULL)
287 		key_free(sensitive_data.server_key);
288 	sensitive_data.server_key = key_generate(KEY_RSA1,
289 	    options.server_key_bits);
290 	verbose("RSA key generation complete.");
291 
292 	for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
293 		if (i % 4 == 0)
294 			rand = arc4random();
295 		sensitive_data.ssh1_cookie[i] = rand & 0xff;
296 		rand >>= 8;
297 	}
298 	arc4random_stir();
299 }
300 
301 void
302 key_regeneration_alarm(int sig)
303 {
304 	int save_errno = errno;
305 	signal(SIGALRM, SIG_DFL);
306 	errno = save_errno;
307 	key_do_regen = 1;
308 }
309 
310 void
311 sshd_exchange_identification(int sock_in, int sock_out)
312 {
313 	int i, mismatch;
314 	int remote_major, remote_minor;
315 	int major, minor;
316 	char *s;
317 	char buf[256];			/* Must not be larger than remote_version. */
318 	char remote_version[256];	/* Must be at least as big as buf. */
319 
320 	if ((options.protocol & SSH_PROTO_1) &&
321 	    (options.protocol & SSH_PROTO_2)) {
322 		major = PROTOCOL_MAJOR_1;
323 		minor = 99;
324 	} else if (options.protocol & SSH_PROTO_2) {
325 		major = PROTOCOL_MAJOR_2;
326 		minor = PROTOCOL_MINOR_2;
327 	} else {
328 		major = PROTOCOL_MAJOR_1;
329 		minor = PROTOCOL_MINOR_1;
330 	}
331 	snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", major, minor, SSH_VERSION);
332 	server_version_string = xstrdup(buf);
333 
334 	if (client_version_string == NULL) {
335 		/* Send our protocol version identification. */
336 		if (atomicio(write, sock_out, server_version_string, strlen(server_version_string))
337 		    != strlen(server_version_string)) {
338 			log("Could not write ident string to %s.", get_remote_ipaddr());
339 			fatal_cleanup();
340 		}
341 
342 		/* Read other side's version identification. */
343 		memset(buf, 0, sizeof(buf));
344 		for (i = 0; i < sizeof(buf) - 1; i++) {
345 			if (atomicio(read, sock_in, &buf[i], 1) != 1) {
346 				log("Did not receive identification string from %s.",
347 				    get_remote_ipaddr());
348 				fatal_cleanup();
349 			}
350 			if (buf[i] == '\r') {
351 				buf[i] = 0;
352 				/* Kludge for F-Secure Macintosh < 1.0.2 */
353 				if (i == 12 &&
354 				    strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
355 					break;
356 				continue;
357 			}
358 			if (buf[i] == '\n') {
359 				buf[i] = 0;
360 				break;
361 			}
362 		}
363 		buf[sizeof(buf) - 1] = 0;
364 		client_version_string = xstrdup(buf);
365 	}
366 
367 	/*
368 	 * Check that the versions match.  In future this might accept
369 	 * several versions and set appropriate flags to handle them.
370 	 */
371 	if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
372 	    &remote_major, &remote_minor, remote_version) != 3) {
373 		s = "Protocol mismatch.\n";
374 		(void) atomicio(write, sock_out, s, strlen(s));
375 		close(sock_in);
376 		close(sock_out);
377 		log("Bad protocol version identification '%.100s' from %s",
378 		    client_version_string, get_remote_ipaddr());
379 		fatal_cleanup();
380 	}
381 	debug("Client protocol version %d.%d; client software version %.100s",
382 	      remote_major, remote_minor, remote_version);
383 
384 	compat_datafellows(remote_version);
385 
386 	if (datafellows & SSH_BUG_SCANNER) {
387 		log("scanned from %s with %s.  Don't panic.",
388 		    get_remote_ipaddr(), client_version_string);
389 		fatal_cleanup();
390 	}
391 
392 	mismatch = 0;
393 	switch(remote_major) {
394 	case 1:
395 		if (remote_minor == 99) {
396 			if (options.protocol & SSH_PROTO_2)
397 				enable_compat20();
398 			else
399 				mismatch = 1;
400 			break;
401 		}
402 		if (!(options.protocol & SSH_PROTO_1)) {
403 			mismatch = 1;
404 			break;
405 		}
406 		if (remote_minor < 3) {
407 			packet_disconnect("Your ssh version is too old and "
408 			    "is no longer supported.  Please install a newer version.");
409 		} else if (remote_minor == 3) {
410 			/* note that this disables agent-forwarding */
411 			enable_compat13();
412 		}
413 		break;
414 	case 2:
415 		if (options.protocol & SSH_PROTO_2) {
416 			enable_compat20();
417 			break;
418 		}
419 		/* FALLTHROUGH */
420 	default:
421 		mismatch = 1;
422 		break;
423 	}
424 	chop(server_version_string);
425 	debug("Local version string %.200s", server_version_string);
426 
427 	if (mismatch) {
428 		s = "Protocol major versions differ.\n";
429 		(void) atomicio(write, sock_out, s, strlen(s));
430 		close(sock_in);
431 		close(sock_out);
432 		log("Protocol major versions differ for %s: %.200s vs. %.200s",
433 		    get_remote_ipaddr(),
434 		    server_version_string, client_version_string);
435 		fatal_cleanup();
436 	}
437 	if (compat20)
438 		packet_set_ssh2_format();
439 }
440 
441 
442 /* Destroy the host and server keys.  They will no longer be needed. */
443 void
444 destroy_sensitive_data(void)
445 {
446 	int i;
447 
448 	if (sensitive_data.server_key) {
449 		key_free(sensitive_data.server_key);
450 		sensitive_data.server_key = NULL;
451 	}
452 	for(i = 0; i < options.num_host_key_files; i++) {
453 		if (sensitive_data.host_keys[i]) {
454 			key_free(sensitive_data.host_keys[i]);
455 			sensitive_data.host_keys[i] = NULL;
456 		}
457 	}
458 	sensitive_data.ssh1_host_key = NULL;
459 	memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
460 }
461 
462 char *
463 list_hostkey_types(void)
464 {
465 	static char buf[1024];
466 	int i;
467 	buf[0] = '\0';
468 	for(i = 0; i < options.num_host_key_files; i++) {
469 		Key *key = sensitive_data.host_keys[i];
470 		if (key == NULL)
471 			continue;
472 		switch(key->type) {
473 		case KEY_RSA:
474 		case KEY_DSA:
475 			strlcat(buf, key_ssh_name(key), sizeof buf);
476 			strlcat(buf, ",", sizeof buf);
477 			break;
478 		}
479 	}
480 	i = strlen(buf);
481 	if (i > 0 && buf[i-1] == ',')
482 		buf[i-1] = '\0';
483 	debug("list_hostkey_types: %s", buf);
484 	return buf;
485 }
486 
487 Key *
488 get_hostkey_by_type(int type)
489 {
490 	int i;
491 	for(i = 0; i < options.num_host_key_files; i++) {
492 		Key *key = sensitive_data.host_keys[i];
493 		if (key != NULL && key->type == type)
494 			return key;
495 	}
496 	return NULL;
497 }
498 
499 /*
500  * returns 1 if connection should be dropped, 0 otherwise.
501  * dropping starts at connection #max_startups_begin with a probability
502  * of (max_startups_rate/100). the probability increases linearly until
503  * all connections are dropped for startups > max_startups
504  */
505 int
506 drop_connection(int startups)
507 {
508 	double p, r;
509 
510 	if (startups < options.max_startups_begin)
511 		return 0;
512 	if (startups >= options.max_startups)
513 		return 1;
514 	if (options.max_startups_rate == 100)
515 		return 1;
516 
517 	p  = 100 - options.max_startups_rate;
518 	p *= startups - options.max_startups_begin;
519 	p /= (double) (options.max_startups - options.max_startups_begin);
520 	p += options.max_startups_rate;
521 	p /= 100.0;
522 	r = arc4random() / (double) UINT_MAX;
523 
524 	debug("drop_connection: p %g, r %g", p, r);
525 	return (r < p) ? 1 : 0;
526 }
527 
528 int *startup_pipes = NULL;	/* options.max_startup sized array of fd ints */
529 int startup_pipe;		/* in child */
530 
531 /*
532  * Main program for the daemon.
533  */
534 int
535 main(int ac, char **av)
536 {
537 	extern char *optarg;
538 	extern int optind;
539 	int opt, sock_in = 0, sock_out = 0, newsock, j, i, fdsetsz, on = 1;
540 	pid_t pid;
541 	socklen_t fromlen;
542 	fd_set *fdset;
543 	struct sockaddr_storage from;
544 	const char *remote_ip;
545 	int remote_port;
546 	FILE *f;
547 	struct linger linger;
548 	struct addrinfo *ai;
549 	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
550 	int listen_sock, maxfd;
551 	int startup_p[2];
552 	int startups = 0;
553 	Key *key;
554 	int ret, key_used = 0;
555 
556 	/* Save argv. */
557 	saved_argv = av;
558 
559 	/* Initialize configuration options to their default values. */
560 	initialize_server_options(&options);
561 
562 	/* Parse command-line arguments. */
563 	while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:u:dDeiqQ46")) != -1) {
564 		switch (opt) {
565 		case '4':
566 			IPv4or6 = AF_INET;
567 			break;
568 		case '6':
569 			IPv4or6 = AF_INET6;
570 			break;
571 		case 'f':
572 			config_file_name = optarg;
573 			break;
574 		case 'd':
575 			if (0 == debug_flag) {
576 				debug_flag = 1;
577 				options.log_level = SYSLOG_LEVEL_DEBUG1;
578 			} else if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
579 				options.log_level++;
580 			} else {
581 				fprintf(stderr, "Too high debugging level.\n");
582 				exit(1);
583 			}
584 			break;
585 		case 'D':
586 			no_daemon_flag = 1;
587 			break;
588 		case 'e':
589 			log_stderr = 1;
590 			break;
591 		case 'i':
592 			inetd_flag = 1;
593 			break;
594 		case 'Q':
595 			/* ignored */
596 			break;
597 		case 'q':
598 			options.log_level = SYSLOG_LEVEL_QUIET;
599 			break;
600 		case 'b':
601 			options.server_key_bits = atoi(optarg);
602 			break;
603 		case 'p':
604 			options.ports_from_cmdline = 1;
605 			if (options.num_ports >= MAX_PORTS) {
606 				fprintf(stderr, "too many ports.\n");
607 				exit(1);
608 			}
609 			options.ports[options.num_ports++] = a2port(optarg);
610 			if (options.ports[options.num_ports-1] == 0) {
611 				fprintf(stderr, "Bad port number.\n");
612 				exit(1);
613 			}
614 			break;
615 		case 'g':
616 			options.login_grace_time = atoi(optarg);
617 			break;
618 		case 'k':
619 			options.key_regeneration_time = atoi(optarg);
620 			break;
621 		case 'h':
622 			if (options.num_host_key_files >= MAX_HOSTKEYS) {
623 				fprintf(stderr, "too many host keys.\n");
624 				exit(1);
625 			}
626 			options.host_key_files[options.num_host_key_files++] = optarg;
627 			break;
628 		case 'V':
629 			client_version_string = optarg;
630 			/* only makes sense with inetd_flag, i.e. no listen() */
631 			inetd_flag = 1;
632 			break;
633 		case 'u':
634 			utmp_len = atoi(optarg);
635 			break;
636 		case '?':
637 		default:
638 			fprintf(stderr, "sshd version %s\n", SSH_VERSION);
639 			fprintf(stderr, "Usage: %s [options]\n", __progname);
640 			fprintf(stderr, "Options:\n");
641 			fprintf(stderr, "  -f file    Configuration file (default %s)\n", _PATH_SERVER_CONFIG_FILE);
642 			fprintf(stderr, "  -d         Debugging mode (multiple -d means more debugging)\n");
643 			fprintf(stderr, "  -i         Started from inetd\n");
644 			fprintf(stderr, "  -D         Do not fork into daemon mode\n");
645 			fprintf(stderr, "  -q         Quiet (no logging)\n");
646 			fprintf(stderr, "  -p port    Listen on the specified port (default: 22)\n");
647 			fprintf(stderr, "  -k seconds Regenerate server key every this many seconds (default: 3600)\n");
648 			fprintf(stderr, "  -g seconds Grace period for authentication (default: 600)\n");
649 			fprintf(stderr, "  -b bits    Size of server RSA key (default: 768 bits)\n");
650 			fprintf(stderr, "  -h file    File from which to read host key (default: %s)\n",
651 			    _PATH_HOST_KEY_FILE);
652 			fprintf(stderr, "  -u len     Maximum hostname length for utmp recording\n");
653 			fprintf(stderr, "  -4         Use IPv4 only\n");
654 			fprintf(stderr, "  -6         Use IPv6 only\n");
655 			exit(1);
656 		}
657 	}
658 	SSLeay_add_all_algorithms();
659 
660 	/*
661 	 * Force logging to stderr until we have loaded the private host
662 	 * key (unless started from inetd)
663 	 */
664 	log_init(__progname,
665 	    options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
666 	    options.log_facility == -1 ? SYSLOG_FACILITY_AUTH : options.log_facility,
667 	    !inetd_flag);
668 
669 	/* Read server configuration options from the configuration file. */
670 	read_server_config(&options, config_file_name);
671 
672 	/* Fill in default values for those options not explicitly set. */
673 	fill_default_server_options(&options);
674 
675 	/* Check that there are no remaining arguments. */
676 	if (optind < ac) {
677 		fprintf(stderr, "Extra argument %s.\n", av[optind]);
678 		exit(1);
679 	}
680 
681 	debug("sshd version %.100s", SSH_VERSION);
682 
683 	/* load private host keys */
684 	sensitive_data.host_keys = xmalloc(options.num_host_key_files*sizeof(Key*));
685 	for(i = 0; i < options.num_host_key_files; i++)
686 		sensitive_data.host_keys[i] = NULL;
687 	sensitive_data.server_key = NULL;
688 	sensitive_data.ssh1_host_key = NULL;
689 	sensitive_data.have_ssh1_key = 0;
690 	sensitive_data.have_ssh2_key = 0;
691 
692 	for(i = 0; i < options.num_host_key_files; i++) {
693 		key = key_load_private(options.host_key_files[i], "", NULL);
694 		sensitive_data.host_keys[i] = key;
695 		if (key == NULL) {
696 			error("Could not load host key: %s",
697 			    options.host_key_files[i]);
698 			sensitive_data.host_keys[i] = NULL;
699 			continue;
700 		}
701 		switch(key->type){
702 		case KEY_RSA1:
703 			sensitive_data.ssh1_host_key = key;
704 			sensitive_data.have_ssh1_key = 1;
705 			break;
706 		case KEY_RSA:
707 		case KEY_DSA:
708 			sensitive_data.have_ssh2_key = 1;
709 			break;
710 		}
711 		debug("private host key: #%d type %d %s", i, key->type,
712 		    key_type(key));
713 	}
714 	if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
715 		log("Disabling protocol version 1. Could not load host key");
716 		options.protocol &= ~SSH_PROTO_1;
717 	}
718 	if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
719 		log("Disabling protocol version 2. Could not load host key");
720 		options.protocol &= ~SSH_PROTO_2;
721 	}
722 	if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
723 		log("sshd: no hostkeys available -- exiting.");
724 		exit(1);
725 	}
726 
727 	/* Check certain values for sanity. */
728 	if (options.protocol & SSH_PROTO_1) {
729 		if (options.server_key_bits < 512 ||
730 		    options.server_key_bits > 32768) {
731 			fprintf(stderr, "Bad server key size.\n");
732 			exit(1);
733 		}
734 		/*
735 		 * Check that server and host key lengths differ sufficiently. This
736 		 * is necessary to make double encryption work with rsaref. Oh, I
737 		 * hate software patents. I dont know if this can go? Niels
738 		 */
739 		if (options.server_key_bits >
740 		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) - SSH_KEY_BITS_RESERVED &&
741 		    options.server_key_bits <
742 		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
743 			options.server_key_bits =
744 			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED;
745 			debug("Forcing server key to %d bits to make it differ from host key.",
746 			    options.server_key_bits);
747 		}
748 	}
749 
750 	/* Initialize the log (it is reinitialized below in case we forked). */
751 	if (debug_flag && !inetd_flag)
752 		log_stderr = 1;
753 	log_init(__progname, options.log_level, options.log_facility, log_stderr);
754 
755 	/*
756 	 * If not in debugging mode, and not started from inetd, disconnect
757 	 * from the controlling terminal, and fork.  The original process
758 	 * exits.
759 	 */
760 	if (!(debug_flag || inetd_flag || no_daemon_flag)) {
761 #ifdef TIOCNOTTY
762 		int fd;
763 #endif /* TIOCNOTTY */
764 		if (daemon(0, 0) < 0)
765 			fatal("daemon() failed: %.200s", strerror(errno));
766 
767 		/* Disconnect from the controlling tty. */
768 #ifdef TIOCNOTTY
769 		fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
770 		if (fd >= 0) {
771 			(void) ioctl(fd, TIOCNOTTY, NULL);
772 			close(fd);
773 		}
774 #endif /* TIOCNOTTY */
775 	}
776 	/* Reinitialize the log (because of the fork above). */
777 	log_init(__progname, options.log_level, options.log_facility, log_stderr);
778 
779 	/* Initialize the random number generator. */
780 	arc4random_stir();
781 
782 	/* Chdir to the root directory so that the current disk can be
783 	   unmounted if desired. */
784 	chdir("/");
785 
786 	/* ignore SIGPIPE */
787 	signal(SIGPIPE, SIG_IGN);
788 
789 	/* Start listening for a socket, unless started from inetd. */
790 	if (inetd_flag) {
791 		int s1;
792 		s1 = dup(0);	/* Make sure descriptors 0, 1, and 2 are in use. */
793 		dup(s1);
794 		sock_in = dup(0);
795 		sock_out = dup(1);
796 		startup_pipe = -1;
797 		/*
798 		 * We intentionally do not close the descriptors 0, 1, and 2
799 		 * as our code for setting the descriptors won\'t work if
800 		 * ttyfd happens to be one of those.
801 		 */
802 		debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
803 		if (options.protocol & SSH_PROTO_1)
804 			generate_ephemeral_server_key();
805 	} else {
806 		for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
807 			if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
808 				continue;
809 			if (num_listen_socks >= MAX_LISTEN_SOCKS)
810 				fatal("Too many listen sockets. "
811 				    "Enlarge MAX_LISTEN_SOCKS");
812 			if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
813 			    ntop, sizeof(ntop), strport, sizeof(strport),
814 			    NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
815 				error("getnameinfo failed");
816 				continue;
817 			}
818 			/* Create socket for listening. */
819 			listen_sock = socket(ai->ai_family, SOCK_STREAM, 0);
820 			if (listen_sock < 0) {
821 				/* kernel may not support ipv6 */
822 				verbose("socket: %.100s", strerror(errno));
823 				continue;
824 			}
825 			if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) {
826 				error("listen_sock O_NONBLOCK: %s", strerror(errno));
827 				close(listen_sock);
828 				continue;
829 			}
830 			/*
831 			 * Set socket options.  We try to make the port
832 			 * reusable and have it close as fast as possible
833 			 * without waiting in unnecessary wait states on
834 			 * close.
835 			 */
836 			setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
837 			    (void *) &on, sizeof(on));
838 			linger.l_onoff = 1;
839 			linger.l_linger = 5;
840 			setsockopt(listen_sock, SOL_SOCKET, SO_LINGER,
841 			    (void *) &linger, sizeof(linger));
842 
843 			debug("Bind to port %s on %s.", strport, ntop);
844 
845 			/* Bind the socket to the desired port. */
846 			if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
847 				error("Bind to port %s on %s failed: %.200s.",
848 				    strport, ntop, strerror(errno));
849 				close(listen_sock);
850 				continue;
851 			}
852 			listen_socks[num_listen_socks] = listen_sock;
853 			num_listen_socks++;
854 
855 			/* Start listening on the port. */
856 			log("Server listening on %s port %s.", ntop, strport);
857 			if (listen(listen_sock, 5) < 0)
858 				fatal("listen: %.100s", strerror(errno));
859 
860 		}
861 		freeaddrinfo(options.listen_addrs);
862 
863 		if (!num_listen_socks)
864 			fatal("Cannot bind any address.");
865 
866 		if (!debug_flag) {
867 			/*
868 			 * Record our pid in /var/run/sshd.pid to make it
869 			 * easier to kill the correct sshd.  We don't want to
870 			 * do this before the bind above because the bind will
871 			 * fail if there already is a daemon, and this will
872 			 * overwrite any old pid in the file.
873 			 */
874 			f = fopen(options.pid_file, "w");
875 			if (f) {
876 				fprintf(f, "%u\n", (u_int) getpid());
877 				fclose(f);
878 			}
879 		}
880 		if (options.protocol & SSH_PROTO_1)
881 			generate_ephemeral_server_key();
882 
883 		/* Arrange to restart on SIGHUP.  The handler needs listen_sock. */
884 		signal(SIGHUP, sighup_handler);
885 
886 		signal(SIGTERM, sigterm_handler);
887 		signal(SIGQUIT, sigterm_handler);
888 
889 		/* Arrange SIGCHLD to be caught. */
890 		signal(SIGCHLD, main_sigchld_handler);
891 
892 		/* setup fd set for listen */
893 		fdset = NULL;
894 		maxfd = 0;
895 		for (i = 0; i < num_listen_socks; i++)
896 			if (listen_socks[i] > maxfd)
897 				maxfd = listen_socks[i];
898 		/* pipes connected to unauthenticated childs */
899 		startup_pipes = xmalloc(options.max_startups * sizeof(int));
900 		for (i = 0; i < options.max_startups; i++)
901 			startup_pipes[i] = -1;
902 
903 		/*
904 		 * Stay listening for connections until the system crashes or
905 		 * the daemon is killed with a signal.
906 		 */
907 		for (;;) {
908 			if (received_sighup)
909 				sighup_restart();
910 			if (fdset != NULL)
911 				xfree(fdset);
912 			fdsetsz = howmany(maxfd+1, NFDBITS) * sizeof(fd_mask);
913 			fdset = (fd_set *)xmalloc(fdsetsz);
914 			memset(fdset, 0, fdsetsz);
915 
916 			for (i = 0; i < num_listen_socks; i++)
917 				FD_SET(listen_socks[i], fdset);
918 			for (i = 0; i < options.max_startups; i++)
919 				if (startup_pipes[i] != -1)
920 					FD_SET(startup_pipes[i], fdset);
921 
922 			/* Wait in select until there is a connection. */
923 			ret = select(maxfd+1, fdset, NULL, NULL, NULL);
924 			if (ret < 0 && errno != EINTR)
925 				error("select: %.100s", strerror(errno));
926 			if (key_used && key_do_regen) {
927 				generate_ephemeral_server_key();
928 				key_used = 0;
929 				key_do_regen = 0;
930 			}
931 			if (ret < 0)
932 				continue;
933 
934 			for (i = 0; i < options.max_startups; i++)
935 				if (startup_pipes[i] != -1 &&
936 				    FD_ISSET(startup_pipes[i], fdset)) {
937 					/*
938 					 * the read end of the pipe is ready
939 					 * if the child has closed the pipe
940 					 * after successful authentication
941 					 * or if the child has died
942 					 */
943 					close(startup_pipes[i]);
944 					startup_pipes[i] = -1;
945 					startups--;
946 				}
947 			for (i = 0; i < num_listen_socks; i++) {
948 				if (!FD_ISSET(listen_socks[i], fdset))
949 					continue;
950 				fromlen = sizeof(from);
951 				newsock = accept(listen_socks[i], (struct sockaddr *)&from,
952 				    &fromlen);
953 				if (newsock < 0) {
954 					if (errno != EINTR && errno != EWOULDBLOCK)
955 						error("accept: %.100s", strerror(errno));
956 					continue;
957 				}
958 				if (fcntl(newsock, F_SETFL, 0) < 0) {
959 					error("newsock del O_NONBLOCK: %s", strerror(errno));
960 					continue;
961 				}
962 				if (drop_connection(startups) == 1) {
963 					debug("drop connection #%d", startups);
964 					close(newsock);
965 					continue;
966 				}
967 				if (pipe(startup_p) == -1) {
968 					close(newsock);
969 					continue;
970 				}
971 
972 				for (j = 0; j < options.max_startups; j++)
973 					if (startup_pipes[j] == -1) {
974 						startup_pipes[j] = startup_p[0];
975 						if (maxfd < startup_p[0])
976 							maxfd = startup_p[0];
977 						startups++;
978 						break;
979 					}
980 
981 				/*
982 				 * Got connection.  Fork a child to handle it, unless
983 				 * we are in debugging mode.
984 				 */
985 				if (debug_flag) {
986 					/*
987 					 * In debugging mode.  Close the listening
988 					 * socket, and start processing the
989 					 * connection without forking.
990 					 */
991 					debug("Server will not fork when running in debugging mode.");
992 					close_listen_socks();
993 					sock_in = newsock;
994 					sock_out = newsock;
995 					startup_pipe = -1;
996 					pid = getpid();
997 					break;
998 				} else {
999 					/*
1000 					 * Normal production daemon.  Fork, and have
1001 					 * the child process the connection. The
1002 					 * parent continues listening.
1003 					 */
1004 					if ((pid = fork()) == 0) {
1005 						/*
1006 						 * Child.  Close the listening and max_startup
1007 						 * sockets.  Start using the accepted socket.
1008 						 * Reinitialize logging (since our pid has
1009 						 * changed).  We break out of the loop to handle
1010 						 * the connection.
1011 						 */
1012 						startup_pipe = startup_p[1];
1013 						for (j = 0; j < options.max_startups; j++)
1014 							if (startup_pipes[j] != -1)
1015 								close(startup_pipes[j]);
1016 						close_listen_socks();
1017 						sock_in = newsock;
1018 						sock_out = newsock;
1019 						log_init(__progname, options.log_level, options.log_facility, log_stderr);
1020 						break;
1021 					}
1022 				}
1023 
1024 				/* Parent.  Stay in the loop. */
1025 				if (pid < 0)
1026 					error("fork: %.100s", strerror(errno));
1027 				else
1028 					debug("Forked child %d.", pid);
1029 
1030 				close(startup_p[1]);
1031 
1032 				/* Mark that the key has been used (it was "given" to the child). */
1033 				if ((options.protocol & SSH_PROTO_1) &&
1034 				    key_used == 0) {
1035 					/* Schedule server key regeneration alarm. */
1036 					signal(SIGALRM, key_regeneration_alarm);
1037 					alarm(options.key_regeneration_time);
1038 					key_used = 1;
1039 				}
1040 
1041 				arc4random_stir();
1042 
1043 				/* Close the new socket (the child is now taking care of it). */
1044 				close(newsock);
1045 			}
1046 			/* child process check (or debug mode) */
1047 			if (num_listen_socks < 0)
1048 				break;
1049 		}
1050 	}
1051 
1052 	/* This is the child processing a new connection. */
1053 
1054 	/*
1055 	 * Disable the key regeneration alarm.  We will not regenerate the
1056 	 * key since we are no longer in a position to give it to anyone. We
1057 	 * will not restart on SIGHUP since it no longer makes sense.
1058 	 */
1059 	alarm(0);
1060 	signal(SIGALRM, SIG_DFL);
1061 	signal(SIGHUP, SIG_DFL);
1062 	signal(SIGTERM, SIG_DFL);
1063 	signal(SIGQUIT, SIG_DFL);
1064 	signal(SIGCHLD, SIG_DFL);
1065 	signal(SIGPIPE, SIG_IGN);
1066 
1067 	/*
1068 	 * Set socket options for the connection.  We want the socket to
1069 	 * close as fast as possible without waiting for anything.  If the
1070 	 * connection is not a socket, these will do nothing.
1071 	 */
1072 	/* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
1073 	linger.l_onoff = 1;
1074 	linger.l_linger = 5;
1075 	setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
1076 
1077 	/* Set keepalives if requested. */
1078 	if (options.keepalives &&
1079 	    setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, (void *)&on,
1080 	    sizeof(on)) < 0)
1081 		error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1082 
1083 	/*
1084 	 * Register our connection.  This turns encryption off because we do
1085 	 * not have a key.
1086 	 */
1087 	packet_set_connection(sock_in, sock_out);
1088 
1089 	remote_port = get_remote_port();
1090 	remote_ip = get_remote_ipaddr();
1091 
1092 	/* Check whether logins are denied from this host. */
1093 #ifdef LIBWRAP
1094 	{
1095 		struct request_info req;
1096 
1097 		request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, NULL);
1098 		fromhost(&req);
1099 
1100 		if (!hosts_access(&req)) {
1101 			refuse(&req);
1102 			close(sock_in);
1103 			close(sock_out);
1104 		}
1105 		verbose("Connection from %.500s port %d", eval_client(&req), remote_port);
1106 	}
1107 #endif /* LIBWRAP */
1108 	/* Log the connection. */
1109 	verbose("Connection from %.500s port %d", remote_ip, remote_port);
1110 
1111 	/*
1112 	 * We don\'t want to listen forever unless the other side
1113 	 * successfully authenticates itself.  So we set up an alarm which is
1114 	 * cleared after successful authentication.  A limit of zero
1115 	 * indicates no limit. Note that we don\'t set the alarm in debugging
1116 	 * mode; it is just annoying to have the server exit just when you
1117 	 * are about to discover the bug.
1118 	 */
1119 	signal(SIGALRM, grace_alarm_handler);
1120 	if (!debug_flag)
1121 		alarm(options.login_grace_time);
1122 
1123 	sshd_exchange_identification(sock_in, sock_out);
1124 	/*
1125 	 * Check that the connection comes from a privileged port.
1126 	 * Rhosts-Authentication only makes sense from priviledged
1127 	 * programs.  Of course, if the intruder has root access on his local
1128 	 * machine, he can connect from any port.  So do not use these
1129 	 * authentication methods from machines that you do not trust.
1130 	 */
1131 	if (remote_port >= IPPORT_RESERVED ||
1132 	    remote_port < IPPORT_RESERVED / 2) {
1133 		debug("Rhosts Authentication disabled, "
1134 		    "originating port not trusted.");
1135 		options.rhosts_authentication = 0;
1136 	}
1137 #if defined(KRB4) && !defined(KRB5)
1138 	if (!packet_connection_is_ipv4() &&
1139 	    options.kerberos_authentication) {
1140 		debug("Kerberos Authentication disabled, only available for IPv4.");
1141 		options.kerberos_authentication = 0;
1142 	}
1143 #endif /* KRB4 */
1144 #ifdef AFS
1145 	/* If machine has AFS, set process authentication group. */
1146 	if (k_hasafs()) {
1147 		k_setpag();
1148 		k_unlog();
1149 	}
1150 #endif /* AFS */
1151 
1152 	packet_set_nonblocking();
1153 
1154 	/* perform the key exchange */
1155 	/* authenticate user and start session */
1156 	if (compat20) {
1157 		do_ssh2_kex();
1158 		do_authentication2();
1159 	} else {
1160 		do_ssh1_kex();
1161 		do_authentication();
1162 	}
1163 
1164 #ifdef KRB4
1165 	/* Cleanup user's ticket cache file. */
1166 	if (options.krb4_ticket_cleanup)
1167 		(void) dest_tkt();
1168 #endif /* KRB4 */
1169 
1170 	/* The connection has been terminated. */
1171 	verbose("Closing connection to %.100s", remote_ip);
1172 
1173 #ifdef USE_PAM
1174 	finish_pam();
1175 #endif /* USE_PAM */
1176 
1177 	packet_close();
1178 	exit(0);
1179 }
1180 
1181 /*
1182  * SSH1 key exchange
1183  */
1184 void
1185 do_ssh1_kex(void)
1186 {
1187 	int i, len;
1188 	int plen, slen;
1189 	int rsafail = 0;
1190 	BIGNUM *session_key_int;
1191 	u_char session_key[SSH_SESSION_KEY_LENGTH];
1192 	u_char cookie[8];
1193 	u_int cipher_type, auth_mask, protocol_flags;
1194 	u_int32_t rand = 0;
1195 
1196 	/*
1197 	 * Generate check bytes that the client must send back in the user
1198 	 * packet in order for it to be accepted; this is used to defy ip
1199 	 * spoofing attacks.  Note that this only works against somebody
1200 	 * doing IP spoofing from a remote machine; any machine on the local
1201 	 * network can still see outgoing packets and catch the random
1202 	 * cookie.  This only affects rhosts authentication, and this is one
1203 	 * of the reasons why it is inherently insecure.
1204 	 */
1205 	for (i = 0; i < 8; i++) {
1206 		if (i % 4 == 0)
1207 			rand = arc4random();
1208 		cookie[i] = rand & 0xff;
1209 		rand >>= 8;
1210 	}
1211 
1212 	/*
1213 	 * Send our public key.  We include in the packet 64 bits of random
1214 	 * data that must be matched in the reply in order to prevent IP
1215 	 * spoofing.
1216 	 */
1217 	packet_start(SSH_SMSG_PUBLIC_KEY);
1218 	for (i = 0; i < 8; i++)
1219 		packet_put_char(cookie[i]);
1220 
1221 	/* Store our public server RSA key. */
1222 	packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
1223 	packet_put_bignum(sensitive_data.server_key->rsa->e);
1224 	packet_put_bignum(sensitive_data.server_key->rsa->n);
1225 
1226 	/* Store our public host RSA key. */
1227 	packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1228 	packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
1229 	packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
1230 
1231 	/* Put protocol flags. */
1232 	packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
1233 
1234 	/* Declare which ciphers we support. */
1235 	packet_put_int(cipher_mask_ssh1(0));
1236 
1237 	/* Declare supported authentication types. */
1238 	auth_mask = 0;
1239 	if (options.rhosts_authentication)
1240 		auth_mask |= 1 << SSH_AUTH_RHOSTS;
1241 	if (options.rhosts_rsa_authentication)
1242 		auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
1243 	if (options.rsa_authentication)
1244 		auth_mask |= 1 << SSH_AUTH_RSA;
1245 #if defined(KRB4) || defined(KRB5)
1246 	if (options.kerberos_authentication)
1247 		auth_mask |= 1 << SSH_AUTH_KERBEROS;
1248 #endif
1249 #ifdef KRB5
1250 	if (options.krb5_tgt_passing)
1251 	  	auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
1252 #endif /* KRB5 */
1253 
1254 #ifdef AFS
1255 	if (options.krb4_tgt_passing)
1256 		auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
1257 	if (options.afs_token_passing)
1258 		auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
1259 #endif
1260 	if (options.challenge_reponse_authentication == 1)
1261 		auth_mask |= 1 << SSH_AUTH_TIS;
1262 	if (options.password_authentication)
1263 		auth_mask |= 1 << SSH_AUTH_PASSWORD;
1264 	packet_put_int(auth_mask);
1265 
1266 	/* Send the packet and wait for it to be sent. */
1267 	packet_send();
1268 	packet_write_wait();
1269 
1270 	debug("Sent %d bit server key and %d bit host key.",
1271 	    BN_num_bits(sensitive_data.server_key->rsa->n),
1272 	    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1273 
1274 	/* Read clients reply (cipher type and session key). */
1275 	packet_read_expect(&plen, SSH_CMSG_SESSION_KEY);
1276 
1277 	/* Get cipher type and check whether we accept this. */
1278 	cipher_type = packet_get_char();
1279 
1280 	if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
1281 		packet_disconnect("Warning: client selects unsupported cipher.");
1282 
1283 	/* Get check bytes from the packet.  These must match those we
1284 	   sent earlier with the public key packet. */
1285 	for (i = 0; i < 8; i++)
1286 		if (cookie[i] != packet_get_char())
1287 			packet_disconnect("IP Spoofing check bytes do not match.");
1288 
1289 	debug("Encryption type: %.200s", cipher_name(cipher_type));
1290 
1291 	/* Get the encrypted integer. */
1292 	session_key_int = BN_new();
1293 	packet_get_bignum(session_key_int, &slen);
1294 
1295 	protocol_flags = packet_get_int();
1296 	packet_set_protocol_flags(protocol_flags);
1297 
1298 	packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY);
1299 
1300 	/*
1301 	 * Decrypt it using our private server key and private host key (key
1302 	 * with larger modulus first).
1303 	 */
1304 	if (BN_cmp(sensitive_data.server_key->rsa->n, sensitive_data.ssh1_host_key->rsa->n) > 0) {
1305 		/* Server key has bigger modulus. */
1306 		if (BN_num_bits(sensitive_data.server_key->rsa->n) <
1307 		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1308 			fatal("do_connection: %s: server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1309 			    get_remote_ipaddr(),
1310 			    BN_num_bits(sensitive_data.server_key->rsa->n),
1311 			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1312 			    SSH_KEY_BITS_RESERVED);
1313 		}
1314 		if (rsa_private_decrypt(session_key_int, session_key_int,
1315 		    sensitive_data.server_key->rsa) <= 0)
1316 			rsafail++;
1317 		if (rsa_private_decrypt(session_key_int, session_key_int,
1318 		    sensitive_data.ssh1_host_key->rsa) <= 0)
1319 			rsafail++;
1320 	} else {
1321 		/* Host key has bigger modulus (or they are equal). */
1322 		if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
1323 		    BN_num_bits(sensitive_data.server_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1324 			fatal("do_connection: %s: host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
1325 			    get_remote_ipaddr(),
1326 			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1327 			    BN_num_bits(sensitive_data.server_key->rsa->n),
1328 			    SSH_KEY_BITS_RESERVED);
1329 		}
1330 		if (rsa_private_decrypt(session_key_int, session_key_int,
1331 		    sensitive_data.ssh1_host_key->rsa) < 0)
1332 			rsafail++;
1333 		if (rsa_private_decrypt(session_key_int, session_key_int,
1334 		    sensitive_data.server_key->rsa) < 0)
1335 			rsafail++;
1336 	}
1337 	/*
1338 	 * Extract session key from the decrypted integer.  The key is in the
1339 	 * least significant 256 bits of the integer; the first byte of the
1340 	 * key is in the highest bits.
1341 	 */
1342 	if (!rsafail) {
1343 		BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1344 		len = BN_num_bytes(session_key_int);
1345 		if (len < 0 || len > sizeof(session_key)) {
1346 			error("do_connection: bad session key len from %s: "
1347 			    "session_key_int %d > sizeof(session_key) %lu",
1348 			    get_remote_ipaddr(), len, (u_long)sizeof(session_key));
1349 			rsafail++;
1350 		} else {
1351 			memset(session_key, 0, sizeof(session_key));
1352 			BN_bn2bin(session_key_int,
1353 			    session_key + sizeof(session_key) - len);
1354 
1355 			compute_session_id(session_id, cookie,
1356 			    sensitive_data.ssh1_host_key->rsa->n,
1357 			    sensitive_data.server_key->rsa->n);
1358 			/*
1359 			 * Xor the first 16 bytes of the session key with the
1360 			 * session id.
1361 			 */
1362 			for (i = 0; i < 16; i++)
1363 				session_key[i] ^= session_id[i];
1364 		}
1365 	}
1366 	if (rsafail) {
1367 		int bytes = BN_num_bytes(session_key_int);
1368 		char *buf = xmalloc(bytes);
1369 		MD5_CTX md;
1370 
1371 		log("do_connection: generating a fake encryption key");
1372 		BN_bn2bin(session_key_int, buf);
1373 		MD5_Init(&md);
1374 		MD5_Update(&md, buf, bytes);
1375 		MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1376 		MD5_Final(session_key, &md);
1377 		MD5_Init(&md);
1378 		MD5_Update(&md, session_key, 16);
1379 		MD5_Update(&md, buf, bytes);
1380 		MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1381 		MD5_Final(session_key + 16, &md);
1382 		memset(buf, 0, bytes);
1383 		xfree(buf);
1384 		for (i = 0; i < 16; i++)
1385 			session_id[i] = session_key[i] ^ session_key[i + 16];
1386 	}
1387 	/* Destroy the private and public keys.  They will no longer be needed. */
1388 	destroy_sensitive_data();
1389 
1390 	/* Destroy the decrypted integer.  It is no longer needed. */
1391 	BN_clear_free(session_key_int);
1392 
1393 	/* Set the session key.  From this on all communications will be encrypted. */
1394 	packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
1395 
1396 	/* Destroy our copy of the session key.  It is no longer needed. */
1397 	memset(session_key, 0, sizeof(session_key));
1398 
1399 	debug("Received session key; encryption turned on.");
1400 
1401 	/* Send an acknowledgement packet.  Note that this packet is sent encrypted. */
1402 	packet_start(SSH_SMSG_SUCCESS);
1403 	packet_send();
1404 	packet_write_wait();
1405 }
1406 
1407 /*
1408  * SSH2 key exchange: diffie-hellman-group1-sha1
1409  */
1410 void
1411 do_ssh2_kex(void)
1412 {
1413 	Kex *kex;
1414 
1415 	if (options.ciphers != NULL) {
1416 		myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1417 		myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
1418 	}
1419 	myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1420 	    compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
1421 	myproposal[PROPOSAL_ENC_ALGS_STOC] =
1422 	    compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
1423 
1424 	if (options.macs != NULL) {
1425 		myproposal[PROPOSAL_MAC_ALGS_CTOS] =
1426 		myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
1427 	}
1428 	myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
1429 
1430 	/* start key exchange */
1431 	kex = kex_setup(myproposal);
1432 	kex->server = 1;
1433 	kex->client_version_string=client_version_string;
1434 	kex->server_version_string=server_version_string;
1435 	kex->load_host_key=&get_hostkey_by_type;
1436 
1437 	xxx_kex = kex;
1438 
1439 	dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
1440 
1441 	session_id2 = kex->session_id;
1442 	session_id2_len = kex->session_id_len;
1443 
1444 #ifdef DEBUG_KEXDH
1445 	/* send 1st encrypted/maced/compressed message */
1446 	packet_start(SSH2_MSG_IGNORE);
1447 	packet_put_cstring("markus");
1448 	packet_send();
1449 	packet_write_wait();
1450 #endif
1451 	debug("KEX done");
1452 }
1453