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