mcpscan-cli 0.19.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.
@@ -0,0 +1,81 @@
1
+ """MCP009 — insecure deserialization.
2
+
3
+ Deserializing attacker-influenced data with pickle / marshal / yaml.load is a
4
+ direct path to remote code execution. A tool that accepts serialized blobs and
5
+ loads them is especially dangerous in an MCP server, where the input often comes
6
+ from an untrusted caller.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from typing import List, Optional, Tuple
13
+
14
+ from ..findings import Finding, Severity
15
+ from ..loaders import FileInfo, by_kind
16
+ from .base import Rule, register
17
+
18
+ # Always-dangerous Python sinks.
19
+ PICKLE = re.compile(r"\b(?:pickle|cPickle|_pickle)\.(?:load|loads)\s*\(")
20
+ MARSHAL = re.compile(r"\bmarshal\.(?:load|loads)\s*\(")
21
+ # yaml.load without an explicit safe loader.
22
+ YAML_LOAD = re.compile(r"\byaml\.load\s*\(")
23
+ YAML_SAFE = re.compile(r"Safe(?:C)?Loader|safe_load")
24
+ # A single-argument yaml.load(x) call — safe to mechanically rewrite. Anything
25
+ # with a second argument (e.g. an explicit Loader=) needs a human to check it.
26
+ YAML_LOAD_SIMPLE = re.compile(r"\byaml\.load\(([^,()]*)\)")
27
+ # Node insecure deserialization.
28
+ JS_UNSERIALIZE = re.compile(r"\b(?:node-serialize|serialize)\s*\.\s*unserialize\s*\(|\bunserialize\s*\(")
29
+
30
+
31
+ @register
32
+ class InsecureDeserialization(Rule):
33
+ id = "MCP009"
34
+ name = "Insecure deserialization"
35
+ severity = Severity.HIGH
36
+ owasp = "MCP05:2025" # Command Injection & Execution (unsafe deserialization -> RCE)
37
+
38
+ def check(self, files: List[FileInfo]) -> List[Finding]:
39
+ out: List[Finding] = []
40
+ for f in by_kind(files, "source"):
41
+ is_py = f.ext == ".py"
42
+ for i, line in enumerate(f.lines, start=1):
43
+ s = line.strip()
44
+ if s.startswith("#") or s.startswith("//"):
45
+ continue
46
+
47
+ hit = sev = None
48
+ if is_py and PICKLE.search(line):
49
+ hit = "pickle deserialization"
50
+ sev = Severity.CRITICAL
51
+ elif is_py and MARSHAL.search(line):
52
+ hit = "marshal deserialization"
53
+ sev = Severity.HIGH
54
+ elif is_py and YAML_LOAD.search(line) and not YAML_SAFE.search(line):
55
+ hit = "yaml.load without SafeLoader"
56
+ sev = Severity.HIGH
57
+ elif not is_py and JS_UNSERIALIZE.search(line):
58
+ hit = "node-serialize unserialize()"
59
+ sev = Severity.CRITICAL
60
+
61
+ if hit:
62
+ out.append(self.finding(
63
+ f, i, line,
64
+ title=f"Insecure deserialization: {hit}",
65
+ detail="Never deserialize untrusted input with these APIs. Use a safe "
66
+ "format (JSON) or a safe loader (yaml.safe_load) and validate "
67
+ "the schema.",
68
+ severity=sev,
69
+ ))
70
+ return out
71
+
72
+ def fix_line(self, line: str) -> Optional[Tuple[str, str]]:
73
+ if YAML_SAFE.search(line):
74
+ return None
75
+ m = YAML_LOAD_SIMPLE.search(line)
76
+ if not m:
77
+ return None
78
+ fixed = YAML_LOAD_SIMPLE.sub(r"yaml.safe_load(\1)", line, count=1)
79
+ return fixed, ("yaml.safe_load() only builds basic Python types (dict, list, str, "
80
+ "int...), so it can't be tricked into instantiating arbitrary "
81
+ "objects the way yaml.load() can.")
@@ -0,0 +1,103 @@
1
+ """MCP010 — disabled TLS verification.
2
+
3
+ An MCP server that turns off certificate verification will happily talk to a
4
+ man-in-the-middle. Tokens and tool output then leak to whoever sits on the wire.
5
+ We flag the usual ways people silence TLS checks.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from typing import List, Optional, Tuple
12
+
13
+ from ..findings import Finding, Severity
14
+ from ..loaders import FileInfo, by_kind
15
+ from .base import Rule, register
16
+
17
+ PY_INSECURE = re.compile(
18
+ r"verify\s*=\s*False"
19
+ r"|ssl\._create_unverified_context"
20
+ r"|ssl\.CERT_NONE"
21
+ r"|check_hostname\s*=\s*False",
22
+ )
23
+ JS_INSECURE = re.compile(
24
+ r"rejectUnauthorized\s*:\s*false"
25
+ r"|NODE_TLS_REJECT_UNAUTHORIZED\s*=\s*['\"]?0",
26
+ )
27
+
28
+ # --- fix_line helpers -------------------------------------------------------
29
+ # Each of these is a bare value/name swap with no argument restructuring, so
30
+ # it can't change what the surrounding call actually does besides re-enabling
31
+ # the check that was turned off.
32
+ _UNVERIFIED_CTX = re.compile(r"ssl\._create_unverified_context\s*\(\s*\)")
33
+ _CERT_NONE = re.compile(r"\bssl\.CERT_NONE\b")
34
+ _REJECT_UNAUTH_FALSE = re.compile(r"rejectUnauthorized\s*:\s*false")
35
+ _NODE_TLS_ENV = re.compile(r"(NODE_TLS_REJECT_UNAUTHORIZED\s*=\s*)(['\"]?)0\2")
36
+
37
+
38
+ def _drop_false_kwarg(line: str, name: str) -> Optional[str]:
39
+ """Remove a `, name=False` / `name=False, ` / bare `name=False` kwarg.
40
+
41
+ Tries the leading-comma form first since the disabled check is rarely the
42
+ first argument in a real call (e.g. `requests.get(url, verify=False)`).
43
+ """
44
+ patterns = [
45
+ rf"\s*,\s*{name}\s*=\s*False\b",
46
+ rf"\b{name}\s*=\s*False\s*,\s*",
47
+ rf"\b{name}\s*=\s*False\b",
48
+ ]
49
+ for pat in patterns:
50
+ fixed, n = re.subn(pat, "", line, count=1)
51
+ if n:
52
+ return fixed
53
+ return None
54
+
55
+
56
+ @register
57
+ class InsecureTransport(Rule):
58
+ id = "MCP010"
59
+ name = "Disabled TLS verification"
60
+ severity = Severity.HIGH
61
+ owasp = "MCP07:2025" # Insufficient Authentication & Authorization (server identity check)
62
+
63
+ def check(self, files: List[FileInfo]) -> List[Finding]:
64
+ out: List[Finding] = []
65
+ for f in by_kind(files, "source", "config", "manifest"):
66
+ pat = PY_INSECURE if f.ext == ".py" else JS_INSECURE
67
+ for i, line in enumerate(f.lines, start=1):
68
+ s = line.strip()
69
+ if s.startswith("#") or s.startswith("//"):
70
+ continue
71
+ if pat.search(line):
72
+ out.append(self.finding(
73
+ f, i, line,
74
+ title="TLS certificate verification disabled",
75
+ detail="Disabling verification exposes the connection to "
76
+ "man-in-the-middle attacks. Keep verification on and trust a "
77
+ "proper CA instead.",
78
+ ))
79
+ return out
80
+
81
+ def fix_line(self, line: str) -> Optional[Tuple[str, str]]:
82
+ if _UNVERIFIED_CTX.search(line):
83
+ fixed = _UNVERIFIED_CTX.sub("ssl.create_default_context()", line)
84
+ return fixed, ("create_default_context() verifies certificates against the "
85
+ "system trust store instead of accepting anything.")
86
+ if _CERT_NONE.search(line):
87
+ fixed = _CERT_NONE.sub("ssl.CERT_REQUIRED", line)
88
+ return fixed, "CERT_REQUIRED makes the handshake fail on an invalid certificate."
89
+ if _REJECT_UNAUTH_FALSE.search(line):
90
+ fixed = _REJECT_UNAUTH_FALSE.sub("rejectUnauthorized: true", line)
91
+ return fixed, "rejectUnauthorized: true restores certificate validation."
92
+ if _NODE_TLS_ENV.search(line):
93
+ fixed = _NODE_TLS_ENV.sub(lambda m: f"{m.group(1)}{m.group(2)}1{m.group(2)}", line)
94
+ return fixed, ("NODE_TLS_REJECT_UNAUTHORIZED=1 is the default, safe setting; "
95
+ "=0 disables TLS verification for the whole process.")
96
+ fixed = _drop_false_kwarg(line, "verify")
97
+ if fixed is not None:
98
+ return fixed, "Dropping verify=False restores the library default (verify=True)."
99
+ fixed = _drop_false_kwarg(line, "check_hostname")
100
+ if fixed is not None:
101
+ return fixed, ("Dropping check_hostname=False restores hostname verification "
102
+ "(the default).")
103
+ return None
@@ -0,0 +1,126 @@
1
+ """MCP022 — a server bound to loopback only still accepts cross-origin
2
+ requests, because it never checks the `Origin` header.
3
+
4
+ Binding to `127.0.0.1`/`localhost` is often treated as equivalent to
5
+ "unreachable by web content." It isn't: any browser tab open on the same
6
+ machine can still reach a loopback-bound HTTP or WebSocket server via CORS
7
+ or an unauthenticated WebSocket upgrade, unless the server explicitly
8
+ checks the `Origin` header. This exact pattern has now surfaced three times
9
+ independently: Ollama's long-known default-CORS behavior, BraveMCP's own
10
+ HTTP bridge before it was fixed 2026-07-13 (v0.2.0) — its own release notes
11
+ at the time called the bug out as generalizing to "a lot of local-AI-tool
12
+ bridges," not just BraveMCP — and Cline's Hub dashboard WebSocket, still
13
+ open today, which accepts unauthenticated `desktopCommand` frames from any
14
+ page open in the same browser when its `ROOM_SECRET` is left at its empty
15
+ default. See `research/2026-08-03.md`'s top compounding opportunity.
16
+
17
+ Two co-occurring conditions in the same file, both required:
18
+
19
+ 1. A bind call explicitly scoped to loopback only (`127.0.0.1` or
20
+ `localhost`) — the "looks safe" case MCP018 (bind-*all*) doesn't cover.
21
+ 2. Either:
22
+ - a permissive CORS setup: an Express/Connect `cors()` call with no
23
+ options argument, a bare Flask-CORS `CORS(app)` call with no
24
+ `origins=`/`resources=` restriction, or an unconditional wildcard
25
+ `Access-Control-Allow-Origin: *` header; or
26
+ - a WebSocket connection handler (`.on('connection', ...)`) with no
27
+ `Origin` check anywhere in the handler window.
28
+
29
+ Deliberately conservative, matching the rest of mcpscan's "high signal over
30
+ recall" design: this only fires on a server that is explicitly, visibly
31
+ loopback-bound (not bind-all — that's MCP018) and demonstrably skips the
32
+ one check that actually matters for a same-machine browser tab.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import re
38
+ from typing import List
39
+
40
+ from ..findings import Finding, Severity
41
+ from ..loaders import FileInfo, by_kind
42
+ from .base import Rule, register
43
+
44
+ _SOURCE_EXTS = {".py", ".js", ".ts", ".mjs", ".cjs", ".tsx", ".jsx"}
45
+ _JS_EXTS = {".js", ".ts", ".mjs", ".cjs", ".tsx", ".jsx"}
46
+
47
+ # A bind call explicitly scoped to loopback only.
48
+ _LOOPBACK_BIND_RE = re.compile(
49
+ r"host['\"]?\s*[:=]\s*['\"](?:127\.0\.0\.1|localhost)['\"]" # Flask/uvicorn host=, JS {host: ...}
50
+ r"|\.listen\s*\(\s*[\w.]+\s*,\s*['\"](?:127\.0\.0\.1|localhost)['\"]" # Node .listen(port, host)
51
+ r"|serve\s*\(\s*[\w.]+\s*,\s*['\"](?:127\.0\.0\.1|localhost)['\"]" # Python websockets.serve(handler, host, ...)
52
+ )
53
+
54
+ # A permissive CORS setup with no origin restriction at all.
55
+ _PERMISSIVE_CORS_RE = re.compile(
56
+ r"\bcors\s*\(\s*\)" # Express cors() — defaults to '*'
57
+ r"|\bCORS\s*\(\s*\w+\s*\)" # Flask-CORS CORS(app) bare
58
+ r"|Access-Control-Allow-Origin['\"]?\s*[,:]\s*['\"]\*['\"]" # literal wildcard header
59
+ )
60
+
61
+ # A WebSocket connection handler registration (JS ecosystem: ws, socket.io, uWebSockets...).
62
+ _WS_CONNECTION_RE = re.compile(r"\.on\s*\(\s*['\"]connection['\"]")
63
+
64
+ # Anything in the handler window that looks like it inspects the Origin header.
65
+ _ORIGIN_CHECK_RE = re.compile(r"origin", re.IGNORECASE)
66
+
67
+ _WINDOW = 20
68
+
69
+
70
+ @register
71
+ class LoopbackBridgeNoOriginCheck(Rule):
72
+ id = "MCP022"
73
+ name = "Loopback-bound server accepts cross-origin requests with no Origin check"
74
+ severity = Severity.HIGH
75
+ owasp = "MCP07:2025" # Insufficient Authentication & Authorization
76
+
77
+ def check(self, files: List[FileInfo]) -> List[Finding]:
78
+ out: List[Finding] = []
79
+ for f in by_kind(files, "source", "manifest"):
80
+ if f.ext not in _SOURCE_EXTS:
81
+ continue
82
+ if not _LOOPBACK_BIND_RE.search(f.text):
83
+ continue
84
+
85
+ lines = f.lines
86
+
87
+ for i, line in enumerate(lines, start=1):
88
+ if _PERMISSIVE_CORS_RE.search(line):
89
+ out.append(self.finding(
90
+ f, i, line,
91
+ title="Loopback-bound server has a permissive CORS setup",
92
+ detail=(
93
+ "This server binds to 127.0.0.1/localhost only, which is "
94
+ "commonly (wrongly) treated as 'unreachable from the web'. "
95
+ "Any browser tab open on the same machine can still reach it "
96
+ "unless the Origin header is checked — this is the exact bug "
97
+ "class BraveMCP's own HTTP bridge shipped and fixed in v0.2.0 "
98
+ "(2026-07-13), and that Cline's Hub dashboard currently has "
99
+ "open. Restrict allowed origins explicitly instead of "
100
+ "defaulting to '*'."
101
+ ),
102
+ ))
103
+
104
+ if f.ext in _JS_EXTS:
105
+ n = len(lines)
106
+ for i, line in enumerate(lines):
107
+ if not _WS_CONNECTION_RE.search(line):
108
+ continue
109
+ window_text = "\n".join(lines[i:min(i + _WINDOW, n)])
110
+ if _ORIGIN_CHECK_RE.search(window_text):
111
+ continue
112
+ out.append(self.finding(
113
+ f, i + 1, line,
114
+ title="Loopback-bound WebSocket accepts connections with no Origin check",
115
+ detail=(
116
+ "This WebSocket server binds to 127.0.0.1/localhost only, but "
117
+ "the connection handler never checks the Origin header before "
118
+ "accepting the upgrade. Any page open in the same browser can "
119
+ "connect and send frames — the same gap behind Cline's "
120
+ "currently-open Hub dashboard bug, where an unset ROOM_SECRET "
121
+ "lets any local webpage send desktopCommand frames. Validate "
122
+ "the Origin header (or an equivalent per-connection secret) "
123
+ "before accepting the upgrade."
124
+ ),
125
+ ))
126
+ return out
@@ -0,0 +1,57 @@
1
+ """MCP007 — path traversal in file-reading tools.
2
+
3
+ A tool that opens a path built from its arguments lets a caller walk out of the
4
+ intended directory (``../../etc/passwd``) and read arbitrary files. We flag file
5
+ reads whose path is interpolated/concatenated rather than a constant literal.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from typing import List
12
+
13
+ from ..findings import Finding, Severity
14
+ from ..loaders import FileInfo, by_kind
15
+ from .base import Rule, register
16
+
17
+ # File-open sinks.
18
+ PY_OPEN = re.compile(
19
+ r"\bopen\s*\(|\.read_text\s*\(|\.read_bytes\s*\(|send_file\s*\(|FileResponse\s*\(",
20
+ )
21
+ JS_OPEN = re.compile(
22
+ r"\bfs\.(?:readFile|readFileSync|createReadStream)\s*\(|\breadFile(?:Sync)?\s*\(",
23
+ )
24
+ # Path is dynamically built (concat / f-string / template / join with a var).
25
+ INTERP = re.compile(r"`[^`]*\$\{|\+\s*\w|f['\"]|\.format\(|os\.path\.join\([^)]*\b\w")
26
+ # Explicit traversal token sitting in a literal.
27
+ TRAVERSAL = re.compile(r"\.\./|\.\.\\")
28
+
29
+
30
+ @register
31
+ class PathTraversal(Rule):
32
+ id = "MCP007"
33
+ name = "Path traversal in file tool"
34
+ severity = Severity.MEDIUM
35
+ owasp = "MCP05:2025" # Command Injection & Execution (untrusted-input-driven action)
36
+
37
+ def check(self, files: List[FileInfo]) -> List[Finding]:
38
+ out: List[Finding] = []
39
+ for f in by_kind(files, "source"):
40
+ is_py = f.ext == ".py"
41
+ sink = PY_OPEN if is_py else JS_OPEN
42
+ for i, line in enumerate(f.lines, start=1):
43
+ s = line.strip()
44
+ if s.startswith("#") or s.startswith("//"):
45
+ continue
46
+ if not sink.search(line):
47
+ continue
48
+ if INTERP.search(line):
49
+ sev = Severity.HIGH if TRAVERSAL.search(line) else Severity.MEDIUM
50
+ out.append(self.finding(
51
+ f, i, line,
52
+ title="File path built from untrusted input",
53
+ detail="Resolve the path and confirm it stays within an allowed base "
54
+ "directory (e.g. os.path.realpath + prefix check) before opening.",
55
+ severity=sev,
56
+ ))
57
+ return out
@@ -0,0 +1,69 @@
1
+ """MCP004 — over-broad permissions in Claude Code / MCP configuration.
2
+
3
+ A repo can ship a `.claude/settings.json` that pre-grants sweeping permissions, so
4
+ that once you trust the project the agent can run anything without prompting. We
5
+ flag wildcard allow-rules and permission-bypassing modes.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from typing import List
12
+
13
+ from ..findings import Finding, Severity
14
+ from ..loaders import FileInfo, by_kind
15
+ from .base import Rule, deny_block_lines, register
16
+
17
+ # Wildcard tool grants: Bash(*), Bash(*:*), Write(*), or a bare "*" entry.
18
+ WILDCARD_RULE = re.compile(
19
+ r'"\s*(?:Bash|Write|Edit|WebFetch|Read)\s*\(\s*\*',
20
+ re.IGNORECASE,
21
+ )
22
+ BARE_WILDCARD = re.compile(r'^\s*"\*"\s*,?\s*$')
23
+ # Permission bypass / auto-accept everything.
24
+ BYPASS_MODE = re.compile(
25
+ r'"defaultMode"\s*:\s*"(?:bypassPermissions|acceptEdits)"'
26
+ r'|dangerouslySkipPermissions\s*:\s*true'
27
+ r'|--dangerously-skip-permissions'
28
+ r'|"autoApprove"\s*:\s*true',
29
+ re.IGNORECASE,
30
+ )
31
+
32
+
33
+ @register
34
+ class OverBroadPermissions(Rule):
35
+ id = "MCP004"
36
+ name = "Over-broad permissions"
37
+ severity = Severity.HIGH
38
+ owasp = "MCP02:2025" # Privilege Escalation via Scope Creep
39
+
40
+ def check(self, files: List[FileInfo]) -> List[Finding]:
41
+ out: List[Finding] = []
42
+ candidates = [f for f in by_kind(files, "config", "manifest")
43
+ if f.in_dot_claude or "permission" in f.text.lower()
44
+ or "defaultMode" in f.text or f.name.endswith(".json")]
45
+ # Wildcards inside a "deny" block are good practice, not a finding.
46
+ for f in candidates:
47
+ deny_lines = deny_block_lines(f.lines)
48
+ for i, line in enumerate(f.lines, start=1):
49
+ if BYPASS_MODE.search(line):
50
+ out.append(self.finding(
51
+ f, i, line,
52
+ title="Permission prompts disabled",
53
+ detail="bypassPermissions / acceptEdits / autoApprove lets the agent "
54
+ "act without asking. Shipping this in a repo is a red flag.",
55
+ severity=Severity.CRITICAL,
56
+ ))
57
+ continue
58
+
59
+ if i in deny_lines:
60
+ continue # wildcards inside deny[] are fine
61
+
62
+ if WILDCARD_RULE.search(line) or BARE_WILDCARD.match(line):
63
+ out.append(self.finding(
64
+ f, i, line,
65
+ title="Wildcard permission grant",
66
+ detail="A wildcard allow-rule (e.g. Bash(*) or \"*\") grants the agent "
67
+ "blanket access. Scope permissions to specific commands/paths.",
68
+ ))
69
+ return out
@@ -0,0 +1,99 @@
1
+ """MCP006 — known-vulnerable MCP SDK versions.
2
+
3
+ A systemic RCE was disclosed across MCP SDK implementations in 2026. This rule
4
+ reads dependency declarations and flags SDK versions below the patched baseline.
5
+ It deliberately uses a small, conservative table — extend `KNOWN_BAD` as advisories
6
+ land.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from typing import List, Tuple
13
+
14
+ from ..findings import Finding, Severity
15
+ from ..loaders import FileInfo, by_kind
16
+ from .base import Rule, register
17
+
18
+ # package name -> (first patched version, advisory note)
19
+ # Audited 2026-07-06 against the GitHub Advisory Database — each baseline is the
20
+ # highest first-patched version among that package's disclosed CVEs, so a version
21
+ # below it may still carry an earlier, already-superseded advisory too.
22
+ KNOWN_BAD = {
23
+ # CVE-2026-25536 (GHSA-345p-7cg4-v4c7): cross-client data leak via shared
24
+ # transport/server reuse, patched 1.26.0. Supersedes the 1.12.0 stdio RCE
25
+ # baseline and the 1.25.2 ReDoS fix (CVE-2026-0621).
26
+ "@modelcontextprotocol/sdk": (
27
+ "1.26.0",
28
+ "CVE-2026-25536: cross-client data leak via shared transport/server reuse "
29
+ "(also fixes the CVE-2026-0621 UriTemplate ReDoS)",
30
+ ),
31
+ # CVE-2025-66416 (GHSA-9h52-p55h-vw2f): no DNS-rebinding protection by
32
+ # default on localhost HTTP servers, patched 1.23.0. Supersedes the 1.9.0
33
+ # message-handling RCE baseline and the 1.9.4 malformed-request DoS fix
34
+ # (CVE-2025-53366).
35
+ "mcp": (
36
+ "1.23.0",
37
+ "CVE-2025-66416: no DNS-rebinding protection by default for localhost "
38
+ "HTTP servers (also fixes the CVE-2025-53366 malformed-request DoS)",
39
+ ),
40
+ # GHSA-vv7q-7jx5-f767 (critical, CVSS 10.0): OpenAPIProvider path params
41
+ # substituted into URLs unescaped, allowing path traversal out of the
42
+ # intended API prefix (authenticated SSRF). Patched 3.2.0, alongside the
43
+ # OAuth confused-deputy (CVE-2026-27124) and Windows install command
44
+ # injection (GHSA-m8x7-r2rg-vh5g) advisories in the same release line.
45
+ # Supersedes the 2.3.0 tool-dispatch baseline and the 2.14.2 OAuth
46
+ # token-audience fix (CVE-2025-69196).
47
+ "fastmcp": (
48
+ "3.2.0",
49
+ "GHSA-vv7q-7jx5-f767: unescaped path params in OpenAPIProvider enable "
50
+ "path traversal / authenticated SSRF (also fixes the CVE-2026-27124 OAuth "
51
+ "confused-deputy and GHSA-m8x7-r2rg-vh5g Windows install command injection)",
52
+ ),
53
+ }
54
+
55
+ # Matches: "@modelcontextprotocol/sdk": "^1.4.2" or mcp==1.2.0 or mcp>=1.0
56
+ DEP_LINE = re.compile(
57
+ r'["\']?(@?[\w./-]+)["\']?\s*'
58
+ r'(?:[:=]\s*["\']?|==|>=|~=|\^|~)\s*'
59
+ r'[\^~>=]*\s*(\d+\.\d+(?:\.\d+)?)'
60
+ )
61
+
62
+
63
+ def _cmp(a: str, b: str) -> int:
64
+ """Return -1/0/1 comparing dotted version strings."""
65
+ pa = [int(x) for x in a.split(".")]
66
+ pb = [int(x) for x in b.split(".")]
67
+ while len(pa) < len(pb): pa.append(0)
68
+ while len(pb) < len(pa): pb.append(0)
69
+ return (pa > pb) - (pa < pb)
70
+
71
+
72
+ @register
73
+ class VulnerableSDK(Rule):
74
+ id = "MCP006"
75
+ name = "Vulnerable MCP SDK version"
76
+ severity = Severity.HIGH
77
+ owasp = "MCP04:2025" # Software Supply Chain Attacks & Dependency Tampering
78
+
79
+ def check(self, files: List[FileInfo]) -> List[Finding]:
80
+ out: List[Finding] = []
81
+ for f in by_kind(files, "manifest", "config"):
82
+ if f.name not in {"package.json", "pyproject.toml", "requirements.txt", "mcp.json"}:
83
+ continue
84
+ for i, line in enumerate(f.lines, start=1):
85
+ m = DEP_LINE.search(line)
86
+ if not m:
87
+ continue
88
+ pkg, ver = m.group(1), m.group(2)
89
+ info: "Tuple[str, str] | None" = KNOWN_BAD.get(pkg)
90
+ if not info:
91
+ continue
92
+ patched, note = info
93
+ if _cmp(ver, patched) < 0:
94
+ out.append(self.finding(
95
+ f, i, line,
96
+ title=f"{pkg} {ver} is vulnerable (< {patched})",
97
+ detail=f"{note}. Upgrade to >= {patched}.",
98
+ ))
99
+ return out
@@ -0,0 +1,82 @@
1
+ """MCP005 — secrets committed into MCP / Claude config.
2
+
3
+ MCP servers are often configured with `env` blocks that people fill in with real
4
+ keys and then commit. We flag high-confidence token shapes and obvious
5
+ KEY=secret assignments in config and manifest files.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from typing import List, Tuple
12
+
13
+ from ..findings import Finding, Severity
14
+ from ..loaders import FileInfo
15
+ from .base import Rule, register
16
+
17
+ # (label, pattern) — high-signal token formats.
18
+ TOKEN_PATTERNS: List[Tuple[str, "re.Pattern[str]"]] = [
19
+ ("Anthropic API key", re.compile(r"sk-ant-[A-Za-z0-9_\-]{20,}")),
20
+ ("OpenAI API key", re.compile(r"sk-(?:proj-)?[A-Za-z0-9]{32,}")),
21
+ ("GitHub token", re.compile(r"gh[pousr]_[A-Za-z0-9]{30,}")),
22
+ ("AWS access key id", re.compile(r"AKIA[0-9A-Z]{16}")),
23
+ ("Slack token", re.compile(r"xox[baprs]-[A-Za-z0-9-]{10,}")),
24
+ ("Google API key", re.compile(r"AIza[0-9A-Za-z_\-]{35}")),
25
+ ("Private key block", re.compile(r"-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----")),
26
+ ]
27
+
28
+ # Generic KEY = "value" assignments where the name screams secret.
29
+ ASSIGN = re.compile(
30
+ r"(?i)\b([A-Z0-9_]*(?:SECRET|TOKEN|PASSWORD|PASSWD|API[_-]?KEY|ACCESS[_-]?KEY)[A-Z0-9_]*)\b"
31
+ r"\s*[:=]\s*['\"]([^'\"]{8,})['\"]"
32
+ )
33
+ # Obvious placeholders we should NOT flag.
34
+ PLACEHOLDER = re.compile(
35
+ r"(?i)\b(your|example|changeme|placeholder|xxx+|<[^>]+>|\.\.\.|todo|dummy|test[_-]?key)\b"
36
+ r"|^\$\{|^\{\{"
37
+ )
38
+
39
+
40
+ @register
41
+ class LeakedSecrets(Rule):
42
+ id = "MCP005"
43
+ name = "Leaked secret in config"
44
+ severity = Severity.HIGH
45
+ owasp = "MCP01:2025" # Token Mismanagement & Secret Exposure
46
+
47
+ def check(self, files: List[FileInfo]) -> List[Finding]:
48
+ out: List[Finding] = []
49
+ for f in files:
50
+ if f.kind not in ("config", "manifest", "source"):
51
+ continue
52
+ for i, line in enumerate(f.lines, start=1):
53
+ for label, pat in TOKEN_PATTERNS:
54
+ if pat.search(line):
55
+ out.append(self.finding(
56
+ f, i, self._redact(line),
57
+ title=f"Committed secret: {label}",
58
+ detail="Rotate this credential and load it from the environment "
59
+ "instead of committing it.",
60
+ severity=Severity.CRITICAL,
61
+ ))
62
+ break
63
+ else:
64
+ m = ASSIGN.search(line)
65
+ if m and not PLACEHOLDER.search(m.group(2)):
66
+ out.append(self.finding(
67
+ f, i, self._redact(line),
68
+ title=f"Hardcoded secret in '{m.group(1)}'",
69
+ detail="Looks like a real credential assigned inline. Move it to an "
70
+ "env var / secret store.",
71
+ ))
72
+ return out
73
+
74
+ @staticmethod
75
+ def _redact(line: str) -> str:
76
+ # Keep enough to locate, hide the secret body.
77
+ def hide(m: "re.Match") -> str:
78
+ s = m.group(0)
79
+ return s[:6] + "...REDACTED..." + s[-2:] if len(s) > 12 else "...REDACTED..."
80
+ for _, pat in TOKEN_PATTERNS:
81
+ line = pat.sub(hide, line)
82
+ return line
mcpscan/rules/ssrf.py ADDED
@@ -0,0 +1,57 @@
1
+ """MCP008 — server-side request forgery (SSRF) in fetch tools.
2
+
3
+ A tool that fetches a URL assembled from its arguments can be steered at internal
4
+ metadata endpoints (169.254.169.254), localhost services, or arbitrary hosts. We
5
+ flag outbound HTTP calls whose URL is interpolated from input.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from typing import List
12
+
13
+ from ..findings import Finding, Severity
14
+ from ..loaders import FileInfo, by_kind
15
+ from .base import Rule, register
16
+
17
+ PY_FETCH = re.compile(
18
+ r"\brequests\.(?:get|post|put|patch|delete|head|request)\s*\("
19
+ r"|\burllib\.request\.urlopen\s*\("
20
+ r"|\bhttpx\.(?:get|post|put|patch|delete|stream|Client)\s*\("
21
+ r"|\baiohttp\b[^\n]*\.(?:get|post|request)\s*\(",
22
+ )
23
+ JS_FETCH = re.compile(
24
+ r"\bfetch\s*\(|\baxios(?:\.(?:get|post|put|patch|delete|request))?\s*\("
25
+ r"|\b(?:https?)\.(?:get|request)\s*\(|\bgot\s*\(",
26
+ )
27
+ INTERP = re.compile(r"`[^`]*\$\{|\+\s*\w|f['\"]|\.format\(|%\s*\(")
28
+ # A literal-looking URL argument (constant) is much lower risk.
29
+ HAS_INTERP_URL = re.compile(r"\(\s*(?:f?['\"`])?[^)]*(?:\$\{|\+\s*\w|f['\"]|\{\})")
30
+
31
+
32
+ @register
33
+ class SSRF(Rule):
34
+ id = "MCP008"
35
+ name = "SSRF in fetch tool"
36
+ severity = Severity.MEDIUM
37
+ owasp = "MCP05:2025" # Command Injection & Execution (untrusted-input-driven action)
38
+
39
+ def check(self, files: List[FileInfo]) -> List[Finding]:
40
+ out: List[Finding] = []
41
+ for f in by_kind(files, "source"):
42
+ is_py = f.ext == ".py"
43
+ sink = PY_FETCH if is_py else JS_FETCH
44
+ for i, line in enumerate(f.lines, start=1):
45
+ s = line.strip()
46
+ if s.startswith("#") or s.startswith("//"):
47
+ continue
48
+ if sink.search(line) and INTERP.search(line):
49
+ out.append(self.finding(
50
+ f, i, line,
51
+ title="Outbound request to a URL built from input",
52
+ detail="Validate the host against an allowlist and block link-local / "
53
+ "private ranges (169.254.169.254, 127.0.0.0/8, 10/8) to prevent "
54
+ "SSRF against cloud metadata and internal services.",
55
+ severity=Severity.HIGH if "169.254" in line else Severity.MEDIUM,
56
+ ))
57
+ return out