Security model¶
What tethered defends against, what it does not, and what locked mode adds to that.
Threat model¶
tethered is a defense-in-depth guardrail, not a security sandbox. It intercepts Python-level socket operations. Code that uses
ctypes,cffi, subprocesses, or C extensions with direct syscalls can bypass it. Ordinary libraries do the same without any intent when they resolve names and connect inside a C library of their own: psycopg2, pycurl and grpcio are examples, and tethered sees nothing they do. For the most common case, the uvloop event loop that uvicorn picks whenever it is installed, tethered refuses to run rather than run unenforced. For a guarantee, combine tethered with controls below Python: an egress proxy or a network policy that names the allowed hosts, containers, seccomp, network namespaces.
tethered's protections are scoped at Python audit events. They defend against:
- Trusted-but-buggy code that calls
socket.connect,requests.get, or similar without thinking about egress (a logging library that phones home for telemetry, a misconfigured dep that fetches metadata from prod). - Opportunistic supply-chain compromise — a dep that was hijacked, its attacker doesn't know tethered is in the process and writes the same Python-level network code anyone would write.
They do not make tethered into a sandbox against a deliberately-malicious dependency that knows tethered is installed and writes a few lines of bypass code. The audit-event surface is one trust boundary; ctypes and cffi are another, and they live in the same process with the same permissions. Python code that targets tethered's own internals is a third, and locked mode narrows it without closing it (see Locked mode).
What tethered protects against¶
Trusted-but-buggy code and supply chain threats: dependencies that use Python's standard socket module (directly or through libraries like requests, urllib3, httpx, aiohttp). tethered prevents these from connecting to destinations not in your allow list. Under asyncio this holds on the standard event loop, where these libraries' async clients use the same socket module. tethered does not run on uvloop (it keeps uvloop from being imported under a policy and refuses to activate over a loaded one), and on Windows it holds only in part on the default ProactorEventLoop; both are described in the next section. Which servers, task queues and client libraries this was measured with, and with which result, is in the compatibility page.
The check covers every address form CPython's socket layer accepts: str, bytes and bytearray hosts, and ports given as any object with __index__. An address on an IP-family socket that tethered cannot read is refused, not allowed. One call carries no address at all and is let through: sendmsg() without one is a write on a connected socket, whose destination was checked when it connected (asyncio writes that way from Python 3.12). One connection is let through whatever the allow list says: the one with which socket.socketpair() joins its own two sockets where the platform has no socketpair() of its own (Windows), which every asyncio event loop makes when it is created. tethered recognises it by the function that makes it, CPython's fallback in the socket module, and by its target: the socket that the same call of that function is listening on, at 127.0.0.1 or ::1, so both ends are in the process. Every other connection to loopback is checked, including one that the fallback function is made to open to any other address. A log-only layer (the global policy or a scope) never suppresses an enforcing one: every layer is evaluated, and an enforcing layer that denies still raises.
What tethered does NOT protect against¶
Native code, and libraries that do not use Python's sockets¶
ctypes/cffi/ direct syscalls — the universal bypass. Native code can call libc'sconnect()(egress),unlink()(deletetethered.pth),setenv()/unsetenv()(mutate_TETHERED_CHILD_POLICY), orexecve()(spawn) directly, all of which skip the Python audit-event machinery tethered hooks into. (Python's ownos.putenv()/os.unsetenv()raise audit events and are detected; the libc calls raise none. In locked mode a changed_TETHERED_CHILD_POLICYis still noticed afterwards, at the next process launch tethered sees that inherits the environment, because that launch is checked against the environment of the process itself. Native code can just as well start the process itself.) None of tethered's locked-mode hardenings stop actypes-armed attacker; they raise the bar for opportunistic attacks but don't close it for deliberate ones.- Libraries that resolve names and connect in C. An extension module that calls the C library's
getaddrinfo()andconnect()itself, or links a client library that does, never passes through Python'ssocketmodule. No audit event is raised, so tethered neither blocks nor reports what it does: the forbidden name is looked up, the forbidden address and port are reached,locked=Trueandfail_closed=Truechange nothing, andlog_onlyreports nothing. An audit hook cannot close this gap. Measured examples, each reaching every forbidden destination under a locked policy: pycurl and curl_cffi (libcurl), tornado'scurl_httpclient, psycopg2 (libpq), mysqlclient, the C extension of mysql-connector-python (its default), pymssql and pyodbc with the FreeTDS driver, grpcio (sync andgrpc.aio), confluent-kafka (librdkafka), pyzmq, andawscrt.http. psycopg 3 is enforced in part: it looks the name up through Python, where it is checked, and then hands the address to libpq, so a raw address or a port outside the rule is reached. Pure-Python drivers of the same services are enforced (pg8000 and asyncpg, PyMySQL, mysql-connector-python withuse_pure=True, oracledb in thin mode, kafka-python). The compatibility page has the table. That such a module is loaded says nothing about its use:_awscrtis loaded by every botocore import when awscrt is installed, while boto3 goes on connecting through urllib3, which is enforced. - Libraries that resolve names themselves and connect through Python. tethered ties an address to a hostname when it sees the lookup (
socket.getaddrinfo,socket.gethostbyname). A resolver that does not go through those leaves tethered with a connection to an address it has no name for. This fails in the safe direction for connections and not for names: no forbidden destination is reached, but a host that the allow list names is refused as well (... 203.0.113.7:443 is not in the allow list), and the name of any host, forbidden ones included, is still sent to the name server. Measured: c-ares through pycares / aiodns (what aiohttp resolves with when aiodns is installed), dnspython, eventlet's default greendns, gevent withGEVENT_RESOLVER=ares, and niquests with a resolver of its own. For c-ares the DNS query is sent in C, so it also reaches a name server at a forbidden address; dnspython's query is asocket.sendtoand is checked like any datagram. tethered keeps pycares from being imported while a policy that is notlog_onlyis active (ImportError), so that aiohttp falls back to its threaded resolver, which is enforced; a pycares that was imported beforeactivate()is left alone. The first refused connection to an address with no known name logs one hint about this. The remedies are the system resolver (aiohttp:activate()before aiohttp is imported, orresolver=aiohttp.ThreadedResolver(); eventlet:EVENTLET_NO_GREENDNS=yes; gevent: its default resolver) or a rule for the address.
Event loops¶
-
asyncio on uvloop: refused, with four exceptions. uvloop's event loop does its networking in libuv, below Python's
socketmodule, and raises no audit event for it: on that loopasyncio.open_connection,loop.create_connection(host, port),loop.getaddrinfo, datagram endpoints, clients built on them such ashttpx.AsyncClient, and launches throughasyncio.create_subprocess_exec/create_subprocess_shellare neither blocked nor reported, whatever the policy. uvicorn runs on uvloop by default whenever it is installed. tethered therefore does not run next to it. While a policy that is notlog_onlyis active, importing uvloop raisesImportError, and a server that takes uvloop only when the import works (uvicorn, its gunicorn worker) runs on the standard loop instead. When uvloop is already loaded,activate()raisesRuntimeErrorand logs the same message as an error: the server does not start. This guards a deployment against silently not being enforced; it is not a barrier to code that is out to get around tethered, which can load any other extension that does its own networking. What remains:- A
log_onlypolicy refuses nothing, uvloop included. It is activated over a loaded uvloop and reports nothing that goes through the loop, so the list of what would be blocked is empty for every asynchronous call. One warning is logged. - A
scope()with noactivate()under it neither keeps uvloop out nor refuses to be entered. On uvloop it is not applied to what goes through the loop. One warning is logged. - An interpreter outside a lock (Interpreters under a lock) holds no policy of its own. The lock refuses its sockets but not its imports: it can load uvloop, and a connection on a uvloop loop then reaches a forbidden destination (measured under mod_wsgi).
activate()looks at its own interpreter only, so uvloop loaded in another interpreter does not stop it. - A server that swallows the refusal. uvicorn's default
--lifespan autotakes an exception from a hand-written ASGI lifespan handler for "lifespan not supported" and serves. An application that callsactivate()there, after uvicorn has loaded uvloop, runs on uvloop with no policy; the error thatactivate()logs is the only trace. FastAPI and Starlette report a failed start-up and the server exits.
What tethered sees on uvloop in those cases is code that uses Python's sockets itself: blocking
socketcalls, also throughasyncio.to_thread, andloop.sock_connecton a Python socket. Name the standard loop in the server's configuration (uvicorn --loop asyncio), or keep uvloop out of the environment. Which servers fall back, which refuse to start and which need a launcher script is in the cookbook. On the standard loop everything tested is enforced: streams,create_connection,sock_connect, datagram endpoints, httpx and aiohttp. - A
-
Other event loops that are not asyncio's. rloop (granian's Rust loop) makes its connections, lookups and launches through Python's
socketandsubprocessmodules and is enforced, with one exception: a datagram sent withtransport.sendto(data, addr)on an unconnected endpoint goes out below Python and is not seen. trio and Twisted go through thesocketmodule and are enforced. - asyncio on the Windows default event loop (
ProactorEventLoop). Windows only. That loop connects and sends datagrams through overlapped I/O calls (_overlapped.ConnectEx,_overlapped.WSASendTo) that raise nosocket.connect/socket.sendtoaudit event. On it, raw-IP destinations, port rules andscope()connect checks are not enforced; only the global policy's DNS-time hostname check applies. tethered logs a one-time warning when a socket is created while a Proactor loop is running. Run the loop asasyncio.SelectorEventLoopfor full enforcement (asyncio.run(main(), loop_factory=asyncio.SelectorEventLoop)on Python 3.12+). Synchronous code on Windows, and asyncio's standard event loop on other platforms, are not affected.
What the socket events do not cover¶
- Lookups for hostnames passed directly to
connect()/sendto(). CPython resolves the address before it raises thesocket.connect/socket.sendtoaudit event, so forsock.connect(("host.example", 443))the DNS lookup happens before tethered sees the call. The connection or datagram itself is still refused. Code that resolves first (socket.getaddrinfo,socket.create_connection, and the HTTP libraries built on them) is checked before the lookup. socket.getnameinfo. Not checked. Its audit event carries the address but not the flags, so a reverse lookup cannot be told apart from numeric formatting (NI_NUMERICHOST), which libraries call on every peer and local address. Reverse lookups throughsocket.gethostbyaddrare checked.- Lookups of the machine's own name. While an
activate()policy is in place,socket.getaddrinfo,socket.gethostbyname/gethostbyname_exandsocket.gethostbyaddrof the name thatsocket.gethostname()returned when the policy was put in place are checked by neither the policy nor any scope, so thatsocket.getfqdn(),smtpliband other code that asks for the machine's own name work under any allow list. Renaming the machine afterwards does not change which name that is. The lookup records no name for the addresses it returns, so the connection that follows is checked like a connection to a raw IP. Under ascope()with noactivate()under it, the name is checked like any other. A lookup with no host or an empty one, which also names the local machine, is never checked. - Connections that are already open. tethered checks connection, DNS and datagram events, not reads and writes. A connection opened before
activate(), or before entering a narrowerscope(), stays usable. That includes a pooled HTTP connection reused inside a request-scopedscope().
Child processes¶
- Egress inside non-Python child processes. Python children auto-inherit tethered (via
tethered.pth+ the_TETHERED_CHILD_POLICYenv var), andexternal_subprocess_policycan monitor or block the launch of any subprocess. But tethered cannot enforce egress rules inside a non-Python executable (curl, ffmpeg, bash, etc.), and it does not see what such a program does to files:subprocess.run(["rm", ".../tethered.pth"])deletes the bootstrap file outside every Python-level guard, and the loss is noticed only at the next launch of a Python child (see The bootstrap file).external_subprocess_policy="block"refuses these launches. For hard subprocess isolation, combine with OS-level controls (seccomp, containers). See the subprocess page. - Spawning a different Python interpreter (e.g.
subprocess.run(["/usr/bin/python3", …])) where tethered isn't installed — the child has notethered.pthto fire, so it runs uncontrolled.external_subprocess_policy="block"shuts this down. - Launches of
sys.executablethat skip the bootstrap.-Sdisablessite.pyand so skips the auto-activationtethered.pth.-I/-Ekeepsite.pyenabled and so are NOT a bypass, with one exception: when tethered is installed in the per-user site-packages (pip install --user),-sand-Iskip that directory and the bootstrap with it. Such launches are treated as external, and so are a launch whose interpreter options cannot be parsed and, on POSIX, a launch whoseargv[0]is notsys.executable(an interpreter works out which installation or virtual environment it belongs to fromargv[0], so started aspythonit can come up where notethered.pthis processed).external_subprocess_policy="block"refuses them. - Python children when tethered is not installed into site-packages.
site.pyrunstethered.pthonly from a site directory: the interpreter's site-packages or the enabled per-user site-packages. An editable install (-e) and a--targetinstall used throughPYTHONPATHhave no such file, whether uv or pip makes them.activate()then logs a warning, no Python child auto-inherits, and everysys.executablelaunch is treated as external. A file of that name that is not tethered's counts as no file: tethered takes atethered.pthfor its bootstrap only while it holds the line tethered installs. Another distribution that ships a top-leveltethered.pthreplaces tethered's when it is installed, without a word from pip or uv (measured with pip 26.2.1 and uv 0.13.0), and uninstalling that distribution removes the file. - Known gaps in the Python-launch classification.
- A
tethered.pthprocessed only through an explicitsite.addsitedir()call is not recognized. The error is on the safe side: the warning above is logged andsys.executablelaunches are treated as external, so they are warned about or, under"block", refused. mod_wsgi'spython-pathoption adds its directories that way and leavessys.executableat the system Python: with tethered installed only in the virtual environment, a Python child launched under the default"warn"runs without tethered. Give mod_wsgi a virtual environment withpython-homeinstead (the cookbook). - A Python child's environment is not inspected beyond the policy variable. Variables that change its site configuration (
PYTHONNOUSERSITE,PYTHONUSERBASE,PYTHONHOME) can keep it from runningtethered.pth. A directory onPYTHONPATHcomes before site-packages, so a package namedtetheredthere is the one the bootstrap imports (measured with Python 3.14). On LinuxLD_PRELOADruns a library of the caller's choosing in the child before Python starts. - If the tethered package is importable only through
PYTHONPATH, a child started with-Eor-Iruns the.pthline but cannot import tethered, and starts without a policy. - A child whose environment is wiped on the way, by a program in between that is not Python (
env -i, a process manager configured to do so), starts without the policy too. - Where Python is embedded,
sys.executableneed not be a Python interpreter: under uWSGI it is the uwsgi binary. tethered recognises such a program and counts every launch as external, a launch of the real interpreter included (the subprocess page); start uWSGI with--py-sys-executable /path/to/python. An embedding program that is itself named like an interpreter (python…,pypy…) is not told apart, and a launch of it is taken for a Python child that inherits the policy.
- A
multiprocessingspawn / forkserver launches on POSIX with Python 3.11–3.13. They raise no audit event (_posixsubprocess.fork_execraises one from Python 3.14), so tethered sees neither the launch nor its environment: noexternal_subprocess_policy, no locked-mode payload check, and no repair of a cleanedos.environ. Workers still inherit the policy while_TETHERED_CHILD_POLICYis intact in the process environment. On Windows, and on POSIX from Python 3.14, these launches are handled.- Workers of the
forkserverstart method, when the fork server is older than the policy. A forkserver worker is a copy of the fork server process, not of the process that asks for it and not a new interpreter. A fork server that was started beforeactivate()holds no policy (or the one before), and so does every worker it forks from then on, also afteractivate(locked=True): neither the copy of the caller's state that a forked child gets nor the bootstrap that a spawned child runs reaches them, and asking the fork server for a worker goes over a socket and raises no launch event, so tethered can neither refuse it nor complete it. Measured on Python 3.14, where forkserver is the default start method on Linux: workers started after the lock reached a forbidden destination.activate()logs one warning when it finds a fork server already running. Callactivate()before the first pool or process is started; a fork server that starts under the policy is an ordinary Python child and passes it on. The same holds for any process that existed beforeactivate(): pool workers started earlier have no policy until they are replaced. - The environment and command line of a direct
_winapi.CreateProcesscall (Windows). The audit event does not carry the environment. tethered reads it formultiprocessingand, inside a virtual environment, for third-party copies of its spawner (joblib's loky, billiard); for any other direct caller the launch is judged as if it inherited the process environment. The event does not deliver a usable command line either (CPython 3.11–3.15 pass that argument incorrectly), so on this route a launch is judged by its executable alone:-Sand other interpreter options are not seen. Launches throughsubprocessare not affected; they are checked from thesubprocess.Popenevent.
Code in the same process¶
- In-process disabling (without
locked=True). Code in the same interpreter can calldeactivate()oractivate()unlesslocked=Trueis used. - Different unlocked policies in the interpreters of one process. Without a lock each interpreter can have a policy of its own, and each enforces its own on the connections made in it. Child processes and later interpreters are another matter, because
_TETHERED_CHILD_POLICYis one variable for the whole process and everyactivate()writes it. A Python child process gets the policy of whichever interpreter activated last, whichever interpreter launches it, and an interpreter created afterwards starts under that policy even if the code that runs in it never imports tethered. Two mod_wsgi application groups with different unlocked policies in one process are an example. Without a lock a launch is not compared with the environment of the process itself, so nothing reports this. Give each application its own process, or lock one policy for the whole process. - In-process tampering with scopes.
scope()is best-effort narrowing within the global ceiling — there is noscope(locked=...)equivalent. A compromised dep inside a scoped function can wipe_scopes.set(()), mutate frozen_ScopeConfigfields viaobject.__setattr__, or monkey-patch_check_scopes— all of which lose the narrowing and fall back to whatever the global policy allows. This is bounded by intersection semantics: scope tampering can never widen egress beyond the global policy, only release the additional narrowing. For a ceiling that takes a token to replace, useactivate(locked=True). Scopes inside a locked global remain soft, in every interpreter; the global has the protection, and the limits, described under Locked mode. - Scope lifetime under generators, executor threads and tasks. A generator suspended inside
with scope():leaves the scope active in the consumer's context between yields. A lookup made in another thread on the scope's behalf is not checked against the scope at DNS time (asyncio'sloop.getaddrinforuns in an executor thread); the connection that follows is checked. A task created inside awith scope():block keeps the scope after the block exits, but with noactivate()policy its laterloop.getaddrinfolookups are no longer recorded, so its connections by hostname are blocked. A scope does not follow work into another thread: a thread started inside the block andloop.run_in_executorrun without it (asyncio.to_threadcarries it), and so does a lookup in the thread pool of gevent's resolver. In each of these theactivate()policy still applies. The compatibility page has what was measured. - In-process Python code written against tethered (with
locked=True). Locked mode requires the token to replace or deactivate the policy and detects changes to the objects it has recorded. It is not a sandbox: code in the same process that targets tethered can still defeat it, withoutctypes. The next section lists what is checked and what is not.
Locked mode — what it does and does not do¶
activate(locked=True, lock_token=...) requires the C extension and does the following:
- Token. Replacing or deactivating the policy requires the token object passed at activation, compared by identity. Only the C extension holds a reference to it; tethered keeps no Python-visible copy.
- Snapshot. At activation the extension records several hundred facts about tethered's own code and the active policy: what every module-level name in
tethered._coreandtethered._policyis bound to (except the active config, which the extension tracks itself, and lower-case scalar runtime state such as flags and counters); every class attribute of the classes defined there; the code object of every Python function found; that no builtin those modules use is shadowed in their namespaces; that no__getattribute__/__getattr__has been added to those classes; and the class and every slot of the active config and policy. - When it is checked. The facts are re-checked on every socket audit event, every process-launch event, every
open/os.remove/os.rename/os.chmod/os.truncate/os.link/os.symlink/_winapi.CopyFile2event whose path mentionstethered.pthortethered.start, and everyos.putenv/os.unsetenvof_TETHERED_CHILD_POLICY. - On a mismatch. The operation is refused for as long as the mismatch lasts:
EgressBlockedfor socket events (creating a socket included),SubprocessBlockedfor the others. One alert line is written to stderr the first time. Restoring the original objects ends the refusals. While the check fails, the policy can be neither replaced nor deactivated, even with the token (TetheredLocked). - tethered's own lookups. The DNS lookups tethered makes to map addresses to hostnames go through the extension, which calls the resolver it captured when the policy was locked (in an interpreter that joined the lock, when it joined). Setting tethered's Python-side reentrancy flag by hand is detected on the next socket event, and a connection or datagram attempted from inside such a lookup is refused.
- Immutable policy data. Allow rules are immutable tuples of strings and integers, and the child-policy payload is compared against an immutable string, so neither can be edited in place.
- Launch environments. A launch environment that carries a different policy, an invalid value or two spellings of the variable is refused. One that simply lacks
_TETHERED_CHILD_POLICYis what ordinary code passes, so it is given the variable where that is possible (asubprocesslaunch, an external program's included, and anos.exec*of the same interpreter) and refused where it is not:os.posix_spawn,os.spawn*and anos.exec*of another program.reactor.spawnProcessof Twisted with its default, empty environment is such a launch. The subprocess page has the routes and the checks. - The bootstrap file.
tethered.pthis guarded against change from Python, and its content is checked at every launch of a Python child; see The bootstrap file. - Other interpreters. The lock is held once per process. An interpreter created while it is held joins it, and every other interpreter is refused the guarded operations; see Interpreters under a lock.
Locked mode is not a sandbox. It stops accidental and casual disabling and detects the tampering described above. Python code written against tethered can still do the following, without ctypes:
- Replace builtins or the standard-library functions the policy calls (
fnmatch.fnmatchcase,ipaddress.ip_address,json.loads,os.pathfunctions). The snapshot covers tethered's two modules, not the modules they call into. - Write into containers whose identity is pinned but whose contents are not: the IP-to-hostname map (an entry naming an allowed host for an address lets a connection to that address through) and the fallback candidate set.
- Change function defaults or closure cells. Code objects are pinned; defaults and closures are not.
- Rebind names in
tethered/__init__.pyortethered._autoactivate, which are not in the snapshot. - Tamper before activation. The snapshot records whatever is in place when
activate()runs, and that includes which C extension is loaded: importing tethered does not load it, the firstactivate()ordeactivate()does. In a child process and in an interpreter that joins a lock, that moment is the bootstrap. - Write startup files. Only
tethered.pthandtethered.startare guarded. Another.pthfile written into a site directory is run by every later child process and every new interpreter, and whensite.pyprocesses it beforetethered.pthit runs before the bootstrap: the child, or the joining interpreter, then records whatever that file put in place.site.pygoes through the.pthfiles of a directory in the order of their names. A distribution that ships a.pthfile of its own has the same effect from the moment it is installed, with nothing written under the lock. - Replace
/sbin/ldconfig, where the process can write it. The launch with whichctypes.util.find_library()reads the linker cache on Linux,/sbin/ldconfig -pwithLC_ALL=CandLANG=Cand nothing else, is not an external launch, so"block"lets it through (the subprocess page). tethered compares the command line and the environment, not the program: code that writes that file, or what it loads, and then makes that launch itself runs any program. The official Python images run the application as root, which can write it. Writing a.pthfile into site-packages (above) takes the same access. From Python 3.13, where an audit hook can write the local variables ofsubprocess.Popen._execute_child(PEP 667), no file has to be written: a hook added after the policy can change the program this launch starts after tethered has checked it (next item), and so start any program (measured on Linux with Python 3.13 and 3.14). - Change a launch after tethered has checked it. An audit hook is handed the objects a launch is made with and cannot replace them. An audit hook added after tethered's runs after it at the same event, and another thread can run between the event and the launch. Either can change the environment
dictasubprocess.Popenlaunch was given, its argument list on POSIX, or the local variables ofsubprocess.Popen._execute_childthat hold them, which is how tethered itself completes an environment. A Python child then starts without the policy, or another program starts under"block". Measured on Windows with Python 3.14: a hook added after the lock removed_TETHERED_CHILD_POLICYfrom an environment tethered had accepted, and the child started without a policy. A launch that inherits the process environment is open to this as well: the interpreter that holds the lock is not refused removing the variable from the process, and tethered refuses the next launch that would inherit, not the one under way. Measured under a locked"block"policy on Linux with Python 3.11 and 3.14: a hook added after the lock removed the variable from the process (os.unsetenv) at thesubprocess.Popenevent of an inheriting launch, that child started without a policy, and the launch after it was refused. Nor does a Python child need a change after the check to start without the policy: its environment is not inspected beyond that variable (see Child processes). - Launch through a copy of
subprocess's own code. tethered judges asubprocesslaunch at itssubprocess.Popenevent and lets the lower-level event that follows (_posixsubprocess.fork_exec,os.posix_spawn,_winapi.CreateProcess) through as part of that launch. It knows where that event comes from by the name of the function, itsenvvariable and the module its globals belong to, and a copy ofsubprocess.Popen._execute_childhas all three: made with globals in whichsys.auditdoes nothing, the copy raises nosubprocess.Popenevent, and the launch it makes is never judged. Measured under a locked"block"policy, on Linux with Python 3.11 to 3.15 and on Windows with Python 3.14: a direct launch of a program was refused, and the copy started it. On POSIX before Python 3.14 the lower-level call raises no event at all (see Child processes). - Start an interpreter that never finishes starting. A join is accepted until the interpreter's
import sitecustomizeevent, and an interpreter that starts withoutsitenever raises it. tethered accepts no join in a process that was started with-S. But code that switchessiteoff for new interpreters after the policy is locked, by rewriting the interpreter configuration, gets an interpreter in which code that runs later can still join, with objects of its own making, and is then not restricted. CPython's internal test modules (_testinternalcapi,_testcapi) offer Python code that kind of access, and native code has it anyway. These modules are not a rarity: most of the installations surveyed ship them, the official Docker images included (see CPython's internal test modules). - Recover the token. Any reference the application keeps (a module global, an attribute, a live frame local) can be found by code in the same process. Only a token nobody keeps, such as
lock_token=object()passed inline, cannot be recovered; such a policy can then never be unlocked.
Other limits:
- With the default
fail_closed=False, a policy check that raises allows the connection, so making a standard-library function raise during matching lets the connection through. Setfail_closed=Truetogether withlocked=True. - A process launch on another thread during an authorized replacement of a locked policy can be refused spuriously.
- A locked policy survives whatever re-executes the process. The new process image inherits the policy from its environment and has it in place before the application is imported, and it cannot be replaced without the token, which did not survive. A uWSGI reload, gunicorn's binary upgrade (
SIGUSR2) under--preloadand Django's autoreloader are such re-executions: an application that then asks for a different locked policy getsTetheredLocked, and what the server does with that differs (uWSGI answers every request with a 500, gunicorn's new master does not start,runserverexits). The same policy asked for again is a no-op. To change a locked policy, stop the server and start it; see the cookbook.
The bootstrap file¶
Locked mode refuses the Python-level operations that would remove tethered.pth, change it or give it a further name, and it refuses creating a tethered.start beside it, which from Python 3.15 makes site.py ignore the import line of tethered.pth (PEP 829). The subprocess page lists the operations and how the file is recognised.
What gets past that guard is met by a check of the content. A tethered.pth counts as the bootstrap only while it holds the line tethered installs and, from Python 3.15, has no tethered.start beside it. activate() checks that, and both are checked again at every launch of a Python child that would inherit. Once the bootstrap file has been emptied, removed, replaced or switched off, a locked policy refuses such a launch, whatever external_subprocess_policy says: the lock promises that no Python child of this interpreter starts without the policy, and nothing can put the file back from inside. Without a lock the launch is an external one, warned about or, under "block", refused. The check answers for the routes the guard does not see (listed below), for an installer that is run from outside the process, and for another distribution that ships a file of the same name.
The limits of both:
- The guard knows the file by its name: in its own directory, however the directory is named in the call (through a symlink or a junction, by a Windows short name, relative to a directory descriptor), and as the same file in another directory, which is what an installation by uv leaves in uv's cache. Not matched: a name of another spelling that existed before the policy was locked; on Linux
/proc/self/fd/Nof a descriptor that was opened for reading, which names the file without a link being made;os.open(..., dir_fd=...), whose audit event does not carry the descriptor;os.ftruncate, which carries only a descriptor (theopenthat would yield a writable one is refused); and anything on a file system that reports no file index (there only the text of the path counts). The/procanddir_fdroutes were measured on Linux with Python 3.11 to 3.15: each emptied the bootstrap file under a locked, fail-closed policy, and the next launch of a Python child was then refused by the check of the content, under the defaultexternal_subprocess_policyas well. os.mknod(POSIX) raises no audit event, so creating atethered.startthat way is not refused. Atethered.startmade so, or there before the policy, is found by the check of the content:activate()warns, and the launch of a Python child is refused under a lock and external without one.- The check of the content says that the file is tethered's, not that nothing else runs at startup: a
tethered.pththat holds tethered's line is the bootstrap whatever other.pthfiles lie beside it (see "Write startup files" above). It is made only at the launches tethered sees. Without a lock, under the defaultexternal_subprocess_policy="warn", a Python child of a process whose bootstrap file has been lost is still started, without a policy; the warning is all there is. - The refusal under a lock has a price: when tethered is removed from the environment of a running locked process, or upgraded to a version whose bootstrap file differs, that process launches no Python child until it is restarted.
- The guard refuses a package installer like any other code.
pip uninstall tethered, or an upgrade, run from a Python child of a locked process stops halfway and leaves the installation without its metadata; see the compatibility page. Install, upgrade and remove tethered from outside the processes that hold a locked policy.
Interpreters under a lock¶
The lock is held once per process, by the interpreter that activated it (the lock holder), and only the holder has the token. For the other interpreters of the process:
- Joining. An interpreter created while the lock is held joins it during its own startup, through the same
tethered.pthbootstrap that child processes use. The bootstrap runs whentethered.pthis in a site directory the interpreter processes and_TETHERED_CHILD_POLICYis in the environment of the process. A joined interpreter gets a locked copy of the holder's policy, taken from the C extension's own record of that policy and not from the variable, and a snapshot of its own copy of tethered's code. Its events are checked like the holder's: it reaches what the policy allows and is refused the rest by its own policy, with the ordinaryEgressBlocked("not in the allow list"). Tampering inside it is detected there and refuses that interpreter everything guarded, with an alert line of its own; the holder and the other interpreters are not affected. It holds no token, so it cannot deactivate, replace or weaken the policy (TetheredLocked), and it is refused everyos.putenv/os.unsetenvof_TETHERED_CHILD_POLICY, which is also what assigning to or deleting fromos.environdoes (SubprocessBlocked). A worker ofconcurrent.futures.InterpreterPoolExecutorthat is created under the lock joins it like any other interpreter. - When a join is accepted. The extension cannot tell tethered's own objects from stand-ins that code in an interpreter has prepared, so it goes by time: a join is accepted only while the interpreter starts, and only once. Startup is over when the extension sees that interpreter's
import sitecustomizeaudit event, whichsite.pyraises right after it has processed the.pthfiles, before any application code runs there. Code that is already running in an interpreter cannot join. This makes a joined interpreter as well protected as a locked child process, and no better: its startup files are trusted (see "Write startup files" above), and the limits listed above apply in every interpreter. -
Outside the lock. While the lock is held, the C extension refuses an interpreter that has not joined it every connection, datagram and lookup made through Python's
socketmodule, without consulting the allow list: loopback and allowed hosts included, and on Windows the connection with whichsocket.socketpair()joins its sockets, so no asyncio event loop can be created there. It also refuses every process launch, and any change totethered.pth/tethered.startor to_TETHERED_CHILD_POLICY. Such an interpreter can still be created and can compute. The extension does not refuse its imports: unless it holds a policy of its own, it can load uvloop, and a connection made on a uvloop event loop, or by any library that connects in C, raises no event and is not refused (the uvloop case was measured, under mod_wsgi). Outside the lock are:- an interpreter that existed before the lock was taken, which includes the main interpreter when a subinterpreter takes the lock, and an interpreter that was still starting while the first lock of the process was being taken;
- one that started without the bootstrap running, because no
tethered.pthis in a site directory it processes (an editable or--targetinstall) or the variable was no longer in the environment of the process (the holder is not refused removing it; launches that would inherit the environment are then refused); - one whose join failed, which logs one warning and starts: a
tethered.pththat is processed only after startup, throughsite.addsitedir(), ends this way, and so does one processed after a startup file has importedsitecustomize, which ends the startup window early; - every other interpreter of a process that runs without
site(-S), where the end of startup cannot be recognised and no join is accepted; - one that joined a policy that has since been replaced or released (next item).
The exception raised there is that interpreter's own
EgressBlocked/SubprocessBlockedwhen tethered is loaded in it, andRuntimeErrorotherwise. The C extension makes these refusals and logs nothing for them.activate()anddeactivate()raiseTetheredLockedin an interpreter that has no locked policy of its own, also when the policy asked for is identical to the locked one; the message says that the interpreter is outside the lock and that no token will help.A locked
log_onlypolicy refuses such an interpreter no connection or lookup, as it refuses the holder none; launches, the bootstrap files and the variable stay refused. Its connections and lookups are then decided by a policy of its own, if it holds one (a copy it joined earlier, or an unlocked policy). One that holds none, for example because the variable was removed from the environment before it was created, is neither refused nor reported. Its socket events keep passing while the holder is being refused after a failed integrity check. -
When the lock changes. When the holder replaces the locked policy with a different one, the interpreters that had joined are outside the lock from then on, and stay there: there is no joining twice. Interpreters created afterwards join the new policy. Replacing the policy with an identical one (the same rules, in any order, and the same settings) keeps them joined. When the lock is released, the extension enforces nothing in any interpreter; a formerly joined interpreter keeps enforcing its copy of the policy from Python and may now deactivate it, and it is outside any lock taken later. If the interpreter that holds the lock is destroyed, the process stays locked for good: joined interpreters keep working, new ones still join, nothing can replace or release the lock, and no interpreter, one created afterwards included, is treated as its holder. Under an unlocked policy nothing of this applies: a subinterpreter gets its own unlocked instance.
- When an interpreter starts. What counts is the moment an interpreter starts, and the application does not always choose that moment.
concurrent.futures.InterpreterPoolExecutorstarts its workers on demand: an executor object created before the lock joins if its first task is submitted afterwards, and a pool with one worker started before the lock and one after has both kinds, so that tasks of one request can end differently. mod_wsgi creates the interpreter of an application group at that group's first request: when two application groups of one process get their first requests at the same moment, the interpreter of the second already exists when the first takes the lock, and that application is outside the lock, with no network through Python's sockets, for as long as the lock is held. A lock covers the process, not the application that took it: an interpreter that runs other code, such as a second mod_wsgi application group that never imports tethered, joins when it is created under the lock and is restricted by that policy, and gets no network through Python's sockets when it existed before. Take the lock before creating interpreters (see early activation); the cookbook has the configurations for servers and pools.
CPython's internal test modules¶
The route listed above as "Start an interpreter that never finishes starting" needs a way to rewrite the interpreter configuration from Python code, and CPython's own test suite brings extension modules that reach it: _testinternalcapi and _testcapi. They are not confined to development installations. A survey of Linux x86-64 images in October 2026 found them importable in:
- the official
python:3.X,python:3.X-slimandpython:3.X-alpineDocker images (3.11 to 3.15); - Debian and Ubuntu with the
python3package (the modules belong tolibpython3.X-stdlib), and Alpine with itspython3package; gcr.io/distroless/python3-debian12and-debian13,cgr.dev/chainguard/python,public.ecr.aws/lambda/python:3.13andcondaforge/miniforge3;- Pythons installed by uv (
uv python install), where_testinternalcapiis compiled into the interpreter and_testcapiis absent.
They were absent from Debian and Ubuntu with only python3-minimal, which has no ctypes either, and from Fedora's python3, Amazon Linux 2023's python3.13 and UBI 9's python3.12 as long as the matching -test package is not installed; those three do have ctypes.
What can be done about it: where the modules are files, remove them from the image. In the official images, deleting _testinternalcapi*.so and _testcapi*.so from the interpreter's lib-dynload directory left tethered's locked mode working (checked on Python 3.13 and 3.14). In a uv-managed Python there is no file to delete. Two cautions. The survey established where the modules can be imported, not that each of them defeats locked mode in each image; what they offer differs between Python versions. And removing them closes this one route: ctypes and other native code remain, as do the other items in the list above.
Known residual DNS divergence¶
Tethered's audit-time getaddrinfo and CPython's own getaddrinfo are independent DNS queries, made one right after the other (tethered's first, inside the audit hook). For a name whose answers differ from one query to the next, as with load balancers that hand out a different subset of their addresses each time (Microsoft Entra ID, M365, large CDNs), the two queries can return different IP sets wherever no cache answers both — leaving the connect-time IP unmapped and producing a spurious block. To repair this, tethered re-resolves recently-allowed hostnames at connect-time when the IP map misses (_fallback_resolve, bounded to 30 candidates per miss). The same search matches an address obtained through socket.gethostbyname / gethostbyname_ex back to its name: those lookups record a candidate but no mapping. A name becomes a candidate only when its lookup was let through by the global policy and by every enforcing scope that saw it, so tethered does not itself resolve a name a layer has just refused. The search is skipped when every layer already allows the raw IP (loopback, an IP or CIDR rule). It also runs under a lock.
The fallback's lookup is a third independent query, and where the answers differ from query to query it misses as often as tethered's first one did. Measured with the DNS benchmark, for a name each of whose answers is 2 addresses drawn at random from 8, under activate(allow=[name], allow_localhost=False), 1,000 connections per row:
| Between the process and the upstream | TTL | First connections of a process refused | Refused in one process |
|---|---|---|---|
| Nothing (glibc asks the upstream) | 0 s | 54.5% | 1, the first connection |
| Nothing | 30 s | 55.5% | not measured |
| Nothing, through gevent's default resolver | 0 s | 55.6% | not measured |
| systemd-resolved | 0 s | 54.9% | 3, all among the first 4 |
| systemd-resolved | 30 s | 0% | not measured |
| dnsmasq | 0 s | 55.6% | 1, the second connection |
| dnsmasq | 30 s | 0% | not measured |
Measured with tethered 1.0.1 on Python 3.14.8 (glibc 2.41), systemd-resolved 257.13, dnsmasq 2.91 and gevent 26.9.0, in two runs; the table is the second, and no share in the first differed from it by more than 3 points. A first connection is one made with an empty IP map (deactivate() and activate() before each). What this shows:
- How often a first connection is refused follows from the answers. When each answer holds k of a pool of P addresses, tethered's own answer lacks the address the application connects to with probability 1 − k/P, and the fallback's answer lacks it again with the same probability: about (1 − k/P)² of first connections are refused, 56% for 2 of 8. A name whose every answer holds the whole pool, in whatever order, does not diverge: the IP map records every address of tethered's answer.
- Without a cache the TTL makes no difference: glibc asks the upstream every time. A caching stub (systemd-resolved, dnsmasq) gives both lookups the answer it holds for as long as the TTL lasts, and nothing was refused with a TTL of 30 s; an answer with a TTL of 0 it does not keep, and the rate was that of no cache.
- gevent's default resolver makes no difference: tethered's lookup and gevent's run one right after the other in the same thread of its pool.
- In a process that keeps running, the refusals stop once tethered has seen the pool: the IP map keeps every address its own lookups returned, up to 4,096. With a pool of 8, every refusal came within the first 4 connections. With 2 addresses drawn from 256, 79 of 1,000 connections in one process were refused, the last of them the 388th.
- The search has a cost: one lookup per name searched, which without a cache is an upstream round trip, and under gevent holds up every greenlet for as long (measured).
Mitigation: allow the upstream's published IP/CIDR ranges (a connect to an address that an IP rule allows is never refused for want of a name, and never searched for); put a caching stub between the process and the upstream, which removes the divergence for every TTL above 0; for a name with a TTL of 0, look it up several times at startup, which records more of its pool; or accept the residual rate as a defense-in-depth trade-off.
Design trade-offs¶
- Fail-open by default. If tethered's matching logic raises an unexpected exception, the connection is allowed and a warning is logged. A bug in tethered should not break your application. Use
fail_closed=Truefor stricter environments. The child-process bootstrap follows the same rule: when the inherited policy haslockedorfail_closedset and cannot be established in a child, the child refuses to start; otherwise a warning is logged and the child continues without it. An interpreter created inside a locked process is treated differently in one respect: if it cannot join the lock it starts all the same, with a warning, and stays outside the lock, where an enforcing policy leaves it no network. See the subprocess page. - A refusal is a
RuntimeError, and the code in between decides what the caller sees.EgressBlockedis deliberately not anOSError, so that retry logic written for network errors does not retry it. The other side of that: code that expects only network errors at that point does not always pass it on. Measured: Twisted reports a refused connection as its ownTimeoutErrorwhen the attempt's timeout is over, and never completes a request whose lookup was refused; pymongo raisesServerSelectionTimeoutErrorwith the refusal only in its text; kafka-python and nats-py raise an error that does not mention tethered; anyio and trio deliver a refused connection inside anExceptionGroup. In each of these nothing forbidden was reached, and tethered's own warning is in the log. The compatibility page lists what each library does. external_subprocess_policy="block"refuses what libraries launch, too. A refused launch raisesSubprocessBlocked, which code that expectsOSErrordoes not catch, and the standard library launches programs of its own: theplatformmodule, andctypes.util.find_library()for a library that is not in the linker cache. The subprocess page says which calls are refused and what tethered does about the others.- Audit hooks are irremovable.
sys.addaudithookhas no remove function (by design — PEP 578).deactivate()makes the hook a no-op but cannot unregister it. This is per-process only — no persistent state, no system changes, everything is gone when the process exits. - An earlier audit hook can refuse tethered's.
sys.addaudithooksilently drops a new hook when a hook already in the process raises on thesys.addaudithookevent. tethered confirms that its hooks are live, with the private audit eventstethered.hook_probeand, in locked mode,tethered._guardian.probe(other audit hooks see them), andactivate()and entering ascope()raiseRuntimeErrorinstead of running unenforced. In a child process this follows the bootstrap rule above: withlockedorfail_closedthe child refuses to start, otherwise it logs a warning and runs without the policy. - IP-to-hostname mapping is bounded. The LRU cache holds up to 4096 addresses, keyed by canonical address, with up to 8 hostnames per address (most recent first). In long-running processes with many unique DNS lookups, older mappings are evicted. A connection to an evicted address is matched to a name only if the fallback search finds it among the current addresses of the 30 most recently allowed names (Known residual DNS divergence); otherwise only IP and CIDR rules apply.
- A direct IP connection is matched to a hostname only through tethered's own lookups. A connection to a raw IP that no lookup has tied to a name goes through the same fallback search: if a fresh lookup of one of the 30 most recently allowed names returns the address, that name's rules apply; otherwise only IP and CIDR rules do, and hostname wildcards won't match. On shared-IP infrastructure (CDNs, cloud hosting), multiple hostnames may resolve to the same IP. A connection is allowed if any hostname remembered for the address, or the raw IP, is allowed, so two allowed names on one address do not block each other. The other side of that: if an allowed hostname shares an IP with a disallowed one, a raw-IP connection to that address passes hostname policy, through the cached mapping or the fallback search. This is inherent to any system that cannot bind a socket to a specific hostname identity.
- Wildcards match text, not address ranges. An address-shaped wildcard such as
10.*or192.0.2.*is anfnmatchpattern over the host string: it matches the addresses it looks like and also every hostname that fits the pattern, such as10.attacker.example, and through the IP map whatever address that name resolves to. tethered logs a warning for such a rule (once per rule per process). Use CIDR notation (10.0.0.0/8) for ranges. - Localhost allows local relays. With the default
allow_localhost=True, any proxy, tunnel, or forwarding agent listening on127.0.0.1or::1can relay traffic to external destinations, bypassing the intent of the egress policy. In high-security environments where local relays are a concern, setallow_localhost=Falseand explicitly allow only the loopback addresses and ports your application needs. The loopback connection with whichsocket.socketpair()joins its own two sockets on Windows, which creating an asyncio event loop makes, needs no rule: it is let through (see What tethered protects against).
Supply chain defense — early activation¶
tethered is most effective when activated before importing untrusted or third-party packages. Any code that runs before activate() executes in an unprotected window — a compromised dependency could make network calls during its import-time initialization.
# ✅ Correct: activate before importing third-party code
import tethered
tethered.activate(allow=["*.stripe.com:443", "db.internal:5432"])
import stripe # its import-time connections are checked
import compromised_pkg # connections outside the allow list are refused
# ❌ Wrong: third-party code runs before tethered is active
import stripe
import compromised_pkg # could phone home during import!
import tethered
tethered.activate(allow=["*.stripe.com:443"]) # too late
For maximum protection, combine early activation with locked=True (every Python child starts under the same locked policy, with a token of its own, and a launch environment that carries another policy is refused), fail_closed=True (so that an error inside the policy check blocks instead of allowing) and, if your workload doesn't legitimately launch external programs, external_subprocess_policy="block" to refuse every external launch. Python children of the same interpreter still start under "block"; they inherit the policy instead.
The same order matters for subinterpreters. Take the lock before creating them, concurrent.futures.InterpreterPoolExecutor workers included: an interpreter created under the lock joins it and enforces the policy, while one that already exists when the lock is taken stays outside it and, unless the policy is log_only, gets no network through Python's sockets for as long as the lock is held. For a pool that means before its first task is submitted, since that is when a worker interpreter starts. Install tethered into site-packages (a regular install, not editable and not --target), because the join is made by the tethered.pth bootstrap. See Interpreters under a lock, and the cookbook for servers that create interpreters themselves (mod_wsgi).
On asyncio, early activation does one more thing: it keeps uvloop out of the process, so that a server which would otherwise pick it runs on the standard event loop, where the policy is enforced. An activate() that comes after uvloop was loaded is refused (RuntimeError), and the server does not start. Which of the two a deployment meets depends on the server and on how it is started, so name the loop where the server lets you, or activate in a launcher script before the server is imported (the cookbook). The same order matters for multiprocessing's fork server and for process pools: start them after activate() (see Child processes).
Recommendations¶
For defense-in-depth, combine tethered with:
- An egress proxy or a network policy that names the allowed hosts, for the traffic that does not go through Python's sockets.
- OS-level sandboxing (containers, seccomp-bpf, network namespaces) for hard isolation.
- Subprocess restrictions (
external_subprocess_policy="block"for hardened environments, plus seccomp filters for non-Python binaries). - Import restrictions to prevent
ctypes/cffiloading in untrusted code paths. On Python 3.11 and 3.12 tethered itself importsctypeswhen it has to write the environment of asubprocesslaunch (an explicitenv=without the policy, an active scope); where that import is refused, the launch is treated as external, or refused under a lock. - The standard asyncio event loop for asyncio applications, named in the server's configuration (
uvicorn --loop asyncio), and no uvloop in the environment where nothing needs it. - Client libraries that go through Python's
socketmodule: a pure-Python database driver in place of one that links a C client library, the system resolver in place of c-ares or a DNS client of the library's own. The compatibility page says which is which. For a library that connects in C, only a control below Python applies. - Images without CPython's internal test modules, where they are separate files (see CPython's internal test modules).
Report a vulnerability¶
Report a vulnerability privately through GitHub's private vulnerability reporting, not in a public issue. Confirmed vulnerabilities are addressed in a patch release.