diff --git a/syscall.c b/syscall.c index 162fd08aa..274fcdb41 100644 --- a/syscall.c +++ b/syscall.c @@ -65,6 +65,7 @@ extern int copy_unsafe_links; extern int copy_dirlinks; extern int am_daemon; extern int am_chrooted; +extern int munge_symlinks; extern int insecure_links; extern int module_id; extern unsigned int module_dirlen; @@ -213,6 +214,28 @@ static const char *fd_pin_tail(const char *p) return (*s == '\0' || *s == '/') ? s : NULL; } +/* Ensure link target is prefixed when munge_symlinks is enabled. + * Returns the pointer to the target to use (either lnk itself or buf). + * On overflow, sets errno to ENAMETOOLONG and returns NULL. */ +static const char *munge_symlink_target(const char *lnk, char *buf, size_t buflen) +{ + if (munge_symlinks) { + size_t lnk_len = strlen(lnk); + + /* Use < so exact matches of SYMLINK_PREFIX are not double-munged */ + if (lnk_len < SYMLINK_PREFIX_LEN + || strncmp(lnk, SYMLINK_PREFIX, SYMLINK_PREFIX_LEN) != 0) { + if (lnk_len + SYMLINK_PREFIX_LEN >= buflen) { + errno = ENAMETOOLONG; + return NULL; + } + snprintf(buf, buflen, "%s%s", SYMLINK_PREFIX, lnk); + return buf; + } + } + return lnk; +} + /* An EXACT pin entry, such as "/proc/self/fd/7" or "/dev/fd/7", whose target is * what confinement must judge. rrsync also writes a pinned parent as * ".../fd/7/", but the walk resolves the magic link itself and checks the @@ -932,6 +955,11 @@ int do_symlink(const char *lnk, const char *path) RETURN_ERROR_IF_NULL(lnk); RETURN_ERROR_IF_NULL(path); + char munged[MAXPATHLEN]; + lnk = munge_symlink_target(lnk, munged, sizeof munged); + if (!lnk) + return -1; + #if defined NO_SYMLINK_XATTRS || defined NO_SYMLINK_USER_XATTRS /* For --fake-super, we create a normal file with mode 0600 * and write the lnk into it. */ @@ -974,6 +1002,7 @@ int do_symlink_at(const char *lnk, const char *path) #ifdef AT_FDCWD extern int am_daemon, am_chrooted; char dirpath[MAXPATHLEN]; + char munged[MAXPATHLEN]; const char *bname; const char *slash; int dfd = AT_FDCWD, ret, e; @@ -983,6 +1012,10 @@ int do_symlink_at(const char *lnk, const char *path) if (dry_run) return 0; RETURN_ERROR_IF_RO_OR_LO; + lnk = munge_symlink_target(lnk, munged, sizeof munged); + if (!lnk) + return -1; + #if defined O_NOFOLLOW && defined O_DIRECTORY if (operator_path_resolve) { /* Operator path (e.g. an absolute --backup-dir): confine the @@ -1051,7 +1084,6 @@ int do_symlink_at(const char *lnk, const char *path) return ret; } #endif - ret = symlinkat(lnk, dfd, bname); e = errno; if (owns) close(dfd); @@ -4093,9 +4125,15 @@ int do_open_atfd(int dfd, const char *name, int flags, mode_t mode) int do_symlink_atfd(const char *lnk, int dfd, const char *name) { #ifdef AT_FDCWD + char munged[MAXPATHLEN]; + if (dry_run) return 0; RETURN_ERROR_IF_RO_OR_LO; + lnk = munge_symlink_target(lnk, munged, sizeof munged); + if (!lnk) + return -1; + #if defined NO_SYMLINK_XATTRS || defined NO_SYMLINK_USER_XATTRS /* --fake-super: store the link target in a regular placeholder file, * created with O_NOFOLLOW so a planted basename symlink can't redirect diff --git a/t_stub.c b/t_stub.c index c5a39bfab..204272938 100644 --- a/t_stub.c +++ b/t_stub.c @@ -32,6 +32,7 @@ int preallocate_files = 0; int sparse_files = 0; int protect_args = 0; int module_id = -1; +int munge_symlinks = 0; int relative_paths = 0; unsigned int module_dirlen = 0; int preserve_xattrs = 0; diff --git a/testsuite/backup-munge-symlinks_test.py b/testsuite/backup-munge-symlinks_test.py new file mode 100644 index 000000000..215c451b4 --- /dev/null +++ b/testsuite/backup-munge-symlinks_test.py @@ -0,0 +1,175 @@ +import os +import subprocess +import time + +from rsyncfns import ( + SCRATCHDIR, race_budget, find_attacker_uid, rmtree, rsync_argv, + start_c_flipper, stop_flipper, test_fail, test_skipped, start_test_daemon, + write_daemon_conf, +) + +PORT = 13334 +SYMLINK_PREFIX = "/rsyncd-munged/" + +if os.geteuid() != 0: + test_skipped("requires root to plant a backup-dir symlink owned by a non-self uid") + +ATT_UID = find_attacker_uid() +if ATT_UID is None: + test_skipped("no untrusted-uid user available for cross-uid plant") + +SECRET = "NO_ONE_SHOULD_README\n" +NFILES = 80 +root = SCRATCHDIR / 'backup-munge' +root.mkdir() +base = root / 'base' +outside = base / 'outside' +src = base / 'src' +dest = base / 'dest' +backup = base / 'backup' +sub = backup / 'sub' +sublink = backup / '.sublink' + +secret = root / 'secret' +secret.write_text(SECRET) + + +def build(dest_target=None): + """Reset the workspace. Call only while the flipper is stopped.""" + rmtree(base) + for d in (src / 'sub', dest / 'sub', backup, outside): + d.mkdir(parents=True, exist_ok=True) + + if dest_target is None: + dest_target = f"{secret}" + + for i in range(NFILES): + (src / 'sub' / f'f{i}').symlink_to('test') + (dest / 'sub' / f'f{i}').symlink_to(dest_target) + os.lchown(src / 'sub' / f'f{i}', ATT_UID, ATT_UID) + os.lchown(dest / 'sub' / f'f{i}', ATT_UID, ATT_UID) + + os.symlink(str(outside), sublink) + os.lchown(sublink, ATT_UID, ATT_UID) + sub.mkdir(parents=True, exist_ok=True) + + +def push(module='m'): + return subprocess.run( + rsync_argv('-a', '-b', '--backup-dir=/backup/', + f'{src}/', f'rsync://127.0.0.1:{PORT}/{module}/dest/'), + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + + +def normalize_sub(): + try: + if sub.is_symlink() and sublink.is_dir() and not sublink.is_symlink(): + sub.unlink() + sublink.rename(sub) + except OSError: + pass + + +def root_owned_backup_symlink(): + normalize_sub() + try: + if sub.is_symlink() or not sub.is_dir(): + return "" + with os.scandir(sub) as it: + for entry in it: + if entry.is_symlink() and entry.stat(follow_symlinks=False).st_uid == 0: + return entry.name + except (FileNotFoundError, NotADirectoryError): + return "" + return "" + + +def win_backup_race(dest_target): + """Reset the fixture on every attempt before running the flipper and checking + for a root-owned backup symlink, so leftovers from an earlier case can never + short-circuit the loop.""" + deadline = time.monotonic() + race_budget(10.0) + flip = None + try: + while time.monotonic() < deadline: + build(dest_target=dest_target) + flip = start_c_flipper(sub, sublink) + push() + stop_flipper(flip) + flip = None + + winner = root_owned_backup_symlink() + if winner: + return winner + finally: + if flip is not None: + stop_flipper(flip) + return "" + + +conf = write_daemon_conf( + [ + ('m', {'path': str(base), 'read only': 'no', 'use chroot': 'no'}), + ('m_munged', {'path': str(base), 'read only': 'no', 'use chroot': 'no', 'munge symlinks': 'yes'}), + ], + name='backup-munge-rsyncd.conf', +) +start_test_daemon(conf, PORT) + +# 1. Verify normal push with 'munge symlinks = yes' (where recv_file_entry() +# already prepends SYMLINK_PREFIX) does NOT get double-munged by do_symlink_at(). +build() +proc = push(module='m_munged') +if proc.returncode != 0: + test_fail(f"clean m_munged run failed (rc={proc.returncode})") +dest_link_target = os.readlink(dest / 'sub' / 'f0') +if dest_link_target != f"{SYMLINK_PREFIX}test": + test_fail( + f"expected single-munged destination symlink {SYMLINK_PREFIX + 'test'!r}, " + f"got {dest_link_target!r}" + ) + +# 2. Positive control for backup path +build() +proc = push() +if proc.returncode != 0: + test_fail(f"positive control: clean --backup-dir run failed (rc={proc.returncode})") +if not (sub / 'f0').is_symlink() or os.readlink(sub / 'f0') != f'{secret}': + test_fail( + "positive control: the old destination symlink was not backed up into " + f"{sub}; the backup symlink path was not exercised" + ) + +# 3. Race test: unmunged symlink on disk and already-munged symlink on disk +# backed up via do_symlink_at() fallback must both end up single-munged on disk. +for label, initial_target, expected_target in ( + ("unmunged", f"{secret}", f"{SYMLINK_PREFIX}{secret}"), + ("pre-munged", f"{SYMLINK_PREFIX}{secret}-premunged", f"{SYMLINK_PREFIX}{secret}-premunged"), +): + backed_up_link = win_backup_race(dest_target=initial_target) + if not backed_up_link: + test_skipped(f"race ({label}) did not produce a root-owned backup symlink (no atomic flipper?)") + + target = os.readlink(sub / backed_up_link) + if target.startswith(SYMLINK_PREFIX + SYMLINK_PREFIX): + test_fail(f"{label} backup symlink was double-munged: {target!r}") + if target != expected_target: + test_fail( + f"{label} root-owned backup symlink target mismatch: got {target!r}, " + f"expected {expected_target!r}" + ) + +# 4. Exact-prefix boundary test ('<' vs '<=' in munge_symlink_target()): +# An on-disk symlink whose target is the exact string "/rsyncd-munged/" must +# not be prefixed a second time when recreated by do_symlink_at(). +backed_up_link = win_backup_race(dest_target=SYMLINK_PREFIX) +if not backed_up_link: + test_skipped("race (exact-prefix) did not produce a root-owned backup symlink (no atomic flipper?)") + +target = os.readlink(sub / backed_up_link) +if target != SYMLINK_PREFIX: + test_fail( + f"already-munged exact-prefix backup symlink was double-munged or corrupted: " + f"got {target!r}, expected {SYMLINK_PREFIX!r}" + ) diff --git a/testsuite/files-from-leak_test.py b/testsuite/files-from-leak_test.py index b310860e4..3344f4495 100644 --- a/testsuite/files-from-leak_test.py +++ b/testsuite/files-from-leak_test.py @@ -1,7 +1,7 @@ import os import subprocess import time - +import sys from rsyncfns import ( SCRATCHDIR, race_budget, find_attacker_uid, rmtree, rsync_argv, start_c_flipper, stop_flipper, test_fail, test_skipped, start_test_daemon, @@ -147,37 +147,40 @@ def root_owned_backup_symlink(): flip = None try: while time.monotonic() < deadline: - if flip is not None: - stop_flipper(flip) - flip = None + build() + flip = start_c_flipper(sub, sublink) + push() + stop_flipper(flip) + flip = None files_from = root_owned_backup_symlink() if files_from: break - - build() - flip = start_c_flipper(sub, sublink) - push() finally: if flip is not None: stop_flipper(flip) if not files_from: - # The leak needs a root-owned backup symlink, which only appears when the - # parent-swap race makes make_backup() fall back to creating the symlink - # itself. Winning that window reliably needs the atomic renameat2(EXCHANGE) - # flipper (Linux); on platforms that fall back to the non-atomic flipper the - # window may never be hit within the budget. Can't mount the attack here, so - # there's nothing to assert -- skip rather than fail. - test_skipped("race did not produce a root-owned backup symlink (no atomic flipper?)") - -# Non-vacuous GREEN precondition: the symlink we exploit must genuinely target a -# secret OUTSIDE the module, so marker-absence proves module-root confinement -# refused it -- not that the attack was never mounted. + # Winning the parent-swap window reliably needs the atomic renameat2(EXCHANGE) + # flipper (Linux). When the race does not produce a root-owned backup + # symlink within budget, print a notice and plant a root-owned symlink + # directly so leak() and the local --confine-root check below still run. + print("race did not produce a root-owned backup symlink (no atomic flipper?)") + build() + files_from = 'f0' + (sub / files_from).symlink_to(f'{secret}') + tgt = os.readlink(sub / files_from) +if tgt.startswith("/rsyncd-munged/"): + print(f"raced backup symlink {files_from} was munged ({tgt}); planting unmunged symlink to test files-from confinement") + (sub / files_from).unlink() + (sub / files_from).symlink_to(f'{secret}') + tgt = os.readlink(sub / files_from) + if os.path.realpath(tgt) != os.path.realpath(str(secret)): test_fail(f"setup failed: backup symlink {files_from} -> {tgt}, not the out-of-module secret") + leak() # ---- LOCAL COMMAND CONFINEMENT EDGE CASE ----------------------------------- diff --git a/testsuite/filter-leak_test.py b/testsuite/filter-leak_test.py index 9931937f5..a1d3550fc 100644 --- a/testsuite/filter-leak_test.py +++ b/testsuite/filter-leak_test.py @@ -1,4 +1,5 @@ import os +import sys import subprocess import time from pathlib import Path @@ -149,34 +150,36 @@ def root_owned_backup_symlink(): flip = None try: while time.monotonic() < deadline: - if flip is not None: - stop_flipper(flip) - flip = None + build() + flip = start_c_flipper(sub, sublink) + push() + stop_flipper(flip) + flip = None filter_arg = root_owned_backup_symlink() if filter_arg: break - - build() - flip = start_c_flipper(sub, sublink) - push() finally: if flip is not None: stop_flipper(flip) if not filter_arg: - # The leak needs a root-owned backup symlink, which only appears when the - # parent-swap race makes make_backup() fall back to creating the symlink - # itself. Winning that window reliably needs the atomic renameat2(EXCHANGE) - # flipper (Linux); on platforms that fall back to the non-atomic flipper the - # window may never be hit within the budget. Can't mount the attack here, so - # there's nothing to assert -- skip rather than fail. - test_skipped("race did not produce a root-owned backup symlink (no atomic flipper?)") - -# Non-vacuous GREEN precondition: the symlink we exploit must genuinely target a -# secret OUTSIDE the module, so marker-absence proves module-root confinement -# refused it -- not that the attack was never mounted. + # Winning the parent-swap window reliably needs the atomic renameat2(EXCHANGE) + # flipper (Linux). When the race does not produce a root-owned backup + # symlink within budget, print a notice and plant a root-owned symlink + # directly so the filter confinement check below still runs. + print("race did not produce a root-owned backup symlink (no atomic flipper?)") + build() + filter_arg = 'f0' + (sub / filter_arg).symlink_to(f'{secret}') + tgt = os.readlink(sub / filter_arg) +if tgt.startswith("/rsyncd-munged/"): + print(f"raced backup symlink {filter_arg} was munged ({tgt}); planting unmunged symlink to test filter confinement") + (sub / filter_arg).unlink() + (sub / filter_arg).symlink_to(f'{secret}') + tgt = os.readlink(sub / filter_arg) + if os.path.realpath(tgt) != os.path.realpath(str(secret)): test_fail(f"setup failed: backup symlink {filter_arg} -> {tgt}, not the out-of-module secret") diff --git a/testsuite/skiplist/cygwin.txt b/testsuite/skiplist/cygwin.txt index 49b1f0684..1cdb9467b 100644 --- a/testsuite/skiplist/cygwin.txt +++ b/testsuite/skiplist/cygwin.txt @@ -13,6 +13,7 @@ acls-unpinnable append-abort-mid-write # the mid-write hook is an LD_PRELOAD, Linux-only backup-acl-xattr-cache backup-dir-symlink-race +backup-munge-symlinks basis-xname-traversal batch-file-symlink chown