sshd.c revision 124211
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 * Privilege Separation:
19 *
20 * Copyright (c) 2000, 2001, 2002 Markus Friedl.  All rights reserved.
21 * Copyright (c) 2002 Niels Provos.  All rights reserved.
22 *
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
25 * are met:
26 * 1. Redistributions of source code must retain the above copyright
27 *    notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 *    notice, this list of conditions and the following disclaimer in the
30 *    documentation and/or other materials provided with the distribution.
31 *
32 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
33 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
34 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
35 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
36 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
37 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
41 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42 */
43
44#include "includes.h"
45RCSID("$OpenBSD: sshd.c,v 1.276 2003/08/28 12:54:34 markus Exp $");
46RCSID("$FreeBSD: head/crypto/openssh/sshd.c 124211 2004-01-07 11:16:27Z des $");
47
48#include <openssl/dh.h>
49#include <openssl/bn.h>
50#include <openssl/md5.h>
51#include <openssl/rand.h>
52#ifdef HAVE_SECUREWARE
53#include <sys/security.h>
54#include <prot.h>
55#endif
56
57#ifdef __FreeBSD__
58#include <resolv.h>
59#endif
60
61#include "ssh.h"
62#include "ssh1.h"
63#include "ssh2.h"
64#include "xmalloc.h"
65#include "rsa.h"
66#include "sshpty.h"
67#include "packet.h"
68#include "mpaux.h"
69#include "log.h"
70#include "servconf.h"
71#include "uidswap.h"
72#include "compat.h"
73#include "buffer.h"
74#include "cipher.h"
75#include "kex.h"
76#include "key.h"
77#include "dh.h"
78#include "myproposal.h"
79#include "authfile.h"
80#include "pathnames.h"
81#include "atomicio.h"
82#include "canohost.h"
83#include "auth.h"
84#include "misc.h"
85#include "dispatch.h"
86#include "channels.h"
87#include "session.h"
88#include "monitor_mm.h"
89#include "monitor.h"
90#include "monitor_wrap.h"
91#include "monitor_fdpass.h"
92
93#ifdef LIBWRAP
94#include <tcpd.h>
95#include <syslog.h>
96int allow_severity = LOG_INFO;
97int deny_severity = LOG_WARNING;
98#endif /* LIBWRAP */
99
100#ifndef O_NOCTTY
101#define O_NOCTTY	0
102#endif
103
104#ifdef HAVE___PROGNAME
105extern char *__progname;
106#else
107char *__progname;
108#endif
109
110/* Server configuration options. */
111ServerOptions options;
112
113/* Name of the server configuration file. */
114char *config_file_name = _PATH_SERVER_CONFIG_FILE;
115
116/*
117 * Flag indicating whether IPv4 or IPv6.  This can be set on the command line.
118 * Default value is AF_UNSPEC means both IPv4 and IPv6.
119 */
120int IPv4or6 = AF_UNSPEC;
121
122/*
123 * Debug mode flag.  This can be set on the command line.  If debug
124 * mode is enabled, extra debugging output will be sent to the system
125 * log, the daemon will not go to background, and will exit after processing
126 * the first connection.
127 */
128int debug_flag = 0;
129
130/* Flag indicating that the daemon should only test the configuration and keys. */
131int test_flag = 0;
132
133/* Flag indicating that the daemon is being started from inetd. */
134int inetd_flag = 0;
135
136/* Flag indicating that sshd should not detach and become a daemon. */
137int no_daemon_flag = 0;
138
139/* debug goes to stderr unless inetd_flag is set */
140int log_stderr = 0;
141
142/* Saved arguments to main(). */
143char **saved_argv;
144int saved_argc;
145
146/*
147 * The sockets that the server is listening; this is used in the SIGHUP
148 * signal handler.
149 */
150#define	MAX_LISTEN_SOCKS	16
151int listen_socks[MAX_LISTEN_SOCKS];
152int num_listen_socks = 0;
153
154/*
155 * the client's version string, passed by sshd2 in compat mode. if != NULL,
156 * sshd will skip the version-number exchange
157 */
158char *client_version_string = NULL;
159char *server_version_string = NULL;
160
161/* for rekeying XXX fixme */
162Kex *xxx_kex;
163
164/*
165 * Any really sensitive data in the application is contained in this
166 * structure. The idea is that this structure could be locked into memory so
167 * that the pages do not get written into swap.  However, there are some
168 * problems. The private key contains BIGNUMs, and we do not (in principle)
169 * have access to the internals of them, and locking just the structure is
170 * not very useful.  Currently, memory locking is not implemented.
171 */
172struct {
173	Key	*server_key;		/* ephemeral server key */
174	Key	*ssh1_host_key;		/* ssh1 host key */
175	Key	**host_keys;		/* all private host keys */
176	int	have_ssh1_key;
177	int	have_ssh2_key;
178	u_char	ssh1_cookie[SSH_SESSION_KEY_LENGTH];
179} sensitive_data;
180
181/*
182 * Flag indicating whether the RSA server key needs to be regenerated.
183 * Is set in the SIGALRM handler and cleared when the key is regenerated.
184 */
185static volatile sig_atomic_t key_do_regen = 0;
186
187/* This is set to true when a signal is received. */
188static volatile sig_atomic_t received_sighup = 0;
189static volatile sig_atomic_t received_sigterm = 0;
190
191/* session identifier, used by RSA-auth */
192u_char session_id[16];
193
194/* same for ssh2 */
195u_char *session_id2 = NULL;
196u_int session_id2_len = 0;
197
198/* record remote hostname or ip */
199u_int utmp_len = MAXHOSTNAMELEN;
200
201/* options.max_startup sized array of fd ints */
202int *startup_pipes = NULL;
203int startup_pipe;		/* in child */
204
205/* variables used for privilege separation */
206int use_privsep;
207struct monitor *pmonitor;
208
209/* message to be displayed after login */
210Buffer loginmsg;
211
212/* Prototypes for various functions defined later in this file. */
213void destroy_sensitive_data(void);
214void demote_sensitive_data(void);
215
216static void do_ssh1_kex(void);
217static void do_ssh2_kex(void);
218
219/*
220 * Close all listening sockets
221 */
222static void
223close_listen_socks(void)
224{
225	int i;
226
227	for (i = 0; i < num_listen_socks; i++)
228		close(listen_socks[i]);
229	num_listen_socks = -1;
230}
231
232static void
233close_startup_pipes(void)
234{
235	int i;
236
237	if (startup_pipes)
238		for (i = 0; i < options.max_startups; i++)
239			if (startup_pipes[i] != -1)
240				close(startup_pipes[i]);
241}
242
243/*
244 * Signal handler for SIGHUP.  Sshd execs itself when it receives SIGHUP;
245 * the effect is to reread the configuration file (and to regenerate
246 * the server key).
247 */
248static void
249sighup_handler(int sig)
250{
251	int save_errno = errno;
252
253	received_sighup = 1;
254	signal(SIGHUP, sighup_handler);
255	errno = save_errno;
256}
257
258/*
259 * Called from the main program after receiving SIGHUP.
260 * Restarts the server.
261 */
262static void
263sighup_restart(void)
264{
265	logit("Received SIGHUP; restarting.");
266	close_listen_socks();
267	close_startup_pipes();
268	execv(saved_argv[0], saved_argv);
269	logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
270	    strerror(errno));
271	exit(1);
272}
273
274/*
275 * Generic signal handler for terminating signals in the master daemon.
276 */
277static void
278sigterm_handler(int sig)
279{
280	received_sigterm = sig;
281}
282
283/*
284 * SIGCHLD handler.  This is called whenever a child dies.  This will then
285 * reap any zombies left by exited children.
286 */
287static void
288main_sigchld_handler(int sig)
289{
290	int save_errno = errno;
291	pid_t pid;
292	int status;
293
294	while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
295	    (pid < 0 && errno == EINTR))
296		;
297
298	signal(SIGCHLD, main_sigchld_handler);
299	errno = save_errno;
300}
301
302/*
303 * Signal handler for the alarm after the login grace period has expired.
304 */
305static void
306grace_alarm_handler(int sig)
307{
308	/* XXX no idea how fix this signal handler */
309
310	/* Log error and exit. */
311	fatal("Timeout before authentication for %s", get_remote_ipaddr());
312}
313
314/*
315 * Signal handler for the key regeneration alarm.  Note that this
316 * alarm only occurs in the daemon waiting for connections, and it does not
317 * do anything with the private key or random state before forking.
318 * Thus there should be no concurrency control/asynchronous execution
319 * problems.
320 */
321static void
322generate_ephemeral_server_key(void)
323{
324	u_int32_t rnd = 0;
325	int i;
326
327	verbose("Generating %s%d bit RSA key.",
328	    sensitive_data.server_key ? "new " : "", options.server_key_bits);
329	if (sensitive_data.server_key != NULL)
330		key_free(sensitive_data.server_key);
331	sensitive_data.server_key = key_generate(KEY_RSA1,
332	    options.server_key_bits);
333	verbose("RSA key generation complete.");
334
335	for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
336		if (i % 4 == 0)
337			rnd = arc4random();
338		sensitive_data.ssh1_cookie[i] = rnd & 0xff;
339		rnd >>= 8;
340	}
341	arc4random_stir();
342}
343
344static void
345key_regeneration_alarm(int sig)
346{
347	int save_errno = errno;
348
349	signal(SIGALRM, SIG_DFL);
350	errno = save_errno;
351	key_do_regen = 1;
352}
353
354static void
355sshd_exchange_identification(int sock_in, int sock_out)
356{
357	int i, mismatch;
358	int remote_major, remote_minor;
359	int major, minor;
360	char *s;
361	char buf[256];			/* Must not be larger than remote_version. */
362	char remote_version[256];	/* Must be at least as big as buf. */
363
364	if ((options.protocol & SSH_PROTO_1) &&
365	    (options.protocol & SSH_PROTO_2)) {
366		major = PROTOCOL_MAJOR_1;
367		minor = 99;
368	} else if (options.protocol & SSH_PROTO_2) {
369		major = PROTOCOL_MAJOR_2;
370		minor = PROTOCOL_MINOR_2;
371	} else {
372		major = PROTOCOL_MAJOR_1;
373		minor = PROTOCOL_MINOR_1;
374	}
375	snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", major, minor, SSH_VERSION);
376	server_version_string = xstrdup(buf);
377
378	/* Send our protocol version identification. */
379	if (atomicio(vwrite, sock_out, server_version_string,
380	    strlen(server_version_string))
381	    != strlen(server_version_string)) {
382		logit("Could not write ident string to %s", get_remote_ipaddr());
383		fatal_cleanup();
384	}
385
386	/* Read other sides version identification. */
387	memset(buf, 0, sizeof(buf));
388	for (i = 0; i < sizeof(buf) - 1; i++) {
389		if (atomicio(read, sock_in, &buf[i], 1) != 1) {
390			logit("Did not receive identification string from %s",
391			    get_remote_ipaddr());
392			fatal_cleanup();
393		}
394		if (buf[i] == '\r') {
395			buf[i] = 0;
396			/* Kludge for F-Secure Macintosh < 1.0.2 */
397			if (i == 12 &&
398			    strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
399				break;
400			continue;
401		}
402		if (buf[i] == '\n') {
403			buf[i] = 0;
404			break;
405		}
406	}
407	buf[sizeof(buf) - 1] = 0;
408	client_version_string = xstrdup(buf);
409
410	/*
411	 * Check that the versions match.  In future this might accept
412	 * several versions and set appropriate flags to handle them.
413	 */
414	if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
415	    &remote_major, &remote_minor, remote_version) != 3) {
416		s = "Protocol mismatch.\n";
417		(void) atomicio(vwrite, sock_out, s, strlen(s));
418		close(sock_in);
419		close(sock_out);
420		logit("Bad protocol version identification '%.100s' from %s",
421		    client_version_string, get_remote_ipaddr());
422		fatal_cleanup();
423	}
424	debug("Client protocol version %d.%d; client software version %.100s",
425	    remote_major, remote_minor, remote_version);
426
427	compat_datafellows(remote_version);
428
429	if (datafellows & SSH_BUG_PROBE) {
430		logit("probed from %s with %s.  Don't panic.",
431		    get_remote_ipaddr(), client_version_string);
432		fatal_cleanup();
433	}
434
435	if (datafellows & SSH_BUG_SCANNER) {
436		logit("scanned from %s with %s.  Don't panic.",
437		    get_remote_ipaddr(), client_version_string);
438		fatal_cleanup();
439	}
440
441	mismatch = 0;
442	switch (remote_major) {
443	case 1:
444		if (remote_minor == 99) {
445			if (options.protocol & SSH_PROTO_2)
446				enable_compat20();
447			else
448				mismatch = 1;
449			break;
450		}
451		if (!(options.protocol & SSH_PROTO_1)) {
452			mismatch = 1;
453			break;
454		}
455		if (remote_minor < 3) {
456			packet_disconnect("Your ssh version is too old and "
457			    "is no longer supported.  Please install a newer version.");
458		} else if (remote_minor == 3) {
459			/* note that this disables agent-forwarding */
460			enable_compat13();
461		}
462		break;
463	case 2:
464		if (options.protocol & SSH_PROTO_2) {
465			enable_compat20();
466			break;
467		}
468		/* FALLTHROUGH */
469	default:
470		mismatch = 1;
471		break;
472	}
473	chop(server_version_string);
474	debug("Local version string %.200s", server_version_string);
475
476	if (mismatch) {
477		s = "Protocol major versions differ.\n";
478		(void) atomicio(vwrite, sock_out, s, strlen(s));
479		close(sock_in);
480		close(sock_out);
481		logit("Protocol major versions differ for %s: %.200s vs. %.200s",
482		    get_remote_ipaddr(),
483		    server_version_string, client_version_string);
484		fatal_cleanup();
485	}
486}
487
488/* Destroy the host and server keys.  They will no longer be needed. */
489void
490destroy_sensitive_data(void)
491{
492	int i;
493
494	if (sensitive_data.server_key) {
495		key_free(sensitive_data.server_key);
496		sensitive_data.server_key = NULL;
497	}
498	for (i = 0; i < options.num_host_key_files; i++) {
499		if (sensitive_data.host_keys[i]) {
500			key_free(sensitive_data.host_keys[i]);
501			sensitive_data.host_keys[i] = NULL;
502		}
503	}
504	sensitive_data.ssh1_host_key = NULL;
505	memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
506}
507
508/* Demote private to public keys for network child */
509void
510demote_sensitive_data(void)
511{
512	Key *tmp;
513	int i;
514
515	if (sensitive_data.server_key) {
516		tmp = key_demote(sensitive_data.server_key);
517		key_free(sensitive_data.server_key);
518		sensitive_data.server_key = tmp;
519	}
520
521	for (i = 0; i < options.num_host_key_files; i++) {
522		if (sensitive_data.host_keys[i]) {
523			tmp = key_demote(sensitive_data.host_keys[i]);
524			key_free(sensitive_data.host_keys[i]);
525			sensitive_data.host_keys[i] = tmp;
526			if (tmp->type == KEY_RSA1)
527				sensitive_data.ssh1_host_key = tmp;
528		}
529	}
530
531	/* We do not clear ssh1_host key and cookie.  XXX - Okay Niels? */
532}
533
534static void
535privsep_preauth_child(void)
536{
537	u_int32_t rnd[256];
538	gid_t gidset[1];
539	struct passwd *pw;
540	int i;
541
542	/* Enable challenge-response authentication for privilege separation */
543	privsep_challenge_enable();
544
545	for (i = 0; i < 256; i++)
546		rnd[i] = arc4random();
547	RAND_seed(rnd, sizeof(rnd));
548
549	/* Demote the private keys to public keys. */
550	demote_sensitive_data();
551
552	if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL)
553		fatal("Privilege separation user %s does not exist",
554		    SSH_PRIVSEP_USER);
555	memset(pw->pw_passwd, 0, strlen(pw->pw_passwd));
556	endpwent();
557
558	/* Change our root directory */
559	if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
560		fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
561		    strerror(errno));
562	if (chdir("/") == -1)
563		fatal("chdir(\"/\"): %s", strerror(errno));
564
565	/* Drop our privileges */
566	debug3("privsep user:group %u:%u", (u_int)pw->pw_uid,
567	    (u_int)pw->pw_gid);
568#if 0
569	/* XXX not ready, to heavy after chroot */
570	do_setusercontext(pw);
571#else
572	gidset[0] = pw->pw_gid;
573	if (setgroups(1, gidset) < 0)
574		fatal("setgroups: %.100s", strerror(errno));
575	permanently_set_uid(pw);
576#endif
577}
578
579static Authctxt *
580privsep_preauth(void)
581{
582	Authctxt *authctxt = NULL;
583	int status;
584	pid_t pid;
585
586	/* Set up unprivileged child process to deal with network data */
587	pmonitor = monitor_init();
588	/* Store a pointer to the kex for later rekeying */
589	pmonitor->m_pkex = &xxx_kex;
590
591	pid = fork();
592	if (pid == -1) {
593		fatal("fork of unprivileged child failed");
594	} else if (pid != 0) {
595		fatal_remove_cleanup((void (*) (void *)) packet_close, NULL);
596
597		debug2("Network child is on pid %ld", (long)pid);
598
599		close(pmonitor->m_recvfd);
600		authctxt = monitor_child_preauth(pmonitor);
601		close(pmonitor->m_sendfd);
602
603		/* Sync memory */
604		monitor_sync(pmonitor);
605
606		/* Wait for the child's exit status */
607		while (waitpid(pid, &status, 0) < 0)
608			if (errno != EINTR)
609				break;
610
611		/* Reinstall, since the child has finished */
612		fatal_add_cleanup((void (*) (void *)) packet_close, NULL);
613
614		return (authctxt);
615	} else {
616		/* child */
617
618		close(pmonitor->m_sendfd);
619
620		/* Demote the child */
621		if (getuid() == 0 || geteuid() == 0)
622			privsep_preauth_child();
623		setproctitle("%s", "[net]");
624	}
625	return (NULL);
626}
627
628static void
629privsep_postauth(Authctxt *authctxt)
630{
631	extern Authctxt *x_authctxt;
632
633	/* XXX - Remote port forwarding */
634	x_authctxt = authctxt;
635
636#ifdef DISABLE_FD_PASSING
637	if (1) {
638#else
639	if (authctxt->pw->pw_uid == 0 || options.use_login) {
640#endif
641		/* File descriptor passing is broken or root login */
642		monitor_apply_keystate(pmonitor);
643		use_privsep = 0;
644		return;
645	}
646
647	/* Authentication complete */
648	alarm(0);
649	if (startup_pipe != -1) {
650		close(startup_pipe);
651		startup_pipe = -1;
652	}
653
654	/* New socket pair */
655	monitor_reinit(pmonitor);
656
657	pmonitor->m_pid = fork();
658	if (pmonitor->m_pid == -1)
659		fatal("fork of unprivileged child failed");
660	else if (pmonitor->m_pid != 0) {
661		fatal_remove_cleanup((void (*) (void *)) packet_close, NULL);
662
663		debug2("User child is on pid %ld", (long)pmonitor->m_pid);
664		close(pmonitor->m_recvfd);
665		monitor_child_postauth(pmonitor);
666
667		/* NEVERREACHED */
668		exit(0);
669	}
670
671	close(pmonitor->m_sendfd);
672
673	/* Demote the private keys to public keys. */
674	demote_sensitive_data();
675
676	/* Drop privileges */
677	do_setusercontext(authctxt->pw);
678
679	/* It is safe now to apply the key state */
680	monitor_apply_keystate(pmonitor);
681}
682
683static char *
684list_hostkey_types(void)
685{
686	Buffer b;
687	char *p;
688	int i;
689
690	buffer_init(&b);
691	for (i = 0; i < options.num_host_key_files; i++) {
692		Key *key = sensitive_data.host_keys[i];
693		if (key == NULL)
694			continue;
695		switch (key->type) {
696		case KEY_RSA:
697		case KEY_DSA:
698			if (buffer_len(&b) > 0)
699				buffer_append(&b, ",", 1);
700			p = key_ssh_name(key);
701			buffer_append(&b, p, strlen(p));
702			break;
703		}
704	}
705	buffer_append(&b, "\0", 1);
706	p = xstrdup(buffer_ptr(&b));
707	buffer_free(&b);
708	debug("list_hostkey_types: %s", p);
709	return p;
710}
711
712Key *
713get_hostkey_by_type(int type)
714{
715	int i;
716
717	for (i = 0; i < options.num_host_key_files; i++) {
718		Key *key = sensitive_data.host_keys[i];
719		if (key != NULL && key->type == type)
720			return key;
721	}
722	return NULL;
723}
724
725Key *
726get_hostkey_by_index(int ind)
727{
728	if (ind < 0 || ind >= options.num_host_key_files)
729		return (NULL);
730	return (sensitive_data.host_keys[ind]);
731}
732
733int
734get_hostkey_index(Key *key)
735{
736	int i;
737
738	for (i = 0; i < options.num_host_key_files; i++) {
739		if (key == sensitive_data.host_keys[i])
740			return (i);
741	}
742	return (-1);
743}
744
745/*
746 * returns 1 if connection should be dropped, 0 otherwise.
747 * dropping starts at connection #max_startups_begin with a probability
748 * of (max_startups_rate/100). the probability increases linearly until
749 * all connections are dropped for startups > max_startups
750 */
751static int
752drop_connection(int startups)
753{
754	double p, r;
755
756	if (startups < options.max_startups_begin)
757		return 0;
758	if (startups >= options.max_startups)
759		return 1;
760	if (options.max_startups_rate == 100)
761		return 1;
762
763	p  = 100 - options.max_startups_rate;
764	p *= startups - options.max_startups_begin;
765	p /= (double) (options.max_startups - options.max_startups_begin);
766	p += options.max_startups_rate;
767	p /= 100.0;
768	r = arc4random() / (double) UINT_MAX;
769
770	debug("drop_connection: p %g, r %g", p, r);
771	return (r < p) ? 1 : 0;
772}
773
774static void
775usage(void)
776{
777	fprintf(stderr, "sshd version %s\n", SSH_VERSION);
778	fprintf(stderr, "Usage: %s [options]\n", __progname);
779	fprintf(stderr, "Options:\n");
780	fprintf(stderr, "  -f file    Configuration file (default %s)\n", _PATH_SERVER_CONFIG_FILE);
781	fprintf(stderr, "  -d         Debugging mode (multiple -d means more debugging)\n");
782	fprintf(stderr, "  -i         Started from inetd\n");
783	fprintf(stderr, "  -D         Do not fork into daemon mode\n");
784	fprintf(stderr, "  -t         Only test configuration file and keys\n");
785	fprintf(stderr, "  -q         Quiet (no logging)\n");
786	fprintf(stderr, "  -p port    Listen on the specified port (default: 22)\n");
787	fprintf(stderr, "  -k seconds Regenerate server key every this many seconds (default: 3600)\n");
788	fprintf(stderr, "  -g seconds Grace period for authentication (default: 600)\n");
789	fprintf(stderr, "  -b bits    Size of server RSA key (default: 768 bits)\n");
790	fprintf(stderr, "  -h file    File from which to read host key (default: %s)\n",
791	    _PATH_HOST_KEY_FILE);
792	fprintf(stderr, "  -u len     Maximum hostname length for utmp recording\n");
793	fprintf(stderr, "  -4         Use IPv4 only\n");
794	fprintf(stderr, "  -6         Use IPv6 only\n");
795	fprintf(stderr, "  -o option  Process the option as if it was read from a configuration file.\n");
796	exit(1);
797}
798
799/*
800 * Main program for the daemon.
801 */
802int
803main(int ac, char **av)
804{
805	extern char *optarg;
806	extern int optind;
807	int opt, sock_in = 0, sock_out = 0, newsock, j, i, fdsetsz, on = 1;
808	pid_t pid;
809	socklen_t fromlen;
810	fd_set *fdset;
811	struct sockaddr_storage from;
812	const char *remote_ip;
813	int remote_port;
814	FILE *f;
815	struct addrinfo *ai;
816	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
817	int listen_sock, maxfd;
818	int startup_p[2];
819	int startups = 0;
820	Authctxt *authctxt;
821	Key *key;
822	int ret, key_used = 0;
823
824#ifdef HAVE_SECUREWARE
825	(void)set_auth_parameters(ac, av);
826#endif
827	__progname = ssh_get_progname(av[0]);
828	init_rng();
829
830	/* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
831	saved_argc = ac;
832	saved_argv = xmalloc(sizeof(*saved_argv) * (ac + 1));
833	for (i = 0; i < ac; i++)
834		saved_argv[i] = xstrdup(av[i]);
835	saved_argv[i] = NULL;
836
837#ifndef HAVE_SETPROCTITLE
838	/* Prepare for later setproctitle emulation */
839	compat_init_setproctitle(ac, av);
840	av = saved_argv;
841#endif
842
843	/* Initialize configuration options to their default values. */
844	initialize_server_options(&options);
845
846	/* Parse command-line arguments. */
847	while ((opt = getopt(ac, av, "f:p:b:k:h:g:u:o:dDeiqtQ46")) != -1) {
848		switch (opt) {
849		case '4':
850			IPv4or6 = AF_INET;
851			break;
852		case '6':
853			IPv4or6 = AF_INET6;
854			break;
855		case 'f':
856			config_file_name = optarg;
857			break;
858		case 'd':
859			if (debug_flag == 0) {
860				debug_flag = 1;
861				options.log_level = SYSLOG_LEVEL_DEBUG1;
862			} else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
863				options.log_level++;
864			break;
865		case 'D':
866			no_daemon_flag = 1;
867			break;
868		case 'e':
869			log_stderr = 1;
870			break;
871		case 'i':
872			inetd_flag = 1;
873			break;
874		case 'Q':
875			/* ignored */
876			break;
877		case 'q':
878			options.log_level = SYSLOG_LEVEL_QUIET;
879			break;
880		case 'b':
881			options.server_key_bits = atoi(optarg);
882			break;
883		case 'p':
884			options.ports_from_cmdline = 1;
885			if (options.num_ports >= MAX_PORTS) {
886				fprintf(stderr, "too many ports.\n");
887				exit(1);
888			}
889			options.ports[options.num_ports++] = a2port(optarg);
890			if (options.ports[options.num_ports-1] == 0) {
891				fprintf(stderr, "Bad port number.\n");
892				exit(1);
893			}
894			break;
895		case 'g':
896			if ((options.login_grace_time = convtime(optarg)) == -1) {
897				fprintf(stderr, "Invalid login grace time.\n");
898				exit(1);
899			}
900			break;
901		case 'k':
902			if ((options.key_regeneration_time = convtime(optarg)) == -1) {
903				fprintf(stderr, "Invalid key regeneration interval.\n");
904				exit(1);
905			}
906			break;
907		case 'h':
908			if (options.num_host_key_files >= MAX_HOSTKEYS) {
909				fprintf(stderr, "too many host keys.\n");
910				exit(1);
911			}
912			options.host_key_files[options.num_host_key_files++] = optarg;
913			break;
914		case 't':
915			test_flag = 1;
916			break;
917		case 'u':
918			utmp_len = atoi(optarg);
919			if (utmp_len > MAXHOSTNAMELEN) {
920				fprintf(stderr, "Invalid utmp length.\n");
921				exit(1);
922			}
923			break;
924		case 'o':
925			if (process_server_config_line(&options, optarg,
926			    "command-line", 0) != 0)
927				exit(1);
928			break;
929		case '?':
930		default:
931			usage();
932			break;
933		}
934	}
935	SSLeay_add_all_algorithms();
936	channel_set_af(IPv4or6);
937
938	/*
939	 * Force logging to stderr until we have loaded the private host
940	 * key (unless started from inetd)
941	 */
942	log_init(__progname,
943	    options.log_level == SYSLOG_LEVEL_NOT_SET ?
944	    SYSLOG_LEVEL_INFO : options.log_level,
945	    options.log_facility == SYSLOG_FACILITY_NOT_SET ?
946	    SYSLOG_FACILITY_AUTH : options.log_facility,
947	    log_stderr || !inetd_flag);
948
949#ifdef _UNICOS
950	/* Cray can define user privs drop all prives now!
951	 * Not needed on PRIV_SU systems!
952	 */
953	drop_cray_privs();
954#endif
955
956	seed_rng();
957
958	/* Read server configuration options from the configuration file. */
959	read_server_config(&options, config_file_name);
960
961	/* Fill in default values for those options not explicitly set. */
962	fill_default_server_options(&options);
963
964	/* Check that there are no remaining arguments. */
965	if (optind < ac) {
966		fprintf(stderr, "Extra argument %s.\n", av[optind]);
967		exit(1);
968	}
969
970	debug("sshd version %.100s", SSH_VERSION);
971
972	/* load private host keys */
973	sensitive_data.host_keys = xmalloc(options.num_host_key_files *
974	    sizeof(Key *));
975	for (i = 0; i < options.num_host_key_files; i++)
976		sensitive_data.host_keys[i] = NULL;
977	sensitive_data.server_key = NULL;
978	sensitive_data.ssh1_host_key = NULL;
979	sensitive_data.have_ssh1_key = 0;
980	sensitive_data.have_ssh2_key = 0;
981
982	for (i = 0; i < options.num_host_key_files; i++) {
983		key = key_load_private(options.host_key_files[i], "", NULL);
984		sensitive_data.host_keys[i] = key;
985		if (key == NULL) {
986			error("Could not load host key: %s",
987			    options.host_key_files[i]);
988			sensitive_data.host_keys[i] = NULL;
989			continue;
990		}
991		switch (key->type) {
992		case KEY_RSA1:
993			sensitive_data.ssh1_host_key = key;
994			sensitive_data.have_ssh1_key = 1;
995			break;
996		case KEY_RSA:
997		case KEY_DSA:
998			sensitive_data.have_ssh2_key = 1;
999			break;
1000		}
1001		debug("private host key: #%d type %d %s", i, key->type,
1002		    key_type(key));
1003	}
1004	if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1005		logit("Disabling protocol version 1. Could not load host key");
1006		options.protocol &= ~SSH_PROTO_1;
1007	}
1008	if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1009		logit("Disabling protocol version 2. Could not load host key");
1010		options.protocol &= ~SSH_PROTO_2;
1011	}
1012	if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1013		logit("sshd: no hostkeys available -- exiting.");
1014		exit(1);
1015	}
1016
1017	/* Check certain values for sanity. */
1018	if (options.protocol & SSH_PROTO_1) {
1019		if (options.server_key_bits < 512 ||
1020		    options.server_key_bits > 32768) {
1021			fprintf(stderr, "Bad server key size.\n");
1022			exit(1);
1023		}
1024		/*
1025		 * Check that server and host key lengths differ sufficiently. This
1026		 * is necessary to make double encryption work with rsaref. Oh, I
1027		 * hate software patents. I dont know if this can go? Niels
1028		 */
1029		if (options.server_key_bits >
1030		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
1031		    SSH_KEY_BITS_RESERVED && options.server_key_bits <
1032		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1033		    SSH_KEY_BITS_RESERVED) {
1034			options.server_key_bits =
1035			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1036			    SSH_KEY_BITS_RESERVED;
1037			debug("Forcing server key to %d bits to make it differ from host key.",
1038			    options.server_key_bits);
1039		}
1040	}
1041
1042	if (use_privsep) {
1043		struct passwd *pw;
1044		struct stat st;
1045
1046		if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL)
1047			fatal("Privilege separation user %s does not exist",
1048			    SSH_PRIVSEP_USER);
1049		if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1050		    (S_ISDIR(st.st_mode) == 0))
1051			fatal("Missing privilege separation directory: %s",
1052			    _PATH_PRIVSEP_CHROOT_DIR);
1053
1054#ifdef HAVE_CYGWIN
1055		if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1056		    (st.st_uid != getuid () ||
1057		    (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1058#else
1059		if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1060#endif
1061			fatal("%s must be owned by root and not group or "
1062			    "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1063	}
1064
1065	/* Configuration looks good, so exit if in test mode. */
1066	if (test_flag)
1067		exit(0);
1068
1069	/*
1070	 * Clear out any supplemental groups we may have inherited.  This
1071	 * prevents inadvertent creation of files with bad modes (in the
1072	 * portable version at least, it's certainly possible for PAM
1073	 * to create a file, and we can't control the code in every
1074	 * module which might be used).
1075	 */
1076	if (setgroups(0, NULL) < 0)
1077		debug("setgroups() failed: %.200s", strerror(errno));
1078
1079	/* Initialize the log (it is reinitialized below in case we forked). */
1080	if (debug_flag && !inetd_flag)
1081		log_stderr = 1;
1082	log_init(__progname, options.log_level, options.log_facility, log_stderr);
1083
1084	/*
1085	 * If not in debugging mode, and not started from inetd, disconnect
1086	 * from the controlling terminal, and fork.  The original process
1087	 * exits.
1088	 */
1089	if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1090#ifdef TIOCNOTTY
1091		int fd;
1092#endif /* TIOCNOTTY */
1093		if (daemon(0, 0) < 0)
1094			fatal("daemon() failed: %.200s", strerror(errno));
1095
1096		/* Disconnect from the controlling tty. */
1097#ifdef TIOCNOTTY
1098		fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1099		if (fd >= 0) {
1100			(void) ioctl(fd, TIOCNOTTY, NULL);
1101			close(fd);
1102		}
1103#endif /* TIOCNOTTY */
1104	}
1105	/* Reinitialize the log (because of the fork above). */
1106	log_init(__progname, options.log_level, options.log_facility, log_stderr);
1107
1108	/* Initialize the random number generator. */
1109	arc4random_stir();
1110
1111	/* Chdir to the root directory so that the current disk can be
1112	   unmounted if desired. */
1113	chdir("/");
1114
1115	/* ignore SIGPIPE */
1116	signal(SIGPIPE, SIG_IGN);
1117
1118	/* Start listening for a socket, unless started from inetd. */
1119	if (inetd_flag) {
1120		int s1;
1121		s1 = dup(0);	/* Make sure descriptors 0, 1, and 2 are in use. */
1122		dup(s1);
1123		sock_in = dup(0);
1124		sock_out = dup(1);
1125		startup_pipe = -1;
1126		/*
1127		 * We intentionally do not close the descriptors 0, 1, and 2
1128		 * as our code for setting the descriptors won\'t work if
1129		 * ttyfd happens to be one of those.
1130		 */
1131		debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
1132		if (options.protocol & SSH_PROTO_1)
1133			generate_ephemeral_server_key();
1134	} else {
1135		for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
1136			if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1137				continue;
1138			if (num_listen_socks >= MAX_LISTEN_SOCKS)
1139				fatal("Too many listen sockets. "
1140				    "Enlarge MAX_LISTEN_SOCKS");
1141			if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
1142			    ntop, sizeof(ntop), strport, sizeof(strport),
1143			    NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1144				error("getnameinfo failed");
1145				continue;
1146			}
1147			/* Create socket for listening. */
1148			listen_sock = socket(ai->ai_family, ai->ai_socktype,
1149			    ai->ai_protocol);
1150			if (listen_sock < 0) {
1151				/* kernel may not support ipv6 */
1152				verbose("socket: %.100s", strerror(errno));
1153				continue;
1154			}
1155			if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) {
1156				error("listen_sock O_NONBLOCK: %s", strerror(errno));
1157				close(listen_sock);
1158				continue;
1159			}
1160			/*
1161			 * Set socket options.
1162			 * Allow local port reuse in TIME_WAIT.
1163			 */
1164			if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
1165			    &on, sizeof(on)) == -1)
1166				error("setsockopt SO_REUSEADDR: %s", strerror(errno));
1167
1168			debug("Bind to port %s on %s.", strport, ntop);
1169
1170			/* Bind the socket to the desired port. */
1171			if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1172				if (!ai->ai_next)
1173				    error("Bind to port %s on %s failed: %.200s.",
1174					    strport, ntop, strerror(errno));
1175				close(listen_sock);
1176				continue;
1177			}
1178			listen_socks[num_listen_socks] = listen_sock;
1179			num_listen_socks++;
1180
1181			/* Start listening on the port. */
1182			logit("Server listening on %s port %s.", ntop, strport);
1183			if (listen(listen_sock, 5) < 0)
1184				fatal("listen: %.100s", strerror(errno));
1185
1186		}
1187		freeaddrinfo(options.listen_addrs);
1188
1189		if (!num_listen_socks)
1190			fatal("Cannot bind any address.");
1191
1192		if (options.protocol & SSH_PROTO_1)
1193			generate_ephemeral_server_key();
1194
1195		/*
1196		 * Arrange to restart on SIGHUP.  The handler needs
1197		 * listen_sock.
1198		 */
1199		signal(SIGHUP, sighup_handler);
1200
1201		signal(SIGTERM, sigterm_handler);
1202		signal(SIGQUIT, sigterm_handler);
1203
1204		/* Arrange SIGCHLD to be caught. */
1205		signal(SIGCHLD, main_sigchld_handler);
1206
1207		/* Write out the pid file after the sigterm handler is setup */
1208		if (!debug_flag) {
1209			/*
1210			 * Record our pid in /var/run/sshd.pid to make it
1211			 * easier to kill the correct sshd.  We don't want to
1212			 * do this before the bind above because the bind will
1213			 * fail if there already is a daemon, and this will
1214			 * overwrite any old pid in the file.
1215			 */
1216			f = fopen(options.pid_file, "wb");
1217			if (f == NULL) {
1218				error("Couldn't create pid file \"%s\": %s",
1219				    options.pid_file, strerror(errno));
1220			} else {
1221				fprintf(f, "%ld\n", (long) getpid());
1222				fclose(f);
1223			}
1224		}
1225
1226		/* setup fd set for listen */
1227		fdset = NULL;
1228		maxfd = 0;
1229		for (i = 0; i < num_listen_socks; i++)
1230			if (listen_socks[i] > maxfd)
1231				maxfd = listen_socks[i];
1232		/* pipes connected to unauthenticated childs */
1233		startup_pipes = xmalloc(options.max_startups * sizeof(int));
1234		for (i = 0; i < options.max_startups; i++)
1235			startup_pipes[i] = -1;
1236
1237		/*
1238		 * Stay listening for connections until the system crashes or
1239		 * the daemon is killed with a signal.
1240		 */
1241		for (;;) {
1242			if (received_sighup)
1243				sighup_restart();
1244			if (fdset != NULL)
1245				xfree(fdset);
1246			fdsetsz = howmany(maxfd+1, NFDBITS) * sizeof(fd_mask);
1247			fdset = (fd_set *)xmalloc(fdsetsz);
1248			memset(fdset, 0, fdsetsz);
1249
1250			for (i = 0; i < num_listen_socks; i++)
1251				FD_SET(listen_socks[i], fdset);
1252			for (i = 0; i < options.max_startups; i++)
1253				if (startup_pipes[i] != -1)
1254					FD_SET(startup_pipes[i], fdset);
1255
1256			/* Wait in select until there is a connection. */
1257			ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1258			if (ret < 0 && errno != EINTR)
1259				error("select: %.100s", strerror(errno));
1260			if (received_sigterm) {
1261				logit("Received signal %d; terminating.",
1262				    (int) received_sigterm);
1263				close_listen_socks();
1264				unlink(options.pid_file);
1265				exit(255);
1266			}
1267			if (key_used && key_do_regen) {
1268				generate_ephemeral_server_key();
1269				key_used = 0;
1270				key_do_regen = 0;
1271			}
1272			if (ret < 0)
1273				continue;
1274
1275			for (i = 0; i < options.max_startups; i++)
1276				if (startup_pipes[i] != -1 &&
1277				    FD_ISSET(startup_pipes[i], fdset)) {
1278					/*
1279					 * the read end of the pipe is ready
1280					 * if the child has closed the pipe
1281					 * after successful authentication
1282					 * or if the child has died
1283					 */
1284					close(startup_pipes[i]);
1285					startup_pipes[i] = -1;
1286					startups--;
1287				}
1288			for (i = 0; i < num_listen_socks; i++) {
1289				if (!FD_ISSET(listen_socks[i], fdset))
1290					continue;
1291				fromlen = sizeof(from);
1292				newsock = accept(listen_socks[i], (struct sockaddr *)&from,
1293				    &fromlen);
1294				if (newsock < 0) {
1295					if (errno != EINTR && errno != EWOULDBLOCK)
1296						error("accept: %.100s", strerror(errno));
1297					continue;
1298				}
1299				if (fcntl(newsock, F_SETFL, 0) < 0) {
1300					error("newsock del O_NONBLOCK: %s", strerror(errno));
1301					close(newsock);
1302					continue;
1303				}
1304				if (drop_connection(startups) == 1) {
1305					debug("drop connection #%d", startups);
1306					close(newsock);
1307					continue;
1308				}
1309				if (pipe(startup_p) == -1) {
1310					close(newsock);
1311					continue;
1312				}
1313
1314				for (j = 0; j < options.max_startups; j++)
1315					if (startup_pipes[j] == -1) {
1316						startup_pipes[j] = startup_p[0];
1317						if (maxfd < startup_p[0])
1318							maxfd = startup_p[0];
1319						startups++;
1320						break;
1321					}
1322
1323				/*
1324				 * Got connection.  Fork a child to handle it, unless
1325				 * we are in debugging mode.
1326				 */
1327				if (debug_flag) {
1328					/*
1329					 * In debugging mode.  Close the listening
1330					 * socket, and start processing the
1331					 * connection without forking.
1332					 */
1333					debug("Server will not fork when running in debugging mode.");
1334					close_listen_socks();
1335					sock_in = newsock;
1336					sock_out = newsock;
1337					startup_pipe = -1;
1338					pid = getpid();
1339					break;
1340				} else {
1341					/*
1342					 * Normal production daemon.  Fork, and have
1343					 * the child process the connection. The
1344					 * parent continues listening.
1345					 */
1346					if ((pid = fork()) == 0) {
1347						/*
1348						 * Child.  Close the listening and max_startup
1349						 * sockets.  Start using the accepted socket.
1350						 * Reinitialize logging (since our pid has
1351						 * changed).  We break out of the loop to handle
1352						 * the connection.
1353						 */
1354						startup_pipe = startup_p[1];
1355						close_startup_pipes();
1356						close_listen_socks();
1357						sock_in = newsock;
1358						sock_out = newsock;
1359						log_init(__progname, options.log_level, options.log_facility, log_stderr);
1360						break;
1361					}
1362				}
1363
1364				/* Parent.  Stay in the loop. */
1365				if (pid < 0)
1366					error("fork: %.100s", strerror(errno));
1367				else
1368					debug("Forked child %ld.", (long)pid);
1369
1370				close(startup_p[1]);
1371
1372				/* Mark that the key has been used (it was "given" to the child). */
1373				if ((options.protocol & SSH_PROTO_1) &&
1374				    key_used == 0) {
1375					/* Schedule server key regeneration alarm. */
1376					signal(SIGALRM, key_regeneration_alarm);
1377					alarm(options.key_regeneration_time);
1378					key_used = 1;
1379				}
1380
1381				arc4random_stir();
1382
1383				/* Close the new socket (the child is now taking care of it). */
1384				close(newsock);
1385			}
1386			/* child process check (or debug mode) */
1387			if (num_listen_socks < 0)
1388				break;
1389		}
1390	}
1391
1392	/* This is the child processing a new connection. */
1393
1394	/*
1395	 * Create a new session and process group since the 4.4BSD
1396	 * setlogin() affects the entire process group.  We don't
1397	 * want the child to be able to affect the parent.
1398	 */
1399#if !defined(SSHD_ACQUIRES_CTTY)
1400	/*
1401	 * If setsid is called, on some platforms sshd will later acquire a
1402	 * controlling terminal which will result in "could not set
1403	 * controlling tty" errors.
1404	 */
1405	if (!debug_flag && !inetd_flag && setsid() < 0)
1406		error("setsid: %.100s", strerror(errno));
1407#endif
1408
1409	/*
1410	 * Disable the key regeneration alarm.  We will not regenerate the
1411	 * key since we are no longer in a position to give it to anyone. We
1412	 * will not restart on SIGHUP since it no longer makes sense.
1413	 */
1414	alarm(0);
1415	signal(SIGALRM, SIG_DFL);
1416	signal(SIGHUP, SIG_DFL);
1417	signal(SIGTERM, SIG_DFL);
1418	signal(SIGQUIT, SIG_DFL);
1419	signal(SIGCHLD, SIG_DFL);
1420	signal(SIGINT, SIG_DFL);
1421
1422	/* Set keepalives if requested. */
1423	if (options.keepalives &&
1424	    setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on,
1425	    sizeof(on)) < 0)
1426		error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1427
1428#ifdef __FreeBSD__
1429	/*
1430	 * Initialize the resolver.  This may not happen automatically
1431	 * before privsep chroot().
1432	 */
1433	if ((_res.options & RES_INIT) == 0) {
1434		debug("res_init()");
1435		res_init();
1436	}
1437#endif
1438
1439	/*
1440	 * Register our connection.  This turns encryption off because we do
1441	 * not have a key.
1442	 */
1443	packet_set_connection(sock_in, sock_out);
1444
1445	remote_port = get_remote_port();
1446	remote_ip = get_remote_ipaddr();
1447
1448#ifdef LIBWRAP
1449	/* Check whether logins are denied from this host. */
1450	{
1451		struct request_info req;
1452
1453		request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1454		fromhost(&req);
1455
1456		if (!hosts_access(&req)) {
1457			debug("Connection refused by tcp wrapper");
1458			refuse(&req);
1459			/* NOTREACHED */
1460			fatal("libwrap refuse returns");
1461		}
1462	}
1463#endif /* LIBWRAP */
1464
1465	/* Log the connection. */
1466	verbose("Connection from %.500s port %d", remote_ip, remote_port);
1467
1468	/*
1469	 * We don\'t want to listen forever unless the other side
1470	 * successfully authenticates itself.  So we set up an alarm which is
1471	 * cleared after successful authentication.  A limit of zero
1472	 * indicates no limit. Note that we don\'t set the alarm in debugging
1473	 * mode; it is just annoying to have the server exit just when you
1474	 * are about to discover the bug.
1475	 */
1476	signal(SIGALRM, grace_alarm_handler);
1477	if (!debug_flag)
1478		alarm(options.login_grace_time);
1479
1480	sshd_exchange_identification(sock_in, sock_out);
1481
1482	packet_set_nonblocking();
1483
1484        /* prepare buffers to collect authentication messages */
1485	buffer_init(&loginmsg);
1486
1487	if (use_privsep)
1488		if ((authctxt = privsep_preauth()) != NULL)
1489			goto authenticated;
1490
1491	/* perform the key exchange */
1492	/* authenticate user and start session */
1493	if (compat20) {
1494		do_ssh2_kex();
1495		authctxt = do_authentication2();
1496	} else {
1497		do_ssh1_kex();
1498		authctxt = do_authentication();
1499	}
1500	/*
1501	 * If we use privilege separation, the unprivileged child transfers
1502	 * the current keystate and exits
1503	 */
1504	if (use_privsep) {
1505		mm_send_keystate(pmonitor);
1506		exit(0);
1507	}
1508
1509 authenticated:
1510	/*
1511	 * In privilege separation, we fork another child and prepare
1512	 * file descriptor passing.
1513	 */
1514	if (use_privsep) {
1515		privsep_postauth(authctxt);
1516		/* the monitor process [priv] will not return */
1517		if (!compat20)
1518			destroy_sensitive_data();
1519	}
1520
1521	/* Perform session preparation. */
1522	do_authenticated(authctxt);
1523
1524	/* The connection has been terminated. */
1525	verbose("Closing connection to %.100s", remote_ip);
1526
1527#ifdef USE_PAM
1528	if (options.use_pam)
1529		finish_pam();
1530#endif /* USE_PAM */
1531
1532	packet_close();
1533
1534	if (use_privsep)
1535		mm_terminate();
1536
1537	exit(0);
1538}
1539
1540/*
1541 * Decrypt session_key_int using our private server key and private host key
1542 * (key with larger modulus first).
1543 */
1544int
1545ssh1_session_key(BIGNUM *session_key_int)
1546{
1547	int rsafail = 0;
1548
1549	if (BN_cmp(sensitive_data.server_key->rsa->n, sensitive_data.ssh1_host_key->rsa->n) > 0) {
1550		/* Server key has bigger modulus. */
1551		if (BN_num_bits(sensitive_data.server_key->rsa->n) <
1552		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1553			fatal("do_connection: %s: server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1554			    get_remote_ipaddr(),
1555			    BN_num_bits(sensitive_data.server_key->rsa->n),
1556			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1557			    SSH_KEY_BITS_RESERVED);
1558		}
1559		if (rsa_private_decrypt(session_key_int, session_key_int,
1560		    sensitive_data.server_key->rsa) <= 0)
1561			rsafail++;
1562		if (rsa_private_decrypt(session_key_int, session_key_int,
1563		    sensitive_data.ssh1_host_key->rsa) <= 0)
1564			rsafail++;
1565	} else {
1566		/* Host key has bigger modulus (or they are equal). */
1567		if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
1568		    BN_num_bits(sensitive_data.server_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1569			fatal("do_connection: %s: host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
1570			    get_remote_ipaddr(),
1571			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1572			    BN_num_bits(sensitive_data.server_key->rsa->n),
1573			    SSH_KEY_BITS_RESERVED);
1574		}
1575		if (rsa_private_decrypt(session_key_int, session_key_int,
1576		    sensitive_data.ssh1_host_key->rsa) < 0)
1577			rsafail++;
1578		if (rsa_private_decrypt(session_key_int, session_key_int,
1579		    sensitive_data.server_key->rsa) < 0)
1580			rsafail++;
1581	}
1582	return (rsafail);
1583}
1584/*
1585 * SSH1 key exchange
1586 */
1587static void
1588do_ssh1_kex(void)
1589{
1590	int i, len;
1591	int rsafail = 0;
1592	BIGNUM *session_key_int;
1593	u_char session_key[SSH_SESSION_KEY_LENGTH];
1594	u_char cookie[8];
1595	u_int cipher_type, auth_mask, protocol_flags;
1596	u_int32_t rnd = 0;
1597
1598	/*
1599	 * Generate check bytes that the client must send back in the user
1600	 * packet in order for it to be accepted; this is used to defy ip
1601	 * spoofing attacks.  Note that this only works against somebody
1602	 * doing IP spoofing from a remote machine; any machine on the local
1603	 * network can still see outgoing packets and catch the random
1604	 * cookie.  This only affects rhosts authentication, and this is one
1605	 * of the reasons why it is inherently insecure.
1606	 */
1607	for (i = 0; i < 8; i++) {
1608		if (i % 4 == 0)
1609			rnd = arc4random();
1610		cookie[i] = rnd & 0xff;
1611		rnd >>= 8;
1612	}
1613
1614	/*
1615	 * Send our public key.  We include in the packet 64 bits of random
1616	 * data that must be matched in the reply in order to prevent IP
1617	 * spoofing.
1618	 */
1619	packet_start(SSH_SMSG_PUBLIC_KEY);
1620	for (i = 0; i < 8; i++)
1621		packet_put_char(cookie[i]);
1622
1623	/* Store our public server RSA key. */
1624	packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
1625	packet_put_bignum(sensitive_data.server_key->rsa->e);
1626	packet_put_bignum(sensitive_data.server_key->rsa->n);
1627
1628	/* Store our public host RSA key. */
1629	packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1630	packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
1631	packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
1632
1633	/* Put protocol flags. */
1634	packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
1635
1636	/* Declare which ciphers we support. */
1637	packet_put_int(cipher_mask_ssh1(0));
1638
1639	/* Declare supported authentication types. */
1640	auth_mask = 0;
1641	if (options.rhosts_rsa_authentication)
1642		auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
1643	if (options.rsa_authentication)
1644		auth_mask |= 1 << SSH_AUTH_RSA;
1645	if (options.challenge_response_authentication == 1)
1646		auth_mask |= 1 << SSH_AUTH_TIS;
1647	if (options.password_authentication)
1648		auth_mask |= 1 << SSH_AUTH_PASSWORD;
1649	packet_put_int(auth_mask);
1650
1651	/* Send the packet and wait for it to be sent. */
1652	packet_send();
1653	packet_write_wait();
1654
1655	debug("Sent %d bit server key and %d bit host key.",
1656	    BN_num_bits(sensitive_data.server_key->rsa->n),
1657	    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1658
1659	/* Read clients reply (cipher type and session key). */
1660	packet_read_expect(SSH_CMSG_SESSION_KEY);
1661
1662	/* Get cipher type and check whether we accept this. */
1663	cipher_type = packet_get_char();
1664
1665	if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
1666		packet_disconnect("Warning: client selects unsupported cipher.");
1667
1668	/* Get check bytes from the packet.  These must match those we
1669	   sent earlier with the public key packet. */
1670	for (i = 0; i < 8; i++)
1671		if (cookie[i] != packet_get_char())
1672			packet_disconnect("IP Spoofing check bytes do not match.");
1673
1674	debug("Encryption type: %.200s", cipher_name(cipher_type));
1675
1676	/* Get the encrypted integer. */
1677	if ((session_key_int = BN_new()) == NULL)
1678		fatal("do_ssh1_kex: BN_new failed");
1679	packet_get_bignum(session_key_int);
1680
1681	protocol_flags = packet_get_int();
1682	packet_set_protocol_flags(protocol_flags);
1683	packet_check_eom();
1684
1685	/* Decrypt session_key_int using host/server keys */
1686	rsafail = PRIVSEP(ssh1_session_key(session_key_int));
1687
1688	/*
1689	 * Extract session key from the decrypted integer.  The key is in the
1690	 * least significant 256 bits of the integer; the first byte of the
1691	 * key is in the highest bits.
1692	 */
1693	if (!rsafail) {
1694		BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1695		len = BN_num_bytes(session_key_int);
1696		if (len < 0 || len > sizeof(session_key)) {
1697			error("do_connection: bad session key len from %s: "
1698			    "session_key_int %d > sizeof(session_key) %lu",
1699			    get_remote_ipaddr(), len, (u_long)sizeof(session_key));
1700			rsafail++;
1701		} else {
1702			memset(session_key, 0, sizeof(session_key));
1703			BN_bn2bin(session_key_int,
1704			    session_key + sizeof(session_key) - len);
1705
1706			compute_session_id(session_id, cookie,
1707			    sensitive_data.ssh1_host_key->rsa->n,
1708			    sensitive_data.server_key->rsa->n);
1709			/*
1710			 * Xor the first 16 bytes of the session key with the
1711			 * session id.
1712			 */
1713			for (i = 0; i < 16; i++)
1714				session_key[i] ^= session_id[i];
1715		}
1716	}
1717	if (rsafail) {
1718		int bytes = BN_num_bytes(session_key_int);
1719		u_char *buf = xmalloc(bytes);
1720		MD5_CTX md;
1721
1722		logit("do_connection: generating a fake encryption key");
1723		BN_bn2bin(session_key_int, buf);
1724		MD5_Init(&md);
1725		MD5_Update(&md, buf, bytes);
1726		MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1727		MD5_Final(session_key, &md);
1728		MD5_Init(&md);
1729		MD5_Update(&md, session_key, 16);
1730		MD5_Update(&md, buf, bytes);
1731		MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1732		MD5_Final(session_key + 16, &md);
1733		memset(buf, 0, bytes);
1734		xfree(buf);
1735		for (i = 0; i < 16; i++)
1736			session_id[i] = session_key[i] ^ session_key[i + 16];
1737	}
1738	/* Destroy the private and public keys. No longer. */
1739	destroy_sensitive_data();
1740
1741	if (use_privsep)
1742		mm_ssh1_session_id(session_id);
1743
1744	/* Destroy the decrypted integer.  It is no longer needed. */
1745	BN_clear_free(session_key_int);
1746
1747	/* Set the session key.  From this on all communications will be encrypted. */
1748	packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
1749
1750	/* Destroy our copy of the session key.  It is no longer needed. */
1751	memset(session_key, 0, sizeof(session_key));
1752
1753	debug("Received session key; encryption turned on.");
1754
1755	/* Send an acknowledgment packet.  Note that this packet is sent encrypted. */
1756	packet_start(SSH_SMSG_SUCCESS);
1757	packet_send();
1758	packet_write_wait();
1759}
1760
1761/*
1762 * SSH2 key exchange: diffie-hellman-group1-sha1
1763 */
1764static void
1765do_ssh2_kex(void)
1766{
1767	Kex *kex;
1768
1769	if (options.ciphers != NULL) {
1770		myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1771		myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
1772	}
1773	myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1774	    compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
1775	myproposal[PROPOSAL_ENC_ALGS_STOC] =
1776	    compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
1777
1778	if (options.macs != NULL) {
1779		myproposal[PROPOSAL_MAC_ALGS_CTOS] =
1780		myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
1781	}
1782	if (!options.compression) {
1783		myproposal[PROPOSAL_COMP_ALGS_CTOS] =
1784		myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
1785	}
1786	myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
1787
1788	/* start key exchange */
1789	kex = kex_setup(myproposal);
1790	kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
1791	kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
1792	kex->server = 1;
1793	kex->client_version_string=client_version_string;
1794	kex->server_version_string=server_version_string;
1795	kex->load_host_key=&get_hostkey_by_type;
1796	kex->host_key_index=&get_hostkey_index;
1797
1798	xxx_kex = kex;
1799
1800	dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
1801
1802	session_id2 = kex->session_id;
1803	session_id2_len = kex->session_id_len;
1804
1805#ifdef DEBUG_KEXDH
1806	/* send 1st encrypted/maced/compressed message */
1807	packet_start(SSH2_MSG_IGNORE);
1808	packet_put_cstring("markus");
1809	packet_send();
1810	packet_write_wait();
1811#endif
1812	debug("KEX done");
1813}
1814