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