Debian Codegraph @

testsuite/temp-dir-symlink-injection_test.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # Absolute --temp-dir parent-component symlink-race: content injection.
3 #
4 # rsync stages each transferred file as a random-named temp in --temp-dir, then
5 # finish_transfer() renames temp->final. With an ABSOLUTE --temp-dir a root
6 # operator's rename source is a full path; a non-root attacker who can write the
7 # temp-dir tree flips a temp-dir parent between a real dir and a foreign-owned
8 # symlink -> outside, observes the random temp name in the real dir, plants
9 # outside/<name> with attacker content, and -- pre-fix -- the temp->final rename
10 # follows the flipped parent and pulls the attacker's out-of-tree file into the
11 # destination (the received file is replaced by injected content).
12 #
13 # The temp CREATE is already confined (secure_mkstemp); this pins the RENAME:
14 # do_rename_at resolves an absolute (operator) side via the ownership walk, so a
15 # foreign-owned flipped parent is refused. RED on stock 3.4.x / --insecure-links,
16 # GREEN here. Root+nobody gated (the cross-uid plant needs root).
17
18 import os
19 import subprocess
20 import time
21
22 import filecmp
23 import sys
24
25 from rsyncfns import (
26 SCRATCHDIR, race_budget, find_attacker_uid,
27 rmtree, rsync_argv, test_fail, test_skipped,
28 )
29
30 if os.geteuid() != 0:
31 test_skipped("requires root to plant a temp-dir symlink owned by a non-self uid")
32 ATT_UID = find_attacker_uid()
33 if ATT_UID is None:
34 test_skipped("no untrusted-uid user available for cross-uid plant")
35
36 NFILES = 40
37 PINNED = 1000000000
38
39 base = SCRATCHDIR / 'tmpdir-inject'
40 src = base / 'src'
41 dest = base / 'dest'
42 tmproot = base / 'tmproot'
43 td = tmproot / 'td' # the temp-dir parent the attacker flips
44 tdlink = tmproot / '.tdlink' # symlink -> outside, swapped in for td
45 outside = base / 'outside'
46
47
48 def build():
49 rmtree(base)
50 for d in (src, dest, tmproot, outside):
51 d.mkdir(parents=True)
52 for i in range(NFILES):
53 # Big payloads so the temp file lingers (an observable race window).
54 (src / f'f{i}').write_text('LEGIT-' + 'x' * 200000 + '\n')
55 (dest / f'f{i}').write_text('old\n')
56 td.mkdir()
57 os.symlink(str(outside), tdlink)
58 os.lchown(tdlink, ATT_UID, ATT_UID)
59
60
61 def push():
62 return subprocess.run(
63 rsync_argv('-r', f'--temp-dir={td}', f'{src}/', f'{dest}/'),
64 stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
65
66
67 def injected():
68 for i in range(NFILES):
69 try:
70 if (dest / f'f{i}').read_text().startswith('PWNED'):
71 return f'f{i}'
72 except OSError:
73 pass
74 return None
75
76
77 # Attacker: in one tight loop, plant outside/<name> for each temp name visible
78 # in the real td, then flip td <-> the foreign symlink (the symlink keeps its
79 # foreign owner across the renames). Must observe + plant + flip concurrently
80 # with the transfer because the temp names are random per push.
81 ATTACK = (
82 "import os, sys, time\n"
83 "td, link, outside = sys.argv[1], sys.argv[2], sys.argv[3]\n"
84 "s = td + '.flip'\n"
85 "parent = os.getppid()\n"
86 "deadline = time.monotonic() + 300\n"
87 "while os.getppid() == parent and time.monotonic() < deadline:\n"
88 " try:\n"
89 " for n in os.listdir(td):\n"
90 " if n[:1] != '.':\n"
91 " open(outside + '/' + n, 'w').write('PWNED')\n"
92 " except OSError:\n"
93 " pass\n"
94 " try:\n"
95 " os.makedirs(td, exist_ok=True)\n"
96 " os.rename(td, s); os.rename(link, td); os.rename(s, link)\n"
97 " os.rename(td, s); os.rename(link, td); os.rename(s, link)\n"
98 " except OSError:\n"
99 " pass\n"
100 )
101
102 build()
103 os.utime(td, (PINNED, PINNED))
104 before = td.stat().st_mtime_ns
105 proc = push()
106 if proc.returncode != 0:
107 test_fail("positive control: clean --temp-dir transfer failed "
108 f"(rc={proc.returncode}):\n{proc.stdout or ''}")
109 if td.stat().st_mtime_ns == before:
110 test_fail(
111 "positive control: --temp-dir did not create or remove a temp file "
112 f"in {td}; the test would not exercise the temp->final rename source")
113 for i in range(NFILES):
114 target = dest / f'f{i}'
115 if not target.is_file():
116 test_fail(f"positive control: --temp-dir did not create {target}")
117 if not filecmp.cmp(src / f'f{i}', target, shallow=False):
118 test_fail(f"positive control: destination content differs for {target}")
119
120 atk = subprocess.Popen([sys.executable, '-c', ATTACK,
121 str(td), str(tdlink), str(outside)])
122 try:
123 deadline = time.monotonic() + race_budget(15.0)
124 while time.monotonic() < deadline:
125 rmtree(dest)
126 dest.mkdir()
127 push()
128 hit = injected()
129 if hit:
130 test_fail(
131 "absolute --temp-dir rename injection: attacker out-of-tree "
132 f"content was renamed into the destination ({hit}) -- the "
133 "temp->final rename followed a flipped foreign-owned temp-dir "
134 "parent symlink.")
135 finally:
136 atk.terminate()
137 try:
138 atk.wait(timeout=5)
139 except subprocess.TimeoutExpired:
140 atk.kill()
141 atk.wait()
142
143 # No injection within the race budget.