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
fix(security): remove loopback auth bypass on /modules/reload (AUD-001)
Mafifrizi06abea4ffd0c
diff --git a/ares/api/server.py b/ares/api/server.pyindex db755b1..34186b5 100644--- a/ares/api/server.py+++ b/ares/api/server.py@@ -2257,33 +2257,14 @@ async def list_modules(@app.post("/modules/reload", tags=["modules"])async def reload_modules(request: Request,+ actor: AuthenticatedUser = Depends(require_operator()),engine: AresEngine = Depends(get_engine),) -> dict[str, Any]:"""Reload plugin registry in-memory from builtin and external module sources.- Security: Strictly permitted for loopback origins (127.0.0.1, ::1, testclient)- or authenticated operators with write/admin privileges.+ Security: Strictly requires operator or team_lead authorization (no IP-based bypass)."""import importlib-- client_host = request.client.host if request.client else "127.0.0.1"- is_loopback = client_host in ("127.0.0.1", "::1", "localhost", "testclient")-- if not is_loopback:- auth_hdr = request.headers.get("Authorization") or request.headers.get("X-API-Key")- if not auth_hdr:- raise HTTPException(- status_code=403,- detail="Remote module reload requires operator authorization.",- )- try:- _ = await require_operator()(request)- except Exception as exc:- raise HTTPException(- status_code=403,- detail="Insufficient permissions for module reload.",- ) from exc-import sysfor mod_name in list(sys.modules.keys()):@@ -2292,7 +2273,7 @@ async def reload_modules(importlib.invalidate_caches()count = engine.load_modules()- logger.info("engine_modules_reloaded", total_modules=count, client=client_host)+ logger.info("engine_modules_reloaded", total_modules=count, operator=actor.username)return {"status": "ok","reloaded": True,diff --git a/ares/core/updater.py b/ares/core/updater.pyindex 0b7c127..22c4b33 100644--- a/ares/core/updater.py+++ b/ares/core/updater.py@@ -1197,10 +1197,26 @@ class PlatformUpdateManager:raise SecurityViolationError(f"Reload notification target '{host}' rejected: Loopback only.")url = f"http://{host}:{port}/modules/reload"+ headers = {"Content-Type": "application/json", "User-Agent": "ARES-CLI-Updater"}+ try:+ from ares.core.config import get_settings+ from ares.core.security import create_access_token++ settings = get_settings()+ token = create_access_token(+ data={"sub": "cli-updater", "role": "operator"},+ secret_key=settings.jwt_signing_key,+ algorithm=settings.ares_jwt_algorithm,+ expires_minutes=5,+ )+ headers["Authorization"] = f"Bearer {token}"+ except Exception:+ pass+req = urllib.request.Request(url,data=b"{}",- headers={"Content-Type": "application/json", "User-Agent": "ARES-CLI-Updater"},+ headers=headers,method="POST",)try:diff --git a/tests/unit/test_modules_reload_security.py b/tests/unit/test_modules_reload_security.pynew file mode 100644index 0000000..ec47ac7--- /dev/null+++ b/tests/unit/test_modules_reload_security.py@@ -0,0 +1,70 @@+"""+Security test for AUD-001: Verification of authentication enforcement on POST /modules/reload.+Ensures zero loopback bypass and strict operator RBAC.+"""++import sys+from starlette.testclient import TestClient++from ares.api.server import app+from ares.api.rbac import AuthenticatedUser, get_current_user+++def test_modules_reload_unauthenticated_rejected_401():+ """Request tanpa token ke /modules/reload -> 401 Unauthorized."""+ with TestClient(app, base_url="http://127.0.0.1") as client:+ resp = client.post("/modules/reload")+ assert resp.status_code == 401+ assert resp.headers.get("www-authenticate") == "Bearer"+++def test_modules_reload_loopback_unauthenticated_rejected_401():+ """Request dari 127.0.0.1 / localhost tanpa token -> 401 (bukan 200)."""+ # 1. base_url 127.0.0.1+ with TestClient(app, base_url="http://127.0.0.1") as client_ip:+ resp = client_ip.post("/modules/reload")+ assert resp.status_code == 401++ # 2. base_url localhost+ with TestClient(app, base_url="http://localhost") as client_host:+ resp = client_host.post("/modules/reload")+ assert resp.status_code == 401++ # 3. With X-Forwarded-For 127.0.0.1+ with TestClient(app, base_url="http://127.0.0.1") as client_fwd:+ resp = client_fwd.post("/modules/reload", headers={"X-Forwarded-For": "127.0.0.1"})+ assert resp.status_code == 401+++def test_modules_reload_operator_authenticated_succeeds_200():+ """Request dengan token valid operator -> 200 OK."""+ saved_modules = dict(sys.modules)+ try:+ app.dependency_overrides[get_current_user] = lambda: AuthenticatedUser(+ username="ops_lead", role="operator"+ )+ with TestClient(app, base_url="http://127.0.0.1") as client:+ resp = client.post("/modules/reload")+ assert resp.status_code == 200+ data = resp.json()+ assert data["status"] == "ok"+ assert data["reloaded"] is True+ assert "module_count" in data+ assert data["module_count"] >= 1+ finally:+ app.dependency_overrides.clear()+ sys.modules.clear()+ sys.modules.update(saved_modules)+++def test_modules_reload_insufficient_role_rejected_403():+ """Request dengan role non-operator (recon/reporter) -> 403 Forbidden."""+ try:+ app.dependency_overrides[get_current_user] = lambda: AuthenticatedUser(+ username="recon_agent", role="recon"+ )+ with TestClient(app, base_url="http://127.0.0.1") as client:+ resp = client.post("/modules/reload")+ assert resp.status_code == 403+ finally:+ app.dependency_overrides.clear()diff --git a/tests/unit/test_updater.py b/tests/unit/test_updater.pyindex 40f0701..cce268f 100644--- a/tests/unit/test_updater.py+++ b/tests/unit/test_updater.py@@ -243,18 +243,39 @@ def test_upgrade_ui_dry_run():# ── 7. POST /modules/reload API Endpoint ──────────────────────────────────────-def test_post_modules_reload_loopback():+def test_post_modules_reload_auth_enforced():saved_modules = dict(sys.modules)try:- with TestClient(app, base_url="http://localhost") as client:- resp = client.post("/modules/reload")- assert resp.status_code == 200- data = resp.json()+ from ares.api.rbac import AuthenticatedUser, get_current_user++ with TestClient(app, base_url="http://127.0.0.1") as client:+ # 1. Unauthenticated from 127.0.0.1 / localhost must return 401 (no loopback bypass)+ resp_no_auth = client.post("/modules/reload")+ assert resp_no_auth.status_code == 401++ with TestClient(app, base_url="http://localhost") as client_lh:+ assert client_lh.post("/modules/reload").status_code == 401++ # 2. Non-operator role (reporter) must return 403 Forbidden+ app.dependency_overrides[get_current_user] = lambda: AuthenticatedUser(+ username="auditor", role="reporter"+ )+ resp_forbidden = client.post("/modules/reload")+ assert resp_forbidden.status_code == 403++ # 3. Valid operator role must return 200 OK+ app.dependency_overrides[get_current_user] = lambda: AuthenticatedUser(+ username="alice", role="operator"+ )+ resp_ok = client.post("/modules/reload")+ assert resp_ok.status_code == 200+ data = resp_ok.json()assert data.get("status") == "ok"assert data.get("reloaded") is Trueassert "module_count" in dataassert data["module_count"] >= 1finally:+ app.dependency_overrides.clear()sys.modules.clear()sys.modules.update(saved_modules)