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