pthguard-lite 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,140 @@
1
+ Metadata-Version: 2.4
2
+ Name: pthguard-lite
3
+ Version: 0.1.0
4
+ Summary: Scan Python site-packages for malicious .pth files and startup backdoors.
5
+ Author: Alessio Auretto
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/alessio1999xx-debug/pthguard-lite
8
+ Project-URL: Repository, https://github.com/alessio1999xx-debug/pthguard-lite
9
+ Project-URL: Pro version, https://py-forge.com/products/pthguard-python-backdoor-scanner?utm_source=pypi&utm_medium=project_page&utm_campaign=pthguard-lite
10
+ Keywords: python-security,supply-chain-security,malware-detection,backdoor-detection,site-packages,pth,pypi,security-scanner,devsecops,cli,stdlib
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Security
22
+ Classifier: Topic :: Utilities
23
+ Requires-Python: >=3.9
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Dynamic: license-file
27
+
28
+ # pthguard-lite: find malicious .pth files in Python site-packages
29
+
30
+ Python runs every line that starts with `import` in a .pth file inside site-packages each time the interpreter starts, which makes these files a quiet place for a supply-chain backdoor. pthguard-lite helps you list the .pth files in an environment and flag the lines that execute code, using only the standard library.
31
+
32
+ - One file, Python 3.9+. Nothing to `pip install`.
33
+ - Safe to invoke as `python -I -S` so your own site customizations stay off.
34
+ - Plain text report; exit code `1` when a HIGH or CRITICAL finding appears.
35
+
36
+ Need RECORD hash checks, a known-bad package list, or a JSON report? That is the full [PthGuard](https://py-forge.com/products/pthguard-python-backdoor-scanner?utm_source=github&utm_medium=readme&utm_campaign=pthguard-lite) (one-time payment, yours to keep, no subscription). A table later in this README lists what lite does and what the paid tool adds. Or get every PyForge tool, current and future, with the [All-Access Pass](https://py-forge.com/pass?utm_source=github&utm_medium=readme&utm_campaign=pthguard-lite) ($99, one payment).
37
+
38
+ ## Install
39
+
40
+ ```bash
41
+ curl -fsSLO https://raw.githubusercontent.com/alessio1999xx-debug/pthguard-lite/main/pthguard_lite.py
42
+ chmod +x pthguard_lite.py
43
+ python -I -S pthguard_lite.py --help
44
+ ```
45
+
46
+ ## What a malicious .pth file looks like
47
+
48
+ Most `.pth` lines are plain path entries. Only lines that start with `import` (or `import` + a tab) are executed by Python's `site` module. A dangerous line looks like this harmless demo — do not put this in a real environment:
49
+
50
+ ```text
51
+ # path entry (not executed)
52
+ /opt/extra/libs
53
+ # executed at every interpreter start:
54
+ import os; os.system("echo demo-only")
55
+ ```
56
+
57
+ pthguard-lite opens `.pth` files as text, skips known-benign virtualenv/setuptools hooks, and flags lines that use patterns such as `exec`, `eval`, `base64`, `subprocess`, `os.system`, `__import__` or a network call. It also checks `sitecustomize.py` and `usercustomize.py` for the same class of startup persistence. It never imports or runs code from the target tree.
58
+
59
+ ## Scan site-packages for backdoors locally and in CI
60
+
61
+ ```bash
62
+ # one venv / site-packages tree
63
+ python -I -S pthguard_lite.py /path/to/venv/lib/python3.12/site-packages
64
+
65
+ # or a single .pth / sitecustomize.py file
66
+ python -I -S pthguard_lite.py ./suspicious.pth
67
+ ```
68
+
69
+ Example output, recorded 25 Nov 2026 (Europe/Rome) on a throwaway `site-packages` tree with one planted `.pth` line (it only prints `hb`; do not use this in a real environment). Exit code `1`.
70
+
71
+ ```text
72
+ ================================================================================
73
+ PTHGUARD-LITE SCAN REPORT
74
+ ================================================================================
75
+ Target : ./site-packages
76
+ .pth Files Inspected : 2
77
+ Customize Hooks Found : 0
78
+ Findings : 1
79
+ Critical/High Threats : 1
80
+ --------------------------------------------------------------------------------
81
+ Findings (1 total):
82
+
83
+ 1. [CRITICAL] Category : MALICIOUS_PTH_HOOK
84
+ Path : /tmp/demo-pth/site-packages/evil.pth
85
+ Details : Dangerous payload line 1: Executable 'exec()' call found
86
+ line_number: 1
87
+ line_sample: import os, base64; exec(base64.b64decode("cHJpbnQoImhiIik="))
88
+ ================================================================================
89
+ ```
90
+
91
+ Minimal GitHub Actions step (fails the job when HIGH/CRITICAL findings appear):
92
+
93
+ ```yaml
94
+ - name: Scan site-packages with pthguard-lite
95
+ run: >
96
+ python -I -S pthguard_lite.py
97
+ "$(python -c 'import site; print(site.getsitepackages()[0])')"
98
+ ```
99
+
100
+ | Finding | What it means |
101
+ |---|---|
102
+ | `MALICIOUS_PTH_HOOK` | An executable `.pth` line matches a high-risk pattern |
103
+ | `EXECUTABLE_PTH_LINE` | An `import …` line runs at startup but is not a known-benign hook — review it |
104
+ | `SUSPICIOUS_CUSTOMIZE_HOOK` | `sitecustomize.py` / `usercustomize.py` looks like credential harvest, decode, subprocess or sockets |
105
+
106
+ ## pthguard-lite vs PthGuard
107
+
108
+ pthguard-lite checks **one** path for risky startup hooks and prints a text report. It does not verify package integrity or scan a whole fleet.
109
+
110
+ | Capability | Lite (free) | Paid PthGuard |
111
+ | --- | --- | --- |
112
+ | Scan target | One site-packages, venv, or file | Several directories / venvs / conda prefixes in one run |
113
+ | Flag `exec()`, base64 decoding and subprocess calls in `.pth`, `sitecustomize.py` and `usercustomize.py` | Yes | Yes |
114
+ | Check installed files against SHA-256 hashes in `RECORD` | No | Yes (also lists unrecorded files; `--skip-records` to turn this off) |
115
+ | Known-bad package list | No | Yes (built-in, extensible with `--known-bad-json`) |
116
+ | Output | Plain text | Text or JSON (`--format`) |
117
+ | `--strict` CI exit and a quarantine script you review before running | No | Yes (`--strict`, `--quarantine-script`) |
118
+
119
+ One-time payment, yours to keep. No subscription. Full tool: [PthGuard](https://py-forge.com/products/pthguard-python-backdoor-scanner?utm_source=github&utm_medium=readme&utm_campaign=pthguard-lite). Or get every PyForge tool, current and future, with the [All-Access Pass](https://py-forge.com/pass?utm_source=github&utm_medium=readme&utm_campaign=pthguard-lite) ($99, one payment).
120
+
121
+ ## Tests
122
+
123
+ ```bash
124
+ python3 test_pthguard_lite.py
125
+ ```
126
+
127
+ ## More free tools from the same author
128
+
129
+ - [agentconfig-audit-lite](https://github.com/alessio1999xx-debug/agentconfig-audit-lite) — Audit MCP config for secrets: plaintext tokens and unpinned npx/uvx servers in `.mcp.json` and `CLAUDE.md`.
130
+ - [agenttrail-scrub-lite](https://github.com/alessio1999xx-debug/agenttrail-scrub-lite) — Claude Code secret scanner: find API keys and tokens leaked in AI agent transcripts.
131
+ - [cronpulse-lite](https://github.com/alessio1999xx-debug/cronpulse-lite) — Cron job monitoring in one Python file: alerts to Slack/Discord/webhook on failure or hang.
132
+ - [depcooldown-lite](https://github.com/alessio1999xx-debug/depcooldown-lite) — Dependency cooldown check: fail CI when a pinned PyPI or npm package is newer than N days.
133
+ - [homelab-doctor-lite](https://github.com/alessio1999xx-debug/homelab-doctor-lite) — Read-only homelab health check: stale images, exposed ports, expiring certs, silent cron, disk.
134
+ - [imagenudge-lite](https://github.com/alessio1999xx-debug/imagenudge-lite) — Docker image update checker: find running containers with a newer image (digest or tag).
135
+ - [pulseping-lite](https://github.com/alessio1999xx-debug/pulseping-lite) — Check SSL certificate expiry and URL/port uptime from cron.
136
+ - [secenv-lite](https://github.com/alessio1999xx-debug/secenv-lite) — Find `.env` files committed to git or missing from `.gitignore`, plus obvious API keys inside.
137
+
138
+ ## License
139
+
140
+ MIT (this lite version). The full PthGuard tool is sold separately under its own license.
@@ -0,0 +1,7 @@
1
+ pthguard_lite.py,sha256=kCpZnxCEIdEoJVfAp4nRqt1Hb9_E2FoGhcvnhbc3F1A,9884
2
+ pthguard_lite-0.1.0.dist-info/licenses/LICENSE,sha256=UogbiChOs5hJVxEarcfEGO-mtfsJmsPtvoSAB493trg,1082
3
+ pthguard_lite-0.1.0.dist-info/METADATA,sha256=frxn6wDQyJLHlaAeYeU918xJUfq0tV-e65QnhrikcTc,8161
4
+ pthguard_lite-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ pthguard_lite-0.1.0.dist-info/entry_points.txt,sha256=BT66CmQNqJF_xGnHzqyxWsXBrVeogbzqbXFLiJUFsqg,53
6
+ pthguard_lite-0.1.0.dist-info/top_level.txt,sha256=663I84jZOjwnXp22nh-YxagS4utc0Be9qz7PmuI0oTk,14
7
+ pthguard_lite-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ pthguard-lite = pthguard_lite:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alessio Auretto (PyForge)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ pthguard_lite
pthguard_lite.py ADDED
@@ -0,0 +1,244 @@
1
+ #!/usr/bin/env python3
2
+ """pthguard-lite: static scan of one Python site-packages/venv for .pth backdoors.
3
+
4
+ Single file, Python 3.9+ standard library only. Inspects files; never executes them.
5
+
6
+ python -I -S pthguard_lite.py /path/to/venv/lib/python3.12/site-packages
7
+ python -I -S pthguard_lite.py --help
8
+
9
+ Full version (RECORD hash checks, known-bad package list, multi-path / Docker
10
+ rootfs scans, JSON + CI exits, quarantine script):
11
+ https://py-forge.com/products/pthguard-python-backdoor-scanner?utm_source=github&utm_medium=code&utm_campaign=pthguard-lite
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import os
17
+ import pathlib
18
+ import re
19
+ import sys
20
+ from typing import Any, Dict, List, Optional, Tuple
21
+
22
+ __version__ = "0.1.0"
23
+
24
+ # site.py only runs .pth lines that start with "import " / "import\t"
25
+ PTH_DANGEROUS_PATTERNS = [
26
+ (re.compile(r"exec\s*\(", re.IGNORECASE), "Executable 'exec()' call found"),
27
+ (re.compile(r"eval\s*\(", re.IGNORECASE), "Dynamic 'eval()' call found"),
28
+ (re.compile(r"base64\.(?:b64decode|decode)", re.IGNORECASE), "Base64 payload decoding detected"),
29
+ (re.compile(r"subprocess\.", re.IGNORECASE), "Subprocess / command execution attempt"),
30
+ (re.compile(r"os\.system\s*\(", re.IGNORECASE), "Direct OS shell execution"),
31
+ (re.compile(r"__import__\s*\(", re.IGNORECASE), "Obfuscated __import__() call"),
32
+ (
33
+ re.compile(r"\b(?:urllib\.request|urllib2|requests|socket|http\.client)\b", re.IGNORECASE),
34
+ "Network / egress socket invocation",
35
+ ),
36
+ ]
37
+
38
+ # Common hooks written by virtualenv / setuptools / pip editable installs
39
+ BENIGN_PTH_LINES = [
40
+ re.compile(r"^import _virtualenv\s*$"),
41
+ re.compile(r"^import (__editable___[\w.]+_finder); \1\.install\([^()]*\)\s*$"),
42
+ re.compile(
43
+ r"^import os; var = 'SETUPTOOLS_USE_DISTUTILS'; enabled = os\.environ\.get\(var, '\w+'\) == '\w+'; "
44
+ r"enabled and __import__\('_distutils_hack'\)\.add_shim\(\); ?$"
45
+ ),
46
+ re.compile(
47
+ r"^import sys, types, os;has_mfs = sys\.version_info > \(3, 5\);p = os\.path\.join\(sys\._getframe\(1\)\.f_locals\['sitedir'\]"
48
+ ),
49
+ ]
50
+
51
+ CUSTOMIZE_SUSPICIOUS_PATTERNS = [
52
+ (re.compile(r"base64\.(?:b64decode|b85decode)", re.IGNORECASE), "Base64 decoding in startup hook"),
53
+ (
54
+ re.compile(r"subprocess\.(?:Popen|check_output|run|call)", re.IGNORECASE),
55
+ "Subprocess spawning on startup",
56
+ ),
57
+ (
58
+ re.compile(r"(?:OPENAI_API_KEY|AWS_SECRET_ACCESS_KEY|SSH_AUTH_SOCK|id_rsa)", re.IGNORECASE),
59
+ "Credential harvesting target reference",
60
+ ),
61
+ (re.compile(r"socket\.(?:socket|create_connection)", re.IGNORECASE), "Network connection on startup"),
62
+ ]
63
+
64
+
65
+ class LiteScanner:
66
+ """Scan one tree for risky .pth / sitecustomize / usercustomize hooks."""
67
+
68
+ def __init__(self, target: str) -> None:
69
+ self.target = target
70
+ self.findings: List[Dict[str, Any]] = []
71
+ self.pth_files = 0
72
+ self.customize_files = 0
73
+
74
+ def add_finding(
75
+ self,
76
+ severity: str,
77
+ category: str,
78
+ path: str,
79
+ description: str,
80
+ details: Optional[Dict[str, Any]] = None,
81
+ ) -> None:
82
+ self.findings.append(
83
+ {
84
+ "severity": severity,
85
+ "category": category,
86
+ "path": path,
87
+ "description": description,
88
+ "details": details or {},
89
+ }
90
+ )
91
+
92
+ def scan_pth_file(self, pth_path: pathlib.Path) -> None:
93
+ self.pth_files += 1
94
+ try:
95
+ content = pth_path.read_text(encoding="utf-8", errors="replace")
96
+ except (OSError, PermissionError) as exc:
97
+ self.add_finding("MEDIUM", "UNREADABLE_FILE", str(pth_path), f"Cannot read .pth file: {exc}")
98
+ return
99
+
100
+ for idx, line in enumerate(content.splitlines(), start=1):
101
+ stripped = line.rstrip()
102
+ if not (stripped.startswith("import ") or stripped.startswith("import\t")):
103
+ continue
104
+ if any(b.search(stripped) for b in BENIGN_PTH_LINES):
105
+ continue
106
+
107
+ reason = next((r for pattern, r in PTH_DANGEROUS_PATTERNS if pattern.search(line)), None)
108
+ if reason:
109
+ self.add_finding(
110
+ "CRITICAL",
111
+ "MALICIOUS_PTH_HOOK",
112
+ str(pth_path),
113
+ f"Dangerous payload line {idx}: {reason}",
114
+ {"line_number": idx, "line_sample": line[:150]},
115
+ )
116
+ else:
117
+ self.add_finding(
118
+ "MEDIUM",
119
+ "EXECUTABLE_PTH_LINE",
120
+ str(pth_path),
121
+ f"Line {idx} runs code at every Python startup (unrecognised hook, review it)",
122
+ {"line_number": idx, "line_sample": line[:150]},
123
+ )
124
+
125
+ def scan_customize_file(self, cust_path: pathlib.Path) -> None:
126
+ self.customize_files += 1
127
+ try:
128
+ content = cust_path.read_text(encoding="utf-8", errors="replace")
129
+ except (OSError, PermissionError) as exc:
130
+ self.add_finding("MEDIUM", "UNREADABLE_FILE", str(cust_path), f"Cannot read file: {exc}")
131
+ return
132
+
133
+ for pattern, reason in CUSTOMIZE_SUSPICIOUS_PATTERNS:
134
+ match = pattern.search(content)
135
+ if match:
136
+ self.add_finding(
137
+ "HIGH",
138
+ "SUSPICIOUS_CUSTOMIZE_HOOK",
139
+ str(cust_path),
140
+ f"Startup persistence risk: {reason}",
141
+ {"matched_token": match.group(0)},
142
+ )
143
+
144
+ def scan_path(self, root: pathlib.Path) -> None:
145
+ if not root.exists():
146
+ self.add_finding("LOW", "PATH_NOT_FOUND", str(root), "Specified scan target path does not exist")
147
+ return
148
+
149
+ if root.is_file():
150
+ if root.suffix == ".pth":
151
+ self.scan_pth_file(root)
152
+ elif root.name in ("sitecustomize.py", "usercustomize.py"):
153
+ self.scan_customize_file(root)
154
+ return
155
+
156
+ for dirpath, _dirnames, filenames in os.walk(root, followlinks=False):
157
+ current = pathlib.Path(dirpath)
158
+ for fname in filenames:
159
+ fpath = current / fname
160
+ if fname.endswith(".pth"):
161
+ self.scan_pth_file(fpath)
162
+ elif fname in ("sitecustomize.py", "usercustomize.py"):
163
+ self.scan_customize_file(fpath)
164
+
165
+ def run(self) -> Dict[str, Any]:
166
+ self.scan_path(pathlib.Path(self.target).resolve())
167
+ threats = sum(1 for f in self.findings if f["severity"] in ("HIGH", "CRITICAL"))
168
+ return {
169
+ "summary": {
170
+ "target": self.target,
171
+ "pth_files": self.pth_files,
172
+ "customize_files": self.customize_files,
173
+ "findings": len(self.findings),
174
+ "threats_detected": threats,
175
+ },
176
+ "findings": self.findings,
177
+ }
178
+
179
+
180
+ def format_text_report(results: Dict[str, Any]) -> str:
181
+ summary = results["summary"]
182
+ findings = results["findings"]
183
+ lines = [
184
+ "================================================================================",
185
+ " PTHGUARD-LITE SCAN REPORT ",
186
+ "================================================================================",
187
+ f"Target : {summary['target']}",
188
+ f".pth Files Inspected : {summary['pth_files']}",
189
+ f"Customize Hooks Found : {summary['customize_files']}",
190
+ f"Findings : {summary['findings']}",
191
+ f"Critical/High Threats : {summary['threats_detected']}",
192
+ "--------------------------------------------------------------------------------",
193
+ ]
194
+ if not findings:
195
+ lines.append("[+] Status: CLEAN. No suspicious .pth or customize hooks detected.")
196
+ else:
197
+ lines.append(f"Findings ({len(findings)} total):")
198
+ for i, f in enumerate(findings, start=1):
199
+ lines.append(f"\n{i}. [{f['severity']}] Category : {f['category']}")
200
+ lines.append(f" Path : {f['path']}")
201
+ lines.append(f" Details : {f['description']}")
202
+ for k, v in f["details"].items():
203
+ lines.append(f" {k}: {v}")
204
+ lines.append("================================================================================")
205
+ return "\n".join(lines)
206
+
207
+
208
+ def build_parser() -> argparse.ArgumentParser:
209
+ p = argparse.ArgumentParser(
210
+ prog="pthguard-lite",
211
+ description=(
212
+ "Static scan of one site-packages/venv path for risky .pth startup hooks "
213
+ "and sitecustomize/usercustomize persistence. Stdlib only; never executes target code."
214
+ ),
215
+ epilog=(
216
+ "Full version: https://py-forge.com/products/pthguard-python-backdoor-scanner"
217
+ "?utm_source=github&utm_medium=cli&utm_campaign=pthguard-lite"
218
+ ),
219
+ formatter_class=argparse.RawDescriptionHelpFormatter,
220
+ )
221
+ p.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
222
+ p.add_argument(
223
+ "target",
224
+ nargs="?",
225
+ help="One site-packages, venv, or file (.pth / sitecustomize.py / usercustomize.py) to scan",
226
+ )
227
+ return p
228
+
229
+
230
+ def main(argv: Optional[List[str]] = None) -> int:
231
+ args = build_parser().parse_args(argv)
232
+ if not args.target:
233
+ build_parser().print_help()
234
+ print("\nError: provide exactly one scan target path.", file=sys.stderr)
235
+ return 2
236
+
237
+ results = LiteScanner(args.target).run()
238
+ print(format_text_report(results))
239
+ # lite: print findings; exit 1 only when HIGH/CRITICAL so a quick check stays useful
240
+ return 1 if results["summary"]["threats_detected"] > 0 else 0
241
+
242
+
243
+ if __name__ == "__main__":
244
+ sys.exit(main())