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