ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.
Python active-directorycloud-securitydefensive-validationfastapigood-first-issuemitre-attackopsecreactred-teamreportingsecurity
"""
ARES MCP Event Bus.
Provides sub-millisecond, non-blocking UDP loopback event telemetry
between the MCP stdio/SSE server and local TUI terminal monitors.
"""
from __future__ import annotations
import json
import socket
import time
from pathlib import Path
from typing import Any
DEFAULT_EVENT_PORT = 27890
DEFAULT_EVENT_HOST = "127.0.0.1"
TOKEN_STATUS_FILE = Path.home() / ".ares" / "mcp_token_status.json"
_MAX_TOKEN_DECISIONS = 256
class McpEventBus:
"""Non-blocking event emitter for MCP server telemetry."""
@staticmethod
def emit(event_type: str, data: dict[str, Any]) -> None:
"""Emit telemetry event to local monitor over UDP loopback."""
payload = {
"timestamp": time.strftime("%H:%M:%S"),
"type": event_type,
"data": data,
}
try:
raw = json.dumps(payload).encode("utf-8")
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(raw, (DEFAULT_EVENT_HOST, DEFAULT_EVENT_PORT))
sock.close()
except Exception:
pass # Silent drop if no listener or network exception
@staticmethod
def _load_decisions() -> dict[str, Any]:
"""Return the per-token decision map, tolerating the legacy single-slot
format and any read/parse error (returns {})."""
if not TOKEN_STATUS_FILE.exists():
return {}
try:
with open(TOKEN_STATUS_FILE, encoding="utf-8") as f:
loaded = json.load(f)
except Exception:
return {}
if isinstance(loaded, dict) and isinstance(loaded.get("decisions"), dict):
return dict(loaded["decisions"])
# Legacy single-slot record: {"token": ..., "decision": ...}
if isinstance(loaded, dict) and "token" in loaded:
return {str(loaded["token"]): {"decision": loaded.get("decision")}}
return {}
@staticmethod
def set_token_decision(token: str, decision: str) -> None:
"""Record operator decision (APPROVED or REJECTED) for a specific token.
Decisions are keyed per token so a decision for one token is never
clobbered by a newer pending token (the previous single-slot file held
only the most recently touched token). (AUDIT run-1 H8)
"""
TOKEN_STATUS_FILE.parent.mkdir(parents=True, exist_ok=True)
decisions = McpEventBus._load_decisions()
decisions[token] = {
"decision": decision,
"timestamp": time.strftime("%H:%M:%S"),
}
# Bound the file size; keep the most recent entries (dicts preserve
# insertion order, and re-setting a token refreshes its position).
if len(decisions) > _MAX_TOKEN_DECISIONS:
decisions = dict(list(decisions.items())[-_MAX_TOKEN_DECISIONS:])
try:
with open(TOKEN_STATUS_FILE, "w", encoding="utf-8") as f:
json.dump({"decisions": decisions}, f, indent=2)
except Exception:
pass
@staticmethod
def get_token_decision(token: str) -> str | None:
"""Read the operator decision for a token, or None if there is none.
None (no decision recorded) is the fail-closed default: callers must
treat anything other than an explicit "APPROVED" as not-approved.
"""
record = McpEventBus._load_decisions().get(token)
if isinstance(record, dict):
return record.get("decision")
return None
class McpEventListener:
"""Non-blocking UDP receiver for terminal monitor."""
def __init__(self, host: str = DEFAULT_EVENT_HOST, port: int = DEFAULT_EVENT_PORT) -> None:
self.host = host
self.port = port
self.sock: socket.socket | None = None
self._bind()
def _bind(self) -> None:
try:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind((self.host, self.port))
self.sock.setblocking(False)
except Exception:
self.sock = None
def poll_events(self) -> list[dict[str, Any]]:
"""Poll incoming UDP events without blocking."""
events: list[dict[str, Any]] = []
if not self.sock:
return events
while True:
try:
data, _ = self.sock.recvfrom(65535)
event = json.loads(data.decode("utf-8"))
events.append(event)
except (OSError, BlockingIOError):
break
except Exception:
break
return events
def close(self) -> None:
if self.sock:
try:
self.sock.close()
except Exception:
pass
self.sock = None