bastionskill 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.
@@ -0,0 +1,19 @@
1
+ """bastionskill — static scanner for skill-poisoning (code-layer).
2
+
3
+ Point it at an agent skill (a SKILL.md plus its bundled scripts). It inspects the
4
+ bundled executable code for malicious behavior — network egress, obfuscated exec,
5
+ secret reads, destructive commands, and persistence/hook install — and reports the
6
+ *shadow*: what the code does that SKILL.md never declared.
7
+
8
+ Prompt-layer risks (malicious SKILL.md instructions, hidden unicode) are delegated
9
+ to bastionsupply; this tool owns the code-layer.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ __version__ = "0.1.0"
15
+
16
+ from .models import Finding, ScanReport, Skill, SourceFile
17
+ from .scanner import scan
18
+
19
+ __all__ = ["Finding", "ScanReport", "Skill", "SourceFile", "scan", "__version__"]
bastionskill/checks.py ADDED
@@ -0,0 +1,192 @@
1
+ """Code-layer detectors.
2
+
3
+ Two tiers, both static (source is read, never executed — so payloads hidden
4
+ behind dead-code or `if False:` / env-flag guards are flagged like any other):
5
+
6
+ * a language-agnostic regex table applied line-by-line to every bundled file, and
7
+ * a Python-only AST tier (`ast` is stdlib) that catches dynamic exec / import /
8
+ attribute-built calls that reflowed regex can miss.
9
+
10
+ Each detector carries a `capability`; `scanner.shadow_findings` compares the set
11
+ of capabilities the code exercises against what SKILL.md declared.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import ast
17
+ import re
18
+ from dataclasses import dataclass
19
+ from typing import Callable
20
+
21
+ from .models import Finding, SourceFile
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class Detector:
26
+ check: str
27
+ severity: str
28
+ capability: str
29
+ pattern: re.Pattern
30
+ message: str
31
+
32
+
33
+ def _d(check, severity, capability, regex, message, flags=0) -> Detector:
34
+ return Detector(check, severity, capability, re.compile(regex, flags), message)
35
+
36
+
37
+ # --- regex tier -------------------------------------------------------------
38
+ # Ordered worst-first only for readability; scanner sorts output itself.
39
+ _REGEX: tuple[Detector, ...] = (
40
+ # persistence / hook install — the lead finding
41
+ _d("hook-install", "critical", "persistence",
42
+ r"\b(Post|Pre|User(Prompt|)|Stop|Notification)ToolUse\b|\bPostToolUse\b|\bPreToolUse\b",
43
+ "installs an agent hook (runs after this skill, persistence)"),
44
+ _d("hook-install", "high", "persistence",
45
+ r"settings\.json|\.claude[\\/](settings|hooks)|[\\/]hooks[\\/]",
46
+ "writes to agent settings/hooks (persistence surface)"),
47
+ _d("lateral-tamper", "high", "persistence",
48
+ r"CLAUDE\.md|mcp\.json|claude_desktop_config|[\\/]skills[\\/]|\.mcp\.json",
49
+ "writes to agent config / other skills (lateral tampering)"),
50
+ _d("persistence", "high", "persistence",
51
+ r"\bcrontab\b|LaunchAgents|LaunchDaemons|\bHKCU\b|\bHKLM\b|systemctl\s+enable",
52
+ "installs OS-level persistence (cron/launchd/registry/systemd)"),
53
+ # network egress
54
+ _d("network-egress", "critical", "network",
55
+ r"\bsocket\.socket\b|\.connect\(\s*\(|\.sendall\(|\.sendto\(",
56
+ "raw socket network egress"),
57
+ _d("network-egress", "high", "network",
58
+ r"\brequests\.(get|post|put|patch|delete)\b|\burllib\.request\b|\bhttp\.client\b|\bfetch\(|\baxios\b",
59
+ "HTTP client call (possible exfiltration)"),
60
+ _d("network-egress", "high", "network",
61
+ r"\bcurl\b|\bwget\b|Invoke-WebRequest|Invoke-RestMethod",
62
+ "shells out to a network client (curl/wget/Invoke-WebRequest)"),
63
+ # secret read
64
+ _d("secret-read", "critical", "secrets",
65
+ r"\.aws[\\/]credentials|id_rsa|id_ed25519|\.ssh[\\/]|\.git-credentials|\.npmrc|KUBECONFIG|keychain",
66
+ "reads credential/secret material"),
67
+ _d("secret-read", "high", "secrets",
68
+ r"(^|[\s\"'/=@])\.env\b",
69
+ "reads a .env secrets file"),
70
+ # obfuscation
71
+ _d("obfuscation", "high", "exec",
72
+ r"base64\s+(-d|--decode)|b64decode|atob\(|FromBase64String",
73
+ "base64-decoded payload (obfuscation)"),
74
+ _d("obfuscation", "critical", "exec",
75
+ r"base64\s+(-d|--decode)[^\n|]*\|\s*(sh|bash|python|node)\b",
76
+ "decodes then pipes to an interpreter (staged exec)"),
77
+ # dynamic exec (regex catch; AST tier confirms for python)
78
+ _d("dynamic-exec", "critical", "exec",
79
+ r"\beval\(|\bexec\(|\bsystem\(|subprocess\.(Popen|call|run|check_output)|os\.popen",
80
+ "dynamic / shell execution"),
81
+ # destructive
82
+ _d("destructive", "high", "destructive",
83
+ r"\brm\s+-rf\b|Remove-Item\b[^\n]*-Recurse|\bmkfs\b|\bdd\s+if=|\bshred\b",
84
+ "destructive filesystem/disk command"),
85
+ )
86
+
87
+
88
+ _BLOCK_COMMENT = re.compile(r"/\*.*?\*/", re.DOTALL)
89
+
90
+
91
+ def _strip_comments(text: str, lang: str) -> str:
92
+ """Blank out comment lines so regex doesn't match code described in prose.
93
+
94
+ Line count is preserved (line numbers stay valid). Conservative: only removes
95
+ FULL-LINE comments (and JS block comments) — trailing comments are left so a
96
+ `#` inside a string is never mistaken for a comment and a real finding hidden.
97
+ ponytail: trailing-comment false positives remain; upgrade to a real tokenizer
98
+ only if they prove noisy on real skills.
99
+ """
100
+ if lang == "javascript":
101
+ text = _BLOCK_COMMENT.sub(lambda m: "\n" * m.group(0).count("\n"), text)
102
+ prefix = "//"
103
+ elif lang in ("python", "bash", "other"):
104
+ prefix = "#"
105
+ else:
106
+ return text
107
+ out = []
108
+ for line in text.split("\n"):
109
+ out.append("" if line.lstrip().startswith(prefix) else line)
110
+ return "\n".join(out)
111
+
112
+
113
+ def scan_regex(f: SourceFile) -> list[Finding]:
114
+ out: list[Finding] = []
115
+ original = f.text.splitlines()
116
+ scanned = _strip_comments(f.text, f.lang).splitlines()
117
+ for i, line in enumerate(scanned, start=1):
118
+ for det in _REGEX:
119
+ if det.pattern.search(line):
120
+ evidence = original[i - 1].strip() if i - 1 < len(original) else line.strip()
121
+ out.append(Finding(
122
+ check=det.check, severity=det.severity, file=f.path,
123
+ message=det.message, evidence=evidence[:200],
124
+ line=i, capability=det.capability,
125
+ ))
126
+ return out
127
+
128
+
129
+ def scan_opaque(opaque_paths: tuple[str, ...]) -> list[Finding]:
130
+ """One HIGH finding per bundled file we cannot read as source.
131
+
132
+ A compiled or binary artifact is an execution surface a static reader is blind
133
+ to — treat "can't inspect" as "don't trust", not as clean.
134
+ """
135
+ return [
136
+ Finding(
137
+ check="opaque-binary", severity="high", file=path, capability="exec",
138
+ message="opaque/compiled bundled file — cannot inspect, do not trust",
139
+ )
140
+ for path in opaque_paths
141
+ ]
142
+
143
+
144
+ # --- python AST tier --------------------------------------------------------
145
+ def _is_name(node: ast.AST, names: set[str]) -> bool:
146
+ return isinstance(node, ast.Name) and node.id in names
147
+
148
+
149
+ class _Visitor(ast.NodeVisitor):
150
+ def __init__(self, path: str) -> None:
151
+ self.path = path
152
+ self.findings: list[Finding] = []
153
+
154
+ def _add(self, check, severity, capability, message, node) -> None:
155
+ self.findings.append(Finding(
156
+ check=check, severity=severity, file=self.path, message=message,
157
+ line=getattr(node, "lineno", 0), capability=capability,
158
+ ))
159
+
160
+ def visit_Call(self, node: ast.Call) -> None:
161
+ func = node.func
162
+ # exec(...) / eval(...)
163
+ if _is_name(func, {"exec", "eval"}):
164
+ self._add("dynamic-exec", "critical", "exec",
165
+ f"AST: dynamic {func.id}() call", node)
166
+ # __import__(...) / importlib.import_module(...)
167
+ if _is_name(func, {"__import__"}) or (
168
+ isinstance(func, ast.Attribute) and func.attr == "import_module"
169
+ ):
170
+ self._add("dynamic-import", "medium", "exec",
171
+ "AST: dynamic import", node)
172
+ # getattr(x, name)(...) — attribute-built call
173
+ if isinstance(func, ast.Call) and _is_name(func.func, {"getattr"}):
174
+ self._add("dynamic-call", "medium", "exec",
175
+ "AST: getattr-built dynamic call", node)
176
+ self.generic_visit(node)
177
+
178
+
179
+ def scan_python_ast(f: SourceFile) -> list[Finding]:
180
+ try:
181
+ tree = ast.parse(f.text)
182
+ except (SyntaxError, ValueError, RecursionError, MemoryError):
183
+ # unparseable or hostile-to-parse python: regex tier still covered it;
184
+ # never let a crafted file crash the scan.
185
+ return []
186
+ v = _Visitor(f.path)
187
+ v.visit(tree)
188
+ return v.findings
189
+
190
+
191
+ def all_checks() -> tuple[Callable[[SourceFile], list[Finding]], ...]:
192
+ return (scan_regex,)
bastionskill/cli.py ADDED
@@ -0,0 +1,199 @@
1
+ """bastionskill command line.
2
+
3
+ bastionskill scan ./some-skill # scan a local skill dir
4
+ bastionskill scan ~/.claude/skills # batch-scan every skill under a dir
5
+ bastionskill scan owner/repo # pre-flight a remote skill (shallow clone)
6
+ bastionskill scan https://github.com/o/r # ... by full URL
7
+ bastionskill scan ./skill --json # machine-readable
8
+ bastionskill scan ./skill --report out.json # signable manifest (hashes, verdict)
9
+ bastionskill scan ./skill --record # append result to the local ledger
10
+ bastionskill scan ./skill --fail-on critical # CI gate threshold (default: high)
11
+ bastionskill harden ./skill -o skill-policy.yaml
12
+ bastionskill ledger # list previously scanned skills + dates
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import json
19
+ import sys
20
+ from pathlib import Path
21
+
22
+ from . import __version__, harden, ledger as ledger_mod, prompt, remote, report
23
+ from .ignore import load as load_ignore
24
+ from .loader import discover_skills, load_skill
25
+ from .models import SEVERITIES, ScanReport, Skill
26
+ from .scanner import scan
27
+
28
+ _RANK = {s: i for i, s in enumerate(SEVERITIES)} # 0 = worst
29
+
30
+
31
+ def _make_output_unicode_safe() -> None:
32
+ for stream in (sys.stdout, sys.stderr):
33
+ try:
34
+ stream.reconfigure(encoding="utf-8", errors="backslashreplace")
35
+ except (AttributeError, ValueError):
36
+ pass
37
+
38
+
39
+ def _resolve_ignore(skill_dir: Path, args):
40
+ if getattr(args, "no_ignore", False):
41
+ return None
42
+ path = args.ignore if getattr(args, "ignore", None) else skill_dir / ".bastionskillignore"
43
+ return load_ignore(path)
44
+
45
+
46
+ def _fails(rep: ScanReport, threshold: str) -> bool:
47
+ if threshold == "none":
48
+ return False
49
+ worst = min((_RANK[f.severity] for f in rep.findings), default=len(SEVERITIES))
50
+ return worst <= _RANK[threshold]
51
+
52
+
53
+ def _scan_one(skill_dir: Path, args) -> tuple[ScanReport, Skill]:
54
+ skill = load_skill(skill_dir, name=args.name)
55
+ rep = scan(skill, ignore=_resolve_ignore(skill_dir, args))
56
+ if getattr(args, "prompt", False):
57
+ rep = ScanReport(
58
+ skill=rep.skill, file_count=rep.file_count,
59
+ findings=rep.findings + tuple(prompt.scan_prompt_layer(skill)),
60
+ )
61
+ return rep, skill
62
+
63
+
64
+ def main(argv=None) -> int:
65
+ _make_output_unicode_safe()
66
+ ap = argparse.ArgumentParser(
67
+ prog="bastionskill", description=__doc__,
68
+ formatter_class=argparse.RawDescriptionHelpFormatter)
69
+ ap.add_argument("--version", action="version", version=f"bastionskill {__version__}")
70
+ sub = ap.add_subparsers(dest="cmd", required=True)
71
+
72
+ ps = sub.add_parser("scan", help="scan a skill (local dir, dir of skills, or remote)")
73
+ ps.add_argument("target", help="skill dir, a dir of skills, or a remote url/owner-repo")
74
+ ps.add_argument("--name", help="override skill name label")
75
+ ps.add_argument("--prompt", action="store_true",
76
+ help="also run the prompt-layer check (hidden unicode)")
77
+ ps.add_argument("--json", action="store_true", help="emit JSON")
78
+ ps.add_argument("--report", help="write a signable scan manifest to this path")
79
+ ps.add_argument("--record", action="store_true", help="append result to the local ledger")
80
+ ps.add_argument("--fail-on", default="high", choices=[*SEVERITIES, "none"],
81
+ help="exit non-zero at this severity or worse (default: high)")
82
+ ps.add_argument("--ignore", help="path to a .bastionskillignore (default: in the skill dir)")
83
+ ps.add_argument("--no-ignore", action="store_true", help="ignore any .bastionskillignore")
84
+
85
+ ph = sub.add_parser("harden", help="emit an agentbastion/bastiongate skill policy")
86
+ ph.add_argument("target", help="skill dir (or remote url/owner-repo)")
87
+ ph.add_argument("--name", help="override skill name label")
88
+ ph.add_argument("-o", "--out", help="write policy.yaml (default: stdout)")
89
+
90
+ pl = sub.add_parser("ledger", help="list previously scanned skills and dates")
91
+ pl.add_argument("--json", action="store_true", help="emit JSON")
92
+
93
+ args = ap.parse_args(argv)
94
+ if args.cmd == "scan":
95
+ return _cmd_scan(args)
96
+ if args.cmd == "harden":
97
+ return _cmd_harden(args)
98
+ if args.cmd == "ledger":
99
+ return _cmd_ledger(args)
100
+ return 2
101
+
102
+
103
+ def _with_target(target: str):
104
+ """Yield a local base path for a target, remote or local, with cleanup.
105
+
106
+ Returns (base_path, checkout_or_None); caller must close the checkout.
107
+ """
108
+ # A local path always wins over remote heuristics, so "skills/mytool" (which
109
+ # also looks like owner/repo shorthand) scans the local dir when it exists.
110
+ p = Path(target)
111
+ if p.exists():
112
+ return p, None
113
+ if remote.is_remote(target):
114
+ checkout = remote.RemoteCheckout(target)
115
+ return checkout.__enter__(), checkout
116
+ _die(f"no such path (and not a recognized remote): {target}")
117
+
118
+
119
+ def _cmd_scan(args) -> int:
120
+ base, checkout = _with_target(args.target)
121
+ manifests = []
122
+ worst_fail = False
123
+ try:
124
+ skill_dirs = discover_skills(base)
125
+ multi = len(skill_dirs) > 1
126
+ for i, d in enumerate(skill_dirs):
127
+ rep, skill = _scan_one(d, args)
128
+ # rug-pull drift is read-only; always surface it.
129
+ prior = ledger_mod.drift(skill)
130
+ if prior:
131
+ print(f"! DRIFT: {skill.source} changed since last scan "
132
+ f"({prior.get('ts', '?')}, was {prior.get('verdict', '?')})",
133
+ file=sys.stderr)
134
+ if args.json:
135
+ print(report.to_json(rep))
136
+ else:
137
+ if i:
138
+ print()
139
+ print(report.to_text(rep))
140
+ if args.record:
141
+ ledger_mod.record(rep, skill)
142
+ if args.report:
143
+ manifests.append(report.to_manifest(rep, skill, __version__))
144
+ worst_fail = worst_fail or _fails(rep, args.fail_on)
145
+ if multi and not args.json:
146
+ print(f"\nscanned {len(skill_dirs)} skills; "
147
+ f"{'FAIL' if worst_fail else 'pass'} at --fail-on {args.fail_on}")
148
+ if args.report:
149
+ Path(args.report).write_text(
150
+ json.dumps({"schema": "bastionskill.report/1", "scans": manifests},
151
+ indent=2, ensure_ascii=False),
152
+ encoding="utf-8")
153
+ print(f"wrote report -> {args.report}", file=sys.stderr)
154
+ finally:
155
+ if checkout:
156
+ checkout.__exit__(None, None, None)
157
+ return 1 if worst_fail else 0
158
+
159
+
160
+ def _cmd_harden(args) -> int:
161
+ base, checkout = _with_target(args.target)
162
+ try:
163
+ d = discover_skills(base)[0]
164
+ skill = load_skill(d, name=args.name)
165
+ yaml = harden.to_policy_yaml(scan(skill))
166
+ finally:
167
+ if checkout:
168
+ checkout.__exit__(None, None, None)
169
+ if args.out:
170
+ Path(args.out).write_text(yaml, encoding="utf-8")
171
+ print(f"wrote policy -> {args.out}")
172
+ else:
173
+ sys.stdout.write(yaml)
174
+ return 0
175
+
176
+
177
+ def _cmd_ledger(args) -> int:
178
+ rows = ledger_mod.summary()
179
+ if args.json:
180
+ print(json.dumps(rows, indent=2, ensure_ascii=False))
181
+ return 0
182
+ if not rows:
183
+ print("ledger empty — scan with --record to populate it.")
184
+ return 0
185
+ print(f"{'last scan':<26} {'verdict':<7} {'risk':<8} source")
186
+ print("-" * 70)
187
+ for e in rows:
188
+ print(f"{e.get('ts', '?'):<26} {e.get('verdict', '?'):<7} "
189
+ f"{e.get('risk', '?'):<8} {e.get('source', '?')}")
190
+ return 0
191
+
192
+
193
+ def _die(msg: str) -> None:
194
+ print(f"bastionskill: {msg}", file=sys.stderr)
195
+ raise SystemExit(2)
196
+
197
+
198
+ if __name__ == "__main__":
199
+ raise SystemExit(main())
bastionskill/harden.py ADDED
@@ -0,0 +1,41 @@
1
+ """Bridge to agentbastion / bastiongate: turn a skill scan into a policy.
2
+
3
+ Closes the trilogy loop the same way the sibling tools' `harden` do. A scan of a
4
+ skill produces a per-skill verdict (allow/deny) plus the capabilities that tripped
5
+ the deny, ready to drop into the firewall's skill policy.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from .models import ScanReport
11
+
12
+ _BLOCK = {"critical", "high"}
13
+
14
+
15
+ def to_policy_yaml(report: ScanReport) -> str:
16
+ tripped = [f for f in report.findings if f.severity in _BLOCK]
17
+ verdict = "deny" if tripped else "allow"
18
+ reasons = sorted({f.check for f in tripped})
19
+ caps = sorted({f.capability for f in tripped if f.capability})
20
+
21
+ lines = [
22
+ "# agentbastion / bastiongate skill policy generated by bastionskill",
23
+ f"# skill: {report.skill} risk={report.risk}",
24
+ "default: allow",
25
+ "skills:",
26
+ f" {_q(report.skill)}:",
27
+ f" verdict: {verdict}",
28
+ ]
29
+ if reasons:
30
+ lines.append(" reasons:")
31
+ lines += [f" - {r}" for r in reasons]
32
+ if caps:
33
+ lines.append(" block_capabilities:")
34
+ lines += [f" - {c}" for c in caps]
35
+ return "\n".join(lines) + "\n"
36
+
37
+
38
+ def _q(name: str) -> str:
39
+ if name and all(c.isalnum() or c in "_-." for c in name):
40
+ return name
41
+ return '"' + name.replace("\\", "\\\\").replace('"', '\\"') + '"'
bastionskill/ignore.py ADDED
@@ -0,0 +1,61 @@
1
+ """`.bastionskillignore` — skip files and suppress findings.
2
+
3
+ Format (gitignore-ish), one rule per line, blank lines and `#` comments skipped:
4
+
5
+ scripts/vendor/* # a bare glob: skip these files entirely
6
+ suppress obfuscation # drop every 'obfuscation' finding
7
+ suppress network-egress scripts/known_client.py # drop only for a path glob
8
+
9
+ Suppression is deliberately coarse — a vetted skill or a noisy check, not a
10
+ per-line waiver. Keep the file in the skill root (or pass a path).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import fnmatch
16
+ from dataclasses import dataclass, field
17
+ from pathlib import Path
18
+
19
+ from .models import Finding
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class _Suppress:
24
+ check: str
25
+ glob: str # "" = all paths
26
+
27
+
28
+ @dataclass
29
+ class IgnoreRules:
30
+ skip_globs: list[str] = field(default_factory=list)
31
+ suppress: list[_Suppress] = field(default_factory=list)
32
+
33
+ def skip_file(self, rel_path: str) -> bool:
34
+ return any(fnmatch.fnmatch(rel_path, g) for g in self.skip_globs)
35
+
36
+ def suppressed(self, f: Finding) -> bool:
37
+ for s in self.suppress:
38
+ if s.check != f.check:
39
+ continue
40
+ if not s.glob or fnmatch.fnmatch(f.file, s.glob):
41
+ return True
42
+ return False
43
+
44
+
45
+ def load(path: str | Path | None) -> IgnoreRules:
46
+ rules = IgnoreRules()
47
+ if path is None:
48
+ return rules
49
+ p = Path(path)
50
+ if not p.is_file():
51
+ return rules
52
+ for raw in p.read_text(encoding="utf-8", errors="replace").splitlines():
53
+ line = raw.strip()
54
+ if not line or line.startswith("#"):
55
+ continue
56
+ parts = line.split()
57
+ if parts[0] == "suppress" and len(parts) >= 2:
58
+ rules.suppress.append(_Suppress(check=parts[1], glob=parts[2] if len(parts) > 2 else ""))
59
+ else:
60
+ rules.skip_globs.append(line)
61
+ return rules
bastionskill/ledger.py ADDED
@@ -0,0 +1,82 @@
1
+ """Local scan ledger — an append-only record of what was scanned, when.
2
+
3
+ One JSONL line per recorded scan at `~/.bastionskill/ledger.jsonl`. It answers
4
+ "have I scanned this before, and did it change since?" — the rug-pull signal:
5
+ same source, different content hash = the skill was modified after you vetted it.
6
+
7
+ Local and dependency-free. The line schema is deliberately flat so a remote sink
8
+ (e.g. Supabase) can later replay it without transformation.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ from datetime import datetime, timezone
15
+ from pathlib import Path
16
+
17
+ from .models import ScanReport, Skill
18
+
19
+ LEDGER_SCHEMA = "bastionskill.ledger/1"
20
+
21
+
22
+ def ledger_path() -> Path:
23
+ return Path.home() / ".bastionskill" / "ledger.jsonl"
24
+
25
+
26
+ def _entries(path: Path) -> list[dict]:
27
+ if not path.is_file():
28
+ return []
29
+ out = []
30
+ for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
31
+ line = line.strip()
32
+ if not line:
33
+ continue
34
+ try:
35
+ out.append(json.loads(line))
36
+ except json.JSONDecodeError:
37
+ continue # tolerate a partially written / corrupt line
38
+ return out
39
+
40
+
41
+ def last_for_source(source: str, path: Path | None = None) -> dict | None:
42
+ """Most recent ledger entry for a source, or None."""
43
+ p = path or ledger_path()
44
+ match = [e for e in _entries(p) if e.get("source") == source]
45
+ return match[-1] if match else None
46
+
47
+
48
+ def record(rep: ScanReport, skill: Skill, path: Path | None = None) -> dict:
49
+ """Append a scan to the ledger. Returns the entry written."""
50
+ p = path or ledger_path()
51
+ p.parent.mkdir(parents=True, exist_ok=True)
52
+ entry = {
53
+ "schema": LEDGER_SCHEMA,
54
+ "ts": datetime.now(timezone.utc).isoformat(),
55
+ "source": skill.source,
56
+ "skill": rep.skill,
57
+ "content_hash": skill.content_hash(),
58
+ "verdict": "allow" if rep.ok else "deny",
59
+ "risk": rep.risk,
60
+ "counts": rep.counts(),
61
+ }
62
+ with open(p, "a", encoding="utf-8") as fh:
63
+ fh.write(json.dumps(entry, ensure_ascii=False) + "\n")
64
+ return entry
65
+
66
+
67
+ def drift(skill: Skill, path: Path | None = None) -> dict | None:
68
+ """If this source was scanned before with a DIFFERENT hash, return the prior
69
+ entry (a rug-pull signal). None if unseen or unchanged."""
70
+ prev = last_for_source(skill.source, path)
71
+ if prev and prev.get("content_hash") != skill.content_hash():
72
+ return prev
73
+ return None
74
+
75
+
76
+ def summary(path: Path | None = None) -> list[dict]:
77
+ """Latest entry per source, most-recent first — the 'scanned skills' table."""
78
+ p = path or ledger_path()
79
+ latest: dict[str, dict] = {}
80
+ for e in _entries(p):
81
+ latest[e.get("source", "")] = e
82
+ return sorted(latest.values(), key=lambda e: e.get("ts", ""), reverse=True)
bastionskill/loader.py ADDED
@@ -0,0 +1,146 @@
1
+ """Load a skill directory into a `Skill` model.
2
+
3
+ Reads SKILL.md (frontmatter `description`), collects bundled source files, and
4
+ records bundled *opaque* files (compiled or binary artifacts we cannot statically
5
+ read — a common poisoning bypass). No network, no code execution — pure read.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from pathlib import Path
12
+
13
+ from .models import Skill, SourceFile
14
+
15
+ # Extensions we treat as executable code worth scanning, mapped to a language tag.
16
+ _LANG_BY_EXT = {
17
+ ".py": "python",
18
+ ".sh": "bash",
19
+ ".bash": "bash",
20
+ ".zsh": "bash",
21
+ ".js": "javascript",
22
+ ".mjs": "javascript",
23
+ ".cjs": "javascript",
24
+ ".ts": "javascript", # close enough for regex heuristics
25
+ ".ps1": "other",
26
+ ".rb": "other",
27
+ ".pl": "other",
28
+ }
29
+
30
+ # Bundled artifacts that execute/load but cannot be read as source -> flagged.
31
+ _OPAQUE_EXTS = {
32
+ ".exe", ".dll", ".so", ".dylib", ".pyc", ".pyd", ".wasm", ".bin",
33
+ ".o", ".a", ".jar", ".class", ".node", ".msi", ".apk", ".deb", ".dmg",
34
+ }
35
+
36
+ # Dirs skipped entirely (never the skill's own payload, and huge).
37
+ _SKIP_ALWAYS = {".git", "node_modules", "__pycache__", ".venv", "venv"}
38
+ # Dirs skipped for SOURCE noise but still swept for opaque binaries — a dropped
39
+ # payload binary lives exactly here, so a security scan must not ignore them.
40
+ _SKIP_SOURCE_ONLY = {"dist", "build"}
41
+ _SKIP_DIRS = _SKIP_ALWAYS | _SKIP_SOURCE_ONLY # for SKILL.md discovery only
42
+
43
+ _FRONTMATTER = re.compile(r"^---\s*\n(.*?)\n---\s*\n", re.DOTALL)
44
+ _DESC = re.compile(r"^description:\s*(.+?)\s*$", re.MULTILINE)
45
+
46
+
47
+ def _read(path: Path) -> str:
48
+ return path.read_text(encoding="utf-8", errors="replace")
49
+
50
+
51
+ def _parse_description(skill_md: str) -> str:
52
+ m = _FRONTMATTER.match(skill_md)
53
+ if not m:
54
+ return ""
55
+ d = _DESC.search(m.group(1))
56
+ return d.group(1).strip() if d else ""
57
+
58
+
59
+ # Magic bytes of executable/loadable formats. Catches a binary even when it has
60
+ # been renamed to look benign, while NOT flagging images/fonts/data (which carry
61
+ # their own magic and legitimately appear in skills).
62
+ _EXEC_MAGIC = (
63
+ b"\x7fELF", # ELF (Linux)
64
+ b"MZ", # PE / DOS (Windows .exe/.dll)
65
+ b"\xfe\xed\xfa\xce", # Mach-O 32
66
+ b"\xfe\xed\xfa\xcf", # Mach-O 64
67
+ b"\xcf\xfa\xed\xfe", # Mach-O 64 LE
68
+ b"\xca\xfe\xba\xbe", # Java class / Mach-O fat
69
+ b"\x00asm", # WebAssembly
70
+ b"dex\n", # Android dex
71
+ )
72
+
73
+
74
+ def _is_executable_blob(path: Path) -> bool:
75
+ """True if the file's magic bytes mark it as a compiled/loadable binary."""
76
+ try:
77
+ with open(path, "rb") as fh:
78
+ head = fh.read(8)
79
+ except OSError:
80
+ return False
81
+ return any(head.startswith(m) for m in _EXEC_MAGIC)
82
+
83
+
84
+ def load_skill(root: str | Path, name: str | None = None) -> Skill:
85
+ """Load the skill rooted at `root`.
86
+
87
+ `root` may be the dir holding SKILL.md, or a parent — the first SKILL.md
88
+ found (breadth-first) wins.
89
+ """
90
+ root = Path(root)
91
+ if not root.exists():
92
+ raise FileNotFoundError(f"no such path: {root}")
93
+
94
+ skill_md = _find_skill_md(root)
95
+ description = _parse_description(_read(skill_md)) if skill_md else ""
96
+ base = skill_md.parent if skill_md else root
97
+
98
+ files: list[SourceFile] = []
99
+ opaque: list[str] = []
100
+ for p in sorted(base.rglob("*")):
101
+ if not p.is_file():
102
+ continue
103
+ if any(part in _SKIP_ALWAYS for part in p.parts):
104
+ continue
105
+ in_build = any(part in _SKIP_SOURCE_ONLY for part in p.parts)
106
+ rel = p.relative_to(base).as_posix()
107
+ lang = _LANG_BY_EXT.get(p.suffix.lower())
108
+ if lang is not None and not in_build:
109
+ files.append(SourceFile(path=rel, text=_read(p), lang=lang))
110
+ elif p.suffix.lower() in _OPAQUE_EXTS or _is_executable_blob(p):
111
+ # opaque binaries are flagged even inside dist/build
112
+ opaque.append(rel)
113
+
114
+ return Skill(
115
+ name=name or base.name,
116
+ description=description,
117
+ files=tuple(files),
118
+ source=str(root),
119
+ opaque=tuple(opaque),
120
+ )
121
+
122
+
123
+ def discover_skills(root: str | Path) -> list[Path]:
124
+ """Return the directory of every skill under `root` (each holds a SKILL.md).
125
+
126
+ Falls back to `[root]` when no SKILL.md exists, so a bare script dir still
127
+ scans as one skill.
128
+ """
129
+ root = Path(root)
130
+ if (root / "SKILL.md").is_file():
131
+ return [root]
132
+ dirs = sorted({
133
+ p.parent for p in root.rglob("SKILL.md")
134
+ if p.is_file() and not any(part in _SKIP_DIRS for part in p.parts)
135
+ })
136
+ return dirs or [root]
137
+
138
+
139
+ def _find_skill_md(root: Path) -> Path | None:
140
+ if (root / "SKILL.md").is_file():
141
+ return root / "SKILL.md"
142
+ matches = sorted(
143
+ p for p in root.rglob("SKILL.md")
144
+ if p.is_file() and not any(part in _SKIP_DIRS for part in p.parts)
145
+ )
146
+ return matches[0] if matches else None
bastionskill/models.py ADDED
@@ -0,0 +1,107 @@
1
+ """Immutable data model for skill-poisoning scanning.
2
+
3
+ A `Skill` holds a SKILL.md declaration plus the bundled `SourceFile`s that run
4
+ when the skill is invoked. Checks read a `Skill` and emit `Finding`s; a
5
+ `ScanReport` collects them.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass, field
11
+
12
+ SEVERITIES = ("critical", "high", "medium", "low")
13
+ _RANK = {s: i for i, s in enumerate(SEVERITIES)} # 0 = worst
14
+
15
+ # Capabilities a bundled script can exercise. The shadow check compares these
16
+ # against what SKILL.md declares.
17
+ CAPABILITIES = ("network", "secrets", "persistence", "destructive", "exec")
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class SourceFile:
22
+ """One bundled file that ships with the skill."""
23
+
24
+ path: str # relative to the skill root
25
+ text: str
26
+ lang: str # "python" | "bash" | "javascript" | "other"
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class Skill:
31
+ """A named skill: its SKILL.md declaration and bundled source files."""
32
+
33
+ name: str
34
+ description: str = "" # SKILL.md frontmatter description (the declared intent)
35
+ files: tuple[SourceFile, ...] = ()
36
+ source: str = "" # dir or url it came from
37
+ opaque: tuple[str, ...] = () # bundled files we cannot statically read
38
+
39
+ def content_hash(self) -> str:
40
+ """Stable sha256 over every bundled file's path + bytes.
41
+
42
+ Drives ledger drift / rug-pull detection: same source, changed hash =
43
+ the skill was modified since the last scan.
44
+ """
45
+ import hashlib
46
+
47
+ h = hashlib.sha256()
48
+ for f in sorted(self.files, key=lambda x: x.path):
49
+ h.update(f.path.encode("utf-8"))
50
+ h.update(b"\0")
51
+ h.update(f.text.encode("utf-8", "replace"))
52
+ h.update(b"\0")
53
+ for name in sorted(self.opaque):
54
+ h.update(b"opaque:")
55
+ h.update(name.encode("utf-8"))
56
+ h.update(b"\0")
57
+ return h.hexdigest()
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class Finding:
62
+ """One risk detected by a check."""
63
+
64
+ check: str # check id, e.g. "hook-install"
65
+ severity: str # one of SEVERITIES
66
+ file: str # relative path, or "" for skill-level
67
+ message: str
68
+ evidence: str = ""
69
+ line: int = 0
70
+ capability: str = "" # one of CAPABILITIES, or "" (drives shadow detection)
71
+
72
+ def __post_init__(self) -> None:
73
+ if self.severity not in _RANK:
74
+ raise ValueError(f"bad severity {self.severity!r}")
75
+
76
+
77
+ @dataclass(frozen=True)
78
+ class ScanReport:
79
+ """Result of scanning one skill."""
80
+
81
+ skill: str
82
+ file_count: int
83
+ findings: tuple[Finding, ...] = ()
84
+
85
+ @property
86
+ def risk(self) -> str:
87
+ """Worst severity present, or 'clean'."""
88
+ if not self.findings:
89
+ return "clean"
90
+ return min((f.severity for f in self.findings), key=lambda s: _RANK[s])
91
+
92
+ @property
93
+ def ok(self) -> bool:
94
+ """True when nothing critical or high was found."""
95
+ return self.risk in ("clean", "medium", "low")
96
+
97
+ def counts(self) -> dict[str, int]:
98
+ out = {s: 0 for s in SEVERITIES}
99
+ for f in self.findings:
100
+ out[f.severity] += 1
101
+ return out
102
+
103
+ def sorted_findings(self) -> tuple[Finding, ...]:
104
+ """Findings worst-first, then by file/line for stable output."""
105
+ return tuple(
106
+ sorted(self.findings, key=lambda f: (_RANK[f.severity], f.file, f.line))
107
+ )
bastionskill/prompt.py ADDED
@@ -0,0 +1,45 @@
1
+ """Prompt-layer check (optional, off by default).
2
+
3
+ v0.1 owns the code-layer. The prompt-layer (malicious SKILL.md instructions,
4
+ injection templates) is bastionsupply's job — it already ships those detectors and
5
+ the shared bastioncorpus. This module keeps only the one prompt-layer check that is
6
+ trivial in the stdlib — hidden / zero-width / bidi unicode in the SKILL.md text —
7
+ and defers everything richer to bastionsupply when it is installed.
8
+
9
+ Enable with `bastionskill scan --prompt <path>`.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import unicodedata
15
+
16
+ from .models import Finding, Skill
17
+
18
+ # Zero-width and bidi-control code points used to hide or reorder text.
19
+ _HIDDEN = {
20
+ "​", "‌", "‍", "", # zero-width space/joiner/BOM
21
+ "‪", "‫", "‬", "‭", "‮", # bidi overrides
22
+ "⁦", "⁧", "⁨", "⁩", # isolates
23
+ }
24
+
25
+
26
+ def scan_prompt_layer(skill: Skill) -> list[Finding]:
27
+ text = skill.description
28
+ out: list[Finding] = []
29
+ hits = sorted({c for c in text if c in _HIDDEN})
30
+ if hits:
31
+ names = ", ".join(unicodedata.name(c, repr(c)) for c in hits)
32
+ out.append(Finding(
33
+ check="hidden-unicode", severity="high", file="SKILL.md",
34
+ message=f"hidden/bidi unicode in description: {names}",
35
+ evidence=text[:160],
36
+ ))
37
+ # Deeper injection detection lives in bastionsupply; use it if present.
38
+ try:
39
+ import bastionsupply # noqa: F401
40
+ except ImportError:
41
+ out.append(Finding(
42
+ check="prompt-layer-note", severity="low", file="SKILL.md",
43
+ message="install bastionsupply for full prompt-layer injection scanning",
44
+ ))
45
+ return out
bastionskill/remote.py ADDED
@@ -0,0 +1,74 @@
1
+ """Fetch a remote skill to a temp dir for pre-flight scanning.
2
+
3
+ The wedge: scan a skill *before* you clone it into your agent. We shallow-clone
4
+ into a throwaway dir and hand back the path; the caller scans it (static — the
5
+ skill's own code is never executed) and cleans up.
6
+
7
+ `git clone` fetches files; it does not run repository code. We still never invoke
8
+ anything inside the cloned tree.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ import shutil
15
+ import subprocess
16
+ import tempfile
17
+ from pathlib import Path
18
+
19
+ # owner/repo (letters, digits, dot, dash, underscore) — GitHub shorthand
20
+ _SHORTHAND = re.compile(r"^[\w.-]+/[\w.-]+$")
21
+
22
+
23
+ def is_remote(target: str) -> bool:
24
+ t = target.strip()
25
+ return (
26
+ t.startswith(("http://", "https://", "git@", "ssh://"))
27
+ or t.endswith(".git")
28
+ or t.startswith("github.com/")
29
+ or bool(_SHORTHAND.match(t))
30
+ )
31
+
32
+
33
+ def _to_clone_url(target: str) -> str:
34
+ t = target.strip()
35
+ if t.startswith(("http://", "https://", "git@", "ssh://")) or t.endswith(".git"):
36
+ return t
37
+ if t.startswith("github.com/"):
38
+ return "https://" + t
39
+ if _SHORTHAND.match(t):
40
+ return f"https://github.com/{t}"
41
+ return t
42
+
43
+
44
+ class RemoteCheckout:
45
+ """Context manager: shallow-clone a remote skill, clean up on exit."""
46
+
47
+ def __init__(self, target: str) -> None:
48
+ self.url = _to_clone_url(target)
49
+ self._dir: str | None = None
50
+
51
+ def __enter__(self) -> Path:
52
+ if shutil.which("git") is None:
53
+ raise RuntimeError("git not found on PATH — needed to scan a remote skill")
54
+ self._dir = tempfile.mkdtemp(prefix="bastionskill-")
55
+ try:
56
+ subprocess.run(
57
+ ["git", "clone", "--depth", "1", "--quiet", self.url, self._dir],
58
+ check=True, capture_output=True, text=True, timeout=120,
59
+ )
60
+ except subprocess.CalledProcessError as e:
61
+ self._cleanup()
62
+ raise RuntimeError(f"git clone failed: {e.stderr.strip() or e}") from e
63
+ except subprocess.TimeoutExpired:
64
+ self._cleanup()
65
+ raise RuntimeError("git clone timed out") from None
66
+ return Path(self._dir)
67
+
68
+ def __exit__(self, *exc) -> None:
69
+ self._cleanup()
70
+
71
+ def _cleanup(self) -> None:
72
+ if self._dir:
73
+ shutil.rmtree(self._dir, ignore_errors=True)
74
+ self._dir = None
bastionskill/report.py ADDED
@@ -0,0 +1,98 @@
1
+ """Render a `ScanReport` as text or JSON."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from datetime import datetime, timezone
7
+
8
+ from .models import ScanReport, Skill
9
+
10
+ MANIFEST_SCHEMA = "bastionskill.manifest/1"
11
+
12
+ _MARK = {"critical": "CRIT", "high": "HIGH", "medium": "MED ", "low": "LOW "}
13
+
14
+
15
+ def to_text(rep: ScanReport) -> str:
16
+ lines: list[str] = []
17
+ c = rep.counts()
18
+ head = (f"skill: {rep.skill} files: {rep.file_count} risk: {rep.risk.upper()}"
19
+ f" (crit {c['critical']} / high {c['high']} /"
20
+ f" med {c['medium']} / low {c['low']})")
21
+ lines.append(head)
22
+ lines.append("-" * len(head))
23
+
24
+ findings = rep.sorted_findings()
25
+ if not findings:
26
+ lines.append("clean: no code-layer risks found.")
27
+ return "\n".join(lines)
28
+
29
+ # Shadow first, called out — it is the headline.
30
+ shadows = [f for f in findings if f.check == "shadow"]
31
+ if shadows:
32
+ lines.append("SHADOW (declared intent != actual behavior):")
33
+ for f in shadows:
34
+ lines.append(f" ! {f.message}")
35
+ lines.append("")
36
+
37
+ for f in findings:
38
+ if f.check == "shadow":
39
+ continue
40
+ loc = f.file + (f":{f.line}" if f.line else "")
41
+ lines.append(f"[{_MARK[f.severity]}] {f.check:<14} {loc}")
42
+ lines.append(f" {f.message}")
43
+ if f.evidence:
44
+ lines.append(f" > {f.evidence}")
45
+ return "\n".join(lines)
46
+
47
+
48
+ def to_manifest(rep: ScanReport, skill: Skill, tool_version: str) -> dict:
49
+ """A stable, signable record of one scan.
50
+
51
+ Deterministic except `generated_at`; carries per-file sha256 and the skill
52
+ content hash so a signature (future) or a Supabase sink can pin exactly what
53
+ was scanned. This is the schema a certification/registry layer would build on.
54
+ """
55
+ import hashlib
56
+
57
+ files = [
58
+ {"path": f.path, "lang": f.lang,
59
+ "sha256": hashlib.sha256(f.text.encode("utf-8", "replace")).hexdigest()}
60
+ for f in sorted(skill.files, key=lambda x: x.path)
61
+ ]
62
+ return {
63
+ "schema": MANIFEST_SCHEMA,
64
+ "tool_version": tool_version,
65
+ "generated_at": datetime.now(timezone.utc).isoformat(),
66
+ "skill": rep.skill,
67
+ "source": skill.source,
68
+ "content_hash": skill.content_hash(),
69
+ "verdict": "allow" if rep.ok else "deny",
70
+ "risk": rep.risk,
71
+ "counts": rep.counts(),
72
+ "files": files,
73
+ "opaque": list(skill.opaque),
74
+ "findings": json.loads(to_json(rep))["findings"],
75
+ }
76
+
77
+
78
+ def to_json(rep: ScanReport) -> str:
79
+ obj = {
80
+ "skill": rep.skill,
81
+ "file_count": rep.file_count,
82
+ "risk": rep.risk,
83
+ "ok": rep.ok,
84
+ "counts": rep.counts(),
85
+ "findings": [
86
+ {
87
+ "check": f.check,
88
+ "severity": f.severity,
89
+ "capability": f.capability,
90
+ "file": f.file,
91
+ "line": f.line,
92
+ "message": f.message,
93
+ "evidence": f.evidence,
94
+ }
95
+ for f in rep.sorted_findings()
96
+ ],
97
+ }
98
+ return json.dumps(obj, indent=2, ensure_ascii=False)
@@ -0,0 +1,92 @@
1
+ """Scan a `Skill`: run code-layer checks, then compute the shadow.
2
+
3
+ The shadow is the product's whole point: capabilities the bundled code exercises
4
+ (network, secrets, persistence, destructive) that SKILL.md never declared.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from .checks import scan_opaque, scan_python_ast, scan_regex
10
+ from .ignore import IgnoreRules
11
+ from .models import Finding, ScanReport, Skill
12
+
13
+ # Words in a SKILL.md description that count as declaring a capability.
14
+ _DECLARES: dict[str, tuple[str, ...]] = {
15
+ "network": ("network", "http", "https", "download", "upload", "fetch",
16
+ "online", "api", "url", "web", "request", "internet"),
17
+ "secrets": ("credential", "secret", "token", "api key", "api-key",
18
+ "password", "auth", "keychain", "ssh"),
19
+ "persistence": ("hook", "background", "daemon", "startup", "cron",
20
+ "persist", "install a hook"),
21
+ "destructive": ("delete", "remove", "wipe", "erase", "clean up", "purge"),
22
+ }
23
+
24
+ # Phrases that explicitly DISCLAIM a capability. A disclaimer over code that does
25
+ # the thing is the strongest shadow, so it always beats a bare keyword mention
26
+ # (e.g. "no network" contains "network" but declares the opposite).
27
+ _NEGATES: dict[str, tuple[str, ...]] = {
28
+ "network": ("no network", "offline", "no internet", "without network",
29
+ "no connection", "runs locally", "fully local"),
30
+ "secrets": ("no credential", "no secret", "reads no", "touches nothing"),
31
+ "persistence": ("no hook", "installs nothing", "no persistence"),
32
+ "destructive": ("read-only", "read only", "never deletes", "non-destructive"),
33
+ }
34
+
35
+ # Only these capabilities drive shadow detection ("exec" is generic and always
36
+ # present in a script; it is not a declared-intent signal on its own).
37
+ _SHADOW_CAPS = ("network", "secrets", "persistence", "destructive")
38
+
39
+
40
+ def _dedupe(findings: list[Finding]) -> list[Finding]:
41
+ seen: set[tuple[str, str, int]] = set()
42
+ out: list[Finding] = []
43
+ for f in findings:
44
+ key = (f.check, f.file, f.line)
45
+ if key in seen:
46
+ continue
47
+ seen.add(key)
48
+ out.append(f)
49
+ return out
50
+
51
+
52
+ def shadow_findings(skill: Skill, code_findings: list[Finding]) -> list[Finding]:
53
+ desc = skill.description.lower()
54
+ exercised = {f.capability for f in code_findings if f.capability in _SHADOW_CAPS}
55
+ out: list[Finding] = []
56
+ for cap in _SHADOW_CAPS:
57
+ if cap not in exercised:
58
+ continue
59
+ disclaimed = any(p in desc for p in _NEGATES.get(cap, ()))
60
+ if not disclaimed and any(word in desc for word in _DECLARES[cap]):
61
+ continue # declared and not disclaimed: code and description agree
62
+ out.append(Finding(
63
+ check="shadow", severity="critical", file="SKILL.md",
64
+ capability=cap,
65
+ message=(f"undeclared {cap}: the code exercises {cap} but SKILL.md "
66
+ f"never says so"),
67
+ evidence=(skill.description[:160] or "(no description)"),
68
+ ))
69
+ return out
70
+
71
+
72
+ def scan(skill: Skill, ignore: IgnoreRules | None = None) -> ScanReport:
73
+ code: list[Finding] = []
74
+ scanned_files = 0
75
+ for f in skill.files:
76
+ if ignore and ignore.skip_file(f.path):
77
+ continue
78
+ scanned_files += 1
79
+ code.extend(scan_regex(f))
80
+ if f.lang == "python":
81
+ code.extend(scan_python_ast(f))
82
+ opaque = [o for o in skill.opaque if not (ignore and ignore.skip_file(o))]
83
+ code.extend(scan_opaque(tuple(opaque)))
84
+ code = _dedupe(code)
85
+ findings = code + shadow_findings(skill, code)
86
+ if ignore:
87
+ findings = [f for f in findings if not ignore.suppressed(f)]
88
+ return ScanReport(
89
+ skill=skill.name,
90
+ file_count=scanned_files + len(opaque),
91
+ findings=tuple(findings),
92
+ )
@@ -0,0 +1,111 @@
1
+ Metadata-Version: 2.4
2
+ Name: bastionskill
3
+ Version: 0.1.0
4
+ Summary: Skill-poisoning scanner: detect malicious bundled code (network egress, secret theft, hook-install persistence, destructive commands) in agent skills before you install them — the code-layer that a plain grepper and a prompt-scanner miss.
5
+ Author-email: Stefano Rizzello <rizzellostefano@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Rinkia/bastionskill
8
+ Project-URL: Repository, https://github.com/Rinkia/bastionskill
9
+ Project-URL: Issues, https://github.com/Rinkia/bastionskill/issues
10
+ Keywords: skill,agent-skill,claude-code,security,supply-chain,prompt-injection,ai-agent,skill-poisoning,agent-security
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Security
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Provides-Extra: prompt
19
+ Requires-Dist: bastionsupply>=0.4.0; extra == "prompt"
20
+ Provides-Extra: dev
21
+ Requires-Dist: pytest>=7.0; extra == "dev"
22
+ Dynamic: license-file
23
+
24
+ # bastionskill
25
+
26
+ Static scanner for **skill-poisoning**. Point it at an agent skill (a `SKILL.md`
27
+ plus its bundled scripts) and it inspects the *bundled executable code* for
28
+ malicious behavior — then reports the **shadow**: what the code does that the
29
+ skill's description never declared.
30
+
31
+ Agent skills bundle scripts that run when the skill is invoked, and can install
32
+ hooks that run afterward. That is an arbitrary-code-execution surface. bastionskill
33
+ is the code-layer leg of the bastion suite; the prompt-layer (malicious SKILL.md
34
+ text) is [bastionsupply](https://github.com/Rinkia/bastionsupply)'s job.
35
+
36
+ ## Install
37
+
38
+ ```bash
39
+ pip install bastionskill
40
+ # optional: full prompt-layer scanning via bastionsupply
41
+ pip install "bastionskill[prompt]"
42
+ ```
43
+
44
+ Zero required dependencies. Python 3.10+.
45
+
46
+ ## Use
47
+
48
+ ```bash
49
+ bastionskill scan ./some-skill # scan a local skill dir
50
+ bastionskill scan ~/.claude/skills # batch-scan every skill under a dir
51
+ bastionskill scan owner/repo # pre-flight a REMOTE skill (shallow clone, no exec)
52
+ bastionskill scan https://github.com/o/r # ... by full URL
53
+ bastionskill scan ./skill --prompt # + hidden-unicode / prompt-layer
54
+ bastionskill scan ./skill --json # machine-readable
55
+ bastionskill scan ./skill --report out.json # signable manifest (per-file hashes, verdict)
56
+ bastionskill scan ./skill --record # append result to the local ledger
57
+ bastionskill scan ./skill --fail-on critical # CI gate threshold (default: high)
58
+ bastionskill harden ./skill -o skill-policy.yaml # agentbastion/bastiongate policy
59
+ bastionskill ledger # list previously scanned skills + dates
60
+ ```
61
+
62
+ `--fail-on` sets the exit-code threshold (`critical|high|medium|low|none`, default
63
+ `high`) — drop it in CI as a pre-install gate. See [docs/github-action.md](docs/github-action.md).
64
+
65
+ **Remote pre-flight** shallow-clones the repo to a temp dir, scans statically, and
66
+ deletes it. The skill's own code is never executed.
67
+
68
+ **Ledger & rug-pull.** `--record` writes each scan to `~/.bastionskill/ledger.jsonl`
69
+ (source, content hash, date, verdict). Re-scan the same source after it changes and
70
+ you get a `! DRIFT` warning — the poisoned-update vector.
71
+
72
+ ## What it catches (code-layer)
73
+
74
+ | Detector | Example |
75
+ |---|---|
76
+ | **hook-install (lead)** | a script that writes a `PostToolUse` hook into `settings.json` = persistence |
77
+ | network egress | `socket.connect`, `requests.post`, `curl`/`wget`, `fetch()` |
78
+ | secret read | `~/.aws/credentials`, `id_rsa`, `.env` |
79
+ | obfuscation | `base64 -d | sh`, `eval(atob(...))` |
80
+ | dynamic exec | `exec()`, `eval()`, `getattr(m,n)()` (Python AST tier) |
81
+ | destructive | `rm -rf`, `Remove-Item -Recurse` |
82
+ | lateral-tamper | writes to `CLAUDE.md`, MCP config, or other skills |
83
+ | **opaque-binary** | bundles a compiled/loadable file it can't inspect (incl. renamed binaries, magic-byte sniffed) |
84
+ | **shadow** | code exercises a capability SKILL.md never declared |
85
+
86
+ Python files get a real `ast` pass (stdlib) on top of regex, so dynamic exec /
87
+ import / attribute-built calls survive reflow. Bash and JS use regex heuristics.
88
+
89
+ Findings are reported **regardless of dead-code or `if False:` / env-flag guards** —
90
+ the scanner reads source, it never runs it, and malware hides behind guards too.
91
+
92
+ ## How it fits the suite
93
+
94
+ - Prompt-layer → [bastionsupply](https://github.com/Rinkia/bastionsupply) (dependency, optional extra)
95
+ - Runtime gating → bastiongate
96
+ - `harden` emits an agentbastion / bastiongate skill policy (allow/deny + blocked capabilities)
97
+
98
+ ## Test fixture
99
+
100
+ The inert, defanged demo skill this scanner is built against lives at
101
+ [Rinkia/poisoned-skill-demo](https://github.com/Rinkia/poisoned-skill-demo) — a
102
+ "markdown formatter" that actually exfiltrates and installs a hook. See its
103
+ `EXPECTED.md` for the findings oracle.
104
+
105
+ ```bash
106
+ bastionskill scan Rinkia/poisoned-skill-demo # scan the demo straight off GitHub
107
+ ```
108
+
109
+ ## License
110
+
111
+ MIT © 2026 Stefano Rizzello
@@ -0,0 +1,18 @@
1
+ bastionskill/__init__.py,sha256=mnI7-mXj3V4Cb77hmQo_rdhHPbEcNCBdppkaaFYtC40,745
2
+ bastionskill/checks.py,sha256=edmqU5sWMm2sdbDCjI4EUhdNEi5FMAE0jRousBVlOtk,7783
3
+ bastionskill/cli.py,sha256=tGI-Ncf3Wu8s42I8lVcxkun4c_grmUQByVbe_sIZeHA,7788
4
+ bastionskill/harden.py,sha256=x2Nh8fCU4VGTfbVONu-rQq0scWa-sPVK9RYr8sK7RPw,1375
5
+ bastionskill/ignore.py,sha256=dcNL2vlbzn0WoCc1sNA_F5jbC-rPdtzQ3j2HZ-Oetfs,1881
6
+ bastionskill/ledger.py,sha256=dTs-zTeJeX3fH7V9XIvn1TeVd2uFSIV2Ejjcf1zVgVE,2820
7
+ bastionskill/loader.py,sha256=1afyxvfoiweHcp1e1YkpC-zSqWFxWlpzPuD0Z48keL8,4908
8
+ bastionskill/models.py,sha256=r-p5oTa7jmX7bxafyDkYZAzbCcemyKM4rp6XtWj9dSA,3358
9
+ bastionskill/prompt.py,sha256=WP86UFnsXx1bgzNWudW1B70gcmXZ03LnUfa43Jy6cpQ,1671
10
+ bastionskill/remote.py,sha256=ZM13-EaZ4QV7uGRoSSLDJNw7ogz27uD_fX9mzn5Rpvg,2394
11
+ bastionskill/report.py,sha256=3D7UfbI0An28EwHn0L3wLQ8YoYN5fZNRw-4nIIACo4k,3142
12
+ bastionskill/scanner.py,sha256=BFvvugE_Z7Pwh5jvuVMjnhiM4hT2weTtY0rbrbKyQQA,3812
13
+ bastionskill-0.1.0.dist-info/licenses/LICENSE,sha256=BZvyzlc8AeEX5rrIdqgXPKWqOXp8O1B-0CDg4vy1o6k,1073
14
+ bastionskill-0.1.0.dist-info/METADATA,sha256=tffsU5Zu6clgpbsay9oQ8mn36lAR7JKiHlqpRKn2E-g,5122
15
+ bastionskill-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
16
+ bastionskill-0.1.0.dist-info/entry_points.txt,sha256=tQBj4XFZCVhvb71tRQ-oe62CZPHF4IH_yG0KmR9F0vY,55
17
+ bastionskill-0.1.0.dist-info/top_level.txt,sha256=ZFjAp_d3FK5wmK2yFiiunCHfMZrtYZJEwzPj43dsKP8,13
18
+ bastionskill-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ bastionskill = bastionskill.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Stefano Rizzello
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ bastionskill