bastionskill 0.1.0__tar.gz

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,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,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,88 @@
1
+ # bastionskill
2
+
3
+ Static scanner for **skill-poisoning**. Point it at an agent skill (a `SKILL.md`
4
+ plus its bundled scripts) and it inspects the *bundled executable code* for
5
+ malicious behavior — then reports the **shadow**: what the code does that the
6
+ skill's description never declared.
7
+
8
+ Agent skills bundle scripts that run when the skill is invoked, and can install
9
+ hooks that run afterward. That is an arbitrary-code-execution surface. bastionskill
10
+ is the code-layer leg of the bastion suite; the prompt-layer (malicious SKILL.md
11
+ text) is [bastionsupply](https://github.com/Rinkia/bastionsupply)'s job.
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ pip install bastionskill
17
+ # optional: full prompt-layer scanning via bastionsupply
18
+ pip install "bastionskill[prompt]"
19
+ ```
20
+
21
+ Zero required dependencies. Python 3.10+.
22
+
23
+ ## Use
24
+
25
+ ```bash
26
+ bastionskill scan ./some-skill # scan a local skill dir
27
+ bastionskill scan ~/.claude/skills # batch-scan every skill under a dir
28
+ bastionskill scan owner/repo # pre-flight a REMOTE skill (shallow clone, no exec)
29
+ bastionskill scan https://github.com/o/r # ... by full URL
30
+ bastionskill scan ./skill --prompt # + hidden-unicode / prompt-layer
31
+ bastionskill scan ./skill --json # machine-readable
32
+ bastionskill scan ./skill --report out.json # signable manifest (per-file hashes, verdict)
33
+ bastionskill scan ./skill --record # append result to the local ledger
34
+ bastionskill scan ./skill --fail-on critical # CI gate threshold (default: high)
35
+ bastionskill harden ./skill -o skill-policy.yaml # agentbastion/bastiongate policy
36
+ bastionskill ledger # list previously scanned skills + dates
37
+ ```
38
+
39
+ `--fail-on` sets the exit-code threshold (`critical|high|medium|low|none`, default
40
+ `high`) — drop it in CI as a pre-install gate. See [docs/github-action.md](docs/github-action.md).
41
+
42
+ **Remote pre-flight** shallow-clones the repo to a temp dir, scans statically, and
43
+ deletes it. The skill's own code is never executed.
44
+
45
+ **Ledger & rug-pull.** `--record` writes each scan to `~/.bastionskill/ledger.jsonl`
46
+ (source, content hash, date, verdict). Re-scan the same source after it changes and
47
+ you get a `! DRIFT` warning — the poisoned-update vector.
48
+
49
+ ## What it catches (code-layer)
50
+
51
+ | Detector | Example |
52
+ |---|---|
53
+ | **hook-install (lead)** | a script that writes a `PostToolUse` hook into `settings.json` = persistence |
54
+ | network egress | `socket.connect`, `requests.post`, `curl`/`wget`, `fetch()` |
55
+ | secret read | `~/.aws/credentials`, `id_rsa`, `.env` |
56
+ | obfuscation | `base64 -d | sh`, `eval(atob(...))` |
57
+ | dynamic exec | `exec()`, `eval()`, `getattr(m,n)()` (Python AST tier) |
58
+ | destructive | `rm -rf`, `Remove-Item -Recurse` |
59
+ | lateral-tamper | writes to `CLAUDE.md`, MCP config, or other skills |
60
+ | **opaque-binary** | bundles a compiled/loadable file it can't inspect (incl. renamed binaries, magic-byte sniffed) |
61
+ | **shadow** | code exercises a capability SKILL.md never declared |
62
+
63
+ Python files get a real `ast` pass (stdlib) on top of regex, so dynamic exec /
64
+ import / attribute-built calls survive reflow. Bash and JS use regex heuristics.
65
+
66
+ Findings are reported **regardless of dead-code or `if False:` / env-flag guards** —
67
+ the scanner reads source, it never runs it, and malware hides behind guards too.
68
+
69
+ ## How it fits the suite
70
+
71
+ - Prompt-layer → [bastionsupply](https://github.com/Rinkia/bastionsupply) (dependency, optional extra)
72
+ - Runtime gating → bastiongate
73
+ - `harden` emits an agentbastion / bastiongate skill policy (allow/deny + blocked capabilities)
74
+
75
+ ## Test fixture
76
+
77
+ The inert, defanged demo skill this scanner is built against lives at
78
+ [Rinkia/poisoned-skill-demo](https://github.com/Rinkia/poisoned-skill-demo) — a
79
+ "markdown formatter" that actually exfiltrates and installs a hook. See its
80
+ `EXPECTED.md` for the findings oracle.
81
+
82
+ ```bash
83
+ bastionskill scan Rinkia/poisoned-skill-demo # scan the demo straight off GitHub
84
+ ```
85
+
86
+ ## License
87
+
88
+ MIT © 2026 Stefano Rizzello
@@ -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__"]
@@ -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,)
@@ -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())
@@ -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('"', '\\"') + '"'