AI coding agents can edit files, run shell commands, and touch infrastructure. One bad rm -rf, force-push, or docker compose down -v can wipe hours of work or production data.
| 1 | # SPDX-License-Identifier: MIT |
| 2 | """Shell metacharacter / chain signals.""" |
| 3 | |
| 4 | from __future__ import annotations |
| 5 | |
| 6 | from agent_guard.config import GuardConfig |
| 7 | from agent_guard.models import Decision, Finding, ParsedCommand, RiskLevel |
| 8 | from agent_guard.parser import parse_command |
| 9 | from agent_guard.risk import SCORE_SHELL_CHAIN |
| 10 | from agent_guard.rules import RuleDefinition, register_rule |
| 11 | |
| 12 | |
| 13 | @register_rule( |
| 14 | RuleDefinition( |
| 15 | id="shell.chain_signal", |
| 16 | category="shell_chain_destructive", |
| 17 | risk=RiskLevel.MEDIUM, |
| 18 | default_decision=Decision.WARN, |
| 19 | description="Flags shell chaining operators as risk signals; analyzes each segment.", |
| 20 | ) |
| 21 | ) |
| 22 | def rule_shell_chain(parsed: ParsedCommand, config: GuardConfig) -> list[Finding]: |
| 23 | if not parsed.has_shell_operators: |
| 24 | return [] |
| 25 | |
| 26 | findings: list[Finding] = [ |
| 27 | Finding( |
| 28 | rule_id="shell.operators", |
| 29 | category="shell_chain_destructive", |
| 30 | risk=RiskLevel.LOW, |
| 31 | decision=Decision.ALLOW, |
| 32 | reason="Shell metacharacters detected; treated as a risk signal, not an automatic block.", |
| 33 | score_delta=SCORE_SHELL_CHAIN, |
| 34 | detected=parsed.shell_operators, |
| 35 | suggestions=("Prefer separate, explicit commands for safer evaluation.",), |
| 36 | ) |
| 37 | ] |
| 38 | |
| 39 | # Analyze remaining segments with a shallow re-parse to catch chained danger |
| 40 | # Avoid infinite recursion: only look at filesystem/git keywords in segments[1:] |
| 41 | for segment in parsed.segments[1:]: |
| 42 | seg = parse_command(segment) |
| 43 | prog = seg.program.lower() |
| 44 | if prog in {"rm", "del", "rmdir", "git", "docker"} or "drop" in segment.lower(): |
| 45 | findings.append( |
| 46 | Finding( |
| 47 | rule_id="shell.chained_sensitive", |
| 48 | category="shell_chain_destructive", |
| 49 | risk=RiskLevel.MEDIUM, |
| 50 | decision=Decision.WARN, |
| 51 | reason="A sensitive operation appears in a chained shell command.", |
| 52 | target=segment[:120], |
| 53 | score_delta=25, |
| 54 | detected=(prog,), |
| 55 | ) |
| 56 | ) |
| 57 | return findings |