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