DEV Community

Cover image for .pth files run every time Python starts. Check yours after the agent-framework compromise
Redlio Labs
Redlio Labs

Posted on Fully Autonomous

.pth files run every time Python starts. Check yours after the agent-framework compromise

On November 17, two malicious releases of agent-framework, the meta-package for Microsoft's Agent Framework, went up on PyPI 33 minutes apart. Both are now quarantined. According to The Hacker News, the package gets about 190,000 downloads a month, and the reports from Socket, Endor Labs, Wiz and others agree on the important part: the payload didn't wait for anyone to import the package.

It dropped a .pth file into site-packages. Python reads those files every time it starts, and runs any line that begins with import. Endor Labs pointed out that this includes running pip itself. Install the package once, and every Python process on that machine or CI runner runs the attacker's code from then on.

Installed once, runs every time Python starts: pip install drops a .pth file, site.py runs its import lines at every start, every process is affected, audit with -S

The payload collected environment variables and credential files (.npmrc, .git-credentials, .docker/config.json, Azure CLI tokens), and asked the cloud for fresh tokens through instance metadata and the GitHub Actions OIDC endpoint. If you installed 1.26.1 or 1.26.2, follow the incident guidance first: isolate the host, rotate credentials from a clean machine, and pin to 1.26.0.

This post is about the general problem. .pth startup hooks are a legitimate Python feature, they're easy to forget about, and most teams have never looked at theirs.

What a .pth file is

A .pth file in a site-packages folder does two things when Python starts:

  • A line with a path adds that path to sys.path. That's how editable installs used to work.
  • A line starting with import (and a space or tab) is executed, as is the rest of that line.

Some packages use the second form for good reasons. setuptools ships distutils-precedence.pth, and coverage tools use one to measure subprocesses. That's exactly why a malicious one blends in.

List the ones that run code

This script finds every .pth file that executes something, shows the line it runs, and tells you which installed package claims the file:

"""pth_audit.py: list .pth files that run code every time Python starts.

Usage: python -S pth_audit.py   (-S stops the hooks running while you look)
Run it with each interpreter or virtualenv you care about.
"""
import site
import sys
from importlib import metadata
from pathlib import Path

# Under -S, Python hasn't switched to the virtualenv's prefix yet, so find it.
venv = Path(sys.executable).parent.parent
prefixes = [venv] if (venv / "pyvenv.cfg").exists() else None
dirs = list(site.getsitepackages(prefixes))
if site.ENABLE_USER_SITE:
    dirs.append(site.getusersitepackages())

# Which installed distribution shipped each file (from its RECORD).
owners = {}
for dist in metadata.distributions(path=dirs):
    for f in dist.files or []:
        if f.suffix == ".pth":
            owners[Path(dist.locate_file(f)).resolve()] = (
                f"{dist.metadata['Name']} {dist.version}"
            )

found = 0
for d in dict.fromkeys(dirs):
    for pth in sorted(Path(d).glob("*.pth")):
        lines = pth.read_text(errors="replace").splitlines()
        # site.py executes any line that starts with "import" plus a space or tab.
        code = [l for l in lines if l.startswith(("import ", "import\t"))]
        if not code:
            continue
        found += 1
        owner = owners.get(pth.resolve(), "NOT OWNED BY ANY INSTALLED PACKAGE")
        print(f"{pth}\n  owner: {owner}")
        for line in code:
            print(f"  runs:  {line[:120]}")

print(f"\n{found} .pth file(s) run code at startup ({sys.executable})")
Enter fullscreen mode Exit fullscreen mode

Run it with -S. That flag tells Python not to process site-packages at startup, so the hooks you're inspecting don't run while you inspect them:

python -S pth_audit.py
.venv/bin/python -S pth_audit.py
Enter fullscreen mode Exit fullscreen mode

Here is the output for a test virtualenv where I added a fake hook next to the real setuptools one:

/tmp/project/.venv/lib/python3.13/site-packages/af_runtime_diag.pth
  owner: NOT OWNED BY ANY INSTALLED PACKAGE
  runs:  import os, base64; exec(base64.b64decode("cHJpbnQoMSk="))
/tmp/project/.venv/lib/python3.13/site-packages/distutils-precedence.pth
  owner: setuptools 84.2.1
  runs:  import os; var = 'SETUPTOOLS_USE_DISTUTILS'; enabled = os.environ.get(var, 'local') == 'local'; enabled and __import__('

2 .pth file(s) run code at startup (/tmp/project/.venv/bin/python)
Enter fullscreen mode Exit fullscreen mode

The fake hook only prints 1. Without -S, it printed that 1 every time I ran pip or python, including the audit itself.

Reading the result

"Not owned by any installed package" is the line to worry about. Every file pip installs is listed in that package's RECORD. A hook nobody owns was written by something other than pip.

An owner doesn't make it safe. In the real attack the malicious .pth came inside the package, so it would show up as owned by agent-framework 1.26.1. The question to ask is whether that package has any reason to run code at startup. A meta-package for an agent framework doesn't.

exec, base64, zlib, urllib or a network call in a .pth line deserves a closer look whatever the owner says.

Make it part of the build

On CI, the risk is short-lived but sharp: the runner holds your deploy credentials for the length of the job. Three habits help:

  1. Pin exact versions with hashes (pip install --require-hashes -r requirements.txt, or a lockfile from uv or Poetry). A release published 30 minutes ago can't reach a build that only installs what you've already locked.
  2. Give jobs short-lived, narrow credentials. OIDC tokens scoped to one environment limit what a stolen token can do, and they expire.
  3. Run the audit after install and fail if a .pth appears that isn't on your allowlist. It takes under a second.

None of this would have made the November 17 releases harmless. But it turns "every Python process on every runner, until someone notices" into "one build that failed for a reason we can see."


I'm Mayursinh, founder of Redlio Labs. We build custom software and add AI features and agents to it for mid-size companies. The script was tested with Python 3.13 in a virtualenv.

Top comments (0)