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,574 @@
1
+ """MCP015 / MCP016 / MCP017 / MCP019 / MCP020: untrusted content and excess
2
+ token scope in GitHub Actions.
3
+
4
+ The first rule category to look at `.github/workflows/*.yml` rather than an MCP
5
+ server's own source or config. Motivated by `research/2026-07-14.md` Pain Radar
6
+ #1 and `research/2026-07-15.md`'s top compounding opportunity: the same root
7
+ cause (an agentic/automated CI workflow treats untrusted issue/PR/comment
8
+ content as instructions or code instead of data) has now been independently
9
+ disclosed across at least four vendors (Claude Code Action, Copilot, Gemini,
10
+ Codex "GitLost"). All three checks below are detectable as a line-window
11
+ heuristic over the raw YAML text — no YAML parser needed, consistent with
12
+ mcpscan staying zero-dependency.
13
+
14
+ MCP015 — script injection: an attacker-controlled context expression (an issue
15
+ title, PR body, review comment, branch name, etc.) is interpolated directly as
16
+ `${{ ... }}` inside a `run:`/`script:` execution step instead of being passed
17
+ through an `env:` variable first and referenced as `$VAR`. GitHub's own
18
+ hardening guide documents this exact anti-pattern and its fix:
19
+ https://docs.github.com/actions/security-guides/security-hardening-for-github-actions#understanding-the-risk-of-script-injections
20
+ A workflow that already follows the recommended env-var indirection never
21
+ matches this rule — the raw `${{ github.event... }}` form never appears inside
22
+ the execution step itself once it's been assigned to `env:` first.
23
+
24
+ MCP016 — "pwn request": a workflow triggers on `pull_request_target` (which
25
+ runs with the base repository's secrets and default token, even for a fork
26
+ PR) and then checks out the fork's own head commit (`actions/checkout` with
27
+ `ref: ${{ github.event.pull_request.head.sha }}` or `.head.ref`) — the fork's
28
+ code now executes with the base repo's trust level. See GitHub Security Lab,
29
+ "Keeping your GitHub Actions and workflows secure: Preventing pwn requests."
30
+
31
+ MCP017 — identity-based-trust / excess-scope reachability, the pattern
32
+ `research/2026-07-16.md`'s top compounding opportunity named "Cordyceps": a
33
+ 2026-07 disclosure scanning ~30,000 high-impact repositories found 300+
34
+ confirmed exploitable on this exact shape (workflows granting a
35
+ PR/issue-triggered job more permission than it needs, with no identity check
36
+ gating it). Deliberately narrower than the "model every bot's trust config"
37
+ version deferred from v0.11.0 (`backlog.md`/`projects/mcpscan.md` TODO):
38
+ instead of guessing what config key means "trust this actor" per third-party
39
+ Action, this checks the generic, action-agnostic shape Cordyceps actually
40
+ confirmed — a workflow triggered by untrusted content (`pull_request_target`,
41
+ `issue_comment`, `issues`, `discussion`, `discussion_comment`) that also
42
+ references a *custom* secret (`${{ secrets.SOMETHING }}`, not the auto-scoped
43
+ `GITHUB_TOKEN` — that one is already governed by the `permissions:` block, a
44
+ distinct mechanism MCP016 already reasons about) with neither of the two
45
+ GitHub-documented gates present anywhere in the file: a protected
46
+ `environment:` (requires manual reviewer approval before the job's secrets
47
+ become available) or an explicit actor/author-association check (e.g.
48
+ `github.event.pull_request.author_association` compared against a trusted
49
+ list, or a `github.actor` allowlist). Custom secrets aren't scoped by
50
+ `permissions:` at all, so that block alone doesn't make this safe — hence
51
+ checking for the two mechanisms that actually do.
52
+
53
+ MCP019: `workflow_run` token/artifact reuse. A workflow triggers on
54
+ `workflow_run` (which always runs the *base* branch's copy of the workflow
55
+ file, with the base repository's default `GITHUB_TOKEN` and secrets, even
56
+ when the triggering run came from a fork PR; GitHub's own docs on
57
+ `workflow_run` describe this trust boundary explicitly), and then either (a)
58
+ checks out the triggering run's own commit/branch
59
+ (`github.event.workflow_run.head_sha`/`.head_branch`) via `actions/checkout`,
60
+ or (b) downloads an artifact that run produced
61
+ (`actions/download-artifact`/`dawidd6/action-download-artifact` referencing
62
+ `github.event.workflow_run.id`), the documented "artifact poisoning"
63
+ pattern GitHub Security Lab and GitHub's own hardening guide both describe.
64
+ Either way, content an attacker fully controlled (by opening the fork PR
65
+ that produced the triggering run) is now checked out or downloaded inside a
66
+ job that still holds the base repo's privileged token, the same "pwn
67
+ request" shape as MCP016, just reached via `workflow_run` instead of
68
+ `pull_request_target` directly. Deliberately not conditioned on the file's
69
+ `permissions:` block (mirrors MCP016, which doesn't check it either): once
70
+ untrusted code or a script is on disk in a privileged job, a scoped-down
71
+ token doesn't stop it from reading secrets out of the job's own environment
72
+ or tampering with the build. The fix is not reaching the untrusted
73
+ ref/artifact in the first place, not narrowing what the token can do
74
+ afterward.
75
+
76
+ MCP020: `GITHUB_TOKEN` over-permissioning. A workflow has no explicit
77
+ `permissions:` key anywhere in the file (top-level or job-level), so its
78
+ token is left at whatever the repository/organization default grants,
79
+ still read-write on every scope for any org created before GitHub flipped
80
+ the new-org default to read-only in February 2023, and for older orgs that
81
+ never revisited the setting. This is a "missing thing" check, not a "found
82
+ something bad" one, and the wrong kind of false positive is expensive here:
83
+ plenty of workflows correctly omit `permissions:` because they truly need no
84
+ elevated scope (this project's own `ci.yml` is exactly that: checkout, install,
85
+ run tests, dogfood-scan itself, nothing that writes anywhere). So the rule
86
+ requires a second, independent condition before it fires: the workflow must
87
+ also contain a recognizable *write* action or command, publishing a
88
+ release, pushing a commit, commenting on or merging a PR/issue, or calling
89
+ the GitHub REST API with a write HTTP verb. A workflow with no
90
+ `permissions:` block that never does any of those stays quiet, the same way
91
+ MCP017 stays quiet on a `GITHUB_TOKEN`-only workflow. `actions/github-script`
92
+ calling a write-shaped REST/GraphQL method is a known, deliberate gap here,
93
+ detecting that would mean parsing the JS callback body, not just a YAML line
94
+ window; worth widening if real-world scans surface it as the dominant shape.
95
+
96
+ All checks are deliberately conservative: they only fire on the literal
97
+ shapes documented above, not on every possible indirect path (e.g. an
98
+ intermediate action re-exporting the same data under a new name, or a
99
+ job-level `environment:`/actor/`permissions:` check this file-level scan
100
+ can't attribute to the specific job that uses the secret or artifact),
101
+ matching the rest of mcpscan's "high signal over recall" design principle.
102
+ """
103
+
104
+ from __future__ import annotations
105
+
106
+ import re
107
+ from typing import List, Tuple
108
+
109
+ from ..findings import Finding, Severity
110
+ from ..loaders import FileInfo
111
+ from .base import Rule, register
112
+
113
+ _WORKFLOW_DIR = ".github/workflows/"
114
+
115
+ # Context expressions whose contents an attacker fully controls.
116
+ _UNTRUSTED_CONTEXTS = (
117
+ r"github\.event\.issue\.title",
118
+ r"github\.event\.issue\.body",
119
+ r"github\.event\.pull_request\.title",
120
+ r"github\.event\.pull_request\.body",
121
+ r"github\.event\.pull_request\.head\.ref",
122
+ r"github\.event\.comment\.body",
123
+ r"github\.event\.review\.body",
124
+ r"github\.event\.review_comment\.body",
125
+ r"github\.event\.discussion\.title",
126
+ r"github\.event\.discussion\.body",
127
+ r"github\.event\.discussion_comment\.body",
128
+ r"github\.head_ref",
129
+ r"github\.event\.head_commit\.message",
130
+ )
131
+ UNTRUSTED_CONTEXT_RE = re.compile(
132
+ r"\$\{\{\s*(?:" + "|".join(_UNTRUSTED_CONTEXTS) + r")[^}]*\}\}"
133
+ )
134
+
135
+ # The two YAML keys that hand raw text to a shell/JS interpreter.
136
+ _EXEC_KEY_RE = re.compile(r"^(\s*)(-\s+)?(run|script)\s*:\s*(.*)$")
137
+ _BLOCK_SCALAR_RE = re.compile(r"^[|>][+-]?\s*$")
138
+
139
+
140
+ def _is_workflow_file(f: FileInfo) -> bool:
141
+ return f.ext in (".yml", ".yaml") and _WORKFLOW_DIR in f.relpath
142
+
143
+
144
+ def _exec_block_ranges(lines: List[str]) -> List[Tuple[int, int]]:
145
+ """Return 0-based, inclusive (start, end) line ranges holding run:/script: text.
146
+
147
+ A `run: |`/`run: >` (or `script: |`) block scalar covers every following
148
+ line indented deeper than the key itself; a single-line `run: <cmd>` value
149
+ is a one-line range.
150
+ """
151
+ out: List[Tuple[int, int]] = []
152
+ i = 0
153
+ n = len(lines)
154
+ while i < n:
155
+ m = _EXEC_KEY_RE.match(lines[i])
156
+ if not m:
157
+ i += 1
158
+ continue
159
+ key_indent = len(m.group(1)) + (len(m.group(2)) if m.group(2) else 0)
160
+ rest = m.group(4).strip()
161
+ if rest == "" or _BLOCK_SCALAR_RE.match(rest):
162
+ j = i + 1
163
+ last = i
164
+ while j < n:
165
+ line = lines[j]
166
+ if line.strip() == "":
167
+ j += 1
168
+ continue
169
+ indent = len(line) - len(line.lstrip(" "))
170
+ if indent <= key_indent:
171
+ break
172
+ last = j
173
+ j += 1
174
+ if last > i:
175
+ out.append((i + 1, last))
176
+ i = j
177
+ else:
178
+ out.append((i, i))
179
+ i += 1
180
+ return out
181
+
182
+
183
+ @register
184
+ class WorkflowScriptInjection(Rule):
185
+ id = "MCP015"
186
+ name = "Untrusted event content interpolated directly into a run/script step"
187
+ severity = Severity.HIGH
188
+ owasp = "MCP05:2025" # Command Injection & Execution
189
+
190
+ def check(self, files: List[FileInfo]) -> List[Finding]:
191
+ out: List[Finding] = []
192
+ for f in files:
193
+ if not _is_workflow_file(f):
194
+ continue
195
+ lines = f.lines
196
+ for start, end in _exec_block_ranges(lines):
197
+ for idx in range(start, end + 1):
198
+ line = lines[idx]
199
+ m = UNTRUSTED_CONTEXT_RE.search(line)
200
+ if not m:
201
+ continue
202
+ out.append(self.finding(
203
+ f, idx + 1, line,
204
+ title="Untrusted event content interpolated directly "
205
+ "into a shell step",
206
+ detail=f"{m.group(0)} is attacker-controlled (an issue/PR "
207
+ "title, body, comment, or branch name) and is "
208
+ "expanded directly into a run/script step, so its "
209
+ "contents execute as shell code. Pass it through an "
210
+ "env: variable first and reference it as $VAR in the "
211
+ "script instead of interpolating ${{ }} directly.",
212
+ ))
213
+ return out
214
+
215
+
216
+ # --- MCP016 -----------------------------------------------------------------
217
+
218
+ _ON_KEY_RE = re.compile(r'^["\']?on["\']?\s*:')
219
+ _PULL_REQUEST_TARGET_RE = re.compile(r"(?:^|[\[\s,'\"])pull_request_target(?:$|[\]\s,:'\"])")
220
+ _CHECKOUT_RE = re.compile(r"uses:\s*actions/checkout@")
221
+ _PR_HEAD_REF_RE = re.compile(
222
+ r"ref:\s*\$\{\{\s*github\.event\.pull_request\.head\.(?:sha|ref)\s*\}\}"
223
+ )
224
+ _STEP_START_RE = re.compile(r"^(\s*)-\s")
225
+
226
+
227
+ def _step_indent(lines: List[str], idx: int) -> int:
228
+ """Return the indent of the step (`- name:`/`- uses:`/`- run:`) containing line idx."""
229
+ for k in range(idx, -1, -1):
230
+ if _STEP_START_RE.match(lines[k]):
231
+ return len(lines[k]) - len(lines[k].lstrip(" "))
232
+ return len(lines[idx]) - len(lines[idx].lstrip(" "))
233
+
234
+
235
+ def _triggers_on_pull_request_target(lines: List[str]) -> bool:
236
+ in_on_block = False
237
+ on_indent = 0
238
+ for line in lines:
239
+ stripped = line.strip()
240
+ if not in_on_block and _ON_KEY_RE.match(stripped):
241
+ in_on_block = True
242
+ on_indent = len(line) - len(line.lstrip(" "))
243
+ if _PULL_REQUEST_TARGET_RE.search(stripped):
244
+ return True
245
+ continue
246
+ if in_on_block:
247
+ if stripped == "":
248
+ continue
249
+ indent = len(line) - len(line.lstrip(" "))
250
+ if indent <= on_indent:
251
+ in_on_block = False
252
+ continue
253
+ if _PULL_REQUEST_TARGET_RE.search(line):
254
+ return True
255
+ return False
256
+
257
+
258
+ @register
259
+ class PwnRequestCheckout(Rule):
260
+ id = "MCP016"
261
+ name = "pull_request_target workflow checks out the fork's own head commit"
262
+ severity = Severity.CRITICAL
263
+ owasp = "MCP04:2025" # Software Supply Chain Attacks & Dependency Tampering
264
+
265
+ def check(self, files: List[FileInfo]) -> List[Finding]:
266
+ out: List[Finding] = []
267
+ for f in files:
268
+ if not _is_workflow_file(f):
269
+ continue
270
+ lines = f.lines
271
+ if not _triggers_on_pull_request_target(lines):
272
+ continue
273
+
274
+ n = len(lines)
275
+ for i, line in enumerate(lines):
276
+ if not _CHECKOUT_RE.search(line):
277
+ continue
278
+ step_indent = _step_indent(lines, i)
279
+ for j in range(i + 1, min(i + 12, n)):
280
+ probe = lines[j]
281
+ if probe.strip() and _STEP_START_RE.match(probe):
282
+ probe_indent = len(probe) - len(probe.lstrip(" "))
283
+ if probe_indent <= step_indent:
284
+ break
285
+ if _PR_HEAD_REF_RE.search(probe):
286
+ out.append(self.finding(
287
+ f, j + 1, probe,
288
+ title="pull_request_target workflow checks out "
289
+ "untrusted fork code",
290
+ detail="This workflow triggers on pull_request_target "
291
+ "(runs with the base repository's secrets and "
292
+ "write-scoped token, even for a fork PR) and "
293
+ "checks out the PR's own head commit — the "
294
+ "fork's code now executes with the base repo's "
295
+ "trust level. Switch to the pull_request "
296
+ "trigger, or gate this job behind a required "
297
+ "reviewer/environment before checkout runs.",
298
+ ))
299
+ break
300
+ return out
301
+
302
+
303
+ # --- MCP017 -----------------------------------------------------------------
304
+
305
+ _UNTRUSTED_TRIGGER_RE = re.compile(
306
+ r"(?:^|[\[\s,'\"])"
307
+ r"(?:pull_request_target|issue_comment|issues|discussion_comment|discussion)"
308
+ r"(?:$|[\]\s,:'\"])"
309
+ )
310
+ _CUSTOM_SECRET_RE = re.compile(
311
+ r"\$\{\{\s*secrets\.(?!GITHUB_TOKEN\b)[A-Za-z0-9_]+"
312
+ )
313
+ _ENVIRONMENT_KEY_RE = re.compile(r"^\s*environment\s*:", re.MULTILINE)
314
+ _ACTOR_GATE_RE = re.compile(r"author_association|github\.actor\b")
315
+
316
+
317
+ def _on_block_text(lines: List[str]) -> str:
318
+ """Return the raw text of the `on:` trigger block (key line included)."""
319
+ out: List[str] = []
320
+ in_on_block = False
321
+ on_indent = 0
322
+ for line in lines:
323
+ stripped = line.strip()
324
+ if not in_on_block and _ON_KEY_RE.match(stripped):
325
+ in_on_block = True
326
+ on_indent = len(line) - len(line.lstrip(" "))
327
+ out.append(line)
328
+ continue
329
+ if in_on_block:
330
+ if stripped == "":
331
+ continue
332
+ indent = len(line) - len(line.lstrip(" "))
333
+ if indent <= on_indent:
334
+ break
335
+ out.append(line)
336
+ return "\n".join(out)
337
+
338
+
339
+ @register
340
+ class UntrustedTriggerSecretReachability(Rule):
341
+ id = "MCP017"
342
+ name = ("Untrusted-trigger workflow reaches a custom secret with no "
343
+ "environment or identity gate")
344
+ severity = Severity.HIGH
345
+ owasp = "MCP02:2025" # Privilege Escalation via Scope Creep
346
+
347
+ def check(self, files: List[FileInfo]) -> List[Finding]:
348
+ out: List[Finding] = []
349
+ for f in files:
350
+ if not _is_workflow_file(f):
351
+ continue
352
+ lines = f.lines
353
+ if not _UNTRUSTED_TRIGGER_RE.search(_on_block_text(lines)):
354
+ continue
355
+
356
+ text = "\n".join(lines)
357
+ if _ENVIRONMENT_KEY_RE.search(text) or _ACTOR_GATE_RE.search(text):
358
+ continue
359
+
360
+ for i, line in enumerate(lines):
361
+ if not _CUSTOM_SECRET_RE.search(line):
362
+ continue
363
+ out.append(self.finding(
364
+ f, i + 1, line,
365
+ title="Untrusted-trigger workflow reaches a custom "
366
+ "secret with no gate",
367
+ detail="This workflow can be triggered by untrusted "
368
+ "content (an issue, PR, or comment from anyone, "
369
+ "not just a repo collaborator) and this step "
370
+ "references a custom secret. Unlike GITHUB_TOKEN, "
371
+ "custom secrets aren't scoped by a permissions: "
372
+ "block, so an unscoped permissions setup doesn't "
373
+ "help here. Gate this job behind a protected "
374
+ "environment: (Settings > Environments, require "
375
+ "reviewers) or an explicit actor/author_association "
376
+ "check before the secret is used, or switch to the "
377
+ "pull_request trigger if the job doesn't actually "
378
+ "need write-scoped secrets.",
379
+ ))
380
+ return out
381
+
382
+
383
+ # --- MCP019 -----------------------------------------------------------------
384
+
385
+ _WORKFLOW_RUN_TRIGGER_RE = re.compile(
386
+ r"(?:^|[\[\s,'\"])workflow_run(?:$|[\]\s,:'\"])"
387
+ )
388
+ _DOWNLOAD_ARTIFACT_RE = re.compile(
389
+ r"uses:\s*(?:actions/download-artifact|dawidd6/action-download-artifact)@"
390
+ )
391
+ _TRIGGERING_RUN_ID_RE = re.compile(
392
+ r"run[-_]id\s*:\s*\$\{\{\s*github\.event\.workflow_run\.id\s*\}\}"
393
+ )
394
+ _WORKFLOW_RUN_HEAD_REF_RE = re.compile(
395
+ r"ref:\s*\$\{\{\s*github\.event\.workflow_run\.head_(?:sha|branch)\s*\}\}"
396
+ )
397
+
398
+
399
+ def _lookahead_in_step(lines: List[str], step_idx: int, pattern: "re.Pattern[str]",
400
+ max_ahead: int = 12) -> "Tuple[int, str] | None":
401
+ """Search up to *max_ahead* lines after the step starting at *step_idx*
402
+ for *pattern*, stopping at the next sibling step boundary so an unrelated
403
+ later step can't false-positive. Returns (0-based line idx, text) or None.
404
+ """
405
+ step_indent = _step_indent(lines, step_idx)
406
+ n = len(lines)
407
+ for j in range(step_idx + 1, min(step_idx + 1 + max_ahead, n)):
408
+ probe = lines[j]
409
+ if probe.strip() and _STEP_START_RE.match(probe):
410
+ probe_indent = len(probe) - len(probe.lstrip(" "))
411
+ if probe_indent <= step_indent:
412
+ break
413
+ if pattern.search(probe):
414
+ return j, probe
415
+ return None
416
+
417
+
418
+ @register
419
+ class WorkflowRunArtifactReuse(Rule):
420
+ id = "MCP019"
421
+ name = ("workflow_run workflow checks out or downloads content from the "
422
+ "triggering (untrusted) run")
423
+ severity = Severity.CRITICAL
424
+ owasp = "MCP04:2025" # Software Supply Chain Attacks & Dependency Tampering
425
+
426
+ def check(self, files: List[FileInfo]) -> List[Finding]:
427
+ out: List[Finding] = []
428
+ for f in files:
429
+ if not _is_workflow_file(f):
430
+ continue
431
+ lines = f.lines
432
+ if not _WORKFLOW_RUN_TRIGGER_RE.search(_on_block_text(lines)):
433
+ continue
434
+
435
+ for i, line in enumerate(lines):
436
+ if _CHECKOUT_RE.search(line):
437
+ hit = _lookahead_in_step(lines, i, _WORKFLOW_RUN_HEAD_REF_RE)
438
+ if hit is None:
439
+ continue
440
+ j, probe = hit
441
+ out.append(self.finding(
442
+ f, j + 1, probe,
443
+ title="workflow_run workflow checks out the "
444
+ "triggering run's own untrusted commit",
445
+ detail="This workflow triggers on workflow_run, which "
446
+ "runs the base branch's copy of this file with "
447
+ "the base repository's secrets and token even "
448
+ "when the triggering run came from a fork PR, "
449
+ "and checks out that run's own head commit/"
450
+ "branch. Building or testing that checkout now "
451
+ "executes attacker-controlled code with the "
452
+ "privileged token. Check out the base ref "
453
+ "instead, or, if the fork's code genuinely "
454
+ "needs to run, gate the job behind a required "
455
+ "reviewer/environment first.",
456
+ ))
457
+ elif _DOWNLOAD_ARTIFACT_RE.search(line):
458
+ hit = _lookahead_in_step(lines, i, _TRIGGERING_RUN_ID_RE)
459
+ if hit is None:
460
+ continue
461
+ j, probe = hit
462
+ out.append(self.finding(
463
+ f, j + 1, probe,
464
+ title="workflow_run workflow downloads an artifact "
465
+ "from the triggering (untrusted) run",
466
+ detail="This workflow triggers on workflow_run and "
467
+ "downloads an artifact produced by the run "
468
+ "that triggered it, while still holding the "
469
+ "base repository's token/secrets, the "
470
+ "documented 'artifact poisoning' pattern. If "
471
+ "the triggering workflow can run on a fork PR, "
472
+ "the artifact's contents are "
473
+ "attacker-controlled. Never extract-and-execute "
474
+ "it directly; validate its contents first, or "
475
+ "use it only as inert data (e.g. a test report "
476
+ "to display, not a script to run).",
477
+ ))
478
+ return out
479
+
480
+
481
+ # --- MCP020 -----------------------------------------------------------------
482
+
483
+ _PERMISSIONS_KEY_RE = re.compile(r"^\s*permissions\s*:", re.MULTILINE)
484
+
485
+ # A deliberately narrow set of shapes that unambiguously *write* to GitHub
486
+ # using the workflow's token. Chosen so a genuinely read-only workflow (this
487
+ # project's own ci.yml: checkout, install, run tests, dogfood-scan itself)
488
+ # never matches any of them. That is the second, independent condition that
489
+ # keeps this "missing permissions:" check from firing on every workflow that
490
+ # simply doesn't need one.
491
+ _WRITE_ACTIONS = (
492
+ r"softprops/action-gh-release@",
493
+ r"actions/create-release@",
494
+ r"peter-evans/create-pull-request@",
495
+ r"peter-evans/create-or-update-comment@",
496
+ r"marocchino/sticky-pull-request-comment@",
497
+ r"stefanzweifel/git-auto-commit-action@",
498
+ r"endbug/add-and-commit@",
499
+ r"ad-m/github-push-action@",
500
+ )
501
+ _WRITE_ACTION_RE = re.compile(
502
+ r"uses:\s*(?:" + "|".join(_WRITE_ACTIONS) + r")", re.IGNORECASE
503
+ )
504
+ _GIT_PUSH_RE = re.compile(r"(?:^|[\s|;&])git\s+push\b")
505
+ _GH_WRITE_CLI_RE = re.compile(
506
+ r"\bgh\s+(?:"
507
+ r"release\s+create"
508
+ r"|pr\s+(?:comment|merge|review|edit|close)"
509
+ r"|issue\s+(?:comment|close|edit)"
510
+ r"|workflow\s+run"
511
+ r"|api\s+\S+.*-X\s*(?:POST|PUT|PATCH|DELETE)"
512
+ r")",
513
+ re.IGNORECASE,
514
+ )
515
+ _CURL_RE = re.compile(r"\bcurl\b")
516
+ _HTTP_WRITE_METHOD_RE = re.compile(r"-X\s*(?:POST|PUT|PATCH|DELETE)", re.IGNORECASE)
517
+ _GITHUB_API_HOST_RE = re.compile(r"api\.github\.com")
518
+
519
+
520
+ def _write_signal(lines: List[str]) -> "Tuple[int, str] | None":
521
+ """Return the (1-based line, text) of the first recognizable write
522
+ action or command, or None. See the module docstring for why this list
523
+ is narrow on purpose."""
524
+ for i, line in enumerate(lines, start=1):
525
+ if _WRITE_ACTION_RE.search(line):
526
+ return i, line
527
+ if _GIT_PUSH_RE.search(line):
528
+ return i, line
529
+ if _GH_WRITE_CLI_RE.search(line):
530
+ return i, line
531
+ if (_CURL_RE.search(line) and _HTTP_WRITE_METHOD_RE.search(line)
532
+ and _GITHUB_API_HOST_RE.search(line)):
533
+ return i, line
534
+ return None
535
+
536
+
537
+ @register
538
+ class MissingPermissionsBlock(Rule):
539
+ id = "MCP020"
540
+ name = "Workflow writes to GitHub with no explicit permissions: block"
541
+ severity = Severity.MEDIUM
542
+ owasp = "MCP02:2025" # Privilege Escalation via Scope Creep
543
+
544
+ def check(self, files: List[FileInfo]) -> List[Finding]:
545
+ out: List[Finding] = []
546
+ for f in files:
547
+ if not _is_workflow_file(f):
548
+ continue
549
+ lines = f.lines
550
+ if _PERMISSIONS_KEY_RE.search("\n".join(lines)):
551
+ continue # an explicit choice was made, whatever it grants
552
+
553
+ hit = _write_signal(lines)
554
+ if hit is None:
555
+ continue
556
+ i, line = hit
557
+ out.append(self.finding(
558
+ f, i, line,
559
+ title="Workflow writes to GitHub with no explicit "
560
+ "permissions: block",
561
+ detail="This workflow has no top-level or job-level "
562
+ "permissions: key anywhere, so its GITHUB_TOKEN gets "
563
+ "whatever the repository or organization default "
564
+ "grants. For any org created before GitHub's "
565
+ "February 2023 default change (or one that reverted "
566
+ "the setting), that default is read/write on every "
567
+ "scope. This workflow writes to GitHub (a release, "
568
+ "PR/issue comment, push, or API call), so add an "
569
+ "explicit permissions: block scoped to only what "
570
+ "this job actually needs (e.g. contents: write, or "
571
+ "pull-requests: write) instead of relying on "
572
+ "whatever the org default happens to be today.",
573
+ ))
574
+ return out
mcpscan/scanner.py ADDED
@@ -0,0 +1,40 @@
1
+ """Orchestration: discover files, run every registered rule, aggregate a Report."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import List, Tuple
6
+
7
+ from .findings import Report
8
+ from .loaders import FileInfo, discover_files
9
+ from .suppress import is_suppressed, load_ignore_patterns, path_ignored
10
+ from . import rules as rules_pkg
11
+
12
+
13
+ def scan(root: str) -> Report:
14
+ report, _files = scan_files(root)
15
+ return report
16
+
17
+
18
+ def scan_files(root: str) -> Tuple[Report, List[FileInfo]]:
19
+ """Like :func:`scan`, but also returns the FileInfo list that was scanned.
20
+
21
+ Callers that only need findings should use :func:`scan`; `--fix` needs the
22
+ files too, to re-read the offending line and write patches back to disk.
23
+ """
24
+ ignore_patterns = load_ignore_patterns(root)
25
+ files = [f for f in discover_files(root)
26
+ if not path_ignored(f.relpath, ignore_patterns)]
27
+
28
+ report = Report(root=root, files_scanned=len(files))
29
+ lines_by_path = {f.relpath: f.lines for f in files}
30
+
31
+ for rule in rules_pkg.all_rules():
32
+ try:
33
+ for finding in rule.check(files):
34
+ if is_suppressed(finding, lines_by_path):
35
+ report.suppressed += 1
36
+ else:
37
+ report.add(finding)
38
+ except Exception as exc: # a buggy rule shouldn't kill the whole scan
39
+ report.errors.append(f"{rule.id} failed: {exc}")
40
+ return report, files
mcpscan/suppress.py ADDED
@@ -0,0 +1,74 @@
1
+ """Suppression support: a `.mcpscanignore` file and inline ignore comments.
2
+
3
+ Inline markers (on the finding's line or the line directly above):
4
+
5
+ risky_call(x) # mcpscan: ignore -> suppress every rule here
6
+ risky_call(x) # mcpscan: ignore[MCP001] -> suppress only MCP001
7
+ risky_call(x) // mcpscan: ignore[MCP001,MCP005]
8
+
9
+ `.mcpscanignore` (repo root) holds gitignore-style globs, one per line; matching
10
+ files are never scanned. Blank lines and `#` comments are ignored.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import fnmatch
16
+ import os
17
+ import re
18
+ from typing import Dict, List, Optional
19
+
20
+ from .findings import Finding
21
+
22
+ IGNORE_FILE = ".mcpscanignore"
23
+
24
+ _MARKER = re.compile(r"mcpscan:\s*ignore(?:\[([A-Za-z0-9_,\s]+)\])?", re.IGNORECASE)
25
+
26
+
27
+ def load_ignore_patterns(root: str) -> List[str]:
28
+ path = os.path.join(root, IGNORE_FILE)
29
+ patterns: List[str] = []
30
+ try:
31
+ with open(path, "r", encoding="utf-8", errors="replace") as fh:
32
+ for raw in fh:
33
+ line = raw.strip()
34
+ if line and not line.startswith("#"):
35
+ patterns.append(line.rstrip("/"))
36
+ except OSError:
37
+ pass
38
+ return patterns
39
+
40
+
41
+ def path_ignored(relpath: str, patterns: List[str]) -> bool:
42
+ rel = relpath.replace(os.sep, "/")
43
+ for pat in patterns:
44
+ if fnmatch.fnmatch(rel, pat) or fnmatch.fnmatch(rel, pat + "/*"):
45
+ return True
46
+ # bare name like "secrets.json" should match anywhere in the tree
47
+ if "/" not in pat and fnmatch.fnmatch(os.path.basename(rel), pat):
48
+ return True
49
+ return False
50
+
51
+
52
+ def _line_suppresses(line: str, rule_id: str) -> bool:
53
+ m = _MARKER.search(line)
54
+ if not m:
55
+ return False
56
+ ids = m.group(1)
57
+ if not ids:
58
+ return True # bare ignore -> all rules
59
+ wanted = {x.strip().upper() for x in ids.split(",") if x.strip()}
60
+ return rule_id.upper() in wanted
61
+
62
+
63
+ def is_suppressed(finding: Finding, lines_by_path: Dict[str, List[str]]) -> bool:
64
+ lines: Optional[List[str]] = lines_by_path.get(finding.path)
65
+ if not lines or finding.line <= 0:
66
+ return False
67
+ idx = finding.line - 1 # 0-based
68
+ candidates = [idx]
69
+ if idx - 1 >= 0:
70
+ candidates.append(idx - 1) # marker on the line above
71
+ for i in candidates:
72
+ if 0 <= i < len(lines) and _line_suppresses(lines[i], finding.rule_id):
73
+ return True
74
+ return False