xref: /openbsd/usr.bin/ssh/sshd.c (revision 610f49f8)
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.226 2002/02/11 16:19:39 markus Exp $");
44 
45 #include <openssl/dh.h>
46 #include <openssl/bn.h>
47 #include <openssl/md5.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 	Buffer b;
475 	char *p;
476 	int i;
477 
478 	buffer_init(&b);
479 	for (i = 0; i < options.num_host_key_files; i++) {
480 		Key *key = sensitive_data.host_keys[i];
481 		if (key == NULL)
482 			continue;
483 		switch (key->type) {
484 		case KEY_RSA:
485 		case KEY_DSA:
486 			if (buffer_len(&b) > 0)
487 				buffer_append(&b, ",", 1);
488 			p = key_ssh_name(key);
489 			buffer_append(&b, p, strlen(p));
490 			break;
491 		}
492 	}
493 	buffer_append(&b, "\0", 1);
494 	p = xstrdup(buffer_ptr(&b));
495 	buffer_free(&b);
496 	debug("list_hostkey_types: %s", p);
497 	return p;
498 }
499 
500 static Key *
501 get_hostkey_by_type(int type)
502 {
503 	int i;
504 	for (i = 0; i < options.num_host_key_files; i++) {
505 		Key *key = sensitive_data.host_keys[i];
506 		if (key != NULL && key->type == type)
507 			return key;
508 	}
509 	return NULL;
510 }
511 
512 /*
513  * returns 1 if connection should be dropped, 0 otherwise.
514  * dropping starts at connection #max_startups_begin with a probability
515  * of (max_startups_rate/100). the probability increases linearly until
516  * all connections are dropped for startups > max_startups
517  */
518 static int
519 drop_connection(int startups)
520 {
521 	double p, r;
522 
523 	if (startups < options.max_startups_begin)
524 		return 0;
525 	if (startups >= options.max_startups)
526 		return 1;
527 	if (options.max_startups_rate == 100)
528 		return 1;
529 
530 	p  = 100 - options.max_startups_rate;
531 	p *= startups - options.max_startups_begin;
532 	p /= (double) (options.max_startups - options.max_startups_begin);
533 	p += options.max_startups_rate;
534 	p /= 100.0;
535 	r = arc4random() / (double) UINT_MAX;
536 
537 	debug("drop_connection: p %g, r %g", p, r);
538 	return (r < p) ? 1 : 0;
539 }
540 
541 static void
542 usage(void)
543 {
544 	fprintf(stderr, "sshd version %s\n", SSH_VERSION);
545 	fprintf(stderr, "Usage: %s [options]\n", __progname);
546 	fprintf(stderr, "Options:\n");
547 	fprintf(stderr, "  -f file    Configuration file (default %s)\n", _PATH_SERVER_CONFIG_FILE);
548 	fprintf(stderr, "  -d         Debugging mode (multiple -d means more debugging)\n");
549 	fprintf(stderr, "  -i         Started from inetd\n");
550 	fprintf(stderr, "  -D         Do not fork into daemon mode\n");
551 	fprintf(stderr, "  -t         Only test configuration file and keys\n");
552 	fprintf(stderr, "  -q         Quiet (no logging)\n");
553 	fprintf(stderr, "  -p port    Listen on the specified port (default: 22)\n");
554 	fprintf(stderr, "  -k seconds Regenerate server key every this many seconds (default: 3600)\n");
555 	fprintf(stderr, "  -g seconds Grace period for authentication (default: 600)\n");
556 	fprintf(stderr, "  -b bits    Size of server RSA key (default: 768 bits)\n");
557 	fprintf(stderr, "  -h file    File from which to read host key (default: %s)\n",
558 	    _PATH_HOST_KEY_FILE);
559 	fprintf(stderr, "  -u len     Maximum hostname length for utmp recording\n");
560 	fprintf(stderr, "  -4         Use IPv4 only\n");
561 	fprintf(stderr, "  -6         Use IPv6 only\n");
562 	fprintf(stderr, "  -o option  Process the option as if it was read from a configuration file.\n");
563 	exit(1);
564 }
565 
566 /*
567  * Main program for the daemon.
568  */
569 int
570 main(int ac, char **av)
571 {
572 	extern char *optarg;
573 	extern int optind;
574 	int opt, sock_in = 0, sock_out = 0, newsock, j, i, fdsetsz, on = 1;
575 	pid_t pid;
576 	socklen_t fromlen;
577 	fd_set *fdset;
578 	struct sockaddr_storage from;
579 	const char *remote_ip;
580 	int remote_port;
581 	FILE *f;
582 	struct linger linger;
583 	struct addrinfo *ai;
584 	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
585 	int listen_sock, maxfd;
586 	int startup_p[2];
587 	int startups = 0;
588 	Key *key;
589 	int ret, key_used = 0;
590 
591 	/* Save argv. */
592 	saved_argv = av;
593 
594 	/* Initialize configuration options to their default values. */
595 	initialize_server_options(&options);
596 
597 	/* Parse command-line arguments. */
598 	while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:u:o:dDeiqtQ46")) != -1) {
599 		switch (opt) {
600 		case '4':
601 			IPv4or6 = AF_INET;
602 			break;
603 		case '6':
604 			IPv4or6 = AF_INET6;
605 			break;
606 		case 'f':
607 			config_file_name = optarg;
608 			break;
609 		case 'd':
610 			if (0 == debug_flag) {
611 				debug_flag = 1;
612 				options.log_level = SYSLOG_LEVEL_DEBUG1;
613 			} else if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
614 				options.log_level++;
615 			} else {
616 				fprintf(stderr, "Too high debugging level.\n");
617 				exit(1);
618 			}
619 			break;
620 		case 'D':
621 			no_daemon_flag = 1;
622 			break;
623 		case 'e':
624 			log_stderr = 1;
625 			break;
626 		case 'i':
627 			inetd_flag = 1;
628 			break;
629 		case 'Q':
630 			/* ignored */
631 			break;
632 		case 'q':
633 			options.log_level = SYSLOG_LEVEL_QUIET;
634 			break;
635 		case 'b':
636 			options.server_key_bits = atoi(optarg);
637 			break;
638 		case 'p':
639 			options.ports_from_cmdline = 1;
640 			if (options.num_ports >= MAX_PORTS) {
641 				fprintf(stderr, "too many ports.\n");
642 				exit(1);
643 			}
644 			options.ports[options.num_ports++] = a2port(optarg);
645 			if (options.ports[options.num_ports-1] == 0) {
646 				fprintf(stderr, "Bad port number.\n");
647 				exit(1);
648 			}
649 			break;
650 		case 'g':
651 			if ((options.login_grace_time = convtime(optarg)) == -1) {
652 				fprintf(stderr, "Invalid login grace time.\n");
653 				exit(1);
654 			}
655 			break;
656 		case 'k':
657 			if ((options.key_regeneration_time = convtime(optarg)) == -1) {
658 				fprintf(stderr, "Invalid key regeneration interval.\n");
659 				exit(1);
660 			}
661 			break;
662 		case 'h':
663 			if (options.num_host_key_files >= MAX_HOSTKEYS) {
664 				fprintf(stderr, "too many host keys.\n");
665 				exit(1);
666 			}
667 			options.host_key_files[options.num_host_key_files++] = optarg;
668 			break;
669 		case 'V':
670 			client_version_string = optarg;
671 			/* only makes sense with inetd_flag, i.e. no listen() */
672 			inetd_flag = 1;
673 			break;
674 		case 't':
675 			test_flag = 1;
676 			break;
677 		case 'u':
678 			utmp_len = atoi(optarg);
679 			break;
680 		case 'o':
681 			if (process_server_config_line(&options, optarg,
682 			    "command-line", 0) != 0)
683 				exit(1);
684 			break;
685 		case '?':
686 		default:
687 			usage();
688 			break;
689 		}
690 	}
691 	SSLeay_add_all_algorithms();
692 	channel_set_af(IPv4or6);
693 
694 	/*
695 	 * Force logging to stderr until we have loaded the private host
696 	 * key (unless started from inetd)
697 	 */
698 	log_init(__progname,
699 	    options.log_level == SYSLOG_LEVEL_NOT_SET ?
700 	    SYSLOG_LEVEL_INFO : options.log_level,
701 	    options.log_facility == SYSLOG_FACILITY_NOT_SET ?
702 	    SYSLOG_FACILITY_AUTH : options.log_facility,
703 	    !inetd_flag);
704 
705 	/* Read server configuration options from the configuration file. */
706 	read_server_config(&options, config_file_name);
707 
708 	/* Fill in default values for those options not explicitly set. */
709 	fill_default_server_options(&options);
710 
711 	/* Check that there are no remaining arguments. */
712 	if (optind < ac) {
713 		fprintf(stderr, "Extra argument %s.\n", av[optind]);
714 		exit(1);
715 	}
716 
717 	debug("sshd version %.100s", SSH_VERSION);
718 
719 	/* load private host keys */
720 	sensitive_data.host_keys = xmalloc(options.num_host_key_files*sizeof(Key*));
721 	for (i = 0; i < options.num_host_key_files; i++)
722 		sensitive_data.host_keys[i] = NULL;
723 	sensitive_data.server_key = NULL;
724 	sensitive_data.ssh1_host_key = NULL;
725 	sensitive_data.have_ssh1_key = 0;
726 	sensitive_data.have_ssh2_key = 0;
727 
728 	for (i = 0; i < options.num_host_key_files; i++) {
729 		key = key_load_private(options.host_key_files[i], "", NULL);
730 		sensitive_data.host_keys[i] = key;
731 		if (key == NULL) {
732 			error("Could not load host key: %s",
733 			    options.host_key_files[i]);
734 			sensitive_data.host_keys[i] = NULL;
735 			continue;
736 		}
737 		switch (key->type) {
738 		case KEY_RSA1:
739 			sensitive_data.ssh1_host_key = key;
740 			sensitive_data.have_ssh1_key = 1;
741 			break;
742 		case KEY_RSA:
743 		case KEY_DSA:
744 			sensitive_data.have_ssh2_key = 1;
745 			break;
746 		}
747 		debug("private host key: #%d type %d %s", i, key->type,
748 		    key_type(key));
749 	}
750 	if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
751 		log("Disabling protocol version 1. Could not load host key");
752 		options.protocol &= ~SSH_PROTO_1;
753 	}
754 	if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
755 		log("Disabling protocol version 2. Could not load host key");
756 		options.protocol &= ~SSH_PROTO_2;
757 	}
758 	if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
759 		log("sshd: no hostkeys available -- exiting.");
760 		exit(1);
761 	}
762 
763 	/* Check certain values for sanity. */
764 	if (options.protocol & SSH_PROTO_1) {
765 		if (options.server_key_bits < 512 ||
766 		    options.server_key_bits > 32768) {
767 			fprintf(stderr, "Bad server key size.\n");
768 			exit(1);
769 		}
770 		/*
771 		 * Check that server and host key lengths differ sufficiently. This
772 		 * is necessary to make double encryption work with rsaref. Oh, I
773 		 * hate software patents. I dont know if this can go? Niels
774 		 */
775 		if (options.server_key_bits >
776 		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) - SSH_KEY_BITS_RESERVED &&
777 		    options.server_key_bits <
778 		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
779 			options.server_key_bits =
780 			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED;
781 			debug("Forcing server key to %d bits to make it differ from host key.",
782 			    options.server_key_bits);
783 		}
784 	}
785 
786 	/* Configuration looks good, so exit if in test mode. */
787 	if (test_flag)
788 		exit(0);
789 
790 	/* Initialize the log (it is reinitialized below in case we forked). */
791 	if (debug_flag && !inetd_flag)
792 		log_stderr = 1;
793 	log_init(__progname, options.log_level, options.log_facility, log_stderr);
794 
795 	/*
796 	 * If not in debugging mode, and not started from inetd, disconnect
797 	 * from the controlling terminal, and fork.  The original process
798 	 * exits.
799 	 */
800 	if (!(debug_flag || inetd_flag || no_daemon_flag)) {
801 #ifdef TIOCNOTTY
802 		int fd;
803 #endif /* TIOCNOTTY */
804 		if (daemon(0, 0) < 0)
805 			fatal("daemon() failed: %.200s", strerror(errno));
806 
807 		/* Disconnect from the controlling tty. */
808 #ifdef TIOCNOTTY
809 		fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
810 		if (fd >= 0) {
811 			(void) ioctl(fd, TIOCNOTTY, NULL);
812 			close(fd);
813 		}
814 #endif /* TIOCNOTTY */
815 	}
816 	/* Reinitialize the log (because of the fork above). */
817 	log_init(__progname, options.log_level, options.log_facility, log_stderr);
818 
819 	/* Initialize the random number generator. */
820 	arc4random_stir();
821 
822 	/* Chdir to the root directory so that the current disk can be
823 	   unmounted if desired. */
824 	chdir("/");
825 
826 	/* ignore SIGPIPE */
827 	signal(SIGPIPE, SIG_IGN);
828 
829 	/* Start listening for a socket, unless started from inetd. */
830 	if (inetd_flag) {
831 		int s1;
832 		s1 = dup(0);	/* Make sure descriptors 0, 1, and 2 are in use. */
833 		dup(s1);
834 		sock_in = dup(0);
835 		sock_out = dup(1);
836 		startup_pipe = -1;
837 		/*
838 		 * We intentionally do not close the descriptors 0, 1, and 2
839 		 * as our code for setting the descriptors won\'t work if
840 		 * ttyfd happens to be one of those.
841 		 */
842 		debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
843 		if (options.protocol & SSH_PROTO_1)
844 			generate_ephemeral_server_key();
845 	} else {
846 		for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
847 			if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
848 				continue;
849 			if (num_listen_socks >= MAX_LISTEN_SOCKS)
850 				fatal("Too many listen sockets. "
851 				    "Enlarge MAX_LISTEN_SOCKS");
852 			if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
853 			    ntop, sizeof(ntop), strport, sizeof(strport),
854 			    NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
855 				error("getnameinfo failed");
856 				continue;
857 			}
858 			/* Create socket for listening. */
859 			listen_sock = socket(ai->ai_family, SOCK_STREAM, 0);
860 			if (listen_sock < 0) {
861 				/* kernel may not support ipv6 */
862 				verbose("socket: %.100s", strerror(errno));
863 				continue;
864 			}
865 			if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) {
866 				error("listen_sock O_NONBLOCK: %s", strerror(errno));
867 				close(listen_sock);
868 				continue;
869 			}
870 			/*
871 			 * Set socket options.  We try to make the port
872 			 * reusable and have it close as fast as possible
873 			 * without waiting in unnecessary wait states on
874 			 * close.
875 			 */
876 			setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
877 			    (void *) &on, sizeof(on));
878 			linger.l_onoff = 1;
879 			linger.l_linger = 5;
880 			setsockopt(listen_sock, SOL_SOCKET, SO_LINGER,
881 			    (void *) &linger, sizeof(linger));
882 
883 			debug("Bind to port %s on %s.", strport, ntop);
884 
885 			/* Bind the socket to the desired port. */
886 			if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
887 				error("Bind to port %s on %s failed: %.200s.",
888 				    strport, ntop, strerror(errno));
889 				close(listen_sock);
890 				continue;
891 			}
892 			listen_socks[num_listen_socks] = listen_sock;
893 			num_listen_socks++;
894 
895 			/* Start listening on the port. */
896 			log("Server listening on %s port %s.", ntop, strport);
897 			if (listen(listen_sock, 5) < 0)
898 				fatal("listen: %.100s", strerror(errno));
899 
900 		}
901 		freeaddrinfo(options.listen_addrs);
902 
903 		if (!num_listen_socks)
904 			fatal("Cannot bind any address.");
905 
906 		if (options.protocol & SSH_PROTO_1)
907 			generate_ephemeral_server_key();
908 
909 		/*
910 		 * Arrange to restart on SIGHUP.  The handler needs
911 		 * listen_sock.
912 		 */
913 		signal(SIGHUP, sighup_handler);
914 
915 		signal(SIGTERM, sigterm_handler);
916 		signal(SIGQUIT, sigterm_handler);
917 
918 		/* Arrange SIGCHLD to be caught. */
919 		signal(SIGCHLD, main_sigchld_handler);
920 
921 		/* Write out the pid file after the sigterm handler is setup */
922 		if (!debug_flag) {
923 			/*
924 			 * Record our pid in /var/run/sshd.pid to make it
925 			 * easier to kill the correct sshd.  We don't want to
926 			 * do this before the bind above because the bind will
927 			 * fail if there already is a daemon, and this will
928 			 * overwrite any old pid in the file.
929 			 */
930 			f = fopen(options.pid_file, "w");
931 			if (f) {
932 				fprintf(f, "%u\n", (u_int) getpid());
933 				fclose(f);
934 			}
935 		}
936 
937 		/* setup fd set for listen */
938 		fdset = NULL;
939 		maxfd = 0;
940 		for (i = 0; i < num_listen_socks; i++)
941 			if (listen_socks[i] > maxfd)
942 				maxfd = listen_socks[i];
943 		/* pipes connected to unauthenticated childs */
944 		startup_pipes = xmalloc(options.max_startups * sizeof(int));
945 		for (i = 0; i < options.max_startups; i++)
946 			startup_pipes[i] = -1;
947 
948 		/*
949 		 * Stay listening for connections until the system crashes or
950 		 * the daemon is killed with a signal.
951 		 */
952 		for (;;) {
953 			if (received_sighup)
954 				sighup_restart();
955 			if (fdset != NULL)
956 				xfree(fdset);
957 			fdsetsz = howmany(maxfd+1, NFDBITS) * sizeof(fd_mask);
958 			fdset = (fd_set *)xmalloc(fdsetsz);
959 			memset(fdset, 0, fdsetsz);
960 
961 			for (i = 0; i < num_listen_socks; i++)
962 				FD_SET(listen_socks[i], fdset);
963 			for (i = 0; i < options.max_startups; i++)
964 				if (startup_pipes[i] != -1)
965 					FD_SET(startup_pipes[i], fdset);
966 
967 			/* Wait in select until there is a connection. */
968 			ret = select(maxfd+1, fdset, NULL, NULL, NULL);
969 			if (ret < 0 && errno != EINTR)
970 				error("select: %.100s", strerror(errno));
971 			if (received_sigterm) {
972 				log("Received signal %d; terminating.",
973 				    (int) received_sigterm);
974 				close_listen_socks();
975 				unlink(options.pid_file);
976 				exit(255);
977 			}
978 			if (key_used && key_do_regen) {
979 				generate_ephemeral_server_key();
980 				key_used = 0;
981 				key_do_regen = 0;
982 			}
983 			if (ret < 0)
984 				continue;
985 
986 			for (i = 0; i < options.max_startups; i++)
987 				if (startup_pipes[i] != -1 &&
988 				    FD_ISSET(startup_pipes[i], fdset)) {
989 					/*
990 					 * the read end of the pipe is ready
991 					 * if the child has closed the pipe
992 					 * after successful authentication
993 					 * or if the child has died
994 					 */
995 					close(startup_pipes[i]);
996 					startup_pipes[i] = -1;
997 					startups--;
998 				}
999 			for (i = 0; i < num_listen_socks; i++) {
1000 				if (!FD_ISSET(listen_socks[i], fdset))
1001 					continue;
1002 				fromlen = sizeof(from);
1003 				newsock = accept(listen_socks[i], (struct sockaddr *)&from,
1004 				    &fromlen);
1005 				if (newsock < 0) {
1006 					if (errno != EINTR && errno != EWOULDBLOCK)
1007 						error("accept: %.100s", strerror(errno));
1008 					continue;
1009 				}
1010 				if (fcntl(newsock, F_SETFL, 0) < 0) {
1011 					error("newsock del O_NONBLOCK: %s", strerror(errno));
1012 					close(newsock);
1013 					continue;
1014 				}
1015 				if (drop_connection(startups) == 1) {
1016 					debug("drop connection #%d", startups);
1017 					close(newsock);
1018 					continue;
1019 				}
1020 				if (pipe(startup_p) == -1) {
1021 					close(newsock);
1022 					continue;
1023 				}
1024 
1025 				for (j = 0; j < options.max_startups; j++)
1026 					if (startup_pipes[j] == -1) {
1027 						startup_pipes[j] = startup_p[0];
1028 						if (maxfd < startup_p[0])
1029 							maxfd = startup_p[0];
1030 						startups++;
1031 						break;
1032 					}
1033 
1034 				/*
1035 				 * Got connection.  Fork a child to handle it, unless
1036 				 * we are in debugging mode.
1037 				 */
1038 				if (debug_flag) {
1039 					/*
1040 					 * In debugging mode.  Close the listening
1041 					 * socket, and start processing the
1042 					 * connection without forking.
1043 					 */
1044 					debug("Server will not fork when running in debugging mode.");
1045 					close_listen_socks();
1046 					sock_in = newsock;
1047 					sock_out = newsock;
1048 					startup_pipe = -1;
1049 					pid = getpid();
1050 					break;
1051 				} else {
1052 					/*
1053 					 * Normal production daemon.  Fork, and have
1054 					 * the child process the connection. The
1055 					 * parent continues listening.
1056 					 */
1057 					if ((pid = fork()) == 0) {
1058 						/*
1059 						 * Child.  Close the listening and max_startup
1060 						 * sockets.  Start using the accepted socket.
1061 						 * Reinitialize logging (since our pid has
1062 						 * changed).  We break out of the loop to handle
1063 						 * the connection.
1064 						 */
1065 						startup_pipe = startup_p[1];
1066 						close_startup_pipes();
1067 						close_listen_socks();
1068 						sock_in = newsock;
1069 						sock_out = newsock;
1070 						log_init(__progname, options.log_level, options.log_facility, log_stderr);
1071 						break;
1072 					}
1073 				}
1074 
1075 				/* Parent.  Stay in the loop. */
1076 				if (pid < 0)
1077 					error("fork: %.100s", strerror(errno));
1078 				else
1079 					debug("Forked child %d.", pid);
1080 
1081 				close(startup_p[1]);
1082 
1083 				/* Mark that the key has been used (it was "given" to the child). */
1084 				if ((options.protocol & SSH_PROTO_1) &&
1085 				    key_used == 0) {
1086 					/* Schedule server key regeneration alarm. */
1087 					signal(SIGALRM, key_regeneration_alarm);
1088 					alarm(options.key_regeneration_time);
1089 					key_used = 1;
1090 				}
1091 
1092 				arc4random_stir();
1093 
1094 				/* Close the new socket (the child is now taking care of it). */
1095 				close(newsock);
1096 			}
1097 			/* child process check (or debug mode) */
1098 			if (num_listen_socks < 0)
1099 				break;
1100 		}
1101 	}
1102 
1103 	/* This is the child processing a new connection. */
1104 
1105 	/*
1106 	 * Disable the key regeneration alarm.  We will not regenerate the
1107 	 * key since we are no longer in a position to give it to anyone. We
1108 	 * will not restart on SIGHUP since it no longer makes sense.
1109 	 */
1110 	alarm(0);
1111 	signal(SIGALRM, SIG_DFL);
1112 	signal(SIGHUP, SIG_DFL);
1113 	signal(SIGTERM, SIG_DFL);
1114 	signal(SIGQUIT, SIG_DFL);
1115 	signal(SIGCHLD, SIG_DFL);
1116 
1117 	/*
1118 	 * Set socket options for the connection.  We want the socket to
1119 	 * close as fast as possible without waiting for anything.  If the
1120 	 * connection is not a socket, these will do nothing.
1121 	 */
1122 	/* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
1123 	linger.l_onoff = 1;
1124 	linger.l_linger = 5;
1125 	setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
1126 
1127 	/* Set keepalives if requested. */
1128 	if (options.keepalives &&
1129 	    setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, (void *)&on,
1130 	    sizeof(on)) < 0)
1131 		error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1132 
1133 	/*
1134 	 * Register our connection.  This turns encryption off because we do
1135 	 * not have a key.
1136 	 */
1137 	packet_set_connection(sock_in, sock_out);
1138 
1139 	remote_port = get_remote_port();
1140 	remote_ip = get_remote_ipaddr();
1141 
1142 #ifdef LIBWRAP
1143 	/* Check whether logins are denied from this host. */
1144 	{
1145 		struct request_info req;
1146 
1147 		request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1148 		fromhost(&req);
1149 
1150 		if (!hosts_access(&req)) {
1151 			debug("Connection refused by tcp wrapper");
1152 			refuse(&req);
1153 			/* NOTREACHED */
1154 			fatal("libwrap refuse returns");
1155 		}
1156 	}
1157 #endif /* LIBWRAP */
1158 
1159 	/* Log the connection. */
1160 	verbose("Connection from %.500s port %d", remote_ip, remote_port);
1161 
1162 	/*
1163 	 * We don\'t want to listen forever unless the other side
1164 	 * successfully authenticates itself.  So we set up an alarm which is
1165 	 * cleared after successful authentication.  A limit of zero
1166 	 * indicates no limit. Note that we don\'t set the alarm in debugging
1167 	 * mode; it is just annoying to have the server exit just when you
1168 	 * are about to discover the bug.
1169 	 */
1170 	signal(SIGALRM, grace_alarm_handler);
1171 	if (!debug_flag)
1172 		alarm(options.login_grace_time);
1173 
1174 	sshd_exchange_identification(sock_in, sock_out);
1175 	/*
1176 	 * Check that the connection comes from a privileged port.
1177 	 * Rhosts-Authentication only makes sense from priviledged
1178 	 * programs.  Of course, if the intruder has root access on his local
1179 	 * machine, he can connect from any port.  So do not use these
1180 	 * authentication methods from machines that you do not trust.
1181 	 */
1182 	if (options.rhosts_authentication &&
1183 	    (remote_port >= IPPORT_RESERVED ||
1184 	    remote_port < IPPORT_RESERVED / 2)) {
1185 		debug("Rhosts Authentication disabled, "
1186 		    "originating port %d not trusted.", remote_port);
1187 		options.rhosts_authentication = 0;
1188 	}
1189 #if defined(KRB4) && !defined(KRB5)
1190 	if (!packet_connection_is_ipv4() &&
1191 	    options.kerberos_authentication) {
1192 		debug("Kerberos Authentication disabled, only available for IPv4.");
1193 		options.kerberos_authentication = 0;
1194 	}
1195 #endif /* KRB4 && !KRB5 */
1196 #ifdef AFS
1197 	/* If machine has AFS, set process authentication group. */
1198 	if (k_hasafs()) {
1199 		k_setpag();
1200 		k_unlog();
1201 	}
1202 #endif /* AFS */
1203 
1204 	packet_set_nonblocking();
1205 
1206 	/* perform the key exchange */
1207 	/* authenticate user and start session */
1208 	if (compat20) {
1209 		do_ssh2_kex();
1210 		do_authentication2();
1211 	} else {
1212 		do_ssh1_kex();
1213 		do_authentication();
1214 	}
1215 	/* The connection has been terminated. */
1216 	verbose("Closing connection to %.100s", remote_ip);
1217 	packet_close();
1218 	exit(0);
1219 }
1220 
1221 /*
1222  * SSH1 key exchange
1223  */
1224 static void
1225 do_ssh1_kex(void)
1226 {
1227 	int i, len;
1228 	int rsafail = 0;
1229 	BIGNUM *session_key_int;
1230 	u_char session_key[SSH_SESSION_KEY_LENGTH];
1231 	u_char cookie[8];
1232 	u_int cipher_type, auth_mask, protocol_flags;
1233 	u_int32_t rand = 0;
1234 
1235 	/*
1236 	 * Generate check bytes that the client must send back in the user
1237 	 * packet in order for it to be accepted; this is used to defy ip
1238 	 * spoofing attacks.  Note that this only works against somebody
1239 	 * doing IP spoofing from a remote machine; any machine on the local
1240 	 * network can still see outgoing packets and catch the random
1241 	 * cookie.  This only affects rhosts authentication, and this is one
1242 	 * of the reasons why it is inherently insecure.
1243 	 */
1244 	for (i = 0; i < 8; i++) {
1245 		if (i % 4 == 0)
1246 			rand = arc4random();
1247 		cookie[i] = rand & 0xff;
1248 		rand >>= 8;
1249 	}
1250 
1251 	/*
1252 	 * Send our public key.  We include in the packet 64 bits of random
1253 	 * data that must be matched in the reply in order to prevent IP
1254 	 * spoofing.
1255 	 */
1256 	packet_start(SSH_SMSG_PUBLIC_KEY);
1257 	for (i = 0; i < 8; i++)
1258 		packet_put_char(cookie[i]);
1259 
1260 	/* Store our public server RSA key. */
1261 	packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
1262 	packet_put_bignum(sensitive_data.server_key->rsa->e);
1263 	packet_put_bignum(sensitive_data.server_key->rsa->n);
1264 
1265 	/* Store our public host RSA key. */
1266 	packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1267 	packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
1268 	packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
1269 
1270 	/* Put protocol flags. */
1271 	packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
1272 
1273 	/* Declare which ciphers we support. */
1274 	packet_put_int(cipher_mask_ssh1(0));
1275 
1276 	/* Declare supported authentication types. */
1277 	auth_mask = 0;
1278 	if (options.rhosts_authentication)
1279 		auth_mask |= 1 << SSH_AUTH_RHOSTS;
1280 	if (options.rhosts_rsa_authentication)
1281 		auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
1282 	if (options.rsa_authentication)
1283 		auth_mask |= 1 << SSH_AUTH_RSA;
1284 #if defined(KRB4) || defined(KRB5)
1285 	if (options.kerberos_authentication)
1286 		auth_mask |= 1 << SSH_AUTH_KERBEROS;
1287 #endif
1288 #if defined(AFS) || defined(KRB5)
1289 	if (options.kerberos_tgt_passing)
1290 		auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
1291 #endif
1292 #ifdef AFS
1293 	if (options.afs_token_passing)
1294 		auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
1295 #endif
1296 	if (options.challenge_response_authentication == 1)
1297 		auth_mask |= 1 << SSH_AUTH_TIS;
1298 	if (options.password_authentication)
1299 		auth_mask |= 1 << SSH_AUTH_PASSWORD;
1300 	packet_put_int(auth_mask);
1301 
1302 	/* Send the packet and wait for it to be sent. */
1303 	packet_send();
1304 	packet_write_wait();
1305 
1306 	debug("Sent %d bit server key and %d bit host key.",
1307 	    BN_num_bits(sensitive_data.server_key->rsa->n),
1308 	    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1309 
1310 	/* Read clients reply (cipher type and session key). */
1311 	packet_read_expect(SSH_CMSG_SESSION_KEY);
1312 
1313 	/* Get cipher type and check whether we accept this. */
1314 	cipher_type = packet_get_char();
1315 
1316 	if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
1317 		packet_disconnect("Warning: client selects unsupported cipher.");
1318 
1319 	/* Get check bytes from the packet.  These must match those we
1320 	   sent earlier with the public key packet. */
1321 	for (i = 0; i < 8; i++)
1322 		if (cookie[i] != packet_get_char())
1323 			packet_disconnect("IP Spoofing check bytes do not match.");
1324 
1325 	debug("Encryption type: %.200s", cipher_name(cipher_type));
1326 
1327 	/* Get the encrypted integer. */
1328 	if ((session_key_int = BN_new()) == NULL)
1329 		fatal("do_ssh1_kex: BN_new failed");
1330 	packet_get_bignum(session_key_int);
1331 
1332 	protocol_flags = packet_get_int();
1333 	packet_set_protocol_flags(protocol_flags);
1334 	packet_check_eom();
1335 
1336 	/*
1337 	 * Decrypt it using our private server key and private host key (key
1338 	 * with larger modulus first).
1339 	 */
1340 	if (BN_cmp(sensitive_data.server_key->rsa->n, sensitive_data.ssh1_host_key->rsa->n) > 0) {
1341 		/* Server key has bigger modulus. */
1342 		if (BN_num_bits(sensitive_data.server_key->rsa->n) <
1343 		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1344 			fatal("do_connection: %s: server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1345 			    get_remote_ipaddr(),
1346 			    BN_num_bits(sensitive_data.server_key->rsa->n),
1347 			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1348 			    SSH_KEY_BITS_RESERVED);
1349 		}
1350 		if (rsa_private_decrypt(session_key_int, session_key_int,
1351 		    sensitive_data.server_key->rsa) <= 0)
1352 			rsafail++;
1353 		if (rsa_private_decrypt(session_key_int, session_key_int,
1354 		    sensitive_data.ssh1_host_key->rsa) <= 0)
1355 			rsafail++;
1356 	} else {
1357 		/* Host key has bigger modulus (or they are equal). */
1358 		if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
1359 		    BN_num_bits(sensitive_data.server_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1360 			fatal("do_connection: %s: host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
1361 			    get_remote_ipaddr(),
1362 			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1363 			    BN_num_bits(sensitive_data.server_key->rsa->n),
1364 			    SSH_KEY_BITS_RESERVED);
1365 		}
1366 		if (rsa_private_decrypt(session_key_int, session_key_int,
1367 		    sensitive_data.ssh1_host_key->rsa) < 0)
1368 			rsafail++;
1369 		if (rsa_private_decrypt(session_key_int, session_key_int,
1370 		    sensitive_data.server_key->rsa) < 0)
1371 			rsafail++;
1372 	}
1373 	/*
1374 	 * Extract session key from the decrypted integer.  The key is in the
1375 	 * least significant 256 bits of the integer; the first byte of the
1376 	 * key is in the highest bits.
1377 	 */
1378 	if (!rsafail) {
1379 		BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1380 		len = BN_num_bytes(session_key_int);
1381 		if (len < 0 || len > sizeof(session_key)) {
1382 			error("do_connection: bad session key len from %s: "
1383 			    "session_key_int %d > sizeof(session_key) %lu",
1384 			    get_remote_ipaddr(), len, (u_long)sizeof(session_key));
1385 			rsafail++;
1386 		} else {
1387 			memset(session_key, 0, sizeof(session_key));
1388 			BN_bn2bin(session_key_int,
1389 			    session_key + sizeof(session_key) - len);
1390 
1391 			compute_session_id(session_id, cookie,
1392 			    sensitive_data.ssh1_host_key->rsa->n,
1393 			    sensitive_data.server_key->rsa->n);
1394 			/*
1395 			 * Xor the first 16 bytes of the session key with the
1396 			 * session id.
1397 			 */
1398 			for (i = 0; i < 16; i++)
1399 				session_key[i] ^= session_id[i];
1400 		}
1401 	}
1402 	if (rsafail) {
1403 		int bytes = BN_num_bytes(session_key_int);
1404 		char *buf = xmalloc(bytes);
1405 		MD5_CTX md;
1406 
1407 		log("do_connection: generating a fake encryption key");
1408 		BN_bn2bin(session_key_int, buf);
1409 		MD5_Init(&md);
1410 		MD5_Update(&md, buf, bytes);
1411 		MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1412 		MD5_Final(session_key, &md);
1413 		MD5_Init(&md);
1414 		MD5_Update(&md, session_key, 16);
1415 		MD5_Update(&md, buf, bytes);
1416 		MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1417 		MD5_Final(session_key + 16, &md);
1418 		memset(buf, 0, bytes);
1419 		xfree(buf);
1420 		for (i = 0; i < 16; i++)
1421 			session_id[i] = session_key[i] ^ session_key[i + 16];
1422 	}
1423 	/* Destroy the private and public keys.  They will no longer be needed. */
1424 	destroy_sensitive_data();
1425 
1426 	/* Destroy the decrypted integer.  It is no longer needed. */
1427 	BN_clear_free(session_key_int);
1428 
1429 	/* Set the session key.  From this on all communications will be encrypted. */
1430 	packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
1431 
1432 	/* Destroy our copy of the session key.  It is no longer needed. */
1433 	memset(session_key, 0, sizeof(session_key));
1434 
1435 	debug("Received session key; encryption turned on.");
1436 
1437 	/* Send an acknowledgement packet.  Note that this packet is sent encrypted. */
1438 	packet_start(SSH_SMSG_SUCCESS);
1439 	packet_send();
1440 	packet_write_wait();
1441 }
1442 
1443 /*
1444  * SSH2 key exchange: diffie-hellman-group1-sha1
1445  */
1446 static void
1447 do_ssh2_kex(void)
1448 {
1449 	Kex *kex;
1450 
1451 	if (options.ciphers != NULL) {
1452 		myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1453 		myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
1454 	}
1455 	myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1456 	    compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
1457 	myproposal[PROPOSAL_ENC_ALGS_STOC] =
1458 	    compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
1459 
1460 	if (options.macs != NULL) {
1461 		myproposal[PROPOSAL_MAC_ALGS_CTOS] =
1462 		myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
1463 	}
1464 	myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
1465 
1466 	/* start key exchange */
1467 	kex = kex_setup(myproposal);
1468 	kex->server = 1;
1469 	kex->client_version_string=client_version_string;
1470 	kex->server_version_string=server_version_string;
1471 	kex->load_host_key=&get_hostkey_by_type;
1472 
1473 	xxx_kex = kex;
1474 
1475 	dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
1476 
1477 	session_id2 = kex->session_id;
1478 	session_id2_len = kex->session_id_len;
1479 
1480 #ifdef DEBUG_KEXDH
1481 	/* send 1st encrypted/maced/compressed message */
1482 	packet_start(SSH2_MSG_IGNORE);
1483 	packet_put_cstring("markus");
1484 	packet_send();
1485 	packet_write_wait();
1486 #endif
1487 	debug("KEX done");
1488 }
1489