forked from NousResearch/hermes-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
fix(gateway,cron): guard cron model-tool path + auto-resume loop breaker (#30719) #247
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,141 @@ | ||
| """Gateway lifecycle guard for cron job creation (#30719). | ||
|
|
||
| An agent running inside a gateway can schedule a cron job that calls | ||
| ``hermes gateway restart`` (or ``launchctl kickstart ai.hermes.gateway`` | ||
| or ``systemctl restart hermes-gateway``). When the cron fires, the | ||
| gateway dies, the supervisor (launchd KeepAlive / systemd Restart=) | ||
| revives it, auto-resume picks up the offending session, and the resumed | ||
| turn re-runs the same logic — a SIGTERM-respawn loop every ~10 seconds | ||
| until manually broken. | ||
|
|
||
| This module rejects cron job specs whose prompt or script contains a | ||
| direct shell-level gateway-lifecycle command. It is enforced at | ||
| ``cron.jobs.create_job`` so it fires on every job-creation path: the | ||
| ``hermes cron create`` CLI subcommand AND the agent's ``cronjob`` model | ||
| tool (which calls ``create_job`` directly, bypassing the CLI layer). | ||
|
|
||
| The pattern is intentionally command-shaped: it anchors on a concrete | ||
| command identifier (``hermes gateway``, ``launchctl ... hermes-gateway``, | ||
| ``systemctl ... hermes-gateway``, ``pkill`` against the gateway) so it | ||
| cannot fire on prose. A cron ``prompt`` is fed to a future LLM, not a | ||
| shell, so an over-broad substring match on English ("Kong API gateway | ||
| autoscaling and restart behavior") would produce a high false-positive | ||
| rate without preventing the actual foot-gun, which requires a real | ||
| command shape. | ||
|
|
||
| This is a defence-in-depth layer. ``tools/terminal_tool.py`` already | ||
| blocks these commands at *execution* time when ``_HERMES_GATEWAY=1``, and | ||
| ``hermes gateway stop|restart`` refuse to self-target from inside the | ||
| gateway. Blocking at *creation* time as well means the agent gets an | ||
| immediate, informative rejection instead of scheduling a job that will | ||
| only fail (silently) when it fires. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import re | ||
| from pathlib import Path | ||
| from typing import Optional | ||
|
|
||
|
|
||
| class GatewayLifecycleBlocked(ValueError): | ||
| """Raised when a cron job spec contains a gateway-lifecycle command.""" | ||
|
|
||
|
|
||
| # Shell-level command shapes that target the gateway lifecycle. Each branch | ||
| # is anchored on a concrete command identifier so a match can only fire on | ||
| # actual shell-command-shaped strings, not on prose. | ||
| _GATEWAY_LIFECYCLE_PATTERN = re.compile( | ||
| r"(?i)" | ||
| # Branch A: `hermes gateway restart|stop` — the canonical foot-gun. | ||
| # `start` is intentionally excluded: starting a gateway from inside a | ||
| # gateway is benign (a no-op or "already running" error), and a | ||
| # legitimate cron job might start a sibling profile's gateway. | ||
| r"(?:hermes\s+gateway\s+(?:restart|stop))" | ||
| # Branch B: launchctl ops on a hermes-gateway label. macOS launchd | ||
| # labels look like `ai.hermes.gateway` / `hermes-gateway`. Requiring the | ||
| # gateway identifier prevents blocking unrelated hermes services (e.g. | ||
| # `launchctl unload ai.hermes.update-checker.plist`). | ||
| r"|(?:launchctl\s+(?:kickstart|unload|load|stop|restart)\b[^\n]*\bhermes[.\-]?gateway)" | ||
| # Branch C: systemctl ops on a hermes-gateway unit. | ||
| r"|(?:systemctl\s+(?:-\S+\s+)*(?:restart|stop|start)\b[^\n]*\bhermes[.\-]?gateway)" | ||
| # Branch D: pkill / kill targeting the hermes gateway process. Both | ||
| # token orders because real reproductions show both. | ||
| r"|(?:p?kill\b[^\n]*\bhermes\b[^\n]*\bgateway)" | ||
| r"|(?:p?kill\b[^\n]*\bgateway\b[^\n]*\bhermes)" | ||
| ) | ||
|
|
||
|
|
||
| def contains_gateway_lifecycle_command(text: str) -> bool: | ||
| """Return True if *text* contains a gateway lifecycle command pattern.""" | ||
| if not text: | ||
| return False | ||
| return bool(_GATEWAY_LIFECYCLE_PATTERN.search(text)) | ||
|
|
||
|
|
||
| def _resolve_script_path(script_path: str) -> Path: | ||
| """Resolve a cron ``script`` value the same way the scheduler does. | ||
|
|
||
| The scheduler (``cron.scheduler``) resolves a bare/relative script path | ||
| under ``<HERMES_HOME>/scripts/`` and only accepts absolute paths as-is. | ||
| We MUST mirror that here so the guard scans the file that will actually | ||
| run — otherwise a job whose script lives at the scheduler's real location | ||
| (``~/.hermes/scripts/restart.sh``) but is passed as the bare name | ||
| ``restart.sh`` would read as a nonexistent relative path and silently | ||
| scan prompt-only content, letting the command through. | ||
| """ | ||
| from hermes_constants import get_hermes_home | ||
|
|
||
| raw = Path(script_path).expanduser() | ||
| if raw.is_absolute(): | ||
| return raw | ||
| return get_hermes_home() / "scripts" / raw | ||
|
|
||
|
|
||
| def _read_script_for_scanning(script_path: str) -> str: | ||
| """Read a script file for lifecycle-pattern scanning. | ||
|
|
||
| Decodes with ``errors="replace"`` so binary or non-UTF-8 content does not | ||
| silently bypass the check — a plain text-mode read raises | ||
| ``UnicodeDecodeError`` on such files, and swallowing that error would let | ||
| an attacker hide the command in binary noise. Returns an empty string | ||
| only when the file cannot be read at all. | ||
| """ | ||
| try: | ||
| return _resolve_script_path(script_path).read_bytes().decode( | ||
| "utf-8", errors="replace" | ||
| ) | ||
| except OSError: | ||
| return "" | ||
|
|
||
|
|
||
| def check_gateway_lifecycle( | ||
| prompt: Optional[str], | ||
| script: Optional[str] = None, | ||
| ) -> None: | ||
| """Raise ``GatewayLifecycleBlocked`` if *prompt* or *script* contains a | ||
| gateway-lifecycle command pattern. | ||
|
|
||
| ``prompt`` is scanned directly. ``script``, when supplied, is read from | ||
| disk and concatenated for the scan. Both are considered together so a | ||
| job cannot slip through by splitting the command across the prompt and | ||
| the script. | ||
|
|
||
| Callers should let the exception propagate when they want the create to | ||
| fail with a ``ValueError``-shaped error (the agent's ``cronjob`` tool | ||
| surfaces this as a tool error; the CLI prints it in red and exits 1). | ||
| """ | ||
| combined = prompt or "" | ||
| if script: | ||
| script_text = _read_script_for_scanning(script) | ||
| if script_text: | ||
| combined = f"{combined}\n{script_text}" | ||
|
|
||
| if contains_gateway_lifecycle_command(combined): | ||
| raise GatewayLifecycleBlocked( | ||
| "Blocked: cron job contains a gateway lifecycle command " | ||
| "(restart/stop/kill). This is blocked to prevent agent-driven " | ||
| "SIGTERM-respawn loops under launchd/systemd supervision " | ||
| "(#30719). Run `hermes gateway restart` from a shell outside " | ||
| "the running gateway instead." | ||
| ) | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🟠 TOCTOU gap: cron lifecycle guard scans script at creation but script can be written later, bypassing the guard (security)
The gateway lifecycle guard in
cron/lifecycle_guard.pychecks script content at job creation time (called fromcron.jobs.create_job:970). When the script file does not exist,_read_script_for_scanning()catchesOSErrorand returns an empty string (line 108-109), falling back to prompt-only scanning. An agent can sequencecronjobcreation (with a non-existent script and clean prompt) followed bywrite_fileto populate the script with lifecycle commands (e.g.,systemctl restart hermes-gateway). The cron scheduler (scheduler.py:_run_job_script) runs scripts without any lifecycle content check. Forno_agent=Truecron jobs, this is the ONLY defense against script-based lifecycle attacks —terminal_tool.py's execution guard does not apply to scheduler-executed scripts. A recurring cron spaced >60s apart can sustain a SIGTERM-respawn loop that evades the restart-loop breaker's 60s default window (defense-3 ingateway/restart_loop_guard.py), since boots spaced ~66s apart never accumulate 3 within the 60s window.💡 Suggestion: Add a defense layer at script execution time in the cron scheduler. Options: (1) In
cron/scheduler.py:_run_job_script, add a pre-execution lifecycle scan using the same_GATEWAY_LIFECYCLE_PATTERNregex before running the script. (2) At creation time, if the script doesn't exist andno_agent=True, reject the job creation or flag it for deferred re-scan. (3) Havecreate_jobmark jobs with apending_lifecycle_checkflag when the script doesn't exist, and check it at execution time.📋 Prompt for AI Agents
In cron/scheduler.py, add a lifecycle content check to
_run_job_script()before executing the script. Importcontains_gateway_lifecycle_commandfromcron.lifecycle_guard, read the script content (with errors='replace' for binary safety), and if a lifecycle command is detected, abort execution and log a warning. This closes the TOCTOU gap for all script execution paths regardless of when the script was written. Example: after resolving the script path and before subprocess execution, add:if contains_gateway_lifecycle_command(path.read_bytes().decode('utf-8', errors='replace')): return (False, 'Blocked: script contains gateway lifecycle command').