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