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