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