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.
- mcpscan/__init__.py +3 -0
- mcpscan/__main__.py +8 -0
- mcpscan/cli.py +150 -0
- mcpscan/discover.py +260 -0
- mcpscan/drift.py +174 -0
- mcpscan/findings.py +84 -0
- mcpscan/fixer.py +108 -0
- mcpscan/loaders.py +103 -0
- mcpscan/mcp_server.py +177 -0
- mcpscan/owasp.py +27 -0
- mcpscan/report.py +158 -0
- mcpscan/rules/__init__.py +25 -0
- mcpscan/rules/auth_gaps.py +105 -0
- mcpscan/rules/base.py +102 -0
- mcpscan/rules/command_injection.py +78 -0
- mcpscan/rules/debug_endpoint.py +143 -0
- mcpscan/rules/dom_trust.py +128 -0
- mcpscan/rules/hooks.py +71 -0
- mcpscan/rules/insecure_deser.py +81 -0
- mcpscan/rules/insecure_transport.py +103 -0
- mcpscan/rules/origin_check.py +126 -0
- mcpscan/rules/path_traversal.py +57 -0
- mcpscan/rules/permissions.py +69 -0
- mcpscan/rules/sdk_versions.py +99 -0
- mcpscan/rules/secrets.py +82 -0
- mcpscan/rules/ssrf.py +57 -0
- mcpscan/rules/tool_annotations.py +148 -0
- mcpscan/rules/tool_poisoning.py +84 -0
- mcpscan/rules/webfetch_domain.py +67 -0
- mcpscan/rules/workflow_injection.py +574 -0
- mcpscan/scanner.py +40 -0
- mcpscan/suppress.py +74 -0
- mcpscan_cli-0.19.1.dist-info/METADATA +913 -0
- mcpscan_cli-0.19.1.dist-info/RECORD +38 -0
- mcpscan_cli-0.19.1.dist-info/WHEEL +5 -0
- mcpscan_cli-0.19.1.dist-info/entry_points.txt +3 -0
- mcpscan_cli-0.19.1.dist-info/licenses/LICENSE +21 -0
- mcpscan_cli-0.19.1.dist-info/top_level.txt +1 -0
mcpscan/fixer.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""`--fix` mode: generate, preview, and (optionally) apply mechanical patches.
|
|
2
|
+
|
|
3
|
+
Only a small subset of findings are safe to auto-patch: a one-line value
|
|
4
|
+
swap that can't change what a call does besides re-enabling the check it
|
|
5
|
+
disabled (dropping a `verify` kwarg pinned to False, swapping `yaml.load` for
|
|
6
|
+
`yaml.safe_load`, etc). Anything that requires restructuring a call or
|
|
7
|
+
choosing new argument values (turning a shell string into an argv list when a
|
|
8
|
+
subprocess call opts into shell execution, replacing `pickle.loads` with a
|
|
9
|
+
schema-validated format) is deliberately left alone; see `Rule.fix_line` for
|
|
10
|
+
the contract each rule opts into.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import difflib
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from typing import Dict, List
|
|
18
|
+
|
|
19
|
+
from .findings import Finding, Report
|
|
20
|
+
from .loaders import FileInfo
|
|
21
|
+
from . import rules as rules_pkg
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class Fix:
|
|
26
|
+
finding: Finding
|
|
27
|
+
before: str
|
|
28
|
+
after: str
|
|
29
|
+
explanation: str
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def compute_fixes(report: Report, files: List[FileInfo]) -> List[Fix]:
|
|
33
|
+
"""Find every finding with a rule-provided mechanical fix for its line."""
|
|
34
|
+
rules_by_id = {r.id: r for r in rules_pkg.all_rules()}
|
|
35
|
+
lines_by_path = {f.relpath: f.lines for f in files}
|
|
36
|
+
fixes: List[Fix] = []
|
|
37
|
+
|
|
38
|
+
for finding in report.sorted():
|
|
39
|
+
rule = rules_by_id.get(finding.rule_id)
|
|
40
|
+
if rule is None or not finding.line:
|
|
41
|
+
continue
|
|
42
|
+
lines = lines_by_path.get(finding.path)
|
|
43
|
+
if not lines or finding.line > len(lines):
|
|
44
|
+
continue
|
|
45
|
+
before = lines[finding.line - 1]
|
|
46
|
+
result = rule.fix_line(before)
|
|
47
|
+
if not result:
|
|
48
|
+
continue
|
|
49
|
+
after, explanation = result
|
|
50
|
+
if after == before:
|
|
51
|
+
continue
|
|
52
|
+
fixes.append(Fix(finding=finding, before=before, after=after, explanation=explanation))
|
|
53
|
+
return fixes
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def render_preview(fixes: List[Fix]) -> str:
|
|
57
|
+
"""Render suggested fixes as per-finding diffs, dry-run style."""
|
|
58
|
+
if not fixes:
|
|
59
|
+
return "mcpscan --fix: no mechanically fixable findings."
|
|
60
|
+
|
|
61
|
+
out: List[str] = []
|
|
62
|
+
for fx in fixes:
|
|
63
|
+
out.append(f"{fx.finding.location()} [{fx.finding.rule_id}] {fx.finding.title}")
|
|
64
|
+
diff = difflib.unified_diff(
|
|
65
|
+
[fx.before + "\n"], [fx.after + "\n"],
|
|
66
|
+
fromfile="before", tofile="after", lineterm="",
|
|
67
|
+
)
|
|
68
|
+
out.extend(line.rstrip("\n") for line in diff
|
|
69
|
+
if not line.startswith(("---", "+++", "@@")))
|
|
70
|
+
out.append(f" why: {fx.explanation}")
|
|
71
|
+
out.append("")
|
|
72
|
+
out.append(f"{len(fixes)} fixable finding(s). Re-run with --apply-fix to write these changes.")
|
|
73
|
+
return "\n".join(out)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def apply_fixes(fixes: List[Fix], files: List[FileInfo]) -> List[str]:
|
|
77
|
+
"""Write fixes to disk, one line replacement per finding. Returns modified paths."""
|
|
78
|
+
abspath_by_rel = {f.relpath: f.abspath for f in files}
|
|
79
|
+
by_path: Dict[str, List[Fix]] = {}
|
|
80
|
+
for fx in fixes:
|
|
81
|
+
by_path.setdefault(fx.finding.path, []).append(fx)
|
|
82
|
+
|
|
83
|
+
modified: List[str] = []
|
|
84
|
+
for relpath, path_fixes in by_path.items():
|
|
85
|
+
abspath = abspath_by_rel.get(relpath)
|
|
86
|
+
if not abspath:
|
|
87
|
+
continue
|
|
88
|
+
with open(abspath, "r", encoding="utf-8", newline="") as fh:
|
|
89
|
+
raw_lines = fh.readlines()
|
|
90
|
+
|
|
91
|
+
changed = False
|
|
92
|
+
for fx in path_fixes:
|
|
93
|
+
idx = fx.finding.line - 1
|
|
94
|
+
if idx >= len(raw_lines):
|
|
95
|
+
continue
|
|
96
|
+
ending = ""
|
|
97
|
+
if raw_lines[idx].endswith("\r\n"):
|
|
98
|
+
ending = "\r\n"
|
|
99
|
+
elif raw_lines[idx].endswith("\n"):
|
|
100
|
+
ending = "\n"
|
|
101
|
+
raw_lines[idx] = fx.after + ending
|
|
102
|
+
changed = True
|
|
103
|
+
|
|
104
|
+
if changed:
|
|
105
|
+
with open(abspath, "w", encoding="utf-8", newline="") as fh:
|
|
106
|
+
fh.writelines(raw_lines)
|
|
107
|
+
modified.append(relpath)
|
|
108
|
+
return modified
|
mcpscan/loaders.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Filesystem discovery: walk a target and classify files for the rules."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import Iterable, List
|
|
8
|
+
|
|
9
|
+
# Directories we never want to descend into.
|
|
10
|
+
IGNORED_DIRS = {
|
|
11
|
+
".git", "node_modules", "dist", "build", "__pycache__",
|
|
12
|
+
".venv", "venv", ".mypy_cache", ".pytest_cache", ".idea", ".tox",
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
# Don't try to read anything larger than this (bytes) — likely a binary/blob.
|
|
16
|
+
MAX_FILE_BYTES = 2_000_000
|
|
17
|
+
|
|
18
|
+
SOURCE_EXTS = {".py", ".js", ".ts", ".mjs", ".cjs", ".tsx", ".jsx", ".sh", ".bash"}
|
|
19
|
+
CONFIG_EXTS = {".json", ".toml", ".yaml", ".yml"}
|
|
20
|
+
|
|
21
|
+
# File/Dir names that mark MCP or Claude Code supply-chain surface.
|
|
22
|
+
MANIFEST_NAMES = {
|
|
23
|
+
"package.json", "mcp.json", "claude_desktop_config.json",
|
|
24
|
+
"pyproject.toml", "requirements.txt", "smithery.yaml", "mcp.yaml",
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class FileInfo:
|
|
30
|
+
relpath: str # path relative to scan root (posix-style)
|
|
31
|
+
abspath: str
|
|
32
|
+
text: str
|
|
33
|
+
kind: str # "source" | "config" | "manifest" | "other"
|
|
34
|
+
in_dot_claude: bool # lives under a .claude/ directory
|
|
35
|
+
|
|
36
|
+
@property
|
|
37
|
+
def lines(self) -> List[str]:
|
|
38
|
+
if self._lines is None:
|
|
39
|
+
self._lines = self.text.splitlines()
|
|
40
|
+
return self._lines
|
|
41
|
+
|
|
42
|
+
_lines: List[str] = field(default=None, repr=False, compare=False)
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def ext(self) -> str:
|
|
46
|
+
return os.path.splitext(self.relpath)[1].lower()
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def name(self) -> str:
|
|
50
|
+
return os.path.basename(self.relpath)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _classify(name: str, ext: str) -> str:
|
|
54
|
+
if name in MANIFEST_NAMES:
|
|
55
|
+
return "manifest"
|
|
56
|
+
if ext in SOURCE_EXTS:
|
|
57
|
+
return "source"
|
|
58
|
+
if ext in CONFIG_EXTS:
|
|
59
|
+
return "config"
|
|
60
|
+
return "other"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def discover_files(root: str) -> List[FileInfo]:
|
|
64
|
+
"""Walk *root*, returning readable text files we care about."""
|
|
65
|
+
root = os.path.abspath(root)
|
|
66
|
+
out: List[FileInfo] = []
|
|
67
|
+
|
|
68
|
+
if os.path.isfile(root):
|
|
69
|
+
info = _load(root, os.path.dirname(root))
|
|
70
|
+
return [info] if info else []
|
|
71
|
+
|
|
72
|
+
for dirpath, dirnames, filenames in os.walk(root):
|
|
73
|
+
dirnames[:] = [d for d in dirnames if d not in IGNORED_DIRS]
|
|
74
|
+
for fn in filenames:
|
|
75
|
+
full = os.path.join(dirpath, fn)
|
|
76
|
+
info = _load(full, root)
|
|
77
|
+
if info:
|
|
78
|
+
out.append(info)
|
|
79
|
+
return out
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _load(full: str, root: str) -> "FileInfo | None":
|
|
83
|
+
name = os.path.basename(full)
|
|
84
|
+
ext = os.path.splitext(name)[1].lower()
|
|
85
|
+
kind = _classify(name, ext)
|
|
86
|
+
if kind == "other":
|
|
87
|
+
return None
|
|
88
|
+
try:
|
|
89
|
+
if os.path.getsize(full) > MAX_FILE_BYTES:
|
|
90
|
+
return None
|
|
91
|
+
with open(full, "r", encoding="utf-8", errors="replace") as fh:
|
|
92
|
+
text = fh.read()
|
|
93
|
+
except OSError:
|
|
94
|
+
return None
|
|
95
|
+
|
|
96
|
+
rel = os.path.relpath(full, root).replace(os.sep, "/")
|
|
97
|
+
in_claude = ".claude/" in ("/" + rel + "/")
|
|
98
|
+
return FileInfo(relpath=rel, abspath=full, text=text, kind=kind, in_dot_claude=in_claude)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def by_kind(files: Iterable[FileInfo], *kinds: str) -> List[FileInfo]:
|
|
102
|
+
wanted = set(kinds)
|
|
103
|
+
return [f for f in files if f.kind in wanted]
|
mcpscan/mcp_server.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
"""A tiny, zero-dependency MCP server exposing mcpscan as a callable tool.
|
|
2
|
+
|
|
3
|
+
Speaks JSON-RPC 2.0 over stdio (newline-delimited messages), implementing just
|
|
4
|
+
enough of the Model Context Protocol for a client to discover and call the
|
|
5
|
+
``scan`` tool. Run it with::
|
|
6
|
+
|
|
7
|
+
mcpscan-mcp # or: python -m mcpscan.mcp_server
|
|
8
|
+
|
|
9
|
+
and point an MCP client (e.g. Claude Desktop / Claude Code) at that command.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import sys
|
|
16
|
+
from typing import Any, Dict, Optional
|
|
17
|
+
|
|
18
|
+
from . import __version__
|
|
19
|
+
from .discover import render_discovery_json, run_discovery
|
|
20
|
+
from .findings import Severity
|
|
21
|
+
from .report import render_json
|
|
22
|
+
from .scanner import scan
|
|
23
|
+
|
|
24
|
+
PROTOCOL_VERSION = "2024-11-05"
|
|
25
|
+
|
|
26
|
+
SCAN_TOOL = {
|
|
27
|
+
"name": "scan",
|
|
28
|
+
"description": (
|
|
29
|
+
"Statically scan a local path (an MCP server, package, or .claude/ directory) "
|
|
30
|
+
"for supply-chain security issues: tool poisoning, command injection, dangerous "
|
|
31
|
+
"hooks, over-broad permissions, leaked secrets, vulnerable SDKs, path traversal "
|
|
32
|
+
"and SSRF. Returns a JSON report. Read-only; never executes the scanned code."
|
|
33
|
+
),
|
|
34
|
+
"inputSchema": {
|
|
35
|
+
"type": "object",
|
|
36
|
+
"properties": {
|
|
37
|
+
"path": {"type": "string", "description": "File or directory to scan."},
|
|
38
|
+
"min_severity": {
|
|
39
|
+
"type": "string",
|
|
40
|
+
"enum": ["info", "low", "medium", "high", "critical"],
|
|
41
|
+
"description": "Only include findings at or above this severity.",
|
|
42
|
+
"default": "info",
|
|
43
|
+
},
|
|
44
|
+
},
|
|
45
|
+
"required": ["path"],
|
|
46
|
+
},
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
DISCOVER_TOOL = {
|
|
50
|
+
"name": "discover",
|
|
51
|
+
"description": (
|
|
52
|
+
"Enumerate well-known MCP client config locations on this machine (Claude "
|
|
53
|
+
"Desktop, Claude Code CLI, Cursor, VS Code, Windsurf, Amazon Q Developer "
|
|
54
|
+
"CLI, Cline) and scan whichever exist with mcpscan's normal rule set. "
|
|
55
|
+
"Closes OWASP MCP09:2025 (Shadow MCP Servers) — surfaces servers a "
|
|
56
|
+
"directory scan of a single project would never see, since these configs "
|
|
57
|
+
"live outside any project tree. Returns a JSON report. Read-only; never "
|
|
58
|
+
"executes the scanned code."
|
|
59
|
+
),
|
|
60
|
+
"inputSchema": {
|
|
61
|
+
"type": "object",
|
|
62
|
+
"properties": {
|
|
63
|
+
"min_severity": {
|
|
64
|
+
"type": "string",
|
|
65
|
+
"enum": ["info", "low", "medium", "high", "critical"],
|
|
66
|
+
"description": "Only include findings at or above this severity.",
|
|
67
|
+
"default": "info",
|
|
68
|
+
},
|
|
69
|
+
},
|
|
70
|
+
},
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _result(req_id: Any, result: Dict[str, Any]) -> Dict[str, Any]:
|
|
75
|
+
return {"jsonrpc": "2.0", "id": req_id, "result": result}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _error(req_id: Any, code: int, message: str) -> Dict[str, Any]:
|
|
79
|
+
return {"jsonrpc": "2.0", "id": req_id, "error": {"code": code, "message": message}}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _run_scan(args: Dict[str, Any]) -> Dict[str, Any]:
|
|
83
|
+
path = args.get("path")
|
|
84
|
+
if not path:
|
|
85
|
+
raise ValueError("'path' is required")
|
|
86
|
+
threshold = Severity.parse(args.get("min_severity", "info"))
|
|
87
|
+
report = scan(path)
|
|
88
|
+
# Filter to the requested floor, but keep the full JSON shape.
|
|
89
|
+
report.findings = report.at_or_above(threshold)
|
|
90
|
+
return {
|
|
91
|
+
"content": [{"type": "text", "text": render_json(report)}],
|
|
92
|
+
"isError": False,
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _run_discover(args: Dict[str, Any]) -> Dict[str, Any]:
|
|
97
|
+
threshold = Severity.parse(args.get("min_severity", "info"))
|
|
98
|
+
discovery = run_discovery()
|
|
99
|
+
# Filter each location's report in place, same pattern as _run_scan.
|
|
100
|
+
for r in discovery.results:
|
|
101
|
+
if r.report:
|
|
102
|
+
r.report.findings = r.report.at_or_above(threshold)
|
|
103
|
+
return {
|
|
104
|
+
"content": [{"type": "text", "text": render_discovery_json(discovery)}],
|
|
105
|
+
"isError": False,
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def handle_request(req: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
|
110
|
+
"""Handle one JSON-RPC request; return a response, or None for notifications."""
|
|
111
|
+
method = req.get("method")
|
|
112
|
+
req_id = req.get("id")
|
|
113
|
+
|
|
114
|
+
# Notifications (no id) get no response.
|
|
115
|
+
if req_id is None and method and method.startswith("notifications/"):
|
|
116
|
+
return None
|
|
117
|
+
|
|
118
|
+
if method == "initialize":
|
|
119
|
+
return _result(req_id, {
|
|
120
|
+
"protocolVersion": PROTOCOL_VERSION,
|
|
121
|
+
"capabilities": {"tools": {}},
|
|
122
|
+
"serverInfo": {"name": "mcpscan", "version": __version__},
|
|
123
|
+
})
|
|
124
|
+
|
|
125
|
+
if method == "tools/list":
|
|
126
|
+
return _result(req_id, {"tools": [SCAN_TOOL, DISCOVER_TOOL]})
|
|
127
|
+
|
|
128
|
+
if method == "tools/call":
|
|
129
|
+
params = req.get("params") or {}
|
|
130
|
+
name = params.get("name")
|
|
131
|
+
if name not in ("scan", "discover"):
|
|
132
|
+
return _error(req_id, -32602, f"unknown tool: {name}")
|
|
133
|
+
try:
|
|
134
|
+
args = params.get("arguments") or {}
|
|
135
|
+
result = _run_scan(args) if name == "scan" else _run_discover(args)
|
|
136
|
+
return _result(req_id, result)
|
|
137
|
+
except Exception as exc: # surface as a tool error, not a transport error
|
|
138
|
+
return _result(req_id, {
|
|
139
|
+
"content": [{"type": "text", "text": f"{name} failed: {exc}"}],
|
|
140
|
+
"isError": True,
|
|
141
|
+
})
|
|
142
|
+
|
|
143
|
+
if method == "ping":
|
|
144
|
+
return _result(req_id, {})
|
|
145
|
+
|
|
146
|
+
if req_id is not None:
|
|
147
|
+
return _error(req_id, -32601, f"method not found: {method}")
|
|
148
|
+
return None
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def serve(stdin=None, stdout=None) -> None:
|
|
152
|
+
stdin = stdin or sys.stdin
|
|
153
|
+
stdout = stdout or sys.stdout
|
|
154
|
+
for raw in stdin:
|
|
155
|
+
raw = raw.strip()
|
|
156
|
+
if not raw:
|
|
157
|
+
continue
|
|
158
|
+
try:
|
|
159
|
+
req = json.loads(raw)
|
|
160
|
+
except json.JSONDecodeError:
|
|
161
|
+
continue
|
|
162
|
+
resp = handle_request(req)
|
|
163
|
+
if resp is not None:
|
|
164
|
+
stdout.write(json.dumps(resp) + "\n")
|
|
165
|
+
stdout.flush()
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def main() -> int: # pragma: no cover
|
|
169
|
+
try:
|
|
170
|
+
serve()
|
|
171
|
+
except KeyboardInterrupt:
|
|
172
|
+
pass
|
|
173
|
+
return 0
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
if __name__ == "__main__": # pragma: no cover
|
|
177
|
+
sys.exit(main())
|
mcpscan/owasp.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""OWASP MCP Top 10 (2025) reference taxonomy.
|
|
2
|
+
|
|
3
|
+
Source of truth: https://github.com/OWASP/www-project-mcp-top-10/blob/main/tab_top10.md
|
|
4
|
+
(the raw content backing https://owasp.org/www-project-mcp-top-10/), read directly
|
|
5
|
+
rather than from a summary, since a wrong category id in a security tool is worse
|
|
6
|
+
than no mapping at all. Version v0.1, Phase 3 (beta release / pilot testing) as of
|
|
7
|
+
2026-07-08 — categories and titles may still shift before a final release.
|
|
8
|
+
|
|
9
|
+
Used by `mcpscan/rules/*.py` (`Rule.owasp`) to tag findings with a category id, and
|
|
10
|
+
by tests to make sure every tagged rule points at a real category.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
# category id (e.g. "MCP01:2025") -> official title
|
|
16
|
+
OWASP_MCP_TOP_10 = {
|
|
17
|
+
"MCP01:2025": "Token Mismanagement & Secret Exposure",
|
|
18
|
+
"MCP02:2025": "Privilege Escalation via Scope Creep",
|
|
19
|
+
"MCP03:2025": "Tool Poisoning",
|
|
20
|
+
"MCP04:2025": "Software Supply Chain Attacks & Dependency Tampering",
|
|
21
|
+
"MCP05:2025": "Command Injection & Execution",
|
|
22
|
+
"MCP06:2025": "Prompt Injection via Contextual Payloads",
|
|
23
|
+
"MCP07:2025": "Insufficient Authentication & Authorization",
|
|
24
|
+
"MCP08:2025": "Lack of Audit and Telemetry",
|
|
25
|
+
"MCP09:2025": "Shadow MCP Servers",
|
|
26
|
+
"MCP10:2025": "Context Injection & Over-Sharing",
|
|
27
|
+
}
|
mcpscan/report.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""Render a Report as human text, JSON, or SARIF 2.1.0."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from typing import Dict
|
|
7
|
+
|
|
8
|
+
from .findings import Report, Severity
|
|
9
|
+
|
|
10
|
+
# ANSI colors keyed by severity.
|
|
11
|
+
_COLOR = {
|
|
12
|
+
Severity.CRITICAL: "\033[1;97;41m",
|
|
13
|
+
Severity.HIGH: "\033[91m",
|
|
14
|
+
Severity.MEDIUM: "\033[93m",
|
|
15
|
+
Severity.LOW: "\033[94m",
|
|
16
|
+
Severity.INFO: "\033[90m",
|
|
17
|
+
}
|
|
18
|
+
_RESET = "\033[0m"
|
|
19
|
+
_DIM = "\033[2m"
|
|
20
|
+
_BOLD = "\033[1m"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def render_text(report: Report, color: bool = True) -> str:
|
|
24
|
+
def c(s: str, code: str) -> str:
|
|
25
|
+
return f"{code}{s}{_RESET}" if color else s
|
|
26
|
+
|
|
27
|
+
lines = []
|
|
28
|
+
findings = report.sorted()
|
|
29
|
+
for f in findings:
|
|
30
|
+
tag = c(f" {f.severity.label.upper():^8} ", _COLOR[f.severity])
|
|
31
|
+
owasp = c(f" [{f.owasp}]", _DIM) if f.owasp else ""
|
|
32
|
+
lines.append(f"{tag} {c(f.rule_id, _BOLD)} {f.title}{owasp}")
|
|
33
|
+
lines.append(f" {c(f.location(), _DIM)}")
|
|
34
|
+
if f.snippet:
|
|
35
|
+
lines.append(f" {c('> ' + f.snippet, _DIM)}")
|
|
36
|
+
if f.detail:
|
|
37
|
+
lines.append(f" {f.detail}")
|
|
38
|
+
lines.append("")
|
|
39
|
+
|
|
40
|
+
counts = report.counts()
|
|
41
|
+
summary = " ".join(
|
|
42
|
+
c(f"{counts[s.label]} {s.label}", _COLOR[s])
|
|
43
|
+
for s in reversed(Severity) if counts[s.label]
|
|
44
|
+
) or c("no findings", "\033[92m")
|
|
45
|
+
|
|
46
|
+
suffix = f" ({report.suppressed} suppressed)" if report.suppressed else ""
|
|
47
|
+
header = (c("mcpscan", _BOLD)
|
|
48
|
+
+ f" scanned {report.files_scanned} files in {report.root}{suffix}")
|
|
49
|
+
footer = f"{_BOLD if color else ''}Summary:{_RESET if color else ''} {summary}"
|
|
50
|
+
body = "\n".join(lines) if findings else c(" Clean — no issues found.\n", "\033[92m")
|
|
51
|
+
err = ""
|
|
52
|
+
if report.errors:
|
|
53
|
+
err = "\n" + "\n".join(" ! " + e for e in report.errors)
|
|
54
|
+
return f"{header}\n\n{body}\n{footer}{err}"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def render_json(report: Report) -> str:
|
|
58
|
+
payload: Dict = {
|
|
59
|
+
"tool": "mcpscan",
|
|
60
|
+
"root": report.root,
|
|
61
|
+
"files_scanned": report.files_scanned,
|
|
62
|
+
"suppressed": report.suppressed,
|
|
63
|
+
"counts": report.counts(),
|
|
64
|
+
"errors": report.errors,
|
|
65
|
+
"findings": [
|
|
66
|
+
{
|
|
67
|
+
"rule_id": f.rule_id,
|
|
68
|
+
"title": f.title,
|
|
69
|
+
"severity": f.severity.label,
|
|
70
|
+
"path": f.path,
|
|
71
|
+
"line": f.line,
|
|
72
|
+
"detail": f.detail,
|
|
73
|
+
"snippet": f.snippet,
|
|
74
|
+
"owasp": f.owasp,
|
|
75
|
+
}
|
|
76
|
+
for f in report.sorted()
|
|
77
|
+
],
|
|
78
|
+
}
|
|
79
|
+
return json.dumps(payload, indent=2)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
# SARIF severity maps onto a small set of levels.
|
|
83
|
+
_SARIF_LEVEL = {
|
|
84
|
+
Severity.CRITICAL: "error",
|
|
85
|
+
Severity.HIGH: "error",
|
|
86
|
+
Severity.MEDIUM: "warning",
|
|
87
|
+
Severity.LOW: "note",
|
|
88
|
+
Severity.INFO: "note",
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _sarif_rules(findings) -> list:
|
|
93
|
+
"""SARIF ``tool.driver.rules`` entries for the rule ids seen in *findings*.
|
|
94
|
+
|
|
95
|
+
Shared by :func:`render_sarif` and ``discover.render_discovery_sarif`` so
|
|
96
|
+
the rule-metadata shape (including the OWASP tag lookup) only lives once.
|
|
97
|
+
"""
|
|
98
|
+
# First OWASP tag seen per rule id — every finding from one rule carries
|
|
99
|
+
# the same tag, so any occurrence works as the rule-level lookup.
|
|
100
|
+
owasp_by_rule: Dict[str, str] = {}
|
|
101
|
+
for f in findings:
|
|
102
|
+
if f.owasp:
|
|
103
|
+
owasp_by_rule.setdefault(f.rule_id, f.owasp)
|
|
104
|
+
rule_ids = sorted({f.rule_id for f in findings})
|
|
105
|
+
return [
|
|
106
|
+
{
|
|
107
|
+
"id": rid,
|
|
108
|
+
**({"properties": {"tags": [owasp_by_rule[rid]],
|
|
109
|
+
"owaspMcpTop10": owasp_by_rule[rid]}}
|
|
110
|
+
if rid in owasp_by_rule else {}),
|
|
111
|
+
}
|
|
112
|
+
for rid in rule_ids
|
|
113
|
+
]
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _sarif_result(f, uri: str) -> Dict:
|
|
117
|
+
"""One SARIF ``results[]`` entry for finding *f*, located at *uri*.
|
|
118
|
+
|
|
119
|
+
*uri* is a separate parameter (not always ``f.path``) so discovery mode
|
|
120
|
+
can point results at the full client-config path instead of the bare
|
|
121
|
+
filename a single-file scan records.
|
|
122
|
+
"""
|
|
123
|
+
return {
|
|
124
|
+
"ruleId": f.rule_id,
|
|
125
|
+
"level": _SARIF_LEVEL[f.severity],
|
|
126
|
+
"message": {"text": f"{f.title}. {f.detail}".strip()},
|
|
127
|
+
"locations": [{
|
|
128
|
+
"physicalLocation": {
|
|
129
|
+
"artifactLocation": {"uri": uri},
|
|
130
|
+
"region": {"startLine": max(1, f.line)},
|
|
131
|
+
}
|
|
132
|
+
}],
|
|
133
|
+
**({"properties": {"owaspMcpTop10": f.owasp}} if f.owasp else {}),
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def render_sarif(report: Report) -> str:
|
|
138
|
+
sarif = {
|
|
139
|
+
"$schema": "https://json.schemastore.org/sarif-2.1.0.json",
|
|
140
|
+
"version": "2.1.0",
|
|
141
|
+
"runs": [{
|
|
142
|
+
"tool": {"driver": {
|
|
143
|
+
"name": "mcpscan",
|
|
144
|
+
"informationUri": "https://github.com/glatinone/mcpscan",
|
|
145
|
+
"rules": _sarif_rules(report.findings),
|
|
146
|
+
}},
|
|
147
|
+
"results": [_sarif_result(f, f.path) for f in report.sorted()],
|
|
148
|
+
}],
|
|
149
|
+
}
|
|
150
|
+
return json.dumps(sarif, indent=2)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def render(report: Report, fmt: str, color: bool = True) -> str:
|
|
154
|
+
if fmt == "json":
|
|
155
|
+
return render_json(report)
|
|
156
|
+
if fmt == "sarif":
|
|
157
|
+
return render_sarif(report)
|
|
158
|
+
return render_text(report, color=color)
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Rule package. Importing it registers every built-in rule."""
|
|
2
|
+
|
|
3
|
+
from .base import REGISTRY, Rule, register # noqa: F401
|
|
4
|
+
|
|
5
|
+
from . import command_injection # noqa: F401,E402
|
|
6
|
+
from . import tool_poisoning # noqa: F401,E402
|
|
7
|
+
from . import hooks # noqa: F401,E402
|
|
8
|
+
from . import permissions # noqa: F401,E402
|
|
9
|
+
from . import secrets # noqa: F401,E402
|
|
10
|
+
from . import sdk_versions # noqa: F401,E402
|
|
11
|
+
from . import path_traversal # noqa: F401,E402
|
|
12
|
+
from . import ssrf # noqa: F401,E402
|
|
13
|
+
from . import insecure_deser # noqa: F401,E402
|
|
14
|
+
from . import insecure_transport # noqa: F401,E402
|
|
15
|
+
from . import webfetch_domain # noqa: F401,E402
|
|
16
|
+
from . import auth_gaps # noqa: F401,E402
|
|
17
|
+
from . import tool_annotations # noqa: F401,E402
|
|
18
|
+
from . import workflow_injection # noqa: F401,E402
|
|
19
|
+
from . import debug_endpoint # noqa: F401,E402
|
|
20
|
+
from . import dom_trust # noqa: F401,E402
|
|
21
|
+
from . import origin_check # noqa: F401,E402
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def all_rules():
|
|
25
|
+
return list(REGISTRY)
|