leashscan 0.1.1__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.
- leashscan/__init__.py +4 -0
- leashscan/__main__.py +3 -0
- leashscan/cli.py +151 -0
- leashscan/findings.py +73 -0
- leashscan/injection.py +122 -0
- leashscan/mcp.py +216 -0
- leashscan/minitoml.py +82 -0
- leashscan/patterns.py +56 -0
- leashscan/permissions.py +154 -0
- leashscan/report.py +201 -0
- leashscan/secrets.py +173 -0
- leashscan/walker.py +103 -0
- leashscan-0.1.1.dist-info/METADATA +170 -0
- leashscan-0.1.1.dist-info/RECORD +18 -0
- leashscan-0.1.1.dist-info/WHEEL +5 -0
- leashscan-0.1.1.dist-info/entry_points.txt +2 -0
- leashscan-0.1.1.dist-info/licenses/LICENSE +21 -0
- leashscan-0.1.1.dist-info/top_level.txt +1 -0
leashscan/__init__.py
ADDED
leashscan/__main__.py
ADDED
leashscan/cli.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""Command-line entry point."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import fnmatch
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from . import __version__, injection, mcp, permissions, report, secrets
|
|
11
|
+
from .findings import SEVERITY_RANK, Finding, dedupe
|
|
12
|
+
|
|
13
|
+
EPILOG = """examples:
|
|
14
|
+
leashscan scan the current project
|
|
15
|
+
leashscan --home also check ~/.ssh, ~/.aws, global MCP + agent configs
|
|
16
|
+
leashscan repo1 repo2 repo3 one combined report for many repos
|
|
17
|
+
leashscan --format html -o report.html client-ready report
|
|
18
|
+
leashscan --format sarif -o leashscan.sarif for GitHub code scanning
|
|
19
|
+
leashscan --fail-on high exit 1 in CI if anything high or worse is found
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def apply_ignores(root: Path, findings: list[Finding]) -> list[Finding]:
|
|
24
|
+
"""Honor `.leashscanignore` globs (path or path:RULE_ID) and inline `leashscan:ignore` comments."""
|
|
25
|
+
rules: list[tuple[str, str | None]] = []
|
|
26
|
+
ig = root / ".leashscanignore"
|
|
27
|
+
if ig.is_file():
|
|
28
|
+
for raw in ig.read_text(errors="ignore").splitlines():
|
|
29
|
+
line = raw.split("#", 1)[0].strip()
|
|
30
|
+
if line:
|
|
31
|
+
pat, _, rule = line.partition(":")
|
|
32
|
+
rules.append((pat.strip(), rule.strip() or None))
|
|
33
|
+
cache: dict[str, list[str]] = {}
|
|
34
|
+
kept = []
|
|
35
|
+
for f in findings:
|
|
36
|
+
p = f.path.replace("\\", "/")
|
|
37
|
+
if any((fnmatch.fnmatch(p, pat) or fnmatch.fnmatch(p, pat.rstrip("/") + "/*"))
|
|
38
|
+
and (rule is None or rule == f.rule_id) for pat, rule in rules):
|
|
39
|
+
continue
|
|
40
|
+
if f.line and not p.startswith("~"):
|
|
41
|
+
if p not in cache:
|
|
42
|
+
try:
|
|
43
|
+
cache[p] = (root / p).read_text(errors="ignore").splitlines()
|
|
44
|
+
except OSError:
|
|
45
|
+
cache[p] = []
|
|
46
|
+
lines = cache[p]
|
|
47
|
+
near = lines[max(0, f.line - 2):f.line]
|
|
48
|
+
if any("leashscan:ignore" in ln for ln in near):
|
|
49
|
+
continue
|
|
50
|
+
kept.append(f)
|
|
51
|
+
return kept
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def scan_paths(paths: list[Path], include_home: bool, max_size: int, only: set[str] | None = None) -> list[Finding]:
|
|
55
|
+
findings: list[Finding] = []
|
|
56
|
+
multi = len(paths) > 1
|
|
57
|
+
for root in paths:
|
|
58
|
+
root = root.resolve()
|
|
59
|
+
part: list[Finding] = []
|
|
60
|
+
if not only or "secrets" in only:
|
|
61
|
+
part += secrets.scan_repo(root, max_size)
|
|
62
|
+
if not only or "mcp" in only:
|
|
63
|
+
part += mcp.scan(root, include_home=False)
|
|
64
|
+
if not only or "permissions" in only:
|
|
65
|
+
part += permissions.scan(root, include_home=False)
|
|
66
|
+
if not only or "injection" in only:
|
|
67
|
+
part += injection.scan(root, max_size)
|
|
68
|
+
part = apply_ignores(root, part)
|
|
69
|
+
if multi:
|
|
70
|
+
for f in part:
|
|
71
|
+
f.path = f"{root.name}/{f.path}"
|
|
72
|
+
findings += part
|
|
73
|
+
if include_home:
|
|
74
|
+
home = Path.home()
|
|
75
|
+
if not only or "home" in only:
|
|
76
|
+
findings += secrets.scan_home(home)
|
|
77
|
+
if not only or "mcp" in only:
|
|
78
|
+
findings += mcp.scan(Path("/nonexistent-leashscan"), include_home=True, home=home)
|
|
79
|
+
if not only or "permissions" in only:
|
|
80
|
+
findings += permissions.scan(Path("/nonexistent-leashscan"), include_home=True, home=home)
|
|
81
|
+
return dedupe(findings)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def main(argv: list[str] | None = None) -> int:
|
|
85
|
+
ap = argparse.ArgumentParser(
|
|
86
|
+
prog="leashscan",
|
|
87
|
+
description="See what your AI coding agents and MCP servers can reach: secrets, risky configs, "
|
|
88
|
+
"over-broad permissions and hidden prompt injection. Offline, read-only, zero dependencies.",
|
|
89
|
+
epilog=EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
90
|
+
)
|
|
91
|
+
ap.add_argument("paths", nargs="*", default=["."], help="folders to scan (default: current folder)")
|
|
92
|
+
ap.add_argument("--home", action="store_true", help="also scan your home folder credentials and global agent configs")
|
|
93
|
+
ap.add_argument("-f", "--format", choices=["text", "json", "sarif", "markdown", "html"], default="text")
|
|
94
|
+
ap.add_argument("-o", "--output", help="write report to a file instead of stdout")
|
|
95
|
+
ap.add_argument("--fail-on", choices=["critical", "high", "medium", "low", "none"], default="none",
|
|
96
|
+
help="exit with code 1 if a finding at or above this severity exists")
|
|
97
|
+
ap.add_argument("--only", help="comma list: secrets,home,mcp,permissions,injection")
|
|
98
|
+
ap.add_argument("--min-severity", choices=["critical", "high", "medium", "low"], default="low",
|
|
99
|
+
help="hide findings below this severity")
|
|
100
|
+
ap.add_argument("--max-file-size", type=int, default=1_000_000, help="skip files bigger than this (bytes)")
|
|
101
|
+
ap.add_argument("--no-color", action="store_true")
|
|
102
|
+
ap.add_argument("-v", "--verbose", action="store_true", help="show every finding")
|
|
103
|
+
ap.add_argument("--badge", action="store_true", help="print a README badge for your grade")
|
|
104
|
+
ap.add_argument("--version", action="version", version=f"leashscan {__version__}")
|
|
105
|
+
args = ap.parse_args(argv)
|
|
106
|
+
|
|
107
|
+
paths = [Path(p) for p in args.paths]
|
|
108
|
+
for p in paths:
|
|
109
|
+
if not p.is_dir():
|
|
110
|
+
print(f"leashscan: not a folder: {p}", file=sys.stderr)
|
|
111
|
+
return 2
|
|
112
|
+
only = {s.strip() for s in args.only.split(",")} if args.only else None
|
|
113
|
+
findings = scan_paths(paths, args.home, args.max_file_size, only)
|
|
114
|
+
cutoff = SEVERITY_RANK[args.min_severity]
|
|
115
|
+
findings = [f for f in findings if SEVERITY_RANK[f.severity] <= cutoff]
|
|
116
|
+
|
|
117
|
+
targets = [str(p.resolve().name or p.resolve()) for p in paths] + (["~ (home)"] if args.home else [])
|
|
118
|
+
if args.format == "json":
|
|
119
|
+
out = report.json_report(findings, targets)
|
|
120
|
+
elif args.format == "sarif":
|
|
121
|
+
out = report.sarif_report(findings, targets)
|
|
122
|
+
elif args.format == "markdown":
|
|
123
|
+
out = report.markdown_report(findings, targets)
|
|
124
|
+
elif args.format == "html":
|
|
125
|
+
out = report.html_report(findings, targets)
|
|
126
|
+
else:
|
|
127
|
+
color = report.use_color(args.no_color) and not args.output
|
|
128
|
+
out = report.text_report(findings, targets, color, args.verbose)
|
|
129
|
+
|
|
130
|
+
if args.output:
|
|
131
|
+
Path(args.output).write_text(out, encoding="utf-8")
|
|
132
|
+
_, grade = report.score(findings)
|
|
133
|
+
print(f"leashscan: grade {grade}, {len(findings)} finding(s), report written to {args.output}", file=sys.stderr)
|
|
134
|
+
else:
|
|
135
|
+
try:
|
|
136
|
+
sys.stdout.write(out)
|
|
137
|
+
except UnicodeEncodeError:
|
|
138
|
+
sys.stdout.write(out.encode("ascii", "replace").decode())
|
|
139
|
+
if args.badge:
|
|
140
|
+
_, grade = report.score(findings)
|
|
141
|
+
print(f"\n[})]({report.REPO_URL})", file=sys.stderr)
|
|
142
|
+
|
|
143
|
+
if args.fail_on != "none":
|
|
144
|
+
limit = SEVERITY_RANK[args.fail_on]
|
|
145
|
+
if any(SEVERITY_RANK[f.severity] <= limit for f in findings):
|
|
146
|
+
return 1
|
|
147
|
+
return 0
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
if __name__ == "__main__":
|
|
151
|
+
raise SystemExit(main())
|
leashscan/findings.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Finding model and scoring."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import asdict, dataclass
|
|
6
|
+
|
|
7
|
+
SEVERITIES = ("critical", "high", "medium", "low")
|
|
8
|
+
SEVERITY_RANK = {s: i for i, s in enumerate(SEVERITIES)}
|
|
9
|
+
SEVERITY_WEIGHT = {"critical": 30, "high": 12, "medium": 4, "low": 1}
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class Finding:
|
|
14
|
+
rule_id: str
|
|
15
|
+
severity: str
|
|
16
|
+
category: str
|
|
17
|
+
title: str
|
|
18
|
+
path: str
|
|
19
|
+
line: int | None = None
|
|
20
|
+
detail: str = ""
|
|
21
|
+
fix: str = ""
|
|
22
|
+
|
|
23
|
+
def key(self) -> tuple:
|
|
24
|
+
return (self.rule_id, self.path, self.line, self.detail)
|
|
25
|
+
|
|
26
|
+
def to_dict(self) -> dict:
|
|
27
|
+
return asdict(self)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def dedupe(findings: list[Finding]) -> list[Finding]:
|
|
31
|
+
seen: set[tuple] = set()
|
|
32
|
+
out: list[Finding] = []
|
|
33
|
+
for f in findings:
|
|
34
|
+
if f.key() in seen:
|
|
35
|
+
continue
|
|
36
|
+
seen.add(f.key())
|
|
37
|
+
out.append(f)
|
|
38
|
+
out.sort(key=lambda f: (SEVERITY_RANK[f.severity], f.category, f.path, f.line or 0))
|
|
39
|
+
return out
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def score(findings: list[Finding]) -> tuple[int, str]:
|
|
43
|
+
"""Return (score 0-100, letter grade)."""
|
|
44
|
+
penalty = 0
|
|
45
|
+
# Diminishing returns per rule so one noisy rule can't dominate.
|
|
46
|
+
per_rule: dict[str, int] = {}
|
|
47
|
+
for f in findings:
|
|
48
|
+
n = per_rule.get(f.rule_id, 0)
|
|
49
|
+
per_rule[f.rule_id] = n + 1
|
|
50
|
+
w = SEVERITY_WEIGHT[f.severity]
|
|
51
|
+
penalty += w if n == 0 else max(1, w // (n + 1))
|
|
52
|
+
value = max(0, 100 - penalty)
|
|
53
|
+
if value >= 90:
|
|
54
|
+
grade = "A"
|
|
55
|
+
elif value >= 75:
|
|
56
|
+
grade = "B"
|
|
57
|
+
elif value >= 60:
|
|
58
|
+
grade = "C"
|
|
59
|
+
elif value >= 40:
|
|
60
|
+
grade = "D"
|
|
61
|
+
else:
|
|
62
|
+
grade = "F"
|
|
63
|
+
if any(f.severity == "critical" for f in findings) and grade in "ABC":
|
|
64
|
+
grade = "D"
|
|
65
|
+
value = min(value, 59)
|
|
66
|
+
return value, grade
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def counts(findings: list[Finding]) -> dict[str, int]:
|
|
70
|
+
c = {s: 0 for s in SEVERITIES}
|
|
71
|
+
for f in findings:
|
|
72
|
+
c[f.severity] += 1
|
|
73
|
+
return c
|
leashscan/injection.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Find hidden text and prompt-injection bait aimed at AI coding agents."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from .findings import Finding
|
|
9
|
+
from .walker import display, iter_files, line_of, read_text
|
|
10
|
+
|
|
11
|
+
AGENT_FILES = {
|
|
12
|
+
"agents.md", "claude.md", "gemini.md", ".cursorrules", ".windsurfrules", ".clinerules",
|
|
13
|
+
"copilot-instructions.md", "conventions.md", ".aider.conf.yml",
|
|
14
|
+
}
|
|
15
|
+
AGENT_DIRS = (".cursor/rules", ".claude/commands", ".claude/agents", ".claude/skills", ".github/prompts",
|
|
16
|
+
".windsurf/rules", ".clinerules")
|
|
17
|
+
DOC_EXT = {".md", ".mdx", ".mdc", ".rst", ".txt", ".html", ".htm"}
|
|
18
|
+
|
|
19
|
+
BIDI = {0x202A, 0x202B, 0x202C, 0x202D, 0x202E, 0x2066, 0x2067, 0x2068, 0x2069}
|
|
20
|
+
ZERO_WIDTH = {0x200B, 0x200C, 0x200D, 0x2060, 0x2061, 0x2062, 0x2063, 0x2064, 0x180E, 0xFEFF}
|
|
21
|
+
|
|
22
|
+
PHRASES = [
|
|
23
|
+
r"ignore (?:all |any )?(?:the )?(?:previous|prior|above|earlier|preceding) (?:instructions|prompts|rules|directions)",
|
|
24
|
+
r"disregard (?:all |any )?(?:the |your )?(?:previous |prior |system )?(?:instructions|prompt|rules)",
|
|
25
|
+
r"forget (?:all |everything )?(?:your |the )?(?:previous |prior )?instructions",
|
|
26
|
+
r"(?:do not|don't|never) (?:tell|inform|mention|reveal|show|alert) (?:this |it )?(?:to )?(?:the )?user",
|
|
27
|
+
r"without (?:telling|informing|asking|notifying) (?:the )?user",
|
|
28
|
+
r"new (?:system )?instructions\s*:",
|
|
29
|
+
r"you are now (?:in )?(?:developer|dan|jailbreak|unrestricted|god) mode",
|
|
30
|
+
r"(?:send|post|upload|exfiltrate|forward|leak) (?:the |all |any )?(?:contents of |content of )?"
|
|
31
|
+
r"(?:\.env|env vars?|environment variables|secrets?|api keys?|credentials|tokens?|ssh keys?|~/\.ssh|~/\.aws)",
|
|
32
|
+
r"(?:cat|read|print) (?:the )?(?:~/\.ssh|~/\.aws|\.env\b|/etc/passwd)",
|
|
33
|
+
r"(?:curl|wget)\s+[^\n|]{0,200}\|\s*(?:sudo\s+)?(?:ba|z)?sh\b",
|
|
34
|
+
r"base64\s+(?:-d|--decode)[^\n]{0,80}\|\s*(?:ba)?sh",
|
|
35
|
+
r"(?:as an? |dear )(?:ai|llm|language model|assistant|coding agent|claude|copilot|cursor|codex)\b[^\n]{0,80}"
|
|
36
|
+
r"(?:must|should|need to|please)",
|
|
37
|
+
]
|
|
38
|
+
PHRASE_RX = re.compile("|".join(f"(?:{p})" for p in PHRASES), re.IGNORECASE)
|
|
39
|
+
HTML_COMMENT = re.compile(r"<!--(.*?)-->", re.DOTALL)
|
|
40
|
+
AI_WORDS = re.compile(r"(?i)\b(ai|llm|assistant|agent|claude|copilot|cursor|codex|gemini|model|chatgpt)\b")
|
|
41
|
+
IMPERATIVE = re.compile(r"(?i)\b(ignore|run|execute|send|post|curl|delete|must|always|never|do not|don't|instead)\b")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _is_agent_file(path: Path, root: Path) -> bool:
|
|
45
|
+
rel = str(path.relative_to(root)).replace("\\", "/").lower()
|
|
46
|
+
return path.name.lower() in AGENT_FILES or any(rel.startswith(d.lower() + "/") for d in AGENT_DIRS)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def decode_tags(s: str) -> str:
|
|
50
|
+
return "".join(chr(ord(c) - 0xE0000) for c in s if 0xE0020 <= ord(c) <= 0xE007E)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _hidden_unicode(text: str, rel: str, agent_file: bool) -> list[Finding]:
|
|
54
|
+
out: list[Finding] = []
|
|
55
|
+
tag_run = re.finditer(r"[\U000E0000-\U000E007F]+", text)
|
|
56
|
+
for m in tag_run:
|
|
57
|
+
msg = decode_tags(m.group(0))
|
|
58
|
+
out.append(Finding(
|
|
59
|
+
"INJ001", "critical", "injection", "Invisible Unicode tag text (hidden instructions)", rel,
|
|
60
|
+
line_of(text, m.start()), detail=f"Decoded hidden text: \"{msg[:160]}\"",
|
|
61
|
+
fix="Delete the invisible characters. Humans can't see this text, but AI models read it.",
|
|
62
|
+
))
|
|
63
|
+
for i, ch in enumerate(text):
|
|
64
|
+
cp = ord(ch)
|
|
65
|
+
if cp in BIDI:
|
|
66
|
+
out.append(Finding("INJ002", "high", "injection", "Bidirectional control character (Trojan Source)", rel,
|
|
67
|
+
line_of(text, i), detail=f"U+{cp:04X} can make code look different from what runs.",
|
|
68
|
+
fix="Remove it unless the file genuinely contains right-to-left text."))
|
|
69
|
+
break
|
|
70
|
+
zw = 0
|
|
71
|
+
first = None
|
|
72
|
+
for i, ch in enumerate(text):
|
|
73
|
+
cp = ord(ch)
|
|
74
|
+
if cp in ZERO_WIDTH:
|
|
75
|
+
if cp == 0xFEFF and i == 0:
|
|
76
|
+
continue
|
|
77
|
+
if cp in (0x200D, 0xFE0F, 0x200C) and i > 0 and ord(text[i - 1]) > 0x2000:
|
|
78
|
+
continue # emoji / script joiners
|
|
79
|
+
zw += 1
|
|
80
|
+
first = first if first is not None else i
|
|
81
|
+
if zw >= (1 if agent_file else 3):
|
|
82
|
+
out.append(Finding("INJ003", "high" if agent_file else "medium", "injection",
|
|
83
|
+
f"{zw} zero-width character(s) hidden in text", rel, line_of(text, first or 0),
|
|
84
|
+
detail="Often used to smuggle or obfuscate instructions for AI agents.",
|
|
85
|
+
fix="Strip them: `leashscan` reports exact lines; most editors can show invisible chars."))
|
|
86
|
+
return out
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def scan(root: Path, max_size: int) -> list[Finding]:
|
|
90
|
+
out: list[Finding] = []
|
|
91
|
+
for path in iter_files(root, max_size):
|
|
92
|
+
agent_file = _is_agent_file(path, root)
|
|
93
|
+
if not agent_file and path.suffix.lower() not in DOC_EXT and path.name.lower() not in AGENT_FILES:
|
|
94
|
+
# still check source files for invisible unicode
|
|
95
|
+
text = read_text(path)
|
|
96
|
+
if text and any(ord(c) > 0x2000 for c in text):
|
|
97
|
+
out += _hidden_unicode(text, display(path, root), False)
|
|
98
|
+
continue
|
|
99
|
+
text = read_text(path)
|
|
100
|
+
if not text:
|
|
101
|
+
continue
|
|
102
|
+
rel = display(path, root)
|
|
103
|
+
out += _hidden_unicode(text, rel, agent_file)
|
|
104
|
+
for m in PHRASE_RX.finditer(text):
|
|
105
|
+
out.append(Finding(
|
|
106
|
+
"INJ010", "high" if agent_file else "medium", "injection",
|
|
107
|
+
"Prompt-injection phrase" + (" in an agent instructions file" if agent_file else ""), rel,
|
|
108
|
+
line_of(text, m.start()), detail=f"\"{m.group(0)[:120]}\"",
|
|
109
|
+
fix="If you didn't write this, remove it. Agents treat this text as instructions.",
|
|
110
|
+
))
|
|
111
|
+
if path.suffix.lower() in {".md", ".mdx", ".mdc", ".html", ".htm"}:
|
|
112
|
+
for m in HTML_COMMENT.finditer(text):
|
|
113
|
+
body = m.group(1)
|
|
114
|
+
if AI_WORDS.search(body) and IMPERATIVE.search(body) and len(body.strip()) > 20:
|
|
115
|
+
if PHRASE_RX.search(body):
|
|
116
|
+
continue # already reported
|
|
117
|
+
out.append(Finding(
|
|
118
|
+
"INJ011", "medium", "injection", "Hidden HTML comment with instructions for AI", rel,
|
|
119
|
+
line_of(text, m.start()), detail=f"\"{' '.join(body.split())[:120]}\"",
|
|
120
|
+
fix="Rendered Markdown hides this from humans but agents read it. Review or remove.",
|
|
121
|
+
))
|
|
122
|
+
return out
|
leashscan/mcp.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
"""Audit MCP server configs used by Claude, Cursor, VS Code, Windsurf, Codex and Gemini."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
try:
|
|
11
|
+
import tomllib
|
|
12
|
+
except ModuleNotFoundError: # Python < 3.11
|
|
13
|
+
from . import minitoml as tomllib # type: ignore
|
|
14
|
+
|
|
15
|
+
from .findings import Finding
|
|
16
|
+
from .patterns import SECRET_NAME, is_env_reference, looks_like_placeholder, match_known_secret, redact
|
|
17
|
+
from .walker import display, read_text
|
|
18
|
+
|
|
19
|
+
PROJECT_CONFIGS = [
|
|
20
|
+
".mcp.json", ".cursor/mcp.json", ".vscode/mcp.json", ".gemini/settings.json",
|
|
21
|
+
".codex/config.toml", ".windsurf/mcp.json", ".roo/mcp.json", "mcp.json",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def home_configs(home: Path) -> list[Path]:
|
|
26
|
+
paths = [
|
|
27
|
+
".claude.json", ".cursor/mcp.json", ".codeium/windsurf/mcp_config.json", ".codex/config.toml",
|
|
28
|
+
".gemini/settings.json", ".config/Claude/claude_desktop_config.json",
|
|
29
|
+
"Library/Application Support/Claude/claude_desktop_config.json",
|
|
30
|
+
"AppData/Roaming/Claude/claude_desktop_config.json",
|
|
31
|
+
".config/Code/User/mcp.json", "Library/Application Support/Code/User/mcp.json",
|
|
32
|
+
"AppData/Roaming/Code/User/mcp.json",
|
|
33
|
+
]
|
|
34
|
+
return [home / p for p in paths]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
SHELL_HINTS = re.compile(r"(?i)(shell|terminal|exec|desktop-?commander|server-commands|run-?command|bash|powershell|cmd-?mcp)")
|
|
38
|
+
FS_HINTS = re.compile(r"(?i)(server-filesystem|filesystem|fs-mcp|file-?system)")
|
|
39
|
+
RUNNERS = {"npx", "bunx", "pnpx", "uvx", "pipx", "dlx"}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def load_servers(path: Path) -> dict[str, dict]:
|
|
43
|
+
text = read_text(path)
|
|
44
|
+
if not text:
|
|
45
|
+
return {}
|
|
46
|
+
data: object
|
|
47
|
+
if path.suffix == ".toml":
|
|
48
|
+
try:
|
|
49
|
+
data = tomllib.loads(text)
|
|
50
|
+
except Exception:
|
|
51
|
+
return {}
|
|
52
|
+
else:
|
|
53
|
+
try:
|
|
54
|
+
data = json.loads(text)
|
|
55
|
+
except json.JSONDecodeError:
|
|
56
|
+
# tolerate JSONC comments
|
|
57
|
+
stripped = re.sub(r"(?m)^\s*//.*$", "", text)
|
|
58
|
+
try:
|
|
59
|
+
data = json.loads(stripped)
|
|
60
|
+
except json.JSONDecodeError:
|
|
61
|
+
return {}
|
|
62
|
+
if not isinstance(data, dict):
|
|
63
|
+
return {}
|
|
64
|
+
servers: dict[str, dict] = {}
|
|
65
|
+
for key in ("mcpServers", "servers", "mcp_servers", "context_servers"):
|
|
66
|
+
block = data.get(key)
|
|
67
|
+
if isinstance(block, dict):
|
|
68
|
+
servers.update({k: v for k, v in block.items() if isinstance(v, dict)})
|
|
69
|
+
projects = data.get("projects") # ~/.claude.json
|
|
70
|
+
if isinstance(projects, dict):
|
|
71
|
+
for proj, cfg in projects.items():
|
|
72
|
+
if isinstance(cfg, dict) and isinstance(cfg.get("mcpServers"), dict):
|
|
73
|
+
for k, v in cfg["mcpServers"].items():
|
|
74
|
+
if isinstance(v, dict):
|
|
75
|
+
servers[f"{k} ({Path(proj).name})"] = v
|
|
76
|
+
return servers
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _package_from_args(command: str, args: list[str]) -> str | None:
|
|
80
|
+
cmd = Path(command).name.lower().removesuffix(".cmd").removesuffix(".exe")
|
|
81
|
+
rest = list(args)
|
|
82
|
+
if cmd in {"pnpm", "yarn", "bun"} and rest[:1] == ["dlx"]:
|
|
83
|
+
rest = rest[1:]
|
|
84
|
+
cmd = "dlx"
|
|
85
|
+
if cmd == "pipx" and rest[:1] == ["run"]:
|
|
86
|
+
rest = rest[1:]
|
|
87
|
+
if cmd not in RUNNERS:
|
|
88
|
+
return None
|
|
89
|
+
for a in rest:
|
|
90
|
+
if a.startswith("-"):
|
|
91
|
+
continue
|
|
92
|
+
return a
|
|
93
|
+
return None
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _unpinned(pkg: str, runner_is_py: bool) -> bool:
|
|
97
|
+
if runner_is_py:
|
|
98
|
+
return not re.search(r"(==|@)\d", pkg)
|
|
99
|
+
name = pkg[1:] if pkg.startswith("@") else pkg
|
|
100
|
+
if "@" not in name:
|
|
101
|
+
return True
|
|
102
|
+
version = name.split("@", 1)[1]
|
|
103
|
+
return version in ("latest", "next", "") or not re.match(r"^\d", version)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def audit_server(name: str, cfg: dict, where: str, home: Path) -> list[Finding]:
|
|
107
|
+
out: list[Finding] = []
|
|
108
|
+
command = str(cfg.get("command", "") or "")
|
|
109
|
+
args = [str(a) for a in (cfg.get("args") or []) if isinstance(a, (str, int, float))]
|
|
110
|
+
joined = " ".join([command, *args])
|
|
111
|
+
label = f"MCP server `{name}`"
|
|
112
|
+
|
|
113
|
+
# 1. Plaintext secrets in env / headers / args / url
|
|
114
|
+
blobs: list[tuple[str, str]] = []
|
|
115
|
+
for field in ("env", "headers", "http_headers", "env_http_headers"):
|
|
116
|
+
block = cfg.get(field)
|
|
117
|
+
if isinstance(block, dict):
|
|
118
|
+
blobs += [(str(k), str(v)) for k, v in block.items()]
|
|
119
|
+
blobs += [("arg", a) for a in args]
|
|
120
|
+
if cfg.get("url"):
|
|
121
|
+
blobs.append(("url", str(cfg["url"])))
|
|
122
|
+
for k, v in blobs:
|
|
123
|
+
if is_env_reference(v):
|
|
124
|
+
continue
|
|
125
|
+
known = match_known_secret(v)
|
|
126
|
+
named = k != "arg" and k != "url" and SECRET_NAME.search(k) and len(v) >= 8 and not looks_like_placeholder(v)
|
|
127
|
+
bearer = v.lower().startswith("bearer ") and len(v) > 20
|
|
128
|
+
token_in_url = k == "url" and re.search(r"(?i)[?&](key|token|api_key|apikey|access_token)=[^&]{8,}", v)
|
|
129
|
+
if known or named or bearer or token_in_url:
|
|
130
|
+
what = known[1] if known else (k if k not in ("arg", "url") else "token")
|
|
131
|
+
out.append(Finding(
|
|
132
|
+
"MCP001", "high", "mcp", f"{label} has a plain-text secret", where,
|
|
133
|
+
detail=f"{what}: {redact(v.split()[-1])}",
|
|
134
|
+
fix="Reference an env var instead (e.g. `\"${API_KEY}\"`, VS Code `${input:...}`) and rotate the key.",
|
|
135
|
+
))
|
|
136
|
+
|
|
137
|
+
# 2. Unpinned packages pulled at launch
|
|
138
|
+
pkg = _package_from_args(command, args)
|
|
139
|
+
if pkg:
|
|
140
|
+
is_py = Path(command).name.startswith(("uvx", "pipx"))
|
|
141
|
+
if _unpinned(pkg, is_py):
|
|
142
|
+
out.append(Finding(
|
|
143
|
+
"MCP002", "medium", "mcp", f"{label} runs an unpinned package", where,
|
|
144
|
+
detail=f"`{pkg}` is fetched fresh on every launch. If that package is hijacked, the new code runs as you.",
|
|
145
|
+
fix=f"Pin an exact version, e.g. `{pkg.split('@latest')[0]}@1.2.3`.",
|
|
146
|
+
))
|
|
147
|
+
if re.search(r"curl[^|]*\|\s*(sudo\s+)?(ba|z)?sh|wget[^|]*\|\s*(ba)?sh|iwr[^|]*\|\s*iex", joined):
|
|
148
|
+
out.append(Finding("MCP007", "high", "mcp", f"{label} pipes a download into a shell", where,
|
|
149
|
+
detail=joined[:160], fix="Install a pinned, checksummed release instead."))
|
|
150
|
+
|
|
151
|
+
# 3. Broad filesystem access
|
|
152
|
+
if FS_HINTS.search(joined) or (command and Path(command).name in ("node", "npx") and "filesystem" in joined):
|
|
153
|
+
broad = []
|
|
154
|
+
for a in args:
|
|
155
|
+
a2 = a.rstrip("/\\")
|
|
156
|
+
if a2 in ("", "~", "$HOME", "${HOME}", "C:", "/Users", "/home", "/root") or a == "/" \
|
|
157
|
+
or a2 == str(home).rstrip("/") or re.fullmatch(r"[A-Za-z]:", a2):
|
|
158
|
+
broad.append(a or "/")
|
|
159
|
+
if broad:
|
|
160
|
+
out.append(Finding(
|
|
161
|
+
"MCP003", "high", "mcp", f"{label} can read/write your whole disk or home", where,
|
|
162
|
+
detail=f"Root(s): {', '.join(broad)}. That includes ~/.ssh, ~/.aws and browser profiles.",
|
|
163
|
+
fix="Limit it to the project folders it actually needs.",
|
|
164
|
+
))
|
|
165
|
+
|
|
166
|
+
# 4. Insecure remote transport
|
|
167
|
+
url = str(cfg.get("url") or cfg.get("serverUrl") or "")
|
|
168
|
+
if url.startswith("http://") and not re.match(r"http://(localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0)", url):
|
|
169
|
+
out.append(Finding("MCP004", "high", "mcp", f"{label} uses unencrypted HTTP", where,
|
|
170
|
+
detail=url.split("?")[0], fix="Use https://."))
|
|
171
|
+
|
|
172
|
+
# 5. Arbitrary command execution
|
|
173
|
+
if SHELL_HINTS.search(" ".join(args) + " " + name) and not FS_HINTS.search(joined):
|
|
174
|
+
out.append(Finding(
|
|
175
|
+
"MCP005", "medium", "mcp", f"{label} can run shell commands", where,
|
|
176
|
+
detail="One prompt injection in a web page, issue or file can become a command on your machine.",
|
|
177
|
+
fix="Keep manual approval on for this server's tools, or run it in a container.",
|
|
178
|
+
))
|
|
179
|
+
|
|
180
|
+
# 6. Dangerous docker flags
|
|
181
|
+
if Path(command).name == "docker" or "docker run" in joined:
|
|
182
|
+
bad = [f for f in ("--privileged", "/var/run/docker.sock", "--net=host", "--network=host", "--pid=host")
|
|
183
|
+
if f in joined]
|
|
184
|
+
if re.search(r"-v\s+/:/|--volume[= ]/:/|-v\s+~[:/]|-v\s+\$HOME", joined):
|
|
185
|
+
bad.append("host root/home mounted")
|
|
186
|
+
if bad:
|
|
187
|
+
out.append(Finding("MCP006", "high", "mcp", f"{label} container escapes its sandbox", where,
|
|
188
|
+
detail=", ".join(bad), fix="Drop these flags and mount only the folders needed."))
|
|
189
|
+
return out
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def scan(root: Path, include_home: bool, home: Path | None = None) -> list[Finding]:
|
|
193
|
+
home = home or Path.home()
|
|
194
|
+
findings: list[Finding] = []
|
|
195
|
+
targets: list[tuple[Path, bool]] = [(root / p, False) for p in PROJECT_CONFIGS]
|
|
196
|
+
if include_home:
|
|
197
|
+
targets += [(p, True) for p in home_configs(home)]
|
|
198
|
+
for path, is_home in targets:
|
|
199
|
+
if not path.is_file():
|
|
200
|
+
continue
|
|
201
|
+
servers = load_servers(path)
|
|
202
|
+
where = ("~/" + str(path.relative_to(home))) if is_home else display(path, root)
|
|
203
|
+
for name, cfg in servers.items():
|
|
204
|
+
findings += audit_server(name, cfg, where, home)
|
|
205
|
+
if servers and not is_home:
|
|
206
|
+
findings.append(Finding(
|
|
207
|
+
"MCP010", "low", "mcp", f"Repo ships {len(servers)} MCP server(s)", where,
|
|
208
|
+
detail="Anyone who clones this and trusts the folder will launch: " + ", ".join(sorted(servers)[:6]),
|
|
209
|
+
fix="Review these before approving them in your editor.",
|
|
210
|
+
))
|
|
211
|
+
return findings
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
if __name__ == "__main__": # pragma: no cover
|
|
215
|
+
for f in scan(Path(sys.argv[1] if len(sys.argv) > 1 else "."), True):
|
|
216
|
+
print(f)
|
leashscan/minitoml.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Tiny TOML subset parser, used only when the stdlib `tomllib` (3.11+) is missing.
|
|
2
|
+
|
|
3
|
+
Handles what agent configs use: [tables], [dotted."quoted".tables], key = "str" | 'str' | bool |
|
|
4
|
+
number | ["arrays", ...] (incl. multi-line) | { inline = "tables" }. Anything else is skipped.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import re
|
|
11
|
+
|
|
12
|
+
_KEY = r'(?:"[^"]*"|\'[^\']*\'|[A-Za-z0-9_\-]+)'
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _split_key(k: str) -> list[str]:
|
|
16
|
+
return [p.strip().strip('"').strip("'") for p in re.findall(_KEY, k)]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _value(src: str):
|
|
20
|
+
s = src.strip()
|
|
21
|
+
if s in ("true", "false"):
|
|
22
|
+
return s == "true"
|
|
23
|
+
if s.startswith("'") and s.endswith("'"):
|
|
24
|
+
return s[1:-1]
|
|
25
|
+
if s.startswith('"') or s.startswith("[") or s.startswith("{"):
|
|
26
|
+
j = re.sub(r"'([^']*)'", lambda m: json.dumps(m.group(1)), s)
|
|
27
|
+
j = re.sub(r"([{,]\s*)(" + _KEY + r")\s*=", lambda m: m.group(1) + json.dumps(_split_key(m.group(2))[0]) + ":", j)
|
|
28
|
+
j = re.sub(r",\s*([\]}])", r"\1", j)
|
|
29
|
+
return json.loads(j)
|
|
30
|
+
try:
|
|
31
|
+
return int(s.replace("_", ""))
|
|
32
|
+
except ValueError:
|
|
33
|
+
return float(s)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _strip_comment(line: str) -> str:
|
|
37
|
+
out, q = [], None
|
|
38
|
+
for ch in line:
|
|
39
|
+
if q:
|
|
40
|
+
if ch == q:
|
|
41
|
+
q = None
|
|
42
|
+
elif ch in "\"'":
|
|
43
|
+
q = ch
|
|
44
|
+
elif ch == "#":
|
|
45
|
+
break
|
|
46
|
+
out.append(ch)
|
|
47
|
+
return "".join(out).strip()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def loads(text: str) -> dict:
|
|
51
|
+
root: dict = {}
|
|
52
|
+
cur = root
|
|
53
|
+
buf = ""
|
|
54
|
+
for raw in text.splitlines():
|
|
55
|
+
line = _strip_comment(raw)
|
|
56
|
+
if buf:
|
|
57
|
+
buf += " " + line
|
|
58
|
+
if buf.count("[") > buf.count("]") or buf.count("{") > buf.count("}"):
|
|
59
|
+
continue
|
|
60
|
+
line, buf = buf, ""
|
|
61
|
+
if not line:
|
|
62
|
+
continue
|
|
63
|
+
if line.startswith("[") and not line.startswith("[["):
|
|
64
|
+
cur = root
|
|
65
|
+
for part in _split_key(line.strip("[]")):
|
|
66
|
+
cur = cur.setdefault(part, {})
|
|
67
|
+
continue
|
|
68
|
+
if "=" not in line:
|
|
69
|
+
continue
|
|
70
|
+
key, _, val = line.partition("=")
|
|
71
|
+
if val.count("[") > val.count("]") or val.count("{") > val.count("}"):
|
|
72
|
+
buf = line
|
|
73
|
+
continue
|
|
74
|
+
parts = _split_key(key)
|
|
75
|
+
target = cur
|
|
76
|
+
for p in parts[:-1]:
|
|
77
|
+
target = target.setdefault(p, {})
|
|
78
|
+
try:
|
|
79
|
+
target[parts[-1]] = _value(val)
|
|
80
|
+
except (ValueError, json.JSONDecodeError):
|
|
81
|
+
continue
|
|
82
|
+
return root
|