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