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