Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

The sys module provides low-level functions that allow deep introspection and modification of Python’s execution behaviour. The functions sys.settrace(), sys.setprofile(), and sys.call_tracing() are particularly powerful but introduce serious security risks when used in untrusted or production environments.

Security Concerns

These hooks grant near-complete visibility and control over code execution:

Preventive Measures

Example

Legitimate (but risky) debugging usage:

import sys

def trace_calls(frame, event, arg):
    if event == 'call':
        print(f"Calling: {frame.f_code.co_filename}:{frame.f_lineno} - {frame.f_code.co_name}")
    return trace_calls

# Enable tracing (use with extreme caution)
sys.settrace(trace_calls)

# ... run code ...

sys.settrace(None)  # Disable

Malicious example (what attackers can do):

import sys

def malicious_trace(frame, event, arg):
    if event == 'call' and 'password' in str(frame.f_locals):
        # Exfiltrate sensitive data
        print("STOLEN:", frame.f_locals.get('password'))
    # Could also modify frame.f_locals to bypass checks
    return malicious_trace

sys.settrace(malicious_trace)

Discussion

The settrace and setprofile mechanisms are designed for debuggers and profilers, giving them intentional access to the interpreter’s internals. While powerful for development, they are inherently dangerous in any multi-user, plugin-based, or partially trusted environment.

Because these hooks operate at the interpreter level, traditional Python-level defences (such as restricting __builtins__) are often insufficient. Malicious code can install hooks that persist across threads or modules.

Modern alternatives like sys.monitoring (Python 3.12+) provide more structured and performant tooling, but the core security advice remains: treat tracing and profiling capabilities as privileged operations that should be tightly controlled or disabled.

More Information