xref: /freebsd/crypto/openssh/sshd.c (revision 33644623554bb0fc57ed3c7d874193a498679b22)
1 /* $OpenBSD: sshd.c,v 1.364 2008/07/10 18:08:11 markus 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/socket.h>
51 #ifdef HAVE_SYS_STAT_H
52 # include <sys/stat.h>
53 #endif
54 #ifdef HAVE_SYS_TIME_H
55 # include <sys/time.h>
56 #endif
57 #include "openbsd-compat/sys-tree.h"
58 #include "openbsd-compat/sys-queue.h"
59 #include <sys/wait.h>
60 
61 #include <errno.h>
62 #include <fcntl.h>
63 #include <netdb.h>
64 #ifdef HAVE_PATHS_H
65 #include <paths.h>
66 #endif
67 #include <grp.h>
68 #include <pwd.h>
69 #include <signal.h>
70 #include <stdarg.h>
71 #include <stdio.h>
72 #include <stdlib.h>
73 #include <string.h>
74 #include <unistd.h>
75 #include <utmp.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 "monitor_fdpass.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 = UT_HOSTSIZE;
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 (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 (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 	/* Parse command-line arguments. */
1297 	while ((opt = getopt(ac, av, "f:p:b:k:h:g:u:o:C:dDeiqrtQRT46")) != -1) {
1298 		switch (opt) {
1299 		case '4':
1300 			options.address_family = AF_INET;
1301 			break;
1302 		case '6':
1303 			options.address_family = AF_INET6;
1304 			break;
1305 		case 'f':
1306 			config_file_name = optarg;
1307 			break;
1308 		case 'd':
1309 			if (debug_flag == 0) {
1310 				debug_flag = 1;
1311 				options.log_level = SYSLOG_LEVEL_DEBUG1;
1312 			} else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1313 				options.log_level++;
1314 			break;
1315 		case 'D':
1316 			no_daemon_flag = 1;
1317 			break;
1318 		case 'e':
1319 			log_stderr = 1;
1320 			break;
1321 		case 'i':
1322 			inetd_flag = 1;
1323 			break;
1324 		case 'r':
1325 			rexec_flag = 0;
1326 			break;
1327 		case 'R':
1328 			rexeced_flag = 1;
1329 			inetd_flag = 1;
1330 			break;
1331 		case 'Q':
1332 			/* ignored */
1333 			break;
1334 		case 'q':
1335 			options.log_level = SYSLOG_LEVEL_QUIET;
1336 			break;
1337 		case 'b':
1338 			options.server_key_bits = (int)strtonum(optarg, 256,
1339 			    32768, NULL);
1340 			break;
1341 		case 'p':
1342 			options.ports_from_cmdline = 1;
1343 			if (options.num_ports >= MAX_PORTS) {
1344 				fprintf(stderr, "too many ports.\n");
1345 				exit(1);
1346 			}
1347 			options.ports[options.num_ports++] = a2port(optarg);
1348 			if (options.ports[options.num_ports-1] == 0) {
1349 				fprintf(stderr, "Bad port number.\n");
1350 				exit(1);
1351 			}
1352 			break;
1353 		case 'g':
1354 			if ((options.login_grace_time = convtime(optarg)) == -1) {
1355 				fprintf(stderr, "Invalid login grace time.\n");
1356 				exit(1);
1357 			}
1358 			break;
1359 		case 'k':
1360 			if ((options.key_regeneration_time = convtime(optarg)) == -1) {
1361 				fprintf(stderr, "Invalid key regeneration interval.\n");
1362 				exit(1);
1363 			}
1364 			break;
1365 		case 'h':
1366 			if (options.num_host_key_files >= MAX_HOSTKEYS) {
1367 				fprintf(stderr, "too many host keys.\n");
1368 				exit(1);
1369 			}
1370 			options.host_key_files[options.num_host_key_files++] = optarg;
1371 			break;
1372 		case 't':
1373 			test_flag = 1;
1374 			break;
1375 		case 'T':
1376 			test_flag = 2;
1377 			break;
1378 		case 'C':
1379 			cp = optarg;
1380 			while ((p = strsep(&cp, ",")) && *p != '\0') {
1381 				if (strncmp(p, "addr=", 5) == 0)
1382 					test_addr = xstrdup(p + 5);
1383 				else if (strncmp(p, "host=", 5) == 0)
1384 					test_host = xstrdup(p + 5);
1385 				else if (strncmp(p, "user=", 5) == 0)
1386 					test_user = xstrdup(p + 5);
1387 				else {
1388 					fprintf(stderr, "Invalid test "
1389 					    "mode specification %s\n", p);
1390 					exit(1);
1391 				}
1392 			}
1393 			break;
1394 		case 'u':
1395 			utmp_len = (u_int)strtonum(optarg, 0, MAXHOSTNAMELEN+1, NULL);
1396 			if (utmp_len > MAXHOSTNAMELEN) {
1397 				fprintf(stderr, "Invalid utmp length.\n");
1398 				exit(1);
1399 			}
1400 			break;
1401 		case 'o':
1402 			line = xstrdup(optarg);
1403 			if (process_server_config_line(&options, line,
1404 			    "command-line", 0, NULL, NULL, NULL, NULL) != 0)
1405 				exit(1);
1406 			xfree(line);
1407 			break;
1408 		case '?':
1409 		default:
1410 			usage();
1411 			break;
1412 		}
1413 	}
1414 	if (rexeced_flag || inetd_flag)
1415 		rexec_flag = 0;
1416 	if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1417 		fatal("sshd re-exec requires execution with an absolute path");
1418 	if (rexeced_flag)
1419 		closefrom(REEXEC_MIN_FREE_FD);
1420 	else
1421 		closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1422 
1423 	SSLeay_add_all_algorithms();
1424 
1425 	/*
1426 	 * Force logging to stderr until we have loaded the private host
1427 	 * key (unless started from inetd)
1428 	 */
1429 	log_init(__progname,
1430 	    options.log_level == SYSLOG_LEVEL_NOT_SET ?
1431 	    SYSLOG_LEVEL_INFO : options.log_level,
1432 	    options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1433 	    SYSLOG_FACILITY_AUTH : options.log_facility,
1434 	    log_stderr || !inetd_flag);
1435 
1436 	/*
1437 	 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1438 	 * root's environment
1439 	 */
1440 	if (getenv("KRB5CCNAME") != NULL)
1441 		unsetenv("KRB5CCNAME");
1442 
1443 #ifdef _UNICOS
1444 	/* Cray can define user privs drop all privs now!
1445 	 * Not needed on PRIV_SU systems!
1446 	 */
1447 	drop_cray_privs();
1448 #endif
1449 
1450 	sensitive_data.server_key = NULL;
1451 	sensitive_data.ssh1_host_key = NULL;
1452 	sensitive_data.have_ssh1_key = 0;
1453 	sensitive_data.have_ssh2_key = 0;
1454 
1455 	/*
1456 	 * If we're doing an extended config test, make sure we have all of
1457 	 * the parameters we need.  If we're not doing an extended test,
1458 	 * do not silently ignore connection test params.
1459 	 */
1460 	if (test_flag >= 2 &&
1461 	   (test_user != NULL || test_host != NULL || test_addr != NULL)
1462 	    && (test_user == NULL || test_host == NULL || test_addr == NULL))
1463 		fatal("user, host and addr are all required when testing "
1464 		   "Match configs");
1465 	if (test_flag < 2 && (test_user != NULL || test_host != NULL ||
1466 	    test_addr != NULL))
1467 		fatal("Config test connection parameter (-C) provided without "
1468 		   "test mode (-T)");
1469 
1470 	/* Fetch our configuration */
1471 	buffer_init(&cfg);
1472 	if (rexeced_flag)
1473 		recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1474 	else
1475 		load_server_config(config_file_name, &cfg);
1476 
1477 	parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1478 	    &cfg, NULL, NULL, NULL);
1479 
1480 	seed_rng();
1481 
1482 	/* Fill in default values for those options not explicitly set. */
1483 	fill_default_server_options(&options);
1484 
1485 	/* challenge-response is implemented via keyboard interactive */
1486 	if (options.challenge_response_authentication)
1487 		options.kbd_interactive_authentication = 1;
1488 
1489 	/* set default channel AF */
1490 	channel_set_af(options.address_family);
1491 
1492 	/* Check that there are no remaining arguments. */
1493 	if (optind < ac) {
1494 		fprintf(stderr, "Extra argument %s.\n", av[optind]);
1495 		exit(1);
1496 	}
1497 
1498 	debug("sshd version %.100s", SSH_RELEASE);
1499 
1500 	/* Store privilege separation user for later use if required. */
1501 	if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1502 		if (use_privsep || options.kerberos_authentication)
1503 			fatal("Privilege separation user %s does not exist",
1504 			    SSH_PRIVSEP_USER);
1505 	} else {
1506 		memset(privsep_pw->pw_passwd, 0, strlen(privsep_pw->pw_passwd));
1507 		privsep_pw = pwcopy(privsep_pw);
1508 		xfree(privsep_pw->pw_passwd);
1509 		privsep_pw->pw_passwd = xstrdup("*");
1510 	}
1511 	endpwent();
1512 
1513 	/* load private host keys */
1514 	sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1515 	    sizeof(Key *));
1516 	for (i = 0; i < options.num_host_key_files; i++)
1517 		sensitive_data.host_keys[i] = NULL;
1518 
1519 	for (i = 0; i < options.num_host_key_files; i++) {
1520 		key = key_load_private(options.host_key_files[i], "", NULL);
1521 		sensitive_data.host_keys[i] = key;
1522 		if (key == NULL) {
1523 			error("Could not load host key: %s",
1524 			    options.host_key_files[i]);
1525 			sensitive_data.host_keys[i] = NULL;
1526 			continue;
1527 		}
1528 		switch (key->type) {
1529 		case KEY_RSA1:
1530 			sensitive_data.ssh1_host_key = key;
1531 			sensitive_data.have_ssh1_key = 1;
1532 			break;
1533 		case KEY_RSA:
1534 		case KEY_DSA:
1535 			sensitive_data.have_ssh2_key = 1;
1536 			break;
1537 		}
1538 		debug("private host key: #%d type %d %s", i, key->type,
1539 		    key_type(key));
1540 	}
1541 	if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1542 		logit("Disabling protocol version 1. Could not load host key");
1543 		options.protocol &= ~SSH_PROTO_1;
1544 	}
1545 	if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1546 		logit("Disabling protocol version 2. Could not load host key");
1547 		options.protocol &= ~SSH_PROTO_2;
1548 	}
1549 	if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1550 		logit("sshd: no hostkeys available -- exiting.");
1551 		exit(1);
1552 	}
1553 
1554 	/* Check certain values for sanity. */
1555 	if (options.protocol & SSH_PROTO_1) {
1556 		if (options.server_key_bits < 512 ||
1557 		    options.server_key_bits > 32768) {
1558 			fprintf(stderr, "Bad server key size.\n");
1559 			exit(1);
1560 		}
1561 		/*
1562 		 * Check that server and host key lengths differ sufficiently. This
1563 		 * is necessary to make double encryption work with rsaref. Oh, I
1564 		 * hate software patents. I dont know if this can go? Niels
1565 		 */
1566 		if (options.server_key_bits >
1567 		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
1568 		    SSH_KEY_BITS_RESERVED && options.server_key_bits <
1569 		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1570 		    SSH_KEY_BITS_RESERVED) {
1571 			options.server_key_bits =
1572 			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1573 			    SSH_KEY_BITS_RESERVED;
1574 			debug("Forcing server key to %d bits to make it differ from host key.",
1575 			    options.server_key_bits);
1576 		}
1577 	}
1578 
1579 	if (use_privsep) {
1580 		struct stat st;
1581 
1582 		if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1583 		    (S_ISDIR(st.st_mode) == 0))
1584 			fatal("Missing privilege separation directory: %s",
1585 			    _PATH_PRIVSEP_CHROOT_DIR);
1586 
1587 #ifdef HAVE_CYGWIN
1588 		if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1589 		    (st.st_uid != getuid () ||
1590 		    (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1591 #else
1592 		if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1593 #endif
1594 			fatal("%s must be owned by root and not group or "
1595 			    "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1596 	}
1597 
1598 	if (test_flag > 1) {
1599 		if (test_user != NULL && test_addr != NULL && test_host != NULL)
1600 			parse_server_match_config(&options, test_user,
1601 			    test_host, test_addr);
1602 		dump_config(&options);
1603 	}
1604 
1605 	/* Configuration looks good, so exit if in test mode. */
1606 	if (test_flag)
1607 		exit(0);
1608 
1609 	/*
1610 	 * Clear out any supplemental groups we may have inherited.  This
1611 	 * prevents inadvertent creation of files with bad modes (in the
1612 	 * portable version at least, it's certainly possible for PAM
1613 	 * to create a file, and we can't control the code in every
1614 	 * module which might be used).
1615 	 */
1616 	if (setgroups(0, NULL) < 0)
1617 		debug("setgroups() failed: %.200s", strerror(errno));
1618 
1619 	if (rexec_flag) {
1620 		rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1621 		for (i = 0; i < rexec_argc; i++) {
1622 			debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1623 			rexec_argv[i] = saved_argv[i];
1624 		}
1625 		rexec_argv[rexec_argc] = "-R";
1626 		rexec_argv[rexec_argc + 1] = NULL;
1627 	}
1628 
1629 	/* Ensure that umask disallows at least group and world write */
1630 	new_umask = umask(0077) | 0022;
1631 	(void) umask(new_umask);
1632 
1633 	/* Initialize the log (it is reinitialized below in case we forked). */
1634 	if (debug_flag && (!inetd_flag || rexeced_flag))
1635 		log_stderr = 1;
1636 	log_init(__progname, options.log_level, options.log_facility, log_stderr);
1637 
1638 	/*
1639 	 * If not in debugging mode, and not started from inetd, disconnect
1640 	 * from the controlling terminal, and fork.  The original process
1641 	 * exits.
1642 	 */
1643 	if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1644 #ifdef TIOCNOTTY
1645 		int fd;
1646 #endif /* TIOCNOTTY */
1647 		if (daemon(0, 0) < 0)
1648 			fatal("daemon() failed: %.200s", strerror(errno));
1649 
1650 		/* Disconnect from the controlling tty. */
1651 #ifdef TIOCNOTTY
1652 		fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1653 		if (fd >= 0) {
1654 			(void) ioctl(fd, TIOCNOTTY, NULL);
1655 			close(fd);
1656 		}
1657 #endif /* TIOCNOTTY */
1658 	}
1659 	/* Reinitialize the log (because of the fork above). */
1660 	log_init(__progname, options.log_level, options.log_facility, log_stderr);
1661 
1662 	/* Initialize the random number generator. */
1663 	arc4random_stir();
1664 
1665 	/* Chdir to the root directory so that the current disk can be
1666 	   unmounted if desired. */
1667 	chdir("/");
1668 
1669 	/* ignore SIGPIPE */
1670 	signal(SIGPIPE, SIG_IGN);
1671 
1672 	/* Get a connection, either from inetd or a listening TCP socket */
1673 	if (inetd_flag) {
1674 		server_accept_inetd(&sock_in, &sock_out);
1675 	} else {
1676 		server_listen();
1677 
1678 		if (options.protocol & SSH_PROTO_1)
1679 			generate_ephemeral_server_key();
1680 
1681 		signal(SIGHUP, sighup_handler);
1682 		signal(SIGCHLD, main_sigchld_handler);
1683 		signal(SIGTERM, sigterm_handler);
1684 		signal(SIGQUIT, sigterm_handler);
1685 
1686 		/*
1687 		 * Write out the pid file after the sigterm handler
1688 		 * is setup and the listen sockets are bound
1689 		 */
1690 		if (!debug_flag) {
1691 			FILE *f = fopen(options.pid_file, "w");
1692 
1693 			if (f == NULL) {
1694 				error("Couldn't create pid file \"%s\": %s",
1695 				    options.pid_file, strerror(errno));
1696 			} else {
1697 				fprintf(f, "%ld\n", (long) getpid());
1698 				fclose(f);
1699 			}
1700 		}
1701 
1702 		/* Accept a connection and return in a forked child */
1703 		server_accept_loop(&sock_in, &sock_out,
1704 		    &newsock, config_s);
1705 	}
1706 
1707 	/* This is the child processing a new connection. */
1708 	setproctitle("%s", "[accepted]");
1709 
1710 	/*
1711 	 * Create a new session and process group since the 4.4BSD
1712 	 * setlogin() affects the entire process group.  We don't
1713 	 * want the child to be able to affect the parent.
1714 	 */
1715 #if !defined(SSHD_ACQUIRES_CTTY)
1716 	/*
1717 	 * If setsid is called, on some platforms sshd will later acquire a
1718 	 * controlling terminal which will result in "could not set
1719 	 * controlling tty" errors.
1720 	 */
1721 	if (!debug_flag && !inetd_flag && setsid() < 0)
1722 		error("setsid: %.100s", strerror(errno));
1723 #endif
1724 
1725 	if (rexec_flag) {
1726 		int fd;
1727 
1728 		debug("rexec start in %d out %d newsock %d pipe %d sock %d",
1729 		    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1730 		dup2(newsock, STDIN_FILENO);
1731 		dup2(STDIN_FILENO, STDOUT_FILENO);
1732 		if (startup_pipe == -1)
1733 			close(REEXEC_STARTUP_PIPE_FD);
1734 		else
1735 			dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
1736 
1737 		dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1738 		close(config_s[1]);
1739 		if (startup_pipe != -1)
1740 			close(startup_pipe);
1741 
1742 		execv(rexec_argv[0], rexec_argv);
1743 
1744 		/* Reexec has failed, fall back and continue */
1745 		error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1746 		recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1747 		log_init(__progname, options.log_level,
1748 		    options.log_facility, log_stderr);
1749 
1750 		/* Clean up fds */
1751 		startup_pipe = REEXEC_STARTUP_PIPE_FD;
1752 		close(config_s[1]);
1753 		close(REEXEC_CONFIG_PASS_FD);
1754 		newsock = sock_out = sock_in = dup(STDIN_FILENO);
1755 		if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1756 			dup2(fd, STDIN_FILENO);
1757 			dup2(fd, STDOUT_FILENO);
1758 			if (fd > STDERR_FILENO)
1759 				close(fd);
1760 		}
1761 		debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
1762 		    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1763 	}
1764 
1765 	/*
1766 	 * Disable the key regeneration alarm.  We will not regenerate the
1767 	 * key since we are no longer in a position to give it to anyone. We
1768 	 * will not restart on SIGHUP since it no longer makes sense.
1769 	 */
1770 	alarm(0);
1771 	signal(SIGALRM, SIG_DFL);
1772 	signal(SIGHUP, SIG_DFL);
1773 	signal(SIGTERM, SIG_DFL);
1774 	signal(SIGQUIT, SIG_DFL);
1775 	signal(SIGCHLD, SIG_DFL);
1776 	signal(SIGINT, SIG_DFL);
1777 
1778 #ifdef __FreeBSD__
1779 	/*
1780 	 * Initialize the resolver.  This may not happen automatically
1781 	 * before privsep chroot().
1782 	 */
1783 	if ((_res.options & RES_INIT) == 0) {
1784 		debug("res_init()");
1785 		res_init();
1786 	}
1787 #ifdef GSSAPI
1788 	/*
1789 	 * Force GSS-API to parse its configuration and load any
1790 	 * mechanism plugins.
1791 	 */
1792 	{
1793 		gss_OID_set mechs;
1794 		OM_uint32 minor_status;
1795 		gss_indicate_mechs(&minor_status, &mechs);
1796 		gss_release_oid_set(&minor_status, &mechs);
1797 	}
1798 #endif
1799 #endif
1800 
1801 	/*
1802 	 * Register our connection.  This turns encryption off because we do
1803 	 * not have a key.
1804 	 */
1805 	packet_set_connection(sock_in, sock_out);
1806 	packet_set_server();
1807 
1808 	/* Set SO_KEEPALIVE if requested. */
1809 	if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
1810 	    setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
1811 		error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1812 
1813 	if ((remote_port = get_remote_port()) < 0) {
1814 		debug("get_remote_port failed");
1815 		cleanup_exit(255);
1816 	}
1817 
1818 	/*
1819 	 * We use get_canonical_hostname with usedns = 0 instead of
1820 	 * get_remote_ipaddr here so IP options will be checked.
1821 	 */
1822 	(void) get_canonical_hostname(0);
1823 	/*
1824 	 * The rest of the code depends on the fact that
1825 	 * get_remote_ipaddr() caches the remote ip, even if
1826 	 * the socket goes away.
1827 	 */
1828 	remote_ip = get_remote_ipaddr();
1829 
1830 #ifdef SSH_AUDIT_EVENTS
1831 	audit_connection_from(remote_ip, remote_port);
1832 #endif
1833 #ifdef LIBWRAP
1834 	allow_severity = options.log_facility|LOG_INFO;
1835 	deny_severity = options.log_facility|LOG_WARNING;
1836 	/* Check whether logins are denied from this host. */
1837 	if (packet_connection_is_on_socket()) {
1838 		struct request_info req;
1839 
1840 		request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1841 		fromhost(&req);
1842 
1843 		if (!hosts_access(&req)) {
1844 			debug("Connection refused by tcp wrapper");
1845 			refuse(&req);
1846 			/* NOTREACHED */
1847 			fatal("libwrap refuse returns");
1848 		}
1849 	}
1850 #endif /* LIBWRAP */
1851 
1852 	/* Log the connection. */
1853 	verbose("Connection from %.500s port %d", remote_ip, remote_port);
1854 
1855 	/*
1856 	 * We don't want to listen forever unless the other side
1857 	 * successfully authenticates itself.  So we set up an alarm which is
1858 	 * cleared after successful authentication.  A limit of zero
1859 	 * indicates no limit. Note that we don't set the alarm in debugging
1860 	 * mode; it is just annoying to have the server exit just when you
1861 	 * are about to discover the bug.
1862 	 */
1863 	signal(SIGALRM, grace_alarm_handler);
1864 	if (!debug_flag)
1865 		alarm(options.login_grace_time);
1866 
1867 	sshd_exchange_identification(sock_in, sock_out);
1868 
1869 	/* In inetd mode, generate ephemeral key only for proto 1 connections */
1870 	if (!compat20 && inetd_flag && sensitive_data.server_key == NULL)
1871 		generate_ephemeral_server_key();
1872 
1873 	packet_set_nonblocking();
1874 
1875 	/* allocate authentication context */
1876 	authctxt = xcalloc(1, sizeof(*authctxt));
1877 
1878 	authctxt->loginmsg = &loginmsg;
1879 
1880 	/* XXX global for cleanup, access from other modules */
1881 	the_authctxt = authctxt;
1882 
1883 	/* prepare buffer to collect messages to display to user after login */
1884 	buffer_init(&loginmsg);
1885 
1886 	if (use_privsep)
1887 		if (privsep_preauth(authctxt) == 1)
1888 			goto authenticated;
1889 
1890 	/* perform the key exchange */
1891 	/* authenticate user and start session */
1892 	if (compat20) {
1893 		do_ssh2_kex();
1894 		do_authentication2(authctxt);
1895 	} else {
1896 		do_ssh1_kex();
1897 		do_authentication(authctxt);
1898 	}
1899 	/*
1900 	 * If we use privilege separation, the unprivileged child transfers
1901 	 * the current keystate and exits
1902 	 */
1903 	if (use_privsep) {
1904 		mm_send_keystate(pmonitor);
1905 		exit(0);
1906 	}
1907 
1908  authenticated:
1909 	/*
1910 	 * Cancel the alarm we set to limit the time taken for
1911 	 * authentication.
1912 	 */
1913 	alarm(0);
1914 	signal(SIGALRM, SIG_DFL);
1915 	authctxt->authenticated = 1;
1916 	if (startup_pipe != -1) {
1917 		close(startup_pipe);
1918 		startup_pipe = -1;
1919 	}
1920 
1921 #ifdef SSH_AUDIT_EVENTS
1922 	audit_event(SSH_AUTH_SUCCESS);
1923 #endif
1924 
1925 #ifdef GSSAPI
1926 	if (options.gss_authentication) {
1927 		temporarily_use_uid(authctxt->pw);
1928 		ssh_gssapi_storecreds();
1929 		restore_uid();
1930 	}
1931 #endif
1932 #ifdef USE_PAM
1933 	if (options.use_pam) {
1934 		do_pam_setcred(1);
1935 		do_pam_session();
1936 	}
1937 #endif
1938 
1939 	/*
1940 	 * In privilege separation, we fork another child and prepare
1941 	 * file descriptor passing.
1942 	 */
1943 	if (use_privsep) {
1944 		privsep_postauth(authctxt);
1945 		/* the monitor process [priv] will not return */
1946 		if (!compat20)
1947 			destroy_sensitive_data();
1948 	}
1949 
1950 	packet_set_timeout(options.client_alive_interval,
1951 	    options.client_alive_count_max);
1952 
1953 	/* Start session. */
1954 	do_authenticated(authctxt);
1955 
1956 	/* The connection has been terminated. */
1957 	packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
1958 	packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
1959 	verbose("Transferred: sent %llu, received %llu bytes", obytes, ibytes);
1960 
1961 	verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
1962 
1963 #ifdef USE_PAM
1964 	if (options.use_pam)
1965 		finish_pam();
1966 #endif /* USE_PAM */
1967 
1968 #ifdef SSH_AUDIT_EVENTS
1969 	PRIVSEP(audit_event(SSH_CONNECTION_CLOSE));
1970 #endif
1971 
1972 	packet_close();
1973 
1974 	if (use_privsep)
1975 		mm_terminate();
1976 
1977 	exit(0);
1978 }
1979 
1980 /*
1981  * Decrypt session_key_int using our private server key and private host key
1982  * (key with larger modulus first).
1983  */
1984 int
1985 ssh1_session_key(BIGNUM *session_key_int)
1986 {
1987 	int rsafail = 0;
1988 
1989 	if (BN_cmp(sensitive_data.server_key->rsa->n,
1990 	    sensitive_data.ssh1_host_key->rsa->n) > 0) {
1991 		/* Server key has bigger modulus. */
1992 		if (BN_num_bits(sensitive_data.server_key->rsa->n) <
1993 		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1994 		    SSH_KEY_BITS_RESERVED) {
1995 			fatal("do_connection: %s: "
1996 			    "server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1997 			    get_remote_ipaddr(),
1998 			    BN_num_bits(sensitive_data.server_key->rsa->n),
1999 			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2000 			    SSH_KEY_BITS_RESERVED);
2001 		}
2002 		if (rsa_private_decrypt(session_key_int, session_key_int,
2003 		    sensitive_data.server_key->rsa) <= 0)
2004 			rsafail++;
2005 		if (rsa_private_decrypt(session_key_int, session_key_int,
2006 		    sensitive_data.ssh1_host_key->rsa) <= 0)
2007 			rsafail++;
2008 	} else {
2009 		/* Host key has bigger modulus (or they are equal). */
2010 		if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
2011 		    BN_num_bits(sensitive_data.server_key->rsa->n) +
2012 		    SSH_KEY_BITS_RESERVED) {
2013 			fatal("do_connection: %s: "
2014 			    "host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
2015 			    get_remote_ipaddr(),
2016 			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2017 			    BN_num_bits(sensitive_data.server_key->rsa->n),
2018 			    SSH_KEY_BITS_RESERVED);
2019 		}
2020 		if (rsa_private_decrypt(session_key_int, session_key_int,
2021 		    sensitive_data.ssh1_host_key->rsa) < 0)
2022 			rsafail++;
2023 		if (rsa_private_decrypt(session_key_int, session_key_int,
2024 		    sensitive_data.server_key->rsa) < 0)
2025 			rsafail++;
2026 	}
2027 	return (rsafail);
2028 }
2029 /*
2030  * SSH1 key exchange
2031  */
2032 static void
2033 do_ssh1_kex(void)
2034 {
2035 	int i, len;
2036 	int rsafail = 0;
2037 	BIGNUM *session_key_int;
2038 	u_char session_key[SSH_SESSION_KEY_LENGTH];
2039 	u_char cookie[8];
2040 	u_int cipher_type, auth_mask, protocol_flags;
2041 
2042 	/*
2043 	 * Generate check bytes that the client must send back in the user
2044 	 * packet in order for it to be accepted; this is used to defy ip
2045 	 * spoofing attacks.  Note that this only works against somebody
2046 	 * doing IP spoofing from a remote machine; any machine on the local
2047 	 * network can still see outgoing packets and catch the random
2048 	 * cookie.  This only affects rhosts authentication, and this is one
2049 	 * of the reasons why it is inherently insecure.
2050 	 */
2051 	arc4random_buf(cookie, sizeof(cookie));
2052 
2053 	/*
2054 	 * Send our public key.  We include in the packet 64 bits of random
2055 	 * data that must be matched in the reply in order to prevent IP
2056 	 * spoofing.
2057 	 */
2058 	packet_start(SSH_SMSG_PUBLIC_KEY);
2059 	for (i = 0; i < 8; i++)
2060 		packet_put_char(cookie[i]);
2061 
2062 	/* Store our public server RSA key. */
2063 	packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
2064 	packet_put_bignum(sensitive_data.server_key->rsa->e);
2065 	packet_put_bignum(sensitive_data.server_key->rsa->n);
2066 
2067 	/* Store our public host RSA key. */
2068 	packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2069 	packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
2070 	packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
2071 
2072 	/* Put protocol flags. */
2073 	packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
2074 
2075 	/* Declare which ciphers we support. */
2076 	packet_put_int(cipher_mask_ssh1(0));
2077 
2078 	/* Declare supported authentication types. */
2079 	auth_mask = 0;
2080 	if (options.rhosts_rsa_authentication)
2081 		auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
2082 	if (options.rsa_authentication)
2083 		auth_mask |= 1 << SSH_AUTH_RSA;
2084 	if (options.challenge_response_authentication == 1)
2085 		auth_mask |= 1 << SSH_AUTH_TIS;
2086 	if (options.password_authentication)
2087 		auth_mask |= 1 << SSH_AUTH_PASSWORD;
2088 	packet_put_int(auth_mask);
2089 
2090 	/* Send the packet and wait for it to be sent. */
2091 	packet_send();
2092 	packet_write_wait();
2093 
2094 	debug("Sent %d bit server key and %d bit host key.",
2095 	    BN_num_bits(sensitive_data.server_key->rsa->n),
2096 	    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2097 
2098 	/* Read clients reply (cipher type and session key). */
2099 	packet_read_expect(SSH_CMSG_SESSION_KEY);
2100 
2101 	/* Get cipher type and check whether we accept this. */
2102 	cipher_type = packet_get_char();
2103 
2104 	if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
2105 		packet_disconnect("Warning: client selects unsupported cipher.");
2106 
2107 	/* Get check bytes from the packet.  These must match those we
2108 	   sent earlier with the public key packet. */
2109 	for (i = 0; i < 8; i++)
2110 		if (cookie[i] != packet_get_char())
2111 			packet_disconnect("IP Spoofing check bytes do not match.");
2112 
2113 	debug("Encryption type: %.200s", cipher_name(cipher_type));
2114 
2115 	/* Get the encrypted integer. */
2116 	if ((session_key_int = BN_new()) == NULL)
2117 		fatal("do_ssh1_kex: BN_new failed");
2118 	packet_get_bignum(session_key_int);
2119 
2120 	protocol_flags = packet_get_int();
2121 	packet_set_protocol_flags(protocol_flags);
2122 	packet_check_eom();
2123 
2124 	/* Decrypt session_key_int using host/server keys */
2125 	rsafail = PRIVSEP(ssh1_session_key(session_key_int));
2126 
2127 	/*
2128 	 * Extract session key from the decrypted integer.  The key is in the
2129 	 * least significant 256 bits of the integer; the first byte of the
2130 	 * key is in the highest bits.
2131 	 */
2132 	if (!rsafail) {
2133 		(void) BN_mask_bits(session_key_int, sizeof(session_key) * 8);
2134 		len = BN_num_bytes(session_key_int);
2135 		if (len < 0 || (u_int)len > sizeof(session_key)) {
2136 			error("do_ssh1_kex: bad session key len from %s: "
2137 			    "session_key_int %d > sizeof(session_key) %lu",
2138 			    get_remote_ipaddr(), len, (u_long)sizeof(session_key));
2139 			rsafail++;
2140 		} else {
2141 			memset(session_key, 0, sizeof(session_key));
2142 			BN_bn2bin(session_key_int,
2143 			    session_key + sizeof(session_key) - len);
2144 
2145 			derive_ssh1_session_id(
2146 			    sensitive_data.ssh1_host_key->rsa->n,
2147 			    sensitive_data.server_key->rsa->n,
2148 			    cookie, session_id);
2149 			/*
2150 			 * Xor the first 16 bytes of the session key with the
2151 			 * session id.
2152 			 */
2153 			for (i = 0; i < 16; i++)
2154 				session_key[i] ^= session_id[i];
2155 		}
2156 	}
2157 	if (rsafail) {
2158 		int bytes = BN_num_bytes(session_key_int);
2159 		u_char *buf = xmalloc(bytes);
2160 		MD5_CTX md;
2161 
2162 		logit("do_connection: generating a fake encryption key");
2163 		BN_bn2bin(session_key_int, buf);
2164 		MD5_Init(&md);
2165 		MD5_Update(&md, buf, bytes);
2166 		MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2167 		MD5_Final(session_key, &md);
2168 		MD5_Init(&md);
2169 		MD5_Update(&md, session_key, 16);
2170 		MD5_Update(&md, buf, bytes);
2171 		MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2172 		MD5_Final(session_key + 16, &md);
2173 		memset(buf, 0, bytes);
2174 		xfree(buf);
2175 		for (i = 0; i < 16; i++)
2176 			session_id[i] = session_key[i] ^ session_key[i + 16];
2177 	}
2178 	/* Destroy the private and public keys. No longer. */
2179 	destroy_sensitive_data();
2180 
2181 	if (use_privsep)
2182 		mm_ssh1_session_id(session_id);
2183 
2184 	/* Destroy the decrypted integer.  It is no longer needed. */
2185 	BN_clear_free(session_key_int);
2186 
2187 	/* Set the session key.  From this on all communications will be encrypted. */
2188 	packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
2189 
2190 	/* Destroy our copy of the session key.  It is no longer needed. */
2191 	memset(session_key, 0, sizeof(session_key));
2192 
2193 	debug("Received session key; encryption turned on.");
2194 
2195 	/* Send an acknowledgment packet.  Note that this packet is sent encrypted. */
2196 	packet_start(SSH_SMSG_SUCCESS);
2197 	packet_send();
2198 	packet_write_wait();
2199 }
2200 
2201 /*
2202  * SSH2 key exchange: diffie-hellman-group1-sha1
2203  */
2204 static void
2205 do_ssh2_kex(void)
2206 {
2207 	Kex *kex;
2208 
2209 	if (options.ciphers != NULL) {
2210 		myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2211 		myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
2212 	}
2213 	myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2214 	    compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
2215 	myproposal[PROPOSAL_ENC_ALGS_STOC] =
2216 	    compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
2217 
2218 	if (options.macs != NULL) {
2219 		myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2220 		myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2221 	}
2222 	if (options.compression == COMP_NONE) {
2223 		myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2224 		myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2225 	} else if (options.compression == COMP_DELAYED) {
2226 		myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2227 		myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com";
2228 	}
2229 
2230 	myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
2231 
2232 	/* start key exchange */
2233 	kex = kex_setup(myproposal);
2234 	kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2235 	kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
2236 	kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2237 	kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2238 	kex->server = 1;
2239 	kex->client_version_string=client_version_string;
2240 	kex->server_version_string=server_version_string;
2241 	kex->load_host_key=&get_hostkey_by_type;
2242 	kex->host_key_index=&get_hostkey_index;
2243 
2244 	xxx_kex = kex;
2245 
2246 	dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
2247 
2248 	session_id2 = kex->session_id;
2249 	session_id2_len = kex->session_id_len;
2250 
2251 #ifdef DEBUG_KEXDH
2252 	/* send 1st encrypted/maced/compressed message */
2253 	packet_start(SSH2_MSG_IGNORE);
2254 	packet_put_cstring("markus");
2255 	packet_send();
2256 	packet_write_wait();
2257 #endif
2258 	debug("KEX done");
2259 }
2260 
2261 /* server specific fatal cleanup */
2262 void
2263 cleanup_exit(int i)
2264 {
2265 	if (the_authctxt)
2266 		do_cleanup(the_authctxt);
2267 #ifdef SSH_AUDIT_EVENTS
2268 	/* done after do_cleanup so it can cancel the PAM auth 'thread' */
2269 	if (!use_privsep || mm_is_monitor())
2270 		audit_event(SSH_CONNECTION_ABANDON);
2271 #endif
2272 	_exit(i);
2273 }
2274