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