xref: /openbsd-src/usr.bin/ssh/sshd.c (revision 4c1e55dc91edd6e69ccc60ce855900fbc12cf34f)
1 /* $OpenBSD: sshd.c,v 1.393 2012/07/10 02:19:15 djm Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
6  * This program is the ssh daemon.  It listens for connections from clients,
7  * and performs authentication, executes use commands or shell, and forwards
8  * information to/from the application to the user client over an encrypted
9  * connection.  This can also handle forwarding of X11, TCP/IP, and
10  * authentication agent connections.
11  *
12  * As far as I am concerned, the code I have written for this software
13  * can be used freely for any purpose.  Any derived versions of this
14  * software must be clearly marked as such, and if the derived work is
15  * incompatible with the protocol description in the RFC file, it must be
16  * called by a name other than "ssh" or "Secure Shell".
17  *
18  * SSH2 implementation:
19  * Privilege Separation:
20  *
21  * Copyright (c) 2000, 2001, 2002 Markus Friedl.  All rights reserved.
22  * Copyright (c) 2002 Niels Provos.  All rights reserved.
23  *
24  * Redistribution and use in source and binary forms, with or without
25  * modification, are permitted provided that the following conditions
26  * are met:
27  * 1. Redistributions of source code must retain the above copyright
28  *    notice, this list of conditions and the following disclaimer.
29  * 2. Redistributions in binary form must reproduce the above copyright
30  *    notice, this list of conditions and the following disclaimer in the
31  *    documentation and/or other materials provided with the distribution.
32  *
33  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
34  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
35  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
36  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
37  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
38  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
39  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
40  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
41  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
42  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43  */
44 
45 #include <sys/types.h>
46 #include <sys/ioctl.h>
47 #include <sys/wait.h>
48 #include <sys/tree.h>
49 #include <sys/stat.h>
50 #include <sys/socket.h>
51 #include <sys/time.h>
52 #include <sys/queue.h>
53 
54 #include <errno.h>
55 #include <fcntl.h>
56 #include <netdb.h>
57 #include <paths.h>
58 #include <pwd.h>
59 #include <signal.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <unistd.h>
64 
65 #include <openssl/dh.h>
66 #include <openssl/bn.h>
67 #include <openssl/md5.h>
68 #include <openssl/rand.h>
69 
70 #include "xmalloc.h"
71 #include "ssh.h"
72 #include "ssh1.h"
73 #include "ssh2.h"
74 #include "rsa.h"
75 #include "sshpty.h"
76 #include "packet.h"
77 #include "log.h"
78 #include "buffer.h"
79 #include "servconf.h"
80 #include "uidswap.h"
81 #include "compat.h"
82 #include "cipher.h"
83 #include "key.h"
84 #include "kex.h"
85 #include "dh.h"
86 #include "myproposal.h"
87 #include "authfile.h"
88 #include "pathnames.h"
89 #include "atomicio.h"
90 #include "canohost.h"
91 #include "hostfile.h"
92 #include "auth.h"
93 #include "misc.h"
94 #include "msg.h"
95 #include "dispatch.h"
96 #include "channels.h"
97 #include "session.h"
98 #include "monitor_mm.h"
99 #include "monitor.h"
100 #ifdef GSSAPI
101 #include "ssh-gss.h"
102 #endif
103 #include "monitor_wrap.h"
104 #include "roaming.h"
105 #include "ssh-sandbox.h"
106 #include "version.h"
107 
108 #ifdef LIBWRAP
109 #include <tcpd.h>
110 #include <syslog.h>
111 int allow_severity = LOG_INFO;
112 int deny_severity = LOG_WARNING;
113 #endif /* LIBWRAP */
114 
115 #ifndef O_NOCTTY
116 #define O_NOCTTY	0
117 #endif
118 
119 /* Re-exec fds */
120 #define REEXEC_DEVCRYPTO_RESERVED_FD	(STDERR_FILENO + 1)
121 #define REEXEC_STARTUP_PIPE_FD		(STDERR_FILENO + 2)
122 #define REEXEC_CONFIG_PASS_FD		(STDERR_FILENO + 3)
123 #define REEXEC_MIN_FREE_FD		(STDERR_FILENO + 4)
124 
125 extern char *__progname;
126 
127 /* Server configuration options. */
128 ServerOptions options;
129 
130 /* Name of the server configuration file. */
131 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
132 
133 /*
134  * Debug mode flag.  This can be set on the command line.  If debug
135  * mode is enabled, extra debugging output will be sent to the system
136  * log, the daemon will not go to background, and will exit after processing
137  * the first connection.
138  */
139 int debug_flag = 0;
140 
141 /* Flag indicating that the daemon should only test the configuration and keys. */
142 int test_flag = 0;
143 
144 /* Flag indicating that the daemon is being started from inetd. */
145 int inetd_flag = 0;
146 
147 /* Flag indicating that sshd should not detach and become a daemon. */
148 int no_daemon_flag = 0;
149 
150 /* debug goes to stderr unless inetd_flag is set */
151 int log_stderr = 0;
152 
153 /* Saved arguments to main(). */
154 char **saved_argv;
155 
156 /* re-exec */
157 int rexeced_flag = 0;
158 int rexec_flag = 1;
159 int rexec_argc = 0;
160 char **rexec_argv;
161 
162 /*
163  * The sockets that the server is listening; this is used in the SIGHUP
164  * signal handler.
165  */
166 #define	MAX_LISTEN_SOCKS	16
167 int listen_socks[MAX_LISTEN_SOCKS];
168 int num_listen_socks = 0;
169 
170 /*
171  * the client's version string, passed by sshd2 in compat mode. if != NULL,
172  * sshd will skip the version-number exchange
173  */
174 char *client_version_string = NULL;
175 char *server_version_string = NULL;
176 
177 /* for rekeying XXX fixme */
178 Kex *xxx_kex;
179 
180 /*
181  * Any really sensitive data in the application is contained in this
182  * structure. The idea is that this structure could be locked into memory so
183  * that the pages do not get written into swap.  However, there are some
184  * problems. The private key contains BIGNUMs, and we do not (in principle)
185  * have access to the internals of them, and locking just the structure is
186  * not very useful.  Currently, memory locking is not implemented.
187  */
188 struct {
189 	Key	*server_key;		/* ephemeral server key */
190 	Key	*ssh1_host_key;		/* ssh1 host key */
191 	Key	**host_keys;		/* all private host keys */
192 	Key	**host_certificates;	/* all public host certificates */
193 	int	have_ssh1_key;
194 	int	have_ssh2_key;
195 	u_char	ssh1_cookie[SSH_SESSION_KEY_LENGTH];
196 } sensitive_data;
197 
198 /*
199  * Flag indicating whether the RSA server key needs to be regenerated.
200  * Is set in the SIGALRM handler and cleared when the key is regenerated.
201  */
202 static volatile sig_atomic_t key_do_regen = 0;
203 
204 /* This is set to true when a signal is received. */
205 static volatile sig_atomic_t received_sighup = 0;
206 static volatile sig_atomic_t received_sigterm = 0;
207 
208 /* session identifier, used by RSA-auth */
209 u_char session_id[16];
210 
211 /* same for ssh2 */
212 u_char *session_id2 = NULL;
213 u_int session_id2_len = 0;
214 
215 /* record remote hostname or ip */
216 u_int utmp_len = MAXHOSTNAMELEN;
217 
218 /* options.max_startup sized array of fd ints */
219 int *startup_pipes = NULL;
220 int startup_pipe;		/* in child */
221 
222 /* variables used for privilege separation */
223 int use_privsep = -1;
224 struct monitor *pmonitor = NULL;
225 int privsep_is_preauth = 1;
226 
227 /* global authentication context */
228 Authctxt *the_authctxt = NULL;
229 
230 /* sshd_config buffer */
231 Buffer cfg;
232 
233 /* message to be displayed after login */
234 Buffer loginmsg;
235 
236 /* Prototypes for various functions defined later in this file. */
237 void destroy_sensitive_data(void);
238 void demote_sensitive_data(void);
239 
240 static void do_ssh1_kex(void);
241 static void do_ssh2_kex(void);
242 
243 /*
244  * Close all listening sockets
245  */
246 static void
247 close_listen_socks(void)
248 {
249 	int i;
250 
251 	for (i = 0; i < num_listen_socks; i++)
252 		close(listen_socks[i]);
253 	num_listen_socks = -1;
254 }
255 
256 static void
257 close_startup_pipes(void)
258 {
259 	int i;
260 
261 	if (startup_pipes)
262 		for (i = 0; i < options.max_startups; i++)
263 			if (startup_pipes[i] != -1)
264 				close(startup_pipes[i]);
265 }
266 
267 /*
268  * Signal handler for SIGHUP.  Sshd execs itself when it receives SIGHUP;
269  * the effect is to reread the configuration file (and to regenerate
270  * the server key).
271  */
272 
273 /*ARGSUSED*/
274 static void
275 sighup_handler(int sig)
276 {
277 	int save_errno = errno;
278 
279 	received_sighup = 1;
280 	signal(SIGHUP, sighup_handler);
281 	errno = save_errno;
282 }
283 
284 /*
285  * Called from the main program after receiving SIGHUP.
286  * Restarts the server.
287  */
288 static void
289 sighup_restart(void)
290 {
291 	logit("Received SIGHUP; restarting.");
292 	close_listen_socks();
293 	close_startup_pipes();
294 	alarm(0);  /* alarm timer persists across exec */
295 	signal(SIGHUP, SIG_IGN); /* will be restored after exec */
296 	execv(saved_argv[0], saved_argv);
297 	logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
298 	    strerror(errno));
299 	exit(1);
300 }
301 
302 /*
303  * Generic signal handler for terminating signals in the master daemon.
304  */
305 /*ARGSUSED*/
306 static void
307 sigterm_handler(int sig)
308 {
309 	received_sigterm = sig;
310 }
311 
312 /*
313  * SIGCHLD handler.  This is called whenever a child dies.  This will then
314  * reap any zombies left by exited children.
315  */
316 /*ARGSUSED*/
317 static void
318 main_sigchld_handler(int sig)
319 {
320 	int save_errno = errno;
321 	pid_t pid;
322 	int status;
323 
324 	while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
325 	    (pid < 0 && errno == EINTR))
326 		;
327 
328 	signal(SIGCHLD, main_sigchld_handler);
329 	errno = save_errno;
330 }
331 
332 /*
333  * Signal handler for the alarm after the login grace period has expired.
334  */
335 /*ARGSUSED*/
336 static void
337 grace_alarm_handler(int sig)
338 {
339 	if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
340 		kill(pmonitor->m_pid, SIGALRM);
341 
342 	/* Log error and exit. */
343 	sigdie("Timeout before authentication for %s", get_remote_ipaddr());
344 }
345 
346 /*
347  * Signal handler for the key regeneration alarm.  Note that this
348  * alarm only occurs in the daemon waiting for connections, and it does not
349  * do anything with the private key or random state before forking.
350  * Thus there should be no concurrency control/asynchronous execution
351  * problems.
352  */
353 static void
354 generate_ephemeral_server_key(void)
355 {
356 	verbose("Generating %s%d bit RSA key.",
357 	    sensitive_data.server_key ? "new " : "", options.server_key_bits);
358 	if (sensitive_data.server_key != NULL)
359 		key_free(sensitive_data.server_key);
360 	sensitive_data.server_key = key_generate(KEY_RSA1,
361 	    options.server_key_bits);
362 	verbose("RSA key generation complete.");
363 
364 	arc4random_buf(sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
365 	arc4random_stir();
366 }
367 
368 /*ARGSUSED*/
369 static void
370 key_regeneration_alarm(int sig)
371 {
372 	int save_errno = errno;
373 
374 	signal(SIGALRM, SIG_DFL);
375 	errno = save_errno;
376 	key_do_regen = 1;
377 }
378 
379 static void
380 sshd_exchange_identification(int sock_in, int sock_out)
381 {
382 	u_int i;
383 	int mismatch;
384 	int remote_major, remote_minor;
385 	int major, minor;
386 	char *s, *newline = "\n";
387 	char buf[256];			/* Must not be larger than remote_version. */
388 	char remote_version[256];	/* Must be at least as big as buf. */
389 
390 	if ((options.protocol & SSH_PROTO_1) &&
391 	    (options.protocol & SSH_PROTO_2)) {
392 		major = PROTOCOL_MAJOR_1;
393 		minor = 99;
394 	} else if (options.protocol & SSH_PROTO_2) {
395 		major = PROTOCOL_MAJOR_2;
396 		minor = PROTOCOL_MINOR_2;
397 		newline = "\r\n";
398 	} else {
399 		major = PROTOCOL_MAJOR_1;
400 		minor = PROTOCOL_MINOR_1;
401 	}
402 
403 	xasprintf(&server_version_string, "SSH-%d.%d-%.100s%s%s%s",
404 	    major, minor, SSH_VERSION,
405 	    *options.version_addendum == '\0' ? "" : " ",
406 	    options.version_addendum, newline);
407 
408 	/* Send our protocol version identification. */
409 	if (roaming_atomicio(vwrite, sock_out, server_version_string,
410 	    strlen(server_version_string))
411 	    != strlen(server_version_string)) {
412 		logit("Could not write ident string to %s", get_remote_ipaddr());
413 		cleanup_exit(255);
414 	}
415 
416 	/* Read other sides version identification. */
417 	memset(buf, 0, sizeof(buf));
418 	for (i = 0; i < sizeof(buf) - 1; i++) {
419 		if (roaming_atomicio(read, sock_in, &buf[i], 1) != 1) {
420 			logit("Did not receive identification string from %s",
421 			    get_remote_ipaddr());
422 			cleanup_exit(255);
423 		}
424 		if (buf[i] == '\r') {
425 			buf[i] = 0;
426 			/* Kludge for F-Secure Macintosh < 1.0.2 */
427 			if (i == 12 &&
428 			    strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
429 				break;
430 			continue;
431 		}
432 		if (buf[i] == '\n') {
433 			buf[i] = 0;
434 			break;
435 		}
436 	}
437 	buf[sizeof(buf) - 1] = 0;
438 	client_version_string = xstrdup(buf);
439 
440 	/*
441 	 * Check that the versions match.  In future this might accept
442 	 * several versions and set appropriate flags to handle them.
443 	 */
444 	if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
445 	    &remote_major, &remote_minor, remote_version) != 3) {
446 		s = "Protocol mismatch.\n";
447 		(void) atomicio(vwrite, sock_out, s, strlen(s));
448 		close(sock_in);
449 		close(sock_out);
450 		logit("Bad protocol version identification '%.100s' from %s",
451 		    client_version_string, get_remote_ipaddr());
452 		cleanup_exit(255);
453 	}
454 	debug("Client protocol version %d.%d; client software version %.100s",
455 	    remote_major, remote_minor, remote_version);
456 
457 	compat_datafellows(remote_version);
458 
459 	if (datafellows & SSH_BUG_PROBE) {
460 		logit("probed from %s with %s.  Don't panic.",
461 		    get_remote_ipaddr(), client_version_string);
462 		cleanup_exit(255);
463 	}
464 
465 	if (datafellows & SSH_BUG_SCANNER) {
466 		logit("scanned from %s with %s.  Don't panic.",
467 		    get_remote_ipaddr(), client_version_string);
468 		cleanup_exit(255);
469 	}
470 
471 	mismatch = 0;
472 	switch (remote_major) {
473 	case 1:
474 		if (remote_minor == 99) {
475 			if (options.protocol & SSH_PROTO_2)
476 				enable_compat20();
477 			else
478 				mismatch = 1;
479 			break;
480 		}
481 		if (!(options.protocol & SSH_PROTO_1)) {
482 			mismatch = 1;
483 			break;
484 		}
485 		if (remote_minor < 3) {
486 			packet_disconnect("Your ssh version is too old and "
487 			    "is no longer supported.  Please install a newer version.");
488 		} else if (remote_minor == 3) {
489 			/* note that this disables agent-forwarding */
490 			enable_compat13();
491 		}
492 		break;
493 	case 2:
494 		if (options.protocol & SSH_PROTO_2) {
495 			enable_compat20();
496 			break;
497 		}
498 		/* FALLTHROUGH */
499 	default:
500 		mismatch = 1;
501 		break;
502 	}
503 	chop(server_version_string);
504 	debug("Local version string %.200s", server_version_string);
505 
506 	if (mismatch) {
507 		s = "Protocol major versions differ.\n";
508 		(void) atomicio(vwrite, sock_out, s, strlen(s));
509 		close(sock_in);
510 		close(sock_out);
511 		logit("Protocol major versions differ for %s: %.200s vs. %.200s",
512 		    get_remote_ipaddr(),
513 		    server_version_string, client_version_string);
514 		cleanup_exit(255);
515 	}
516 }
517 
518 /* Destroy the host and server keys.  They will no longer be needed. */
519 void
520 destroy_sensitive_data(void)
521 {
522 	int i;
523 
524 	if (sensitive_data.server_key) {
525 		key_free(sensitive_data.server_key);
526 		sensitive_data.server_key = NULL;
527 	}
528 	for (i = 0; i < options.num_host_key_files; i++) {
529 		if (sensitive_data.host_keys[i]) {
530 			key_free(sensitive_data.host_keys[i]);
531 			sensitive_data.host_keys[i] = NULL;
532 		}
533 		if (sensitive_data.host_certificates[i]) {
534 			key_free(sensitive_data.host_certificates[i]);
535 			sensitive_data.host_certificates[i] = NULL;
536 		}
537 	}
538 	sensitive_data.ssh1_host_key = NULL;
539 	memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
540 }
541 
542 /* Demote private to public keys for network child */
543 void
544 demote_sensitive_data(void)
545 {
546 	Key *tmp;
547 	int i;
548 
549 	if (sensitive_data.server_key) {
550 		tmp = key_demote(sensitive_data.server_key);
551 		key_free(sensitive_data.server_key);
552 		sensitive_data.server_key = tmp;
553 	}
554 
555 	for (i = 0; i < options.num_host_key_files; i++) {
556 		if (sensitive_data.host_keys[i]) {
557 			tmp = key_demote(sensitive_data.host_keys[i]);
558 			key_free(sensitive_data.host_keys[i]);
559 			sensitive_data.host_keys[i] = tmp;
560 			if (tmp->type == KEY_RSA1)
561 				sensitive_data.ssh1_host_key = tmp;
562 		}
563 		/* Certs do not need demotion */
564 	}
565 
566 	/* We do not clear ssh1_host key and cookie.  XXX - Okay Niels? */
567 }
568 
569 static void
570 privsep_preauth_child(void)
571 {
572 	u_int32_t rnd[256];
573 	gid_t gidset[1];
574 	struct passwd *pw;
575 
576 	/* Enable challenge-response authentication for privilege separation */
577 	privsep_challenge_enable();
578 
579 	arc4random_stir();
580 	arc4random_buf(rnd, sizeof(rnd));
581 	RAND_seed(rnd, sizeof(rnd));
582 
583 	/* Demote the private keys to public keys. */
584 	demote_sensitive_data();
585 
586 	if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL)
587 		fatal("Privilege separation user %s does not exist",
588 		    SSH_PRIVSEP_USER);
589 	memset(pw->pw_passwd, 0, strlen(pw->pw_passwd));
590 	endpwent();
591 
592 	/* Change our root directory */
593 	if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
594 		fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
595 		    strerror(errno));
596 	if (chdir("/") == -1)
597 		fatal("chdir(\"/\"): %s", strerror(errno));
598 
599 	/* Drop our privileges */
600 	debug3("privsep user:group %u:%u", (u_int)pw->pw_uid,
601 	    (u_int)pw->pw_gid);
602 #if 0
603 	/* XXX not ready, too heavy after chroot */
604 	do_setusercontext(pw);
605 #else
606 	gidset[0] = pw->pw_gid;
607 	if (setgroups(1, gidset) < 0)
608 		fatal("setgroups: %.100s", strerror(errno));
609 	permanently_set_uid(pw);
610 #endif
611 }
612 
613 static int
614 privsep_preauth(Authctxt *authctxt)
615 {
616 	int status;
617 	pid_t pid;
618 	struct ssh_sandbox *box = NULL;
619 
620 	/* Set up unprivileged child process to deal with network data */
621 	pmonitor = monitor_init();
622 	/* Store a pointer to the kex for later rekeying */
623 	pmonitor->m_pkex = &xxx_kex;
624 
625 	if (use_privsep == PRIVSEP_ON)
626 		box = ssh_sandbox_init();
627 	pid = fork();
628 	if (pid == -1) {
629 		fatal("fork of unprivileged child failed");
630 	} else if (pid != 0) {
631 		debug2("Network child is on pid %ld", (long)pid);
632 
633 		pmonitor->m_pid = pid;
634 		if (box != NULL)
635 			ssh_sandbox_parent_preauth(box, pid);
636 		monitor_child_preauth(authctxt, pmonitor);
637 
638 		/* Sync memory */
639 		monitor_sync(pmonitor);
640 
641 		/* Wait for the child's exit status */
642 		while (waitpid(pid, &status, 0) < 0) {
643 			if (errno == EINTR)
644 				continue;
645 			pmonitor->m_pid = -1;
646 			fatal("%s: waitpid: %s", __func__, strerror(errno));
647 		}
648 		privsep_is_preauth = 0;
649 		pmonitor->m_pid = -1;
650 		if (WIFEXITED(status)) {
651 			if (WEXITSTATUS(status) != 0)
652 				fatal("%s: preauth child exited with status %d",
653 				    __func__, WEXITSTATUS(status));
654 		} else if (WIFSIGNALED(status))
655 			fatal("%s: preauth child terminated by signal %d",
656 			    __func__, WTERMSIG(status));
657 		if (box != NULL)
658 			ssh_sandbox_parent_finish(box);
659 		return 1;
660 	} else {
661 		/* child */
662 		close(pmonitor->m_sendfd);
663 		close(pmonitor->m_log_recvfd);
664 
665 		/* Arrange for logging to be sent to the monitor */
666 		set_log_handler(mm_log_handler, pmonitor);
667 
668 		/* Demote the child */
669 		if (getuid() == 0 || geteuid() == 0)
670 			privsep_preauth_child();
671 		setproctitle("%s", "[net]");
672 		if (box != NULL)
673 			ssh_sandbox_child(box);
674 
675 		return 0;
676 	}
677 }
678 
679 static void
680 privsep_postauth(Authctxt *authctxt)
681 {
682 	u_int32_t rnd[256];
683 
684 	if (authctxt->pw->pw_uid == 0 || options.use_login) {
685 		/* File descriptor passing is broken or root login */
686 		use_privsep = 0;
687 		goto skip;
688 	}
689 
690 	/* New socket pair */
691 	monitor_reinit(pmonitor);
692 
693 	pmonitor->m_pid = fork();
694 	if (pmonitor->m_pid == -1)
695 		fatal("fork of unprivileged child failed");
696 	else if (pmonitor->m_pid != 0) {
697 		verbose("User child is on pid %ld", (long)pmonitor->m_pid);
698 		buffer_clear(&loginmsg);
699 		monitor_child_postauth(pmonitor);
700 
701 		/* NEVERREACHED */
702 		exit(0);
703 	}
704 
705 	/* child */
706 
707 	close(pmonitor->m_sendfd);
708 	pmonitor->m_sendfd = -1;
709 
710 	/* Demote the private keys to public keys. */
711 	demote_sensitive_data();
712 
713 	arc4random_stir();
714 	arc4random_buf(rnd, sizeof(rnd));
715 	RAND_seed(rnd, sizeof(rnd));
716 
717 	/* Drop privileges */
718 	do_setusercontext(authctxt->pw);
719 
720  skip:
721 	/* It is safe now to apply the key state */
722 	monitor_apply_keystate(pmonitor);
723 
724 	/*
725 	 * Tell the packet layer that authentication was successful, since
726 	 * this information is not part of the key state.
727 	 */
728 	packet_set_authenticated();
729 }
730 
731 static char *
732 list_hostkey_types(void)
733 {
734 	Buffer b;
735 	const char *p;
736 	char *ret;
737 	int i;
738 	Key *key;
739 
740 	buffer_init(&b);
741 	for (i = 0; i < options.num_host_key_files; i++) {
742 		key = sensitive_data.host_keys[i];
743 		if (key == NULL)
744 			continue;
745 		switch (key->type) {
746 		case KEY_RSA:
747 		case KEY_DSA:
748 		case KEY_ECDSA:
749 			if (buffer_len(&b) > 0)
750 				buffer_append(&b, ",", 1);
751 			p = key_ssh_name(key);
752 			buffer_append(&b, p, strlen(p));
753 			break;
754 		}
755 		/* If the private key has a cert peer, then list that too */
756 		key = sensitive_data.host_certificates[i];
757 		if (key == NULL)
758 			continue;
759 		switch (key->type) {
760 		case KEY_RSA_CERT_V00:
761 		case KEY_DSA_CERT_V00:
762 		case KEY_RSA_CERT:
763 		case KEY_DSA_CERT:
764 		case KEY_ECDSA_CERT:
765 			if (buffer_len(&b) > 0)
766 				buffer_append(&b, ",", 1);
767 			p = key_ssh_name(key);
768 			buffer_append(&b, p, strlen(p));
769 			break;
770 		}
771 	}
772 	buffer_append(&b, "\0", 1);
773 	ret = xstrdup(buffer_ptr(&b));
774 	buffer_free(&b);
775 	debug("list_hostkey_types: %s", ret);
776 	return ret;
777 }
778 
779 static Key *
780 get_hostkey_by_type(int type, int need_private)
781 {
782 	int i;
783 	Key *key;
784 
785 	for (i = 0; i < options.num_host_key_files; i++) {
786 		switch (type) {
787 		case KEY_RSA_CERT_V00:
788 		case KEY_DSA_CERT_V00:
789 		case KEY_RSA_CERT:
790 		case KEY_DSA_CERT:
791 		case KEY_ECDSA_CERT:
792 			key = sensitive_data.host_certificates[i];
793 			break;
794 		default:
795 			key = sensitive_data.host_keys[i];
796 			break;
797 		}
798 		if (key != NULL && key->type == type)
799 			return need_private ?
800 			    sensitive_data.host_keys[i] : key;
801 	}
802 	return NULL;
803 }
804 
805 Key *
806 get_hostkey_public_by_type(int type)
807 {
808 	return get_hostkey_by_type(type, 0);
809 }
810 
811 Key *
812 get_hostkey_private_by_type(int type)
813 {
814 	return get_hostkey_by_type(type, 1);
815 }
816 
817 Key *
818 get_hostkey_by_index(int ind)
819 {
820 	if (ind < 0 || ind >= options.num_host_key_files)
821 		return (NULL);
822 	return (sensitive_data.host_keys[ind]);
823 }
824 
825 int
826 get_hostkey_index(Key *key)
827 {
828 	int i;
829 
830 	for (i = 0; i < options.num_host_key_files; i++) {
831 		if (key_is_cert(key)) {
832 			if (key == sensitive_data.host_certificates[i])
833 				return (i);
834 		} else {
835 			if (key == sensitive_data.host_keys[i])
836 				return (i);
837 		}
838 	}
839 	return (-1);
840 }
841 
842 /*
843  * returns 1 if connection should be dropped, 0 otherwise.
844  * dropping starts at connection #max_startups_begin with a probability
845  * of (max_startups_rate/100). the probability increases linearly until
846  * all connections are dropped for startups > max_startups
847  */
848 static int
849 drop_connection(int startups)
850 {
851 	int p, r;
852 
853 	if (startups < options.max_startups_begin)
854 		return 0;
855 	if (startups >= options.max_startups)
856 		return 1;
857 	if (options.max_startups_rate == 100)
858 		return 1;
859 
860 	p  = 100 - options.max_startups_rate;
861 	p *= startups - options.max_startups_begin;
862 	p /= options.max_startups - options.max_startups_begin;
863 	p += options.max_startups_rate;
864 	r = arc4random_uniform(100);
865 
866 	debug("drop_connection: p %d, r %d", p, r);
867 	return (r < p) ? 1 : 0;
868 }
869 
870 static void
871 usage(void)
872 {
873 	fprintf(stderr, "%s, %s\n",
874 	    SSH_VERSION, SSLeay_version(SSLEAY_VERSION));
875 	fprintf(stderr,
876 "usage: sshd [-46DdeiqTt] [-b bits] [-C connection_spec] [-c host_cert_file]\n"
877 "            [-f config_file] [-g login_grace_time] [-h host_key_file]\n"
878 "            [-k key_gen_time] [-o option] [-p port] [-u len]\n"
879 	);
880 	exit(1);
881 }
882 
883 static void
884 send_rexec_state(int fd, Buffer *conf)
885 {
886 	Buffer m;
887 
888 	debug3("%s: entering fd = %d config len %d", __func__, fd,
889 	    buffer_len(conf));
890 
891 	/*
892 	 * Protocol from reexec master to child:
893 	 *	string	configuration
894 	 *	u_int	ephemeral_key_follows
895 	 *	bignum	e		(only if ephemeral_key_follows == 1)
896 	 *	bignum	n			"
897 	 *	bignum	d			"
898 	 *	bignum	iqmp			"
899 	 *	bignum	p			"
900 	 *	bignum	q			"
901 	 */
902 	buffer_init(&m);
903 	buffer_put_cstring(&m, buffer_ptr(conf));
904 
905 	if (sensitive_data.server_key != NULL &&
906 	    sensitive_data.server_key->type == KEY_RSA1) {
907 		buffer_put_int(&m, 1);
908 		buffer_put_bignum(&m, sensitive_data.server_key->rsa->e);
909 		buffer_put_bignum(&m, sensitive_data.server_key->rsa->n);
910 		buffer_put_bignum(&m, sensitive_data.server_key->rsa->d);
911 		buffer_put_bignum(&m, sensitive_data.server_key->rsa->iqmp);
912 		buffer_put_bignum(&m, sensitive_data.server_key->rsa->p);
913 		buffer_put_bignum(&m, sensitive_data.server_key->rsa->q);
914 	} else
915 		buffer_put_int(&m, 0);
916 
917 	if (ssh_msg_send(fd, 0, &m) == -1)
918 		fatal("%s: ssh_msg_send failed", __func__);
919 
920 	buffer_free(&m);
921 
922 	debug3("%s: done", __func__);
923 }
924 
925 static void
926 recv_rexec_state(int fd, Buffer *conf)
927 {
928 	Buffer m;
929 	char *cp;
930 	u_int len;
931 
932 	debug3("%s: entering fd = %d", __func__, fd);
933 
934 	buffer_init(&m);
935 
936 	if (ssh_msg_recv(fd, &m) == -1)
937 		fatal("%s: ssh_msg_recv failed", __func__);
938 	if (buffer_get_char(&m) != 0)
939 		fatal("%s: rexec version mismatch", __func__);
940 
941 	cp = buffer_get_string(&m, &len);
942 	if (conf != NULL)
943 		buffer_append(conf, cp, len + 1);
944 	xfree(cp);
945 
946 	if (buffer_get_int(&m)) {
947 		if (sensitive_data.server_key != NULL)
948 			key_free(sensitive_data.server_key);
949 		sensitive_data.server_key = key_new_private(KEY_RSA1);
950 		buffer_get_bignum(&m, sensitive_data.server_key->rsa->e);
951 		buffer_get_bignum(&m, sensitive_data.server_key->rsa->n);
952 		buffer_get_bignum(&m, sensitive_data.server_key->rsa->d);
953 		buffer_get_bignum(&m, sensitive_data.server_key->rsa->iqmp);
954 		buffer_get_bignum(&m, sensitive_data.server_key->rsa->p);
955 		buffer_get_bignum(&m, sensitive_data.server_key->rsa->q);
956 		rsa_generate_additional_parameters(
957 		    sensitive_data.server_key->rsa);
958 	}
959 	buffer_free(&m);
960 
961 	debug3("%s: done", __func__);
962 }
963 
964 /* Accept a connection from inetd */
965 static void
966 server_accept_inetd(int *sock_in, int *sock_out)
967 {
968 	int fd;
969 
970 	startup_pipe = -1;
971 	if (rexeced_flag) {
972 		close(REEXEC_CONFIG_PASS_FD);
973 		*sock_in = *sock_out = dup(STDIN_FILENO);
974 		if (!debug_flag) {
975 			startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
976 			close(REEXEC_STARTUP_PIPE_FD);
977 		}
978 	} else {
979 		*sock_in = dup(STDIN_FILENO);
980 		*sock_out = dup(STDOUT_FILENO);
981 	}
982 	/*
983 	 * We intentionally do not close the descriptors 0, 1, and 2
984 	 * as our code for setting the descriptors won't work if
985 	 * ttyfd happens to be one of those.
986 	 */
987 	if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
988 		dup2(fd, STDIN_FILENO);
989 		dup2(fd, STDOUT_FILENO);
990 		if (fd > STDOUT_FILENO)
991 			close(fd);
992 	}
993 	debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
994 }
995 
996 /*
997  * Listen for TCP connections
998  */
999 static void
1000 server_listen(void)
1001 {
1002 	int ret, listen_sock, on = 1;
1003 	struct addrinfo *ai;
1004 	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1005 
1006 	for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
1007 		if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1008 			continue;
1009 		if (num_listen_socks >= MAX_LISTEN_SOCKS)
1010 			fatal("Too many listen sockets. "
1011 			    "Enlarge MAX_LISTEN_SOCKS");
1012 		if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1013 		    ntop, sizeof(ntop), strport, sizeof(strport),
1014 		    NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1015 			error("getnameinfo failed: %.100s",
1016 			    ssh_gai_strerror(ret));
1017 			continue;
1018 		}
1019 		/* Create socket for listening. */
1020 		listen_sock = socket(ai->ai_family, ai->ai_socktype,
1021 		    ai->ai_protocol);
1022 		if (listen_sock < 0) {
1023 			/* kernel may not support ipv6 */
1024 			verbose("socket: %.100s", strerror(errno));
1025 			continue;
1026 		}
1027 		if (set_nonblock(listen_sock) == -1) {
1028 			close(listen_sock);
1029 			continue;
1030 		}
1031 		/*
1032 		 * Set socket options.
1033 		 * Allow local port reuse in TIME_WAIT.
1034 		 */
1035 		if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
1036 		    &on, sizeof(on)) == -1)
1037 			error("setsockopt SO_REUSEADDR: %s", strerror(errno));
1038 
1039 		debug("Bind to port %s on %s.", strport, ntop);
1040 
1041 		/* Bind the socket to the desired port. */
1042 		if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1043 			error("Bind to port %s on %s failed: %.200s.",
1044 			    strport, ntop, strerror(errno));
1045 			close(listen_sock);
1046 			continue;
1047 		}
1048 		listen_socks[num_listen_socks] = listen_sock;
1049 		num_listen_socks++;
1050 
1051 		/* Start listening on the port. */
1052 		if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1053 			fatal("listen on [%s]:%s: %.100s",
1054 			    ntop, strport, strerror(errno));
1055 		logit("Server listening on %s port %s.", ntop, strport);
1056 	}
1057 	freeaddrinfo(options.listen_addrs);
1058 
1059 	if (!num_listen_socks)
1060 		fatal("Cannot bind any address.");
1061 }
1062 
1063 /*
1064  * The main TCP accept loop. Note that, for the non-debug case, returns
1065  * from this function are in a forked subprocess.
1066  */
1067 static void
1068 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1069 {
1070 	fd_set *fdset;
1071 	int i, j, ret, maxfd;
1072 	int key_used = 0, startups = 0;
1073 	int startup_p[2] = { -1 , -1 };
1074 	struct sockaddr_storage from;
1075 	socklen_t fromlen;
1076 	pid_t pid;
1077 
1078 	/* setup fd set for accept */
1079 	fdset = NULL;
1080 	maxfd = 0;
1081 	for (i = 0; i < num_listen_socks; i++)
1082 		if (listen_socks[i] > maxfd)
1083 			maxfd = listen_socks[i];
1084 	/* pipes connected to unauthenticated childs */
1085 	startup_pipes = xcalloc(options.max_startups, sizeof(int));
1086 	for (i = 0; i < options.max_startups; i++)
1087 		startup_pipes[i] = -1;
1088 
1089 	/*
1090 	 * Stay listening for connections until the system crashes or
1091 	 * the daemon is killed with a signal.
1092 	 */
1093 	for (;;) {
1094 		if (received_sighup)
1095 			sighup_restart();
1096 		if (fdset != NULL)
1097 			xfree(fdset);
1098 		fdset = (fd_set *)xcalloc(howmany(maxfd + 1, NFDBITS),
1099 		    sizeof(fd_mask));
1100 
1101 		for (i = 0; i < num_listen_socks; i++)
1102 			FD_SET(listen_socks[i], fdset);
1103 		for (i = 0; i < options.max_startups; i++)
1104 			if (startup_pipes[i] != -1)
1105 				FD_SET(startup_pipes[i], fdset);
1106 
1107 		/* Wait in select until there is a connection. */
1108 		ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1109 		if (ret < 0 && errno != EINTR)
1110 			error("select: %.100s", strerror(errno));
1111 		if (received_sigterm) {
1112 			logit("Received signal %d; terminating.",
1113 			    (int) received_sigterm);
1114 			close_listen_socks();
1115 			unlink(options.pid_file);
1116 			exit(received_sigterm == SIGTERM ? 0 : 255);
1117 		}
1118 		if (key_used && key_do_regen) {
1119 			generate_ephemeral_server_key();
1120 			key_used = 0;
1121 			key_do_regen = 0;
1122 		}
1123 		if (ret < 0)
1124 			continue;
1125 
1126 		for (i = 0; i < options.max_startups; i++)
1127 			if (startup_pipes[i] != -1 &&
1128 			    FD_ISSET(startup_pipes[i], fdset)) {
1129 				/*
1130 				 * the read end of the pipe is ready
1131 				 * if the child has closed the pipe
1132 				 * after successful authentication
1133 				 * or if the child has died
1134 				 */
1135 				close(startup_pipes[i]);
1136 				startup_pipes[i] = -1;
1137 				startups--;
1138 			}
1139 		for (i = 0; i < num_listen_socks; i++) {
1140 			if (!FD_ISSET(listen_socks[i], fdset))
1141 				continue;
1142 			fromlen = sizeof(from);
1143 			*newsock = accept(listen_socks[i],
1144 			    (struct sockaddr *)&from, &fromlen);
1145 			if (*newsock < 0) {
1146 				if (errno != EINTR && errno != EWOULDBLOCK)
1147 					error("accept: %.100s",
1148 					    strerror(errno));
1149 				if (errno == EMFILE || errno == ENFILE)
1150 					usleep(100 * 1000);
1151 				continue;
1152 			}
1153 			if (unset_nonblock(*newsock) == -1) {
1154 				close(*newsock);
1155 				continue;
1156 			}
1157 			if (drop_connection(startups) == 1) {
1158 				debug("drop connection #%d", startups);
1159 				close(*newsock);
1160 				continue;
1161 			}
1162 			if (pipe(startup_p) == -1) {
1163 				close(*newsock);
1164 				continue;
1165 			}
1166 
1167 			if (rexec_flag && socketpair(AF_UNIX,
1168 			    SOCK_STREAM, 0, config_s) == -1) {
1169 				error("reexec socketpair: %s",
1170 				    strerror(errno));
1171 				close(*newsock);
1172 				close(startup_p[0]);
1173 				close(startup_p[1]);
1174 				continue;
1175 			}
1176 
1177 			for (j = 0; j < options.max_startups; j++)
1178 				if (startup_pipes[j] == -1) {
1179 					startup_pipes[j] = startup_p[0];
1180 					if (maxfd < startup_p[0])
1181 						maxfd = startup_p[0];
1182 					startups++;
1183 					break;
1184 				}
1185 
1186 			/*
1187 			 * Got connection.  Fork a child to handle it, unless
1188 			 * we are in debugging mode.
1189 			 */
1190 			if (debug_flag) {
1191 				/*
1192 				 * In debugging mode.  Close the listening
1193 				 * socket, and start processing the
1194 				 * connection without forking.
1195 				 */
1196 				debug("Server will not fork when running in debugging mode.");
1197 				close_listen_socks();
1198 				*sock_in = *newsock;
1199 				*sock_out = *newsock;
1200 				close(startup_p[0]);
1201 				close(startup_p[1]);
1202 				startup_pipe = -1;
1203 				pid = getpid();
1204 				if (rexec_flag) {
1205 					send_rexec_state(config_s[0],
1206 					    &cfg);
1207 					close(config_s[0]);
1208 				}
1209 				break;
1210 			}
1211 
1212 			/*
1213 			 * Normal production daemon.  Fork, and have
1214 			 * the child process the connection. The
1215 			 * parent continues listening.
1216 			 */
1217 			if ((pid = fork()) == 0) {
1218 				/*
1219 				 * Child.  Close the listening and
1220 				 * max_startup sockets.  Start using
1221 				 * the accepted socket. Reinitialize
1222 				 * logging (since our pid has changed).
1223 				 * We break out of the loop to handle
1224 				 * the connection.
1225 				 */
1226 				startup_pipe = startup_p[1];
1227 				close_startup_pipes();
1228 				close_listen_socks();
1229 				*sock_in = *newsock;
1230 				*sock_out = *newsock;
1231 				log_init(__progname,
1232 				    options.log_level,
1233 				    options.log_facility,
1234 				    log_stderr);
1235 				if (rexec_flag)
1236 					close(config_s[0]);
1237 				break;
1238 			}
1239 
1240 			/* Parent.  Stay in the loop. */
1241 			if (pid < 0)
1242 				error("fork: %.100s", strerror(errno));
1243 			else
1244 				debug("Forked child %ld.", (long)pid);
1245 
1246 			close(startup_p[1]);
1247 
1248 			if (rexec_flag) {
1249 				send_rexec_state(config_s[0], &cfg);
1250 				close(config_s[0]);
1251 				close(config_s[1]);
1252 			}
1253 
1254 			/*
1255 			 * Mark that the key has been used (it
1256 			 * was "given" to the child).
1257 			 */
1258 			if ((options.protocol & SSH_PROTO_1) &&
1259 			    key_used == 0) {
1260 				/* Schedule server key regeneration alarm. */
1261 				signal(SIGALRM, key_regeneration_alarm);
1262 				alarm(options.key_regeneration_time);
1263 				key_used = 1;
1264 			}
1265 
1266 			close(*newsock);
1267 
1268 			/*
1269 			 * Ensure that our random state differs
1270 			 * from that of the child
1271 			 */
1272 			arc4random_stir();
1273 		}
1274 
1275 		/* child process check (or debug mode) */
1276 		if (num_listen_socks < 0)
1277 			break;
1278 	}
1279 }
1280 
1281 
1282 /*
1283  * Main program for the daemon.
1284  */
1285 int
1286 main(int ac, char **av)
1287 {
1288 	extern char *optarg;
1289 	extern int optind;
1290 	int opt, i, j, on = 1;
1291 	int sock_in = -1, sock_out = -1, newsock = -1;
1292 	const char *remote_ip;
1293 	int remote_port;
1294 	char *line;
1295 	int config_s[2] = { -1 , -1 };
1296 	u_int64_t ibytes, obytes;
1297 	mode_t new_umask;
1298 	Key *key;
1299 	Authctxt *authctxt;
1300 	struct connection_info *connection_info = get_connection_info(0, 0);
1301 
1302 	/* Save argv. */
1303 	saved_argv = av;
1304 	rexec_argc = ac;
1305 
1306 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1307 	sanitise_stdfd();
1308 
1309 	/* Initialize configuration options to their default values. */
1310 	initialize_server_options(&options);
1311 
1312 	/* Parse command-line arguments. */
1313 	while ((opt = getopt(ac, av, "f:p:b:k:h:g:u:o:C:dDeiqrtQRT46")) != -1) {
1314 		switch (opt) {
1315 		case '4':
1316 			options.address_family = AF_INET;
1317 			break;
1318 		case '6':
1319 			options.address_family = AF_INET6;
1320 			break;
1321 		case 'f':
1322 			config_file_name = optarg;
1323 			break;
1324 		case 'c':
1325 			if (options.num_host_cert_files >= MAX_HOSTCERTS) {
1326 				fprintf(stderr, "too many host certificates.\n");
1327 				exit(1);
1328 			}
1329 			options.host_cert_files[options.num_host_cert_files++] =
1330 			   derelativise_path(optarg);
1331 			break;
1332 		case 'd':
1333 			if (debug_flag == 0) {
1334 				debug_flag = 1;
1335 				options.log_level = SYSLOG_LEVEL_DEBUG1;
1336 			} else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1337 				options.log_level++;
1338 			break;
1339 		case 'D':
1340 			no_daemon_flag = 1;
1341 			break;
1342 		case 'e':
1343 			log_stderr = 1;
1344 			break;
1345 		case 'i':
1346 			inetd_flag = 1;
1347 			break;
1348 		case 'r':
1349 			rexec_flag = 0;
1350 			break;
1351 		case 'R':
1352 			rexeced_flag = 1;
1353 			inetd_flag = 1;
1354 			break;
1355 		case 'Q':
1356 			/* ignored */
1357 			break;
1358 		case 'q':
1359 			options.log_level = SYSLOG_LEVEL_QUIET;
1360 			break;
1361 		case 'b':
1362 			options.server_key_bits = (int)strtonum(optarg, 256,
1363 			    32768, NULL);
1364 			break;
1365 		case 'p':
1366 			options.ports_from_cmdline = 1;
1367 			if (options.num_ports >= MAX_PORTS) {
1368 				fprintf(stderr, "too many ports.\n");
1369 				exit(1);
1370 			}
1371 			options.ports[options.num_ports++] = a2port(optarg);
1372 			if (options.ports[options.num_ports-1] <= 0) {
1373 				fprintf(stderr, "Bad port number.\n");
1374 				exit(1);
1375 			}
1376 			break;
1377 		case 'g':
1378 			if ((options.login_grace_time = convtime(optarg)) == -1) {
1379 				fprintf(stderr, "Invalid login grace time.\n");
1380 				exit(1);
1381 			}
1382 			break;
1383 		case 'k':
1384 			if ((options.key_regeneration_time = convtime(optarg)) == -1) {
1385 				fprintf(stderr, "Invalid key regeneration interval.\n");
1386 				exit(1);
1387 			}
1388 			break;
1389 		case 'h':
1390 			if (options.num_host_key_files >= MAX_HOSTKEYS) {
1391 				fprintf(stderr, "too many host keys.\n");
1392 				exit(1);
1393 			}
1394 			options.host_key_files[options.num_host_key_files++] =
1395 			   derelativise_path(optarg);
1396 			break;
1397 		case 't':
1398 			test_flag = 1;
1399 			break;
1400 		case 'T':
1401 			test_flag = 2;
1402 			break;
1403 		case 'C':
1404 			if (parse_server_match_testspec(connection_info,
1405 			    optarg) == -1)
1406 				exit(1);
1407 			break;
1408 		case 'u':
1409 			utmp_len = (u_int)strtonum(optarg, 0, MAXHOSTNAMELEN+1, NULL);
1410 			if (utmp_len > MAXHOSTNAMELEN) {
1411 				fprintf(stderr, "Invalid utmp length.\n");
1412 				exit(1);
1413 			}
1414 			break;
1415 		case 'o':
1416 			line = xstrdup(optarg);
1417 			if (process_server_config_line(&options, line,
1418 			    "command-line", 0, NULL, NULL) != 0)
1419 				exit(1);
1420 			xfree(line);
1421 			break;
1422 		case '?':
1423 		default:
1424 			usage();
1425 			break;
1426 		}
1427 	}
1428 	if (rexeced_flag || inetd_flag)
1429 		rexec_flag = 0;
1430 	if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1431 		fatal("sshd re-exec requires execution with an absolute path");
1432 	if (rexeced_flag)
1433 		closefrom(REEXEC_MIN_FREE_FD);
1434 	else
1435 		closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1436 
1437 	OpenSSL_add_all_algorithms();
1438 
1439 	/*
1440 	 * Force logging to stderr until we have loaded the private host
1441 	 * key (unless started from inetd)
1442 	 */
1443 	log_init(__progname,
1444 	    options.log_level == SYSLOG_LEVEL_NOT_SET ?
1445 	    SYSLOG_LEVEL_INFO : options.log_level,
1446 	    options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1447 	    SYSLOG_FACILITY_AUTH : options.log_facility,
1448 	    log_stderr || !inetd_flag);
1449 
1450 	sensitive_data.server_key = NULL;
1451 	sensitive_data.ssh1_host_key = NULL;
1452 	sensitive_data.have_ssh1_key = 0;
1453 	sensitive_data.have_ssh2_key = 0;
1454 
1455 	/*
1456 	 * If we're doing an extended config test, make sure we have all of
1457 	 * the parameters we need.  If we're not doing an extended test,
1458 	 * do not silently ignore connection test params.
1459 	 */
1460 	if (test_flag >= 2 && server_match_spec_complete(connection_info) == 0)
1461 		fatal("user, host and addr are all required when testing "
1462 		   "Match configs");
1463 	if (test_flag < 2 && server_match_spec_complete(connection_info) >= 0)
1464 		fatal("Config test connection parameter (-C) provided without "
1465 		   "test mode (-T)");
1466 
1467 	/* Fetch our configuration */
1468 	buffer_init(&cfg);
1469 	if (rexeced_flag)
1470 		recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1471 	else
1472 		load_server_config(config_file_name, &cfg);
1473 
1474 	parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1475 	    &cfg, NULL);
1476 
1477 	/* Fill in default values for those options not explicitly set. */
1478 	fill_default_server_options(&options);
1479 
1480 	/* challenge-response is implemented via keyboard interactive */
1481 	if (options.challenge_response_authentication)
1482 		options.kbd_interactive_authentication = 1;
1483 
1484 	/* set default channel AF */
1485 	channel_set_af(options.address_family);
1486 
1487 	/* Check that there are no remaining arguments. */
1488 	if (optind < ac) {
1489 		fprintf(stderr, "Extra argument %s.\n", av[optind]);
1490 		exit(1);
1491 	}
1492 
1493 	debug("sshd version %.100s", SSH_VERSION);
1494 
1495 	/* load private host keys */
1496 	sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1497 	    sizeof(Key *));
1498 	for (i = 0; i < options.num_host_key_files; i++)
1499 		sensitive_data.host_keys[i] = NULL;
1500 
1501 	for (i = 0; i < options.num_host_key_files; i++) {
1502 		key = key_load_private(options.host_key_files[i], "", NULL);
1503 		sensitive_data.host_keys[i] = key;
1504 		if (key == NULL) {
1505 			error("Could not load host key: %s",
1506 			    options.host_key_files[i]);
1507 			sensitive_data.host_keys[i] = NULL;
1508 			continue;
1509 		}
1510 		switch (key->type) {
1511 		case KEY_RSA1:
1512 			sensitive_data.ssh1_host_key = key;
1513 			sensitive_data.have_ssh1_key = 1;
1514 			break;
1515 		case KEY_RSA:
1516 		case KEY_DSA:
1517 		case KEY_ECDSA:
1518 			sensitive_data.have_ssh2_key = 1;
1519 			break;
1520 		}
1521 		debug("private host key: #%d type %d %s", i, key->type,
1522 		    key_type(key));
1523 	}
1524 	if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1525 		logit("Disabling protocol version 1. Could not load host key");
1526 		options.protocol &= ~SSH_PROTO_1;
1527 	}
1528 	if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1529 		logit("Disabling protocol version 2. Could not load host key");
1530 		options.protocol &= ~SSH_PROTO_2;
1531 	}
1532 	if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1533 		logit("sshd: no hostkeys available -- exiting.");
1534 		exit(1);
1535 	}
1536 
1537 	/*
1538 	 * Load certificates. They are stored in an array at identical
1539 	 * indices to the public keys that they relate to.
1540 	 */
1541 	sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
1542 	    sizeof(Key *));
1543 	for (i = 0; i < options.num_host_key_files; i++)
1544 		sensitive_data.host_certificates[i] = NULL;
1545 
1546 	for (i = 0; i < options.num_host_cert_files; i++) {
1547 		key = key_load_public(options.host_cert_files[i], NULL);
1548 		if (key == NULL) {
1549 			error("Could not load host certificate: %s",
1550 			    options.host_cert_files[i]);
1551 			continue;
1552 		}
1553 		if (!key_is_cert(key)) {
1554 			error("Certificate file is not a certificate: %s",
1555 			    options.host_cert_files[i]);
1556 			key_free(key);
1557 			continue;
1558 		}
1559 		/* Find matching private key */
1560 		for (j = 0; j < options.num_host_key_files; j++) {
1561 			if (key_equal_public(key,
1562 			    sensitive_data.host_keys[j])) {
1563 				sensitive_data.host_certificates[j] = key;
1564 				break;
1565 			}
1566 		}
1567 		if (j >= options.num_host_key_files) {
1568 			error("No matching private key for certificate: %s",
1569 			    options.host_cert_files[i]);
1570 			key_free(key);
1571 			continue;
1572 		}
1573 		sensitive_data.host_certificates[j] = key;
1574 		debug("host certificate: #%d type %d %s", j, key->type,
1575 		    key_type(key));
1576 	}
1577 	/* Check certain values for sanity. */
1578 	if (options.protocol & SSH_PROTO_1) {
1579 		if (options.server_key_bits < 512 ||
1580 		    options.server_key_bits > 32768) {
1581 			fprintf(stderr, "Bad server key size.\n");
1582 			exit(1);
1583 		}
1584 		/*
1585 		 * Check that server and host key lengths differ sufficiently. This
1586 		 * is necessary to make double encryption work with rsaref. Oh, I
1587 		 * hate software patents. I dont know if this can go? Niels
1588 		 */
1589 		if (options.server_key_bits >
1590 		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
1591 		    SSH_KEY_BITS_RESERVED && options.server_key_bits <
1592 		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1593 		    SSH_KEY_BITS_RESERVED) {
1594 			options.server_key_bits =
1595 			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1596 			    SSH_KEY_BITS_RESERVED;
1597 			debug("Forcing server key to %d bits to make it differ from host key.",
1598 			    options.server_key_bits);
1599 		}
1600 	}
1601 
1602 	if (use_privsep) {
1603 		struct stat st;
1604 
1605 		if (getpwnam(SSH_PRIVSEP_USER) == NULL)
1606 			fatal("Privilege separation user %s does not exist",
1607 			    SSH_PRIVSEP_USER);
1608 		if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1609 		    (S_ISDIR(st.st_mode) == 0))
1610 			fatal("Missing privilege separation directory: %s",
1611 			    _PATH_PRIVSEP_CHROOT_DIR);
1612 		if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1613 			fatal("%s must be owned by root and not group or "
1614 			    "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1615 	}
1616 
1617 	if (test_flag > 1) {
1618 		if (server_match_spec_complete(connection_info) == 1)
1619 			parse_server_match_config(&options, connection_info);
1620 		dump_config(&options);
1621 	}
1622 
1623 	/* Configuration looks good, so exit if in test mode. */
1624 	if (test_flag)
1625 		exit(0);
1626 
1627 	if (rexec_flag) {
1628 		rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1629 		for (i = 0; i < rexec_argc; i++) {
1630 			debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1631 			rexec_argv[i] = saved_argv[i];
1632 		}
1633 		rexec_argv[rexec_argc] = "-R";
1634 		rexec_argv[rexec_argc + 1] = NULL;
1635 	}
1636 
1637 	/* Ensure that umask disallows at least group and world write */
1638 	new_umask = umask(0077) | 0022;
1639 	(void) umask(new_umask);
1640 
1641 	/* Initialize the log (it is reinitialized below in case we forked). */
1642 	if (debug_flag && (!inetd_flag || rexeced_flag))
1643 		log_stderr = 1;
1644 	log_init(__progname, options.log_level, options.log_facility, log_stderr);
1645 
1646 	/*
1647 	 * If not in debugging mode, and not started from inetd, disconnect
1648 	 * from the controlling terminal, and fork.  The original process
1649 	 * exits.
1650 	 */
1651 	if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1652 		int fd;
1653 
1654 		if (daemon(0, 0) < 0)
1655 			fatal("daemon() failed: %.200s", strerror(errno));
1656 
1657 		/* Disconnect from the controlling tty. */
1658 		fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1659 		if (fd >= 0) {
1660 			(void) ioctl(fd, TIOCNOTTY, NULL);
1661 			close(fd);
1662 		}
1663 	}
1664 	/* Reinitialize the log (because of the fork above). */
1665 	log_init(__progname, options.log_level, options.log_facility, log_stderr);
1666 
1667 	/* Initialize the random number generator. */
1668 	arc4random_stir();
1669 
1670 	/* Chdir to the root directory so that the current disk can be
1671 	   unmounted if desired. */
1672 	chdir("/");
1673 
1674 	/* ignore SIGPIPE */
1675 	signal(SIGPIPE, SIG_IGN);
1676 
1677 	/* Get a connection, either from inetd or a listening TCP socket */
1678 	if (inetd_flag) {
1679 		server_accept_inetd(&sock_in, &sock_out);
1680 	} else {
1681 		server_listen();
1682 
1683 		if (options.protocol & SSH_PROTO_1)
1684 			generate_ephemeral_server_key();
1685 
1686 		signal(SIGHUP, sighup_handler);
1687 		signal(SIGCHLD, main_sigchld_handler);
1688 		signal(SIGTERM, sigterm_handler);
1689 		signal(SIGQUIT, sigterm_handler);
1690 
1691 		/*
1692 		 * Write out the pid file after the sigterm handler
1693 		 * is setup and the listen sockets are bound
1694 		 */
1695 		if (!debug_flag) {
1696 			FILE *f = fopen(options.pid_file, "w");
1697 
1698 			if (f == NULL) {
1699 				error("Couldn't create pid file \"%s\": %s",
1700 				    options.pid_file, strerror(errno));
1701 			} else {
1702 				fprintf(f, "%ld\n", (long) getpid());
1703 				fclose(f);
1704 			}
1705 		}
1706 
1707 		/* Accept a connection and return in a forked child */
1708 		server_accept_loop(&sock_in, &sock_out,
1709 		    &newsock, config_s);
1710 	}
1711 
1712 	/* This is the child processing a new connection. */
1713 	setproctitle("%s", "[accepted]");
1714 
1715 	/*
1716 	 * Create a new session and process group since the 4.4BSD
1717 	 * setlogin() affects the entire process group.  We don't
1718 	 * want the child to be able to affect the parent.
1719 	 */
1720 	if (!debug_flag && !inetd_flag && setsid() < 0)
1721 		error("setsid: %.100s", strerror(errno));
1722 
1723 	if (rexec_flag) {
1724 		int fd;
1725 
1726 		debug("rexec start in %d out %d newsock %d pipe %d sock %d",
1727 		    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1728 		dup2(newsock, STDIN_FILENO);
1729 		dup2(STDIN_FILENO, STDOUT_FILENO);
1730 		if (startup_pipe == -1)
1731 			close(REEXEC_STARTUP_PIPE_FD);
1732 		else
1733 			dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
1734 
1735 		dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1736 		close(config_s[1]);
1737 		if (startup_pipe != -1)
1738 			close(startup_pipe);
1739 
1740 		execv(rexec_argv[0], rexec_argv);
1741 
1742 		/* Reexec has failed, fall back and continue */
1743 		error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1744 		recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1745 		log_init(__progname, options.log_level,
1746 		    options.log_facility, log_stderr);
1747 
1748 		/* Clean up fds */
1749 		startup_pipe = REEXEC_STARTUP_PIPE_FD;
1750 		close(config_s[1]);
1751 		close(REEXEC_CONFIG_PASS_FD);
1752 		newsock = sock_out = sock_in = dup(STDIN_FILENO);
1753 		if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1754 			dup2(fd, STDIN_FILENO);
1755 			dup2(fd, STDOUT_FILENO);
1756 			if (fd > STDERR_FILENO)
1757 				close(fd);
1758 		}
1759 		debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
1760 		    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1761 	}
1762 
1763 	/* Executed child processes don't need these. */
1764 	fcntl(sock_out, F_SETFD, FD_CLOEXEC);
1765 	fcntl(sock_in, F_SETFD, FD_CLOEXEC);
1766 
1767 	/*
1768 	 * Disable the key regeneration alarm.  We will not regenerate the
1769 	 * key since we are no longer in a position to give it to anyone. We
1770 	 * will not restart on SIGHUP since it no longer makes sense.
1771 	 */
1772 	alarm(0);
1773 	signal(SIGALRM, SIG_DFL);
1774 	signal(SIGHUP, SIG_DFL);
1775 	signal(SIGTERM, SIG_DFL);
1776 	signal(SIGQUIT, SIG_DFL);
1777 	signal(SIGCHLD, SIG_DFL);
1778 
1779 	/*
1780 	 * Register our connection.  This turns encryption off because we do
1781 	 * not have a key.
1782 	 */
1783 	packet_set_connection(sock_in, sock_out);
1784 	packet_set_server();
1785 
1786 	/* Set SO_KEEPALIVE if requested. */
1787 	if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
1788 	    setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
1789 		error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1790 
1791 	if ((remote_port = get_remote_port()) < 0) {
1792 		debug("get_remote_port failed");
1793 		cleanup_exit(255);
1794 	}
1795 
1796 	/*
1797 	 * We use get_canonical_hostname with usedns = 0 instead of
1798 	 * get_remote_ipaddr here so IP options will be checked.
1799 	 */
1800 	(void) get_canonical_hostname(0);
1801 	/*
1802 	 * The rest of the code depends on the fact that
1803 	 * get_remote_ipaddr() caches the remote ip, even if
1804 	 * the socket goes away.
1805 	 */
1806 	remote_ip = get_remote_ipaddr();
1807 
1808 #ifdef LIBWRAP
1809 	/* Check whether logins are denied from this host. */
1810 	if (packet_connection_is_on_socket()) {
1811 		struct request_info req;
1812 
1813 		request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1814 		fromhost(&req);
1815 
1816 		if (!hosts_access(&req)) {
1817 			debug("Connection refused by tcp wrapper");
1818 			refuse(&req);
1819 			/* NOTREACHED */
1820 			fatal("libwrap refuse returns");
1821 		}
1822 	}
1823 #endif /* LIBWRAP */
1824 
1825 	/* Log the connection. */
1826 	verbose("Connection from %.500s port %d", remote_ip, remote_port);
1827 
1828 	/*
1829 	 * We don't want to listen forever unless the other side
1830 	 * successfully authenticates itself.  So we set up an alarm which is
1831 	 * cleared after successful authentication.  A limit of zero
1832 	 * indicates no limit. Note that we don't set the alarm in debugging
1833 	 * mode; it is just annoying to have the server exit just when you
1834 	 * are about to discover the bug.
1835 	 */
1836 	signal(SIGALRM, grace_alarm_handler);
1837 	if (!debug_flag)
1838 		alarm(options.login_grace_time);
1839 
1840 	sshd_exchange_identification(sock_in, sock_out);
1841 
1842 	/* In inetd mode, generate ephemeral key only for proto 1 connections */
1843 	if (!compat20 && inetd_flag && sensitive_data.server_key == NULL)
1844 		generate_ephemeral_server_key();
1845 
1846 	packet_set_nonblocking();
1847 
1848 	/* allocate authentication context */
1849 	authctxt = xcalloc(1, sizeof(*authctxt));
1850 
1851 	/* XXX global for cleanup, access from other modules */
1852 	the_authctxt = authctxt;
1853 
1854 	/* prepare buffer to collect messages to display to user after login */
1855 	buffer_init(&loginmsg);
1856 	auth_debug_reset();
1857 
1858 	if (use_privsep)
1859 		if (privsep_preauth(authctxt) == 1)
1860 			goto authenticated;
1861 
1862 	/* perform the key exchange */
1863 	/* authenticate user and start session */
1864 	if (compat20) {
1865 		do_ssh2_kex();
1866 		do_authentication2(authctxt);
1867 	} else {
1868 		do_ssh1_kex();
1869 		do_authentication(authctxt);
1870 	}
1871 	/*
1872 	 * If we use privilege separation, the unprivileged child transfers
1873 	 * the current keystate and exits
1874 	 */
1875 	if (use_privsep) {
1876 		mm_send_keystate(pmonitor);
1877 		exit(0);
1878 	}
1879 
1880  authenticated:
1881 	/*
1882 	 * Cancel the alarm we set to limit the time taken for
1883 	 * authentication.
1884 	 */
1885 	alarm(0);
1886 	signal(SIGALRM, SIG_DFL);
1887 	authctxt->authenticated = 1;
1888 	if (startup_pipe != -1) {
1889 		close(startup_pipe);
1890 		startup_pipe = -1;
1891 	}
1892 
1893 	/*
1894 	 * In privilege separation, we fork another child and prepare
1895 	 * file descriptor passing.
1896 	 */
1897 	if (use_privsep) {
1898 		privsep_postauth(authctxt);
1899 		/* the monitor process [priv] will not return */
1900 		if (!compat20)
1901 			destroy_sensitive_data();
1902 	}
1903 
1904 	packet_set_timeout(options.client_alive_interval,
1905 	    options.client_alive_count_max);
1906 
1907 	/* Start session. */
1908 	do_authenticated(authctxt);
1909 
1910 	/* The connection has been terminated. */
1911 	packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
1912 	packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
1913 	verbose("Transferred: sent %llu, received %llu bytes",
1914 	    (unsigned long long)obytes, (unsigned long long)ibytes);
1915 
1916 	verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
1917 	packet_close();
1918 
1919 	if (use_privsep)
1920 		mm_terminate();
1921 
1922 	exit(0);
1923 }
1924 
1925 /*
1926  * Decrypt session_key_int using our private server key and private host key
1927  * (key with larger modulus first).
1928  */
1929 int
1930 ssh1_session_key(BIGNUM *session_key_int)
1931 {
1932 	int rsafail = 0;
1933 
1934 	if (BN_cmp(sensitive_data.server_key->rsa->n,
1935 	    sensitive_data.ssh1_host_key->rsa->n) > 0) {
1936 		/* Server key has bigger modulus. */
1937 		if (BN_num_bits(sensitive_data.server_key->rsa->n) <
1938 		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1939 		    SSH_KEY_BITS_RESERVED) {
1940 			fatal("do_connection: %s: "
1941 			    "server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1942 			    get_remote_ipaddr(),
1943 			    BN_num_bits(sensitive_data.server_key->rsa->n),
1944 			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1945 			    SSH_KEY_BITS_RESERVED);
1946 		}
1947 		if (rsa_private_decrypt(session_key_int, session_key_int,
1948 		    sensitive_data.server_key->rsa) <= 0)
1949 			rsafail++;
1950 		if (rsa_private_decrypt(session_key_int, session_key_int,
1951 		    sensitive_data.ssh1_host_key->rsa) <= 0)
1952 			rsafail++;
1953 	} else {
1954 		/* Host key has bigger modulus (or they are equal). */
1955 		if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
1956 		    BN_num_bits(sensitive_data.server_key->rsa->n) +
1957 		    SSH_KEY_BITS_RESERVED) {
1958 			fatal("do_connection: %s: "
1959 			    "host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
1960 			    get_remote_ipaddr(),
1961 			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1962 			    BN_num_bits(sensitive_data.server_key->rsa->n),
1963 			    SSH_KEY_BITS_RESERVED);
1964 		}
1965 		if (rsa_private_decrypt(session_key_int, session_key_int,
1966 		    sensitive_data.ssh1_host_key->rsa) < 0)
1967 			rsafail++;
1968 		if (rsa_private_decrypt(session_key_int, session_key_int,
1969 		    sensitive_data.server_key->rsa) < 0)
1970 			rsafail++;
1971 	}
1972 	return (rsafail);
1973 }
1974 /*
1975  * SSH1 key exchange
1976  */
1977 static void
1978 do_ssh1_kex(void)
1979 {
1980 	int i, len;
1981 	int rsafail = 0;
1982 	BIGNUM *session_key_int;
1983 	u_char session_key[SSH_SESSION_KEY_LENGTH];
1984 	u_char cookie[8];
1985 	u_int cipher_type, auth_mask, protocol_flags;
1986 
1987 	/*
1988 	 * Generate check bytes that the client must send back in the user
1989 	 * packet in order for it to be accepted; this is used to defy ip
1990 	 * spoofing attacks.  Note that this only works against somebody
1991 	 * doing IP spoofing from a remote machine; any machine on the local
1992 	 * network can still see outgoing packets and catch the random
1993 	 * cookie.  This only affects rhosts authentication, and this is one
1994 	 * of the reasons why it is inherently insecure.
1995 	 */
1996 	arc4random_buf(cookie, sizeof(cookie));
1997 
1998 	/*
1999 	 * Send our public key.  We include in the packet 64 bits of random
2000 	 * data that must be matched in the reply in order to prevent IP
2001 	 * spoofing.
2002 	 */
2003 	packet_start(SSH_SMSG_PUBLIC_KEY);
2004 	for (i = 0; i < 8; i++)
2005 		packet_put_char(cookie[i]);
2006 
2007 	/* Store our public server RSA key. */
2008 	packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
2009 	packet_put_bignum(sensitive_data.server_key->rsa->e);
2010 	packet_put_bignum(sensitive_data.server_key->rsa->n);
2011 
2012 	/* Store our public host RSA key. */
2013 	packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2014 	packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
2015 	packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
2016 
2017 	/* Put protocol flags. */
2018 	packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
2019 
2020 	/* Declare which ciphers we support. */
2021 	packet_put_int(cipher_mask_ssh1(0));
2022 
2023 	/* Declare supported authentication types. */
2024 	auth_mask = 0;
2025 	if (options.rhosts_rsa_authentication)
2026 		auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
2027 	if (options.rsa_authentication)
2028 		auth_mask |= 1 << SSH_AUTH_RSA;
2029 	if (options.challenge_response_authentication == 1)
2030 		auth_mask |= 1 << SSH_AUTH_TIS;
2031 	if (options.password_authentication)
2032 		auth_mask |= 1 << SSH_AUTH_PASSWORD;
2033 	packet_put_int(auth_mask);
2034 
2035 	/* Send the packet and wait for it to be sent. */
2036 	packet_send();
2037 	packet_write_wait();
2038 
2039 	debug("Sent %d bit server key and %d bit host key.",
2040 	    BN_num_bits(sensitive_data.server_key->rsa->n),
2041 	    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2042 
2043 	/* Read clients reply (cipher type and session key). */
2044 	packet_read_expect(SSH_CMSG_SESSION_KEY);
2045 
2046 	/* Get cipher type and check whether we accept this. */
2047 	cipher_type = packet_get_char();
2048 
2049 	if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
2050 		packet_disconnect("Warning: client selects unsupported cipher.");
2051 
2052 	/* Get check bytes from the packet.  These must match those we
2053 	   sent earlier with the public key packet. */
2054 	for (i = 0; i < 8; i++)
2055 		if (cookie[i] != packet_get_char())
2056 			packet_disconnect("IP Spoofing check bytes do not match.");
2057 
2058 	debug("Encryption type: %.200s", cipher_name(cipher_type));
2059 
2060 	/* Get the encrypted integer. */
2061 	if ((session_key_int = BN_new()) == NULL)
2062 		fatal("do_ssh1_kex: BN_new failed");
2063 	packet_get_bignum(session_key_int);
2064 
2065 	protocol_flags = packet_get_int();
2066 	packet_set_protocol_flags(protocol_flags);
2067 	packet_check_eom();
2068 
2069 	/* Decrypt session_key_int using host/server keys */
2070 	rsafail = PRIVSEP(ssh1_session_key(session_key_int));
2071 
2072 	/*
2073 	 * Extract session key from the decrypted integer.  The key is in the
2074 	 * least significant 256 bits of the integer; the first byte of the
2075 	 * key is in the highest bits.
2076 	 */
2077 	if (!rsafail) {
2078 		(void) BN_mask_bits(session_key_int, sizeof(session_key) * 8);
2079 		len = BN_num_bytes(session_key_int);
2080 		if (len < 0 || (u_int)len > sizeof(session_key)) {
2081 			error("do_ssh1_kex: bad session key len from %s: "
2082 			    "session_key_int %d > sizeof(session_key) %lu",
2083 			    get_remote_ipaddr(), len, (u_long)sizeof(session_key));
2084 			rsafail++;
2085 		} else {
2086 			memset(session_key, 0, sizeof(session_key));
2087 			BN_bn2bin(session_key_int,
2088 			    session_key + sizeof(session_key) - len);
2089 
2090 			derive_ssh1_session_id(
2091 			    sensitive_data.ssh1_host_key->rsa->n,
2092 			    sensitive_data.server_key->rsa->n,
2093 			    cookie, session_id);
2094 			/*
2095 			 * Xor the first 16 bytes of the session key with the
2096 			 * session id.
2097 			 */
2098 			for (i = 0; i < 16; i++)
2099 				session_key[i] ^= session_id[i];
2100 		}
2101 	}
2102 	if (rsafail) {
2103 		int bytes = BN_num_bytes(session_key_int);
2104 		u_char *buf = xmalloc(bytes);
2105 		MD5_CTX md;
2106 
2107 		logit("do_connection: generating a fake encryption key");
2108 		BN_bn2bin(session_key_int, buf);
2109 		MD5_Init(&md);
2110 		MD5_Update(&md, buf, bytes);
2111 		MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2112 		MD5_Final(session_key, &md);
2113 		MD5_Init(&md);
2114 		MD5_Update(&md, session_key, 16);
2115 		MD5_Update(&md, buf, bytes);
2116 		MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2117 		MD5_Final(session_key + 16, &md);
2118 		memset(buf, 0, bytes);
2119 		xfree(buf);
2120 		for (i = 0; i < 16; i++)
2121 			session_id[i] = session_key[i] ^ session_key[i + 16];
2122 	}
2123 	/* Destroy the private and public keys. No longer. */
2124 	destroy_sensitive_data();
2125 
2126 	if (use_privsep)
2127 		mm_ssh1_session_id(session_id);
2128 
2129 	/* Destroy the decrypted integer.  It is no longer needed. */
2130 	BN_clear_free(session_key_int);
2131 
2132 	/* Set the session key.  From this on all communications will be encrypted. */
2133 	packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
2134 
2135 	/* Destroy our copy of the session key.  It is no longer needed. */
2136 	memset(session_key, 0, sizeof(session_key));
2137 
2138 	debug("Received session key; encryption turned on.");
2139 
2140 	/* Send an acknowledgment packet.  Note that this packet is sent encrypted. */
2141 	packet_start(SSH_SMSG_SUCCESS);
2142 	packet_send();
2143 	packet_write_wait();
2144 }
2145 
2146 /*
2147  * SSH2 key exchange: diffie-hellman-group1-sha1
2148  */
2149 static void
2150 do_ssh2_kex(void)
2151 {
2152 	Kex *kex;
2153 
2154 	if (options.ciphers != NULL) {
2155 		myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2156 		myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
2157 	}
2158 	myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2159 	    compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
2160 	myproposal[PROPOSAL_ENC_ALGS_STOC] =
2161 	    compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
2162 
2163 	if (options.macs != NULL) {
2164 		myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2165 		myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2166 	}
2167 	if (options.compression == COMP_NONE) {
2168 		myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2169 		myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2170 	} else if (options.compression == COMP_DELAYED) {
2171 		myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2172 		myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com";
2173 	}
2174 	if (options.kex_algorithms != NULL)
2175 		myproposal[PROPOSAL_KEX_ALGS] = options.kex_algorithms;
2176 
2177 	myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
2178 
2179 	/* start key exchange */
2180 	kex = kex_setup(myproposal);
2181 	kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2182 	kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
2183 	kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2184 	kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2185 	kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
2186 	kex->server = 1;
2187 	kex->client_version_string=client_version_string;
2188 	kex->server_version_string=server_version_string;
2189 	kex->load_host_public_key=&get_hostkey_public_by_type;
2190 	kex->load_host_private_key=&get_hostkey_private_by_type;
2191 	kex->host_key_index=&get_hostkey_index;
2192 
2193 	xxx_kex = kex;
2194 
2195 	dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
2196 
2197 	session_id2 = kex->session_id;
2198 	session_id2_len = kex->session_id_len;
2199 
2200 #ifdef DEBUG_KEXDH
2201 	/* send 1st encrypted/maced/compressed message */
2202 	packet_start(SSH2_MSG_IGNORE);
2203 	packet_put_cstring("markus");
2204 	packet_send();
2205 	packet_write_wait();
2206 #endif
2207 	debug("KEX done");
2208 }
2209 
2210 /* server specific fatal cleanup */
2211 void
2212 cleanup_exit(int i)
2213 {
2214 	if (the_authctxt) {
2215 		do_cleanup(the_authctxt);
2216 		if (use_privsep && privsep_is_preauth && pmonitor->m_pid > 1) {
2217 			debug("Killing privsep child %d", pmonitor->m_pid);
2218 			if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
2219 			    errno != ESRCH)
2220 				error("%s: kill(%d): %s", __func__,
2221 				    pmonitor->m_pid, strerror(errno));
2222 		}
2223 	}
2224 	_exit(i);
2225 }
2226