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