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: resolve all CodeQL code-scanning alerts

Beenu Arora8c78432d5b31
diff --git a/services/api/app/api/v1/endpoints/detection_loop.py b/services/api/app/api/v1/endpoints/detection_loop.py
index 022128816..eaeb3218e 100644
--- a/services/api/app/api/v1/endpoints/detection_loop.py
+++ b/services/api/app/api/v1/endpoints/detection_loop.py
@@ -25,11 +25,11 @@ from datetime import UTC, datetime
from typing import Any
import httpx
-from fastapi import APIRouter, Depends, HTTPException, status
+from fastapi import APIRouter, HTTPException, status
from pydantic import BaseModel, Field
-from sqlalchemy import select, text
+from sqlalchemy import text
-from app.api.v1.deps import AuthUser, DBSession, require_permission
+from app.api.v1.deps import AuthUser, DBSession
from app.core.config import settings
router = APIRouter(prefix="/detection-loop", tags=["detection_rules", "detection_loop"])
diff --git a/services/api/app/api/v1/endpoints/identity_timeline.py b/services/api/app/api/v1/endpoints/identity_timeline.py
index b2b9ed7f3..37860feef 100644
--- a/services/api/app/api/v1/endpoints/identity_timeline.py
+++ b/services/api/app/api/v1/endpoints/identity_timeline.py
@@ -17,13 +17,15 @@ import uuid
from datetime import UTC, datetime, timedelta
from typing import Any, Literal
-from fastapi import APIRouter, HTTPException, Query, status
+import structlog
+from fastapi import APIRouter, Query, status
from pydantic import BaseModel, Field
from sqlalchemy import text
from app.api.v1.deps import AuthUser, DBSession
router = APIRouter(prefix="/identity-timeline", tags=["identity_timeline"])
+log = structlog.get_logger(__name__)
# ────────────────────────────────────────────────────────────────────────────
# Pydantic schemas
@@ -67,14 +69,6 @@ class BuildTimelineRequest(BaseModel):
# Helpers
# ────────────────────────────────────────────────────────────────────────────
-_FIELD_MAP: dict[IdentityKind, list[str]] = {
- "user": ["user", "username", "src_user", "dest_user", "actor"],
- "device": ["hostname", "device", "src_host", "computer_name"],
- "service_account": ["service_account", "svc_account", "process_user"],
- "ip": ["src_ip", "source_ip", "ip_address", "remote_ip"],
-}
-
-
def _risk_score(events: list[TimelineEvent]) -> float:
"""Simple heuristic: sum severity weights, cap at 100."""
weights = {"critical": 40, "high": 20, "medium": 10, "low": 3, "info": 1}
@@ -148,8 +142,8 @@ async def build_timeline(
raw=row.evidence,
)
)
- except Exception:
- pass # table may not exist in all deployments
+ except Exception as exc:
+ log.debug("aisoc_alerts table not available; skipping", error=str(exc))
# ── 2. Raw events from aisoc_events (if table exists) ──────────────────
try:
@@ -183,8 +177,8 @@ async def build_timeline(
raw=row.raw_event,
)
)
- except Exception:
- pass
+ except Exception as exc:
+ log.debug("aisoc_events table not available; skipping", error=str(exc))
# ── 3. Sort chronologically ─────────────────────────────────────────────
events.sort(key=lambda e: e.timestamp)
diff --git a/services/api/app/api/v1/endpoints/knowledge_base.py b/services/api/app/api/v1/endpoints/knowledge_base.py
index 4a0fc1f50..eddff5fe0 100644
--- a/services/api/app/api/v1/endpoints/knowledge_base.py
+++ b/services/api/app/api/v1/endpoints/knowledge_base.py
@@ -15,7 +15,6 @@ Endpoints
from __future__ import annotations
-import json
import os
import uuid
from datetime import UTC, datetime
diff --git a/services/api/app/api/v1/endpoints/nl_query.py b/services/api/app/api/v1/endpoints/nl_query.py
index d94e01478..0ec469dce 100644
--- a/services/api/app/api/v1/endpoints/nl_query.py
+++ b/services/api/app/api/v1/endpoints/nl_query.py
@@ -17,9 +17,10 @@ import textwrap
import uuid
from datetime import UTC, datetime
from typing import Any
+from urllib.parse import urlparse
import httpx
-from fastapi import APIRouter, HTTPException, status
+from fastapi import APIRouter, status
from pydantic import BaseModel, Field
from app.api.v1.deps import AuthUser
@@ -27,6 +28,29 @@ from app.core.config import settings
router = APIRouter(prefix="/nl-query", tags=["nl_query"])
+
+def _validate_es_url(url: str) -> str:
+ """Validate that *url* matches the configured Elasticsearch/OpenSearch host.
+
+ Raises ValueError if the host or scheme does not match, preventing SSRF
+ by ensuring the client can only reach the pre-approved endpoint.
+ """
+ allowed_raw = (
+ getattr(settings, "ES_URL", None)
+ or getattr(settings, "ELASTICSEARCH_URL", None)
+ or getattr(settings, "OPENSEARCH_URL", "http://localhost:9200")
+ )
+ allowed = urlparse(allowed_raw)
+ candidate = urlparse(url)
+ if candidate.scheme not in ("http", "https"):
+ raise ValueError(f"Unsupported URL scheme: {candidate.scheme!r}")
+ if candidate.netloc != allowed.netloc:
+ raise ValueError(
+ f"ES URL host {candidate.netloc!r} is not the configured host "
+ f"{allowed.netloc!r}"
+ )
+ return url
+
# ────────────────────────────────────────────────────────────────────────────
# Pydantic schemas
# ────────────────────────────────────────────────────────────────────────────
@@ -178,6 +202,12 @@ async def _execute_esql(
esql: str, es_url: str, es_api_key: str, max_rows: int
) -> QueryResult:
"""Run an ES|QL query against Elasticsearch and return structured results."""
+ # Validate URL against configured host before making any outbound request.
+ try:
+ safe_url = _validate_es_url(es_url)
+ except ValueError as exc:
+ raise httpx.RequestError(str(exc)) from exc
+
# Ensure LIMIT clause
query = esql if "| LIMIT" in esql.upper() else f"{esql}\n| LIMIT {max_rows}"
import time
@@ -185,7 +215,7 @@ async def _execute_esql(
t0 = time.monotonic()
async with httpx.AsyncClient(timeout=20) as client:
resp = await client.post(
- f"{es_url.rstrip('/')}/_query",
+ f"{safe_url.rstrip('/')}/_query",
headers={
"Authorization": f"ApiKey {es_api_key}",
"Content-Type": "application/json",
diff --git a/services/api/app/auth/oidc.py b/services/api/app/auth/oidc.py
index 828153e7b..1c2ef33cf 100644
--- a/services/api/app/auth/oidc.py
+++ b/services/api/app/auth/oidc.py
@@ -235,7 +235,7 @@ async def oidc_callback(
}
)
- redirect_url = state_data.get("redirect", "/")
+ redirect_url = _safe_redirect(state_data.get("redirect", "/"))
response = RedirectResponse(url=redirect_url, status_code=302)
response.set_cookie("aisoc_token", token, httponly=True, samesite="lax", secure=request.url.scheme == "https")
response.delete_cookie("oidc_state")
diff --git a/services/connectors/app/api/router.py b/services/connectors/app/api/router.py
index 9a40d32a6..958fb3511 100644
--- a/services/connectors/app/api/router.py
+++ b/services/connectors/app/api/router.py
@@ -25,6 +25,7 @@ service's lifespan), not in this router.
from __future__ import annotations
+import re
from typing import Any
import structlog
@@ -38,6 +39,17 @@ from app.federated.query import QueryError, parse_unified_query
logger = structlog.get_logger()
router = APIRouter()
+_CTRL_RE = re.compile(r"[\x00-\x1f\x7f]")
+
+
+def _safe_log_val(value: str) -> str:
+ """Strip ASCII control characters (incl. newlines) from a string before logging.
+
+ Prevents log-injection attacks where a user-controlled value such as a
+ connector_id could embed newline sequences that forge extra log lines.
+ """
+ return _CTRL_RE.sub("", value)
+
class TestConnectionRequest(BaseModel):
"""Stateless test-connection payload.
@@ -151,7 +163,7 @@ async def test_connector_connection(connector_id: str, payload: TestConnectionRe
detail=f"connector config does not match schema: {exc}",
) from exc
except Exception: # pragma: no cover - last-ditch
- logger.exception("connector.test.constructor_error", connector_id=connector_id)
+ logger.exception("connector.test.constructor_error", connector_id=_safe_log_val(connector_id))
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Failed to construct connector. Check your configuration.",
@@ -164,7 +176,7 @@ async def test_connector_connection(connector_id: str, payload: TestConnectionRe
# {"success": False, "error": ...}. If one raises anyway, we
# convert to the same shape so the wizard UI doesn't have two
# error formats to deal with.
- logger.exception("connector.test.runtime_error", connector_id=connector_id)
+ logger.exception("connector.test.runtime_error", connector_id=_safe_log_val(connector_id))
result = {"success": False, "connector": connector_id, "error": "Connection test failed"}
if not isinstance(result, dict):
@@ -222,7 +234,7 @@ async def run_federated_query(connector_id: str, payload: FederatedQueryRequest)
except QueryError as exc:
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)) from exc
except Exception:
- logger.exception("connector.query.runtime_error", connector_id=connector_id)
+ logger.exception("connector.query.runtime_error", connector_id=_safe_log_val(connector_id))
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail="Backend query failed. Check connector configuration and connectivity.",
diff --git a/services/realtime/src/index.ts b/services/realtime/src/index.ts
index 49a49b2da..ccaa7ac12 100644
--- a/services/realtime/src/index.ts
+++ b/services/realtime/src/index.ts
@@ -271,10 +271,31 @@ async function startKafkaConsumer() {
// --- Web Push routes (Phase 4B mobile responder PWA) ---
// Public key is needed by the browser to subscribe; the rest are
// authenticated routes the API gateway forwards on behalf of a user.
+// Rate-limit push mutation routes: 20 req / min per IP to prevent abuse.
+const pushSubscribeRateLimitExceeded = makeRateLimiter(20, 60_000);
+
+function pushRateLimit(
+ req: express.Request,
+ res: express.Response,
+ next: express.NextFunction,
+): void {
+ const ip =
+ (req.headers['x-forwarded-for'] as string | undefined)
+ ?.split(',')[0]
+ ?.trim() ||
+ req.socket.remoteAddress ||
+ 'unknown';
+ if (pushSubscribeRateLimitExceeded(ip)) {
+ res.status(429).json({ error: 'Rate limit exceeded' });
+ return;
+ }
+ next();
+}
+
app.get('/v1/push/public-key', pushManager.publicKeyHandler);
-app.post('/v1/push/subscribe', pushManager.subscribeHandler);
-app.post('/v1/push/unsubscribe', pushManager.unsubscribeHandler);
-app.post('/v1/push/test', pushManager.testNotifyHandler);
+app.post('/v1/push/subscribe', pushRateLimit, pushManager.subscribeHandler);
+app.post('/v1/push/unsubscribe', pushRateLimit, pushManager.unsubscribeHandler);
+app.post('/v1/push/test', pushRateLimit, pushManager.testNotifyHandler);
// --- Internal broadcast endpoint (called by other services) ---
// POST /internal/agent-event