xref: /openbsd/usr.bin/ssh/sshd.c (revision 771fbea0)
1 /* $OpenBSD: sshd.c,v 1.575 2021/06/06 11:34:16 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 	sigset_t nsigset, osigset;
1091 
1092 	/* setup fd set for accept */
1093 	fdset = NULL;
1094 	maxfd = 0;
1095 	for (i = 0; i < num_listen_socks; i++)
1096 		if (listen_socks[i] > maxfd)
1097 			maxfd = listen_socks[i];
1098 	/* pipes connected to unauthenticated child sshd processes */
1099 	startup_pipes = xcalloc(options.max_startups, sizeof(int));
1100 	startup_flags = xcalloc(options.max_startups, sizeof(int));
1101 	for (i = 0; i < options.max_startups; i++)
1102 		startup_pipes[i] = -1;
1103 
1104 	/*
1105 	 * Prepare signal mask that we use to block signals that might set
1106 	 * received_sigterm or received_sighup, so that we are guaranteed
1107 	 * to immediately wake up the pselect if a signal is received after
1108 	 * the flag is checked.
1109 	 */
1110 	sigemptyset(&nsigset);
1111 	sigaddset(&nsigset, SIGHUP);
1112 	sigaddset(&nsigset, SIGCHLD);
1113 	sigaddset(&nsigset, SIGTERM);
1114 	sigaddset(&nsigset, SIGQUIT);
1115 
1116 	/*
1117 	 * Stay listening for connections until the system crashes or
1118 	 * the daemon is killed with a signal.
1119 	 */
1120 	for (;;) {
1121 		sigprocmask(SIG_BLOCK, &nsigset, &osigset);
1122 		if (received_sigterm) {
1123 			logit("Received signal %d; terminating.",
1124 			    (int) received_sigterm);
1125 			close_listen_socks();
1126 			if (options.pid_file != NULL)
1127 				unlink(options.pid_file);
1128 			exit(received_sigterm == SIGTERM ? 0 : 255);
1129 		}
1130 		if (ostartups != startups) {
1131 			setproctitle("%s [listener] %d of %d-%d startups",
1132 			    listener_proctitle, startups,
1133 			    options.max_startups_begin, options.max_startups);
1134 			ostartups = startups;
1135 		}
1136 		if (received_sighup) {
1137 			if (!lameduck) {
1138 				debug("Received SIGHUP; waiting for children");
1139 				close_listen_socks();
1140 				lameduck = 1;
1141 			}
1142 			if (listening <= 0) {
1143 				sigprocmask(SIG_SETMASK, &osigset, NULL);
1144 				sighup_restart();
1145 			}
1146 		}
1147 		free(fdset);
1148 		fdset = xcalloc(howmany(maxfd + 1, NFDBITS),
1149 		    sizeof(fd_mask));
1150 
1151 		for (i = 0; i < num_listen_socks; i++)
1152 			FD_SET(listen_socks[i], fdset);
1153 		for (i = 0; i < options.max_startups; i++)
1154 			if (startup_pipes[i] != -1)
1155 				FD_SET(startup_pipes[i], fdset);
1156 
1157 		/* Wait until a connection arrives or a child exits. */
1158 		ret = pselect(maxfd+1, fdset, NULL, NULL, NULL, &osigset);
1159 		if (ret == -1 && errno != EINTR)
1160 			error("pselect: %.100s", strerror(errno));
1161 		sigprocmask(SIG_SETMASK, &osigset, NULL);
1162 		if (received_sigterm)
1163 			continue;
1164 
1165 		for (i = 0; i < options.max_startups; i++) {
1166 			if (startup_pipes[i] == -1 ||
1167 			    !FD_ISSET(startup_pipes[i], fdset))
1168 				continue;
1169 			switch (read(startup_pipes[i], &c, sizeof(c))) {
1170 			case -1:
1171 				if (errno == EINTR || errno == EAGAIN)
1172 					continue;
1173 				if (errno != EPIPE) {
1174 					error_f("startup pipe %d (fd=%d): "
1175 					    "read %s", i, startup_pipes[i],
1176 					    strerror(errno));
1177 				}
1178 				/* FALLTHROUGH */
1179 			case 0:
1180 				/* child exited or completed auth */
1181 				close(startup_pipes[i]);
1182 				srclimit_done(startup_pipes[i]);
1183 				startup_pipes[i] = -1;
1184 				startups--;
1185 				if (startup_flags[i])
1186 					listening--;
1187 				break;
1188 			case 1:
1189 				/* child has finished preliminaries */
1190 				if (startup_flags[i]) {
1191 					listening--;
1192 					startup_flags[i] = 0;
1193 				}
1194 				break;
1195 			}
1196 		}
1197 		for (i = 0; i < num_listen_socks; i++) {
1198 			if (!FD_ISSET(listen_socks[i], fdset))
1199 				continue;
1200 			fromlen = sizeof(from);
1201 			*newsock = accept(listen_socks[i],
1202 			    (struct sockaddr *)&from, &fromlen);
1203 			if (*newsock == -1) {
1204 				if (errno != EINTR && errno != EWOULDBLOCK &&
1205 				    errno != ECONNABORTED)
1206 					error("accept: %.100s",
1207 					    strerror(errno));
1208 				if (errno == EMFILE || errno == ENFILE)
1209 					usleep(100 * 1000);
1210 				continue;
1211 			}
1212 			if (unset_nonblock(*newsock) == -1 ||
1213 			    pipe(startup_p) == -1)
1214 				continue;
1215 			if (drop_connection(*newsock, startups, startup_p[0])) {
1216 				close(*newsock);
1217 				close(startup_p[0]);
1218 				close(startup_p[1]);
1219 				continue;
1220 			}
1221 
1222 			if (rexec_flag && socketpair(AF_UNIX,
1223 			    SOCK_STREAM, 0, config_s) == -1) {
1224 				error("reexec socketpair: %s",
1225 				    strerror(errno));
1226 				close(*newsock);
1227 				close(startup_p[0]);
1228 				close(startup_p[1]);
1229 				continue;
1230 			}
1231 
1232 			for (j = 0; j < options.max_startups; j++)
1233 				if (startup_pipes[j] == -1) {
1234 					startup_pipes[j] = startup_p[0];
1235 					if (maxfd < startup_p[0])
1236 						maxfd = startup_p[0];
1237 					startups++;
1238 					startup_flags[j] = 1;
1239 					break;
1240 				}
1241 
1242 			/*
1243 			 * Got connection.  Fork a child to handle it, unless
1244 			 * we are in debugging mode.
1245 			 */
1246 			if (debug_flag) {
1247 				/*
1248 				 * In debugging mode.  Close the listening
1249 				 * socket, and start processing the
1250 				 * connection without forking.
1251 				 */
1252 				debug("Server will not fork when running in debugging mode.");
1253 				close_listen_socks();
1254 				*sock_in = *newsock;
1255 				*sock_out = *newsock;
1256 				close(startup_p[0]);
1257 				close(startup_p[1]);
1258 				startup_pipe = -1;
1259 				pid = getpid();
1260 				if (rexec_flag) {
1261 					send_rexec_state(config_s[0], cfg);
1262 					close(config_s[0]);
1263 				}
1264 				return;
1265 			}
1266 
1267 			/*
1268 			 * Normal production daemon.  Fork, and have
1269 			 * the child process the connection. The
1270 			 * parent continues listening.
1271 			 */
1272 			listening++;
1273 			if ((pid = fork()) == 0) {
1274 				/*
1275 				 * Child.  Close the listening and
1276 				 * max_startup sockets.  Start using
1277 				 * the accepted socket. Reinitialize
1278 				 * logging (since our pid has changed).
1279 				 * We return from this function to handle
1280 				 * the connection.
1281 				 */
1282 				startup_pipe = startup_p[1];
1283 				close_startup_pipes();
1284 				close_listen_socks();
1285 				*sock_in = *newsock;
1286 				*sock_out = *newsock;
1287 				log_init(__progname,
1288 				    options.log_level,
1289 				    options.log_facility,
1290 				    log_stderr);
1291 				if (rexec_flag)
1292 					close(config_s[0]);
1293 				else {
1294 					/*
1295 					 * Signal parent that the preliminaries
1296 					 * for this child are complete. For the
1297 					 * re-exec case, this happens after the
1298 					 * child has received the rexec state
1299 					 * from the server.
1300 					 */
1301 					(void)atomicio(vwrite, startup_pipe,
1302 					    "\0", 1);
1303 				}
1304 				return;
1305 			}
1306 
1307 			/* Parent.  Stay in the loop. */
1308 			if (pid == -1)
1309 				error("fork: %.100s", strerror(errno));
1310 			else
1311 				debug("Forked child %ld.", (long)pid);
1312 
1313 			close(startup_p[1]);
1314 
1315 			if (rexec_flag) {
1316 				close(config_s[1]);
1317 				send_rexec_state(config_s[0], cfg);
1318 				close(config_s[0]);
1319 			}
1320 			close(*newsock);
1321 		}
1322 	}
1323 }
1324 
1325 /*
1326  * If IP options are supported, make sure there are none (log and
1327  * return an error if any are found).  Basically we are worried about
1328  * source routing; it can be used to pretend you are somebody
1329  * (ip-address) you are not. That itself may be "almost acceptable"
1330  * under certain circumstances, but rhosts authentication is useless
1331  * if source routing is accepted. Notice also that if we just dropped
1332  * source routing here, the other side could use IP spoofing to do
1333  * rest of the interaction and could still bypass security.  So we
1334  * exit here if we detect any IP options.
1335  */
1336 static void
1337 check_ip_options(struct ssh *ssh)
1338 {
1339 	int sock_in = ssh_packet_get_connection_in(ssh);
1340 	struct sockaddr_storage from;
1341 	u_char opts[200];
1342 	socklen_t i, option_size = sizeof(opts), fromlen = sizeof(from);
1343 	char text[sizeof(opts) * 3 + 1];
1344 
1345 	memset(&from, 0, sizeof(from));
1346 	if (getpeername(sock_in, (struct sockaddr *)&from,
1347 	    &fromlen) == -1)
1348 		return;
1349 	if (from.ss_family != AF_INET)
1350 		return;
1351 	/* XXX IPv6 options? */
1352 
1353 	if (getsockopt(sock_in, IPPROTO_IP, IP_OPTIONS, opts,
1354 	    &option_size) >= 0 && option_size != 0) {
1355 		text[0] = '\0';
1356 		for (i = 0; i < option_size; i++)
1357 			snprintf(text + i*3, sizeof(text) - i*3,
1358 			    " %2.2x", opts[i]);
1359 		fatal("Connection from %.100s port %d with IP opts: %.800s",
1360 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), text);
1361 	}
1362 	return;
1363 }
1364 
1365 /* Set the routing domain for this process */
1366 static void
1367 set_process_rdomain(struct ssh *ssh, const char *name)
1368 {
1369 	int rtable, ortable = getrtable();
1370 	const char *errstr;
1371 
1372 	if (name == NULL)
1373 		return; /* default */
1374 
1375 	if (strcmp(name, "%D") == 0) {
1376 		/* "expands" to routing domain of connection */
1377 		if ((name = ssh_packet_rdomain_in(ssh)) == NULL)
1378 			return;
1379 	}
1380 
1381 	rtable = (int)strtonum(name, 0, 255, &errstr);
1382 	if (errstr != NULL) /* Shouldn't happen */
1383 		fatal("Invalid routing domain \"%s\": %s", name, errstr);
1384 	if (rtable != ortable && setrtable(rtable) != 0)
1385 		fatal("Unable to set routing domain %d: %s",
1386 		    rtable, strerror(errno));
1387 	debug_f("set routing domain %d (was %d)", rtable, ortable);
1388 }
1389 
1390 static void
1391 accumulate_host_timing_secret(struct sshbuf *server_cfg,
1392     struct sshkey *key)
1393 {
1394 	static struct ssh_digest_ctx *ctx;
1395 	u_char *hash;
1396 	size_t len;
1397 	struct sshbuf *buf;
1398 	int r;
1399 
1400 	if (ctx == NULL && (ctx = ssh_digest_start(SSH_DIGEST_SHA512)) == NULL)
1401 		fatal_f("ssh_digest_start");
1402 	if (key == NULL) { /* finalize */
1403 		/* add server config in case we are using agent for host keys */
1404 		if (ssh_digest_update(ctx, sshbuf_ptr(server_cfg),
1405 		    sshbuf_len(server_cfg)) != 0)
1406 			fatal_f("ssh_digest_update");
1407 		len = ssh_digest_bytes(SSH_DIGEST_SHA512);
1408 		hash = xmalloc(len);
1409 		if (ssh_digest_final(ctx, hash, len) != 0)
1410 			fatal_f("ssh_digest_final");
1411 		options.timing_secret = PEEK_U64(hash);
1412 		freezero(hash, len);
1413 		ssh_digest_free(ctx);
1414 		ctx = NULL;
1415 		return;
1416 	}
1417 	if ((buf = sshbuf_new()) == NULL)
1418 		fatal_f("could not allocate buffer");
1419 	if ((r = sshkey_private_serialize(key, buf)) != 0)
1420 		fatal_fr(r, "decode key");
1421 	if (ssh_digest_update(ctx, sshbuf_ptr(buf), sshbuf_len(buf)) != 0)
1422 		fatal_f("ssh_digest_update");
1423 	sshbuf_reset(buf);
1424 	sshbuf_free(buf);
1425 }
1426 
1427 static char *
1428 prepare_proctitle(int ac, char **av)
1429 {
1430 	char *ret = NULL;
1431 	int i;
1432 
1433 	for (i = 0; i < ac; i++)
1434 		xextendf(&ret, " ", "%s", av[i]);
1435 	return ret;
1436 }
1437 
1438 /*
1439  * Main program for the daemon.
1440  */
1441 int
1442 main(int ac, char **av)
1443 {
1444 	struct ssh *ssh = NULL;
1445 	extern char *optarg;
1446 	extern int optind;
1447 	int r, opt, on = 1, already_daemon, remote_port;
1448 	int sock_in = -1, sock_out = -1, newsock = -1;
1449 	const char *remote_ip, *rdomain;
1450 	char *fp, *line, *laddr, *logfile = NULL;
1451 	int config_s[2] = { -1 , -1 };
1452 	u_int i, j;
1453 	u_int64_t ibytes, obytes;
1454 	mode_t new_umask;
1455 	struct sshkey *key;
1456 	struct sshkey *pubkey;
1457 	int keytype;
1458 	Authctxt *authctxt;
1459 	struct connection_info *connection_info = NULL;
1460 
1461 	/* Save argv. */
1462 	saved_argv = av;
1463 	rexec_argc = ac;
1464 
1465 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1466 	sanitise_stdfd();
1467 
1468 	/* Initialize configuration options to their default values. */
1469 	initialize_server_options(&options);
1470 
1471 	/* Parse command-line arguments. */
1472 	while ((opt = getopt(ac, av,
1473 	    "C:E:b:c:f:g:h:k:o:p:u:46DQRTdeiqrt")) != -1) {
1474 		switch (opt) {
1475 		case '4':
1476 			options.address_family = AF_INET;
1477 			break;
1478 		case '6':
1479 			options.address_family = AF_INET6;
1480 			break;
1481 		case 'f':
1482 			config_file_name = optarg;
1483 			break;
1484 		case 'c':
1485 			servconf_add_hostcert("[command-line]", 0,
1486 			    &options, optarg);
1487 			break;
1488 		case 'd':
1489 			if (debug_flag == 0) {
1490 				debug_flag = 1;
1491 				options.log_level = SYSLOG_LEVEL_DEBUG1;
1492 			} else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1493 				options.log_level++;
1494 			break;
1495 		case 'D':
1496 			no_daemon_flag = 1;
1497 			break;
1498 		case 'E':
1499 			logfile = optarg;
1500 			/* FALLTHROUGH */
1501 		case 'e':
1502 			log_stderr = 1;
1503 			break;
1504 		case 'i':
1505 			inetd_flag = 1;
1506 			break;
1507 		case 'r':
1508 			rexec_flag = 0;
1509 			break;
1510 		case 'R':
1511 			rexeced_flag = 1;
1512 			inetd_flag = 1;
1513 			break;
1514 		case 'Q':
1515 			/* ignored */
1516 			break;
1517 		case 'q':
1518 			options.log_level = SYSLOG_LEVEL_QUIET;
1519 			break;
1520 		case 'b':
1521 			/* protocol 1, ignored */
1522 			break;
1523 		case 'p':
1524 			options.ports_from_cmdline = 1;
1525 			if (options.num_ports >= MAX_PORTS) {
1526 				fprintf(stderr, "too many ports.\n");
1527 				exit(1);
1528 			}
1529 			options.ports[options.num_ports++] = a2port(optarg);
1530 			if (options.ports[options.num_ports-1] <= 0) {
1531 				fprintf(stderr, "Bad port number.\n");
1532 				exit(1);
1533 			}
1534 			break;
1535 		case 'g':
1536 			if ((options.login_grace_time = convtime(optarg)) == -1) {
1537 				fprintf(stderr, "Invalid login grace time.\n");
1538 				exit(1);
1539 			}
1540 			break;
1541 		case 'k':
1542 			/* protocol 1, ignored */
1543 			break;
1544 		case 'h':
1545 			servconf_add_hostkey("[command-line]", 0,
1546 			    &options, optarg, 1);
1547 			break;
1548 		case 't':
1549 			test_flag = 1;
1550 			break;
1551 		case 'T':
1552 			test_flag = 2;
1553 			break;
1554 		case 'C':
1555 			connection_info = get_connection_info(ssh, 0, 0);
1556 			if (parse_server_match_testspec(connection_info,
1557 			    optarg) == -1)
1558 				exit(1);
1559 			break;
1560 		case 'u':
1561 			utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
1562 			if (utmp_len > HOST_NAME_MAX+1) {
1563 				fprintf(stderr, "Invalid utmp length.\n");
1564 				exit(1);
1565 			}
1566 			break;
1567 		case 'o':
1568 			line = xstrdup(optarg);
1569 			if (process_server_config_line(&options, line,
1570 			    "command-line", 0, NULL, NULL, &includes) != 0)
1571 				exit(1);
1572 			free(line);
1573 			break;
1574 		case '?':
1575 		default:
1576 			usage();
1577 			break;
1578 		}
1579 	}
1580 	if (rexeced_flag || inetd_flag)
1581 		rexec_flag = 0;
1582 	if (!test_flag && rexec_flag && !path_absolute(av[0]))
1583 		fatal("sshd re-exec requires execution with an absolute path");
1584 	if (rexeced_flag)
1585 		closefrom(REEXEC_MIN_FREE_FD);
1586 	else
1587 		closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1588 
1589 #ifdef WITH_OPENSSL
1590 	OpenSSL_add_all_algorithms();
1591 #endif
1592 
1593 	/* If requested, redirect the logs to the specified logfile. */
1594 	if (logfile != NULL)
1595 		log_redirect_stderr_to(logfile);
1596 	/*
1597 	 * Force logging to stderr until we have loaded the private host
1598 	 * key (unless started from inetd)
1599 	 */
1600 	log_init(__progname,
1601 	    options.log_level == SYSLOG_LEVEL_NOT_SET ?
1602 	    SYSLOG_LEVEL_INFO : options.log_level,
1603 	    options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1604 	    SYSLOG_FACILITY_AUTH : options.log_facility,
1605 	    log_stderr || !inetd_flag || debug_flag);
1606 
1607 	sensitive_data.have_ssh2_key = 0;
1608 
1609 	/*
1610 	 * If we're not doing an extended test do not silently ignore connection
1611 	 * test params.
1612 	 */
1613 	if (test_flag < 2 && connection_info != NULL)
1614 		fatal("Config test connection parameter (-C) provided without "
1615 		    "test mode (-T)");
1616 
1617 	/* Fetch our configuration */
1618 	if ((cfg = sshbuf_new()) == NULL)
1619 		fatal_f("sshbuf_new failed");
1620 	if (rexeced_flag) {
1621 		setproctitle("%s", "[rexeced]");
1622 		recv_rexec_state(REEXEC_CONFIG_PASS_FD, cfg);
1623 		if (!debug_flag) {
1624 			startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
1625 			close(REEXEC_STARTUP_PIPE_FD);
1626 			/*
1627 			 * Signal parent that this child is at a point where
1628 			 * they can go away if they have a SIGHUP pending.
1629 			 */
1630 			(void)atomicio(vwrite, startup_pipe, "\0", 1);
1631 		}
1632 	} else if (strcasecmp(config_file_name, "none") != 0)
1633 		load_server_config(config_file_name, cfg);
1634 
1635 	parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1636 	    cfg, &includes, NULL);
1637 
1638 	if (options.moduli_file != NULL)
1639 		dh_set_moduli_file(options.moduli_file);
1640 
1641 	/* Fill in default values for those options not explicitly set. */
1642 	fill_default_server_options(&options);
1643 
1644 	/* challenge-response is implemented via keyboard interactive */
1645 	if (options.challenge_response_authentication)
1646 		options.kbd_interactive_authentication = 1;
1647 
1648 	/* Check that options are sensible */
1649 	if (options.authorized_keys_command_user == NULL &&
1650 	    (options.authorized_keys_command != NULL &&
1651 	    strcasecmp(options.authorized_keys_command, "none") != 0))
1652 		fatal("AuthorizedKeysCommand set without "
1653 		    "AuthorizedKeysCommandUser");
1654 	if (options.authorized_principals_command_user == NULL &&
1655 	    (options.authorized_principals_command != NULL &&
1656 	    strcasecmp(options.authorized_principals_command, "none") != 0))
1657 		fatal("AuthorizedPrincipalsCommand set without "
1658 		    "AuthorizedPrincipalsCommandUser");
1659 
1660 	/*
1661 	 * Check whether there is any path through configured auth methods.
1662 	 * Unfortunately it is not possible to verify this generally before
1663 	 * daemonisation in the presence of Match block, but this catches
1664 	 * and warns for trivial misconfigurations that could break login.
1665 	 */
1666 	if (options.num_auth_methods != 0) {
1667 		for (i = 0; i < options.num_auth_methods; i++) {
1668 			if (auth2_methods_valid(options.auth_methods[i],
1669 			    1) == 0)
1670 				break;
1671 		}
1672 		if (i >= options.num_auth_methods)
1673 			fatal("AuthenticationMethods cannot be satisfied by "
1674 			    "enabled authentication methods");
1675 	}
1676 
1677 	/* Check that there are no remaining arguments. */
1678 	if (optind < ac) {
1679 		fprintf(stderr, "Extra argument %s.\n", av[optind]);
1680 		exit(1);
1681 	}
1682 
1683 	debug("sshd version %s, %s", SSH_VERSION, SSH_OPENSSL_VERSION);
1684 
1685 	/* load host keys */
1686 	sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1687 	    sizeof(struct sshkey *));
1688 	sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
1689 	    sizeof(struct sshkey *));
1690 
1691 	if (options.host_key_agent) {
1692 		if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
1693 			setenv(SSH_AUTHSOCKET_ENV_NAME,
1694 			    options.host_key_agent, 1);
1695 		if ((r = ssh_get_authentication_socket(NULL)) == 0)
1696 			have_agent = 1;
1697 		else
1698 			error_r(r, "Could not connect to agent \"%s\"",
1699 			    options.host_key_agent);
1700 	}
1701 
1702 	for (i = 0; i < options.num_host_key_files; i++) {
1703 		int ll = options.host_key_file_userprovided[i] ?
1704 		    SYSLOG_LEVEL_ERROR : SYSLOG_LEVEL_DEBUG1;
1705 
1706 		if (options.host_key_files[i] == NULL)
1707 			continue;
1708 		if ((r = sshkey_load_private(options.host_key_files[i], "",
1709 		    &key, 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 (sshkey_is_sk(key) &&
1713 		    key->sk_flags & SSH_SK_USER_PRESENCE_REQD) {
1714 			debug("host key %s requires user presence, ignoring",
1715 			    options.host_key_files[i]);
1716 			key->sk_flags &= ~SSH_SK_USER_PRESENCE_REQD;
1717 		}
1718 		if (r == 0 && key != NULL &&
1719 		    (r = sshkey_shield_private(key)) != 0) {
1720 			do_log2_r(r, ll, "Unable to shield host key \"%s\"",
1721 			    options.host_key_files[i]);
1722 			sshkey_free(key);
1723 			key = NULL;
1724 		}
1725 		if ((r = sshkey_load_public(options.host_key_files[i],
1726 		    &pubkey, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR)
1727 			do_log2_r(r, ll, "Unable to load host key \"%s\"",
1728 			    options.host_key_files[i]);
1729 		if (pubkey != NULL && key != NULL) {
1730 			if (!sshkey_equal(pubkey, key)) {
1731 				error("Public key for %s does not match "
1732 				    "private key", options.host_key_files[i]);
1733 				sshkey_free(pubkey);
1734 				pubkey = NULL;
1735 			}
1736 		}
1737 		if (pubkey == NULL && key != NULL) {
1738 			if ((r = sshkey_from_private(key, &pubkey)) != 0)
1739 				fatal_r(r, "Could not demote key: \"%s\"",
1740 				    options.host_key_files[i]);
1741 		}
1742 		sensitive_data.host_keys[i] = key;
1743 		sensitive_data.host_pubkeys[i] = pubkey;
1744 
1745 		if (key == NULL && pubkey != NULL && have_agent) {
1746 			debug("will rely on agent for hostkey %s",
1747 			    options.host_key_files[i]);
1748 			keytype = pubkey->type;
1749 		} else if (key != NULL) {
1750 			keytype = key->type;
1751 			accumulate_host_timing_secret(cfg, key);
1752 		} else {
1753 			do_log2(ll, "Unable to load host key: %s",
1754 			    options.host_key_files[i]);
1755 			sensitive_data.host_keys[i] = NULL;
1756 			sensitive_data.host_pubkeys[i] = NULL;
1757 			continue;
1758 		}
1759 
1760 		switch (keytype) {
1761 		case KEY_RSA:
1762 		case KEY_DSA:
1763 		case KEY_ECDSA:
1764 		case KEY_ED25519:
1765 		case KEY_ECDSA_SK:
1766 		case KEY_ED25519_SK:
1767 		case KEY_XMSS:
1768 			if (have_agent || key != NULL)
1769 				sensitive_data.have_ssh2_key = 1;
1770 			break;
1771 		}
1772 		if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash,
1773 		    SSH_FP_DEFAULT)) == NULL)
1774 			fatal("sshkey_fingerprint failed");
1775 		debug("%s host key #%d: %s %s",
1776 		    key ? "private" : "agent", i, sshkey_ssh_name(pubkey), fp);
1777 		free(fp);
1778 	}
1779 	accumulate_host_timing_secret(cfg, NULL);
1780 	if (!sensitive_data.have_ssh2_key) {
1781 		logit("sshd: no hostkeys available -- exiting.");
1782 		exit(1);
1783 	}
1784 
1785 	/*
1786 	 * Load certificates. They are stored in an array at identical
1787 	 * indices to the public keys that they relate to.
1788 	 */
1789 	sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
1790 	    sizeof(struct sshkey *));
1791 	for (i = 0; i < options.num_host_key_files; i++)
1792 		sensitive_data.host_certificates[i] = NULL;
1793 
1794 	for (i = 0; i < options.num_host_cert_files; i++) {
1795 		if (options.host_cert_files[i] == NULL)
1796 			continue;
1797 		if ((r = sshkey_load_public(options.host_cert_files[i],
1798 		    &key, NULL)) != 0) {
1799 			error_r(r, "Could not load host certificate \"%s\"",
1800 			    options.host_cert_files[i]);
1801 			continue;
1802 		}
1803 		if (!sshkey_is_cert(key)) {
1804 			error("Certificate file is not a certificate: %s",
1805 			    options.host_cert_files[i]);
1806 			sshkey_free(key);
1807 			continue;
1808 		}
1809 		/* Find matching private key */
1810 		for (j = 0; j < options.num_host_key_files; j++) {
1811 			if (sshkey_equal_public(key,
1812 			    sensitive_data.host_pubkeys[j])) {
1813 				sensitive_data.host_certificates[j] = key;
1814 				break;
1815 			}
1816 		}
1817 		if (j >= options.num_host_key_files) {
1818 			error("No matching private key for certificate: %s",
1819 			    options.host_cert_files[i]);
1820 			sshkey_free(key);
1821 			continue;
1822 		}
1823 		sensitive_data.host_certificates[j] = key;
1824 		debug("host certificate: #%u type %d %s", j, key->type,
1825 		    sshkey_type(key));
1826 	}
1827 
1828 	if (use_privsep) {
1829 		struct stat st;
1830 
1831 		if (getpwnam(SSH_PRIVSEP_USER) == NULL)
1832 			fatal("Privilege separation user %s does not exist",
1833 			    SSH_PRIVSEP_USER);
1834 		endpwent();
1835 		if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1836 		    (S_ISDIR(st.st_mode) == 0))
1837 			fatal("Missing privilege separation directory: %s",
1838 			    _PATH_PRIVSEP_CHROOT_DIR);
1839 		if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1840 			fatal("%s must be owned by root and not group or "
1841 			    "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1842 	}
1843 
1844 	if (test_flag > 1) {
1845 		/*
1846 		 * If no connection info was provided by -C then use
1847 		 * use a blank one that will cause no predicate to match.
1848 		 */
1849 		if (connection_info == NULL)
1850 			connection_info = get_connection_info(ssh, 0, 0);
1851 		connection_info->test = 1;
1852 		parse_server_match_config(&options, &includes, connection_info);
1853 		dump_config(&options);
1854 	}
1855 
1856 	/* Configuration looks good, so exit if in test mode. */
1857 	if (test_flag)
1858 		exit(0);
1859 
1860 	if (rexec_flag) {
1861 		if (rexec_argc < 0)
1862 			fatal("rexec_argc %d < 0", rexec_argc);
1863 		rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1864 		for (i = 0; i < (u_int)rexec_argc; i++) {
1865 			debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1866 			rexec_argv[i] = saved_argv[i];
1867 		}
1868 		rexec_argv[rexec_argc] = "-R";
1869 		rexec_argv[rexec_argc + 1] = NULL;
1870 	}
1871 	listener_proctitle = prepare_proctitle(ac, av);
1872 
1873 	/* Ensure that umask disallows at least group and world write */
1874 	new_umask = umask(0077) | 0022;
1875 	(void) umask(new_umask);
1876 
1877 	/* Initialize the log (it is reinitialized below in case we forked). */
1878 	if (debug_flag && (!inetd_flag || rexeced_flag))
1879 		log_stderr = 1;
1880 	log_init(__progname, options.log_level,
1881 	    options.log_facility, log_stderr);
1882 	for (i = 0; i < options.num_log_verbose; i++)
1883 		log_verbose_add(options.log_verbose[i]);
1884 
1885 	/*
1886 	 * If not in debugging mode, not started from inetd and not already
1887 	 * daemonized (eg re-exec via SIGHUP), disconnect from the controlling
1888 	 * terminal, and fork.  The original process exits.
1889 	 */
1890 	already_daemon = daemonized();
1891 	if (!(debug_flag || inetd_flag || no_daemon_flag || already_daemon)) {
1892 
1893 		if (daemon(0, 0) == -1)
1894 			fatal("daemon() failed: %.200s", strerror(errno));
1895 
1896 		disconnect_controlling_tty();
1897 	}
1898 	/* Reinitialize the log (because of the fork above). */
1899 	log_init(__progname, options.log_level, options.log_facility, log_stderr);
1900 
1901 	/*
1902 	 * Chdir to the root directory so that the current disk can be
1903 	 * unmounted if desired.
1904 	 */
1905 	if (chdir("/") == -1)
1906 		error("chdir(\"/\"): %s", strerror(errno));
1907 
1908 	/* ignore SIGPIPE */
1909 	ssh_signal(SIGPIPE, SIG_IGN);
1910 
1911 	/* Get a connection, either from inetd or a listening TCP socket */
1912 	if (inetd_flag) {
1913 		server_accept_inetd(&sock_in, &sock_out);
1914 	} else {
1915 		server_listen();
1916 
1917 		ssh_signal(SIGHUP, sighup_handler);
1918 		ssh_signal(SIGCHLD, main_sigchld_handler);
1919 		ssh_signal(SIGTERM, sigterm_handler);
1920 		ssh_signal(SIGQUIT, sigterm_handler);
1921 
1922 		/*
1923 		 * Write out the pid file after the sigterm handler
1924 		 * is setup and the listen sockets are bound
1925 		 */
1926 		if (options.pid_file != NULL && !debug_flag) {
1927 			FILE *f = fopen(options.pid_file, "w");
1928 
1929 			if (f == NULL) {
1930 				error("Couldn't create pid file \"%s\": %s",
1931 				    options.pid_file, strerror(errno));
1932 			} else {
1933 				fprintf(f, "%ld\n", (long) getpid());
1934 				fclose(f);
1935 			}
1936 		}
1937 
1938 		/* Accept a connection and return in a forked child */
1939 		server_accept_loop(&sock_in, &sock_out,
1940 		    &newsock, config_s);
1941 	}
1942 
1943 	/* This is the child processing a new connection. */
1944 	setproctitle("%s", "[accepted]");
1945 
1946 	/*
1947 	 * Create a new session and process group since the 4.4BSD
1948 	 * setlogin() affects the entire process group.  We don't
1949 	 * want the child to be able to affect the parent.
1950 	 */
1951 	if (!debug_flag && !inetd_flag && setsid() == -1)
1952 		error("setsid: %.100s", strerror(errno));
1953 
1954 	if (rexec_flag) {
1955 		debug("rexec start in %d out %d newsock %d pipe %d sock %d",
1956 		    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1957 		dup2(newsock, STDIN_FILENO);
1958 		dup2(STDIN_FILENO, STDOUT_FILENO);
1959 		if (startup_pipe == -1)
1960 			close(REEXEC_STARTUP_PIPE_FD);
1961 		else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) {
1962 			dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
1963 			close(startup_pipe);
1964 			startup_pipe = REEXEC_STARTUP_PIPE_FD;
1965 		}
1966 
1967 		dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1968 		close(config_s[1]);
1969 
1970 		ssh_signal(SIGHUP, SIG_IGN); /* avoid reset to SIG_DFL */
1971 		execv(rexec_argv[0], rexec_argv);
1972 
1973 		/* Reexec has failed, fall back and continue */
1974 		error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1975 		recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1976 		log_init(__progname, options.log_level,
1977 		    options.log_facility, log_stderr);
1978 
1979 		/* Clean up fds */
1980 		close(REEXEC_CONFIG_PASS_FD);
1981 		newsock = sock_out = sock_in = dup(STDIN_FILENO);
1982 		if (stdfd_devnull(1, 1, 0) == -1)
1983 			error_f("stdfd_devnull failed");
1984 		debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
1985 		    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1986 	}
1987 
1988 	/* Executed child processes don't need these. */
1989 	fcntl(sock_out, F_SETFD, FD_CLOEXEC);
1990 	fcntl(sock_in, F_SETFD, FD_CLOEXEC);
1991 
1992 	/* We will not restart on SIGHUP since it no longer makes sense. */
1993 	ssh_signal(SIGALRM, SIG_DFL);
1994 	ssh_signal(SIGHUP, SIG_DFL);
1995 	ssh_signal(SIGTERM, SIG_DFL);
1996 	ssh_signal(SIGQUIT, SIG_DFL);
1997 	ssh_signal(SIGCHLD, SIG_DFL);
1998 
1999 	/*
2000 	 * Register our connection.  This turns encryption off because we do
2001 	 * not have a key.
2002 	 */
2003 	if ((ssh = ssh_packet_set_connection(NULL, sock_in, sock_out)) == NULL)
2004 		fatal("Unable to create connection");
2005 	the_active_state = ssh;
2006 	ssh_packet_set_server(ssh);
2007 
2008 	check_ip_options(ssh);
2009 
2010 	/* Prepare the channels layer */
2011 	channel_init_channels(ssh);
2012 	channel_set_af(ssh, options.address_family);
2013 	process_permitopen(ssh, &options);
2014 
2015 	/* Set SO_KEEPALIVE if requested. */
2016 	if (options.tcp_keep_alive && ssh_packet_connection_is_on_socket(ssh) &&
2017 	    setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) == -1)
2018 		error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
2019 
2020 	if ((remote_port = ssh_remote_port(ssh)) < 0) {
2021 		debug("ssh_remote_port failed");
2022 		cleanup_exit(255);
2023 	}
2024 
2025 	/*
2026 	 * The rest of the code depends on the fact that
2027 	 * ssh_remote_ipaddr() caches the remote ip, even if
2028 	 * the socket goes away.
2029 	 */
2030 	remote_ip = ssh_remote_ipaddr(ssh);
2031 
2032 	rdomain = ssh_packet_rdomain_in(ssh);
2033 
2034 	/* Log the connection. */
2035 	laddr = get_local_ipaddr(sock_in);
2036 	verbose("Connection from %s port %d on %s port %d%s%s%s",
2037 	    remote_ip, remote_port, laddr,  ssh_local_port(ssh),
2038 	    rdomain == NULL ? "" : " rdomain \"",
2039 	    rdomain == NULL ? "" : rdomain,
2040 	    rdomain == NULL ? "" : "\"");
2041 	free(laddr);
2042 
2043 	/*
2044 	 * We don't want to listen forever unless the other side
2045 	 * successfully authenticates itself.  So we set up an alarm which is
2046 	 * cleared after successful authentication.  A limit of zero
2047 	 * indicates no limit. Note that we don't set the alarm in debugging
2048 	 * mode; it is just annoying to have the server exit just when you
2049 	 * are about to discover the bug.
2050 	 */
2051 	ssh_signal(SIGALRM, grace_alarm_handler);
2052 	if (!debug_flag)
2053 		alarm(options.login_grace_time);
2054 
2055 	if ((r = kex_exchange_identification(ssh, -1,
2056 	    options.version_addendum)) != 0)
2057 		sshpkt_fatal(ssh, r, "banner exchange");
2058 
2059 	ssh_packet_set_nonblocking(ssh);
2060 
2061 	/* allocate authentication context */
2062 	authctxt = xcalloc(1, sizeof(*authctxt));
2063 	ssh->authctxt = authctxt;
2064 
2065 	/* XXX global for cleanup, access from other modules */
2066 	the_authctxt = authctxt;
2067 
2068 	/* Set default key authentication options */
2069 	if ((auth_opts = sshauthopt_new_with_keys_defaults()) == NULL)
2070 		fatal("allocation failed");
2071 
2072 	/* prepare buffer to collect messages to display to user after login */
2073 	if ((loginmsg = sshbuf_new()) == NULL)
2074 		fatal_f("sshbuf_new failed");
2075 	auth_debug_reset();
2076 
2077 	if (use_privsep) {
2078 		if (privsep_preauth(ssh) == 1)
2079 			goto authenticated;
2080 	} else if (have_agent) {
2081 		if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) {
2082 			error_r(r, "Unable to get agent socket");
2083 			have_agent = 0;
2084 		}
2085 	}
2086 
2087 	/* perform the key exchange */
2088 	/* authenticate user and start session */
2089 	do_ssh2_kex(ssh);
2090 	do_authentication2(ssh);
2091 
2092 	/*
2093 	 * If we use privilege separation, the unprivileged child transfers
2094 	 * the current keystate and exits
2095 	 */
2096 	if (use_privsep) {
2097 		mm_send_keystate(ssh, pmonitor);
2098 		ssh_packet_clear_keys(ssh);
2099 		exit(0);
2100 	}
2101 
2102  authenticated:
2103 	/*
2104 	 * Cancel the alarm we set to limit the time taken for
2105 	 * authentication.
2106 	 */
2107 	alarm(0);
2108 	ssh_signal(SIGALRM, SIG_DFL);
2109 	authctxt->authenticated = 1;
2110 	if (startup_pipe != -1) {
2111 		close(startup_pipe);
2112 		startup_pipe = -1;
2113 	}
2114 
2115 	if (options.routing_domain != NULL)
2116 		set_process_rdomain(ssh, options.routing_domain);
2117 
2118 	/*
2119 	 * In privilege separation, we fork another child and prepare
2120 	 * file descriptor passing.
2121 	 */
2122 	if (use_privsep) {
2123 		privsep_postauth(ssh, authctxt);
2124 		/* the monitor process [priv] will not return */
2125 	}
2126 
2127 	ssh_packet_set_timeout(ssh, options.client_alive_interval,
2128 	    options.client_alive_count_max);
2129 
2130 	/* Try to send all our hostkeys to the client */
2131 	notify_hostkeys(ssh);
2132 
2133 	/* Start session. */
2134 	do_authenticated(ssh, authctxt);
2135 
2136 	/* The connection has been terminated. */
2137 	ssh_packet_get_bytes(ssh, &ibytes, &obytes);
2138 	verbose("Transferred: sent %llu, received %llu bytes",
2139 	    (unsigned long long)obytes, (unsigned long long)ibytes);
2140 
2141 	verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
2142 	ssh_packet_close(ssh);
2143 
2144 	if (use_privsep)
2145 		mm_terminate();
2146 
2147 	exit(0);
2148 }
2149 
2150 int
2151 sshd_hostkey_sign(struct ssh *ssh, struct sshkey *privkey,
2152     struct sshkey *pubkey, u_char **signature, size_t *slenp,
2153     const u_char *data, size_t dlen, const char *alg)
2154 {
2155 	int r;
2156 
2157 	if (use_privsep) {
2158 		if (privkey) {
2159 			if (mm_sshkey_sign(ssh, privkey, signature, slenp,
2160 			    data, dlen, alg, options.sk_provider, NULL,
2161 			    ssh->compat) < 0)
2162 				fatal_f("privkey sign failed");
2163 		} else {
2164 			if (mm_sshkey_sign(ssh, pubkey, signature, slenp,
2165 			    data, dlen, alg, options.sk_provider, NULL,
2166 			    ssh->compat) < 0)
2167 				fatal_f("pubkey sign failed");
2168 		}
2169 	} else {
2170 		if (privkey) {
2171 			if (sshkey_sign(privkey, signature, slenp, data, dlen,
2172 			    alg, options.sk_provider, NULL, ssh->compat) < 0)
2173 				fatal_f("privkey sign failed");
2174 		} else {
2175 			if ((r = ssh_agent_sign(auth_sock, pubkey,
2176 			    signature, slenp, data, dlen, alg,
2177 			    ssh->compat)) != 0) {
2178 				fatal_fr(r, "agent sign failed");
2179 			}
2180 		}
2181 	}
2182 	return 0;
2183 }
2184 
2185 /* SSH2 key exchange */
2186 static void
2187 do_ssh2_kex(struct ssh *ssh)
2188 {
2189 	char *myproposal[PROPOSAL_MAX] = { KEX_SERVER };
2190 	struct kex *kex;
2191 	int r;
2192 
2193 	myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(ssh,
2194 	    options.kex_algorithms);
2195 	myproposal[PROPOSAL_ENC_ALGS_CTOS] = compat_cipher_proposal(ssh,
2196 	    options.ciphers);
2197 	myproposal[PROPOSAL_ENC_ALGS_STOC] = compat_cipher_proposal(ssh,
2198 	    options.ciphers);
2199 	myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2200 	    myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2201 
2202 	if (options.compression == COMP_NONE) {
2203 		myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2204 		    myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2205 	}
2206 
2207 	if (options.rekey_limit || options.rekey_interval)
2208 		ssh_packet_set_rekey_limits(ssh, options.rekey_limit,
2209 		    options.rekey_interval);
2210 
2211 	myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal(
2212 	    ssh, list_hostkey_types());
2213 
2214 	/* start key exchange */
2215 	if ((r = kex_setup(ssh, myproposal)) != 0)
2216 		fatal_r(r, "kex_setup");
2217 	kex = ssh->kex;
2218 #ifdef WITH_OPENSSL
2219 	kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_server;
2220 	kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_server;
2221 	kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_server;
2222 	kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_server;
2223 	kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_server;
2224 	kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2225 	kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2226 	kex->kex[KEX_ECDH_SHA2] = kex_gen_server;
2227 #endif
2228 	kex->kex[KEX_C25519_SHA256] = kex_gen_server;
2229 	kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_server;
2230 	kex->load_host_public_key=&get_hostkey_public_by_type;
2231 	kex->load_host_private_key=&get_hostkey_private_by_type;
2232 	kex->host_key_index=&get_hostkey_index;
2233 	kex->sign = sshd_hostkey_sign;
2234 
2235 	ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &kex->done);
2236 
2237 #ifdef DEBUG_KEXDH
2238 	/* send 1st encrypted/maced/compressed message */
2239 	if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 ||
2240 	    (r = sshpkt_put_cstring(ssh, "markus")) != 0 ||
2241 	    (r = sshpkt_send(ssh)) != 0 ||
2242 	    (r = ssh_packet_write_wait(ssh)) != 0)
2243 		fatal_fr(r, "send test");
2244 #endif
2245 	debug("KEX done");
2246 }
2247 
2248 /* server specific fatal cleanup */
2249 void
2250 cleanup_exit(int i)
2251 {
2252 	if (the_active_state != NULL && the_authctxt != NULL) {
2253 		do_cleanup(the_active_state, the_authctxt);
2254 		if (use_privsep && privsep_is_preauth &&
2255 		    pmonitor != NULL && pmonitor->m_pid > 1) {
2256 			debug("Killing privsep child %d", pmonitor->m_pid);
2257 			if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
2258 			    errno != ESRCH) {
2259 				error_f("kill(%d): %s", pmonitor->m_pid,
2260 				    strerror(errno));
2261 			}
2262 		}
2263 	}
2264 	_exit(i);
2265 }
2266