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