1/* $OpenBSD: sshd.c,v 1.602 2024/01/08 00:34:34 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/mman.h>
50#include <sys/socket.h>
51#ifdef HAVE_SYS_STAT_H
52# include <sys/stat.h>
53#endif
54#ifdef HAVE_SYS_TIME_H
55# include <sys/time.h>
56#endif
57#include "openbsd-compat/sys-tree.h"
58#include "openbsd-compat/sys-queue.h"
59#include <sys/wait.h>
60
61#include <errno.h>
62#include <fcntl.h>
63#include <netdb.h>
64#ifdef HAVE_PATHS_H
65#include <paths.h>
66#endif
67#include <grp.h>
68#ifdef HAVE_POLL_H
69#include <poll.h>
70#endif
71#include <pwd.h>
72#include <signal.h>
73#include <stdarg.h>
74#include <stdio.h>
75#include <stdlib.h>
76#include <string.h>
77#include <unistd.h>
78#include <limits.h>
79
80#ifdef WITH_OPENSSL
81#include <openssl/dh.h>
82#include <openssl/bn.h>
83#include <openssl/rand.h>
84#include "openbsd-compat/openssl-compat.h"
85#endif
86
87#ifdef HAVE_SECUREWARE
88#include <sys/security.h>
89#include <prot.h>
90#endif
91
92#ifdef __FreeBSD__
93#include <resolv.h>
94#if defined(GSSAPI) && defined(HAVE_GSSAPI_GSSAPI_H)
95#include <gssapi/gssapi.h>
96#elif defined(GSSAPI) && defined(HAVE_GSSAPI_H)
97#include <gssapi.h>
98#endif
99#endif
100
101#include "xmalloc.h"
102#include "ssh.h"
103#include "ssh2.h"
104#include "sshpty.h"
105#include "packet.h"
106#include "log.h"
107#include "sshbuf.h"
108#include "misc.h"
109#include "match.h"
110#include "servconf.h"
111#include "uidswap.h"
112#include "compat.h"
113#include "cipher.h"
114#include "digest.h"
115#include "sshkey.h"
116#include "kex.h"
117#include "authfile.h"
118#include "pathnames.h"
119#include "atomicio.h"
120#include "canohost.h"
121#include "hostfile.h"
122#include "auth.h"
123#include "authfd.h"
124#include "msg.h"
125#include "dispatch.h"
126#include "channels.h"
127#include "session.h"
128#include "monitor.h"
129#ifdef GSSAPI
130#include "ssh-gss.h"
131#endif
132#include "monitor_wrap.h"
133#include "ssh-sandbox.h"
134#include "auth-options.h"
135#include "version.h"
136#include "ssherr.h"
137#include "sk-api.h"
138#include "srclimit.h"
139#include "dh.h"
140#include "blacklist_client.h"
141
142#ifdef LIBWRAP
143#include <tcpd.h>
144#include <syslog.h>
145#endif /* LIBWRAP */
146
147/* Re-exec fds */
148#define REEXEC_DEVCRYPTO_RESERVED_FD	(STDERR_FILENO + 1)
149#define REEXEC_STARTUP_PIPE_FD		(STDERR_FILENO + 2)
150#define REEXEC_CONFIG_PASS_FD		(STDERR_FILENO + 3)
151#define REEXEC_MIN_FREE_FD		(STDERR_FILENO + 4)
152
153extern char *__progname;
154
155/* Server configuration options. */
156ServerOptions options;
157
158/* Name of the server configuration file. */
159char *config_file_name = _PATH_SERVER_CONFIG_FILE;
160
161/*
162 * Debug mode flag.  This can be set on the command line.  If debug
163 * mode is enabled, extra debugging output will be sent to the system
164 * log, the daemon will not go to background, and will exit after processing
165 * the first connection.
166 */
167int debug_flag = 0;
168
169/*
170 * Indicating that the daemon should only test the configuration and keys.
171 * If test_flag > 1 ("-T" flag), then sshd will also dump the effective
172 * configuration, optionally using connection information provided by the
173 * "-C" flag.
174 */
175static int test_flag = 0;
176
177/* Flag indicating that the daemon is being started from inetd. */
178static int inetd_flag = 0;
179
180/* Flag indicating that sshd should not detach and become a daemon. */
181static int no_daemon_flag = 0;
182
183/* debug goes to stderr unless inetd_flag is set */
184static int log_stderr = 0;
185
186/* Saved arguments to main(). */
187static char **saved_argv;
188static int saved_argc;
189
190/* re-exec */
191static int rexeced_flag = 0;
192static int rexec_flag = 1;
193static int rexec_argc = 0;
194static char **rexec_argv;
195
196/*
197 * The sockets that the server is listening; this is used in the SIGHUP
198 * signal handler.
199 */
200#define	MAX_LISTEN_SOCKS	16
201static int listen_socks[MAX_LISTEN_SOCKS];
202static int num_listen_socks = 0;
203
204/* Daemon's agent connection */
205int auth_sock = -1;
206static int have_agent = 0;
207
208/*
209 * Any really sensitive data in the application is contained in this
210 * structure. The idea is that this structure could be locked into memory so
211 * that the pages do not get written into swap.  However, there are some
212 * problems. The private key contains BIGNUMs, and we do not (in principle)
213 * have access to the internals of them, and locking just the structure is
214 * not very useful.  Currently, memory locking is not implemented.
215 */
216struct {
217	struct sshkey	**host_keys;		/* all private host keys */
218	struct sshkey	**host_pubkeys;		/* all public host keys */
219	struct sshkey	**host_certificates;	/* all public host certificates */
220	int		have_ssh2_key;
221} sensitive_data;
222
223/* This is set to true when a signal is received. */
224static volatile sig_atomic_t received_sighup = 0;
225static volatile sig_atomic_t received_sigterm = 0;
226
227/* record remote hostname or ip */
228u_int utmp_len = HOST_NAME_MAX+1;
229
230/*
231 * startup_pipes/flags are used for tracking children of the listening sshd
232 * process early in their lifespans. This tracking is needed for three things:
233 *
234 * 1) Implementing the MaxStartups limit of concurrent unauthenticated
235 *    connections.
236 * 2) Avoiding a race condition for SIGHUP processing, where child processes
237 *    may have listen_socks open that could collide with main listener process
238 *    after it restarts.
239 * 3) Ensuring that rexec'd sshd processes have received their initial state
240 *    from the parent listen process before handling SIGHUP.
241 *
242 * Child processes signal that they have completed closure of the listen_socks
243 * and (if applicable) received their rexec state by sending a char over their
244 * sock. Child processes signal that authentication has completed by closing
245 * the sock (or by exiting).
246 */
247static int *startup_pipes = NULL;
248static int *startup_flags = NULL;	/* Indicates child closed listener */
249static int startup_pipe = -1;		/* in child */
250
251/* variables used for privilege separation */
252int use_privsep = -1;
253struct monitor *pmonitor = NULL;
254int privsep_is_preauth = 1;
255static int privsep_chroot = 1;
256
257/* global connection state and authentication contexts */
258Authctxt *the_authctxt = NULL;
259struct ssh *the_active_state;
260
261/* global key/cert auth options. XXX move to permanent ssh->authctxt? */
262struct sshauthopt *auth_opts = NULL;
263
264/* sshd_config buffer */
265struct sshbuf *cfg;
266
267/* Included files from the configuration file */
268struct include_list includes = TAILQ_HEAD_INITIALIZER(includes);
269
270/* message to be displayed after login */
271struct sshbuf *loginmsg;
272
273/* Unprivileged user */
274struct passwd *privsep_pw = NULL;
275
276/* Prototypes for various functions defined later in this file. */
277void destroy_sensitive_data(void);
278void demote_sensitive_data(void);
279static void do_ssh2_kex(struct ssh *);
280
281static char *listener_proctitle;
282
283/*
284 * Close all listening sockets
285 */
286static void
287close_listen_socks(void)
288{
289	int i;
290
291	for (i = 0; i < num_listen_socks; i++)
292		close(listen_socks[i]);
293	num_listen_socks = 0;
294}
295
296static void
297close_startup_pipes(void)
298{
299	int i;
300
301	if (startup_pipes)
302		for (i = 0; i < options.max_startups; i++)
303			if (startup_pipes[i] != -1)
304				close(startup_pipes[i]);
305}
306
307/*
308 * Signal handler for SIGHUP.  Sshd execs itself when it receives SIGHUP;
309 * the effect is to reread the configuration file (and to regenerate
310 * the server key).
311 */
312
313static void
314sighup_handler(int sig)
315{
316	received_sighup = 1;
317}
318
319/*
320 * Called from the main program after receiving SIGHUP.
321 * Restarts the server.
322 */
323static void
324sighup_restart(void)
325{
326	logit("Received SIGHUP; restarting.");
327	if (options.pid_file != NULL)
328		unlink(options.pid_file);
329	platform_pre_restart();
330	close_listen_socks();
331	close_startup_pipes();
332	ssh_signal(SIGHUP, SIG_IGN); /* will be restored after exec */
333	execv(saved_argv[0], saved_argv);
334	logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
335	    strerror(errno));
336	exit(1);
337}
338
339/*
340 * Generic signal handler for terminating signals in the master daemon.
341 */
342static void
343sigterm_handler(int sig)
344{
345	received_sigterm = sig;
346}
347
348/*
349 * SIGCHLD handler.  This is called whenever a child dies.  This will then
350 * reap any zombies left by exited children.
351 */
352static void
353main_sigchld_handler(int sig)
354{
355	int save_errno = errno;
356	pid_t pid;
357	int status;
358
359	while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
360	    (pid == -1 && errno == EINTR))
361		;
362	errno = save_errno;
363}
364
365/*
366 * Signal handler for the alarm after the login grace period has expired.
367 */
368static void
369grace_alarm_handler(int sig)
370{
371	/*
372	 * Try to kill any processes that we have spawned, E.g. authorized
373	 * keys command helpers or privsep children.
374	 */
375	if (getpgid(0) == getpid()) {
376		ssh_signal(SIGTERM, SIG_IGN);
377		kill(0, SIGTERM);
378	}
379
380	BLACKLIST_NOTIFY(the_active_state, BLACKLIST_AUTH_FAIL, "ssh");
381
382	/* Log error and exit. */
383	sigdie("Timeout before authentication for %s port %d",
384	    ssh_remote_ipaddr(the_active_state),
385	    ssh_remote_port(the_active_state));
386}
387
388/* Destroy the host and server keys.  They will no longer be needed. */
389void
390destroy_sensitive_data(void)
391{
392	u_int i;
393
394	for (i = 0; i < options.num_host_key_files; i++) {
395		if (sensitive_data.host_keys[i]) {
396			sshkey_free(sensitive_data.host_keys[i]);
397			sensitive_data.host_keys[i] = NULL;
398		}
399		if (sensitive_data.host_certificates[i]) {
400			sshkey_free(sensitive_data.host_certificates[i]);
401			sensitive_data.host_certificates[i] = NULL;
402		}
403	}
404}
405
406/* Demote private to public keys for network child */
407void
408demote_sensitive_data(void)
409{
410	struct sshkey *tmp;
411	u_int i;
412	int r;
413
414	for (i = 0; i < options.num_host_key_files; i++) {
415		if (sensitive_data.host_keys[i]) {
416			if ((r = sshkey_from_private(
417			    sensitive_data.host_keys[i], &tmp)) != 0)
418				fatal_r(r, "could not demote host %s key",
419				    sshkey_type(sensitive_data.host_keys[i]));
420			sshkey_free(sensitive_data.host_keys[i]);
421			sensitive_data.host_keys[i] = tmp;
422		}
423		/* Certs do not need demotion */
424	}
425}
426
427static void
428reseed_prngs(void)
429{
430	u_int32_t rnd[256];
431
432#ifdef WITH_OPENSSL
433	RAND_poll();
434#endif
435	arc4random_stir(); /* noop on recent arc4random() implementations */
436	arc4random_buf(rnd, sizeof(rnd)); /* let arc4random notice PID change */
437
438#ifdef WITH_OPENSSL
439	RAND_seed(rnd, sizeof(rnd));
440	/* give libcrypto a chance to notice the PID change */
441	if ((RAND_bytes((u_char *)rnd, 1)) != 1)
442		fatal("%s: RAND_bytes failed", __func__);
443#endif
444
445	explicit_bzero(rnd, sizeof(rnd));
446}
447
448static void
449privsep_preauth_child(void)
450{
451	gid_t gidset[1];
452
453	/* Enable challenge-response authentication for privilege separation */
454	privsep_challenge_enable();
455
456#ifdef GSSAPI
457	/* Cache supported mechanism OIDs for later use */
458	ssh_gssapi_prepare_supported_oids();
459#endif
460
461	reseed_prngs();
462
463	/* Demote the private keys to public keys. */
464	demote_sensitive_data();
465
466	/* Demote the child */
467	if (privsep_chroot) {
468		/* Change our root directory */
469		if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
470			fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
471			    strerror(errno));
472		if (chdir("/") == -1)
473			fatal("chdir(\"/\"): %s", strerror(errno));
474
475		/* Drop our privileges */
476		debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
477		    (u_int)privsep_pw->pw_gid);
478		gidset[0] = privsep_pw->pw_gid;
479		if (setgroups(1, gidset) == -1)
480			fatal("setgroups: %.100s", strerror(errno));
481		permanently_set_uid(privsep_pw);
482	}
483}
484
485static int
486privsep_preauth(struct ssh *ssh)
487{
488	int status, r;
489	pid_t pid;
490	struct ssh_sandbox *box = NULL;
491
492	/* Set up unprivileged child process to deal with network data */
493	pmonitor = monitor_init();
494	/* Store a pointer to the kex for later rekeying */
495	pmonitor->m_pkex = &ssh->kex;
496
497	if (use_privsep == PRIVSEP_ON)
498		box = ssh_sandbox_init(pmonitor);
499	pid = fork();
500	if (pid == -1) {
501		fatal("fork of unprivileged child failed");
502	} else if (pid != 0) {
503		debug2("Network child is on pid %ld", (long)pid);
504
505		pmonitor->m_pid = pid;
506		if (have_agent) {
507			r = ssh_get_authentication_socket(&auth_sock);
508			if (r != 0) {
509				error_r(r, "Could not get agent socket");
510				have_agent = 0;
511			}
512		}
513		if (box != NULL)
514			ssh_sandbox_parent_preauth(box, pid);
515		monitor_child_preauth(ssh, pmonitor);
516
517		/* Wait for the child's exit status */
518		while (waitpid(pid, &status, 0) == -1) {
519			if (errno == EINTR)
520				continue;
521			pmonitor->m_pid = -1;
522			fatal_f("waitpid: %s", strerror(errno));
523		}
524		privsep_is_preauth = 0;
525		pmonitor->m_pid = -1;
526		if (WIFEXITED(status)) {
527			if (WEXITSTATUS(status) != 0)
528				fatal_f("preauth child exited with status %d",
529				    WEXITSTATUS(status));
530		} else if (WIFSIGNALED(status))
531			fatal_f("preauth child terminated by signal %d",
532			    WTERMSIG(status));
533		if (box != NULL)
534			ssh_sandbox_parent_finish(box);
535		return 1;
536	} else {
537		/* child */
538		close(pmonitor->m_sendfd);
539		close(pmonitor->m_log_recvfd);
540
541		/* Arrange for logging to be sent to the monitor */
542		set_log_handler(mm_log_handler, pmonitor);
543
544		privsep_preauth_child();
545		setproctitle("%s", "[net]");
546		if (box != NULL)
547			ssh_sandbox_child(box);
548
549		return 0;
550	}
551}
552
553static void
554privsep_postauth(struct ssh *ssh, Authctxt *authctxt)
555{
556#ifdef DISABLE_FD_PASSING
557	if (1) {
558#else
559	if (authctxt->pw->pw_uid == 0) {
560#endif
561		/* File descriptor passing is broken or root login */
562		use_privsep = 0;
563		goto skip;
564	}
565
566	/* New socket pair */
567	monitor_reinit(pmonitor);
568
569	pmonitor->m_pid = fork();
570	if (pmonitor->m_pid == -1)
571		fatal("fork of unprivileged child failed");
572	else if (pmonitor->m_pid != 0) {
573		verbose("User child is on pid %ld", (long)pmonitor->m_pid);
574		sshbuf_reset(loginmsg);
575		monitor_clear_keystate(ssh, pmonitor);
576		monitor_child_postauth(ssh, pmonitor);
577
578		/* NEVERREACHED */
579		exit(0);
580	}
581
582	/* child */
583
584	close(pmonitor->m_sendfd);
585	pmonitor->m_sendfd = -1;
586
587	/* Demote the private keys to public keys. */
588	demote_sensitive_data();
589
590	reseed_prngs();
591
592	/* Drop privileges */
593	do_setusercontext(authctxt->pw);
594
595 skip:
596	/* It is safe now to apply the key state */
597	monitor_apply_keystate(ssh, pmonitor);
598
599	/*
600	 * Tell the packet layer that authentication was successful, since
601	 * this information is not part of the key state.
602	 */
603	ssh_packet_set_authenticated(ssh);
604}
605
606static void
607append_hostkey_type(struct sshbuf *b, const char *s)
608{
609	int r;
610
611	if (match_pattern_list(s, options.hostkeyalgorithms, 0) != 1) {
612		debug3_f("%s key not permitted by HostkeyAlgorithms", s);
613		return;
614	}
615	if ((r = sshbuf_putf(b, "%s%s", sshbuf_len(b) > 0 ? "," : "", s)) != 0)
616		fatal_fr(r, "sshbuf_putf");
617}
618
619static char *
620list_hostkey_types(void)
621{
622	struct sshbuf *b;
623	struct sshkey *key;
624	char *ret;
625	u_int i;
626
627	if ((b = sshbuf_new()) == NULL)
628		fatal_f("sshbuf_new failed");
629	for (i = 0; i < options.num_host_key_files; i++) {
630		key = sensitive_data.host_keys[i];
631		if (key == NULL)
632			key = sensitive_data.host_pubkeys[i];
633		if (key == NULL)
634			continue;
635		switch (key->type) {
636		case KEY_RSA:
637			/* for RSA we also support SHA2 signatures */
638			append_hostkey_type(b, "rsa-sha2-512");
639			append_hostkey_type(b, "rsa-sha2-256");
640			/* FALLTHROUGH */
641		case KEY_DSA:
642		case KEY_ECDSA:
643		case KEY_ED25519:
644		case KEY_ECDSA_SK:
645		case KEY_ED25519_SK:
646		case KEY_XMSS:
647			append_hostkey_type(b, sshkey_ssh_name(key));
648			break;
649		}
650		/* If the private key has a cert peer, then list that too */
651		key = sensitive_data.host_certificates[i];
652		if (key == NULL)
653			continue;
654		switch (key->type) {
655		case KEY_RSA_CERT:
656			/* for RSA we also support SHA2 signatures */
657			append_hostkey_type(b,
658			    "rsa-sha2-512-cert-v01@openssh.com");
659			append_hostkey_type(b,
660			    "rsa-sha2-256-cert-v01@openssh.com");
661			/* FALLTHROUGH */
662		case KEY_DSA_CERT:
663		case KEY_ECDSA_CERT:
664		case KEY_ED25519_CERT:
665		case KEY_ECDSA_SK_CERT:
666		case KEY_ED25519_SK_CERT:
667		case KEY_XMSS_CERT:
668			append_hostkey_type(b, sshkey_ssh_name(key));
669			break;
670		}
671	}
672	if ((ret = sshbuf_dup_string(b)) == NULL)
673		fatal_f("sshbuf_dup_string failed");
674	sshbuf_free(b);
675	debug_f("%s", ret);
676	return ret;
677}
678
679static struct sshkey *
680get_hostkey_by_type(int type, int nid, int need_private, struct ssh *ssh)
681{
682	u_int i;
683	struct sshkey *key;
684
685	for (i = 0; i < options.num_host_key_files; i++) {
686		switch (type) {
687		case KEY_RSA_CERT:
688		case KEY_DSA_CERT:
689		case KEY_ECDSA_CERT:
690		case KEY_ED25519_CERT:
691		case KEY_ECDSA_SK_CERT:
692		case KEY_ED25519_SK_CERT:
693		case KEY_XMSS_CERT:
694			key = sensitive_data.host_certificates[i];
695			break;
696		default:
697			key = sensitive_data.host_keys[i];
698			if (key == NULL && !need_private)
699				key = sensitive_data.host_pubkeys[i];
700			break;
701		}
702		if (key == NULL || key->type != type)
703			continue;
704		switch (type) {
705		case KEY_ECDSA:
706		case KEY_ECDSA_SK:
707		case KEY_ECDSA_CERT:
708		case KEY_ECDSA_SK_CERT:
709			if (key->ecdsa_nid != nid)
710				continue;
711			/* FALLTHROUGH */
712		default:
713			return need_private ?
714			    sensitive_data.host_keys[i] : key;
715		}
716	}
717	return NULL;
718}
719
720struct sshkey *
721get_hostkey_public_by_type(int type, int nid, struct ssh *ssh)
722{
723	return get_hostkey_by_type(type, nid, 0, ssh);
724}
725
726struct sshkey *
727get_hostkey_private_by_type(int type, int nid, struct ssh *ssh)
728{
729	return get_hostkey_by_type(type, nid, 1, ssh);
730}
731
732struct sshkey *
733get_hostkey_by_index(int ind)
734{
735	if (ind < 0 || (u_int)ind >= options.num_host_key_files)
736		return (NULL);
737	return (sensitive_data.host_keys[ind]);
738}
739
740struct sshkey *
741get_hostkey_public_by_index(int ind, struct ssh *ssh)
742{
743	if (ind < 0 || (u_int)ind >= options.num_host_key_files)
744		return (NULL);
745	return (sensitive_data.host_pubkeys[ind]);
746}
747
748int
749get_hostkey_index(struct sshkey *key, int compare, struct ssh *ssh)
750{
751	u_int i;
752
753	for (i = 0; i < options.num_host_key_files; i++) {
754		if (sshkey_is_cert(key)) {
755			if (key == sensitive_data.host_certificates[i] ||
756			    (compare && sensitive_data.host_certificates[i] &&
757			    sshkey_equal(key,
758			    sensitive_data.host_certificates[i])))
759				return (i);
760		} else {
761			if (key == sensitive_data.host_keys[i] ||
762			    (compare && sensitive_data.host_keys[i] &&
763			    sshkey_equal(key, sensitive_data.host_keys[i])))
764				return (i);
765			if (key == sensitive_data.host_pubkeys[i] ||
766			    (compare && sensitive_data.host_pubkeys[i] &&
767			    sshkey_equal(key, sensitive_data.host_pubkeys[i])))
768				return (i);
769		}
770	}
771	return (-1);
772}
773
774/* Inform the client of all hostkeys */
775static void
776notify_hostkeys(struct ssh *ssh)
777{
778	struct sshbuf *buf;
779	struct sshkey *key;
780	u_int i, nkeys;
781	int r;
782	char *fp;
783
784	/* Some clients cannot cope with the hostkeys message, skip those. */
785	if (ssh->compat & SSH_BUG_HOSTKEYS)
786		return;
787
788	if ((buf = sshbuf_new()) == NULL)
789		fatal_f("sshbuf_new");
790	for (i = nkeys = 0; i < options.num_host_key_files; i++) {
791		key = get_hostkey_public_by_index(i, ssh);
792		if (key == NULL || key->type == KEY_UNSPEC ||
793		    sshkey_is_cert(key))
794			continue;
795		fp = sshkey_fingerprint(key, options.fingerprint_hash,
796		    SSH_FP_DEFAULT);
797		debug3_f("key %d: %s %s", i, sshkey_ssh_name(key), fp);
798		free(fp);
799		if (nkeys == 0) {
800			/*
801			 * Start building the request when we find the
802			 * first usable key.
803			 */
804			if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
805			    (r = sshpkt_put_cstring(ssh, "hostkeys-00@openssh.com")) != 0 ||
806			    (r = sshpkt_put_u8(ssh, 0)) != 0) /* want reply */
807				sshpkt_fatal(ssh, r, "%s: start request", __func__);
808		}
809		/* Append the key to the request */
810		sshbuf_reset(buf);
811		if ((r = sshkey_putb(key, buf)) != 0)
812			fatal_fr(r, "couldn't put hostkey %d", i);
813		if ((r = sshpkt_put_stringb(ssh, buf)) != 0)
814			sshpkt_fatal(ssh, r, "%s: append key", __func__);
815		nkeys++;
816	}
817	debug3_f("sent %u hostkeys", nkeys);
818	if (nkeys == 0)
819		fatal_f("no hostkeys");
820	if ((r = sshpkt_send(ssh)) != 0)
821		sshpkt_fatal(ssh, r, "%s: send", __func__);
822	sshbuf_free(buf);
823}
824
825/*
826 * returns 1 if connection should be dropped, 0 otherwise.
827 * dropping starts at connection #max_startups_begin with a probability
828 * of (max_startups_rate/100). the probability increases linearly until
829 * all connections are dropped for startups > max_startups
830 */
831static int
832should_drop_connection(int startups)
833{
834	int p, r;
835
836	if (startups < options.max_startups_begin)
837		return 0;
838	if (startups >= options.max_startups)
839		return 1;
840	if (options.max_startups_rate == 100)
841		return 1;
842
843	p  = 100 - options.max_startups_rate;
844	p *= startups - options.max_startups_begin;
845	p /= options.max_startups - options.max_startups_begin;
846	p += options.max_startups_rate;
847	r = arc4random_uniform(100);
848
849	debug_f("p %d, r %d", p, r);
850	return (r < p) ? 1 : 0;
851}
852
853/*
854 * Check whether connection should be accepted by MaxStartups.
855 * Returns 0 if the connection is accepted. If the connection is refused,
856 * returns 1 and attempts to send notification to client.
857 * Logs when the MaxStartups condition is entered or exited, and periodically
858 * while in that state.
859 */
860static int
861drop_connection(int sock, int startups, int notify_pipe)
862{
863	char *laddr, *raddr;
864	const char msg[] = "Exceeded MaxStartups\r\n";
865	static time_t last_drop, first_drop;
866	static u_int ndropped;
867	LogLevel drop_level = SYSLOG_LEVEL_VERBOSE;
868	time_t now;
869
870	now = monotime();
871	if (!should_drop_connection(startups) &&
872	    srclimit_check_allow(sock, notify_pipe) == 1) {
873		if (last_drop != 0 &&
874		    startups < options.max_startups_begin - 1) {
875			/* XXX maybe need better hysteresis here */
876			logit("exited MaxStartups throttling after %s, "
877			    "%u connections dropped",
878			    fmt_timeframe(now - first_drop), ndropped);
879			last_drop = 0;
880		}
881		return 0;
882	}
883
884#define SSHD_MAXSTARTUPS_LOG_INTERVAL	(5 * 60)
885	if (last_drop == 0) {
886		error("beginning MaxStartups throttling");
887		drop_level = SYSLOG_LEVEL_INFO;
888		first_drop = now;
889		ndropped = 0;
890	} else if (last_drop + SSHD_MAXSTARTUPS_LOG_INTERVAL < now) {
891		/* Periodic logs */
892		error("in MaxStartups throttling for %s, "
893		    "%u connections dropped",
894		    fmt_timeframe(now - first_drop), ndropped + 1);
895		drop_level = SYSLOG_LEVEL_INFO;
896	}
897	last_drop = now;
898	ndropped++;
899
900	laddr = get_local_ipaddr(sock);
901	raddr = get_peer_ipaddr(sock);
902	do_log2(drop_level, "drop connection #%d from [%s]:%d on [%s]:%d "
903	    "past MaxStartups", startups, raddr, get_peer_port(sock),
904	    laddr, get_local_port(sock));
905	free(laddr);
906	free(raddr);
907	/* best-effort notification to client */
908	(void)write(sock, msg, sizeof(msg) - 1);
909	return 1;
910}
911
912static void
913usage(void)
914{
915	if (options.version_addendum != NULL &&
916	    *options.version_addendum != '\0')
917		fprintf(stderr, "%s %s, %s\n",
918		    SSH_RELEASE,
919		    options.version_addendum, SSH_OPENSSL_VERSION);
920	else
921		fprintf(stderr, "%s, %s\n",
922		    SSH_RELEASE, SSH_OPENSSL_VERSION);
923	fprintf(stderr,
924"usage: sshd [-46DdeGiqTtV] [-C connection_spec] [-c host_cert_file]\n"
925"            [-E log_file] [-f config_file] [-g login_grace_time]\n"
926"            [-h host_key_file] [-o option] [-p port] [-u len]\n"
927	);
928	exit(1);
929}
930
931static void
932send_rexec_state(int fd, struct sshbuf *conf)
933{
934	struct sshbuf *m = NULL, *inc = NULL;
935	struct include_item *item = NULL;
936	int r;
937
938	debug3_f("entering fd = %d config len %zu", fd,
939	    sshbuf_len(conf));
940
941	if ((m = sshbuf_new()) == NULL || (inc = sshbuf_new()) == NULL)
942		fatal_f("sshbuf_new failed");
943
944	/* pack includes into a string */
945	TAILQ_FOREACH(item, &includes, entry) {
946		if ((r = sshbuf_put_cstring(inc, item->selector)) != 0 ||
947		    (r = sshbuf_put_cstring(inc, item->filename)) != 0 ||
948		    (r = sshbuf_put_stringb(inc, item->contents)) != 0)
949			fatal_fr(r, "compose includes");
950	}
951
952	/*
953	 * Protocol from reexec master to child:
954	 *	string	configuration
955	 *	string	included_files[] {
956	 *		string	selector
957	 *		string	filename
958	 *		string	contents
959	 *	}
960	 */
961	if ((r = sshbuf_put_stringb(m, conf)) != 0 ||
962	    (r = sshbuf_put_stringb(m, inc)) != 0)
963		fatal_fr(r, "compose config");
964	if (ssh_msg_send(fd, 0, m) == -1)
965		error_f("ssh_msg_send failed");
966
967	sshbuf_free(m);
968	sshbuf_free(inc);
969
970	debug3_f("done");
971}
972
973static void
974recv_rexec_state(int fd, struct sshbuf *conf)
975{
976	struct sshbuf *m, *inc;
977	u_char *cp, ver;
978	size_t len;
979	int r;
980	struct include_item *item;
981
982	debug3_f("entering fd = %d", fd);
983
984	if ((m = sshbuf_new()) == NULL || (inc = sshbuf_new()) == NULL)
985		fatal_f("sshbuf_new failed");
986	if (ssh_msg_recv(fd, m) == -1)
987		fatal_f("ssh_msg_recv failed");
988	if ((r = sshbuf_get_u8(m, &ver)) != 0)
989		fatal_fr(r, "parse version");
990	if (ver != 0)
991		fatal_f("rexec version mismatch");
992	if ((r = sshbuf_get_string(m, &cp, &len)) != 0 ||
993	    (r = sshbuf_get_stringb(m, inc)) != 0)
994		fatal_fr(r, "parse config");
995
996	if (conf != NULL && (r = sshbuf_put(conf, cp, len)))
997		fatal_fr(r, "sshbuf_put");
998
999	while (sshbuf_len(inc) != 0) {
1000		item = xcalloc(1, sizeof(*item));
1001		if ((item->contents = sshbuf_new()) == NULL)
1002			fatal_f("sshbuf_new failed");
1003		if ((r = sshbuf_get_cstring(inc, &item->selector, NULL)) != 0 ||
1004		    (r = sshbuf_get_cstring(inc, &item->filename, NULL)) != 0 ||
1005		    (r = sshbuf_get_stringb(inc, item->contents)) != 0)
1006			fatal_fr(r, "parse includes");
1007		TAILQ_INSERT_TAIL(&includes, item, entry);
1008	}
1009
1010	free(cp);
1011	sshbuf_free(m);
1012
1013	debug3_f("done");
1014}
1015
1016/* Accept a connection from inetd */
1017static void
1018server_accept_inetd(int *sock_in, int *sock_out)
1019{
1020	if (rexeced_flag) {
1021		close(REEXEC_CONFIG_PASS_FD);
1022		*sock_in = *sock_out = dup(STDIN_FILENO);
1023	} else {
1024		*sock_in = dup(STDIN_FILENO);
1025		*sock_out = dup(STDOUT_FILENO);
1026	}
1027	/*
1028	 * We intentionally do not close the descriptors 0, 1, and 2
1029	 * as our code for setting the descriptors won't work if
1030	 * ttyfd happens to be one of those.
1031	 */
1032	if (stdfd_devnull(1, 1, !log_stderr) == -1)
1033		error_f("stdfd_devnull failed");
1034	debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
1035}
1036
1037/*
1038 * Listen for TCP connections
1039 */
1040static void
1041listen_on_addrs(struct listenaddr *la)
1042{
1043	int ret, listen_sock;
1044	struct addrinfo *ai;
1045	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1046
1047	for (ai = la->addrs; ai; ai = ai->ai_next) {
1048		if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1049			continue;
1050		if (num_listen_socks >= MAX_LISTEN_SOCKS)
1051			fatal("Too many listen sockets. "
1052			    "Enlarge MAX_LISTEN_SOCKS");
1053		if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1054		    ntop, sizeof(ntop), strport, sizeof(strport),
1055		    NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1056			error("getnameinfo failed: %.100s",
1057			    ssh_gai_strerror(ret));
1058			continue;
1059		}
1060		/* Create socket for listening. */
1061		listen_sock = socket(ai->ai_family, ai->ai_socktype,
1062		    ai->ai_protocol);
1063		if (listen_sock == -1) {
1064			/* kernel may not support ipv6 */
1065			verbose("socket: %.100s", strerror(errno));
1066			continue;
1067		}
1068		if (set_nonblock(listen_sock) == -1) {
1069			close(listen_sock);
1070			continue;
1071		}
1072		if (fcntl(listen_sock, F_SETFD, FD_CLOEXEC) == -1) {
1073			verbose("socket: CLOEXEC: %s", strerror(errno));
1074			close(listen_sock);
1075			continue;
1076		}
1077		/* Socket options */
1078		set_reuseaddr(listen_sock);
1079		if (la->rdomain != NULL &&
1080		    set_rdomain(listen_sock, la->rdomain) == -1) {
1081			close(listen_sock);
1082			continue;
1083		}
1084
1085		/* Only communicate in IPv6 over AF_INET6 sockets. */
1086		if (ai->ai_family == AF_INET6)
1087			sock_set_v6only(listen_sock);
1088
1089		debug("Bind to port %s on %s.", strport, ntop);
1090
1091		/* Bind the socket to the desired port. */
1092		if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) == -1) {
1093			error("Bind to port %s on %s failed: %.200s.",
1094			    strport, ntop, strerror(errno));
1095			close(listen_sock);
1096			continue;
1097		}
1098		listen_socks[num_listen_socks] = listen_sock;
1099		num_listen_socks++;
1100
1101		/* Start listening on the port. */
1102		if (listen(listen_sock, SSH_LISTEN_BACKLOG) == -1)
1103			fatal("listen on [%s]:%s: %.100s",
1104			    ntop, strport, strerror(errno));
1105		logit("Server listening on %s port %s%s%s.",
1106		    ntop, strport,
1107		    la->rdomain == NULL ? "" : " rdomain ",
1108		    la->rdomain == NULL ? "" : la->rdomain);
1109	}
1110}
1111
1112static void
1113server_listen(void)
1114{
1115	u_int i;
1116
1117	/* Initialise per-source limit tracking. */
1118	srclimit_init(options.max_startups, options.per_source_max_startups,
1119	    options.per_source_masklen_ipv4, options.per_source_masklen_ipv6);
1120
1121	for (i = 0; i < options.num_listen_addrs; i++) {
1122		listen_on_addrs(&options.listen_addrs[i]);
1123		freeaddrinfo(options.listen_addrs[i].addrs);
1124		free(options.listen_addrs[i].rdomain);
1125		memset(&options.listen_addrs[i], 0,
1126		    sizeof(options.listen_addrs[i]));
1127	}
1128	free(options.listen_addrs);
1129	options.listen_addrs = NULL;
1130	options.num_listen_addrs = 0;
1131
1132	if (!num_listen_socks)
1133		fatal("Cannot bind any address.");
1134}
1135
1136/*
1137 * The main TCP accept loop. Note that, for the non-debug case, returns
1138 * from this function are in a forked subprocess.
1139 */
1140static void
1141server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1142{
1143	struct pollfd *pfd = NULL;
1144	int i, j, ret, npfd;
1145	int ostartups = -1, startups = 0, listening = 0, lameduck = 0;
1146	int startup_p[2] = { -1 , -1 }, *startup_pollfd;
1147	char c = 0;
1148	struct sockaddr_storage from;
1149	socklen_t fromlen;
1150	pid_t pid;
1151	u_char rnd[256];
1152	sigset_t nsigset, osigset;
1153#ifdef LIBWRAP
1154	struct request_info req;
1155
1156	request_init(&req, RQ_DAEMON, __progname, 0);
1157#endif
1158
1159	/* pipes connected to unauthenticated child sshd processes */
1160	startup_pipes = xcalloc(options.max_startups, sizeof(int));
1161	startup_flags = xcalloc(options.max_startups, sizeof(int));
1162	startup_pollfd = xcalloc(options.max_startups, sizeof(int));
1163	for (i = 0; i < options.max_startups; i++)
1164		startup_pipes[i] = -1;
1165
1166	/*
1167	 * Prepare signal mask that we use to block signals that might set
1168	 * received_sigterm or received_sighup, so that we are guaranteed
1169	 * to immediately wake up the ppoll if a signal is received after
1170	 * the flag is checked.
1171	 */
1172	sigemptyset(&nsigset);
1173	sigaddset(&nsigset, SIGHUP);
1174	sigaddset(&nsigset, SIGCHLD);
1175	sigaddset(&nsigset, SIGTERM);
1176	sigaddset(&nsigset, SIGQUIT);
1177
1178	/* sized for worst-case */
1179	pfd = xcalloc(num_listen_socks + options.max_startups,
1180	    sizeof(struct pollfd));
1181
1182	/*
1183	 * Stay listening for connections until the system crashes or
1184	 * the daemon is killed with a signal.
1185	 */
1186	for (;;) {
1187		sigprocmask(SIG_BLOCK, &nsigset, &osigset);
1188		if (received_sigterm) {
1189			logit("Received signal %d; terminating.",
1190			    (int) received_sigterm);
1191			close_listen_socks();
1192			if (options.pid_file != NULL)
1193				unlink(options.pid_file);
1194			exit(received_sigterm == SIGTERM ? 0 : 255);
1195		}
1196		if (ostartups != startups) {
1197			setproctitle("%s [listener] %d of %d-%d startups",
1198			    listener_proctitle, startups,
1199			    options.max_startups_begin, options.max_startups);
1200			ostartups = startups;
1201		}
1202		if (received_sighup) {
1203			if (!lameduck) {
1204				debug("Received SIGHUP; waiting for children");
1205				close_listen_socks();
1206				lameduck = 1;
1207			}
1208			if (listening <= 0) {
1209				sigprocmask(SIG_SETMASK, &osigset, NULL);
1210				sighup_restart();
1211			}
1212		}
1213
1214		for (i = 0; i < num_listen_socks; i++) {
1215			pfd[i].fd = listen_socks[i];
1216			pfd[i].events = POLLIN;
1217		}
1218		npfd = num_listen_socks;
1219		for (i = 0; i < options.max_startups; i++) {
1220			startup_pollfd[i] = -1;
1221			if (startup_pipes[i] != -1) {
1222				pfd[npfd].fd = startup_pipes[i];
1223				pfd[npfd].events = POLLIN;
1224				startup_pollfd[i] = npfd++;
1225			}
1226		}
1227
1228		/* Wait until a connection arrives or a child exits. */
1229		ret = ppoll(pfd, npfd, NULL, &osigset);
1230		if (ret == -1 && errno != EINTR) {
1231			error("ppoll: %.100s", strerror(errno));
1232			if (errno == EINVAL)
1233				cleanup_exit(1); /* can't recover */
1234		}
1235		sigprocmask(SIG_SETMASK, &osigset, NULL);
1236		if (ret == -1)
1237			continue;
1238
1239		for (i = 0; i < options.max_startups; i++) {
1240			if (startup_pipes[i] == -1 ||
1241			    startup_pollfd[i] == -1 ||
1242			    !(pfd[startup_pollfd[i]].revents & (POLLIN|POLLHUP)))
1243				continue;
1244			switch (read(startup_pipes[i], &c, sizeof(c))) {
1245			case -1:
1246				if (errno == EINTR || errno == EAGAIN)
1247					continue;
1248				if (errno != EPIPE) {
1249					error_f("startup pipe %d (fd=%d): "
1250					    "read %s", i, startup_pipes[i],
1251					    strerror(errno));
1252				}
1253				/* FALLTHROUGH */
1254			case 0:
1255				/* child exited or completed auth */
1256				close(startup_pipes[i]);
1257				srclimit_done(startup_pipes[i]);
1258				startup_pipes[i] = -1;
1259				startups--;
1260				if (startup_flags[i])
1261					listening--;
1262				break;
1263			case 1:
1264				/* child has finished preliminaries */
1265				if (startup_flags[i]) {
1266					listening--;
1267					startup_flags[i] = 0;
1268				}
1269				break;
1270			}
1271		}
1272		for (i = 0; i < num_listen_socks; i++) {
1273			if (!(pfd[i].revents & POLLIN))
1274				continue;
1275			fromlen = sizeof(from);
1276			*newsock = accept(listen_socks[i],
1277			    (struct sockaddr *)&from, &fromlen);
1278			if (*newsock == -1) {
1279				if (errno != EINTR && errno != EWOULDBLOCK &&
1280				    errno != ECONNABORTED && errno != EAGAIN)
1281					error("accept: %.100s",
1282					    strerror(errno));
1283				if (errno == EMFILE || errno == ENFILE)
1284					usleep(100 * 1000);
1285				continue;
1286			}
1287#ifdef LIBWRAP
1288			/* Check whether logins are denied from this host. */
1289			request_set(&req, RQ_FILE, *newsock,
1290			    RQ_CLIENT_NAME, "", RQ_CLIENT_ADDR, "", 0);
1291			sock_host(&req);
1292			if (!hosts_access(&req)) {
1293				const struct linger l = { .l_onoff = 1,
1294				    .l_linger  = 0 };
1295
1296				(void )setsockopt(*newsock, SOL_SOCKET,
1297				    SO_LINGER, &l, sizeof(l));
1298				(void )close(*newsock);
1299				/*
1300				 * Mimic message from libwrap's refuse() as
1301				 * precisely as we can afford.  The authentic
1302				 * message prints the IP address and the
1303				 * hostname it resolves to in parentheses.  If
1304				 * the IP address cannot be resolved to a
1305				 * hostname, the IP address will be repeated
1306				 * in parentheses.  As name resolution in the
1307				 * main server loop could stall, and logging
1308				 * resolved names adds little or no value to
1309				 * incident investigation, this implementation
1310				 * only repeats the IP address in parentheses.
1311				 * This should resemble librwap's refuse()
1312				 * closely enough not to break auditing
1313				 * software like sshguard or custom scripts.
1314				 */
1315				syslog(LOG_WARNING,
1316				    "refused connect from %s (%s)",
1317				    eval_hostaddr(req.client),
1318				    eval_hostaddr(req.client));
1319				debug("Connection refused by tcp wrapper");
1320				continue;
1321			}
1322#endif /* LIBWRAP */
1323			if (unset_nonblock(*newsock) == -1) {
1324				close(*newsock);
1325				continue;
1326			}
1327			if (pipe(startup_p) == -1) {
1328				error_f("pipe(startup_p): %s", strerror(errno));
1329				close(*newsock);
1330				continue;
1331			}
1332			if (drop_connection(*newsock, startups, startup_p[0])) {
1333				close(*newsock);
1334				close(startup_p[0]);
1335				close(startup_p[1]);
1336				continue;
1337			}
1338
1339			if (rexec_flag && socketpair(AF_UNIX,
1340			    SOCK_STREAM, 0, config_s) == -1) {
1341				error("reexec socketpair: %s",
1342				    strerror(errno));
1343				close(*newsock);
1344				close(startup_p[0]);
1345				close(startup_p[1]);
1346				continue;
1347			}
1348
1349			for (j = 0; j < options.max_startups; j++)
1350				if (startup_pipes[j] == -1) {
1351					startup_pipes[j] = startup_p[0];
1352					startups++;
1353					startup_flags[j] = 1;
1354					break;
1355				}
1356
1357			/*
1358			 * Got connection.  Fork a child to handle it, unless
1359			 * we are in debugging mode.
1360			 */
1361			if (debug_flag) {
1362				/*
1363				 * In debugging mode.  Close the listening
1364				 * socket, and start processing the
1365				 * connection without forking.
1366				 */
1367				debug("Server will not fork when running in debugging mode.");
1368				close_listen_socks();
1369				*sock_in = *newsock;
1370				*sock_out = *newsock;
1371				close(startup_p[0]);
1372				close(startup_p[1]);
1373				startup_pipe = -1;
1374				pid = getpid();
1375				if (rexec_flag) {
1376					send_rexec_state(config_s[0], cfg);
1377					close(config_s[0]);
1378				}
1379				free(pfd);
1380				return;
1381			}
1382
1383			/*
1384			 * Normal production daemon.  Fork, and have
1385			 * the child process the connection. The
1386			 * parent continues listening.
1387			 */
1388			platform_pre_fork();
1389			listening++;
1390			if ((pid = fork()) == 0) {
1391				/*
1392				 * Child.  Close the listening and
1393				 * max_startup sockets.  Start using
1394				 * the accepted socket. Reinitialize
1395				 * logging (since our pid has changed).
1396				 * We return from this function to handle
1397				 * the connection.
1398				 */
1399				platform_post_fork_child();
1400				startup_pipe = startup_p[1];
1401				close_startup_pipes();
1402				close_listen_socks();
1403				*sock_in = *newsock;
1404				*sock_out = *newsock;
1405				log_init(__progname,
1406				    options.log_level,
1407				    options.log_facility,
1408				    log_stderr);
1409				if (rexec_flag)
1410					close(config_s[0]);
1411				else {
1412					/*
1413					 * Signal parent that the preliminaries
1414					 * for this child are complete. For the
1415					 * re-exec case, this happens after the
1416					 * child has received the rexec state
1417					 * from the server.
1418					 */
1419					(void)atomicio(vwrite, startup_pipe,
1420					    "\0", 1);
1421				}
1422				free(pfd);
1423				return;
1424			}
1425
1426			/* Parent.  Stay in the loop. */
1427			platform_post_fork_parent(pid);
1428			if (pid == -1)
1429				error("fork: %.100s", strerror(errno));
1430			else
1431				debug("Forked child %ld.", (long)pid);
1432
1433			close(startup_p[1]);
1434
1435			if (rexec_flag) {
1436				close(config_s[1]);
1437				send_rexec_state(config_s[0], cfg);
1438				close(config_s[0]);
1439			}
1440			close(*newsock);
1441
1442			/*
1443			 * Ensure that our random state differs
1444			 * from that of the child
1445			 */
1446			arc4random_stir();
1447			arc4random_buf(rnd, sizeof(rnd));
1448#ifdef WITH_OPENSSL
1449			RAND_seed(rnd, sizeof(rnd));
1450			if ((RAND_bytes((u_char *)rnd, 1)) != 1)
1451				fatal("%s: RAND_bytes failed", __func__);
1452#endif
1453			explicit_bzero(rnd, sizeof(rnd));
1454		}
1455	}
1456}
1457
1458/*
1459 * If IP options are supported, make sure there are none (log and
1460 * return an error if any are found).  Basically we are worried about
1461 * source routing; it can be used to pretend you are somebody
1462 * (ip-address) you are not. That itself may be "almost acceptable"
1463 * under certain circumstances, but rhosts authentication is useless
1464 * if source routing is accepted. Notice also that if we just dropped
1465 * source routing here, the other side could use IP spoofing to do
1466 * rest of the interaction and could still bypass security.  So we
1467 * exit here if we detect any IP options.
1468 */
1469static void
1470check_ip_options(struct ssh *ssh)
1471{
1472#ifdef IP_OPTIONS
1473	int sock_in = ssh_packet_get_connection_in(ssh);
1474	struct sockaddr_storage from;
1475	u_char opts[200];
1476	socklen_t i, option_size = sizeof(opts), fromlen = sizeof(from);
1477	char text[sizeof(opts) * 3 + 1];
1478
1479	memset(&from, 0, sizeof(from));
1480	if (getpeername(sock_in, (struct sockaddr *)&from,
1481	    &fromlen) == -1)
1482		return;
1483	if (from.ss_family != AF_INET)
1484		return;
1485	/* XXX IPv6 options? */
1486
1487	if (getsockopt(sock_in, IPPROTO_IP, IP_OPTIONS, opts,
1488	    &option_size) >= 0 && option_size != 0) {
1489		text[0] = '\0';
1490		for (i = 0; i < option_size; i++)
1491			snprintf(text + i*3, sizeof(text) - i*3,
1492			    " %2.2x", opts[i]);
1493		fatal("Connection from %.100s port %d with IP opts: %.800s",
1494		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), text);
1495	}
1496	return;
1497#endif /* IP_OPTIONS */
1498}
1499
1500/* Set the routing domain for this process */
1501static void
1502set_process_rdomain(struct ssh *ssh, const char *name)
1503{
1504#if defined(HAVE_SYS_SET_PROCESS_RDOMAIN)
1505	if (name == NULL)
1506		return; /* default */
1507
1508	if (strcmp(name, "%D") == 0) {
1509		/* "expands" to routing domain of connection */
1510		if ((name = ssh_packet_rdomain_in(ssh)) == NULL)
1511			return;
1512	}
1513	/* NB. We don't pass 'ssh' to sys_set_process_rdomain() */
1514	return sys_set_process_rdomain(name);
1515#elif defined(__OpenBSD__)
1516	int rtable, ortable = getrtable();
1517	const char *errstr;
1518
1519	if (name == NULL)
1520		return; /* default */
1521
1522	if (strcmp(name, "%D") == 0) {
1523		/* "expands" to routing domain of connection */
1524		if ((name = ssh_packet_rdomain_in(ssh)) == NULL)
1525			return;
1526	}
1527
1528	rtable = (int)strtonum(name, 0, 255, &errstr);
1529	if (errstr != NULL) /* Shouldn't happen */
1530		fatal("Invalid routing domain \"%s\": %s", name, errstr);
1531	if (rtable != ortable && setrtable(rtable) != 0)
1532		fatal("Unable to set routing domain %d: %s",
1533		    rtable, strerror(errno));
1534	debug_f("set routing domain %d (was %d)", rtable, ortable);
1535#else /* defined(__OpenBSD__) */
1536	fatal("Unable to set routing domain: not supported in this platform");
1537#endif
1538}
1539
1540static void
1541accumulate_host_timing_secret(struct sshbuf *server_cfg,
1542    struct sshkey *key)
1543{
1544	static struct ssh_digest_ctx *ctx;
1545	u_char *hash;
1546	size_t len;
1547	struct sshbuf *buf;
1548	int r;
1549
1550	if (ctx == NULL && (ctx = ssh_digest_start(SSH_DIGEST_SHA512)) == NULL)
1551		fatal_f("ssh_digest_start");
1552	if (key == NULL) { /* finalize */
1553		/* add server config in case we are using agent for host keys */
1554		if (ssh_digest_update(ctx, sshbuf_ptr(server_cfg),
1555		    sshbuf_len(server_cfg)) != 0)
1556			fatal_f("ssh_digest_update");
1557		len = ssh_digest_bytes(SSH_DIGEST_SHA512);
1558		hash = xmalloc(len);
1559		if (ssh_digest_final(ctx, hash, len) != 0)
1560			fatal_f("ssh_digest_final");
1561		options.timing_secret = PEEK_U64(hash);
1562		freezero(hash, len);
1563		ssh_digest_free(ctx);
1564		ctx = NULL;
1565		return;
1566	}
1567	if ((buf = sshbuf_new()) == NULL)
1568		fatal_f("could not allocate buffer");
1569	if ((r = sshkey_private_serialize(key, buf)) != 0)
1570		fatal_fr(r, "encode %s key", sshkey_ssh_name(key));
1571	if (ssh_digest_update(ctx, sshbuf_ptr(buf), sshbuf_len(buf)) != 0)
1572		fatal_f("ssh_digest_update");
1573	sshbuf_reset(buf);
1574	sshbuf_free(buf);
1575}
1576
1577static char *
1578prepare_proctitle(int ac, char **av)
1579{
1580	char *ret = NULL;
1581	int i;
1582
1583	for (i = 0; i < ac; i++)
1584		xextendf(&ret, " ", "%s", av[i]);
1585	return ret;
1586}
1587
1588static void
1589print_config(struct ssh *ssh, struct connection_info *connection_info)
1590{
1591	/*
1592	 * If no connection info was provided by -C then use
1593	 * use a blank one that will cause no predicate to match.
1594	 */
1595	if (connection_info == NULL)
1596		connection_info = get_connection_info(ssh, 0, 0);
1597	connection_info->test = 1;
1598	parse_server_match_config(&options, &includes, connection_info);
1599	dump_config(&options);
1600	exit(0);
1601}
1602
1603/*
1604 * Main program for the daemon.
1605 */
1606int
1607main(int ac, char **av)
1608{
1609	struct ssh *ssh = NULL;
1610	extern char *optarg;
1611	extern int optind;
1612	int r, opt, on = 1, do_dump_cfg = 0, already_daemon, remote_port;
1613	int sock_in = -1, sock_out = -1, newsock = -1;
1614	const char *remote_ip, *rdomain;
1615	char *fp, *line, *laddr, *logfile = NULL;
1616	int config_s[2] = { -1 , -1 };
1617	u_int i, j;
1618	u_int64_t ibytes, obytes;
1619	mode_t new_umask;
1620	struct sshkey *key;
1621	struct sshkey *pubkey;
1622	int keytype;
1623	Authctxt *authctxt;
1624	struct connection_info *connection_info = NULL;
1625	sigset_t sigmask;
1626
1627#ifdef HAVE_SECUREWARE
1628	(void)set_auth_parameters(ac, av);
1629#endif
1630	__progname = ssh_get_progname(av[0]);
1631
1632	sigemptyset(&sigmask);
1633	sigprocmask(SIG_SETMASK, &sigmask, NULL);
1634
1635	/* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1636	saved_argc = ac;
1637	rexec_argc = ac;
1638	saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1639	for (i = 0; (int)i < ac; i++)
1640		saved_argv[i] = xstrdup(av[i]);
1641	saved_argv[i] = NULL;
1642
1643#ifndef HAVE_SETPROCTITLE
1644	/* Prepare for later setproctitle emulation */
1645	compat_init_setproctitle(ac, av);
1646	av = saved_argv;
1647#endif
1648
1649	if (geteuid() == 0 && setgroups(0, NULL) == -1)
1650		debug("setgroups(): %.200s", strerror(errno));
1651
1652	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1653	sanitise_stdfd();
1654
1655	/* Initialize configuration options to their default values. */
1656	initialize_server_options(&options);
1657
1658	/* Parse command-line arguments. */
1659	while ((opt = getopt(ac, av,
1660	    "C:E:b:c:f:g:h:k:o:p:u:46DGQRTdeiqrtV")) != -1) {
1661		switch (opt) {
1662		case '4':
1663			options.address_family = AF_INET;
1664			break;
1665		case '6':
1666			options.address_family = AF_INET6;
1667			break;
1668		case 'f':
1669			config_file_name = optarg;
1670			break;
1671		case 'c':
1672			servconf_add_hostcert("[command-line]", 0,
1673			    &options, optarg);
1674			break;
1675		case 'd':
1676			if (debug_flag == 0) {
1677				debug_flag = 1;
1678				options.log_level = SYSLOG_LEVEL_DEBUG1;
1679			} else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1680				options.log_level++;
1681			break;
1682		case 'D':
1683			no_daemon_flag = 1;
1684			break;
1685		case 'G':
1686			do_dump_cfg = 1;
1687			break;
1688		case 'E':
1689			logfile = optarg;
1690			/* FALLTHROUGH */
1691		case 'e':
1692			log_stderr = 1;
1693			break;
1694		case 'i':
1695			inetd_flag = 1;
1696			break;
1697		case 'r':
1698			rexec_flag = 0;
1699			break;
1700		case 'R':
1701			rexeced_flag = 1;
1702			inetd_flag = 1;
1703			break;
1704		case 'Q':
1705			/* ignored */
1706			break;
1707		case 'q':
1708			options.log_level = SYSLOG_LEVEL_QUIET;
1709			break;
1710		case 'b':
1711			/* protocol 1, ignored */
1712			break;
1713		case 'p':
1714			options.ports_from_cmdline = 1;
1715			if (options.num_ports >= MAX_PORTS) {
1716				fprintf(stderr, "too many ports.\n");
1717				exit(1);
1718			}
1719			options.ports[options.num_ports++] = a2port(optarg);
1720			if (options.ports[options.num_ports-1] <= 0) {
1721				fprintf(stderr, "Bad port number.\n");
1722				exit(1);
1723			}
1724			break;
1725		case 'g':
1726			if ((options.login_grace_time = convtime(optarg)) == -1) {
1727				fprintf(stderr, "Invalid login grace time.\n");
1728				exit(1);
1729			}
1730			break;
1731		case 'k':
1732			/* protocol 1, ignored */
1733			break;
1734		case 'h':
1735			servconf_add_hostkey("[command-line]", 0,
1736			    &options, optarg, 1);
1737			break;
1738		case 't':
1739			test_flag = 1;
1740			break;
1741		case 'T':
1742			test_flag = 2;
1743			break;
1744		case 'C':
1745			connection_info = get_connection_info(ssh, 0, 0);
1746			if (parse_server_match_testspec(connection_info,
1747			    optarg) == -1)
1748				exit(1);
1749			break;
1750		case 'u':
1751			utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
1752			if (utmp_len > HOST_NAME_MAX+1) {
1753				fprintf(stderr, "Invalid utmp length.\n");
1754				exit(1);
1755			}
1756			break;
1757		case 'o':
1758			line = xstrdup(optarg);
1759			if (process_server_config_line(&options, line,
1760			    "command-line", 0, NULL, NULL, &includes) != 0)
1761				exit(1);
1762			free(line);
1763			break;
1764		case 'V':
1765			fprintf(stderr, "%s, %s\n",
1766			    SSH_RELEASE, SSH_OPENSSL_VERSION);
1767			exit(0);
1768		default:
1769			usage();
1770			break;
1771		}
1772	}
1773	if (rexeced_flag || inetd_flag)
1774		rexec_flag = 0;
1775	if (!test_flag && !do_dump_cfg && rexec_flag && !path_absolute(av[0]))
1776		fatal("sshd re-exec requires execution with an absolute path");
1777	if (rexeced_flag)
1778		closefrom(REEXEC_MIN_FREE_FD);
1779	else
1780		closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1781
1782	seed_rng();
1783
1784	/* If requested, redirect the logs to the specified logfile. */
1785	if (logfile != NULL)
1786		log_redirect_stderr_to(logfile);
1787	/*
1788	 * Force logging to stderr until we have loaded the private host
1789	 * key (unless started from inetd)
1790	 */
1791	log_init(__progname,
1792	    options.log_level == SYSLOG_LEVEL_NOT_SET ?
1793	    SYSLOG_LEVEL_INFO : options.log_level,
1794	    options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1795	    SYSLOG_FACILITY_AUTH : options.log_facility,
1796	    log_stderr || !inetd_flag || debug_flag);
1797
1798	/*
1799	 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1800	 * root's environment
1801	 */
1802	if (getenv("KRB5CCNAME") != NULL)
1803		(void) unsetenv("KRB5CCNAME");
1804
1805	sensitive_data.have_ssh2_key = 0;
1806
1807	/*
1808	 * If we're not doing an extended test do not silently ignore connection
1809	 * test params.
1810	 */
1811	if (test_flag < 2 && connection_info != NULL)
1812		fatal("Config test connection parameter (-C) provided without "
1813		    "test mode (-T)");
1814
1815	/* Fetch our configuration */
1816	if ((cfg = sshbuf_new()) == NULL)
1817		fatal_f("sshbuf_new failed");
1818	if (rexeced_flag) {
1819		setproctitle("%s", "[rexeced]");
1820		recv_rexec_state(REEXEC_CONFIG_PASS_FD, cfg);
1821		if (!debug_flag) {
1822			startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
1823			close(REEXEC_STARTUP_PIPE_FD);
1824			/*
1825			 * Signal parent that this child is at a point where
1826			 * they can go away if they have a SIGHUP pending.
1827			 */
1828			(void)atomicio(vwrite, startup_pipe, "\0", 1);
1829		}
1830	} else if (strcasecmp(config_file_name, "none") != 0)
1831		load_server_config(config_file_name, cfg);
1832
1833	parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1834	    cfg, &includes, NULL, rexeced_flag);
1835
1836#ifdef WITH_OPENSSL
1837	if (options.moduli_file != NULL)
1838		dh_set_moduli_file(options.moduli_file);
1839#endif
1840
1841	/* Fill in default values for those options not explicitly set. */
1842	fill_default_server_options(&options);
1843
1844	/* Check that options are sensible */
1845	if (options.authorized_keys_command_user == NULL &&
1846	    (options.authorized_keys_command != NULL &&
1847	    strcasecmp(options.authorized_keys_command, "none") != 0))
1848		fatal("AuthorizedKeysCommand set without "
1849		    "AuthorizedKeysCommandUser");
1850	if (options.authorized_principals_command_user == NULL &&
1851	    (options.authorized_principals_command != NULL &&
1852	    strcasecmp(options.authorized_principals_command, "none") != 0))
1853		fatal("AuthorizedPrincipalsCommand set without "
1854		    "AuthorizedPrincipalsCommandUser");
1855
1856	/*
1857	 * Check whether there is any path through configured auth methods.
1858	 * Unfortunately it is not possible to verify this generally before
1859	 * daemonisation in the presence of Match block, but this catches
1860	 * and warns for trivial misconfigurations that could break login.
1861	 */
1862	if (options.num_auth_methods != 0) {
1863		for (i = 0; i < options.num_auth_methods; i++) {
1864			if (auth2_methods_valid(options.auth_methods[i],
1865			    1) == 0)
1866				break;
1867		}
1868		if (i >= options.num_auth_methods)
1869			fatal("AuthenticationMethods cannot be satisfied by "
1870			    "enabled authentication methods");
1871	}
1872
1873	/* Check that there are no remaining arguments. */
1874	if (optind < ac) {
1875		fprintf(stderr, "Extra argument %s.\n", av[optind]);
1876		exit(1);
1877	}
1878
1879	debug("sshd version %s, %s", SSH_VERSION, SSH_OPENSSL_VERSION);
1880
1881	if (do_dump_cfg)
1882		print_config(ssh, connection_info);
1883
1884	/* Store privilege separation user for later use if required. */
1885	privsep_chroot = use_privsep && (getuid() == 0 || geteuid() == 0);
1886	if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1887		if (privsep_chroot || options.kerberos_authentication)
1888			fatal("Privilege separation user %s does not exist",
1889			    SSH_PRIVSEP_USER);
1890	} else {
1891		privsep_pw = pwcopy(privsep_pw);
1892		freezero(privsep_pw->pw_passwd, strlen(privsep_pw->pw_passwd));
1893		privsep_pw->pw_passwd = xstrdup("*");
1894	}
1895	endpwent();
1896
1897	/* load host keys */
1898	sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1899	    sizeof(struct sshkey *));
1900	sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
1901	    sizeof(struct sshkey *));
1902
1903	if (options.host_key_agent) {
1904		if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
1905			setenv(SSH_AUTHSOCKET_ENV_NAME,
1906			    options.host_key_agent, 1);
1907		if ((r = ssh_get_authentication_socket(NULL)) == 0)
1908			have_agent = 1;
1909		else
1910			error_r(r, "Could not connect to agent \"%s\"",
1911			    options.host_key_agent);
1912	}
1913
1914	for (i = 0; i < options.num_host_key_files; i++) {
1915		int ll = options.host_key_file_userprovided[i] ?
1916		    SYSLOG_LEVEL_ERROR : SYSLOG_LEVEL_DEBUG1;
1917
1918		if (options.host_key_files[i] == NULL)
1919			continue;
1920		if ((r = sshkey_load_private(options.host_key_files[i], "",
1921		    &key, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR)
1922			do_log2_r(r, ll, "Unable to load host key \"%s\"",
1923			    options.host_key_files[i]);
1924		if (sshkey_is_sk(key) &&
1925		    key->sk_flags & SSH_SK_USER_PRESENCE_REQD) {
1926			debug("host key %s requires user presence, ignoring",
1927			    options.host_key_files[i]);
1928			key->sk_flags &= ~SSH_SK_USER_PRESENCE_REQD;
1929		}
1930		if (r == 0 && key != NULL &&
1931		    (r = sshkey_shield_private(key)) != 0) {
1932			do_log2_r(r, ll, "Unable to shield host key \"%s\"",
1933			    options.host_key_files[i]);
1934			sshkey_free(key);
1935			key = NULL;
1936		}
1937		if ((r = sshkey_load_public(options.host_key_files[i],
1938		    &pubkey, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR)
1939			do_log2_r(r, ll, "Unable to load host key \"%s\"",
1940			    options.host_key_files[i]);
1941		if (pubkey != NULL && key != NULL) {
1942			if (!sshkey_equal(pubkey, key)) {
1943				error("Public key for %s does not match "
1944				    "private key", options.host_key_files[i]);
1945				sshkey_free(pubkey);
1946				pubkey = NULL;
1947			}
1948		}
1949		if (pubkey == NULL && key != NULL) {
1950			if ((r = sshkey_from_private(key, &pubkey)) != 0)
1951				fatal_r(r, "Could not demote key: \"%s\"",
1952				    options.host_key_files[i]);
1953		}
1954		if (pubkey != NULL && (r = sshkey_check_rsa_length(pubkey,
1955		    options.required_rsa_size)) != 0) {
1956			error_fr(r, "Host key %s", options.host_key_files[i]);
1957			sshkey_free(pubkey);
1958			sshkey_free(key);
1959			continue;
1960		}
1961		sensitive_data.host_keys[i] = key;
1962		sensitive_data.host_pubkeys[i] = pubkey;
1963
1964		if (key == NULL && pubkey != NULL && have_agent) {
1965			debug("will rely on agent for hostkey %s",
1966			    options.host_key_files[i]);
1967			keytype = pubkey->type;
1968		} else if (key != NULL) {
1969			keytype = key->type;
1970			accumulate_host_timing_secret(cfg, key);
1971		} else {
1972			do_log2(ll, "Unable to load host key: %s",
1973			    options.host_key_files[i]);
1974			sensitive_data.host_keys[i] = NULL;
1975			sensitive_data.host_pubkeys[i] = NULL;
1976			continue;
1977		}
1978
1979		switch (keytype) {
1980		case KEY_RSA:
1981		case KEY_DSA:
1982		case KEY_ECDSA:
1983		case KEY_ED25519:
1984		case KEY_ECDSA_SK:
1985		case KEY_ED25519_SK:
1986		case KEY_XMSS:
1987			if (have_agent || key != NULL)
1988				sensitive_data.have_ssh2_key = 1;
1989			break;
1990		}
1991		if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash,
1992		    SSH_FP_DEFAULT)) == NULL)
1993			fatal("sshkey_fingerprint failed");
1994		debug("%s host key #%d: %s %s",
1995		    key ? "private" : "agent", i, sshkey_ssh_name(pubkey), fp);
1996		free(fp);
1997	}
1998	accumulate_host_timing_secret(cfg, NULL);
1999	if (!sensitive_data.have_ssh2_key) {
2000		logit("sshd: no hostkeys available -- exiting.");
2001		exit(1);
2002	}
2003
2004	/*
2005	 * Load certificates. They are stored in an array at identical
2006	 * indices to the public keys that they relate to.
2007	 */
2008	sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
2009	    sizeof(struct sshkey *));
2010	for (i = 0; i < options.num_host_key_files; i++)
2011		sensitive_data.host_certificates[i] = NULL;
2012
2013	for (i = 0; i < options.num_host_cert_files; i++) {
2014		if (options.host_cert_files[i] == NULL)
2015			continue;
2016		if ((r = sshkey_load_public(options.host_cert_files[i],
2017		    &key, NULL)) != 0) {
2018			error_r(r, "Could not load host certificate \"%s\"",
2019			    options.host_cert_files[i]);
2020			continue;
2021		}
2022		if (!sshkey_is_cert(key)) {
2023			error("Certificate file is not a certificate: %s",
2024			    options.host_cert_files[i]);
2025			sshkey_free(key);
2026			continue;
2027		}
2028		/* Find matching private key */
2029		for (j = 0; j < options.num_host_key_files; j++) {
2030			if (sshkey_equal_public(key,
2031			    sensitive_data.host_pubkeys[j])) {
2032				sensitive_data.host_certificates[j] = key;
2033				break;
2034			}
2035		}
2036		if (j >= options.num_host_key_files) {
2037			error("No matching private key for certificate: %s",
2038			    options.host_cert_files[i]);
2039			sshkey_free(key);
2040			continue;
2041		}
2042		sensitive_data.host_certificates[j] = key;
2043		debug("host certificate: #%u type %d %s", j, key->type,
2044		    sshkey_type(key));
2045	}
2046
2047	if (privsep_chroot) {
2048		struct stat st;
2049
2050		if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
2051		    (S_ISDIR(st.st_mode) == 0))
2052			fatal("Missing privilege separation directory: %s",
2053			    _PATH_PRIVSEP_CHROOT_DIR);
2054
2055#ifdef HAVE_CYGWIN
2056		if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
2057		    (st.st_uid != getuid () ||
2058		    (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
2059#else
2060		if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
2061#endif
2062			fatal("%s must be owned by root and not group or "
2063			    "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
2064	}
2065
2066	if (test_flag > 1)
2067		print_config(ssh, connection_info);
2068
2069	/* Configuration looks good, so exit if in test mode. */
2070	if (test_flag)
2071		exit(0);
2072
2073	/*
2074	 * Clear out any supplemental groups we may have inherited.  This
2075	 * prevents inadvertent creation of files with bad modes (in the
2076	 * portable version at least, it's certainly possible for PAM
2077	 * to create a file, and we can't control the code in every
2078	 * module which might be used).
2079	 */
2080	if (setgroups(0, NULL) < 0)
2081		debug("setgroups() failed: %.200s", strerror(errno));
2082
2083	if (rexec_flag) {
2084		if (rexec_argc < 0)
2085			fatal("rexec_argc %d < 0", rexec_argc);
2086		rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
2087		for (i = 0; i < (u_int)rexec_argc; i++) {
2088			debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
2089			rexec_argv[i] = saved_argv[i];
2090		}
2091		rexec_argv[rexec_argc] = "-R";
2092		rexec_argv[rexec_argc + 1] = NULL;
2093	}
2094	listener_proctitle = prepare_proctitle(ac, av);
2095
2096	/* Ensure that umask disallows at least group and world write */
2097	new_umask = umask(0077) | 0022;
2098	(void) umask(new_umask);
2099
2100	/* Initialize the log (it is reinitialized below in case we forked). */
2101	if (debug_flag && (!inetd_flag || rexeced_flag))
2102		log_stderr = 1;
2103	log_init(__progname, options.log_level,
2104	    options.log_facility, log_stderr);
2105	for (i = 0; i < options.num_log_verbose; i++)
2106		log_verbose_add(options.log_verbose[i]);
2107
2108	/*
2109	 * If not in debugging mode, not started from inetd and not already
2110	 * daemonized (eg re-exec via SIGHUP), disconnect from the controlling
2111	 * terminal, and fork.  The original process exits.
2112	 */
2113	already_daemon = daemonized();
2114	if (!(debug_flag || inetd_flag || no_daemon_flag || already_daemon)) {
2115
2116		if (daemon(0, 0) == -1)
2117			fatal("daemon() failed: %.200s", strerror(errno));
2118
2119		disconnect_controlling_tty();
2120	}
2121	/* Reinitialize the log (because of the fork above). */
2122	log_init(__progname, options.log_level, options.log_facility, log_stderr);
2123
2124	/* Avoid killing the process in high-pressure swapping environments. */
2125	if (!inetd_flag && madvise(NULL, 0, MADV_PROTECT) != 0)
2126		debug("madvise(): %.200s", strerror(errno));
2127
2128	/*
2129	 * Chdir to the root directory so that the current disk can be
2130	 * unmounted if desired.
2131	 */
2132	if (chdir("/") == -1)
2133		error("chdir(\"/\"): %s", strerror(errno));
2134
2135	/* ignore SIGPIPE */
2136	ssh_signal(SIGPIPE, SIG_IGN);
2137
2138	/* Get a connection, either from inetd or a listening TCP socket */
2139	if (inetd_flag) {
2140		server_accept_inetd(&sock_in, &sock_out);
2141	} else {
2142		platform_pre_listen();
2143		server_listen();
2144
2145		ssh_signal(SIGHUP, sighup_handler);
2146		ssh_signal(SIGCHLD, main_sigchld_handler);
2147		ssh_signal(SIGTERM, sigterm_handler);
2148		ssh_signal(SIGQUIT, sigterm_handler);
2149
2150		/*
2151		 * Write out the pid file after the sigterm handler
2152		 * is setup and the listen sockets are bound
2153		 */
2154		if (options.pid_file != NULL && !debug_flag) {
2155			FILE *f = fopen(options.pid_file, "w");
2156
2157			if (f == NULL) {
2158				error("Couldn't create pid file \"%s\": %s",
2159				    options.pid_file, strerror(errno));
2160			} else {
2161				fprintf(f, "%ld\n", (long) getpid());
2162				fclose(f);
2163			}
2164		}
2165
2166		/* Accept a connection and return in a forked child */
2167		server_accept_loop(&sock_in, &sock_out,
2168		    &newsock, config_s);
2169	}
2170
2171	/* This is the child processing a new connection. */
2172	setproctitle("%s", "[accepted]");
2173
2174	/*
2175	 * Create a new session and process group since the 4.4BSD
2176	 * setlogin() affects the entire process group.  We don't
2177	 * want the child to be able to affect the parent.
2178	 */
2179	if (!debug_flag && !inetd_flag && setsid() == -1)
2180		error("setsid: %.100s", strerror(errno));
2181
2182	if (rexec_flag) {
2183		debug("rexec start in %d out %d newsock %d pipe %d sock %d",
2184		    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
2185		if (dup2(newsock, STDIN_FILENO) == -1)
2186			debug3_f("dup2 stdin: %s", strerror(errno));
2187		if (dup2(STDIN_FILENO, STDOUT_FILENO) == -1)
2188			debug3_f("dup2 stdout: %s", strerror(errno));
2189		if (startup_pipe == -1)
2190			close(REEXEC_STARTUP_PIPE_FD);
2191		else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) {
2192			if (dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD) == -1)
2193				debug3_f("dup2 startup_p: %s", strerror(errno));
2194			close(startup_pipe);
2195			startup_pipe = REEXEC_STARTUP_PIPE_FD;
2196		}
2197
2198		if (dup2(config_s[1], REEXEC_CONFIG_PASS_FD) == -1)
2199			debug3_f("dup2 config_s: %s", strerror(errno));
2200		close(config_s[1]);
2201
2202		ssh_signal(SIGHUP, SIG_IGN); /* avoid reset to SIG_DFL */
2203		execv(rexec_argv[0], rexec_argv);
2204
2205		/* Reexec has failed, fall back and continue */
2206		error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
2207		recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
2208		log_init(__progname, options.log_level,
2209		    options.log_facility, log_stderr);
2210
2211		/* Clean up fds */
2212		close(REEXEC_CONFIG_PASS_FD);
2213		newsock = sock_out = sock_in = dup(STDIN_FILENO);
2214		if (stdfd_devnull(1, 1, 0) == -1)
2215			error_f("stdfd_devnull failed");
2216		debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
2217		    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
2218	}
2219
2220	/* Executed child processes don't need these. */
2221	fcntl(sock_out, F_SETFD, FD_CLOEXEC);
2222	fcntl(sock_in, F_SETFD, FD_CLOEXEC);
2223
2224	/* We will not restart on SIGHUP since it no longer makes sense. */
2225	ssh_signal(SIGALRM, SIG_DFL);
2226	ssh_signal(SIGHUP, SIG_DFL);
2227	ssh_signal(SIGTERM, SIG_DFL);
2228	ssh_signal(SIGQUIT, SIG_DFL);
2229	ssh_signal(SIGCHLD, SIG_DFL);
2230	ssh_signal(SIGINT, SIG_DFL);
2231
2232#ifdef __FreeBSD__
2233	/*
2234	 * Initialize the resolver.  This may not happen automatically
2235	 * before privsep chroot().
2236	 */
2237	if ((_res.options & RES_INIT) == 0) {
2238		debug("res_init()");
2239		res_init();
2240	}
2241#ifdef GSSAPI
2242	/*
2243	 * Force GSS-API to parse its configuration and load any
2244	 * mechanism plugins.
2245	 */
2246	{
2247		gss_OID_set mechs;
2248		OM_uint32 minor_status;
2249		gss_indicate_mechs(&minor_status, &mechs);
2250		gss_release_oid_set(&minor_status, &mechs);
2251	}
2252#endif
2253#endif
2254
2255	/*
2256	 * Register our connection.  This turns encryption off because we do
2257	 * not have a key.
2258	 */
2259	if ((ssh = ssh_packet_set_connection(NULL, sock_in, sock_out)) == NULL)
2260		fatal("Unable to create connection");
2261	the_active_state = ssh;
2262	ssh_packet_set_server(ssh);
2263
2264	check_ip_options(ssh);
2265
2266	/* Prepare the channels layer */
2267	channel_init_channels(ssh);
2268	channel_set_af(ssh, options.address_family);
2269	process_channel_timeouts(ssh, &options);
2270	process_permitopen(ssh, &options);
2271
2272	/* Set SO_KEEPALIVE if requested. */
2273	if (options.tcp_keep_alive && ssh_packet_connection_is_on_socket(ssh) &&
2274	    setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) == -1)
2275		error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
2276
2277	if ((remote_port = ssh_remote_port(ssh)) < 0) {
2278		debug("ssh_remote_port failed");
2279		cleanup_exit(255);
2280	}
2281
2282	if (options.routing_domain != NULL)
2283		set_process_rdomain(ssh, options.routing_domain);
2284
2285	/*
2286	 * The rest of the code depends on the fact that
2287	 * ssh_remote_ipaddr() caches the remote ip, even if
2288	 * the socket goes away.
2289	 */
2290	remote_ip = ssh_remote_ipaddr(ssh);
2291
2292#ifdef HAVE_LOGIN_CAP
2293	/* Also caches remote hostname for sandboxed child. */
2294	auth_get_canonical_hostname(ssh, options.use_dns);
2295#endif
2296
2297#ifdef SSH_AUDIT_EVENTS
2298	audit_connection_from(remote_ip, remote_port);
2299#endif
2300
2301	rdomain = ssh_packet_rdomain_in(ssh);
2302
2303	/* Log the connection. */
2304	laddr = get_local_ipaddr(sock_in);
2305	verbose("Connection from %s port %d on %s port %d%s%s%s",
2306	    remote_ip, remote_port, laddr,  ssh_local_port(ssh),
2307	    rdomain == NULL ? "" : " rdomain \"",
2308	    rdomain == NULL ? "" : rdomain,
2309	    rdomain == NULL ? "" : "\"");
2310	free(laddr);
2311
2312	/*
2313	 * We don't want to listen forever unless the other side
2314	 * successfully authenticates itself.  So we set up an alarm which is
2315	 * cleared after successful authentication.  A limit of zero
2316	 * indicates no limit. Note that we don't set the alarm in debugging
2317	 * mode; it is just annoying to have the server exit just when you
2318	 * are about to discover the bug.
2319	 */
2320	ssh_signal(SIGALRM, grace_alarm_handler);
2321	if (!debug_flag)
2322		alarm(options.login_grace_time);
2323
2324	if ((r = kex_exchange_identification(ssh, -1,
2325	    options.version_addendum)) != 0)
2326		sshpkt_fatal(ssh, r, "banner exchange");
2327
2328	ssh_packet_set_nonblocking(ssh);
2329
2330	/* allocate authentication context */
2331	authctxt = xcalloc(1, sizeof(*authctxt));
2332	ssh->authctxt = authctxt;
2333
2334	authctxt->loginmsg = loginmsg;
2335
2336	/* XXX global for cleanup, access from other modules */
2337	the_authctxt = authctxt;
2338
2339	/* Set default key authentication options */
2340	if ((auth_opts = sshauthopt_new_with_keys_defaults()) == NULL)
2341		fatal("allocation failed");
2342
2343	/* prepare buffer to collect messages to display to user after login */
2344	if ((loginmsg = sshbuf_new()) == NULL)
2345		fatal_f("sshbuf_new failed");
2346	auth_debug_reset();
2347
2348	BLACKLIST_INIT();
2349
2350	if (use_privsep) {
2351		if (privsep_preauth(ssh) == 1)
2352			goto authenticated;
2353	} else if (have_agent) {
2354		if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) {
2355			error_r(r, "Unable to get agent socket");
2356			have_agent = 0;
2357		}
2358	}
2359
2360	/* perform the key exchange */
2361	/* authenticate user and start session */
2362	do_ssh2_kex(ssh);
2363	do_authentication2(ssh);
2364
2365	/*
2366	 * If we use privilege separation, the unprivileged child transfers
2367	 * the current keystate and exits
2368	 */
2369	if (use_privsep) {
2370		mm_send_keystate(ssh, pmonitor);
2371		ssh_packet_clear_keys(ssh);
2372		exit(0);
2373	}
2374
2375 authenticated:
2376	/*
2377	 * Cancel the alarm we set to limit the time taken for
2378	 * authentication.
2379	 */
2380	alarm(0);
2381	ssh_signal(SIGALRM, SIG_DFL);
2382	authctxt->authenticated = 1;
2383	if (startup_pipe != -1) {
2384		close(startup_pipe);
2385		startup_pipe = -1;
2386	}
2387
2388#ifdef SSH_AUDIT_EVENTS
2389	audit_event(ssh, SSH_AUTH_SUCCESS);
2390#endif
2391
2392#ifdef GSSAPI
2393	if (options.gss_authentication) {
2394		temporarily_use_uid(authctxt->pw);
2395		ssh_gssapi_storecreds();
2396		restore_uid();
2397	}
2398#endif
2399#ifdef USE_PAM
2400	if (options.use_pam) {
2401		do_pam_setcred(1);
2402		do_pam_session(ssh);
2403	}
2404#endif
2405
2406	/*
2407	 * In privilege separation, we fork another child and prepare
2408	 * file descriptor passing.
2409	 */
2410	if (use_privsep) {
2411		privsep_postauth(ssh, authctxt);
2412		/* the monitor process [priv] will not return */
2413	}
2414
2415	ssh_packet_set_timeout(ssh, options.client_alive_interval,
2416	    options.client_alive_count_max);
2417
2418	/* Try to send all our hostkeys to the client */
2419	notify_hostkeys(ssh);
2420
2421	/* Start session. */
2422	do_authenticated(ssh, authctxt);
2423
2424	/* The connection has been terminated. */
2425	ssh_packet_get_bytes(ssh, &ibytes, &obytes);
2426	verbose("Transferred: sent %llu, received %llu bytes",
2427	    (unsigned long long)obytes, (unsigned long long)ibytes);
2428
2429	verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
2430
2431#ifdef USE_PAM
2432	if (options.use_pam)
2433		finish_pam();
2434#endif /* USE_PAM */
2435
2436#ifdef SSH_AUDIT_EVENTS
2437	PRIVSEP(audit_event(ssh, SSH_CONNECTION_CLOSE));
2438#endif
2439
2440	ssh_packet_close(ssh);
2441
2442	if (use_privsep)
2443		mm_terminate();
2444
2445	exit(0);
2446}
2447
2448int
2449sshd_hostkey_sign(struct ssh *ssh, struct sshkey *privkey,
2450    struct sshkey *pubkey, u_char **signature, size_t *slenp,
2451    const u_char *data, size_t dlen, const char *alg)
2452{
2453	int r;
2454
2455	if (use_privsep) {
2456		if (privkey) {
2457			if (mm_sshkey_sign(ssh, privkey, signature, slenp,
2458			    data, dlen, alg, options.sk_provider, NULL,
2459			    ssh->compat) < 0)
2460				fatal_f("privkey sign failed");
2461		} else {
2462			if (mm_sshkey_sign(ssh, pubkey, signature, slenp,
2463			    data, dlen, alg, options.sk_provider, NULL,
2464			    ssh->compat) < 0)
2465				fatal_f("pubkey sign failed");
2466		}
2467	} else {
2468		if (privkey) {
2469			if (sshkey_sign(privkey, signature, slenp, data, dlen,
2470			    alg, options.sk_provider, NULL, ssh->compat) < 0)
2471				fatal_f("privkey sign failed");
2472		} else {
2473			if ((r = ssh_agent_sign(auth_sock, pubkey,
2474			    signature, slenp, data, dlen, alg,
2475			    ssh->compat)) != 0) {
2476				fatal_fr(r, "agent sign failed");
2477			}
2478		}
2479	}
2480	return 0;
2481}
2482
2483/* SSH2 key exchange */
2484static void
2485do_ssh2_kex(struct ssh *ssh)
2486{
2487	char *hkalgs = NULL, *myproposal[PROPOSAL_MAX];
2488	const char *compression = NULL;
2489	struct kex *kex;
2490	int r;
2491
2492	if (options.rekey_limit || options.rekey_interval)
2493		ssh_packet_set_rekey_limits(ssh, options.rekey_limit,
2494		    options.rekey_interval);
2495
2496	if (options.compression == COMP_NONE)
2497		compression = "none";
2498	hkalgs = list_hostkey_types();
2499
2500	kex_proposal_populate_entries(ssh, myproposal, options.kex_algorithms,
2501	    options.ciphers, options.macs, compression, hkalgs);
2502
2503	free(hkalgs);
2504
2505	/* start key exchange */
2506	if ((r = kex_setup(ssh, myproposal)) != 0)
2507		fatal_r(r, "kex_setup");
2508	kex_set_server_sig_algs(ssh, options.pubkey_accepted_algos);
2509	kex = ssh->kex;
2510
2511#ifdef WITH_OPENSSL
2512	kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_server;
2513	kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_server;
2514	kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_server;
2515	kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_server;
2516	kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_server;
2517	kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2518	kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2519# ifdef OPENSSL_HAS_ECC
2520	kex->kex[KEX_ECDH_SHA2] = kex_gen_server;
2521# endif
2522#endif
2523	kex->kex[KEX_C25519_SHA256] = kex_gen_server;
2524	kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_server;
2525	kex->load_host_public_key=&get_hostkey_public_by_type;
2526	kex->load_host_private_key=&get_hostkey_private_by_type;
2527	kex->host_key_index=&get_hostkey_index;
2528	kex->sign = sshd_hostkey_sign;
2529
2530	ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &kex->done);
2531	kex_proposal_free_entries(myproposal);
2532
2533#ifdef DEBUG_KEXDH
2534	/* send 1st encrypted/maced/compressed message */
2535	if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 ||
2536	    (r = sshpkt_put_cstring(ssh, "markus")) != 0 ||
2537	    (r = sshpkt_send(ssh)) != 0 ||
2538	    (r = ssh_packet_write_wait(ssh)) != 0)
2539		fatal_fr(r, "send test");
2540#endif
2541	debug("KEX done");
2542}
2543
2544/* server specific fatal cleanup */
2545void
2546cleanup_exit(int i)
2547{
2548	if (the_active_state != NULL && the_authctxt != NULL) {
2549		do_cleanup(the_active_state, the_authctxt);
2550		if (use_privsep && privsep_is_preauth &&
2551		    pmonitor != NULL && pmonitor->m_pid > 1) {
2552			debug("Killing privsep child %d", pmonitor->m_pid);
2553			if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
2554			    errno != ESRCH) {
2555				error_f("kill(%d): %s", pmonitor->m_pid,
2556				    strerror(errno));
2557			}
2558		}
2559	}
2560#ifdef SSH_AUDIT_EVENTS
2561	/* done after do_cleanup so it can cancel the PAM auth 'thread' */
2562	if (the_active_state != NULL && (!use_privsep || mm_is_monitor()))
2563		audit_event(the_active_state, SSH_CONNECTION_ABANDON);
2564#endif
2565	_exit(i);
2566}
2567