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