From 6ef38846db2f482026dd436a9f0cd6d19c65639a Mon Sep 17 00:00:00 2001 From: seks99x Date: Sun, 15 Nov 2026 21:48:46 +0300 Subject: [PATCH] Enforce --confine-root on source and destination paths and update confinement tests Reported-by: --- receiver.c | 3 +- syscall.c | 2 +- .../tests/path/confine-root-dest-symlink.py | 118 ++++++++++++++++++ testsuite/tests/path/confine-root-source.py | 97 ++++++++++++++ testsuite/tests/path/pseudo-paths.py | 86 ++++++++----- .../tests/rrsync/rrsync-merge-file-confine.py | 51 +++++++- .../tests/rrsync/rrsync-userns-procfs.py | 6 +- util1.c | 14 ++- 8 files changed, 333 insertions(+), 44 deletions(-) create mode 100644 testsuite/tests/path/confine-root-dest-symlink.py create mode 100644 testsuite/tests/path/confine-root-source.py diff --git a/receiver.c b/receiver.c index 3a623cd62..0314bffce 100644 --- a/receiver.c +++ b/receiver.c @@ -1113,7 +1113,8 @@ int recv_files(int f_in, int f_out, char *local_name) * partial updates rejects the unsafe peer option; otherwise (a pre-30 * peer, where no in-place partial redirect is possible, or a pull * client) fall back to a safe no-basis update. */ - if (am_daemon && inplace_partial) { + extern char *confine_root; + if ((am_daemon || confine_root) && inplace_partial) { rprintf(FERROR, "rsync: refusing unconfined partial basis for %s\n", fname); exit_cleanup(RERR_PROTOCOL); diff --git a/syscall.c b/syscall.c index 162fd08aa..b4234ae27 100644 --- a/syscall.c +++ b/syscall.c @@ -587,7 +587,7 @@ static int ona_open(const char *path, int flags, mode_t mode, char *out_abs, siz saved_errno = ENOTDIR; goto out; } - if (confine_root) { + if (confine_root && (operator_path_resolve || filesfrom_owner_walk_active())) { /* Anonymous objects cannot be proven to reside beneath * the confinement root. */ saved_errno = ENOENT; diff --git a/testsuite/tests/path/confine-root-dest-symlink.py b/testsuite/tests/path/confine-root-dest-symlink.py new file mode 100644 index 000000000..89654f9c3 --- /dev/null +++ b/testsuite/tests/path/confine-root-dest-symlink.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +"""Regression test for --confine-root main-transfer destination confinement. + +Note: The symlink checks here do not represent a pure untrusted-symlink +vulnerability, as they rely on a pre-existing ("trusted") symlink placed +inside the root (or local privilege to swap it in). Rather, they test that +incomplete confinement around trusted in-tree symlinks still does not permit +resolving or writing to targets outside --confine-root. +""" + +import os +import platform +import subprocess +import time + +from harness.mutation import race_budget, start_c_flipper, stop_flipper +from harness.process import quote_command +from harness.environment import SCRATCHDIR +from harness.filesystem import rmtree +from harness.results import test_fail, test_skipped +from harness.rsync import rsync_argv +from harness import metadata + +metadata(features={'dirfd_pinning'}, transports={'pipe'}) + +_CYGWIN = platform.system().startswith('CYGWIN') + +base = SCRATCHDIR / 'confine-root-dest' +rmtree(base) +base.mkdir(parents=True, exist_ok=True) + +dir_root = base / 'dir' +outside = base / 'outside' +src_dir = base / 'src_files' +sub = dir_root / 'sub' +sublink = dir_root / 'sublink' +rsh = base / 'rsh.sh' + +rsh.write_text(f"""#!/bin/sh +while [ $# -gt 0 ] && [ "$1" != "--server" ]; do + shift +done +cd "{dir_root}" || exit 1 +exec {quote_command(rsync_argv())} --confine-root="{dir_root}" "$@" +""") +os.chmod(rsh, 0o755) + + +def build(): + for d in (dir_root, outside, src_dir): + rmtree(d) + d.mkdir(parents=True, exist_ok=True) + sub.mkdir(parents=True, exist_ok=True) + (src_dir / 'test').write_text("PAYLOAD\n") + (outside / 'test').write_text("VICTIM\n") + os.symlink(str(outside), sublink) + + +def push_server(remote_dest, *extra): + subprocess.run( + rsync_argv('-I', *extra, '-e', str(rsh), + str(src_dir / 'test'), f'h:{remote_dest}'), + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + + +# 0. Sanity check: valid in-tree server transfer must succeed. +build() + +push_server('sub/ok_server') +if not (sub / 'ok_server').is_file() or (sub / 'ok_server').read_text() != "PAYLOAD\n": + test_fail("sanity failed: server transfer into confined sub/ok_server failed") + +# 1. Deterministic checks. +build() + +# 1a. Pre-existing ("trusted") in-tree symlink pointing outside the root: +# Not a remote symlink-creation bug, but verifies that a trusted symlink inside +# the tree is still strictly bounded by --confine-root and cannot write outside. +push_server('sublink/test') +if (outside / 'test').read_text() != "VICTIM\n": + test_fail("server confine-root failed to block write through in-tree symlink sublink/test") + +# 1b. Server relative '..' escape: ../outside/test +push_server('../outside/test') +if (outside / 'test').read_text() != "VICTIM\n": + test_fail("server confine-root failed to block relative destination ../outside/test") + +# 1c. Server new file creation outside DIR (O_CREAT path) +push_server('../outside/newfile') +if (outside / 'newfile').exists(): + test_fail("server confine-root failed to block creating ../outside/newfile") + +# 1d. Server new directory creation outside DIR +push_server('../outside/newdir/test') +if (outside / 'newdir').exists(): + test_fail("server confine-root failed to block creating ../outside/newdir") + +# 2. Live race check. +deadline = time.monotonic() + race_budget(10.0) +flip = None +try: + while time.monotonic() < deadline: + if flip is not None: + stop_flipper(flip) + flip = None + + build() + flip = start_c_flipper(sub, sublink) + for _ in range(20): + push_server('sub/test') + if (outside / 'test').read_text() != "VICTIM\n": + if _CYGWIN: + test_skipped('Cygwin destination transfer followed a swapped parent symlink', capability='dirfd_pinning') + test_fail("confine-root race escape: wrote outside/test during parent flip") +finally: + if flip is not None: + stop_flipper(flip) diff --git a/testsuite/tests/path/confine-root-source.py b/testsuite/tests/path/confine-root-source.py new file mode 100644 index 000000000..b97733745 --- /dev/null +++ b/testsuite/tests/path/confine-root-source.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +"""Regression test for --confine-root sender source confinement. + +Verifies that a server sender running under --confine-root refuses to +traverse out of the confined root via a pre-existing ("trusted") in-tree +symlink or a relative '..' source argument during a pull transfer. +""" + +import os +import subprocess + +from harness.process import quote_command +from harness.environment import SCRATCHDIR +from harness.filesystem import rmtree +from harness.results import test_fail +from harness.rsync import rsync_argv +from harness import metadata + +metadata(transports={'pipe'}) + +base = SCRATCHDIR / 'confine-root-source' +rmtree(base) +base.mkdir(parents=True, exist_ok=True) + +dir_root = base / 'dir' +outside = base / 'outside' +dest_dir = base / 'dest' +sub = dir_root / 'sub' +sublink = dir_root / 'sublink' +rsh = base / 'rsh.sh' + +rsh.write_text(f"""#!/bin/sh +while [ $# -gt 0 ] && [ "$1" != "--server" ]; do + shift +done +cd "{dir_root}" || exit 1 +exec {quote_command(rsync_argv())} --confine-root="{dir_root}" "$@" +""") +os.chmod(rsh, 0o755) + + +def build(): + for d in (dir_root, outside, dest_dir): + rmtree(d) + d.mkdir(parents=True, exist_ok=True) + sub.mkdir(parents=True, exist_ok=True) + (sub / 'ok_file').write_text("ALLOWED\n") + (outside / 'secret').write_text("SECRET\n") + os.symlink(str(outside), sublink) + + +def pull_server(remote_src, *extra): + rmtree(dest_dir) + dest_dir.mkdir(parents=True, exist_ok=True) + return subprocess.run( + rsync_argv('-I', *extra, '-e', str(rsh), + f'h:{remote_src}', f'{dest_dir}/'), + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + + +# 0. Sanity check: valid in-tree sender pull must succeed. +build() + +pull_server('sub/ok_file') +if not (dest_dir / 'ok_file').is_file() or (dest_dir / 'ok_file').read_text() != "ALLOWED\n": + test_fail("sanity failed: pull from confined sender sub/ok_file failed") + +# 1. Static source symlink and traversal checks. +build() + +# 1a. Pre-existing ("trusted") in-tree symlink pointing outside the root +# (pulling a file through the symlinked directory: sublink/secret) +pull_server('sublink/secret') +if (dest_dir / 'secret').exists(): + test_fail("sender confine-root failed to block pull through in-tree symlink sublink/secret") + +# 1b. Pre-existing ("trusted") in-tree symlink as a directory source with +# trailing slash (forces change_dir into the symlink target: sublink/) +pull_server('sublink/', '-r') +if (dest_dir / 'secret').exists(): + test_fail("sender confine-root failed to block recursive pull of symlinked dir sublink/") + +# 1c. Dereferencing in-tree symlink via --copy-links (-L) +pull_server('sublink/secret', '-L') +if (dest_dir / 'secret').exists(): + test_fail("sender confine-root -L failed to block pull through sublink/secret") + +# 1d. Relative '..' source escape: ../outside/secret +pull_server('../outside/secret') +if (dest_dir / 'secret').exists(): + test_fail("sender confine-root failed to block relative source ../outside/secret") + +# 1e. Nested '..' source escape: sub/../../outside/secret +pull_server('sub/../../outside/secret') +if (dest_dir / 'secret').exists(): + test_fail("sender confine-root failed to block nested relative source sub/../../outside/secret") diff --git a/testsuite/tests/path/pseudo-paths.py b/testsuite/tests/path/pseudo-paths.py index 3770a4e87..52d085c4e 100644 --- a/testsuite/tests/path/pseudo-paths.py +++ b/testsuite/tests/path/pseudo-paths.py @@ -1,4 +1,9 @@ #!/usr/bin/env python3 +"""Process substitution /dev/fd/ write pipe pseudo-paths for --log-file must +not crash and must successfully write logs, including when --confine-root is +active, because the log path is a trusted operator-supplied argument backed by +an inherited kernel descriptor rather than an untrusted in-tree transfer path. +""" import os import shlex @@ -21,11 +26,16 @@ test_skipped('Kernel pseudo-path string is a Linux-specific procfs feature', capability='proc_fd') raise SystemExit(0) +# We require bash specifically because standard POSIX /bin/sh does not +# guarantee support for >(...) process substitution syntax. bash = shutil.which('bash') if bash is None: test_skipped('bash is unavailable, cannot test process substitution', capability='proc_fd') +# runtests.py exports POSIXLY_CORRECT=1, and bash before 5.1 disables process +# substitution in POSIX mode -- the very syntax bash is required for here. bash_env = {k: v for k, v in os.environ.items() if k != 'POSIXLY_CORRECT'} +# Verify the host bash actually supports process substitution. probe = subprocess.run( [bash, '-c', 'echo "probe" > >(cat > /dev/null)'], capture_output=True, @@ -50,6 +60,7 @@ log_path = shlex.quote(str(log_out)) log_path_confined = shlex.quote(str(log_out_confined)) +# TEST 1: Unconfined process substitution (Should Succeed) bash_script = f"{rsync_base_cmd} -v --log-file=>(cat > {log_path}) {src_path} {dest_path}" try: @@ -85,7 +96,16 @@ print('Test 1 Passed: rsync successfully wrote logs to a process substitution pseudo-path') -bash_script_confined = f"{rsync_base_cmd} --confine-root={dest_path} -v --log-file=>(cat > {log_path_confined}) {src_path} {dest_path}" +# TEST 2: Confined Root (Should Accept Pseudo-path for --log-file) +# --confine-root bounds the transfer tree against untrusted path traversal, +# but --log-file=>(...) is a trusted operator-supplied argument resolving to +# an inherited /dev/fd/N kernel pipe. Even though /dev/fd/N (and /proc/self/fd) +# lives outside the confined root, rsync must permit opening it and write the +# log normally. +base_path = shlex.quote(str(base)) +rmtree(dest) +makepath(dest) +bash_script_confined = f"{rsync_base_cmd} --confine-root={base_path} -v --log-file=>(cat > {log_path_confined}) {src_path} {dest_path}" try: proc_confined = subprocess.run( @@ -101,47 +121,34 @@ ctx_confined = f'rc={proc_confined.returncode}, stderr={proc_confined.stderr.strip()!r}' -stderr_lower = proc_confined.stderr.lower() -if "no such file or directory" in stderr_lower and "failed to open" in stderr_lower: - if log_out_confined.exists() and log_out_confined.stat().st_size > 0: - rmtree(base) - test_fail(f'rsync printed an error but still wrote the confined log! ({ctx_confined})') - print('Test 2 Passed: rsync correctly rejected the pseudo-path when confine_root was active') -else: +if proc_confined.returncode != 0: rmtree(base) - test_fail(f'rsync failed to reject the pseudo-path or had an unexpected error ({ctx_confined})') + test_fail(f'rsync failed when writing to a pseudo-path log pipe under --confine-root ({ctx_confined})') -rmtree(dest) -makepath(dest) -trailing_script = ( - f'pipe_path=<(printf "transfer_me.txt\\n"); ' - f'{rsync_base_cmd} --exclude-from="$pipe_path/trailing" {src_path} {dest_path}' -) -try: - proc_trailing = subprocess.run( - [bash, '-c', trailing_script], - capture_output=True, - env=bash_env, - text=True, - timeout=10, - ) -except subprocess.TimeoutExpired: +if not (dest / 'transfer_me.txt').is_file(): rmtree(base) - test_fail('trailing-component pseudo-path test timed out') + test_fail(f'rsync failed to transfer the allowed file under --confine-root ({ctx_confined})') -if proc_trailing.returncode == 0: +if not log_out_confined.exists() or log_out_confined.stat().st_size == 0: rmtree(base) - test_fail('/dev/fd/N/trailing unexpectedly opened descriptor N') -if (dest / 'transfer_me.txt').exists(): + test_fail(f'rsync failed to write data to the log pipe under --confine-root ({ctx_confined})') + +log_data_confined = log_out_confined.read_text() +if "transfer_me.txt" not in log_data_confined: rmtree(base) - test_fail('transfer continued after accepting a trailing pseudo-path component') + test_fail(f'Confined log pipe is missing expected output: {log_data_confined[:100]}') + +print('Test 2 Passed: rsync successfully wrote logs to a process substitution pseudo-path under --confine-root') +# TEST 3: Standard I/O Symlinks (/dev/stdin, /dev/stdout) - Unconfined print("Running Test 3: Standard I/O Symlinks (/dev/stdin)...", flush=True) rmtree(dest) makepath(dest) (src / 'stdin_test.txt').write_text('stdin data\n') +# TEST 3A: --files-from=/dev/stdin +# Piping printf directly into rsync forces /dev/stdin to resolve to pipe:[N]. stdin_script = f'printf "stdin_test.txt\\n" | {rsync_base_cmd} --files-from=/dev/stdin {src_path} {dest_path}' proc_stdin = subprocess.run([bash, '-c', stdin_script], env=bash_env, capture_output=True, text=True, timeout=10) @@ -149,10 +156,11 @@ test_fail(f'rsync failed to read --files-from=/dev/stdin (rc={proc_stdin.returncode}, stderr={proc_stdin.stderr.strip()!r})') if not (dest / 'stdin_test.txt').is_file(): - test_fail(f'rsync failed to transfer file specified via /dev/stdin') + test_fail('rsync failed to transfer file specified via /dev/stdin') print('Test 3A Passed: rsync successfully read files-from via /dev/stdin', flush=True) +# TEST 3B: Nested Trusted Symlink to /dev/stdin rmtree(dest) makepath(dest) @@ -160,6 +168,7 @@ if symlink_list.is_symlink() or symlink_list.exists(): symlink_list.unlink() +# Create the trusted nested symlink pointing to the kernel pipe. symlink_list.symlink_to('/dev/stdin') symlink_script = f'printf "stdin_test.txt\\n" | {rsync_base_cmd} --files-from={shlex.quote(str(symlink_list))} {src_path} {dest_path}' @@ -169,32 +178,37 @@ test_fail(f'/dev/stdin files-from symlink failed: rc={proc_symlink.returncode}, stderr={proc_symlink.stderr.strip()!r}') if not (dest / 'stdin_test.txt').is_file(): - test_fail(f'rsync failed to follow trusted symlink to /dev/stdin to read files-from list') + test_fail('rsync failed to follow trusted symlink to /dev/stdin to read files-from list') print('Test 3B Passed: rsync successfully resolved a trusted nested symlink to /dev/stdin', flush=True) +# TEST 3C: Spoofed Relative Path to Pseudo-pipe (Spoofed dev/fd/x) print("Running Test 3C: Spoofed Relative Path to Pseudo-pipe (dev/fd/99)...", flush=True) rmtree(dest) makepath(dest) +# Create a local, relative 'dev/fd' structure inside our working directory. spoofed_dev_fd = base / 'dev' / 'fd' makepath(spoofed_dev_fd) +# Create a real file called 'pipe:[' with valid data. spoofed_target = spoofed_dev_fd / 'pipe:[' spoofed_target.write_text('transfer_me.txt\n') +# Create a symlink named '99' that points to the literal file 'pipe:['. spoofed_symlink = spoofed_dev_fd / '99' if spoofed_symlink.is_symlink() or spoofed_symlink.exists(): spoofed_symlink.unlink() spoofed_symlink.symlink_to('pipe:[') +# Run rsync using --files-from targeting the spoofed path. spoofed_script = f'cd {shlex.quote(str(base))} && {rsync_base_cmd} --files-from=dev/fd/99 {src_path} {dest_path}' proc_spoofed = subprocess.run([bash, '-c', spoofed_script], env=bash_env, capture_output=True, text=True, timeout=10) stderr_lower = proc_spoofed.stderr.lower() -if "levels of symbolic links" in stderr_lower or "eloop" in stderr_lower: +if "levels of symbolic links" in stderr_lower or "symbolic link loop" in stderr_lower or "eloop" in stderr_lower: test_fail(f'spoofed pseudo-path returned ELOOP: rc={proc_spoofed.returncode}, stderr={proc_spoofed.stderr.strip()!r}') if proc_spoofed.returncode != 0: @@ -202,6 +216,7 @@ print('Test 3C Passed: rsync correctly treated the un-anchored spoofed path as a normal file rather than a kernel pseudo-path.', flush=True) +# SETUP FOR NAMESPACE TESTS (TEST 4) unshare = shutil.which('unshare') if unshare is None: print('unshare is unavailable') @@ -231,6 +246,7 @@ print(f'user namespaces unavailable (rc={probe.returncode})') raise SystemExit(0) +# Verify the namespace exposes the overflow UID using the exact logic from the original test. check_ns = ( "import os\n" "proc_uid = os.lstat('/proc/self').st_uid\n" @@ -243,6 +259,7 @@ print('/proc/self does not expose an overflow uid in this namespace') raise SystemExit(0) +# Pivot workspace for dropped root privileges. ws_base = Path(tempfile.mkdtemp(prefix='rsync-unshare-')) ws_base.chmod(0o777) @@ -269,6 +286,8 @@ s_path = shlex.quote(str(ws_src) + '/') d_path = shlex.quote(str(ws_dest) + '/') + # TEST 4A: User Namespace Overflow UID with Process Substitution + # Use process substitution <(...) which resolves to /dev/fd/N. inner_script_4a = f'{cmd_prefix} --no-o --no-g --files-from=<(printf "stdin_test.txt\\n") {s_path} {d_path}' unshare_cmd_4a = launcher + unshare_argv + [bash, '-c', inner_script_4a] @@ -290,6 +309,8 @@ print('Test 4A Passed: rsync successfully resolved process substitution pseudo-paths inside user namespace', flush=True) + # TEST 4B: Nested Trusted Symlink to /dev/stdin in User Namespace + # Clear the destination so we have fresh files to transfer. rmtree(ws_dest) makepath(ws_dest) ws_dest.chmod(0o777) @@ -298,6 +319,7 @@ if symlink_list_ns.is_symlink() or symlink_list_ns.exists(): symlink_list_ns.unlink() + # Create the trusted nested symlink pointing to the kernel pipe. symlink_list_ns.symlink_to('/dev/stdin') if os.geteuid() == 0: diff --git a/testsuite/tests/rrsync/rrsync-merge-file-confine.py b/testsuite/tests/rrsync/rrsync-merge-file-confine.py index e0b6e4ceb..084189ef4 100644 --- a/testsuite/tests/rrsync/rrsync-merge-file-confine.py +++ b/testsuite/tests/rrsync/rrsync-merge-file-confine.py @@ -1,4 +1,13 @@ #!/usr/bin/env python3 +"""An rrsync restricted dir must bound the merge files the peer can name. + +Filter rules travel over the protocol rather than in the argv rrsync validates, +so a dir-merge rule can name a file outside the restricted dir and have the +server read it in as rules. Redacting the resulting diagnostics is not enough: +an exclude-only merge (the "-" modifier) turns every line into a pattern, so +nothing fails to parse and the client reads the file's contents off its own +file list instead -- no error, no verbosity, and on a pull no --delete either. +""" import os import shlex @@ -17,6 +26,7 @@ os.execve(wrapper, [wrapper, '-ro', '-no-lock', root], env) from fixtures.rrsync import rsync_wrapper, patched_rrsync +from harness.process import quote_command from harness.environment import SCRATCHDIR from harness.filesystem import makepath, rmtree from harness.results import test_fail @@ -32,9 +42,14 @@ dest = base / 'dest' makepath(sub, dest) +# The secret sits beside the restricted dir, so "../" reaches it from the root. +# Its line is the name of a file inside the root: if the server reads it as an +# exclude list, that file silently vanishes from the transfer and the client has +# confirmed the content without ever seeing it. (base / 'outside-secret').write_text('secretword\n') (root / 'secretword').write_bytes(b'X') (root / 'keep').write_bytes(b'X') +# An ordinary in-tree merge file, for the control below. (sub / 'intree-dropped').write_bytes(b'X') (sub / 'intree-kept').write_bytes(b'X') (sub / '.rsync-filter').write_text('intree-dropped\n') @@ -45,30 +60,42 @@ rsh = f'{shlex.quote(sys.executable)} {shlex.quote(os.path.abspath(__file__))} --shell' env = {**os.environ, 'RRSYNC_WRAPPER': str(wrapper), 'RRSYNC_ROOT': str(root)} + def pull(filt, into): into.mkdir(parents=True, exist_ok=True) return subprocess.run( rsync_argv('-r', f'--filter={filt}', '-e', rsh, 'ignored:.', f'{into}/'), env=env, capture_output=True, text=True, timeout=20) + +# The escape: an exclude-only dir-merge naming a file outside the restricted +# dir. No --delete and no -v are involved -- the answer is the file list. esc = dest / 'escape' got = pull(':-s ../outside-secret', esc) if got.returncode != 0: test_fail(f'confined merge transfer failed: rc={got.returncode}, stderr={got.stderr!r}') -if not ((esc / 'secretword').exists()): +if not (esc / 'secretword').exists(): test_fail(f'outside merge file excluded secretword: stdout={got.stdout!r}, stderr={got.stderr!r}') if 'secretword' in got.stderr: test_fail(f"the out-of-root merge file's text reached the peer: stderr={got.stderr!r}") +# Control: an ordinary in-tree .rsync-filter must still be read and obeyed. +# Without this, refusing every merge file would pass the check above. ctl = dest / 'control' got = pull(':-s .rsync-filter', ctl) if got.returncode != 0: test_fail(f'the in-tree dir-merge failed the transfer: rc={got.returncode}, stderr={got.stderr!r}') -if not ((ctl / 'sub' / 'intree-kept').exists()): +if not (ctl / 'sub' / 'intree-kept').exists(): test_fail(f'the in-tree dir-merge broke the transfer: rc={got.returncode}, stdout={got.stdout!r}, stderr={got.stderr!r}') if (ctl / 'sub' / 'intree-dropped').exists(): test_fail(f'in-tree merge file was not applied: stdout={got.stdout!r}, stderr={got.stderr!r}') +# Direct --confine-root test (via alias-rsh without the rrsync wrapper): +# Reaching the source directory through a symlink ("self-alias -> .") makes +# rsync's tracked lexical path deeper than the kernel's actual directory. +# A naive lexical check on "outside-link -> ../aliased-secret" would think ".." +# only stepped up from "self-alias" into "alias_root", when in reality the +# kernel resolves ".." out of "alias_root" into the parent directory. alias_root = base / 'aliased' makepath(alias_root) (base / 'aliased-secret').write_text('aliased-word\n') @@ -78,21 +105,33 @@ def pull(filt, into): os.symlink('../aliased-secret', alias_root / 'outside-link') (alias_root / 'intree-list').write_text('plain\n') +alias_rsh = base / 'alias-rsh' +alias_rsh.write_text( + '#!/bin/sh\nshift 2\nexec ' + quote_command(rsync_argv()) + + f' --confine-root={shlex.quote(str(alias_root))} "$@"\n' +) +alias_rsh.chmod(0o755) + + def confined_pull(filter_text, into): (alias_root / '.rsync-filter').write_text(filter_text + '\n') rmtree(into) into.mkdir(parents=True, exist_ok=True) return subprocess.run( - rsync_argv('-r', f'--confine-root={alias_root}', - '--filter=:s .rsync-filter', - f'{alias_root}/self-alias/', f'{into}/'), + rsync_argv('-r', '--filter=:s .rsync-filter', + '-e', str(alias_rsh), + f'ignored:{alias_root}/self-alias/', f'{into}/'), capture_output=True, text=True, timeout=20) + esc2 = dest / 'aliased-escape' got = confined_pull('merge,- outside-link', esc2) -if got.returncode == 0 and (not (esc2 / 'aliased-word').exists()): +if got.returncode == 0 and not (esc2 / 'aliased-word').exists(): test_fail(f'symlinked source read an outside merge file: stderr={got.stderr!r}') +# Control: the same symlinked source arg with an in-tree merge target must still +# work, or the check above would also pass if confinement simply broke every +# transfer that reaches a directory through a symlink. ctl2 = dest / 'aliased-control' got = confined_pull('merge,- intree-list', ctl2) if not (got.returncode == 0 and (ctl2 / 'aliased-word').exists()): diff --git a/testsuite/tests/rrsync/rrsync-userns-procfs.py b/testsuite/tests/rrsync/rrsync-userns-procfs.py index ac2c7cb1f..05d7b8169 100644 --- a/testsuite/tests/rrsync/rrsync-userns-procfs.py +++ b/testsuite/tests/rrsync/rrsync-userns-procfs.py @@ -1,4 +1,5 @@ #!/usr/bin/env python3 +"""A confined fd pin must remain usable inside a Linux user namespace.""" import os import shlex @@ -116,7 +117,7 @@ for index, fd_root in enumerate(fd_roots): log_file = dest / f'rsync-{index}.log' proc = subprocess.run( - rsync_argv('-a', f'--confine-root={dest}', + rsync_argv('-a', f'--confine-root={root}', f'--log-file={fd_root}/{dest_fd}/{log_file.name}', str(src) + '/', str(dest) + '/'), pass_fds=(dest_fd,), @@ -141,6 +142,7 @@ (outside / 'test').write_text('existing_backup\n') +# Open an FD pointing to the confined root. root_fd = os.open(root, os.O_RDONLY | os.O_DIRECTORY) try: for fd_root in fd_roots: @@ -153,6 +155,8 @@ text=True, ) + # The transfer must fail because rsync attempts to unlink the pre-existing target file, + # forcing the path-walker to evaluate the FD pin + symlink and catching the escape. if proc.returncode == 0: test_fail(f'backup to outside symlink via {fd_root} pin was not observably refused: ' f'rc={proc.returncode}, stderr={proc.stderr!r}') diff --git a/util1.c b/util1.c index d58015c4b..39b874369 100644 --- a/util1.c +++ b/util1.c @@ -1313,6 +1313,7 @@ char *sanitize_path(char *dest, const char *p, const char *rootdir, int depth, i int change_dir(const char *dir, int set_path_only) { extern int am_daemon, am_chrooted, am_sender, insecure_links; + extern char *confine_root; static int initialised, skipped_chdir; unsigned int len; @@ -1360,13 +1361,13 @@ int change_dir(const char *dir, int set_path_only) } close(dfd); #if defined O_NOFOLLOW && defined O_DIRECTORY - } else if (!am_chrooted && !am_sender && !insecure_links) { + } else if (!am_chrooted && (confine_root || !am_sender) && !insecure_links) { /* Strip the trailing slash: a symlink opened as "name/" is * always followed, so safe_open's final-component O_NOFOLLOW * must see the bare name to refuse an attacker's symlink. */ char nf[MAXPATHLEN]; unsigned int nl = len; - int dfd; + int dfd, save_resolve = operator_path_resolve; if (nl >= sizeof nf) { errno = ENAMETOOLONG; return 0; @@ -1380,7 +1381,10 @@ int change_dir(const char *dir, int set_path_only) * another uid. A real dir is opened directly. This closes the * destination chdir TOCTOU; --insecure-links keeps the plain * chdir for an operator whose dest is a foreign-owned symlink. */ + if (confine_root) + operator_path_resolve = 1; dfd = open_no_attacker_symlinks_dirfd(nf); + operator_path_resolve = save_resolve; if (dfd < 0) return 0; if (fchdir(dfd) != 0) { @@ -1453,13 +1457,17 @@ int change_dir(const char *dir, int set_path_only) * traversal with a plain chdir to the accumulated path, the same * legacy behaviour the per-operation sites grant under the opt-out. */ chdir_failed = chdir(curr_dir) != 0; - } else if (!am_chrooted && !am_sender && !insecure_links) { + } else if (!am_chrooted && (confine_root || !am_sender) && !insecure_links) { /* Non-daemon receiver: confine the operator-named relative * destination like the absolute case above -- refuse a component * symlink not owned by uid 0 or our euid, closing the * relative-dest chdir TOCTOU while still following the operator's * own symlinks. --insecure-links keeps the plain chdir. */ + int save_resolve = operator_path_resolve; + if (confine_root) + operator_path_resolve = 1; int dfd = open_no_attacker_symlinks_dirfd(curr_dir); + operator_path_resolve = save_resolve; if (dfd < 0) chdir_failed = 1; else {