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