sshd.c revision 199804
1/* $OpenBSD: sshd.c,v 1.367 2009/05/28 16:50:16 andreas Exp $ */
2/*
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 *                    All rights reserved
6 * This program is the ssh daemon.  It listens for connections from clients,
7 * and performs authentication, executes use commands or shell, and forwards
8 * information to/from the application to the user client over an encrypted
9 * connection.  This can also handle forwarding of X11, TCP/IP, and
10 * authentication agent connections.
11 *
12 * As far as I am concerned, the code I have written for this software
13 * can be used freely for any purpose.  Any derived versions of this
14 * software must be clearly marked as such, and if the derived work is
15 * incompatible with the protocol description in the RFC file, it must be
16 * called by a name other than "ssh" or "Secure Shell".
17 *
18 * SSH2 implementation:
19 * Privilege Separation:
20 *
21 * Copyright (c) 2000, 2001, 2002 Markus Friedl.  All rights reserved.
22 * Copyright (c) 2002 Niels Provos.  All rights reserved.
23 *
24 * Redistribution and use in source and binary forms, with or without
25 * modification, are permitted provided that the following conditions
26 * are met:
27 * 1. Redistributions of source code must retain the above copyright
28 *    notice, this list of conditions and the following disclaimer.
29 * 2. Redistributions in binary form must reproduce the above copyright
30 *    notice, this list of conditions and the following disclaimer in the
31 *    documentation and/or other materials provided with the distribution.
32 *
33 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
34 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
35 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
36 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
37 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
38 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
39 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
40 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
41 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
42 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43 */
44
45#include "includes.h"
46__RCSID("$FreeBSD: head/crypto/openssh/sshd.c 199804 2009-11-25 15:12:24Z attilio $");
47
48#include <sys/types.h>
49#include <sys/ioctl.h>
50#include <sys/mman.h>
51#include <sys/socket.h>
52#ifdef HAVE_SYS_STAT_H
53# include <sys/stat.h>
54#endif
55#ifdef HAVE_SYS_TIME_H
56# include <sys/time.h>
57#endif
58#include "openbsd-compat/sys-tree.h"
59#include "openbsd-compat/sys-queue.h"
60#include <sys/wait.h>
61
62#include <errno.h>
63#include <fcntl.h>
64#include <netdb.h>
65#ifdef HAVE_PATHS_H
66#include <paths.h>
67#endif
68#include <grp.h>
69#include <pwd.h>
70#include <signal.h>
71#include <stdarg.h>
72#include <stdio.h>
73#include <stdlib.h>
74#include <string.h>
75#include <unistd.h>
76#include <utmp.h>
77
78#include <openssl/dh.h>
79#include <openssl/bn.h>
80#include <openssl/md5.h>
81#include <openssl/rand.h>
82#include "openbsd-compat/openssl-compat.h"
83
84#ifdef HAVE_SECUREWARE
85#include <sys/security.h>
86#include <prot.h>
87#endif
88
89#ifdef __FreeBSD__
90#include <resolv.h>
91#if defined(GSSAPI) && defined(HAVE_GSSAPI_H)
92#include <gssapi.h>
93#elif defined(GSSAPI) && defined(HAVE_GSSAPI_GSSAPI_H)
94#include <gssapi/gssapi.h>
95#endif
96#endif
97
98#include "xmalloc.h"
99#include "ssh.h"
100#include "ssh1.h"
101#include "ssh2.h"
102#include "rsa.h"
103#include "sshpty.h"
104#include "packet.h"
105#include "log.h"
106#include "buffer.h"
107#include "servconf.h"
108#include "uidswap.h"
109#include "compat.h"
110#include "cipher.h"
111#include "key.h"
112#include "kex.h"
113#include "dh.h"
114#include "myproposal.h"
115#include "authfile.h"
116#include "pathnames.h"
117#include "atomicio.h"
118#include "canohost.h"
119#include "hostfile.h"
120#include "auth.h"
121#include "misc.h"
122#include "msg.h"
123#include "dispatch.h"
124#include "channels.h"
125#include "session.h"
126#include "monitor_mm.h"
127#include "monitor.h"
128#ifdef GSSAPI
129#include "ssh-gss.h"
130#endif
131#include "monitor_wrap.h"
132#include "roaming.h"
133#include "version.h"
134
135#ifdef LIBWRAP
136#include <tcpd.h>
137#include <syslog.h>
138int allow_severity;
139int deny_severity;
140#endif /* LIBWRAP */
141
142#ifndef O_NOCTTY
143#define O_NOCTTY	0
144#endif
145
146/* Re-exec fds */
147#define REEXEC_DEVCRYPTO_RESERVED_FD	(STDERR_FILENO + 1)
148#define REEXEC_STARTUP_PIPE_FD		(STDERR_FILENO + 2)
149#define REEXEC_CONFIG_PASS_FD		(STDERR_FILENO + 3)
150#define REEXEC_MIN_FREE_FD		(STDERR_FILENO + 4)
151
152extern char *__progname;
153
154/* Server configuration options. */
155ServerOptions options;
156
157/* Name of the server configuration file. */
158char *config_file_name = _PATH_SERVER_CONFIG_FILE;
159
160/*
161 * Debug mode flag.  This can be set on the command line.  If debug
162 * mode is enabled, extra debugging output will be sent to the system
163 * log, the daemon will not go to background, and will exit after processing
164 * the first connection.
165 */
166int debug_flag = 0;
167
168/* Flag indicating that the daemon should only test the configuration and keys. */
169int test_flag = 0;
170
171/* Flag indicating that the daemon is being started from inetd. */
172int inetd_flag = 0;
173
174/* Flag indicating that sshd should not detach and become a daemon. */
175int no_daemon_flag = 0;
176
177/* debug goes to stderr unless inetd_flag is set */
178int log_stderr = 0;
179
180/* Saved arguments to main(). */
181char **saved_argv;
182int saved_argc;
183
184/* re-exec */
185int rexeced_flag = 0;
186int rexec_flag = 1;
187int rexec_argc = 0;
188char **rexec_argv;
189
190/*
191 * The sockets that the server is listening; this is used in the SIGHUP
192 * signal handler.
193 */
194#define	MAX_LISTEN_SOCKS	16
195int listen_socks[MAX_LISTEN_SOCKS];
196int num_listen_socks = 0;
197
198/*
199 * the client's version string, passed by sshd2 in compat mode. if != NULL,
200 * sshd will skip the version-number exchange
201 */
202char *client_version_string = NULL;
203char *server_version_string = NULL;
204
205/* for rekeying XXX fixme */
206Kex *xxx_kex;
207
208/*
209 * Any really sensitive data in the application is contained in this
210 * structure. The idea is that this structure could be locked into memory so
211 * that the pages do not get written into swap.  However, there are some
212 * problems. The private key contains BIGNUMs, and we do not (in principle)
213 * have access to the internals of them, and locking just the structure is
214 * not very useful.  Currently, memory locking is not implemented.
215 */
216struct {
217	Key	*server_key;		/* ephemeral server key */
218	Key	*ssh1_host_key;		/* ssh1 host key */
219	Key	**host_keys;		/* all private host keys */
220	int	have_ssh1_key;
221	int	have_ssh2_key;
222	u_char	ssh1_cookie[SSH_SESSION_KEY_LENGTH];
223} sensitive_data;
224
225/*
226 * Flag indicating whether the RSA server key needs to be regenerated.
227 * Is set in the SIGALRM handler and cleared when the key is regenerated.
228 */
229static volatile sig_atomic_t key_do_regen = 0;
230
231/* This is set to true when a signal is received. */
232static volatile sig_atomic_t received_sighup = 0;
233static volatile sig_atomic_t received_sigterm = 0;
234
235/* session identifier, used by RSA-auth */
236u_char session_id[16];
237
238/* same for ssh2 */
239u_char *session_id2 = NULL;
240u_int session_id2_len = 0;
241
242/* record remote hostname or ip */
243u_int utmp_len = UT_HOSTSIZE;
244
245/* options.max_startup sized array of fd ints */
246int *startup_pipes = NULL;
247int startup_pipe;		/* in child */
248
249/* variables used for privilege separation */
250int use_privsep = -1;
251struct monitor *pmonitor = NULL;
252
253/* global authentication context */
254Authctxt *the_authctxt = NULL;
255
256/* sshd_config buffer */
257Buffer cfg;
258
259/* message to be displayed after login */
260Buffer loginmsg;
261
262/* Unprivileged user */
263struct passwd *privsep_pw = NULL;
264
265/* Prototypes for various functions defined later in this file. */
266void destroy_sensitive_data(void);
267void demote_sensitive_data(void);
268
269static void do_ssh1_kex(void);
270static void do_ssh2_kex(void);
271
272/*
273 * Close all listening sockets
274 */
275static void
276close_listen_socks(void)
277{
278	int i;
279
280	for (i = 0; i < num_listen_socks; i++)
281		close(listen_socks[i]);
282	num_listen_socks = -1;
283}
284
285static void
286close_startup_pipes(void)
287{
288	int i;
289
290	if (startup_pipes)
291		for (i = 0; i < options.max_startups; i++)
292			if (startup_pipes[i] != -1)
293				close(startup_pipes[i]);
294}
295
296/*
297 * Signal handler for SIGHUP.  Sshd execs itself when it receives SIGHUP;
298 * the effect is to reread the configuration file (and to regenerate
299 * the server key).
300 */
301
302/*ARGSUSED*/
303static void
304sighup_handler(int sig)
305{
306	int save_errno = errno;
307
308	received_sighup = 1;
309	signal(SIGHUP, sighup_handler);
310	errno = save_errno;
311}
312
313/*
314 * Called from the main program after receiving SIGHUP.
315 * Restarts the server.
316 */
317static void
318sighup_restart(void)
319{
320	logit("Received SIGHUP; restarting.");
321	close_listen_socks();
322	close_startup_pipes();
323	alarm(0);  /* alarm timer persists across exec */
324	execv(saved_argv[0], saved_argv);
325	logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
326	    strerror(errno));
327	exit(1);
328}
329
330/*
331 * Generic signal handler for terminating signals in the master daemon.
332 */
333/*ARGSUSED*/
334static void
335sigterm_handler(int sig)
336{
337	received_sigterm = sig;
338}
339
340/*
341 * SIGCHLD handler.  This is called whenever a child dies.  This will then
342 * reap any zombies left by exited children.
343 */
344/*ARGSUSED*/
345static void
346main_sigchld_handler(int sig)
347{
348	int save_errno = errno;
349	pid_t pid;
350	int status;
351
352	while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
353	    (pid < 0 && errno == EINTR))
354		;
355
356	signal(SIGCHLD, main_sigchld_handler);
357	errno = save_errno;
358}
359
360/*
361 * Signal handler for the alarm after the login grace period has expired.
362 */
363/*ARGSUSED*/
364static void
365grace_alarm_handler(int sig)
366{
367	if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
368		kill(pmonitor->m_pid, SIGALRM);
369
370	/* Log error and exit. */
371	sigdie("Timeout before authentication for %s", get_remote_ipaddr());
372}
373
374/*
375 * Signal handler for the key regeneration alarm.  Note that this
376 * alarm only occurs in the daemon waiting for connections, and it does not
377 * do anything with the private key or random state before forking.
378 * Thus there should be no concurrency control/asynchronous execution
379 * problems.
380 */
381static void
382generate_ephemeral_server_key(void)
383{
384	verbose("Generating %s%d bit RSA key.",
385	    sensitive_data.server_key ? "new " : "", options.server_key_bits);
386	if (sensitive_data.server_key != NULL)
387		key_free(sensitive_data.server_key);
388	sensitive_data.server_key = key_generate(KEY_RSA1,
389	    options.server_key_bits);
390	verbose("RSA key generation complete.");
391
392	arc4random_buf(sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
393	arc4random_stir();
394}
395
396/*ARGSUSED*/
397static void
398key_regeneration_alarm(int sig)
399{
400	int save_errno = errno;
401
402	signal(SIGALRM, SIG_DFL);
403	errno = save_errno;
404	key_do_regen = 1;
405}
406
407static void
408sshd_exchange_identification(int sock_in, int sock_out)
409{
410	u_int i;
411	int mismatch;
412	int remote_major, remote_minor;
413	int major, minor;
414	char *s, *newline = "\n";
415	char buf[256];			/* Must not be larger than remote_version. */
416	char remote_version[256];	/* Must be at least as big as buf. */
417
418	if ((options.protocol & SSH_PROTO_1) &&
419	    (options.protocol & SSH_PROTO_2)) {
420		major = PROTOCOL_MAJOR_1;
421		minor = 99;
422	} else if (options.protocol & SSH_PROTO_2) {
423		major = PROTOCOL_MAJOR_2;
424		minor = PROTOCOL_MINOR_2;
425		newline = "\r\n";
426	} else {
427		major = PROTOCOL_MAJOR_1;
428		minor = PROTOCOL_MINOR_1;
429	}
430	snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s%s", major, minor,
431	    SSH_VERSION, newline);
432	server_version_string = xstrdup(buf);
433
434	/* Send our protocol version identification. */
435	if (roaming_atomicio(vwrite, sock_out, server_version_string,
436	    strlen(server_version_string))
437	    != strlen(server_version_string)) {
438		logit("Could not write ident string to %s", get_remote_ipaddr());
439		cleanup_exit(255);
440	}
441
442	/* Read other sides version identification. */
443	memset(buf, 0, sizeof(buf));
444	for (i = 0; i < sizeof(buf) - 1; i++) {
445		if (roaming_atomicio(read, sock_in, &buf[i], 1) != 1) {
446			logit("Did not receive identification string from %s",
447			    get_remote_ipaddr());
448			cleanup_exit(255);
449		}
450		if (buf[i] == '\r') {
451			buf[i] = 0;
452			/* Kludge for F-Secure Macintosh < 1.0.2 */
453			if (i == 12 &&
454			    strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
455				break;
456			continue;
457		}
458		if (buf[i] == '\n') {
459			buf[i] = 0;
460			break;
461		}
462	}
463	buf[sizeof(buf) - 1] = 0;
464	client_version_string = xstrdup(buf);
465
466	/*
467	 * Check that the versions match.  In future this might accept
468	 * several versions and set appropriate flags to handle them.
469	 */
470	if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
471	    &remote_major, &remote_minor, remote_version) != 3) {
472		s = "Protocol mismatch.\n";
473		(void) atomicio(vwrite, sock_out, s, strlen(s));
474		close(sock_in);
475		close(sock_out);
476		logit("Bad protocol version identification '%.100s' from %s",
477		    client_version_string, get_remote_ipaddr());
478		cleanup_exit(255);
479	}
480	debug("Client protocol version %d.%d; client software version %.100s",
481	    remote_major, remote_minor, remote_version);
482
483	compat_datafellows(remote_version);
484
485	if (datafellows & SSH_BUG_PROBE) {
486		logit("probed from %s with %s.  Don't panic.",
487		    get_remote_ipaddr(), client_version_string);
488		cleanup_exit(255);
489	}
490
491	if (datafellows & SSH_BUG_SCANNER) {
492		logit("scanned from %s with %s.  Don't panic.",
493		    get_remote_ipaddr(), client_version_string);
494		cleanup_exit(255);
495	}
496
497	mismatch = 0;
498	switch (remote_major) {
499	case 1:
500		if (remote_minor == 99) {
501			if (options.protocol & SSH_PROTO_2)
502				enable_compat20();
503			else
504				mismatch = 1;
505			break;
506		}
507		if (!(options.protocol & SSH_PROTO_1)) {
508			mismatch = 1;
509			break;
510		}
511		if (remote_minor < 3) {
512			packet_disconnect("Your ssh version is too old and "
513			    "is no longer supported.  Please install a newer version.");
514		} else if (remote_minor == 3) {
515			/* note that this disables agent-forwarding */
516			enable_compat13();
517		}
518		break;
519	case 2:
520		if (options.protocol & SSH_PROTO_2) {
521			enable_compat20();
522			break;
523		}
524		/* FALLTHROUGH */
525	default:
526		mismatch = 1;
527		break;
528	}
529	chop(server_version_string);
530	debug("Local version string %.200s", server_version_string);
531
532	if (mismatch) {
533		s = "Protocol major versions differ.\n";
534		(void) atomicio(vwrite, sock_out, s, strlen(s));
535		close(sock_in);
536		close(sock_out);
537		logit("Protocol major versions differ for %s: %.200s vs. %.200s",
538		    get_remote_ipaddr(),
539		    server_version_string, client_version_string);
540		cleanup_exit(255);
541	}
542}
543
544/* Destroy the host and server keys.  They will no longer be needed. */
545void
546destroy_sensitive_data(void)
547{
548	int i;
549
550	if (sensitive_data.server_key) {
551		key_free(sensitive_data.server_key);
552		sensitive_data.server_key = NULL;
553	}
554	for (i = 0; i < options.num_host_key_files; i++) {
555		if (sensitive_data.host_keys[i]) {
556			key_free(sensitive_data.host_keys[i]);
557			sensitive_data.host_keys[i] = NULL;
558		}
559	}
560	sensitive_data.ssh1_host_key = NULL;
561	memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
562}
563
564/* Demote private to public keys for network child */
565void
566demote_sensitive_data(void)
567{
568	Key *tmp;
569	int i;
570
571	if (sensitive_data.server_key) {
572		tmp = key_demote(sensitive_data.server_key);
573		key_free(sensitive_data.server_key);
574		sensitive_data.server_key = tmp;
575	}
576
577	for (i = 0; i < options.num_host_key_files; i++) {
578		if (sensitive_data.host_keys[i]) {
579			tmp = key_demote(sensitive_data.host_keys[i]);
580			key_free(sensitive_data.host_keys[i]);
581			sensitive_data.host_keys[i] = tmp;
582			if (tmp->type == KEY_RSA1)
583				sensitive_data.ssh1_host_key = tmp;
584		}
585	}
586
587	/* We do not clear ssh1_host key and cookie.  XXX - Okay Niels? */
588}
589
590static void
591privsep_preauth_child(void)
592{
593	u_int32_t rnd[256];
594	gid_t gidset[1];
595
596	/* Enable challenge-response authentication for privilege separation */
597	privsep_challenge_enable();
598
599	arc4random_stir();
600	arc4random_buf(rnd, sizeof(rnd));
601	RAND_seed(rnd, sizeof(rnd));
602
603	/* Demote the private keys to public keys. */
604	demote_sensitive_data();
605
606	/* Change our root directory */
607	if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
608		fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
609		    strerror(errno));
610	if (chdir("/") == -1)
611		fatal("chdir(\"/\"): %s", strerror(errno));
612
613	/* Drop our privileges */
614	debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
615	    (u_int)privsep_pw->pw_gid);
616#if 0
617	/* XXX not ready, too heavy after chroot */
618	do_setusercontext(privsep_pw);
619#else
620	gidset[0] = privsep_pw->pw_gid;
621	if (setgroups(1, gidset) < 0)
622		fatal("setgroups: %.100s", strerror(errno));
623	permanently_set_uid(privsep_pw);
624#endif
625}
626
627static int
628privsep_preauth(Authctxt *authctxt)
629{
630	int status;
631	pid_t pid;
632
633	/* Set up unprivileged child process to deal with network data */
634	pmonitor = monitor_init();
635	/* Store a pointer to the kex for later rekeying */
636	pmonitor->m_pkex = &xxx_kex;
637
638	pid = fork();
639	if (pid == -1) {
640		fatal("fork of unprivileged child failed");
641	} else if (pid != 0) {
642		debug2("Network child is on pid %ld", (long)pid);
643
644		close(pmonitor->m_recvfd);
645		pmonitor->m_pid = pid;
646		monitor_child_preauth(authctxt, pmonitor);
647		close(pmonitor->m_sendfd);
648
649		/* Sync memory */
650		monitor_sync(pmonitor);
651
652		/* Wait for the child's exit status */
653		while (waitpid(pid, &status, 0) < 0)
654			if (errno != EINTR)
655				break;
656		return (1);
657	} else {
658		/* child */
659
660		close(pmonitor->m_sendfd);
661
662		/* Demote the child */
663		if (getuid() == 0 || geteuid() == 0)
664			privsep_preauth_child();
665		setproctitle("%s", "[net]");
666	}
667	return (0);
668}
669
670static void
671privsep_postauth(Authctxt *authctxt)
672{
673	u_int32_t rnd[256];
674
675#ifdef DISABLE_FD_PASSING
676	if (1) {
677#else
678	if (authctxt->pw->pw_uid == 0 || options.use_login) {
679#endif
680		/* File descriptor passing is broken or root login */
681		use_privsep = 0;
682		goto skip;
683	}
684
685	/* New socket pair */
686	monitor_reinit(pmonitor);
687
688	pmonitor->m_pid = fork();
689	if (pmonitor->m_pid == -1)
690		fatal("fork of unprivileged child failed");
691	else if (pmonitor->m_pid != 0) {
692		verbose("User child is on pid %ld", (long)pmonitor->m_pid);
693		close(pmonitor->m_recvfd);
694		buffer_clear(&loginmsg);
695		monitor_child_postauth(pmonitor);
696
697		/* NEVERREACHED */
698		exit(0);
699	}
700
701	close(pmonitor->m_sendfd);
702
703	/* Demote the private keys to public keys. */
704	demote_sensitive_data();
705
706	arc4random_stir();
707	arc4random_buf(rnd, sizeof(rnd));
708	RAND_seed(rnd, sizeof(rnd));
709
710	/* Drop privileges */
711	do_setusercontext(authctxt->pw);
712
713 skip:
714	/* It is safe now to apply the key state */
715	monitor_apply_keystate(pmonitor);
716
717	/*
718	 * Tell the packet layer that authentication was successful, since
719	 * this information is not part of the key state.
720	 */
721	packet_set_authenticated();
722}
723
724static char *
725list_hostkey_types(void)
726{
727	Buffer b;
728	const char *p;
729	char *ret;
730	int i;
731
732	buffer_init(&b);
733	for (i = 0; i < options.num_host_key_files; i++) {
734		Key *key = sensitive_data.host_keys[i];
735		if (key == NULL)
736			continue;
737		switch (key->type) {
738		case KEY_RSA:
739		case KEY_DSA:
740			if (buffer_len(&b) > 0)
741				buffer_append(&b, ",", 1);
742			p = key_ssh_name(key);
743			buffer_append(&b, p, strlen(p));
744			break;
745		}
746	}
747	buffer_append(&b, "\0", 1);
748	ret = xstrdup(buffer_ptr(&b));
749	buffer_free(&b);
750	debug("list_hostkey_types: %s", ret);
751	return ret;
752}
753
754Key *
755get_hostkey_by_type(int type)
756{
757	int i;
758
759	for (i = 0; i < options.num_host_key_files; i++) {
760		Key *key = sensitive_data.host_keys[i];
761		if (key != NULL && key->type == type)
762			return key;
763	}
764	return NULL;
765}
766
767Key *
768get_hostkey_by_index(int ind)
769{
770	if (ind < 0 || ind >= options.num_host_key_files)
771		return (NULL);
772	return (sensitive_data.host_keys[ind]);
773}
774
775int
776get_hostkey_index(Key *key)
777{
778	int i;
779
780	for (i = 0; i < options.num_host_key_files; i++) {
781		if (key == sensitive_data.host_keys[i])
782			return (i);
783	}
784	return (-1);
785}
786
787/*
788 * returns 1 if connection should be dropped, 0 otherwise.
789 * dropping starts at connection #max_startups_begin with a probability
790 * of (max_startups_rate/100). the probability increases linearly until
791 * all connections are dropped for startups > max_startups
792 */
793static int
794drop_connection(int startups)
795{
796	int p, r;
797
798	if (startups < options.max_startups_begin)
799		return 0;
800	if (startups >= options.max_startups)
801		return 1;
802	if (options.max_startups_rate == 100)
803		return 1;
804
805	p  = 100 - options.max_startups_rate;
806	p *= startups - options.max_startups_begin;
807	p /= options.max_startups - options.max_startups_begin;
808	p += options.max_startups_rate;
809	r = arc4random_uniform(100);
810
811	debug("drop_connection: p %d, r %d", p, r);
812	return (r < p) ? 1 : 0;
813}
814
815static void
816usage(void)
817{
818	fprintf(stderr, "%s, %s\n",
819	    SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
820	fprintf(stderr,
821"usage: sshd [-46DdeiqTt] [-b bits] [-C connection_spec] [-f config_file]\n"
822"            [-g login_grace_time] [-h host_key_file] [-k key_gen_time]\n"
823"            [-o option] [-p port] [-u len]\n"
824	);
825	exit(1);
826}
827
828static void
829send_rexec_state(int fd, Buffer *conf)
830{
831	Buffer m;
832
833	debug3("%s: entering fd = %d config len %d", __func__, fd,
834	    buffer_len(conf));
835
836	/*
837	 * Protocol from reexec master to child:
838	 *	string	configuration
839	 *	u_int	ephemeral_key_follows
840	 *	bignum	e		(only if ephemeral_key_follows == 1)
841	 *	bignum	n			"
842	 *	bignum	d			"
843	 *	bignum	iqmp			"
844	 *	bignum	p			"
845	 *	bignum	q			"
846	 *	string rngseed		(only if OpenSSL is not self-seeded)
847	 */
848	buffer_init(&m);
849	buffer_put_cstring(&m, buffer_ptr(conf));
850
851	if (sensitive_data.server_key != NULL &&
852	    sensitive_data.server_key->type == KEY_RSA1) {
853		buffer_put_int(&m, 1);
854		buffer_put_bignum(&m, sensitive_data.server_key->rsa->e);
855		buffer_put_bignum(&m, sensitive_data.server_key->rsa->n);
856		buffer_put_bignum(&m, sensitive_data.server_key->rsa->d);
857		buffer_put_bignum(&m, sensitive_data.server_key->rsa->iqmp);
858		buffer_put_bignum(&m, sensitive_data.server_key->rsa->p);
859		buffer_put_bignum(&m, sensitive_data.server_key->rsa->q);
860	} else
861		buffer_put_int(&m, 0);
862
863#ifndef OPENSSL_PRNG_ONLY
864	rexec_send_rng_seed(&m);
865#endif
866
867	if (ssh_msg_send(fd, 0, &m) == -1)
868		fatal("%s: ssh_msg_send failed", __func__);
869
870	buffer_free(&m);
871
872	debug3("%s: done", __func__);
873}
874
875static void
876recv_rexec_state(int fd, Buffer *conf)
877{
878	Buffer m;
879	char *cp;
880	u_int len;
881
882	debug3("%s: entering fd = %d", __func__, fd);
883
884	buffer_init(&m);
885
886	if (ssh_msg_recv(fd, &m) == -1)
887		fatal("%s: ssh_msg_recv failed", __func__);
888	if (buffer_get_char(&m) != 0)
889		fatal("%s: rexec version mismatch", __func__);
890
891	cp = buffer_get_string(&m, &len);
892	if (conf != NULL)
893		buffer_append(conf, cp, len + 1);
894	xfree(cp);
895
896	if (buffer_get_int(&m)) {
897		if (sensitive_data.server_key != NULL)
898			key_free(sensitive_data.server_key);
899		sensitive_data.server_key = key_new_private(KEY_RSA1);
900		buffer_get_bignum(&m, sensitive_data.server_key->rsa->e);
901		buffer_get_bignum(&m, sensitive_data.server_key->rsa->n);
902		buffer_get_bignum(&m, sensitive_data.server_key->rsa->d);
903		buffer_get_bignum(&m, sensitive_data.server_key->rsa->iqmp);
904		buffer_get_bignum(&m, sensitive_data.server_key->rsa->p);
905		buffer_get_bignum(&m, sensitive_data.server_key->rsa->q);
906		rsa_generate_additional_parameters(
907		    sensitive_data.server_key->rsa);
908	}
909
910#ifndef OPENSSL_PRNG_ONLY
911	rexec_recv_rng_seed(&m);
912#endif
913
914	buffer_free(&m);
915
916	debug3("%s: done", __func__);
917}
918
919/* Accept a connection from inetd */
920static void
921server_accept_inetd(int *sock_in, int *sock_out)
922{
923	int fd;
924
925	startup_pipe = -1;
926	if (rexeced_flag) {
927		close(REEXEC_CONFIG_PASS_FD);
928		*sock_in = *sock_out = dup(STDIN_FILENO);
929		if (!debug_flag) {
930			startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
931			close(REEXEC_STARTUP_PIPE_FD);
932		}
933	} else {
934		*sock_in = dup(STDIN_FILENO);
935		*sock_out = dup(STDOUT_FILENO);
936	}
937	/*
938	 * We intentionally do not close the descriptors 0, 1, and 2
939	 * as our code for setting the descriptors won't work if
940	 * ttyfd happens to be one of those.
941	 */
942	if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
943		dup2(fd, STDIN_FILENO);
944		dup2(fd, STDOUT_FILENO);
945		if (fd > STDOUT_FILENO)
946			close(fd);
947	}
948	debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
949}
950
951/*
952 * Listen for TCP connections
953 */
954static void
955server_listen(void)
956{
957	int ret, listen_sock, on = 1;
958	struct addrinfo *ai;
959	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
960
961	for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
962		if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
963			continue;
964		if (num_listen_socks >= MAX_LISTEN_SOCKS)
965			fatal("Too many listen sockets. "
966			    "Enlarge MAX_LISTEN_SOCKS");
967		if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
968		    ntop, sizeof(ntop), strport, sizeof(strport),
969		    NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
970			error("getnameinfo failed: %.100s",
971			    ssh_gai_strerror(ret));
972			continue;
973		}
974		/* Create socket for listening. */
975		listen_sock = socket(ai->ai_family, ai->ai_socktype,
976		    ai->ai_protocol);
977		if (listen_sock < 0) {
978			/* kernel may not support ipv6 */
979			verbose("socket: %.100s", strerror(errno));
980			continue;
981		}
982		if (set_nonblock(listen_sock) == -1) {
983			close(listen_sock);
984			continue;
985		}
986		/*
987		 * Set socket options.
988		 * Allow local port reuse in TIME_WAIT.
989		 */
990		if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
991		    &on, sizeof(on)) == -1)
992			error("setsockopt SO_REUSEADDR: %s", strerror(errno));
993
994#ifdef IPV6_V6ONLY
995		/* Only communicate in IPv6 over AF_INET6 sockets. */
996		if (ai->ai_family == AF_INET6) {
997			if (setsockopt(listen_sock, IPPROTO_IPV6, IPV6_V6ONLY,
998			    &on, sizeof(on)) == -1)
999				error("setsockopt IPV6_V6ONLY: %s",
1000				    strerror(errno));
1001		}
1002#endif
1003
1004		debug("Bind to port %s on %s.", strport, ntop);
1005
1006		/* Bind the socket to the desired port. */
1007		if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1008			error("Bind to port %s on %s failed: %.200s.",
1009			    strport, ntop, strerror(errno));
1010			close(listen_sock);
1011			continue;
1012		}
1013		listen_socks[num_listen_socks] = listen_sock;
1014		num_listen_socks++;
1015
1016		/* Start listening on the port. */
1017		if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1018			fatal("listen on [%s]:%s: %.100s",
1019			    ntop, strport, strerror(errno));
1020		logit("Server listening on %s port %s.", ntop, strport);
1021	}
1022	freeaddrinfo(options.listen_addrs);
1023
1024	if (!num_listen_socks)
1025		fatal("Cannot bind any address.");
1026}
1027
1028/*
1029 * The main TCP accept loop. Note that, for the non-debug case, returns
1030 * from this function are in a forked subprocess.
1031 */
1032static void
1033server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1034{
1035	fd_set *fdset;
1036	int i, j, ret, maxfd;
1037	int key_used = 0, startups = 0;
1038	int startup_p[2] = { -1 , -1 };
1039	struct sockaddr_storage from;
1040	socklen_t fromlen;
1041	pid_t pid;
1042
1043	/* setup fd set for accept */
1044	fdset = NULL;
1045	maxfd = 0;
1046	for (i = 0; i < num_listen_socks; i++)
1047		if (listen_socks[i] > maxfd)
1048			maxfd = listen_socks[i];
1049	/* pipes connected to unauthenticated childs */
1050	startup_pipes = xcalloc(options.max_startups, sizeof(int));
1051	for (i = 0; i < options.max_startups; i++)
1052		startup_pipes[i] = -1;
1053
1054	/*
1055	 * Stay listening for connections until the system crashes or
1056	 * the daemon is killed with a signal.
1057	 */
1058	for (;;) {
1059		if (received_sighup)
1060			sighup_restart();
1061		if (fdset != NULL)
1062			xfree(fdset);
1063		fdset = (fd_set *)xcalloc(howmany(maxfd + 1, NFDBITS),
1064		    sizeof(fd_mask));
1065
1066		for (i = 0; i < num_listen_socks; i++)
1067			FD_SET(listen_socks[i], fdset);
1068		for (i = 0; i < options.max_startups; i++)
1069			if (startup_pipes[i] != -1)
1070				FD_SET(startup_pipes[i], fdset);
1071
1072		/* Wait in select until there is a connection. */
1073		ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1074		if (ret < 0 && errno != EINTR)
1075			error("select: %.100s", strerror(errno));
1076		if (received_sigterm) {
1077			logit("Received signal %d; terminating.",
1078			    (int) received_sigterm);
1079			close_listen_socks();
1080			unlink(options.pid_file);
1081			exit(255);
1082		}
1083		if (key_used && key_do_regen) {
1084			generate_ephemeral_server_key();
1085			key_used = 0;
1086			key_do_regen = 0;
1087		}
1088		if (ret < 0)
1089			continue;
1090
1091		for (i = 0; i < options.max_startups; i++)
1092			if (startup_pipes[i] != -1 &&
1093			    FD_ISSET(startup_pipes[i], fdset)) {
1094				/*
1095				 * the read end of the pipe is ready
1096				 * if the child has closed the pipe
1097				 * after successful authentication
1098				 * or if the child has died
1099				 */
1100				close(startup_pipes[i]);
1101				startup_pipes[i] = -1;
1102				startups--;
1103			}
1104		for (i = 0; i < num_listen_socks; i++) {
1105			if (!FD_ISSET(listen_socks[i], fdset))
1106				continue;
1107			fromlen = sizeof(from);
1108			*newsock = accept(listen_socks[i],
1109			    (struct sockaddr *)&from, &fromlen);
1110			if (*newsock < 0) {
1111				if (errno != EINTR && errno != EAGAIN &&
1112				    errno != EWOULDBLOCK)
1113					error("accept: %.100s", strerror(errno));
1114				continue;
1115			}
1116			if (unset_nonblock(*newsock) == -1) {
1117				close(*newsock);
1118				continue;
1119			}
1120			if (drop_connection(startups) == 1) {
1121				debug("drop connection #%d", startups);
1122				close(*newsock);
1123				continue;
1124			}
1125			if (pipe(startup_p) == -1) {
1126				close(*newsock);
1127				continue;
1128			}
1129
1130			if (rexec_flag && socketpair(AF_UNIX,
1131			    SOCK_STREAM, 0, config_s) == -1) {
1132				error("reexec socketpair: %s",
1133				    strerror(errno));
1134				close(*newsock);
1135				close(startup_p[0]);
1136				close(startup_p[1]);
1137				continue;
1138			}
1139
1140			for (j = 0; j < options.max_startups; j++)
1141				if (startup_pipes[j] == -1) {
1142					startup_pipes[j] = startup_p[0];
1143					if (maxfd < startup_p[0])
1144						maxfd = startup_p[0];
1145					startups++;
1146					break;
1147				}
1148
1149			/*
1150			 * Got connection.  Fork a child to handle it, unless
1151			 * we are in debugging mode.
1152			 */
1153			if (debug_flag) {
1154				/*
1155				 * In debugging mode.  Close the listening
1156				 * socket, and start processing the
1157				 * connection without forking.
1158				 */
1159				debug("Server will not fork when running in debugging mode.");
1160				close_listen_socks();
1161				*sock_in = *newsock;
1162				*sock_out = *newsock;
1163				close(startup_p[0]);
1164				close(startup_p[1]);
1165				startup_pipe = -1;
1166				pid = getpid();
1167				if (rexec_flag) {
1168					send_rexec_state(config_s[0],
1169					    &cfg);
1170					close(config_s[0]);
1171				}
1172				break;
1173			}
1174
1175			/*
1176			 * Normal production daemon.  Fork, and have
1177			 * the child process the connection. The
1178			 * parent continues listening.
1179			 */
1180			platform_pre_fork();
1181			if ((pid = fork()) == 0) {
1182				/*
1183				 * Child.  Close the listening and
1184				 * max_startup sockets.  Start using
1185				 * the accepted socket. Reinitialize
1186				 * logging (since our pid has changed).
1187				 * We break out of the loop to handle
1188				 * the connection.
1189				 */
1190				platform_post_fork_child();
1191				startup_pipe = startup_p[1];
1192				close_startup_pipes();
1193				close_listen_socks();
1194				*sock_in = *newsock;
1195				*sock_out = *newsock;
1196				log_init(__progname,
1197				    options.log_level,
1198				    options.log_facility,
1199				    log_stderr);
1200				if (rexec_flag)
1201					close(config_s[0]);
1202				break;
1203			}
1204
1205			/* Parent.  Stay in the loop. */
1206			platform_post_fork_parent(pid);
1207			if (pid < 0)
1208				error("fork: %.100s", strerror(errno));
1209			else
1210				debug("Forked child %ld.", (long)pid);
1211
1212			close(startup_p[1]);
1213
1214			if (rexec_flag) {
1215				send_rexec_state(config_s[0], &cfg);
1216				close(config_s[0]);
1217				close(config_s[1]);
1218			}
1219
1220			/*
1221			 * Mark that the key has been used (it
1222			 * was "given" to the child).
1223			 */
1224			if ((options.protocol & SSH_PROTO_1) &&
1225			    key_used == 0) {
1226				/* Schedule server key regeneration alarm. */
1227				signal(SIGALRM, key_regeneration_alarm);
1228				alarm(options.key_regeneration_time);
1229				key_used = 1;
1230			}
1231
1232			close(*newsock);
1233
1234			/*
1235			 * Ensure that our random state differs
1236			 * from that of the child
1237			 */
1238			arc4random_stir();
1239		}
1240
1241		/* child process check (or debug mode) */
1242		if (num_listen_socks < 0)
1243			break;
1244	}
1245}
1246
1247
1248/*
1249 * Main program for the daemon.
1250 */
1251int
1252main(int ac, char **av)
1253{
1254	extern char *optarg;
1255	extern int optind;
1256	int opt, i, on = 1;
1257	int sock_in = -1, sock_out = -1, newsock = -1;
1258	const char *remote_ip;
1259	char *test_user = NULL, *test_host = NULL, *test_addr = NULL;
1260	int remote_port;
1261	char *line, *p, *cp;
1262	int config_s[2] = { -1 , -1 };
1263	u_int64_t ibytes, obytes;
1264	mode_t new_umask;
1265	Key *key;
1266	Authctxt *authctxt;
1267
1268#ifdef HAVE_SECUREWARE
1269	(void)set_auth_parameters(ac, av);
1270#endif
1271	__progname = ssh_get_progname(av[0]);
1272	init_rng();
1273
1274	/* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1275	saved_argc = ac;
1276	rexec_argc = ac;
1277	saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1278	for (i = 0; i < ac; i++)
1279		saved_argv[i] = xstrdup(av[i]);
1280	saved_argv[i] = NULL;
1281
1282#ifndef HAVE_SETPROCTITLE
1283	/* Prepare for later setproctitle emulation */
1284	compat_init_setproctitle(ac, av);
1285	av = saved_argv;
1286#endif
1287
1288	if (geteuid() == 0 && setgroups(0, NULL) == -1)
1289		debug("setgroups(): %.200s", strerror(errno));
1290
1291	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1292	sanitise_stdfd();
1293
1294	/* Initialize configuration options to their default values. */
1295	initialize_server_options(&options);
1296
1297	/* Avoid killing the process in high-pressure swapping environments. */
1298	if (madvise(NULL, 0, MADV_PROTECT) != 0)
1299		debug("madvise(): %.200s", strerror(errno));
1300
1301	/* Parse command-line arguments. */
1302	while ((opt = getopt(ac, av, "f:p:b:k:h:g:u:o:C:dDeiqrtQRT46")) != -1) {
1303		switch (opt) {
1304		case '4':
1305			options.address_family = AF_INET;
1306			break;
1307		case '6':
1308			options.address_family = AF_INET6;
1309			break;
1310		case 'f':
1311			config_file_name = optarg;
1312			break;
1313		case 'd':
1314			if (debug_flag == 0) {
1315				debug_flag = 1;
1316				options.log_level = SYSLOG_LEVEL_DEBUG1;
1317			} else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1318				options.log_level++;
1319			break;
1320		case 'D':
1321			no_daemon_flag = 1;
1322			break;
1323		case 'e':
1324			log_stderr = 1;
1325			break;
1326		case 'i':
1327			inetd_flag = 1;
1328			break;
1329		case 'r':
1330			rexec_flag = 0;
1331			break;
1332		case 'R':
1333			rexeced_flag = 1;
1334			inetd_flag = 1;
1335			break;
1336		case 'Q':
1337			/* ignored */
1338			break;
1339		case 'q':
1340			options.log_level = SYSLOG_LEVEL_QUIET;
1341			break;
1342		case 'b':
1343			options.server_key_bits = (int)strtonum(optarg, 256,
1344			    32768, NULL);
1345			break;
1346		case 'p':
1347			options.ports_from_cmdline = 1;
1348			if (options.num_ports >= MAX_PORTS) {
1349				fprintf(stderr, "too many ports.\n");
1350				exit(1);
1351			}
1352			options.ports[options.num_ports++] = a2port(optarg);
1353			if (options.ports[options.num_ports-1] <= 0) {
1354				fprintf(stderr, "Bad port number.\n");
1355				exit(1);
1356			}
1357			break;
1358		case 'g':
1359			if ((options.login_grace_time = convtime(optarg)) == -1) {
1360				fprintf(stderr, "Invalid login grace time.\n");
1361				exit(1);
1362			}
1363			break;
1364		case 'k':
1365			if ((options.key_regeneration_time = convtime(optarg)) == -1) {
1366				fprintf(stderr, "Invalid key regeneration interval.\n");
1367				exit(1);
1368			}
1369			break;
1370		case 'h':
1371			if (options.num_host_key_files >= MAX_HOSTKEYS) {
1372				fprintf(stderr, "too many host keys.\n");
1373				exit(1);
1374			}
1375			options.host_key_files[options.num_host_key_files++] = optarg;
1376			break;
1377		case 't':
1378			test_flag = 1;
1379			break;
1380		case 'T':
1381			test_flag = 2;
1382			break;
1383		case 'C':
1384			cp = optarg;
1385			while ((p = strsep(&cp, ",")) && *p != '\0') {
1386				if (strncmp(p, "addr=", 5) == 0)
1387					test_addr = xstrdup(p + 5);
1388				else if (strncmp(p, "host=", 5) == 0)
1389					test_host = xstrdup(p + 5);
1390				else if (strncmp(p, "user=", 5) == 0)
1391					test_user = xstrdup(p + 5);
1392				else {
1393					fprintf(stderr, "Invalid test "
1394					    "mode specification %s\n", p);
1395					exit(1);
1396				}
1397			}
1398			break;
1399		case 'u':
1400			utmp_len = (u_int)strtonum(optarg, 0, MAXHOSTNAMELEN+1, NULL);
1401			if (utmp_len > MAXHOSTNAMELEN) {
1402				fprintf(stderr, "Invalid utmp length.\n");
1403				exit(1);
1404			}
1405			break;
1406		case 'o':
1407			line = xstrdup(optarg);
1408			if (process_server_config_line(&options, line,
1409			    "command-line", 0, NULL, NULL, NULL, NULL) != 0)
1410				exit(1);
1411			xfree(line);
1412			break;
1413		case '?':
1414		default:
1415			usage();
1416			break;
1417		}
1418	}
1419	if (rexeced_flag || inetd_flag)
1420		rexec_flag = 0;
1421	if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1422		fatal("sshd re-exec requires execution with an absolute path");
1423	if (rexeced_flag)
1424		closefrom(REEXEC_MIN_FREE_FD);
1425	else
1426		closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1427
1428	SSLeay_add_all_algorithms();
1429
1430	/*
1431	 * Force logging to stderr until we have loaded the private host
1432	 * key (unless started from inetd)
1433	 */
1434	log_init(__progname,
1435	    options.log_level == SYSLOG_LEVEL_NOT_SET ?
1436	    SYSLOG_LEVEL_INFO : options.log_level,
1437	    options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1438	    SYSLOG_FACILITY_AUTH : options.log_facility,
1439	    log_stderr || !inetd_flag);
1440
1441	/*
1442	 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1443	 * root's environment
1444	 */
1445	if (getenv("KRB5CCNAME") != NULL)
1446		unsetenv("KRB5CCNAME");
1447
1448#ifdef _UNICOS
1449	/* Cray can define user privs drop all privs now!
1450	 * Not needed on PRIV_SU systems!
1451	 */
1452	drop_cray_privs();
1453#endif
1454
1455	sensitive_data.server_key = NULL;
1456	sensitive_data.ssh1_host_key = NULL;
1457	sensitive_data.have_ssh1_key = 0;
1458	sensitive_data.have_ssh2_key = 0;
1459
1460	/*
1461	 * If we're doing an extended config test, make sure we have all of
1462	 * the parameters we need.  If we're not doing an extended test,
1463	 * do not silently ignore connection test params.
1464	 */
1465	if (test_flag >= 2 &&
1466	   (test_user != NULL || test_host != NULL || test_addr != NULL)
1467	    && (test_user == NULL || test_host == NULL || test_addr == NULL))
1468		fatal("user, host and addr are all required when testing "
1469		   "Match configs");
1470	if (test_flag < 2 && (test_user != NULL || test_host != NULL ||
1471	    test_addr != NULL))
1472		fatal("Config test connection parameter (-C) provided without "
1473		   "test mode (-T)");
1474
1475	/* Fetch our configuration */
1476	buffer_init(&cfg);
1477	if (rexeced_flag)
1478		recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1479	else
1480		load_server_config(config_file_name, &cfg);
1481
1482	parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1483	    &cfg, NULL, NULL, NULL);
1484
1485	seed_rng();
1486
1487	/* Fill in default values for those options not explicitly set. */
1488	fill_default_server_options(&options);
1489
1490	/* challenge-response is implemented via keyboard interactive */
1491	if (options.challenge_response_authentication)
1492		options.kbd_interactive_authentication = 1;
1493
1494	/* set default channel AF */
1495	channel_set_af(options.address_family);
1496
1497	/* Check that there are no remaining arguments. */
1498	if (optind < ac) {
1499		fprintf(stderr, "Extra argument %s.\n", av[optind]);
1500		exit(1);
1501	}
1502
1503	debug("sshd version %.100s", SSH_RELEASE);
1504
1505	/* Store privilege separation user for later use if required. */
1506	if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1507		if (use_privsep || options.kerberos_authentication)
1508			fatal("Privilege separation user %s does not exist",
1509			    SSH_PRIVSEP_USER);
1510	} else {
1511		memset(privsep_pw->pw_passwd, 0, strlen(privsep_pw->pw_passwd));
1512		privsep_pw = pwcopy(privsep_pw);
1513		xfree(privsep_pw->pw_passwd);
1514		privsep_pw->pw_passwd = xstrdup("*");
1515	}
1516	endpwent();
1517
1518	/* load private host keys */
1519	sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1520	    sizeof(Key *));
1521	for (i = 0; i < options.num_host_key_files; i++)
1522		sensitive_data.host_keys[i] = NULL;
1523
1524	for (i = 0; i < options.num_host_key_files; i++) {
1525		key = key_load_private(options.host_key_files[i], "", NULL);
1526		sensitive_data.host_keys[i] = key;
1527		if (key == NULL) {
1528			error("Could not load host key: %s",
1529			    options.host_key_files[i]);
1530			sensitive_data.host_keys[i] = NULL;
1531			continue;
1532		}
1533		switch (key->type) {
1534		case KEY_RSA1:
1535			sensitive_data.ssh1_host_key = key;
1536			sensitive_data.have_ssh1_key = 1;
1537			break;
1538		case KEY_RSA:
1539		case KEY_DSA:
1540			sensitive_data.have_ssh2_key = 1;
1541			break;
1542		}
1543		debug("private host key: #%d type %d %s", i, key->type,
1544		    key_type(key));
1545	}
1546	if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1547		logit("Disabling protocol version 1. Could not load host key");
1548		options.protocol &= ~SSH_PROTO_1;
1549	}
1550	if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1551		logit("Disabling protocol version 2. Could not load host key");
1552		options.protocol &= ~SSH_PROTO_2;
1553	}
1554	if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1555		logit("sshd: no hostkeys available -- exiting.");
1556		exit(1);
1557	}
1558
1559	/* Check certain values for sanity. */
1560	if (options.protocol & SSH_PROTO_1) {
1561		if (options.server_key_bits < 512 ||
1562		    options.server_key_bits > 32768) {
1563			fprintf(stderr, "Bad server key size.\n");
1564			exit(1);
1565		}
1566		/*
1567		 * Check that server and host key lengths differ sufficiently. This
1568		 * is necessary to make double encryption work with rsaref. Oh, I
1569		 * hate software patents. I dont know if this can go? Niels
1570		 */
1571		if (options.server_key_bits >
1572		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
1573		    SSH_KEY_BITS_RESERVED && options.server_key_bits <
1574		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1575		    SSH_KEY_BITS_RESERVED) {
1576			options.server_key_bits =
1577			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1578			    SSH_KEY_BITS_RESERVED;
1579			debug("Forcing server key to %d bits to make it differ from host key.",
1580			    options.server_key_bits);
1581		}
1582	}
1583
1584	if (use_privsep) {
1585		struct stat st;
1586
1587		if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1588		    (S_ISDIR(st.st_mode) == 0))
1589			fatal("Missing privilege separation directory: %s",
1590			    _PATH_PRIVSEP_CHROOT_DIR);
1591
1592#ifdef HAVE_CYGWIN
1593		if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1594		    (st.st_uid != getuid () ||
1595		    (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1596#else
1597		if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1598#endif
1599			fatal("%s must be owned by root and not group or "
1600			    "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1601	}
1602
1603	if (test_flag > 1) {
1604		if (test_user != NULL && test_addr != NULL && test_host != NULL)
1605			parse_server_match_config(&options, test_user,
1606			    test_host, test_addr);
1607		dump_config(&options);
1608	}
1609
1610	/* Configuration looks good, so exit if in test mode. */
1611	if (test_flag)
1612		exit(0);
1613
1614	/*
1615	 * Clear out any supplemental groups we may have inherited.  This
1616	 * prevents inadvertent creation of files with bad modes (in the
1617	 * portable version at least, it's certainly possible for PAM
1618	 * to create a file, and we can't control the code in every
1619	 * module which might be used).
1620	 */
1621	if (setgroups(0, NULL) < 0)
1622		debug("setgroups() failed: %.200s", strerror(errno));
1623
1624	if (rexec_flag) {
1625		rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1626		for (i = 0; i < rexec_argc; i++) {
1627			debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1628			rexec_argv[i] = saved_argv[i];
1629		}
1630		rexec_argv[rexec_argc] = "-R";
1631		rexec_argv[rexec_argc + 1] = NULL;
1632	}
1633
1634	/* Ensure that umask disallows at least group and world write */
1635	new_umask = umask(0077) | 0022;
1636	(void) umask(new_umask);
1637
1638	/* Initialize the log (it is reinitialized below in case we forked). */
1639	if (debug_flag && (!inetd_flag || rexeced_flag))
1640		log_stderr = 1;
1641	log_init(__progname, options.log_level, options.log_facility, log_stderr);
1642
1643	/*
1644	 * If not in debugging mode, and not started from inetd, disconnect
1645	 * from the controlling terminal, and fork.  The original process
1646	 * exits.
1647	 */
1648	if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1649#ifdef TIOCNOTTY
1650		int fd;
1651#endif /* TIOCNOTTY */
1652		if (daemon(0, 0) < 0)
1653			fatal("daemon() failed: %.200s", strerror(errno));
1654
1655		/* Disconnect from the controlling tty. */
1656#ifdef TIOCNOTTY
1657		fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1658		if (fd >= 0) {
1659			(void) ioctl(fd, TIOCNOTTY, NULL);
1660			close(fd);
1661		}
1662#endif /* TIOCNOTTY */
1663	}
1664	/* Reinitialize the log (because of the fork above). */
1665	log_init(__progname, options.log_level, options.log_facility, log_stderr);
1666
1667	/* Initialize the random number generator. */
1668	arc4random_stir();
1669
1670	/* Chdir to the root directory so that the current disk can be
1671	   unmounted if desired. */
1672	chdir("/");
1673
1674	/* ignore SIGPIPE */
1675	signal(SIGPIPE, SIG_IGN);
1676
1677	/* Get a connection, either from inetd or a listening TCP socket */
1678	if (inetd_flag) {
1679		server_accept_inetd(&sock_in, &sock_out);
1680	} else {
1681		server_listen();
1682
1683		if (options.protocol & SSH_PROTO_1)
1684			generate_ephemeral_server_key();
1685
1686		signal(SIGHUP, sighup_handler);
1687		signal(SIGCHLD, main_sigchld_handler);
1688		signal(SIGTERM, sigterm_handler);
1689		signal(SIGQUIT, sigterm_handler);
1690
1691		/*
1692		 * Write out the pid file after the sigterm handler
1693		 * is setup and the listen sockets are bound
1694		 */
1695		if (!debug_flag) {
1696			FILE *f = fopen(options.pid_file, "w");
1697
1698			if (f == NULL) {
1699				error("Couldn't create pid file \"%s\": %s",
1700				    options.pid_file, strerror(errno));
1701			} else {
1702				fprintf(f, "%ld\n", (long) getpid());
1703				fclose(f);
1704			}
1705		}
1706
1707		/* Accept a connection and return in a forked child */
1708		server_accept_loop(&sock_in, &sock_out,
1709		    &newsock, config_s);
1710	}
1711
1712	/* This is the child processing a new connection. */
1713	setproctitle("%s", "[accepted]");
1714
1715	/*
1716	 * Create a new session and process group since the 4.4BSD
1717	 * setlogin() affects the entire process group.  We don't
1718	 * want the child to be able to affect the parent.
1719	 */
1720#if !defined(SSHD_ACQUIRES_CTTY)
1721	/*
1722	 * If setsid is called, on some platforms sshd will later acquire a
1723	 * controlling terminal which will result in "could not set
1724	 * controlling tty" errors.
1725	 */
1726	if (!debug_flag && !inetd_flag && setsid() < 0)
1727		error("setsid: %.100s", strerror(errno));
1728#endif
1729
1730	if (rexec_flag) {
1731		int fd;
1732
1733		debug("rexec start in %d out %d newsock %d pipe %d sock %d",
1734		    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1735		dup2(newsock, STDIN_FILENO);
1736		dup2(STDIN_FILENO, STDOUT_FILENO);
1737		if (startup_pipe == -1)
1738			close(REEXEC_STARTUP_PIPE_FD);
1739		else
1740			dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
1741
1742		dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1743		close(config_s[1]);
1744		if (startup_pipe != -1)
1745			close(startup_pipe);
1746
1747		execv(rexec_argv[0], rexec_argv);
1748
1749		/* Reexec has failed, fall back and continue */
1750		error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1751		recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1752		log_init(__progname, options.log_level,
1753		    options.log_facility, log_stderr);
1754
1755		/* Clean up fds */
1756		startup_pipe = REEXEC_STARTUP_PIPE_FD;
1757		close(config_s[1]);
1758		close(REEXEC_CONFIG_PASS_FD);
1759		newsock = sock_out = sock_in = dup(STDIN_FILENO);
1760		if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1761			dup2(fd, STDIN_FILENO);
1762			dup2(fd, STDOUT_FILENO);
1763			if (fd > STDERR_FILENO)
1764				close(fd);
1765		}
1766		debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
1767		    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1768	}
1769
1770	/*
1771	 * Disable the key regeneration alarm.  We will not regenerate the
1772	 * key since we are no longer in a position to give it to anyone. We
1773	 * will not restart on SIGHUP since it no longer makes sense.
1774	 */
1775	alarm(0);
1776	signal(SIGALRM, SIG_DFL);
1777	signal(SIGHUP, SIG_DFL);
1778	signal(SIGTERM, SIG_DFL);
1779	signal(SIGQUIT, SIG_DFL);
1780	signal(SIGCHLD, SIG_DFL);
1781	signal(SIGINT, SIG_DFL);
1782
1783#ifdef __FreeBSD__
1784	/*
1785	 * Initialize the resolver.  This may not happen automatically
1786	 * before privsep chroot().
1787	 */
1788	if ((_res.options & RES_INIT) == 0) {
1789		debug("res_init()");
1790		res_init();
1791	}
1792#ifdef GSSAPI
1793	/*
1794	 * Force GSS-API to parse its configuration and load any
1795	 * mechanism plugins.
1796	 */
1797	{
1798		gss_OID_set mechs;
1799		OM_uint32 minor_status;
1800		gss_indicate_mechs(&minor_status, &mechs);
1801		gss_release_oid_set(&minor_status, &mechs);
1802	}
1803#endif
1804#endif
1805
1806	/*
1807	 * Register our connection.  This turns encryption off because we do
1808	 * not have a key.
1809	 */
1810	packet_set_connection(sock_in, sock_out);
1811	packet_set_server();
1812
1813	/* Set SO_KEEPALIVE if requested. */
1814	if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
1815	    setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
1816		error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1817
1818	if ((remote_port = get_remote_port()) < 0) {
1819		debug("get_remote_port failed");
1820		cleanup_exit(255);
1821	}
1822
1823	/*
1824	 * We use get_canonical_hostname with usedns = 0 instead of
1825	 * get_remote_ipaddr here so IP options will be checked.
1826	 */
1827	(void) get_canonical_hostname(0);
1828	/*
1829	 * The rest of the code depends on the fact that
1830	 * get_remote_ipaddr() caches the remote ip, even if
1831	 * the socket goes away.
1832	 */
1833	remote_ip = get_remote_ipaddr();
1834
1835#ifdef SSH_AUDIT_EVENTS
1836	audit_connection_from(remote_ip, remote_port);
1837#endif
1838#ifdef LIBWRAP
1839	allow_severity = options.log_facility|LOG_INFO;
1840	deny_severity = options.log_facility|LOG_WARNING;
1841	/* Check whether logins are denied from this host. */
1842	if (packet_connection_is_on_socket()) {
1843		struct request_info req;
1844
1845		request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1846		fromhost(&req);
1847
1848		if (!hosts_access(&req)) {
1849			debug("Connection refused by tcp wrapper");
1850			refuse(&req);
1851			/* NOTREACHED */
1852			fatal("libwrap refuse returns");
1853		}
1854	}
1855#endif /* LIBWRAP */
1856
1857	/* Log the connection. */
1858	verbose("Connection from %.500s port %d", remote_ip, remote_port);
1859
1860	/*
1861	 * We don't want to listen forever unless the other side
1862	 * successfully authenticates itself.  So we set up an alarm which is
1863	 * cleared after successful authentication.  A limit of zero
1864	 * indicates no limit. Note that we don't set the alarm in debugging
1865	 * mode; it is just annoying to have the server exit just when you
1866	 * are about to discover the bug.
1867	 */
1868	signal(SIGALRM, grace_alarm_handler);
1869	if (!debug_flag)
1870		alarm(options.login_grace_time);
1871
1872	sshd_exchange_identification(sock_in, sock_out);
1873
1874	/* In inetd mode, generate ephemeral key only for proto 1 connections */
1875	if (!compat20 && inetd_flag && sensitive_data.server_key == NULL)
1876		generate_ephemeral_server_key();
1877
1878	packet_set_nonblocking();
1879
1880	/* allocate authentication context */
1881	authctxt = xcalloc(1, sizeof(*authctxt));
1882
1883	authctxt->loginmsg = &loginmsg;
1884
1885	/* XXX global for cleanup, access from other modules */
1886	the_authctxt = authctxt;
1887
1888	/* prepare buffer to collect messages to display to user after login */
1889	buffer_init(&loginmsg);
1890
1891	if (use_privsep)
1892		if (privsep_preauth(authctxt) == 1)
1893			goto authenticated;
1894
1895	/* perform the key exchange */
1896	/* authenticate user and start session */
1897	if (compat20) {
1898		do_ssh2_kex();
1899		do_authentication2(authctxt);
1900	} else {
1901		do_ssh1_kex();
1902		do_authentication(authctxt);
1903	}
1904	/*
1905	 * If we use privilege separation, the unprivileged child transfers
1906	 * the current keystate and exits
1907	 */
1908	if (use_privsep) {
1909		mm_send_keystate(pmonitor);
1910		exit(0);
1911	}
1912
1913 authenticated:
1914	/*
1915	 * Cancel the alarm we set to limit the time taken for
1916	 * authentication.
1917	 */
1918	alarm(0);
1919	signal(SIGALRM, SIG_DFL);
1920	authctxt->authenticated = 1;
1921	if (startup_pipe != -1) {
1922		close(startup_pipe);
1923		startup_pipe = -1;
1924	}
1925
1926#ifdef SSH_AUDIT_EVENTS
1927	audit_event(SSH_AUTH_SUCCESS);
1928#endif
1929
1930#ifdef GSSAPI
1931	if (options.gss_authentication) {
1932		temporarily_use_uid(authctxt->pw);
1933		ssh_gssapi_storecreds();
1934		restore_uid();
1935	}
1936#endif
1937#ifdef USE_PAM
1938	if (options.use_pam) {
1939		do_pam_setcred(1);
1940		do_pam_session();
1941	}
1942#endif
1943
1944	/*
1945	 * In privilege separation, we fork another child and prepare
1946	 * file descriptor passing.
1947	 */
1948	if (use_privsep) {
1949		privsep_postauth(authctxt);
1950		/* the monitor process [priv] will not return */
1951		if (!compat20)
1952			destroy_sensitive_data();
1953	}
1954
1955	packet_set_timeout(options.client_alive_interval,
1956	    options.client_alive_count_max);
1957
1958	/* Start session. */
1959	do_authenticated(authctxt);
1960
1961	/* The connection has been terminated. */
1962	packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
1963	packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
1964	verbose("Transferred: sent %llu, received %llu bytes", obytes, ibytes);
1965
1966	verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
1967
1968#ifdef USE_PAM
1969	if (options.use_pam)
1970		finish_pam();
1971#endif /* USE_PAM */
1972
1973#ifdef SSH_AUDIT_EVENTS
1974	PRIVSEP(audit_event(SSH_CONNECTION_CLOSE));
1975#endif
1976
1977	packet_close();
1978
1979	if (use_privsep)
1980		mm_terminate();
1981
1982	exit(0);
1983}
1984
1985/*
1986 * Decrypt session_key_int using our private server key and private host key
1987 * (key with larger modulus first).
1988 */
1989int
1990ssh1_session_key(BIGNUM *session_key_int)
1991{
1992	int rsafail = 0;
1993
1994	if (BN_cmp(sensitive_data.server_key->rsa->n,
1995	    sensitive_data.ssh1_host_key->rsa->n) > 0) {
1996		/* Server key has bigger modulus. */
1997		if (BN_num_bits(sensitive_data.server_key->rsa->n) <
1998		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1999		    SSH_KEY_BITS_RESERVED) {
2000			fatal("do_connection: %s: "
2001			    "server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
2002			    get_remote_ipaddr(),
2003			    BN_num_bits(sensitive_data.server_key->rsa->n),
2004			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2005			    SSH_KEY_BITS_RESERVED);
2006		}
2007		if (rsa_private_decrypt(session_key_int, session_key_int,
2008		    sensitive_data.server_key->rsa) <= 0)
2009			rsafail++;
2010		if (rsa_private_decrypt(session_key_int, session_key_int,
2011		    sensitive_data.ssh1_host_key->rsa) <= 0)
2012			rsafail++;
2013	} else {
2014		/* Host key has bigger modulus (or they are equal). */
2015		if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
2016		    BN_num_bits(sensitive_data.server_key->rsa->n) +
2017		    SSH_KEY_BITS_RESERVED) {
2018			fatal("do_connection: %s: "
2019			    "host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
2020			    get_remote_ipaddr(),
2021			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2022			    BN_num_bits(sensitive_data.server_key->rsa->n),
2023			    SSH_KEY_BITS_RESERVED);
2024		}
2025		if (rsa_private_decrypt(session_key_int, session_key_int,
2026		    sensitive_data.ssh1_host_key->rsa) < 0)
2027			rsafail++;
2028		if (rsa_private_decrypt(session_key_int, session_key_int,
2029		    sensitive_data.server_key->rsa) < 0)
2030			rsafail++;
2031	}
2032	return (rsafail);
2033}
2034/*
2035 * SSH1 key exchange
2036 */
2037static void
2038do_ssh1_kex(void)
2039{
2040	int i, len;
2041	int rsafail = 0;
2042	BIGNUM *session_key_int;
2043	u_char session_key[SSH_SESSION_KEY_LENGTH];
2044	u_char cookie[8];
2045	u_int cipher_type, auth_mask, protocol_flags;
2046
2047	/*
2048	 * Generate check bytes that the client must send back in the user
2049	 * packet in order for it to be accepted; this is used to defy ip
2050	 * spoofing attacks.  Note that this only works against somebody
2051	 * doing IP spoofing from a remote machine; any machine on the local
2052	 * network can still see outgoing packets and catch the random
2053	 * cookie.  This only affects rhosts authentication, and this is one
2054	 * of the reasons why it is inherently insecure.
2055	 */
2056	arc4random_buf(cookie, sizeof(cookie));
2057
2058	/*
2059	 * Send our public key.  We include in the packet 64 bits of random
2060	 * data that must be matched in the reply in order to prevent IP
2061	 * spoofing.
2062	 */
2063	packet_start(SSH_SMSG_PUBLIC_KEY);
2064	for (i = 0; i < 8; i++)
2065		packet_put_char(cookie[i]);
2066
2067	/* Store our public server RSA key. */
2068	packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
2069	packet_put_bignum(sensitive_data.server_key->rsa->e);
2070	packet_put_bignum(sensitive_data.server_key->rsa->n);
2071
2072	/* Store our public host RSA key. */
2073	packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2074	packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
2075	packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
2076
2077	/* Put protocol flags. */
2078	packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
2079
2080	/* Declare which ciphers we support. */
2081	packet_put_int(cipher_mask_ssh1(0));
2082
2083	/* Declare supported authentication types. */
2084	auth_mask = 0;
2085	if (options.rhosts_rsa_authentication)
2086		auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
2087	if (options.rsa_authentication)
2088		auth_mask |= 1 << SSH_AUTH_RSA;
2089	if (options.challenge_response_authentication == 1)
2090		auth_mask |= 1 << SSH_AUTH_TIS;
2091	if (options.password_authentication)
2092		auth_mask |= 1 << SSH_AUTH_PASSWORD;
2093	packet_put_int(auth_mask);
2094
2095	/* Send the packet and wait for it to be sent. */
2096	packet_send();
2097	packet_write_wait();
2098
2099	debug("Sent %d bit server key and %d bit host key.",
2100	    BN_num_bits(sensitive_data.server_key->rsa->n),
2101	    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2102
2103	/* Read clients reply (cipher type and session key). */
2104	packet_read_expect(SSH_CMSG_SESSION_KEY);
2105
2106	/* Get cipher type and check whether we accept this. */
2107	cipher_type = packet_get_char();
2108
2109	if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
2110		packet_disconnect("Warning: client selects unsupported cipher.");
2111
2112	/* Get check bytes from the packet.  These must match those we
2113	   sent earlier with the public key packet. */
2114	for (i = 0; i < 8; i++)
2115		if (cookie[i] != packet_get_char())
2116			packet_disconnect("IP Spoofing check bytes do not match.");
2117
2118	debug("Encryption type: %.200s", cipher_name(cipher_type));
2119
2120	/* Get the encrypted integer. */
2121	if ((session_key_int = BN_new()) == NULL)
2122		fatal("do_ssh1_kex: BN_new failed");
2123	packet_get_bignum(session_key_int);
2124
2125	protocol_flags = packet_get_int();
2126	packet_set_protocol_flags(protocol_flags);
2127	packet_check_eom();
2128
2129	/* Decrypt session_key_int using host/server keys */
2130	rsafail = PRIVSEP(ssh1_session_key(session_key_int));
2131
2132	/*
2133	 * Extract session key from the decrypted integer.  The key is in the
2134	 * least significant 256 bits of the integer; the first byte of the
2135	 * key is in the highest bits.
2136	 */
2137	if (!rsafail) {
2138		(void) BN_mask_bits(session_key_int, sizeof(session_key) * 8);
2139		len = BN_num_bytes(session_key_int);
2140		if (len < 0 || (u_int)len > sizeof(session_key)) {
2141			error("do_ssh1_kex: bad session key len from %s: "
2142			    "session_key_int %d > sizeof(session_key) %lu",
2143			    get_remote_ipaddr(), len, (u_long)sizeof(session_key));
2144			rsafail++;
2145		} else {
2146			memset(session_key, 0, sizeof(session_key));
2147			BN_bn2bin(session_key_int,
2148			    session_key + sizeof(session_key) - len);
2149
2150			derive_ssh1_session_id(
2151			    sensitive_data.ssh1_host_key->rsa->n,
2152			    sensitive_data.server_key->rsa->n,
2153			    cookie, session_id);
2154			/*
2155			 * Xor the first 16 bytes of the session key with the
2156			 * session id.
2157			 */
2158			for (i = 0; i < 16; i++)
2159				session_key[i] ^= session_id[i];
2160		}
2161	}
2162	if (rsafail) {
2163		int bytes = BN_num_bytes(session_key_int);
2164		u_char *buf = xmalloc(bytes);
2165		MD5_CTX md;
2166
2167		logit("do_connection: generating a fake encryption key");
2168		BN_bn2bin(session_key_int, buf);
2169		MD5_Init(&md);
2170		MD5_Update(&md, buf, bytes);
2171		MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2172		MD5_Final(session_key, &md);
2173		MD5_Init(&md);
2174		MD5_Update(&md, session_key, 16);
2175		MD5_Update(&md, buf, bytes);
2176		MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2177		MD5_Final(session_key + 16, &md);
2178		memset(buf, 0, bytes);
2179		xfree(buf);
2180		for (i = 0; i < 16; i++)
2181			session_id[i] = session_key[i] ^ session_key[i + 16];
2182	}
2183	/* Destroy the private and public keys. No longer. */
2184	destroy_sensitive_data();
2185
2186	if (use_privsep)
2187		mm_ssh1_session_id(session_id);
2188
2189	/* Destroy the decrypted integer.  It is no longer needed. */
2190	BN_clear_free(session_key_int);
2191
2192	/* Set the session key.  From this on all communications will be encrypted. */
2193	packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
2194
2195	/* Destroy our copy of the session key.  It is no longer needed. */
2196	memset(session_key, 0, sizeof(session_key));
2197
2198	debug("Received session key; encryption turned on.");
2199
2200	/* Send an acknowledgment packet.  Note that this packet is sent encrypted. */
2201	packet_start(SSH_SMSG_SUCCESS);
2202	packet_send();
2203	packet_write_wait();
2204}
2205
2206/*
2207 * SSH2 key exchange: diffie-hellman-group1-sha1
2208 */
2209static void
2210do_ssh2_kex(void)
2211{
2212	Kex *kex;
2213
2214	if (options.ciphers != NULL) {
2215		myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2216		myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
2217	}
2218	myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2219	    compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
2220	myproposal[PROPOSAL_ENC_ALGS_STOC] =
2221	    compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
2222
2223	if (options.macs != NULL) {
2224		myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2225		myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2226	}
2227	if (options.compression == COMP_NONE) {
2228		myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2229		myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2230	} else if (options.compression == COMP_DELAYED) {
2231		myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2232		myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com";
2233	}
2234
2235	myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
2236
2237	/* start key exchange */
2238	kex = kex_setup(myproposal);
2239	kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2240	kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
2241	kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2242	kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2243	kex->server = 1;
2244	kex->client_version_string=client_version_string;
2245	kex->server_version_string=server_version_string;
2246	kex->load_host_key=&get_hostkey_by_type;
2247	kex->host_key_index=&get_hostkey_index;
2248
2249	xxx_kex = kex;
2250
2251	dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
2252
2253	session_id2 = kex->session_id;
2254	session_id2_len = kex->session_id_len;
2255
2256#ifdef DEBUG_KEXDH
2257	/* send 1st encrypted/maced/compressed message */
2258	packet_start(SSH2_MSG_IGNORE);
2259	packet_put_cstring("markus");
2260	packet_send();
2261	packet_write_wait();
2262#endif
2263	debug("KEX done");
2264}
2265
2266/* server specific fatal cleanup */
2267void
2268cleanup_exit(int i)
2269{
2270	if (the_authctxt)
2271		do_cleanup(the_authctxt);
2272#ifdef SSH_AUDIT_EVENTS
2273	/* done after do_cleanup so it can cancel the PAM auth 'thread' */
2274	if (!use_privsep || mm_is_monitor())
2275		audit_event(SSH_CONNECTION_ABANDON);
2276#endif
2277	_exit(i);
2278}
2279