title: Safely import module using sys.addaudithook
body: <p>I recently found out about the new <a href="https://docs.python.org/3/library/sys.html#sys.addaudithook" rel="nofollow noreferrer"><code>sys.addaudithook</code></a> in python. I run a service that involves running some untrusted scripts and I want to use the audit hooks to further secure the system. Scripts are running in a isolated container anyway but extra protection doesn't hurt.</p>
  <p>Right now my code is this:</p>
  <pre class="lang-py prettyprint-override"><code>import sys
  
  def audithook(event, args):
          if event.startswith('os.') or event.startswith('sys.') or event.startswith('socket.') or event.startswith('winreg.') or event.startswith('webbrowser.') or event.startswith('shutil.') or event == &quot;import&quot;:
                  raise RuntimeError(&quot;Attempt to break out of sandbox&quot;);
  
  # Some code here that explicitly requires filesystem access
  
  sys.addaudithook(audithook)
  
  import untrusted_module
  
  # More code that uses other
  # Results need to eventually be saved to a file, that seems to work fine if I open the file before creating the hook then just write to it later. This is why I can't protect the entire program.
  </code></pre>
  <p>However, importing the file triggers quite a few hooks in the process of compiling the other file to bytecode and running it. I want to only prevent file system access inside the script itself and not the process of importing it.</p>
  <p>I could try to set it to ignore some number N events before blocking new ones but the number of audit events seems to vary significantly depending on if the script changed or not, and how recent the stored bytecode is.</p>
  <p>The entire audithook feature seems to be poorly documented and I can find very little about it online. Does anyone know how to use it to secure 1 module?</p>