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 | """Filesystem destruction and protected-path rules.""" |
| 3 | |
| 4 | from __future__ import annotations |
| 5 | |
| 6 | import re |
| 7 | |
| 8 | from agent_guard.config import GuardConfig |
| 9 | from agent_guard.filesystem import ( |
| 10 | is_dangerous_root_target, |
| 11 | is_system_path, |
| 12 | looks_like_build_artifact, |
| 13 | matches_protected_path, |
| 14 | ) |
| 15 | from agent_guard.models import Decision, Finding, ParsedCommand, RiskLevel |
| 16 | from agent_guard.risk import ( |
| 17 | SCORE_PROTECTED_PATH, |
| 18 | SCORE_RECURSIVE_DELETION, |
| 19 | SCORE_ROOT_DELETION, |
| 20 | SCORE_SYSTEM_PATH, |
| 21 | ) |
| 22 | from agent_guard.rules import RuleDefinition, register_rule |
| 23 | |
| 24 | _RM_RECURSIVE_FLAGS = re.compile(r"^-.*[rR].*$|^-.*[fF].*[rR].*$|^-[rR][fF].*$|^-[fF][rR].*$") |
| 25 | |
| 26 | |
| 27 | def _has_recursive_flag(flags: tuple[str, ...]) -> bool: |
| 28 | for flag in flags: |
| 29 | # Combined short flags: -rf, -fr, -r, -R, --recursive |
| 30 | if flag in {"-r", "-R", "--recursive", "-rf", "-fr", "-fR", "-Rf", "-rF", "-FR", "-Rm"}: |
| 31 | return True |
| 32 | if flag.startswith("-") and not flag.startswith("--"): |
| 33 | body = flag[1:] |
| 34 | if "r" in body.lower() and ("f" in body.lower() or True): |
| 35 | # -r alone or combined with others |
| 36 | if "r" in body.lower(): |
| 37 | return True |
| 38 | if flag == "--recursive": |
| 39 | return True |
| 40 | return False |
| 41 | |
| 42 | |
| 43 | def _delete_targets(parsed: ParsedCommand) -> list[str]: |
| 44 | prog = parsed.program.lower().replace("\\", "/").split("/")[-1] |
| 45 | if prog.endswith(".exe"): |
| 46 | prog = prog[:-4] |
| 47 | |
| 48 | targets: list[str] = [] |
| 49 | if prog in {"rm", "rmdir", "del", "erase", "rd"}: |
| 50 | targets.extend(p for p in parsed.positional if not p.startswith("-")) |
| 51 | elif prog in {"remove-item", "ri"}: |
| 52 | targets.extend(parsed.positional) |
| 53 | elif prog == "python" or prog.startswith("python"): |
| 54 | joined = " ".join(parsed.arguments) |
| 55 | if "shutil.rmtree" in joined or "rmtree" in joined: |
| 56 | # Extract string literals roughly |
| 57 | for match in re.finditer(r"['\"]([^'\"]+)['\"]", joined): |
| 58 | targets.append(match.group(1)) |
| 59 | return targets |
| 60 | |
| 61 | |
| 62 | def _is_delete_command(parsed: ParsedCommand) -> bool: |
| 63 | prog = parsed.program.lower().replace("\\", "/").split("/")[-1] |
| 64 | if prog.endswith(".exe"): |
| 65 | prog = prog[:-4] |
| 66 | if prog in {"rm", "rmdir", "del", "erase", "rd", "remove-item", "ri"}: |
| 67 | return True |
| 68 | joined = " ".join(parsed.arguments).lower() |
| 69 | if "shutil.rmtree" in joined: |
| 70 | return True |
| 71 | # PowerShell Remove-Item -Recurse |
| 72 | raw_lower = parsed.raw.lower() |
| 73 | return bool("remove-item" in raw_lower and ("-recurse" in raw_lower or "-r " in raw_lower)) |
| 74 | |
| 75 | |
| 76 | @register_rule( |
| 77 | RuleDefinition( |
| 78 | id="filesystem.recursive_delete", |
| 79 | category="destructive_filesystem", |
| 80 | risk=RiskLevel.HIGH, |
| 81 | default_decision=Decision.BLOCK, |
| 82 | description="Detects recursive directory deletion (rm -rf, rmdir /s, Remove-Item -Recurse).", |
| 83 | ) |
| 84 | ) |
| 85 | def rule_recursive_delete(parsed: ParsedCommand, config: GuardConfig) -> list[Finding]: |
| 86 | if not _is_delete_command(parsed): |
| 87 | return [] |
| 88 | |
| 89 | prog = parsed.program.lower().replace("\\", "/").split("/")[-1] |
| 90 | if prog.endswith(".exe"): |
| 91 | prog = prog[:-4] |
| 92 | |
| 93 | recursive = _has_recursive_flag(parsed.flags) |
| 94 | raw_lower = parsed.raw.lower() |
| 95 | if "remove-item" in raw_lower and "-recurse" in raw_lower: |
| 96 | recursive = True |
| 97 | if "/s" in parsed.flags or any(f.lower() == "/s" for f in parsed.flags): |
| 98 | recursive = True |
| 99 | if "shutil.rmtree" in " ".join(parsed.arguments).lower(): |
| 100 | recursive = True |
| 101 | if prog in {"rmdir", "rd"} and any(f.lower() in {"/s", "-s"} for f in parsed.flags): |
| 102 | recursive = True |
| 103 | |
| 104 | if not recursive and prog not in {"rmdir"}: |
| 105 | # Non-recursive rm of a single file is lower risk — still check targets |
| 106 | pass |
| 107 | |
| 108 | targets = _delete_targets(parsed) |
| 109 | if not targets and "shutil.rmtree" not in parsed.raw: |
| 110 | # rm -rf with no target still suspicious if recursive |
| 111 | if recursive: |
| 112 | return [ |
| 113 | Finding( |
| 114 | rule_id="filesystem.recursive_delete", |
| 115 | category="destructive_filesystem", |
| 116 | risk=RiskLevel.HIGH, |
| 117 | decision=Decision.WARN, |
| 118 | reason="Recursive deletion requested without a clear target.", |
| 119 | score_delta=SCORE_RECURSIVE_DELETION, |
| 120 | suggestions=("Specify an explicit, regenerable path if intentional.",), |
| 121 | ) |
| 122 | ] |
| 123 | return [] |
| 124 | |
| 125 | findings: list[Finding] = [] |
| 126 | for target in targets or ["."]: |
| 127 | if is_dangerous_root_target(target): |
| 128 | findings.append( |
| 129 | Finding( |
| 130 | rule_id="filesystem.root_delete", |
| 131 | category="destructive_filesystem", |
| 132 | risk=RiskLevel.CRITICAL, |
| 133 | decision=Decision.BLOCK, |
| 134 | reason="Recursive deletion inside the source directory." |
| 135 | if target in {".", "./"} |
| 136 | else "Recursive deletion of a filesystem root is catastrophic.", |
| 137 | target=target, |
| 138 | score_delta=SCORE_ROOT_DELETION, |
| 139 | suggestions=("Never delete filesystem roots. Use a specific subdirectory.",), |
| 140 | ) |
| 141 | ) |
| 142 | # Spec example for rm -rf ./src says "source directory" — handle below |
| 143 | continue |
| 144 | |
| 145 | if is_system_path(target): |
| 146 | findings.append( |
| 147 | Finding( |
| 148 | rule_id="filesystem.system_path_delete", |
| 149 | category="destructive_filesystem", |
| 150 | risk=RiskLevel.CRITICAL, |
| 151 | decision=Decision.BLOCK, |
| 152 | reason="Deletion targets a sensitive system or user configuration path.", |
| 153 | target=target, |
| 154 | score_delta=SCORE_SYSTEM_PATH, |
| 155 | ) |
| 156 | ) |
| 157 | continue |
| 158 | |
| 159 | matched = matches_protected_path(target, config.protected_paths, config.project_root) |
| 160 | if matched: |
| 161 | findings.append( |
| 162 | Finding( |
| 163 | rule_id="filesystem.protected_path_delete", |
| 164 | category="destructive_filesystem", |
| 165 | risk=RiskLevel.CRITICAL, |
| 166 | decision=Decision.BLOCK, |
| 167 | reason="Deletion targets a protected path.", |
| 168 | target=target, |
| 169 | score_delta=SCORE_PROTECTED_PATH + (SCORE_RECURSIVE_DELETION if recursive else 0), |
| 170 | detected=(matched,), |
| 171 | suggestions=("Remove the path from protected_paths only if intentional.",), |
| 172 | ) |
| 173 | ) |
| 174 | continue |
| 175 | |
| 176 | # ./src style — project source |
| 177 | name = target.replace("\\", "/").rstrip("/").split("/")[-1] |
| 178 | if recursive and name in {"src", "source", "lib", "app"}: |
| 179 | findings.append( |
| 180 | Finding( |
| 181 | rule_id="filesystem.recursive_delete", |
| 182 | category="destructive_filesystem", |
| 183 | risk=RiskLevel.CRITICAL, |
| 184 | decision=Decision.BLOCK, |
| 185 | reason="Recursive deletion inside the source directory.", |
| 186 | target=target, |
| 187 | score_delta=SCORE_RECURSIVE_DELETION + 40, |
| 188 | suggestions=("Delete specific build artifacts instead of source trees.",), |
| 189 | ) |
| 190 | ) |
| 191 | continue |
| 192 | |
| 193 | if recursive and looks_like_build_artifact(target): |
| 194 | findings.append( |
| 195 | Finding( |
| 196 | rule_id="filesystem.recursive_delete", |
| 197 | category="destructive_filesystem", |
| 198 | risk=RiskLevel.LOW, |
| 199 | decision=Decision.ALLOW, |
| 200 | reason="Recursive deletion of a regenerable build/dependency directory.", |
| 201 | target=target, |
| 202 | score_delta=10, |
| 203 | ) |
| 204 | ) |
| 205 | continue |
| 206 | |
| 207 | if recursive: |
| 208 | findings.append( |
| 209 | Finding( |
| 210 | rule_id="filesystem.recursive_delete", |
| 211 | category="destructive_filesystem", |
| 212 | risk=RiskLevel.HIGH, |
| 213 | decision=Decision.BLOCK, |
| 214 | reason="Recursive deletion can permanently remove project files.", |
| 215 | target=target, |
| 216 | score_delta=SCORE_RECURSIVE_DELETION, |
| 217 | suggestions=("Prefer deleting specific files or regenerable directories.",), |
| 218 | ) |
| 219 | ) |
| 220 | else: |
| 221 | findings.append( |
| 222 | Finding( |
| 223 | rule_id="filesystem.file_delete", |
| 224 | category="destructive_filesystem", |
| 225 | risk=RiskLevel.MEDIUM, |
| 226 | decision=Decision.WARN, |
| 227 | reason="File deletion requested.", |
| 228 | target=target, |
| 229 | score_delta=25, |
| 230 | ) |
| 231 | ) |
| 232 | return findings |
| 233 | |
| 234 | |
| 235 | @register_rule( |
| 236 | RuleDefinition( |
| 237 | id="filesystem.protected_path_access", |
| 238 | category="secret_access", |
| 239 | risk=RiskLevel.HIGH, |
| 240 | default_decision=Decision.BLOCK, |
| 241 | description="Detects read/write access to configured protected paths.", |
| 242 | ) |
| 243 | ) |
| 244 | def rule_protected_access(parsed: ParsedCommand, config: GuardConfig) -> list[Finding]: |
| 245 | prog = parsed.program.lower().replace("\\", "/").split("/")[-1] |
| 246 | if prog.endswith(".exe"): |
| 247 | prog = prog[:-4] |
| 248 | |
| 249 | readers = { |
| 250 | "cat", |
| 251 | "type", |
| 252 | "get-content", |
| 253 | "gc", |
| 254 | "less", |
| 255 | "more", |
| 256 | "head", |
| 257 | "tail", |
| 258 | "bat", |
| 259 | "hexdump", |
| 260 | "xxd", |
| 261 | "open", |
| 262 | "notepad", |
| 263 | "code", |
| 264 | "vim", |
| 265 | "nano", |
| 266 | "emacs", |
| 267 | "sed", |
| 268 | "awk", |
| 269 | } |
| 270 | writers = {"cp", "copy", "mv", "move", "tee", "set-content", "out-file", "echo"} |
| 271 | |
| 272 | if prog not in readers | writers and prog not in {"rm", "del", "rmdir"}: |
| 273 | # Also check any positional that looks protected for generic commands |
| 274 | pass |
| 275 | |
| 276 | findings: list[Finding] = [] |
| 277 | candidates = list(parsed.positional) |
| 278 | # echo foo > .env style — look in raw for protected names |
| 279 | for target in candidates: |
| 280 | matched = matches_protected_path(target, config.protected_paths, config.project_root) |
| 281 | if not matched: |
| 282 | continue |
| 283 | if prog in readers or prog in {"rm", "del", "cat", "type"}: |
| 284 | findings.append( |
| 285 | Finding( |
| 286 | rule_id="filesystem.protected_path_access", |
| 287 | category="secret_access", |
| 288 | risk=RiskLevel.HIGH, |
| 289 | decision=Decision.BLOCK, |
| 290 | reason="Sensitive file access detected.", |
| 291 | target=target, |
| 292 | score_delta=SCORE_PROTECTED_PATH, |
| 293 | detected=(matched,), |
| 294 | suggestions=("Use redacted examples or non-secret fixtures instead.",), |
| 295 | ) |
| 296 | ) |
| 297 | elif prog in writers: |
| 298 | findings.append( |
| 299 | Finding( |
| 300 | rule_id="filesystem.protected_path_write", |
| 301 | category="secret_access", |
| 302 | risk=RiskLevel.HIGH, |
| 303 | decision=Decision.BLOCK, |
| 304 | reason="Write targeting a protected path.", |
| 305 | target=target, |
| 306 | score_delta=SCORE_PROTECTED_PATH, |
| 307 | detected=(matched,), |
| 308 | ) |
| 309 | ) |
| 310 | return findings |