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