mcp_security.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. """Security checks for user-configured MCP server entries.
  2. Blocks three narrow shapes (see ``validate_mcp_server_entry``), including a hardcoded IOC blocklist
  3. for the June 2026 hermes-0day campaign. Runs BOTH at save time (``_save_mcp_server`` — dashboard API +
  4. CLI) and at spawn time (``tools.mcp_tool._filter_suspicious_mcp_servers``), so a hand-edited or
  5. pre-planted ``config.yaml`` entry is caught before it can execute.
  6. """
  7. from __future__ import annotations
  8. import os
  9. import re
  10. import shlex
  11. from typing import Any
  12. _SHELL_INTERPRETERS = frozenset({
  13. "bash", "sh", "zsh", "dash", "fish", "cmd", "cmd.exe", "powershell", "powershell.exe", "pwsh", "pwsh.exe",
  14. })
  15. _EGRESS_PATTERN = re.compile(
  16. r"(?<![\w.-])(?:curl|wget|nc|ncat|socat)(?![\w.-])"
  17. r"|/dev/tcp/"
  18. r"|\bInvoke-WebRequest\b"
  19. r"|\bInvoke-RestMethod\b"
  20. r"|\bSystem\.Net\.WebClient\b",
  21. re.IGNORECASE,
  22. )
  23. _EXFIL_HINT_PATTERN = re.compile(
  24. r"\.env\b|--data-binary|--data-raw|\b-X\s+POST\b|\bPOST\b|<\s*[^\s]+",
  25. re.IGNORECASE,
  26. )
  27. # OS persistence surfaces an MCP server has no legitimate reason to write to (the hermes-0day
  28. # SSH-key/PAM/sudoers/cron shape). Matched anywhere in the inline script.
  29. _PERSISTENCE_PATTERN = re.compile(
  30. r"authorized_keys" # SSH key persistence (the campaign's payload)
  31. r"|\.ssh/" # any write under ~/.ssh
  32. r"|/etc/ssh\b" # sshd_config / AuthorizedKeysCommand backdoor
  33. r"|/etc/pam\.d\b|pam_[\w-]+\.so" # PAM credential logger
  34. r"|/etc/sudoers" # sudoers escalation
  35. r"|/etc/cron|crontab\b" # cron persistence
  36. r"|/etc/rc\.local|/etc/systemd" # init / unit persistence
  37. r"|\.bashrc\b|\.bash_profile\b|\.profile\b|\.zshrc\b", # shell rc backdoor
  38. re.IGNORECASE,
  39. )
  40. # Indicators of compromise, June 2026 hermes-0day campaign: exact attacker artifacts observed on
  41. # multiple compromised public instances. Hardcoded so a pre-planted config.yaml is refused.
  42. _IOC_SUBSTRINGS = (
  43. "AAAAC3NzaC1lZDI1NTE5AAAAICBoh1oDC4DnsO1m5mJ4yfEKrQebaFh", # attacker SSH public key
  44. "hermes-0day",
  45. # Attacker source IPs seen authenticating with the key.
  46. "60.165.167.",
  47. "118.182.244.156",
  48. "61.178.123.196",
  49. )
  50. def _command_basename(command: Any) -> str:
  51. text = str(command or "").strip()
  52. if not text:
  53. return ""
  54. try:
  55. parts = shlex.split(text, posix=(os.name != "nt"))
  56. except ValueError:
  57. parts = text.split()
  58. first = parts[0] if parts else text
  59. return os.path.basename(first).lower()
  60. def _inline_script(args: Any) -> str:
  61. if args is None:
  62. return ""
  63. if isinstance(args, (list, tuple)):
  64. return " ".join(str(item) for item in args)
  65. return str(args)
  66. def _entry_text(entry: dict[str, Any]) -> str:
  67. """Flatten command + args + env values into one string for IOC scanning."""
  68. parts: list[str] = [str(entry.get("command") or "")]
  69. parts.append(_inline_script(entry.get("args")))
  70. env = entry.get("env")
  71. if isinstance(env, dict):
  72. parts.extend(str(v) for v in env.values())
  73. return " ".join(parts)
  74. def validate_mcp_server_entry(name: str, entry: dict[str, Any]) -> list[str]:
  75. """Return security warnings for an MCP server entry (empty = not suspicious).
  76. Intentionally not a whitelist — custom commands, Python scripts, npx, uvx stay legal. Only three
  77. narrow shapes are blocked: (1) a known IOC anywhere in command/args/env, (2) a shell interpreter
  78. with network egress in its inline script, (3) a shell interpreter writing an OS persistence surface.
  79. * a shell interpreter whose inline script writes to an OS persistence surface (June 2026 hermes-0day
  80. SSH/PAM/sudoers/cron shape). See #45620.
  81. """
  82. if not isinstance(entry, dict):
  83. return []
  84. issues: list[str] = []
  85. flat = _entry_text(entry)
  86. for ioc in _IOC_SUBSTRINGS:
  87. if ioc in flat:
  88. # One IOC is enough to refuse; don't leak the full match list.
  89. issues.append(
  90. f"MCP server '{name}' contains a known hermes-0day "
  91. f"indicator-of-compromise ('{ioc}')"
  92. )
  93. return issues
  94. command = entry.get("command")
  95. if _command_basename(command) not in _SHELL_INTERPRETERS:
  96. return issues
  97. script = _inline_script(entry.get("args"))
  98. if not script:
  99. return issues
  100. if _EGRESS_PATTERN.search(script):
  101. issue = (
  102. f"MCP server '{name}' uses shell interpreter '{command}' with "
  103. f"network egress in args"
  104. )
  105. if _EXFIL_HINT_PATTERN.search(script):
  106. issue += " and exfiltration-shaped arguments"
  107. issues.append(issue)
  108. if _PERSISTENCE_PATTERN.search(script):
  109. issues.append(
  110. f"MCP server '{name}' uses shell interpreter '{command}' to write "
  111. f"to an OS persistence surface (SSH keys / PAM / sudoers / cron / "
  112. f"shell rc) — this is the hermes-0day backdoor shape, not a real "
  113. f"MCP server"
  114. )
  115. return issues