xref: /netbsd-src/crypto/external/bsd/openssh/dist/sshd.c (revision bdc22b2e01993381dcefeff2bc9b56ca75a4235c)
1 /*	$NetBSD: sshd.c,v 1.31 2018/05/23 16:04:13 christos Exp $	*/
2 /* $OpenBSD: sshd.c,v 1.506 2018/03/03 03:15:51 djm Exp $ */
3 /*
4  * Author: Tatu Ylonen <ylo@cs.hut.fi>
5  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6  *                    All rights reserved
7  * This program is the ssh daemon.  It listens for connections from clients,
8  * and performs authentication, executes use commands or shell, and forwards
9  * information to/from the application to the user client over an encrypted
10  * connection.  This can also handle forwarding of X11, TCP/IP, and
11  * authentication agent connections.
12  *
13  * As far as I am concerned, the code I have written for this software
14  * can be used freely for any purpose.  Any derived versions of this
15  * software must be clearly marked as such, and if the derived work is
16  * incompatible with the protocol description in the RFC file, it must be
17  * called by a name other than "ssh" or "Secure Shell".
18  *
19  * SSH2 implementation:
20  * Privilege Separation:
21  *
22  * Copyright (c) 2000, 2001, 2002 Markus Friedl.  All rights reserved.
23  * Copyright (c) 2002 Niels Provos.  All rights reserved.
24  *
25  * Redistribution and use in source and binary forms, with or without
26  * modification, are permitted provided that the following conditions
27  * are met:
28  * 1. Redistributions of source code must retain the above copyright
29  *    notice, this list of conditions and the following disclaimer.
30  * 2. Redistributions in binary form must reproduce the above copyright
31  *    notice, this list of conditions and the following disclaimer in the
32  *    documentation and/or other materials provided with the distribution.
33  *
34  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
35  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
36  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
37  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
38  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
39  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
40  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
41  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
42  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
43  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44  */
45 
46 #include "includes.h"
47 __RCSID("$NetBSD: sshd.c,v 1.31 2018/05/23 16:04:13 christos Exp $");
48 #include <sys/types.h>
49 #include <sys/param.h>
50 #include <sys/ioctl.h>
51 #include <sys/wait.h>
52 #include <sys/tree.h>
53 #include <sys/stat.h>
54 #include <sys/socket.h>
55 #include <sys/time.h>
56 #include <sys/queue.h>
57 
58 #include <errno.h>
59 #include <fcntl.h>
60 #include <netdb.h>
61 #include <paths.h>
62 #include <pwd.h>
63 #include <signal.h>
64 #include <stdio.h>
65 #include <stdlib.h>
66 #include <string.h>
67 #include <unistd.h>
68 #include <limits.h>
69 
70 #ifdef WITH_OPENSSL
71 #include <openssl/bn.h>
72 #endif
73 
74 #include "xmalloc.h"
75 #include "ssh.h"
76 #include "ssh2.h"
77 #include "sshpty.h"
78 #include "packet.h"
79 #include "log.h"
80 #include "buffer.h"
81 #include "misc.h"
82 #include "match.h"
83 #include "servconf.h"
84 #include "uidswap.h"
85 #include "compat.h"
86 #include "cipher.h"
87 #include "digest.h"
88 #include "key.h"
89 #include "kex.h"
90 #include "myproposal.h"
91 #include "authfile.h"
92 #include "pathnames.h"
93 #include "atomicio.h"
94 #include "canohost.h"
95 #include "hostfile.h"
96 #include "auth.h"
97 #include "authfd.h"
98 #include "misc.h"
99 #include "msg.h"
100 #include "dispatch.h"
101 #include "channels.h"
102 #include "session.h"
103 #include "monitor.h"
104 #ifdef GSSAPI
105 #include "ssh-gss.h"
106 #endif
107 #include "monitor_wrap.h"
108 #include "ssh-sandbox.h"
109 #include "auth-options.h"
110 #include "version.h"
111 #include "ssherr.h"
112 
113 #include "pfilter.h"
114 
115 #ifdef LIBWRAP
116 #include <tcpd.h>
117 #include <syslog.h>
118 int allow_severity = LOG_INFO;
119 int deny_severity = LOG_WARNING;
120 #endif /* LIBWRAP */
121 
122 #ifdef WITH_LDAP_PUBKEY
123 #include "ldapauth.h"
124 #endif
125 
126 #ifndef HOST_NAME_MAX
127 #define HOST_NAME_MAX MAXHOSTNAMELEN
128 #endif
129 
130 /* Re-exec fds */
131 #define REEXEC_DEVCRYPTO_RESERVED_FD	(STDERR_FILENO + 1)
132 #define REEXEC_STARTUP_PIPE_FD		(STDERR_FILENO + 2)
133 #define REEXEC_CONFIG_PASS_FD		(STDERR_FILENO + 3)
134 #define REEXEC_MIN_FREE_FD		(STDERR_FILENO + 4)
135 
136 extern char *__progname;
137 
138 /* Server configuration options. */
139 ServerOptions options;
140 
141 /* Name of the server configuration file. */
142 const char *config_file_name = _PATH_SERVER_CONFIG_FILE;
143 
144 /*
145  * Debug mode flag.  This can be set on the command line.  If debug
146  * mode is enabled, extra debugging output will be sent to the system
147  * log, the daemon will not go to background, and will exit after processing
148  * the first connection.
149  */
150 int debug_flag = 0;
151 
152 /*
153  * Indicating that the daemon should only test the configuration and keys.
154  * If test_flag > 1 ("-T" flag), then sshd will also dump the effective
155  * configuration, optionally using connection information provided by the
156  * "-C" flag.
157  */
158 int test_flag = 0;
159 
160 /* Flag indicating that the daemon is being started from inetd. */
161 int inetd_flag = 0;
162 
163 /* Flag indicating that sshd should not detach and become a daemon. */
164 int no_daemon_flag = 0;
165 
166 /* debug goes to stderr unless inetd_flag is set */
167 int log_stderr = 0;
168 
169 /* Saved arguments to main(). */
170 char **saved_argv;
171 
172 /* re-exec */
173 int rexeced_flag = 0;
174 int rexec_flag = 1;
175 int rexec_argc = 0;
176 char **rexec_argv;
177 
178 /*
179  * The sockets that the server is listening; this is used in the SIGHUP
180  * signal handler.
181  */
182 #define	MAX_LISTEN_SOCKS	16
183 int listen_socks[MAX_LISTEN_SOCKS];
184 int num_listen_socks = 0;
185 
186 /*
187  * the client's version string, passed by sshd2 in compat mode. if != NULL,
188  * sshd will skip the version-number exchange
189  */
190 char *client_version_string = NULL;
191 char *server_version_string = NULL;
192 
193 /* Daemon's agent connection */
194 int auth_sock = -1;
195 int have_agent = 0;
196 
197 /*
198  * Any really sensitive data in the application is contained in this
199  * structure. The idea is that this structure could be locked into memory so
200  * that the pages do not get written into swap.  However, there are some
201  * problems. The private key contains BIGNUMs, and we do not (in principle)
202  * have access to the internals of them, and locking just the structure is
203  * not very useful.  Currently, memory locking is not implemented.
204  */
205 struct {
206 	struct sshkey	**host_keys;		/* all private host keys */
207 	struct sshkey	**host_pubkeys;		/* all public host keys */
208 	struct sshkey	**host_certificates;	/* all public host certificates */
209 	int		have_ssh2_key;
210 } sensitive_data;
211 
212 /* This is set to true when a signal is received. */
213 static volatile sig_atomic_t received_sighup = 0;
214 static volatile sig_atomic_t received_sigterm = 0;
215 
216 /* session identifier, used by RSA-auth */
217 u_char session_id[16];
218 
219 /* same for ssh2 */
220 u_char *session_id2 = NULL;
221 u_int session_id2_len = 0;
222 
223 /* record remote hostname or ip */
224 u_int utmp_len = HOST_NAME_MAX+1;
225 
226 /* options.max_startup sized array of fd ints */
227 int *startup_pipes = NULL;
228 int startup_pipe;		/* in child */
229 
230 /* variables used for privilege separation */
231 int use_privsep = -1;
232 struct monitor *pmonitor = NULL;
233 int privsep_is_preauth = 1;
234 
235 /* global authentication context */
236 Authctxt *the_authctxt = NULL;
237 
238 /* global key/cert auth options. XXX move to permanent ssh->authctxt? */
239 struct sshauthopt *auth_opts = NULL;
240 
241 /* sshd_config buffer */
242 Buffer cfg;
243 
244 /* message to be displayed after login */
245 Buffer loginmsg;
246 
247 /* Prototypes for various functions defined later in this file. */
248 void destroy_sensitive_data(void);
249 void demote_sensitive_data(void);
250 static void do_ssh2_kex(void);
251 
252 /*
253  * Close all listening sockets
254  */
255 static void
256 close_listen_socks(void)
257 {
258 	int i;
259 
260 	for (i = 0; i < num_listen_socks; i++)
261 		close(listen_socks[i]);
262 	num_listen_socks = -1;
263 }
264 
265 static void
266 close_startup_pipes(void)
267 {
268 	int i;
269 
270 	if (startup_pipes)
271 		for (i = 0; i < options.max_startups; i++)
272 			if (startup_pipes[i] != -1)
273 				close(startup_pipes[i]);
274 }
275 
276 /*
277  * Signal handler for SIGHUP.  Sshd execs itself when it receives SIGHUP;
278  * the effect is to reread the configuration file (and to regenerate
279  * the server key).
280  */
281 
282 /*ARGSUSED*/
283 static void
284 sighup_handler(int sig)
285 {
286 	int save_errno = errno;
287 
288 	received_sighup = 1;
289 	errno = save_errno;
290 }
291 
292 /*
293  * Called from the main program after receiving SIGHUP.
294  * Restarts the server.
295  */
296 __dead static void
297 sighup_restart(void)
298 {
299 	logit("Received SIGHUP; restarting.");
300 	if (options.pid_file != NULL)
301 		unlink(options.pid_file);
302 	close_listen_socks();
303 	close_startup_pipes();
304 	alarm(0);  /* alarm timer persists across exec */
305 	signal(SIGHUP, SIG_IGN); /* will be restored after exec */
306 	execv(saved_argv[0], saved_argv);
307 	logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
308 	    strerror(errno));
309 	exit(1);
310 }
311 
312 /*
313  * Generic signal handler for terminating signals in the master daemon.
314  */
315 /*ARGSUSED*/
316 static void
317 sigterm_handler(int sig)
318 {
319 	received_sigterm = sig;
320 }
321 
322 /*
323  * SIGCHLD handler.  This is called whenever a child dies.  This will then
324  * reap any zombies left by exited children.
325  */
326 /*ARGSUSED*/
327 static void
328 main_sigchld_handler(int sig)
329 {
330 	int save_errno = errno;
331 	pid_t pid;
332 	int status;
333 
334 	while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
335 	    (pid < 0 && errno == EINTR))
336 		;
337 	errno = save_errno;
338 }
339 
340 /*
341  * Signal handler for the alarm after the login grace period has expired.
342  */
343 /*ARGSUSED*/
344 __dead static void
345 grace_alarm_handler(int sig)
346 {
347 	pfilter_notify(1);
348 	if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
349 		kill(pmonitor->m_pid, SIGALRM);
350 
351 	/*
352 	 * Try to kill any processes that we have spawned, E.g. authorized
353 	 * keys command helpers.
354 	 */
355 	if (getpgid(0) == getpid()) {
356 		signal(SIGTERM, SIG_IGN);
357 		killpg(0, SIGTERM);
358 	}
359 
360 	/* Log error and exit. */
361 	sigdie("Timeout before authentication for %s port %d",
362 	    ssh_remote_ipaddr(active_state), ssh_remote_port(active_state));
363 }
364 
365 static void
366 sshd_exchange_identification(struct ssh *ssh, int sock_in, int sock_out)
367 {
368 	u_int i;
369 	int remote_major, remote_minor;
370 	char *s;
371 	char buf[256];			/* Must not be larger than remote_version. */
372 	char remote_version[256];	/* Must be at least as big as buf. */
373 
374 	xasprintf(&server_version_string, "SSH-%d.%d-%.100s%s%s\r\n",
375 	    PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2, SSH_VERSION,
376 	    *options.version_addendum == '\0' ? "" : " ",
377 	    options.version_addendum);
378 
379 	/* Send our protocol version identification. */
380 	if (atomicio(vwrite, sock_out, server_version_string,
381 	    strlen(server_version_string))
382 	    != strlen(server_version_string)) {
383 		logit("Could not write ident string to %s port %d",
384 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
385 		cleanup_exit(255);
386 	}
387 
388 	/* Read other sides version identification. */
389 	memset(buf, 0, sizeof(buf));
390 	for (i = 0; i < sizeof(buf) - 1; i++) {
391 		if (atomicio(read, sock_in, &buf[i], 1) != 1) {
392 			logit("Did not receive identification string "
393 			    "from %s port %d",
394 			    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
395 			cleanup_exit(255);
396 		}
397 		if (buf[i] == '\r') {
398 			buf[i] = 0;
399 			/* Kludge for F-Secure Macintosh < 1.0.2 */
400 			if (i == 12 &&
401 			    strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
402 				break;
403 			continue;
404 		}
405 		if (buf[i] == '\n') {
406 			buf[i] = 0;
407 			break;
408 		}
409 	}
410 	buf[sizeof(buf) - 1] = 0;
411 	client_version_string = xstrdup(buf);
412 
413 	/*
414 	 * Check that the versions match.  In future this might accept
415 	 * several versions and set appropriate flags to handle them.
416 	 */
417 	if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
418 	    &remote_major, &remote_minor, remote_version) != 3) {
419 		s = __UNCONST("Protocol mismatch.\n");
420 		(void) atomicio(vwrite, sock_out, s, strlen(s));
421 		logit("Bad protocol version identification '%.100s' "
422 		    "from %s port %d", client_version_string,
423 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
424 		close(sock_in);
425 		close(sock_out);
426 		cleanup_exit(255);
427 	}
428 	debug("Client protocol version %d.%d; client software version %.100s",
429 	    remote_major, remote_minor, remote_version);
430 	logit("SSH: Server;Ltype: Version;Remote: %s-%d;Protocol: %d.%d;Client: %.100s",
431 	      ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
432 	    remote_major, remote_minor, remote_version);
433 
434 	ssh->compat = compat_datafellows(remote_version);
435 
436 	if ((ssh->compat & SSH_BUG_PROBE) != 0) {
437 		logit("probed from %s port %d with %s.  Don't panic.",
438 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
439 		    client_version_string);
440 		cleanup_exit(255);
441 	}
442 	if ((ssh->compat & SSH_BUG_SCANNER) != 0) {
443 		logit("scanned from %s port %d with %s.  Don't panic.",
444 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
445 		    client_version_string);
446 		cleanup_exit(255);
447 	}
448 	if ((ssh->compat & SSH_BUG_RSASIGMD5) != 0) {
449 		logit("Client version \"%.100s\" uses unsafe RSA signature "
450 		    "scheme; disabling use of RSA keys", remote_version);
451 	}
452 
453 	chop(server_version_string);
454 	debug("Local version string %.200s", server_version_string);
455 
456 	if (remote_major != 2 &&
457 	    !(remote_major == 1 && remote_minor == 99)) {
458 		s = __UNCONST("Protocol major versions differ.\n");
459 		(void) atomicio(vwrite, sock_out, s, strlen(s));
460 		close(sock_in);
461 		close(sock_out);
462 		logit("Protocol major versions differ for %s port %d: "
463 		    "%.200s vs. %.200s",
464 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
465 		    server_version_string, client_version_string);
466 		cleanup_exit(255);
467 	}
468 }
469 
470 /* Destroy the host and server keys.  They will no longer be needed. */
471 void
472 destroy_sensitive_data(void)
473 {
474 	u_int i;
475 
476 	for (i = 0; i < options.num_host_key_files; i++) {
477 		if (sensitive_data.host_keys[i]) {
478 			key_free(sensitive_data.host_keys[i]);
479 			sensitive_data.host_keys[i] = NULL;
480 		}
481 		if (sensitive_data.host_certificates[i]) {
482 			key_free(sensitive_data.host_certificates[i]);
483 			sensitive_data.host_certificates[i] = NULL;
484 		}
485 	}
486 }
487 
488 /* Demote private to public keys for network child */
489 void
490 demote_sensitive_data(void)
491 {
492 	struct sshkey *tmp;
493 	u_int i;
494 
495 	for (i = 0; i < options.num_host_key_files; i++) {
496 		if (sensitive_data.host_keys[i]) {
497 			tmp = key_demote(sensitive_data.host_keys[i]);
498 			key_free(sensitive_data.host_keys[i]);
499 			sensitive_data.host_keys[i] = tmp;
500 		}
501 		/* Certs do not need demotion */
502 	}
503 }
504 
505 static void
506 privsep_preauth_child(void)
507 {
508 	gid_t gidset[1];
509 	struct passwd *pw;
510 
511 	/* Enable challenge-response authentication for privilege separation */
512 	privsep_challenge_enable();
513 
514 #ifdef GSSAPI
515 	/* Cache supported mechanism OIDs for later use */
516 	if (options.gss_authentication)
517 		ssh_gssapi_prepare_supported_oids();
518 #endif
519 
520 	/* Demote the private keys to public keys. */
521 	demote_sensitive_data();
522 
523 	/* Demote the child */
524 	if (getuid() == 0 || geteuid() == 0) {
525 		if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL)
526 			fatal("Privilege separation user %s does not exist",
527 			    SSH_PRIVSEP_USER);
528 		pw = pwcopy(pw); /* Ensure mutable */
529 		endpwent();
530 		freezero(pw->pw_passwd, strlen(pw->pw_passwd));
531 
532 		/* Change our root directory */
533 		if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
534 			fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
535 			    strerror(errno));
536 		if (chdir("/") == -1)
537 			fatal("chdir(\"/\"): %s", strerror(errno));
538 
539 		/*
540 		 * Drop our privileges
541 		 * NB. Can't use setusercontext() after chroot.
542 		 */
543 		debug3("privsep user:group %u:%u", (u_int)pw->pw_uid,
544 		    (u_int)pw->pw_gid);
545 		gidset[0] = pw->pw_gid;
546 		if (setgroups(1, gidset) < 0)
547 			fatal("setgroups: %.100s", strerror(errno));
548 		permanently_set_uid(pw);
549 	}
550 }
551 
552 static int
553 privsep_preauth(Authctxt *authctxt)
554 {
555 	int status, r;
556 	pid_t pid;
557 	struct ssh_sandbox *box = NULL;
558 
559 	/* Set up unprivileged child process to deal with network data */
560 	pmonitor = monitor_init();
561 	/* Store a pointer to the kex for later rekeying */
562 	pmonitor->m_pkex = &active_state->kex;
563 
564 	if (use_privsep == PRIVSEP_ON)
565 		box = ssh_sandbox_init();
566 	pid = fork();
567 	if (pid == -1) {
568 		fatal("fork of unprivileged child failed");
569 	} else if (pid != 0) {
570 		debug2("Network child is on pid %ld", (long)pid);
571 
572 		pmonitor->m_pid = pid;
573 		if (have_agent) {
574 			r = ssh_get_authentication_socket(&auth_sock);
575 			if (r != 0) {
576 				error("Could not get agent socket: %s",
577 				    ssh_err(r));
578 				have_agent = 0;
579 			}
580 		}
581 		if (box != NULL)
582 			ssh_sandbox_parent_preauth(box, pid);
583 		monitor_child_preauth(authctxt, pmonitor);
584 
585 		/* Wait for the child's exit status */
586 		while (waitpid(pid, &status, 0) < 0) {
587 			if (errno == EINTR)
588 				continue;
589 			pmonitor->m_pid = -1;
590 			fatal("%s: waitpid: %s", __func__, strerror(errno));
591 		}
592 		privsep_is_preauth = 0;
593 		pmonitor->m_pid = -1;
594 		if (WIFEXITED(status)) {
595 			if (WEXITSTATUS(status) != 0)
596 				fatal("%s: preauth child exited with status %d",
597 				    __func__, WEXITSTATUS(status));
598 		} else if (WIFSIGNALED(status))
599 			fatal("%s: preauth child terminated by signal %d",
600 			    __func__, WTERMSIG(status));
601 		if (box != NULL)
602 			ssh_sandbox_parent_finish(box);
603 		return 1;
604 	} else {
605 		/* child */
606 		close(pmonitor->m_sendfd);
607 		close(pmonitor->m_log_recvfd);
608 
609 		/* Arrange for logging to be sent to the monitor */
610 		set_log_handler(mm_log_handler, pmonitor);
611 
612 		privsep_preauth_child();
613 		setproctitle("%s", "[net]");
614 		if (box != NULL)
615 			ssh_sandbox_child(box);
616 
617 		return 0;
618 	}
619 }
620 
621 static void
622 privsep_postauth(Authctxt *authctxt)
623 {
624 	if (authctxt->pw->pw_uid == 0) {
625 		/* File descriptor passing is broken or root login */
626 		use_privsep = 0;
627 		goto skip;
628 	}
629 
630 	/* New socket pair */
631 	monitor_reinit(pmonitor);
632 
633 	pmonitor->m_pid = fork();
634 	if (pmonitor->m_pid == -1)
635 		fatal("fork of unprivileged child failed");
636 	else if (pmonitor->m_pid != 0) {
637 		verbose("User child is on pid %ld", (long)pmonitor->m_pid);
638 		buffer_clear(&loginmsg);
639 		monitor_clear_keystate(pmonitor);
640 		monitor_child_postauth(pmonitor);
641 
642 		/* NEVERREACHED */
643 		exit(0);
644 	}
645 
646 	/* child */
647 
648 	close(pmonitor->m_sendfd);
649 	pmonitor->m_sendfd = -1;
650 
651 	/* Demote the private keys to public keys. */
652 	demote_sensitive_data();
653 
654 	/* Drop privileges */
655 	do_setusercontext(authctxt->pw);
656 
657  skip:
658 	/* It is safe now to apply the key state */
659 	monitor_apply_keystate(pmonitor);
660 
661 	/*
662 	 * Tell the packet layer that authentication was successful, since
663 	 * this information is not part of the key state.
664 	 */
665 	packet_set_authenticated();
666 }
667 
668 static char *
669 list_hostkey_types(void)
670 {
671 	Buffer b;
672 	const char *p;
673 	char *ret;
674 	u_int i;
675 	struct sshkey *key;
676 
677 	buffer_init(&b);
678 	for (i = 0; i < options.num_host_key_files; i++) {
679 		key = sensitive_data.host_keys[i];
680 		if (key == NULL)
681 			key = sensitive_data.host_pubkeys[i];
682 		if (key == NULL)
683 			continue;
684 		/* Check that the key is accepted in HostkeyAlgorithms */
685 		if (match_pattern_list(sshkey_ssh_name(key),
686 		    options.hostkeyalgorithms, 0) != 1) {
687 			debug3("%s: %s key not permitted by HostkeyAlgorithms",
688 			    __func__, sshkey_ssh_name(key));
689 			continue;
690 		}
691 		switch (key->type) {
692 		case KEY_RSA:
693 		case KEY_DSA:
694 		case KEY_ECDSA:
695 		case KEY_ED25519:
696 		case KEY_XMSS:
697 			if (buffer_len(&b) > 0)
698 				buffer_append(&b, ",", 1);
699 			p = key_ssh_name(key);
700 			buffer_append(&b, p, strlen(p));
701 
702 			/* for RSA we also support SHA2 signatures */
703 			if (key->type == KEY_RSA) {
704 				p = ",rsa-sha2-512,rsa-sha2-256";
705 				buffer_append(&b, p, strlen(p));
706 			}
707 			break;
708 		}
709 		/* If the private key has a cert peer, then list that too */
710 		key = sensitive_data.host_certificates[i];
711 		if (key == NULL)
712 			continue;
713 		switch (key->type) {
714 		case KEY_RSA_CERT:
715 		case KEY_DSA_CERT:
716 		case KEY_ECDSA_CERT:
717 		case KEY_ED25519_CERT:
718 		case KEY_XMSS_CERT:
719 			if (buffer_len(&b) > 0)
720 				buffer_append(&b, ",", 1);
721 			p = key_ssh_name(key);
722 			buffer_append(&b, p, strlen(p));
723 			break;
724 		}
725 	}
726 	if ((ret = sshbuf_dup_string(&b)) == NULL)
727 		fatal("%s: sshbuf_dup_string failed", __func__);
728 	buffer_free(&b);
729 	debug("list_hostkey_types: %s", ret);
730 	return ret;
731 }
732 
733 static struct sshkey *
734 get_hostkey_by_type(int type, int nid, int need_private, struct ssh *ssh)
735 {
736 	u_int i;
737 	struct sshkey *key;
738 
739 	for (i = 0; i < options.num_host_key_files; i++) {
740 		switch (type) {
741 		case KEY_RSA_CERT:
742 		case KEY_DSA_CERT:
743 		case KEY_ECDSA_CERT:
744 		case KEY_ED25519_CERT:
745 		case KEY_XMSS_CERT:
746 			key = sensitive_data.host_certificates[i];
747 			break;
748 		default:
749 			key = sensitive_data.host_keys[i];
750 			if (key == NULL && !need_private)
751 				key = sensitive_data.host_pubkeys[i];
752 			break;
753 		}
754 		if (key != NULL && key->type == type &&
755 		    (key->type != KEY_ECDSA || key->ecdsa_nid == nid))
756 			return need_private ?
757 			    sensitive_data.host_keys[i] : key;
758 	}
759 	return NULL;
760 }
761 
762 struct sshkey *
763 get_hostkey_public_by_type(int type, int nid, struct ssh *ssh)
764 {
765 	return get_hostkey_by_type(type, nid, 0, ssh);
766 }
767 
768 struct sshkey *
769 get_hostkey_private_by_type(int type, int nid, struct ssh *ssh)
770 {
771 	return get_hostkey_by_type(type, nid, 1, ssh);
772 }
773 
774 struct sshkey *
775 get_hostkey_by_index(int ind)
776 {
777 	if (ind < 0 || (u_int)ind >= options.num_host_key_files)
778 		return (NULL);
779 	return (sensitive_data.host_keys[ind]);
780 }
781 
782 struct sshkey *
783 get_hostkey_public_by_index(int ind, struct ssh *ssh)
784 {
785 	if (ind < 0 || (u_int)ind >= options.num_host_key_files)
786 		return (NULL);
787 	return (sensitive_data.host_pubkeys[ind]);
788 }
789 
790 int
791 get_hostkey_index(struct sshkey *key, int compare, struct ssh *ssh)
792 {
793 	u_int i;
794 
795 	for (i = 0; i < options.num_host_key_files; i++) {
796 		if (key_is_cert(key)) {
797 			if (key == sensitive_data.host_certificates[i] ||
798 			    (compare && sensitive_data.host_certificates[i] &&
799 			    sshkey_equal(key,
800 			    sensitive_data.host_certificates[i])))
801 				return (i);
802 		} else {
803 			if (key == sensitive_data.host_keys[i] ||
804 			    (compare && sensitive_data.host_keys[i] &&
805 			    sshkey_equal(key, sensitive_data.host_keys[i])))
806 				return (i);
807 			if (key == sensitive_data.host_pubkeys[i] ||
808 			    (compare && sensitive_data.host_pubkeys[i] &&
809 			    sshkey_equal(key, sensitive_data.host_pubkeys[i])))
810 				return (i);
811 		}
812 	}
813 	return (-1);
814 }
815 
816 /* Inform the client of all hostkeys */
817 static void
818 notify_hostkeys(struct ssh *ssh)
819 {
820 	struct sshbuf *buf;
821 	struct sshkey *key;
822 	u_int i, nkeys;
823 	int r;
824 	char *fp;
825 
826 	/* Some clients cannot cope with the hostkeys message, skip those. */
827 	if (datafellows & SSH_BUG_HOSTKEYS)
828 		return;
829 
830 	if ((buf = sshbuf_new()) == NULL)
831 		fatal("%s: sshbuf_new", __func__);
832 	for (i = nkeys = 0; i < options.num_host_key_files; i++) {
833 		key = get_hostkey_public_by_index(i, ssh);
834 		if (key == NULL || key->type == KEY_UNSPEC ||
835 		    sshkey_is_cert(key))
836 			continue;
837 		fp = sshkey_fingerprint(key, options.fingerprint_hash,
838 		    SSH_FP_DEFAULT);
839 		debug3("%s: key %d: %s %s", __func__, i,
840 		    sshkey_ssh_name(key), fp);
841 		free(fp);
842 		if (nkeys == 0) {
843 			packet_start(SSH2_MSG_GLOBAL_REQUEST);
844 			packet_put_cstring("hostkeys-00@openssh.com");
845 			packet_put_char(0); /* want-reply */
846 		}
847 		sshbuf_reset(buf);
848 		if ((r = sshkey_putb(key, buf)) != 0)
849 			fatal("%s: couldn't put hostkey %d: %s",
850 			    __func__, i, ssh_err(r));
851 		packet_put_string(sshbuf_ptr(buf), sshbuf_len(buf));
852 		nkeys++;
853 	}
854 	debug3("%s: sent %u hostkeys", __func__, nkeys);
855 	if (nkeys == 0)
856 		fatal("%s: no hostkeys", __func__);
857 	packet_send();
858 	sshbuf_free(buf);
859 }
860 
861 /*
862  * returns 1 if connection should be dropped, 0 otherwise.
863  * dropping starts at connection #max_startups_begin with a probability
864  * of (max_startups_rate/100). the probability increases linearly until
865  * all connections are dropped for startups > max_startups
866  */
867 static int
868 drop_connection(int startups)
869 {
870 	int p, r;
871 
872 	if (startups < options.max_startups_begin)
873 		return 0;
874 	if (startups >= options.max_startups)
875 		return 1;
876 	if (options.max_startups_rate == 100)
877 		return 1;
878 
879 	p  = 100 - options.max_startups_rate;
880 	p *= startups - options.max_startups_begin;
881 	p /= options.max_startups - options.max_startups_begin;
882 	p += options.max_startups_rate;
883 	r = arc4random_uniform(100);
884 
885 	debug("drop_connection: p %d, r %d", p, r);
886 	return (r < p) ? 1 : 0;
887 }
888 
889 __dead static void
890 usage(void)
891 {
892 	fprintf(stderr, "%s, %s\n",
893 	    SSH_VERSION,
894 #ifdef WITH_OPENSSL
895 	    SSLeay_version(SSLEAY_VERSION)
896 #else
897 	    "without OpenSSL"
898 #endif
899 	);
900 	fprintf(stderr,
901 "usage: sshd [-46DdeiqTt] [-C connection_spec] [-c host_cert_file]\n"
902 "            [-E log_file] [-f config_file] [-g login_grace_time]\n"
903 "            [-h host_key_file] [-o option] [-p port] [-u len]\n"
904 	);
905 	exit(1);
906 }
907 
908 static void
909 send_rexec_state(int fd, struct sshbuf *conf)
910 {
911 	struct sshbuf *m;
912 	int r;
913 
914 	debug3("%s: entering fd = %d config len %zu", __func__, fd,
915 	    sshbuf_len(conf));
916 
917 	/*
918 	 * Protocol from reexec master to child:
919 	 *	string	configuration
920 	 */
921 	if ((m = sshbuf_new()) == NULL)
922 		fatal("%s: sshbuf_new failed", __func__);
923 	if ((r = sshbuf_put_stringb(m, conf)) != 0)
924 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
925 	if (ssh_msg_send(fd, 0, m) == -1)
926 		fatal("%s: ssh_msg_send failed", __func__);
927 
928 	sshbuf_free(m);
929 
930 	debug3("%s: done", __func__);
931 }
932 
933 static void
934 recv_rexec_state(int fd, Buffer *conf)
935 {
936 	Buffer m;
937 	char *cp;
938 	u_int len;
939 
940 	debug3("%s: entering fd = %d", __func__, fd);
941 
942 	buffer_init(&m);
943 
944 	if (ssh_msg_recv(fd, &m) == -1)
945 		fatal("%s: ssh_msg_recv failed", __func__);
946 	if (buffer_get_char(&m) != 0)
947 		fatal("%s: rexec version mismatch", __func__);
948 
949 	cp = buffer_get_string(&m, &len);
950 	if (conf != NULL)
951 		buffer_append(conf, cp, len);
952 	free(cp);
953 
954 	buffer_free(&m);
955 
956 	debug3("%s: done", __func__);
957 }
958 
959 /* Accept a connection from inetd */
960 static void
961 server_accept_inetd(int *sock_in, int *sock_out)
962 {
963 	int fd;
964 
965 	startup_pipe = -1;
966 	if (rexeced_flag) {
967 		close(REEXEC_CONFIG_PASS_FD);
968 		*sock_in = *sock_out = dup(STDIN_FILENO);
969 		if (!debug_flag) {
970 			startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
971 			close(REEXEC_STARTUP_PIPE_FD);
972 		}
973 	} else {
974 		*sock_in = dup(STDIN_FILENO);
975 		*sock_out = dup(STDOUT_FILENO);
976 	}
977 	/*
978 	 * We intentionally do not close the descriptors 0, 1, and 2
979 	 * as our code for setting the descriptors won't work if
980 	 * ttyfd happens to be one of those.
981 	 */
982 	if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
983 		dup2(fd, STDIN_FILENO);
984 		dup2(fd, STDOUT_FILENO);
985 		if (!log_stderr)
986 			dup2(fd, STDERR_FILENO);
987 		if (fd > (log_stderr ? STDERR_FILENO : STDOUT_FILENO))
988 			close(fd);
989 	}
990 	debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
991 }
992 
993 /*
994  * Listen for TCP connections
995  */
996 static void
997 listen_on_addrs(struct listenaddr *la)
998 {
999 	int ret, listen_sock;
1000 	struct addrinfo *ai;
1001 	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1002 	int socksize;
1003 	socklen_t socksizelen = sizeof(int);
1004 
1005 	for (ai = la->addrs; ai; ai = ai->ai_next) {
1006 		if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1007 			continue;
1008 		if (num_listen_socks >= MAX_LISTEN_SOCKS)
1009 			fatal("Too many listen sockets. "
1010 			    "Enlarge MAX_LISTEN_SOCKS");
1011 		if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1012 		    ntop, sizeof(ntop), strport, sizeof(strport),
1013 		    NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1014 			error("getnameinfo failed: %.100s",
1015 			    ssh_gai_strerror(ret));
1016 			continue;
1017 		}
1018 		/* Create socket for listening. */
1019 		listen_sock = socket(ai->ai_family, ai->ai_socktype,
1020 		    ai->ai_protocol);
1021 		if (listen_sock < 0) {
1022 			/* kernel may not support ipv6 */
1023 			verbose("socket: %.100s", strerror(errno));
1024 			continue;
1025 		}
1026 		if (set_nonblock(listen_sock) == -1) {
1027 			close(listen_sock);
1028 			continue;
1029 		}
1030 		if (fcntl(listen_sock, F_SETFD, FD_CLOEXEC) == -1) {
1031 			verbose("socket: CLOEXEC: %s", strerror(errno));
1032 			close(listen_sock);
1033 			continue;
1034 		}
1035 		/* Socket options */
1036 		set_reuseaddr(listen_sock);
1037 		if (la->rdomain != NULL &&
1038 		    set_rdomain(listen_sock, la->rdomain) == -1) {
1039 			close(listen_sock);
1040 			continue;
1041 		}
1042 
1043 		debug("Bind to port %s on %s.", strport, ntop);
1044 
1045 		getsockopt(listen_sock, SOL_SOCKET, SO_RCVBUF,
1046 				   &socksize, &socksizelen);
1047 		debug("Server TCP RWIN socket size: %d", socksize);
1048 		debug("HPN Buffer Size: %d", options.hpn_buffer_size);
1049 
1050 		/* Bind the socket to the desired port. */
1051 		if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1052 			error("Bind to port %s on %s failed: %.200s.",
1053 			    strport, ntop, strerror(errno));
1054 			close(listen_sock);
1055 			continue;
1056 		}
1057 		listen_socks[num_listen_socks] = listen_sock;
1058 		num_listen_socks++;
1059 
1060 		/* Start listening on the port. */
1061 		if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1062 			fatal("listen on [%s]:%s: %.100s",
1063 			    ntop, strport, strerror(errno));
1064 		logit("Server listening on %s port %s%s%s.",
1065 		    ntop, strport,
1066 		    la->rdomain == NULL ? "" : " rdomain ",
1067 		    la->rdomain == NULL ? "" : la->rdomain);
1068 	}
1069 }
1070 
1071 static void
1072 server_listen(void)
1073 {
1074 	u_int i;
1075 
1076 	for (i = 0; i < options.num_listen_addrs; i++) {
1077 		listen_on_addrs(&options.listen_addrs[i]);
1078 		freeaddrinfo(options.listen_addrs[i].addrs);
1079 		free(options.listen_addrs[i].rdomain);
1080 		memset(&options.listen_addrs[i], 0,
1081 		    sizeof(options.listen_addrs[i]));
1082 	}
1083 	free(options.listen_addrs);
1084 	options.listen_addrs = NULL;
1085 	options.num_listen_addrs = 0;
1086 
1087 	if (!num_listen_socks)
1088 		fatal("Cannot bind any address.");
1089 }
1090 
1091 /*
1092  * The main TCP accept loop. Note that, for the non-debug case, returns
1093  * from this function are in a forked subprocess.
1094  */
1095 static void
1096 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1097 {
1098 	fd_set *fdset;
1099 	int i, j, ret, maxfd;
1100 	int startups = 0;
1101 	int startup_p[2] = { -1 , -1 };
1102 	struct sockaddr_storage from;
1103 	socklen_t fromlen;
1104 	pid_t pid;
1105 
1106 	/* setup fd set for accept */
1107 	fdset = NULL;
1108 	maxfd = 0;
1109 	for (i = 0; i < num_listen_socks; i++)
1110 		if (listen_socks[i] > maxfd)
1111 			maxfd = listen_socks[i];
1112 	/* pipes connected to unauthenticated childs */
1113 	startup_pipes = xcalloc(options.max_startups, sizeof(int));
1114 	for (i = 0; i < options.max_startups; i++)
1115 		startup_pipes[i] = -1;
1116 
1117 	pfilter_init();
1118 	/*
1119 	 * Stay listening for connections until the system crashes or
1120 	 * the daemon is killed with a signal.
1121 	 */
1122 	for (;;) {
1123 		if (received_sighup)
1124 			sighup_restart();
1125 		free(fdset);
1126 		fdset = xcalloc(howmany(maxfd + 1, NFDBITS),
1127 		    sizeof(fd_mask));
1128 
1129 		for (i = 0; i < num_listen_socks; i++)
1130 			FD_SET(listen_socks[i], fdset);
1131 		for (i = 0; i < options.max_startups; i++)
1132 			if (startup_pipes[i] != -1)
1133 				FD_SET(startup_pipes[i], fdset);
1134 
1135 		/* Wait in select until there is a connection. */
1136 		ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1137 		if (ret < 0 && errno != EINTR)
1138 			error("select: %.100s", strerror(errno));
1139 		if (received_sigterm) {
1140 			logit("Received signal %d; terminating.",
1141 			    (int) received_sigterm);
1142 			close_listen_socks();
1143 			if (options.pid_file != NULL)
1144 				unlink(options.pid_file);
1145 			exit(received_sigterm == SIGTERM ? 0 : 255);
1146 		}
1147 		if (ret < 0)
1148 			continue;
1149 
1150 		for (i = 0; i < options.max_startups; i++)
1151 			if (startup_pipes[i] != -1 &&
1152 			    FD_ISSET(startup_pipes[i], fdset)) {
1153 				/*
1154 				 * the read end of the pipe is ready
1155 				 * if the child has closed the pipe
1156 				 * after successful authentication
1157 				 * or if the child has died
1158 				 */
1159 				close(startup_pipes[i]);
1160 				startup_pipes[i] = -1;
1161 				startups--;
1162 			}
1163 		for (i = 0; i < num_listen_socks; i++) {
1164 			if (!FD_ISSET(listen_socks[i], fdset))
1165 				continue;
1166 			fromlen = sizeof(from);
1167 			*newsock = accept(listen_socks[i],
1168 			    (struct sockaddr *)&from, &fromlen);
1169 			if (*newsock < 0) {
1170 				if (errno != EINTR && errno != EWOULDBLOCK &&
1171 				    errno != ECONNABORTED)
1172 					error("accept: %.100s",
1173 					    strerror(errno));
1174 				if (errno == EMFILE || errno == ENFILE)
1175 					usleep(100 * 1000);
1176 				continue;
1177 			}
1178 			if (unset_nonblock(*newsock) == -1) {
1179 				close(*newsock);
1180 				continue;
1181 			}
1182 			if (drop_connection(startups) == 1) {
1183 				char *laddr = get_local_ipaddr(*newsock);
1184 				char *raddr = get_peer_ipaddr(*newsock);
1185 
1186 				verbose("drop connection #%d from [%s]:%d "
1187 				    "on [%s]:%d past MaxStartups", startups,
1188 				    raddr, get_peer_port(*newsock),
1189 				    laddr, get_local_port(*newsock));
1190 				free(laddr);
1191 				free(raddr);
1192 				close(*newsock);
1193 				continue;
1194 			}
1195 			if (pipe(startup_p) == -1) {
1196 				close(*newsock);
1197 				continue;
1198 			}
1199 
1200 			if (rexec_flag && socketpair(AF_UNIX,
1201 			    SOCK_STREAM, 0, config_s) == -1) {
1202 				error("reexec socketpair: %s",
1203 				    strerror(errno));
1204 				close(*newsock);
1205 				close(startup_p[0]);
1206 				close(startup_p[1]);
1207 				continue;
1208 			}
1209 
1210 			for (j = 0; j < options.max_startups; j++)
1211 				if (startup_pipes[j] == -1) {
1212 					startup_pipes[j] = startup_p[0];
1213 					if (maxfd < startup_p[0])
1214 						maxfd = startup_p[0];
1215 					startups++;
1216 					break;
1217 				}
1218 
1219 			/*
1220 			 * Got connection.  Fork a child to handle it, unless
1221 			 * we are in debugging mode.
1222 			 */
1223 			if (debug_flag) {
1224 				/*
1225 				 * In debugging mode.  Close the listening
1226 				 * socket, and start processing the
1227 				 * connection without forking.
1228 				 */
1229 				debug("Server will not fork when running in debugging mode.");
1230 				close_listen_socks();
1231 				*sock_in = *newsock;
1232 				*sock_out = *newsock;
1233 				close(startup_p[0]);
1234 				close(startup_p[1]);
1235 				startup_pipe = -1;
1236 				pid = getpid();
1237 				if (rexec_flag) {
1238 					send_rexec_state(config_s[0],
1239 					    &cfg);
1240 					close(config_s[0]);
1241 				}
1242 				break;
1243 			}
1244 
1245 			/*
1246 			 * Normal production daemon.  Fork, and have
1247 			 * the child process the connection. The
1248 			 * parent continues listening.
1249 			 */
1250 			if ((pid = fork()) == 0) {
1251 				/*
1252 				 * Child.  Close the listening and
1253 				 * max_startup sockets.  Start using
1254 				 * the accepted socket. Reinitialize
1255 				 * logging (since our pid has changed).
1256 				 * We break out of the loop to handle
1257 				 * the connection.
1258 				 */
1259 				startup_pipe = startup_p[1];
1260 				close_startup_pipes();
1261 				close_listen_socks();
1262 				*sock_in = *newsock;
1263 				*sock_out = *newsock;
1264 				log_init(__progname,
1265 				    options.log_level,
1266 				    options.log_facility,
1267 				    log_stderr);
1268 				if (rexec_flag)
1269 					close(config_s[0]);
1270 				break;
1271 			}
1272 
1273 			/* Parent.  Stay in the loop. */
1274 			if (pid < 0)
1275 				error("fork: %.100s", strerror(errno));
1276 			else
1277 				debug("Forked child %ld.", (long)pid);
1278 
1279 			close(startup_p[1]);
1280 
1281 			if (rexec_flag) {
1282 				send_rexec_state(config_s[0], &cfg);
1283 				close(config_s[0]);
1284 				close(config_s[1]);
1285 			}
1286 			close(*newsock);
1287 		}
1288 
1289 		/* child process check (or debug mode) */
1290 		if (num_listen_socks < 0)
1291 			break;
1292 	}
1293 }
1294 
1295 /*
1296  * If IP options are supported, make sure there are none (log and
1297  * return an error if any are found).  Basically we are worried about
1298  * source routing; it can be used to pretend you are somebody
1299  * (ip-address) you are not. That itself may be "almost acceptable"
1300  * under certain circumstances, but rhosts autentication is useless
1301  * if source routing is accepted. Notice also that if we just dropped
1302  * source routing here, the other side could use IP spoofing to do
1303  * rest of the interaction and could still bypass security.  So we
1304  * exit here if we detect any IP options.
1305  */
1306 static void
1307 check_ip_options(struct ssh *ssh)
1308 {
1309 	int sock_in = ssh_packet_get_connection_in(ssh);
1310 	struct sockaddr_storage from;
1311 	socklen_t fromlen = sizeof(from);
1312 #ifdef IP_OPTIONS
1313 	socklen_t option_size, i;
1314 	u_char opts[200];
1315 	socklen_t i, option_size = sizeof(opts), fromlen = sizeof(from);
1316 	char text[sizeof(opts) * 3 + 1];
1317 #endif
1318 
1319 	memset(&from, 0, sizeof(from));
1320 	if (getpeername(sock_in, (struct sockaddr *)&from,
1321 	    &fromlen) < 0)
1322 		return;
1323 	if (from.ss_family != AF_INET)
1324 		return;
1325 	/* XXX IPv6 options? */
1326 #ifdef IP_OPTIONS
1327 	if (getsockopt(sock_in, IPPROTO_IP, IP_OPTIONS, opts,
1328 	    &option_size) >= 0 && option_size != 0) {
1329 		text[0] = '\0';
1330 		for (i = 0; i < option_size; i++)
1331 			snprintf(text + i*3, sizeof(text) - i*3,
1332 			    " %2.2x", opts[i]);
1333 		fatal("Connection from %.100s port %d with IP opts: %.800s",
1334 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), text);
1335 	}
1336 #endif
1337 	return;
1338 }
1339 
1340 /* Set the routing domain for this process */
1341 #if !defined(__OpenBSD__)
1342 __dead
1343 #endif
1344 static void
1345 set_process_rdomain(struct ssh *ssh, const char *name)
1346 {
1347 #if defined(__OpenBSD__)
1348 	int rtable, ortable = getrtable();
1349 	const char *errstr;
1350 
1351 	if (name == NULL)
1352 		return; /* default */
1353 
1354 	if (strcmp(name, "%D") == 0) {
1355 		/* "expands" to routing domain of connection */
1356 		if ((name = ssh_packet_rdomain_in(ssh)) == NULL)
1357 			return;
1358 	}
1359 
1360 	rtable = (int)strtonum(name, 0, 255, &errstr);
1361 	if (errstr != NULL) /* Shouldn't happen */
1362 		fatal("Invalid routing domain \"%s\": %s", name, errstr);
1363 	if (rtable != ortable && setrtable(rtable) != 0)
1364 		fatal("Unable to set routing domain %d: %s",
1365 		    rtable, strerror(errno));
1366 	debug("%s: set routing domain %d (was %d)", __func__, rtable, ortable);
1367 #else /* defined(__OpenBSD__) */
1368 	fatal("Unable to set routing domain: not supported in this platform");
1369 #endif
1370 }
1371 
1372 /*
1373  * Main program for the daemon.
1374  */
1375 int
1376 main(int ac, char **av)
1377 {
1378 	struct ssh *ssh = NULL;
1379 	extern char *optarg;
1380 	extern int optind;
1381 	int r, opt, on = 1, already_daemon, remote_port;
1382 	int sock_in = -1, sock_out = -1, newsock = -1;
1383 	const char *remote_ip, *rdomain;
1384 	char *fp, *line, *laddr, *logfile = NULL;
1385 	int config_s[2] = { -1 , -1 };
1386 	u_int i, j;
1387 	u_int64_t ibytes, obytes;
1388 	mode_t new_umask;
1389 	struct sshkey *key;
1390 	struct sshkey *pubkey;
1391 	int keytype;
1392 	Authctxt *authctxt;
1393 	struct connection_info *connection_info = NULL;
1394 
1395 	ssh_malloc_init();	/* must be called before any mallocs */
1396 	/* Save argv. */
1397 	saved_argv = av;
1398 	rexec_argc = ac;
1399 
1400 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1401 	sanitise_stdfd();
1402 
1403 	/* Initialize configuration options to their default values. */
1404 	initialize_server_options(&options);
1405 
1406 	/* Parse command-line arguments. */
1407 	while ((opt = getopt(ac, av,
1408 	    "C:E:b:c:f:g:h:k:o:p:u:46DQRTdeiqrt")) != -1) {
1409 		switch (opt) {
1410 		case '4':
1411 			options.address_family = AF_INET;
1412 			break;
1413 		case '6':
1414 			options.address_family = AF_INET6;
1415 			break;
1416 		case 'f':
1417 			config_file_name = optarg;
1418 			break;
1419 		case 'c':
1420 			servconf_add_hostcert("[command-line]", 0,
1421 			    &options, optarg);
1422 			break;
1423 		case 'd':
1424 			if (debug_flag == 0) {
1425 				debug_flag = 1;
1426 				options.log_level = SYSLOG_LEVEL_DEBUG1;
1427 			} else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1428 				options.log_level++;
1429 			break;
1430 		case 'D':
1431 			no_daemon_flag = 1;
1432 			break;
1433 		case 'E':
1434 			logfile = optarg;
1435 			/* FALLTHROUGH */
1436 		case 'e':
1437 			log_stderr = 1;
1438 			break;
1439 		case 'i':
1440 			inetd_flag = 1;
1441 			break;
1442 		case 'r':
1443 			rexec_flag = 0;
1444 			break;
1445 		case 'R':
1446 			rexeced_flag = 1;
1447 			inetd_flag = 1;
1448 			break;
1449 		case 'Q':
1450 			/* ignored */
1451 			break;
1452 		case 'q':
1453 			options.log_level = SYSLOG_LEVEL_QUIET;
1454 			break;
1455 		case 'b':
1456 			/* protocol 1, ignored */
1457 			break;
1458 		case 'p':
1459 			options.ports_from_cmdline = 1;
1460 			if (options.num_ports >= MAX_PORTS) {
1461 				fprintf(stderr, "too many ports.\n");
1462 				exit(1);
1463 			}
1464 			options.ports[options.num_ports++] = a2port(optarg);
1465 			if (options.ports[options.num_ports-1] <= 0) {
1466 				fprintf(stderr, "Bad port number.\n");
1467 				exit(1);
1468 			}
1469 			break;
1470 		case 'g':
1471 			if ((options.login_grace_time = convtime(optarg)) == -1) {
1472 				fprintf(stderr, "Invalid login grace time.\n");
1473 				exit(1);
1474 			}
1475 			break;
1476 		case 'k':
1477 			/* protocol 1, ignored */
1478 			break;
1479 		case 'h':
1480 			servconf_add_hostkey("[command-line]", 0,
1481 			    &options, optarg);
1482 			break;
1483 		case 't':
1484 			test_flag = 1;
1485 			break;
1486 		case 'T':
1487 			test_flag = 2;
1488 			break;
1489 		case 'C':
1490 			connection_info = get_connection_info(0, 0);
1491 			if (parse_server_match_testspec(connection_info,
1492 			    optarg) == -1)
1493 				exit(1);
1494 			break;
1495 		case 'u':
1496 			utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
1497 			if (utmp_len > HOST_NAME_MAX+1) {
1498 				fprintf(stderr, "Invalid utmp length.\n");
1499 				exit(1);
1500 			}
1501 			break;
1502 		case 'o':
1503 			line = xstrdup(optarg);
1504 			if (process_server_config_line(&options, line,
1505 			    "command-line", 0, NULL, NULL) != 0)
1506 				exit(1);
1507 			free(line);
1508 			break;
1509 		case '?':
1510 		default:
1511 			usage();
1512 			break;
1513 		}
1514 	}
1515 	if (rexeced_flag || inetd_flag)
1516 		rexec_flag = 0;
1517 	if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1518 		fatal("sshd re-exec requires execution with an absolute path");
1519 	if (rexeced_flag)
1520 		r = closefrom(REEXEC_MIN_FREE_FD);
1521 	else
1522 		r = closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1523 	if (r == -1)
1524 		fatal("closefrom failed: %.200s", strerror(errno));
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 	buffer_init(&cfg);
1556 	if (rexeced_flag)
1557 		recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1558 	else if (strcasecmp(config_file_name, "none") != 0)
1559 		load_server_config(config_file_name, &cfg);
1560 
1561 	parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1562 	    &cfg, NULL);
1563 
1564 	/* Fill in default values for those options not explicitly set. */
1565 	fill_default_server_options(&options);
1566 
1567 	/* challenge-response is implemented via keyboard interactive */
1568 	if (options.challenge_response_authentication)
1569 		options.kbd_interactive_authentication = 1;
1570 
1571 	/* Check that options are sensible */
1572 	if (options.authorized_keys_command_user == NULL &&
1573 	    (options.authorized_keys_command != NULL &&
1574 	    strcasecmp(options.authorized_keys_command, "none") != 0))
1575 		fatal("AuthorizedKeysCommand set without "
1576 		    "AuthorizedKeysCommandUser");
1577 	if (options.authorized_principals_command_user == NULL &&
1578 	    (options.authorized_principals_command != NULL &&
1579 	    strcasecmp(options.authorized_principals_command, "none") != 0))
1580 		fatal("AuthorizedPrincipalsCommand set without "
1581 		    "AuthorizedPrincipalsCommandUser");
1582 
1583 	/*
1584 	 * Check whether there is any path through configured auth methods.
1585 	 * Unfortunately it is not possible to verify this generally before
1586 	 * daemonisation in the presence of Match block, but this catches
1587 	 * and warns for trivial misconfigurations that could break login.
1588 	 */
1589 	if (options.num_auth_methods != 0) {
1590 		for (i = 0; i < options.num_auth_methods; i++) {
1591 			if (auth2_methods_valid(options.auth_methods[i],
1592 			    1) == 0)
1593 				break;
1594 		}
1595 		if (i >= options.num_auth_methods)
1596 			fatal("AuthenticationMethods cannot be satisfied by "
1597 			    "enabled authentication methods");
1598 	}
1599 
1600 	/* Check that there are no remaining arguments. */
1601 	if (optind < ac) {
1602 		fprintf(stderr, "Extra argument %s.\n", av[optind]);
1603 		exit(1);
1604 	}
1605 
1606 #ifdef WITH_LDAP_PUBKEY
1607 	/* ldap_options_print(&options.lpk); */
1608 	/* XXX initialize/check ldap connection and set *LD */
1609 	if (options.lpk.on) {
1610 	    if (options.lpk.l_conf && (ldap_parse_lconf(&options.lpk) < 0) )
1611 		error("[LDAP] could not parse %s", options.lpk.l_conf);
1612 	    if (ldap_connect(&options.lpk) < 0)
1613 		error("[LDAP] could not initialize ldap connection");
1614 	}
1615 #endif
1616 	debug("sshd version %s, %s", SSH_VERSION,
1617 #ifdef WITH_OPENSSL
1618 	    SSLeay_version(SSLEAY_VERSION)
1619 #else
1620 	    "without OpenSSL"
1621 #endif
1622 	);
1623 
1624 	/* load host keys */
1625 	sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1626 	    sizeof(struct sshkey *));
1627 	sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
1628 	    sizeof(struct sshkey *));
1629 
1630 	if (options.host_key_agent) {
1631 		if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
1632 			setenv(SSH_AUTHSOCKET_ENV_NAME,
1633 			    options.host_key_agent, 1);
1634 		if ((r = ssh_get_authentication_socket(NULL)) == 0)
1635 			have_agent = 1;
1636 		else
1637 			error("Could not connect to agent \"%s\": %s",
1638 			    options.host_key_agent, ssh_err(r));
1639 	}
1640 
1641 	for (i = 0; i < options.num_host_key_files; i++) {
1642 		if (options.host_key_files[i] == NULL)
1643 			continue;
1644 		key = key_load_private(options.host_key_files[i], "", NULL);
1645 		pubkey = key_load_public(options.host_key_files[i], NULL);
1646 
1647 		if (pubkey == NULL && key != NULL)
1648 			pubkey = key_demote(key);
1649 		sensitive_data.host_keys[i] = key;
1650 		sensitive_data.host_pubkeys[i] = pubkey;
1651 
1652 		if (key == NULL && pubkey != NULL && have_agent) {
1653 			debug("will rely on agent for hostkey %s",
1654 			    options.host_key_files[i]);
1655 			keytype = pubkey->type;
1656 		} else if (key != NULL) {
1657 			keytype = key->type;
1658 		} else {
1659 			error("Could not load host key: %s",
1660 			    options.host_key_files[i]);
1661 			sensitive_data.host_keys[i] = NULL;
1662 			sensitive_data.host_pubkeys[i] = NULL;
1663 			continue;
1664 		}
1665 
1666 		switch (keytype) {
1667 		case KEY_RSA:
1668 		case KEY_DSA:
1669 		case KEY_ECDSA:
1670 		case KEY_ED25519:
1671 		case KEY_XMSS:
1672 			if (have_agent || key != NULL)
1673 				sensitive_data.have_ssh2_key = 1;
1674 			break;
1675 		}
1676 		if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash,
1677 		    SSH_FP_DEFAULT)) == NULL)
1678 			fatal("sshkey_fingerprint failed");
1679 		debug("%s host key #%d: %s %s",
1680 		    key ? "private" : "agent", i, sshkey_ssh_name(pubkey), fp);
1681 		free(fp);
1682 	}
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 		key = key_load_public(options.host_cert_files[i], NULL);
1701 		if (key == NULL) {
1702 			error("Could not load host certificate: %s",
1703 			    options.host_cert_files[i]);
1704 			continue;
1705 		}
1706 		if (!key_is_cert(key)) {
1707 			error("Certificate file is not a certificate: %s",
1708 			    options.host_cert_files[i]);
1709 			key_free(key);
1710 			continue;
1711 		}
1712 		/* Find matching private key */
1713 		for (j = 0; j < options.num_host_key_files; j++) {
1714 			if (key_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 			key_free(key);
1724 			continue;
1725 		}
1726 		sensitive_data.host_certificates[j] = key;
1727 		debug("host certificate: #%u type %d %s", j, key->type,
1728 		    key_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] = __UNCONST("-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 #ifdef LIBWRAP
1938 	/* Check whether logins are denied from this host. */
1939 	if (packet_connection_is_on_socket()) {
1940 		struct request_info req;
1941 
1942 		request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1943 		fromhost(&req);
1944 
1945 		if (!hosts_access(&req)) {
1946 			debug("Connection refused by tcp wrapper");
1947 			refuse(&req);
1948 			/* NOTREACHED */
1949 			fatal("libwrap refuse returns");
1950 		}
1951 	}
1952 #endif /* LIBWRAP */
1953 
1954 	rdomain = ssh_packet_rdomain_in(ssh);
1955 
1956 	/* Log the connection. */
1957 	laddr = get_local_ipaddr(sock_in);
1958 	verbose("Connection from %s port %d on %s port %d%s%s%s",
1959 	    remote_ip, remote_port, laddr,  ssh_local_port(ssh),
1960 	    rdomain == NULL ? "" : " rdomain \"",
1961 	    rdomain == NULL ? "" : rdomain,
1962 	    rdomain == NULL ? "" : "\"");
1963 	free(laddr);
1964 
1965 	/* set the HPN options for the child */
1966 	channel_set_hpn(options.hpn_disabled, options.hpn_buffer_size);
1967 
1968 	/*
1969 	 * We don't want to listen forever unless the other side
1970 	 * successfully authenticates itself.  So we set up an alarm which is
1971 	 * cleared after successful authentication.  A limit of zero
1972 	 * indicates no limit. Note that we don't set the alarm in debugging
1973 	 * mode; it is just annoying to have the server exit just when you
1974 	 * are about to discover the bug.
1975 	 */
1976 	signal(SIGALRM, grace_alarm_handler);
1977 	if (!debug_flag)
1978 		alarm(options.login_grace_time);
1979 
1980 	sshd_exchange_identification(ssh, sock_in, sock_out);
1981 	packet_set_nonblocking();
1982 
1983 	/* allocate authentication context */
1984 	authctxt = xcalloc(1, sizeof(*authctxt));
1985 
1986 	/* XXX global for cleanup, access from other modules */
1987 	the_authctxt = authctxt;
1988 
1989 	/* Set default key authentication options */
1990 	if ((auth_opts = sshauthopt_new_with_keys_defaults()) == NULL)
1991 		fatal("allocation failed");
1992 
1993 	/* prepare buffer to collect messages to display to user after login */
1994 	buffer_init(&loginmsg);
1995 	auth_debug_reset();
1996 
1997 	if (use_privsep) {
1998 		if (privsep_preauth(authctxt) == 1)
1999 			goto authenticated;
2000 	} else if (have_agent) {
2001 		if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) {
2002 			error("Unable to get agent socket: %s", ssh_err(r));
2003 			have_agent = 0;
2004 		}
2005 	}
2006 
2007 	/* perform the key exchange */
2008 	/* authenticate user and start session */
2009 	do_ssh2_kex();
2010 	do_authentication2(authctxt);
2011 
2012 	/*
2013 	 * If we use privilege separation, the unprivileged child transfers
2014 	 * the current keystate and exits
2015 	 */
2016 	if (use_privsep) {
2017 		mm_send_keystate(pmonitor);
2018 		packet_clear_keys();
2019 		exit(0);
2020 	}
2021 
2022  authenticated:
2023 	/*
2024 	 * Cancel the alarm we set to limit the time taken for
2025 	 * authentication.
2026 	 */
2027 	alarm(0);
2028 	signal(SIGALRM, SIG_DFL);
2029 	authctxt->authenticated = 1;
2030 	if (startup_pipe != -1) {
2031 		close(startup_pipe);
2032 		startup_pipe = -1;
2033 	}
2034 
2035 #ifdef USE_PAM
2036 	if (options.use_pam) {
2037 		do_pam_setcred(1);
2038 		do_pam_session(ssh);
2039 	}
2040 #endif
2041 
2042 	if (options.routing_domain != NULL)
2043 		set_process_rdomain(ssh, options.routing_domain);
2044 
2045 	/*
2046 	 * In privilege separation, we fork another child and prepare
2047 	 * file descriptor passing.
2048 	 */
2049 	if (use_privsep) {
2050 		privsep_postauth(authctxt);
2051 		/* the monitor process [priv] will not return */
2052 	}
2053 
2054 	packet_set_timeout(options.client_alive_interval,
2055 	    options.client_alive_count_max);
2056 
2057 	/* Try to send all our hostkeys to the client */
2058 	notify_hostkeys(ssh);
2059 
2060 	/* Start session. */
2061 	do_authenticated(ssh, authctxt);
2062 
2063 #ifdef USE_PAM
2064 	if (options.use_pam)
2065 		finish_pam();
2066 #endif /* USE_PAM */
2067 
2068 	/* The connection has been terminated. */
2069 	packet_get_bytes(&ibytes, &obytes);
2070 	verbose("Transferred: sent %llu, received %llu bytes",
2071 	    (unsigned long long)obytes, (unsigned long long)ibytes);
2072 
2073 	verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
2074 	packet_close();
2075 
2076 	if (use_privsep)
2077 		mm_terminate();
2078 
2079 	exit(0);
2080 }
2081 
2082 int
2083 sshd_hostkey_sign(struct sshkey *privkey, struct sshkey *pubkey,
2084     u_char **signature, size_t *slen, const u_char *data, size_t dlen,
2085     const char *alg, u_int flag)
2086 {
2087 	int r;
2088 	u_int xxx_slen, xxx_dlen = dlen;
2089 
2090 	if (privkey) {
2091 		if (PRIVSEP(key_sign(privkey, signature, &xxx_slen, data, xxx_dlen,
2092 		    alg) < 0))
2093 			fatal("%s: key_sign failed", __func__);
2094 		if (slen)
2095 			*slen = xxx_slen;
2096 	} else if (use_privsep) {
2097 		if (mm_key_sign(pubkey, signature, &xxx_slen, data, xxx_dlen,
2098 		    alg) < 0)
2099 			fatal("%s: pubkey_sign failed", __func__);
2100 		if (slen)
2101 			*slen = xxx_slen;
2102 	} else {
2103 		if ((r = ssh_agent_sign(auth_sock, pubkey, signature, slen,
2104 		    data, dlen, alg, datafellows)) != 0)
2105 			fatal("%s: ssh_agent_sign failed: %s",
2106 			    __func__, ssh_err(r));
2107 	}
2108 	return 0;
2109 }
2110 
2111 /* SSH2 key exchange */
2112 static void
2113 do_ssh2_kex(void)
2114 {
2115 	const char *myproposal[PROPOSAL_MAX] = { KEX_SERVER };
2116 	struct kex *kex;
2117 	int r;
2118 
2119 	myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(
2120 	    options.kex_algorithms);
2121 
2122 	if (strcmp(options.ciphers, KEX_SERVER_ENCRYPT) == 0 &&
2123 	    options.none_enabled == 1) {
2124 		debug ("WARNING: None cipher enabled");
2125 		myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2126 		myproposal[PROPOSAL_ENC_ALGS_STOC] = KEX_SERVER_ENCRYPT_INCLUDE_NONE;
2127 	} else {
2128 		myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2129 		myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
2130 	}
2131 
2132 	myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2133 	    compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
2134 	myproposal[PROPOSAL_ENC_ALGS_STOC] =
2135 	    compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
2136 
2137 	myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2138 	    myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2139 
2140 	if (options.compression == COMP_NONE) {
2141 		myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2142 		    myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2143 	}
2144 
2145 	if (options.rekey_limit || options.rekey_interval)
2146 		packet_set_rekey_limits(options.rekey_limit,
2147 		    options.rekey_interval);
2148 
2149 	myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal(
2150 	    list_hostkey_types());
2151 
2152 	/* start key exchange */
2153 	if ((r = kex_setup(active_state, myproposal)) != 0)
2154 		fatal("kex_setup: %s", ssh_err(r));
2155 	kex = active_state->kex;
2156 #ifdef WITH_OPENSSL
2157 	kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2158 	kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
2159 	kex->kex[KEX_DH_GRP14_SHA256] = kexdh_server;
2160 	kex->kex[KEX_DH_GRP16_SHA512] = kexdh_server;
2161 	kex->kex[KEX_DH_GRP18_SHA512] = kexdh_server;
2162 	kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2163 	kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2164 	kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
2165 #endif
2166 	kex->kex[KEX_C25519_SHA256] = kexc25519_server;
2167 	kex->server = 1;
2168 	kex->client_version_string=client_version_string;
2169 	kex->server_version_string=server_version_string;
2170 	kex->load_host_public_key=&get_hostkey_public_by_type;
2171 	kex->load_host_private_key=&get_hostkey_private_by_type;
2172 	kex->host_key_index=&get_hostkey_index;
2173 	kex->sign = sshd_hostkey_sign;
2174 
2175 	ssh_dispatch_run_fatal(active_state, DISPATCH_BLOCK, &kex->done);
2176 
2177 	session_id2 = kex->session_id;
2178 	session_id2_len = kex->session_id_len;
2179 
2180 #ifdef DEBUG_KEXDH
2181 	/* send 1st encrypted/maced/compressed message */
2182 	packet_start(SSH2_MSG_IGNORE);
2183 	packet_put_cstring("markus");
2184 	packet_send();
2185 	packet_write_wait();
2186 #endif
2187 	debug("KEX done");
2188 }
2189 
2190 /* server specific fatal cleanup */
2191 void
2192 cleanup_exit(int i)
2193 {
2194 	struct ssh *ssh = active_state; /* XXX */
2195 
2196 	if (i == 255)
2197 		pfilter_notify(1);
2198 
2199 	if (the_authctxt) {
2200 		do_cleanup(ssh, the_authctxt);
2201 		if (use_privsep && privsep_is_preauth &&
2202 		    pmonitor != NULL && pmonitor->m_pid > 1) {
2203 			debug("Killing privsep child %d", pmonitor->m_pid);
2204 			if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
2205 			    errno != ESRCH)
2206 				error("%s: kill(%d): %s", __func__,
2207 				    pmonitor->m_pid, strerror(errno));
2208 		}
2209 	}
2210 	_exit(i);
2211 }
2212