xref: /titanic_50/usr/src/cmd/ssh/sshd/sshd.c (revision 355b4669e025ff377602b6fc7caaf30dbc218371)
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 		audit_sshd_login(&ah, authctxt->pw->pw_uid,
1804 			authctxt->pw->pw_gid);
1805 
1806 		fatal_add_cleanup((void (*)(void *))audit_sshd_logout,
1807 			(void *)&ah);
1808 #endif /* HAVE_BSM */
1809 
1810 #ifdef GSSAPI
1811 		fatal_add_cleanup((void (*)(void *))ssh_gssapi_cleanup_creds,
1812 			(void *)&xxx_gssctxt);
1813 #endif /* GSSAPI */
1814 
1815 		altprivsep_do_monitor(authctxt, aps_child);
1816 
1817 		/* If we got here the connection is dead. */
1818 		fatal_remove_cleanup((void (*)(void *))altprivsep_shutdown_sock,
1819 			(void *)&newsock);
1820 
1821 		if (compat20) {
1822 			debug3("Recording SSHv2 session logout in wtmpx");
1823 			record_logout(getpid(), NULL, "sshd", authctxt->user);
1824 		}
1825 
1826 		/*
1827 		 * Make sure the socket is closed. The monitor can't call
1828 		 * packet_close here as it's done a packet_set_connection()
1829 		 * with the pipe to the child instead of the socket.
1830 		 */
1831 		(void) shutdown(newsock, SHUT_RDWR);
1832 
1833 #ifdef GSSAPI
1834 		fatal_remove_cleanup((void (*)(void *))ssh_gssapi_cleanup_creds,
1835 			&xxx_gssctxt);
1836 		ssh_gssapi_cleanup_creds(xxx_gssctxt);
1837 		ssh_gssapi_server_mechs(NULL); /* release cached mechs list */
1838 #endif /* GSSAPI */
1839 
1840 #ifdef HAVE_BSM
1841 		fatal_remove_cleanup((void (*)(void *))audit_sshd_logout, (void *)&ah);
1842 		audit_sshd_logout(&ah);
1843 #endif /* HAVE_BSM */
1844 
1845 #ifdef USE_PAM
1846 		finish_pam(authctxt);
1847 #endif /* USE_PAM */
1848 
1849 		return (ret);
1850 
1851 		/* NOTREACHED */
1852 
1853 	} else {
1854 
1855 		/* ALTPRIVSEP Child */
1856 
1857 		/*
1858 		 * Drop privileges, access to privileged resources.
1859 		 *
1860 		 * Destroy private host keys, if any.
1861 		 *
1862 		 * No need to release any GSS credentials -- sshd only acquires
1863 		 * creds to determine what mechs it can negotiate then releases
1864 		 * them right away and uses GSS_C_NO_CREDENTIAL to accept
1865 		 * contexts.
1866 		 */
1867 		debug2("Unprivileged server process dropping privileges");
1868 		permanently_set_uid(authctxt->pw);
1869 		destroy_sensitive_data();
1870 		ssh_gssapi_server_mechs(NULL); /* release cached mechs list */
1871 
1872 #ifdef HAVE_BSM
1873 		fatal_remove_cleanup(
1874 			(void (*)(void *))audit_failed_login_cleanup,
1875 			(void *)authctxt);
1876 #endif /* HAVE_BSM */
1877 
1878 		/* Logged-in session. */
1879 		do_authenticated(authctxt);
1880 
1881 		/* The connection has been terminated. */
1882 		verbose("Closing connection to %.100s", remote_ip);
1883 
1884 		packet_close();
1885 
1886 		return (0);
1887 
1888 		/* NOTREACHED */
1889 	}
1890 
1891 #else /* ALTPRIVSEP */
1892 
1893 	if (compat20) {
1894 		debug3("Recording SSHv2 session login in wtmpx");
1895 		record_login(getpid(), NULL, "sshd", authctxt->user);
1896 	}
1897 
1898 #ifdef HAVE_BSM
1899 	fatal_remove_cleanup(
1900 		(void (*)(void *))audit_failed_login_cleanup,
1901 		(void *)authctxt);
1902 
1903 	audit_sshd_login(&ah, authctxt->pw->pw_uid,
1904 		authctxt->pw->pw_gid);
1905 
1906 	fatal_add_cleanup((void (*)(void *))audit_sshd_logout,
1907 		(void *)&ah);
1908 #endif /* HAVE_BSM */
1909 
1910 #ifdef GSSAPI
1911 	fatal_add_cleanup((void (*)(void *))ssh_gssapi_cleanup_creds,
1912 		(void *)&xxx_gssctxt);
1913 #endif /* GSSAPI */
1914 
1915 	/* Perform session preparation. */
1916 	do_authenticated(authctxt);
1917 
1918 	/* XXX - Add PRIVSEP() macro */
1919 	if (compat20) {
1920 		debug3("Recording SSHv2 session logout in wtmpx");
1921 		record_logout(getpid(), NULL, "sshd", authctxt->user);
1922 	}
1923 
1924 #ifdef GSSAPI
1925 	fatal_remove_cleanup((void (*)(void *))ssh_gssapi_cleanup_creds,
1926 		&xxx_gssctxt);
1927 	ssh_gssapi_cleanup_creds(xxx_gssctxt);
1928 	ssh_gssapi_server_mechs(NULL); /* release cached server mechs */
1929 #endif /* GSSAPI */
1930 
1931 #ifdef HAVE_BSM
1932 	fatal_remove_cleanup((void (*)(void *))audit_sshd_logout, (void *)&ah);
1933 	audit_sshd_logout(&ah);
1934 #endif /* HAVE_BSM */
1935 
1936 #ifdef USE_PAM
1937 	finish_pam(authctxt);
1938 #endif /* USE_PAM */
1939 
1940 	/* The connection has been terminated. */
1941 	verbose("Closing connection to %.100s", remote_ip);
1942 
1943 	packet_close();
1944 
1945 	if (use_privsep)
1946 		mm_terminate();
1947 
1948 	return (0);
1949 #endif /* ALTPRIVSEP */
1950 }
1951 
1952 /*
1953  * Decrypt session_key_int using our private server key and private host key
1954  * (key with larger modulus first).
1955  */
1956 int
1957 ssh1_session_key(BIGNUM *session_key_int)
1958 {
1959 	int rsafail = 0;
1960 
1961 	if (BN_cmp(sensitive_data.server_key->rsa->n, sensitive_data.ssh1_host_key->rsa->n) > 0) {
1962 		/* Server key has bigger modulus. */
1963 		if (BN_num_bits(sensitive_data.server_key->rsa->n) <
1964 		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1965 			fatal("do_connection: %s: server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1966 			    get_remote_ipaddr(),
1967 			    BN_num_bits(sensitive_data.server_key->rsa->n),
1968 			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1969 			    SSH_KEY_BITS_RESERVED);
1970 		}
1971 		if (rsa_private_decrypt(session_key_int, session_key_int,
1972 		    sensitive_data.server_key->rsa) <= 0)
1973 			rsafail++;
1974 		if (rsa_private_decrypt(session_key_int, session_key_int,
1975 		    sensitive_data.ssh1_host_key->rsa) <= 0)
1976 			rsafail++;
1977 	} else {
1978 		/* Host key has bigger modulus (or they are equal). */
1979 		if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
1980 		    BN_num_bits(sensitive_data.server_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1981 			fatal("do_connection: %s: host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
1982 			    get_remote_ipaddr(),
1983 			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1984 			    BN_num_bits(sensitive_data.server_key->rsa->n),
1985 			    SSH_KEY_BITS_RESERVED);
1986 		}
1987 		if (rsa_private_decrypt(session_key_int, session_key_int,
1988 		    sensitive_data.ssh1_host_key->rsa) < 0)
1989 			rsafail++;
1990 		if (rsa_private_decrypt(session_key_int, session_key_int,
1991 		    sensitive_data.server_key->rsa) < 0)
1992 			rsafail++;
1993 	}
1994 	return (rsafail);
1995 }
1996 /*
1997  * SSH1 key exchange
1998  */
1999 static void
2000 do_ssh1_kex(void)
2001 {
2002 	int i, len;
2003 	int rsafail = 0;
2004 	BIGNUM *session_key_int;
2005 	u_char session_key[SSH_SESSION_KEY_LENGTH];
2006 	u_char cookie[8];
2007 	u_int cipher_type, auth_mask, protocol_flags;
2008 	u_int32_t rnd = 0;
2009 
2010 	/*
2011 	 * Generate check bytes that the client must send back in the user
2012 	 * packet in order for it to be accepted; this is used to defy ip
2013 	 * spoofing attacks.  Note that this only works against somebody
2014 	 * doing IP spoofing from a remote machine; any machine on the local
2015 	 * network can still see outgoing packets and catch the random
2016 	 * cookie.  This only affects rhosts authentication, and this is one
2017 	 * of the reasons why it is inherently insecure.
2018 	 */
2019 	for (i = 0; i < 8; i++) {
2020 		if (i % 4 == 0)
2021 			rnd = arc4random();
2022 		cookie[i] = rnd & 0xff;
2023 		rnd >>= 8;
2024 	}
2025 
2026 	/*
2027 	 * Send our public key.  We include in the packet 64 bits of random
2028 	 * data that must be matched in the reply in order to prevent IP
2029 	 * spoofing.
2030 	 */
2031 	packet_start(SSH_SMSG_PUBLIC_KEY);
2032 	for (i = 0; i < 8; i++)
2033 		packet_put_char(cookie[i]);
2034 
2035 	/* Store our public server RSA key. */
2036 	packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
2037 	packet_put_bignum(sensitive_data.server_key->rsa->e);
2038 	packet_put_bignum(sensitive_data.server_key->rsa->n);
2039 
2040 	/* Store our public host RSA key. */
2041 	packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2042 	packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
2043 	packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
2044 
2045 	/* Put protocol flags. */
2046 	packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
2047 
2048 	/* Declare which ciphers we support. */
2049 	packet_put_int(cipher_mask_ssh1(0));
2050 
2051 	/* Declare supported authentication types. */
2052 	auth_mask = 0;
2053 	if (options.rhosts_authentication)
2054 		auth_mask |= 1 << SSH_AUTH_RHOSTS;
2055 	if (options.rhosts_rsa_authentication)
2056 		auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
2057 	if (options.rsa_authentication)
2058 		auth_mask |= 1 << SSH_AUTH_RSA;
2059 #if defined(KRB4) || defined(KRB5)
2060 	if (options.kerberos_authentication)
2061 		auth_mask |= 1 << SSH_AUTH_KERBEROS;
2062 #endif
2063 #if defined(AFS) || defined(KRB5)
2064 	if (options.kerberos_tgt_passing)
2065 		auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
2066 #endif
2067 #ifdef AFS
2068 	if (options.afs_token_passing)
2069 		auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
2070 #endif
2071 	if (options.challenge_response_authentication == 1)
2072 		auth_mask |= 1 << SSH_AUTH_TIS;
2073 	if (options.password_authentication)
2074 		auth_mask |= 1 << SSH_AUTH_PASSWORD;
2075 	packet_put_int(auth_mask);
2076 
2077 	/* Send the packet and wait for it to be sent. */
2078 	packet_send();
2079 	packet_write_wait();
2080 
2081 	debug("Sent %d bit server key and %d bit host key.",
2082 	    BN_num_bits(sensitive_data.server_key->rsa->n),
2083 	    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2084 
2085 	/* Read clients reply (cipher type and session key). */
2086 	packet_read_expect(SSH_CMSG_SESSION_KEY);
2087 
2088 	/* Get cipher type and check whether we accept this. */
2089 	cipher_type = packet_get_char();
2090 
2091 	if (!(cipher_mask_ssh1(0) & (1 << cipher_type))) {
2092 		packet_disconnect("Warning: client selects unsupported cipher.");
2093 	}
2094 
2095 	/* Get check bytes from the packet.  These must match those we
2096 	   sent earlier with the public key packet. */
2097 	for (i = 0; i < 8; i++) {
2098 		if (cookie[i] != packet_get_char()) {
2099 			packet_disconnect("IP Spoofing check bytes do not match.");
2100 		}
2101 	}
2102 
2103 	debug("Encryption type: %.200s", cipher_name(cipher_type));
2104 
2105 	/* Get the encrypted integer. */
2106 	if ((session_key_int = BN_new()) == NULL)
2107 		fatal("do_ssh1_kex: BN_new failed");
2108 	packet_get_bignum(session_key_int);
2109 
2110 	protocol_flags = packet_get_int();
2111 	packet_set_protocol_flags(protocol_flags);
2112 	packet_check_eom();
2113 
2114 	/* Decrypt session_key_int using host/server keys */
2115 	rsafail = PRIVSEP(ssh1_session_key(session_key_int));
2116 
2117 	/*
2118 	 * Extract session key from the decrypted integer.  The key is in the
2119 	 * least significant 256 bits of the integer; the first byte of the
2120 	 * key is in the highest bits.
2121 	 */
2122 	if (!rsafail) {
2123 		(void) BN_mask_bits(session_key_int, sizeof(session_key) * 8);
2124 		len = BN_num_bytes(session_key_int);
2125 		if (len < 0 || len > sizeof(session_key)) {
2126 			error("do_connection: bad session key len from %s: "
2127 			    "session_key_int %d > sizeof(session_key) %lu",
2128 			    get_remote_ipaddr(), len, (u_long)sizeof(session_key));
2129 			rsafail++;
2130 		} else {
2131 			(void) memset(session_key, 0, sizeof(session_key));
2132 			(void) BN_bn2bin(session_key_int,
2133 			    session_key + sizeof(session_key) - len);
2134 
2135 			compute_session_id(session_id, cookie,
2136 			    sensitive_data.ssh1_host_key->rsa->n,
2137 			    sensitive_data.server_key->rsa->n);
2138 			/*
2139 			 * Xor the first 16 bytes of the session key with the
2140 			 * session id.
2141 			 */
2142 			for (i = 0; i < 16; i++)
2143 				session_key[i] ^= session_id[i];
2144 		}
2145 	}
2146 	if (rsafail) {
2147 		int bytes = BN_num_bytes(session_key_int);
2148 		u_char *buf = xmalloc(bytes);
2149 		MD5_CTX md;
2150 
2151 		log("do_connection: generating a fake encryption key");
2152 		(void) BN_bn2bin(session_key_int, buf);
2153 		MD5_Init(&md);
2154 		MD5_Update(&md, buf, bytes);
2155 		MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2156 		MD5_Final(session_key, &md);
2157 		MD5_Init(&md);
2158 		MD5_Update(&md, session_key, 16);
2159 		MD5_Update(&md, buf, bytes);
2160 		MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2161 		MD5_Final(session_key + 16, &md);
2162 		(void) memset(buf, 0, bytes);
2163 		xfree(buf);
2164 		for (i = 0; i < 16; i++)
2165 			session_id[i] = session_key[i] ^ session_key[i + 16];
2166 	}
2167 	/* Destroy the private and public keys. No longer. */
2168 	destroy_sensitive_data();
2169 
2170 	if (use_privsep)
2171 		mm_ssh1_session_id(session_id);
2172 
2173 	/* Destroy the decrypted integer.  It is no longer needed. */
2174 	BN_clear_free(session_key_int);
2175 
2176 	/* Set the session key.  From this on all communications will be encrypted. */
2177 	packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
2178 
2179 	/* Destroy our copy of the session key.  It is no longer needed. */
2180 	(void) memset(session_key, 0, sizeof(session_key));
2181 
2182 	debug("Received session key; encryption turned on.");
2183 
2184 	/* Send an acknowledgment packet.  Note that this packet is sent encrypted. */
2185 	packet_start(SSH_SMSG_SUCCESS);
2186 	packet_send();
2187 	packet_write_wait();
2188 }
2189 
2190 /*
2191  * SSH2 key exchange: diffie-hellman-group1-sha1
2192  */
2193 static void
2194 do_ssh2_kex(void)
2195 {
2196 	Kex *kex;
2197 	Kex_hook_func kex_hook = NULL;
2198 	char **locales;
2199 
2200 	if (options.ciphers != NULL) {
2201 		myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2202 		myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
2203 	}
2204 	myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2205 	    compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
2206 	myproposal[PROPOSAL_ENC_ALGS_STOC] =
2207 	    compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
2208 
2209 	if (options.macs != NULL) {
2210 		myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2211 		myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2212 	}
2213 	if (!options.compression) {
2214 		myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2215 		myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2216 	}
2217 
2218 	/*
2219 	 * Prepare kex algs / hostkey algs (excluding GSS, which is
2220 	 * handled in the kex hook.
2221 	 *
2222 	 * XXX This should probably move to the kex hook as well, where
2223 	 * all non-constant kex offer material belongs.
2224 	 */
2225 	myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
2226 
2227 	/* If we have no host key algs we can't offer KEXDH/KEX_DH_GEX */
2228 	if (myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] == NULL ||
2229 	    *myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] == '\0')
2230 		myproposal[PROPOSAL_KEX_ALGS] = "";
2231 
2232 	if ((locales = g11n_getlocales()) != NULL) {
2233 		/* Solaris 9 SSH expects a list of locales */
2234 		if (datafellows & SSH_BUG_LOCALES_NOT_LANGTAGS)
2235 			myproposal[PROPOSAL_LANG_STOC] = xjoin(locales, ',');
2236 		else
2237 			myproposal[PROPOSAL_LANG_STOC] =
2238 				g11n_locales2langs(locales);
2239 	}
2240 
2241 	if ((myproposal[PROPOSAL_LANG_STOC] != NULL) ||
2242 	    (strcmp(myproposal[PROPOSAL_LANG_STOC], "")) != 0)
2243 		myproposal[PROPOSAL_LANG_CTOS] =
2244 			xstrdup(myproposal[PROPOSAL_LANG_STOC]);
2245 
2246 #ifdef GSSAPI
2247 	if (options.gss_keyex)
2248 		kex_hook = ssh_gssapi_server_kex_hook;
2249 #endif /* GSSAPI */
2250 
2251 	/* start key exchange */
2252 	kex = kex_setup(NULL, myproposal, kex_hook);
2253 	kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2254 	kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2255 #ifdef GSSAPI
2256 	kex->kex[KEX_GSS_GRP1_SHA1] = kexgss_server;
2257 #endif /* GSSAPI */
2258 	kex->server = 1;
2259 	kex->client_version_string=client_version_string;
2260 	kex->server_version_string=server_version_string;
2261 	kex->load_host_key=&get_hostkey_by_type;
2262 	kex->host_key_index=&get_hostkey_index;
2263 
2264 	xxx_kex = kex;
2265 
2266 	dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
2267 
2268 	if (kex->name) {
2269 		xfree(kex->name);
2270 		kex->name = NULL;
2271 	}
2272 	session_id2 = kex->session_id;
2273 	session_id2_len = kex->session_id_len;
2274 
2275 #ifdef DEBUG_KEXDH
2276 	/* send 1st encrypted/maced/compressed message */
2277 	packet_start(SSH2_MSG_IGNORE);
2278 	packet_put_cstring("markus");
2279 	packet_send();
2280 	packet_write_wait();
2281 #endif
2282 	debug("KEX done");
2283 }
2284