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