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