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