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