Debian Codegraph @

testsuite/chmod-symlink-race_test.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # Python rewrite of testsuite/chmod-symlink-race.test.
3 #
4 # Regression test for the symlink-TOCTOU class of bug applied to chmod()
5 # on the receiver side. The CVE-2026-29518 fix used
6 # secure_relative_open() for the basis-file open, but every other
7 # path-based syscall the receiver runs on sender-controllable paths is
8 # vulnerable to the same primitive: a local attacker swaps a symlink
9 # into one of the parent directory components between the receiver's
10 # check and its act, and the syscall escapes the module.
11 #
12 # The helper t_chmod_secure exercises the new do_chmod_at() wrapper
13 # across four scenarios; see the shell version for the full enumeration.
14 # After the helper runs we sanity-check the outside sentinel's mode
15 # from Python too, in case the helper's internal stat() ever drifts.
16
17 import os
18 import subprocess
19
20 from rsyncfns import SCRATCHDIR, TOOLDIR, rmtree, test_fail
21
22
23 mod = SCRATCHDIR / 'module'
24 trap_outside = SCRATCHDIR / 'trap'
25 rmtree(mod)
26 rmtree(trap_outside)
27 mod.mkdir(parents=True)
28 (mod / 'realdir').mkdir(parents=True)
29 trap_outside.mkdir(parents=True)
30
31 # File-system objects the helper expects.
32 (mod / 'realdir' / 'sentinel').write_text("bystander\n")
33 os.chmod(mod / 'realdir' / 'sentinel', 0o600)
34 (trap_outside / 'sentinel').write_text("target\n")
35 os.chmod(trap_outside / 'sentinel', 0o600)
36 os.symlink('realdir', mod / 'inside_link')
37 os.symlink('../trap', mod / 'escape_link')
38 (mod / 'topfile').write_text("top\n")
39 os.chmod(mod / 'topfile', 0o600)
40 # A LEAF symlink (final path component) escaping the tree, for the leaf-flip
41 # scenario: do_chmod_at('realdir/leaflink') has a legitimate real parent but an
42 # escaping symlink leaf, so it isolates the O_NOFOLLOW leaf guard from the
43 # parent-confinement scenarios. Target is the same outside sentinel (relative to
44 # realdir/, the outside trap is ../../trap).
45 os.symlink('../../trap/sentinel', mod / 'realdir' / 'leaflink')
46
47 proc = subprocess.run([str(TOOLDIR / 't_chmod_secure'), str(mod)])
48 if proc.returncode != 0:
49 test_fail("t_chmod_secure reported failures (see stderr above)")
50
51 # Second-look sanity check from Python.
52 sentinel_mode = (trap_outside / 'sentinel').stat().st_mode & 0o777
53 if sentinel_mode != 0o600:
54 test_fail(
55 f"outside sentinel mode changed from 600 to {oct(sentinel_mode)[2:]} "
56 "-- chmod escaped the module"
57 )