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