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