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