Debian Codegraph @

testsuite/rrsync-symlink_test.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # rrsync (the SSH-restricted-rsync wrapper) must close its realpath-vs-exec
3 # TOCTOU window so an attacker cannot flip a path component after rrsync's
4 # validation but before the spawned rsync resolves it.
5 #
6 # Threat: support/rrsync does
7 # real_arg = os.path.realpath(arg)
8 # if arg != real_arg and not real_arg.startswith(args.dir_slash):
9 # die('unsafe arg:', ...)
10 # and then runs rsync against the same arg string. Between realpath() and the
11 # spawned rsync's resolution of the path, an attacker can flip a component from
12 # a real entry (which passes realpath) to a symlink escaping the restricted
13 # dir. rsync then transfers data from / to outside the restricted dir.
14 #
15 # This is a TOCTOU race; static plants are caught by realpath. The fix pins the
16 # validated inode with os.open(O_RDONLY|O_NOFOLLOW) + os.fstat() during
17 # validation and hands rsync a name rooted at that pinned fd, so the resolution
18 # is atomic with the check.
19 #
20 # WHAT THIS TEST FLIPS, AND WHY IT IS A DIRECTORY COMPONENT
21 #
22 # rrsync pins every component ABOVE the argument's last one, in both
23 # directions, and that is what this exercises: an intermediate directory is
24 # swapped for a symlink pointing outside the tree.
25 #
26 # It deliberately does not flip the LAST component, because rrsync does not
27 # always pin that one and the stub below could not judge it if it did:
28 # * a receiver destination that does not exist yet has no inode to pin, so
29 # the leaf is necessarily still resolved by name -- that is what creating a
30 # file means;
31 # * a sender source cannot be handed a /proc/self/fd magic link at all: rsync
32 # lstat()s a source argument, sees S_IFLNK, and sends a symlink instead of
33 # the file (see rrsync-pull-delivers-content).
34 # Leaf behaviour is therefore asserted against the real binary in
35 # rrsync-sender-leaf-flip, which can observe what rsync actually does with a
36 # raced leaf rather than what this stub assumes.
37 #
38 # Sender direction only. The receiver has a residual window this cannot yet
39 # assert: when the destination leaf does not exist -- including the instant
40 # between the flipper's two renames -- rrsync falls back to pinning the parent,
41 # and if THAT open also loses the race it passes the argument through unpinned.
42 # Measured over a 5s race, this stub's "rsync" reached the outside marker 8
43 # times as a sender and 11 as a receiver against a pristine 3.4.4 rrsync; with
44 # the inode pin it is 0 as a sender and still 2 as a receiver, on the branch
45 # base as well as with the sender fix. The receiver fallback predates this
46 # change and is tracked separately.
47 #
48 # Test machinery:
49 # * The system rrsync hardcodes RSYNC = '/usr/bin/rsync'; we copy it
50 # to scratch and patch RSYNC to a tiny "fake rsync" stub whose only
51 # job is to open its last argv (the validated path) and emit its
52 # content. The race signal is whether the fake rsync ever emits the
53 # attacker's outside-the-tree secret. For an intermediate component the
54 # stub is a faithful model: whatever rsync does with the final name, it
55 # must not be able to reach it through a flipped parent.
56 # * A flipper subprocess (rsyncfns.start_path_flipper) swaps the
57 # restricted dir's 'dir' name between (a) a real directory and (b) a
58 # symlink to the outside tree. The flip is rename-based and atomic.
59 # * We loop rrsync invocations for up to RACE_TIMEOUT seconds; observing
60 # the secret marker in ANY iteration's stdout is the leak signal.
61 #
62 # Runs at any uid (the race is timing-only, not ownership-based).
63
64 import os
65 import subprocess
66 import time
67
68 from rsyncfns import (
69 race_budget, SCRATCHDIR, patched_rrsync, proc_self_fd_pins, rmtree,
70 start_path_flipper, stop_flipper, test_fail, test_skipped,
71 )
72
73 # rrsync closes this realpath-vs-exec TOCTOU by inode-pinning through
74 # /proc/self/fd (Linux-only). Where that primitive is absent (the BSDs, Solaris,
75 # macOS, Cygwin) rrsync falls through unpinned by design, so the race is not
76 # closed and this test cannot pass -- skip rather than report the intended gap.
77 if not proc_self_fd_pins():
78 test_skipped("rrsync's realpath-vs-exec inode-pin needs /proc/self/fd "
79 "(Linux); unhardened fallback elsewhere by design")
80
81
82 MARKER = b"AUDIT_RRSYNC_RACE_LEAK_MARKER_DO_NOT_DISCLOSE"
83
84 base = SCRATCHDIR / 'rrsync_race'
85 restricted = base / 'restricted'
86 outside = base / 'outside'
87 rmtree(base)
88 restricted.mkdir(parents=True)
89 outside.mkdir(parents=True)
90
91 # Same leaf name on both sides, so the ONLY thing that decides which file the
92 # spawned rsync reaches is which inode the 'dir' component resolved to.
93 (outside / 'target').write_bytes(MARKER)
94
95 # Two sibling names in the restricted dir that the flipper swaps, so the 'dir'
96 # component alternates between a real directory and a symlink escaping the
97 # tree. We use distinct setup names that the flipper then rotates -- the same
98 # shape symlink-race-source/dest use.
99 real_dir = restricted / 'dir'
100 real_dir.mkdir()
101 (real_dir / 'target').write_bytes(b"benign_in_tree_content\n")
102 evil_path = restricted / 'evil'
103 os.symlink(str(outside), evil_path)
104
105 # Fake rsync stub: prints the bytes at its last argv (the path rrsync passed).
106 fake_rsync = base / 'fake_rsync'
107 fake_rsync.write_text(
108 "#!/usr/bin/env python3\n"
109 "import sys\n"
110 "try:\n"
111 " with open(sys.argv[-1], 'rb') as f:\n"
112 " sys.stdout.buffer.write(f.read())\n"
113 "except OSError:\n"
114 " pass\n"
115 )
116 fake_rsync.chmod(0o755)
117
118 # Patched rrsync: RSYNC → fake_rsync (via the shared, path-robust helper).
119 test_rrsync = patched_rrsync(base, rsync_path=str(fake_rsync))
120
121
122 def race(rrsync_flags, ssh_cmd):
123 """Run rrsync in a loop against the flipping tree; True if the secret leaked."""
124 env = {**os.environ, 'SSH_ORIGINAL_COMMAND': ssh_cmd}
125 deadline = time.monotonic() + race_budget()
126 while time.monotonic() < deadline:
127 proc = subprocess.run(
128 [str(test_rrsync), *rrsync_flags, '-no-lock', str(restricted)],
129 stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, env=env)
130 if MARKER in proc.stdout:
131 return True
132 return False
133
134
135 flip = start_path_flipper(real_dir, evil_path)
136 try:
137 leaked = race(['-ro'], "rsync --server --sender -lt . dir/target")
138 finally:
139 stop_flipper(flip)
140
141 if leaked:
142 test_fail(
143 "rrsync realpath-vs-exec TOCTOU: an intermediate path component "
144 "(real directory -> symlink to the outside tree) was followed by the "
145 f"spawned rsync; the secret marker {MARKER!r} was emitted, proving "
146 "the path was resolved AFTER rrsync's realpath check validated it. "
147 "Fix: pin the validated inode with os.open(O_RDONLY|O_NOFOLLOW) + "
148 "os.fstat() during validation, then root the argument handed to rsync "
149 "at that pinned fd.")
150
151 print('rrsync pins intermediate sender path components against the realpath-vs-exec race')