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