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