foldscan 0.1.0__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.
foldscan/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
File without changes
@@ -0,0 +1,284 @@
1
+ """SKILL.md frontmatter and prose-structure rules. Owned by the prose rule-author (S3).
2
+
3
+ Interface: analyze_skill_md(path: str, text: str) -> list[Finding]
4
+
5
+ The frontmatter is screened for YAML tags and alias bombs before ruamel's SAFE loader sees it, and every
6
+ parser failure degrades to a finding instead of an exception. Heuristics here are raise-only or
7
+ conservative: when in doubt, a rule stays silent rather than flagging ordinary prose.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import re
13
+
14
+ from ruamel.yaml import YAML
15
+
16
+ from foldscan.analyze.registry import emit
17
+ from foldscan.model import Finding, Layer
18
+
19
+ MAX_FRONTMATTER_BYTES = 64 * 1024
20
+ MAX_ANCHORS_AND_ALIASES = 10
21
+
22
+ BUILTIN_COMMANDS = frozenset({
23
+ "init", "commit", "review", "compact", "clear", "config", "help", "login", "logout", "memory", "model",
24
+ "permissions", "plan", "mcp", "agents", "hooks", "doctor", "cost", "status", "resume", "bug",
25
+ "terminal-setup", "security-review",
26
+ })
27
+
28
+ # Description phrasing that claims every request or overrides other skills and built-ins.
29
+ _SHADOW_DESC = re.compile(
30
+ r"\b(?:for|on)\s+(?:every|all)\s+(?:\w+\s+)?(?:tasks?|requests?)\b"
31
+ r"|\balways\s+(?:use|invoke|run|trigger|activate)\s+(?:this|it|the\s+skill)\b"
32
+ r"|\bbefore\s+(?:any|all)\s+other\s+skills?\b"
33
+ r"|\binstead\s+of\s+(?:the\s+)?built[- ]?in\b",
34
+ re.IGNORECASE,
35
+ )
36
+ _UNRESTRICTED_BASH = frozenset({"Bash", "Bash(*)", "Bash(*:*)"})
37
+ _PERMISSION_KEYS = ("allowed-tools", "allowed_tools", "tools")
38
+ _NARROW_TASK = re.compile(r"\b(?:summari[sz]e|format|convert|lint|csv|markdown)\b", re.IGNORECASE)
39
+ _NETWORK_CMD = re.compile(r"\b(?:curl|wget)\b", re.IGNORECASE)
40
+ _URL = re.compile(r"https?://([^/\s\"'<>)`]+)", re.IGNORECASE)
41
+ _CREDENTIAL_OR_REGISTRY = re.compile(
42
+ r"~/\.(?:ssh|aws|npmrc|pypirc|netrc|git-credentials|docker/config\.json|kube/config|config/gcloud)"
43
+ r"|\.npmrc\b|\.pypirc\b|\bpip\.conf\b|\.yarnrc\b|PIP_INDEX_URL|UV_INDEX_URL|\bregistry\s*=",
44
+ re.IGNORECASE,
45
+ )
46
+ # Hosts that count as documentation for the mismatch heuristic. Matched by exact domain or subdomain only,
47
+ # so a name like docs.attacker.example does not pass.
48
+ _DOC_DOMAINS = ("python.org", "readthedocs.io", "readthedocs.org", "mozilla.org", "anthropic.com", "claude.com")
49
+ _BOUNDARY = frozenset(" \t[{,:-?")
50
+ _ANCHOR_NAME = re.compile(r"[A-Za-z0-9_-]")
51
+ _TOP_KEY = re.compile(r"^([A-Za-z_][\w-]*)[ \t]*:(.*)$")
52
+
53
+
54
+ def _is_boundary(line: str, i: int) -> bool:
55
+ return i == 0 or line[i - 1] in _BOUNDARY
56
+
57
+
58
+ def _mask_quotes(line: str) -> list[bool]:
59
+ """Mark characters that sit inside a quoted scalar or a comment.
60
+
61
+ Quotes open only at a token boundary, so an apostrophe in "don't" does not hide later text. State resets
62
+ per line, which can only over-flag, never hide a tag.
63
+ """
64
+ masked = [False] * len(line)
65
+ quote: str | None = None
66
+ i = 0
67
+ while i < len(line):
68
+ ch = line[i]
69
+ if quote is not None:
70
+ masked[i] = True
71
+ if quote == '"' and ch == "\\" and i + 1 < len(line):
72
+ masked[i + 1] = True
73
+ i += 2
74
+ continue
75
+ if ch == quote:
76
+ if quote == "'" and i + 1 < len(line) and line[i + 1] == "'":
77
+ masked[i + 1] = True
78
+ i += 2
79
+ continue
80
+ quote = None
81
+ i += 1
82
+ continue
83
+ if ch in "\"'" and _is_boundary(line, i):
84
+ quote = ch
85
+ masked[i] = True
86
+ elif ch == "#" and _is_boundary(line, i):
87
+ break
88
+ i += 1
89
+ return masked
90
+
91
+
92
+ def _line_specials(line: str) -> tuple[bool, int]:
93
+ """Return (has_tag, anchor_or_alias_count) for the unquoted part of one frontmatter line."""
94
+ masked = _mask_quotes(line)
95
+ tag = False
96
+ refs = 0
97
+ for i, ch in enumerate(line):
98
+ if masked[i] or ch not in "!&*" or not _is_boundary(line, i):
99
+ continue
100
+ if ch == "!":
101
+ before = line[:i].rstrip()
102
+ # A tag starts a node: after line start, a key colon, a sequence dash, a flow opener or an anchor.
103
+ # "Wow !" is prose, not a tag.
104
+ if not before or before[-1] in ":-[{,?" or re.search(r"&\S*$", before):
105
+ tag = True
106
+ elif i + 1 < len(line) and _ANCHOR_NAME.match(line[i + 1]):
107
+ refs += 1
108
+ return tag, refs
109
+
110
+
111
+ def _parse(fm_text: str) -> dict | None:
112
+ try:
113
+ data = YAML(typ="safe", pure=True).load(fm_text)
114
+ except Exception: # any parser failure is a finding, never a crash
115
+ return None
116
+ return data if isinstance(data, dict) else None
117
+
118
+
119
+ def _fallback_fields(fm_lines: list[str]) -> dict[str, str]:
120
+ """Top-level `key: value` pairs read line by line, used only when the YAML parse failed."""
121
+ fields: dict[str, str] = {}
122
+ for line in fm_lines:
123
+ m = _TOP_KEY.match(line)
124
+ if m and m.group(1) not in fields:
125
+ fields[m.group(1)] = m.group(2).strip().strip("\"'")
126
+ return fields
127
+
128
+
129
+ def _text(value: object) -> str:
130
+ return value.strip() if isinstance(value, str) else ""
131
+
132
+
133
+ def _key_line(fm_lines: list[str], keys: tuple[str, ...]) -> int:
134
+ """1-based line in the original file of the first top-level key, or 1 when not found."""
135
+ rx = re.compile("^(?:" + "|".join(re.escape(k) for k in keys) + r")\s*:")
136
+ for idx, line in enumerate(fm_lines):
137
+ if rx.match(line):
138
+ return idx + 2 # fm_lines[0] is file line 2
139
+ return 1
140
+
141
+
142
+ def _tool_tokens(value: object) -> list[str]:
143
+ """Split an allowed-tools value into entries, keeping commas and spaces inside parentheses."""
144
+ if isinstance(value, list):
145
+ return [str(v).strip() for v in value if str(v).strip()]
146
+ if not isinstance(value, str):
147
+ return []
148
+ tokens: list[str] = []
149
+ buf: list[str] = []
150
+ depth = 0
151
+ for ch in value.strip().strip("[]"):
152
+ if ch == "(":
153
+ depth += 1
154
+ elif ch == ")":
155
+ depth = max(0, depth - 1)
156
+ if depth == 0 and (ch == "," or ch.isspace()):
157
+ if buf:
158
+ tokens.append("".join(buf))
159
+ buf = []
160
+ else:
161
+ buf.append(ch)
162
+ if buf:
163
+ tokens.append("".join(buf))
164
+ return tokens
165
+
166
+
167
+ def _permission_reason(value: object) -> str | None:
168
+ tokens = _tool_tokens(value)
169
+ unrestricted = [t for t in tokens if t in _UNRESTRICTED_BASH]
170
+ if unrestricted:
171
+ return f"grants unrestricted shell access ({unrestricted[0]})"
172
+ if "*" in tokens:
173
+ return "grants every tool (*)"
174
+ if "WebFetch" in tokens and any(t == "Bash" or t.startswith("Bash(") for t in tokens):
175
+ return "combines WebFetch with Bash"
176
+ for t in tokens:
177
+ m = re.fullmatch(r"Write\((.*)\)", t)
178
+ if m and (m.group(1).startswith(("~", "/")) or ".." in m.group(1)):
179
+ return f"allows writes outside the skill ({t})"
180
+ return None
181
+
182
+
183
+ def _body_hit(body: list[str], first_line: int) -> tuple[int, str] | None:
184
+ """First body line that fetches from the network to a non-doc host, or reads credential/registry config."""
185
+ for idx, line in enumerate(body):
186
+ hit = bool(_NETWORK_CMD.search(line)) or _CREDENTIAL_OR_REGISTRY.search(line) is not None
187
+ for m in _URL.finditer(line):
188
+ host = m.group(1).split("@")[-1].split(":")[0].lower()
189
+ if not any(host == d or host.endswith("." + d) for d in _DOC_DOMAINS):
190
+ hit = True
191
+ if hit:
192
+ return first_line + idx, line.strip()[:160]
193
+ return None
194
+
195
+
196
+ def _missing(path: str, reason: str, line: int) -> Finding:
197
+ return emit("FS-META-MISSING", f"SKILL.md metadata problem: {reason}.", path=path, layer=Layer.META,
198
+ line=line)
199
+
200
+
201
+ def analyze_skill_md(path: str, text: str) -> list[Finding]:
202
+ out: list[Finding] = []
203
+ lines = text.lstrip("").split("\n")
204
+ if not lines or lines[0].rstrip("\r") != "---":
205
+ return [_missing(path, "no YAML frontmatter at the top of the file", 1)]
206
+ close = next((i for i in range(1, len(lines)) if lines[i].rstrip() == "---"), None)
207
+ if close is None:
208
+ return [_missing(path, "frontmatter is not closed by a '---' line", 1)]
209
+
210
+ fm_lines = lines[1:close]
211
+ fm_text = "\n".join(fm_lines)
212
+ body = lines[close + 1:]
213
+ body_first_line = close + 2 # 1-based line of body[0]
214
+
215
+ if len(fm_text.encode("utf-8", "replace")) > MAX_FRONTMATTER_BYTES:
216
+ return [emit("FS-META-UNSAFE-YAML", "Frontmatter exceeds 64 KB and was not parsed.", path=path,
217
+ layer=Layer.META, line=1)]
218
+
219
+ tag_lines: list[int] = []
220
+ ref_lines: list[int] = []
221
+ total_refs = 0
222
+ for idx, line in enumerate(fm_lines):
223
+ tag, refs = _line_specials(line)
224
+ if tag:
225
+ tag_lines.append(idx + 2)
226
+ if refs:
227
+ ref_lines.append(idx + 2)
228
+ total_refs += refs
229
+ if tag_lines or total_refs > MAX_ANCHORS_AND_ALIASES:
230
+ if tag_lines:
231
+ reason = "uses YAML tags (language-specific tags are never allowed in SKILL.md)"
232
+ at = tag_lines[0]
233
+ evidence = fm_lines[tag_lines[0] - 2].strip()
234
+ else:
235
+ reason = f"uses {total_refs} anchors and aliases (limit {MAX_ANCHORS_AND_ALIASES})"
236
+ at = ref_lines[0]
237
+ evidence = fm_lines[ref_lines[0] - 2].strip()
238
+ return [emit("FS-META-UNSAFE-YAML", f"Frontmatter {reason}. Parsing was refused.", path=path,
239
+ layer=Layer.META, line=at, evidence=evidence)]
240
+
241
+ data = _parse(fm_text)
242
+ fields: dict[str, object] = dict(data) if data is not None else dict(_fallback_fields(fm_lines))
243
+ name = _text(fields.get("name"))
244
+ desc = _text(fields.get("description"))
245
+
246
+ problems = []
247
+ if data is None:
248
+ problems.append("frontmatter could not be parsed as YAML")
249
+ missing = [k for k, v in (("name", name), ("description", desc)) if not v]
250
+ if missing:
251
+ problems.append(f"lacks {' and '.join(missing)}")
252
+ if problems:
253
+ out.append(_missing(path, "; ".join(problems), 1))
254
+
255
+ if name:
256
+ if name.lstrip("/").strip().lower() in BUILTIN_COMMANDS:
257
+ out.append(emit("FS-META-SHADOW", f"Skill name '{name}' claims a built-in Claude Code command.",
258
+ path=path, layer=Layer.META, line=_key_line(fm_lines, ("name",)), evidence=name))
259
+ if desc:
260
+ m = _SHADOW_DESC.search(desc)
261
+ if m:
262
+ out.append(emit("FS-META-SHADOW",
263
+ "Description asks to run for every request, ahead of other skills, or in place of "
264
+ "a built-in.", path=path, layer=Layer.META,
265
+ line=_key_line(fm_lines, ("description",)), evidence=desc))
266
+
267
+ for key in _PERMISSION_KEYS:
268
+ if key not in fields:
269
+ continue
270
+ why = _permission_reason(fields[key])
271
+ if why:
272
+ out.append(emit("FS-META-PERMS", f"'{key}' {why}.", path=path, layer=Layer.META,
273
+ line=_key_line(fm_lines, (key,)), evidence=str(fields[key])))
274
+
275
+ if desc and _NARROW_TASK.search(desc):
276
+ hit = _body_hit(body, body_first_line)
277
+ if hit:
278
+ at, snippet = hit
279
+ out.append(emit("FS-META-MISMATCH",
280
+ "Description claims a narrow local task, but the body fetches from the network, "
281
+ "reads credential paths or changes registry config.", path=path, layer=Layer.META,
282
+ line=at, confidence="low",
283
+ evidence=f'description: "{desc[:160]}" | body line {at}: {snippet}'))
284
+ return out
@@ -0,0 +1,208 @@
1
+ """Rule registry. Owned by the main agent: subagents propose additions, never edit directly.
2
+
3
+ Every rule has stable metadata (used by SARIF, docs and `foldscan rules`) and is emitted
4
+ through `emit()`, so severities and AST mappings live in exactly one place.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from dataclasses import dataclass
11
+
12
+ from foldscan.model import Confidence, Finding, Layer, Location, Severity
13
+
14
+ RULESET_VERSION = "2026.11.0"
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class Rule:
19
+ rule_id: str
20
+ name: str # PascalCase, <= 255 chars (SARIF)
21
+ title: str
22
+ description: str # <= 1024 chars
23
+ ast: tuple[str, ...]
24
+ severity: Severity
25
+ confidence: Confidence = "high"
26
+
27
+
28
+ RULES: dict[str, Rule] = {}
29
+
30
+
31
+ def rule(rule_id: str, name: str, title: str, description: str, ast: tuple[str, ...],
32
+ severity: Severity, confidence: Confidence = "high") -> Rule:
33
+ assert rule_id not in RULES, f"duplicate rule {rule_id}"
34
+ assert len(description) <= 1024 and len(name) <= 255
35
+ r = Rule(rule_id, name, title, description, ast, severity, confidence)
36
+ RULES[rule_id] = r
37
+ return r
38
+
39
+
40
+ def emit(rule_id: str, message: str, *, path: str, layer: Layer = Layer.RAW, evidence: str = "",
41
+ line: int | None = None, decode_chain: list[str] | None = None,
42
+ severity: Severity | None = None, confidence: Confidence | None = None) -> Finding:
43
+ r = RULES[rule_id]
44
+ return Finding(
45
+ rule_id=rule_id,
46
+ ast_id=list(r.ast),
47
+ severity=severity if severity is not None else r.severity,
48
+ confidence=confidence or r.confidence,
49
+ title=r.title,
50
+ message=safe_evidence(message, 1024),
51
+ evidence=safe_evidence(evidence),
52
+ layer=layer,
53
+ location=Location(path=path, start_line=line, end_line=line, decode_chain=decode_chain or []),
54
+ )
55
+
56
+
57
+ _SECRET_PATTERNS = [
58
+ re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)"),
59
+ re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b"),
60
+ re.compile(r"\bgh[pousr]_[A-Za-z0-9]{36,}\b|\bgithub_pat_[A-Za-z0-9_]{40,}\b"),
61
+ re.compile(r"\bxox[abposr]-[A-Za-z0-9-]{10,}\b"),
62
+ re.compile(r"\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}\b"),
63
+ re.compile(r"\bnpm_[A-Za-z0-9]{36}\b|\bpypi-[A-Za-z0-9_-]{40,}\b"),
64
+ re.compile(r"(?i)\b(?:password|passwd|secret|token|api[_-]?key|_authToken)\b(\s*[:=]\s*[\"']?)[^\s\"']{6,}"),
65
+ re.compile(r"https?://[^/\s:@]+:[^/\s@]+@"), # credentials embedded in URLs
66
+ ]
67
+
68
+
69
+ def redact(text: str) -> str:
70
+ """Remove secrets before evidence reaches any report, log or model (security review V15/V16)."""
71
+ for rx in _SECRET_PATTERNS:
72
+ text = rx.sub(lambda m: (m.group(0).split(m.group(1))[0] + m.group(1) if m.lastindex else "")
73
+ + "[REDACTED]", text)
74
+ return text
75
+
76
+
77
+ def safe_evidence(text: str, limit: int = 400) -> str:
78
+ """Redact secrets, then escape control characters (incl. ANSI/OSC) so evidence cannot drive a terminal."""
79
+ out = []
80
+ for ch in redact(text[: limit * 2])[:limit]:
81
+ o = ord(ch)
82
+ if ch in "\t" or (o >= 0x20 and o != 0x7F and not (0x80 <= o < 0xA0) and not (0xD800 <= o < 0xE000)):
83
+ out.append(ch)
84
+ elif ch == "\n":
85
+ out.append("\\n")
86
+ else:
87
+ out.append(f"\\x{o:02x}" if o < 0x100 else f"\\u{o:04x}")
88
+ return "".join(out)
89
+
90
+
91
+ S = Severity
92
+
93
+ # ---- Coverage and inventory -------------------------------------------------------------
94
+ rule("FS-COV-UNSCANNABLE", "UnscannableFile", "File could not be analyzed",
95
+ "The file type has no analyzer or could not be read. Nothing inside it was checked; treat it as "
96
+ "unreviewed code (OWASP AST08).", ("AST08",), S.HIGH)
97
+ rule("FS-COV-TRUNCATED", "AnalysisTruncated", "A size or depth limit was reached",
98
+ "An internal limit was hit, so part of the content was not analyzed. Attackers pad files to hit "
99
+ "exactly these limits.", ("AST08",), S.HIGH)
100
+ rule("FS-INV-SYMLINK-ESCAPE", "SymlinkEscapesRoot", "Symlink points outside the skill",
101
+ "A symbolic link resolves outside the skill directory. It was not followed.", ("AST06", "AST01"), S.HIGH)
102
+ rule("FS-INV-HIDDEN-EXEC", "HiddenExecutable", "Hidden file contains executable content",
103
+ "A dotfile or file in a hidden directory contains script or binary content. Agents and installers "
104
+ "can run files SKILL.md never mentions.", ("AST08", "AST01"), S.MEDIUM)
105
+ rule("FS-INV-EXT-MISMATCH", "ExtensionMismatch", "File extension does not match content",
106
+ "The magic bytes disagree with the extension, a common way to hide archives or binaries.",
107
+ ("AST08",), S.MEDIUM)
108
+
109
+ # ---- Whitespace padding (Trail of Bits csv-summarizer) ----------------------------------
110
+ rule("FS-WS-PADDING", "WhitespacePadding", "Abnormal whitespace padding",
111
+ "A very long run of blank lines or spaces separates content. Padding is used to push payloads past "
112
+ "scanner and model context limits.", ("AST08", "AST01"), S.HIGH)
113
+
114
+ # ---- Archives and indirection (Trail of Bits context-loader) ----------------------------
115
+ rule("FS-ARC-PRESENT", "ArchiveBundled", "Skill bundles an archive",
116
+ "An archive or Office document is bundled. Its members were unpacked and scanned.", ("AST08",), S.MEDIUM)
117
+ rule("FS-ARC-SCRIPT", "ScriptInsideArchive", "Executable script inside an archive",
118
+ "A script or binary is hidden inside an archive or Office document, where pattern scanners do not "
119
+ "look.", ("AST01", "AST08"), S.HIGH)
120
+ rule("FS-ARC-BOMB", "ArchiveBomb", "Archive exceeds decompression limits",
121
+ "Decompression ratio, size or nesting exceeded safe limits; remaining members were not analyzed.",
122
+ ("AST08",), S.HIGH)
123
+ rule("FS-ARC-TRAVERSAL", "ArchivePathTraversal", "Archive member path escapes extraction root",
124
+ "An archive member uses an absolute path or '..' segments (zip-slip).", ("AST01",), S.HIGH)
125
+ rule("FS-IND-BINARY", "InstructionIndirectionLocal", "Instructions redirected to a bundled file",
126
+ "SKILL.md tells the agent to take instructions from an archive, document, image or binary, which "
127
+ "hides the real instructions from review.", ("AST05", "AST01"), S.HIGH)
128
+ rule("FS-IND-REMOTE", "InstructionIndirectionRemote", "Instructions fetched from a remote URL",
129
+ "SKILL.md tells the agent to load instructions from the network. What the URL serves can change "
130
+ "after review.", ("AST05", "AST07"), S.HIGH)
131
+
132
+ # ---- Bytecode (Trail of Bits simple-formatter) -----------------------------------------
133
+ rule("FS-PYC-SHIPPED", "BytecodeShipped", "Compiled Python bytecode is bundled",
134
+ "Skills have no reason to ship .pyc files; Python may load them instead of the reviewed source.",
135
+ ("AST01", "AST08"), S.HIGH)
136
+ rule("FS-PYC-MISMATCH", "BytecodeSourceMismatch", "Bytecode does not match its source",
137
+ "The .pyc contains names or constants absent from the matching .py source. The code that runs is "
138
+ "not the code that was reviewed.", ("AST01",), S.CRITICAL)
139
+ rule("FS-PYC-ORPHAN", "BytecodeWithoutSource", "Bytecode has no matching source",
140
+ "A .pyc file has no sibling source file to review.", ("AST01", "AST08"), S.HIGH)
141
+
142
+ # ---- Config / registry writes (Trail of Bits dev-env-setup) -----------------------------
143
+ rule("FS-CFG-REGISTRY", "PackageRegistryRedirect", "Package registry redirected",
144
+ "Content writes a package-manager registry setting (.npmrc, .yarnrc, pip.conf, uv, PIP_INDEX_URL) to "
145
+ "a non-default host. Deterministic: no model verdict can lower this.", ("AST02", "AST01"), S.CRITICAL)
146
+ rule("FS-PERSIST-RC", "ShellStartupWrite", "Writes to shell startup or scheduler",
147
+ "Content modifies shell rc files, cron, launch agents or git hooks to persist.", ("AST01", "AST03"), S.HIGH)
148
+
149
+ # ---- Encodings and Unicode (Adversa) -----------------------------------------------------
150
+ rule("FS-ENC-LAYERED", "LayeredEncoding", "Content hidden under multiple encodings",
151
+ "A blob decodes through two or more layers. Every layer was rescanned with the full ruleset.",
152
+ ("AST01",), S.MEDIUM)
153
+ rule("FS-UNI-CONFUSABLE", "ConfusableCharacters", "Look-alike characters in commands or URLs",
154
+ "Characters from another script imitate Latin letters inside code, a command or a URL. Rules matched "
155
+ "after folding them.", ("AST01",), S.HIGH)
156
+ rule("FS-UNI-INVISIBLE", "InvisibleCharacters", "Invisible zero-width characters",
157
+ "Zero-width characters can split keywords so pattern matching misses them.", ("AST01",), S.MEDIUM)
158
+ rule("FS-UNI-BIDI", "BidiControlCharacters", "Bidirectional control characters",
159
+ "Bidi overrides make displayed text differ from the bytes that run (Trojan Source).", ("AST01",), S.HIGH)
160
+
161
+ # ---- Execution, exfiltration, prompt injection ------------------------------------------
162
+ rule("FS-EXEC-REMOTE", "RemoteFetchExecute", "Downloads and executes remote code",
163
+ "Content pipes or passes downloaded content to a shell or interpreter.", ("AST01", "AST02"), S.CRITICAL)
164
+ rule("FS-SECRET-ACCESS", "SecretFileAccess", "Reads credential stores",
165
+ "Content reads SSH keys, cloud credentials, package tokens or keychains.", ("AST01", "AST03"), S.HIGH)
166
+ rule("FS-SECRET-EXFIL", "SecretExfiltration", "Sends secrets or environment over the network",
167
+ "Credential or environment access appears together with a network send in the same file.",
168
+ ("AST01",), S.CRITICAL, "medium")
169
+ rule("FS-PI-OVERRIDE", "InstructionOverride", "Attempts to override the agent's instructions",
170
+ "Text asks the agent to ignore, set aside or replace prior instructions or safety rules.",
171
+ ("AST01", "AST05"), S.HIGH, "medium")
172
+ rule("FS-PI-SECRECY", "SecrecyFromUser", "Asks the agent to hide actions from the user",
173
+ "Text tells the agent not to mention, reveal or report a step to the user.", ("AST01",), S.HIGH)
174
+ rule("FS-PI-JUDGE-ADDRESS", "AddressesReviewer", "Text addresses scanners or reviewers",
175
+ "Content speaks to a security scanner, reviewer or AI judge, usually to steer its verdict. That is "
176
+ "itself evidence of malicious intent.", ("AST01", "AST08"), S.HIGH)
177
+
178
+ # ---- S3: taint, obfuscation, metadata, YARA, judge ----------------------------------------
179
+ rule("FS-TAINT-SECRET-NET", "TaintSecretToNetwork", "Secret flows to a network call",
180
+ "Data read from environment variables or credential files reaches a network sink, possibly across "
181
+ "files in the skill.", ("AST01",), S.CRITICAL)
182
+ rule("FS-TAINT-SECRET-EXEC", "TaintSecretToExec", "Secret or external data flows into code execution",
183
+ "Environment, file or network data reaches eval, exec, a shell or a subprocess call.", ("AST01",), S.HIGH)
184
+ rule("FS-OBF-DYNAMIC-EXEC", "DynamicExecution", "Command or code assembled at runtime",
185
+ "A command or code string is built from fragments (variables, chr(), join, getattr) and then executed, "
186
+ "which hides it from literal pattern matching.", ("AST01",), S.HIGH)
187
+ rule("FS-OBF-SELF-EXTRACT", "SelfExtractingPayload", "Decompresses or decodes data, then executes it",
188
+ "Data is decoded or decompressed and immediately executed (self-extracting packing). Static analysis "
189
+ "cannot fully see what runs; dynamic detonation is planned for v1.x.", ("AST01", "AST08"), S.HIGH)
190
+ rule("FS-META-MISSING", "SkillMetadataMissing", "SKILL.md metadata missing or malformed",
191
+ "The SKILL.md frontmatter is missing, unparseable or lacks name/description.", ("AST04",), S.LOW)
192
+ rule("FS-META-UNSAFE-YAML", "UnsafeYamlFrontmatter", "Frontmatter uses YAML tags or alias bombs",
193
+ "The frontmatter uses language-specific YAML tags or excessive aliases, which can attack parsers.",
194
+ ("AST04", "AST01"), S.HIGH)
195
+ rule("FS-META-SHADOW", "TriggerShadowing", "Skill claims built-in commands or broad triggers",
196
+ "The skill name or description claims a built-in command (e.g. /commit, /init) or asks to be used for "
197
+ "every task, so it runs where the user expects something else.", ("AST04",), S.MEDIUM)
198
+ rule("FS-META-PERMS", "OverbroadPermissions", "Skill requests broad tool permissions",
199
+ "allowed-tools or similar metadata grants unrestricted shell, network or write access.", ("AST03",), S.MEDIUM)
200
+ rule("FS-YARA-MATCH", "YaraSignature", "YARA signature matched",
201
+ "A foldscan YARA signature matched this content. Severity comes from the signature's metadata.",
202
+ ("AST01",), S.HIGH)
203
+ rule("FS-JUDGE-RAISED", "ModelRaisedConcern", "Model review raised a concern",
204
+ "The optional LLM review flagged behavior the deterministic rules did not. It can only raise severity, "
205
+ "never lower a deterministic finding.", ("AST01",), S.MEDIUM, "medium")
206
+ rule("FS-META-MISMATCH", "PurposeBehaviorMismatch", "Declared purpose does not match behavior",
207
+ "The skill's description does not account for what its code does (model-assisted, raise-only).",
208
+ ("AST03",), S.MEDIUM, "medium")
File without changes
@@ -0,0 +1,157 @@
1
+ """Content rules: run on every view (raw, folded, decoded, archive member, bytecode strings, OCR).
2
+
3
+ Patterns avoid nested quantifiers and run with a timeout (regex DoS guard).
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass
9
+
10
+ import regex
11
+
12
+ from foldscan.analyze.registry import emit
13
+ from foldscan.model import Finding, Layer
14
+ from foldscan.normalize.text import View
15
+
16
+ TIMEOUT = 0.5 # seconds per pattern per view
17
+ F = regex.IGNORECASE | regex.MULTILINE
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class Pattern:
22
+ rule_id: str
23
+ rx: regex.Pattern[str]
24
+ message: str
25
+ prose_ok: bool = True # also fires in Markdown prose (False = code/command contexts only)
26
+ code_ok: bool = True # also fires in source code files (False = instruction text only)
27
+
28
+
29
+ def p(rule_id: str, pattern: str, message: str, prose_ok: bool = True, code_ok: bool = True) -> Pattern:
30
+ return Pattern(rule_id, regex.compile(pattern, F), message, prose_ok, code_ok)
31
+
32
+
33
+ DOWNLOADERS = r"(?:curl|wget|iwr|invoke-webrequest|irm|invoke-restmethod|fetch|aria2c)"
34
+ SHELLS = r"(?:ba|z|da|k|fi)?sh|python[0-9.]*|perl|ruby|node|iex|invoke-expression|pwsh|powershell"
35
+
36
+ PATTERNS: list[Pattern] = [
37
+ # Fetch and execute
38
+ p("FS-EXEC-REMOTE", rf"\b{DOWNLOADERS}\b[^\n|;]{{0,300}}\|\s*(?:sudo\s+)?(?:{SHELLS})\b",
39
+ "Downloaded content is piped straight into an interpreter."),
40
+ p("FS-EXEC-REMOTE", rf"(?:{SHELLS})\s+-c\s+[\"']?\$\(\s*{DOWNLOADERS}\b",
41
+ "Interpreter runs the output of a download."),
42
+ p("FS-EXEC-REMOTE", r"\b(?:bash|sh|zsh)\s+<\(\s*(?:curl|wget)\b", "Process substitution runs a download."),
43
+ p("FS-EXEC-REMOTE", r"\b(?:eval|exec)\s*\(\s*(?:requests\.get|urlopen|httpx\.get|fetch)\s*\(",
44
+ "Code evaluates content fetched from the network."),
45
+ p("FS-EXEC-REMOTE", r"\biex\s*\(\s*(?:new-object\s+net\.webclient|iwr|irm|invoke-webrequest)",
46
+ "PowerShell executes downloaded content."),
47
+ # Credential stores
48
+ p("FS-SECRET-ACCESS", r"~?/?\.(?:ssh/(?:id_[a-z0-9]+|authorized_keys|config)|aws/credentials|"
49
+ r"config/gcloud|docker/config\.json|kube/config|npmrc|pypirc|netrc|git-credentials)\b",
50
+ "References a credential store."),
51
+ p("FS-SECRET-ACCESS", r"\bsecurity\s+find-(?:generic|internet)-password\b|\bsecret-tool\s+lookup\b|"
52
+ r"\bcmdkey\s+/list\b|Login\s+Data|Cookies\.sqlite|key4\.db",
53
+ "Reads OS keychain or browser credential storage."),
54
+ # Registry / config redirection (deterministic floor; cannot be lowered)
55
+ p("FS-CFG-REGISTRY", r"\bregistry\s*=\s*[\"']?https?://(?!registry\.npmjs\.org|registry\.yarnpkg\.com)"
56
+ r"[^\s\"']+", "Sets an npm/yarn registry to a non-default host."),
57
+ p("FS-CFG-REGISTRY", r"\b(?:npm|yarn|pnpm)\s+config\s+set\s+[\"']?(?:@[\w-]+:)?registry\b",
58
+ "Changes the package registry via the package manager CLI."),
59
+ p("FS-CFG-REGISTRY", r"\b(?:index-url|extra-index-url|PIP_INDEX_URL|PIP_EXTRA_INDEX_URL|UV_INDEX_URL|"
60
+ r"UV_EXTRA_INDEX_URL)\s*[=:]\s*[\"']?https?://(?!pypi\.org)[^\s\"']+",
61
+ "Points pip/uv at a non-default package index."),
62
+ p("FS-CFG-REGISTRY", r"(?:>>?|tee\s+(?:-a\s+)?|write_text\(|open\([^)]{0,80}[\"'][wa])[^\n]{0,80}"
63
+ r"(?:\.npmrc|\.yarnrc|pip\.conf|pip\.ini|uv\.toml)", "Writes a package-manager config file."),
64
+ # Persistence
65
+ p("FS-PERSIST-RC", r"(?:>>|tee\s+-a|write_text\(|open\([^)]{0,80}[\"']a)[^\n]{0,80}"
66
+ r"\.(?:bashrc|zshrc|bash_profile|zprofile|profile|config/fish/config\.fish)\b",
67
+ "Appends to a shell startup file."),
68
+ p("FS-PERSIST-RC", r"\bcrontab\s+-|/etc/cron|LaunchAgents/[^\s]+\.plist|launchctl\s+load|"
69
+ r"systemctl\s+(?:--user\s+)?enable|\.git/hooks/(?:pre|post)-", "Installs a scheduled or startup job."),
70
+ # Prompt injection: override (multilingual, paraphrase-aware)
71
+ p("FS-PI-OVERRIDE", r"\b(?:ignore|disregard|forget|set\s+aside|override|bypass|drop|discard)\s+"
72
+ r"(?:all\s+|any\s+)?(?:of\s+)?(?:the\s+|your\s+)?(?:previous|prior|earlier|above|preceding|original|"
73
+ r"existing|system)\s+(?:instructions?|guidance|rules|directions|prompts?|guidelines|constraints)",
74
+ "Asks the agent to discard its prior instructions."),
75
+ p("FS-PI-OVERRIDE", r"\b(?:ignora|olvida|descarta)\s+(?:todas\s+)?(?:las\s+)?instrucciones\s+"
76
+ r"(?:anteriores|previas)|\bignore[zr]?\s+(?:toutes\s+)?(?:les\s+)?instructions\s+(?:précédentes|"
77
+ r"antérieures)|\bignoriere\s+(?:alle\s+)?(?:vorherigen|bisherigen)\s+(?:Anweisungen|Regeln)|"
78
+ r"\bignore\s+(?:todas\s+)?as\s+instruções\s+anteriores|忽略(?:之前|以上|先前)的(?:所有)?(?:指令|说明)|"
79
+ r"игнорируй(?:те)?\s+(?:все\s+)?(?:предыдущие|прежние)\s+инструкции|以前の指示を無視",
80
+ "Asks the agent to discard its prior instructions (non-English)."),
81
+ p("FS-PI-OVERRIDE", r"\b(?:disable|turn\s+off|skip|bypass)\s+(?:the\s+)?(?:safety|permission|"
82
+ r"confirmation|approval)\s+(?:checks?|prompts?|rules|features?)|--dangerously-skip-permissions",
83
+ "Asks the agent to switch off safety or permission checks."),
84
+ # Secrecy toward the user
85
+ p("FS-PI-SECRECY", r"\b(?:do\s+not|don'?t|never)\s+(?:mention|tell|inform|reveal|disclose|show|report|"
86
+ r"notify)\s+(?:this|it|that|anything)?\s*(?:step|action|command|file)?\s*(?:to\s+)?(?:the\s+)?user\b",
87
+ "Tells the agent to hide a step from the user."),
88
+ p("FS-PI-SECRECY", r"\bwithout\s+(?:telling|informing|notifying|asking)\s+the\s+user\b",
89
+ "Tells the agent to act without the user's knowledge."),
90
+ # Bare "silently" is ordinary in code comments ("silently fall back"); only instruction text counts.
91
+ p("FS-PI-SECRECY", r"\b(?:silently|quietly)\s+(?:run|execute|install|send|upload|copy|download|add|"
92
+ r"modify|edit|delete|remove|write|post|fetch|read)\b", "Tells the agent to act without the user's "
93
+ "knowledge.", code_ok=False),
94
+ p("FS-PI-SECRECY", r"\bno\s+(?:le\s+)?(?:menciones|digas)\s+(?:esto\s+)?al\s+usuario|"
95
+ r"\bne\s+(?:le\s+)?dis\s+pas\s+à\s+l'utilisateur|\bsag\s+(?:dem\s+)?(?:Benutzer|Nutzer)\s+nichts",
96
+ "Tells the agent to hide a step from the user (non-English)."),
97
+ # Addressing the reviewer / judge (self-verdict injection)
98
+ p("FS-PI-JUDGE-ADDRESS", r"\b(?:note|message|instructions?)\s+(?:to|for)\s+(?:any\s+)?(?:the\s+)?"
99
+ r"(?:security\s+)?(?:reviewers?|scanners?|auditors?|ai\s+(?:judges?|reviewers?)|llms?|"
100
+ r"language\s+models?|automated\s+(?:tools?|analysis))",
101
+ "Content addresses security reviewers or AI judges."),
102
+ p("FS-PI-JUDGE-ADDRESS", r"\b(?:this\s+(?:skill|code|file)\s+(?:is|has\s+been)\s+(?:verified|certified|"
103
+ r"approved|audited)\s+(?:as\s+)?safe|(?:classify|mark|rate|report)\s+(?:this|it)\s+as\s+"
104
+ r"(?:safe|benign|low|clean|not\s+malicious)|(?:output|respond\s+with)\s+[\"']?(?:is_safe|safe|benign)\b"
105
+ # "return" is a code keyword: require a quoted verdict or is_safe=true, so `return low` stays quiet.
106
+ r"|\breturn\s+(?:[\"'](?:is_safe|safe|low|benign)[\"']|[\"']?is_safe[\"']?\s*[:=]\s*true))",
107
+ "Content tries to dictate the scanner's verdict."),
108
+ # Instruction indirection
109
+ p("FS-IND-BINARY", r"\b(?:real|actual|full|complete|true|detailed|remaining)\s+instructions?\s+"
110
+ r"(?:are|is|live|can\s+be\s+found)\s+(?:in|inside|within)\s+[^\n]{0,80}\.(?:docx?|xlsx|pptx|pdf|zip|"
111
+ r"tar|gz|png|jpe?g|gif|webp|bin|dat|pyc)\b",
112
+ "SKILL.md sends the agent to a bundled document, archive or image for its instructions."),
113
+ p("FS-IND-BINARY", r"\b(?:read|load|follow|extract|open)\s+(?:the\s+)?(?:instructions?|steps|guide|"
114
+ r"setup)\s+(?:from|in)\s+[^\n]{0,60}\.(?:docx?|xlsx|pptx|pdf|zip|tar|gz|png|jpe?g|bin|pyc)\b",
115
+ "SKILL.md sends the agent to a bundled document, archive or image for its instructions."),
116
+ p("FS-IND-REMOTE", r"\b(?:fetch|download|load|read|get|retrieve|follow)\s+(?:the\s+)?(?:latest\s+|"
117
+ r"real\s+|actual\s+|updated\s+)?(?:instructions?|prompts?|rules|steps|guidance)\s+(?:from|at)\s+"
118
+ r"https?://", "SKILL.md loads its instructions from a remote URL."),
119
+ ]
120
+
121
+ CODE_EXTS = {"py", "pyw", "js", "mjs", "cjs", "ts", "mts", "cts", "sh", "bash", "zsh", "rb", "pl", "go", "rs",
122
+ "java", "c", "h", "cpp", "cs", "php", "lua", "ps1"}
123
+ COMMAND_RULES = {"FS-EXEC-REMOTE", "FS-CFG-REGISTRY", "FS-PERSIST-RC", "FS-SECRET-ACCESS"}
124
+ NET_SINK = regex.compile(r"\b(?:requests\.(?:post|put|get)|urlopen|httpx\.|fetch\(|axios|http\.request|"
125
+ r"socket\.(?:socket|create_connection)|curl\s|wget\s|nc\s+-|Invoke-WebRequest|"
126
+ r"\.sendall\(|dns\.resolver)", F)
127
+ ENV_SOURCE = regex.compile(r"\bos\.environ\b|\bprocess\.env\b|\bgetenv\(|\$ENV:|\bprintenv\b|\benv\s*\||"
128
+ r"\bset\s*\|", F)
129
+
130
+
131
+ def scan_view(view: View) -> list[Finding]:
132
+ findings: list[Finding] = []
133
+ text = view.text
134
+ ext = view.path.split("!/")[-1].rsplit("/", 1)[-1].rpartition(".")[2].lower()
135
+ is_code = ext in CODE_EXTS
136
+ for pat in PATTERNS:
137
+ if is_code and not pat.code_ok:
138
+ continue
139
+ try:
140
+ for m in pat.rx.finditer(text, timeout=TIMEOUT):
141
+ findings.append(emit(pat.rule_id, pat.message, path=view.path, layer=view.layer,
142
+ line=view.line_of(m.start()), decode_chain=view.decode_chain,
143
+ evidence=text[max(0, m.start() - 20): m.end() + 40]))
144
+ break # one finding per pattern per view keeps reports readable
145
+ except TimeoutError:
146
+ findings.append(emit("FS-COV-TRUNCATED", f"Pattern for {pat.rule_id} timed out on this view.",
147
+ path=view.path, layer=view.layer))
148
+ # Secret source + network sink in the same view (taint-lite; full AST taint lands in S3)
149
+ has_secret = any(f.rule_id == "FS-SECRET-ACCESS" for f in findings) or ENV_SOURCE.search(text)
150
+ sink = NET_SINK.search(text)
151
+ prose = view.path.lower().endswith((".md", ".txt", ".rst")) and view.layer in (Layer.RAW, Layer.FOLDED)
152
+ if has_secret and sink and not prose:
153
+ findings.append(emit("FS-SECRET-EXFIL", "Credential or environment access and a network send appear "
154
+ "in the same file.", path=view.path, layer=view.layer,
155
+ line=view.line_of(sink.start()), decode_chain=view.decode_chain,
156
+ evidence=text[max(0, sink.start() - 40): sink.end() + 60]))
157
+ return findings