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,105 @@
1
+ """MCP012 — remote MCP servers with no authentication or a hardcoded static token.
2
+
3
+ Remote (HTTP/SSE) MCP server entries are reachable over the network, so they need
4
+ some credential to stop anyone who can reach the URL from calling their tools.
5
+ Two patterns get flagged:
6
+
7
+ 1. A remote server entry with no auth-bearing header/field at all.
8
+ 2. A bearer token or API key hardcoded as a literal string in a header instead
9
+ of being pulled from the environment (`${TOKEN}` / `$TOKEN`).
10
+
11
+ Local, command/stdio-launched servers are out of scope — they inherit the
12
+ caller's own OS-level permissions and don't need a network credential.
13
+
14
+ 2026 field data puts no-auth and static-token MCP deployments at 60-90% of
15
+ real installs, well ahead of tool-poisoning-style findings — see
16
+ `research/2026-07-03.md`.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import re
23
+ from typing import Any, Dict, Iterator, List, Tuple
24
+
25
+ from ..findings import Finding, Severity
26
+ from ..loaders import FileInfo
27
+ from .base import Rule, register
28
+
29
+ _SERVER_KEYS = ("mcpServers", "servers", "mcp_servers")
30
+ _URL_KEYS = ("url", "serverUrl", "endpoint")
31
+ _AUTH_HEADER_NAMES = {"authorization", "x-api-key", "api-key", "apikey", "x-auth-token", "auth-token"}
32
+
33
+ # A value that's an environment reference, not a literal secret.
34
+ ENV_INTERPOLATION = re.compile(r"^\$\{[^}]+\}$|^\$[A-Za-z_][A-Za-z0-9_]*$")
35
+ # Looks like a real token/key rather than a short placeholder word.
36
+ STATIC_TOKEN_SHAPE = re.compile(r"^(Bearer\s+)?[A-Za-z0-9_\-.]{16,}$")
37
+
38
+
39
+ def _iter_server_entries(data: Any) -> Iterator[Tuple[str, Dict]]:
40
+ if not isinstance(data, dict):
41
+ return
42
+ for key in _SERVER_KEYS:
43
+ servers = data.get(key)
44
+ if isinstance(servers, dict):
45
+ for name, cfg in servers.items():
46
+ if isinstance(cfg, dict):
47
+ yield name, cfg
48
+
49
+
50
+ @register
51
+ class AuthGaps(Rule):
52
+ id = "MCP012"
53
+ name = "MCP server with no auth or a hardcoded static token"
54
+ severity = Severity.HIGH
55
+ owasp = "MCP07:2025" # Insufficient Authentication & Authorization
56
+
57
+ def check(self, files: List[FileInfo]) -> List[Finding]:
58
+ out: List[Finding] = []
59
+ for f in files:
60
+ if f.ext != ".json":
61
+ continue
62
+ try:
63
+ data = json.loads(f.text)
64
+ except (ValueError, TypeError):
65
+ continue
66
+
67
+ for name, cfg in _iter_server_entries(data):
68
+ url = next((cfg.get(k) for k in _URL_KEYS if isinstance(cfg.get(k), str)), None)
69
+ if not url or not url.startswith(("http://", "https://")):
70
+ continue # local/stdio server: not this rule's concern
71
+
72
+ headers = cfg.get("headers") if isinstance(cfg.get("headers"), dict) else {}
73
+ auth_value = next(
74
+ (v for k, v in headers.items() if k.lower() in _AUTH_HEADER_NAMES), None
75
+ )
76
+ line = self._line_for(f, name)
77
+
78
+ if auth_value is None:
79
+ out.append(self.finding(
80
+ f, line, f'"{name}": {{"url": "{url}"}}',
81
+ title=f"Remote MCP server '{name}' has no authentication",
82
+ detail="This server is reachable over the network with no "
83
+ "Authorization / API-key header configured — anyone who can "
84
+ "reach the URL can call its tools.",
85
+ ))
86
+ elif (isinstance(auth_value, str)
87
+ and not ENV_INTERPOLATION.match(auth_value.strip())
88
+ and STATIC_TOKEN_SHAPE.match(auth_value.strip())):
89
+ out.append(self.finding(
90
+ f, line, f'"{name}" auth header hardcodes a literal token',
91
+ title=f"Static long-lived token hardcoded for '{name}'",
92
+ detail="The auth header is a literal token instead of an environment "
93
+ "reference (e.g. ${TOKEN}) — it can't be rotated without editing "
94
+ "this file, and leaks if the file is shared or committed.",
95
+ severity=Severity.MEDIUM,
96
+ ))
97
+ return out
98
+
99
+ @staticmethod
100
+ def _line_for(f: FileInfo, server_name: str) -> int:
101
+ needle = f'"{server_name}"'
102
+ for i, line in enumerate(f.lines, start=1):
103
+ if needle in line:
104
+ return i
105
+ return 0
mcpscan/rules/base.py ADDED
@@ -0,0 +1,102 @@
1
+ """Rule base class, a registry, and shared regex-scanning helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Callable, List, Optional, Pattern, Tuple
7
+
8
+ from ..findings import Finding, Severity
9
+ from ..loaders import FileInfo
10
+
11
+ # Populated by @register; the scanner iterates over this.
12
+ REGISTRY: "List[Rule]" = []
13
+
14
+
15
+ class Rule:
16
+ """A single detector. Subclasses implement :meth:`check`."""
17
+
18
+ id: str = "MCP000"
19
+ name: str = "unnamed rule"
20
+ severity: Severity = Severity.MEDIUM
21
+ owasp: str = "" # OWASP MCP Top 10 (2025) category id, e.g. "MCP05:2025"
22
+
23
+ def check(self, files: List[FileInfo]) -> List[Finding]: # pragma: no cover
24
+ raise NotImplementedError
25
+
26
+ def fix_line(self, line: str) -> Optional[Tuple[str, str]]:
27
+ """Return `(fixed_line, explanation)` if *line* can be mechanically repaired.
28
+
29
+ Default: not fixable. Only override this for a substitution confident
30
+ enough that it can't be the wrong call — e.g. swapping `yaml.load` for
31
+ `yaml.safe_load`. Fixes that require choosing new argument values or
32
+ restructuring a call (like turning a shell string into an argv list for
33
+ `shell=True`) belong in a human's hands, not `--fix`.
34
+ """
35
+ return None
36
+
37
+ # --- helpers shared by most rules -------------------------------------
38
+
39
+ def finding(self, f: FileInfo, line: int, snippet: str, *,
40
+ title: str = "", detail: str = "",
41
+ severity: "Severity | None" = None) -> Finding:
42
+ return Finding(
43
+ rule_id=self.id,
44
+ title=title or self.name,
45
+ severity=severity or self.severity,
46
+ path=f.relpath,
47
+ line=line,
48
+ detail=detail,
49
+ snippet=snippet.strip()[:200],
50
+ owasp=self.owasp,
51
+ )
52
+
53
+ def scan_lines(self, f: FileInfo, pattern: Pattern[str], *,
54
+ title: str = "", detail: str = "",
55
+ severity: "Severity | None" = None,
56
+ predicate: "Callable[[re.Match], bool] | None" = None
57
+ ) -> List[Finding]:
58
+ """Yield a finding for every line in *f* matching *pattern*."""
59
+ out: List[Finding] = []
60
+ for i, line in enumerate(f.lines, start=1):
61
+ m = pattern.search(line)
62
+ if not m:
63
+ continue
64
+ if predicate and not predicate(m):
65
+ continue
66
+ out.append(self.finding(f, i, line, title=title,
67
+ detail=detail, severity=severity))
68
+ return out
69
+
70
+
71
+ def register(cls):
72
+ """Class decorator that adds a rule instance to the registry."""
73
+ REGISTRY.append(cls())
74
+ return cls
75
+
76
+
77
+ def compile_any(*patterns: str, flags: int = re.IGNORECASE) -> Pattern[str]:
78
+ """Compile an alternation of patterns into one regex."""
79
+ return re.compile("|".join(f"(?:{p})" for p in patterns), flags)
80
+
81
+
82
+ def deny_block_lines(lines: List[str]) -> "set[int]":
83
+ """Return the 1-based line numbers that fall inside a `"deny": [...]` array.
84
+
85
+ Tracks bracket depth from the `"deny"` key onward so multi-line deny lists
86
+ are fully covered, not just the one or two lines after the key. Wildcards
87
+ that a config explicitly *denies* are good practice, not a finding.
88
+ """
89
+ out: "set[int]" = set()
90
+ active = False
91
+ depth = 0
92
+ for i, line in enumerate(lines, start=1):
93
+ if not active and '"deny"' in line.lower():
94
+ active = True
95
+ depth = 0
96
+ if not active:
97
+ continue
98
+ depth += line.count("[") - line.count("]")
99
+ out.add(i)
100
+ if depth <= 0:
101
+ active = False
102
+ return out
@@ -0,0 +1,78 @@
1
+ """MCP001 — command injection sinks in MCP server source.
2
+
3
+ ~43% of MCP CVEs in early 2026 were command-injection patterns. We flag shell
4
+ execution that is reachable from tool handlers, prioritising calls that look like
5
+ they interpolate untrusted 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
+ # Python sinks that ALWAYS spawn a shell, so a built command string is injectable.
18
+ PY_SINKS = re.compile(r"\b(os\.system|os\.popen)\b", re.IGNORECASE)
19
+ # subprocess.* is only injectable when shell=True (otherwise the argv is literal).
20
+ PY_SHELL_TRUE = re.compile(r"shell\s*=\s*True")
21
+
22
+ # Node/TS sinks.
23
+ JS_SINKS = re.compile(
24
+ r"\b(child_process\.)?(execSync|exec|spawnSync|spawn)\s*\(",
25
+ )
26
+
27
+ # Heuristic that the command string is dynamically built (interpolation /
28
+ # concatenation / f-string) rather than a constant literal.
29
+ INTERP = re.compile(r"`[^`]*\$\{|\+\s*\w|%\s*\(|\.format\(|f['\"]|\$\{")
30
+
31
+ # eval-family — always suspicious in a tool handler.
32
+ EVAL = re.compile(r"\beval\s*\(|\bexec\s*\(|\bFunction\s*\(")
33
+
34
+
35
+ @register
36
+ class CommandInjection(Rule):
37
+ id = "MCP001"
38
+ name = "Potential command injection"
39
+ severity = Severity.HIGH
40
+ owasp = "MCP05:2025" # Command Injection & Execution
41
+
42
+ def check(self, files: List[FileInfo]) -> List[Finding]:
43
+ out = []
44
+ for f in by_kind(files, "source", "manifest"):
45
+ if f.ext not in {".py", ".js", ".ts", ".mjs", ".cjs", ".tsx", ".jsx"}:
46
+ continue
47
+ is_py = f.ext == ".py"
48
+ for i, line in enumerate(f.lines, start=1):
49
+ stripped = line.strip()
50
+ if stripped.startswith("#") or stripped.startswith("//"):
51
+ continue
52
+
53
+ hit = None
54
+ sev = self.severity
55
+
56
+ if is_py and PY_SHELL_TRUE.search(line):
57
+ hit = "subprocess called with shell=True"
58
+ sev = Severity.CRITICAL if INTERP.search(line) else Severity.HIGH
59
+ elif is_py and PY_SINKS.search(line):
60
+ hit = "shell execution sink"
61
+ sev = Severity.CRITICAL if INTERP.search(line) else Severity.MEDIUM
62
+ elif not is_py and JS_SINKS.search(line):
63
+ hit = "child process execution"
64
+ sev = Severity.CRITICAL if INTERP.search(line) else Severity.MEDIUM
65
+ elif EVAL.search(line):
66
+ hit = "dynamic code execution (eval/exec)"
67
+ sev = Severity.HIGH
68
+
69
+ if hit:
70
+ out.append(self.finding(
71
+ f, i, line,
72
+ title=f"Command injection risk: {hit}",
73
+ detail="Tool handlers that shell out with interpolated input let a "
74
+ "crafted argument run arbitrary commands. Use argument "
75
+ "lists (no shell=True), validate inputs, or avoid eval.",
76
+ severity=sev,
77
+ ))
78
+ return out
@@ -0,0 +1,143 @@
1
+ """MCP018 — a debug/proxy/inspector server bound to all interfaces exposes an
2
+ unauthenticated connect/exec-style endpoint.
3
+
4
+ This exact vulnerability shape has now been independently confirmed twice in
5
+ the MCP tooling ecosystem itself: Anthropic's own MCP Inspector
6
+ (CVE-2025-49596, CVSS 9.4) and MCPJam Inspector (CVE-2026-23744, CVSS 9.8, no
7
+ user interaction required) both bound their HTTP proxy to every network
8
+ interface instead of localhost and exposed a connect-style endpoint that
9
+ accepted a raw command/args payload with no authentication — achieving remote
10
+ code execution from a single crafted request. Two unrelated teams building
11
+ tools in mcpscan's exact target domain made the identical insecure-default
12
+ mistake roughly eight months apart. See `research/2026-07-17.md`'s top
13
+ compounding opportunity.
14
+
15
+ Two co-occurring conditions in the same file, both required:
16
+
17
+ 1. A server bind call that exposes the process to every network interface,
18
+ not just localhost — an explicit all-interfaces host (`0.0.0.0`, `::`, or
19
+ an empty host string), or a Node `.listen(port)` call with no host
20
+ argument at all (which defaults to all interfaces).
21
+ 2. A route/handler whose path looks like a debug/inspector connect-or-exec
22
+ endpoint, which spawns a process using a command/args value read straight
23
+ out of the request body, with no authentication check anywhere in the
24
+ handler.
25
+
26
+ Deliberately conservative, matching the rest of mcpscan's "high signal over
27
+ recall" design: this only fires on the literal shape both disclosed CVEs
28
+ share (bind-all + unauthenticated request-driven process spawn on a
29
+ connect/exec-shaped route), not on every HTTP server that happens to spawn a
30
+ process anywhere in the file.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import re
36
+ from typing import List
37
+
38
+ from ..findings import Finding, Severity
39
+ from ..loaders import FileInfo, by_kind
40
+ from .base import Rule, register
41
+
42
+ _SOURCE_EXTS = {".py", ".js", ".ts", ".mjs", ".cjs", ".tsx", ".jsx"}
43
+
44
+ # A bind call exposing the process to every network interface.
45
+ _BIND_ALL_RE = re.compile(
46
+ r"host\s*=\s*['\"](?:0\.0\.0\.0|::|)['\"]" # Flask/uvicorn/FastAPI host=
47
+ r"|HTTPServer\s*\(\s*\(\s*['\"]['\"]\s*," # Python http.server (('', port))
48
+ r"|\.listen\s*\(\s*[\w.]+\s*,\s*['\"]0\.0\.0\.0['\"]" # Node .listen(port, '0.0.0.0')
49
+ r"|\.listen\s*\(\s*[\w.]+\s*\)" # Node .listen(port) — no host, defaults all
50
+ )
51
+
52
+ # An HTTP route/handler registration.
53
+ _ROUTE_CALL_RE = re.compile(
54
+ r"@\w+\.route\s*\(|\.(?:get|post|put|all|route)\s*\(|app\.(?:get|post|put|all)\s*\("
55
+ )
56
+ # ...whose path string looks like a debug/inspector connect-or-exec endpoint.
57
+ _CONNECT_PATH_RE = re.compile(
58
+ r"['\"][^'\"]*(?:connect|exec|spawn)[^'\"]*['\"]", re.IGNORECASE
59
+ )
60
+
61
+ # The handler parses the request body somewhere in the window...
62
+ _REQUEST_BODY_RE = re.compile(
63
+ r"req\.body|request\.json|ctx\.request\.body|request\.get_json\(\)",
64
+ re.IGNORECASE,
65
+ )
66
+ # ...and a spawn call is given a command/args-shaped field access as an
67
+ # argument (parsed body -> variable -> field access is the common real-world
68
+ # shape, not necessarily the same line as the parse call itself).
69
+ _SPAWN_CALL_RE = re.compile(
70
+ r"\b(?:spawn|spawnSync|exec|execSync|subprocess\.(?:run|Popen|call))\s*\("
71
+ )
72
+ _COMMAND_FIELD_ACCESS_RE = re.compile(
73
+ r"\[['\"]?(?:command|cmd|args)['\"]?\]"
74
+ r"|\.(?:command|cmd|args)\b"
75
+ r"|\.get\(['\"](?:command|cmd|args)['\"]",
76
+ re.IGNORECASE,
77
+ )
78
+
79
+ # Anything in the handler window that looks like an auth check.
80
+ _AUTH_CHECK_RE = re.compile(
81
+ r"authoriz|authenticat|api[_-]?key|bearer|verify.?token|require.?auth",
82
+ re.IGNORECASE,
83
+ )
84
+
85
+ _WINDOW = 30
86
+
87
+
88
+ @register
89
+ class UnauthenticatedConnectExecEndpoint(Rule):
90
+ id = "MCP018"
91
+ name = ("Debug/proxy server bound to all interfaces exposes an "
92
+ "unauthenticated connect/exec endpoint")
93
+ severity = Severity.CRITICAL
94
+ owasp = "MCP07:2025" # Insufficient Authentication & Authorization
95
+
96
+ def check(self, files: List[FileInfo]) -> List[Finding]:
97
+ out: List[Finding] = []
98
+ for f in by_kind(files, "source", "manifest"):
99
+ if f.ext not in _SOURCE_EXTS:
100
+ continue
101
+ lines = f.lines
102
+ if not _BIND_ALL_RE.search(f.text):
103
+ continue
104
+
105
+ n = len(lines)
106
+ for i, line in enumerate(lines):
107
+ if not (_ROUTE_CALL_RE.search(line) and _CONNECT_PATH_RE.search(line)):
108
+ continue
109
+
110
+ window = lines[i:min(i + _WINDOW, n)]
111
+ window_text = "\n".join(window)
112
+ if _AUTH_CHECK_RE.search(window_text):
113
+ continue
114
+ if not _REQUEST_BODY_RE.search(window_text):
115
+ continue
116
+
117
+ spawn_idx = None
118
+ for j, wline in enumerate(window):
119
+ if _SPAWN_CALL_RE.search(wline) and _COMMAND_FIELD_ACCESS_RE.search(wline):
120
+ spawn_idx = i + j
121
+ break
122
+ if spawn_idx is None:
123
+ continue
124
+
125
+ out.append(self.finding(
126
+ f, spawn_idx + 1, lines[spawn_idx],
127
+ title="Unauthenticated connect/exec endpoint on a server "
128
+ "bound to all interfaces",
129
+ detail=(
130
+ "This server binds to every network interface (not just "
131
+ "localhost) and exposes a connect/exec-style endpoint "
132
+ "that spawns a process using a command/args value taken "
133
+ "directly from the request body, with no authentication "
134
+ "check in the handler. This is the exact shape behind "
135
+ "Anthropic's own MCP Inspector RCE (CVE-2025-49596, "
136
+ "CVSS 9.4) and MCPJam Inspector (CVE-2026-23744, CVSS "
137
+ "9.8) — any host that can reach this port can run "
138
+ "arbitrary commands. Bind to 127.0.0.1/localhost only, "
139
+ "and require an authentication token before accepting a "
140
+ "command payload."
141
+ ),
142
+ ))
143
+ return out
@@ -0,0 +1,128 @@
1
+ """MCP021 — a click handler dispatches a privileged action with no
2
+ `event.isTrusted` check.
3
+
4
+ Confirmed root-cause mechanism (Manifold Security, reported to Anthropic's
5
+ bug bounty program 2026-05-21; still unpatched against the shipped v1.0.80
6
+ as of 2026-07-07, corroborated by Bleeping Computer and The Hacker News):
7
+ Claude for Chrome's content-script click handler on claude.ai never checks
8
+ `event.isTrusted` before reading a clicked element's `data-task-id`
9
+ attribute and dispatching the associated agentic task (reading recent
10
+ Gmail, creating a calendar meeting, modifying Salesforce leads, ...). Any
11
+ other script with DOM access on the page — commonly another installed
12
+ browser extension, which routinely holds script access to claude.ai — can
13
+ construct the same element and dispatch a synthetic click event
14
+ (`element.dispatchEvent(new MouseEvent('click'))`), and the handler has no
15
+ way to tell it apart from a real user gesture. No CVE has been assigned;
16
+ Anthropic's internal ticket was marked "Resolved" without the fix (a single
17
+ `isTrusted` check) actually shipping across eight point releases.
18
+
19
+ This is a general web-security anti-pattern, not unique to that one
20
+ extension: any content script, extension popup, or browser-facing web app
21
+ that reads data off a clicked element and forwards it to a privileged sink
22
+ (extension messaging, a background script, an approve/grant/authorize call)
23
+ without checking `event.isTrusted` has the identical gap — a script can
24
+ forge the "user clicked this" signal a privileged action relies on.
25
+
26
+ Scoped narrow and high-signal, matching the rest of mcpscan's design: a
27
+ click listener registration, followed within a line window by *both*
28
+ (a) a read of the clicked element's own data (`.dataset.x` /
29
+ `getAttribute(...)`) and (b) a privileged dispatch (extension messaging, or
30
+ an approve/grant/authorize-named call) — with no `isTrusted` check anywhere
31
+ in that window. A handler that checks `event.isTrusted` before acting, or
32
+ that never reads element data at all (e.g. a purely cosmetic click
33
+ handler), never matches.
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ import re
39
+ from typing import List
40
+
41
+ from ..findings import Finding, Severity
42
+ from ..loaders import FileInfo, by_kind
43
+ from .base import Rule, register
44
+
45
+ _JS_EXTS = {".js", ".ts", ".mjs", ".cjs", ".tsx", ".jsx"}
46
+
47
+ _CLICK_LISTENER_RE = re.compile(
48
+ r"addEventListener\s*\(\s*['\"]click['\"]"
49
+ r"|\.onclick\s*=\s*(?:function\b|\([^)]*\)\s*=>)"
50
+ )
51
+
52
+ # The handler reads data off the element that was actually clicked.
53
+ _ELEMENT_DATA_READ_RE = re.compile(r"\.dataset\.\w+|getAttribute\s*\(")
54
+
55
+ # ...and forwards it to something privileged: extension/background
56
+ # messaging, or a call that looks like it grants/approves/authorizes an
57
+ # action.
58
+ _PRIVILEGED_SINK_RE = re.compile(
59
+ r"chrome\.runtime\.sendMessage\s*\("
60
+ r"|browser\.runtime\.sendMessage\s*\("
61
+ r"|\.postMessage\s*\("
62
+ r"|\b(?:approve|grant|authoriz)\w*\s*\(",
63
+ re.IGNORECASE,
64
+ )
65
+
66
+ _IS_TRUSTED_RE = re.compile(r"\.isTrusted\b")
67
+
68
+ _WINDOW = 30
69
+
70
+
71
+ @register
72
+ class UntrustedClickPrivilegedAction(Rule):
73
+ id = "MCP021"
74
+ name = "Click handler dispatches a privileged action with no event.isTrusted check"
75
+ severity = Severity.HIGH
76
+ owasp = "MCP07:2025" # Insufficient Authentication & Authorization
77
+
78
+ def check(self, files: List[FileInfo]) -> List[Finding]:
79
+ out: List[Finding] = []
80
+ for f in by_kind(files, "source"):
81
+ if f.ext not in _JS_EXTS:
82
+ continue
83
+ lines = f.lines
84
+ n = len(lines)
85
+ for i, line in enumerate(lines):
86
+ if not _CLICK_LISTENER_RE.search(line):
87
+ continue
88
+
89
+ window = lines[i:min(i + _WINDOW, n)]
90
+ window_text = "\n".join(window)
91
+ if _IS_TRUSTED_RE.search(window_text):
92
+ continue
93
+ if not _ELEMENT_DATA_READ_RE.search(window_text):
94
+ continue
95
+
96
+ sink_idx = None
97
+ for j, wline in enumerate(window):
98
+ if _PRIVILEGED_SINK_RE.search(wline):
99
+ sink_idx = i + j
100
+ break
101
+ if sink_idx is None:
102
+ continue
103
+
104
+ out.append(self.finding(
105
+ f, sink_idx + 1, lines[sink_idx],
106
+ title="Click handler dispatches a privileged action "
107
+ "with no event.isTrusted check",
108
+ detail=(
109
+ "This click handler reads data off the clicked "
110
+ "element and forwards it to a privileged sink "
111
+ "(extension messaging, or an approve/grant/"
112
+ "authorize call) without checking event.isTrusted "
113
+ "anywhere in the handler. Any other script with DOM "
114
+ "access on the page — commonly another installed "
115
+ "browser extension — can construct the same "
116
+ "element and dispatch a synthetic click event "
117
+ "(element.dispatchEvent(new MouseEvent('click'))), "
118
+ "and this handler has no way to tell it apart from "
119
+ "a real user gesture. This is the confirmed root "
120
+ "cause behind Claude for Chrome's still-unpatched "
121
+ "click-spoofing flaw (reported to Anthropic's bug "
122
+ "bounty 2026-05-21, confirmed still broken against "
123
+ "v1.0.80 on 2026-07-07 by Manifold Security). Check "
124
+ "event.isTrusted before reading or acting on "
125
+ "anything in the handler."
126
+ ),
127
+ ))
128
+ return out
mcpscan/rules/hooks.py ADDED
@@ -0,0 +1,71 @@
1
+ """MCP003 — dangerous hooks in Claude Code projects.
2
+
3
+ `.claude/settings.json` (and friends) can register hooks that run shell commands
4
+ automatically on events like PreToolUse / PostToolUse. A malicious repo can ship a
5
+ hook that fires the moment you open it. We flag the classic remote-exec and
6
+ exfiltration shapes.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from typing import List
13
+
14
+ from ..findings import Finding, Severity
15
+ from ..loaders import FileInfo
16
+ from .base import Rule, register
17
+
18
+ # curl/wget piped straight into a shell — remote code execution.
19
+ REMOTE_EXEC = re.compile(
20
+ r"(?:curl|wget|iwr|Invoke-WebRequest)\b[^|;\n]*\|\s*(?:ba)?sh\b"
21
+ r"|(?:curl|wget)\b[^|;\n]*\|\s*(?:python|node|perl)\b",
22
+ re.IGNORECASE,
23
+ )
24
+ # base64 -d | sh and friends.
25
+ OBFUSCATED = re.compile(r"base64\s+(?:-d|--decode)[^|]*\|\s*(?:ba)?sh|eval\s*\(?\s*atob", re.IGNORECASE)
26
+ # Reading env/secrets and shipping them somewhere.
27
+ EXFIL = re.compile(
28
+ r"(?:env|printenv|cat\s+[^|;\n]*\.env|echo\s+\$[A-Z_]+)[^|;\n]*\|\s*(?:curl|wget|nc)\b"
29
+ r"|(?:curl|wget|nc)\b[^|\n]*(?:\$[A-Z_]+|\benv\b|TOKEN|SECRET|KEY)",
30
+ re.IGNORECASE,
31
+ )
32
+
33
+
34
+ @register
35
+ class DangerousHooks(Rule):
36
+ id = "MCP003"
37
+ name = "Dangerous Claude Code hook"
38
+ severity = Severity.CRITICAL
39
+ owasp = "MCP05:2025" # Command Injection & Execution
40
+
41
+ def check(self, files: List[FileInfo]) -> List[Finding]:
42
+ out: List[Finding] = []
43
+ for f in files:
44
+ # Hooks live in .claude/ settings, but a command string can hide
45
+ # anywhere; we scan broadly and lean on the patterns themselves.
46
+ looks_hooky = f.in_dot_claude or "hook" in f.text.lower() or f.name.endswith(".sh")
47
+ if not looks_hooky:
48
+ continue
49
+ for i, line in enumerate(f.lines, start=1):
50
+ if REMOTE_EXEC.search(line):
51
+ out.append(self.finding(
52
+ f, i, line,
53
+ title="Hook pipes a remote payload into a shell",
54
+ detail="`curl … | sh` in a hook runs attacker-controlled code on the "
55
+ "machine of anyone who opens the project. Never auto-fetch+exec.",
56
+ ))
57
+ elif OBFUSCATED.search(line):
58
+ out.append(self.finding(
59
+ f, i, line,
60
+ title="Hook executes obfuscated (base64) payload",
61
+ detail="Decoding then executing a blob hides intent from review.",
62
+ ))
63
+ elif EXFIL.search(line):
64
+ out.append(self.finding(
65
+ f, i, line,
66
+ title="Hook may exfiltrate environment/secrets",
67
+ detail="A hook sending env vars or tokens over the network is a "
68
+ "credential-theft pattern.",
69
+ severity=Severity.HIGH,
70
+ ))
71
+ return out