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