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.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
fix(realtime): stop verifying tickets against a published constant, and stop treating an unset internal token as authorized (#941)
Beenu Arora2f0e954f2feb
diff --git a/.env.example b/.env.exampleindex 79aa82169..234da0391 100644--- a/.env.example+++ b/.env.example@@ -84,11 +84,11 @@ AISOC_DEMO_MODE=false# intentionally separate from SECRET_KEY so the realtime edge can be rotated# independently and a leaked ticket can never forge a full API session.#-# Leave blank in development: both services fall back to a well-known dev secret-# so docker-compose "just works". In production you MUST set a real value —-# the ticket endpoint fails closed (503) and the realtime service rejects every-# connection until this is wired. Generate with:-# python -c "import secrets; print(secrets.token_hex(32))"+# `make up` generates this. There is no development fallback any more: both+# sides used to fall back to a constant committed to this repository, and no+# manifest passed either the real secret or the variable the production check+# read, so that constant was the effective key in every deployment. Unset, the+# ticket endpoint fails closed (503) and realtime rejects every connection.AISOC_REALTIME_JWT_SECRET=# Time-to-live (seconds) for minted realtime tickets. Kept short so a leaked# ticket is only briefly useful; the frontend re-mints on every (re)connect.@@ -371,6 +371,11 @@ AISOC_SERVICE_TOKEN=# service answers 503 on every mutating route, which is deliberate: it used to# answer 200 to anyone who could reach the port.AISOC_ACTIONS_SERVICE_TOKEN=++# Bearer for realtime's /internal/* fan-out routes (API/agents -> realtime),+# sent as the x-internal-token header. `make up` generates it. The guard used+# to treat an unset value as authorized, and nothing set it.+REALTIME_INTERNAL_TOKEN=# Optional per-service overrides, if you'd rather not share one secret:# AISOC_PURPLE_TEAM_SERVICE_TOKEN=# AISOC_HONEYTOKENS_SERVICE_TOKEN=diff --git a/docker-compose.yml b/docker-compose.ymlindex 4e1db513e..8a8bc3be6 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -399,6 +399,12 @@ services:# match whatever the connectors service verifies with, or the console# token the API forwards there fails its signature check.SECRET_KEY: ${SECRET_KEY:-dev_secret_key_change_in_production}+ # The API mints realtime tickets and calls realtime's /internal/* routes,+ # so it needs the same two secrets the realtime container reads. Neither+ # was passed to either side before, which is why both guards there were+ # running on a published constant or not running at all.+ AISOC_REALTIME_JWT_SECRET: ${AISOC_REALTIME_JWT_SECRET:-}+ REALTIME_INTERNAL_TOKEN: ${REALTIME_INTERNAL_TOKEN:-}# The credential this service presents when it proxies the connector# catalog and "Test connection" to the connectors service.# `_service_token()` in app/api/v1/endpoints/connectors.py reads@@ -1178,6 +1184,12 @@ services:REDIS_URL: redis://:redis_dev_secret@redis:6379REDIS_PASSWORD: redis_dev_secretPORT: 4000+ # Both are generated by `make up`. Neither was passed to this container+ # before, which is what made the ticket verifier fall back to a constant+ # published in this repository and the /internal/* guard treat every+ # caller as authorized.+ AISOC_REALTIME_JWT_SECRET: ${AISOC_REALTIME_JWT_SECRET:-}+ REALTIME_INTERNAL_TOKEN: ${REALTIME_INTERNAL_TOKEN:-}networks:- aisocrestart: unless-stoppeddiff --git a/scripts/ensure_env.py b/scripts/ensure_env.pyindex eb12ee6ca..43e0c8b27 100644--- a/scripts/ensure_env.py+++ b/scripts/ensure_env.py@@ -105,6 +105,23 @@ GENERATED: dict[str, tuple[Callable[[], str], str]] = {lambda: secrets.token_urlsafe(32),"Shared bearer for the actions service (API -> actions). Gates every response action.",),+ # The HS256 key the API signs realtime tickets with and the realtime edge+ # verifies them against. Both sides previously fell back to a constant+ # committed to this repository whenever this was unset — which no manifest+ # ever set — so anyone who could reach the edge could mint a ticket for any+ # tenant by signing with a published value.+ "AISOC_REALTIME_JWT_SECRET": (+ lambda: secrets.token_urlsafe(32),+ "HS256 key for realtime WebSocket/SSE tickets. Shared by the API (mints) and realtime (verifies).",+ ),+ # Service-to-service bearer for realtime's /internal/* fan-out routes.+ # Their guard treated an unset value as authorized, and nothing set it, so+ # the routes accepted an arbitrary tenant_id from any caller that could+ # reach the port.+ "REALTIME_INTERNAL_TOKEN": (+ lambda: secrets.token_urlsafe(32),+ "Bearer for realtime's /internal/* fan-out (API/agents -> realtime). Sent as x-internal-token.",+ ),}diff --git a/services/api/app/core/config.py b/services/api/app/core/config.pyindex b76c60a2a..ad3b80000 100644--- a/services/api/app/core/config.py+++ b/services/api/app/core/config.py@@ -23,6 +23,11 @@ INSECURE_SECRET_KEY_DEFAULTS: frozenset[str] = frozenset("dev_secret_key_change_in_production","changeme","secret",+ # The former realtime dev fallback. Published in this repository's+ # history, so it is refused rather than forgotten: copying it out of an+ # older checkout into .env must not produce a working deployment keyed+ # on a value anyone can read.+ "aisoc-dev-realtime-ticket-secret-not-for-production",})@@ -545,10 +550,11 @@ class Settings(BaseSettings):# fan-out auth), so the realtime edge can be rotated independently and a# leaked ticket secret never forges a full API session.#- # When empty in a development-class environment, both services fall back- # to ``DEV_REALTIME_TICKET_SECRET`` so local docker-compose "just works".- # Outside development the ticket endpoint fails closed (503) until a real- # secret is wired, and the realtime service rejects every connection.+ # Generated by ``make up`` and passed to both this service and realtime.+ # When empty the ticket endpoint fails closed (503) and the realtime edge+ # rejects every connection, in every environment — there is no development+ # fallback, because the one that used to be here was a constant committed+ # to this repository and no manifest ever set the real secret.AISOC_REALTIME_JWT_SECRET: str = ""# Time-to-live, in seconds, for minted realtime tickets. Kept short so a# leaked ticket is only briefly useful; the frontend re-mints on every@@ -827,17 +833,23 @@ def realtime_ticket_secret(s: Settings | None = None) -> str | None:* If ``AISOC_REALTIME_JWT_SECRET`` is set to a non-empty, non-insecurevalue, use it (any environment).- * Otherwise, in a development-class environment, fall back to the shared- ``DEV_REALTIME_TICKET_SECRET`` so local stacks work with zero config.- * Otherwise (production with the secret unset or set to a known insecure- placeholder), return ``None`` — the caller must fail closed.+ * Otherwise return ``None`` — the caller must fail closed.++ There is deliberately no development fallback. Both this and the Node+ verifier used to fall back to ``DEV_REALTIME_TICKET_SECRET``, a constant+ committed to this repository, and no manifest ever set the real secret or+ the environment variable the production check read — so that constant was+ the effective HMAC key everywhere, and anyone who could reach the realtime+ edge could mint a ticket for any tenant (GHSA-4m55-xhcm-wjcr).++ ``make up`` now generates ``AISOC_REALTIME_JWT_SECRET`` and compose passes+ it to this service and to realtime, so local stacks still work with zero+ manual config — on a real key rather than a published one."""s = s or settingsconfigured = (s.AISOC_REALTIME_JWT_SECRET or "").strip()if configured and configured not in INSECURE_SECRET_KEY_DEFAULTS:return configured- if is_dev_env(s.ENVIRONMENT):- return DEV_REALTIME_TICKET_SECRETreturn Nonediff --git a/services/api/tests/api/v1/endpoints/test_realtime_ticket.py b/services/api/tests/api/v1/endpoints/test_realtime_ticket.pyindex 40a745889..37b0907f5 100644--- a/services/api/tests/api/v1/endpoints/test_realtime_ticket.py+++ b/services/api/tests/api/v1/endpoints/test_realtime_ticket.py@@ -67,9 +67,23 @@ def test_secret_uses_configured_value_in_any_env():assert realtime_ticket_secret(s) == _REAL_SECRET-def test_secret_falls_back_to_dev_default_in_development():+def test_secret_does_not_fall_back_to_the_published_default_in_development():+ """GHSA-4m55-xhcm-wjcr. This asserted the fallback and was the vulnerability.++ The fallback was a constant committed to this repository, and the check+ that was supposed to confine it to development read an environment+ variable no shipped manifest passed to the realtime container — so it was+ the effective HMAC key everywhere, and a ticket for any tenant could be+ minted by signing with a published value.+ """s = _settings(ENVIRONMENT="development", AISOC_REALTIME_JWT_SECRET="")- assert realtime_ticket_secret(s) == DEV_REALTIME_TICKET_SECRET+ assert realtime_ticket_secret(s) is None+++def test_the_retired_dev_secret_is_refused_even_when_set_explicitly():+ """Pasting it out of an older checkout must not produce a working key."""+ s = _settings(ENVIRONMENT="development", AISOC_REALTIME_JWT_SECRET=DEV_REALTIME_TICKET_SECRET)+ assert realtime_ticket_secret(s) is Nonedef test_secret_is_none_in_prod_when_unset():diff --git a/services/realtime/src/auth.ts b/services/realtime/src/auth.tsindex c8839d9ba..3d48f039a 100644--- a/services/realtime/src/auth.ts+++ b/services/realtime/src/auth.ts@@ -20,10 +20,6 @@ import crypto from 'crypto';// Must equal `REALTIME_TICKET_AUDIENCE` in services/api/app/core/security.py.export const REALTIME_TICKET_AUDIENCE = 'aisoc-realtime';-// Must equal `DEV_REALTIME_TICKET_SECRET` in services/api/app/core/config.py.-// Shared dev fallback so local docker-compose works with zero secret plumbing.-const DEV_REALTIME_TICKET_SECRET = 'aisoc-dev-realtime-ticket-secret-not-for-production';-// Mirror INSECURE_SECRET_KEY_DEFAULTS in services/api/app/core/config.py so a// placeholder secret is treated as "unset" on this side too.const INSECURE_SECRET_DEFAULTS = new Set<string>([@@ -31,15 +27,13 @@ const INSECURE_SECRET_DEFAULTS = new Set<string>(['dev_secret_key_change_in_production','changeme','secret',+ // The former hardcoded dev fallback. It is published in this repository's+ // history, so it is listed here to be *refused* rather than removed: an+ // operator who copies it out of an older checkout into .env must not get a+ // working deployment keyed on a value anyone can read.+ 'aisoc-dev-realtime-ticket-secret-not-for-production',]);-function isProductionEnv(): boolean {- const env = (process.env.AISOC_ENV || process.env.ENVIRONMENT || process.env.APP_ENV || '')- .trim()- .toLowerCase();- return env === 'production' || env === 'prod';-}-/*** Resolve the effective HS256 secret used to verify realtime tickets.*@@ -53,9 +47,17 @@ export function resolveTicketSecret(): string | null {if (configured && !INSECURE_SECRET_DEFAULTS.has(configured)) {return configured;}- if (!isProductionEnv()) {- return DEV_REALTIME_TICKET_SECRET;- }+ // No development fallback. This used to return DEV_REALTIME_TICKET_SECRET+ // whenever the environment did not look like production, and the check read+ // AISOC_ENV / ENVIRONMENT / APP_ENV from the container's own environment —+ // which no shipped manifest passed to this service. The production branch+ // was therefore unreachable and a constant published in this repository was+ // the effective HMAC key in every deployment, so anyone who could reach the+ // edge could mint a ticket for any tenant (GHSA-4m55-xhcm-wjcr).+ //+ // `make up` now generates AISOC_REALTIME_JWT_SECRET and compose passes it to+ // both the API that mints tickets and this service, so failing closed here+ // costs the local stack nothing.return null;}diff --git a/services/realtime/src/index.ts b/services/realtime/src/index.tsindex daf6c1ec0..8355c1579 100644--- a/services/realtime/src/index.ts+++ b/services/realtime/src/index.ts@@ -1,5 +1,6 @@import express from 'express';import cors from 'cors';+import crypto from 'crypto';import http from 'http';import { WebSocketServer } from 'ws';import { Kafka } from 'kafkajs';@@ -96,10 +97,6 @@ if (REALTIME_TICKET_SECRET === null) {'AISOC_REALTIME_JWT_SECRET is unset or insecure in a production environment — ' +'realtime WS/SSE connections will be rejected until a real secret is wired.',);-} else if (- REALTIME_TICKET_SECRET === 'aisoc-dev-realtime-ticket-secret-not-for-production'-) {- log.warn('Using the shared development realtime ticket secret — do NOT use in production.');}/**@@ -678,12 +675,32 @@ app.post('/v1/push/test', pushRateLimit, asyncRoute(pushManager.testNotifyHandle// POST /internal/agent-event// Body: { tenant_id?: string, run_id: string, kind: string, agent: string, summary: string, data?: unknown }// The realtime service re-broadcasts to all WebSocket clients on the `agents` channel.-const INTERNAL_TOKEN = process.env.INTERNAL_TOKEN || '';+// `REALTIME_INTERNAL_TOKEN` is the name the API sends this under and the name+// `make up` generates; `INTERNAL_TOKEN` is read second so an existing+// deployment that set the older name keeps working.+const INTERNAL_TOKEN = (process.env.REALTIME_INTERNAL_TOKEN || process.env.INTERNAL_TOKEN || '').trim();function requireInternal(req: express.Request, res: express.Response): boolean {- if (!INTERNAL_TOKEN) return true;+ // Fails closed. This returned `true` — authorized — when the token was+ // unset, and no shipped manifest set it, so the guard never ran: any caller+ // who could reach the port could inject events into any tenant's live stream+ // by naming the tenant in the body, and could push a notification with+ // attacker-chosen title, body and URL to that tenant's devices+ // (GHSA-mqjp-pcpr-7c37).+ if (!INTERNAL_TOKEN) {+ res.status(503).json({+ error: 'realtime internal auth is not configured',+ detail: 'set REALTIME_INTERNAL_TOKEN (run `make env`, which generates it, and restart)',+ });+ return false;+ }const auth = req.headers['x-internal-token'];- if (auth !== INTERNAL_TOKEN) {+ if (typeof auth !== 'string' || auth.length !== INTERNAL_TOKEN.length) {+ res.status(401).json({ error: 'unauthorized' });+ return false;+ }+ // Constant-time: a length-independent compare on a bearer is a timing oracle.+ if (!crypto.timingSafeEqual(Buffer.from(auth), Buffer.from(INTERNAL_TOKEN))) {res.status(401).json({ error: 'unauthorized' });return false;}diff --git a/services/realtime/test/auth.test.ts b/services/realtime/test/auth.test.tsindex ae9a3cf9e..ff3923616 100644--- a/services/realtime/test/auth.test.ts+++ b/services/realtime/test/auth.test.ts@@ -117,17 +117,29 @@ test('rejects a non-numeric exp', () => {assert.equal(verifyRealtimeTicket(token, SECRET), null);});-test('resolveTicketSecret falls back to the dev secret outside production', () => {+// GHSA-4m55-xhcm-wjcr. This asserted the fallback and was the vulnerability:+// the constant is published in this repository, and the production check read+// an environment variable no shipped manifest passed to this container, so it+// was the effective HMAC key in every deployment.+test('resolveTicketSecret does not fall back to the published dev secret', () => {const prev = { ...process.env };try {delete process.env.AISOC_REALTIME_JWT_SECRET;process.env.ENVIRONMENT = 'development';delete process.env.AISOC_ENV;delete process.env.APP_ENV;- assert.equal(- resolveTicketSecret(),- 'aisoc-dev-realtime-ticket-secret-not-for-production',- );+ assert.equal(resolveTicketSecret(), null);+ } finally {+ process.env = prev;+ }+});++test('the retired dev secret is refused even when set explicitly', () => {+ const prev = { ...process.env };+ try {+ process.env.AISOC_REALTIME_JWT_SECRET =+ 'aisoc-dev-realtime-ticket-secret-not-for-production';+ assert.equal(resolveTicketSecret(), null);} finally {process.env = prev;}