Debian Codegraph @

Lib/test/audit-tests.py

raw
1 """This script contains the actual auditing tests.
2
3 It should not be imported directly, but should be run by the test_audit
4 module with arguments identifying each test.
5
6 """
7
8 import contextlib
9 import os
10 import sys
11
12
13 class TestHook:
14 """Used in standard hook tests to collect any logged events.
15
16 Should be used in a with block to ensure that it has no impact
17 after the test completes.
18 """
19
20 def __init__(self, raise_on_events=None, exc_type=RuntimeError):
21 self.raise_on_events = raise_on_events or ()
22 self.exc_type = exc_type
23 self.seen = []
24 self.closed = False
25
26 def __enter__(self, *a):
27 sys.addaudithook(self)
28 return self
29
30 def __exit__(self, *a):
31 self.close()
32
33 def close(self):
34 self.closed = True
35
36 @property
37 def seen_events(self):
38 return [i[0] for i in self.seen]
39
40 def __call__(self, event, args):
41 if self.closed:
42 return
43 self.seen.append((event, args))
44 if event in self.raise_on_events:
45 raise self.exc_type("saw event " + event)
46
47
48 # Simple helpers, since we are not in unittest here
49 def assertEqual(x, y):
50 if x != y:
51 raise AssertionError(f"{x!r} should equal {y!r}")
52
53
54 def assertIn(el, series):
55 if el not in series:
56 raise AssertionError(f"{el!r} should be in {series!r}")
57
58
59 def assertNotIn(el, series):
60 if el in series:
61 raise AssertionError(f"{el!r} should not be in {series!r}")
62
63
64 def assertSequenceEqual(x, y):
65 if len(x) != len(y):
66 raise AssertionError(f"{x!r} should equal {y!r}")
67 if any(ix != iy for ix, iy in zip(x, y)):
68 raise AssertionError(f"{x!r} should equal {y!r}")
69
70
71 @contextlib.contextmanager
72 def assertRaises(ex_type):
73 try:
74 yield
75 assert False, f"expected {ex_type}"
76 except BaseException as ex:
77 if isinstance(ex, AssertionError):
78 raise
79 assert type(ex) is ex_type, f"{ex} should be {ex_type}"
80
81
82 def test_basic():
83 with TestHook() as hook:
84 sys.audit("test_event", 1, 2, 3)
85 assertEqual(hook.seen[0][0], "test_event")
86 assertEqual(hook.seen[0][1], (1, 2, 3))
87
88
89 def test_block_add_hook():
90 # Raising an exception should prevent a new hook from being added,
91 # but will not propagate out.
92 with TestHook(raise_on_events="sys.addaudithook") as hook1:
93 with TestHook() as hook2:
94 sys.audit("test_event")
95 assertIn("test_event", hook1.seen_events)
96 assertNotIn("test_event", hook2.seen_events)
97
98
99 def test_block_add_hook_baseexception():
100 # Raising BaseException will propagate out when adding a hook
101 with assertRaises(BaseException):
102 with TestHook(
103 raise_on_events="sys.addaudithook", exc_type=BaseException
104 ) as hook1:
105 # Adding this next hook should raise BaseException
106 with TestHook() as hook2:
107 pass
108
109
110 def test_marshal():
111 import marshal
112 o = ("a", "b", "c", 1, 2, 3)
113 payload = marshal.dumps(o)
114
115 with TestHook() as hook:
116 assertEqual(o, marshal.loads(marshal.dumps(o)))
117
118 try:
119 with open("test-marshal.bin", "wb") as f:
120 marshal.dump(o, f)
121 with open("test-marshal.bin", "rb") as f:
122 assertEqual(o, marshal.load(f))
123 finally:
124 os.unlink("test-marshal.bin")
125
126 actual = [(a[0], a[1]) for e, a in hook.seen if e == "marshal.dumps"]
127 assertSequenceEqual(actual, [(o, marshal.version)] * 2)
128
129 actual = [a[0] for e, a in hook.seen if e == "marshal.loads"]
130 assertSequenceEqual(actual, [payload])
131
132 actual = [e for e, a in hook.seen if e == "marshal.load"]
133 assertSequenceEqual(actual, ["marshal.load"])
134
135
136 def test_pickle():
137 import pickle
138
139 class PicklePrint:
140 def __reduce_ex__(self, p):
141 return str, ("Pwned!",)
142
143 payload_1 = pickle.dumps(PicklePrint())
144 payload_2 = pickle.dumps(("a", "b", "c", 1, 2, 3))
145
146 # Before we add the hook, ensure our malicious pickle loads
147 assertEqual("Pwned!", pickle.loads(payload_1))
148
149 with TestHook(raise_on_events="pickle.find_class") as hook:
150 with assertRaises(RuntimeError):
151 # With the hook enabled, loading globals is not allowed
152 pickle.loads(payload_1)
153 # pickles with no globals are okay
154 pickle.loads(payload_2)
155
156
157 def test_monkeypatch():
158 class A:
159 pass
160
161 class B:
162 pass
163
164 class C(A):
165 pass
166
167 a = A()
168
169 with TestHook() as hook:
170 # Catch name changes
171 C.__name__ = "X"
172 # Catch type changes
173 C.__bases__ = (B,)
174 # Ensure bypassing __setattr__ is still caught
175 type.__dict__["__bases__"].__set__(C, (B,))
176 # Catch attribute replacement
177 C.__init__ = B.__init__
178 # Catch attribute addition
179 C.new_attr = 123
180 # Catch class changes
181 a.__class__ = B
182
183 actual = [(a[0], a[1]) for e, a in hook.seen if e == "object.__setattr__"]
184 assertSequenceEqual(
185 [(C, "__name__"), (C, "__bases__"), (C, "__bases__"), (a, "__class__")], actual
186 )
187
188
189 def test_open(testfn):
190 # SSLContext.load_dh_params uses _Py_fopen_obj rather than normal open()
191 try:
192 import ssl
193
194 load_dh_params = ssl.create_default_context().load_dh_params
195 except ImportError:
196 load_dh_params = None
197
198 # Try a range of "open" functions.
199 # All of them should fail
200 with TestHook(raise_on_events={"open"}) as hook:
201 for fn, *args in [
202 (open, testfn, "r"),
203 (open, sys.executable, "rb"),
204 (open, 3, "wb"),
205 (open, testfn, "w", -1, None, None, None, False, lambda *a: 1),
206 (load_dh_params, testfn),
207 ]:
208 if not fn:
209 continue
210 with assertRaises(RuntimeError):
211 try:
212 fn(*args)
213 except NotImplementedError:
214 if fn == load_dh_params:
215 # Not callable in some builds
216 load_dh_params = None
217 raise RuntimeError
218 else:
219 raise
220
221 actual_mode = [(a[0], a[1]) for e, a in hook.seen if e == "open" and a[1]]
222 actual_flag = [(a[0], a[2]) for e, a in hook.seen if e == "open" and not a[1]]
223 assertSequenceEqual(
224 [
225 i
226 for i in [
227 (testfn, "r"),
228 (sys.executable, "r"),
229 (3, "w"),
230 (testfn, "w"),
231 (testfn, "rb") if load_dh_params else None,
232 ]
233 if i is not None
234 ],
235 actual_mode,
236 )
237 assertSequenceEqual([], actual_flag)
238
239
240 def test_cantrace():
241 traced = []
242
243 def trace(frame, event, *args):
244 if frame.f_code == TestHook.__call__.__code__:
245 traced.append(event)
246
247 old = sys.settrace(trace)
248 try:
249 with TestHook() as hook:
250 # No traced call
251 eval("1")
252
253 # No traced call
254 hook.__cantrace__ = False
255 eval("2")
256
257 # One traced call
258 hook.__cantrace__ = True
259 eval("3")
260
261 # Two traced calls (writing to private member, eval)
262 hook.__cantrace__ = 1
263 eval("4")
264
265 # One traced call (writing to private member)
266 hook.__cantrace__ = 0
267 finally:
268 sys.settrace(old)
269
270 assertSequenceEqual(["call"] * 4, traced)
271
272
273 def test_mmap():
274 import mmap
275
276 with TestHook() as hook:
277 mmap.mmap(-1, 8)
278 assertEqual(hook.seen[0][1][:2], (-1, 8))
279
280
281 def test_excepthook():
282 def excepthook(exc_type, exc_value, exc_tb):
283 if exc_type is not RuntimeError:
284 sys.__excepthook__(exc_type, exc_value, exc_tb)
285
286 def hook(event, args):
287 if event == "sys.excepthook":
288 if not isinstance(args[2], args[1]):
289 raise TypeError(f"Expected isinstance({args[2]!r}, " f"{args[1]!r})")
290 if args[0] != excepthook:
291 raise ValueError(f"Expected {args[0]} == {excepthook}")
292 print(event, repr(args[2]))
293
294 sys.addaudithook(hook)
295 sys.excepthook = excepthook
296 raise RuntimeError("fatal-error")
297
298
299 def test_unraisablehook():
300 from _testcapi import err_formatunraisable
301
302 def unraisablehook(hookargs):
303 pass
304
305 def hook(event, args):
306 if event == "sys.unraisablehook":
307 if args[0] != unraisablehook:
308 raise ValueError(f"Expected {args[0]} == {unraisablehook}")
309 print(event, repr(args[1].exc_value), args[1].err_msg)
310
311 sys.addaudithook(hook)
312 sys.unraisablehook = unraisablehook
313 err_formatunraisable(RuntimeError("nonfatal-error"),
314 "Exception ignored for audit hook test")
315
316
317 def test_winreg():
318 from winreg import OpenKey, EnumKey, CloseKey, HKEY_LOCAL_MACHINE
319
320 def hook(event, args):
321 if not event.startswith("winreg."):
322 return
323 print(event, *args)
324
325 sys.addaudithook(hook)
326
327 k = OpenKey(HKEY_LOCAL_MACHINE, "Software")
328 EnumKey(k, 0)
329 try:
330 EnumKey(k, 10000)
331 except OSError:
332 pass
333 else:
334 raise RuntimeError("Expected EnumKey(HKLM, 10000) to fail")
335
336 kv = k.Detach()
337 CloseKey(kv)
338
339
340 def test_socket():
341 import socket
342
343 def hook(event, args):
344 if event.startswith("socket."):
345 print(event, *args)
346
347 sys.addaudithook(hook)
348
349 socket.gethostname()
350
351 # Don't care if this fails, we just want the audit message
352 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
353 try:
354 # Don't care if this fails, we just want the audit message
355 sock.bind(('127.0.0.1', 8080))
356 except Exception:
357 pass
358 finally:
359 sock.close()
360
361
362 def test_gc():
363 import gc
364
365 def hook(event, args):
366 if event.startswith("gc."):
367 print(event, *args)
368
369 sys.addaudithook(hook)
370
371 gc.get_objects(generation=1)
372
373 x = object()
374 y = [x]
375
376 gc.get_referrers(x)
377 gc.get_referents(y)
378
379
380 def test_http_client():
381 import http.client
382
383 def hook(event, args):
384 if event.startswith("http.client."):
385 print(event, *args[1:])
386
387 sys.addaudithook(hook)
388
389 conn = http.client.HTTPConnection('www.python.org')
390 try:
391 conn.request('GET', '/')
392 except OSError:
393 print('http.client.send', '[cannot send]')
394 finally:
395 conn.close()
396
397
398 def test_sqlite3():
399 import sqlite3
400
401 def hook(event, *args):
402 if event.startswith("sqlite3."):
403 print(event, *args)
404
405 sys.addaudithook(hook)
406 cx1 = sqlite3.connect(":memory:")
407 cx2 = sqlite3.Connection(":memory:")
408
409 # Configured without --enable-loadable-sqlite-extensions
410 try:
411 if hasattr(sqlite3.Connection, "enable_load_extension"):
412 cx1.enable_load_extension(False)
413 try:
414 cx1.load_extension("test")
415 except sqlite3.OperationalError:
416 pass
417 else:
418 raise RuntimeError("Expected sqlite3.load_extension to fail")
419 finally:
420 cx1.close()
421 cx2.close()
422
423 def test_sys_getframe():
424 import sys
425
426 def hook(event, args):
427 if event.startswith("sys."):
428 print(event, args[0].f_code.co_name)
429
430 sys.addaudithook(hook)
431 sys._getframe()
432
433
434 def test_sys_getframemodulename():
435 import sys
436
437 def hook(event, args):
438 if event.startswith("sys."):
439 print(event, *args)
440
441 sys.addaudithook(hook)
442 sys._getframemodulename()
443
444
445 def test_threading():
446 import _thread
447
448 def hook(event, args):
449 if event.startswith(("_thread.", "cpython.PyThreadState", "test.")):
450 print(event, args)
451
452 sys.addaudithook(hook)
453
454 lock = _thread.allocate_lock()
455 lock.acquire()
456
457 class test_func:
458 def __repr__(self): return "<test_func>"
459 def __call__(self):
460 sys.audit("test.test_func")
461 lock.release()
462
463 i = _thread.start_new_thread(test_func(), ())
464 lock.acquire()
465
466 handle = _thread.start_joinable_thread(test_func())
467 handle.join()
468
469
470 def test_threading_abort():
471 # Ensures that aborting PyThreadState_New raises the correct exception
472 import _thread
473
474 class ThreadNewAbortError(Exception):
475 pass
476
477 def hook(event, args):
478 if event == "cpython.PyThreadState_New":
479 raise ThreadNewAbortError()
480
481 sys.addaudithook(hook)
482
483 try:
484 _thread.start_new_thread(lambda: None, ())
485 except ThreadNewAbortError:
486 # Other exceptions are raised and the test will fail
487 pass
488
489
490 def test_wmi_exec_query():
491 import _wmi
492
493 def hook(event, args):
494 if event.startswith("_wmi."):
495 print(event, args[0])
496
497 sys.addaudithook(hook)
498 try:
499 _wmi.exec_query("SELECT * FROM Win32_OperatingSystem")
500 except WindowsError as e:
501 # gh-112278: WMI may be slow response when first called, but we still
502 # get the audit event, so just ignore the timeout
503 if e.winerror != 258:
504 raise
505
506 def test_syslog():
507 import syslog
508
509 def hook(event, args):
510 if event.startswith("syslog."):
511 print(event, *args)
512
513 sys.addaudithook(hook)
514 syslog.openlog('python')
515 syslog.syslog('test')
516 syslog.setlogmask(syslog.LOG_DEBUG)
517 syslog.closelog()
518 # implicit open
519 syslog.syslog('test2')
520 # open with default ident
521 syslog.openlog(logoption=syslog.LOG_NDELAY, facility=syslog.LOG_LOCAL0)
522 sys.argv = None
523 syslog.openlog()
524 syslog.closelog()
525
526
527 def test_not_in_gc():
528 import gc
529
530 hook = lambda *a: None
531 sys.addaudithook(hook)
532
533 for o in gc.get_objects():
534 if isinstance(o, list):
535 assert hook not in o
536
537
538 def test_time(mode):
539 import time
540
541 def hook(event, args):
542 if event.startswith("time."):
543 if mode == 'print':
544 print(event, *args)
545 elif mode == 'fail':
546 raise AssertionError('hook failed')
547 sys.addaudithook(hook)
548
549 time.sleep(0)
550 time.sleep(0.0625) # 1/16, a small exact float
551 try:
552 time.sleep(-1)
553 except ValueError:
554 pass
555
556 def test_sys_monitoring_register_callback():
557 import sys
558
559 def hook(event, args):
560 if event.startswith("sys.monitoring"):
561 print(event, args)
562
563 sys.addaudithook(hook)
564 sys.monitoring.register_callback(1, 1, None)
565
566
567 def test_winapi_createnamedpipe(pipe_name):
568 import _winapi
569
570 def hook(event, args):
571 if event == "_winapi.CreateNamedPipe":
572 print(event, args)
573
574 sys.addaudithook(hook)
575 _winapi.CreateNamedPipe(pipe_name, _winapi.PIPE_ACCESS_DUPLEX, 8, 2, 0, 0, 0, 0)
576
577
578 def test_assert_unicode():
579 import sys
580 sys.addaudithook(lambda *args: None)
581 try:
582 sys.audit(9)
583 except TypeError:
584 pass
585 else:
586 raise RuntimeError("Expected sys.audit(9) to fail.")
587
588
589 if __name__ == "__main__":
590 from test.support import suppress_msvcrt_asserts
591
592 suppress_msvcrt_asserts()
593
594 test = sys.argv[1]
595 globals()[test](*sys.argv[2:])