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