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