Debian Codegraph @

syscall.c

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