"""dangerous-command-guard — literal, unobfuscated shell/git/SQL/publish
pattern matching, ported from PinkyAI's `rules::dangerous_commands` engine
module (see README.md "Provenance").
**Obfuscation limits, stated plainly:** every pattern here matches the
literal, spelled-out command. Like any regex-based check, it does not
survive deliberate obfuscation — a general, known limitation of
pattern-based detection, not something this tool tries to solve. Regex
on plain text catches what a user or an unsophisticated script actually
types; it is not a sandbox and isn't trying to be one.
Pure stdlib, no network call, no execution of anything it scans.
"""
from __future__ import annotations
import argparse
import json
import re
import sys
from dataclasses import dataclass
from pathlib import Path
_PUBLISH_VERBS: tuple[str, ...] = (
"@JuliaRegistrator register",
"LocalRegistry.register(",
"PacletSubmit[",
"Publish-Module",
"Publish-PSResource",
"ResourceSubmit[",
"alr publish",
"az bicep publish",
"bal publish",
"bal push",
"bazel run --stamp",
"bazel run //:publish",
"buf push",
"bun publish",
"cabal upload",
"cargo publish",
"chicken-install -init",
"clj -X:deploy",
"clojure -X:deploy",
"cpan-upload",
"cue mod publish",
"dart pub publish",
"deno publish",
"docker compose push",
"docker push",
"dotnet nuget push",
"dub publish",
"dune-release",
"dzil release",
"elm bump",
"elm publish",
"fez upload",
"flutter pub publish",
"forge create",
"forge verify-contract",
"fpm publish",
"gem push",
"gleam publish",
"godot --headless --export-release",
"gradle publish",
"gradlew publish",
"haxelib submit",
"helm push",
"lake upload",
"lein deploy",
"lein deploy clojars",
"luarocks upload",
"mix hex.publish",
"mvn deploy",
"nimble publish",
"npm publish",
"npx hardhat ignition deploy",
"opam publish",
"pdk release",
"pnpm publish",
"pod trunk push",
"poetry publish",
"puppet module push",
"ql-dist",
"raco pkg catalog-archive",
"raco pkg publish",
"rover graph publish",
"rover subgraph publish",
"sf package version create",
"sf project deploy start",
"sfdx force:source:deploy",
"spago publish",
"stack upload",
"swipl pack publish",
"teacup put",
"tk apply",
"twine upload",
"uv publish",
"yarn npm publish",
"yarn publish",
"zef publish",
)
_PRE_REGISTRY_PUBLISH = (
r"\b(?:npm\s+publish|yarn\s+publish|cargo\s+publish|gem\s+push|twine\s+upload|"
r"pip\s+upload|mvn\s+deploy|gradlew?\s+publish)\b"
)
def _publish_pattern() -> re.Pattern[str]:
"""The engine's `publish_command_pattern()` (L2-T06), one for one: every
registry publish verb, whitespace-flexible, word-bounded when it ends in
a word character, plus the pre-registry literals."""
alts: list[str] = []
for verb in _PUBLISH_VERBS:
alt = re.escape(verb).replace("\\ ", "\\s+").replace(" ", "\\s+")
if verb[-1].isalnum():
alt += "\\b"
if alt not in alts:
alts.append(alt)
return re.compile(f"(?:{_PRE_REGISTRY_PUBLISH}|(?:^|\\s|[;&|(`])(?:{'|'.join(alts)}))")
_PINKYAI_KEYCHAIN_NAMES = (
"pinkyai",
"anthropic-api-key",
"pii-vault-key",
"auth0-access-token",
"auth0-refresh-token",
"ai.pinky.quarantine",
"content-key-v1",
"ai.pinky.lineage",
"credential-id-key-v1",
"ai.pinky.audit-chain",
"head-anchor-v1",
)
def _pinkyai_keychain_read_pattern() -> re.Pattern[str]:
"""Ported from the engine's `pinkyai_keychain_read_pattern`, byte for
byte: a name counts only as a whole argument (after whitespace or a
flag cluster such as `-wa`, optionally quoted, ending at whitespace, a
quote, a shell separator or the end), so `-s pinkyai-other` does not
match. `security dump-keychain` matches only with `-d` (decrypt).
Not covered, as in the engine: `security -i` on stdin and a name
assembled at run time.
"""
names = "|".join(re.escape(n) for n in _PINKYAI_KEYCHAIN_NAMES)
arg = rf"""(?:\s|\s-[A-Za-z]*)['"]?(?:{names})(?:['"\s;|&)]|$)"""
return re.compile(
rf"\bsecurity\s+find-(?:generic|internet)-password\b[^\n;|&]*?{arg}"
r"|\bsecurity\s+dump-keychain\b[^\n;|&]*\s-[A-Za-z]*d"
rf"|\bsecret-tool\s+(?:lookup|search)\b[^\n;|&]*?{arg}"
)
_PATTERNS: list[tuple[str, str, str, re.Pattern[str]]] = [
(
"rm_rf_broad_path",
"block",
"critical",
re.compile(
r"\brm\s+(?:-rf|-fr|-Rf|-fR|-RF|-FR)\s+(?:/|~|\$HOME)\S*"
r"|\brm\s+(?:-rf|-fr|-Rf|-fR|-RF|-FR)\s+\.{1,2}(?:\s|$)"
),
),
(
"curl_pipe_shell",
"block",
"critical",
re.compile(r"\b(?:curl|wget)\b[^\n|]*\|\s*(?:sudo\s+)?(?:bash|sh|zsh)\b"),
),
(
"disk_write_to_device",
"block",
"critical",
re.compile(r"\bdd\b[^\n]{0,80}\bof=/dev/\S+|\bmkfs(?:\.\w+)?\s+/dev/\S+"),
),
(
"fork_bomb",
"block",
"critical",
re.compile(r":\s*\(\s*\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:"),
),
("git_reset_hard", "warn", "high", re.compile(r"\bgit\s+reset\b[^\n]*--hard\b")),
(
"base64_pipe_shell",
"block",
"critical",
re.compile(
r"\bbase64\b[^\n|]*(?:-d|-D|--decode)[^\n|]*\|\s*"
r"(?:sudo\s+)?(?:bash|sh|zsh|python3?|perl|ruby|node)\b"
),
),
("pinkyai_keychain_read", "block", "critical", _pinkyai_keychain_read_pattern()),
("chmod_777", "warn", "high", re.compile(r"\bchmod\s+(?:-R\s+)?0?777\b")),
("git_force_push", "warn", "high", re.compile(r"\bgit\s+push\b[^\n]*(?:--force(?:[^-]|$)|\s-f(?:\s|$))")),
(
"sql_drop_or_truncate",
"block",
"critical",
re.compile(r"(?i)\b(?:DROP\s+(?:TABLE|DATABASE)|TRUNCATE\s+TABLE)\b"),
),
(
"publish",
"warn",
"high",
_publish_pattern(),
),
("infra_destroy", "block", "critical", re.compile(r"""(?x)\b(?:
(?:terraform|tofu)\s+destroy
| (?:terraform|tofu)\s+apply\b[^\n]*-destroy
| pulumi\s+(?:destroy|stack\s+rm)
| cdk\s+destroy
| cdktf\s+destroy
| sam\s+delete
| (?:serverless|sls)\s+remove
| kubectl\s+delete\s+(?:namespace|ns|node|nodes|pv|persistentvolumes?|crd|customresourcedefinitions?|clusterrole|clusterrolebinding)\b
| kubectl\s+delete\b[^\n]*(?:\s--all(?:\s|$)|\s-A(?:\s|$)|\s--all-namespaces)
| gcloud\s+(?:projects|sql\s+instances|compute\s+instances|container\s+clusters|storage\s+buckets|run\s+services|functions)\s+delete
| gsutil\s+(?:rm\s+-r|rb)\b
| az\s+(?:group|vm|aks|sql\s+server|sql\s+db|storage\s+account|webapp|functionapp|cosmosdb)\s+delete
| aws\s+(?:s3\s+rb|s3\s+rm\b[^\n]*--recursive|s3api\s+delete-bucket|rds\s+delete-db-(?:instance|cluster)|ec2\s+terminate-instances|cloudformation\s+delete-stack|dynamodb\s+delete-table|eks\s+delete-cluster|ecs\s+delete-(?:cluster|service)|lambda\s+delete-function|iam\s+delete-(?:user|role))
| fly(?:ctl)?\s+(?:apps\s+destroy|destroy|volumes\s+destroy|postgres\s+destroy)
| vercel\s+(?:remove|rm)\b
| netlify\s+sites:delete
| heroku\s+(?:apps:destroy|pg:reset)
| gh\s+repo\s+delete
| helm\s+(?:uninstall|delete)\b[^\n]*--all-namespaces
)""")),
("infra_delete", "warn", "high", re.compile(r"""(?x)\b(?:
kubectl\s+delete\s+(?:deploy(?:ment)?s?|sts|statefulsets?|svc|services?|ing(?:ress)?(?:es)?|pvc|persistentvolumeclaims?|secrets?|configmaps?|cm|jobs?|cronjobs?|daemonsets?|ds)\b
| helm\s+(?:uninstall|delete)\b
| docker\s+(?:system|volume|image|container|network)\s+prune
| docker\s+rm\s+-f\b
| docker\s+rmi\b
| docker(?:\s+compose|-compose)\s+down\b[^\n]*(?:\s-v(?:\s|$)|--volumes|--rmi)
| podman\s+(?:system|volume)\s+prune
)""")),
("db_reset", "block", "critical", re.compile(r"""(?x)(?:\b(?:
(?:rails|rake|bin/rails)\s+db:(?:drop|reset|purge|schema:load\b[^\n]*--force)
| prisma\s+(?:migrate\s+reset|db\s+push\b[^\n]*--force-reset)
| alembic\s+downgrade\s+base
| (?:manage\.py|django-admin)\s+(?:flush|migrate\s+\S+\s+zero|reset_db|sqlflush)
| artisan\s+(?:migrate:fresh|migrate:reset|db:wipe|migrate:rollback\b[^\n]*--step=0)
| mix\s+ecto\.(?:drop|reset)
| dotnet\s+ef\s+database\s+drop
| flyway\s+clean
| liquibase\s+(?:dropAll|drop-all)
| dbmate\s+drop
| knex\s+migrate:rollback\b[^\n]*--all
| goose\s+(?:reset|down-to\s+0)
| sequelize(?:-cli)?\s+db:drop
| typeorm\s+schema:drop
| drizzle-kit\s+drop
| atlas\s+schema\s+clean
| dropdb\s
| mysqladmin\b[^\n]*\sdrop\s
| redis-cli\b[^\n]*\b(?:FLUSHALL|FLUSHDB|flushall|flushdb)\b
| supabase\s+db\s+reset
| pscale\s+database\s+delete
| wrangler\s+d1\s+delete
| turso\s+db\s+destroy
)|dropDatabase\(\))""")),
]
_ACTION_RANK = {"block": 2, "warn": 1}
@dataclass(frozen=True)
class Finding:
rule_id: str
action: str
severity: str
line: int
column: int
matched: str
def to_dict(self) -> dict[str, object]:
return {
"rule_id": self.rule_id,
"action": self.action,
"severity": self.severity,
"line": self.line,
"column": self.column,
"matched": self.matched,
}
def check_text(text: str) -> list[Finding]:
"""Scans `text` (a single command, or a multi-line script) line by
line against every pattern. Pure, no I/O.
"""
findings: list[Finding] = []
for line_no, line in enumerate(text.splitlines() or [text], start=1):
for rule_id, action, severity, pattern in _PATTERNS:
for match in pattern.finditer(line):
findings.append(
Finding(
rule_id=rule_id,
action=action,
severity=severity,
line=line_no,
column=match.start() + 1,
matched=match.group(0),
)
)
return findings
def worst_action(findings: list[Finding]) -> str | None:
"""The highest-ranked action across `findings` (`"block"` beats
`"warn"`), or `None` if `findings` is empty.
"""
if not findings:
return None
return max((f.action for f in findings), key=lambda a: _ACTION_RANK[a])
def _print_human(findings: list[Finding]) -> None:
if not findings:
print("dangerous-command-guard: no matches for the 7 patterns this tool checks.")
return
for f in findings:
print(f"[{f.action}/{f.severity}] {f.rule_id} — line {f.line}, col {f.column} — {f.matched!r}")
worst = worst_action(findings)
if worst == "block":
print("\nAt least one BLOCK-tier match. Treat as: do not run without explicit, informed confirmation.")
else:
print("\nOnly WARN-tier matches. Often intentional — flag it, let the human decide.")
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="Check a shell command/script for high-risk literal patterns.")
parser.add_argument("command", nargs="?", help="The exact command to check")
parser.add_argument("--file", help="Path to a script file to check")
parser.add_argument("--stdin", action="store_true", help="Read the command/script from stdin")
parser.add_argument("--json", action="store_true", help="Print findings as JSON instead of text")
args = parser.parse_args(argv)
if args.stdin:
text = sys.stdin.read()
elif args.file:
text = Path(args.file).read_text(encoding="utf-8")
elif args.command is not None:
text = args.command
else:
parser.error("provide a command, --file, or --stdin")
return 2
findings = check_text(text)
if args.json:
print(json.dumps([f.to_dict() for f in findings], indent=2))
else:
_print_human(findings)
action = worst_action(findings)
if action == "block":
return 2
if action == "warn":
return 1
return 0
if __name__ == "__main__":
sys.exit(main())