approval_floors.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. """Pre-gate floors for :mod:`tools.approval`: decisions that never reach a prompt.
  2. Unconditional blocks (hardline, ``sudo -S`` password piping, the user's own
  3. ``approvals.deny`` globs) and the permanent command allowlist match. All of
  4. them run BEFORE yolo / ``approvals.mode: off`` / cron approve-mode; the
  5. allowlist runs after. Session state stays in ``tools.approval`` and is read
  6. through it at call time.
  7. """
  8. import fnmatch
  9. import logging
  10. import re
  11. import time
  12. import uuid
  13. from tools import approval_context as _ctx
  14. from utils import unlink_files_older_than
  15. from tools.approval_detection import (
  16. _MALFORMED_EXEC_DESCRIPTION, _PARSER_LIMIT_DESCRIPTION, _deny_command_variants)
  17. logger = logging.getLogger("tools.approval")
  18. def _match_user_deny_rule(command: str) -> str | None:
  19. """Return the matching ``approvals.deny`` glob, or None. User-defined fnmatch
  20. globs that block unconditionally — like the hardline floor, a match fires
  21. BEFORE the yolo / mode=off bypass ("never let the agent run this, even under
  22. yolo"). Case-insensitive, run over the same normalized/deobfuscated variants
  23. the dangerous-pattern detector uses so quoting tricks (``r\\m``,
  24. ``git st""atus``) can't sidestep a rule."""
  25. try:
  26. deny_patterns = _ctx._get_approval_config().get("deny") or []
  27. except Exception:
  28. return None
  29. globs = [p.strip() for p in deny_patterns if isinstance(p, str) and p.strip()]
  30. if not globs:
  31. return None
  32. for command_variant in _deny_command_variants(command):
  33. candidate = command_variant.lower().strip()
  34. for pattern in globs:
  35. if fnmatch.fnmatchcase(candidate, pattern.lower()):
  36. return pattern
  37. return None
  38. def _user_deny_block_result(pattern: str) -> dict:
  39. """Build the standard block result for an ``approvals.deny`` match."""
  40. return {"approved": False, "user_deny": True, "message": (
  41. f"BLOCKED: this command matches the user-defined deny rule "
  42. f"'{pattern}' (approvals.deny in config.yaml). It cannot be "
  43. "executed via the agent — not even with --yolo, /yolo, or "
  44. "approvals.mode=off. Do NOT retry or rephrase this command; the user has explicitly forbidden it.")}
  45. def _save_blocked_payload(command: str) -> str | None:
  46. """Persist a parser-limit-blocked command as a runnable script. That block
  47. fires on payload SIZE/shape, not the operation — usually a legitimate script
  48. the model inlined. Saving it makes recovery one turn (`bash <file>`) instead
  49. of two, and is strictly safer than the hint-only path: the file goes through
  50. the normal execution pipeline (including the referenced-script content guard)
  51. and nothing runs here. Returns the path, or None on any failure (hint falls
  52. back to write_file)."""
  53. try:
  54. from hermes_constants import get_hermes_home
  55. script_dir = get_hermes_home() / "cache" / "blocked-scripts"
  56. script_dir.mkdir(parents=True, exist_ok=True)
  57. # Opportunistic cleanup: blocked payloads older than 7 days.
  58. unlink_files_older_than(script_dir, "blocked-*.sh", 7 * 86400)
  59. path = script_dir / f"blocked-{int(time.time())}-{uuid.uuid4().hex[:8]}.sh"
  60. path.write_text(
  61. "#!/usr/bin/env bash\n"
  62. "# Auto-saved by Hermes: this command exceeded the inline command\n"
  63. "# parser limit and was blocked from direct execution. Review it,\n"
  64. f"# then run it via: bash {path}\n" + command + ("" if command.endswith("\n") else "\n"),
  65. # Force UTF-8 + lossy decode so non-UTF-8 child output can't crash the gateway thread on
  66. # locale-mismatched Windows (#53137).
  67. # Force UTF-8 + lossy decode so non-UTF-8 child output can't crash the gateway thread on
  68. # locale-mismatched Windows (#53137).
  69. # Force UTF-8 + lossy decode so non-UTF-8 child output can't crash the gateway thread on
  70. # locale-mismatched Windows (#53137).
  71. encoding="utf-8", errors="replace",
  72. )
  73. return str(path)
  74. except Exception:
  75. logger.debug("failed to save blocked payload", exc_info=True)
  76. return None
  77. _RECOVERY_PREFIX = (
  78. " RECOVERY: this block fires on oversized/unparseable inline "
  79. "command payloads (heredocs, giant one-liners), not on the operation itself. "
  80. )
  81. def _hardline_block_result(description: str, command: str = "") -> dict:
  82. """Build the standard block result for a hardline match."""
  83. message = (
  84. f"BLOCKED (hardline): {description}. "
  85. "This command is on the unconditional blocklist and cannot "
  86. "be executed via the agent — not even with --yolo, /yolo, "
  87. "approvals.mode=off, or cron approve mode. If you genuinely "
  88. "need to run it, run it yourself in a terminal outside the agent."
  89. )
  90. # The parser-limit block is almost always a giant inline payload, not a forbidden operation, and is typically
  91. # followed by blind rephrase retries — point at the saved script (or the write_file recipe).
  92. if description in (_PARSER_LIMIT_DESCRIPTION, _MALFORMED_EXEC_DESCRIPTION):
  93. saved = _save_blocked_payload(command) if command else None
  94. if saved:
  95. message += _RECOVERY_PREFIX + (
  96. f"Your command was saved to {saved} — review it, then run: terminal(command=\"bash {saved}\"). "
  97. "Do not retry inline."
  98. )
  99. else:
  100. message += _RECOVERY_PREFIX + (
  101. "Write the script to a file with write_file, "
  102. "then run it: terminal(command=\"bash /path/script.sh\") or "
  103. "\"python3 /path/script.py\". Do not retry inline."
  104. )
  105. return {"approved": False, "hardline": True, "message": message}
  106. def _sudo_stdin_block_result(description: str) -> dict:
  107. """Build the standard block result for sudo stdin guard."""
  108. return {"approved": False, "message": (
  109. f"BLOCKED: {description}. "
  110. "Do not pipe passwords to 'sudo -S' — this is a brute-force "
  111. "attack vector. Set SUDO_PASSWORD in your .env file if the "
  112. "agent needs passwordless sudo, or run the sudo command manually in your own terminal.")}
  113. # Shell control characters that make a command compound when they appear OUTSIDE quotes. Inside quotes they are
  114. # literal to the outer shell — but they become executable again if an option like `-c`/`-e`/`--eval` (or a git `-c
  115. # alias.x=!...`) hands the quoted argument to another interpreter, so quoted control chars only disqualify a command
  116. # when such an option is present.
  117. # Port of can1357/oh-my-pi#7553.
  118. _SHELL_CONTROL_CHARS = frozenset("\n\r;&|<>`$()")
  119. _REINTERPRETED_ARGUMENT_RE = re.compile(r"(?:^|[ \t])(?:-[^-\s]*[ce]|--(?:command|eval))(?:[= \t]|$)")
  120. def _has_allowlist_shell_operator(command: str) -> bool:
  121. """Return True when a command is too compound for the allowlist shortcut.
  122. Quote-aware: metacharacters inside quotes or behind a backslash are literal
  123. arguments (``cargo bench -- '^a(b|c)$'``), not shell syntax. Still
  124. disqualifying: ``$`` or backtick inside DOUBLE quotes (expansion stays
  125. active), and any quoted/escaped control character when the command also
  126. carries a ``-c``/``-e``/``--command``/``--eval``-style option that would
  127. hand the quoted text to another interpreter."""
  128. command = command or ""
  129. quote = None # None | "'" | '"'
  130. has_reinterpretable = False
  131. i = 0
  132. n = len(command)
  133. while i < n:
  134. ch = command[i]
  135. if ch == "\\" and quote != "'":
  136. nxt = command[i + 1] if i + 1 < n else ""
  137. if nxt in _SHELL_CONTROL_CHARS:
  138. has_reinterpretable = True
  139. i += 2
  140. continue
  141. if quote is not None:
  142. if ch == quote:
  143. quote = None
  144. elif quote == '"' and ch in ("`", "$"):
  145. return True # expansion is active inside double quotes
  146. elif ch in _SHELL_CONTROL_CHARS:
  147. has_reinterpretable = True
  148. elif ch in ("'", '"'):
  149. quote = ch
  150. elif ch == "$":
  151. # Unquoted $ is only compound when it opens a substitution ("$HOME"
  152. # stays simple, matching the historical `\$\(` behavior).
  153. if i + 1 < n and command[i + 1] == "(":
  154. return True
  155. elif ch in _SHELL_CONTROL_CHARS and ch not in "()":
  156. return True
  157. i += 1
  158. # An unterminated quote means we can't reason about the command shape.
  159. if quote is not None:
  160. return True
  161. return has_reinterpretable and bool(_REINTERPRETED_ARGUMENT_RE.search(command))
  162. def _matching_permanent_allowlist_entry(command: str) -> str | None:
  163. """The command_allowlist entry matching this exact command text or as a glob, or None.
  164. Permanent approvals historically store dangerous-pattern keys such as
  165. ``recursive delete``; manual entries are command text, possibly with
  166. shell-style wildcards like ``podman *``."""
  167. from tools import approval as _a
  168. command = (command or "").strip()
  169. if not command or _has_allowlist_shell_operator(command):
  170. return None
  171. with _a._lock:
  172. patterns = tuple(_a._permanent_set())
  173. for pattern in patterns:
  174. pattern = pattern.strip() if isinstance(pattern, str) else ""
  175. if pattern and (command == pattern or (any(ch in pattern for ch in "*?[")
  176. and fnmatch.fnmatchcase(command, pattern))):
  177. return pattern
  178. return None
  179. def _command_matches_permanent_allowlist(command: str) -> bool:
  180. """True when command_allowlist holds this exact command text or a matching glob."""
  181. return _matching_permanent_allowlist_entry(command) is not None