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