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