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