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