Python core binding (P1)
Ready
The hub proposes this hook for the containers it fits, and nothing changes until a player approves the proposal (Hook proposals). The cheat sheet has the steps by hand.
The base of every Python hook package. It loads vulnboxd's core library into the Python process, keeps the current request's id in a context variable, and wraps the handful of standard-library functions through which a Python service starts processes, opens connections and opens files, so each of those can be linked to the request that caused it. It gets in with a compose-only change: a read-only mount of the hook directory and PYTHONPATH. The image and the source stay untouched.
On its own P1 reports processes, connections and files for code that marks its requests with the small public API (see Source change). The framework packages mark requests automatically and are installed by the same change: P2 (WSGI), P3 (ASGI), P4 (aiohttp, Sanic, Tornado, Twisted, raw asyncio/trio), P5 (gevent/eventlet), P6 (socketserver, http.server) and P7 (C-level database and HTTP clients).
Covers
| Versions | |
|---|---|
| CPython | 3.8–3.14, including the free-threaded 3.14t build |
| PyPy | 3.9+ (tested: 3.10, 3.11) |
| C library | glibc and musl (Alpine); x86_64 and aarch64 |
| Dependencies | none: standard library only (ctypes, contextvars) |
The P1 sample service runs the same scenario on CPython 3.8, 3.9, 3.10, 3.11, 3.12, 3.13, 3.14, 3.14t, PyPy 3.10 and PyPy 3.11 in one container.
What the kernel already links without any hook: a process or thread per connection (forking servers, gunicorn's sync worker, socketserver.ForkingTCPServer / ThreadingTCPServer, a thread per request), where the process or thread has exactly one client socket at a time. P1 is needed wherever one thread serves many requests in turn: asyncio, gevent/eventlet, thread pools that hand work over.
How it gets in
From a registry (local development, or a build with network; the same release as the hook directory): pip install vbxtrace==1.0.0, then python -m vbxtrace app.py or import vbxtrace.auto first (no sitecustomize needed); see Local development.
Compose-only. The hub proposes:
services:
<service>:
+ volumes:
+ - /usr/local/lib/vulnboxd/trace:/opt/vbxtrace:ro
+ environment:
+ PYTHONPATH: /opt/vbxtrace/pythonIf the service already sets PYTHONPATH, the hook directory is appended to it with : (PYTHONPATH: /app/src:/opt/vbxtrace/python); in a Dockerfile ENV PYTHONPATH=..., the compose value replaces the image's, so the proposal repeats the image's value in front.
What happens at startup: Python imports the first sitecustomize module on sys.path, which is now /opt/vbxtrace/python/sitecustomize.py. It
- runs the
sitecustomizethe image would have used otherwise (the next one onsys.path, e.g. the one Debian's system Python ships); an error in it is re-raised afterwards, so Python reports it exactly as before ("Error in sitecustomize; ..."); - unless
VBXTRACE=0, loads/opt/vbxtrace/libvbxtrace-<arch>.sowithctypes(<arch>fromuname -m), checks its ABI version, installs P1's wrappers and imports every framework module (fw_*.py) the other Python packages put next to it. Nothing third-party is imported: framework modules only register post-import hooks that run when the program imports the framework itself.
Applying it by hand is the same edit. The hub proposes it when it detects: requirements*.txt, pyproject.toml, Pipfile(.lock), poetry.lock, uv.lock, setup.py; a base image python:*, pypy:*, ghcr.io/astral-sh/uv*, tiangolo/*; or python, gunicorn, uvicorn, hypercorn, daphne, granian, waitress-serve, uwsgi or flask in the command (proposals/compose.toml).
Child processes inherit PYTHONPATH, so Python programs the service starts are hooked too. An older interpreter that finds the files (Python 2, Python 3.7 and older) fails to import the binding and silently carries on without it.
Not loaded when the interpreter ignores the environment or site: python -E, -I (isolated mode) and -S. The hub's detection notes such commands.
Source change for servers no package knows
A hand-rolled select/selectors loop or a custom protocol server can mark its requests with the public API (vendored no-op shim: P6):
import vbxtrace
with vbxtrace.session(conn): # a raw session on an accepted socket (thread/fork per connection)
handle(conn)
with vbxtrace.request(local_port=8080, peer=("10.0.0.7", 51234), index=0,
protocol=vbxtrace.PROTO_HTTP1) as r:
...
r.status = 200
s = vbxtrace.Session(conn) # an event loop: on accept
with s: # around each piece of work for that connection
on_readable(conn)
s.close() # when the connection ends
child = vbxtrace.handoff() # work moved somewhere context does not follow
with vbxtrace.adopt(child): # ... on the thread that runs it
work()When the request's number on its connection cannot be known exactly, pass index=vbxtrace.REQUEST_INDEX_UNKNOWN (never a guess or a per-process counter): the sensor then links the request only through other exact facts. Every function is safe to call when the hook is not loaded.
What it records
P1 emits events only while a request is current (a context id is set); work outside requests is never reported.
| Event | Emitted from | Join key |
|---|---|---|
spawned | subprocess.Popen.__init__ (also subprocess.run, os.popen, asyncio.create_subprocess_*, which use it), os.fork, os.forkpty, os.posix_spawn, os.posix_spawnp (os.spawn* go through os.fork), multiprocessing Process.start with the spawn/forkserver start methods | child pid |
context_enter / context_exit | around os.system (libc forks inside; the pid never reaches Python, but the thread is blocked in the call, so "this thread runs the request" is exact for its duration) | thread |
connected | socket.socket.connect / connect_ex (blocking connects, socket.create_connection, everything built on them: requests/urllib3, http.client, redis, pymongo, PyMySQL, ...), asyncio's selector-loop sock_connect (non-blocking connects: asyncio.open_connection, loop.create_connection, asyncpg, aiohttp's client, httpx async), socket.socket.sendto on UDP (once per socket and request) | local port (+ peer, transport tcp/udp) |
opened | builtins.open / io.open (flags computed exactly as io.FileIO does, O_CLOEXEC included), os.open (the flags passed, plus O_CLOEXEC which Python always adds) | pid + fd |
context_enter / context_exit | around each concurrent.futures.ThreadPoolExecutor work item (also loop.run_in_executor, asyncio.to_thread) | thread |
Opens through an opener= callable report through that opener (usually os.open); open(fd) on an existing descriptor reports nothing (no new open). Unix-socket connections have no port and are not reported. A connection reported twice in a row (green socket classes wrapping a real socket) is reported once; so is a child reported by two wrappers (gevent's fork calling the os.fork it captured).
Context following
The request's context id lives in a contextvars.ContextVar. It follows automatically:
awaitand everything in the same task; new asyncio tasks (create_task,gather, ...) copy the context they are created in, so tasks a request starts keep its id — also after the request ended (background work is still that request's work);- trio and anyio tasks the same way; greenlets: each greenlet has its own context (greenlet ≥ 0.4.17), see P5 for
spawn.
P1 carries it where Python does not:
ThreadPoolExecutor.submit(and sorun_in_executor,asyncio.to_thread, Django'sasgiref): the work item runs with the submitter's id, betweencontext_enterandcontext_exiton the worker thread (exact: the worker runs only that item meanwhile, so the kernel can link e.g. libc's DNS lookups there too). Items submitted outside a request run with no id, never with whatever the worker last had.threading.Thread.start: a thread started inside a request runs with its id (Thread.runis shadowed on the instance). Not for threads of libraries that keep worker threads — pools, reactors, servers (targets orThreadsubclasses fromconcurrent.futures,multiprocessing,asyncio,twisted,anyio,gevent,waitress,gunicorn,django,sqlalchemy,psycopg_pool, ...): a pool thread that happens to be started by request A must not report request B's work as A's. Their work items are carried per item instead (P1:ThreadPoolExecutor; P4: Twisted's thread pool).
Needs vbxtrace.handoff() / adopt(): work queued to threads you start yourself and feed through a queue.Queue (the id is carried into the thread when it starts, not with each item).
Known gaps
- C extensions doing their own I/O bypass the wrappers:
psycopg2/psycopg(libpq),mysqlclient,pycurl— covered by P7; others (e.g.lxmlfetching URLs,grpcio's C core,confluent-kafka) are linked only by the kernel's thread rule where it applies. - uvloop: its loop is C, so non-blocking connects made through it (
asyncio.open_connectionunder uvloop) are not reported; blockingsocketconnects still are. File opens and processes are unaffected. subprocesschildren are reported with their pid;os.systemandpty.spawn-style C forks only throughcontext_enter/exit(the sensor links the thread's fork).- Python started with
-E,-Ior-S, or an embedded interpreter that skipssite(some uWSGI setups with--no-site), does not load the hook. multiprocessingchildren started with the forkserver method are children of the forkserver process; they are reported with their pid, but the kernel lineage is the forkserver's.
Safety
- Every wrapper calls the original first with exactly the arguments it got (
*args, **kwargs, so even aTypeErrorfor a bad call is the original's) and returns its result unchanged; an exception from the original propagates untouched (the traceback gains one frame: the wrapper's). The binding's own work runs afterwards insidetry/except Exception, which counts the error and returns. - Module-level functions (
open,os.open,os.fork, ...) are replaced by callables that, like the builtins, do not bind as methods when stored as class attributes (Python 3.8'spathlibdoes that), pickle by reference and print like the original (repr(open)is still<built-in function open>). - Semaphore check first: every wrapper first asks the core whether a tracer is attached (
vbx_v1_enabled_mask(), onectypescall) and does nothing else while none is. Outside a request it stops right after that. - Off after 5 internal errors for the rest of the process.
VBXTRACE=0in the environment: nothing is installed at all (openstays the builtin). - The post-import hook puts the real loader back on the module and its spec before the module's code runs, so a module never sees vbxtrace's loader.
- Chaos test: with
VBXTRACE_CHAOS=1every event call into the core raises inside the guards (the queries still answer, so every wrapper runs its whole path); the samples' responses are byte-identical to the hooked and the un-hooked runs, and the unit tests (hooks/python/p1/tests) check failing queries, the error limit, transparency of exceptions,sitecustomizechaining and the import hook. - Overhead: without a tracer each wrapper costs one
ctypescall and returns. Overhead has not been measured yet; it will be measured on the sample services in the dedicated performance phase.
Turning it off
Set VBXTRACE=0 in the service's environment and restart it, or revert the change that added the hook; vulnboxd's rollback covers a hook that breaks a service.
Removing the PYTHONPATH entry and the mount removes every Python package at once; nothing stays in the image.
Troubleshooting
- Are the probes there?
readelf -n /usr/local/lib/vulnboxd/trace/libvbxtrace-x86_64.solists them;sudo bpftrace -l 'usdt:/usr/local/lib/vulnboxd/trace/libvbxtrace-x86_64.so:*'too. - Is the hook loaded?
grep vbxtrace /proc/<pid>/mapsinside the container shows the library;docker compose exec <service> python -c 'import vbxtrace; print(vbxtrace._core.state.on)'printsTrue. WithVBXTRACE_DEBUG=1the binding prints what it loaded and every internal error (with a traceback) to stderr. - Which links did a flow get? The hub shows each link's method; this package's are
hook:P1. - Nothing is linked: check that
PYTHONPATHreally reaches the process (aCMDrunningpython -I, an entrypoint script that resets the environment,sudodropping variables), that the mount is at/opt/vbxtrace, and that the image's Python is 3.8 or newer. - The image has its own
sitecustomize: it still runs (first); if it fails, Python reports it as before and the hook is installed anyway. - Samples:
hooks/run-samples.sh python --package p1runs the scenario on every interpreter (sampleversions: 370 recorded events matchgolden.eventsacross CPython 3.8–3.14, 3.14t, PyPy 3.10 and 3.11; chaos and baseline responses byte-identical); the unit tests run withpython3 -m unittest discover -s hooks/python/p1/testsaftercargo run -p vbxtrace-harness -- dist.