xref: /openbsd/usr.bin/ssh/sshd.c (revision 84a23681)
1 /* $OpenBSD: sshd.c,v 1.614 2024/12/07 10:12:19 djm Exp $ */
2 /*
3  * Copyright (c) 2000, 2001, 2002 Markus Friedl.  All rights reserved.
4  * Copyright (c) 2002 Niels Provos.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include <sys/types.h>
28 #include <sys/ioctl.h>
29 #include <sys/wait.h>
30 #include <sys/tree.h>
31 #include <sys/stat.h>
32 #include <sys/socket.h>
33 #include <sys/time.h>
34 #include <sys/queue.h>
35 
36 #include <errno.h>
37 #include <fcntl.h>
38 #include <netdb.h>
39 #include <paths.h>
40 #include <poll.h>
41 #include <pwd.h>
42 #include <signal.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <stdarg.h>
47 #include <unistd.h>
48 #include <limits.h>
49 
50 #ifdef WITH_OPENSSL
51 #include <openssl/bn.h>
52 #include <openssl/evp.h>
53 #endif
54 
55 #include "xmalloc.h"
56 #include "ssh.h"
57 #include "sshpty.h"
58 #include "log.h"
59 #include "sshbuf.h"
60 #include "misc.h"
61 #include "servconf.h"
62 #include "compat.h"
63 #include "digest.h"
64 #include "sshkey.h"
65 #include "authfile.h"
66 #include "pathnames.h"
67 #include "canohost.h"
68 #include "hostfile.h"
69 #include "auth.h"
70 #include "authfd.h"
71 #include "msg.h"
72 #include "version.h"
73 #include "ssherr.h"
74 #include "sk-api.h"
75 #include "addr.h"
76 #include "srclimit.h"
77 
78 /* Re-exec fds */
79 #define REEXEC_DEVCRYPTO_RESERVED_FD	(STDERR_FILENO + 1)
80 #define REEXEC_STARTUP_PIPE_FD		(STDERR_FILENO + 2)
81 #define REEXEC_CONFIG_PASS_FD		(STDERR_FILENO + 3)
82 #define REEXEC_MIN_FREE_FD		(STDERR_FILENO + 4)
83 
84 extern char *__progname;
85 
86 /* Server configuration options. */
87 ServerOptions options;
88 
89 /*
90  * Debug mode flag.  This can be set on the command line.  If debug
91  * mode is enabled, extra debugging output will be sent to the system
92  * log, the daemon will not go to background, and will exit after processing
93  * the first connection.
94  */
95 int debug_flag = 0;
96 
97 /* Saved arguments to main(). */
98 static char **saved_argv;
99 
100 /*
101  * The sockets that the server is listening; this is used in the SIGHUP
102  * signal handler.
103  */
104 #define	MAX_LISTEN_SOCKS	16
105 static int listen_socks[MAX_LISTEN_SOCKS];
106 static int num_listen_socks = 0;
107 
108 /*
109  * Any really sensitive data in the application is contained in this
110  * structure. The idea is that this structure could be locked into memory so
111  * that the pages do not get written into swap.  However, there are some
112  * problems. The private key contains BIGNUMs, and we do not (in principle)
113  * have access to the internals of them, and locking just the structure is
114  * not very useful.  Currently, memory locking is not implemented.
115  */
116 struct {
117 	struct sshkey	**host_keys;		/* all private host keys */
118 	struct sshkey	**host_pubkeys;		/* all public host keys */
119 	struct sshkey	**host_certificates;	/* all public host certificates */
120 	int		have_ssh2_key;
121 } sensitive_data;
122 
123 /* This is set to true when a signal is received. */
124 static volatile sig_atomic_t received_siginfo = 0;
125 static volatile sig_atomic_t received_sigchld = 0;
126 static volatile sig_atomic_t received_sighup = 0;
127 static volatile sig_atomic_t received_sigterm = 0;
128 
129 /* record remote hostname or ip */
130 u_int utmp_len = HOST_NAME_MAX+1;
131 
132 /*
133  * The early_child/children array below is used for tracking children of the
134  * listening sshd process early in their lifespans, before they have
135  * completed authentication. This tracking is needed for four things:
136  *
137  * 1) Implementing the MaxStartups limit of concurrent unauthenticated
138  *    connections.
139  * 2) Avoiding a race condition for SIGHUP processing, where child processes
140  *    may have listen_socks open that could collide with main listener process
141  *    after it restarts.
142  * 3) Ensuring that rexec'd sshd processes have received their initial state
143  *    from the parent listen process before handling SIGHUP.
144  * 4) Tracking and logging unsuccessful exits from the preauth sshd monitor,
145  *    including and especially those for LoginGraceTime timeouts.
146  *
147  * Child processes signal that they have completed closure of the listen_socks
148  * and (if applicable) received their rexec state by sending a char over their
149  * sock.
150  *
151  * Child processes signal that authentication has completed by sending a
152  * second char over the socket before closing it, otherwise the listener will
153  * continue tracking the child (and using up a MaxStartups slot) until the
154  * preauth subprocess exits, whereupon the listener will log its exit status.
155  * preauth processes will exit with a status of EXIT_LOGIN_GRACE to indicate
156  * they did not authenticate before the LoginGraceTime alarm fired.
157  */
158 struct early_child {
159 	int pipefd;
160 	int early;		/* Indicates child closed listener */
161 	char *id;		/* human readable connection identifier */
162 	pid_t pid;
163 	struct xaddr addr;
164 	int have_addr;
165 	int status, have_status;
166 };
167 static struct early_child *children;
168 static int children_active;
169 static int startup_pipe = -1;		/* in child */
170 
171 /* sshd_config buffer */
172 struct sshbuf *cfg;
173 
174 /* Included files from the configuration file */
175 struct include_list includes = TAILQ_HEAD_INITIALIZER(includes);
176 
177 /* message to be displayed after login */
178 struct sshbuf *loginmsg;
179 
180 static char *listener_proctitle;
181 
182 /*
183  * Close all listening sockets
184  */
185 static void
close_listen_socks(void)186 close_listen_socks(void)
187 {
188 	int i;
189 
190 	for (i = 0; i < num_listen_socks; i++)
191 		close(listen_socks[i]);
192 	num_listen_socks = 0;
193 }
194 
195 /* Allocate and initialise the children array */
196 static void
child_alloc(void)197 child_alloc(void)
198 {
199 	int i;
200 
201 	children = xcalloc(options.max_startups, sizeof(*children));
202 	for (i = 0; i < options.max_startups; i++) {
203 		children[i].pipefd = -1;
204 		children[i].pid = -1;
205 	}
206 }
207 
208 /* Register a new connection in the children array; child pid comes later */
209 static struct early_child *
child_register(int pipefd,int sockfd)210 child_register(int pipefd, int sockfd)
211 {
212 	int i, lport, rport;
213 	char *laddr = NULL, *raddr = NULL;
214 	struct early_child *child = NULL;
215 	struct sockaddr_storage addr;
216 	socklen_t addrlen = sizeof(addr);
217 	struct sockaddr *sa = (struct sockaddr *)&addr;
218 
219 	for (i = 0; i < options.max_startups; i++) {
220 		if (children[i].pipefd != -1 || children[i].pid > 0)
221 			continue;
222 		child = &(children[i]);
223 		break;
224 	}
225 	if (child == NULL) {
226 		fatal_f("error: accepted connection when all %d child "
227 		    " slots full", options.max_startups);
228 	}
229 	child->pipefd = pipefd;
230 	child->early = 1;
231 	/* record peer address, if available */
232 	if (getpeername(sockfd, sa, &addrlen) == 0 &&
233 	   addr_sa_to_xaddr(sa, addrlen, &child->addr) == 0)
234 		child->have_addr = 1;
235 	/* format peer address string for logs */
236 	if ((lport = get_local_port(sockfd)) == 0 ||
237 	    (rport = get_peer_port(sockfd)) == 0) {
238 		/* Not a TCP socket */
239 		raddr = get_peer_ipaddr(sockfd);
240 		xasprintf(&child->id, "connection from %s", raddr);
241 	} else {
242 		laddr = get_local_ipaddr(sockfd);
243 		raddr = get_peer_ipaddr(sockfd);
244 		xasprintf(&child->id, "connection from %s to %s", raddr, laddr);
245 	}
246 	free(laddr);
247 	free(raddr);
248 	if (++children_active > options.max_startups)
249 		fatal_f("internal error: more children than max_startups");
250 
251 	return child;
252 }
253 
254 /*
255  * Finally free a child entry. Don't call this directly.
256  */
257 static void
child_finish(struct early_child * child)258 child_finish(struct early_child *child)
259 {
260 	if (children_active == 0)
261 		fatal_f("internal error: children_active underflow");
262 	if (child->pipefd != -1)
263 		close(child->pipefd);
264 	free(child->id);
265 	memset(child, '\0', sizeof(*child));
266 	child->pipefd = -1;
267 	child->pid = -1;
268 	children_active--;
269 }
270 
271 /*
272  * Close a child's pipe. This will not stop tracking the child immediately
273  * (it will still be tracked for waitpid()) unless force_final is set, or
274  * child has already exited.
275  */
276 static void
child_close(struct early_child * child,int force_final,int quiet)277 child_close(struct early_child *child, int force_final, int quiet)
278 {
279 	if (!quiet)
280 		debug_f("enter%s", force_final ? " (forcing)" : "");
281 	if (child->pipefd != -1) {
282 		close(child->pipefd);
283 		child->pipefd = -1;
284 	}
285 	if (child->pid == -1 || force_final)
286 		child_finish(child);
287 }
288 
289 /* Record a child exit. Safe to call from signal handlers */
290 static void
child_exit(pid_t pid,int status)291 child_exit(pid_t pid, int status)
292 {
293 	int i;
294 
295 	if (children == NULL || pid <= 0)
296 		return;
297 	for (i = 0; i < options.max_startups; i++) {
298 		if (children[i].pid == pid) {
299 			children[i].have_status = 1;
300 			children[i].status = status;
301 			break;
302 		}
303 	}
304 }
305 
306 /*
307  * Reap a child entry that has exited, as previously flagged
308  * using child_exit().
309  * Handles logging of exit condition and will finalise the child if its pipe
310  * had already been closed.
311  */
312 static void
child_reap(struct early_child * child)313 child_reap(struct early_child *child)
314 {
315 	LogLevel level = SYSLOG_LEVEL_DEBUG1;
316 	int was_crash, penalty_type = SRCLIMIT_PENALTY_NONE;
317 
318 	/* Log exit information */
319 	if (WIFSIGNALED(child->status)) {
320 		/*
321 		 * Increase logging for signals potentially associated
322 		 * with serious conditions.
323 		 */
324 		if ((was_crash = signal_is_crash(WTERMSIG(child->status))))
325 			level = SYSLOG_LEVEL_ERROR;
326 		do_log2(level, "session process %ld for %s killed by "
327 		    "signal %d%s", (long)child->pid, child->id,
328 		    WTERMSIG(child->status), child->early ? " (early)" : "");
329 		if (was_crash)
330 			penalty_type = SRCLIMIT_PENALTY_CRASH;
331 	} else if (!WIFEXITED(child->status)) {
332 		penalty_type = SRCLIMIT_PENALTY_CRASH;
333 		error("session process %ld for %s terminated abnormally, "
334 		    "status=0x%x%s", (long)child->pid, child->id, child->status,
335 		    child->early ? " (early)" : "");
336 	} else {
337 		/* Normal exit. We care about the status */
338 		switch (WEXITSTATUS(child->status)) {
339 		case 0:
340 			debug3_f("preauth child %ld for %s completed "
341 			    "normally %s", (long)child->pid, child->id,
342 			    child->early ? " (early)" : "");
343 			break;
344 		case EXIT_LOGIN_GRACE:
345 			penalty_type = SRCLIMIT_PENALTY_GRACE_EXCEEDED;
346 			logit("Timeout before authentication for %s, "
347 			    "pid = %ld%s", child->id, (long)child->pid,
348 			    child->early ? " (early)" : "");
349 			break;
350 		case EXIT_CHILD_CRASH:
351 			penalty_type = SRCLIMIT_PENALTY_CRASH;
352 			logit("Session process %ld unpriv child crash for %s%s",
353 			    (long)child->pid, child->id,
354 			    child->early ? " (early)" : "");
355 			break;
356 		case EXIT_AUTH_ATTEMPTED:
357 			penalty_type = SRCLIMIT_PENALTY_AUTHFAIL;
358 			debug_f("preauth child %ld for %s exited "
359 			    "after unsuccessful auth attempt %s",
360 			    (long)child->pid, child->id,
361 			    child->early ? " (early)" : "");
362 			break;
363 		case EXIT_CONFIG_REFUSED:
364 			penalty_type = SRCLIMIT_PENALTY_REFUSECONNECTION;
365 			debug_f("preauth child %ld for %s prohibited by"
366 			    "RefuseConnection %s",
367 			    (long)child->pid, child->id,
368 			    child->early ? " (early)" : "");
369 			break;
370 		default:
371 			penalty_type = SRCLIMIT_PENALTY_NOAUTH;
372 			debug_f("preauth child %ld for %s exited "
373 			    "with status %d%s", (long)child->pid, child->id,
374 			    WEXITSTATUS(child->status),
375 			    child->early ? " (early)" : "");
376 			break;
377 		}
378 	}
379 
380 	if (child->have_addr)
381 		srclimit_penalise(&child->addr, penalty_type);
382 
383 	child->pid = -1;
384 	child->have_status = 0;
385 	if (child->pipefd == -1)
386 		child_finish(child);
387 }
388 
389 /* Reap all children that have exited; called after SIGCHLD */
390 static void
child_reap_all_exited(void)391 child_reap_all_exited(void)
392 {
393 	int i;
394 	pid_t pid;
395 	int status;
396 
397 	if (children == NULL)
398 		return;
399 
400 	for (;;) {
401 		if ((pid = waitpid(-1, &status, WNOHANG)) == 0)
402 			break;
403 		else if (pid == -1) {
404 			if (errno == EINTR || errno == EAGAIN)
405 				continue;
406 			if (errno != ECHILD)
407 				error_f("waitpid: %s", strerror(errno));
408 			break;
409 		}
410 		child_exit(pid, status);
411 	}
412 
413 	for (i = 0; i < options.max_startups; i++) {
414 		if (!children[i].have_status)
415 			continue;
416 		child_reap(&(children[i]));
417 	}
418 }
419 
420 static void
close_startup_pipes(void)421 close_startup_pipes(void)
422 {
423 	int i;
424 
425 	if (children == NULL)
426 		return;
427 	for (i = 0; i < options.max_startups; i++) {
428 		if (children[i].pipefd != -1)
429 			child_close(&(children[i]), 1, 1);
430 	}
431 }
432 
433 /* Called after SIGINFO */
434 static void
show_info(void)435 show_info(void)
436 {
437 	int i;
438 
439 	/* XXX print listening sockets here too */
440 	if (children == NULL)
441 		return;
442 	logit("%d active startups", children_active);
443 	for (i = 0; i < options.max_startups; i++) {
444 		if (children[i].pipefd == -1 && children[i].pid <= 0)
445 			continue;
446 		logit("child %d: fd=%d pid=%ld %s%s", i, children[i].pipefd,
447 		    (long)children[i].pid, children[i].id,
448 		    children[i].early ? " (early)" : "");
449 	}
450 	srclimit_penalty_info();
451 }
452 
453 /*
454  * Signal handler for SIGHUP.  Sshd execs itself when it receives SIGHUP;
455  * the effect is to reread the configuration file (and to regenerate
456  * the server key).
457  */
458 
459 static void
sighup_handler(int sig)460 sighup_handler(int sig)
461 {
462 	received_sighup = 1;
463 }
464 
465 /*
466  * Called from the main program after receiving SIGHUP.
467  * Restarts the server.
468  */
469 static void
sighup_restart(void)470 sighup_restart(void)
471 {
472 	logit("Received SIGHUP; restarting.");
473 	if (options.pid_file != NULL)
474 		unlink(options.pid_file);
475 	close_listen_socks();
476 	close_startup_pipes();
477 	ssh_signal(SIGHUP, SIG_IGN); /* will be restored after exec */
478 	execv(saved_argv[0], saved_argv);
479 	logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
480 	    strerror(errno));
481 	exit(1);
482 }
483 
484 /*
485  * Generic signal handler for terminating signals in the master daemon.
486  */
487 static void
sigterm_handler(int sig)488 sigterm_handler(int sig)
489 {
490 	received_sigterm = sig;
491 }
492 
493 static void
siginfo_handler(int sig)494 siginfo_handler(int sig)
495 {
496 	received_siginfo = 1;
497 }
498 
499 static void
main_sigchld_handler(int sig)500 main_sigchld_handler(int sig)
501 {
502 	received_sigchld = 1;
503 }
504 
505 /*
506  * returns 1 if connection should be dropped, 0 otherwise.
507  * dropping starts at connection #max_startups_begin with a probability
508  * of (max_startups_rate/100). the probability increases linearly until
509  * all connections are dropped for startups > max_startups
510  */
511 static int
should_drop_connection(int startups)512 should_drop_connection(int startups)
513 {
514 	int p, r;
515 
516 	if (startups < options.max_startups_begin)
517 		return 0;
518 	if (startups >= options.max_startups)
519 		return 1;
520 	if (options.max_startups_rate == 100)
521 		return 1;
522 
523 	p  = 100 - options.max_startups_rate;
524 	p *= startups - options.max_startups_begin;
525 	p /= options.max_startups - options.max_startups_begin;
526 	p += options.max_startups_rate;
527 	r = arc4random_uniform(100);
528 
529 	debug_f("p %d, r %d", p, r);
530 	return (r < p) ? 1 : 0;
531 }
532 
533 /*
534  * Check whether connection should be accepted by MaxStartups or for penalty.
535  * Returns 0 if the connection is accepted. If the connection is refused,
536  * returns 1 and attempts to send notification to client.
537  * Logs when the MaxStartups condition is entered or exited, and periodically
538  * while in that state.
539  */
540 static int
drop_connection(int sock,int startups,int notify_pipe)541 drop_connection(int sock, int startups, int notify_pipe)
542 {
543 	static struct log_ratelimit_ctx ratelimit_maxstartups;
544 	static struct log_ratelimit_ctx ratelimit_penalty;
545 	static int init_done;
546 	char *laddr, *raddr;
547 	const char *reason = NULL, *subreason = NULL;
548 	const char msg[] = "Not allowed at this time\r\n";
549 	struct log_ratelimit_ctx *rl = NULL;
550 	int ratelimited;
551 	u_int ndropped;
552 
553 	if (!init_done) {
554 		init_done = 1;
555 		log_ratelimit_init(&ratelimit_maxstartups, 4, 60, 20, 5*60);
556 		log_ratelimit_init(&ratelimit_penalty, 8, 60, 30, 2*60);
557 	}
558 
559 	/* PerSourcePenalties */
560 	if (!srclimit_penalty_check_allow(sock, &subreason)) {
561 		reason = "PerSourcePenalties";
562 		rl = &ratelimit_penalty;
563 	} else {
564 		/* MaxStartups */
565 		if (!should_drop_connection(startups) &&
566 		    srclimit_check_allow(sock, notify_pipe) == 1)
567 			return 0;
568 		reason = "Maxstartups";
569 		rl = &ratelimit_maxstartups;
570 	}
571 
572 	laddr = get_local_ipaddr(sock);
573 	raddr = get_peer_ipaddr(sock);
574 	ratelimited = log_ratelimit(rl, time(NULL), NULL, &ndropped);
575 	do_log2(ratelimited ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
576 	    "drop connection #%d from [%s]:%d on [%s]:%d %s",
577 	    startups,
578 	    raddr, get_peer_port(sock),
579 	    laddr, get_local_port(sock),
580 	    subreason != NULL ? subreason : reason);
581 	free(laddr);
582 	free(raddr);
583 	if (ndropped != 0) {
584 		logit("%s logging rate-limited: additional %u connections "
585 		    "dropped", reason, ndropped);
586 	}
587 
588 	/* best-effort notification to client */
589 	(void)write(sock, msg, sizeof(msg) - 1);
590 	return 1;
591 }
592 
593 static void
usage(void)594 usage(void)
595 {
596 	fprintf(stderr, "%s, %s\n", SSH_VERSION, SSH_OPENSSL_VERSION);
597 	fprintf(stderr,
598 "usage: sshd [-46DdeGiqTtV] [-C connection_spec] [-c host_cert_file]\n"
599 "            [-E log_file] [-f config_file] [-g login_grace_time]\n"
600 "            [-h host_key_file] [-o option] [-p port] [-u len]\n"
601 	);
602 	exit(1);
603 }
604 
605 static struct sshbuf *
pack_hostkeys(void)606 pack_hostkeys(void)
607 {
608 	struct sshbuf *keybuf = NULL, *hostkeys = NULL;
609 	int r;
610 	u_int i;
611 
612 	if ((keybuf = sshbuf_new()) == NULL ||
613 	    (hostkeys = sshbuf_new()) == NULL)
614 		fatal_f("sshbuf_new failed");
615 
616 	/* pack hostkeys into a string. Empty key slots get empty strings */
617 	for (i = 0; i < options.num_host_key_files; i++) {
618 		/* private key */
619 		sshbuf_reset(keybuf);
620 		if (sensitive_data.host_keys[i] != NULL &&
621 		    (r = sshkey_private_serialize(sensitive_data.host_keys[i],
622 		    keybuf)) != 0)
623 			fatal_fr(r, "serialize hostkey private");
624 		if ((r = sshbuf_put_stringb(hostkeys, keybuf)) != 0)
625 			fatal_fr(r, "compose hostkey private");
626 		/* public key */
627 		if (sensitive_data.host_pubkeys[i] != NULL) {
628 			if ((r = sshkey_puts(sensitive_data.host_pubkeys[i],
629 			    hostkeys)) != 0)
630 				fatal_fr(r, "compose hostkey public");
631 		} else {
632 			if ((r = sshbuf_put_string(hostkeys, NULL, 0)) != 0)
633 				fatal_fr(r, "compose hostkey empty public");
634 		}
635 		/* cert */
636 		if (sensitive_data.host_certificates[i] != NULL) {
637 			if ((r = sshkey_puts(
638 			    sensitive_data.host_certificates[i],
639 			    hostkeys)) != 0)
640 				fatal_fr(r, "compose host cert");
641 		} else {
642 			if ((r = sshbuf_put_string(hostkeys, NULL, 0)) != 0)
643 				fatal_fr(r, "compose host cert empty");
644 		}
645 	}
646 
647 	sshbuf_free(keybuf);
648 	return hostkeys;
649 }
650 
651 static void
send_rexec_state(int fd,struct sshbuf * conf)652 send_rexec_state(int fd, struct sshbuf *conf)
653 {
654 	struct sshbuf *m = NULL, *inc = NULL, *hostkeys = NULL;
655 	struct include_item *item = NULL;
656 	int r, sz;
657 
658 	debug3_f("entering fd = %d config len %zu", fd,
659 	    sshbuf_len(conf));
660 
661 	if ((m = sshbuf_new()) == NULL ||
662 	    (inc = sshbuf_new()) == NULL)
663 		fatal_f("sshbuf_new failed");
664 
665 	/* pack includes into a string */
666 	TAILQ_FOREACH(item, &includes, entry) {
667 		if ((r = sshbuf_put_cstring(inc, item->selector)) != 0 ||
668 		    (r = sshbuf_put_cstring(inc, item->filename)) != 0 ||
669 		    (r = sshbuf_put_stringb(inc, item->contents)) != 0)
670 			fatal_fr(r, "compose includes");
671 	}
672 
673 	hostkeys = pack_hostkeys();
674 
675 	/*
676 	 * Protocol from reexec master to child:
677 	 *	string	configuration
678 	 *	uint64	timing_secret
679 	 *	string	host_keys[] {
680 	 *		string private_key
681 	 *		string public_key
682 	 *		string certificate
683 	 *	}
684 	 *	string	included_files[] {
685 	 *		string	selector
686 	 *		string	filename
687 	 *		string	contents
688 	 *	}
689 	 */
690 	if ((r = sshbuf_put_stringb(m, conf)) != 0 ||
691 	    (r = sshbuf_put_u64(m, options.timing_secret)) != 0 ||
692 	    (r = sshbuf_put_stringb(m, hostkeys)) != 0 ||
693 	    (r = sshbuf_put_stringb(m, inc)) != 0)
694 		fatal_fr(r, "compose config");
695 
696 	/* We need to fit the entire message inside the socket send buffer */
697 	sz = ROUNDUP(sshbuf_len(m) + 5, 16*1024);
698 	if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &sz, sizeof sz) == -1)
699 		fatal_f("setsockopt SO_SNDBUF: %s", strerror(errno));
700 
701 	if (ssh_msg_send(fd, 0, m) == -1)
702 		error_f("ssh_msg_send failed");
703 
704 	sshbuf_free(m);
705 	sshbuf_free(inc);
706 	sshbuf_free(hostkeys);
707 
708 	debug3_f("done");
709 }
710 
711 /*
712  * Listen for TCP connections
713  */
714 static void
listen_on_addrs(struct listenaddr * la)715 listen_on_addrs(struct listenaddr *la)
716 {
717 	int ret, listen_sock;
718 	struct addrinfo *ai;
719 	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
720 
721 	for (ai = la->addrs; ai; ai = ai->ai_next) {
722 		if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
723 			continue;
724 		if (num_listen_socks >= MAX_LISTEN_SOCKS)
725 			fatal("Too many listen sockets. "
726 			    "Enlarge MAX_LISTEN_SOCKS");
727 		if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
728 		    ntop, sizeof(ntop), strport, sizeof(strport),
729 		    NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
730 			error("getnameinfo failed: %.100s",
731 			    ssh_gai_strerror(ret));
732 			continue;
733 		}
734 		/* Create socket for listening. */
735 		listen_sock = socket(ai->ai_family, ai->ai_socktype,
736 		    ai->ai_protocol);
737 		if (listen_sock == -1) {
738 			/* kernel may not support ipv6 */
739 			verbose("socket: %.100s", strerror(errno));
740 			continue;
741 		}
742 		if (set_nonblock(listen_sock) == -1) {
743 			close(listen_sock);
744 			continue;
745 		}
746 		if (fcntl(listen_sock, F_SETFD, FD_CLOEXEC) == -1) {
747 			verbose("socket: CLOEXEC: %s", strerror(errno));
748 			close(listen_sock);
749 			continue;
750 		}
751 		/* Socket options */
752 		set_reuseaddr(listen_sock);
753 		if (la->rdomain != NULL &&
754 		    set_rdomain(listen_sock, la->rdomain) == -1) {
755 			close(listen_sock);
756 			continue;
757 		}
758 
759 		debug("Bind to port %s on %s.", strport, ntop);
760 
761 		/* Bind the socket to the desired port. */
762 		if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) == -1) {
763 			error("Bind to port %s on %s failed: %.200s.",
764 			    strport, ntop, strerror(errno));
765 			close(listen_sock);
766 			continue;
767 		}
768 		listen_socks[num_listen_socks] = listen_sock;
769 		num_listen_socks++;
770 
771 		/* Start listening on the port. */
772 		if (listen(listen_sock, SSH_LISTEN_BACKLOG) == -1)
773 			fatal("listen on [%s]:%s: %.100s",
774 			    ntop, strport, strerror(errno));
775 		logit("Server listening on %s port %s%s%s.",
776 		    ntop, strport,
777 		    la->rdomain == NULL ? "" : " rdomain ",
778 		    la->rdomain == NULL ? "" : la->rdomain);
779 	}
780 }
781 
782 static void
server_listen(void)783 server_listen(void)
784 {
785 	u_int i;
786 
787 	/* Initialise per-source limit tracking. */
788 	srclimit_init(options.max_startups,
789 	    options.per_source_max_startups,
790 	    options.per_source_masklen_ipv4,
791 	    options.per_source_masklen_ipv6,
792 	    &options.per_source_penalty,
793 	    options.per_source_penalty_exempt);
794 
795 	for (i = 0; i < options.num_listen_addrs; i++) {
796 		listen_on_addrs(&options.listen_addrs[i]);
797 		freeaddrinfo(options.listen_addrs[i].addrs);
798 		free(options.listen_addrs[i].rdomain);
799 		memset(&options.listen_addrs[i], 0,
800 		    sizeof(options.listen_addrs[i]));
801 	}
802 	free(options.listen_addrs);
803 	options.listen_addrs = NULL;
804 	options.num_listen_addrs = 0;
805 
806 	if (!num_listen_socks)
807 		fatal("Cannot bind any address.");
808 }
809 
810 /*
811  * The main TCP accept loop. Note that, for the non-debug case, returns
812  * from this function are in a forked subprocess.
813  */
814 static void
server_accept_loop(int * sock_in,int * sock_out,int * newsock,int * config_s,int log_stderr)815 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s,
816     int log_stderr)
817 {
818 	struct pollfd *pfd = NULL;
819 	int i, ret, npfd;
820 	int oactive = -1, listening = 0, lameduck = 0;
821 	int startup_p[2] = { -1 , -1 }, *startup_pollfd;
822 	char c = 0;
823 	struct sockaddr_storage from;
824 	struct early_child *child;
825 	socklen_t fromlen;
826 	sigset_t nsigset, osigset;
827 
828 	/* setup fd set for accept */
829 	/* pipes connected to unauthenticated child sshd processes */
830 	child_alloc();
831 	startup_pollfd = xcalloc(options.max_startups, sizeof(int));
832 
833 	/*
834 	 * Prepare signal mask that we use to block signals that might set
835 	 * received_sigterm/hup/chld/info, so that we are guaranteed
836 	 * to immediately wake up the ppoll if a signal is received after
837 	 * the flag is checked.
838 	 */
839 	sigemptyset(&nsigset);
840 	sigaddset(&nsigset, SIGHUP);
841 	sigaddset(&nsigset, SIGCHLD);
842 	sigaddset(&nsigset, SIGINFO);
843 	sigaddset(&nsigset, SIGTERM);
844 	sigaddset(&nsigset, SIGQUIT);
845 
846 	/* sized for worst-case */
847 	pfd = xcalloc(num_listen_socks + options.max_startups,
848 	    sizeof(struct pollfd));
849 
850 	/*
851 	 * Stay listening for connections until the system crashes or
852 	 * the daemon is killed with a signal.
853 	 */
854 	for (;;) {
855 		sigprocmask(SIG_BLOCK, &nsigset, &osigset);
856 		if (received_sigterm) {
857 			logit("Received signal %d; terminating.",
858 			    (int) received_sigterm);
859 			close_listen_socks();
860 			if (options.pid_file != NULL)
861 				unlink(options.pid_file);
862 			exit(received_sigterm == SIGTERM ? 0 : 255);
863 		}
864 		if (received_sigchld) {
865 			child_reap_all_exited();
866 			received_sigchld = 0;
867 		}
868 		if (received_siginfo) {
869 			show_info();
870 			received_siginfo = 0;
871 		}
872 		if (oactive != children_active) {
873 			setproctitle("%s [listener] %d of %d-%d startups",
874 			    listener_proctitle, children_active,
875 			    options.max_startups_begin, options.max_startups);
876 			oactive = children_active;
877 		}
878 		if (received_sighup) {
879 			if (!lameduck) {
880 				debug("Received SIGHUP; waiting for children");
881 				close_listen_socks();
882 				lameduck = 1;
883 			}
884 			if (listening <= 0) {
885 				sigprocmask(SIG_SETMASK, &osigset, NULL);
886 				sighup_restart();
887 			}
888 		}
889 
890 		for (i = 0; i < num_listen_socks; i++) {
891 			pfd[i].fd = listen_socks[i];
892 			pfd[i].events = POLLIN;
893 		}
894 		npfd = num_listen_socks;
895 		for (i = 0; i < options.max_startups; i++) {
896 			startup_pollfd[i] = -1;
897 			if (children[i].pipefd != -1) {
898 				pfd[npfd].fd = children[i].pipefd;
899 				pfd[npfd].events = POLLIN;
900 				startup_pollfd[i] = npfd++;
901 			}
902 		}
903 
904 		/* Wait until a connection arrives or a child exits. */
905 		ret = ppoll(pfd, npfd, NULL, &osigset);
906 		if (ret == -1 && errno != EINTR) {
907 			error("ppoll: %.100s", strerror(errno));
908 			if (errno == EINVAL)
909 				cleanup_exit(1); /* can't recover */
910 		}
911 		sigprocmask(SIG_SETMASK, &osigset, NULL);
912 		if (ret == -1)
913 			continue;
914 
915 		for (i = 0; i < options.max_startups; i++) {
916 			if (children[i].pipefd == -1 ||
917 			    startup_pollfd[i] == -1 ||
918 			    !(pfd[startup_pollfd[i]].revents & (POLLIN|POLLHUP)))
919 				continue;
920 			switch (read(children[i].pipefd, &c, sizeof(c))) {
921 			case -1:
922 				if (errno == EINTR || errno == EAGAIN)
923 					continue;
924 				if (errno != EPIPE) {
925 					error_f("startup pipe %d (fd=%d): "
926 					    "read %s", i, children[i].pipefd,
927 					    strerror(errno));
928 				}
929 				/* FALLTHROUGH */
930 			case 0:
931 				/* child exited preauth */
932 				if (children[i].early)
933 					listening--;
934 				srclimit_done(children[i].pipefd);
935 				child_close(&(children[i]), 0, 0);
936 				break;
937 			case 1:
938 				if (children[i].early && c == '\0') {
939 					/* child has finished preliminaries */
940 					listening--;
941 					children[i].early = 0;
942 					debug2_f("child %lu for %s received "
943 					    "config", (long)children[i].pid,
944 					    children[i].id);
945 				} else if (!children[i].early && c == '\001') {
946 					/* child has completed auth */
947 					debug2_f("child %lu for %s auth done",
948 					    (long)children[i].pid,
949 					    children[i].id);
950 					child_close(&(children[i]), 1, 0);
951 				} else {
952 					error_f("unexpected message 0x%02x "
953 					    "child %ld for %s in state %d",
954 					    (int)c, (long)children[i].pid,
955 					    children[i].id, children[i].early);
956 				}
957 				break;
958 			}
959 		}
960 		for (i = 0; i < num_listen_socks; i++) {
961 			if (!(pfd[i].revents & POLLIN))
962 				continue;
963 			fromlen = sizeof(from);
964 			*newsock = accept(listen_socks[i],
965 			    (struct sockaddr *)&from, &fromlen);
966 			if (*newsock == -1) {
967 				if (errno != EINTR && errno != EWOULDBLOCK &&
968 				    errno != ECONNABORTED)
969 					error("accept: %.100s",
970 					    strerror(errno));
971 				if (errno == EMFILE || errno == ENFILE)
972 					usleep(100 * 1000);
973 				continue;
974 			}
975 			if (unset_nonblock(*newsock) == -1) {
976 				close(*newsock);
977 				continue;
978 			}
979 			if (pipe(startup_p) == -1) {
980 				error_f("pipe(startup_p): %s", strerror(errno));
981 				close(*newsock);
982 				continue;
983 			}
984 			if (drop_connection(*newsock,
985 			    children_active, startup_p[0])) {
986 				close(*newsock);
987 				close(startup_p[0]);
988 				close(startup_p[1]);
989 				continue;
990 			}
991 
992 			if (socketpair(AF_UNIX,
993 			    SOCK_STREAM, 0, config_s) == -1) {
994 				error("reexec socketpair: %s",
995 				    strerror(errno));
996 				close(*newsock);
997 				close(startup_p[0]);
998 				close(startup_p[1]);
999 				continue;
1000 			}
1001 
1002 			/*
1003 			 * Got connection.  Fork a child to handle it, unless
1004 			 * we are in debugging mode.
1005 			 */
1006 			if (debug_flag) {
1007 				/*
1008 				 * In debugging mode.  Close the listening
1009 				 * socket, and start processing the
1010 				 * connection without forking.
1011 				 */
1012 				debug("Server will not fork when running in debugging mode.");
1013 				close_listen_socks();
1014 				*sock_in = *newsock;
1015 				*sock_out = *newsock;
1016 				close(startup_p[0]);
1017 				close(startup_p[1]);
1018 				startup_pipe = -1;
1019 				send_rexec_state(config_s[0], cfg);
1020 				close(config_s[0]);
1021 				free(pfd);
1022 				return;
1023 			}
1024 
1025 			/*
1026 			 * Normal production daemon.  Fork, and have
1027 			 * the child process the connection. The
1028 			 * parent continues listening.
1029 			 */
1030 			listening++;
1031 			child = child_register(startup_p[0], *newsock);
1032 			if ((child->pid = fork()) == 0) {
1033 				/*
1034 				 * Child.  Close the listening and
1035 				 * max_startup sockets.  Start using
1036 				 * the accepted socket. Reinitialize
1037 				 * logging (since our pid has changed).
1038 				 * We return from this function to handle
1039 				 * the connection.
1040 				 */
1041 				startup_pipe = startup_p[1];
1042 				close_startup_pipes();
1043 				close_listen_socks();
1044 				*sock_in = *newsock;
1045 				*sock_out = *newsock;
1046 				log_init(__progname,
1047 				    options.log_level,
1048 				    options.log_facility,
1049 				    log_stderr);
1050 				close(config_s[0]);
1051 				free(pfd);
1052 				return;
1053 			}
1054 
1055 			/* Parent.  Stay in the loop. */
1056 			if (child->pid == -1)
1057 				error("fork: %.100s", strerror(errno));
1058 			else
1059 				debug("Forked child %ld.", (long)child->pid);
1060 
1061 			close(startup_p[1]);
1062 
1063 			close(config_s[1]);
1064 			send_rexec_state(config_s[0], cfg);
1065 			close(config_s[0]);
1066 			close(*newsock);
1067 		}
1068 	}
1069 }
1070 
1071 static void
accumulate_host_timing_secret(struct sshbuf * server_cfg,struct sshkey * key)1072 accumulate_host_timing_secret(struct sshbuf *server_cfg,
1073     struct sshkey *key)
1074 {
1075 	static struct ssh_digest_ctx *ctx;
1076 	u_char *hash;
1077 	size_t len;
1078 	struct sshbuf *buf;
1079 	int r;
1080 
1081 	if (ctx == NULL && (ctx = ssh_digest_start(SSH_DIGEST_SHA512)) == NULL)
1082 		fatal_f("ssh_digest_start");
1083 	if (key == NULL) { /* finalize */
1084 		/* add server config in case we are using agent for host keys */
1085 		if (ssh_digest_update(ctx, sshbuf_ptr(server_cfg),
1086 		    sshbuf_len(server_cfg)) != 0)
1087 			fatal_f("ssh_digest_update");
1088 		len = ssh_digest_bytes(SSH_DIGEST_SHA512);
1089 		hash = xmalloc(len);
1090 		if (ssh_digest_final(ctx, hash, len) != 0)
1091 			fatal_f("ssh_digest_final");
1092 		options.timing_secret = PEEK_U64(hash);
1093 		freezero(hash, len);
1094 		ssh_digest_free(ctx);
1095 		ctx = NULL;
1096 		return;
1097 	}
1098 	if ((buf = sshbuf_new()) == NULL)
1099 		fatal_f("could not allocate buffer");
1100 	if ((r = sshkey_private_serialize(key, buf)) != 0)
1101 		fatal_fr(r, "encode %s key", sshkey_ssh_name(key));
1102 	if (ssh_digest_update(ctx, sshbuf_ptr(buf), sshbuf_len(buf)) != 0)
1103 		fatal_f("ssh_digest_update");
1104 	sshbuf_reset(buf);
1105 	sshbuf_free(buf);
1106 }
1107 
1108 static char *
prepare_proctitle(int ac,char ** av)1109 prepare_proctitle(int ac, char **av)
1110 {
1111 	char *ret = NULL;
1112 	int i;
1113 
1114 	for (i = 0; i < ac; i++)
1115 		xextendf(&ret, " ", "%s", av[i]);
1116 	return ret;
1117 }
1118 
1119 static void
print_config(struct connection_info * connection_info)1120 print_config(struct connection_info *connection_info)
1121 {
1122 	connection_info->test = 1;
1123 	parse_server_match_config(&options, &includes, connection_info);
1124 	dump_config(&options);
1125 	exit(0);
1126 }
1127 
1128 /*
1129  * Main program for the daemon.
1130  */
1131 int
main(int ac,char ** av)1132 main(int ac, char **av)
1133 {
1134 	extern char *optarg;
1135 	extern int optind;
1136 	int log_stderr = 0, inetd_flag = 0, test_flag = 0, no_daemon_flag = 0;
1137 	char *config_file_name = _PATH_SERVER_CONFIG_FILE;
1138 	int r, opt, do_dump_cfg = 0, keytype, already_daemon, have_agent = 0;
1139 	int sock_in = -1, sock_out = -1, newsock = -1, rexec_argc = 0;
1140 	int devnull, config_s[2] = { -1 , -1 }, have_connection_info = 0;
1141 	char *fp, *line, *logfile = NULL, **rexec_argv = NULL;
1142 	struct stat sb;
1143 	u_int i, j;
1144 	mode_t new_umask;
1145 	struct sshkey *key;
1146 	struct sshkey *pubkey;
1147 	struct connection_info connection_info;
1148 	sigset_t sigmask;
1149 
1150 	memset(&connection_info, 0, sizeof(connection_info));
1151 
1152 	sigemptyset(&sigmask);
1153 	sigprocmask(SIG_SETMASK, &sigmask, NULL);
1154 
1155 	/* Save argv. */
1156 	saved_argv = av;
1157 	rexec_argc = ac;
1158 
1159 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1160 	sanitise_stdfd();
1161 
1162 	/* Initialize configuration options to their default values. */
1163 	initialize_server_options(&options);
1164 
1165 	/* Parse command-line arguments. */
1166 	while ((opt = getopt(ac, av,
1167 	    "C:E:b:c:f:g:h:k:o:p:u:46DGQRTdeiqrtV")) != -1) {
1168 		switch (opt) {
1169 		case '4':
1170 			options.address_family = AF_INET;
1171 			break;
1172 		case '6':
1173 			options.address_family = AF_INET6;
1174 			break;
1175 		case 'f':
1176 			config_file_name = optarg;
1177 			break;
1178 		case 'c':
1179 			servconf_add_hostcert("[command-line]", 0,
1180 			    &options, optarg);
1181 			break;
1182 		case 'd':
1183 			if (debug_flag == 0) {
1184 				debug_flag = 1;
1185 				options.log_level = SYSLOG_LEVEL_DEBUG1;
1186 			} else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1187 				options.log_level++;
1188 			break;
1189 		case 'D':
1190 			no_daemon_flag = 1;
1191 			break;
1192 		case 'G':
1193 			do_dump_cfg = 1;
1194 			break;
1195 		case 'E':
1196 			logfile = optarg;
1197 			/* FALLTHROUGH */
1198 		case 'e':
1199 			log_stderr = 1;
1200 			break;
1201 		case 'i':
1202 			inetd_flag = 1;
1203 			break;
1204 		case 'r':
1205 			logit("-r option is deprecated");
1206 			break;
1207 		case 'R':
1208 			fatal("-R not supported here");
1209 			break;
1210 		case 'Q':
1211 			/* ignored */
1212 			break;
1213 		case 'q':
1214 			options.log_level = SYSLOG_LEVEL_QUIET;
1215 			break;
1216 		case 'b':
1217 			/* protocol 1, ignored */
1218 			break;
1219 		case 'p':
1220 			options.ports_from_cmdline = 1;
1221 			if (options.num_ports >= MAX_PORTS) {
1222 				fprintf(stderr, "too many ports.\n");
1223 				exit(1);
1224 			}
1225 			options.ports[options.num_ports++] = a2port(optarg);
1226 			if (options.ports[options.num_ports-1] <= 0) {
1227 				fprintf(stderr, "Bad port number.\n");
1228 				exit(1);
1229 			}
1230 			break;
1231 		case 'g':
1232 			if ((options.login_grace_time = convtime(optarg)) == -1) {
1233 				fprintf(stderr, "Invalid login grace time.\n");
1234 				exit(1);
1235 			}
1236 			break;
1237 		case 'k':
1238 			/* protocol 1, ignored */
1239 			break;
1240 		case 'h':
1241 			servconf_add_hostkey("[command-line]", 0,
1242 			    &options, optarg, 1);
1243 			break;
1244 		case 't':
1245 			test_flag = 1;
1246 			break;
1247 		case 'T':
1248 			test_flag = 2;
1249 			break;
1250 		case 'C':
1251 			if (parse_server_match_testspec(&connection_info,
1252 			    optarg) == -1)
1253 				exit(1);
1254 			have_connection_info = 1;
1255 			break;
1256 		case 'u':
1257 			utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
1258 			if (utmp_len > HOST_NAME_MAX+1) {
1259 				fprintf(stderr, "Invalid utmp length.\n");
1260 				exit(1);
1261 			}
1262 			break;
1263 		case 'o':
1264 			line = xstrdup(optarg);
1265 			if (process_server_config_line(&options, line,
1266 			    "command-line", 0, NULL, NULL, &includes) != 0)
1267 				exit(1);
1268 			free(line);
1269 			break;
1270 		case 'V':
1271 			fprintf(stderr, "%s, %s\n",
1272 			    SSH_VERSION, SSH_OPENSSL_VERSION);
1273 			exit(0);
1274 		default:
1275 			usage();
1276 			break;
1277 		}
1278 	}
1279 	if (!test_flag && !inetd_flag && !do_dump_cfg && !path_absolute(av[0]))
1280 		fatal("sshd requires execution with an absolute path");
1281 
1282 	closefrom(STDERR_FILENO + 1);
1283 
1284 	/* Reserve fds we'll need later for reexec things */
1285 	if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1)
1286 		fatal("open %s: %s", _PATH_DEVNULL, strerror(errno));
1287 	while (devnull < REEXEC_MIN_FREE_FD) {
1288 		if ((devnull = dup(devnull)) == -1)
1289 			fatal("dup %s: %s", _PATH_DEVNULL, strerror(errno));
1290 	}
1291 
1292 #ifdef WITH_OPENSSL
1293 	OpenSSL_add_all_algorithms();
1294 #endif
1295 
1296 	/* If requested, redirect the logs to the specified logfile. */
1297 	if (logfile != NULL) {
1298 		char *cp, pid_s[32];
1299 
1300 		snprintf(pid_s, sizeof(pid_s), "%ld", (unsigned long)getpid());
1301 		cp = percent_expand(logfile,
1302 		    "p", pid_s,
1303 		    "P", "sshd",
1304 		    (char *)NULL);
1305 		log_redirect_stderr_to(cp);
1306 		free(cp);
1307 	}
1308 
1309 	/*
1310 	 * Force logging to stderr until we have loaded the private host
1311 	 * key (unless started from inetd)
1312 	 */
1313 	log_init(__progname,
1314 	    options.log_level == SYSLOG_LEVEL_NOT_SET ?
1315 	    SYSLOG_LEVEL_INFO : options.log_level,
1316 	    options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1317 	    SYSLOG_FACILITY_AUTH : options.log_facility,
1318 	    log_stderr || !inetd_flag || debug_flag);
1319 
1320 	sensitive_data.have_ssh2_key = 0;
1321 
1322 	/*
1323 	 * If we're not doing an extended test do not silently ignore connection
1324 	 * test params.
1325 	 */
1326 	if (test_flag < 2 && have_connection_info)
1327 		fatal("Config test connection parameter (-C) provided without "
1328 		    "test mode (-T)");
1329 
1330 	/* Fetch our configuration */
1331 	if ((cfg = sshbuf_new()) == NULL)
1332 		fatal("sshbuf_new config failed");
1333 	if (strcasecmp(config_file_name, "none") != 0)
1334 		load_server_config(config_file_name, cfg);
1335 
1336 	parse_server_config(&options, config_file_name, cfg,
1337 	    &includes, NULL, 0);
1338 
1339 	/* Fill in default values for those options not explicitly set. */
1340 	fill_default_server_options(&options);
1341 
1342 	/* Check that options are sensible */
1343 	if (options.authorized_keys_command_user == NULL &&
1344 	    (options.authorized_keys_command != NULL &&
1345 	    strcasecmp(options.authorized_keys_command, "none") != 0))
1346 		fatal("AuthorizedKeysCommand set without "
1347 		    "AuthorizedKeysCommandUser");
1348 	if (options.authorized_principals_command_user == NULL &&
1349 	    (options.authorized_principals_command != NULL &&
1350 	    strcasecmp(options.authorized_principals_command, "none") != 0))
1351 		fatal("AuthorizedPrincipalsCommand set without "
1352 		    "AuthorizedPrincipalsCommandUser");
1353 
1354 	/*
1355 	 * Check whether there is any path through configured auth methods.
1356 	 * Unfortunately it is not possible to verify this generally before
1357 	 * daemonisation in the presence of Match blocks, but this catches
1358 	 * and warns for trivial misconfigurations that could break login.
1359 	 */
1360 	if (options.num_auth_methods != 0) {
1361 		for (i = 0; i < options.num_auth_methods; i++) {
1362 			if (auth2_methods_valid(options.auth_methods[i],
1363 			    1) == 0)
1364 				break;
1365 		}
1366 		if (i >= options.num_auth_methods)
1367 			fatal("AuthenticationMethods cannot be satisfied by "
1368 			    "enabled authentication methods");
1369 	}
1370 
1371 	/* Check that there are no remaining arguments. */
1372 	if (optind < ac) {
1373 		fprintf(stderr, "Extra argument %s.\n", av[optind]);
1374 		exit(1);
1375 	}
1376 
1377 	debug("sshd version %s, %s", SSH_VERSION, SSH_OPENSSL_VERSION);
1378 
1379 	if (do_dump_cfg)
1380 		print_config(&connection_info);
1381 
1382 	/* load host keys */
1383 	sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1384 	    sizeof(struct sshkey *));
1385 	sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
1386 	    sizeof(struct sshkey *));
1387 
1388 	if (options.host_key_agent) {
1389 		if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
1390 			setenv(SSH_AUTHSOCKET_ENV_NAME,
1391 			    options.host_key_agent, 1);
1392 		if ((r = ssh_get_authentication_socket(NULL)) == 0)
1393 			have_agent = 1;
1394 		else
1395 			error_r(r, "Could not connect to agent \"%s\"",
1396 			    options.host_key_agent);
1397 	}
1398 
1399 	for (i = 0; i < options.num_host_key_files; i++) {
1400 		int ll = options.host_key_file_userprovided[i] ?
1401 		    SYSLOG_LEVEL_ERROR : SYSLOG_LEVEL_DEBUG1;
1402 
1403 		if (options.host_key_files[i] == NULL)
1404 			continue;
1405 		if ((r = sshkey_load_private(options.host_key_files[i], "",
1406 		    &key, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR)
1407 			do_log2_r(r, ll, "Unable to load host key \"%s\"",
1408 			    options.host_key_files[i]);
1409 		if (sshkey_is_sk(key) &&
1410 		    key->sk_flags & SSH_SK_USER_PRESENCE_REQD) {
1411 			debug("host key %s requires user presence, ignoring",
1412 			    options.host_key_files[i]);
1413 			key->sk_flags &= ~SSH_SK_USER_PRESENCE_REQD;
1414 		}
1415 		if (r == 0 && key != NULL &&
1416 		    (r = sshkey_shield_private(key)) != 0) {
1417 			do_log2_r(r, ll, "Unable to shield host key \"%s\"",
1418 			    options.host_key_files[i]);
1419 			sshkey_free(key);
1420 			key = NULL;
1421 		}
1422 		if ((r = sshkey_load_public(options.host_key_files[i],
1423 		    &pubkey, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR)
1424 			do_log2_r(r, ll, "Unable to load host key \"%s\"",
1425 			    options.host_key_files[i]);
1426 		if (pubkey != NULL && key != NULL) {
1427 			if (!sshkey_equal(pubkey, key)) {
1428 				error("Public key for %s does not match "
1429 				    "private key", options.host_key_files[i]);
1430 				sshkey_free(pubkey);
1431 				pubkey = NULL;
1432 			}
1433 		}
1434 		if (pubkey == NULL && key != NULL) {
1435 			if ((r = sshkey_from_private(key, &pubkey)) != 0)
1436 				fatal_r(r, "Could not demote key: \"%s\"",
1437 				    options.host_key_files[i]);
1438 		}
1439 		if (pubkey != NULL && (r = sshkey_check_rsa_length(pubkey,
1440 		    options.required_rsa_size)) != 0) {
1441 			error_fr(r, "Host key %s", options.host_key_files[i]);
1442 			sshkey_free(pubkey);
1443 			sshkey_free(key);
1444 			continue;
1445 		}
1446 		sensitive_data.host_keys[i] = key;
1447 		sensitive_data.host_pubkeys[i] = pubkey;
1448 
1449 		if (key == NULL && pubkey != NULL && have_agent) {
1450 			debug("will rely on agent for hostkey %s",
1451 			    options.host_key_files[i]);
1452 			keytype = pubkey->type;
1453 		} else if (key != NULL) {
1454 			keytype = key->type;
1455 			accumulate_host_timing_secret(cfg, key);
1456 		} else {
1457 			do_log2(ll, "Unable to load host key: %s",
1458 			    options.host_key_files[i]);
1459 			sensitive_data.host_keys[i] = NULL;
1460 			sensitive_data.host_pubkeys[i] = NULL;
1461 			continue;
1462 		}
1463 
1464 		switch (keytype) {
1465 		case KEY_RSA:
1466 		case KEY_DSA:
1467 		case KEY_ECDSA:
1468 		case KEY_ED25519:
1469 		case KEY_ECDSA_SK:
1470 		case KEY_ED25519_SK:
1471 		case KEY_XMSS:
1472 			if (have_agent || key != NULL)
1473 				sensitive_data.have_ssh2_key = 1;
1474 			break;
1475 		}
1476 		if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash,
1477 		    SSH_FP_DEFAULT)) == NULL)
1478 			fatal("sshkey_fingerprint failed");
1479 		debug("%s host key #%d: %s %s",
1480 		    key ? "private" : "agent", i, sshkey_ssh_name(pubkey), fp);
1481 		free(fp);
1482 	}
1483 	accumulate_host_timing_secret(cfg, NULL);
1484 	if (!sensitive_data.have_ssh2_key) {
1485 		logit("sshd: no hostkeys available -- exiting.");
1486 		exit(1);
1487 	}
1488 
1489 	/*
1490 	 * Load certificates. They are stored in an array at identical
1491 	 * indices to the public keys that they relate to.
1492 	 */
1493 	sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
1494 	    sizeof(struct sshkey *));
1495 	for (i = 0; i < options.num_host_key_files; i++)
1496 		sensitive_data.host_certificates[i] = NULL;
1497 
1498 	for (i = 0; i < options.num_host_cert_files; i++) {
1499 		if (options.host_cert_files[i] == NULL)
1500 			continue;
1501 		if ((r = sshkey_load_public(options.host_cert_files[i],
1502 		    &key, NULL)) != 0) {
1503 			error_r(r, "Could not load host certificate \"%s\"",
1504 			    options.host_cert_files[i]);
1505 			continue;
1506 		}
1507 		if (!sshkey_is_cert(key)) {
1508 			error("Certificate file is not a certificate: %s",
1509 			    options.host_cert_files[i]);
1510 			sshkey_free(key);
1511 			continue;
1512 		}
1513 		/* Find matching private key */
1514 		for (j = 0; j < options.num_host_key_files; j++) {
1515 			if (sshkey_equal_public(key,
1516 			    sensitive_data.host_pubkeys[j])) {
1517 				sensitive_data.host_certificates[j] = key;
1518 				break;
1519 			}
1520 		}
1521 		if (j >= options.num_host_key_files) {
1522 			error("No matching private key for certificate: %s",
1523 			    options.host_cert_files[i]);
1524 			sshkey_free(key);
1525 			continue;
1526 		}
1527 		sensitive_data.host_certificates[j] = key;
1528 		debug("host certificate: #%u type %d %s", j, key->type,
1529 		    sshkey_type(key));
1530 	}
1531 
1532 	/* Ensure privsep directory is correctly configured. */
1533 	if (getpwnam(SSH_PRIVSEP_USER) == NULL)
1534 		fatal("Privilege separation user %s does not exist",
1535 		    SSH_PRIVSEP_USER);
1536 	endpwent();
1537 	if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &sb) == -1) ||
1538 	    (S_ISDIR(sb.st_mode) == 0))
1539 		fatal("Missing privilege separation directory: %s",
1540 		    _PATH_PRIVSEP_CHROOT_DIR);
1541 	if (sb.st_uid != 0 || (sb.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1542 		fatal("%s must be owned by root and not group or "
1543 		    "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1544 
1545 	if (test_flag > 1)
1546 		print_config(&connection_info);
1547 
1548 	/* Configuration looks good, so exit if in test mode. */
1549 	if (test_flag)
1550 		exit(0);
1551 
1552 	/* Prepare arguments for sshd-session */
1553 	if (rexec_argc < 0)
1554 		fatal("rexec_argc %d < 0", rexec_argc);
1555 	rexec_argv = xcalloc(rexec_argc + 3, sizeof(char *));
1556 	/* Point to the sshd-session binary instead of sshd */
1557 	rexec_argv[0] = options.sshd_session_path;
1558 	for (i = 1; i < (u_int)rexec_argc; i++) {
1559 		debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1560 		rexec_argv[i] = saved_argv[i];
1561 	}
1562 	rexec_argv[rexec_argc++] = "-R";
1563 	rexec_argv[rexec_argc] = NULL;
1564 	if (stat(rexec_argv[0], &sb) != 0 || !(sb.st_mode & (S_IXOTH|S_IXUSR)))
1565 		fatal("%s does not exist or is not executable", rexec_argv[0]);
1566 	debug3("using %s for re-exec", rexec_argv[0]);
1567 
1568 	/* Ensure that the privsep binary exists now too. */
1569 	if (stat(options.sshd_auth_path, &sb) != 0 ||
1570 	    !(sb.st_mode & (S_IXOTH|S_IXUSR))) {
1571 		fatal("%s does not exist or is not executable",
1572 		    options.sshd_auth_path);
1573 	}
1574 
1575 	listener_proctitle = prepare_proctitle(ac, av);
1576 
1577 	/* Ensure that umask disallows at least group and world write */
1578 	new_umask = umask(0077) | 0022;
1579 	(void) umask(new_umask);
1580 
1581 	/* Initialize the log (it is reinitialized below in case we forked). */
1582 	if (debug_flag && !inetd_flag)
1583 		log_stderr = 1;
1584 	log_init(__progname, options.log_level,
1585 	    options.log_facility, log_stderr);
1586 	for (i = 0; i < options.num_log_verbose; i++)
1587 		log_verbose_add(options.log_verbose[i]);
1588 
1589 	/*
1590 	 * If not in debugging mode, not started from inetd and not already
1591 	 * daemonized (eg re-exec via SIGHUP), disconnect from the controlling
1592 	 * terminal, and fork.  The original process exits.
1593 	 */
1594 	already_daemon = daemonized();
1595 	if (!(debug_flag || inetd_flag || no_daemon_flag || already_daemon)) {
1596 
1597 		if (daemon(0, 0) == -1)
1598 			fatal("daemon() failed: %.200s", strerror(errno));
1599 
1600 		disconnect_controlling_tty();
1601 	}
1602 	/* Reinitialize the log (because of the fork above). */
1603 	log_init(__progname, options.log_level, options.log_facility, log_stderr);
1604 
1605 	/*
1606 	 * Chdir to the root directory so that the current disk can be
1607 	 * unmounted if desired.
1608 	 */
1609 	if (chdir("/") == -1)
1610 		error("chdir(\"/\"): %s", strerror(errno));
1611 
1612 	/* ignore SIGPIPE */
1613 	ssh_signal(SIGPIPE, SIG_IGN);
1614 
1615 	/* Get a connection, either from inetd or a listening TCP socket */
1616 	if (inetd_flag) {
1617 		/* Send configuration to ancestor sshd-session process */
1618 		if (socketpair(AF_UNIX, SOCK_STREAM, 0, config_s) == -1)
1619 			fatal("socketpair: %s", strerror(errno));
1620 		send_rexec_state(config_s[0], cfg);
1621 		close(config_s[0]);
1622 	} else {
1623 		server_listen();
1624 
1625 		ssh_signal(SIGHUP, sighup_handler);
1626 		ssh_signal(SIGCHLD, main_sigchld_handler);
1627 		ssh_signal(SIGTERM, sigterm_handler);
1628 		ssh_signal(SIGQUIT, sigterm_handler);
1629 		ssh_signal(SIGINFO, siginfo_handler);
1630 
1631 		/*
1632 		 * Write out the pid file after the sigterm handler
1633 		 * is setup and the listen sockets are bound
1634 		 */
1635 		if (options.pid_file != NULL && !debug_flag) {
1636 			FILE *f = fopen(options.pid_file, "w");
1637 
1638 			if (f == NULL) {
1639 				error("Couldn't create pid file \"%s\": %s",
1640 				    options.pid_file, strerror(errno));
1641 			} else {
1642 				fprintf(f, "%ld\n", (long) getpid());
1643 				fclose(f);
1644 			}
1645 		}
1646 
1647 		/* Accept a connection and return in a forked child */
1648 		server_accept_loop(&sock_in, &sock_out,
1649 		    &newsock, config_s, log_stderr);
1650 	}
1651 
1652 	/* This is the child processing a new connection. */
1653 	setproctitle("%s", "[accepted]");
1654 
1655 	/*
1656 	 * Create a new session and process group since the 4.4BSD
1657 	 * setlogin() affects the entire process group.  We don't
1658 	 * want the child to be able to affect the parent.
1659 	 */
1660 	if (!debug_flag && !inetd_flag && setsid() == -1)
1661 		error("setsid: %.100s", strerror(errno));
1662 
1663 	debug("rexec start in %d out %d newsock %d pipe %d sock %d/%d",
1664 	    sock_in, sock_out, newsock, startup_pipe, config_s[0], config_s[1]);
1665 	if (!inetd_flag) {
1666 		if (dup2(newsock, STDIN_FILENO) == -1)
1667 			fatal("dup2 stdin: %s", strerror(errno));
1668 		if (dup2(STDIN_FILENO, STDOUT_FILENO) == -1)
1669 			fatal("dup2 stdout: %s", strerror(errno));
1670 		if (newsock > STDOUT_FILENO)
1671 			close(newsock);
1672 	}
1673 	if (config_s[1] != REEXEC_CONFIG_PASS_FD) {
1674 		if (dup2(config_s[1], REEXEC_CONFIG_PASS_FD) == -1)
1675 			fatal("dup2 config_s: %s", strerror(errno));
1676 		close(config_s[1]);
1677 	}
1678 	if (startup_pipe == -1)
1679 		close(REEXEC_STARTUP_PIPE_FD);
1680 	else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) {
1681 		if (dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD) == -1)
1682 			fatal("dup2 startup_p: %s", strerror(errno));
1683 		close(startup_pipe);
1684 	}
1685 	log_redirect_stderr_to(NULL);
1686 	closefrom(REEXEC_MIN_FREE_FD);
1687 
1688 	ssh_signal(SIGHUP, SIG_IGN); /* avoid reset to SIG_DFL */
1689 	execv(rexec_argv[0], rexec_argv);
1690 
1691 	fatal("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1692 }
1693 
1694 /* server specific fatal cleanup */
1695 void
cleanup_exit(int i)1696 cleanup_exit(int i)
1697 {
1698 	_exit(i);
1699 }
1700