Skip to content
Back to search

skill-sentry

MarketplaceWorks with Claude CodeGitHub

Security tooling for Claude Code and Codex: audit plugins, skills, hooks and MCP servers.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/paulofh--skill-sentry/badge.svg)](/listings/paulofh--skill-sentry)

HTML

<a href="/listings/paulofh--skill-sentry"><img src="/api/listings/paulofh--skill-sentry/badge.svg" alt="findsafeskills safety rating" /></a>

Install

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

/plugin marketplace add PauloFH/skill-sentry
/plugin install skill-sentry@skill-sentry

This repository is both the plugin and its own marketplace. The marketplace installs from `main`, and `main` only receives changes that passed CI (the test suite on Linux, Windows and macOS, plus install checks against the real Claude Code and Codex CLIs).

Install the audit with `npx skills add PauloFH/skill-sentry` (Claude Code, Codex and other agents). The runtime guard and harden need the plugin. Similarly named skills exist, so use the exact `PauloFH/skill-sentry` source. See [skills.sh](#skillssh).

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 18 lines
  1. {
  2. "$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
  3. "name": "skill-sentry",
  4. "description": "Security tooling for Claude Code and Codex: audit plugins, skills, hooks and MCP servers.",
  5. "owner": {
  6. "name": "Paulo Roberto Fernandes Holanda"
  7. },
  8. "plugins": [
  9. {
  10. "name": "skill-sentry",
  11. "source": "./",
  12. "version": "0.2.0",
  13. "category": "security",
  14. "description": "Static scanner and runtime guard that audits installed Claude Code and Codex plugins, skills, hooks and MCP servers for malicious behavior.",
  15. "homepage": "https://github.com/PauloFH/skill-sentry"
  16. }
  17. ]
  18. }
README.md · README · 240 lines
  1. **English** | [Português](README.pt.md) | [Español](README.es.md) | [中文](README.zh.md)
  2. 🌐 https://paulofh.github.io/skill-sentry/
  3. # skill-sentry
  4. A zero-dependency Claude Code plugin that audits the plugins, skills, hooks and MCP servers installed on your machine for malicious behavior, hardens your Claude Code settings, and guards risky tool calls at runtime.
  5. Third-party skills and plugins are code and instructions that run with your privileges. A malicious one can steal credentials, install a crypto miner, open a backdoor, or quietly instruct the model to do those things for it. skill-sentry gives you a fast, local, readable second look.
  6. - **Audit** (`/skill-sentry:audit`): a static scanner reads every installed plugin, skill, hook and MCP server config, scores each component and reports findings by category: miner, rce, secret, exfil, persistence, permissions, destructive, obfuscation, injection, supply, skill, config.
  7. - **Harden** (`/skill-sentry:harden`): reviews your `settings.json` and applies only the tightening steps you approve one by one.
  8. - **Guard** (PreToolUse hook): inspects tool calls as they happen and blocks or asks before the dangerous ones.
  9. Requires Node 18 or newer. No npm dependencies.
  10. Since 0.1.1 it also works in OpenAI Codex: see [Codex support](#codex-support).
  11. ## Threat model and honest limits
  12. skill-sentry is a second pair of eyes, not a shield. Read this before trusting it.
  13. - It is **not an antivirus and not a sandbox**. It does not isolate anything and cannot undo damage.
  14. - The scanner is **static analysis only**. It reads files with pattern rules and never executes them. Sufficiently creative code can evade pattern rules.
  15. - It **cannot see other plugins' hooks while they execute**. It only reads their configuration and scripts.
  16. - It **cannot inspect code that is fetched at runtime** (for example a package launched with a floating version tag, or a script downloaded and then run). It can only flag that this happens.
  17. - The guard is a best-effort filter. **Sufficiently obfuscated shell can bypass it.** It inspects commands, paths and URLs; for Write and Edit it looks at the target path only, never the content.
  18. - A clean report is not proof of safety. A bad report is a reason to look closer.
  19. Mitigations worth doing regardless: pin plugin versions, avoid auto-update for third-party marketplaces, read what you install, and apply the settings from `/skill-sentry:harden`.
  20. ## Install
  21. ```
  22. /plugin marketplace add PauloFH/skill-sentry
  23. /plugin install skill-sentry@skill-sentry
  24. ```
  25. This repository is both the plugin and its own marketplace. The marketplace installs from `main`, and `main` only receives changes that passed CI (the test suite on Linux, Windows and macOS, plus install checks against the real Claude Code and Codex CLIs).
  26. Install the audit with `npx skills add PauloFH/skill-sentry` (Claude Code, Codex and other agents). The runtime guard and harden need the plugin. Similarly named skills exist, so use the exact `PauloFH/skill-sentry` source. See [skills.sh](#skillssh).
  27. ## Usage
  28. ### Audit installed components
  29. ```
  30. /skill-sentry:audit
  31. ```
  32. Claude runs the scanner, then presents a summary (components per verdict, what changed since the baseline), every problem found while reading configs, and a table for each component that is not `ok`. The scanner's verdict is never lowered: if Claude disagrees it adds its own opinion in a separate "Agent assessment" column, so you always see both. Text copied from scanned files is treated as untrusted data and never followed as instructions.
  33. Verdicts come from a score: critical findings weigh 40, high 15, medium 5. Each rule counts once per component, at its highest severity, and the score is capped at 100.
  34. | Score | Verdict |
  35. | --- | --- |
  36. | below 10 | ok |
  37. | 10 to 29 | review |
  38. | 30 to 59 | suspicious |
  39. | 60 and above | malicious |
  40. Any critical finding raises the verdict to at least `suspicious`. Combinations escalate within a file: exfiltration next to secret access becomes critical, and obfuscation next to rce, exfil or secret findings becomes high.
  41. `/skill-sentry:audit` is the normal entry point. To run the script yourself, note that for an installed plugin the scripts live under the plugin install directory, `~/.claude/plugins/cache/skill-sentry/skill-sentry/<version>/`; the paths below are relative to that directory (or to a clone of this repository).
  42. Useful options (you can ask Claude for them, or run the script yourself):
  43. ```
  44. node skills/audit/scripts/scan.mjs --json
  45. node skills/audit/scripts/scan.mjs --path <dir>
  46. node skills/audit/scripts/scan.mjs --component <id>
  47. node skills/audit/scripts/scan.mjs --diff-only
  48. node skills/audit/scripts/scan.mjs --update-baseline
  49. ```
  50. - `--path <dir>` vets a single folder, so you can check a skill or plugin **before installing it**. It does not read or write the baseline.
  51. - `--component <id>` scans one installed component.
  52. - `--diff-only` shows only components added or changed since the baseline. The first full scan creates the baseline automatically.
  53. - `--update-baseline` accepts the current state as the new baseline (Claude asks first).
  54. ### Harden your settings
  55. ```
  56. /skill-sentry:harden
  57. ```
  58. Claude lists each recommendation, explains why it matters, and applies one only after your explicit yes for that item. A timestamped backup of `settings.json` is made before any change, and the helper merges only what you approved.
  59. | Id | What it does |
  60. | --- | --- |
  61. | `ask-curl` | Ask before running curl |
  62. | `ask-wget` | Ask before running wget |
  63. | `deny-ssh-read` | Deny reading `~/.ssh` |
  64. | `deny-aws-read` | Deny reading `~/.aws` |
  65. | `ask-env-read` | Ask before reading `.env` files |
  66. | `disable-skill-shell` | Turn off inline shell execution inside skills (trade-off: official plugins that gather context that way will stop doing so) |
  67. Two more items are shown for information only and never applied: reviewing third-party marketplaces (`third-party-autoupdate`) and restricting marketplaces and hooks through managed settings (`managed-settings`).
  68. ### Runtime guard
  69. The guard is a PreToolUse hook installed with the plugin. It watches Bash, PowerShell, Read, Write, Edit, NotebookEdit, Grep, Glob, WebFetch and MCP tool calls.
  70. | Decision | When |
  71. | --- | --- |
  72. | deny | A critical rule matches (for example download-and-execute pipes, reverse shells, crypto-miner launches, disk or home-directory wipes). Always blocked unless you allowlisted that exact command. |
  73. | ask | A high-risk rule matches and a skill or plugin is the likely origin of the call. Also always for writes to skill-sentry's own data or install directory (or to any other installed skill-sentry copy, such as the one installed for Codex), shell commands that mention those directories, and writes through unusual Windows path forms (device paths, UNC paths, 8.3 short names, NTFS streams, trailing dot or space). |
  74. | log | A high-risk rule matches but no skill or plugin is attributed as the likely origin. Recorded in `guard.log`, not interrupted. |
  75. If the guard itself fails, it fails open: it writes a line to `guard.log` and lets the call proceed rather than breaking your session.
  76. The default audit (`scan.mjs` with only `--json` and/or `--diff-only`) and `harden.mjs check` run without a prompt. Audits with `--path` or `--component`, baseline updates (`--update-baseline`), allowlisting (`--allow`) and `harden.mjs apply` show a confirmation prompt by design: approve it for the action you already agreed to. Under the Bash tool, write the script path with forward slashes (`C:/Users/...`).
  77. ### Allowlist
  78. If a finding is a known false positive, allow it one finding at a time:
  79. ```
  80. node skills/audit/scripts/scan.mjs --allow <componentId> <ruleId> <file> --reason "why"
  81. ```
  82. An entry is tied to the sha256 of that file, so it **stops applying as soon as the file changes**. Entries that let a blocked command through are exact-string matches. Claude only runs this after you say yes.
  83. If the `skillspector` command is installed, the audit can offer a second opinion with it. skill-sentry never installs it.
  84. ## Codex support
  85. skill-sentry 0.1.1 brings the same audit and guard to OpenAI Codex, plus a recommend-only harden.
  86. ### What the audit covers in Codex
  87. - `config.toml`: approval and sandbox settings, MCP servers, literal secrets, trusted projects, the shell environment policy
  88. - `rules/*.rules` execution policy files
  89. - plugins, and the hooks they ship together with each hook's trust state
  90. - MCP servers
  91. - skills, including `~/.agents/skills`
  92. - `AGENTS.md` instruction files
  93. - the `notify` program
  94. Windows and WSL Codex homes are detected automatically. Pick what to audit with `--agent claude|codex|all` (default `all`), add a home with `--codex-home <dir>` (repeatable) and skip WSL with `--no-wsl`:
  95. ```
  96. node skills/audit/scripts/scan.mjs --agent codex
  97. node skills/audit/scripts/scan.mjs --agent all --codex-home <dir> --no-wsl
  98. ```
  99. ### Install in Codex
  100. ```
  101. codex plugin marketplace add PauloFH/skill-sentry
  102. codex plugin add skill-sentry@skill-sentry
  103. ```
  104. This install from the public GitHub repository is verified on Windows and WSL Codex.
  105. Then **start Codex once, then trust the guard hook**. Codex does not run a hook until you trust it, and enabling a plugin does not trust its hooks. On its first start after the install, Codex writes an install file into the plugin folder, which changes the hook's fingerprint. So trust the hook after that first start: open `/hooks` in Codex (or "Review hooks" in the desktop app), review the skill-sentry hook and trust it. Until you do, the guard does not run.
  106. Then ask Codex to run the skill-sentry audit for your first report. This is verified on WSL Codex only. On Windows Codex it may need your approval for the shell commands it runs.
  107. ### Guard under Codex
  108. The guard is a PreToolUse hook here too. Codex has no "ask", so it can only allow or deny, and the tiers are:
  109. | Tier | When | Codex behaviour |
  110. | --- | --- | --- |
  111. | 1 | A critical rule matches | deny |
  112. | 2 | A high rule for rce, exfil, miner or destructive; a secret and network egress in one command; a network-capable call after an attributed (skill or plugin) call that read a secret was allowed on retry earlier in the session | deny. If you really meant it, run it yourself in a terminal. |
  113. | 3 | Any other high rule with an attributed origin (a skill or plugin) | denied the first time, with the reason. An identical retry in the same session within 10 minutes is allowed once. |
  114. | 4 | A high rule with no skill or plugin attributed | logged only |
  115. | 5 | Writes to skill-sentry's own files (any installed copy), or unusual path forms | deny |
  116. `apply_patch` patches are inspected too. Most patches the guard cannot read are denied: one that comes from a file or a pipe, or that uses shell expansion. A patch command hidden behind dynamic or obfuscated shell (see the limits below) is not detected.
  117. ### Codex limits
  118. - Codex has no "ask": the guard can only allow or deny.
  119. - It fails open: if the hook errors or exceeds Codex's timeout (about 5 seconds), the call runs.
  120. - Hooks need trust (`/hooks`). The `dangerously-bypass-hook-trust` flag of Codex turns that protection off.
  121. - After a plugin update Codex marks the hook `modified` and stops running it until you trust it again in `/hooks`.
  122. - The tier 3 retry is confirmed by the model, not by you.
  123. - Interactive input sent to a running shell (`write_stdin`) is not hooked.
  124. - Commands that build names or paths at run time are not analysed: `eval`, variables, globs, interpreter one-liners such as `python -c`, or a script written in one call and run in a later one.
  125. - Origin attribution is lost when more than about 1 MiB of output follows the skill read in the session; the call then counts as tier 4.
  126. - Under WSL, if the session starts under `/mnt/c` and your node toolchain (for example mise) refuses to start there, the guard fails open. Start the session under `/home/...`.
  127. - WSL Codex and Windows Codex keep separate skill-sentry data (taint, baseline, allowlist).
  128. - Under the `workspace-write` sandbox the audit needs your approval to write its report to `~/.claude/skill-sentry`.
  129. - Reading skill-sentry's own `SKILL.md` through a chained shell command (`cd ... && cat ...`) may be denied. The plain read works.
  130. - Mentioning a bare `skill-sentry` path in a shell command can still prompt in Claude Code (self-protect).
  131. ### Harden under Codex
  132. ```
  133. node skills/audit/scripts/harden.mjs check --agent codex
  134. ```
  135. Plain `check` stays Claude-only. Codex hardening is **recommend-only**: skill-sentry never edits Codex files. Each recommendation comes with a snippet for you to apply yourself:
  136. | Id | What it recommends |
  137. | --- | --- |
  138. | `approval-sandbox` | Keep `approval_policy` and `sandbox_mode` on the sandboxed, ask-on-request defaults |
  139. | `broad-allow-rules` | Replace execution policy allow rules that end at a shell or interpreter with prompt rules |
  140. | `secrets-in-config` | Move literal secrets out of `config.toml` and reference an environment variable |
  141. | `env-excludes` | Keep the default environment excludes so secret-looking variables are not passed to commands |
  142. | `mcp-auto-approve` | Do not auto-approve MCP servers or tools |
  143. | `approvals-reviewer` | Keep `approvals_reviewer` on `user` |
  144. | `trusted-tmp-projects` | Do not trust projects that live in temp directories |
  145. | `hooks-enabled` | Keep Codex hooks enabled, so the guard can run |
  146. | `trust-guard-hook` | Trust the skill-sentry hook in `/hooks` |
  147. ### Two installs, one version
  148. If Claude Code and Codex run different skill-sentry versions, a newer scanner recognises older releases and shows an "update both installs" note. An older scanner may report the newer copy as suspicious or malicious (a false positive) until both installs are updated. **Update both installs** after each release.
  149. ### skills.sh
  150. `npx skills add PauloFH/skill-sentry` installs the audit only, as the skill `skill-sentry-audit` (in Claude Code, `/skill-sentry-audit`). It cannot install the runtime guard (a hook) or harden: install the plugin for those. With `-g` the skills CLI copies the skill to `~/.agents/skills/skill-sentry-audit`, where Codex reads it, and links `~/.claude/skills/skill-sentry-audit` to it for Claude Code. CI checks this install with the real skills CLI on Linux and Windows. Without a ref it installs the default branch (`main`); pin a release with `npx skills add PauloFH/skill-sentry#v<version>` (for example `#v0.2.0`). Installs under `$CLAUDE_CONFIG_DIR/skills` (when that variable is set) are not covered: the scanner and the guard look in `~/.claude/skills` only.
  151. Similarly named skills exist on skills.sh (for example `skillsentry`). They are other projects: use the exact `PauloFH/skill-sentry` source.
  152. Next to the plugin of the same release, every scanner (plugin or standalone) recognises the other copies as skill-sentry. The guard lets the standalone audit run its scan, and lets Codex read its `SKILL.md`, only when that folder is a verified copy of the plugin's own audit. Any other command on that folder asks (Claude Code) or is denied (Codex), and so do those two on a copy the guard cannot verify (a newer version than the plugin, a dev or PR build, a `--rename` install) until both installs match. Update both installs after each release. A copy installed under another name with `--rename` has a changed `SKILL.md`, so the scanners no longer recognise it.
  153. ## Data and privacy
  154. - **No network calls and no telemetry.** Everything runs locally.
  155. - It writes only to `~/.claude/skill-sentry/`: `baseline.json`, `allowlist.json`, `guard.log` and `reports/`. The one exception is `harden`, which edits your `settings.json` after approval, with a backup.
  156. - Environment variables (mainly for testing): `SKILL_SENTRY_DATA_DIR` (data directory), `SKILL_SENTRY_CLAUDE_HOME` (default `~/.claude`), `SKILL_SENTRY_HOME_DIR` (where `~/.claude.json` is read from), `SKILL_SENTRY_CODEX_HOME` (replaces the default Codex home) and `SKILL_SENTRY_NO_WSL=1` (do not look for Codex homes inside WSL).
  157. ## Validation
  158. Tested against a real Windows 11 installation (68 components): 2 flagged. One was rated malicious: a third-party orchestration plugin that launches agents with permission prompts disabled and auto-approves commands, powerful by design rather than malware. One was rated review: test scripts that use the skip-permissions flag. Everything else came back ok. The project has 240+ automated tests.
  159. ## Credits and inspiration
  160. - CybeDefend, ["Are Claude Code skills safe?"](https://www.cybedefend.com/blog/are-claude-code-skills-safe)
  161. - The "Agent Skills in the Wild" study (January 2026)
  162. - NVIDIA SkillSpector, a complementary scanner (`skillspector scan <dir> --no-llm`). Use it alongside skill-sentry for a second opinion.
  163. ## License
  164. MIT. See [LICENSE](LICENSE).
scripts/lib/rules.mjs · Bundled script · 376 lines · 7 findings marked
  1. import { normalizePath, escapeInvisible, truncate, invisibleRegex } from './text.mjs';
  2. /**
  3. * @typedef {'critical'|'high'|'medium'|'info'} Severity
  4. * @typedef {'code'|'markdown'|'config'|'binary'|'other'} FileKind
  5. * @typedef {{ ruleId: string, category: string, severity: Severity, line: number, snippet: string }} Match
  6. * @typedef {{ id: string, category: string, severity: Severity, pattern: RegExp,
  7. * appliesTo: Array<'code'|'markdown'|'config'|'command'|'path'>, description: string,
  8. * kindSeverity?: Partial<Record<FileKind, Severity>> }} Rule
  9. */
  10. // Signature words are assembled from fragments so detector sources stay inert.
  11. const j = (...p) => p.join('');
  12. const MINER_NAMES = [
  13. j('xm', 'rig'), j('xmr', '-stak'), j('cpu', 'miner'), j('minerd'), j('eth', 'miner'), j('nb', 'miner'),
    • Note: Quoted as data in code: Names a cryptocurrency miner, without a pool or options to run it
    • Line 15 on GitHub
  14. j('phoenix', 'miner'), j('cg', 'miner'), j('bfg', 'miner'), j('lol', 'miner'), j('t-', 'rex'),
  15. j('gmi', 'ner'), j('teamred', 'miner'), j('nice', 'hash'), j('coin', 'hive'), j('crypto', 'loot'),
  16. ];
  17. const POOL_HOSTS = [
  18. j('mine', 'xmr'), j('support', 'xmr'), j('nano', 'pool'), j('2', 'miners'), j('f2', 'pool'),
  19. j('hash', 'vault'), j('monero', 'ocean'), j('c3', 'pool'), j('moneroocean'), j('ethermine'),
  20. ];
  21. const EXFIL_HOSTS = [
  22. 'webhook\\.site', 'pastebin\\.com', 'transfer\\.sh', 'file\\.io', '0x0\\.st', 'anonfiles',
  23. '[a-z0-9-]+\\.ngrok(?:-free)?\\.(?:io|app|dev)', 'ngrok\\.io',
  24. 'discord(?:app)?\\.com/api/webhooks', 'api\\.telegram\\.org/bot',
  25. 'requestbin', 'pipedream\\.net', 'interact\\.sh', 'oast\\.(?:fun|live|pro|site|me)',
  26. 'burpcollaborator', 'hookbin', 'beeceptor',
  27. ];
  28. const ALL = ['code', 'markdown', 'config', 'command'];
  29. const CODE_CMD = ['code', 'command'];
  30. const SCRIPTY = ['code', 'config', 'command'];
  31. const PROSE = ['markdown'];
  32. // download tool, optional `| tee …` stages, then a pipe into a shell (any args, `$SHELL` included)
  33. // or into an interpreter reading its program from stdin.
  34. const PIPE_TO_INTERPRETER = new RegExp(
  35. '\\b(?:curl|wget|iwr|irm|invoke-webrequest|invoke-restmethod)\\b[^\\n|;]{0,150}'
  36. + '(?:\\|\\s*(?:sudo\\s+)?tee\\b[^\\n|;]{0,100}){0,3}'
  37. + '\\|\\s*(?:sudo(?:\\s+-\\S+){0,4}\\s+)?(?:(?:\\/\\S{0,60}\\/)?env\\s+)?(?:\\S{0,80}\\/)?["\']?'
  38. + '(?:(?:(?:ba|z|da|k|c)?sh|iex|invoke-expression)\\b|\\$\\{?shell\\b\\}?'
  39. + '|(?:python[23]?|node|perl|ruby|php)(?=\\s*(?:$|[;&|)]|-(?:\\s|$))))',
  40. 'i');
  41. // PowerShell web download cmdlets, optionally wrapped in `(`, `$(`, and `.Content` access.
  42. const PS_DOWNLOAD = '(?:new-object\\s+(?:system\\.)?net\\.webclient|iwr|irm|invoke-webrequest|invoke-restmethod)\\b';
  43. /** @returns {Rule} */
  44. const r = (id, category, severity, pattern, appliesTo, description) =>
  45. ({ id, category, severity, pattern, appliesTo, description });
  46. /** @type {Rule[]} */
  47. export const RULES = [
  48. // ---- MINER ----
  49. r('MINER_BINARY', 'miner', 'critical', new RegExp(`\\b(?:${MINER_NAMES.join('|')})\\b`, 'i'), ALL,
  50. 'References a known cryptocurrency miner'),
  51. r('MINER_POOL_URL', 'miner', 'critical', new RegExp(`${j('stra', 'tum')}\\+(?:tcp|ssl|tls)://|\\b(?:${POOL_HOSTS.join('|')})\\.`, 'i'), ALL,
  52. 'Mining pool URL or hostname'),
  53. r('MINER_FLAGS', 'miner', 'high', /--donate-level\b|--coin[= ]+(?:monero|xmr|ethash)\b|--cpu-priority\b|--randomx\b/i, ALL,
    • Note: Quoted as data in code: Runs or configures a cryptocurrency miner
    • Line 59 on GitHub
  54. 'Typical miner command-line flags'),
  55. // ---- RCE ----
  56. r('RCE_DOWNLOAD_PIPE_SHELL', 'rce', 'critical', PIPE_TO_INTERPRETER, ALL,
  57. 'Downloads content and pipes it straight into a shell or interpreter'),
  58. r('RCE_PROCESS_SUBST', 'rce', 'critical',
  59. /(?:^|[\s;&|(])(?:(?:ba|z|da|k)?sh|source|\.)\s+<\(\s*(?:curl|wget|iwr|irm|invoke-webrequest|invoke-restmethod)\b/i, ALL,
  60. 'Shell sources or executes the output of a download'),
  61. r('RCE_EVAL_SUBST', 'rce', 'critical', /\beval\s+["']?(?:\$\(|`)\s*(?:curl|wget)\b/i, ALL,
  62. 'eval of the output of a download'),
  63. r('RCE_IEX_DOWNLOAD', 'rce', 'critical',
  64. new RegExp(`\\b(?:iex|invoke-expression)\\b\\s*(?:\\$?\\(\\s*){0,3}${PS_DOWNLOAD}`
  65. + `|\\[scriptblock\\]::create\\s*(?:\\$?\\(\\s*){0,3}${PS_DOWNLOAD}|\\.downloadstring\\s*\\(`, 'i'),
  66. ALL, 'PowerShell download-and-evaluate'),
  67. r('RCE_SHELL_C_SUBST', 'rce', 'critical', /\b(?:ba|z|da)?sh\s+-c\s+["']?\$\(\s*(?:curl|wget)\b/i, ALL,
  68. 'Shell executes the output of a download'),
  69. r('RCE_POWERSHELL_ENCODED', 'rce', 'high',
  70. /\b(?:powershell|pwsh)(?:\.exe)?\b[^\n]{0,300}\s-e(?:nc(?:odedcommand)?)?\s+['"]?[A-Za-z0-9+/=]{8,}/i, ALL,
  71. 'PowerShell encoded command'),
  72. r('RCE_REVERSE_SHELL', 'rce', 'critical',
  73. /\/dev\/tcp\/[\w.$-]+\/\d+|\bn(?:c|cat)\b[^\n]{0,300}\s-e\s+\/?\S*sh\b|\b(?:ba)?sh\s+-i\s*>&|\bmkfifo\b[^\n]{0,300}\bnc\b/i, ALL,
  74. 'Reverse shell construction'),
  75. r('RCE_DOWNLOAD_EXEC', 'rce', 'high',
  76. /\b(?:curl|wget)\b[^\n;]{0,120}?(?:\s-o\s*|>\s*)\S{1,100}\s*(?:&&|;)\s*(?:sudo\s+)?(?:chmod\s+\+?[ugoa]*x|\.\/|sh\s|bash\s)/i, ALL,
  77. 'Downloads a file then makes it executable / runs it'),
  78. r('RCE_LOLBIN_DOWNLOAD', 'rce', 'high',
  79. /\bmshta\b[^\n]{0,300}https?:|\bcertutil(?:\.exe)?\s+[^\n]{0,300}-urlcache\b|\bbitsadmin\b[^\n]{0,300}\/transfer\b|\bregsvr32\b[^\n]{0,300}\/i:https?:/i, ALL,
  80. 'Windows living-off-the-land downloader'),
  81. // ---- SECRET ----
  82. r('SECRET_SSH_KEY_REF', 'secret', 'high',
  83. /\.ssh[/\\](?:id_[a-z0-9_]+(?!\.pub)\b|authorized_keys|[a-z0-9_]*_key\b)|\bid_(?:rsa|ed25519|ecdsa|dsa)\b(?!\.pub)/i, ALL,
  84. 'References an SSH private key'),
  85. r('SECRET_SSH_DIR_READ', 'secret', 'high',
  86. /\b(?:cat|type|grep|egrep|rg|ag|findstr|select-string|sls|get-content|gc|tar|zip|7z|compress-archive|cp|copy|copy-item|xcopy|robocopy|scp|rsync|base64|xxd|od|strings|find)\b[^\n|;&]{0,300}(?:^|[\s"'=(])(?:(?:~|\$\{?HOME\}?|%USERPROFILE%|\$env:USERPROFILE|[a-z]:[/\\]users[/\\][^/\\\n"']+|\/(?:home|Users)\/[^/\s"']+|\/root)?[/\\])?\.ssh(?:[/\\]\*?)?(?=$|[\s"';|&)])/i,
  87. ['command'], 'Reads or archives the whole SSH key directory'),
  88. r('SECRET_AWS_CREDENTIALS_REF', 'secret', 'high', /\.aws[/\\](?:credentials|sso)\b/i, ALL, 'References AWS credentials'),
  89. r('SECRET_CLAUDE_CREDENTIALS_REF', 'secret', 'high', /\.claude[/\\]\.credentials\.json/i, ALL,
  90. 'References Claude Code credentials'),
  91. r('SECRET_GIT_NETRC_REF', 'secret', 'high', /(?:^|[\s/\\"'=])(?:\.git-credentials|\.netrc|_netrc)\b/i, ALL,
  92. 'References stored git/netrc credentials'),
  93. r('SECRET_BROWSER_DATA_REF', 'secret', 'high',
  94. /(?:google[-/\\ ]chrome|chromium|brave|microsoft[/\\ ]edge|mozilla[/\\ ]firefox|vivaldi)[^\n]{0,300}(?:login data|cookies|logins\.json|key4\.db|web data)/i,
  95. ALL, 'References browser credential or cookie stores'),
  96. r('SECRET_WALLET_REF', 'secret', 'high',
  97. /\bwallet\.dat\b|[/\\]\.(?:electrum|monero|bitcoin)\b|[/\\]exodus[/\\]|\bmetamask\b|keystore[/\\]utc--/i, ALL,
  98. 'References cryptocurrency wallet files'),
  99. r('SECRET_ENV_FILE_READ', 'secret', 'high',
  100. // `cp .env.example .env` (creating .env from a template) writes the file, it does not read it. The exemption needs
  101. // exactly two operands and only plain flags: no `-t`/`--target-directory` (which would copy the real .env elsewhere),
  102. // and the template operand never starts with `-` (`cp -t/tmp/q.env.example .env` is an option, not a template).
  103. /\b(?:cat|type|cp(?!\s+(?:(?:-(?![a-z]*t)[a-z]+|--(?!target)[a-z][a-z-]*)\s+)*["']?(?!-)[^\s"'|;&]*\.env\.(?:example|sample|template|dist)["']?\s+["']?[^\s"'|;&]*\.env["']?\s*(?:$|[|;&]))|scp|base64|tar|zip|get-content|gc)\b[^\n|;&]{0,300}(?:^|[\s/\\])\.env(?:\.(?!example|sample|template)[\w-]+)?(?=\s|$|["'|;&])/i,
  104. ['command'], 'Reads a .env file'),
  105. r('SECRET_ENV_DUMP_PIPE', 'secret', 'high',
  106. /JSON\.stringify\(\s*process\.env\b|\bdict\(\s*os\.environ\s*\)|\b(?:printenv|env)\b\s*\|\s*(?:curl|nc|base64)\b|\bget-childitem\s+env:[^\n]{0,300}\|\s*(?:iwr|irm|invoke-)/i,
  107. CODE_CMD, 'Dumps the whole environment into a pipe or serializer'),
  108. r('SECRET_TOKEN_LITERAL', 'secret', 'high',
  109. /\bgh[pousr]_[A-Za-z0-9]{36,}\b|\bAKIA[0-9A-Z]{16}\b|\bsk-ant-[A-Za-z0-9_-]{20,}|-----BEGIN (?:RSA |OPENSSH |EC |DSA )?PRIVATE KEY-----|\bxox[baprs]-[A-Za-z0-9-]{10,}/,
  110. ['code', 'config', 'command', 'markdown'], 'Embedded credential or private key material'),
  111. // ---- EXFIL ----
  112. r('EXFIL_KNOWN_SERVICE', 'exfil', 'high', new RegExp(`(?:^|[^a-z0-9.-])(?:${EXFIL_HOSTS.join('|')})`, 'i'), ALL,
  113. 'Known data-exfiltration / paste / tunnel service'),
  114. r('EXFIL_UPLOAD_FILE', 'exfil', 'high',
  115. /\bcurl\b[^\n]{0,120}?\s(?:-d|--data(?:-binary|-raw|-urlencode)?|-F|--form|-T|--upload-file)(?:\s+|=)["']?(?:[\w.-]+=)?@\S|\bwget\b[^\n]{0,300}--post-file\b|\b(?:iwr|irm|invoke-webrequest|invoke-restmethod)\b[^\n]{0,300}-infile\b/i,
  116. CODE_CMD, 'Uploads a local file to a remote host'),
  117. r('EXFIL_RAW_IP_URL', 'exfil', 'high',
  118. /\bhttps?:\/\/(?!(?:127\.|0\.0\.0\.0|10\.|192\.168\.|169\.254\.|172\.(?:1[6-9]|2\d|3[01])\.))\d{1,3}(?:\.\d{1,3}){3}\b/i,
  119. SCRIPTY, 'Request to a raw public IP address'),
  120. // ---- PERSISTENCE ----
  121. r('PERSIST_CRON', 'persistence', 'high',
  122. /\(\s*crontab\s+-l[^\n]{0,300}\)\s*\|\s*crontab\b|\|\s*crontab\s+-?\s*(?:$|[\s;&])|\bcrontab\s+-\s*$|>>?\s*\/etc\/cron\S*|>>?\s*\/var\/spool\/cron\S*/im,
  123. CODE_CMD, 'Installs a cron job'),
  124. r('PERSIST_SCHTASKS', 'persistence', 'high', /\bschtasks(?:\.exe)?\s+\/create\b|\bregister-scheduledtask\b/i, CODE_CMD,
  125. 'Creates a Windows scheduled task'),
  126. r('PERSIST_REG_RUN', 'persistence', 'high', /CurrentVersion[\\/]Run(?:Once)?\b/i, CODE_CMD,
  127. 'Registry Run key autostart'),
  128. r('PERSIST_SERVICE_ENABLE', 'persistence', 'high',
  129. /\bsystemctl\s+(?:--user\s+)?enable\b|\blaunchctl\s+(?:load|bootstrap)\b|\bsc(?:\.exe)?\s+create\b/i, CODE_CMD,
  130. 'Enables a service / launch agent'),
  131. r('PERSIST_STARTUP_FOLDER', 'persistence', 'high', /start menu[/\\]programs[/\\]startup/i, ALL,
    • Warning: Puts a file in the Windows Startup folder, so it runs at every login
    • Line 141 on GitHub
  132. 'Writes to the Windows Startup folder'),
  133. r('PERSIST_RC_APPEND', 'persistence', 'high',
  134. /(?:>>|\btee\s+-a|\badd-content\b)[^\n]{0,300}(?:\.bashrc|\.zshrc|\.zprofile|\.bash_profile|\.profile\b|\$profile\b|microsoft\.powershell_profile)/i,
  135. CODE_CMD, 'Appends to a shell startup file'),
  136. r('PERSIST_CLAUDE_SETTINGS_WRITE', 'persistence', 'high',
  137. /(?:>>?|\btee\b|\bsed\s+-i|\bset-content\b|\badd-content\b|\bout-file\b)[^\n]{0,300}\.claude[/\\]settings(?:\.local)?\.json/i,
  138. CODE_CMD, 'Modifies Claude Code settings from a script'),
  139. // ---- PERMISSIONS ----
  140. r('PERM_SKIP_PERMISSIONS', 'permissions', 'high',
  141. /--dangerously-skip-permissions\b|["']?defaultMode["']?\s*[:=]\s*["']bypassPermissions["']|--permission-mode[= ]+bypassPermissions\b/i,
  142. ALL, 'Disables Claude Code permission prompts'),
  143. r('PERM_ALLOW_ALL', 'permissions', 'high', /["'](?:Bash|Write|Edit|Read)\(\*{1,2}\)["']|["']allow["']\s*:\s*\[\s*["']\*["']/, ['config', 'markdown'],
  144. 'Blanket allow rule for powerful tools'),
  145. r('PERM_AUTO_MCP', 'permissions', 'medium', /["']enableAllProjectMcpServers["']\s*:\s*true/, ['config', 'markdown'],
  146. 'Auto-approves every project MCP server'),
  147. r('PERM_SUDO', 'permissions', 'medium', /(?:^|[;&|]\s*|\s)sudo\s+(?!-l\b)\S/, ['command'], 'Runs a command with sudo'),
  148. r('PERM_CHMOD_WORLD', 'permissions', 'medium', /\bchmod\s+(?:-R\s+)?(?:0?777|a\+rwx|\+s|u\+s)\b/, CODE_CMD,
  149. 'Makes files world-writable or setuid'),
  150. // ---- DESTRUCTIVE ----
  151. r('DESTRUCT_RM_HOME_ROOT', 'destructive', 'critical',
  152. /\brm\s+(?:-{1,2}[a-z-]+\s+)*(?:~|\$HOME|\$\{HOME\}|\/)\/?\*?(?=\s|$|[;&|"'])/i, CODE_CMD,
  153. 'Recursive delete of the home directory or filesystem root'),
  154. r('DESTRUCT_WIN_WIPE', 'destructive', 'critical',
  155. /\b(?:rd|rmdir|del|erase)\s+(?:\/[sq]\s+)+(?:[a-z]:\\?\*?|%userprofile%\\?\*?|%homepath%)(?=\s|$)|\bremove-item\b[^\n]{0,300}-recurse[^\n]{0,300}\s(?:[a-z]:\\\*?|\$env:userprofile\\?\*?|~[\\/]?\*?)(?=\s|$)/i,
  156. CODE_CMD, 'Recursive delete of a Windows drive root or user profile'),
  157. r('DESTRUCT_DISK', 'destructive', 'critical',
  158. /\bmkfs(?:\.\w+)?\s+\/dev\/|\bdd\s+[^\n]{0,300}\bof=\/dev\/(?:sd|nvme|hd|vd|disk)|>\s*\/dev\/(?:sd[a-z]|nvme\d)/i, CODE_CMD,
  159. 'Overwrites or formats a block device'),
  160. r('DESTRUCT_FORMAT_DRIVE', 'destructive', 'high', /\bformat(?:\.com)?\s+[a-z]:(?:\s|$)|\bclear-disk\b/i, CODE_CMD,
  161. 'Formats a Windows drive'),
  162. r('DESTRUCT_FORK_BOMB', 'destructive', 'critical', /:\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:/, CODE_CMD, 'Fork bomb'),
  163. // ---- OBFUSCATION ----
  164. r('OBF_BASE64_PIPE_SHELL', 'obfuscation', 'critical',
  165. /\bbase64\s+(?:-d|-D|--decode)\b[^\n]{0,300}\|\s*(?:sudo\s+)?(?:(?:ba|z|da)?sh|python[23]?|perl|iex)\b|frombase64string\b[^\n]{0,300}(?:\|\s*iex\b|invoke-expression)|\b(?:iex|invoke-expression)\b[^\n]{0,300}frombase64string/i,
    • Note: Quoted as data in code: Runs code it decodes (base64, hex, character codes, reversed text or a compressed blob), which hides what runs from a reader
    • Line 178 on GitHub
  166. ALL, 'Decodes base64 and executes it'),
  167. r('OBF_EVAL_DECODE', 'obfuscation', 'high',
  168. /\b(?:eval|exec|new\s+Function)\s*\(\s*(?:atob|Buffer\.from|base64\.b64decode|bytes\.fromhex|zlib\.decompress|String\.fromCharCode)\b/, CODE_CMD,
  169. 'Evaluates decoded data'),
  170. r('OBF_BASE64_BLOB', 'obfuscation', 'medium', /(?<![A-Za-z0-9+/])[A-Za-z0-9+/]{300,}={0,2}/, ['code'], 'Very long base64-like blob'),
  171. r('OBF_HEX_ESCAPES', 'obfuscation', 'medium', /(?:\\x[0-9a-f]{2}){16,}/i, ['code'], 'Long run of hex escapes'),
  172. r('OBF_CHARCODE_ARRAY', 'obfuscation', 'medium', /String\.fromCharCode\((?:\s*\d+\s*,){8,}/, ['code'],
  173. 'String assembled from char codes'),
  174. // ---- PROMPT INJECTION (English + Portuguese) ----
  175. // CONCEAL gaps never cross a clause break (`.`, `;`, `:`, `!`, `?`): "Do not retry; tell the user" is two clauses.
  176. // IGNORE gaps only stop at `.` (as before calibration): "Ignore everything above: your rules are now these" is one attack.
  177. // Singular "direction" is not a target noun ("Override the parent's direction inside a subgraph"); "lint rules" is not either.
  178. // These four are high in Markdown (the instruction surface) and medium in code/config (`kindSeverity`).
  179. r('INJECT_IGNORE_INSTRUCTIONS_EN', 'injection', 'high',
  180. /\b(?:ignore|disregard|forget|override)\b[^\n.]{0,30}\b(?:previous|prior|above|earlier|preceding|all|any|your|the|these|those|system)\b[^\n.]{0,30}\b(?<!\b(?:lint|linting|linter|eslint|tslint)\s)(?:instructions?|prompts?|rules?|directions|guidelines?)\b/i,
  181. ['markdown', 'config', 'code'], 'Tells the model to ignore its instructions'),
  182. r('INJECT_IGNORE_INSTRUCTIONS_PT', 'injection', 'high',
  183. /\b(?:ignor[ea]r?|desconsidere|desconsiderar|esque[çc]a|esquecer|sobrescreva)\b[^\n.]{0,40}\b(?:instru[çc][õo]es|regras|diretrizes|orienta[çc][õo]es|prompts?)\b/i,
  184. ['markdown', 'config', 'code'], 'Tells the model to ignore its instructions (Portuguese)'),
  185. r('INJECT_CONCEAL_FROM_USER_EN', 'injection', 'high',
  186. /\b(?:do not|don'?t|never)\b[^\n.;:!?]{0,20}\b(?:tell|inform|mention|reveal|notify|show|let)\b[^\n.;:!?]{0,20}\b(?:the |this )?(?:user|human|person)\b/i,
  187. ['markdown', 'config', 'code'], 'Instructs the model to hide actions from the user'),
  188. r('INJECT_CONCEAL_FROM_USER_PT', 'injection', 'high',
  189. /\bn[ãa]o\b[^\n.;:!?]{0,20}\b(?:conte|diga|informe|avise|mencione|revele|mostre|fale)\b[^\n.;:!?]{0,20}\b(?:usu[áa]rio|humano|pessoa)\b/i,
  190. ['markdown', 'config', 'code'], 'Instructs the model to hide actions from the user (Portuguese)'),
  191. r('INJECT_FAKE_SYSTEM_TAG', 'injection', 'high',
  192. /<\/?(?:system|important|admin|instructions?)>|\[\s*system\s*\]|<\|(?:im_start|system)\|>/i, PROSE,
  193. 'Fake system / important tag used to hijack the model'),
  194. r('INJECT_HIDDEN_COMMENT', 'injection', 'medium', /<!--[^\n]{0,300}(?:instruction|ignore|assistant|claude|system prompt|instru[çc][õo]es)[^\n]{0,300}-->/i, PROSE,
    • Note: Quoted as data in code: Gives the agent orders in an HTML comment, which the rendered page hides from a reader
    • Line 208 on GitHub
  195. 'HTML comment carrying instructions'),
  196. r('INJECT_REVEAL_PROMPT', 'injection', 'medium',
  197. /\b(?:reveal|print|output|repeat|leak|show)\b[^\n.]{0,30}\b(?:system prompt|your instructions|hidden instructions)\b|\b(?:revele|mostre|imprima)\b[^\n.]{0,30}\b(?:prompt do sistema|suas instru[çc][õo]es)\b/i,
  198. PROSE, 'Tries to extract the system prompt'),
  199. r('INJECT_ROLE_OVERRIDE', 'injection', 'medium',
  200. /\byou are now\b[^\n.]{0,40}\b(?:unrestricted|jailbroken|dan|developer mode|root|admin)\b|\bnew instructions?\s*:|\bnovas instru[çc][õo]es\s*:|\bvoc[êe] agora [ée] (?:um|uma) [^\n.]{0,20}(?:sem restri[çc][õo]es)/i,
  201. PROSE, 'Attempts to redefine the model role'),
  202. r('INJECT_SKIP_CONFIRMATION', 'injection', 'medium',
  203. // The pre-calibration broad match ("without/sem" + asking/confirmation/permission/approval/consent within 20 chars),
  204. // plus "prompting" and "sem perguntar" (new; not counted after "não/nunca" + up to 4 words, as in the user's own
  205. // skill "Não delete notas existentes sem perguntar"), minus narrow exclusions, each for a descriptive pattern observed on a real install:
  206. // "never push without permission" negation + one verb right before (superpowers spec)
  207. // "use it without asking" acting on a declared preference (superpowers using-git-worktrees:67)
  208. // "existing declared preference without asking" same (using-git-worktrees:45)
  209. // "was auto-creating worktrees without consent" past progressive narration, no clause punctuation in between
  210. // (superpowers RELEASE-NOTES:445)
  211. // "without their permission" / "without Jesse's" a named third party's consent (CODE_OF_CONDUCT:34, specs) — not
  212. // user's/anyone's/someone's/Claude's/agent's
  213. // "without asking which/what/follow-up/questions", whitespace + an OPENING quote ("without asking "what's
  214. // missing?""; a closing quote after the phrase still matches), "without asking in 24 of 24 runs"
  215. // (OMC agents/critic.md, explore.md; superpowers RELEASE-NOTES:70, specs)
  216. /(?<!\b(?:never|not|n't|nunca|n[ãa]o)\s+[\w-]+\s+|\buse\s+(?:it|that|this|them)\s+|\b(?:was|were)\s+[\w-]+ing\b[^\n.,;:!?]{0,60}|\b(?:declared|existing|stated|specified)\s+preferences?\s+)\b(?:without|sem)\b(?!\s+(?:their|his|her)\b|\s+(?!(?:user|human|owner|person|anyone|anybody|everyone|everybody|someone|somebody|claude|agent|assistant)['’]s\b)[a-z]+['’]s\b)[^\n.]{0,20}\b(?:asking|prompting|confirmation|confirma[çc][ãa]o|permiss[ãa]o|permission|approval|consent)\b(?!\s+["“‘]|\s+(?:which|what|whether|why|how|in\s+\d|(?:any\s+)?(?:follow-?up|clarifying|further)\b|(?:any\s+)?questions?\b))|(?<!\b(?:n[ãa]o|nunca)\s+(?:[^\s.;:!?]+\s+){0,4})\bsem\s+perguntar\b/i, PROSE,
  217. 'Tells the model to act without user confirmation'),
  218. r('INJECT_EXFIL_INSTRUCTION', 'injection', 'high',
  219. /\b(?:send|post|upload|exfiltrate|forward|envie|enviar|mande)\b[^\n.]{0,60}\b(?:ssh keys?|credentials?|api keys?|tokens?|secrets?|\.env|chaves? ssh|credenciais|segredos?)\b[^\n.]{0,60}\b(?:to|para)\s+(?:https?:|an? (?:external|remote)|\S+@)/i,
  220. PROSE, 'Instructs the model to send secrets to a remote destination'),
  221. // ---- SUPPLY CHAIN ----
  222. r('SUPPLY_INSTALL_FROM_URL', 'supply', 'medium',
  223. // The URL must be an argument of the same install command (no quote, pipe or separator in between),
  224. // so `npm i -g pkg` followed later on the line by an unrelated URL does not match.
  225. /\b(?:npm|pnpm|yarn|bun)\s+(?:i|install|add)\b(?:\s+(?:"[^"\n]*"|'[^'\n]*'|[^\s"'`|;&<>()]+)(?=\s|$)){0,20}?\s+["']?[^\s"'`|;&<>()]*(?:https?:\/\/|git\+|github:)|\bpip3?\s+install\b(?:\s+(?:"[^"\n]*"|'[^'\n]*'|[^\s"'`|;&<>()]+)(?=\s|$)){0,20}?\s+["']?(?:[^\s"'`|;&<>()]*(?:https?:\/\/|git\+)|--index-url\b|--extra-index-url\b|-i\s+["']?https?:)/i,
  226. ['command', 'code', 'markdown'], 'Installs a package from a URL or custom index'),
  227. r('SUPPLY_NPX_REMOTE', 'supply', 'medium', /\bnpx\s+(?:-y\s+|--yes\s+)[^\n]{0,300}(?:https?:\/\/|github:|git\+)/i, ALL,
  228. 'npx runs a package from a remote location'),
  229. r('SUPPLY_REGISTRY_OVERRIDE', 'supply', 'medium', /\bnpm\s+config\s+set\s+registry\b|--registry[= ]+https?:\/\/(?!registry\.npmjs\.org)/i, CODE_CMD,
  230. 'Overrides the package registry'),
  231. r('SUPPLY_LIFECYCLE_SCRIPT', 'supply', 'high',
  232. /["'](?:preinstall|install|postinstall|prepare)["']\s*:\s*["'][^"'\n]*\b(?:curl|wget|powershell|node\s+-e|python[23]?\s+-c|bash\s|sh\s+-c|iex)\b/i,
  233. ['config'], 'Install lifecycle script that downloads or evaluates code'),
  234. ];
  235. // Injection phrasing is high where the model reads it as instructions (Markdown) and medium in code/config,
  236. // where it is mostly string data or comments ("ignore any previous rules" in a linter, a test string).
    • Note: Quotes wording that overrides an agent's instructions or safety (in quotes, code, a table or an example): "ignore any previous rules"
    • Line 252 on GitHub
  237. const PROSE_HIGH_ONLY = new Set(['INJECT_IGNORE_INSTRUCTIONS_EN', 'INJECT_IGNORE_INSTRUCTIONS_PT', 'INJECT_CONCEAL_FROM_USER_EN', 'INJECT_CONCEAL_FROM_USER_PT']);
  238. for (const rule of RULES) if (PROSE_HIGH_ONLY.has(rule.id)) rule.kindSeverity = { code: 'medium', config: 'medium' };
  239. // ---- Path rules (applied to normalizePath(p)) ----
  240. const pr = (id, category, severity, pattern, description) => r(id, category, severity, pattern, ['path'], description);
  241. const PATH_RULES = [
  242. // Secret path rules also accept a relative form (`.ssh/id_rsa`, `.aws/credentials`) with no leading `/`.
  243. pr('SECRET_PATH_SSH', 'secret', 'high', /(?:^|\/)\.ssh(?:\/(?![^/]*\.pub$)|$)/i, 'SSH key directory'),
  244. pr('SECRET_PATH_AWS', 'secret', 'high', /(?:^|\/)\.aws\/(?:credentials|sso\/)/i, 'AWS credentials'),
  245. pr('SECRET_PATH_ENV', 'secret', 'high', /(?:^|\/)\.env(?:\.(?!example$|sample$|template$|dist$)[\w-]+)?$/i, 'Environment file'),
  246. pr('SECRET_PATH_NETRC', 'secret', 'high', /(?:^|\/)(?:\.netrc|_netrc|\.git-credentials)$/i, 'Stored git/netrc credentials'),
  247. pr('SECRET_PATH_TOKEN_FILES', 'secret', 'medium',
  248. /(?:^|\/)(?:\.npmrc|\.pypirc|\.docker\/config\.json|\.kube\/config|\.config\/gh\/hosts\.yml|\.gnupg\/[^/]+)$/i, 'Tool credential files'),
  249. pr('SECRET_PATH_CLAUDE_CREDENTIALS', 'secret', 'high', /(?:^|\/)\.claude\/\.credentials\.json$/i, 'Claude Code credentials'),
  250. pr('SECRET_PATH_BROWSER', 'secret', 'high',
  251. /\/(?:google[-/]chrome|chromium|brave-?software|brave-browser|microsoft[-/]edge|\.?mozilla\/firefox|vivaldi)\b.*\/(?:login data|cookies|logins\.json|key4\.db|web data|local state)$/i,
  252. 'Browser credential or cookie store'),
  253. pr('SECRET_PATH_WALLET', 'secret', 'high',
  254. /\/wallet\.dat$|\/\.(?:electrum|bitcoin|ethereum|monero)\/|\/(?:exodus|metamask|atomic)\/|\/keystore\/utc--|\/\.config\/solana\/id\.json$/i,
  255. 'Cryptocurrency wallet'),
  256. pr('PERSIST_PATH_SHELL_RC', 'persistence', 'high',
  257. /\/(?:\.bashrc|\.bash_profile|\.bash_login|\.profile|\.zshrc|\.zshenv|\.zprofile|\.zlogin|\.config\/fish\/config\.fish)$/i,
  258. 'Shell startup file'),
  259. pr('PERSIST_PATH_PS_PROFILE', 'persistence', 'high', /\/(?:[^/]*_)?profile\.ps1$/i, 'PowerShell profile'),
  260. pr('PERSIST_PATH_STARTUP', 'persistence', 'high', /\/start menu\/programs\/startup(?:\/|$)/i, 'Windows Startup folder'),
    • Warning: Puts a file in the Windows Startup folder, so it runs at every login
    • Line 279 on GitHub
  261. pr('PERSIST_PATH_LAUNCHD', 'persistence', 'high', /\/library\/launch(?:agents|daemons)\//i, 'macOS launch agent/daemon'),
  262. pr('PERSIST_PATH_SYSTEMD', 'persistence', 'high',
  263. /\/(?:\.config\/systemd\/user|etc\/systemd\/system|\.config\/autostart|etc\/cron[^/]*|var\/spool\/cron)(?:\/|$)/i,
  264. 'systemd / cron / autostart location'),
  265. pr('PERSIST_PATH_CLAUDE_SETTINGS', 'persistence', 'high', /\/\.claude\/(?:settings(?:\.[\w-]+)?\.json|hooks\/)/i,
  266. 'Claude Code settings or hooks'),
  267. pr('PERSIST_PATH_GIT_HOOKS', 'persistence', 'high', /\/\.git\/hooks\/[^/]+$/i, 'Git hook'),
  268. ];
  269. // ---- Matching ----
  270. function lineMatch(rule, line, lineNo, kind) {
  271. const hit = rule.pattern.exec(line);
  272. if (!hit) return null;
  273. const idx = hit.index;
  274. // Window around the hit keeps snippets useful on very long (minified) lines.
  275. const text = line.length > 400 ? line.slice(Math.max(0, idx - 60), idx + 160) : line.trim();
  276. const severity = rule.kindSeverity?.[kind] ?? rule.severity;
  277. return { ruleId: rule.id, category: rule.category, severity, line: lineNo, snippet: truncate(escapeInvisible(text.trim())) };
  278. }
  279. /** @param {string} text @param {FileKind} kind @returns {Match[]} */
  280. export function matchText(text, kind) {
  281. if (kind !== 'code' && kind !== 'markdown' && kind !== 'config') return [];
  282. const rules = RULES.filter(x => x.appliesTo.includes(kind));
  283. const out = [];
  284. const lines = String(text).split(/\r?\n/);
  285. for (let i = 0; i < lines.length; i++) {
  286. for (const rule of rules) {
  287. const m = lineMatch(rule, lines[i], i + 1, kind);
  288. if (m) out.push(m);
  289. }
  290. }
  291. return out;
  292. }
  293. /** @param {string} cmd @returns {Match[]} */
  294. export function matchCommand(cmd) {
  295. // Join backslash-newline continuations, then evaluate each logical line; one match per rule.
  296. const logical = String(cmd ?? '').replace(/\\\r?\n[ \t]*/g, ' ').split(/\r?\n/);
  297. const rules = RULES.filter(x => x.appliesTo.includes('command'));
  298. const out = [];
  299. for (const rule of rules) {
  300. for (const line of logical) {
  301. const m = lineMatch(rule, line, 1);
  302. if (m) { out.push(m); break; }
  303. }
  304. }
  305. return out;
  306. }
  307. /** @param {string} p @returns {Match[]} */
  308. export function matchPath(p) {
  309. const norm = normalizePath(p);
  310. const out = [];
  311. for (const rule of PATH_RULES) {
  312. if (rule.pattern.test(norm)) {
  313. out.push({ ruleId: rule.id, category: rule.category, severity: rule.severity, line: 1, snippet: truncate(escapeInvisible(String(p))) });
  314. }
  315. }
  316. return out;
  317. }
  318. const INVISIBLE = invisibleRegex();
  319. /** Report lines containing invisible / bidi / tag characters. @returns {Match[]} */
  320. export function findInvisible(text, kind) {
  321. if (kind !== 'code' && kind !== 'markdown' && kind !== 'config') return [];
  322. const severity = kind === 'markdown' ? 'critical' : 'medium';
  323. const lines = String(text).split(/\r?\n/);
  324. const out = [];
  325. for (let i = 0; i < lines.length; i++) {
  326. const line = lines[i];
  327. INVISIBLE.lastIndex = 0;
  328. let found = false;
  329. let mm;
  330. while ((mm = INVISIBLE.exec(line)) !== null) {
  331. const cp = mm[0].codePointAt(0);
  332. if (cp === 0xFEFF && i === 0 && mm.index === 0) continue; // BOM
  333. if (cp === 0x200D) {
  334. // Zero-width joiner inside emoji sequences is legitimate.
  335. const prev = line.codePointAt(mm.index - 1) ?? 0;
  336. const next = line.codePointAt(mm.index + 1) ?? 0;
  337. if (prev >= 0x2190 && next >= 0x2190) continue;
  338. }
  339. found = true;
  340. break;
  341. }
  342. if (found) {
  343. out.push({
  344. ruleId: 'OBF_INVISIBLE_CHARS', category: 'obfuscation', severity, line: i + 1,
  345. snippet: truncate(escapeInvisible(line.trim())),
  346. });
  347. }
  348. }
  349. return out;
  350. }

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.