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