Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

security(api): harden /fusion + /cases proxy endpoints against SSRF and log injection

Beenu Aroraa589d2662ab6
diff --git a/.gitleaksignore b/.gitleaksignore
new file mode 100644
index 000000000..4ea404d34
--- /dev/null
+++ b/.gitleaksignore
@@ -0,0 +1,31 @@
+# gitleaks ignore list
+#
+# Each entry is a triaged false-positive. New entries MUST include a comment
+# explaining why the match is benign. If a finding cannot be justified, do not
+# add it here -- rotate the secret and remove the leak from the source.
+#
+# Format: <absolute_or_repo_relative_path>:<rule-id>:<line>
+
+# Positive test fixture for the `jwt-none-alg` detection rule. This file is
+# *expected* to contain a JWT with `alg: none` because the detection engine
+# runs against it as ground truth.
+detections/fixtures/positive/jwt-none-alg.json:jwt:2
+
+# Render IaC env-var keys (`AISOC_DISABLE_NEO4J`, `AISOC_DISABLE_QDRANT`).
+# The generic-api-key rule fires on the long key name; the value is "true",
+# not a secret.
+infra/render/render.yaml:generic-api-key:70
+infra/render/render.yaml:generic-api-key:124
+
+# Detection rule literal: `count_5min_per_ip_gt: 30` matches the heuristic.
+# This is a rule definition, not a credential.
+scripts/detection_specs_part3_application.py:generic-api-key:61
+
+# Detection rule positive sample: an `alg: none` JWT used to validate the
+# matching detection rule. Same fixture pattern as jwt-none-alg.json.
+scripts/detection_specs_part2.py:jwt:1111
+
+# Pre-generated Fernet key used as a deterministic test default in
+# `test_security_defaults.py`. Real deployments inject AISOC_CREDENTIAL_KEY
+# as a secret at runtime; this value is *never* used outside tests.
+services/api/tests/test_security_defaults.py:generic-api-key:34
diff --git a/services/api/app/api/v1/endpoints/cases.py b/services/api/app/api/v1/endpoints/cases.py
index befe31560..f4fae8a20 100644
--- a/services/api/app/api/v1/endpoints/cases.py
+++ b/services/api/app/api/v1/endpoints/cases.py
@@ -21,9 +21,11 @@ from __future__ import annotations
import logging
import os
+import re
import uuid
from datetime import UTC, datetime
from typing import Any, Literal
+from urllib.parse import quote
import httpx
from fastapi import APIRouter, HTTPException, Query, Response, status
@@ -46,6 +48,26 @@ _AGENTS_URL = (
or "http://agents:8084"
).rstrip("/")
+# Tight allowlist for proxied request paths. We only ever proxy to a fixed
+# upstream (`_AGENTS_URL`) on a known set of investigation routes, so the
+# path must be a pure relative path — no scheme, no host, no control bytes,
+# no traversal sequences. This neutralises partial-SSRF (an attacker cannot
+# redirect the request to a different host) and log-injection (the path
+# can never contain CR/LF or other control characters).
+_SAFE_PROXY_PATH_RE = re.compile(r"^/[A-Za-z0-9_\-./%]*$")
+
+
+def _validate_agents_path(path: str) -> str:
+ """Reject any proxied path that isn't a tightly constrained relative path."""
+ if (
+ not isinstance(path, str)
+ or not _SAFE_PROXY_PATH_RE.match(path)
+ or ".." in path
+ or path.startswith("//") # protocol-relative URL
+ ):
+ raise HTTPException(status_code=400, detail="invalid_request_path")
+ return path
+
# ────────────────────────────────────────────────────────────────────────────
# Pydantic schemas
# ────────────────────────────────────────────────────────────────────────────
@@ -835,13 +857,14 @@ async def update_task(
async def _agents_proxy(method: str, path: str, **kwargs: Any) -> httpx.Response:
- url = f"{_AGENTS_URL}{path}"
+ safe_path = _validate_agents_path(path)
+ url = f"{_AGENTS_URL}{safe_path}"
timeout = kwargs.pop("timeout", 30.0)
try:
async with httpx.AsyncClient(timeout=timeout) as client:
return await client.request(method, url, **kwargs)
except httpx.HTTPError as exc:
- logger.exception("Agents service request failed: %s %s", method, url)
+ logger.exception("Agents service request failed: %s %s", method, safe_path)
raise HTTPException(
status_code=503,
detail=f"Agents service unavailable: {exc}",
@@ -902,12 +925,25 @@ async def case_investigation_run(
run_id: str,
user: AuthUser,
) -> dict[str, Any]:
- resp = await _agents_proxy("GET", f"/api/v1/investigations/{run_id}")
+ # URL-encode the user-supplied run_id so it cannot inject `/`, `?`, `#`,
+ # CR/LF, or other URL syntax into the proxied path.
+ safe_run_id = quote(run_id, safe="")
+ resp = await _agents_proxy("GET", f"/api/v1/investigations/{safe_run_id}")
if resp.status_code >= 400:
raise HTTPException(status_code=resp.status_code, detail=resp.text)
return resp.json()
+# Filename sanitiser for Content-Disposition: keep only safe ASCII so the
+# header cannot be split with CR/LF and the value renders consistently.
+_SAFE_FILENAME_RE = re.compile(r"[^A-Za-z0-9._-]")
+
+
+def _safe_filename_segment(value: str) -> str:
+ """Reduce an identifier to a Content-Disposition-safe filename segment."""
+ return _SAFE_FILENAME_RE.sub("_", value)[:64] or "unknown"
+
+
@router.get(
"/{case_id}/investigations/{run_id}/report.pdf",
summary="Download investigation PDF report",
@@ -917,16 +953,19 @@ async def case_investigation_pdf(
run_id: str,
user: AuthUser,
) -> Response:
- resp = await _agents_proxy("GET", f"/api/v1/investigations/{run_id}/report.pdf")
+ safe_run_id = quote(run_id, safe="")
+ resp = await _agents_proxy("GET", f"/api/v1/investigations/{safe_run_id}/report.pdf")
if resp.status_code >= 400:
raise HTTPException(status_code=resp.status_code, detail=resp.text)
+ safe_case_id = _safe_filename_segment(case_id)
+ safe_run_id_filename = _safe_filename_segment(run_id)
return Response(
content=resp.content,
media_type=resp.headers.get("content-type", "application/pdf"),
headers={
"Content-Disposition": resp.headers.get(
"content-disposition",
- f'attachment; filename="case-{case_id}-{run_id}.pdf"',
+ f'attachment; filename="case-{safe_case_id}-{safe_run_id_filename}.pdf"',
),
},
)
diff --git a/services/api/app/api/v1/endpoints/fusion.py b/services/api/app/api/v1/endpoints/fusion.py
index 1a3fe7a00..73f7a8110 100644
--- a/services/api/app/api/v1/endpoints/fusion.py
+++ b/services/api/app/api/v1/endpoints/fusion.py
@@ -26,7 +26,9 @@ from __future__ import annotations
import logging
import os
+import re
from typing import Any
+from urllib.parse import quote
from uuid import UUID
import httpx
@@ -45,19 +47,39 @@ _FUSION_URL = (
or ""
).rstrip("/")
+# Tight allowlist for proxied request paths. We only ever proxy to a fixed
+# upstream (`_FUSION_URL`) on a known set of routes, so the path must be a
+# pure relative path with no scheme, host, control characters, or traversal
+# sequences. This neutralises partial-SSRF (an attacker cannot redirect the
+# request elsewhere) and log-injection (the path can never contain CR/LF).
+_SAFE_PATH_RE = re.compile(r"^/[A-Za-z0-9_\-./%]*$")
+
+
+def _validate_proxy_path(path: str) -> str:
+ """Reject any proxied path that isn't a tightly constrained relative path."""
+ if (
+ not isinstance(path, str)
+ or not _SAFE_PATH_RE.match(path)
+ or ".." in path
+ or path.startswith("//") # protocol-relative URL
+ ):
+ raise HTTPException(status_code=400, detail="invalid_request_path")
+ return path
+
async def _proxy_get(path: str, params: dict[str, Any] | None = None) -> dict[str, Any] | None:
"""Forward GET to fusion if configured. Return None on transport error."""
if not _FUSION_URL:
return None
+ safe_path = _validate_proxy_path(path)
try:
async with httpx.AsyncClient(timeout=15.0) as client:
- resp = await client.get(f"{_FUSION_URL}{path}", params=params or {})
+ resp = await client.get(f"{_FUSION_URL}{safe_path}", params=params or {})
if resp.status_code >= 500:
logger.warning(
"Fusion upstream returned %s for %s; falling back to stub",
resp.status_code,
- path,
+ safe_path,
)
return None
if resp.status_code == 404:
@@ -172,8 +194,12 @@ async def entity_risk_detail(
) -> dict[str, Any]:
if entity_type == "ip":
entity_type = "src_ip"
+ # URL-encode user-controlled path segments so they cannot inject `/`,
+ # `?`, `#`, or other URL syntax into the proxied path.
+ safe_type = quote(entity_type, safe="")
+ safe_value = quote(entity_value, safe="")
upstream = await _proxy_get(
- f"/entity-risk/{entity_type}/{entity_value}",
+ f"/entity-risk/{safe_type}/{safe_value}",
params={"tenant_id": str(tenant_id)},
)
if upstream is not None: