Debian Codegraph @

syscall.c

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 /*
2 * Syscall wrappers to ensure that nothing gets done in dry_run mode
3 * and to handle system peculiarities.
4 *
5 * Copyright (C) 1998 Andrew Tridgell
6 * Copyright (C) 2002 Martin Pool
7 * Copyright (C) 2003-2022 Wayne Davison
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, visit the http://fsf.org website.
21 */
22
23 #include "rsync.h"
24
25 /* Exercise the pre-*at() portability tier on modern build hosts. */
26 #ifdef RSYNC_TEST_NO_AT_FDCWD
27 #undef AT_FDCWD
28 #undef AT_SYMLINK_NOFOLLOW
29 #undef HAVE_LINKAT
30 #undef HAVE_OPENAT2
31 #undef HAVE_UTIMENSAT
32 #undef O_RESOLVE_BENEATH
33 #endif
34
35 #if !defined MKNOD_CREATES_SOCKETS && defined HAVE_SYS_UN_H
36 #include <sys/un.h> /* for the socket+bind() fallback in do_mknod() */
37 #endif
38 #ifdef HAVE_SYS_ATTR_H
39 #include <sys/attr.h>
40 #endif
41
42 #if defined HAVE_SYS_FALLOCATE && !defined HAVE_FALLOCATE
43 #include <sys/syscall.h>
44 #endif
45
46 #ifdef __linux__
47 #include <sys/syscall.h> /* SYS_fchmodat2 / SYS_fallocate raw-syscall wrappers */
48 #endif
49
50 #include "ifuncs.h"
51
52 extern int dry_run;
53 extern int am_root;
54 extern int am_sender;
55 extern int read_only;
56 extern int list_only;
57 extern int inplace;
58 extern int preallocate_files;
59 extern int sparse_files;
60 extern int preserve_perms;
61 extern int preserve_executability;
62 extern int open_noatime;
63 extern int copy_links;
64 extern int copy_unsafe_links;
65 extern int am_daemon;
66 extern int am_chrooted;
67 extern int insecure_links;
68 extern int module_id;
69 extern unsigned int module_dirlen;
70 extern char *module_dir;
71 extern int module_dirfd; /* daemon: served module root pinned by identity, or -1 */
72 extern char *confine_root; /* --confine-root, or NULL; see confinement_root() */
73 extern unsigned int confine_rootlen;
74 extern char curr_dir[MAXPATHLEN]; /* defined below; fwd-declared for the seed */
75 extern int operator_path_resolve; /* defined below; fwd-declared for the exclude check */
76
77 #if defined AT_FDCWD && defined O_NOFOLLOW && defined O_DIRECTORY
78 /* Open a trusted absolute anchor directory as an owned dirfd. When the anchor is
79 * the served module root and the daemon pinned it by identity (module_dirfd), dup
80 * that fd rather than re-resolving the absolute path with openat(AT_FDCWD, ...) --
81 * which re-traverses the module's ancestors as the dropped-privilege module uid
82 * and EACCESes when the module sits under a non-traversable parent (a 0700 home).
83 * Functionally identical (same inode), just privilege-drop-safe. Gated like its
84 * callers (the secure resolver and dpc_dir_fd both require these three). */
85 static int open_anchor_dirfd(const char *path)
86 {
87 if (module_dirfd >= 0 && am_daemon && module_dir && strcmp(path, module_dir) == 0)
88 return dup(module_dirfd);
89 return openat(AT_FDCWD, path, O_RDONLY | O_DIRECTORY);
90 }
91 #endif
92
93 /* Single gate for whether path resolution must be hardened against
94 * parent-component symlink races (TOCTOU). Used by the do_*_at()/do_*_atfd()
95 * wrappers and the receiver's secure-open/secure-mkstemp choices. Hardens
96 * every non-chrooted receiver (a chroot is its own confinement); the sender is
97 * excluded so it still follows -L/--copy-links symlinks. A daemon chroot with
98 * an inner-module /./ boundary still needs these checks because the kernel
99 * chroot confines the outer path, not the inner module. */
100 int secure_relpath_active(void)
101 {
102 /* The "insecure links" / --insecure-links opt-out restores the legacy
103 * follow-any-symlink behaviour uniformly, so it disables the secure
104 * resolver on the RECEIVER side too (not just the sender enumeration that
105 * already checks symlink_optout_allowed()). Without this an opted-out
106 * module still confined receiver writes/stats through a pre-existing
107 * in-module symlink -- failing to match the pre-3.4.3 behaviour the opt-out
108 * promises (documented in rsyncd.conf(5) "munge symlinks"/"insecure links"). */
109 if (symlink_optout_allowed())
110 return 0;
111 if (am_daemon && am_chrooted && module_dirlen)
112 return 1;
113 return !am_chrooted && (am_daemon || !am_sender);
114 }
115
116 /* Whether the operator-supplied-path symlink confinement is opted out. For a
117 * non-daemon transfer this is the local --insecure-links flag. For a daemon it
118 * is governed ONLY by the module's "insecure links" config (lp_insecure_links)
119 * -- never by a peer-supplied --insecure-links (a client cannot disable a
120 * daemon's confinement; the daemon also drops a connection that sends it). So a
121 * forwarded flag is structurally inert here. */
122 int symlink_optout_allowed(void)
123 {
124 if (am_daemon)
125 return module_id >= 0 && lp_insecure_links(module_id);
126 return insecure_links;
127 }
128
129 /* The root an operator/peer-supplied path must stay under, or NULL when nothing
130 * is confined. A daemon has the served module; a server launched by a wrapper
131 * with its own restricted directory (rrsync) gets one from --confine-root.
132 *
133 * A daemon never honours --confine-root: module_dir is the boundary there, and
134 * the option arrives in a peer-supplied argv, so obeying it could only loosen
135 * the module. */
136 static const char *confinement_root(unsigned int *lenp)
137 {
138 if (am_daemon) {
139 *lenp = module_dirlen;
140 return module_dir;
141 }
142 *lenp = confine_rootlen;
143 return confine_root;
144 }
145
•146 /* Split a recognised fd-pin prefix off `p`, returning the tail -- "" for the
147 * pin directory itself, otherwise a string starting with '/'. NULL when `p`
148 * is not in an fd-pin namespace. */
149 static const char *fd_pin_tail(const char *p)
150 {
151 const char *s;
152
•153 if (strncmp(p, "/dev/fd", 7) == 0) {
154 s = p + 7;
155 return (*s == '\0' || *s == '/') ? s : NULL;
156 }
157
158 if (strncmp(p, "/proc/", 6) != 0)
159 return NULL;
160 s = p + 6;
161 if (strncmp(s, "self/", 5) == 0) /* "/proc/self/..." */
162 s += 4;
163 else { /* "/proc/<pid>/..." */
164 const char *d = s;
165 while (*s >= '0' && *s <= '9')
166 s++;
167 if (s == d || *s != '/')
168 return NULL;
169 }
170 if (strncmp(s, "/fd", 3) != 0)
171 return NULL;
172 s += 3;
173 return (*s == '\0' || *s == '/') ? s : NULL;
174 }
175
•176 /* An EXACT pin entry, such as "/proc/self/fd/7" or "/dev/fd/7", whose target is
177 * what confinement must judge. rrsync also writes a pinned parent as
178 * ".../fd/7/<leaf>", but the walk resolves the magic link itself and checks the
179 * components past it, so only the bare entry is resolved here. Requiring all
180 * digits keeps a planted name like ".../fd/outside-secret" out. */
181 static int is_exact_fd_pin(const char *p)
182 {
183 const char *tail = fd_pin_tail(p);
184
185 if (!tail || *tail != '/')
186 return 0;
187 for (++tail; *tail >= '0' && *tail <= '9'; tail++) {}
188 return *tail == '\0' && tail[-1] != '/';
189 }
190
191 /* Refuse (return 1) when the ABSOLUTE resolved path `abspath` lands OUTSIDE the
192 * confinement root, for an operator/peer-supplied path that must stay inside it
193 * (--partial-dir/--backup-dir/alt-basis/merge files: operator_path_resolve). An
194 * in-tree symlink owned by uid 0 / the euid is followed by design, so it can
195 * redirect the resolved target outside the root; this catches that escape.
196 *
197 * This is ROOT confinement only. The daemon exclude/filter list is a name-based
198 * visibility filter, NOT a physical-path boundary: a symlink whose own name is
199 * not excluded may still resolve into an excluded IN-tree subtree, exactly as in
200 * stock rsync. The defense for a writable module is `munge symlinks` (see
201 * rsyncd.conf(5)), not this walk. */
202 static int abspath_outside_confinement(const char *abspath)
203 {
204 unsigned int rootlen;
205 const char *root = confinement_root(&rootlen);
206 char pinned[MAXPATHLEN];
207
208 if (!root || !abspath)
209 return 0;
210 if (rootlen <= 1) /* root is "/": nothing is outside */
211 return 0;
212 /* An fd pin (rrsync rewrites a validated option path to /proc/self/fd/N so
213 * no later symlink can redirect it) is spelled outside the root by
214 * construction. Judge it by what it points AT rather than by its spelling,
215 * so a pin is neither wrongly refused nor blindly trusted. A pin we cannot
216 * resolve to an absolute path is refused, not waved through: an unreadable
217 * pin is exactly the case where we cannot say where the open would land. */
218 if (!am_daemon) {
219 const char *tail = fd_pin_tail(abspath);
220 if (tail && !*tail)
221 return 0; /* the pin directory: transit, opens nothing */
222 if (is_exact_fd_pin(abspath)) {
223 ssize_t n = readlink(abspath, pinned, sizeof pinned - 1);
224 if (n <= 0 || pinned[0] != '/')
225 return operator_path_resolve ? 1 : 0;
226 pinned[n] = '\0';
227 abspath = pinned;
228 }
229 }
230 if (strncmp(abspath, root, rootlen) == 0
231 && (abspath[rootlen] == '\0' || abspath[rootlen] == '/'))
232 return 0; /* inside: name-based exclude is not a boundary */
233 /* Not under the root. An ABSOLUTE walk passes through the root's ancestors
234 * ("/", "/home", ...) on the way down -- those are not "outside", just
235 * not-yet-arrived, so allow them. A path that has truly DIVERGED is
236 * outside: refuse it for an operator/peer path that must stay in the tree
237 * (operator_path_resolve); other opens (--log-file, --*-from, lock/motd)
238 * may legitimately live elsewhere. The --insecure-links / "insecure links
239 * = yes" opt-out short-circuits before we get here. */
240 size_t alen = strlen(abspath);
241 if (alen == 0
242 || (strncmp(abspath, root, alen) == 0 && root[alen] == '/'))
243 return 0; /* ancestor of the root: still descending */
244 return operator_path_resolve ? 1 : 0;
245 }
246
247 /* Advance the tracked absolute path `abspath` by one resolved component,
248 * normalizing "." and ".." exactly as openat() does so the module-confinement
249 * check (abspath_outside_confinement) sees the REAL resolved target. -1/
250 * ENAMETOOLONG on overflow. */
251 static int abspath_step(char *abspath, size_t cap, const char *comp, size_t comp_len)
252 {
253 if (comp_len == 1 && comp[0] == '.')
254 return 0; /* "." -- no movement */
255 if (comp_len == 2 && comp[0] == '.' && comp[1] == '.') {
256 char *s = strrchr(abspath, '/'); /* ".." -- pop a component */
257 if (s)
258 *s = '\0';
259 else
260 abspath[0] = '\0';
261 return 0;
262 }
263 size_t al = strlen(abspath);
264 size_t off = (al > 0 && abspath[al-1] == '/') ? al : al + 1; /* no "//" */
265 if (off + comp_len >= cap) {
266 errno = ENAMETOOLONG;
267 return -1;
268 }
269 if (off != al)
270 abspath[al] = '/';
271 memcpy(abspath + off, comp, comp_len + 1);
272 return 0;
273 }
274
275 /* Open an operator-supplied path, refusing to traverse any symlink (parent or
276 * leaf) not owned by uid 0 or our euid. A trusted-owned symlink (e.g. root's
277 * /var/log -> /data/log) is still followed; an untrusted one fails ELOOP.
278 * Unlike plain O_NOFOLLOW this also defends a planted parent component
279 * (--log-file=$plant/log), not just a planted leaf. Used for opens that may
280 * transit attacker-writable parents: --log-file, --password-file, --*-from,
281 * --read/write-batch, daemon motd/lock/early-input/--config.
282 *
283 * Walks component-by-component with fstatat(AT_SYMLINK_NOFOLLOW) +
284 * openat(O_NOFOLLOW), splicing a trusted symlink's target back into the path.
285 * Returns the fd, or -1 (errno ELOOP on the security refusal so callers can
286 * tell it apart). Falls back to plain open() where openat/O_NOFOLLOW are
287 * unavailable. */
288 /* Core walk. When out_abs is non-NULL and the path resolves to a directory
289 * (O_DIRECTORY), the resolved absolute path is copied there -- owner_walk_parent
290 * uses it to filter-check the (otherwise unchecked) leaf basename. */
291 static int ona_open(const char *path, int flags, mode_t mode, char *out_abs, size_t out_cap)
292 {
293 #if defined AT_FDCWD && defined O_NOFOLLOW
294 /* O_CLOEXEC predates some still-supported targets; mirror rand_bytes()'s
295 * fallback in syscall.c so a build without it still compiles. */
296 #ifndef O_CLOEXEC
297 #define O_CLOEXEC 0
298 #endif
299 if (!path || !*path) {
300 errno = EINVAL;
301 return -1;
302 }
303
304 /* Opted out (local --insecure-links, or a daemon module with "insecure
305 * links = yes"): restore the legacy symlink-following open. */
306 if (symlink_optout_allowed())
307 return open(path, flags, mode);
308
309 const uid_t trusted_uid = geteuid();
310 int dfd = AT_FDCWD;
311 int dfd_owns = 0;
312
313 /* Absolute path of the current dir, for the confinement refusal
314 * (abspath_outside_confinement). A relative operator path starts at the
315 * daemon's cwd == the module root; an absolute one (or a followed absolute
316 * symlink target) restarts at "/". */
317 char abspath[MAXPATHLEN];
318 abspath[0] = '\0';
319 if (am_daemon && module_dir && module_dir[0] == '/')
320 strlcpy(abspath, module_dir, sizeof abspath); /* "/" for a path=/ module */
321 else if (confine_root) {
322 /* Unlike a daemon's, this cwd is not pinned to the root -- the receiver
323 * chdir's into the destination -- so it has to be read, not assumed.
324 * It must be the PHYSICAL cwd: curr_dir is the lexical name change_dir()
325 * was given, so after descending a trusted symlink the tracker sits at a
326 * different depth than the kernel, and a ".." that really escapes looks
327 * like it landed inside.
328 *
329 * Without it there is nothing to measure against, and an empty tracker
330 * does NOT deny by itself -- a leading ".." pops nothing and an empty
331 * path reads as an ancestor of the root -- so refuse the open instead. */
332 if (!getcwd(abspath, sizeof abspath))
333 return -1;
334 }
335
336 /* An fd pin (rrsync rewrites an option path to /proc/self/fd/N so no
337 * later symlink can redirect it) is spelled outside the root by
338 * construction, so the walk has to be allowed through /proc/self/fd to
339 * reach the magic link. This only suspends the check for that prefix:
340 * following the link restarts the walk at its absolute target, and every
341 * component of THAT is checked, so a pin aimed outside is still refused. */
342 int pin_transit = !am_daemon && confine_root && fd_pin_tail(path) != NULL;
343
344 /* Path-walk state. `remaining` is the unconsumed tail; we splice
345 * symlink targets back into it as we go. Sized 2x MAXPATHLEN so a
346 * one-level expansion can't immediately overflow; deeper chains
347 * fail with ENAMETOOLONG below. */
348 char remaining[MAXPATHLEN * 2];
349 if (strlcpy(remaining, path, sizeof remaining) >= sizeof remaining) {
350 errno = ENAMETOOLONG;
351 return -1;
352 }
353
354 /* Absolute path: pin "/" as the starting dfd. */
355 if (remaining[0] == '/') {
356 dfd = open("/", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
357 if (dfd < 0)
358 return -1;
359 dfd_owns = 1;
360 abspath[0] = '\0'; /* now resolving from "/" */
361 char *p = remaining;
362 while (*p == '/') p++;
363 memmove(remaining, p, strlen(p) + 1);
364 }
365
366 int loops = 40; /* SYMLOOP_MAX-ish; breaks symlink cycles. Counts symlink
367 * expansions only (below), NOT path depth -- a deep but
368 * symlink-free path must resolve, not ELOOP. */
369 int retfd = -1;
370 int saved_errno = 0;
371
372 while (*remaining) {
373 /* Peel one component off the front of `remaining`. */
374 char *slash = strchr(remaining, '/');
375 size_t comp_len = slash ? (size_t)(slash - remaining) : strlen(remaining);
376 char comp[MAXPATHLEN];
377 if (comp_len == 0 || comp_len >= sizeof comp) {
378 saved_errno = comp_len == 0 ? EINVAL : ENAMETOOLONG;
379 goto out;
380 }
381 memcpy(comp, remaining, comp_len);
382 comp[comp_len] = '\0';
383 int is_last = (slash == NULL);
384
385 /* Inspect this component without following symlinks. */
386 STRUCT_STAT lst;
387 if (fstatat(dfd, comp, &lst, AT_SYMLINK_NOFOLLOW) < 0) {
388 /* The leaf may not exist yet (O_CREAT case). Allow it
389 * and openat with O_NOFOLLOW so a race-planted leaf
390 * symlink at this instant is still refused. */
391 if (is_last && errno == ENOENT && (flags & O_CREAT)) {
392 if (abspath_step(abspath, sizeof abspath, comp, comp_len) < 0) {
393 saved_errno = errno;
394 goto out;
395 }
396 if (!pin_transit && abspath_outside_confinement(abspath)) {
397 saved_errno = ELOOP;
398 goto out;
399 }
400 retfd = openat(dfd, comp, flags | O_NOFOLLOW, mode);
401 saved_errno = errno;
402 goto out;
403 }
404 saved_errno = errno;
405 goto out;
406 }
407
408 if (S_ISLNK(lst.st_mode)) {
•409 /* Symlink: untrusted owner is refused; trusted owner is followed
410 * via readlinkat + splice. In a user namespace the /proc/self and
411 * /dev/fd symlinks may report the overflow uid, so
412 * allow those exact components while traversing a recognised pin. */
413 int namespace_pin = pin_transit
414 && ((strcmp(abspath, "/proc") == 0 && strcmp(comp, "self") == 0)
415 || (strcmp(abspath, "/dev") == 0 && strcmp(comp, "fd") == 0));
416 if (!namespace_pin && lst.st_uid != 0 && lst.st_uid != trusted_uid) {
417 saved_errno = ELOOP;
418 goto out;
419 }
420 if (--loops < 0) { /* cap symlink-follow chains */
421 saved_errno = ELOOP;
422 goto out;
423 }
424 char target[MAXPATHLEN];
425 ssize_t n = readlinkat(dfd, comp, target, sizeof target - 1);
426 if (n < 0) {
427 saved_errno = errno;
428 goto out;
429 }
430 target[n] = '\0';
431
432 /* Splice: new `remaining` = <target> + <tail-after-comp>.
433 * Absolute target restarts the walk from "/". */
434 char tail[MAXPATHLEN];
435 tail[0] = '\0';
436 if (slash)
437 strlcpy(tail, slash, sizeof tail);
438
439 char rebuilt[MAXPATHLEN * 2];
440 if (snprintf(rebuilt, sizeof rebuilt, "%s%s",
441 target, tail) >= (int)sizeof rebuilt) {
442 saved_errno = ENAMETOOLONG;
443 goto out;
444 }
445
446 if (target[0] == '/') {
447 if (dfd_owns) close(dfd);
448 dfd = open("/", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
449 if (dfd < 0) {
450 saved_errno = errno;
451 dfd_owns = 0;
452 goto out;
453 }
454 dfd_owns = 1;
455 abspath[0] = '\0'; /* followed an absolute target: restart from "/" */
456 /* "self" resolves to "<pid>", still inside the pin;
457 * the magic link itself lands elsewhere and ends the
458 * exemption. Never turns back on. */
459 pin_transit = pin_transit && fd_pin_tail(rebuilt) != NULL;
460 char *p = rebuilt;
461 while (*p == '/') p++;
462 strlcpy(remaining, p, sizeof remaining);
463 } else {
464 strlcpy(remaining, rebuilt, sizeof remaining);
465 }
466 continue;
467 }
468
469 /* Non-symlink. */
470 if (is_last) {
471 if (abspath_step(abspath, sizeof abspath, comp, comp_len) < 0) {
472 saved_errno = errno;
473 goto out;
474 }
475 if (!pin_transit && abspath_outside_confinement(abspath)) {
476 saved_errno = ELOOP;
477 goto out;
478 }
479 retfd = openat(dfd, comp, flags | O_NOFOLLOW, mode);
480 saved_errno = errno;
481 /* Resolved leaf dir (O_DIRECTORY): hand its path back so
482 * owner_walk_parent can filter-check the operation's leaf. */
483 if (retfd >= 0 && out_abs && out_cap)
484 /* Root-resolved (".." popped abspath empty) tracked daemon walk:
485 * hand back "/" so owner_walk_parent still leaf-checks (path=/ bypass). */
486 strlcpy(out_abs, (am_daemon && !abspath[0]) ? "/" : abspath, out_cap);
487 goto out;
488 }
489
490 if (!S_ISDIR(lst.st_mode)) {
491 saved_errno = ENOTDIR;
492 goto out;
493 }
494 /* track the resolved path so a target outside the module is refused */
495 if (abspath_step(abspath, sizeof abspath, comp, comp_len) < 0) {
496 saved_errno = errno;
497 goto out;
498 }
499 if (!pin_transit && abspath_outside_confinement(abspath)) {
500 saved_errno = ELOOP;
501 goto out;
502 }
503 int next = openat(dfd, comp, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
504 if (next < 0) {
505 saved_errno = errno;
506 goto out;
507 }
508 if (dfd_owns) close(dfd);
509 dfd = next;
510 dfd_owns = 1;
511
512 /* Advance `remaining` past this component (and the slash). */
513 if (slash) {
514 char *p = slash;
515 while (*p == '/') p++;
516 memmove(remaining, p, strlen(p) + 1);
517 } else {
518 remaining[0] = '\0';
519 }
520 }
521
522 /* Path resolved entirely to a directory (no leaf component left).
523 * If the caller wanted O_DIRECTORY we already hold the dirfd we
524 * built up; otherwise it's an EISDIR. */
525 if (flags & O_DIRECTORY) {
526 retfd = dfd;
527 dfd_owns = 0; /* caller now owns it */
528 saved_errno = 0;
529 if (out_abs && out_cap)
530 /* Root-resolved (".." popped abspath empty) tracked daemon walk:
531 * hand back "/" so owner_walk_parent still leaf-checks (path=/ bypass). */
532 strlcpy(out_abs, (am_daemon && !abspath[0]) ? "/" : abspath, out_cap);
533 } else {
534 saved_errno = EISDIR;
535 }
536
537 out:
538 if (dfd_owns) close(dfd);
539 errno = saved_errno;
540 return retfd;
541 #else
542 /* Pre-AT_FDCWD / no O_NOFOLLOW systems: best-effort fallback. */
543 (void)out_abs; (void)out_cap;
544 return open(path, flags, mode);
545 #endif
546 }
547
548 int open_no_attacker_symlinks(const char *path, int flags, mode_t mode)
549 {
550 return ona_open(path, flags, mode, NULL, 0);
551 }
552
553 /* When set, the do_*_at() wrappers resolve their path as an OPERATOR-supplied
554 * directory path (an absolute or relative --backup-dir/--temp-dir/--*-dest)
555 * using the ownership walk -- follow a symlink owned by uid 0 or our euid,
556 * refuse any other-uid one, at every component -- instead of the stricter
557 * transfer-path resolver (which refuses all symlinks and is confined beneath the
558 * transfer root). An operator path may legitimately point outside the tree, so
559 * the trust signal is authority (ownership), not location. Set around the
560 * relevant ops by backup.c et al.; the opt-out (--insecure-links / "insecure
561 * links =") restores legacy following. Default 0 (transfer-path resolver). */
562 int operator_path_resolve = 0;
563
564 #if defined AT_FDCWD && defined O_NOFOLLOW && defined O_DIRECTORY
565 /* For an operator-supplied path: open its parent directory via the ownership
566 * walk (handles absolute and relative paths) and point *bname at the final
567 * component. Returns the dirfd (caller closes) or -1 with errno set. */
568 int owner_walk_parent(const char *path, const char **bname)
569 {
570 const char *slash = strrchr(path, '/');
571 char dir[MAXPATHLEN], pabs[MAXPATHLEN];
572 size_t dlen;
573 int dfd;
574
575 *bname = slash ? slash + 1 : path;
576 pabs[0] = '\0';
577 if (!slash)
578 dfd = ona_open(".", O_RDONLY | O_DIRECTORY, 0, pabs, sizeof pabs);
579 else {
580 dlen = slash == path ? 1 : (size_t)(slash - path); /* "/x" -> parent "/" */
581 if (dlen >= sizeof dir) {
582 errno = ENAMETOOLONG;
583 return -1;
584 }
585 memcpy(dir, path, dlen);
586 dir[dlen] = '\0';
587 dfd = ona_open(dir, O_RDONLY | O_DIRECTORY, 0, pabs, sizeof pabs);
588 }
589 if (dfd < 0)
590 return -1;
591 /* owner_walk only resolved the PARENT; check the resolved leaf too, so a
592 * symlinked operator path cannot act on a leaf that resolves OUTSIDE the
593 * module in an otherwise-served dir. (The module exclude/filter is name-
594 * based and not enforced here -- see abspath_outside_confinement.) */
595 if (pabs[0]) {
596 char leafabs[MAXPATHLEN];
597 if (snprintf(leafabs, sizeof leafabs, "%s/%s", pabs, *bname) >= (int)sizeof leafabs) {
598 close(dfd);
599 errno = ENAMETOOLONG; /* fail closed, never skip the check */
600 return -1;
601 }
602 if (abspath_outside_confinement(leafabs)) {
603 close(dfd);
604 errno = ELOOP;
605 return -1;
606 }
607 }
608 return dfd;
609 }
610 #endif
611
612 #ifndef S_BLKSIZE
613 # if defined hpux || defined __hpux__ || defined __hpux
614 # define S_BLKSIZE 1024
615 # elif defined _AIX && defined _I386
616 # define S_BLKSIZE 4096
617 # else
618 # define S_BLKSIZE 512
619 # endif
620 #endif
621
622 #ifdef SUPPORT_CRTIMES
623 #ifdef HAVE_GETATTRLIST
624 #pragma pack(push, 4)
625 struct create_time {
626 uint32 length;
627 struct timespec crtime;
628 };
629 #pragma pack(pop)
630 #elif defined __CYGWIN__
631 #include <windows.h>
632 #endif
633 #endif
634
635 #define RETURN_ERROR_IF(x,e) \
636 do { \
637 if (x) { \
638 errno = (e); \
639 return -1; \
640 } \
641 } while (0)
642
643 #define RETURN_ERROR_IF_RO_OR_LO RETURN_ERROR_IF(read_only || list_only, EROFS)
644
645 /* A NULL path reaching one of the path-forwarding wrappers below is always a
646 * caller bug; reject it rather than forwarding NULL to libc. Also quiets the
647 * static analyzer's interprocedural nonnull false positives. */
648 #define RETURN_ERROR_IF_NULL(p) RETURN_ERROR_IF(!(p), EFAULT)
649
650 int do_unlink(const char *path)
651 {
652 if (dry_run) return 0;
653 RETURN_ERROR_IF_RO_OR_LO;
654 return unlink(path);
655 }
656
657 /*
658 Symlink-race-safe variant of do_unlink() for receiver-side use. See
659 the comment on do_chmod_at() for the threat model. unlink() resolves
660 parent components, so a parent-symlink swap can delete an outside
661 file under the daemon's authority. Defence: open the parent of path
662 under secure_relative_open() and use unlinkat() (flags=0) against
663 that dirfd.
664
665 Falls through to do_unlink() for the same dry-run / non-daemon /
666 chrooted / no-parent / absolute-path cases as the other wrappers.
667 */
668 int do_unlink_at(const char *path)
669 {
670 #ifdef AT_FDCWD
671 extern int am_daemon, am_chrooted;
672 char dirpath[MAXPATHLEN];
673 const char *bname;
674 const char *slash;
675 int dfd, ret, e;
676 size_t dlen;
677
678 if (dry_run) return 0;
679 RETURN_ERROR_IF_RO_OR_LO;
680 RETURN_ERROR_IF_NULL(path);
681
682 #if defined O_NOFOLLOW && defined O_DIRECTORY
683 if (operator_path_resolve) {
684 if (symlink_optout_allowed())
685 return unlink(path);
686 dfd = owner_walk_parent(path, &bname);
687 if (dfd < 0)
688 return -1;
689 ret = unlinkat(dfd, bname, 0);
690 e = errno;
691 close(dfd);
692 errno = e;
693 return ret;
694 }
695 #endif
696
697 if (!secure_relpath_active())
698 return unlink(path);
699
700 if (!path || !*path || *path == '/')
701 return unlink(path);
702
703 slash = strrchr(path, '/');
704 if (!slash)
705 return unlink(path);
706
707 dlen = slash - path;
708 if (dlen >= sizeof dirpath) {
709 errno = ENAMETOOLONG;
710 return -1;
711 }
712 memcpy(dirpath, path, dlen);
713 dirpath[dlen] = '\0';
714 bname = slash + 1;
715
716 dfd = secure_relative_open(NULL, dirpath, O_RDONLY | O_DIRECTORY, 0);
717 if (dfd < 0)
718 return -1;
719
720 ret = unlinkat(dfd, bname, 0);
721 e = errno;
722 close(dfd);
723 errno = e;
724 return ret;
725 #else
726 return do_unlink(path);
727 #endif
728 }
729
730 #ifdef SUPPORT_LINKS
731 int do_symlink(const char *lnk, const char *path)
732 {
733 if (dry_run) return 0;
734 RETURN_ERROR_IF_RO_OR_LO;
735 RETURN_ERROR_IF_NULL(lnk);
736 RETURN_ERROR_IF_NULL(path);
737
738 #if defined NO_SYMLINK_XATTRS || defined NO_SYMLINK_USER_XATTRS
739 /* For --fake-super, we create a normal file with mode 0600
740 * and write the lnk into it. */
741 if (am_root < 0) {
742 int ok, len = strlen(lnk);
743 int fd = open(path, O_WRONLY|O_CREAT|O_TRUNC, S_IWUSR|S_IRUSR);
744 if (fd < 0)
745 return -1;
746 ok = write(fd, lnk, len) == len;
747 if (close(fd) < 0)
748 ok = 0;
749 return ok ? 0 : -1;
750 }
751 #endif
752
753 return symlink(lnk, path);
754 }
755
756 /*
757 Symlink-race-safe variant of do_symlink() for receiver-side use. See
758 the comment on do_chmod_at() for the threat model. For a real symlink
759 only the parent directory of `path` needs protection -- symlinkat()
760 does not resolve the final component (it creates it). Defence: open
761 the parent of `path` under secure_relative_open() and call symlinkat()
762 against that dirfd; a top-level (no-slash) path has no parent to
763 confine, so it uses AT_FDCWD directly. The link target string `lnk` is
764 stored verbatim and not resolved at creation time, so it doesn't need
765 scrutiny here.
766
767 For --fake-super (am_root < 0) the "symlink" is written as a regular
768 file, so the final component IS resolved at creation: we create it
769 with openat(... O_NOFOLLOW) so a pre-planted symlink at the basename
770 cannot redirect the write outside the module. This protection applies
771 to top-level paths too -- the previous code fell through to the
772 bare-path do_symlink() there, whose plain open() followed such a
773 symlink.
774 */
775 int do_symlink_at(const char *lnk, const char *path)
776 {
777 #ifdef AT_FDCWD
778 extern int am_daemon, am_chrooted;
779 char dirpath[MAXPATHLEN];
780 const char *bname;
781 const char *slash;
782 int dfd = AT_FDCWD, ret, e;
783 BOOL owns = False;
784 size_t dlen;
785
786 if (dry_run) return 0;
787 RETURN_ERROR_IF_RO_OR_LO;
788
789 #if defined O_NOFOLLOW && defined O_DIRECTORY
790 if (operator_path_resolve) {
791 /* Operator path (e.g. an absolute --backup-dir): confine the
792 * parent with the ownership walk, then fall through to the shared
793 * leaf-creation below so fake-super emulation is preserved. */
794 if (symlink_optout_allowed())
795 return do_symlink(lnk, path);
796 dfd = owner_walk_parent(path, &bname);
797 if (dfd < 0)
798 return -1;
799 owns = True;
800 } else
801 #endif
802 {
803 if (!secure_relpath_active())
804 return do_symlink(lnk, path);
805
806 if (!path || !*path || *path == '/')
807 return do_symlink(lnk, path);
808
809 /* A path with a slash needs secure_relative_open to confine its
810 * parent; a top-level path is in CWD (AT_FDCWD), no parent to
811 * subvert. The leaf is protected below either way (symlinkat()
812 * won't follow it; the fake-super openat() uses O_NOFOLLOW). */
813 slash = strrchr(path, '/');
814 if (slash) {
815 dlen = slash - path;
816 if (dlen >= sizeof dirpath) {
817 errno = ENAMETOOLONG;
818 return -1;
819 }
820 memcpy(dirpath, path, dlen);
821 dirpath[dlen] = '\0';
822 bname = slash + 1;
823 dfd = secure_relative_open(NULL, dirpath, O_RDONLY | O_DIRECTORY, 0);
824 if (dfd < 0)
825 return -1;
826 owns = True;
827 } else {
828 bname = path;
829 }
830 }
831
832 #if defined NO_SYMLINK_XATTRS || defined NO_SYMLINK_USER_XATTRS
833 /* For --fake-super, do_symlink writes the link target into a
834 * regular file rather than creating a real symlink. Do that here
835 * against the (secure or AT_FDCWD) dirfd, with O_NOFOLLOW so a pre-
836 * planted symlink at the basename can't redirect the file creation. */
837 if (am_root < 0) {
838 int len = strlen(lnk);
839 int fd = openat(dfd, bname,
840 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW,
841 S_IWUSR | S_IRUSR);
842 if (fd < 0) {
843 e = errno;
844 if (owns) close(dfd);
845 errno = e;
846 return -1;
847 }
848 ret = (write(fd, lnk, len) == len) ? 0 : -1;
849 if (close(fd) < 0)
850 ret = -1;
851 e = errno;
852 if (owns) close(dfd);
853 errno = e;
854 return ret;
855 }
856 #endif
857
858 ret = symlinkat(lnk, dfd, bname);
859 e = errno;
860 if (owns) close(dfd);
861 errno = e;
862 return ret;
863 #else
864 return do_symlink(lnk, path);
865 #endif
866 }
867
868 /* NOFOLLOW_HIT_SYMLINK() lives in rsync.h (shared with util1.c's change_dir). */
869
870 #if defined NO_SYMLINK_XATTRS || defined NO_SYMLINK_USER_XATTRS
871 ssize_t do_readlink(const char *path, char *buf, size_t bufsiz)
872 {
873 /* For --fake-super, we read the link from the file. */
874 if (am_root < 0) {
875 int fd = do_open_nofollow(path, O_RDONLY);
876 if (fd >= 0) {
877 int len = read(fd, buf, bufsiz);
878 close(fd);
879 return len;
880 }
881 if (!NOFOLLOW_HIT_SYMLINK(errno))
882 return -1;
883 /* A real symlink needs to be turned into a fake one on the receiving
884 * side, so tell the generator that the link has no length. */
885 if (!am_sender)
886 return 0;
887 /* Otherwise fall through and let the sender report the real length. */
888 }
889
890 return readlink(path, buf, bufsiz);
891 }
892 #endif
893
894 ssize_t do_readlink_atfd(int dfd, const char *name, char *buf, size_t bufsiz)
895 {
896 #ifdef AT_FDCWD
897 # if defined NO_SYMLINK_XATTRS || defined NO_SYMLINK_USER_XATTRS
898 if (am_root < 0) {
899 int fd = openat(dfd, name, O_RDONLY | O_NOFOLLOW);
900 if (fd >= 0) {
901 int len = read(fd, buf, bufsiz);
902 close(fd);
903 return len;
904 }
905 if (!NOFOLLOW_HIT_SYMLINK(errno))
906 return -1;
907 if (!am_sender)
908 return 0;
909 }
910 # endif
911 return readlinkat(dfd, name, buf, bufsiz);
912 #else
913 (void)dfd;
914 return do_readlink(name, buf, bufsiz);
915 #endif
916 }
917 #endif
918
919 #if defined HAVE_LINK || defined HAVE_LINKAT
920 int do_link(const char *old_path, const char *new_path)
921 {
922 if (dry_run) return 0;
923 RETURN_ERROR_IF_RO_OR_LO;
924 RETURN_ERROR_IF_NULL(old_path);
925 RETURN_ERROR_IF_NULL(new_path);
926 #ifdef HAVE_LINKAT
927 return linkat(AT_FDCWD, old_path, AT_FDCWD, new_path, 0);
928 #else
929 return link(old_path, new_path);
930 #endif
931 }
932
933 /*
934 Symlink-race-safe variant of do_link() for receiver-side use. See
935 the comment on do_chmod_at() for the threat model. link() resolves
936 parent components of *both* old_path and new_path, so a parent-
937 symlink swap on either side can plant the new hard link outside
938 the module, or hard-link an outside file into the module (read
939 disclosure).
940
941 Defence: open each parent under secure_relative_open() and use
942 linkat() between the two dirfds, reusing one when the parents
943 match. flags=0 matches the existing do_link() (don't follow a
944 symbolic-link old_path). Only available on systems with linkat();
945 pre-AT_FDCWD systems fall through to do_link().
946 */
947 int do_link_at(const char *old_path, const char *new_path)
948 {
949 #if defined AT_FDCWD && defined HAVE_LINKAT
950 extern int am_daemon, am_chrooted;
951 char old_dirpath[MAXPATHLEN], new_dirpath[MAXPATHLEN];
952 const char *old_bname, *new_bname;
953 const char *old_slash, *new_slash;
954 int old_dfd = AT_FDCWD, new_dfd = AT_FDCWD;
955 BOOL old_owns = False, new_owns = False;
956 int ret, e;
957 size_t old_dlen = 0, new_dlen = 0;
958
959 if (dry_run) return 0;
960 RETURN_ERROR_IF_RO_OR_LO;
961
962 if (!secure_relpath_active())
963 return do_link(old_path, new_path);
964
965 if (!old_path || !*old_path || !new_path || !*new_path)
966 return do_link(old_path, new_path);
967
968 #if defined O_NOFOLLOW && defined O_DIRECTORY
969 /* Operator-supplied path (a --backup-dir/--link-dest side): resolve each
970 * parent via the ownership walk (follow uid0/euid symlinks, refuse others). */
971 if (operator_path_resolve) {
972 if (symlink_optout_allowed())
973 return do_link(old_path, new_path);
974 old_dfd = owner_walk_parent(old_path, &old_bname);
975 if (old_dfd < 0)
976 return -1;
977 new_dfd = owner_walk_parent(new_path, &new_bname);
978 if (new_dfd < 0) {
979 e = errno;
980 close(old_dfd);
981 errno = e;
982 return -1;
983 }
984 ret = linkat(old_dfd, old_bname, new_dfd, new_bname, 0);
985 e = errno;
986 close(new_dfd);
987 close(old_dfd);
988 errno = e;
989 return ret;
990 }
991 #endif
992
993 old_slash = strrchr(old_path, '/');
994 new_slash = strrchr(new_path, '/');
995
996 /* Resolve each path's parent dir independently. A path without a
997 * slash lives in CWD (AT_FDCWD), no parent open required. A path
998 * with a slash needs secure_relative_open to confine its parent
999 * resolution -- otherwise a parent symlink (e.g. --link-dest=cd
1000 * where cd -> /outside) lets the kernel-level linkat(AT_FDCWD,
1001 * "cd/target.txt", ...) escape the module. An absolute path uses
1002 * AT_FDCWD + the full path; each side is confined independently, so an
1003 * absolute source (e.g. an absolute --link-dest) cannot disable
1004 * confinement of a relative destination. An absolute side is an operator
1005 * path resolved via the ownership walk (foreign-owned parent symlink refused;
1006 * --insecure-links keeps the legacy AT_FDCWD path). */
1007 if (*old_path == '/') {
1008 #if defined O_NOFOLLOW && defined O_DIRECTORY
1009 if (!symlink_optout_allowed()) {
1010 operator_path_resolve = 1; /* operator side: enforce module-exclude */
1011 old_dfd = owner_walk_parent(old_path, &old_bname);
1012 operator_path_resolve = 0;
1013 if (old_dfd < 0)
1014 return -1;
1015 old_owns = True;
1016 } else
1017 #endif
1018 old_bname = old_path;
1019 } else if (old_slash) {
1020 old_dlen = old_slash - old_path;
1021 if (old_dlen >= sizeof old_dirpath) { errno = ENAMETOOLONG; return -1; }
1022 memcpy(old_dirpath, old_path, old_dlen);
1023 old_dirpath[old_dlen] = '\0';
1024 old_bname = old_slash + 1;
1025 old_dfd = secure_relative_open(NULL, old_dirpath, O_RDONLY | O_DIRECTORY, 0);
1026 if (old_dfd < 0)
1027 return -1;
1028 old_owns = True;
1029 } else {
1030 old_bname = old_path;
1031 }
1032
1033 if (*new_path == '/') {
1034 #if defined O_NOFOLLOW && defined O_DIRECTORY
1035 if (!symlink_optout_allowed()) {
1036 operator_path_resolve = 1; /* operator side: enforce module-exclude */
1037 new_dfd = owner_walk_parent(new_path, &new_bname);
1038 operator_path_resolve = 0;
1039 if (new_dfd < 0) {
1040 e = errno;
1041 if (old_owns) close(old_dfd);
1042 errno = e;
1043 return -1;
1044 }
1045 new_owns = True;
1046 } else
1047 #endif
1048 new_bname = new_path;
1049 } else if (new_slash) {
1050 new_dlen = new_slash - new_path;
1051 if (new_dlen >= sizeof new_dirpath) {
1052 e = ENAMETOOLONG;
1053 if (old_owns) close(old_dfd);
1054 errno = e;
1055 return -1;
1056 }
1057 memcpy(new_dirpath, new_path, new_dlen);
1058 new_dirpath[new_dlen] = '\0';
1059 new_bname = new_slash + 1;
1060 if (old_owns && old_dlen == new_dlen
1061 && memcmp(old_dirpath, new_dirpath, old_dlen) == 0) {
1062 new_dfd = old_dfd;
1063 } else {
1064 new_dfd = secure_relative_open(NULL, new_dirpath, O_RDONLY | O_DIRECTORY, 0);
1065 if (new_dfd < 0) {
1066 e = errno;
1067 if (old_owns) close(old_dfd);
1068 errno = e;
1069 return -1;
1070 }
1071 new_owns = True;
1072 }
1073 } else {
1074 new_bname = new_path;
1075 }
1076
1077 ret = linkat(old_dfd, old_bname, new_dfd, new_bname, 0);
1078 e = errno;
1079 if (new_owns)
1080 close(new_dfd);
1081 if (old_owns)
1082 close(old_dfd);
1083 errno = e;
1084 return ret;
1085 #else
1086 return do_link(old_path, new_path);
1087 #endif
1088 }
1089 #endif
1090
1091 int do_lchown(const char *path, uid_t owner, gid_t group)
1092 {
1093 if (dry_run) return 0;
1094 RETURN_ERROR_IF_RO_OR_LO;
1095 RETURN_ERROR_IF_NULL(path);
1096 #ifndef HAVE_LCHOWN
1097 #define lchown chown
1098 #endif
1099 return lchown(path, owner, group);
1100 }
1101
1102 /*
1103 Symlink-race-safe variant of do_lchown() for receiver-side use. See the
1104 comment on do_chmod_at() for the threat model and design rationale.
1105
1106 Resolves the parent directory under secure_relative_open() and invokes
1107 fchownat(..., AT_SYMLINK_NOFOLLOW) against that dirfd, so that an
1108 attacker who substitutes a symlink into one of the parent components
1109 cannot redirect the chown outside the receiver's confinement. The
1110 AT_SYMLINK_NOFOLLOW flag matches lchown()'s "do not follow a final-
1111 component symlink" semantics.
1112
1113 Falls through to do_lchown() in the dry-run / non-daemon / chrooted /
1114 absolute-path / no-parent cases, identical to do_chmod_at().
1115 */
1116 int do_lchown_at(const char *fname, uid_t owner, gid_t group)
1117 {
1118 #if defined AT_FDCWD && defined AT_SYMLINK_NOFOLLOW
1119 extern int am_daemon, am_chrooted;
1120 char dirpath[MAXPATHLEN];
1121 const char *bname;
1122 const char *slash;
1123 int dfd, ret, e;
1124 size_t dlen;
1125
1126 if (dry_run) return 0;
1127 RETURN_ERROR_IF_RO_OR_LO;
1128
1129 #if defined O_NOFOLLOW && defined O_DIRECTORY
1130 /* Operator-supplied path: resolve the parent via the ownership walk, as
1131 * the other do_*_at() wrappers do. Without this the caller's
1132 * operator_path_resolve has no effect here, and an absolute name would
1133 * fall straight through to the unconfined full-path do_lchown(). */
1134 if (operator_path_resolve && fname && *fname) {
1135 if (symlink_optout_allowed())
1136 return do_lchown(fname, owner, group);
1137 dfd = owner_walk_parent(fname, &bname);
1138 if (dfd < 0)
1139 return -1;
1140 ret = fchownat(dfd, bname, owner, group, AT_SYMLINK_NOFOLLOW);
1141 e = errno;
1142 close(dfd);
1143 errno = e;
1144 return ret;
1145 }
1146 #endif
1147
1148 if (!secure_relpath_active())
1149 return do_lchown(fname, owner, group);
1150
1151 if (!fname || !*fname || *fname == '/')
1152 return do_lchown(fname, owner, group);
1153
1154 slash = strrchr(fname, '/');
1155 if (!slash)
1156 return do_lchown(fname, owner, group);
1157
1158 dlen = slash - fname;
1159 if (dlen >= sizeof dirpath) {
1160 errno = ENAMETOOLONG;
1161 return -1;
1162 }
1163 memcpy(dirpath, fname, dlen);
1164 dirpath[dlen] = '\0';
1165 bname = slash + 1;
1166
1167 dfd = secure_relative_open(NULL, dirpath, O_RDONLY | O_DIRECTORY, 0);
1168 if (dfd < 0)
1169 return -1;
1170
1171 ret = fchownat(dfd, bname, owner, group, AT_SYMLINK_NOFOLLOW);
1172 e = errno;
1173 close(dfd);
1174 errno = e;
1175 return ret;
1176 #else
1177 return do_lchown(fname, owner, group);
1178 #endif
1179 }
1180
1181 int do_mknod(const char *pathname, mode_t mode, dev_t dev)
1182 {
1183 if (dry_run) return 0;
1184 RETURN_ERROR_IF_RO_OR_LO;
1185 RETURN_ERROR_IF_NULL(pathname);
1186
1187 /* For --fake-super, we create a normal file with mode 0600. */
1188 if (am_root < 0) {
1189 int fd = open(pathname, O_WRONLY|O_CREAT|O_TRUNC, S_IWUSR|S_IRUSR);
1190 if (fd < 0 || close(fd) < 0)
1191 return -1;
1192 return 0;
1193 }
1194
1195 /* Try mknod first: it handles every node type on Linux. Only if it
1196 * can't make this type on this filesystem (sockets on the BSDs/macOS/
1197 * Solaris, or an old system lacking FIFO support) do we retry with the
1198 * type-specific primitive. That capability is filesystem-dependent, so
1199 * it is decided per call -- not cached, not probed at build time. */
1200 #ifdef HAVE_MKNOD
1201 if (mknod(pathname, mode, dev) == 0)
1202 return 0;
1203 #endif
1204 #ifdef HAVE_MKFIFO
1205 if (S_ISFIFO(mode))
1206 return mkfifo(pathname, mode);
1207 #endif
1208 #ifdef HAVE_SYS_UN_H
1209 if (S_ISSOCK(mode)) {
1210 int sock;
1211 struct sockaddr_un saddr;
1212 unsigned int len = strlcpy(saddr.sun_path, pathname, sizeof saddr.sun_path);
1213 if (len >= sizeof saddr.sun_path) {
1214 errno = ENAMETOOLONG;
1215 return -1;
1216 }
1217 #ifdef HAVE_SOCKADDR_UN_LEN
1218 saddr.sun_len = len + 1;
1219 #endif
1220 saddr.sun_family = AF_UNIX;
1221
1222 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0
1223 || (unlink(pathname) < 0 && errno != ENOENT)
1224 || (bind(sock, (struct sockaddr*)&saddr, sizeof saddr)) < 0)
1225 return -1;
1226 close(sock);
1227 #ifdef HAVE_CHMOD
1228 return do_chmod(pathname, mode);
1229 #else
1230 return 0;
1231 #endif
1232 }
1233 #endif
1234 #ifdef HAVE_MKNOD
1235 return -1; /* mknod() failed for a regular/device node; errno is set */
1236 #else
1237 errno = ENOSYS;
1238 return -1;
1239 #endif
1240 }
1241
1242 /*
1243 Symlink-race-safe variant of do_mknod() for receiver-side use. See
1244 the comment on do_chmod_at() for the threat model. Defence: open
1245 the parent of pathname under secure_relative_open() and use
1246 mknodat() against that dirfd. mknodat() covers both regular-file
1247 (S_IFREG with dev=0) and FIFO (S_IFIFO) and device-node creation.
1248
1249 A top-level (no-slash) pathname has no parent to confine, so it uses
1250 AT_FDCWD; the final component is still protected (mknodat/mkfifoat do
1251 not follow it, and the fake-super openat() uses O_NOFOLLOW).
1252
1253 Fake-super (am_root < 0) is handled inline against the (secure or
1254 AT_FDCWD) dirfd: it creates a regular empty file (the same file-as-
1255 metadata-placeholder pattern do_mknod uses) via openat() with
1256 O_NOFOLLOW so a pre-planted symlink at the basename can't redirect
1257 the file creation -- top-level paths included (the previous code fell
1258 through to the bare-path do_mknod() there, whose plain open() followed
1259 such a symlink). On Linux, sockets are recreated with mknodat() like any
1260 other special file; on systems where mknod() can't create sockets the
1261 at-variant fails instead of re-resolving an unsafe parent.
1262 */
1263 int do_mknod_at(const char *pathname, mode_t mode, dev_t dev)
1264 {
1265 /* HAVE_MKNODAT: older Darwin declares AT_FDCWD but not mknodat(), so
1266 * the at-variant won't build there; fall back to do_mknod() (#896). */
1267 #if defined(AT_FDCWD) && defined(HAVE_MKNODAT)
1268 extern int am_daemon, am_chrooted;
1269 char dirpath[MAXPATHLEN];
1270 const char *bname;
1271 const char *slash;
1272 int dfd = AT_FDCWD, ret, e;
1273 BOOL owns = False;
1274 size_t dlen;
1275
1276 if (dry_run) return 0;
1277 RETURN_ERROR_IF_RO_OR_LO;
1278
1279 #if defined O_NOFOLLOW && defined O_DIRECTORY
1280 if (operator_path_resolve) {
1281 if (symlink_optout_allowed())
1282 return do_mknod(pathname, mode, dev);
1283 dfd = owner_walk_parent(pathname, &bname);
1284 if (dfd < 0)
1285 return -1;
1286 if (am_root < 0) {
1287 /* Fake-super represents a special file with an inert regular
1288 * placeholder. Keep that representation when the destination
1289 * is an operator path, but create it relative to the verified
1290 * parent so the confinement guarantee is unchanged. */
1291 int fd = openat(dfd, bname,
1292 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW,
1293 S_IWUSR | S_IRUSR);
1294 ret = fd < 0 ? -1 : close(fd);
1295 } else {
1296 ret = mknodat(dfd, bname, mode, dev);
1297 }
1298 if (ret < 0 && am_root >= 0) {
1299 /* mknodat() can't make a FIFO/socket on the BSDs/macOS/
1300 * Solaris (EINVAL); retry race-safely on the held dirfd,
1301 * mirroring the secure-relpath path below. Without this a
1302 * FIFO backup to an operator --backup-dir fails there. */
1303 #ifdef HAVE_MKFIFOAT
1304 if (S_ISFIFO(mode))
1305 ret = mkfifoat(dfd, bname, mode);
1306 else
1307 #endif
1308 if (S_ISSOCK(mode))
1309 errno = EOPNOTSUPP; /* no dirfd-relative socket bind */
1310 }
1311 e = errno;
1312 close(dfd);
1313 errno = e;
1314 return ret;
1315 }
1316 #endif
1317
1318 if (!secure_relpath_active())
1319 return do_mknod(pathname, mode, dev);
1320
1321 if (!pathname || !*pathname || *pathname == '/')
1322 return do_mknod(pathname, mode, dev);
1323
1324 /* A path with a slash needs secure_relative_open to confine its
1325 * parent resolution; a top-level path lives in CWD (AT_FDCWD) with
1326 * no parent to subvert. The final component is protected below
1327 * regardless. */
1328 slash = strrchr(pathname, '/');
1329 if (slash) {
1330 dlen = slash - pathname;
1331 if (dlen >= sizeof dirpath) {
1332 errno = ENAMETOOLONG;
1333 return -1;
1334 }
1335 memcpy(dirpath, pathname, dlen);
1336 dirpath[dlen] = '\0';
1337 bname = slash + 1;
1338 dfd = secure_relative_open(NULL, dirpath, O_RDONLY | O_DIRECTORY, 0);
1339 if (dfd < 0)
1340 return -1;
1341 owns = True;
1342 } else {
1343 bname = pathname;
1344 }
1345
1346 if (am_root < 0) {
1347 /* For --fake-super, do_mknod creates a regular empty
1348 * file as a placeholder for the special-file metadata
1349 * (which is stored in xattrs elsewhere). Do that against
1350 * the (secure or AT_FDCWD) dirfd, with O_NOFOLLOW so a
1351 * pre-planted symlink at the basename can't redirect the
1352 * file creation. */
1353 int fd = openat(dfd, bname,
1354 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW,
1355 S_IWUSR | S_IRUSR);
1356 if (fd < 0) {
1357 e = errno;
1358 if (owns) close(dfd);
1359 errno = e;
1360 return -1;
1361 }
1362 ret = (close(fd) < 0) ? -1 : 0;
1363 e = errno;
1364 if (owns) close(dfd);
1365 errno = e;
1366 return ret;
1367 }
1368
1369 /* Try mknodat first (handles every type on Linux); on failure retry
1370 * race-safely with the type-specific primitive. Decided per call --
1371 * the capability is filesystem-dependent (see do_mknod()). */
1372 ret = mknodat(dfd, bname, mode, dev);
1373 if (ret < 0) {
1374 #ifdef HAVE_MKFIFOAT
1375 if (S_ISFIFO(mode))
1376 ret = mkfifoat(dfd, bname, mode);
1377 else
1378 #endif
1379 if (S_ISSOCK(mode)) {
1380 /* There is no dirfd-relative socket bind without
1381 * /proc/self/fd: a top-level path can bind via
1382 * do_mknod(), but a nested one fails safe rather than
1383 * re-resolve a potentially unsafe parent. */
1384 if (dfd == AT_FDCWD)
1385 ret = do_mknod(pathname, mode, dev);
1386 else
1387 errno = EOPNOTSUPP;
1388 }
1389 /* else: regular/device node -- keep mknodat()'s errno */
1390 }
1391 e = errno;
1392 if (owns) close(dfd);
1393 errno = e;
1394 return ret;
1395 #else
1396 return do_mknod(pathname, mode, dev);
1397 #endif
1398 }
1399
1400 int do_rmdir(const char *pathname)
1401 {
1402 if (dry_run) return 0;
1403 RETURN_ERROR_IF_RO_OR_LO;
1404 return rmdir(pathname);
1405 }
1406
1407 /*
1408 Symlink-race-safe variant of do_rmdir(). See do_unlink_at() above;
1409 same shape but with AT_REMOVEDIR set to require the target be a
1410 directory.
1411 */
1412 int do_rmdir_at(const char *pathname)
1413 {
1414 #ifdef AT_FDCWD
1415 extern int am_daemon, am_chrooted;
1416 char dirpath[MAXPATHLEN];
1417 const char *bname;
1418 const char *slash;
1419 int dfd, ret, e;
1420 size_t dlen;
1421
1422 if (dry_run) return 0;
1423 RETURN_ERROR_IF_RO_OR_LO;
1424 RETURN_ERROR_IF_NULL(pathname);
1425
1426 #if defined O_NOFOLLOW && defined O_DIRECTORY
1427 if (operator_path_resolve) {
1428 if (symlink_optout_allowed())
1429 return do_rmdir(pathname);
1430 dfd = owner_walk_parent(pathname, &bname);
1431 if (dfd < 0)
1432 return -1;
1433 ret = unlinkat(dfd, bname, AT_REMOVEDIR);
1434 e = errno;
1435 close(dfd);
1436 errno = e;
1437 return ret;
1438 }
1439 #endif
1440
1441 if (!secure_relpath_active())
1442 return rmdir(pathname);
1443
1444 if (!pathname || !*pathname || *pathname == '/')
1445 return rmdir(pathname);
1446
1447 slash = strrchr(pathname, '/');
1448 if (!slash)
1449 return rmdir(pathname);
1450
1451 dlen = slash - pathname;
1452 if (dlen >= sizeof dirpath) {
1453 errno = ENAMETOOLONG;
1454 return -1;
1455 }
1456 memcpy(dirpath, pathname, dlen);
1457 dirpath[dlen] = '\0';
1458 bname = slash + 1;
1459
1460 dfd = secure_relative_open(NULL, dirpath, O_RDONLY | O_DIRECTORY, 0);
1461 if (dfd < 0)
1462 return -1;
1463
1464 ret = unlinkat(dfd, bname, AT_REMOVEDIR);
1465 e = errno;
1466 close(dfd);
1467 errno = e;
1468 return ret;
1469 #else
1470 return do_rmdir(pathname);
1471 #endif
1472 }
1473
1474 int do_open(const char *pathname, int flags, mode_t mode)
1475 {
1476 RETURN_ERROR_IF_NULL(pathname);
1477 if (flags != O_RDONLY) {
1478 RETURN_ERROR_IF(dry_run, 0);
1479 RETURN_ERROR_IF_RO_OR_LO;
1480 }
1481
1482 #ifdef O_NOATIME
1483 if (open_noatime)
1484 flags |= O_NOATIME;
1485 #endif
1486
1487 return open(pathname, flags | O_BINARY, mode);
1488 }
1489
1490 /*
1491 Symlink-race-safe variant of do_open() for receiver-side use. See
1492 the comment on do_chmod_at() for the threat model. open() resolves
1493 parent components, so a parent-symlink swap can redirect the open
1494 to a file outside the module. This wrapper is defence-in-depth for
1495 bare-path do_open() sites that callers know are otherwise
1496 protected by secure parent-syscalls (e.g. generator.c's in-place
1497 backup creation, where robust_unlink() rejects the symlinked
1498 parent before this open is reached): if any of those upstream
1499 protections is later removed or regresses, the open here still
1500 refuses to escape the module.
1501
1502 Defence: open the parent of pathname under secure_relative_open()
1503 and call openat() against the resulting dirfd with O_NOFOLLOW
1504 (so the basename itself isn't followed if it happens to be a
1505 pre-planted symlink, which is what we want for O_CREAT|O_EXCL).
1506 */
1507 int do_open_at(const char *pathname, int flags, mode_t mode)
1508 {
1509 #ifdef AT_FDCWD
1510 extern int am_daemon, am_chrooted;
1511 char dirpath[MAXPATHLEN];
1512 const char *bname;
1513 const char *slash;
1514 int dfd, ret, e;
1515 size_t dlen;
1516
1517 if (flags != O_RDONLY) {
1518 RETURN_ERROR_IF(dry_run, 0);
1519 RETURN_ERROR_IF_RO_OR_LO;
1520 }
1521
1522 #if defined O_NOFOLLOW && defined O_DIRECTORY
1523 if (operator_path_resolve) {
1524 if (symlink_optout_allowed())
1525 return do_open(pathname, flags, mode);
1526 dfd = owner_walk_parent(pathname, &bname);
1527 if (dfd < 0)
1528 return -1;
1529 ret = openat(dfd, bname, flags | O_NOFOLLOW, mode);
1530 e = errno;
1531 close(dfd);
1532 errno = e;
1533 return ret;
1534 }
1535 #endif
1536
1537 if (!secure_relpath_active())
1538 return do_open(pathname, flags, mode);
1539
1540 if (!pathname || !*pathname || *pathname == '/')
1541 return do_open(pathname, flags, mode);
1542
1543 slash = strrchr(pathname, '/');
1544 if (!slash)
1545 return do_open(pathname, flags, mode);
1546
1547 dlen = slash - pathname;
1548 if (dlen >= sizeof dirpath) {
1549 errno = ENAMETOOLONG;
1550 return -1;
1551 }
1552 memcpy(dirpath, pathname, dlen);
1553 dirpath[dlen] = '\0';
1554 bname = slash + 1;
1555
1556 dfd = secure_relative_open(NULL, dirpath, O_RDONLY | O_DIRECTORY, 0);
1557 if (dfd < 0)
1558 return -1;
1559
1560 #ifdef O_NOATIME
1561 if (open_noatime)
1562 flags |= O_NOATIME;
1563 #endif
1564
1565 ret = openat(dfd, bname, flags | O_NOFOLLOW | O_BINARY, mode);
1566 e = errno;
1567 close(dfd);
1568 errno = e;
1569 return ret;
1570 #else
1571 return do_open(pathname, flags, mode);
1572 #endif
1573 }
1574
1575 #ifdef HAVE_CHMOD
1576 int do_chmod(const char *path, mode_t mode)
1577 {
1578 static int switch_step = 0;
1579 int code;
1580
1581 if (dry_run) return 0;
1582 RETURN_ERROR_IF_RO_OR_LO;
1583 RETURN_ERROR_IF_NULL(path);
1584
1585 switch (switch_step) {
1586 #ifdef HAVE_LCHMOD
1587 case 0:
1588 if ((code = lchmod(path, mode & CHMOD_BITS)) == 0)
1589 break;
1590 if (errno == ENOSYS)
1591 switch_step++;
1592 else if (errno != ENOTSUP)
1593 break;
1594 #endif
1595 /* FALLTHROUGH */
1596 default:
1597 if (S_ISLNK(mode)) {
1598 # if defined HAVE_SETATTRLIST
1599 struct attrlist attrList;
1600 uint32_t m = mode & CHMOD_BITS; /* manpage is wrong: not mode_t! */
1601
1602 memset(&attrList, 0, sizeof attrList);
1603 attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
1604 attrList.commonattr = ATTR_CMN_ACCESSMASK;
1605 if ((code = setattrlist(path, &attrList, &m, sizeof m, FSOPT_NOFOLLOW)) == 0)
1606 break;
1607 if (errno == ENOTSUP)
1608 code = 1;
1609 # else
1610 code = 1;
1611 # endif
1612 } else
1613 code = chmod(path, mode & CHMOD_BITS); /* DISCOURAGED FUNCTION */
1614 break;
1615 }
1616 if (code != 0 && (preserve_perms || preserve_executability))
1617 return code;
1618 return 0;
1619 }
1620
1621 /* chmod `name` relative to dfd without following a final-component symlink.
1622 * The held parent fd confines the ancestors; this closes the leaf race (an
1623 * attacker swapping the leaf to a symlink that fchmodat(...,0) would follow out
1624 * of the tree).
1625 *
1626 * Never follows the leaf: a regular file or dir is pinned via
1627 * openat(O_NOFOLLOW) and chmod'd with fchmod() (leaf-safe, every kernel, and
1628 * fakeroot-wrappable unlike the raw fchmodat2() syscall); a symlink leaf is
1629 * refused (ELOOP, or EMLINK/EFTYPE on the BSDs). Other types or an open
1630 * failure fall to fchmodat(AT_SYMLINK_NOFOLLOW) (a real no-follow chmod on
1631 * glibc>=2.32 / Linux>=6.6), then the raw fchmodat2() syscall. If no
1632 * no-follow primitive exists we skip with a warning rather than follow the
1633 * leaf.
1634 *
1635 * A FIFO takes the fd path on Linux and the pathname path elsewhere -- see the
1636 * S_ISFIFO arm below for why, and for what that costs. Note the type used to
1637 * choose between them comes from the lstat above, so a leaf swapped between
1638 * that and the open is classified by what it WAS: an observed regular file or
1639 * dir that becomes a FIFO is still opened. O_NOFOLLOW rejects symlinks, not
1640 * type changes. Constraining the open to the observed type would close that;
1641 * it is not done here. */
1642 static int do_fchmodat_nofollow(int dfd, const char *name, mode_t mode)
1643 {
1644 #if defined AT_FDCWD && defined AT_SYMLINK_NOFOLLOW
1645 mode &= CHMOD_BITS;
1646 # ifdef O_NOFOLLOW
1647 {
1648 STRUCT_STAT st;
1649 int oflags = O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_NOCTTY;
1650 if (do_lstat_atfd(dfd, name, &st) < 0)
1651 return -1;
1652 if (S_ISLNK(st.st_mode)) {
1653 errno = ELOOP; /* refuse to chmod through a symlink leaf */
1654 return -1;
1655 }
1656 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode) || S_ISFIFO(st.st_mode)) {
1657 int fd;
1658 # ifndef __linux__
1659 /* Never open a FIFO here. Opening one -- even O_NONBLOCK --
1660 * makes this process a reader for as long as the descriptor
1661 * lives, which wakes a writer blocked in open(O_WRONLY) and
1662 * can cost it a SIGPIPE or the bytes it writes before we
1663 * close. The pathname call reaches the same end state
1664 * without that: it succeeds outright when the mode is
1665 * grantable, and when macOS refuses an ungrantable setgid
1666 * with EPERM (having applied nothing), asking again without
1667 * that bit gives exactly what fchmod() would have -- it drops
1668 * the bit it cannot grant and applies the ordinary ones.
1669 * Measured on macOS: fchmodat(2750) EPERM leaving 0600,
1670 * fchmodat(0750) ok giving 0750, for a FIFO and a directory
1671 * alike.
1672 *
1673 * This is a pathname call, so unlike the descriptor path it
1674 * does not pin the inode; a leaf swapped for another object
1675 * of the same name is chmod'd instead. AT_SYMLINK_NOFOLLOW
1676 * still keeps it off a symlink's target. That trade buys
1677 * away the reader hazard, and only for FIFOs.
1678 *
1679 * Only S_ISGID is retried. An ungrantable S_ISUID would
1680 * still fail where fchmod() would have cleared it, but
1681 * setuid is meaningless on a FIFO and the behaviour is
1682 * undemonstrated, so it is not coded for.
1683 *
1684 * Linux keeps the fd-first order it has always had. */
1685 if (S_ISFIFO(st.st_mode)) {
1686 if (fchmodat(dfd, name, mode, AT_SYMLINK_NOFOLLOW) == 0)
1687 return 0;
1688 if (errno == EPERM && (mode & S_ISGID)
1689 && fchmodat(dfd, name, mode & ~S_ISGID,
1690 AT_SYMLINK_NOFOLLOW) == 0)
1691 return 0;
1692 return -1;
1693 }
1694 # endif
1695 # ifdef O_CLOEXEC
1696 oflags |= O_CLOEXEC;
1697 # endif
1698 fd = openat(dfd, name, oflags);
1699 if (fd >= 0) {
1700 int r = fchmod(fd, mode), e = errno;
1701 close(fd);
1702 errno = e;
1703 return r;
1704 }
1705 /* A leaf swapped for a symlink between the lstat above and
1706 * this open: refuse rather than fall through. The errno is
1707 * not the same everywhere -- Linux/Solaris ELOOP, FreeBSD
1708 * EMLINK, NetBSD EFTYPE. */
1709 if (errno == ELOOP
1710 # ifdef EMLINK
1711 || errno == EMLINK
1712 # endif
1713 # ifdef EFTYPE
1714 || errno == EFTYPE
1715 # endif
1716 )
1717 return -1; /* raced to a symlink: refuse */
1718 /* otherwise (e.g. EACCES on an unreadable file) fall through */
1719 }
1720 }
1721 # endif
1722 # if defined __linux__
1723 {
1724 int r = fchmodat(dfd, name, mode, AT_SYMLINK_NOFOLLOW);
1725 if (r == 0)
1726 return 0;
1727 if (errno != ENOTSUP && errno != EOPNOTSUPP && errno != ENOSYS)
1728 return r; /* a real error (EPERM, ENOENT, ...) */
1729 }
1730 # ifdef SYS_fchmodat2
1731 {
1732 int r = syscall(SYS_fchmodat2, dfd, name, (unsigned int)mode, AT_SYMLINK_NOFOLLOW);
1733 if (r == 0)
1734 return 0;
1735 if (errno != ENOSYS && errno != EPERM && errno != EOPNOTSUPP)
1736 return r;
1737 }
1738 # endif
1739 /* No symlink-safe chmod primitive here: skip rather than follow the leaf. */
1740 rprintf(FWARNING, "do_chmod: no symlink-safe chmod for \"%s\"; mode not set\n", name);
1741 return 1;
1742 # else
1743 return fchmodat(dfd, name, mode, AT_SYMLINK_NOFOLLOW);
1744 # endif
1745 #else
1746 (void)dfd;
1747 (void)mode;
1748 /* No symlink-safe chmod primitive here: skip rather than follow the leaf. */
1749 rprintf(FWARNING, "do_chmod: no symlink-safe chmod for \"%s\"; mode not set\n", name);
1750 return 1;
1751 #endif
1752 }
1753
1754 /*
1755 Symlink-race-safe variant of do_chmod() for receiver-side use.
1756
1757 Threat model: on a daemon running with "use chroot = no" (the prerequisite
1758 for CVE-2026-29518), a local attacker can race a symlink swap of one of
1759 the parent directory components of a path the receiver is about to chmod.
1760 Because chmod() resolves symlinks at every component, the swap redirects
1761 the chmod outside the receiver's confinement.
1762
1763 Defence: open the *parent* directory of fname under secure_relative_open()
1764 (a portable per-component O_NOFOLLOW walk on held parent dirfds) and do
1765 fchmodat() against that dirfd. A symlink substituted into one of the parent
1766 components is then either followed within the tree (legitimate dir-symlinks
1767 still work) or rejected (escape attempts fail).
1768
1769 Final-component handling matches do_chmod(): fchmodat() with flag 0
1770 follows a symlink at the final component, which is the same behaviour as
1771 chmod() and matches every current call site (the file being chmod'd is
1772 one the receiver itself just created or transferred). For the rare case
1773 where the caller wants to chmod a symlink-as-an-object (S_ISLNK in the
1774 mode bits), we fall through to do_chmod() which has portability code for
1775 that case.
1776
1777 Falls back to do_chmod() for absolute paths and for paths with no parent
1778 component, where there is nothing to protect against.
1779 */
1780 int do_chmod_at(const char *fname, mode_t mode)
1781 {
1782 #ifdef AT_FDCWD
1783 extern int am_daemon, am_chrooted;
1784 char dirpath[MAXPATHLEN];
1785 const char *bname;
1786 const char *slash;
1787 int dfd, ret, e;
1788 size_t dlen;
1789
1790 if (dry_run) return 0;
1791 RETURN_ERROR_IF_RO_OR_LO;
1792
1793 #if defined O_NOFOLLOW && defined O_DIRECTORY
1794 /* Operator-supplied path: resolve the parent via the ownership walk, as
1795 * the other do_*_at() wrappers do. Without this the caller's
1796 * operator_path_resolve has no effect here, and an absolute name would
1797 * fall straight through to the unconfined full-path do_chmod().
1798 * S_ISLNK(mode) still needs do_chmod()'s lchmod()/setattrlist() handling. */
1799 if (operator_path_resolve && fname && *fname && !S_ISLNK(mode)) {
1800 if (symlink_optout_allowed())
1801 return do_chmod(fname, mode);
1802 dfd = owner_walk_parent(fname, &bname);
1803 if (dfd < 0)
1804 return -1;
1805 ret = do_fchmodat_nofollow(dfd, bname, mode);
1806 e = errno;
1807 close(dfd);
1808 errno = e;
1809 return ret;
1810 }
1811 #endif
1812
1813 /* Only the daemon-without-chroot case is exposed to the symlink-
1814 * race attack: a chroot already confines the receiver, and a
1815 * non-daemon rsync runs with the user's own authority so a
1816 * symlink they planted can only redirect to files they could
1817 * already access. Everywhere else, fall through to plain
1818 * do_chmod() to avoid the dirfd-open overhead on every call. */
1819 if (!secure_relpath_active())
1820 return do_chmod(fname, mode);
1821
1822 if (!fname || !*fname || *fname == '/' || S_ISLNK(mode))
1823 return do_chmod(fname, mode);
1824
1825 slash = strrchr(fname, '/');
1826 if (!slash)
1827 return do_chmod(fname, mode);
1828
1829 dlen = slash - fname;
1830 if (dlen >= sizeof dirpath) {
1831 errno = ENAMETOOLONG;
1832 return -1;
1833 }
1834 memcpy(dirpath, fname, dlen);
1835 dirpath[dlen] = '\0';
1836 bname = slash + 1;
1837
1838 dfd = secure_relative_open(NULL, dirpath, O_RDONLY | O_DIRECTORY, 0);
1839 if (dfd < 0)
1840 return -1;
1841
1842 ret = do_fchmodat_nofollow(dfd, bname, mode);
1843 e = errno;
1844 close(dfd);
1845 errno = e;
1846 return ret;
1847 #else
1848 return do_chmod(fname, mode);
1849 #endif
1850 }
1851 #endif
1852
1853 int do_rename(const char *old_path, const char *new_path)
1854 {
1855 if (dry_run) return 0;
1856 RETURN_ERROR_IF_RO_OR_LO;
1857 return rename(old_path, new_path);
1858 }
1859
1860 /*
1861 Symlink-race-safe variant of do_rename() for receiver-side use. See
1862 the comment on do_chmod_at() for the threat model and design rationale.
1863
1864 rename() is the central tmp -> final operation in rsync; if either the
1865 source or the destination has an attacker-substituted symlink in one
1866 of its parent components, the rename can publish or vanish files
1867 outside the module. Defence: open the parent of *each* path under
1868 secure_relative_open() and use renameat() against the resulting
1869 dirfds. When old_path and new_path share the same parent (the common
1870 case -- tmp file living next to its final name), we reuse the same
1871 dirfd for both sides.
1872
1873 Falls through to do_rename() in dry-run, non-daemon, chrooted and
1874 absolute-path cases, identical to the other do_*_at() wrappers.
1875 */
1876 int do_rename_at(const char *old_path, const char *new_path)
1877 {
1878 #ifdef AT_FDCWD
1879 extern int am_daemon, am_chrooted;
1880 char old_dirpath[MAXPATHLEN], new_dirpath[MAXPATHLEN];
1881 const char *old_bname, *new_bname;
1882 const char *old_slash, *new_slash;
1883 int old_dfd = AT_FDCWD, new_dfd = AT_FDCWD;
1884 BOOL old_owns = False, new_owns = False;
1885 int ret = -1, e;
1886 size_t old_dlen = 0, new_dlen = 0;
1887
1888 if (dry_run) return 0;
1889 RETURN_ERROR_IF_RO_OR_LO;
1890
1891 if (!secure_relpath_active())
1892 return do_rename(old_path, new_path);
1893
1894 if (!old_path || !*old_path || !new_path || !*new_path)
1895 return do_rename(old_path, new_path);
1896
1897 #if defined O_NOFOLLOW && defined O_DIRECTORY
1898 /* Operator-supplied path (e.g. a --backup-dir destination or a --temp-dir
1899 * source): resolve each side's parent via the ownership walk (follow
1900 * uid0/euid symlinks, refuse others; absolute and relative alike). */
1901 if (operator_path_resolve) {
1902 if (symlink_optout_allowed())
1903 return do_rename(old_path, new_path);
1904 old_dfd = owner_walk_parent(old_path, &old_bname);
1905 if (old_dfd < 0)
1906 return -1;
1907 new_dfd = owner_walk_parent(new_path, &new_bname);
1908 if (new_dfd < 0) {
1909 e = errno;
1910 close(old_dfd);
1911 errno = e;
1912 return -1;
1913 }
1914 ret = renameat(old_dfd, old_bname, new_dfd, new_bname);
1915 e = errno;
1916 close(new_dfd);
1917 close(old_dfd);
1918 errno = e;
1919 return ret;
1920 }
1921 #endif
1922
1923 old_slash = strrchr(old_path, '/');
1924 new_slash = strrchr(new_path, '/');
1925
1926 /* Confine each side independently. A *relative* side is a transfer path,
1927 * confined beneath the tree via secure_relative_open(). An *absolute* side is
1928 * an operator path (an absolute --temp-dir/--partial-dir temp file): resolve
1929 * its parent via the ownership walk so a flipped foreign-owned parent symlink
1930 * can't redirect the rename out of tree, while still allowing the operator's
1931 * own dirs/".."/uid0-or-euid symlinks. (--insecure-links keeps the legacy
1932 * unconfined AT_FDCWD path.) Doing each side independently means an absolute
1933 * source never disables confinement of a relative destination. */
1934 if (*old_path == '/') {
1935 #if defined O_NOFOLLOW && defined O_DIRECTORY
1936 if (!symlink_optout_allowed()) {
1937 operator_path_resolve = 1; /* operator side: enforce module-exclude */
1938 old_dfd = owner_walk_parent(old_path, &old_bname);
1939 operator_path_resolve = 0;
1940 if (old_dfd < 0)
1941 return -1;
1942 old_owns = True;
1943 } else
1944 #endif
1945 old_bname = old_path;
1946 } else if (old_slash) {
1947 old_dlen = old_slash - old_path;
1948 if (old_dlen >= sizeof old_dirpath) {
1949 errno = ENAMETOOLONG;
1950 return -1;
1951 }
1952 memcpy(old_dirpath, old_path, old_dlen);
1953 old_dirpath[old_dlen] = '\0';
1954 old_bname = old_slash + 1;
1955 old_dfd = secure_relative_open(NULL, old_dirpath, O_RDONLY | O_DIRECTORY, 0);
1956 if (old_dfd < 0)
1957 return -1;
1958 old_owns = True;
1959 } else {
1960 old_bname = old_path;
1961 }
1962
1963 if (*new_path == '/') {
1964 #if defined O_NOFOLLOW && defined O_DIRECTORY
1965 if (!symlink_optout_allowed()) {
1966 operator_path_resolve = 1; /* operator side: enforce module-exclude */
1967 new_dfd = owner_walk_parent(new_path, &new_bname);
1968 operator_path_resolve = 0;
1969 if (new_dfd < 0) {
1970 e = errno;
1971 if (old_owns) close(old_dfd);
1972 errno = e;
1973 return -1;
1974 }
1975 new_owns = True;
1976 } else
1977 #endif
1978 new_bname = new_path;
1979 } else if (new_slash) {
1980 new_dlen = new_slash - new_path;
1981 if (new_dlen >= sizeof new_dirpath) {
1982 e = ENAMETOOLONG;
1983 if (old_owns) close(old_dfd);
1984 errno = e;
1985 return -1;
1986 }
1987 memcpy(new_dirpath, new_path, new_dlen);
1988 new_dirpath[new_dlen] = '\0';
1989 new_bname = new_slash + 1;
1990 if (old_owns && old_dlen == new_dlen
1991 && memcmp(old_dirpath, new_dirpath, old_dlen) == 0) {
1992 new_dfd = old_dfd;
1993 } else {
1994 new_dfd = secure_relative_open(NULL, new_dirpath, O_RDONLY | O_DIRECTORY, 0);
1995 if (new_dfd < 0) {
1996 e = errno;
1997 if (old_owns) close(old_dfd);
1998 errno = e;
1999 return -1;
2000 }
2001 new_owns = True;
2002 }
2003 } else {
2004 new_bname = new_path;
2005 }
2006
2007 ret = renameat(old_dfd, old_bname, new_dfd, new_bname);
2008 e = errno;
2009 if (new_owns)
2010 close(new_dfd);
2011 if (old_owns)
2012 close(old_dfd);
2013 errno = e;
2014 return ret;
2015 #else
2016 return do_rename(old_path, new_path);
2017 #endif
2018 }
2019
2020 #ifdef HAVE_FTRUNCATE
2021 int do_ftruncate(int fd, OFF_T size)
2022 {
2023 int ret;
2024
2025 if (dry_run) return 0;
2026 RETURN_ERROR_IF_RO_OR_LO;
2027
2028 do {
2029 ret = ftruncate(fd, size);
2030 } while (ret < 0 && errno == EINTR);
2031
2032 return ret;
2033 }
2034 #endif
2035
2036 void trim_trailing_slashes(char *name)
2037 {
2038 int l;
2039 /* Some BSD systems cannot make a directory if the name
2040 * contains a trailing slash.
2041 * <http://www.opensource.apple.com/bugs/X/BSD%20Kernel/2734739.html> */
2042
2043 /* Don't change empty string; and also we can't improve on
2044 * "/" */
2045
2046 l = strlen(name);
2047 while (l > 1) {
2048 if (name[--l] != '/')
2049 break;
2050 name[l] = '\0';
2051 }
2052 }
2053
2054 int do_mkdir(char *path, mode_t mode)
2055 {
2056 if (dry_run) return 0;
2057 RETURN_ERROR_IF_RO_OR_LO;
2058 RETURN_ERROR_IF_NULL(path);
2059 trim_trailing_slashes(path);
2060 return mkdir(path, mode);
2061 }
2062
2063 /*
2064 Symlink-race-safe variant of do_mkdir() for receiver-side use. See
2065 the comment on do_chmod_at() for the threat model and design rationale.
2066
2067 mkdir() resolves parent symlinks at every component, so a parent-
2068 component swap can place an attacker-named directory outside the
2069 module. Defence: open the parent of fname under secure_relative_open()
2070 and call mkdirat() against that dirfd.
2071
2072 Mutates path in place to trim trailing slashes (matches do_mkdir()).
2073 Falls through to do_mkdir() in dry-run, non-daemon, chrooted, no-
2074 parent and absolute-path cases.
2075 */
2076 int do_mkdir_at(char *path, mode_t mode)
2077 {
2078 #ifdef AT_FDCWD
2079 extern int am_daemon, am_chrooted;
2080 char dirpath[MAXPATHLEN];
2081 const char *bname;
2082 const char *slash;
2083 int dfd, ret, e;
2084 size_t dlen;
2085
2086 if (dry_run) return 0;
2087 RETURN_ERROR_IF_RO_OR_LO;
2088 RETURN_ERROR_IF_NULL(path);
2089 trim_trailing_slashes(path);
2090
2091 #if defined O_NOFOLLOW && defined O_DIRECTORY
2092 if (operator_path_resolve) {
2093 if (symlink_optout_allowed())
2094 return mkdir(path, mode);
2095 dfd = owner_walk_parent(path, &bname);
2096 if (dfd < 0)
2097 return -1;
2098 ret = mkdirat(dfd, bname, mode);
2099 e = errno;
2100 close(dfd);
2101 errno = e;
2102 return ret;
2103 }
2104 #endif
2105
2106 if (!secure_relpath_active())
2107 return mkdir(path, mode);
2108
2109 if (!path || !*path || *path == '/')
2110 return mkdir(path, mode);
2111
2112 slash = strrchr(path, '/');
2113 if (!slash)
2114 return mkdir(path, mode);
2115
2116 dlen = slash - path;
2117 if (dlen >= sizeof dirpath) {
2118 errno = ENAMETOOLONG;
2119 return -1;
2120 }
2121 memcpy(dirpath, path, dlen);
2122 dirpath[dlen] = '\0';
2123 bname = slash + 1;
2124
2125 dfd = secure_relative_open(NULL, dirpath, O_RDONLY | O_DIRECTORY, 0);
2126 if (dfd < 0)
2127 return -1;
2128
2129 ret = mkdirat(dfd, bname, mode);
2130 e = errno;
2131 close(dfd);
2132 errno = e;
2133 return ret;
2134 #else
2135 return do_mkdir(path, mode);
2136 #endif
2137 }
2138
2139 /* like mkstemp but forces permissions */
2140 int do_mkstemp(char *template, mode_t perms)
2141 {
2142 RETURN_ERROR_IF(dry_run, 0);
2143 RETURN_ERROR_IF(read_only, EROFS);
2144 perms |= S_IWUSR;
2145
2146 #if defined HAVE_SECURE_MKSTEMP && defined HAVE_FCHMOD && (!defined HAVE_OPEN64 || defined HAVE_MKSTEMP64)
2147 {
2148 int fd = mkstemp(template);
2149 if (fd == -1)
2150 return -1;
2151 if (fchmod(fd, perms) != 0 && preserve_perms) {
2152 int errno_save = errno;
2153 close(fd);
2154 unlink(template);
2155 errno = errno_save;
2156 return -1;
2157 }
2158 #if defined HAVE_SETMODE && O_BINARY
2159 setmode(fd, O_BINARY);
2160 #endif
2161 return fd;
2162 }
2163 #else
2164 if (!mktemp(template))
2165 return -1;
2166 return do_open(template, O_RDWR|O_EXCL|O_CREAT, perms);
2167 #endif
2168 }
2169
2170 int do_stat(const char *path, STRUCT_STAT *st)
2171 {
2172 RETURN_ERROR_IF_NULL(path);
2173 #ifdef USE_STAT64_FUNCS
2174 return stat64(path, st);
2175 #else
2176 return stat(path, st);
2177 #endif
2178 }
2179
2180 int do_lstat(const char *path, STRUCT_STAT *st)
2181 {
2182 RETURN_ERROR_IF_NULL(path);
2183 #ifdef SUPPORT_LINKS
2184 # ifdef USE_STAT64_FUNCS
2185 return lstat64(path, st);
2186 # else
2187 return lstat(path, st);
2188 # endif
2189 #else
2190 return do_stat(path, st);
2191 #endif
2192 }
2193
2194 /*
2195 Symlink-race-safe variants of do_stat() / do_lstat() for receiver-
2196 side use. See the comment on do_chmod_at() for the threat model.
2197 stat() and lstat() resolve parent components, so a parent-symlink
2198 swap can make the receiver's stat see attributes of a victim file
2199 outside the module -- which then drives later behaviour (e.g.
2200 "this isn't a directory, delete it" -> attacker-controlled unlink
2201 on something outside the module).
2202
2203 Defence: open the parent under secure_relative_open() and use
2204 fstatat() with AT_SYMLINK_NOFOLLOW (lstat) or 0 (stat) against
2205 that dirfd. Same fall-through gating as the other wrappers.
2206 */
2207 static int do_xstat_at(const char *path, STRUCT_STAT *st, int at_flags, int (*fallback)(const char *, STRUCT_STAT *))
2208 {
2209 #ifdef AT_FDCWD
2210 extern int am_daemon, am_chrooted;
2211 char dirpath[MAXPATHLEN];
2212 const char *bname;
2213 const char *slash;
2214 int dfd, ret, e;
2215 size_t dlen;
2216
2217 #if defined O_NOFOLLOW && defined O_DIRECTORY
2218 if (operator_path_resolve) {
2219 if (symlink_optout_allowed())
2220 return fallback(path, st);
2221 dfd = owner_walk_parent(path, &bname);
2222 if (dfd < 0)
2223 return -1;
2224 ret = fstatat(dfd, bname, st, at_flags);
2225 e = errno;
2226 close(dfd);
2227 errno = e;
2228 return ret;
2229 }
2230 #endif
2231
2232 if (!secure_relpath_active())
2233 return fallback(path, st);
2234
2235 if (!path || !*path || *path == '/')
2236 return fallback(path, st);
2237
2238 slash = strrchr(path, '/');
2239 if (!slash)
2240 return fallback(path, st);
2241
2242 dlen = slash - path;
2243 if (dlen >= sizeof dirpath) {
2244 errno = ENAMETOOLONG;
2245 return -1;
2246 }
2247 memcpy(dirpath, path, dlen);
2248 dirpath[dlen] = '\0';
2249 bname = slash + 1;
2250
2251 dfd = secure_relative_open(NULL, dirpath, O_RDONLY | O_DIRECTORY, 0);
2252 if (dfd < 0)
2253 return -1;
2254
2255 ret = fstatat(dfd, bname, st, at_flags);
2256 e = errno;
2257 close(dfd);
2258 errno = e;
2259 return ret;
2260 #else
2261 (void)at_flags;
2262 return fallback(path, st);
2263 #endif
2264 }
2265
2266 int do_stat_at(const char *path, STRUCT_STAT *st)
2267 {
2268 return do_xstat_at(path, st, 0, do_stat);
2269 }
2270
2271 int do_lstat_at(const char *path, STRUCT_STAT *st)
2272 {
2273 #if defined SUPPORT_LINKS && defined AT_FDCWD && defined AT_SYMLINK_NOFOLLOW
2274 return do_xstat_at(path, st, AT_SYMLINK_NOFOLLOW, do_lstat);
2275 #elif defined SUPPORT_LINKS
2276 return do_lstat(path, st);
2277 #else
2278 return do_xstat_at(path, st, 0, do_stat);
2279 #endif
2280 }
2281
2282 int do_fstat(int fd, STRUCT_STAT *st)
2283 {
2284 #ifdef USE_STAT64_FUNCS
2285 return fstat64(fd, st);
2286 #else
2287 return fstat(fd, st);
2288 #endif
2289 }
2290
2291 OFF_T do_lseek(int fd, OFF_T offset, int whence)
2292 {
2293 #ifdef HAVE_LSEEK64
2294 return lseek64(fd, offset, whence);
2295 #else
2296 return lseek(fd, offset, whence);
2297 #endif
2298 }
2299
2300 #ifdef HAVE_SETATTRLIST
2301 int do_setattrlist_times(const char *path, STRUCT_STAT *stp)
2302 {
2303 struct attrlist attrList;
2304 struct timespec ts[2];
2305
2306 if (dry_run) return 0;
2307 RETURN_ERROR_IF_RO_OR_LO;
2308
2309 /* setattrlist() takes a raw path and follows parent symlinks
2310 * (FSOPT_NOFOLLOW only blocks the final component). When hardened
2311 * resolution is active -- secure_relpath_active(): any non-chroot
2312 * daemon/receiver module, plus a /./ inner-module chroot -- return
2313 * ENOSYS so set_times()' tier walk falls through to do_utimensat_at(),
2314 * which routes the update through a secure parent dirfd. The attribute
2315 * set this would have used (ATTR_CMN_MODTIME / ATTR_CMN_ACCTIME) is the
2316 * same set utimensat() handles, so no functionality is lost. */
2317 if (secure_relpath_active()) {
2318 errno = ENOSYS;
2319 return -1;
2320 }
2321
2322 /* Yes, this is in the opposite order of utime and similar. */
2323 ts[0].tv_sec = stp->st_mtime;
2324 ts[0].tv_nsec = stp->ST_MTIME_NSEC;
2325
2326 ts[1].tv_sec = stp->st_atime;
2327 ts[1].tv_nsec = stp->ST_ATIME_NSEC;
2328
2329 memset(&attrList, 0, sizeof attrList);
2330 attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
2331 attrList.commonattr = ATTR_CMN_MODTIME | ATTR_CMN_ACCTIME;
2332 return setattrlist(path, &attrList, ts, sizeof ts, FSOPT_NOFOLLOW);
2333 }
2334
2335 #ifdef SUPPORT_CRTIMES
2336 int do_setattrlist_crtime(const char *path, time_t crtime)
2337 {
2338 struct attrlist attrList;
2339 struct timespec ts;
2340
2341 if (dry_run) return 0;
2342 RETURN_ERROR_IF_RO_OR_LO;
2343
2344 /* setattrlist() is path-based and follows parent symlinks
2345 * (FSOPT_NOFOLLOW only blocks the final component), and macOS has no
2346 * at-aware variant targeting ATTR_CMN_CRTIME. As with POSIX ACLs where
2347 * the OS offers no race-safe primitive, we keep --crtimes functional
2348 * (daemon and non-daemon) and accept the parent-component symlink race
2349 * as a documented residual rather than dropping crtime. A daemon
2350 * operator who does not want that residual can disable the feature with
2351 * "refuse options = crtimes" in rsyncd.conf. */
2352 ts.tv_sec = crtime;
2353 ts.tv_nsec = 0;
2354
2355 memset(&attrList, 0, sizeof attrList);
2356 attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
2357 attrList.commonattr = ATTR_CMN_CRTIME;
2358 return setattrlist(path, &attrList, &ts, sizeof ts, FSOPT_NOFOLLOW);
2359 }
2360 #endif
2361 #endif /* HAVE_SETATTRLIST */
2362
2363 #ifdef SUPPORT_CRTIMES
2364 time_t get_create_time(const char *path, STRUCT_STAT *stp)
2365 {
2366 #ifdef HAVE_GETATTRLIST
2367 static struct create_time attrBuf;
2368 struct attrlist attrList;
2369
2370 (void)stp;
2371 /* getattrlist() is path-based and follows parent symlinks; like
2372 * do_setattrlist_crtime() there is no race-safe variant, so reading the
2373 * source crtime stays functional and the parent-component symlink race
2374 * is an accepted residual (refusable via "refuse options = crtimes"). */
2375 memset(&attrList, 0, sizeof attrList);
2376 attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
2377 attrList.commonattr = ATTR_CMN_CRTIME;
2378 if (getattrlist(path, &attrList, &attrBuf, sizeof attrBuf, FSOPT_NOFOLLOW) < 0)
2379 return 0;
2380 return attrBuf.crtime.tv_sec;
2381 #elif defined __CYGWIN__
2382 (void)path;
2383 return stp->st_birthtime;
2384 #else
2385 #error Unknown crtimes implementation
2386 #endif
2387 }
2388
2389 #if defined __CYGWIN__
2390 int do_SetFileTime(const char *path, time_t crtime)
2391 {
2392 if (dry_run) return 0;
2393 RETURN_ERROR_IF_RO_OR_LO;
2394
2395 int cnt = MultiByteToWideChar(CP_UTF8, 0, path, -1, NULL, 0);
2396 if (cnt == 0)
2397 return -1;
2398 WCHAR *pathw = new_array(WCHAR, cnt);
2399 if (!pathw)
2400 return -1;
2401 MultiByteToWideChar(CP_UTF8, 0, path, -1, pathw, cnt);
2402 HANDLE handle = CreateFileW(pathw, FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
2403 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
2404 free(pathw);
2405 if (handle == INVALID_HANDLE_VALUE)
2406 return -1;
2407 int64 temp_time = (crtime * 10000000LL) + 116444736000000000LL;
2408 FILETIME birth_time;
2409 birth_time.dwLowDateTime = (DWORD)temp_time;
2410 birth_time.dwHighDateTime = (DWORD)(temp_time >> 32);
2411 int ok = SetFileTime(handle, &birth_time, NULL, NULL);
2412 CloseHandle(handle);
2413 return ok ? 0 : -1;
2414 }
2415 #endif
2416 #endif /* SUPPORT_CRTIMES */
2417
2418 #ifdef HAVE_UTIMENSAT
2419 int do_utimensat(const char *path, STRUCT_STAT *stp)
2420 {
2421 struct timespec t[2];
2422
2423 if (dry_run) return 0;
2424 RETURN_ERROR_IF_RO_OR_LO;
2425 RETURN_ERROR_IF_NULL(path);
2426
2427 t[0].tv_sec = stp->st_atime;
2428 #ifdef ST_ATIME_NSEC
2429 t[0].tv_nsec = stp->ST_ATIME_NSEC;
2430 #else
2431 t[0].tv_nsec = 0;
2432 #endif
2433 t[1].tv_sec = stp->st_mtime;
2434 #ifdef ST_MTIME_NSEC
2435 t[1].tv_nsec = stp->ST_MTIME_NSEC;
2436 #else
2437 t[1].tv_nsec = 0;
2438 #endif
2439 return utimensat(AT_FDCWD, path, t, AT_SYMLINK_NOFOLLOW);
2440 }
2441
2442 /*
2443 Symlink-race-safe variant of do_utimensat() for receiver-side use.
2444 See the comment on do_chmod_at() for the threat model. utimes()
2445 resolves parent components and follows a final-component symlink;
2446 lutimes() doesn't follow the final component but still resolves
2447 parents. Either way, a parent-symlink swap can redirect the
2448 timestamp update outside the module. Defence: open the parent of
2449 path under secure_relative_open() and call utimensat() with
2450 AT_SYMLINK_NOFOLLOW against that dirfd.
2451
2452 Falls through to do_utimensat() in the same dry-run / non-daemon /
2453 chrooted / no-parent / absolute-path cases as the other wrappers.
2454 Returns -1 with errno=ENOSYS on systems without utimensat()
2455 (caller is expected to fall back to the legacy tier walk).
2456 */
2457 int do_utimensat_at(const char *path, STRUCT_STAT *stp)
2458 {
2459 #ifdef AT_FDCWD
2460 extern int am_daemon, am_chrooted;
2461 struct timespec t[2];
2462 char dirpath[MAXPATHLEN];
2463 const char *bname;
2464 const char *slash;
2465 int dfd, ret, e;
2466 size_t dlen;
2467
2468 if (dry_run) return 0;
2469 RETURN_ERROR_IF_RO_OR_LO;
2470
2471 if (!secure_relpath_active())
2472 return do_utimensat(path, stp);
2473
2474 if (!path || !*path || *path == '/')
2475 return do_utimensat(path, stp);
2476
2477 slash = strrchr(path, '/');
2478 if (!slash)
2479 return do_utimensat(path, stp);
2480
2481 dlen = slash - path;
2482 if (dlen >= sizeof dirpath) {
2483 errno = ENAMETOOLONG;
2484 return -1;
2485 }
2486 memcpy(dirpath, path, dlen);
2487 dirpath[dlen] = '\0';
2488 bname = slash + 1;
2489
2490 t[0].tv_sec = stp->st_atime;
2491 #ifdef ST_ATIME_NSEC
2492 t[0].tv_nsec = stp->ST_ATIME_NSEC;
2493 #else
2494 t[0].tv_nsec = 0;
2495 #endif
2496 t[1].tv_sec = stp->st_mtime;
2497 #ifdef ST_MTIME_NSEC
2498 t[1].tv_nsec = stp->ST_MTIME_NSEC;
2499 #else
2500 t[1].tv_nsec = 0;
2501 #endif
2502
2503 dfd = secure_relative_open(NULL, dirpath, O_RDONLY | O_DIRECTORY, 0);
2504 if (dfd < 0)
2505 return -1;
2506
2507 ret = utimensat(dfd, bname, t, AT_SYMLINK_NOFOLLOW);
2508 e = errno;
2509 close(dfd);
2510 errno = e;
2511 return ret;
2512 #else
2513 return do_utimensat(path, stp);
2514 #endif
2515 }
2516 #endif
2517
2518 #ifdef HAVE_LUTIMES
2519 int do_lutimes(const char *path, STRUCT_STAT *stp)
2520 {
2521 struct timeval t[2];
2522
2523 if (dry_run) return 0;
2524 RETURN_ERROR_IF_RO_OR_LO;
2525
2526 t[0].tv_sec = stp->st_atime;
2527 #ifdef ST_ATIME_NSEC
2528 t[0].tv_usec = stp->ST_ATIME_NSEC / 1000;
2529 #else
2530 t[0].tv_usec = 0;
2531 #endif
2532 t[1].tv_sec = stp->st_mtime;
2533 #ifdef ST_MTIME_NSEC
2534 t[1].tv_usec = stp->ST_MTIME_NSEC / 1000;
2535 #else
2536 t[1].tv_usec = 0;
2537 #endif
2538 return lutimes(path, t);
2539 }
2540 #endif
2541
2542 #ifdef HAVE_UTIMES
2543 int do_utimes(const char *path, STRUCT_STAT *stp)
2544 {
2545 struct timeval t[2];
2546
2547 if (dry_run) return 0;
2548 RETURN_ERROR_IF_RO_OR_LO;
2549
2550 t[0].tv_sec = stp->st_atime;
2551 #ifdef ST_ATIME_NSEC
2552 t[0].tv_usec = stp->ST_ATIME_NSEC / 1000;
2553 #else
2554 t[0].tv_usec = 0;
2555 #endif
2556 t[1].tv_sec = stp->st_mtime;
2557 #ifdef ST_MTIME_NSEC
2558 t[1].tv_usec = stp->ST_MTIME_NSEC / 1000;
2559 #else
2560 t[1].tv_usec = 0;
2561 #endif
2562 return utimes(path, t);
2563 }
2564
2565 #elif defined HAVE_UTIME
2566 int do_utime(const char *path, STRUCT_STAT *stp)
2567 {
2568 #ifdef HAVE_STRUCT_UTIMBUF
2569 struct utimbuf tbuf;
2570 #else
2571 time_t t[2];
2572 #endif
2573
2574 if (dry_run) return 0;
2575 RETURN_ERROR_IF_RO_OR_LO;
2576
2577 # ifdef HAVE_STRUCT_UTIMBUF
2578 tbuf.actime = stp->st_atime;
2579 tbuf.modtime = stp->st_mtime;
2580 return utime(path, &tbuf);
2581 # else
2582 t[0] = stp->st_atime;
2583 t[1] = stp->st_mtime;
2584 return utime(path, t);
2585 # endif
2586 }
2587
2588 #else
2589 #error Need utimes or utime function.
2590 #endif
2591
2592 #ifdef SUPPORT_PREALLOCATION
2593 #ifdef FALLOC_FL_KEEP_SIZE
2594 #define DO_FALLOC_OPTIONS FALLOC_FL_KEEP_SIZE
2595 #else
2596 #define DO_FALLOC_OPTIONS 0
2597 #endif
2598
2599 OFF_T do_fallocate(int fd, OFF_T offset, OFF_T length)
2600 {
2601 /* FALLOC_FL_KEEP_SIZE lets --preallocate/--inplace keep the file size at 0
2602 * until data is written, but a later hole-punch (for --sparse) can only
2603 * deallocate blocks that lie within the file's size -- with KEEP_SIZE the
2604 * reserved blocks sit beyond EOF and the punch silently does nothing,
2605 * leaving the file fully allocated. So when holes will also be punched,
2606 * preallocate at full size instead (write_sparse then punches the nulls). */
2607 int opts = (inplace || preallocate_files) && sparse_files <= 0 ? DO_FALLOC_OPTIONS : 0;
2608 int ret;
2609 RETURN_ERROR_IF(dry_run, 0);
2610 RETURN_ERROR_IF_RO_OR_LO;
2611 if (length & 1) /* make the length not match the desired length */
2612 length++;
2613 else
2614 length--;
2615 #if defined HAVE_FALLOCATE
2616 ret = fallocate(fd, opts, offset, length);
2617 #elif defined HAVE_SYS_FALLOCATE
2618 ret = syscall(SYS_fallocate, fd, opts, (loff_t)offset, (loff_t)length);
2619 #elif defined HAVE_EFFICIENT_POSIX_FALLOCATE
2620 ret = posix_fallocate(fd, offset, length);
2621 #else
2622 #error Coding error in SUPPORT_PREALLOCATION logic.
2623 #endif
2624 if (ret < 0)
2625 return ret;
2626 if (opts == 0) {
2627 STRUCT_STAT st;
2628 if (do_fstat(fd, &st) < 0)
2629 return length;
2630 return st.st_blocks * S_BLKSIZE;
2631 }
2632 /* With FALLOC_FL_KEEP_SIZE the blocks for [0, length) are reserved even
2633 * though the file size stays put. Return that reserved length (not 0) so
2634 * the caller's preallocated_len is meaningful: write_sparse() needs it to
2635 * choose do_punch_hole() over a plain lseek() when turning a null run into
2636 * a hole, and the receiver uses it to trim any over-preallocation. (A
2637 * stray 0 here, from 2019's switch to KEEP_SIZE, is why --preallocate
2638 * --sparse stopped producing sparse files.) */
2639 return length;
2640 }
2641 #endif
2642
2643 /* Punch a hole at pos for len bytes. The current file position must be at pos and will be
2644 * changed to be at pos + len. */
2645 int do_punch_hole(int fd, OFF_T pos, OFF_T len)
2646 {
2647 #ifdef HAVE_FALLOCATE
2648 # ifdef HAVE_FALLOC_FL_PUNCH_HOLE
2649 if (fallocate(fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, pos, len) == 0) {
2650 if (do_lseek(fd, len, SEEK_CUR) != pos + len)
2651 return -1;
2652 return 0;
2653 }
2654 # endif
2655 # ifdef HAVE_FALLOC_FL_ZERO_RANGE
2656 if (fallocate(fd, FALLOC_FL_ZERO_RANGE, pos, len) == 0) {
2657 if (do_lseek(fd, len, SEEK_CUR) != pos + len)
2658 return -1;
2659 return 0;
2660 }
2661 # endif
2662 #else
2663 (void)pos;
2664 #endif
2665 {
2666 char zeros[4096];
2667 memset(zeros, 0, sizeof zeros);
2668 while (len > 0) {
2669 int chunk = len > (int)sizeof zeros ? (int)sizeof zeros : len;
2670 int wrote = write(fd, zeros, chunk);
2671 if (wrote <= 0) {
2672 if (wrote < 0 && errno == EINTR)
2673 continue;
2674 return -1;
2675 }
2676 len -= wrote;
2677 }
2678 }
2679 return 0;
2680 }
2681
2682 int do_open_nofollow(const char *pathname, int flags)
2683 {
2684 #ifndef O_NOFOLLOW
2685 STRUCT_STAT f_st, l_st;
2686 #endif
2687 int fd;
2688
2689 if (flags != O_RDONLY) {
2690 RETURN_ERROR_IF(dry_run, 0);
2691 RETURN_ERROR_IF_RO_OR_LO;
2692 #ifndef O_NOFOLLOW
2693 /* This function doesn't support write attempts w/o O_NOFOLLOW. */
2694 errno = EINVAL;
2695 return -1;
2696 #endif
2697 }
2698
2699 #ifdef O_NOATIME
2700 if (open_noatime)
2701 flags |= O_NOATIME;
2702 #endif
2703
2704 #ifdef O_NOFOLLOW
2705 fd = open(pathname, flags|O_NOFOLLOW);
2706 #else
2707 if (do_lstat(pathname, &l_st) < 0)
2708 return -1;
2709 if (S_ISLNK(l_st.st_mode)) {
2710 errno = ELOOP;
2711 return -1;
2712 }
2713 if ((fd = open(pathname, flags)) < 0)
2714 return fd;
2715 if (do_fstat(fd, &f_st) < 0) {
2716 close_and_return_error:
2717 {
2718 int save_errno = errno;
2719 close(fd);
2720 errno = save_errno;
2721 }
2722 return -1;
2723 }
2724 if (l_st.st_dev != f_st.st_dev || l_st.st_ino != f_st.st_ino) {
2725 errno = EINVAL;
2726 goto close_and_return_error;
2727 }
2728 #endif
2729
2730 return fd;
2731 }
2732
2733 /*
2734 open a file relative to a base directory. The basedir can be NULL,
2735 in which case the current working directory is used. The relpath
2736 must be a relative path. Resolution cannot escape basedir (or the
2737 cwd, when basedir is NULL): no ".." jumps above the start, no
2738 symlinks pointing outside, no absolute paths.
2739
2740 Symlinks *within* basedir are followed normally — earlier rsync
2741 versions rejected every symlink with O_NOFOLLOW on each component,
2742 which broke legitimate directory symlinks on the receiver side
2743 (https://github.com/RsyncProject/rsync/issues/715).
2744
2745 Escape prevention is handled by a single portable mechanism on every
2746 platform: a per-component O_NOFOLLOW walk on a stack of held parent
2747 dirfds (the dirstack helpers above). Each component is opened
2748 relative to a pinned parent fd, so no rename or symlink-swap can
2749 redirect resolution; ".." pops to the already-held parent (never
2750 above the anchor); an in-tree directory symlink is followed by
2751 reading its target and walking it on the same stack (absolute
2752 targets refused, symlink hops bounded). Single-component + O_NOFOLLOW
2753 + a pinned parent fd is race-free by construction, with no kernel
2754 "beneath" primitive required (see dev-notes/resolver-race-freeness).
2755
2756 The relpath must also not contain any ../ elements in the path
2757 (except for a deliberately re-anchored module path; see below).
2758 */
2759
2760 /* Returns 1 if path has any "/"-separated component that is exactly
2761 * "..", 0 otherwise. Used by secure_relative_open's front-door
2762 * validation to reject ".." inputs (bare "..", "foo/..", "subdir/..")
2763 * for non-re-anchored paths; the walk itself resolves an in-tree ".."
2764 * safely (ds_descend pops to the held parent) for a re-anchored path. */
2765 static int path_has_dotdot_component(const char *path)
2766 {
2767 const char *p = path;
2768
2769 while (*p) {
2770 const char *q;
2771 if (*p == '/') { p++; continue; }
2772 q = p;
2773 while (*q && *q != '/')
2774 q++;
2775 if (q - p == 2 && p[0] == '.' && p[1] == '.')
2776 return 1;
2777 p = q;
2778 }
2779 return 0;
2780 }
2781
2782 /* The logical current directory (maintained by change_dir() in util1.c).
2783 * Defined here -- rather than in util1.c -- so the test helpers that link
2784 * syscall.o but not util1.o (tls, trimslash) get the definition without a
2785 * weak-symbol fallback, which is not portable to PE/COFF targets (Cygwin). */
2786 char curr_dir[MAXPATHLEN];
2787 unsigned int curr_dir_len;
2788
2789 #if defined(O_NOFOLLOW) && defined(O_DIRECTORY) && defined(AT_FDCWD)
2790 /* In-tree symlink following for secure_relative_open()'s directory walk (below).
2791 * An early version refused every symlink with O_NOFOLLOW on each component, which
2792 * broke legitimate within-tree directory symlinks (--keep-dirlinks #715, and -aR
2793 * through a symlinked parent); the walk now follows them safely.
2794 *
2795 * A directory walk keeps a stack of the open dirfds from the anchor (index 0,
2796 * borrowed -- not closed here) down to the current directory. Descending into
2797 * a real subdirectory pushes its fd; a ".." in a followed symlink target pops
2798 * back to the already-pinned parent fd rather than re-resolving ".." with
2799 * openat(), so an ancestor renamed mid-walk cannot redirect the climb, and the
2800 * climb can never rise above the anchor (a pop at the anchor returns ELOOP).
2801 * This matches RESOLVE_BENEATH, which allows in-tree ".." that stays beneath the
2802 * root. Absolute symlink targets are refused; symlink hops are bounded. */
2803 #ifndef SECURE_OPEN_MAXSYMLINKS
2804 #define SECURE_OPEN_MAXSYMLINKS 40
2805 #endif
2806
2807 /* Max directory levels held open at once during a single resolve. The walk
2808 * holds one fd per component, so depth is bounded by RLIMIT_NOFILE anyway; a
2809 * fixed array (no malloc/realloc) keeps the stack simple and the static
2810 * analyzer happy. Mirrors DPC_MAXDEPTH's fixed-cap approach. */
2811 #define DS_MAXDEPTH 1024
2812
2813 struct dirstack {
2814 int fds[DS_MAXDEPTH]; /* fds[0] = anchor (borrowed); fds[top] = current dir */
2815 int top;
2816 /* Absolute path of fds[top], maintained as we descend/pop, for the
2817 * exclude-aware refusal (abspath_outside_confinement). Empty unless the
2818 * caller seeds it with the anchor's absolute path; then a followed symlink
2819 * that redirects the walk into a module-excluded dir is refused. */
2820 char abspath[MAXPATHLEN];
2821 };
2822
2823 /* Append "/comp" to ds->abspath (no-op if it's unseeded/empty so non-daemon
2824 * callers pay nothing). Returns -1 (ENAMETOOLONG) on overflow. */
2825 static int ds_path_push(struct dirstack *ds, const char *comp)
2826 {
2827 size_t al = strlen(ds->abspath);
2828 if (al == 0)
2829 return 0; /* unseeded: tracking disabled for this walk */
2830 size_t cl = strlen(comp);
2831 if (al + 1 + cl >= sizeof ds->abspath) {
2832 errno = ENAMETOOLONG;
2833 return -1;
2834 }
2835 ds->abspath[al] = '/';
2836 memcpy(ds->abspath + al + 1, comp, cl + 1);
2837 return 0;
2838 }
2839
2840 /* Drop the last component of ds->abspath (mirrors a ".." pop). */
2841 static void ds_path_pop(struct dirstack *ds)
2842 {
2843 char *slash;
2844 if (!ds->abspath[0])
2845 return;
2846 slash = strrchr(ds->abspath, '/');
2847 if (slash && slash != ds->abspath)
2848 *slash = '\0';
2849 }
2850
2851 /* Initialise with `anchor` (which may be AT_FDCWD) as the un-owned base.
2852 * Returns int for caller symmetry, but cannot fail (the fd array is inline). */
2853 static int ds_init(struct dirstack *ds, int anchor)
2854 {
2855 ds->abspath[0] = '\0';
2856 ds->fds[0] = anchor;
2857 ds->top = 0;
2858 return 0;
2859 }
2860
2861 /* Close every pushed fd (but not the borrowed anchor at index 0). */
2862 static void ds_free(struct dirstack *ds)
2863 {
2864 while (ds->top > 0)
2865 close(ds->fds[ds->top--]);
2866 }
2867
2868 static int ds_cur(struct dirstack *ds)
2869 {
2870 return ds->fds[ds->top];
2871 }
2872
2873 static int ds_push(struct dirstack *ds, int fd)
2874 {
2875 if (ds->top + 1 >= DS_MAXDEPTH) { /* deeper than we'll hold open */
2876 close(fd);
2877 errno = ENOMEM;
2878 return -1;
2879 }
2880 ds->fds[++ds->top] = fd;
2881 return 0;
2882 }
2883
2884 /* Detach the current dir as an owned fd the caller must close. At the anchor
2885 * (top 0) the anchor is borrowed, so return a fresh dup of it instead. */
2886 static int ds_take(struct dirstack *ds)
2887 {
2888 if (ds->top > 0)
2889 return ds->fds[ds->top--];
2890 return openat(ds->fds[0], ".", O_RDONLY | O_DIRECTORY);
2891 }
2892
2893 static int ds_walk_path(struct dirstack *ds, char *path, int *hops);
2894
2895 /* Descend one path component on the stack: "." stays, ".." pops to the pinned
2896 * parent (ELOOP at the anchor), a real subdirectory is pushed, and an in-tree
2897 * directory symlink is followed by walking its (relative, possibly
2898 * ..-containing) target on the same stack. Returns 0, or -1 with errno set:
2899 * ELOOP for a refused/escaping symlink or a hop overrun, otherwise the
2900 * underlying openat()/readlinkat() errno (ENOENT, a real ENOTDIR, EACCES). */
2901 static int ds_descend(struct dirstack *ds, const char *part, int *hops)
2902 {
2903 if (part[0] == '.' && part[1] == '\0')
2904 return 0; /* "." -- no movement */
2905 if (part[0] == '.' && part[1] == '.' && part[2] == '\0') {
2906 if (ds->top == 0) { /* would rise above the anchor */
2907 errno = ELOOP;
2908 return -1;
2909 }
2910 close(ds->fds[ds->top--]); /* pop to the held parent fd */
2911 ds_path_pop(ds);
2912 return 0;
2913 }
2914
2915 int fd = openat(ds_cur(ds), part, O_RDONLY | O_DIRECTORY | O_NOFOLLOW);
2916 if (fd != -1) { /* a real subdirectory */
2917 if (ds_push(ds, fd) < 0)
2918 return -1;
2919 if (ds_path_push(ds, part) < 0)
2920 return -1;
2921 /* exclude-aware: refuse descending into a module-hidden dir (catches a
2922 * symlink that redirected the walk into an excluded subtree). */
2923 if (abspath_outside_confinement(ds->abspath)) {
2924 errno = ELOOP;
2925 return -1;
2926 }
2927 return 0;
2928 }
2929 /* O_NOFOLLOW refused a symlink (NOFOLLOW_HIT_SYMLINK: ELOOP on Linux, EMLINK
2930 * on FreeBSD, EFTYPE on NetBSD/OpenBSD), or O_DIRECTORY hit a non-directory
2931 * (ENOTDIR). Either may be a symlink, so fall through to the readlink probe;
2932 * anything else is a hard error. */
2933 if (errno != ENOTDIR && !NOFOLLOW_HIT_SYMLINK(errno)) {
2934 if (errno == EMFILE || errno == ENFILE) {
2935 /* The resolver holds one dirfd per path component, so a deep path
2936 * can exhaust descriptors where plain open() would not. Hint at
2937 * the fix once -- otherwise "Too many open files" is opaque. */
2938 static int warned = 0;
2939 if (!warned) {
2940 int e = errno;
2941 warned = 1;
2942 rprintf(FWARNING, "out of file descriptors resolving a deep path;"
2943 " raise the open-file limit (e.g. `ulimit -n`)\n");
2944 errno = e;
2945 }
2946 }
2947 return -1;
2948 }
2949 int open_errno = errno;
2950
2951 char buf[MAXPATHLEN];
2952 ssize_t n = readlinkat(ds_cur(ds), part, buf, sizeof buf - 1);
2953 if (n < 0) {
2954 if (errno == EINVAL) /* not a symlink: a real non-dir */
2955 errno = open_errno;
2956 return -1;
2957 }
2958 if (n == 0 || (size_t)n >= sizeof buf - 1) {
2959 errno = ELOOP; /* empty or truncated target */
2960 return -1;
2961 }
2962 buf[n] = '\0';
2963 if (buf[0] == '/') { /* absolute target: refuse */
2964 errno = ELOOP;
2965 return -1;
2966 }
2967 if (--(*hops) < 0) {
2968 errno = ELOOP;
2969 return -1;
2970 }
2971 return ds_walk_path(ds, buf, hops);
2972 }
2973
2974 /* Walk every component of a relative path on the stack (used for the basedir,
2975 * and for a followed symlink's target -- which may contain ".."). */
2976 static int ds_walk_path(struct dirstack *ds, char *path, int *hops)
2977 {
2978 char *save = NULL;
2979 for (char *c = strtok_r(path, "/", &save); c; c = strtok_r(NULL, "/", &save)) {
2980 if (ds_descend(ds, c, hops) < 0)
2981 return -1;
2982 }
2983 return 0;
2984 }
2985
2986 /* Walk `relpath` confined beneath the borrowed anchor dirfd (which may be
2987 * AT_FDCWD) and return the opened leaf fd, or -1. Does NOT close `anchor_fd` --
2988 * the caller owns it. Shared by secure_relative_open() (which first resolves a
2989 * basedir to the anchor) and secure_relative_open_at() (handed an already-open
2990 * anchor, e.g. a held module-root fd). `hops` is the shared symlink-hop budget. */
2991 static int secure_walk_at(int anchor_fd, const char *anchor_abspath,
2992 const char *relpath, int flags, mode_t mode, int *hops)
2993 {
2994 struct dirstack ds;
2995 int retfd = -1;
2996 char *path_copy;
2997
2998 if (ds_init(&ds, anchor_fd) < 0)
2999 return -1;
3000 /* Seed the abspath tracker so the exclude-aware refusal can map a resolved
3001 * path back to module-relative. Only an absolute anchor enables it. */
3002 if (anchor_abspath && anchor_abspath[0] == '/')
3003 strlcpy(ds.abspath, anchor_abspath, sizeof ds.abspath);
3004 path_copy = my_strdup(relpath, __FILE__, __LINE__);
3005 if (!path_copy) {
3006 ds_free(&ds);
3007 return -1;
3008 }
3009
3010 /* Trim trailing slashes so the last-component test below is exact, then
3011 * note the offset of the final component. */
3012 size_t pclen = strlen(path_copy);
3013 while (pclen > 1 && path_copy[pclen-1] == '/')
3014 path_copy[--pclen] = '\0';
3015 char *last_slash = strrchr(path_copy, '/');
3016 size_t last_off = last_slash ? (size_t)(last_slash + 1 - path_copy) : 0;
3017
3018 int saw_component = 0;
3019 char *psave = NULL;
3020 for (char *part = strtok_r(path_copy, "/", &psave);
3021 part != NULL;
3022 part = strtok_r(NULL, "/", &psave))
3023 {
3024 int is_last = (size_t)(part - path_copy) == last_off;
3025 saw_component = 1;
3026
3027 /* A literal "." or ".." is a movement, not a name to open. It must go
3028 * through ds_descend(), which refuses to pop above the anchor, BEFORE
3029 * the leaf fast paths below -- those openat() the component directly,
3030 * so a final ".." would otherwise hand back the anchor's own parent
3031 * (with O_NOFOLLOW) or open it transiently (without O_DIRECTORY). */
3032 if (part[0] == '.'
3033 && (part[1] == '\0' || (part[1] == '.' && part[2] == '\0'))) {
3034 if (ds_descend(&ds, part, hops) < 0)
3035 goto cleanup;
3036 if (is_last) {
3037 if (flags & O_DIRECTORY)
3038 retfd = ds_take(&ds);
3039 else
3040 errno = EISDIR;
3041 goto cleanup;
3042 }
3043 continue;
3044 }
3045
3046 /* File leaf (final component, caller did not ask for O_DIRECTORY):
3047 * never follow a symlink leaf. */
3048 if (is_last && !(flags & O_DIRECTORY)) {
3049 if (ds.abspath[0]) {
3050 char leafabs[MAXPATHLEN];
3051 if (snprintf(leafabs, sizeof leafabs, "%s/%s", ds.abspath, part)
3052 < (int)sizeof leafabs
3053 && abspath_outside_confinement(leafabs)) {
3054 errno = ELOOP;
3055 goto cleanup;
3056 }
3057 }
3058 int next_fd = openat(ds_cur(&ds), part, O_RDONLY | O_DIRECTORY | O_NOFOLLOW);
3059 if (next_fd == -1 && (errno == ENOTDIR || errno == ENOENT)) {
3060 retfd = openat(ds_cur(&ds), part, flags | O_NOFOLLOW, mode);
3061 goto cleanup;
3062 }
3063 if (next_fd == -1)
3064 goto cleanup;
3065 close(next_fd);
3066 errno = EISDIR;
3067 goto cleanup;
3068 }
3069
3070 /* O_DIRECTORY|O_NOFOLLOW leaf: the caller's O_NOFOLLOW governs the leaf. */
3071 if (is_last && (flags & O_NOFOLLOW)) {
3072 retfd = openat(ds_cur(&ds), part, O_RDONLY | O_DIRECTORY | O_NOFOLLOW);
3073 goto cleanup;
3074 }
3075
3076 /* Directory component (intermediate, or an O_DIRECTORY leaf to follow):
3077 * descend on the stack, following in-tree symlinks. */
3078 if (ds_descend(&ds, part, hops) < 0) {
3079 if (!is_last && errno == ENOTDIR)
3080 errno = ELOOP;
3081 goto cleanup;
3082 }
3083 if (is_last) {
3084 retfd = ds_take(&ds);
3085 goto cleanup;
3086 }
3087 }
3088
3089 /* Empty relpath: hand back a real anchor for an O_DIRECTORY caller (ds_take
3090 * dups the borrowed anchor), else EISDIR. An AT_FDCWD anchor is not a
3091 * resolvable target, so it fails rather than silently returning the cwd. */
3092 if (!saw_component) {
3093 if ((flags & O_DIRECTORY) && anchor_fd != AT_FDCWD)
3094 retfd = ds_take(&ds);
3095 else
3096 errno = EISDIR;
3097 }
3098
3099 cleanup:
3100 free(path_copy);
3101 ds_free(&ds);
3102 return retfd;
3103 }
3104 #endif /* O_NOFOLLOW && O_DIRECTORY && AT_FDCWD */
3105
3106 int secure_relative_open(const char *basedir, const char *relpath, int flags, mode_t mode)
3107 {
3108 extern int am_daemon, am_chrooted;
3109 extern char *module_dir;
3110 extern unsigned int module_dirlen;
3111 char modrel_buf[MAXPATHLEN];
3112 int reanchored = 0;
3113
3114 if (!relpath || relpath[0] == '/') {
3115 // must be a relative path
3116 errno = EINVAL;
3117 return -1;
3118 }
3119
3120 /* Sanitizing daemon (am_daemon && !am_chrooted) and the /./ inner-module
3121 * chroot (am_daemon && am_chrooted && module_dirlen) -- both keep the module
3122 * root, not the cwd, as the trust boundary. Here we have chdir'd into a
3123 * sub-dir of the module (the transfer destination), so a relative alt-dest
3124 * like "../01" may legitimately climb to a sibling that is still inside the
3125 * module (#915). Confining beneath the cwd would reject that climb.
3126 * Re-anchor at the module root by prefixing the cwd's module-relative path
3127 * (from rsync's logical curr_dir[], a guaranteed lexical prefix of
3128 * module_dir, unlike getcwd()) and resolving beneath module_dir; RESOLVE_
3129 * BENEATH then allows in-module climbs and still rejects escapes. Only for
3130 * paths that contain "..". module_dirlen is 0 for a `path = /` module
3131 * (clientserver.c), so the non-chroot arm gates on module_dir, not its
3132 * length, to cover that case too -- the prefix check below treats
3133 * module_dirlen 0 as "module root is /". */
3134 if (am_daemon && (!am_chrooted || module_dirlen)
3135 && module_dir && module_dir[0] == '/'
3136 && (basedir == NULL || basedir[0] != '/')
3137 && (path_has_dotdot_component(relpath)
3138 || (basedir && path_has_dotdot_component(basedir)))) {
3139 const char *p;
3140 int n;
3141 if (curr_dir_len >= module_dirlen
3142 && strncmp(curr_dir, module_dir, module_dirlen) == 0
3143 && (curr_dir[module_dirlen] == '\0' || curr_dir[module_dirlen] == '/')) {
3144 for (p = curr_dir + module_dirlen; *p == '/'; p++) {}
3145 if (basedir)
3146 n = snprintf(modrel_buf, sizeof modrel_buf, "%s%s%s/%s",
3147 p, *p ? "/" : "", basedir, relpath);
3148 else
3149 n = snprintf(modrel_buf, sizeof modrel_buf, "%s%s%s",
3150 p, *p ? "/" : "", relpath);
3151 if (n < 0 || n >= (int)sizeof modrel_buf) {
3152 errno = ENAMETOOLONG;
3153 return -1;
3154 }
3155 basedir = module_dir; /* absolute, operator-trusted anchor */
3156 relpath = modrel_buf;
3157 reanchored = 1;
3158 }
3159 /* else: cwd not under module root as expected -- fall through to the
3160 * front-door rejection below (fail safe). */
3161 }
3162
3163 /* Reject any path with a literal ".." component (bare "..",
3164 * "../foo", "foo/..", "foo/../bar", "subdir/..") at the front door,
3165 * with EINVAL, so callers can rely on the validation regardless of
3166 * platform. Skipped for a re-anchored path: its ".." is deliberate,
3167 * stays within the module, and is adjudicated safely by the walk
3168 * below (ds_descend pops a "../" to the held parent, never above the
3169 * anchor). */
3170 if (!reanchored) {
3171 if (path_has_dotdot_component(relpath)) {
3172 errno = EINVAL;
3173 return -1;
3174 }
3175 if (basedir && basedir[0] != '/' && path_has_dotdot_component(basedir)) {
3176 errno = EINVAL;
3177 return -1;
3178 }
3179 }
3180
3181 #ifdef O_NOATIME
3182 if (open_noatime)
3183 flags |= O_NOATIME;
3184 #endif
3185
3186 #if !defined(O_NOFOLLOW) || !defined(O_DIRECTORY) || !defined(AT_FDCWD)
3187 // really old system, all we can do is live with the risks
3188 if (!basedir) {
3189 return open(relpath, flags, mode);
3190 }
3191 char fullpath[MAXPATHLEN];
3192 pathjoin(fullpath, sizeof fullpath, basedir, relpath);
3193 return open(fullpath, flags, mode);
3194 #else
3195 int dirfd = AT_FDCWD; /* anchor for the relpath walk (owned unless AT_FDCWD) */
3196 int hops = SECURE_OPEN_MAXSYMLINKS; /* shared symlink-hop budget */
3197 if (basedir != NULL) {
3198 if (basedir[0] == '/') {
3199 /* Absolute basedir: operator-trusted. Prefer the identity-pinned
3200 * module-root fd when this is the served module, so a dropped-
3201 * privilege daemon need not re-traverse the absolute path. */
3202 dirfd = open_anchor_dirfd(basedir);
3203 if (dirfd == -1)
3204 return -1;
3205 } else {
3206 /* Relative basedir: resolve it on a dirfd stack anchored at
3207 * the CWD, following in-tree directory symlinks -- the
3208 * portable RESOLVE_BENEATH equivalent. A symlink target's
3209 * ".." may climb but not above the CWD anchor. */
3210 struct dirstack bds;
3211 char *bcopy;
3212 if (ds_init(&bds, AT_FDCWD) < 0)
3213 return -1;
3214 bcopy = my_strdup(basedir, __FILE__, __LINE__);
3215 if (!bcopy) {
3216 ds_free(&bds);
3217 return -1;
3218 }
3219 if (ds_walk_path(&bds, bcopy, &hops) < 0) {
3220 int e = errno;
3221 free(bcopy);
3222 ds_free(&bds);
3223 errno = e;
3224 return -1;
3225 }
3226 free(bcopy);
3227 dirfd = ds_take(&bds); /* owned dirfd for the basedir */
3228 ds_free(&bds);
3229 if (dirfd == -1)
3230 return -1;
3231 }
3232 }
3233
3234 /* Absolute path of the anchor, for the exclude-aware refusal: the cwd (==
3235 * module root for a daemon) when AT_FDCWD, or an operator-trusted absolute
3236 * basedir. A relative basedir's resolved abspath isn't tracked, so leave it
3237 * unseeded (the refusal is then a no-op for that uncommon case). */
3238 const char *anchor_abspath = !basedir ? curr_dir
3239 : (basedir[0] == '/' ? basedir : NULL);
3240 int retfd = secure_walk_at(dirfd, anchor_abspath, relpath, flags, mode, &hops);
3241 if (dirfd != AT_FDCWD)
3242 close(dirfd);
3243 return retfd;
3244 #endif // O_NOFOLLOW, O_DIRECTORY
3245 }
3246
3247 /* Common fd-anchored resolver. A caller may explicitly allow literal ".."
3248 * components when the fd itself is the confinement boundary: secure_walk_at()
3249 * resolves each one by popping its held-dirfd stack and refuses a pop above the
3250 * anchor. Other callers retain the front-door validation used by
3251 * secure_relative_open(). */
3252 static int secure_relative_open_at_internal(int anchor_fd, const char *relpath,
3253 int flags, mode_t mode, int allow_dotdot)
3254 {
3255 #if !defined(O_NOFOLLOW) || !defined(O_DIRECTORY) || !defined(AT_FDCWD)
3256 (void)anchor_fd; (void)relpath; (void)flags; (void)mode; (void)allow_dotdot;
3257 errno = ENOSYS;
3258 return -1;
3259 #else
3260 int hops = SECURE_OPEN_MAXSYMLINKS;
3261 if (!relpath || relpath[0] == '/') {
3262 errno = EINVAL;
3263 return -1;
3264 }
3265 if (!allow_dotdot && path_has_dotdot_component(relpath)) {
3266 errno = EINVAL;
3267 return -1;
3268 }
3269 #ifdef O_NOATIME
3270 if (open_noatime)
3271 flags |= O_NOATIME;
3272 #endif
3273 /* The anchor fd's absolute path isn't known here (it may be a held module
3274 * root or a climbed-to dir), so leave the abspath tracker unseeded; the
3275 * exclude-aware refusal is a no-op for this entry point. */
3276 return secure_walk_at(anchor_fd, NULL, relpath, flags, mode, &hops);
3277 #endif
3278 }
3279
3280 /* Like secure_relative_open() but anchored at an already-open directory fd
3281 * (borrowed -- the caller keeps ownership) rather than a basedir path. Lets a
3282 * caller pin the trust root once -- e.g. a daemon's module root opened while
3283 * still privileged -- and resolve a relative path beneath it without re-walking
3284 * the absolute path as a dropped-privilege uid. The ordinary entry point keeps
3285 * rejecting literal ".." components as suspicious caller input. */
3286 int secure_relative_open_at(int anchor_fd, const char *relpath, int flags, mode_t mode)
3287 {
3288 return secure_relative_open_at_internal(anchor_fd, relpath, flags, mode, 0);
3289 }
3290
3291 /* Resolve a path that may contain literal ".." beneath a trusted anchor fd.
3292 * Used for a followed symlink target, where parent-relative components are
3293 * normal pathname semantics. The held-fd stack still refuses every escape
3294 * above anchor_fd. */
3295 int secure_relative_open_at_beneath(int anchor_fd, const char *relpath,
3296 int flags, mode_t mode)
3297 {
3298 return secure_relative_open_at_internal(anchor_fd, relpath, flags, mode, 1);
3299 }
3300
3301 #if defined O_NOFOLLOW && defined O_DIRECTORY && defined AT_FDCWD
3302 /* Fill buf with len random bytes. Prefers /dev/urandom for cryptographic
3303 * quality; falls back to rand() if /dev/urandom cannot be opened or read
3304 * (e.g. inside a chroot or container without /dev populated). */
3305 static void rand_bytes(unsigned char *buf, size_t len)
3306 {
3307 #ifndef O_CLOEXEC
3308 #define O_CLOEXEC 0
3309 #endif
3310 int fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
3311 if (fd >= 0) {
3312 ssize_t n = read(fd, buf, len);
3313 close(fd);
3314 if (n == (ssize_t)len) {
3315 return;
3316 }
3317 }
3318 for (size_t i = 0; i < len; i++) {
3319 buf[i] = (unsigned char)rand();
3320 }
3321 }
3322 #endif
3323
3324 /* Create a unique temp file directly in directory `dfd` for the held-dirfd
3325 * traversal: `filename` is the basename ending in "XXXXXX", rewritten in place
3326 * to the chosen name. O_EXCL|O_NOFOLLOW so a planted name can't be followed or
3327 * clobbered. Does NOT close dfd (the caller owns it). Returns the fd, or -1.
3328 * This is the create loop shared with secure_mkstemp(). */
3329 int do_mkstemp_atfd(int dfd, char *filename, mode_t perms)
3330 {
3331 #ifdef AT_FDCWD
3332 static const char letters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
3333 size_t filename_len = strlen(filename);
3334 char *suffix;
3335 int fd = -1;
3336
3337 if (filename_len < 6) {
3338 errno = EINVAL;
3339 return -1;
3340 }
3341 suffix = filename + filename_len - 6; /* Points to XXXXXX */
3342 if (strcmp(suffix, "XXXXXX") != 0) {
3343 errno = EINVAL;
3344 return -1;
3345 }
3346
3347 perms |= S_IWUSR;
3348 for (int tries = 0; tries < 100; tries++) {
3349 unsigned char rbytes[6];
3350 rand_bytes(rbytes, sizeof(rbytes));
3351 for (int i = 0; i < 6; i++)
3352 suffix[i] = letters[rbytes[i] % (sizeof(letters) - 1)];
3353
3354 fd = openat(dfd, filename, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW, perms);
3355 if (fd >= 0)
3356 break;
3357 if (errno != EEXIST)
3358 return -1;
3359 }
3360
3361 if (fd >= 0) {
3362 if (fchmod(fd, perms) != 0 && preserve_perms) {
3363 int errno_save = errno;
3364 close(fd);
3365 unlinkat(dfd, filename, 0);
3366 errno = errno_save;
3367 return -1;
3368 }
3369 #if defined HAVE_SETMODE && O_BINARY
3370 setmode(fd, O_BINARY);
3371 #endif
3372 }
3373 return fd;
3374 #else
3375 (void)dfd; (void)filename; (void)perms;
3376 errno = ENOSYS;
3377 return -1;
3378 #endif
3379 }
3380
3381 /*
3382 Secure version of mkstemp that prevents symlink attacks on parent directories.
3383 Like secure_relative_open(), this walks the path checking each component
3384 with O_NOFOLLOW to prevent TOCTOU race conditions.
3385
3386 The template may be relative or absolute, but must not contain ../ components.
3387 Returns fd on success, -1 on error.
3388 */
3389 int secure_mkstemp(char *template, mode_t perms, int operator_path)
3390 {
3391 #if !defined(O_NOFOLLOW) || !defined(O_DIRECTORY) || !defined(AT_FDCWD)
3392 /* Fall back to regular mkstemp on old systems */
3393 return do_mkstemp(template, perms);
3394 #else
3395 char *lastslash;
3396 int dirfd = AT_FDCWD;
3397 int fd = -1;
3398
3399 if (!template) {
3400 errno = EINVAL;
3401 return -1;
3402 }
3403 if (strncmp(template, "../", 3) == 0 || strstr(template, "/../")) {
3404 errno = EINVAL;
3405 return -1;
3406 }
3407
3408 /* An operator-supplied --temp-dir may point outside the tree; --insecure-links
3409 * (or a daemon module's "insecure links =") restores legacy following. */
3410 if (operator_path && symlink_optout_allowed())
3411 return do_mkstemp(template, perms);
3412
3413 /* Open the temp file's directory. For an operator --temp-dir use the
3414 * ownership walk (follow a uid0/euid-owned symlink, refuse a foreign one,
3415 * absolute and relative alike); otherwise -- the deep-entry-dir fallback when
3416 * the held-dirfd cache declines -- use the strict transfer-path resolver
3417 * (refuse all symlinks, confine beneath the transfer root). The temp file
3418 * itself is created below with O_EXCL|O_NOFOLLOW, so a planted name can't be
3419 * followed either way. */
3420 lastslash = strrchr(template, '/');
3421 if (lastslash) {
3422 char dirbuf[MAXPATHLEN];
3423 size_t dlen = lastslash - template;
3424 const char *dir;
3425 if (dlen == 0)
3426 dir = "/";
3427 else {
3428 if (dlen >= sizeof dirbuf) {
3429 errno = ENAMETOOLONG;
3430 return -1;
3431 }
3432 memcpy(dirbuf, template, dlen);
3433 dirbuf[dlen] = '\0';
3434 dir = dirbuf;
3435 }
3436 dirfd = operator_path
3437 ? open_no_attacker_symlinks(dir, O_RDONLY | O_DIRECTORY, 0)
3438 : secure_relative_open(dir, ".", O_RDONLY | O_DIRECTORY, 0);
3439 if (dirfd < 0)
3440 return -1;
3441 }
3442
3443 /* Create the temp file in the securely-opened directory. */
3444 {
3445 char *filename = lastslash ? lastslash + 1 : template;
3446 int e;
3447 fd = do_mkstemp_atfd(dirfd, filename, perms);
3448 e = errno;
3449 if (dirfd != AT_FDCWD) close(dirfd);
3450 errno = e;
3451 }
3452 return fd;
3453 #endif
3454 }
3455
3456 /*
3457 varient of do_open/do_open_nofollow which does do_open() if the
3458 copy_links or copy_unsafe_links options are set and does
3459 do_open_nofollow() otherwise
3460
3461 This is used to prevent a race condition where an attacker could be
3462 switching a file between being a symlink and being a normal file
3463
3464 The open is always done with O_RDONLY flags
3465 */
3466 int do_open_checklinks(const char *pathname)
3467 {
3468 if (copy_links || copy_unsafe_links) {
3469 return do_open(pathname, O_RDONLY, 0);
3470 }
3471 return do_open_nofollow(pathname, O_RDONLY);
3472 }
3473
3474 /* Held-directory-fd traversal.
3475 *
3476 * Rather than re-resolve a full path on every syscall (do_*_at() re-opens the
3477 * parent via secure_relative_open() each call), the generator and receiver
3478 * open each directory ONCE via open_dir_secure() and issue single-component
3479 * *at() ops against that held dirfd with the do_*_atfd() wrappers below. The
3480 * parent is a pinned fd, not re-resolved, so the per-entry symlink-race window
3481 * is closed and the re-resolution overhead is gone.
3482 *
3483 * open_dir_secure() owns both the authority gate and the resolver choice: it
3484 * returns a held dirfd only when hardened resolution is in effect, else -1
3485 * with errno==0 so the caller falls back to the do_*_at() wrappers
3486 * (behaviour-neutral). The do_*_atfd() wrappers are thin shims with the same
3487 * leaf semantics as do_*_at() (dry-run/read-only guards, AT_SYMLINK_NOFOLLOW,
3488 * fake-super placeholder files); they never re-check the gate or re-resolve a
3489 * parent. */
3490
3491 int open_dir_secure(const char *dirname)
3492 {
3493 #ifdef AT_FDCWD
3494 extern int am_daemon, am_chrooted;
3495 int dfd;
3496
3497 /* Authority gate, identical to the do_*_at() wrappers. When hardened
3498 * resolution isn't in effect, return -1 with errno cleared so the caller
3499 * uses the full-path wrappers. */
3500 if (!secure_relpath_active()) {
3501 errno = 0;
3502 return -1;
3503 }
3504
3505 if (!dirname || !*dirname) {
3506 /* The transfer root itself (file->dirname == NULL): the cwd. */
3507 dfd = openat(AT_FDCWD, ".", O_RDONLY | O_DIRECTORY);
3508 } else if (dirname[0] == '/') {
3509 /* An absolute dirname is not expected for an in-transfer entry;
3510 * leave it to the legacy path. */
3511 errno = 0;
3512 return -1;
3513 } else {
3514 dfd = secure_relative_open(NULL, dirname, O_RDONLY | O_DIRECTORY, 0);
3515 }
3516
3517 if (dfd >= 0) {
3518 /* O_CLOEXEC on every tier (the per-component walk fallback
3519 * doesn't thread our flags onto the returned dirfd). */
3520 int fl = fcntl(dfd, F_GETFD);
3521 if (fl >= 0)
3522 fcntl(dfd, F_SETFD, fl | FD_CLOEXEC);
3523 }
3524 return dfd;
3525 #else
3526 (void)dirname;
3527 errno = 0;
3528 return -1;
3529 #endif
3530 }
3531
3532 /* Persistent ancestor-dirfd stack for held-directory traversal.
3533 *
3534 * The transfer's file list is path-sorted, so iterating it walks the tree in
3535 * DFS order and consecutive directory resolutions share a long leading prefix.
3536 * Rather than re-resolve a full path from the anchor each time (re-opening
3537 * every ancestor dir per file), we keep the whole current ancestor chain open
3538 * as pinned, race-safe dirfds and, on the next resolution, reuse the longest
3539 * common component prefix -- popping only the divergent tail and descending the
3540 * new tail. Each directory is then opened once while we are inside its subtree.
3541 *
3542 * The chain is relative to the process cwd (for a NULL anchor), so change_dir()
3543 * drops it on any real chdir; it otherwise persists across flist chunks (the
3544 * pinned fds stay valid, and a raced/replaced ancestor resolves to the original
3545 * inode the fd holds -- the held-dirfd race-safety property, not a hazard).
3546 * Each component is resolved with ds_descend(), which follows in-tree directory
3547 * symlinks exactly as secure_relative_open() does; only the resolved dir fd is
3548 * kept (intermediate symlink-target fds are closed -- sound, since an open
3549 * dirfd needs no live parent). */
3550 #if defined AT_FDCWD && defined O_NOFOLLOW && defined O_DIRECTORY
3551 #define DPC_MAXDEPTH 64
3552 static const char *dpc_anchor = (const char *)-2;
3553 static int dpc_base = -1; /* opened anchor dir (owned), or -1 */
3554 static int dpc_fd[DPC_MAXDEPTH]; /* dpc_fd[i] = dir after components 0..i */
3555 static char dpc_name[DPC_MAXDEPTH][256]; /* textual component names */
3556 static int dpc_depth = 0;
3557
3558 void reset_dir_fd_cache(void)
3559 {
3560 while (dpc_depth > 0)
3561 close(dpc_fd[--dpc_depth]);
3562 if (dpc_base >= 0)
3563 close(dpc_base);
3564 dpc_base = -1;
3565 dpc_anchor = (const char *)-2;
3566 }
3567
3568 /* Resolve directory `dirpath` beneath `anchor` (NULL = cwd, else an absolute
3569 * trusted root), reusing the held ancestor stack. Returns a BORROWED dirfd
3570 * owned by the cache (do NOT close), or -1 (errno preserved for a real open
3571 * error, errno==0 for an uncacheable path -- "..", too deep/long, or a relative
3572 * non-cwd anchor) so the caller can fall back to secure_relative_open(). */
3573 static int dpc_dir_fd(const char *anchor, const char *dirpath)
3574 {
3575 char copy[MAXPATHLEN];
3576 char *comps[DPC_MAXDEPTH];
3577 char *sv = NULL;
3578 int nc = 0, p, i;
3579
3580 if (anchor && anchor[0] != '/') { errno = 0; return -1; }
3581 if (!dirpath)
3582 dirpath = "";
3583 if (dirpath[0] == '/') { errno = 0; return -1; }
3584
3585 if (anchor != dpc_anchor || dpc_base < 0) {
3586 int fl;
3587 reset_dir_fd_cache();
3588 dpc_base = open_anchor_dirfd(anchor ? anchor : ".");
3589 if (dpc_base < 0)
3590 return -1;
3591 if ((fl = fcntl(dpc_base, F_GETFD)) >= 0)
3592 fcntl(dpc_base, F_SETFD, fl | FD_CLOEXEC);
3593 dpc_anchor = anchor;
3594 }
3595
3596 if (strlcpy(copy, dirpath, sizeof copy) >= sizeof copy) { errno = ENAMETOOLONG; return -1; }
3597 for (char *c = strtok_r(copy, "/", &sv); c; c = strtok_r(NULL, "/", &sv)) {
3598 if (c[0] == '.' && c[1] == '\0')
3599 continue; /* "." */
3600 if (c[0] == '.' && c[1] == '.' && c[2] == '\0') { errno = 0; return -1; }
3601 if (nc >= DPC_MAXDEPTH || strlen(c) >= sizeof dpc_name[0]) {
3602 /* Too deep / a too-long component to cache. Release the held
3603 * ancestor fds first so the caller's full-path fallback walk does
3604 * not stack on top of them: a deep tree plus a low RLIMIT_NOFILE
3605 * (e.g. OpenBSD's default 128) would otherwise exhaust descriptors
3606 * (cache depth + walk depth). */
3607 reset_dir_fd_cache();
3608 errno = 0;
3609 return -1;
3610 }
3611 comps[nc++] = c;
3612 }
3613
3614 /* Reuse the longest common prefix; drop the divergent tail. */
3615 for (p = 0; p < dpc_depth && p < nc && strcmp(dpc_name[p], comps[p]) == 0; p++)
3616 ;
3617 while (dpc_depth > p)
3618 close(dpc_fd[--dpc_depth]);
3619
3620 /* Descend the new tail, holding each resolved component. */
3621 for (i = p; i < nc; i++) {
3622 int afd = dpc_depth > 0 ? dpc_fd[dpc_depth-1] : dpc_base;
3623 struct dirstack ds;
3624 int hops = SECURE_OPEN_MAXSYMLINKS;
3625 int fd, fl;
3626 if (ds_init(&ds, afd) < 0)
3627 return -1;
3628 if (ds_descend(&ds, comps[i], &hops) < 0) {
3629 int e = errno;
3630 ds_free(&ds);
3631 errno = e;
3632 return -1;
3633 }
3634 fd = ds_take(&ds);
3635 ds_free(&ds); /* closes intermediate symlink fds, not afd */
3636 if (fd < 0)
3637 return -1;
3638 if ((fl = fcntl(fd, F_GETFD)) >= 0)
3639 fcntl(fd, F_SETFD, fl | FD_CLOEXEC);
3640 strlcpy(dpc_name[dpc_depth], comps[i], sizeof dpc_name[0]);
3641 dpc_fd[dpc_depth++] = fd;
3642 }
3643
3644 return nc > 0 ? dpc_fd[dpc_depth-1] : dpc_base;
3645 }
3646
3647 /* Public entry for the sender (no secure_relpath_active gate: its send paths
3648 * confine unconditionally). Borrowed fd; -1 => caller uses the full walk. */
3649 int held_dir_path_fd(const char *anchor, const char *dirpath)
3650 {
3651 return dpc_dir_fd(anchor, dirpath);
3652 }
3653
3654 int get_dir_fd(const char *dirname)
3655 {
3656 if (!secure_relpath_active()) { errno = 0; return -1; }
3657 return dpc_dir_fd(NULL, dirname);
3658 }
3659 #else
3660 void reset_dir_fd_cache(void)
3661 {
3662 }
3663 int held_dir_path_fd(const char *anchor, const char *dirpath)
3664 {
3665 (void)anchor;
3666 (void)dirpath;
3667 errno = 0;
3668 return -1;
3669 }
3670 int get_dir_fd(const char *dirname)
3671 {
3672 (void)dirname;
3673 errno = 0;
3674 return -1;
3675 }
3676 #endif
3677
3678 /* Return the cached current-directory fd iff `path` lives directly in the
3679 * entry's own directory (file->dirname) -- the common case for held-dirfd
3680 * traversal. Returns -1 (caller falls back to the do_*_at() wrappers) for
3681 * anything elsewhere: --temp-dir/--partial-dir/--backup-dir, an absolute path,
3682 * a differently-nested dir, or when open_dir_secure() is gated off. The dirfd
3683 * is opened once and cached.
3684 *
3685 * file->basename is NOT assumed to equal `path`'s leaf (a temp file has a
3686 * different basename), so the caller derives the leaf from `path`. */
3687 int held_dfd_for(const char *path, const struct file_struct *file)
3688 {
3689 const char *slash, *dn;
3690 size_t plen;
3691
3692 if (!path || *path == '/')
3693 return -1;
3694 dn = file && file->dirname ? file->dirname : "";
3695 slash = strrchr(path, '/');
3696 plen = slash ? (size_t)(slash - path) : 0;
3697 if (strlen(dn) != plen || memcmp(path, dn, plen) != 0)
3698 return -1;
3699 return get_dir_fd(file ? file->dirname : NULL);
3700 }
3701
3702 int do_unlink_atfd(int dfd, const char *name, int flags)
3703 {
3704 #ifdef AT_FDCWD
3705 if (dry_run) return 0;
3706 RETURN_ERROR_IF_RO_OR_LO;
3707 return unlinkat(dfd, name, flags);
3708 #else
3709 (void)dfd; (void)name; (void)flags;
3710 errno = ENOSYS;
3711 return -1;
3712 #endif
3713 }
3714
3715 int do_mkdir_atfd(int dfd, const char *name, mode_t mode)
3716 {
3717 #ifdef AT_FDCWD
3718 if (dry_run) return 0;
3719 RETURN_ERROR_IF_RO_OR_LO;
3720 return mkdirat(dfd, name, mode);
3721 #else
3722 (void)dfd; (void)name; (void)mode;
3723 errno = ENOSYS;
3724 return -1;
3725 #endif
3726 }
3727
3728 #ifdef HAVE_CHMOD
3729 int do_chmod_atfd(int dfd, const char *name, mode_t mode)
3730 {
3731 #ifdef AT_FDCWD
3732 if (dry_run) return 0;
3733 RETURN_ERROR_IF_RO_OR_LO;
3734 /* Do not follow a final-component symlink (closes the leaf race; the
3735 * held parent dfd already confines the ancestors). A symlink-as-object
3736 * (S_ISLNK(mode)) is still handled by the caller via the full-path
3737 * do_chmod() lchmod/setattrlist code, exactly as do_chmod_at() does. */
3738 return do_fchmodat_nofollow(dfd, name, mode);
3739 #else
3740 (void)dfd; (void)name; (void)mode;
3741 errno = ENOSYS;
3742 return -1;
3743 #endif
3744 }
3745 #endif
3746
3747 int do_lchown_atfd(int dfd, const char *name, uid_t owner, gid_t group)
3748 {
3749 #ifdef AT_FDCWD
3750 if (dry_run) return 0;
3751 RETURN_ERROR_IF_RO_OR_LO;
3752 return fchownat(dfd, name, owner, group, AT_SYMLINK_NOFOLLOW);
3753 #else
3754 (void)dfd; (void)name; (void)owner; (void)group;
3755 errno = ENOSYS;
3756 return -1;
3757 #endif
3758 }
3759
3760 /* Mode/owner on an already-open fd (no path, no symlink to follow): the
3761 * race-free way to set metadata on a cross-tree operator-path leaf that was
3762 * pinned with O_NOFOLLOW. See set_file_attrs(). */
3763 int do_fchown(int fd, uid_t owner, gid_t group)
3764 {
3765 if (dry_run) return 0;
3766 RETURN_ERROR_IF_RO_OR_LO;
3767 return fchown(fd, owner, group);
3768 }
3769
3770 #ifdef HAVE_CHMOD
3771 int do_fchmod(int fd, mode_t mode)
3772 {
3773 if (dry_run) return 0;
3774 RETURN_ERROR_IF_RO_OR_LO;
3775 return fchmod(fd, mode);
3776 }
3777 #endif
3778
3779 #ifdef HAVE_FUTIMENS
3780 /* Set times on an already-open fd (the race-free counterpart for a pinned
3781 * cross-tree operator leaf -- see set_file_attrs()). */
3782 int do_futimens(int fd, STRUCT_STAT *stp)
3783 {
3784 struct timespec t[2];
3785
3786 if (dry_run) return 0;
3787 RETURN_ERROR_IF_RO_OR_LO;
3788 t[0].tv_sec = stp->st_atime;
3789 #ifdef ST_ATIME_NSEC
3790 t[0].tv_nsec = stp->ST_ATIME_NSEC;
3791 #else
3792 t[0].tv_nsec = 0;
3793 #endif
3794 t[1].tv_sec = stp->st_mtime;
3795 #ifdef ST_MTIME_NSEC
3796 t[1].tv_nsec = stp->ST_MTIME_NSEC;
3797 #else
3798 t[1].tv_nsec = 0;
3799 #endif
3800 return futimens(fd, t);
3801 }
3802 #endif
3803
3804 #ifdef HAVE_UTIMENSAT
3805 int do_utimensat_atfd(int dfd, const char *name, STRUCT_STAT *stp)
3806 {
3807 #ifdef AT_FDCWD
3808 struct timespec t[2];
3809
3810 if (dry_run) return 0;
3811 RETURN_ERROR_IF_RO_OR_LO;
3812
3813 t[0].tv_sec = stp->st_atime;
3814 #ifdef ST_ATIME_NSEC
3815 t[0].tv_nsec = stp->ST_ATIME_NSEC;
3816 #else
3817 t[0].tv_nsec = 0;
3818 #endif
3819 t[1].tv_sec = stp->st_mtime;
3820 #ifdef ST_MTIME_NSEC
3821 t[1].tv_nsec = stp->ST_MTIME_NSEC;
3822 #else
3823 t[1].tv_nsec = 0;
3824 #endif
3825 return utimensat(dfd, name, t, AT_SYMLINK_NOFOLLOW);
3826 #else
3827 (void)dfd; (void)name; (void)stp;
3828 errno = ENOSYS;
3829 return -1;
3830 #endif
3831 }
3832 #endif
3833
3834 int do_open_atfd(int dfd, const char *name, int flags, mode_t mode)
3835 {
3836 #ifdef AT_FDCWD
3837 if (flags != O_RDONLY) {
3838 RETURN_ERROR_IF(dry_run, 0);
3839 RETURN_ERROR_IF_RO_OR_LO;
3840 }
3841 #ifdef O_NOATIME
3842 if (open_noatime)
3843 flags |= O_NOATIME;
3844 #endif
3845 return openat(dfd, name, flags | O_NOFOLLOW | O_BINARY, mode);
3846 #else
3847 (void)dfd; (void)name; (void)flags; (void)mode;
3848 errno = ENOSYS;
3849 return -1;
3850 #endif
3851 }
3852
3853 int do_symlink_atfd(const char *lnk, int dfd, const char *name)
3854 {
3855 #ifdef AT_FDCWD
3856 if (dry_run) return 0;
3857 RETURN_ERROR_IF_RO_OR_LO;
3858
3859 #if defined NO_SYMLINK_XATTRS || defined NO_SYMLINK_USER_XATTRS
3860 /* --fake-super: store the link target in a regular placeholder file,
3861 * created with O_NOFOLLOW so a planted basename symlink can't redirect
3862 * the write (mirrors do_symlink_at()). */
3863 if (am_root < 0) {
3864 int len = strlen(lnk);
3865 int ok;
3866 int fd = openat(dfd, name, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW,
3867 S_IWUSR | S_IRUSR);
3868 if (fd < 0)
3869 return -1;
3870 ok = write(fd, lnk, len) == len;
3871 if (close(fd) < 0)
3872 ok = 0;
3873 return ok ? 0 : -1;
3874 }
3875 #endif
3876 return symlinkat(lnk, dfd, name);
3877 #else
3878 (void)lnk; (void)dfd; (void)name;
3879 errno = ENOSYS;
3880 return -1;
3881 #endif
3882 }
3883
3884 int do_mknod_atfd(int dfd, const char *name, mode_t mode, dev_t dev)
3885 {
3886 #ifdef AT_FDCWD
3887 if (dry_run) return 0;
3888 RETURN_ERROR_IF_RO_OR_LO;
3889
3890 if (am_root < 0) {
3891 /* --fake-super: regular empty placeholder file (O_NOFOLLOW). */
3892 int fd = openat(dfd, name, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW,
3893 S_IWUSR | S_IRUSR);
3894 if (fd < 0)
3895 return -1;
3896 return (close(fd) < 0) ? -1 : 0;
3897 }
3898
3899 /* Try mknodat first; on failure retry race-safely with the type-
3900 * specific primitive (see do_mknod()). HAVE_MKNODAT, not HAVE_MKNOD:
3901 * older Darwin has mknod() but not mknodat(), so keying off the former
3902 * compiles a call that then fails to link (#161). */
3903 #ifdef HAVE_MKNODAT
3904 if (mknodat(dfd, name, mode, dev) == 0)
3905 return 0;
3906 #endif
3907 #ifdef HAVE_MKFIFOAT
3908 if (S_ISFIFO(mode))
3909 return mkfifoat(dfd, name, mode);
3910 #endif
3911 if (S_ISSOCK(mode)) {
3912 /* No dirfd-relative socket bind without /proc/self/fd; fail safe.
3913 * (The generator routes sockets to do_mknod_at(), not here.) */
3914 errno = EOPNOTSUPP;
3915 return -1;
3916 }
3917 #ifdef HAVE_MKNODAT
3918 return -1; /* mknodat()'s errno (regular/device node) */
3919 #else
3920 /* Must match the guard above: reporting "mknodat()'s errno" where the
3921 * call was never compiled would return a stale errno. */
3922 (void)dev;
3923 errno = ENOSYS;
3924 return -1;
3925 #endif
3926 #else
3927 (void)dfd; (void)name; (void)mode; (void)dev;
3928 errno = ENOSYS;
3929 return -1;
3930 #endif
3931 }
3932
3933 int do_rename_atfd(int old_dfd, const char *old_name, int new_dfd, const char *new_name)
3934 {
3935 #ifdef AT_FDCWD
3936 if (dry_run) return 0;
3937 RETURN_ERROR_IF_RO_OR_LO;
3938 return renameat(old_dfd, old_name, new_dfd, new_name);
3939 #else
3940 (void)old_dfd; (void)old_name; (void)new_dfd; (void)new_name;
3941 errno = ENOSYS;
3942 return -1;
3943 #endif
3944 }
3945
3946 #if defined HAVE_LINK || defined HAVE_LINKAT
3947 int do_link_atfd(int old_dfd, const char *old_name, int new_dfd, const char *new_name, int flags)
3948 {
3949 #if defined AT_FDCWD && defined HAVE_LINKAT
3950 if (dry_run) return 0;
3951 RETURN_ERROR_IF_RO_OR_LO;
3952 return linkat(old_dfd, old_name, new_dfd, new_name, flags);
3953 #else
3954 (void)old_dfd; (void)old_name; (void)new_dfd; (void)new_name; (void)flags;
3955 errno = ENOSYS;
3956 return -1;
3957 #endif
3958 }
3959 #endif
3960
3961 int do_lstat_atfd(int dfd, const char *name, STRUCT_STAT *st)
3962 {
3963 #ifdef AT_FDCWD
3964 # ifdef SUPPORT_LINKS
3965 return fstatat(dfd, name, st, AT_SYMLINK_NOFOLLOW);
3966 # else
3967 return fstatat(dfd, name, st, 0);
3968 # endif
3969 #else
3970 (void)dfd; (void)name; (void)st;
3971 errno = ENOSYS;
3972 return -1;
3973 #endif
3974 }
3975
3976 int do_stat_atfd(int dfd, const char *name, STRUCT_STAT *st)
3977 {
3978 #ifdef AT_FDCWD
3979 return fstatat(dfd, name, st, 0);
3980 #else
3981 (void)dfd; (void)name; (void)st;
3982 errno = ENOSYS;
3983 return -1;
3984 #endif
3985 }