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