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