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