security_advisories.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. """Security advisory checker for Hermes Agent.
  2. Cheap (one ``importlib.metadata.version()`` call per advisory package, safe on every CLI startup)
  3. and silent unless a compromised package is actually installed.
  4. """
  5. from __future__ import annotations
  6. import logging
  7. import os
  8. import sys
  9. from dataclasses import dataclass
  10. from pathlib import Path
  11. from typing import Iterable, Optional
  12. from hermes_constants import display_hermes_home
  13. logger = logging.getLogger(__name__)
  14. # Advisory catalog. To add one: append an ``Advisory`` to ``ADVISORIES`` with ``compromised`` as
  15. # ``(pkg_name, frozenset_of_versions)`` pairs (versions exactly as ``importlib.metadata.version()``
  16. # returns them; an empty frozenset flags ANY installed version — rare, namespace compromise only)
  17. # and 2-4 copy/pasteable ``remediation`` lines. Never remove old advisories: users on an older
  18. # release with the compromised package must still get warned.
  19. @dataclass(frozen=True)
  20. class Advisory:
  21. """``id`` is lowercase-hyphen, stable and never reused (it is what acks key on). ``remediation``
  22. is ordered: uninstall command first, then credential audit/rotation guidance. Steps may use
  23. ``{hermes_home}``; ``full_remediation_text`` fills it with ``display_hermes_home()`` at render
  24. time so a profile / HERMES_HOME user is sent to their own .env.
  25. """
  26. id: str
  27. title: str
  28. summary: str
  29. url: str
  30. compromised: tuple[tuple[str, frozenset[str]], ...]
  31. remediation: tuple[str, ...]
  32. published: str = ""
  33. severity: str = "high" # low / medium / high / critical
  34. ADVISORIES: tuple[Advisory, ...] = (
  35. Advisory(
  36. id="shai-hulud-2026-05",
  37. title="Mini Shai-Hulud worm — mistralai 2.4.6 compromised on PyPI",
  38. summary=(
  39. "PyPI quarantined the mistralai package on 2026-05-12 after a "
  40. "malicious 2.4.6 release. The worm steals credentials from "
  41. "environment variables and credential files (~/.npmrc, ~/.pypirc, "
  42. "~/.aws/credentials, GitHub PATs, cloud SDK tokens) and exfils "
  43. "them to a hardcoded webhook. If you ran any Python process that "
  44. "imported mistralai 2.4.6 — including hermes when configured "
  45. "with provider=mistral for TTS or STT — assume those credentials "
  46. "are exposed. PyPI has since removed 2.4.6 and the project ships "
  47. "clean releases again (2.4.7, 2.4.8); this advisory only fires if "
  48. "the compromised 2.4.6 is still installed."
  49. ),
  50. url="https://socket.dev/blog/mini-shai-hulud-worm-pypi",
  51. compromised=(("mistralai", frozenset({"2.4.6"})),),
  52. remediation=(
  53. "Run: pip uninstall -y mistralai (or: uv pip uninstall mistralai)",
  54. "Rotate API keys in {hermes_home}/.env (OpenRouter, Anthropic, OpenAI, "
  55. "Nous, GitHub, AWS, Google, Mistral, etc.).",
  56. "Audit ~/.npmrc, ~/.pypirc, ~/.aws/credentials, ~/.config/gh/hosts.yml, "
  57. "and any other credential files for tokens that may have been read.",
  58. "Check GitHub for unexpected new SSH keys, deploy keys, or webhook "
  59. "additions on repos you have admin on.",
  60. "After cleanup: hermes doctor --ack shai-hulud-2026-05 to dismiss "
  61. "this warning.",
  62. ),
  63. published="2026-05-12",
  64. severity="critical",
  65. ),
  66. )
  67. @dataclass(frozen=True)
  68. class AdvisoryHit:
  69. """One package-version match against an advisory."""
  70. advisory: Advisory
  71. package: str
  72. installed_version: str
  73. def _installed_version(pkg_name: str) -> Optional[str]:
  74. """Installed version of ``pkg_name`` via ``importlib.metadata`` (uv venvs may lack pip), or
  75. None if not installed or metadata is corrupt — never crash the CLI startup path.
  76. """
  77. from importlib.metadata import PackageNotFoundError, version
  78. try:
  79. return version(pkg_name)
  80. except PackageNotFoundError:
  81. return None
  82. except Exception:
  83. logger.debug("importlib.metadata.version(%s) raised", pkg_name, exc_info=True)
  84. return None
  85. def detect_compromised(advisories: Iterable[Advisory] = ADVISORIES) -> list[AdvisoryHit]:
  86. """All hits: package installed AND version in the compromised set (or the set is empty)."""
  87. return [
  88. AdvisoryHit(advisory, pkg_name, installed)
  89. for advisory in advisories
  90. for pkg_name, bad_versions in advisory.compromised
  91. if (installed := _installed_version(pkg_name)) is not None and (not bad_versions or installed in bad_versions)
  92. ]
  93. # ─── Acknowledgement persistence ──────────────────────────────────────────────
  94. # Acks live under ``security.acked_advisories`` in config.yaml as a list of advisory IDs — the only
  95. # state (no per-host data or timestamps), so a shared config.yaml dismisses everywhere.
  96. def get_acked_ids() -> set[str]:
  97. """Advisory IDs the user has dismissed; empty when config can't be loaded (never block startup —
  98. the advisory keeps firing until config is repaired).
  99. """
  100. try:
  101. from hermes_cli.config import load_config
  102. raw = (load_config().get("security") or {}).get("acked_advisories") or []
  103. except Exception:
  104. logger.debug("Could not load config for advisory acks", exc_info=True)
  105. return set()
  106. return {str(x).strip() for x in raw if str(x).strip()} if isinstance(raw, list) else set()
  107. def ack_advisory(advisory_id: str) -> bool:
  108. """Persist an ack for ``advisory_id``. Returns True on success."""
  109. advisory_id = advisory_id.strip()
  110. if not advisory_id:
  111. return False
  112. try:
  113. from hermes_cli.config import load_config, save_config
  114. except Exception:
  115. logger.warning("Could not import config module to persist ack")
  116. return False
  117. try:
  118. cfg = load_config()
  119. sec = cfg.setdefault("security", {})
  120. existing = sec.get("acked_advisories") or []
  121. if not isinstance(existing, list):
  122. existing = []
  123. if advisory_id not in existing:
  124. sec["acked_advisories"] = existing + [advisory_id]
  125. save_config(cfg)
  126. return True
  127. except Exception:
  128. logger.exception("Failed to persist advisory ack for %s", advisory_id)
  129. return False
  130. def filter_unacked(hits: list[AdvisoryHit]) -> list[AdvisoryHit]:
  131. """Only hits whose advisories the user has not dismissed."""
  132. acked = get_acked_ids() if hits else set()
  133. return [h for h in hits if h.advisory.id not in acked]
  134. def _term_supports_color() -> bool:
  135. return not os.environ.get("NO_COLOR") and sys.stdout.isatty()
  136. def short_banner_lines(hits: list[AdvisoryHit]) -> list[str]:
  137. """1-3 short unstyled lines for a startup banner; always names the worst hit explicitly."""
  138. if not hits:
  139. return []
  140. primary = hits[0]
  141. lines = [
  142. f"SECURITY ADVISORY [{primary.advisory.id}]: {primary.advisory.title}",
  143. f" Detected: {primary.package}=={primary.installed_version}",
  144. " Run 'hermes doctor' for remediation steps.",
  145. ]
  146. if len(hits) > 1:
  147. lines.insert(1, f" ({len(hits) - 1} additional advisor{'ies' if len(hits) > 2 else 'y'} also active.)")
  148. return lines
  149. def full_remediation_text(hit: AdvisoryHit) -> list[str]:
  150. """Multi-line block describing the advisory + remediation."""
  151. a = hit.advisory
  152. return [
  153. f"=== {a.title} ===",
  154. f"ID: {a.id} Severity: {a.severity} Published: {a.published}",
  155. f"Detected: {hit.package}=={hit.installed_version}",
  156. f"Reference: {a.url}",
  157. "",
  158. a.summary,
  159. "",
  160. "Remediation:",
  161. *(f" {i}. {step.format(hermes_home=display_hermes_home())}" for i, step in enumerate(a.remediation, 1)),
  162. ]
  163. # ─── Startup-banner gating ────────────────────────────────────────────────────
  164. # Once the banner is seen we cache that in ``~/.hermes/cache/advisory_banner_seen`` (one
  165. # ``<id> <timestamp>`` line per advisory). Acked advisories never re-banner; cached-but-not-acked
  166. # ones re-banner after 24h so the user doesn't fully forget.
  167. _BANNER_CACHE_FILE = "advisory_banner_seen"
  168. _BANNER_REPEAT_HOURS = 24
  169. def _banner_cache_path() -> Optional[Path]:
  170. try:
  171. from hermes_constants import get_hermes_home
  172. cache_dir = Path(get_hermes_home()) / "cache"
  173. cache_dir.mkdir(parents=True, exist_ok=True)
  174. return cache_dir / _BANNER_CACHE_FILE
  175. except Exception:
  176. return None
  177. def _read_banner_cache() -> dict[str, float]:
  178. p = _banner_cache_path()
  179. try:
  180. lines = p.read_text(encoding="utf-8-sig").splitlines() if p is not None and p.exists() else []
  181. except Exception:
  182. return {}
  183. out: dict[str, float] = {}
  184. for parts in (line.split(None, 1) for line in lines):
  185. try:
  186. if len(parts) == 2:
  187. out[parts[0]] = float(parts[1])
  188. except ValueError:
  189. continue
  190. return out
  191. def _write_banner_cache(seen: dict[str, float]) -> None:
  192. try:
  193. if (p := _banner_cache_path()) is not None:
  194. p.write_text("\n".join(f"{aid} {ts}" for aid, ts in seen.items()) + "\n", encoding="utf-8")
  195. except Exception:
  196. logger.debug("Could not write advisory banner cache", exc_info=True)
  197. def hits_due_for_banner(hits: list[AdvisoryHit], *, repeat_hours: int = _BANNER_REPEAT_HOURS) -> list[AdvisoryHit]:
  198. """Hits whose banner is due (not acked, not recently shown). Side effect: stamps the banner
  199. cache for every returned hit, so callers must render the result.
  200. """
  201. import time
  202. fresh = filter_unacked(hits)
  203. if not fresh:
  204. return []
  205. now = time.time()
  206. cache = _read_banner_cache()
  207. cutoff = now - (repeat_hours * 3600)
  208. due = [hit for hit in fresh if cache.get(hit.advisory.id, 0.0) < cutoff]
  209. for hit in due:
  210. cache[hit.advisory.id] = now
  211. if due:
  212. _write_banner_cache(cache)
  213. return due
  214. def startup_banner(hits: list[AdvisoryHit]) -> Optional[str]:
  215. """Printable startup banner, or None if nothing is due (updates the banner cache)."""
  216. due = hits_due_for_banner(hits)
  217. if not due:
  218. return None
  219. text = "\n".join(short_banner_lines(due))
  220. return f"\x1b[1;31m{text}\x1b[0m" if _term_supports_color() else text
  221. def gateway_log_message(hits: list[AdvisoryHit]) -> Optional[str]:
  222. """One-line log message for gateway operators, or None."""
  223. fresh = filter_unacked(hits)
  224. if not fresh:
  225. return None
  226. if len(fresh) == 1:
  227. h = fresh[0]
  228. return (f"Security advisory [{h.advisory.id}] active: {h.package}=={h.installed_version} "
  229. f"matches {h.advisory.title}. See {h.advisory.url}")
  230. return (f"{len(fresh)} security advisories active (IDs: {', '.join(h.advisory.id for h in fresh)}). "
  231. "Run `hermes doctor` on the gateway host for details.")