xref: /freebsd/crypto/openssh/sshd.c (revision 1d66272a85cde1c8a69c58f4b5dd649babd6eca6)
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 	signal(SIGPIPE, SIG_IGN);
1065 
1066 	/*
1067 	 * Set socket options for the connection.  We want the socket to
1068 	 * close as fast as possible without waiting for anything.  If the
1069 	 * connection is not a socket, these will do nothing.
1070 	 */
1071 	/* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
1072 	linger.l_onoff = 1;
1073 	linger.l_linger = 5;
1074 	setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
1075 
1076 	/*
1077 	 * Register our connection.  This turns encryption off because we do
1078 	 * not have a key.
1079 	 */
1080 	packet_set_connection(sock_in, sock_out);
1081 
1082 	remote_port = get_remote_port();
1083 	remote_ip = get_remote_ipaddr();
1084 
1085 	/* Check whether logins are denied from this host. */
1086 #ifdef LIBWRAP
1087 	{
1088 		struct request_info req;
1089 
1090 		request_init(&req, RQ_DAEMON, av0, RQ_FILE, sock_in, NULL);
1091 		fromhost(&req);
1092 
1093 		if (!hosts_access(&req)) {
1094 			close(sock_in);
1095 			close(sock_out);
1096 			refuse(&req);
1097 		}
1098 		verbose("Connection from %.500s port %d", eval_client(&req), remote_port);
1099 	}
1100 #endif /* LIBWRAP */
1101 	/* Log the connection. */
1102 	verbose("Connection from %.500s port %d", remote_ip, remote_port);
1103 
1104 	/*
1105 	 * We don\'t want to listen forever unless the other side
1106 	 * successfully authenticates itself.  So we set up an alarm which is
1107 	 * cleared after successful authentication.  A limit of zero
1108 	 * indicates no limit. Note that we don\'t set the alarm in debugging
1109 	 * mode; it is just annoying to have the server exit just when you
1110 	 * are about to discover the bug.
1111 	 */
1112 	signal(SIGALRM, grace_alarm_handler);
1113 	if (!debug_flag)
1114 		alarm(options.login_grace_time);
1115 
1116 	sshd_exchange_identification(sock_in, sock_out);
1117 	/*
1118 	 * Check that the connection comes from a privileged port.  Rhosts-
1119 	 * and Rhosts-RSA-Authentication only make sense from priviledged
1120 	 * programs.  Of course, if the intruder has root access on his local
1121 	 * machine, he can connect from any port.  So do not use these
1122 	 * authentication methods from machines that you do not trust.
1123 	 */
1124 	if (remote_port >= IPPORT_RESERVED ||
1125 	    remote_port < IPPORT_RESERVED / 2) {
1126 		options.rhosts_authentication = 0;
1127 		options.rhosts_rsa_authentication = 0;
1128 	}
1129 #ifdef KRB4
1130 	if (!packet_connection_is_ipv4() &&
1131 	    options.krb4_authentication) {
1132 		debug("Kerberos Authentication disabled, only available for IPv4.");
1133 		options.krb4_authentication = 0;
1134 	}
1135 #endif /* KRB4 */
1136 
1137 	packet_set_nonblocking();
1138 
1139 	/* perform the key exchange */
1140 	/* authenticate user and start session */
1141 	if (compat20) {
1142 		do_ssh2_kex();
1143 		do_authentication2();
1144 	} else {
1145 		do_ssh1_kex();
1146 		do_authentication();
1147 	}
1148 
1149 #ifdef KRB4
1150 	/* Cleanup user's ticket cache file. */
1151 	if (options.krb4_ticket_cleanup)
1152 		(void) dest_tkt();
1153 #endif /* KRB4 */
1154 
1155 	/* The connection has been terminated. */
1156 	verbose("Closing connection to %.100s", remote_ip);
1157 
1158 #ifdef USE_PAM
1159 	finish_pam();
1160 #endif /* USE_PAM */
1161 
1162 	packet_close();
1163 	exit(0);
1164 }
1165 
1166 /*
1167  * SSH1 key exchange
1168  */
1169 void
1170 do_ssh1_kex()
1171 {
1172 	int i, len;
1173 	int plen, slen;
1174 	BIGNUM *session_key_int;
1175 	unsigned char session_key[SSH_SESSION_KEY_LENGTH];
1176 	unsigned char cookie[8];
1177 	unsigned int cipher_type, auth_mask, protocol_flags;
1178 	u_int32_t rand = 0;
1179 
1180 	/*
1181 	 * Generate check bytes that the client must send back in the user
1182 	 * packet in order for it to be accepted; this is used to defy ip
1183 	 * spoofing attacks.  Note that this only works against somebody
1184 	 * doing IP spoofing from a remote machine; any machine on the local
1185 	 * network can still see outgoing packets and catch the random
1186 	 * cookie.  This only affects rhosts authentication, and this is one
1187 	 * of the reasons why it is inherently insecure.
1188 	 */
1189 	for (i = 0; i < 8; i++) {
1190 		if (i % 4 == 0)
1191 			rand = arc4random();
1192 		cookie[i] = rand & 0xff;
1193 		rand >>= 8;
1194 	}
1195 
1196 	/*
1197 	 * Send our public key.  We include in the packet 64 bits of random
1198 	 * data that must be matched in the reply in order to prevent IP
1199 	 * spoofing.
1200 	 */
1201 	packet_start(SSH_SMSG_PUBLIC_KEY);
1202 	for (i = 0; i < 8; i++)
1203 		packet_put_char(cookie[i]);
1204 
1205 	/* Store our public server RSA key. */
1206 	packet_put_int(BN_num_bits(public_key->n));
1207 	packet_put_bignum(public_key->e);
1208 	packet_put_bignum(public_key->n);
1209 
1210 	/* Store our public host RSA key. */
1211 	packet_put_int(BN_num_bits(sensitive_data.host_key->n));
1212 	packet_put_bignum(sensitive_data.host_key->e);
1213 	packet_put_bignum(sensitive_data.host_key->n);
1214 
1215 	/* Put protocol flags. */
1216 	packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
1217 
1218 	/* Declare which ciphers we support. */
1219 	packet_put_int(cipher_mask_ssh1(0));
1220 
1221 	/* Declare supported authentication types. */
1222 	auth_mask = 0;
1223 	if (options.rhosts_authentication)
1224 		auth_mask |= 1 << SSH_AUTH_RHOSTS;
1225 	if (options.rhosts_rsa_authentication)
1226 		auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
1227 	if (options.rsa_authentication)
1228 		auth_mask |= 1 << SSH_AUTH_RSA;
1229 #ifdef KRB4
1230 	if (options.krb4_authentication)
1231 		auth_mask |= 1 << SSH_AUTH_KRB4;
1232 #endif
1233 #ifdef KRB5
1234 	if (options.krb5_authentication) {
1235 	  	auth_mask |= 1 << SSH_AUTH_KRB5;
1236                 /* compatibility with MetaCentre ssh */
1237 		auth_mask |= 1 << SSH_AUTH_KRB4;
1238         }
1239 	if (options.krb5_tgt_passing)
1240 	  	auth_mask |= 1 << SSH_PASS_KRB5_TGT;
1241 #endif /* KRB5 */
1242 
1243 #ifdef AFS
1244 	if (options.krb4_tgt_passing)
1245 		auth_mask |= 1 << SSH_PASS_KRB4_TGT;
1246 	if (options.afs_token_passing)
1247 		auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
1248 #endif
1249 #ifdef SKEY
1250 	if (options.skey_authentication == 1)
1251 		auth_mask |= 1 << SSH_AUTH_TIS;
1252 #endif
1253 	if (options.password_authentication)
1254 		auth_mask |= 1 << SSH_AUTH_PASSWORD;
1255 	packet_put_int(auth_mask);
1256 
1257 	/* Send the packet and wait for it to be sent. */
1258 	packet_send();
1259 	packet_write_wait();
1260 
1261 	debug("Sent %d bit public key and %d bit host key.",
1262 	      BN_num_bits(public_key->n), BN_num_bits(sensitive_data.host_key->n));
1263 
1264 	/* Read clients reply (cipher type and session key). */
1265 	packet_read_expect(&plen, SSH_CMSG_SESSION_KEY);
1266 
1267 	/* Get cipher type and check whether we accept this. */
1268 	cipher_type = packet_get_char();
1269 
1270 	if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
1271 		packet_disconnect("Warning: client selects unsupported cipher.");
1272 
1273 	/* Get check bytes from the packet.  These must match those we
1274 	   sent earlier with the public key packet. */
1275 	for (i = 0; i < 8; i++)
1276 		if (cookie[i] != packet_get_char())
1277 			packet_disconnect("IP Spoofing check bytes do not match.");
1278 
1279 	debug("Encryption type: %.200s", cipher_name(cipher_type));
1280 
1281 	/* Get the encrypted integer. */
1282 	session_key_int = BN_new();
1283 	packet_get_bignum(session_key_int, &slen);
1284 
1285 	protocol_flags = packet_get_int();
1286 	packet_set_protocol_flags(protocol_flags);
1287 
1288 	packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY);
1289 
1290 	/*
1291 	 * Decrypt it using our private server key and private host key (key
1292 	 * with larger modulus first).
1293 	 */
1294 	if (BN_cmp(sensitive_data.private_key->n, sensitive_data.host_key->n) > 0) {
1295 		/* Private key has bigger modulus. */
1296 		if (BN_num_bits(sensitive_data.private_key->n) <
1297 		    BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
1298 			fatal("do_connection: %s: private_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1299 			      get_remote_ipaddr(),
1300 			      BN_num_bits(sensitive_data.private_key->n),
1301 			      BN_num_bits(sensitive_data.host_key->n),
1302 			      SSH_KEY_BITS_RESERVED);
1303 		}
1304 		rsa_private_decrypt(session_key_int, session_key_int,
1305 				    sensitive_data.private_key);
1306 		rsa_private_decrypt(session_key_int, session_key_int,
1307 				    sensitive_data.host_key);
1308 	} else {
1309 		/* Host key has bigger modulus (or they are equal). */
1310 		if (BN_num_bits(sensitive_data.host_key->n) <
1311 		    BN_num_bits(sensitive_data.private_key->n) + SSH_KEY_BITS_RESERVED) {
1312 			fatal("do_connection: %s: host_key %d < private_key %d + SSH_KEY_BITS_RESERVED %d",
1313 			      get_remote_ipaddr(),
1314 			      BN_num_bits(sensitive_data.host_key->n),
1315 			      BN_num_bits(sensitive_data.private_key->n),
1316 			      SSH_KEY_BITS_RESERVED);
1317 		}
1318 		rsa_private_decrypt(session_key_int, session_key_int,
1319 				    sensitive_data.host_key);
1320 		rsa_private_decrypt(session_key_int, session_key_int,
1321 				    sensitive_data.private_key);
1322 	}
1323 
1324 	compute_session_id(session_id, cookie,
1325 			   sensitive_data.host_key->n,
1326 			   sensitive_data.private_key->n);
1327 
1328 	/* Destroy the private and public keys.  They will no longer be needed. */
1329 	destroy_sensitive_data();
1330 
1331 	/*
1332 	 * Extract session key from the decrypted integer.  The key is in the
1333 	 * least significant 256 bits of the integer; the first byte of the
1334 	 * key is in the highest bits.
1335 	 */
1336 	BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1337 	len = BN_num_bytes(session_key_int);
1338 	if (len < 0 || len > sizeof(session_key))
1339 		fatal("do_connection: bad len from %s: session_key_int %d > sizeof(session_key) %d",
1340 		      get_remote_ipaddr(),
1341 		      len, sizeof(session_key));
1342 	memset(session_key, 0, sizeof(session_key));
1343 	BN_bn2bin(session_key_int, session_key + sizeof(session_key) - len);
1344 
1345 	/* Destroy the decrypted integer.  It is no longer needed. */
1346 	BN_clear_free(session_key_int);
1347 
1348 	/* Xor the first 16 bytes of the session key with the session id. */
1349 	for (i = 0; i < 16; i++)
1350 		session_key[i] ^= session_id[i];
1351 
1352 	/* Set the session key.  From this on all communications will be encrypted. */
1353 	packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
1354 
1355 	/* Destroy our copy of the session key.  It is no longer needed. */
1356 	memset(session_key, 0, sizeof(session_key));
1357 
1358 	debug("Received session key; encryption turned on.");
1359 
1360 	/* Send an acknowledgement packet.  Note that this packet is sent encrypted. */
1361 	packet_start(SSH_SMSG_SUCCESS);
1362 	packet_send();
1363 	packet_write_wait();
1364 }
1365 
1366 /*
1367  * SSH2 key exchange: diffie-hellman-group1-sha1
1368  */
1369 void
1370 do_ssh2_kex()
1371 {
1372 	Buffer *server_kexinit;
1373 	Buffer *client_kexinit;
1374 	int payload_len;
1375 	int i;
1376 	Kex *kex;
1377 	char *cprop[PROPOSAL_MAX];
1378 
1379 /* KEXINIT */
1380 
1381 	if (options.ciphers != NULL) {
1382 		myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1383 		myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
1384 	}
1385 	server_kexinit = kex_init(myproposal);
1386 	client_kexinit = xmalloc(sizeof(*client_kexinit));
1387 	buffer_init(client_kexinit);
1388 
1389 	/* algorithm negotiation */
1390 	kex_exchange_kexinit(server_kexinit, client_kexinit, cprop);
1391 	kex = kex_choose_conf(cprop, myproposal, 1);
1392 	for (i = 0; i < PROPOSAL_MAX; i++)
1393 		xfree(cprop[i]);
1394 
1395 	switch (kex->kex_type) {
1396 	case DH_GRP1_SHA1:
1397 		ssh_dh1_server(kex, client_kexinit, server_kexinit);
1398 		break;
1399 	case DH_GEX_SHA1:
1400 		ssh_dhgex_server(kex, client_kexinit, server_kexinit);
1401 		break;
1402 	default:
1403 		fatal("Unsupported key exchange %d", kex->kex_type);
1404 	}
1405 
1406 	debug("send SSH2_MSG_NEWKEYS.");
1407 	packet_start(SSH2_MSG_NEWKEYS);
1408 	packet_send();
1409 	packet_write_wait();
1410 	debug("done: send SSH2_MSG_NEWKEYS.");
1411 
1412 	debug("Wait SSH2_MSG_NEWKEYS.");
1413 	packet_read_expect(&payload_len, SSH2_MSG_NEWKEYS);
1414 	debug("GOT SSH2_MSG_NEWKEYS.");
1415 
1416 #ifdef DEBUG_KEXDH
1417 	/* send 1st encrypted/maced/compressed message */
1418 	packet_start(SSH2_MSG_IGNORE);
1419 	packet_put_cstring("markus");
1420 	packet_send();
1421 	packet_write_wait();
1422 #endif
1423 
1424 	debug("done: KEX2.");
1425 }
1426 
1427 /*
1428  * SSH2 key exchange
1429  */
1430 
1431 /* diffie-hellman-group1-sha1 */
1432 
1433 void
1434 ssh_dh1_server(Kex *kex, Buffer *client_kexinit, Buffer *server_kexinit)
1435 {
1436 #ifdef DEBUG_KEXDH
1437 	int i;
1438 #endif
1439 	int payload_len, dlen;
1440 	int slen;
1441 	unsigned char *signature = NULL;
1442 	unsigned char *server_host_key_blob = NULL;
1443 	unsigned int sbloblen;
1444 	unsigned int klen, kout;
1445 	unsigned char *kbuf;
1446 	unsigned char *hash;
1447 	BIGNUM *shared_secret = 0;
1448 	DH *dh;
1449 	BIGNUM *dh_client_pub = 0;
1450 
1451 /* KEXDH */
1452 	debug("Wait SSH2_MSG_KEXDH_INIT.");
1453 	packet_read_expect(&payload_len, SSH2_MSG_KEXDH_INIT);
1454 
1455 	/* key, cert */
1456 	dh_client_pub = BN_new();
1457 	if (dh_client_pub == NULL)
1458 		fatal("dh_client_pub == NULL");
1459 	packet_get_bignum2(dh_client_pub, &dlen);
1460 
1461 #ifdef DEBUG_KEXDH
1462 	fprintf(stderr, "\ndh_client_pub= ");
1463 	BN_print_fp(stderr, dh_client_pub);
1464 	fprintf(stderr, "\n");
1465 	debug("bits %d", BN_num_bits(dh_client_pub));
1466 #endif
1467 
1468 	/* generate DH key */
1469 	dh = dh_new_group1();			/* XXX depends on 'kex' */
1470 
1471 #ifdef DEBUG_KEXDH
1472 	fprintf(stderr, "\np= ");
1473 	BN_print_fp(stderr, dh->p);
1474 	fprintf(stderr, "\ng= ");
1475 	bn_print(dh->g);
1476 	fprintf(stderr, "\npub= ");
1477 	BN_print_fp(stderr, dh->pub_key);
1478 	fprintf(stderr, "\n");
1479         DHparams_print_fp(stderr, dh);
1480 #endif
1481 	if (!dh_pub_is_valid(dh, dh_client_pub))
1482 		packet_disconnect("bad client public DH value");
1483 
1484 	klen = DH_size(dh);
1485 	kbuf = xmalloc(klen);
1486 	kout = DH_compute_key(kbuf, dh_client_pub, dh);
1487 
1488 #ifdef DEBUG_KEXDH
1489 	debug("shared secret: len %d/%d", klen, kout);
1490 	fprintf(stderr, "shared secret == ");
1491 	for (i = 0; i< kout; i++)
1492 		fprintf(stderr, "%02x", (kbuf[i])&0xff);
1493 	fprintf(stderr, "\n");
1494 #endif
1495 	shared_secret = BN_new();
1496 
1497 	BN_bin2bn(kbuf, kout, shared_secret);
1498 	memset(kbuf, 0, klen);
1499 	xfree(kbuf);
1500 
1501 	/* XXX precompute? */
1502 	dsa_make_key_blob(sensitive_data.dsa_host_key,
1503 			  &server_host_key_blob, &sbloblen);
1504 
1505 	/* calc H */			/* XXX depends on 'kex' */
1506 	hash = kex_hash(
1507 	    client_version_string,
1508 	    server_version_string,
1509 	    buffer_ptr(client_kexinit), buffer_len(client_kexinit),
1510 	    buffer_ptr(server_kexinit), buffer_len(server_kexinit),
1511 	    (char *)server_host_key_blob, sbloblen,
1512 	    dh_client_pub,
1513 	    dh->pub_key,
1514 	    shared_secret
1515 	);
1516 	buffer_free(client_kexinit);
1517 	buffer_free(server_kexinit);
1518 	xfree(client_kexinit);
1519 	xfree(server_kexinit);
1520 #ifdef DEBUG_KEXDH
1521 	fprintf(stderr, "hash == ");
1522 	for (i = 0; i< 20; i++)
1523 		fprintf(stderr, "%02x", (hash[i])&0xff);
1524 	fprintf(stderr, "\n");
1525 #endif
1526 	/* save session id := H */
1527 	/* XXX hashlen depends on KEX */
1528 	session_id2_len = 20;
1529 	session_id2 = xmalloc(session_id2_len);
1530 	memcpy(session_id2, hash, session_id2_len);
1531 
1532 	/* sign H */
1533 	/* XXX hashlen depends on KEX */
1534 	dsa_sign(sensitive_data.dsa_host_key, &signature, &slen, hash, 20);
1535 
1536 	destroy_sensitive_data();
1537 
1538 	/* send server hostkey, DH pubkey 'f' and singed H */
1539 	packet_start(SSH2_MSG_KEXDH_REPLY);
1540 	packet_put_string((char *)server_host_key_blob, sbloblen);
1541 	packet_put_bignum2(dh->pub_key);	/* f */
1542 	packet_put_string((char *)signature, slen);
1543 	packet_send();
1544 	xfree(signature);
1545 	xfree(server_host_key_blob);
1546 	packet_write_wait();
1547 
1548 	kex_derive_keys(kex, hash, shared_secret);
1549 	packet_set_kex(kex);
1550 
1551 	/* have keys, free DH */
1552 	DH_free(dh);
1553 }
1554 
1555 /* diffie-hellman-group-exchange-sha1 */
1556 
1557 void
1558 ssh_dhgex_server(Kex *kex, Buffer *client_kexinit, Buffer *server_kexinit)
1559 {
1560 #ifdef DEBUG_KEXDH
1561 	int i;
1562 #endif
1563 	int payload_len, dlen;
1564 	int slen, nbits;
1565 	unsigned char *signature = NULL;
1566 	unsigned char *server_host_key_blob = NULL;
1567 	unsigned int sbloblen;
1568 	unsigned int klen, kout;
1569 	unsigned char *kbuf;
1570 	unsigned char *hash;
1571 	BIGNUM *shared_secret = 0;
1572 	DH *dh;
1573 	BIGNUM *dh_client_pub = 0;
1574 
1575 /* KEXDHGEX */
1576 	debug("Wait SSH2_MSG_KEX_DH_GEX_REQUEST.");
1577 	packet_read_expect(&payload_len, SSH2_MSG_KEX_DH_GEX_REQUEST);
1578 	nbits = packet_get_int();
1579 	dh = choose_dh(nbits);
1580 
1581 	debug("Sending SSH2_MSG_KEX_DH_GEX_GROUP.");
1582 	packet_start(SSH2_MSG_KEX_DH_GEX_GROUP);
1583 	packet_put_bignum2(dh->p);
1584 	packet_put_bignum2(dh->g);
1585 	packet_send();
1586 	packet_write_wait();
1587 
1588 	debug("Wait SSH2_MSG_KEX_DH_GEX_INIT.");
1589 	packet_read_expect(&payload_len, SSH2_MSG_KEX_DH_GEX_INIT);
1590 
1591 	/* key, cert */
1592 	dh_client_pub = BN_new();
1593 	if (dh_client_pub == NULL)
1594 		fatal("dh_client_pub == NULL");
1595 	packet_get_bignum2(dh_client_pub, &dlen);
1596 
1597 #ifdef DEBUG_KEXDH
1598 	fprintf(stderr, "\ndh_client_pub= ");
1599 	BN_print_fp(stderr, dh_client_pub);
1600 	fprintf(stderr, "\n");
1601 	debug("bits %d", BN_num_bits(dh_client_pub));
1602 #endif
1603 
1604 #ifdef DEBUG_KEXDH
1605 	fprintf(stderr, "\np= ");
1606 	BN_print_fp(stderr, dh->p);
1607 	fprintf(stderr, "\ng= ");
1608 	bn_print(dh->g);
1609 	fprintf(stderr, "\npub= ");
1610 	BN_print_fp(stderr, dh->pub_key);
1611 	fprintf(stderr, "\n");
1612         DHparams_print_fp(stderr, dh);
1613 #endif
1614 	if (!dh_pub_is_valid(dh, dh_client_pub))
1615 		packet_disconnect("bad client public DH value");
1616 
1617 	klen = DH_size(dh);
1618 	kbuf = xmalloc(klen);
1619 	kout = DH_compute_key(kbuf, dh_client_pub, dh);
1620 
1621 #ifdef DEBUG_KEXDH
1622 	debug("shared secret: len %d/%d", klen, kout);
1623 	fprintf(stderr, "shared secret == ");
1624 	for (i = 0; i< kout; i++)
1625 		fprintf(stderr, "%02x", (kbuf[i])&0xff);
1626 	fprintf(stderr, "\n");
1627 #endif
1628 	shared_secret = BN_new();
1629 
1630 	BN_bin2bn(kbuf, kout, shared_secret);
1631 	memset(kbuf, 0, klen);
1632 	xfree(kbuf);
1633 
1634 	/* XXX precompute? */
1635 	dsa_make_key_blob(sensitive_data.dsa_host_key,
1636 			  &server_host_key_blob, &sbloblen);
1637 
1638 	/* calc H */			/* XXX depends on 'kex' */
1639 	hash = kex_hash_gex(
1640 	    client_version_string,
1641 	    server_version_string,
1642 	    buffer_ptr(client_kexinit), buffer_len(client_kexinit),
1643 	    buffer_ptr(server_kexinit), buffer_len(server_kexinit),
1644 	    (char *)server_host_key_blob, sbloblen,
1645 	    nbits, dh->p, dh->g,
1646 	    dh_client_pub,
1647 	    dh->pub_key,
1648 	    shared_secret
1649 	);
1650 	buffer_free(client_kexinit);
1651 	buffer_free(server_kexinit);
1652 	xfree(client_kexinit);
1653 	xfree(server_kexinit);
1654 #ifdef DEBUG_KEXDH
1655 	fprintf(stderr, "hash == ");
1656 	for (i = 0; i< 20; i++)
1657 		fprintf(stderr, "%02x", (hash[i])&0xff);
1658 	fprintf(stderr, "\n");
1659 #endif
1660 	/* save session id := H */
1661 	/* XXX hashlen depends on KEX */
1662 	session_id2_len = 20;
1663 	session_id2 = xmalloc(session_id2_len);
1664 	memcpy(session_id2, hash, session_id2_len);
1665 
1666 	/* sign H */
1667 	/* XXX hashlen depends on KEX */
1668 	dsa_sign(sensitive_data.dsa_host_key, &signature, &slen, hash, 20);
1669 
1670 	destroy_sensitive_data();
1671 
1672 	/* send server hostkey, DH pubkey 'f' and singed H */
1673 	packet_start(SSH2_MSG_KEX_DH_GEX_REPLY);
1674 	packet_put_string((char *)server_host_key_blob, sbloblen);
1675 	packet_put_bignum2(dh->pub_key);	/* f */
1676 	packet_put_string((char *)signature, slen);
1677 	packet_send();
1678 	xfree(signature);
1679 	xfree(server_host_key_blob);
1680 	packet_write_wait();
1681 
1682 	kex_derive_keys(kex, hash, shared_secret);
1683 	packet_set_kex(kex);
1684 
1685 	/* have keys, free DH */
1686 	DH_free(dh);
1687 }
1688 
1689