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