Text of peps.python.org › pep-0578 as Styx crawled it on Nov 19, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

PEP 578 – Python Runtime Audit Hooks | peps.python.org

PEP 578 – Python Runtime Audit Hooks PEP 578 – Python Runtime Audit Hooks Author : Steve Dower <steve.dower at python.org> BDFL-Delegate : Christian Heimes <christian at python.org> Status : Final Type : Standards Track Created : 16-Jun-2018 Python-Version : 3.8 Post-History : 28-Mar-2019, 07-May-2019 Table of Contents Abstract Background Overview of Changes Audit Hook Verified Open Hook API Availability Suggested Audit Hook Locations Performance Impact Rejected Ideas Separate module for audit hooks Flag in sys.flags to indicate “audited” mode Why Not A Sandbox Relationship to PEP 551 References Copyright Important This PEP is a historical document.

The up-to-date, canonical documentation can now be found at Audit events table . × See PEP 1 for how to propose changes. Abstract This PEP describes additions to the Python API and specific behaviors for the CPython implementation that make actions taken by the Python runtime visible to auditing tools. Visibility into these actions provides opportunities for test frameworks, logging frameworks, and security tools to monitor and optionally limit actions taken by the runtime.

This PEP proposes adding two APIs to provide insights into a running Python application: one for arbitrary events, and another specific to the module import system. The APIs are intended to be available in all Python implementations, though the specific messages and values used are unspecified here to allow implementations the freedom to determine how best to provide information to their users. Some examples likely to be used in CPython are provided for explanatory purposes.

See PEP 551 for discussion and recommendations on enhancing the security of a Python runtime making use of these auditing APIs. Background Python provides access to a wide range of low-level functionality on many common operating systems. While this is incredibly useful for “write-once, run-anywhere” scripting, it also makes monitoring of software written in Python difficult. Because Python uses native system APIs directly, existing monitoring tools either suffer from limited context or auditing bypass.

Limited context occurs when system monitoring can report that an action occurred, but cannot explain the sequence of events leading to it. For example, network monitoring at the OS level may be able to report “listening started on port 5678”, but may not be able to provide the process ID, command line, parent process, or the local state in the program at the point that triggered the action. Firewall controls to prevent such an action are similarly limited, typically to process names or some global state such as the current user, and in any case rarely provide a useful log file correlated with other application messages.

Auditing bypass can occur when the typical system tool used for an action would ordinarily report its use, but accessing the APIs via Python do not trigger this. For example, invoking “curl” to make HTTP requests may be specifically monitored in an audited system, but Python’s “urlretrieve” function is not. Within a long-running Python application, particularly one that processes user-provided information such as a web app, there is a risk of unexpected behavior.

This may be due to bugs in the code, or deliberately induced by a malicious user. In both cases, normal application logging may be bypassed resulting in no indication that anything out of the ordinary has occurred. Additionally, and somewhat unique to Python, it is very easy to affect the code that is run in an application by manipulating either the import system’s search path or placing files earlier on the path than intended.

This is often seen when developers create a script with the same name as the module they intend to use - for example, a random.py file that attempts to import the standard library random module. This is not sandboxing, as this proposal does not attempt to prevent malicious behavior (though it enables some new options to do so). See the Why Not A Sandbox section below for further discussion. Overview of Changes The aim of these changes is to enable both application developers and system administrators to integrate Python into their existing monitoring systems without dictating how those systems look or behave.

We propose two API changes to enable this: an Audit Hook and Verified Open Hook. Both are available from Python and native code, allowing applications and frameworks written in pure Python code to take advantage of the extra messages, while also allowing embedders or system administrators to deploy builds of Python where auditing is always enabled. Only CPython is bound to provide the native APIs as described here. Other implementations should provide the pure Python APIs, and may provide native versions as appropriate for their underlying runtimes.

Auditing events are likewise considered implementation specific, but are bound by normal feature compatibility guarantees. Audit Hook In order to observe actions taken by the runtime (on behalf of the caller), an API is required to raise messages from within certain operations. These operations are typically deep within the Python runtime or standard library, such as dynamic code compilation, module imports, DNS resolution, or use of certain modules such as ctypes .

The following new C APIs allow embedders and CPython implementors to send and receive audit hook messages: # Add an auditing hook typedef int ( * hook_func )( const char * event , PyObject * args , void * userData ); int PySys_AddAuditHook ( hook_func hook , void * userData ); # Raise an event with all auditing hooks int PySys_Audit ( const char * event , PyObject * args ); The new Python APIs for receiving and raising audit hooks are: # Add an auditing hook sys . addaudithook ( hook : Callable [[ str , tuple ]]) # Raise an event with all auditing hooks sys . audit ( str , * args ) Hooks are added by calling PySys_AddAuditHook() from C at any time, including before Py_Initialize() , or by calling sys.addaudithook() from Python code.

Hooks cannot be removed or replaced. For CPython, hooks added from C are global, while hooks added from Python are only for the current interpreter. Global hooks are executed before interpreter hooks. When events of interest are occurring, code can either call PySys_Audit() from C (while the GIL is held) or sys.audit() . The string argument is the name of the event, and the tuple contains arguments. A given event name should have a fixed schema for arguments, which should be considered a public API (for each x.y version release), and thus should only change between feature releases with updated documentation.

To minimize overhead and simplify handling in native code hook implementations, named arguments are not supported. For maximum compatibility, events using the same name as an event in the reference interpreter CPython should make every attempt to use compatible arguments. Including the name or an abbreviation of the implementation in implementation-specific event names will also help prevent collisions. For example, a pypy.jit_invoked event is clearly distinguished from an ipy.jit_invoked event.

Events raised from Python modules should include their module or package name in the event name. While event names may be arbitrary UTF-8 strings, for consistency across implementations it is recommended to use valid Python dotted names and avoid encoding specific details in the name. For example, an import event with the module name spam as an argument is preferable to a spam module imported event with no arguments. Avoid using embedded null characters or you may upset those who implement hooks using C.

When an event is audited, each hook is called in the order it was added (as much as is possible), passing the event name and arguments. If any hook returns with an exception set, later hooks are ignored and in general the Python runtime should terminate - exceptions from hooks are not intended to be h

The rest of this page is on the live site.