sshd.c revision 226046
1193323Sed/* $OpenBSD: sshd.c,v 1.385 2011/06/23 09:34:13 djm Exp $ */
2193323Sed/* $FreeBSD: head/crypto/openssh/sshd.c 226046 2011-10-05 22:08:17Z des $ */
3193323Sed/*
4193323Sed * Author: Tatu Ylonen <ylo@cs.hut.fi>
5193323Sed * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6193323Sed *                    All rights reserved
7193323Sed * This program is the ssh daemon.  It listens for connections from clients,
8193323Sed * and performs authentication, executes use commands or shell, and forwards
9193323Sed * information to/from the application to the user client over an encrypted
10193323Sed * connection.  This can also handle forwarding of X11, TCP/IP, and
11193323Sed * authentication agent connections.
12193323Sed *
13193323Sed * As far as I am concerned, the code I have written for this software
14193323Sed * can be used freely for any purpose.  Any derived versions of this
15193323Sed * software must be clearly marked as such, and if the derived work is
16193323Sed * incompatible with the protocol description in the RFC file, it must be
17193323Sed * called by a name other than "ssh" or "Secure Shell".
18193323Sed *
19193323Sed * SSH2 implementation:
20193323Sed * Privilege Separation:
21193323Sed *
22193323Sed * Copyright (c) 2000, 2001, 2002 Markus Friedl.  All rights reserved.
23193323Sed * Copyright (c) 2002 Niels Provos.  All rights reserved.
24193323Sed *
25193323Sed * Redistribution and use in source and binary forms, with or without
26193323Sed * modification, are permitted provided that the following conditions
27193323Sed * are met:
28193323Sed * 1. Redistributions of source code must retain the above copyright
29193323Sed *    notice, this list of conditions and the following disclaimer.
30193323Sed * 2. Redistributions in binary form must reproduce the above copyright
31193323Sed *    notice, this list of conditions and the following disclaimer in the
32193323Sed *    documentation and/or other materials provided with the distribution.
33193323Sed *
34193323Sed * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
35193323Sed * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
36193323Sed * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
37193323Sed * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
38193323Sed * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
39193323Sed * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
40193323Sed * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
41193323Sed * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
42193323Sed * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
43193323Sed * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44193323Sed */
45193323Sed
46193323Sed#include "includes.h"
47193323Sed__RCSID("$FreeBSD: head/crypto/openssh/sshd.c 226046 2011-10-05 22:08:17Z des $");
48193323Sed
49193323Sed#include <sys/types.h>
50193323Sed#include <sys/ioctl.h>
51193323Sed#include <sys/mman.h>
52193323Sed#include <sys/socket.h>
53193323Sed#ifdef HAVE_SYS_STAT_H
54193323Sed# include <sys/stat.h>
55193323Sed#endif
56193323Sed#ifdef HAVE_SYS_TIME_H
57193323Sed# include <sys/time.h>
58193323Sed#endif
59193323Sed#include "openbsd-compat/sys-tree.h"
60193323Sed#include "openbsd-compat/sys-queue.h"
61193323Sed#include <sys/wait.h>
62193323Sed
63193323Sed#include <errno.h>
64193323Sed#include <fcntl.h>
65193323Sed#include <netdb.h>
66193323Sed#ifdef HAVE_PATHS_H
67193323Sed#include <paths.h>
68193323Sed#endif
69193323Sed#include <grp.h>
70193323Sed#include <pwd.h>
71193323Sed#include <signal.h>
72193323Sed#include <stdarg.h>
73193323Sed#include <stdio.h>
74193323Sed#include <stdlib.h>
75193323Sed#include <string.h>
76193323Sed#include <unistd.h>
77193323Sed
78193323Sed#include <openssl/dh.h>
79193323Sed#include <openssl/bn.h>
80193323Sed#include <openssl/md5.h>
81193323Sed#include <openssl/rand.h>
82193323Sed#include "openbsd-compat/openssl-compat.h"
83193323Sed
84193323Sed#ifdef HAVE_SECUREWARE
85193323Sed#include <sys/security.h>
86193323Sed#include <prot.h>
87193323Sed#endif
88193323Sed
89193323Sed#ifdef __FreeBSD__
90193323Sed#include <resolv.h>
91193323Sed#if defined(GSSAPI) && defined(HAVE_GSSAPI_H)
92193323Sed#include <gssapi.h>
93193323Sed#elif defined(GSSAPI) && defined(HAVE_GSSAPI_GSSAPI_H)
94193323Sed#include <gssapi/gssapi.h>
95193323Sed#endif
96193323Sed#endif
97193323Sed
98193323Sed#include "xmalloc.h"
99193323Sed#include "ssh.h"
100193323Sed#include "ssh1.h"
101193323Sed#include "ssh2.h"
102193323Sed#include "rsa.h"
103193323Sed#include "sshpty.h"
104193323Sed#include "packet.h"
105193323Sed#include "log.h"
106193323Sed#include "buffer.h"
107193323Sed#include "servconf.h"
108193323Sed#include "uidswap.h"
109193323Sed#include "compat.h"
110193323Sed#include "cipher.h"
111193323Sed#include "key.h"
112193323Sed#include "kex.h"
113193323Sed#include "dh.h"
114193323Sed#include "myproposal.h"
115193323Sed#include "authfile.h"
116193323Sed#include "pathnames.h"
117193323Sed#include "atomicio.h"
118193323Sed#include "canohost.h"
119193323Sed#include "hostfile.h"
120193323Sed#include "auth.h"
121193323Sed#include "misc.h"
122193323Sed#include "msg.h"
123193323Sed#include "dispatch.h"
124193323Sed#include "channels.h"
125193323Sed#include "session.h"
126193323Sed#include "monitor_mm.h"
127193323Sed#include "monitor.h"
128193323Sed#ifdef GSSAPI
129193323Sed#include "ssh-gss.h"
130193323Sed#endif
131193323Sed#include "monitor_wrap.h"
132193323Sed#include "roaming.h"
133193323Sed#include "ssh-sandbox.h"
134193323Sed#include "version.h"
135193323Sed
136193323Sed#ifdef LIBWRAP
137193323Sed#include <tcpd.h>
138193323Sed#include <syslog.h>
139193323Sedint allow_severity;
140193323Sedint deny_severity;
141193323Sed#endif /* LIBWRAP */
142193323Sed
143193323Sed#ifndef O_NOCTTY
144193323Sed#define O_NOCTTY	0
145193323Sed#endif
146193323Sed
147193323Sed/* Re-exec fds */
148193323Sed#define REEXEC_DEVCRYPTO_RESERVED_FD	(STDERR_FILENO + 1)
149193323Sed#define REEXEC_STARTUP_PIPE_FD		(STDERR_FILENO + 2)
150193323Sed#define REEXEC_CONFIG_PASS_FD		(STDERR_FILENO + 3)
151193323Sed#define REEXEC_MIN_FREE_FD		(STDERR_FILENO + 4)
152193323Sed
153193323Sedextern char *__progname;
154193323Sed
155193323Sed/* Server configuration options. */
156193323SedServerOptions options;
157193323Sed
158193323Sed/* Name of the server configuration file. */
159193323Sedchar *config_file_name = _PATH_SERVER_CONFIG_FILE;
160193323Sed
161193323Sed/*
162193323Sed * Debug mode flag.  This can be set on the command line.  If debug
163193323Sed * mode is enabled, extra debugging output will be sent to the system
164193323Sed * log, the daemon will not go to background, and will exit after processing
165193323Sed * the first connection.
166193323Sed */
167193323Sedint debug_flag = 0;
168193323Sed
169193323Sed/* Flag indicating that the daemon should only test the configuration and keys. */
170193323Sedint test_flag = 0;
171193323Sed
172193323Sed/* Flag indicating that the daemon is being started from inetd. */
173193323Sedint inetd_flag = 0;
174193323Sed
175193323Sed/* Flag indicating that sshd should not detach and become a daemon. */
176193323Sedint no_daemon_flag = 0;
177193323Sed
178193323Sed/* debug goes to stderr unless inetd_flag is set */
179193323Sedint log_stderr = 0;
180193323Sed
181193323Sed/* Saved arguments to main(). */
182193323Sedchar **saved_argv;
183193323Sedint saved_argc;
184193323Sed
185193323Sed/* re-exec */
186193323Sedint rexeced_flag = 0;
187193323Sedint rexec_flag = 1;
188193323Sedint rexec_argc = 0;
189193323Sedchar **rexec_argv;
190193323Sed
191193323Sed/*
192193323Sed * The sockets that the server is listening; this is used in the SIGHUP
193193323Sed * signal handler.
194193323Sed */
195193323Sed#define	MAX_LISTEN_SOCKS	16
196193323Sedint listen_socks[MAX_LISTEN_SOCKS];
197193323Sedint num_listen_socks = 0;
198193323Sed
199193323Sed/*
200193323Sed * the client's version string, passed by sshd2 in compat mode. if != NULL,
201193323Sed * sshd will skip the version-number exchange
202193323Sed */
203193323Sedchar *client_version_string = NULL;
204193323Sedchar *server_version_string = NULL;
205193323Sed
206193323Sed/* for rekeying XXX fixme */
207193323SedKex *xxx_kex;
208193323Sed
209193323Sed/*
210193323Sed * Any really sensitive data in the application is contained in this
211193323Sed * structure. The idea is that this structure could be locked into memory so
212193323Sed * that the pages do not get written into swap.  However, there are some
213193323Sed * problems. The private key contains BIGNUMs, and we do not (in principle)
214193323Sed * have access to the internals of them, and locking just the structure is
215193323Sed * not very useful.  Currently, memory locking is not implemented.
216193323Sed */
217193323Sedstruct {
218193323Sed	Key	*server_key;		/* ephemeral server key */
219193323Sed	Key	*ssh1_host_key;		/* ssh1 host key */
220193323Sed	Key	**host_keys;		/* all private host keys */
221193323Sed	Key	**host_certificates;	/* all public host certificates */
222193323Sed	int	have_ssh1_key;
223193323Sed	int	have_ssh2_key;
224193323Sed	u_char	ssh1_cookie[SSH_SESSION_KEY_LENGTH];
225193323Sed} sensitive_data;
226193323Sed
227193323Sed/*
228193323Sed * Flag indicating whether the RSA server key needs to be regenerated.
229193323Sed * Is set in the SIGALRM handler and cleared when the key is regenerated.
230193323Sed */
231193323Sedstatic volatile sig_atomic_t key_do_regen = 0;
232193323Sed
233193323Sed/* This is set to true when a signal is received. */
234193323Sedstatic volatile sig_atomic_t received_sighup = 0;
235193323Sedstatic volatile sig_atomic_t received_sigterm = 0;
236193323Sed
237193323Sed/* session identifier, used by RSA-auth */
238193323Sedu_char session_id[16];
239193323Sed
240193323Sed/* same for ssh2 */
241193323Sedu_char *session_id2 = NULL;
242193323Sedu_int session_id2_len = 0;
243193323Sed
244193323Sed/* record remote hostname or ip */
245193323Sedu_int utmp_len = MAXHOSTNAMELEN;
246193323Sed
247193323Sed/* options.max_startup sized array of fd ints */
248193323Sedint *startup_pipes = NULL;
249193323Sedint startup_pipe;		/* in child */
250193323Sed
251193323Sed/* variables used for privilege separation */
252193323Sedint use_privsep = -1;
253193323Sedstruct monitor *pmonitor = NULL;
254193323Sed
255193323Sed/* global authentication context */
256193323SedAuthctxt *the_authctxt = NULL;
257193323Sed
258193323Sed/* sshd_config buffer */
259193323SedBuffer cfg;
260193323Sed
261193323Sed/* message to be displayed after login */
262193323SedBuffer loginmsg;
263193323Sed
264193323Sed/* Unprivileged user */
265193323Sedstruct passwd *privsep_pw = NULL;
266193323Sed
267193323Sed/* Prototypes for various functions defined later in this file. */
268193323Sedvoid destroy_sensitive_data(void);
269193323Sedvoid demote_sensitive_data(void);
270193323Sed
271193323Sedstatic void do_ssh1_kex(void);
272193323Sedstatic void do_ssh2_kex(void);
273193323Sed
274193323Sed/*
275193323Sed * Close all listening sockets
276193323Sed */
277193323Sedstatic void
278193323Sedclose_listen_socks(void)
279193323Sed{
280193323Sed	int i;
281193323Sed
282193323Sed	for (i = 0; i < num_listen_socks; i++)
283193323Sed		close(listen_socks[i]);
284193323Sed	num_listen_socks = -1;
285193323Sed}
286193323Sed
287193323Sedstatic void
288193323Sedclose_startup_pipes(void)
289193323Sed{
290193323Sed	int i;
291193323Sed
292193323Sed	if (startup_pipes)
293193323Sed		for (i = 0; i < options.max_startups; i++)
294193323Sed			if (startup_pipes[i] != -1)
295193323Sed				close(startup_pipes[i]);
296193323Sed}
297193323Sed
298193323Sed/*
299193323Sed * Signal handler for SIGHUP.  Sshd execs itself when it receives SIGHUP;
300193323Sed * the effect is to reread the configuration file (and to regenerate
301193323Sed * the server key).
302193323Sed */
303193323Sed
304193323Sed/*ARGSUSED*/
305193323Sedstatic void
306193323Sedsighup_handler(int sig)
307193323Sed{
308193323Sed	int save_errno = errno;
309193323Sed
310193323Sed	received_sighup = 1;
311193323Sed	signal(SIGHUP, sighup_handler);
312193323Sed	errno = save_errno;
313193323Sed}
314193323Sed
315193323Sed/*
316193323Sed * Called from the main program after receiving SIGHUP.
317193323Sed * Restarts the server.
318193323Sed */
319193323Sedstatic void
320193323Sedsighup_restart(void)
321193323Sed{
322193323Sed	logit("Received SIGHUP; restarting.");
323193323Sed	close_listen_socks();
324193323Sed	close_startup_pipes();
325193323Sed	alarm(0);  /* alarm timer persists across exec */
326193323Sed	signal(SIGHUP, SIG_IGN); /* will be restored after exec */
327193323Sed	execv(saved_argv[0], saved_argv);
328193323Sed	logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
329193323Sed	    strerror(errno));
330193323Sed	exit(1);
331193323Sed}
332193323Sed
333193323Sed/*
334193323Sed * Generic signal handler for terminating signals in the master daemon.
335193323Sed */
336193323Sed/*ARGSUSED*/
337193323Sedstatic void
338193323Sedsigterm_handler(int sig)
339193323Sed{
340193323Sed	received_sigterm = sig;
341193323Sed}
342193323Sed
343193323Sed/*
344193323Sed * SIGCHLD handler.  This is called whenever a child dies.  This will then
345193323Sed * reap any zombies left by exited children.
346193323Sed */
347193323Sed/*ARGSUSED*/
348193323Sedstatic void
349193323Sedmain_sigchld_handler(int sig)
350193323Sed{
351193323Sed	int save_errno = errno;
352193323Sed	pid_t pid;
353193323Sed	int status;
354193323Sed
355193323Sed	while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
356193323Sed	    (pid < 0 && errno == EINTR))
357193323Sed		;
358193323Sed
359193323Sed	signal(SIGCHLD, main_sigchld_handler);
360193323Sed	errno = save_errno;
361193323Sed}
362193323Sed
363193323Sed/*
364193323Sed * Signal handler for the alarm after the login grace period has expired.
365193323Sed */
366193323Sed/*ARGSUSED*/
367193323Sedstatic void
368193323Sedgrace_alarm_handler(int sig)
369193323Sed{
370193323Sed	if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
371193323Sed		kill(pmonitor->m_pid, SIGALRM);
372193323Sed
373193323Sed	/* Log error and exit. */
374193323Sed	sigdie("Timeout before authentication for %s", get_remote_ipaddr());
375193323Sed}
376193323Sed
377193323Sed/*
378193323Sed * Signal handler for the key regeneration alarm.  Note that this
379193323Sed * alarm only occurs in the daemon waiting for connections, and it does not
380193323Sed * do anything with the private key or random state before forking.
381193323Sed * Thus there should be no concurrency control/asynchronous execution
382193323Sed * problems.
383193323Sed */
384193323Sedstatic void
385193323Sedgenerate_ephemeral_server_key(void)
386193323Sed{
387193323Sed	verbose("Generating %s%d bit RSA key.",
388193323Sed	    sensitive_data.server_key ? "new " : "", options.server_key_bits);
389193323Sed	if (sensitive_data.server_key != NULL)
390193323Sed		key_free(sensitive_data.server_key);
391193323Sed	sensitive_data.server_key = key_generate(KEY_RSA1,
392193323Sed	    options.server_key_bits);
393193323Sed	verbose("RSA key generation complete.");
394193323Sed
395193323Sed	arc4random_buf(sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
396193323Sed	arc4random_stir();
397193323Sed}
398193323Sed
399193323Sed/*ARGSUSED*/
400193323Sedstatic void
401193323Sedkey_regeneration_alarm(int sig)
402193323Sed{
403193323Sed	int save_errno = errno;
404193323Sed
405193323Sed	signal(SIGALRM, SIG_DFL);
406193323Sed	errno = save_errno;
407193323Sed	key_do_regen = 1;
408193323Sed}
409193323Sed
410193323Sedstatic void
411193323Sedsshd_exchange_identification(int sock_in, int sock_out)
412193323Sed{
413193323Sed	u_int i;
414193323Sed	int mismatch;
415193323Sed	int remote_major, remote_minor;
416193323Sed	int major, minor;
417193323Sed	char *s, *newline = "\n";
418193323Sed	char buf[256];			/* Must not be larger than remote_version. */
419193323Sed	char remote_version[256];	/* Must be at least as big as buf. */
420193323Sed
421193323Sed	if ((options.protocol & SSH_PROTO_1) &&
422193323Sed	    (options.protocol & SSH_PROTO_2)) {
423193323Sed		major = PROTOCOL_MAJOR_1;
424193323Sed		minor = 99;
425193323Sed	} else if (options.protocol & SSH_PROTO_2) {
426193323Sed		major = PROTOCOL_MAJOR_2;
427193323Sed		minor = PROTOCOL_MINOR_2;
428193323Sed		newline = "\r\n";
429193323Sed	} else {
430193323Sed		major = PROTOCOL_MAJOR_1;
431193323Sed		minor = PROTOCOL_MINOR_1;
432193323Sed	}
433193323Sed	snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s%s", major, minor,
434193323Sed	    SSH_RELEASE, newline);
435193323Sed	server_version_string = xstrdup(buf);
436193323Sed
437193323Sed	/* Send our protocol version identification. */
438193323Sed	if (roaming_atomicio(vwrite, sock_out, server_version_string,
439193323Sed	    strlen(server_version_string))
440193323Sed	    != strlen(server_version_string)) {
441193323Sed		logit("Could not write ident string to %s", get_remote_ipaddr());
442193323Sed		cleanup_exit(255);
443193323Sed	}
444193323Sed
445193323Sed	/* Read other sides version identification. */
446193323Sed	memset(buf, 0, sizeof(buf));
447193323Sed	for (i = 0; i < sizeof(buf) - 1; i++) {
448193323Sed		if (roaming_atomicio(read, sock_in, &buf[i], 1) != 1) {
449193323Sed			logit("Did not receive identification string from %s",
450193323Sed			    get_remote_ipaddr());
451193323Sed			cleanup_exit(255);
452193323Sed		}
453193323Sed		if (buf[i] == '\r') {
454193323Sed			buf[i] = 0;
455193323Sed			/* Kludge for F-Secure Macintosh < 1.0.2 */
456193323Sed			if (i == 12 &&
457193323Sed			    strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
458193323Sed				break;
459193323Sed			continue;
460193323Sed		}
461193323Sed		if (buf[i] == '\n') {
462193323Sed			buf[i] = 0;
463193323Sed			break;
464193323Sed		}
465193323Sed	}
466193323Sed	buf[sizeof(buf) - 1] = 0;
467193323Sed	client_version_string = xstrdup(buf);
468193323Sed
469193323Sed	/*
470193323Sed	 * Check that the versions match.  In future this might accept
471193323Sed	 * several versions and set appropriate flags to handle them.
472193323Sed	 */
473193323Sed	if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
474193323Sed	    &remote_major, &remote_minor, remote_version) != 3) {
475193323Sed		s = "Protocol mismatch.\n";
476193323Sed		(void) atomicio(vwrite, sock_out, s, strlen(s));
477193323Sed		close(sock_in);
478193323Sed		close(sock_out);
479193323Sed		logit("Bad protocol version identification '%.100s' from %s",
480193323Sed		    client_version_string, get_remote_ipaddr());
481193323Sed		cleanup_exit(255);
482193323Sed	}
483193323Sed	debug("Client protocol version %d.%d; client software version %.100s",
484193323Sed	    remote_major, remote_minor, remote_version);
485193323Sed
486193323Sed	compat_datafellows(remote_version);
487193323Sed
488193323Sed	if (datafellows & SSH_BUG_PROBE) {
489193323Sed		logit("probed from %s with %s.  Don't panic.",
490193323Sed		    get_remote_ipaddr(), client_version_string);
491193323Sed		cleanup_exit(255);
492193323Sed	}
493193323Sed
494193323Sed	if (datafellows & SSH_BUG_SCANNER) {
495193323Sed		logit("scanned from %s with %s.  Don't panic.",
496193323Sed		    get_remote_ipaddr(), client_version_string);
497193323Sed		cleanup_exit(255);
498193323Sed	}
499193323Sed
500193323Sed	mismatch = 0;
501193323Sed	switch (remote_major) {
502193323Sed	case 1:
503193323Sed		if (remote_minor == 99) {
504193323Sed			if (options.protocol & SSH_PROTO_2)
505193323Sed				enable_compat20();
506193323Sed			else
507193323Sed				mismatch = 1;
508193323Sed			break;
509193323Sed		}
510193323Sed		if (!(options.protocol & SSH_PROTO_1)) {
511193323Sed			mismatch = 1;
512193323Sed			break;
513193323Sed		}
514193323Sed		if (remote_minor < 3) {
515193323Sed			packet_disconnect("Your ssh version is too old and "
516193323Sed			    "is no longer supported.  Please install a newer version.");
517193323Sed		} else if (remote_minor == 3) {
518193323Sed			/* note that this disables agent-forwarding */
519193323Sed			enable_compat13();
520193323Sed		}
521193323Sed		break;
522193323Sed	case 2:
523193323Sed		if (options.protocol & SSH_PROTO_2) {
524193323Sed			enable_compat20();
525193323Sed			break;
526193323Sed		}
527193323Sed		/* FALLTHROUGH */
528193323Sed	default:
529193323Sed		mismatch = 1;
530193323Sed		break;
531193323Sed	}
532193323Sed	chop(server_version_string);
533193323Sed	debug("Local version string %.200s", server_version_string);
534193323Sed
535193323Sed	if (mismatch) {
536193323Sed		s = "Protocol major versions differ.\n";
537193323Sed		(void) atomicio(vwrite, sock_out, s, strlen(s));
538193323Sed		close(sock_in);
539193323Sed		close(sock_out);
540193323Sed		logit("Protocol major versions differ for %s: %.200s vs. %.200s",
541193323Sed		    get_remote_ipaddr(),
542193323Sed		    server_version_string, client_version_string);
543193323Sed		cleanup_exit(255);
544193323Sed	}
545193323Sed}
546193323Sed
547193323Sed/* Destroy the host and server keys.  They will no longer be needed. */
548193323Sedvoid
549193323Seddestroy_sensitive_data(void)
550193323Sed{
551193323Sed	int i;
552193323Sed
553193323Sed	if (sensitive_data.server_key) {
554193323Sed		key_free(sensitive_data.server_key);
555193323Sed		sensitive_data.server_key = NULL;
556193323Sed	}
557193323Sed	for (i = 0; i < options.num_host_key_files; i++) {
558193323Sed		if (sensitive_data.host_keys[i]) {
559193323Sed			key_free(sensitive_data.host_keys[i]);
560193323Sed			sensitive_data.host_keys[i] = NULL;
561193323Sed		}
562193323Sed		if (sensitive_data.host_certificates[i]) {
563193323Sed			key_free(sensitive_data.host_certificates[i]);
564193323Sed			sensitive_data.host_certificates[i] = NULL;
565193323Sed		}
566193323Sed	}
567193323Sed	sensitive_data.ssh1_host_key = NULL;
568193323Sed	memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
569193323Sed}
570193323Sed
571193323Sed/* Demote private to public keys for network child */
572193323Sedvoid
573193323Seddemote_sensitive_data(void)
574193323Sed{
575193323Sed	Key *tmp;
576193323Sed	int i;
577193323Sed
578193323Sed	if (sensitive_data.server_key) {
579193323Sed		tmp = key_demote(sensitive_data.server_key);
580193323Sed		key_free(sensitive_data.server_key);
581193323Sed		sensitive_data.server_key = tmp;
582193323Sed	}
583193323Sed
584193323Sed	for (i = 0; i < options.num_host_key_files; i++) {
585193323Sed		if (sensitive_data.host_keys[i]) {
586193323Sed			tmp = key_demote(sensitive_data.host_keys[i]);
587193323Sed			key_free(sensitive_data.host_keys[i]);
588193323Sed			sensitive_data.host_keys[i] = tmp;
589193323Sed			if (tmp->type == KEY_RSA1)
590193323Sed				sensitive_data.ssh1_host_key = tmp;
591193323Sed		}
592193323Sed		/* Certs do not need demotion */
593193323Sed	}
594193323Sed
595193323Sed	/* We do not clear ssh1_host key and cookie.  XXX - Okay Niels? */
596193323Sed}
597193323Sed
598193323Sedstatic void
599193323Sedprivsep_preauth_child(void)
600193323Sed{
601193323Sed	u_int32_t rnd[256];
602193323Sed	gid_t gidset[1];
603193323Sed
604193323Sed	/* Enable challenge-response authentication for privilege separation */
605193323Sed	privsep_challenge_enable();
606193323Sed
607193323Sed	arc4random_stir();
608193323Sed	arc4random_buf(rnd, sizeof(rnd));
609193323Sed	RAND_seed(rnd, sizeof(rnd));
610193323Sed
611193323Sed	/* Demote the private keys to public keys. */
612193323Sed	demote_sensitive_data();
613193323Sed
614193323Sed	/* Change our root directory */
615193323Sed	if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
616193323Sed		fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
617193323Sed		    strerror(errno));
618193323Sed	if (chdir("/") == -1)
619193323Sed		fatal("chdir(\"/\"): %s", strerror(errno));
620193323Sed
621193323Sed	/* Drop our privileges */
622193323Sed	debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
623193323Sed	    (u_int)privsep_pw->pw_gid);
624193323Sed#if 0
625193323Sed	/* XXX not ready, too heavy after chroot */
626193323Sed	do_setusercontext(privsep_pw);
627193323Sed#else
628193323Sed	gidset[0] = privsep_pw->pw_gid;
629193323Sed	if (setgroups(1, gidset) < 0)
630193323Sed		fatal("setgroups: %.100s", strerror(errno));
631193323Sed	permanently_set_uid(privsep_pw);
632193323Sed#endif
633193323Sed}
634193323Sed
635193323Sedstatic int
636193323Sedprivsep_preauth(Authctxt *authctxt)
637193323Sed{
638193323Sed	int status;
639193323Sed	pid_t pid;
640193323Sed	struct ssh_sandbox *box = NULL;
641193323Sed
642193323Sed	/* Set up unprivileged child process to deal with network data */
643193323Sed	pmonitor = monitor_init();
644193323Sed	/* Store a pointer to the kex for later rekeying */
645193323Sed	pmonitor->m_pkex = &xxx_kex;
646193323Sed
647193323Sed	if (use_privsep == PRIVSEP_SANDBOX)
648193323Sed		box = ssh_sandbox_init();
649193323Sed	pid = fork();
650193323Sed	if (pid == -1) {
651193323Sed		fatal("fork of unprivileged child failed");
652193323Sed	} else if (pid != 0) {
653193323Sed		debug2("Network child is on pid %ld", (long)pid);
654193323Sed
655193323Sed		if (box != NULL)
656193323Sed			ssh_sandbox_parent_preauth(box, pid);
657193323Sed		pmonitor->m_pid = pid;
658193323Sed		monitor_child_preauth(authctxt, pmonitor);
659193323Sed
660193323Sed		/* Sync memory */
661193323Sed		monitor_sync(pmonitor);
662193323Sed
663193323Sed		/* Wait for the child's exit status */
664193323Sed		while (waitpid(pid, &status, 0) < 0) {
665193323Sed			if (errno != EINTR)
666193323Sed				fatal("%s: waitpid: %s", __func__,
667193323Sed				    strerror(errno));
668193323Sed		}
669193323Sed		if (WIFEXITED(status)) {
670193323Sed			if (WEXITSTATUS(status) != 0)
671193323Sed				fatal("%s: preauth child exited with status %d",
672193323Sed				    __func__, WEXITSTATUS(status));
673193323Sed		} else if (WIFSIGNALED(status))
674193323Sed			fatal("%s: preauth child terminated by signal %d",
675193323Sed			    __func__, WTERMSIG(status));
676193323Sed		if (box != NULL)
677193323Sed			ssh_sandbox_parent_finish(box);
678193323Sed		return 1;
679193323Sed	} else {
680193323Sed		/* child */
681193323Sed		close(pmonitor->m_sendfd);
682193323Sed		close(pmonitor->m_log_recvfd);
683193323Sed
684193323Sed		/* Arrange for logging to be sent to the monitor */
685193323Sed		set_log_handler(mm_log_handler, pmonitor);
686193323Sed
687193323Sed		/* Demote the child */
688193323Sed		if (getuid() == 0 || geteuid() == 0)
689193323Sed			privsep_preauth_child();
690193323Sed		setproctitle("%s", "[net]");
691193323Sed		if (box != NULL)
692193323Sed			ssh_sandbox_child(box);
693193323Sed
694193323Sed		return 0;
695193323Sed	}
696193323Sed}
697193323Sed
698193323Sedstatic void
699193323Sedprivsep_postauth(Authctxt *authctxt)
700193323Sed{
701193323Sed	u_int32_t rnd[256];
702193323Sed
703193323Sed#ifdef DISABLE_FD_PASSING
704193323Sed	if (1) {
705193323Sed#else
706193323Sed	if (authctxt->pw->pw_uid == 0 || options.use_login) {
707193323Sed#endif
708193323Sed		/* File descriptor passing is broken or root login */
709193323Sed		use_privsep = 0;
710193323Sed		goto skip;
711193323Sed	}
712193323Sed
713193323Sed	/* New socket pair */
714193323Sed	monitor_reinit(pmonitor);
715193323Sed
716193323Sed	pmonitor->m_pid = fork();
717193323Sed	if (pmonitor->m_pid == -1)
718193323Sed		fatal("fork of unprivileged child failed");
719193323Sed	else if (pmonitor->m_pid != 0) {
720193323Sed		verbose("User child is on pid %ld", (long)pmonitor->m_pid);
721193323Sed		buffer_clear(&loginmsg);
722193323Sed		monitor_child_postauth(pmonitor);
723193323Sed
724193323Sed		/* NEVERREACHED */
725193323Sed		exit(0);
726193323Sed	}
727193323Sed
728193323Sed	/* child */
729193323Sed
730193323Sed	close(pmonitor->m_sendfd);
731193323Sed	pmonitor->m_sendfd = -1;
732193323Sed
733193323Sed	/* Demote the private keys to public keys. */
734193323Sed	demote_sensitive_data();
735193323Sed
736193323Sed	arc4random_stir();
737193323Sed	arc4random_buf(rnd, sizeof(rnd));
738193323Sed	RAND_seed(rnd, sizeof(rnd));
739193323Sed
740193323Sed	/* Drop privileges */
741193323Sed	do_setusercontext(authctxt->pw);
742193323Sed
743193323Sed skip:
744193323Sed	/* It is safe now to apply the key state */
745193323Sed	monitor_apply_keystate(pmonitor);
746193323Sed
747193323Sed	/*
748193323Sed	 * Tell the packet layer that authentication was successful, since
749193323Sed	 * this information is not part of the key state.
750193323Sed	 */
751193323Sed	packet_set_authenticated();
752193323Sed}
753193323Sed
754193323Sedstatic char *
755193323Sedlist_hostkey_types(void)
756193323Sed{
757193323Sed	Buffer b;
758193323Sed	const char *p;
759193323Sed	char *ret;
760193323Sed	int i;
761193323Sed	Key *key;
762193323Sed
763193323Sed	buffer_init(&b);
764193323Sed	for (i = 0; i < options.num_host_key_files; i++) {
765193323Sed		key = sensitive_data.host_keys[i];
766193323Sed		if (key == NULL)
767193323Sed			continue;
768193323Sed		switch (key->type) {
769193323Sed		case KEY_RSA:
770193323Sed		case KEY_DSA:
771193323Sed		case KEY_ECDSA:
772193323Sed			if (buffer_len(&b) > 0)
773193323Sed				buffer_append(&b, ",", 1);
774193323Sed			p = key_ssh_name(key);
775193323Sed			buffer_append(&b, p, strlen(p));
776193323Sed			break;
777193323Sed		}
778193323Sed		/* If the private key has a cert peer, then list that too */
779193323Sed		key = sensitive_data.host_certificates[i];
780193323Sed		if (key == NULL)
781193323Sed			continue;
782193323Sed		switch (key->type) {
783193323Sed		case KEY_RSA_CERT_V00:
784193323Sed		case KEY_DSA_CERT_V00:
785193323Sed		case KEY_RSA_CERT:
786193323Sed		case KEY_DSA_CERT:
787193323Sed		case KEY_ECDSA_CERT:
788193323Sed			if (buffer_len(&b) > 0)
789193323Sed				buffer_append(&b, ",", 1);
790193323Sed			p = key_ssh_name(key);
791193323Sed			buffer_append(&b, p, strlen(p));
792193323Sed			break;
793193323Sed		}
794193323Sed	}
795193323Sed	buffer_append(&b, "\0", 1);
796193323Sed	ret = xstrdup(buffer_ptr(&b));
797193323Sed	buffer_free(&b);
798193323Sed	debug("list_hostkey_types: %s", ret);
799193323Sed	return ret;
800193323Sed}
801193323Sed
802193323Sedstatic Key *
803193323Sedget_hostkey_by_type(int type, int need_private)
804193323Sed{
805193323Sed	int i;
806193323Sed	Key *key;
807193323Sed
808193323Sed	for (i = 0; i < options.num_host_key_files; i++) {
809193323Sed		switch (type) {
810193323Sed		case KEY_RSA_CERT_V00:
811193323Sed		case KEY_DSA_CERT_V00:
812193323Sed		case KEY_RSA_CERT:
813193323Sed		case KEY_DSA_CERT:
814193323Sed		case KEY_ECDSA_CERT:
815193323Sed			key = sensitive_data.host_certificates[i];
816193323Sed			break;
817193323Sed		default:
818193323Sed			key = sensitive_data.host_keys[i];
819193323Sed			break;
820193323Sed		}
821193323Sed		if (key != NULL && key->type == type)
822193323Sed			return need_private ?
823193323Sed			    sensitive_data.host_keys[i] : key;
824193323Sed	}
825193323Sed	return NULL;
826193323Sed}
827193323Sed
828193323SedKey *
829193323Sedget_hostkey_public_by_type(int type)
830193323Sed{
831193323Sed	return get_hostkey_by_type(type, 0);
832193323Sed}
833193323Sed
834193323SedKey *
835193323Sedget_hostkey_private_by_type(int type)
836193323Sed{
837193323Sed	return get_hostkey_by_type(type, 1);
838193323Sed}
839193323Sed
840193323SedKey *
841193323Sedget_hostkey_by_index(int ind)
842193323Sed{
843193323Sed	if (ind < 0 || ind >= options.num_host_key_files)
844193323Sed		return (NULL);
845193323Sed	return (sensitive_data.host_keys[ind]);
846193323Sed}
847193323Sed
848193323Sedint
849193323Sedget_hostkey_index(Key *key)
850193323Sed{
851193323Sed	int i;
852193323Sed
853193323Sed	for (i = 0; i < options.num_host_key_files; i++) {
854193323Sed		if (key_is_cert(key)) {
855193323Sed			if (key == sensitive_data.host_certificates[i])
856193323Sed				return (i);
857193323Sed		} else {
858193323Sed			if (key == sensitive_data.host_keys[i])
859193323Sed				return (i);
860193323Sed		}
861193323Sed	}
862193323Sed	return (-1);
863193323Sed}
864193323Sed
865193323Sed/*
866193323Sed * returns 1 if connection should be dropped, 0 otherwise.
867193323Sed * dropping starts at connection #max_startups_begin with a probability
868193323Sed * of (max_startups_rate/100). the probability increases linearly until
869193323Sed * all connections are dropped for startups > max_startups
870193323Sed */
871193323Sedstatic int
872193323Seddrop_connection(int startups)
873193323Sed{
874	int p, r;
875
876	if (startups < options.max_startups_begin)
877		return 0;
878	if (startups >= options.max_startups)
879		return 1;
880	if (options.max_startups_rate == 100)
881		return 1;
882
883	p  = 100 - options.max_startups_rate;
884	p *= startups - options.max_startups_begin;
885	p /= options.max_startups - options.max_startups_begin;
886	p += options.max_startups_rate;
887	r = arc4random_uniform(100);
888
889	debug("drop_connection: p %d, r %d", p, r);
890	return (r < p) ? 1 : 0;
891}
892
893static void
894usage(void)
895{
896	fprintf(stderr, "%s, %s\n",
897	    SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
898	fprintf(stderr,
899"usage: sshd [-46DdeiqTt] [-b bits] [-C connection_spec] [-c host_cert_file]\n"
900"            [-f config_file] [-g login_grace_time] [-h host_key_file]\n"
901"            [-k key_gen_time] [-o option] [-p port] [-u len]\n"
902	);
903	exit(1);
904}
905
906static void
907send_rexec_state(int fd, Buffer *conf)
908{
909	Buffer m;
910
911	debug3("%s: entering fd = %d config len %d", __func__, fd,
912	    buffer_len(conf));
913
914	/*
915	 * Protocol from reexec master to child:
916	 *	string	configuration
917	 *	u_int	ephemeral_key_follows
918	 *	bignum	e		(only if ephemeral_key_follows == 1)
919	 *	bignum	n			"
920	 *	bignum	d			"
921	 *	bignum	iqmp			"
922	 *	bignum	p			"
923	 *	bignum	q			"
924	 *	string rngseed		(only if OpenSSL is not self-seeded)
925	 */
926	buffer_init(&m);
927	buffer_put_cstring(&m, buffer_ptr(conf));
928
929	if (sensitive_data.server_key != NULL &&
930	    sensitive_data.server_key->type == KEY_RSA1) {
931		buffer_put_int(&m, 1);
932		buffer_put_bignum(&m, sensitive_data.server_key->rsa->e);
933		buffer_put_bignum(&m, sensitive_data.server_key->rsa->n);
934		buffer_put_bignum(&m, sensitive_data.server_key->rsa->d);
935		buffer_put_bignum(&m, sensitive_data.server_key->rsa->iqmp);
936		buffer_put_bignum(&m, sensitive_data.server_key->rsa->p);
937		buffer_put_bignum(&m, sensitive_data.server_key->rsa->q);
938	} else
939		buffer_put_int(&m, 0);
940
941#ifndef OPENSSL_PRNG_ONLY
942	rexec_send_rng_seed(&m);
943#endif
944
945	if (ssh_msg_send(fd, 0, &m) == -1)
946		fatal("%s: ssh_msg_send failed", __func__);
947
948	buffer_free(&m);
949
950	debug3("%s: done", __func__);
951}
952
953static void
954recv_rexec_state(int fd, Buffer *conf)
955{
956	Buffer m;
957	char *cp;
958	u_int len;
959
960	debug3("%s: entering fd = %d", __func__, fd);
961
962	buffer_init(&m);
963
964	if (ssh_msg_recv(fd, &m) == -1)
965		fatal("%s: ssh_msg_recv failed", __func__);
966	if (buffer_get_char(&m) != 0)
967		fatal("%s: rexec version mismatch", __func__);
968
969	cp = buffer_get_string(&m, &len);
970	if (conf != NULL)
971		buffer_append(conf, cp, len + 1);
972	xfree(cp);
973
974	if (buffer_get_int(&m)) {
975		if (sensitive_data.server_key != NULL)
976			key_free(sensitive_data.server_key);
977		sensitive_data.server_key = key_new_private(KEY_RSA1);
978		buffer_get_bignum(&m, sensitive_data.server_key->rsa->e);
979		buffer_get_bignum(&m, sensitive_data.server_key->rsa->n);
980		buffer_get_bignum(&m, sensitive_data.server_key->rsa->d);
981		buffer_get_bignum(&m, sensitive_data.server_key->rsa->iqmp);
982		buffer_get_bignum(&m, sensitive_data.server_key->rsa->p);
983		buffer_get_bignum(&m, sensitive_data.server_key->rsa->q);
984		rsa_generate_additional_parameters(
985		    sensitive_data.server_key->rsa);
986	}
987
988#ifndef OPENSSL_PRNG_ONLY
989	rexec_recv_rng_seed(&m);
990#endif
991
992	buffer_free(&m);
993
994	debug3("%s: done", __func__);
995}
996
997/* Accept a connection from inetd */
998static void
999server_accept_inetd(int *sock_in, int *sock_out)
1000{
1001	int fd;
1002
1003	startup_pipe = -1;
1004	if (rexeced_flag) {
1005		close(REEXEC_CONFIG_PASS_FD);
1006		*sock_in = *sock_out = dup(STDIN_FILENO);
1007		if (!debug_flag) {
1008			startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
1009			close(REEXEC_STARTUP_PIPE_FD);
1010		}
1011	} else {
1012		*sock_in = dup(STDIN_FILENO);
1013		*sock_out = dup(STDOUT_FILENO);
1014	}
1015	/*
1016	 * We intentionally do not close the descriptors 0, 1, and 2
1017	 * as our code for setting the descriptors won't work if
1018	 * ttyfd happens to be one of those.
1019	 */
1020	if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1021		dup2(fd, STDIN_FILENO);
1022		dup2(fd, STDOUT_FILENO);
1023		if (fd > STDOUT_FILENO)
1024			close(fd);
1025	}
1026	debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
1027}
1028
1029/*
1030 * Listen for TCP connections
1031 */
1032static void
1033server_listen(void)
1034{
1035	int ret, listen_sock, on = 1;
1036	struct addrinfo *ai;
1037	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1038	int socksize;
1039	socklen_t len;
1040
1041	for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
1042		if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1043			continue;
1044		if (num_listen_socks >= MAX_LISTEN_SOCKS)
1045			fatal("Too many listen sockets. "
1046			    "Enlarge MAX_LISTEN_SOCKS");
1047		if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1048		    ntop, sizeof(ntop), strport, sizeof(strport),
1049		    NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1050			error("getnameinfo failed: %.100s",
1051			    ssh_gai_strerror(ret));
1052			continue;
1053		}
1054		/* Create socket for listening. */
1055		listen_sock = socket(ai->ai_family, ai->ai_socktype,
1056		    ai->ai_protocol);
1057		if (listen_sock < 0) {
1058			/* kernel may not support ipv6 */
1059			verbose("socket: %.100s", strerror(errno));
1060			continue;
1061		}
1062		if (set_nonblock(listen_sock) == -1) {
1063			close(listen_sock);
1064			continue;
1065		}
1066		/*
1067		 * Set socket options.
1068		 * Allow local port reuse in TIME_WAIT.
1069		 */
1070		if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
1071		    &on, sizeof(on)) == -1)
1072			error("setsockopt SO_REUSEADDR: %s", strerror(errno));
1073
1074		/* Only communicate in IPv6 over AF_INET6 sockets. */
1075		if (ai->ai_family == AF_INET6)
1076			sock_set_v6only(listen_sock);
1077
1078		debug("Bind to port %s on %s.", strport, ntop);
1079
1080		len = sizeof(socksize);
1081		getsockopt(listen_sock, SOL_SOCKET, SO_RCVBUF, &socksize, &len);
1082		debug("Server TCP RWIN socket size: %d", socksize);
1083		debug("HPN Buffer Size: %d", options.hpn_buffer_size);
1084
1085		/* Bind the socket to the desired port. */
1086		if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1087			error("Bind to port %s on %s failed: %.200s.",
1088			    strport, ntop, strerror(errno));
1089			close(listen_sock);
1090			continue;
1091		}
1092		listen_socks[num_listen_socks] = listen_sock;
1093		num_listen_socks++;
1094
1095		/* Start listening on the port. */
1096		if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1097			fatal("listen on [%s]:%s: %.100s",
1098			    ntop, strport, strerror(errno));
1099		logit("Server listening on %s port %s.", ntop, strport);
1100	}
1101	freeaddrinfo(options.listen_addrs);
1102
1103	if (!num_listen_socks)
1104		fatal("Cannot bind any address.");
1105}
1106
1107/*
1108 * The main TCP accept loop. Note that, for the non-debug case, returns
1109 * from this function are in a forked subprocess.
1110 */
1111static void
1112server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1113{
1114	fd_set *fdset;
1115	int i, j, ret, maxfd;
1116	int key_used = 0, startups = 0;
1117	int startup_p[2] = { -1 , -1 };
1118	struct sockaddr_storage from;
1119	socklen_t fromlen;
1120	pid_t pid;
1121
1122	/* setup fd set for accept */
1123	fdset = NULL;
1124	maxfd = 0;
1125	for (i = 0; i < num_listen_socks; i++)
1126		if (listen_socks[i] > maxfd)
1127			maxfd = listen_socks[i];
1128	/* pipes connected to unauthenticated childs */
1129	startup_pipes = xcalloc(options.max_startups, sizeof(int));
1130	for (i = 0; i < options.max_startups; i++)
1131		startup_pipes[i] = -1;
1132
1133	/*
1134	 * Stay listening for connections until the system crashes or
1135	 * the daemon is killed with a signal.
1136	 */
1137	for (;;) {
1138		if (received_sighup)
1139			sighup_restart();
1140		if (fdset != NULL)
1141			xfree(fdset);
1142		fdset = (fd_set *)xcalloc(howmany(maxfd + 1, NFDBITS),
1143		    sizeof(fd_mask));
1144
1145		for (i = 0; i < num_listen_socks; i++)
1146			FD_SET(listen_socks[i], fdset);
1147		for (i = 0; i < options.max_startups; i++)
1148			if (startup_pipes[i] != -1)
1149				FD_SET(startup_pipes[i], fdset);
1150
1151		/* Wait in select until there is a connection. */
1152		ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1153		if (ret < 0 && errno != EINTR)
1154			error("select: %.100s", strerror(errno));
1155		if (received_sigterm) {
1156			logit("Received signal %d; terminating.",
1157			    (int) received_sigterm);
1158			close_listen_socks();
1159			unlink(options.pid_file);
1160			exit(received_sigterm == SIGTERM ? 0 : 255);
1161		}
1162		if (key_used && key_do_regen) {
1163			generate_ephemeral_server_key();
1164			key_used = 0;
1165			key_do_regen = 0;
1166		}
1167		if (ret < 0)
1168			continue;
1169
1170		for (i = 0; i < options.max_startups; i++)
1171			if (startup_pipes[i] != -1 &&
1172			    FD_ISSET(startup_pipes[i], fdset)) {
1173				/*
1174				 * the read end of the pipe is ready
1175				 * if the child has closed the pipe
1176				 * after successful authentication
1177				 * or if the child has died
1178				 */
1179				close(startup_pipes[i]);
1180				startup_pipes[i] = -1;
1181				startups--;
1182			}
1183		for (i = 0; i < num_listen_socks; i++) {
1184			if (!FD_ISSET(listen_socks[i], fdset))
1185				continue;
1186			fromlen = sizeof(from);
1187			*newsock = accept(listen_socks[i],
1188			    (struct sockaddr *)&from, &fromlen);
1189			if (*newsock < 0) {
1190				if (errno != EINTR && errno != EAGAIN &&
1191				    errno != EWOULDBLOCK)
1192					error("accept: %.100s", strerror(errno));
1193				continue;
1194			}
1195			if (unset_nonblock(*newsock) == -1) {
1196				close(*newsock);
1197				continue;
1198			}
1199			if (drop_connection(startups) == 1) {
1200				debug("drop connection #%d", startups);
1201				close(*newsock);
1202				continue;
1203			}
1204			if (pipe(startup_p) == -1) {
1205				close(*newsock);
1206				continue;
1207			}
1208
1209			if (rexec_flag && socketpair(AF_UNIX,
1210			    SOCK_STREAM, 0, config_s) == -1) {
1211				error("reexec socketpair: %s",
1212				    strerror(errno));
1213				close(*newsock);
1214				close(startup_p[0]);
1215				close(startup_p[1]);
1216				continue;
1217			}
1218
1219			for (j = 0; j < options.max_startups; j++)
1220				if (startup_pipes[j] == -1) {
1221					startup_pipes[j] = startup_p[0];
1222					if (maxfd < startup_p[0])
1223						maxfd = startup_p[0];
1224					startups++;
1225					break;
1226				}
1227
1228			/*
1229			 * Got connection.  Fork a child to handle it, unless
1230			 * we are in debugging mode.
1231			 */
1232			if (debug_flag) {
1233				/*
1234				 * In debugging mode.  Close the listening
1235				 * socket, and start processing the
1236				 * connection without forking.
1237				 */
1238				debug("Server will not fork when running in debugging mode.");
1239				close_listen_socks();
1240				*sock_in = *newsock;
1241				*sock_out = *newsock;
1242				close(startup_p[0]);
1243				close(startup_p[1]);
1244				startup_pipe = -1;
1245				pid = getpid();
1246				if (rexec_flag) {
1247					send_rexec_state(config_s[0],
1248					    &cfg);
1249					close(config_s[0]);
1250				}
1251				break;
1252			}
1253
1254			/*
1255			 * Normal production daemon.  Fork, and have
1256			 * the child process the connection. The
1257			 * parent continues listening.
1258			 */
1259			platform_pre_fork();
1260			if ((pid = fork()) == 0) {
1261				/*
1262				 * Child.  Close the listening and
1263				 * max_startup sockets.  Start using
1264				 * the accepted socket. Reinitialize
1265				 * logging (since our pid has changed).
1266				 * We break out of the loop to handle
1267				 * the connection.
1268				 */
1269				platform_post_fork_child();
1270				startup_pipe = startup_p[1];
1271				close_startup_pipes();
1272				close_listen_socks();
1273				*sock_in = *newsock;
1274				*sock_out = *newsock;
1275				log_init(__progname,
1276				    options.log_level,
1277				    options.log_facility,
1278				    log_stderr);
1279				if (rexec_flag)
1280					close(config_s[0]);
1281				break;
1282			}
1283
1284			/* Parent.  Stay in the loop. */
1285			platform_post_fork_parent(pid);
1286			if (pid < 0)
1287				error("fork: %.100s", strerror(errno));
1288			else
1289				debug("Forked child %ld.", (long)pid);
1290
1291			close(startup_p[1]);
1292
1293			if (rexec_flag) {
1294				send_rexec_state(config_s[0], &cfg);
1295				close(config_s[0]);
1296				close(config_s[1]);
1297			}
1298
1299			/*
1300			 * Mark that the key has been used (it
1301			 * was "given" to the child).
1302			 */
1303			if ((options.protocol & SSH_PROTO_1) &&
1304			    key_used == 0) {
1305				/* Schedule server key regeneration alarm. */
1306				signal(SIGALRM, key_regeneration_alarm);
1307				alarm(options.key_regeneration_time);
1308				key_used = 1;
1309			}
1310
1311			close(*newsock);
1312
1313			/*
1314			 * Ensure that our random state differs
1315			 * from that of the child
1316			 */
1317			arc4random_stir();
1318		}
1319
1320		/* child process check (or debug mode) */
1321		if (num_listen_socks < 0)
1322			break;
1323	}
1324}
1325
1326
1327/*
1328 * Main program for the daemon.
1329 */
1330int
1331main(int ac, char **av)
1332{
1333	extern char *optarg;
1334	extern int optind;
1335	int opt, i, j, on = 1;
1336	int sock_in = -1, sock_out = -1, newsock = -1;
1337	const char *remote_ip;
1338	char *test_user = NULL, *test_host = NULL, *test_addr = NULL;
1339	int remote_port;
1340	char *line, *p, *cp;
1341	int config_s[2] = { -1 , -1 };
1342	u_int64_t ibytes, obytes;
1343	mode_t new_umask;
1344	Key *key;
1345	Authctxt *authctxt;
1346
1347#ifdef HAVE_SECUREWARE
1348	(void)set_auth_parameters(ac, av);
1349#endif
1350	__progname = ssh_get_progname(av[0]);
1351
1352	/* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1353	saved_argc = ac;
1354	rexec_argc = ac;
1355	saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1356	for (i = 0; i < ac; i++)
1357		saved_argv[i] = xstrdup(av[i]);
1358	saved_argv[i] = NULL;
1359
1360#ifndef HAVE_SETPROCTITLE
1361	/* Prepare for later setproctitle emulation */
1362	compat_init_setproctitle(ac, av);
1363	av = saved_argv;
1364#endif
1365
1366	if (geteuid() == 0 && setgroups(0, NULL) == -1)
1367		debug("setgroups(): %.200s", strerror(errno));
1368
1369	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1370	sanitise_stdfd();
1371
1372	/* Initialize configuration options to their default values. */
1373	initialize_server_options(&options);
1374
1375	/* Parse command-line arguments. */
1376	while ((opt = getopt(ac, av, "f:p:b:k:h:g:u:o:C:dDeiqrtQRT46")) != -1) {
1377		switch (opt) {
1378		case '4':
1379			options.address_family = AF_INET;
1380			break;
1381		case '6':
1382			options.address_family = AF_INET6;
1383			break;
1384		case 'f':
1385			config_file_name = optarg;
1386			break;
1387		case 'c':
1388			if (options.num_host_cert_files >= MAX_HOSTCERTS) {
1389				fprintf(stderr, "too many host certificates.\n");
1390				exit(1);
1391			}
1392			options.host_cert_files[options.num_host_cert_files++] =
1393			   derelativise_path(optarg);
1394			break;
1395		case 'd':
1396			if (debug_flag == 0) {
1397				debug_flag = 1;
1398				options.log_level = SYSLOG_LEVEL_DEBUG1;
1399			} else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1400				options.log_level++;
1401			break;
1402		case 'D':
1403			no_daemon_flag = 1;
1404			break;
1405		case 'e':
1406			log_stderr = 1;
1407			break;
1408		case 'i':
1409			inetd_flag = 1;
1410			break;
1411		case 'r':
1412			rexec_flag = 0;
1413			break;
1414		case 'R':
1415			rexeced_flag = 1;
1416			inetd_flag = 1;
1417			break;
1418		case 'Q':
1419			/* ignored */
1420			break;
1421		case 'q':
1422			options.log_level = SYSLOG_LEVEL_QUIET;
1423			break;
1424		case 'b':
1425			options.server_key_bits = (int)strtonum(optarg, 256,
1426			    32768, NULL);
1427			break;
1428		case 'p':
1429			options.ports_from_cmdline = 1;
1430			if (options.num_ports >= MAX_PORTS) {
1431				fprintf(stderr, "too many ports.\n");
1432				exit(1);
1433			}
1434			options.ports[options.num_ports++] = a2port(optarg);
1435			if (options.ports[options.num_ports-1] <= 0) {
1436				fprintf(stderr, "Bad port number.\n");
1437				exit(1);
1438			}
1439			break;
1440		case 'g':
1441			if ((options.login_grace_time = convtime(optarg)) == -1) {
1442				fprintf(stderr, "Invalid login grace time.\n");
1443				exit(1);
1444			}
1445			break;
1446		case 'k':
1447			if ((options.key_regeneration_time = convtime(optarg)) == -1) {
1448				fprintf(stderr, "Invalid key regeneration interval.\n");
1449				exit(1);
1450			}
1451			break;
1452		case 'h':
1453			if (options.num_host_key_files >= MAX_HOSTKEYS) {
1454				fprintf(stderr, "too many host keys.\n");
1455				exit(1);
1456			}
1457			options.host_key_files[options.num_host_key_files++] =
1458			   derelativise_path(optarg);
1459			break;
1460		case 't':
1461			test_flag = 1;
1462			break;
1463		case 'T':
1464			test_flag = 2;
1465			break;
1466		case 'C':
1467			cp = optarg;
1468			while ((p = strsep(&cp, ",")) && *p != '\0') {
1469				if (strncmp(p, "addr=", 5) == 0)
1470					test_addr = xstrdup(p + 5);
1471				else if (strncmp(p, "host=", 5) == 0)
1472					test_host = xstrdup(p + 5);
1473				else if (strncmp(p, "user=", 5) == 0)
1474					test_user = xstrdup(p + 5);
1475				else {
1476					fprintf(stderr, "Invalid test "
1477					    "mode specification %s\n", p);
1478					exit(1);
1479				}
1480			}
1481			break;
1482		case 'u':
1483			utmp_len = (u_int)strtonum(optarg, 0, MAXHOSTNAMELEN+1, NULL);
1484			if (utmp_len > MAXHOSTNAMELEN) {
1485				fprintf(stderr, "Invalid utmp length.\n");
1486				exit(1);
1487			}
1488			break;
1489		case 'o':
1490			line = xstrdup(optarg);
1491			if (process_server_config_line(&options, line,
1492			    "command-line", 0, NULL, NULL, NULL, NULL) != 0)
1493				exit(1);
1494			xfree(line);
1495			break;
1496		case '?':
1497		default:
1498			usage();
1499			break;
1500		}
1501	}
1502	if (rexeced_flag || inetd_flag)
1503		rexec_flag = 0;
1504	if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1505		fatal("sshd re-exec requires execution with an absolute path");
1506	if (rexeced_flag)
1507		closefrom(REEXEC_MIN_FREE_FD);
1508	else
1509		closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1510
1511	OpenSSL_add_all_algorithms();
1512
1513	/*
1514	 * Force logging to stderr until we have loaded the private host
1515	 * key (unless started from inetd)
1516	 */
1517	log_init(__progname,
1518	    options.log_level == SYSLOG_LEVEL_NOT_SET ?
1519	    SYSLOG_LEVEL_INFO : options.log_level,
1520	    options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1521	    SYSLOG_FACILITY_AUTH : options.log_facility,
1522	    log_stderr || !inetd_flag);
1523
1524	/*
1525	 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1526	 * root's environment
1527	 */
1528	if (getenv("KRB5CCNAME") != NULL)
1529		unsetenv("KRB5CCNAME");
1530
1531#ifdef _UNICOS
1532	/* Cray can define user privs drop all privs now!
1533	 * Not needed on PRIV_SU systems!
1534	 */
1535	drop_cray_privs();
1536#endif
1537
1538	sensitive_data.server_key = NULL;
1539	sensitive_data.ssh1_host_key = NULL;
1540	sensitive_data.have_ssh1_key = 0;
1541	sensitive_data.have_ssh2_key = 0;
1542
1543	/*
1544	 * If we're doing an extended config test, make sure we have all of
1545	 * the parameters we need.  If we're not doing an extended test,
1546	 * do not silently ignore connection test params.
1547	 */
1548	if (test_flag >= 2 &&
1549	   (test_user != NULL || test_host != NULL || test_addr != NULL)
1550	    && (test_user == NULL || test_host == NULL || test_addr == NULL))
1551		fatal("user, host and addr are all required when testing "
1552		   "Match configs");
1553	if (test_flag < 2 && (test_user != NULL || test_host != NULL ||
1554	    test_addr != NULL))
1555		fatal("Config test connection parameter (-C) provided without "
1556		   "test mode (-T)");
1557
1558	/* Fetch our configuration */
1559	buffer_init(&cfg);
1560	if (rexeced_flag)
1561		recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1562	else
1563		load_server_config(config_file_name, &cfg);
1564
1565	parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1566	    &cfg, NULL, NULL, NULL);
1567
1568	seed_rng();
1569
1570	/* Fill in default values for those options not explicitly set. */
1571	fill_default_server_options(&options);
1572
1573	/* challenge-response is implemented via keyboard interactive */
1574	if (options.challenge_response_authentication)
1575		options.kbd_interactive_authentication = 1;
1576
1577	/* set default channel AF */
1578	channel_set_af(options.address_family);
1579
1580	/* Check that there are no remaining arguments. */
1581	if (optind < ac) {
1582		fprintf(stderr, "Extra argument %s.\n", av[optind]);
1583		exit(1);
1584	}
1585
1586	debug("sshd version %.100s", SSH_RELEASE);
1587
1588	/* Store privilege separation user for later use if required. */
1589	if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1590		if (use_privsep || options.kerberos_authentication)
1591			fatal("Privilege separation user %s does not exist",
1592			    SSH_PRIVSEP_USER);
1593	} else {
1594		memset(privsep_pw->pw_passwd, 0, strlen(privsep_pw->pw_passwd));
1595		privsep_pw = pwcopy(privsep_pw);
1596		xfree(privsep_pw->pw_passwd);
1597		privsep_pw->pw_passwd = xstrdup("*");
1598	}
1599	endpwent();
1600
1601	/* load private host keys */
1602	sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1603	    sizeof(Key *));
1604	for (i = 0; i < options.num_host_key_files; i++)
1605		sensitive_data.host_keys[i] = NULL;
1606
1607	for (i = 0; i < options.num_host_key_files; i++) {
1608		key = key_load_private(options.host_key_files[i], "", NULL);
1609		sensitive_data.host_keys[i] = key;
1610		if (key == NULL) {
1611			error("Could not load host key: %s",
1612			    options.host_key_files[i]);
1613			sensitive_data.host_keys[i] = NULL;
1614			continue;
1615		}
1616		switch (key->type) {
1617		case KEY_RSA1:
1618			sensitive_data.ssh1_host_key = key;
1619			sensitive_data.have_ssh1_key = 1;
1620			break;
1621		case KEY_RSA:
1622		case KEY_DSA:
1623		case KEY_ECDSA:
1624			sensitive_data.have_ssh2_key = 1;
1625			break;
1626		}
1627		debug("private host key: #%d type %d %s", i, key->type,
1628		    key_type(key));
1629	}
1630	if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1631		logit("Disabling protocol version 1. Could not load host key");
1632		options.protocol &= ~SSH_PROTO_1;
1633	}
1634	if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1635		logit("Disabling protocol version 2. Could not load host key");
1636		options.protocol &= ~SSH_PROTO_2;
1637	}
1638	if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1639		logit("sshd: no hostkeys available -- exiting.");
1640		exit(1);
1641	}
1642
1643	/*
1644	 * Load certificates. They are stored in an array at identical
1645	 * indices to the public keys that they relate to.
1646	 */
1647	sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
1648	    sizeof(Key *));
1649	for (i = 0; i < options.num_host_key_files; i++)
1650		sensitive_data.host_certificates[i] = NULL;
1651
1652	for (i = 0; i < options.num_host_cert_files; i++) {
1653		key = key_load_public(options.host_cert_files[i], NULL);
1654		if (key == NULL) {
1655			error("Could not load host certificate: %s",
1656			    options.host_cert_files[i]);
1657			continue;
1658		}
1659		if (!key_is_cert(key)) {
1660			error("Certificate file is not a certificate: %s",
1661			    options.host_cert_files[i]);
1662			key_free(key);
1663			continue;
1664		}
1665		/* Find matching private key */
1666		for (j = 0; j < options.num_host_key_files; j++) {
1667			if (key_equal_public(key,
1668			    sensitive_data.host_keys[j])) {
1669				sensitive_data.host_certificates[j] = key;
1670				break;
1671			}
1672		}
1673		if (j >= options.num_host_key_files) {
1674			error("No matching private key for certificate: %s",
1675			    options.host_cert_files[i]);
1676			key_free(key);
1677			continue;
1678		}
1679		sensitive_data.host_certificates[j] = key;
1680		debug("host certificate: #%d type %d %s", j, key->type,
1681		    key_type(key));
1682	}
1683	/* Check certain values for sanity. */
1684	if (options.protocol & SSH_PROTO_1) {
1685		if (options.server_key_bits < 512 ||
1686		    options.server_key_bits > 32768) {
1687			fprintf(stderr, "Bad server key size.\n");
1688			exit(1);
1689		}
1690		/*
1691		 * Check that server and host key lengths differ sufficiently. This
1692		 * is necessary to make double encryption work with rsaref. Oh, I
1693		 * hate software patents. I dont know if this can go? Niels
1694		 */
1695		if (options.server_key_bits >
1696		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
1697		    SSH_KEY_BITS_RESERVED && options.server_key_bits <
1698		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1699		    SSH_KEY_BITS_RESERVED) {
1700			options.server_key_bits =
1701			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1702			    SSH_KEY_BITS_RESERVED;
1703			debug("Forcing server key to %d bits to make it differ from host key.",
1704			    options.server_key_bits);
1705		}
1706	}
1707
1708	if (use_privsep) {
1709		struct stat st;
1710
1711		if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1712		    (S_ISDIR(st.st_mode) == 0))
1713			fatal("Missing privilege separation directory: %s",
1714			    _PATH_PRIVSEP_CHROOT_DIR);
1715
1716#ifdef HAVE_CYGWIN
1717		if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1718		    (st.st_uid != getuid () ||
1719		    (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1720#else
1721		if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1722#endif
1723			fatal("%s must be owned by root and not group or "
1724			    "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1725	}
1726
1727	if (test_flag > 1) {
1728		if (test_user != NULL && test_addr != NULL && test_host != NULL)
1729			parse_server_match_config(&options, test_user,
1730			    test_host, test_addr);
1731		dump_config(&options);
1732	}
1733
1734	/* Configuration looks good, so exit if in test mode. */
1735	if (test_flag)
1736		exit(0);
1737
1738	/*
1739	 * Clear out any supplemental groups we may have inherited.  This
1740	 * prevents inadvertent creation of files with bad modes (in the
1741	 * portable version at least, it's certainly possible for PAM
1742	 * to create a file, and we can't control the code in every
1743	 * module which might be used).
1744	 */
1745	if (setgroups(0, NULL) < 0)
1746		debug("setgroups() failed: %.200s", strerror(errno));
1747
1748	if (rexec_flag) {
1749		rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1750		for (i = 0; i < rexec_argc; i++) {
1751			debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1752			rexec_argv[i] = saved_argv[i];
1753		}
1754		rexec_argv[rexec_argc] = "-R";
1755		rexec_argv[rexec_argc + 1] = NULL;
1756	}
1757
1758	/* Ensure that umask disallows at least group and world write */
1759	new_umask = umask(0077) | 0022;
1760	(void) umask(new_umask);
1761
1762	/* Initialize the log (it is reinitialized below in case we forked). */
1763	if (debug_flag && (!inetd_flag || rexeced_flag))
1764		log_stderr = 1;
1765	log_init(__progname, options.log_level, options.log_facility, log_stderr);
1766
1767	/*
1768	 * If not in debugging mode, and not started from inetd, disconnect
1769	 * from the controlling terminal, and fork.  The original process
1770	 * exits.
1771	 */
1772	if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1773#ifdef TIOCNOTTY
1774		int fd;
1775#endif /* TIOCNOTTY */
1776		if (daemon(0, 0) < 0)
1777			fatal("daemon() failed: %.200s", strerror(errno));
1778
1779		/* Disconnect from the controlling tty. */
1780#ifdef TIOCNOTTY
1781		fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1782		if (fd >= 0) {
1783			(void) ioctl(fd, TIOCNOTTY, NULL);
1784			close(fd);
1785		}
1786#endif /* TIOCNOTTY */
1787	}
1788	/* Reinitialize the log (because of the fork above). */
1789	log_init(__progname, options.log_level, options.log_facility, log_stderr);
1790
1791	/* Avoid killing the process in high-pressure swapping environments. */
1792	if (!inetd_flag && madvise(NULL, 0, MADV_PROTECT) != 0)
1793		debug("madvise(): %.200s", strerror(errno));
1794
1795	/* Initialize the random number generator. */
1796	arc4random_stir();
1797
1798	/* Chdir to the root directory so that the current disk can be
1799	   unmounted if desired. */
1800	chdir("/");
1801
1802	/* ignore SIGPIPE */
1803	signal(SIGPIPE, SIG_IGN);
1804
1805	/* Get a connection, either from inetd or a listening TCP socket */
1806	if (inetd_flag) {
1807		server_accept_inetd(&sock_in, &sock_out);
1808	} else {
1809		platform_pre_listen();
1810		server_listen();
1811
1812		if (options.protocol & SSH_PROTO_1)
1813			generate_ephemeral_server_key();
1814
1815		signal(SIGHUP, sighup_handler);
1816		signal(SIGCHLD, main_sigchld_handler);
1817		signal(SIGTERM, sigterm_handler);
1818		signal(SIGQUIT, sigterm_handler);
1819
1820		/*
1821		 * Write out the pid file after the sigterm handler
1822		 * is setup and the listen sockets are bound
1823		 */
1824		if (!debug_flag) {
1825			FILE *f = fopen(options.pid_file, "w");
1826
1827			if (f == NULL) {
1828				error("Couldn't create pid file \"%s\": %s",
1829				    options.pid_file, strerror(errno));
1830			} else {
1831				fprintf(f, "%ld\n", (long) getpid());
1832				fclose(f);
1833			}
1834		}
1835
1836		/* Accept a connection and return in a forked child */
1837		server_accept_loop(&sock_in, &sock_out,
1838		    &newsock, config_s);
1839	}
1840
1841	/* This is the child processing a new connection. */
1842	setproctitle("%s", "[accepted]");
1843
1844	/*
1845	 * Create a new session and process group since the 4.4BSD
1846	 * setlogin() affects the entire process group.  We don't
1847	 * want the child to be able to affect the parent.
1848	 */
1849#if !defined(SSHD_ACQUIRES_CTTY)
1850	/*
1851	 * If setsid is called, on some platforms sshd will later acquire a
1852	 * controlling terminal which will result in "could not set
1853	 * controlling tty" errors.
1854	 */
1855	if (!debug_flag && !inetd_flag && setsid() < 0)
1856		error("setsid: %.100s", strerror(errno));
1857#endif
1858
1859	if (rexec_flag) {
1860		int fd;
1861
1862		debug("rexec start in %d out %d newsock %d pipe %d sock %d",
1863		    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1864		dup2(newsock, STDIN_FILENO);
1865		dup2(STDIN_FILENO, STDOUT_FILENO);
1866		if (startup_pipe == -1)
1867			close(REEXEC_STARTUP_PIPE_FD);
1868		else
1869			dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
1870
1871		dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1872		close(config_s[1]);
1873		if (startup_pipe != -1)
1874			close(startup_pipe);
1875
1876		execv(rexec_argv[0], rexec_argv);
1877
1878		/* Reexec has failed, fall back and continue */
1879		error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1880		recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1881		log_init(__progname, options.log_level,
1882		    options.log_facility, log_stderr);
1883
1884		/* Clean up fds */
1885		startup_pipe = REEXEC_STARTUP_PIPE_FD;
1886		close(config_s[1]);
1887		close(REEXEC_CONFIG_PASS_FD);
1888		newsock = sock_out = sock_in = dup(STDIN_FILENO);
1889		if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1890			dup2(fd, STDIN_FILENO);
1891			dup2(fd, STDOUT_FILENO);
1892			if (fd > STDERR_FILENO)
1893				close(fd);
1894		}
1895		debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
1896		    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1897	}
1898
1899	/* Executed child processes don't need these. */
1900	fcntl(sock_out, F_SETFD, FD_CLOEXEC);
1901	fcntl(sock_in, F_SETFD, FD_CLOEXEC);
1902
1903	/*
1904	 * Disable the key regeneration alarm.  We will not regenerate the
1905	 * key since we are no longer in a position to give it to anyone. We
1906	 * will not restart on SIGHUP since it no longer makes sense.
1907	 */
1908	alarm(0);
1909	signal(SIGALRM, SIG_DFL);
1910	signal(SIGHUP, SIG_DFL);
1911	signal(SIGTERM, SIG_DFL);
1912	signal(SIGQUIT, SIG_DFL);
1913	signal(SIGCHLD, SIG_DFL);
1914	signal(SIGINT, SIG_DFL);
1915
1916#ifdef __FreeBSD__
1917	/*
1918	 * Initialize the resolver.  This may not happen automatically
1919	 * before privsep chroot().
1920	 */
1921	if ((_res.options & RES_INIT) == 0) {
1922		debug("res_init()");
1923		res_init();
1924	}
1925#ifdef GSSAPI
1926	/*
1927	 * Force GSS-API to parse its configuration and load any
1928	 * mechanism plugins.
1929	 */
1930	{
1931		gss_OID_set mechs;
1932		OM_uint32 minor_status;
1933		gss_indicate_mechs(&minor_status, &mechs);
1934		gss_release_oid_set(&minor_status, &mechs);
1935	}
1936#endif
1937#endif
1938
1939	/*
1940	 * Register our connection.  This turns encryption off because we do
1941	 * not have a key.
1942	 */
1943	packet_set_connection(sock_in, sock_out);
1944	packet_set_server();
1945
1946	/* Set SO_KEEPALIVE if requested. */
1947	if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
1948	    setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
1949		error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1950
1951	if ((remote_port = get_remote_port()) < 0) {
1952		debug("get_remote_port failed");
1953		cleanup_exit(255);
1954	}
1955
1956	/*
1957	 * We use get_canonical_hostname with usedns = 0 instead of
1958	 * get_remote_ipaddr here so IP options will be checked.
1959	 */
1960	(void) get_canonical_hostname(0);
1961	/*
1962	 * The rest of the code depends on the fact that
1963	 * get_remote_ipaddr() caches the remote ip, even if
1964	 * the socket goes away.
1965	 */
1966	remote_ip = get_remote_ipaddr();
1967
1968#ifdef SSH_AUDIT_EVENTS
1969	audit_connection_from(remote_ip, remote_port);
1970#endif
1971#ifdef LIBWRAP
1972	allow_severity = options.log_facility|LOG_INFO;
1973	deny_severity = options.log_facility|LOG_WARNING;
1974	/* Check whether logins are denied from this host. */
1975	if (packet_connection_is_on_socket()) {
1976		struct request_info req;
1977
1978		request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1979		fromhost(&req);
1980
1981		if (!hosts_access(&req)) {
1982			debug("Connection refused by tcp wrapper");
1983			refuse(&req);
1984			/* NOTREACHED */
1985			fatal("libwrap refuse returns");
1986		}
1987	}
1988#endif /* LIBWRAP */
1989
1990	/* Log the connection. */
1991	verbose("Connection from %.500s port %d", remote_ip, remote_port);
1992
1993	/* Set HPN options for the child. */
1994	channel_set_hpn(options.hpn_disabled, options.hpn_buffer_size);
1995
1996	/*
1997	 * We don't want to listen forever unless the other side
1998	 * successfully authenticates itself.  So we set up an alarm which is
1999	 * cleared after successful authentication.  A limit of zero
2000	 * indicates no limit. Note that we don't set the alarm in debugging
2001	 * mode; it is just annoying to have the server exit just when you
2002	 * are about to discover the bug.
2003	 */
2004	signal(SIGALRM, grace_alarm_handler);
2005	if (!debug_flag)
2006		alarm(options.login_grace_time);
2007
2008	sshd_exchange_identification(sock_in, sock_out);
2009
2010	/* In inetd mode, generate ephemeral key only for proto 1 connections */
2011	if (!compat20 && inetd_flag && sensitive_data.server_key == NULL)
2012		generate_ephemeral_server_key();
2013
2014	packet_set_nonblocking();
2015
2016	/* allocate authentication context */
2017	authctxt = xcalloc(1, sizeof(*authctxt));
2018
2019	authctxt->loginmsg = &loginmsg;
2020
2021	/* XXX global for cleanup, access from other modules */
2022	the_authctxt = authctxt;
2023
2024	/* prepare buffer to collect messages to display to user after login */
2025	buffer_init(&loginmsg);
2026	auth_debug_reset();
2027
2028	if (use_privsep)
2029		if (privsep_preauth(authctxt) == 1)
2030			goto authenticated;
2031
2032	/* perform the key exchange */
2033	/* authenticate user and start session */
2034	if (compat20) {
2035		do_ssh2_kex();
2036		do_authentication2(authctxt);
2037	} else {
2038		do_ssh1_kex();
2039		do_authentication(authctxt);
2040	}
2041	/*
2042	 * If we use privilege separation, the unprivileged child transfers
2043	 * the current keystate and exits
2044	 */
2045	if (use_privsep) {
2046		mm_send_keystate(pmonitor);
2047		exit(0);
2048	}
2049
2050 authenticated:
2051	/*
2052	 * Cancel the alarm we set to limit the time taken for
2053	 * authentication.
2054	 */
2055	alarm(0);
2056	signal(SIGALRM, SIG_DFL);
2057	authctxt->authenticated = 1;
2058	if (startup_pipe != -1) {
2059		close(startup_pipe);
2060		startup_pipe = -1;
2061	}
2062
2063#ifdef SSH_AUDIT_EVENTS
2064	audit_event(SSH_AUTH_SUCCESS);
2065#endif
2066
2067#ifdef GSSAPI
2068	if (options.gss_authentication) {
2069		temporarily_use_uid(authctxt->pw);
2070		ssh_gssapi_storecreds();
2071		restore_uid();
2072	}
2073#endif
2074#ifdef USE_PAM
2075	if (options.use_pam) {
2076		do_pam_setcred(1);
2077		do_pam_session();
2078	}
2079#endif
2080
2081	/*
2082	 * In privilege separation, we fork another child and prepare
2083	 * file descriptor passing.
2084	 */
2085	if (use_privsep) {
2086		privsep_postauth(authctxt);
2087		/* the monitor process [priv] will not return */
2088		if (!compat20)
2089			destroy_sensitive_data();
2090	}
2091
2092	packet_set_timeout(options.client_alive_interval,
2093	    options.client_alive_count_max);
2094
2095	/* Start session. */
2096	do_authenticated(authctxt);
2097
2098	/* The connection has been terminated. */
2099	packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
2100	packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
2101	verbose("Transferred: sent %llu, received %llu bytes",
2102	    (unsigned long long)obytes, (unsigned long long)ibytes);
2103
2104	verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
2105
2106#ifdef USE_PAM
2107	if (options.use_pam)
2108		finish_pam();
2109#endif /* USE_PAM */
2110
2111#ifdef SSH_AUDIT_EVENTS
2112	PRIVSEP(audit_event(SSH_CONNECTION_CLOSE));
2113#endif
2114
2115	packet_close();
2116
2117	if (use_privsep)
2118		mm_terminate();
2119
2120	exit(0);
2121}
2122
2123/*
2124 * Decrypt session_key_int using our private server key and private host key
2125 * (key with larger modulus first).
2126 */
2127int
2128ssh1_session_key(BIGNUM *session_key_int)
2129{
2130	int rsafail = 0;
2131
2132	if (BN_cmp(sensitive_data.server_key->rsa->n,
2133	    sensitive_data.ssh1_host_key->rsa->n) > 0) {
2134		/* Server key has bigger modulus. */
2135		if (BN_num_bits(sensitive_data.server_key->rsa->n) <
2136		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
2137		    SSH_KEY_BITS_RESERVED) {
2138			fatal("do_connection: %s: "
2139			    "server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
2140			    get_remote_ipaddr(),
2141			    BN_num_bits(sensitive_data.server_key->rsa->n),
2142			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2143			    SSH_KEY_BITS_RESERVED);
2144		}
2145		if (rsa_private_decrypt(session_key_int, session_key_int,
2146		    sensitive_data.server_key->rsa) <= 0)
2147			rsafail++;
2148		if (rsa_private_decrypt(session_key_int, session_key_int,
2149		    sensitive_data.ssh1_host_key->rsa) <= 0)
2150			rsafail++;
2151	} else {
2152		/* Host key has bigger modulus (or they are equal). */
2153		if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
2154		    BN_num_bits(sensitive_data.server_key->rsa->n) +
2155		    SSH_KEY_BITS_RESERVED) {
2156			fatal("do_connection: %s: "
2157			    "host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
2158			    get_remote_ipaddr(),
2159			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2160			    BN_num_bits(sensitive_data.server_key->rsa->n),
2161			    SSH_KEY_BITS_RESERVED);
2162		}
2163		if (rsa_private_decrypt(session_key_int, session_key_int,
2164		    sensitive_data.ssh1_host_key->rsa) < 0)
2165			rsafail++;
2166		if (rsa_private_decrypt(session_key_int, session_key_int,
2167		    sensitive_data.server_key->rsa) < 0)
2168			rsafail++;
2169	}
2170	return (rsafail);
2171}
2172/*
2173 * SSH1 key exchange
2174 */
2175static void
2176do_ssh1_kex(void)
2177{
2178	int i, len;
2179	int rsafail = 0;
2180	BIGNUM *session_key_int;
2181	u_char session_key[SSH_SESSION_KEY_LENGTH];
2182	u_char cookie[8];
2183	u_int cipher_type, auth_mask, protocol_flags;
2184
2185	/*
2186	 * Generate check bytes that the client must send back in the user
2187	 * packet in order for it to be accepted; this is used to defy ip
2188	 * spoofing attacks.  Note that this only works against somebody
2189	 * doing IP spoofing from a remote machine; any machine on the local
2190	 * network can still see outgoing packets and catch the random
2191	 * cookie.  This only affects rhosts authentication, and this is one
2192	 * of the reasons why it is inherently insecure.
2193	 */
2194	arc4random_buf(cookie, sizeof(cookie));
2195
2196	/*
2197	 * Send our public key.  We include in the packet 64 bits of random
2198	 * data that must be matched in the reply in order to prevent IP
2199	 * spoofing.
2200	 */
2201	packet_start(SSH_SMSG_PUBLIC_KEY);
2202	for (i = 0; i < 8; i++)
2203		packet_put_char(cookie[i]);
2204
2205	/* Store our public server RSA key. */
2206	packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
2207	packet_put_bignum(sensitive_data.server_key->rsa->e);
2208	packet_put_bignum(sensitive_data.server_key->rsa->n);
2209
2210	/* Store our public host RSA key. */
2211	packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2212	packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
2213	packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
2214
2215	/* Put protocol flags. */
2216	packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
2217
2218	/* Declare which ciphers we support. */
2219	packet_put_int(cipher_mask_ssh1(0));
2220
2221	/* Declare supported authentication types. */
2222	auth_mask = 0;
2223	if (options.rhosts_rsa_authentication)
2224		auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
2225	if (options.rsa_authentication)
2226		auth_mask |= 1 << SSH_AUTH_RSA;
2227	if (options.challenge_response_authentication == 1)
2228		auth_mask |= 1 << SSH_AUTH_TIS;
2229	if (options.password_authentication)
2230		auth_mask |= 1 << SSH_AUTH_PASSWORD;
2231	packet_put_int(auth_mask);
2232
2233	/* Send the packet and wait for it to be sent. */
2234	packet_send();
2235	packet_write_wait();
2236
2237	debug("Sent %d bit server key and %d bit host key.",
2238	    BN_num_bits(sensitive_data.server_key->rsa->n),
2239	    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2240
2241	/* Read clients reply (cipher type and session key). */
2242	packet_read_expect(SSH_CMSG_SESSION_KEY);
2243
2244	/* Get cipher type and check whether we accept this. */
2245	cipher_type = packet_get_char();
2246
2247	if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
2248		packet_disconnect("Warning: client selects unsupported cipher.");
2249
2250	/* Get check bytes from the packet.  These must match those we
2251	   sent earlier with the public key packet. */
2252	for (i = 0; i < 8; i++)
2253		if (cookie[i] != packet_get_char())
2254			packet_disconnect("IP Spoofing check bytes do not match.");
2255
2256	debug("Encryption type: %.200s", cipher_name(cipher_type));
2257
2258	/* Get the encrypted integer. */
2259	if ((session_key_int = BN_new()) == NULL)
2260		fatal("do_ssh1_kex: BN_new failed");
2261	packet_get_bignum(session_key_int);
2262
2263	protocol_flags = packet_get_int();
2264	packet_set_protocol_flags(protocol_flags);
2265	packet_check_eom();
2266
2267	/* Decrypt session_key_int using host/server keys */
2268	rsafail = PRIVSEP(ssh1_session_key(session_key_int));
2269
2270	/*
2271	 * Extract session key from the decrypted integer.  The key is in the
2272	 * least significant 256 bits of the integer; the first byte of the
2273	 * key is in the highest bits.
2274	 */
2275	if (!rsafail) {
2276		(void) BN_mask_bits(session_key_int, sizeof(session_key) * 8);
2277		len = BN_num_bytes(session_key_int);
2278		if (len < 0 || (u_int)len > sizeof(session_key)) {
2279			error("do_ssh1_kex: bad session key len from %s: "
2280			    "session_key_int %d > sizeof(session_key) %lu",
2281			    get_remote_ipaddr(), len, (u_long)sizeof(session_key));
2282			rsafail++;
2283		} else {
2284			memset(session_key, 0, sizeof(session_key));
2285			BN_bn2bin(session_key_int,
2286			    session_key + sizeof(session_key) - len);
2287
2288			derive_ssh1_session_id(
2289			    sensitive_data.ssh1_host_key->rsa->n,
2290			    sensitive_data.server_key->rsa->n,
2291			    cookie, session_id);
2292			/*
2293			 * Xor the first 16 bytes of the session key with the
2294			 * session id.
2295			 */
2296			for (i = 0; i < 16; i++)
2297				session_key[i] ^= session_id[i];
2298		}
2299	}
2300	if (rsafail) {
2301		int bytes = BN_num_bytes(session_key_int);
2302		u_char *buf = xmalloc(bytes);
2303		MD5_CTX md;
2304
2305		logit("do_connection: generating a fake encryption key");
2306		BN_bn2bin(session_key_int, buf);
2307		MD5_Init(&md);
2308		MD5_Update(&md, buf, bytes);
2309		MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2310		MD5_Final(session_key, &md);
2311		MD5_Init(&md);
2312		MD5_Update(&md, session_key, 16);
2313		MD5_Update(&md, buf, bytes);
2314		MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2315		MD5_Final(session_key + 16, &md);
2316		memset(buf, 0, bytes);
2317		xfree(buf);
2318		for (i = 0; i < 16; i++)
2319			session_id[i] = session_key[i] ^ session_key[i + 16];
2320	}
2321	/* Destroy the private and public keys. No longer. */
2322	destroy_sensitive_data();
2323
2324	if (use_privsep)
2325		mm_ssh1_session_id(session_id);
2326
2327	/* Destroy the decrypted integer.  It is no longer needed. */
2328	BN_clear_free(session_key_int);
2329
2330	/* Set the session key.  From this on all communications will be encrypted. */
2331	packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
2332
2333	/* Destroy our copy of the session key.  It is no longer needed. */
2334	memset(session_key, 0, sizeof(session_key));
2335
2336	debug("Received session key; encryption turned on.");
2337
2338	/* Send an acknowledgment packet.  Note that this packet is sent encrypted. */
2339	packet_start(SSH_SMSG_SUCCESS);
2340	packet_send();
2341	packet_write_wait();
2342}
2343
2344/*
2345 * SSH2 key exchange: diffie-hellman-group1-sha1
2346 */
2347static void
2348do_ssh2_kex(void)
2349{
2350	Kex *kex;
2351
2352	if (options.ciphers != NULL) {
2353		myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2354		myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
2355#ifdef	NONE_CIPHER_ENABLED
2356	} else if (options.none_enabled == 1) {
2357		debug ("WARNING: None cipher enabled");
2358		myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2359		myproposal[PROPOSAL_ENC_ALGS_STOC] = KEX_ENCRYPT_INCLUDE_NONE;
2360#endif
2361	}
2362	myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2363	    compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
2364	myproposal[PROPOSAL_ENC_ALGS_STOC] =
2365	    compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
2366
2367	if (options.macs != NULL) {
2368		myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2369		myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2370	}
2371	if (options.compression == COMP_NONE) {
2372		myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2373		myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2374	} else if (options.compression == COMP_DELAYED) {
2375		myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2376		myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com";
2377	}
2378	if (options.kex_algorithms != NULL)
2379		myproposal[PROPOSAL_KEX_ALGS] = options.kex_algorithms;
2380
2381	myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
2382
2383	/* start key exchange */
2384	kex = kex_setup(myproposal);
2385	kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2386	kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
2387	kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2388	kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2389	kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
2390	kex->server = 1;
2391	kex->client_version_string=client_version_string;
2392	kex->server_version_string=server_version_string;
2393	kex->load_host_public_key=&get_hostkey_public_by_type;
2394	kex->load_host_private_key=&get_hostkey_private_by_type;
2395	kex->host_key_index=&get_hostkey_index;
2396
2397	xxx_kex = kex;
2398
2399	dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
2400
2401	session_id2 = kex->session_id;
2402	session_id2_len = kex->session_id_len;
2403
2404#ifdef DEBUG_KEXDH
2405	/* send 1st encrypted/maced/compressed message */
2406	packet_start(SSH2_MSG_IGNORE);
2407	packet_put_cstring("markus");
2408	packet_send();
2409	packet_write_wait();
2410#endif
2411	debug("KEX done");
2412}
2413
2414/* server specific fatal cleanup */
2415void
2416cleanup_exit(int i)
2417{
2418	if (the_authctxt)
2419		do_cleanup(the_authctxt);
2420#ifdef SSH_AUDIT_EVENTS
2421	/* done after do_cleanup so it can cancel the PAM auth 'thread' */
2422	if (!use_privsep || mm_is_monitor())
2423		audit_event(SSH_CONNECTION_ABANDON);
2424#endif
2425	_exit(i);
2426}
2427