Python's dynamic nature makes it hard to implement and reason about audit hooks written in Python. sys.addaudithook() is really only design for testing, debugging, and playing around with auditing. You absolutely have to write a custom interpreter if you want to take auditing serious.
Please also keep in mind that sys.addaudithook() does **not** add a global hook. The function adds a per-interpreter hook. It just looks global to most people because a process typically has just one interpreter. I have filed bpo-43472 to track the issue.
$ cat auditsub.py
import sys
import _xxsubinterpreters
def hook(*args):
print(args)
sys.addaudithook(hook)
import os
os.system('echo main interpreter')
sub = _xxsubinterpreters.create()
_xxsubinterpreters.run_string(sub, "import os; os.system('echo you got pwned')", None)
$ ./python auditsub.py
('os.system', (b'echo main interpreter',))
main interpreter
you got pwned |