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