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