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