piton-cli 0.4.2__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,436 @@
1
+ """
2
+ Deterministic AI Coding-Agent Supply-Chain Linter (Piton).
3
+
4
+ Catches real-world coding-agent RCE & poisoning attacks in repository configs:
5
+ 1. `.claude/settings.json` & `.claude/settings.local.json`:
6
+ - Malicious `hooks` (`PreToolUse`, `PostToolUse`, `SessionStart`, `UserPromptSubmit`, `Stop`)
7
+ running download-and-exec (`curl|sh`, `wget|bash`), reverse shells, base64/inline payloads,
8
+ or harvesting `~/.aws`, `~/.ssh`, `.env`, `GITHUB_TOKEN`, `NPM_TOKEN`, etc.
9
+ - Dangerous overly-broad `permissions.allow` rules (`Bash`, `Bash(*)`, `Bash(curl*)`, `Bash(rm*)`).
10
+ 2. `.vscode/tasks.json` (full JSONC support: `//` inline comments, `/* */` block comments, trailing commas):
11
+ - Auto-executing `runOptions.runOn == "folderOpen"` tasks (classic repo-open RCE).
12
+ 3. `.mcp.json`, `mcp.json`, `.cursor/mcp.json`, `.vscode/mcp.json`:
13
+ - Malicious STDIO server `command`/`args` executing download-and-exec, reverse shells, or credential exfil.
14
+ 4. `.cursor/rules/*`, `.cursorrules`, `CLAUDE.md`, `AGENTS.md`, `.github/copilot-instructions.md`,
15
+ `.claude/skills/**/*.md`, `.claude/commands/**/*.md`:
16
+ - Invisible/bidi Unicode smuggling (zero-width chars, Trojan Source bidi overrides, Unicode Tags; UTF-8 BOM ignored)
17
+ - Covert prompt-injection instruction overrides, shell RCE, & credential exfiltration directives
18
+ (calibrated so benign docs like "Never commit .env" do NOT false-positive).
19
+ """
20
+
21
+ import json
22
+ from pathlib import Path
23
+ import re
24
+ from typing import Any, Dict, List, Tuple
25
+ import unicodedata
26
+ from pydantic import BaseModel
27
+
28
+ from piton.iac.poisoning_lint import (
29
+ INVISIBLE_UNICODE_RE,
30
+ LintSeverity,
31
+ PoisoningFinding,
32
+ )
33
+
34
+ # High-signal shell RCE & credential-harvesting patterns inside hook / MCP STDIO commands
35
+ _HOOK_DOWNLOAD_EXEC_RE = re.compile(
36
+ r"(?i)\b(?:curl|wget|fetch)\b[^\n]{0,200}\|\s*(?:sh|bash|zsh|dash|python3?|node|perl|ruby)\b"
37
+ )
38
+ _HOOK_REVERSE_SHELL_RE = re.compile(
39
+ r"(?i)(?:/dev/tcp/|nc\s+-[a-z]*e|ncat\s+-[a-z]*e|bash\s+-i\s+>&|mkfifo\s+/tmp/|socat\s+exec:|python3?\s+-c\s+['\"][^'\"]{0,200}socket)"
40
+ )
41
+ _HOOK_OBFUSCATED_EXEC_RE = re.compile(
42
+ r"(?i)(?:base64\s+(?:-d|--decode)[^\n]{0,120}\|\s*(?:sh|bash|zsh|python3?|node)|eval\s+\$\(|powershell[^\n]{0,80}-enc(?:odedcommand)?)"
43
+ )
44
+ _HOOK_CRED_EXFIL_RE = re.compile(
45
+ r"(?i)(?:(?:~/|\$HOME/)\.ssh|(?:~/|\$HOME/)\.aws|(?:~/|\$HOME/)\.kube|(?:~/|\$HOME/)\.npmrc|(?:~/|\$HOME/)\.netrc|/etc/shadow|id_rsa|aws_secret_access_key|github_token|npm_token|openai_api_key|anthropic_api_key|stripe_api_key|\.env\b)"
46
+ r"[^\n]{0,160}(?:curl|wget|nc|http://|https://|base64|webhook|discord|telegram|pastebin)"
47
+ )
48
+ _HOOK_NET_POST_RE = re.compile(
49
+ r"(?i)\b(?:curl|wget)\b[^\n]{0,180}(?:-d\b|--data|--upload-file|-F\b|-H\b|-X\s*POST)[^\n]{0,180}(?:\$[A-Z_]{3,}|/etc/|~/\.|\$HOME/\.|\.env\b|id_rsa)"
50
+ )
51
+ _DANGEROUS_PERMISSION_RE = re.compile(
52
+ r"(?i)^(?:Bash$|Bash\(\s*(?:\*|rm\b|curl\b|wget\b|sh\b|bash\b|sudo\b|chmod\b|chown\b|/bin/sh\b|/bin/bash\b))"
53
+ )
54
+
55
+ # Dedicated coding-agent instruction/rule file catalog (prevents false positives on benign CLAUDE.md docs)
56
+ AGENT_RULE_PATTERNS: Tuple[Tuple[str, LintSeverity, str, str], ...] = (
57
+ (
58
+ "AGENT_RULE_INSTRUCTION_OVERRIDE",
59
+ LintSeverity.CRITICAL,
60
+ r"(ignore\s+(all\s+)?(previous|prior|above)\s+instructions?|disregard\s+(all\s+)?(previous|prior)|new\s+system\s+prompt|override\s+system\s+instructions?)",
61
+ "Agent rule file contains prompt-override directives attempting to hijack coding-agent instructions.",
62
+ ),
63
+ (
64
+ "AGENT_RULE_COVERT_CONCEALMENT",
65
+ LintSeverity.CRITICAL,
66
+ r"(do\s+not\s+(tell|inform|mention|show|notify)\s+the\s+user|never\s+mention\s+this|hide\s+this\s+from\s+the\s+user|silently\s+(send|forward|copy|bcc|exfiltrate|execute))",
67
+ "Agent rule file contains covert concealment directives instructing the agent to hide actions from the user.",
68
+ ),
69
+ (
70
+ "AGENT_RULE_CREDENTIAL_EXFIL",
71
+ LintSeverity.CRITICAL,
72
+ r"((?:~/|\$HOME/)\.ssh/id_(?:rsa|ed25519)|(?:~/|\$HOME/)\.aws/credentials|/etc/shadow|(?:read|cat|copy|send|post|upload|forward|exfiltrat\w*)\s+[^\n]{0,80}(?:~/\.ssh|~/\.aws/credentials|id_rsa|id_ed25519|/etc/shadow)|(?:send|post|upload|forward|exfiltrat\w*|curl|wget)\s+[^\n]{0,80}\.env\b|\bexfiltrat\w*\b[^\n]{0,80}(?:\.env\b|secret|token|key|ssh|cred|passwd)|webhook\.site|ngrok\.io|pass\s+(all|the)\s+(api\s+keys?|secrets?|tokens?|credentials?))",
73
+ "Agent rule file directs credential reading or covert outbound exfiltration.",
74
+ ),
75
+ (
76
+ "AGENT_RULE_SHELL_RCE",
77
+ LintSeverity.HIGH,
78
+ r"(\bcurl\s+[^|\n]{1,120}\|\s*(?:ba)?sh\b|\bwget\s+[^|\n]{1,120}\|\s*(?:ba)?sh\b|powershell\s+-enc)",
79
+ "Agent rule file embeds pipe-to-shell or encoded command execution directives.",
80
+ ),
81
+ )
82
+
83
+ _MCP_CONFIG_CANDIDATES = (
84
+ ".mcp.json",
85
+ "mcp.json",
86
+ ".cursor/mcp.json",
87
+ ".vscode/mcp.json",
88
+ )
89
+
90
+
91
+ class AgentConfigScanResult(BaseModel):
92
+ scanned_files: List[str]
93
+ findings: List[PoisoningFinding]
94
+
95
+ @property
96
+ def critical_or_high_count(self) -> int:
97
+ return sum(
98
+ 1
99
+ for f in self.findings
100
+ if f.severity in (LintSeverity.CRITICAL, LintSeverity.HIGH)
101
+ )
102
+
103
+
104
+ def _parse_jsonc(raw: str) -> Any:
105
+ """
106
+ Parses JSONC (VS Code / Cursor config files) by stripping `//` inline comments,
107
+ `/* ... */` block comments outside strings, and trailing commas before `}` or `]`.
108
+ """
109
+ out: List[str] = []
110
+ i = 0
111
+ n = len(raw)
112
+ in_str = False
113
+ esc = False
114
+ while i < n:
115
+ ch = raw[i]
116
+ if in_str:
117
+ out.append(ch)
118
+ if esc:
119
+ esc = False
120
+ elif ch == "\\":
121
+ esc = True
122
+ elif ch == '"':
123
+ in_str = False
124
+ i += 1
125
+ continue
126
+ if ch == '"':
127
+ in_str = True
128
+ out.append(ch)
129
+ i += 1
130
+ continue
131
+ if ch == "/" and i + 1 < n and raw[i + 1] == "/":
132
+ i += 2
133
+ while i < n and raw[i] not in ("\n", "\r"):
134
+ i += 1
135
+ continue
136
+ if ch == "/" and i + 1 < n and raw[i + 1] == "*":
137
+ i += 2
138
+ while i + 1 < n and not (raw[i] == "*" and raw[i + 1] == "/"):
139
+ i += 1
140
+ i += 2
141
+ continue
142
+ out.append(ch)
143
+ i += 1
144
+
145
+ stripped = "".join(out)
146
+ # Remove trailing commas before closing object/array braces
147
+ stripped = re.sub(r",(\s*[}\]])", r"\1", stripped)
148
+ return json.loads(stripped)
149
+
150
+
151
+ def _extract_hook_commands(obj: Any, path_prefix: str = "") -> List[tuple[str, str]]:
152
+ """Recursively extracts `(hook_path, command_string)` from `.claude/settings.json` hooks."""
153
+ out: List[tuple[str, str]] = []
154
+ if isinstance(obj, dict):
155
+ cmd = obj.get("command")
156
+ if isinstance(cmd, str) and cmd.strip():
157
+ out.append((path_prefix or "hooks", cmd.strip()))
158
+ for k, v in obj.items():
159
+ if k == "command":
160
+ continue
161
+ sub = f"{path_prefix}.{k}" if path_prefix else str(k)
162
+ out.extend(_extract_hook_commands(v, sub))
163
+ elif isinstance(obj, list):
164
+ for idx, item in enumerate(obj):
165
+ out.extend(_extract_hook_commands(item, f"{path_prefix}[{idx}]"))
166
+ return out
167
+
168
+
169
+ def _lint_shell_command(
170
+ server_label: str,
171
+ rel_path: str,
172
+ loc: str,
173
+ raw_cmd: str,
174
+ subject: str,
175
+ ) -> List[PoisoningFinding]:
176
+ findings: List[PoisoningFinding] = []
177
+ cmd = unicodedata.normalize("NFKC", raw_cmd)
178
+ if _HOOK_DOWNLOAD_EXEC_RE.search(cmd):
179
+ findings.append(
180
+ PoisoningFinding(
181
+ server_name=server_label,
182
+ tool_name=rel_path,
183
+ rule_id="AGENT_HOOK_DOWNLOAD_EXEC",
184
+ severity=LintSeverity.CRITICAL,
185
+ field_path=loc,
186
+ message=f"{subject} downloads and pipes remote code directly into a shell/interpreter.",
187
+ matched_snippet=cmd[:160],
188
+ )
189
+ )
190
+ if _HOOK_REVERSE_SHELL_RE.search(cmd):
191
+ findings.append(
192
+ PoisoningFinding(
193
+ server_name=server_label,
194
+ tool_name=rel_path,
195
+ rule_id="AGENT_HOOK_REVERSE_SHELL",
196
+ severity=LintSeverity.CRITICAL,
197
+ field_path=loc,
198
+ message=f"{subject} contains an interactive/reverse shell command.",
199
+ matched_snippet=cmd[:160],
200
+ )
201
+ )
202
+ if _HOOK_OBFUSCATED_EXEC_RE.search(cmd):
203
+ findings.append(
204
+ PoisoningFinding(
205
+ server_name=server_label,
206
+ tool_name=rel_path,
207
+ rule_id="AGENT_HOOK_OBFUSCATED_EXEC",
208
+ severity=LintSeverity.CRITICAL,
209
+ field_path=loc,
210
+ message=f"{subject} decodes or dynamically evaluates obfuscated shell payloads.",
211
+ matched_snippet=cmd[:160],
212
+ )
213
+ )
214
+ if _HOOK_CRED_EXFIL_RE.search(cmd) or _HOOK_NET_POST_RE.search(cmd):
215
+ findings.append(
216
+ PoisoningFinding(
217
+ server_name=server_label,
218
+ tool_name=rel_path,
219
+ rule_id="AGENT_HOOK_CREDENTIAL_EXFIL",
220
+ severity=LintSeverity.CRITICAL,
221
+ field_path=loc,
222
+ message=f"{subject} accesses credentials/secrets and transmits data over the network.",
223
+ matched_snippet=cmd[:160],
224
+ )
225
+ )
226
+ return findings
227
+
228
+
229
+ def lint_claude_settings(rel_path: str, data: Dict[str, Any]) -> List[PoisoningFinding]:
230
+ findings: List[PoisoningFinding] = []
231
+
232
+ hooks = data.get("hooks")
233
+ if hooks is not None:
234
+ for hook_loc, raw_cmd in _extract_hook_commands(hooks, "hooks"):
235
+ findings.extend(
236
+ _lint_shell_command("agent-config", rel_path, hook_loc, raw_cmd, "Claude Code hook")
237
+ )
238
+
239
+ perms = data.get("permissions")
240
+ if isinstance(perms, dict):
241
+ allow_list = perms.get("allow")
242
+ if isinstance(allow_list, list):
243
+ for entry in allow_list:
244
+ if isinstance(entry, str) and _DANGEROUS_PERMISSION_RE.search(entry.strip()):
245
+ findings.append(
246
+ PoisoningFinding(
247
+ server_name="agent-config",
248
+ tool_name=rel_path,
249
+ rule_id="AGENT_UNSAFE_PERMISSION_WILDCARD",
250
+ severity=LintSeverity.HIGH,
251
+ field_path="permissions.allow",
252
+ message=f"Overly permissive auto-approve rule '{entry.strip()}' bypasses human confirmation for dangerous shell commands.",
253
+ matched_snippet=entry.strip()[:120],
254
+ )
255
+ )
256
+ return findings
257
+
258
+
259
+ def lint_vscode_tasks(rel_path: str, data: Dict[str, Any]) -> List[PoisoningFinding]:
260
+ findings: List[PoisoningFinding] = []
261
+ tasks = data.get("tasks")
262
+ if not isinstance(tasks, list):
263
+ return findings
264
+ for idx, task in enumerate(tasks):
265
+ if not isinstance(task, dict):
266
+ continue
267
+ run_opts = task.get("runOptions")
268
+ if isinstance(run_opts, dict) and str(run_opts.get("runOn") or "").lower() == "folderopen":
269
+ label = str(task.get("label") or f"task[{idx}]")
270
+ cmd = str(task.get("command") or "")
271
+ findings.append(
272
+ PoisoningFinding(
273
+ server_name="agent-config",
274
+ tool_name=rel_path,
275
+ rule_id="VSCODE_FOLDER_OPEN_AUTORUN",
276
+ severity=LintSeverity.CRITICAL,
277
+ field_path=f"tasks[{idx}].runOptions.runOn",
278
+ message="VS Code / Cursor task executes automatically on folderOpen (untrusted repo RCE vector).",
279
+ matched_snippet=cmd[:160] or label,
280
+ )
281
+ )
282
+ return findings
283
+
284
+
285
+ def lint_mcp_stdio_configs(rel_path: str, data: Dict[str, Any]) -> List[PoisoningFinding]:
286
+ findings: List[PoisoningFinding] = []
287
+ servers = data.get("mcpServers") or data.get("servers")
288
+ if not isinstance(servers, dict):
289
+ return findings
290
+ for srv_name, srv_cfg in servers.items():
291
+ if not isinstance(srv_cfg, dict):
292
+ continue
293
+ cmd = srv_cfg.get("command")
294
+ args = srv_cfg.get("args") or []
295
+ if isinstance(cmd, str) and cmd.strip():
296
+ full_cmd = " ".join([cmd.strip()] + [str(a) for a in args if a is not None])
297
+ findings.extend(
298
+ _lint_shell_command(
299
+ "mcp-config",
300
+ rel_path,
301
+ f"mcpServers.{srv_name}",
302
+ full_cmd,
303
+ f"MCP STDIO server '{srv_name}' command",
304
+ )
305
+ )
306
+ return findings
307
+
308
+
309
+ def lint_agent_instruction_file(rel_path: str, content: str) -> List[PoisoningFinding]:
310
+ """
311
+ Scans the full coding-agent instruction/rule/skill markdown file for invisible/bidi
312
+ Unicode smuggling, prompt-override directives, covert concealment, shell RCE, and
313
+ credential exfiltration instructions — without flagging benign docs like "Never commit .env".
314
+ """
315
+ findings: List[PoisoningFinding] = []
316
+ # Strip standard leading UTF-8 BOM so legitimate editors don't trigger invisible-Unicode
317
+ text = content[1:] if content.startswith("\ufeff") else content
318
+ if not text:
319
+ return findings
320
+
321
+ m_inv = INVISIBLE_UNICODE_RE.search(text)
322
+ if m_inv:
323
+ start = max(0, m_inv.start() - 30)
324
+ end = min(len(text), m_inv.end() + 70)
325
+ findings.append(
326
+ PoisoningFinding(
327
+ server_name="agent-rules",
328
+ tool_name=rel_path,
329
+ rule_id="AGENT_RULE_INVISIBLE_UNICODE",
330
+ severity=LintSeverity.CRITICAL,
331
+ field_path="content",
332
+ message="Agent rule file contains invisible zero-width, bidi-override, or Unicode tag characters.",
333
+ matched_snippet=repr(text[start:end]),
334
+ )
335
+ )
336
+
337
+ normalized = unicodedata.normalize("NFKC", INVISIBLE_UNICODE_RE.sub("", text))
338
+ for rule_id, severity, pattern, msg in AGENT_RULE_PATTERNS:
339
+ m = re.search(pattern, normalized, re.IGNORECASE)
340
+ if m:
341
+ findings.append(
342
+ PoisoningFinding(
343
+ server_name="agent-rules",
344
+ tool_name=rel_path,
345
+ rule_id=rule_id,
346
+ severity=severity,
347
+ field_path="content",
348
+ message=msg,
349
+ matched_snippet=m.group(0)[:140],
350
+ )
351
+ )
352
+
353
+ return findings
354
+
355
+
356
+ def scan_agent_supply_chain(repo_path: Path) -> AgentConfigScanResult:
357
+ """
358
+ Scans a repository for coding-agent RCE hooks, auto-run tasks, malicious STDIO MCP
359
+ commands, and poisoned instruction/skill files across Claude Code, Cursor, VS Code, and Copilot.
360
+ """
361
+ repo_root = repo_path.resolve()
362
+ scanned: List[str] = []
363
+ findings: List[PoisoningFinding] = []
364
+
365
+ # 1. Claude Code settings & hooks
366
+ for rel in (".claude/settings.json", ".claude/settings.local.json"):
367
+ p = repo_root / rel
368
+ if p.is_file():
369
+ scanned.append(rel)
370
+ try:
371
+ data = _parse_jsonc(p.read_text(encoding="utf-8"))
372
+ if isinstance(data, dict):
373
+ findings.extend(lint_claude_settings(rel, data))
374
+ except Exception:
375
+ pass
376
+
377
+ # 2. VS Code / Cursor tasks.json folderOpen RCE (full JSONC support)
378
+ tasks_path = repo_root / ".vscode" / "tasks.json"
379
+ if tasks_path.is_file():
380
+ scanned.append(".vscode/tasks.json")
381
+ try:
382
+ data = _parse_jsonc(tasks_path.read_text(encoding="utf-8"))
383
+ if isinstance(data, dict):
384
+ findings.extend(lint_vscode_tasks(".vscode/tasks.json", data))
385
+ except Exception:
386
+ pass
387
+
388
+ # 3. MCP JSON configs (STDIO command/args RCE scan before `piton init --probe`)
389
+ for rel in _MCP_CONFIG_CANDIDATES:
390
+ p = repo_root / rel
391
+ if p.is_file():
392
+ scanned.append(rel)
393
+ try:
394
+ data = _parse_jsonc(p.read_text(encoding="utf-8"))
395
+ if isinstance(data, dict):
396
+ findings.extend(lint_mcp_stdio_configs(rel, data))
397
+ except Exception:
398
+ pass
399
+
400
+ # 4. Coding-agent rules, instructions & skill markdown files
401
+ rule_candidates: List[Path] = []
402
+ for single in (
403
+ ".cursorrules",
404
+ "CLAUDE.md",
405
+ ".claude/CLAUDE.md",
406
+ "AGENTS.md",
407
+ ".github/copilot-instructions.md",
408
+ ):
409
+ p = repo_root / single
410
+ if p.is_file():
411
+ rule_candidates.append(p)
412
+
413
+ for glob_dir, patterns in (
414
+ (repo_root / ".cursor" / "rules", ("*.mdc", "*.md", "*.txt")),
415
+ (repo_root / ".claude" / "skills", ("*.md",)),
416
+ (repo_root / ".claude" / "commands", ("*.md",)),
417
+ (repo_root / ".agents" / "skills", ("*.md",)),
418
+ ):
419
+ if glob_dir.is_dir():
420
+ for pat in patterns:
421
+ rule_candidates.extend(sorted(glob_dir.rglob(pat)))
422
+
423
+ seen_paths = set()
424
+ for p in rule_candidates:
425
+ if p in seen_paths or not p.is_file():
426
+ continue
427
+ seen_paths.add(p)
428
+ rel = str(p.relative_to(repo_root))
429
+ scanned.append(rel)
430
+ try:
431
+ content = p.read_text(encoding="utf-8", errors="replace")
432
+ findings.extend(lint_agent_instruction_file(rel, content))
433
+ except Exception:
434
+ pass
435
+
436
+ return AgentConfigScanResult(scanned_files=scanned, findings=findings)