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