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