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