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