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