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