Debian Codegraph @

test/test_dynamic.py

raw
1 import pytest
2 from shared_vars import *
3 from subprocess import PIPE, DEVNULL
4 import signal
5 import time
6 import select
7
8 def is_not_cap_sys_admin() -> str | None:
9 try:
10 with open('/proc/self/status') as f:
11 for line in f:
12 if line.startswith('CapEff:'):
13 capeff = int(line.split()[1], 16)
14 break
15 else:
16 return 'Capability can not be found in status'
17 except OSError:
18 return 'Can not query /proc to know capability'
19
20 if bool(capeff & (1 << 21)): # CAP_SYS_ADMIN = 21
21 return None
22 return 'Lack of CAP_SYS_ADMIN capability'
23
24 TEST = str(PROJ_DIR / 'build' / 'test')
25 assert run_process(['make', '-C', str(PROJ_DIR), 'test'], False)[0] == 0
26
27 def pid_state(pid: int) -> str | None:
28 """
29 Race condition: perhaps kernel killed process but ceccomp hasn't exit,
30 so test is zombie and not being collected. Test this case
31 """
32 try:
33 os.kill(pid, 0)
34 except ProcessLookupError:
35 return None
36 try:
37 with open(f'/proc/{pid}/stat') as f:
38 state = f.read().split(' ', 4)[2]
39 except:
40 return None
41 else:
42 return None if state == 'Z' else state
43
44 def filter_execve_k(text: str) -> str:
45 lines = text.splitlines()
46 for i, line in enumerate(lines):
47 if 'execve' in line or 'sendfile' in line:
48 lines[i] = line[:23] + ' MAY VARY ' + line[33:]
49 return '\n'.join(lines)
50
51 # -a x86_64 option in COMMON_OPTS will be ignored in trace/probe
52
53 ##### TEST CASES #####
54 @pytest.mark.xfail(XFAIL_DYNAMIC, reason=XFAIL_REASON)
55 def test_probe(errns: SimpleNamespace):
56 piper, pipew = os.pipe()
57 os.set_inheritable(pipew, True)
58 argv = [CECCOMP, 'probe', *COMMON_OPTS, '-o', f'/proc/self/fd/{pipew}', TEST, '1']
59 _, stdout, stderr = run_process(argv, False, pipew)
60 os.close(pipew)
61 errns.stderr = stderr
62
63 expect_file = TEST_DIR / 'dyn_log' / 'probe.log'
64 with expect_file.open() as f:
65 expect = f.read()
66 with os.fdopen(piper) as f:
67 assert f.read() == expect
68
69 pid = int(stdout.split('=')[1])
70 end = time.time() + 3
71 while pid_state(pid) and time.time() < end:
72 time.sleep(0.0625)
73 last_state = pid_state(pid)
74 assert last_state is None or last_state == 'X'
75
76
77 @pytest.mark.xfail(XFAIL_DYNAMIC, reason=XFAIL_REASON)
78 def test_trace(errns: SimpleNamespace):
79 piper, pipew = os.pipe()
80 os.set_inheritable(pipew, True)
81 argv = [CECCOMP, 'trace', *COMMON_OPTS, '-o', f'/proc/self/fd/{pipew}', TEST, '0']
82 _, _, stderr = run_process(argv, False, pipew)
83 os.close(pipew)
84 errns.stderr = stderr
85
86 expect_file = TEST_DIR / 'dyn_log' / 'trace.log'
87 with expect_file.open() as f:
88 expect = f.read()
89 with os.fdopen(piper) as f:
90 assert filter_execve_k(f.read()) == filter_execve_k(expect)
91 assert 'WARN' in stderr
92
93
94 @pytest.mark.xfail(XFAIL_DYNAMIC, reason=XFAIL_REASON)
95 def test_seize(errns: SimpleNamespace):
96 efd = os.eventfd(0, 0)
97 tp = subprocess.Popen([TEST, '2', str(efd)],
98 stdin=DEVNULL, stdout=PIPE, stderr=DEVNULL, text=True, pass_fds=(efd,))
99 pid = int(tp.stdout.readline().split('=')[1])
100
101 argv = [CECCOMP, 'trace', *COMMON_OPTS, '-p', str(pid), '-s']
102 cp = subprocess.Popen(argv, stdin=DEVNULL, stdout=PIPE, stderr=PIPE, text=True)
103 pre_line = cp.stderr.readline()
104
105 os.eventfd_write(efd, 1)
106
107 rl, _, _ = select.select([tp.stdout], [], [], 2)
108 if rl:
109 pid = int(rl[0].readline().split('=')[1]) # child pid
110 else:
111 with open(f'/proc/{tp.pid}/wchan') as f:
112 t_kfunc = f.read()
113 with open(f'/proc/{cp.pid}/wchan') as f:
114 c_kfunc = f.read()
115 errns.stderr = f'TEST in {t_kfunc}\nCECCOMP in {c_kfunc}'
116 tp.terminate()
117 cp.terminate()
118 assert False, 'Found signal race condition? Pls report to upstream'
119
120 cp.terminate()
121 stdout, stderr = cp.communicate()
122 errns.stderr = pre_line + stderr
123
124 pid_exist = True
125 try:
126 os.kill(pid, 0)
127 except ProcessLookupError:
128 pid_exist = False
129 else:
130 os.eventfd_write(efd, 1)
131 assert pid_exist is True
132
133 expect_file = TEST_DIR / 'dyn_log' / 'trace.log'
134 with expect_file.open() as f:
135 assert filter_execve_k(stdout) == filter_execve_k(f.read())
136
137 @pytest.mark.xfail(XFAIL_DYNAMIC, reason=XFAIL_REASON)
138 def test_trace_pid(errns: SimpleNamespace):
139 if msg := is_not_cap_sys_admin():
140 pytest.skip(msg)
141
142 efd = os.eventfd(0, 0)
143 tp = subprocess.Popen([TEST, '3', str(efd)],
144 stdin=DEVNULL, stdout=PIPE, stderr=DEVNULL, text=True, pass_fds=(efd,))
145 pid = int(tp.stdout.readline().split('=')[1])
146
147 _, stdout, stderr = run_process(
148 [CECCOMP, 'trace', *COMMON_OPTS, '-p', str(pid)],
149 )
150 errns.stderr = stderr
151
152 os.eventfd_write(efd, 1)
153
154 expect_file = TEST_DIR / 'dyn_log' / 'trace.log'
155 with expect_file.open() as f:
156 assert filter_execve_k(stdout) == filter_execve_k(f.read())