DibaGuard / docs /TECHNICAL.md
DibaAi's picture
DibaGuard: public licence-clean release (Dibachain)
5d97275 verified
|
Raw History Blame Contribute Delete
48.4 kB
# DibaGuard β€” Technical Documentation
> **Open-release copy** ([DibaAi/DibaGuard-Open](https://huggingface.co/DibaAi/DibaGuard-Open)). This document was written for the private build of DibaGuard. Numbers that involve the HTTP request model (`http_v2`) were measured with that model, which is **not** part of the open release; the open release ships the licence-clean network models described in `CLEAN_MODELS.md`. Licence statements inside this document are superseded by `DATA_LICENSES.md`, `CLEAN_MODELS.md` and the repository's `LICENSE`, `LICENSE-WEIGHTS` and `NOTICE` files. Sections of the original that were written in Persian were removed from this copy; nothing else was edited.
*Version 2.5 (2026-10-31). Open-release copy, see the note below.*
DibaGuard is a CPU-light attack-detection and protection layer for networks, web applications, blockchain nodes and
databases. It sits where a WAF, an IDS and a host firewall would sit β€” inline in front of an application, as an
external decision service for an existing load balancer, or beside a host β€” and turns traffic into *calibrated*
verdicts: every alarm comes with a controlled false-alarm rate, a named attack family, the evidence that produced
it, and an action chosen by the operator's policy (report only, or enforce).
This document explains how it is built and why: the neural networks and the statistics around them, the ideas that
make it work on networks it has never seen, everything that was built and measured, what failed and what was
changed, and how to run, test and integrate it. Every number in the results chapter is produced by a script in the
repository and regenerated when this document is built.
---
## 1. The problem, and the shape of the answer
Attack detection fails in practice for three reasons, and the design answers each one:
1. **Models trained on one network do not transfer to another.** A classifier trained on public datasets learns the
datasets' quirks (one testbed's packet sizes, another's address plan). Measured early in this project: per-flow
models with ~0.99 AUROC inside a dataset dropped to 0.47–0.93 on a held-out network, with almost no detection at
a useful false-alarm rate. **Answer:** the learned parts only see *behaviour* (how a source acts over time, how
a request or query is *structured*), never raw identities or sizes; and every learned score is turned into a
decision by **conformal calibration on the site's own traffic**, so the false-alarm rate is controlled *at the
site*, whatever the training data was.
2. **False alarms, not missed attacks, are what get a security tool switched off.** **Answer:** an explicit
false-alarm budget (α, by default 10⁻³ per source-minute) split across tiers; the reference data each threshold
is computed from is kept clean *and* complete (sections 4.3–4.5); a first-contact source is never blocked on
weak evidence; shared addresses (NAT/CGNAT) are challenged rather than blocked; application servers are never
blocked at the network level.
3. **Real attacks are distributed, slow, and adaptive.** **Answer:** a cascade in which every tier looks at a
different scale β€” one event, one source's recent stream, one source over half an hour, one destination, the
whole site, a fingerprint shared across thousands of sources β€” plus hard, explainable signatures for what never
needs statistics, and a feedback loop that the operator controls and an attacker cannot poison.
The result is one engine (`dibaguard/engine.py`) with a protective shell (`dibaguard/shield/`), a database tier,
an HTTP edge, a Go fast path, an LLM bridge and an operator console.
---
## 2. Architecture at a glance
```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ DibaGuard ───────────────────────────────┐
traffic ──► adapters ──► CASCADE (per event, vectorised) SHIELD
flows (NetFlow/IPFIX) tier 0 entity state (36 behaviour counters / source) policy (report | enforce)
HTTP (proxy/authz) tier 1 monotone tree prior + Mondrian conformal rules (any language, LLM)
JSON-RPC (chain nodes) tier 1' site-only anomaly (shape features, Fisher) enforcer (nft/iptables/netsh/
DB logs (6 engines) tier 2 GRU sequence network (per-source state) dry-run), TTLs
tier 4 per-source evidence: CUSUM, fast + slow posture audit (open ports)
tier 5 destination-flood evidence feedback (anti-poisoning)
tier 6 campaign tracker (distributed low-and-slow) NAT / IPv6 identity
HTTP HttpModel2 (byte n-gram net, site-conditioned) review queue, report
session stream tier, signatures A01–A22,
SQL-context analysis of parameters
DB DbNet + signatures + behaviour + provenance
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
β–Ό β–Ό
Go fast path (inline proxy / authz for nginx, Envoy, LLM bridge (MCP + REST) and the
HAProxy, Traefik, Caddy): signatures, model, blocklist operator console (English, approval-gated)
```
Every tier produces a score; every score becomes a **p-value against the site's own reference**; a tier alarms when
its p-value is under its share of the false-alarm budget. Families are named by transparent rules over the
behaviour counters (port walking = scan, the same service again and again with failures = brute force, a flood of
new sources on one destination = DDoS), with the learned family head only filling gaps.
---
## 3. The learned models
### 3.1 Tier 0 β€” entity state (behaviour counters)
For every source the engine keeps a small record updated per event (`dibaguard/flows/entity.py`): exponentially
decayed counters over three horizons (10 s, 2 min, 30 min) of flows, bytes, packets, and the *shares* of flows that
got no reply, were SYN-only, were reset, went to a never-seen port, went to a never-seen host, repeated an already
used (host, port), or were very short β€” 30 numbers β€” plus the gap to the previous flow, its moving average, and three
destination-side counters (flows to that destination, its no-reply share, its share of new sources). 36 features,
bounded memory (LRU over sources, 512 (host, port) keys per source). The same code computes training features and
runtime features, so they are the same numbers.
These counters are the representation every other tier reads. They are deliberately *scale-free* and *identity-free*:
no address, no absolute size β€” the reason the models transfer between networks.
### 3.2 Tier 1 β€” monotone gradient-boosted prior
A CatBoost model of symmetric (oblivious) trees over 24 source-side counters (8 behaviours Γ— 3 horizons), trained
with **monotone constraints**: more port walking, more failed connects, more repetition can only raise the score.
This was introduced after finding that unconstrained trees, trained on public datasets, scored a textbook SYN scan
*lower* than benign traffic β€” an artefact of how those datasets were captured. The constraint makes the prior
behave like a security analyst's intuition and removes that class of artefact. The trees are evaluated by our own
numpy evaluator (~320,000 flows/s per core; 16 KB file) and a Go port; the score is turned into a p-value against
the site's reference **per service Γ— source age** (Mondrian conformal, section 4.2).
### 3.3 Tier 1β€² β€” site-only anomaly
No labels at all: for each source-side *shape* feature (shares, not volumes β€” a busy but ordinary client is not
anomalous), the upper-tail p-value against the site's own reference is computed and the p-values are combined with
Fisher's method; the combined score is itself calibrated conformally. Pure volume (`flows`) and repetition are left
out on purpose: both drift for hours in benign traffic and would make the tier a flash-crowd detector. On held-out
networks this tier alone reached AUROC 0.92–0.996.
### 3.4 Tier 2 β€” GRU sequence network (SeqNet)
What one flow cannot show and even decayed counters only summarise, the *order* of a source's flows does: a scan
walks ports, brute force repeats one service with short failed connects, a beacon returns at a fixed gap.
```
per flow: 65 numeric features (log sizes/packets/duration/bytes-per-packet, no-reply, 18 TCP flag bits,
the 36 entity counters, gap flags) βŠ• port embedding (1,280 Γ— 16; exact for 0–1023, hashed above)
βŠ• protocol embedding (5 Γ— 4) β†’ 85 inputs
encoder: Linear 85β†’64, ReLU, Linear 64β†’64, ReLU
GRU: 2 layers, hidden 64, causal (one step per flow; the runtime keeps one hidden vector per source)
site: a context vector pooled from the site's own benign streams β†’ Linear 64β†’128 β†’ (Ξ³, Ξ²) FiLM on the
top hidden state: the same weights read every network relative to that network's normal
head: Linear 64β†’64, ReLU, Linear 64β†’40 (attack logit + family logits)
```
It runs only on *warm* sources (a few flows of history); its reference is drawn from warm sources only, so it is
never judged against first-contact traffic. Numpy and Go implementations agree to parity tolerance (a step costs
~8.6 Β΅s in Go at d = 24, kept at d = 64 for accuracy).
### 3.5 HTTP β€” HttpModel2 (site-conditioned byte n-gram network)
Requests are first **canonicalised** (`dibaguard/http/canon.py`): method and path, then query, body, cookie and
selected header fields as `q:k=v | b:k=v | c:k=v | h:k=v`, each value decoded to a fixpoint (URL encoding over
up to four rounds, `%uXXXX`, HTML entities, `\xNN`/`\uNNNN`, Unicode NFKC, SQL comment and whitespace folding), so
encodings cannot hide a payload from what comes next.
```
text β†’ byte n-grams of orders 2–6 (rolling FNV hash + splitmix64 finaliser, 262,144 buckets)
β†’ EmbeddingBag (mean, 48 dims, int8 with per-column scales) [the "bag" vector v]
βŠ• 7 side features (decoding depth, length, number of parameters, Persian share, non-ASCII, specials, digits)
βŠ• cosine distance between v and the SITE's mean bag vector
β†’ Linear 56β†’128, ReLU β†’ FiLM from the SITE context (Linear 128β†’256 β†’ Ξ³, Ξ²) β†’ Linear 128β†’1 (attack logit)
temperature 1.72 (calibrated); per-Host profile + per-Host conformal reference
```
The site profile is computed from a few hundred of the site's own benign requests (bootstrapped automatically from
the first requests the layer sees, rebuilt every epoch, one profile per Host when one layer protects many sites).
That is what lets one model serve a Persian shop, a WordPress blog and a JSON API: each is judged against its own
normal. Persian traffic is first-class (the side features, the Persian false-positive suite). The site's n-gram
*novelty* score exists in the model (`HttpModel2.novelty`) and was evaluated (AUROC 0.92 on WordPress vs 0.61 for
the plain model), but is **not** part of the live verdict yet.
### 3.6 HTTP session tier
A client's requests are also fed to the entity state as events of its stream (the "port" is a hash of the path),
so the same behaviour counters describe enumeration (walking ids with failures), scraping (walking pages, all
served), credential stuffing (one endpoint failing again and again) and L7 floods. The tier-1 model scores the
stream; **the tier has its own conformal reference** of the site's benign sessions (a request stream is not a flow
stream: a visitor reading ten product pages walks ten "ports", and judging it against flows would call every browser
a scanner β€” measured, and fixed in v2.5).
### 3.7 DbNet β€” the database query network
One small network for every query language DibaGuard reads (SQL dialects, CQL, MongoDB commands and filters, Redis
commands, Elasticsearch requests, Cypher). Its input is the query's **structure**: string literals become `'s'`,
numbers `0`, hex blobs `0x`, ids that mix digits and letters `h`, identifiers that are not part of a language (table,
column, key names) `x`, credential-like names `cred`, JSON keys keep their names only when they are language
(commands, `$operators`) or credentials; MySQL version-comments are unwrapped and inline comments reduced to a
marker. The network therefore judges what a query *does*, whatever the schema, and a scary word inside a properly
quoted value is just `'s'`.
```
structure β†’ byte n-grams 2–6 (same hashing as the HTTP tier, 65,536 buckets) β†’ EmbeddingBag (mean, 48, int8)
β†’ Linear 48β†’64, ReLU β†’ Linear 64β†’7 (benign, injection, rce, privilege, destructive, recon, unbounded)
```
Trained on a generated corpus (`scripts/db_corpus.py`): a probabilistic SQL grammar and templates for the normal
workloads of many application styles on 13 engines, and attack templates delivered *through* application queries
(numeric and string injection points) with obfuscations; n-gram dropout and label smoothing; evaluated on *held-out
templates* (attack techniques and application idioms never seen in training). Its threshold is set per database by
conformal calibration on that database's own normal queries (Ξ±/10 per query: databases see thousands a minute).
~80 Β΅s per query in Python batches; 2.4 MB.
### 3.8 What each learned part is trained on
| model | data | split used for the numbers |
|---|---|---|
| monotone prior, GRU | NetFlow-style corpora of public datasets (see section 9) | leave-one-dataset-out |
| HttpModel2 | labelled HTTP corpora + the ModSecurity 2025 archive's first 20 days | last 10 days (time split), unseen sites |
| DbNet | generated grammar corpus | held-out templates; independent lab generator |
The licence status of each source is audited in `docs/DATA_LICENSES.md` (section 9 summarises it).
---
## 4. Turning scores into decisions: calibration science
### 4.1 Conformal false-alarm control
For a score *s* and a reference set of the site's own benign scores *R*, the p-value is
`p = (1 + #{r ∈ R : r β‰₯ s}) / (1 + |R|)`; alarming when `p < Ξ±` gives a false-alarm rate of at most Ξ± on traffic
exchangeable with the reference β€” whatever the model, whatever the training data. Every tier is calibrated this
way; the budget Ξ± is split across tiers (half to the per-event tiers, the rest to evidence, destination and
campaign tiers) so the total stays within Ξ±.
### 4.2 Mondrian cells: service Γ— source age
A first flow of any client looks different from its hundredth, and a DNS flow from an HTTPS one. References are kept
per **service Γ— age bucket** (age = how many flows the source has really shown: 1, 2–5, 6–20, 21–100, 101–500,
>500); a young bucket with too little data is pooled with its neighbours rather than abstaining (so a slow scanner
living in a thin bucket is still judged); only a source's very first flow abstains.
### 4.3 References that follow the site β€” and do not ratchet
Every 30 minutes all references are rebuilt at once from the last two hours of traffic, mixed with an immutable
*anchor* (a sample of the first clean calibration), so the reference follows the site but cannot drift without
bound. Two failure modes had to be designed out, and both were measured:
* **The ratchet.** Leaving every alarmed event out of the next reference truncates its upper tail; the next
threshold drops; more benign events alarm; they are left out too. Measured in the low-and-slow lab: benign alarms
went **1.8% β†’ 6% β†’ 10% β†’ 15% β†’ 18% β†’ 21%** of source-minutes over six hours. Fix: an un-named soft alarm at the Ξ±
budget *is* the benign tail and stays in the reference.
* **Self-poisoning.** Keeping everything in lets a weakly-detected attacker teach the reference to accept it.
Measured: an evolving scan's recall went 1.0 β†’ 0 over twelve waves, and an AI scraper that was not yet alarmed
became 20% of the session reference within one wave. Fix: (a) every event of a source whose alarms *keep coming*
(a decayed count reaching 3 over the window) stays out; (b) **no single source may write more than ~1% of a
reference** (busy benign sources are subsampled, not excluded).
With both, the hard lab's twelve evasion waves keep every flow attack at 1.0 recall while benign alarms fell by an
order of magnitude.
### 4.4 Drift or poisoning? The drift guard
Before each epoch's reference is adopted, its upper tail is compared with the anchor's: if more than 3% of the
window sits above the anchor's 99th percentile, the guard asks *who put it there*. A shift spread across many sources
is a site that changed (a release, a new client population) β€” adopted and reported. A shift driven by a handful of
sources (the top 20 sources owning more than half of the tail, or fewer than 30 sources in it) is an attacker
"boiling the frog" β€” their rows are held out and they are logged.
### 4.5 Evidence: CUSUM over a source's stream
A slow attacker never produces one very unusual event; it produces many slightly unusual ones. Each source carries
two evidence accumulators (time constants 2 min and 30 min) over `βˆ’log p` of its suspicious events (p < 0.5), with a
one-sided CUSUM allowance equal to the benign mean plus one standard deviation of that quantity, floored at zero β€”
so chatty benign clients and flash crowds never accumulate, while a scan at one probe a minute does. The evidence is
itself judged against an out-of-sample reference.
### 4.6 Destinations, and campaigns
* **Destination tier**: a destination flooded by many new sources (distributed DoS) is detected from the
destination's own evidence; a flow is *acted on* only if its own source piles on (several flows within ~10 s) β€” a
visitor who opened one page of the attacked server is watched, never rate-limited (fixed in v2.5 after the lab
showed benign visitors being rate-limited during an SSH botnet attack).
A pool of bots that keeps reconnecting is no longer "new" after its first contact, so a volume far over the
destination's norm (2.5Γ—) carried by *young* sources also counts; while the destination evidence reference is
still filling (a small network has few destinations), only the unmistakable flood β€” three times the calibrated
peak, young sources β€” does.
* **Campaign tier** (`dibaguard/campaign.py`): a 3,000-proxy credential-stuffing run or a 400-machine SSH botnet
guessing once per half hour per machine has no suspicious source at all. The tier fingerprints events
(flows: service Γ— failed-connect or short-auth-session; HTTP: host Γ— method Γ— path template), counts **distinct
failing sources per fingerprint per 5-minute window**, compares with that fingerprint's own benign history
(median/MAD, never tighter than Poisson; a pooled prior while young), and runs a one-sided CUSUM over windows so a
slow campaign adds up over hours; a strong spike fires at once. Members are the sources that failed on an active
fingerprint and **never succeeded** on it β€” a user who mistyped a password and then logged in is not a member.
Internet background radiation is part of every public site's normal and is in the reference; only a departure
from it is a campaign. Every failing source counts towards *detecting* a campaign (logging in once first cannot hide
it); a source that succeeded is shielded from *membership* only for one slip, for an hour, while it is not mostly
failing. In a network with no failing background at all, sixteen distinct failing sources in a window stand out.
Three corrections came out of the independent validation (2026-10-31): a completed connection to a port now also
answers for that port's failed-connect fingerprint (the two are separate keys, so an ordinary client's one failed
connect during a live scan used to make it a block-safe member: 20.7 % of benign source-minutes on SIMARGL 2021);
members must be shaped like a campaign's sources (young, or failing at least half the time β€” on HTTP: brand new, or
failing most requests); and a fingerprint that stays active is adopted slowly β€” one active window in four joins its
own history and the CUSUM is capped β€” so a lasting benign level shift ends within about two hours instead of never.
* **Global scan tier**: the site-wide rate of unanswered / half-open flows is judged against the site's **own**
one-hour level (floor + 4Γ—, seeded from the calibration window), and while it is hot only scan-shaped sources are
flagged; at a milder surge (1.5Γ—) only young sources that do nothing but fail. An absolute floor alone alarmed about
half of all benign source-minutes on real traffic whose normal includes many unanswered flows (validation V-22).
* **Deterministic behaviour rules** next to the statistical tiers, for sources the site has not known for long
(< 500 flows; an attacker is caught long before that): a *slow scan* (β‰₯ 20 attempts on the 30-minute horizon, β‰₯ 80 %
to never-used endpoints, β‰₯ 80 % failing) and *sustained guessing* on an interactive login service (β‰₯ 120 short
sessions on the 30-minute horizon, β‰₯ 80 % to an endpoint already used: SSH / RDP / telnet / FTP / VNC β€” 15 guesses a
minute for half an hour was invisible before). The age gate came from real traffic: in CSE-CIC-IDS2018 the flow
exporter cuts established users' long RDP sessions into many short records (~82k benign records flagged without
it), and established hosts' unanswered lookups walk "new" endpoints too.
### 4.7 Established machines
Real networks are full of legitimate machines that repeat themselves at a high rate: SCADA servers polling PLCs every
second, monitoring agents, API clients, CDN edges, workstations talking to a proxy, directory and file servers. On
networks unlike the training data the unfamiliar-network lab showed them being named "brute force", excluded from the
reference, and β€” once their pace changed β€” alarmed (and in one case blocked) for good. Two rules fixed it:
* *Brute force* means repetition **and** a sign of failure (no reply, reset) or an attacker's rate **on an
authentication service**. Many connections to a proxy, a broker or an API without failures are a busy client. A
*short* flow (under 10 ms, one or two packets) is not a failure: every DNS / NTP exchange is that short, and counting
it made office workstations "brute forcers" (3–5 blocked per run before the fix, 0 after).
* A source with hundreds of flows of history whose flows show **no failure at all**, named only for repeating itself,
is *established*: it stays in the reference, its purely statistical alarms (prior, sequence, evidence β€” its pace,
not its shape) are not alarms, and it is never auto-blocked. A change of shape, a flood, a campaign still alarm. The
exception never applies to services where repeated short sessions are password guessing (SSH, RDP, telnet, FTP, VNC,
databases, mail logins).
---
## 5. HTTP edge: signatures and SQL-context analysis
### 5.1 Request signatures (playbook A01–A22)
What needs no statistics is caught by explainable, named signatures over the canonical text β€” JNDI/Log4Shell,
CMS exploit paths, SQL injection, NoSQL operator injection, traversal/LFI, command injection, XSS, SSTI/XXE/SSRF,
sensitive-file probes, and AI crawlers that declare themselves β€” each with a family and a default action (block or
challenge, overridable by policy). The same signatures run in Go (RE2, with exact per-signature prefilters so benign
requests skip every regex β€” a browser User-Agent costs ~4 Β΅s) and a parity test proves Python and Go agree on every
fixture.
**One canonical text, the same on every path.** Canonicalisation (`http/canon.py`, `http/parse.py`) is where an
evasion lives or dies, and the independent validation found it was the weakest point (V-01…V-08). Since then: SQL
comments are folded only outside quoted literals and the unfolded text is judged too (a `/*' union …*/` wrapper can no
longer delete live code); `#…` / `--…` line comments are removed *before* line breaks are folded (`union#x⏎select`);
tab / newline inside a URL scheme are deleted as browsers do (`javaβ‡₯script:`); every occurrence of a duplicate JSON key
and every value of a repeated header is judged; nothing is truncated silently β€” every multipart field is its own
value, whole values are written within a 32 KB budget and the rest becomes an `x:oversized` part that is itself
suspicious. The Go fast path now builds the **byte-identical** text (`go/dibaguard/canon.go`, `parse.go`, with
Python's NFKC and HTML-entity tables generated into Go): on 1,398 parity requests text and depth are identical, so the
sidecar judges the same text the inline path saw. A canonicalisation fuzz of 3,000 cases (11 payload families Γ— 18
placements Γ— transforms): Python and Go block 99.3 % each, their verdicts diverge on 0 % (32.8 % before), and 0.7 % β€”
case-variant entity names browsers do not decode and multipart names broken by a newline β€” are missed by every path
(12.7 % before). Regexes that were quadratic on crafted input are linear-time matchers (`shield/rx.py`).
### 5.2 SQL-context analysis (A22)
The database tier's understanding brought to the edge (`dibaguard/http/sqlctx.py`). Every parameter β€” query string,
body, cookies, the headers attackers like (User-Agent, Referer, X-Forwarded-For…), and *keys*, because payloads hide
in keys β€” is decoded as a server would (URL Γ—3, HTML entities, `%u`, `\x`, `\u`, null bytes), passes a gate (a
character that can close a literal or cut a statement, a word only SQL uses, or a boolean joined to a number or
quote), and is then **placed into the contexts applications build queries with**: numeric, single-quoted,
double-quoted (judged as a string with the quotes swapped), parenthesised, LIKE. The resulting query is judged by
the database tier's signatures on its literal-stripped structure: a value that stays inside its quotes is data
(O'Reilly, Persian text, JSON, URLs); one that breaks out into a tautology (including arithmetic ones like
`5*5=25`), a UNION extraction with an attack's fingerprint, a stacked statement, a time delay, an error-based
extractor, a scalar sub-query or a comment cut is an injection β€” named A22 and blocked. DbNet runs as a second
opinion on values that speak SQL; a hit only DbNet sees is soft (challenge), and a parameter whose DbNet-only hits
come from many different clients with never a signature is learned as that site's own syntax (a filter language).
Values are cached (user agents and cookies repeat endlessly): ~37 Β΅s per request; the work per request is bounded β€”
every field, in overlapping 960-character windows, within a 6,144-character budget β€” and when the budget runs out the
request gets a soft verdict (alarm and challenge), never a silent pass. The hard part of A22 also runs inline in Go
(`sqlctx.go`, verdict-identical on the fixture), so `' or 1 in (1,2)-- -` no longer waits for the sidecar. The
fallback "a literal closed by the payload" needs real SQL between the break-out and the comment or `;` in string
contexts: English prose with an apostrophe and `--` (`I'm happy -- 5 stars`) was blocked as SQLi before (validation
V-18: 146 users per 1,000 per day in a simulated shop; 0 now).
Head-to-head with **libinjection** (the SQL-injection engine behind ModSecurity CRS rule 942100), rule engine against
rule engine on the same real requests (`guard_jobs/compare_waf.py`, run on Kaggle): on the visible SQL payloads of the
ModSecurity 2025 archive DibaGuard catches every request libinjection catches and 24 more; on the 80,234 benign
zanbil.ir requests it raises no alarm where libinjection raises 12; on SR-BH 2020 it catches more. The archive was
labelled by CRS itself, so the comparison is, if anything, tilted towards libinjection.
### 5.3 Payload provenance (DB ↔ HTTP)
When an injection reaches a database through an application server, the database tier sees the application's
address. The layer keeps a short ring of recent decoded requests and finds the web request whose tokens and literals
match the query's payload within a few seconds β€” and acts on *that* client. The application server is never blocked.
---
## 6. The database tier
`dibaguard/shield/database.py` understands 13 engines (PostgreSQL, MySQL/MariaDB, MSSQL, Oracle, CockroachDB,
ClickHouse, MongoDB, CouchDB, Cassandra/ScyllaDB, Redis, Memcached, etcd, Elasticsearch/OpenSearch, Neo4j, InfluxDB,
plus Kafka/ZooKeeper ports for the posture audit) and reads six log formats as they are written (PostgreSQL stderr
log, MySQL general log with thread β†’ client tracking, MongoDB JSON log, Cassandra audit log, Redis MONITOR,
Elasticsearch audit JSON). Three views of every query, combined:
* **signatures** on views that remove *data*: SQL/CQL/Cypher literals, JSON string values (keys and `$operators`
kept), and the arguments of ordinary key-value commands (only CONFIG/SLAVEOF/EVAL/MODULE/ACL/FLUSH… are read with
their arguments). Families: rce from the database (COPY … TO PROGRAM, xp_cmdshell, CONFIG SET dir, `$where`,
UDFs, LOAD DATA / INTO OUTFILE, Lua escapes, ES scripts, APOC), privilege escalation, destruction and ransom
notes, injection, credential/catalog recon, unbounded reads.
* **DbNet** (section 3.7), thresholded per database.
* **behaviour per client**: authentication-failure bursts; rows read over three times the client's own busiest
minute *and* five times its peers' current median (a sales surge lifts every app server together; a dump makes one
stand out), and the same per **table** β€” a paged dump of `customers` through the application's own connection is
+13 % of the application's rows but five times its reads of that table (validation V-21, caught since); clients
that never talked to this database; and β€” the key to precision β€” query *shapes* the
applications run in their normal workload are trusted for the soft families (an injection is by definition a
structure the application did not write).
Policy: every DB family maps to an action (`db_rce`, `db_privilege`, `db_destructive`, `db_injection`: block;
`db_exfil`: rate-limit; `db_recon`, `db_new_client`: monitor). **An application server is never blocked at the
network level** (that would take the application down): its alarm carries the exact remediation to run on the
database (`pg_terminate_backend`, `KILL`, `db.killOp`, `CLIENT KILL`, `nodetool`…), and payload provenance acts on
the web attacker behind it. Report mode records everything and acts on nothing.
---
## 7. The shield: policy, enforcement, identity, feedback
* **Policy** (`shield/policy.py`): `mode` report | enforce, Ξ±, per-family actions, minimum action score, TTLs,
allowlist, posture rules, database section. Report mode is the default.
* **Enforcer** (`shield/enforce.py`): nftables, iptables, Windows Firewall (netsh) or dry-run, with TTLs and an
audit log; IPv6 blocks cover the address's /64 (rotation inside a /64 is free for an attacker).
* **When to act**: only with history or a hard signal (`block_ok`); otherwise a block *or a rate limit* becomes a watch
(flows) or a challenge (HTTP) β€” a first-contact source raising only a soft behavioural tier, a visitor caught in a
flood it did not pile onto, an IoT device on a flooded broker are never limited. An enforced action takes its *name*
from the alarms that make it enforceable (one event's confidence and another event's name are no verdict).
**Shared addresses** β€” the CGNAT range, or an address seen with six or more user-agents within 15 minutes β€” are
judged per user behind them (sub-entities) and are challenged, not blocked, as a whole; the attacker's own requests
are still refused inline. An address whose recent traffic is mostly alarmed or failing (β‰₯ 70 % of β‰₯ 20 requests in
~10 min) is judged whole and is not exempted: eight rotated user-agents no longer buy one stuffer a challenge.
**IPv6** sources are judged as their /64 (detection state as well as blocks), so a fresh address per request inside
one subscriber's /64 is one source. **Machine clients**: search-engine crawlers matched by user-agent *and* their
published ranges are watched, never acted on as an address; a behavioural challenge on a client that is not a
browser becomes a rate limit (a JavaScript challenge would cut it off); an established client polling the same
endpoints with every request answered does not trip the session tier.
* **Bounded state that an attacker cannot flush or rewind**: every per-source table evicts a fresh entry before one
that has earned state (8+ flows, evidence, risk); an out-of-order event never moves a clock back and counts with
its weight at the record's clock, exp(βˆ’lateness / Ο„).
* **Posture audit** (`shield/posture.py`): what the host exposes that the policy did not ask for (P1–P5: unexpected
public listeners, databases/Redis/Docker facing the internet, plaintext management, enforce mode without a
firewall, public chain RPC), closed automatically only when the policy says so.
* **Rules in any language** (`shield/rules.py`): "block anyone brute forcing ssh over 30 attempts per minute"
β€” interpreted by the built-in bilingual parser or by any LLM
through a fixed schema, shown back as a precise rule before installing, enforced from the first second (no
learning window). Behavioural conditions (flows/requests per minute, new ports per minute, no-reply share, repeat
share) are filled from the engine's counters.
* **Feedback** (`shield/feedback.py`): confirm / reject / always-ok, with immediate effect (lift, reset evidence,
re-learn the site). Guarded against poisoning: clearing a source whose alarms carry hard evidence needs a second,
explicit confirmation; a burst of clears (more than 50 an hour) needs confirmation; nothing wider than a /24 (/48)
can be allowlisted through feedback; one verdict teaches at most 20 requests; the journal is a hash chain, so an
edited or deleted verdict is detected.
* **Review queue**: hard alarms always; soft ones only when sustained; many sources deviating together without an
attack shape collapse into one `site:drift` item.
---
## 8. Runtime, integration, operations
* **Go fast path** (`go/dibaguard`): one decision function shared by the inline reverse proxy (`dibaguard-proxy`) and
the external-authorization service (`dibaguard-authz`) for nginx `auth_request`, ingress-nginx, Envoy `ext_authz`,
Traefik ForwardAuth, Caddy forward_auth and HAProxy (Lua auth-request, or a Runtime-API blocklist syncer so HAProxy
drops blocked sources in its own data path). Client identity: right-to-left walk over trusted proxies only,
`Forwarded:`, PROXY protocol v1/v2, IPv6 normalisation and /64 grouping; malformed escapes and `;` kept as data so
they cannot hide a payload. Tested against real nginx 1.30.6. See `docs/INTEGRATIONS.md`.
* **LLM bridge** (`dibaguard/llm.py`): every capability is a tool, served over MCP (stdio) and REST; state-changing
calls and re-calibration need the console token and a CSRF header; traffic feeds that carry sources need the feed
token (`DIBAGUARD_FEED_TOKEN`, sent by the Go proxy and authz service), so nobody who merely reaches the port can
make the layer block an address of their choice.
* **Operator console** (`dibaguard/console.py`, `docs/CONSOLE.md`): overview, incidents with evidence and
remediation, review queue, rules (interpret β†’ install), policy (switching to enforce requires typing ENFORCE),
databases, posture, and *Teach*: connect any LLM (OpenAI-compatible or Anthropic) and talk to the layer in any
language; the LLM only *proposes* changes, the operator approves each one.
* **High availability** (`dibaguard/state.py`, `docs/HA.md`) and **performance** (`docs/PERFORMANCE.md`):
snapshots without pickle, shared enforcement between replicas, source-affinity routing, measured scale.
* **QA** (`scripts/qa_all.py`): every test file, Go tests and builds, the sidecar over REST and MCP, the proxy end to
end; the private documentation Space is rebuilt from the current numbers (`scripts/make_space_docs.py`).
---
## 9. Data and licences
The audit in `docs/DATA_LICENSES.md` classifies every source. In short: several public corpora the early models
were trained on (the NetFlow v2/v3 collections and re-uploads of them, some mirrored copies, several payload lists)
are **not** cleared for commercial use; the original CIC releases (with citation), SIMARGL 2021, LUFlow from its
author, SR-BH 2020, the ModSecurity 2025 archive and our own generators are. A licence-clean retraining of the
flow, sequence and HTTP models from cleared sources only is part of v2.5's work (`docs/CLEAN_MODELS.md`). The DB
tier and the SQL-context analysis use no third-party training data at all.
---
## 10. Ideas that make it work (summary)
1. **Behaviour, not identity**: scale-free, identity-free stream counters as the shared representation.
2. **Calibrate at the site**: conformal p-values against the site's own traffic, per service Γ— source age.
3. **Site-conditioned networks** (FiLM on a context pooled from the site's own normal) for both flows and HTTP.
4. **Structure, not text**: SQL-context analysis and DbNet judge what a value *does* to a query.
5. **Clean but complete references**: keep the benign tail, keep sustained sources out, cap every source's share,
anchor every epoch, and ask *who* moved the tail before adopting drift.
6. **Many scales**: event, stream, half-hour, destination, site, fingerprint-across-sources (campaigns).
7. **Act carefully**: block only with history or hard evidence; never block shared addresses or application servers
as a whole; attribute injections to their web source.
8. **Humans and LLMs in the loop, safely**: rules in any language with a precise read-back; approval-gated LLM
proposals; a feedback loop that cannot be poisoned by a click or a chat.
9. **Attackers fail; busy machines don't**: failure signs separate brute force from polling, and established
failure-free machines are trusted for their pace while still judged for their shape.
10. **Test where it hurts**: every number comes from labs written to break the system (evolving attackers, internet
radiation, unfamiliar networks, an independent red team), and every fault they found is fixed and kept as a test.
---
## 11. History: what was built, what failed, what changed
| version | what | lesson |
|---|---|---|
| v1 | per-flow tree models on public datasets; HTTP byte n-gram model | in-dataset 0.99 AUROC, 0.47–0.93 on unseen networks: per-flow features do not transfer |
| v1.5 | entity-stream features | alone they transfer (held-out AUROC 0.62β†’0.99 on one testbed, 0.47β†’0.99 on another); raw flow fields hurt |
| v2 | GRU sequence net with site context; site-conditioned HTTP model; monotone prior; site-only anomaly; conformal per tier | unconstrained trees scored scans *below* benign β†’ monotone constraints |
| v2.1 | evidence per source, Mondrian service Γ— true age, epoch re-calibration, shield (policy, enforcer, posture, playbook, JSON-RPC), Go proxy, LLM bridge | an FPR ratchet over hours β†’ epoch re-calibration with anchor |
| v2.2 | feedback, multilingual rules, destination tier, slow evidence, red-team lab | stale feedback inflated precision β†’ fresh per run, reject TTL |
| v2.3 | hard lab (evolving attacker), zero-mean CUSUM, newborn rules, global tiers, platforms lab, per-Host HTTP profiles, signatures A15–A21 + Go RE2 port | a single HTTP profile for many sites flagged 18% of one site's traffic β†’ per-Host profiles |
| v2.4 | database tier (13 engines, 6 log formats, DbNet, provenance), SQL-context analysis at the edge | real SQLi recall 0.536 β†’ 0.984 on visible payloads; the old 0.539 was measured on CRS labels that include brute-force passwords and payload-less rows |
| v2.5 | campaign tier, low-and-slow lab, unfamiliar-network lab, drift guard, reference hygiene (ratchet + poisoning), session reference, destination-tier action gating, NAT/CGNAT/IPv6 identity, feedback anti-poisoning, authz integrations, console, HA, performance, licence audit and clean retraining, independent red team | the stricter labs found real faults (ratchet, self-poisoning, collateral rate-limits, mis-calibrated session tier) β€” each fixed and re-measured |
| v2.6 | independent validation of three properties (22 findings), every one fixed at its root; Go canonical text byte-identical to Python; A22 inline in Go; feed token; per-table exfiltration; slow-scan and sustained-guessing rules; bounded, un-rewindable state | numbers can hide in arithmetic: a float32 rounding tie alarmed 99.7 % of CRS negatives, a reference size between n_needed and 1/Ξ± silently disabled a tier, and two fingerprints of one port made ordinary clients members of a live scan campaign |
### Independent red team
An independent red team (an agent that did not build the system, working only through the code and the Python API,
offline) attacked v2.5 for evasion, cascade bypass, poisoning and resource exhaustion and reported ten findings with
reproducible tests (`docs/REDTEAM_FINDINGS.md`, `tests/redteam/`): SQL tautology spellings outside the signatures
(between / in / is true / regexp / xor / bare `or 1`), modern XSS event handlers, single-step traversal to secrets,
missing command names, EVAL-wrapped Redis RCE and Mongo operator injection on identity fields, slow database
exfiltration under the 5-minute horizon, campaign immunity bought with one successful login, a feedback guard based on
a hand-written family list, payloads in headers the model text left out, and a crafted request costing ~330 ms. All
ten are fixed; their tests now run as regression tests. The defences that held (canonicalisation against ten classic
obfuscation layers, coverage of every common SQL sink, the journal's hash chain, the allowlist width cap) are listed
with numbers in the same document.
### Independent validation: correctness, reliability, independent data
A second, independent team (an agent that did not build the system) validated three properties
(`docs/VALIDATION_REPORT.md`, tests in `tests/validation/`): **security correctness** (can the engine be bypassed β€”
canonicalisation fuzz of 3,000 cases, Go/Python parity, header/body/JSON smuggling, state attacks: LRU flushing,
late records, reference poisoning, identity tricks, the sidecar's feeds), **detection reliability** (multi-stage
kill chains, and harm to legitimate users over 26 simulated hours of a shop), and **independent validation** on data
and environments nobody here designed (the OWASP CRS regression suite, real benign and attack HTTP traffic, public
flow captures run on Kaggle). It reported 22 findings, 10 of them high. All were fixed at the root and every repro
became a regression test; the re-measurement:
| measure | before | after |
|---|---|---|
| fuzz: Python / Go inline block | 72.5 % / 68.4 % | 99.3 % / 99.3 % |
| fuzz: Python–Go verdicts diverge / missed by every path | 32.8 % / 12.7 % | 0.0 % / 0.7 % |
| credential stuffing with 8 rotated user-agents / inside one IPv6 /64 | 300/300 served, never blocked | blocked after 40 / blocked |
| one attack request in the HTTP bootstrap; attacker-chosen `Host` profile | model-only detection 87.5 β†’ 68.8 %; 0 % | unchanged / 100 % flagged |
| SSH guessing 15/min for 30 min; paged dump of `customers` via the app | 0 alarms; 0 alarms | caught; caught |
| legitimate users blocked / challenged per 1,000 per day (simulated shop) | 146 / 180 | **0** [0, 0.3] / 50.5 |
| partner API clients and the search crawler challenged | all | none |
| English review sentences with `'` and `--` blocked | 16/16 | 0/16 |
| benign source-minutes alarmed on real flows (CSE-CIC-IDS2018 / SIMARGL 2021) | 49.6 % / 43.8 % | 6.8 % / 24.1 % (1.0 % without the global tiers) |
Two faults were found while re-testing the fixes and are fixed too: scores equal up to float32 rounding were treated
as different (one unit in the last place over a reference full of identical scores is p = 1/(n+1): the session tier
alarmed 99.7 % of CRS negative tests on the intermediate tree, 7.3 % after), and a reference whose size lies between
the PAC minimum and 1/Ξ± returned an infinite threshold (a tier silently off).
---
## 12. Running and testing
```bash
# the sidecar (start in report mode with the dry-run backend; switch to enforce only after a review)
python -m dibaguard.llm http --models models --port 8787 --policy policy.json --backend dryrun
# the console: http://127.0.0.1:8787/console (SSH-tunnel it; never expose it)
# Go fast path: dibaguard-proxy (inline) or dibaguard-authz (behind nginx / Envoy / HAProxy / Traefik / Caddy)
python scripts/qa_all.py # everything that can be verified in minutes
python scripts/qa_all.py --labs # plus every lab
python scripts/benchmark_all.py --run # the reproducible benchmark (several seeds) β†’ bench/benchmark.{json,md}
```
Labs: `redteam_lab.py` (six waves of the playbook), `redteam_hard.py` (an attacker that evolves to evade over twelve
waves, hostile benign traffic), `redteam_platforms.py` (WordPress, Joomla, Drupal, JSON API, generic + chain RPC),
`redteam_db.py` (six databases, twelve scenarios, real log formats), `redteam_slow.py` (distributed low-and-slow
campaigns among internet background radiation), `redteam_networks.py` (OT/IoT, office, multi-tenant hosting), and
`eval_sqli_http.py` (real production data). All of them run in memory on synthetic or archived data; nothing is sent
to any host.
---
## 13. Results
*(This chapter is generated from `bench/benchmark.json` and the evaluation reports when the document is built.)*
{{RESULTS}}
---
## 14. Limitations (honest)
* Payload inspection needs the traffic in clear text (at the TLS-terminating proxy or from logs); the behavioural
tiers need only flow metadata, so encrypted traffic is covered for behaviour, not for payloads.
* Steady-state benign alarm rates in the strictest lab are a few times the 10⁻³ budget during warm-up hours and
around it afterwards; a longer calibration (a day rather than two hours) is recommended.
* The IDOR / business-logic enumeration that uses the application's own query shapes is invisible to the database
tier by design (the HTTP session tier challenges it).
* DbNet alone generalises to unseen *injection* techniques; for unseen RCE/privilege/destructive forms the signatures
carry the detection.
* The site n-gram novelty tier is evaluated but not live; online learning of model weights is deliberately not done
(retraining is offline, fed by the feedback export).
* On public flow captures whose benign traffic differs strongly from the calibration window (an attack burst that
changes the whole network's shape, or unidirectional records), the realised benign source-minute alarm rate is
still above the 10⁻³ budget (see the independent validation above); the labs meet it.
* A slow *distributed* scan among internet background radiation is found by the campaign tier in 6–17 minutes (seconds
while an absolute global floor alarmed every failed connect site-wide β€” which on real traffic meant about half of
all benign source-minutes).
* Python state costs ~3–3.6 KB per tracked source (the design budget is 300 bytes): size `max_entities` to RAM, or put
the Go tiers in front (validation V-17, performance B9). Re-calibration still runs on the hot path (B2).
* The licence-clean network models can replace the shipped ones (equal or better on every GREEN network neither saw,
`docs/CLEAN_MODELS.md`); the licence-clean HTTP model cannot β€” it collapses on applications it never saw β€” so a
commercial build has no licence-clean HTTP model yet.
* Several early training corpora are not cleared for commercial use (section 9); the clean retraining replaces them.