security_audit_startup.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. """Startup security posture audit (warn-on-load, never blocks).
  2. Surfaces dangerous host / deployment posture at process start. Checks are advisory and
  3. independently fail-safe: they return human-readable strings, any internal error yields no finding,
  4. and nothing here ever raises or blocks startup.
  5. """
  6. from __future__ import annotations
  7. import logging
  8. import os
  9. import re
  10. from pathlib import Path
  11. from typing import Optional
  12. logger = logging.getLogger("hermes.security_audit")
  13. # The audit runs once per process even if both the CLI and gateway startup paths call it.
  14. _AUDIT_RAN = False
  15. def _is_root() -> bool:
  16. """True when the process runs as POSIX uid 0. Always False on Windows."""
  17. getuid = getattr(os, "geteuid", None) or getattr(os, "getuid", None)
  18. try:
  19. return getuid is not None and getuid() == 0
  20. except Exception:
  21. return False
  22. def _running_as_root() -> Optional[str]:
  23. return None if not _is_root() else (
  24. "Running as ROOT. The agent's terminal/file tools execute with full root privileges — a single "
  25. "prompt-injection or exposed endpoint is a full host compromise. Run Hermes as an unprivileged user "
  26. "(or in a sandboxed terminal backend / container with a non-root user).")
  27. def _iter_sshd_config_lines() -> list[str]:
  28. """Non-comment lines from sshd_config + its drop-in directory."""
  29. lines: list[str] = []
  30. paths: list[Path] = [Path("/etc/ssh/sshd_config")]
  31. try:
  32. paths.extend(sorted(Path("/etc/ssh/sshd_config.d").glob("*.conf")))
  33. except Exception:
  34. pass
  35. for p in paths:
  36. try:
  37. raw_lines = p.read_text(encoding="utf-8-sig", errors="replace").splitlines()
  38. except Exception:
  39. continue
  40. lines.extend(s for s in map(str.strip, raw_lines) if s and not s.startswith("#"))
  41. return lines
  42. def _ssh_password_auth_enabled() -> Optional[str]:
  43. """Warn when sshd has password auth enabled — the classic brute-force surface, which pairs
  44. badly with a root-capable agent box. None when there is no sshd config to read.
  45. """
  46. lines = _iter_sshd_config_lines()
  47. if not lines:
  48. return None
  49. # Last directive wins in sshd_config. Default (no directive) is "yes".
  50. directives = [m.group(1).lower() for m in map(re.compile(r"(?i)^PasswordAuthentication\s+(\w+)").match, lines) if m]
  51. if directives and directives[-1] == "no":
  52. return None
  53. qualifier = "" if directives else " (default — no explicit directive)"
  54. return (f"SSH password authentication is ENABLED{qualifier}. Password auth is brute-forceable and dangerous "
  55. "on an internet-facing box. Set 'PasswordAuthentication no' in sshd_config and use key-based auth.")
  56. def _in_container() -> bool:
  57. """Best-effort container detection (Docker / Podman / generic OCI)."""
  58. if os.path.exists("/.dockerenv"):
  59. return True
  60. if os.environ.get("HERMES_DESKTOP_CHILD_PID"):
  61. return False # desktop child, not a server container
  62. try:
  63. cgroup = Path("/proc/1/cgroup").read_text(encoding="utf-8", errors="replace")
  64. except Exception:
  65. return False
  66. return any(tok in cgroup for tok in ("docker", "containerd", "kubepods", "libpod"))
  67. def _path_is_mounted(path: Path) -> bool:
  68. """True if *path* sits on a persistent mount per /proc/mounts, i.e. the most specific
  69. mountpoint at or above it is NOT the ephemeral container root overlay/tmpfs.
  70. """
  71. try:
  72. target = path.resolve()
  73. except Exception:
  74. target = path
  75. try:
  76. mounts = Path("/proc/mounts").read_text(encoding="utf-8", errors="replace").splitlines()
  77. except Exception:
  78. return True # can't tell — fail safe (no warning)
  79. # (mountpoint, fstype) entries at or above target; the longest wins, first one on ties.
  80. covering = [
  81. (Path(parts[1]), parts[2])
  82. for parts in (line.split() for line in mounts)
  83. if len(parts) >= 3 and (Path(parts[1]) == target or Path(parts[1]) in target.parents)
  84. ]
  85. if not covering:
  86. return True
  87. best_fstype = max(covering, key=lambda entry: len(str(entry[0])))[1]
  88. return best_fstype not in ("overlay", "tmpfs", "aufs")
  89. def _container_no_volume_mount(hermes_home: Optional[Path]) -> Optional[str]:
  90. if not _in_container():
  91. return None
  92. if hermes_home is None:
  93. from hermes_constants import get_hermes_home
  94. hermes_home = get_hermes_home()
  95. if _path_is_mounted(hermes_home): # any error propagates to run_security_audit (= no finding)
  96. return None
  97. return (f"Running in a container but the data dir ({hermes_home}) is NOT on a persistent volume mount — "
  98. "sessions, memory, skills, and API keys are ephemeral and lost on container restart. Mount a host "
  99. "volume over the HERMES_HOME data directory.")
  100. def _network_listener_without_auth(config: Optional[dict]) -> list[str]:
  101. """Warn about a network-accessible API server with no API_SERVER_KEY. Read-only against
  102. config + env; overlaps the hard fail-closed guards but surfaces the posture at startup.
  103. """
  104. # Any error (incl. an unimportable gateway package) propagates to run_security_audit.
  105. from gateway.platforms.base import is_network_accessible
  106. plats = (config or {}).get("platforms") or {}
  107. api = plats.get("api_server") if isinstance(plats, dict) else None
  108. if not (isinstance(api, dict) and api.get("enabled")):
  109. return []
  110. extra = api.get("extra") or {}
  111. host = extra.get("host") or os.environ.get("API_SERVER_HOST", "127.0.0.1")
  112. key = extra.get("key") or os.environ.get("API_SERVER_KEY", "")
  113. if not is_network_accessible(str(host)) or str(key).strip():
  114. return []
  115. return [f"OpenAI-compatible API server is network-accessible ({host}) with NO API_SERVER_KEY. It dispatches "
  116. "terminal-capable agent work — an unauthenticated network endpoint is remote code execution. "
  117. "Set a strong API_SERVER_KEY."]
  118. def run_security_audit(*, hermes_home: Optional[Path] = None, config: Optional[dict] = None) -> list[str]:
  119. """Run all checks and return human-readable warning strings. Pure (no logging); a check that
  120. raises simply contributes no finding.
  121. """
  122. findings: list[str] = []
  123. for check in (_running_as_root, _ssh_password_auth_enabled, lambda: _container_no_volume_mount(hermes_home),
  124. lambda: _network_listener_without_auth(config)):
  125. try:
  126. r = check()
  127. except Exception:
  128. continue
  129. if isinstance(r, list):
  130. findings.extend(r)
  131. elif r:
  132. findings.append(r)
  133. return findings
  134. def log_startup_security_warnings(
  135. *, hermes_home: Optional[Path] = None, config: Optional[dict] = None, force: bool = False
  136. ) -> list[str]:
  137. """Run the audit once per process (``force=True`` re-runs) and log each finding as a warning."""
  138. global _AUDIT_RAN
  139. if _AUDIT_RAN and not force:
  140. return []
  141. _AUDIT_RAN = True
  142. findings = run_security_audit(hermes_home=hermes_home, config=config)
  143. if findings:
  144. logger.warning("Security posture audit found %d issue(s) — review your deployment:", len(findings))
  145. for i, f in enumerate(findings, 1):
  146. logger.warning(" [security %d/%d] %s", i, len(findings), f)
  147. return findings