🛡️ IronJean v2.6 ModernBERT WAF - Vectorized Landmark Pooling
IronJean WAF v2.6 is an enterprise-grade, transformer-based Web Application Firewall (WAF) classification model engineered on top of ModernBERT-base and purpose-built for REST API Gateways and modern backend microservices.
It combines Vectorized Landmark Pooling, Multi-Pass Recursive Anti-Evasion Normalization, Exploit-Aware Network Landmark Anonymization, and Syntax-Aware Sliding-Window Chunking with Early-Exit, leveraging ModernBERT's 8,192-token context window (RoPE + Flash Attention / Unpadding) to inspect complete HTTP headers and arbitrarily large API request bodies (> 8,000 chars / > 8,192 tokens) without truncation blindspots—delivering deterministic, millisecond-level threat detection across structured API payload trees without lexical keyword overfitting.
Unlike traditional regex rules, legacy 512-token BERT classifiers, or simple [CLS] sequence transformers, IronJean WAF is specifically tailored to the semantic grammar of REST API protocols (REST/JSON, GraphQL, XML/SOAP, Form/Multipart, gRPC, OAuth2/JWT) while achieving a benchmarked 99.9994% Global Accuracy ("Five Nines") (99.9988% Precision / 0.0012% FPR, 100.0000% Recall / 0.0000% FNR — only 1 FP and 0 FN across 160,500 payloads), 100.00% Precision (0 FP) across all 5 external WAF benchmarks (100.00% Accuracy on both waf-bench and gotestwaf), and 227/227 PASS on live Postman-Echo gateway integration tests (15.51 s, 167 ms E2E on Java DJL ONNX FP16 CUDA), sourced exclusively from fully cleaned open-source and synthetic datasets as part of my independent research.
Interactive DevSecOps Playground: Try IronJean v2.6 Live on Hugging Face Spaces — submit JSON HTTP requests online on ZeroGPU with live HTTPNormalizer v2.6 inspection, sliding-window chunking, and curated OWASP/CVE presets.
Supported Attack Vectors: 22 attack families, modern 2024–2026 CVEs, and evasion techniques natively detected out-of-the-box by IronJean WAF v2 across all 4 HTTP landmarks (METHOD, URI, HEADERS, BODY).
Zero-Forgetting WAF Domain Adaptation: ModernBERT Landmark Pooling + WiSE-FT + Swagger Synthesizer ingests any local or remote Swagger 2.0 / OpenAPI 3.x contract, endpoints, path parameters, query types, and JSON/XML/Form schemas.
🛠️ Pre-Trained WAF Baseline & Transfer-Learning Checkpoint: Rather than a rigid black-box rule engine, IronJean v2 is designed as an open WAF baseline checkpoint. Having already learned HTTP landmark structure and common OWASP exploit patterns, it provides a solid starting point for Shadow Mode evaluation, threshold calibration, or lightweight domain adaptation (e.g., via WiSE-FT) on your own production telemetry.
🆕 News notes v2.6 - 22/11/2026
- Syntax-Aware Sliding-Window Chunking with Early-Exit (
modeling_ironjean.py):- Adds
IronJeanWAFClassifier.build_sliding_windows()and nativeIronJeanWAFPipelinechunking for oversized HTTP bodies (> 8,000 chars, up to32overlapping chunks /~205 KB+plus an anchored extreme tail window) with zero overhead on standard requests (<= 8,000 chars). - Snaps chunk boundaries to JSON/XML/Form/Multipart structural delimiters, wraps split fragments in balanced syntax containers (eliminating truncated-JSON/XML breakout false positives), short-circuits immediately via Early-Exit once any chunk crosses the attack threshold, and adds a
_NormalizedLandmarkStrsentinel guaranteeing single-pass normalization.
- Adds
- Upgraded
HTTPNormalizerv2.6:- Fail-Closed JWT Validation & Exploit Unpacking (
is_healthy_jwt/normalize_healthy_jwts): Enforces strict JSON-object payload verification and signature checks on JWTs, blocks malformed or non-UTF-8 JWT-shaped credentials from falling through to opaque Bearer acceptance, and unpacks unhealthy JWT segments via lossy Base64URL decoding so ModernBERT inspects decoded attack claims directly. - Head + Middle-Exploit + Tail Header Guard (
> 512 chars): Replaces prefix truncation with a 3-window preservation guard (head + detected middle exploit excerpt + tail), defeating> 512-char header padding bypasses. - New Anti-Evasion Decoders & Zero-ReDoS Hardening: Adds consecutive HTML numeric entity run decoding (
HTML_NUMERIC_ENTITY_RUN_REGEX,>= 3consecutive&#x..;/&#..;→ printable ASCII32..126incl.<and>), extends<...XSS tag decoding (link,meta,style,marquee,video,bgsound), decodes literal shell-tab evasion (SHELL_TAB_EVASION_REGEX, e.g.ls\t-l\t/→ls -l /while preserving Windows paths such asC:\temp), introduces Content-Type-awaredecode_plushandling (preserving literal+in JSON/XML/Multipart/User-Agent andC++in queries), bounds slash-delimited Base64 scanning to O(k) linear complexity (eliminating O(k²) CPU DoS), and enforces 1:1normalize_sequence()↔serialize_http()round-trip parity.
- Fail-Closed JWT Validation & Exploit Unpacking (
- Upgraded
test_hf.pyv2.6:- Integrates
IronJeanWAFClassifier.build_sliding_windowsas a Single Source of Truth across both PyTorch SafeTensors and ONNX Runtime (FP32,FP16,INT8) inference loops and pipeline checks, printing per-request chunk telemetry ([chunks=k/N]). - Expands the live evaluation suite to 13 OWASP & Long-Payload Scenarios with a
21.5 KB(8,469unique tokens /11,932processed tokens across4chunks) Benign JSON Batch and a21.5 KB(21,553 chars) Needle-in-a-Haystack SQLi@ENDtest (plus a 3rdpipeline()check), and hardens cross-platform Linux/WindowsCUDAExecutionProviderdetection.
- Integrates
- Contrastive Technical Markdown/LaTeX Immunity & URI Rebalancing
v40:- Adds 50/50 contrastive technical documentation blocks inside structured
text/markdownandtext/plainbodies containing inline LaTeX math (`$...$`) and backticked identifiers (`id`,`user_id`,`status`) while strictly preserving 0 Safe backtick/LaTeX leaks in URIs, headers, JSON, forms, and multipart payloads—achieving zero false positives on technical Markdown documentation while maintaining> 99.99%RCE command-substitution blocking. - Rebalances URI sub-resource word tails (
/{base}/{id}/{word}) and root short-key queries (/?<short_key>=v) to ~50/50 parity, achieving 99.9994% Global Accuracy (1FP,0FN) internally and 100.00% Precision (0FP) across all 5 external WAF benchmarks (includingshengqin-waf0FP /0genuine exploits missed).
- Adds 50/50 contrastive technical documentation blocks inside structured
🆕 News notes v2.5 - 18/11/2026 (continued)
- Upgraded model
SafetensorsFP16 (model.fp16.safetensors):- Dual Hugging Face SafeTensors Release (
FP32+FP16): Now exports both the masterFP32checkpoint (model.safetensors,568.5 MB) and a native half-precisionFP16checkpoint (model.fp16.safetensors,284.2 MB, loadable viavariant="fp16",dtype=torch.float16) in the same repository—cutting download bandwidth, disk footprint, and GPU/CPU RAM loading overhead by 2× with< 0.0001%logit drift (100.00%classification parity across all 11 OWASP scenarios).
- Dual Hugging Face SafeTensors Release (
- Upgraded
HTTPNormalizerv2.5 New 2025–2026 Critical CVEs & Runtime/Parser Anti-Evasion:CVE-2026-114938(Java4Shell — HotSpot JVM AVX-512decodeBlockIntrinsic Underflow RCE)CVE-2026-29000(PHP2Shell — PHP Enginerfc1867Multipart &PHP_SESSION_UPLOAD_PROGRESSHeap/UAF RCE)CVE-2025-24813(Apache Tomcat PartialPUT+Content-Range.session//sessionDeserialization RCE)CVE-2026-21876(OWASP CRS MultipartContent-Type: charset=...Smuggling &UTF-7/IBM037Evasion)CVE-2025-55182(React2Shell — React 19 / Next.js RSC Flight Protocol Deserialization RCE) &CVE-2025-1974(IngressNightmare — Kubernetes Ingress-NGINX Admission Controller RCE)
- Upgraded
test_hf.pyv2.5:- Default SafeTensors
FP16(--fp16) vs. Explicit ONNX (--onnx --fp16): Runningpython test_hf.py --fp16now benchmarks SafeTensorsFP16(model.fp16.safetensors,variant="fp16") by default (symmetrical with--fp32formodel.safetensors), while passing--onnx --fp16(or--onnx fp16) targets ONNX RuntimeFP16(model_fp16.onnx). - Automatic Hugging Face Dynamic Module Cache Self-Healing (
_purge_unreadable_hf_cached_modules): Automatically detects and purges unreadable or antivirus-locked cached module files under~/.cache/huggingface/modules/transformers_modulesprior tofrom_pretrained(..., trust_remote_code=True).
- Default SafeTensors
🆕 News notes v2.5 - 17/11/2026 (continued)
- Upgraded
HTTPNormalizerv2.5:- Context-Aware CLI & SQL-Procedure Prose De-Biasing (
debias_operator_free_tech_terms): Neutralizes operator-free, flag-free documentary mentions of sensitive CLI commands and SQL procedures (whoami,uname,ifconfig, ...). - Strict UTF-8 Base64 Validation & Signed Session Cookie Immunity: Enforced strict UTF-8 validation (
\uFFFDrejection) on Base64 token inspection and native Express/Sails.js signed cookie recognition (s:<id>.<hmac>), preventing binary HMAC-SHA256 signatures from decoding into accidental SQL comment tokens (*/)—validated end-to-end across 227/227 live Postman-Echo tests (includingOPTIONSCORS preflights andmultipart/form-datafile uploads).
- Context-Aware CLI & SQL-Procedure Prose De-Biasing (
- Upgraded
test_hf.pyv2.5 (Multi-Backend SafeTensors & ONNX GPU/CPU Benchmark Suite):- Unified SafeTensors & ONNX Runtime CLI: Added native CLI flags to benchmark PyTorch SafeTensors alongside all three ONNX Runtime exports (
--onnx fp32/--fp32,--onnx fp16/--fp16,--onnx int8/--int8) with explicit hardware provider targeting (--gpu/--cuda,--cpu, or--device auto) and local/remote Hub resolution (--hub). - Zero-Config Windows 11 CUDA 13 & cuDNN 9 DLL Auto-Discovery (
_register_venv_nvidia_dlls): Automatically locates and registers bundled pip wheel DLL directories (site-packages/nvidia/cu13/bin/x86_64andsite-packages/nvidia/cudnn/bin) viaos.add_dll_directory()andPATHprior to initializingonnxruntime-gpu, seamlessly activatingCUDAExecutionProvideron Windows 11 even when PyTorch (CUDA 12) and ONNX Runtime (CUDA 13) use different CUDA major versions. - End-to-End Pipeline Verification on ONNX & PyTorch: Extended the
IronJeanWAFPipelineverification block to execute across both native Hugging Facepipeline()and ONNX Runtime sessions on Landmark strings and raw HTTP dictionaries.
- Unified SafeTensors & ONNX Runtime CLI: Added native CLI flags to benchmark PyTorch SafeTensors alongside all three ONNX Runtime exports (
🆕 News notes v2.5 - 11/11/2026
- Upgraded
HTTPNormalizerv2.5: Pre-compiled LRU regex engine (maxsize=2048), multi-block/double-encoded MySQL/*!...*/comment unwrapping, UTF-16LE/ASCII hex SQL literal decoding (0x...), standaloneWAITFOR DELAYcanonicalization, strengthened Cookie/Redirect/CMD guards, and strictkey=valueraw-payload framing—validated across 204/204 production Postman-Echo tests. - Sub-Route CMS Topological Rebalancing (
v34b): Balanced level-3 WordPress/blog/*sub-routes (wp-content/themes,uploads,plugins,wp-includes/js,my-account) to ~50/50 Safe/Attack parity to eliminate sub-route prior skew. - Spike-Free Convergence (
eval_loss: 0.000015) & SOTA Benchmarks: Achieved 100.00% (1.0) Validation Accuracy, Precision, Recall, and F1 (1.51e-5loss — 99.9985% confidence), 100.00% onv34b(160,500/160,500at719.25 req/s),waf-bench(77/77),gotestwaf(822/822), andopenappsec-attacks(73,924/73,924), 99.93% onshengqin-waf(0FP at0.85prod threshold), and 100.00% Precision (0FP) onhttp-attack-requests. - Terminal Phase of Training (
v34→v34b): Early low-LR warmup alignment of the classification head combined with losslessCookie:exploit preservation (HTTPNormalizerv2.5) eliminated contradictory[SEP]header signals and late Focal Loss (γ = 2.0) gradient spikes—drivingeval_loss4.6× lower at Epoch 2 (2.14e-5, 0 FP) and 2.3× lower at Epoch 3 (1.51e-5, zero loss spikes across Epochs 2–3). - Unified Landmark Pooling & TensorBoard Telemetry (
runs/): Unified async GPU/ONNXlandmark_poolkernel across training and Hugging Facetrust_remote_code=True, with interactive TensorBoard logs published in./runs.
🆕 News notes v2.4 - 7/11/2026
- Upgraded
HTTPNormalizerv2.4 Generic Rule Refactoring & Zero-ReDoS Architecture: Removed all one-off dataset patches in favor of generic, ReDoS-safe anti-evasion and canonicalization rules:- Double-Encoded & Truncated HTML Entity Unwrapping: Recursively unwraps
&before numeric or named HTML/XSS entities (&#0000106,&lt;,&colon;), supports truncated HTML5&periowith a query-parameter negative lookahead(?![a-zA-Z0-9_]*=)(preventing collisions with benign URL parameters such as&period=5y), and expands inline numeric entity decoding across 5-digit decimal padding and attribute delimiters. - Unified LFI & SQL Comment De-Obfuscation: Non-backtracking LFI traversal canonicalization across Unix/Windows targets (
etc/(passwd|shadow|issue|hosts|group)|boot.ini|win.ini|system.ini), overlong UTF-8%c0ndot-evasion decoding, and targeted SQL function comment unwrapping (database/**...**/()→database()) that preserves LDAP wildcard filters (/*)(uid=*))(|(uid=*/) and/**/SQLi tokens. - Canonical SQLi, CMDi & XSS Structural Normalization: Generic canonicalization for
UNION ALL SELECT, negative-ID-\d+ UNION SELECT, standaloneCONCAT(...)with SQL introspection functions (database(),version(),user(),information_schema), long hex literals (0x[0-9a-f]{24,}), booleanOR/AND x BETWEEN y AND z,|| col IS [NOT] NULL,AND user_name() =, chained shell commands (& dir,| id,; whoami), malformed self-closing event tags (<img </onload=...>), and bare/encoded<parameter probes. - Benign Query Parameter Canonicalization: Generic normalization for
example.com/org/nettest URLs, international postal addresses (street, number), non-OAST email addresses in query parameters, intra-word*/$typos, and leading-dot uppercase acronyms (=.DOTe) while strictly preserving Unix dotfile reconnaissance probes (.env,.npmrc,.htaccess,.dockerenv).
- Double-Encoded & Truncated HTML Entity Unwrapping: Recursively unwraps
- Fixed ONNX Exporter (
export_onnx.py) for FP16 (model_fp16.onnx) & Dynamic INT8 (model_quantized_int8.onnx):- FP16 RoPE
CastGraph Fix: Replaced legacyonnxconverter_common.float16—which mutated ModernBERT's Rotary Position Embedding node (/model/layers.*/attn/rotary_emb/Cast_1) without updating downstreamValueInfoProtosignatures (ORT_FAIL: Type (tensor(float16)) ... does not match expected type (tensor(float)))—with ONNX Runtime's transformer-awareonnxruntime.transformers.float16.convert_float_to_float16(onnx_model, keep_io_types=True). This produces a valid FP16 graph (285 MB, optimized for NVIDIA Tensor Core GPUs) while keeping I/Ologitsintensor(float)(FP32) for direct Java DJL compatibility. - Lossless Dynamic INT8 Quantization (
100%Holdout Parity on CPU): Fixed the weight/logit collapse caused by naiveQuantType.QInt8dynamic quantization on ModernBERT (where multiplying unsigneduint8activations by signedint8weights overflows AVX2vpmaddubsw16-bit accumulators on high-amplitude GeGLU layers, while quantizingGatherandGemmdegrades token embeddings and Landmark Pooling logits). Switching toweight_type=QuantType.QUInt8(32-bit accumulation), restricting quantization toop_types_to_quantize=['MatMul'](keeping token embeddings inFP32), and excluding the final Landmark classification head (nodes_to_exclude=['/classifier/Gemm']) restores 100.00% (50/50) Holdout accuracy at a254 MBfootprint (~2–4 msproduction CPU latency alongside nativeFP32).
- FP16 RoPE
- Macro-Topological URI Prefix & Query-Key De-Biasing (
v33Dataset): Audited and rebalanced all 14 URI prefix families (/api/v1/*,/api/*,/blog/*,/wp-*,/publico/*,/actuator/*,/nexus.*,/assets/*,/auth/*), single-letter query keys (?q=,?s=,?p=,?id=), and natural-language punctuation/numeric templates to strict ~50/50 Safe/Attack parity—eliminating structural prefix and parameter-name shortcuts. - 100.00% Accuracy Across Internal & Major External WAF Benchmarks: Achieved 100.00% Global Accuracy (
0FP,0FN) on the 160,500-requestv33corpus, 100.00% onwaf-bench(77/77), 100.00% ongotestwaf(822/822), 100.00% onopenappsec-attacks(73,924/73,924), 99.73% onshengqin-waf(1FP /0.10%FPR), and 98.46% onhttp-attack-requestswith 100.00% Precision (0FP /0.00%FPR).
🆕 News notes v2.3 - 31/10/2026
- Upgraded
HTTPNormalizerv2.3: Now bundled viatrust_remote_code=True. Added in-distributionOPTIONS/HEADverb canonicalization (GETwhenEMPTY_BODY,POSTif a body is present) andOriginauthority anonymization for zero-false-positive CORS preflight inspection, smart WindowsCRLF(\r\n→\n) body normalization (preservingmultipart/form-dataand CRLF/Smuggling payloads), recursive[SEP]landmark anti-collision filtering acrossURI/HEADERS/BODY, deep payload inspection across non-target HTTP headers (Accept-Encoding,Acceptwith MIME wildcard stripping,Cache-Control,Connection), 100% deterministic User-Agent canonicalization (canonicalize_healthy_user_agent) with a configurableBLOCK_SCANNER_USER_AGENTStoggle, strengthened Cookie/UA/Host/JWT exploit guards, and new anti-evasion decoders. - Dotted False-Friends, Technical Markdown & Root-URI Parity (
v28): Introduced a parametric "Dotted False-Friends" generator, symmetric root-URI containers (/?q=,/?p=,/?s=,POST /form-urlencoded), technical cybersecurity Markdown documentation (nested links, release notes, YAML/code blocks), and complex punctuation/SQL-keyword prose. - New Attack Signatures: Added stacked SQLi, Windows arithmetic & network recon CMD injection, SMTP/IMAP
CRLFcommand splitting, LDAP OID filter injection, and OAST SSRF/Log4Shell callback domains.
🆕 News notes v2.2 - 25/10/2026
- Balanced 22 Attack Families: Expanded from 12 to 22 offensive families (Next.js/Vite/PHP CVEs, Prototype Pollution, Cloud SSRF, JWT, SSTI, Deserialization, NoSQL, GraphQL) with strict 50/50 anti-shortcut parity across all keywords and User-Agents.
- Upgraded
HTTPNormalizerv2.2: Added authority IP normalization (Host/Referer→<DOMAIN>, local LAN IPs), exploit-aware<DOMAIN>/<IP>guards, and recursive\u00XXUnicode decoding. - Broader Threat & Benchmark Coverage: Maintained 99.9994% Global Accuracy — "Five Nines" — internally while boosting zero-shot scores across
shengqin-waf(99.38%),secureai-waf(98.36%),waf-bench(96.10%),nosql-waf(94.39%), andai-waf(89.97%).
🆕 News notes v2.1 - 20/10/2026
- Balanced Protocol & Verb Coverage: Expanded to 160,500 requests with strict 50/50 Safe/Attack parity across all HTTP methods (
GET,POST,PUT,PATCH,DELETE) andContent-Typeformats (JSON objects/arrays, XML/SOAP, Form, Multipart, gRPC). - Markdown & HTML5 False-Positive Immunity: Native support for
text/markdown(technical prose, code blocks) andtext/htmldocuments without false alarms. - Upgraded
HTTPNormalizerv2.1: Added smart cookie/telemetry anonymization (anonymize_cookies), advanced anti-evasion decoding (Log4j, decimal IPv4, sponge-case), and non-target header inspection. - Broader Threat & Benchmark Coverage: Added detection for dotfile recon, open redirects, and HTTP request smuggling, validated across 9 external Hugging Face benchmarks.
🆕 News notes v2.0 - Initial release 11/10/2026
⚡ Key Architectural Innovations
1. Vectorized Landmark Pooling (trust_remote_code=True)
Traditional sentence transformers collapse sequence representations onto the initial [CLS] token, discarding spatial boundary relationships between HTTP fields.
IronJean WAF implements Vectorized Landmark Pooling:
- Delimiter tokens (
[SEP]) segment the request into four discrete landmarks:METHOD,URI,HEADERS, andBODY. - The final representation is computed via parallel vectorized pooling over
[SEP]hidden states:
$$\text{Pooled} = \frac{1}{\max\left(1, \sum \mathbf{M}{\text{SEP}}\right)} \sum{t=1}^S \mathbf{h}t \cdot \mathbf{M}{\text{SEP}, t}$$
- Native Hugging Face Integration (
trust_remote_code=True): Packaged with custom modeling (modeling_ironjean.py) registered underAutoModelForSequenceClassificationandpipeline("text-classification"). External developers can load the full landmark-pooling architecture zero-shot without defining custom PyTorch boilerplate. - Fully Exportable to ONNX: For zero-trust production environments, the pooling graph is baked directly into
model.onnx, requiring no Python runtime.
2. Multi-Pass Recursive Anti-Evasion Decoding & Anti-DoS Compression
Attackers frequently chain multiple encoding layers and padding buffers to evade signature inspection or overflow context windows. IronJean WAF incorporates a deterministic pre-inference unwrapping pipeline (convergence loop up to depth = 3) that:
- Recursively unwraps URL-encoding, Base64 (including unpadded and
/-delimited path tokens), ASCII Unicode escapes (\u00XX), HTML numeric/named entities, Log4j JNDI lookups (${lower:x},${::-x}), decimal IPv4 SSRF targets (http://2852039166), SQL inline comments (/*!50000...*/), Sponge-Case keywords (sElEcT→SELECT), and Null-Byte extension bypasses (%00.jpg→\x00.jpg). - Compresses repetitive character floods (
(.)\1{127,}→ 32 chars) to defeat Context-Window Flooding and ReDoS while preserving buffer-overflow/fuzzing anomaly signatures.
3. Exploit-Aware Network Landmark Anonymization (<IP> & <DOMAIN>)
To prevent the neural network from memorizing environment-specific corporate hostnames, LAN subnets, or proxy topologies, authority and forwarding headers (Host, Referer, Origin, X-Forwarded-For, X-Real-IP, True-Client-IP, CF-Connecting-IP, X-Forwarded-Host) are mapped to canonical <DOMAIN> and <IP> landmarks.
- Exploit-Aware Negative Lookaheads: Explicitly preserve Cloud Metadata SSRF targets (
169.254.169.254,100.100.100.200,metadata.google.internal), OAST callback domains (interact.sh,oastify.com,burpcollaborator.net), Java/PHP gadget namespaces (class.module.classLoader,convert.iconv.*), and JS DOM objects (document.cookie,window.location) so attacks are never masked. - In-Distribution CORS & Verb Canonicalization: Automatically maps bodiless
OPTIONSandHEADrequests toMETHOD: GET(orPOSTif a body is present), ensuring CORS preflights are evaluated strictly inside the model's nominal training distribution.
4. Syntax-Aware Sliding-Window Chunking with Early-Exit
Even an 8,192-token context window can be targeted by "Needle-in-a-Haystack" evasion, where an attacker pads an HTTP body past 8,192 tokens (> 20 KB) and appends a malicious payload at the extreme tail. To eliminate truncation blindspots with zero overhead on standard requests (<= 8,000 chars), IronJeanWAFClassifier.build_sliding_windows() and IronJeanWAFPipeline implement syntax-aware sliding-window inspection:
- Context-Preserving Overlapping Windows & Anchored Tail: Bodies exceeding
8,000characters are segmented into overlapping windows (7,600-char window,1,200-char overlap /6,400-char stride, up to32chunks /~205 KB+), each prefixed by the originalMETHOD,URI, andHEADERSlandmarks. The final window is right-aligned to avoid tiny orphaned stubs, and an anchored extreme-tail window guarantees end-of-body exploits are always inspected even past205 KB. - Syntax-Aware Boundary Snapping & Balanced Container Wrapping: Automatically detects
JSON,XML,FORM, andTEXTbodies, snapping slice boundaries to clean structural delimiters (JSON objects/keys, balanced XML tags,&separators, or line/paragraph breaks) and wrapping split JSON/XML fragments in minimal balanced containers ({"items":[...]},<root>...</root>)—preventing naive mid-token splits from creating artificial breakout false positives. - Early-Exit Short-Circuiting & Single-Pass Parity: Evaluates chunks sequentially via max-risk aggregation and short-circuits immediately once any window crosses the attack threshold (default
0.85), while the_NormalizedLandmarkStrsentinel guarantees single-passHTTPNormalizerexecution across both PyTorch SafeTensors and ONNX Runtime inference paths.
5. Two-Stage Curriculum: Focal Hard-Mining to Cross-Entropy Calibration
Trained via a two-stage curriculum across 3 epochs:
- Epochs 1–2 (Hard-Example Mining): Focal Loss (α = 1.0, γ = 2.0) down-weights easy canonical exploits to focus gradient updates on hard boundary cases (e.g., "Dotted False-Friends" like
Shell.me/System.Text.Json, root-URI short parameters/?q=, technical cybersecurity Markdown, and French/English apostrophes vs. SQL quotes). - Epoch 3 (Logit Calibration): Switches to standard Cross-Entropy (
label_smoothing = 0.0) under linear learning-rate decay (from peak2 × 10⁻⁵with 10% warmup down to0) to sharpen output probabilities without compressing OOD logit margins—driving validation Recall to 100.00% (0FN), validation Accuracy to 99.9938%, and 0 FP across all 5 external WAF benchmarks.
⚙️ Dataset Provenance
To ensure a comprehensive and resilient mapping of HTTP threat vectors, the dataset was meticulously aggregated and curated from the following sources:
- Simulated Enterprise Telemetry (WAF Factory datasets): Rigorously generated HTTP logs designed to mirror the natural variance, structural complexity, and edge cases of legitimate enterprise traffic, ensuring realistic baseline behaviors without using proprietary production data.
- CAPEC™ (Common Attack Pattern Enumeration and Classification): Integration of standardized, industry-recognized attack patterns to guarantee baseline coverage of known exploit topologies.
- miomit/xss_generation: Synthetic, deeply obfuscated cross-site scripting payloads to train the model's attention mechanism against advanced evasion and mutation techniques.
- Custom Synthetic & Noise Data: Custom-engineered synthetic payloads combined with deliberate label noise, specifically designed to force structural learning and provide maximum resilience.
🛸 Training Dynamics: Focal Hard-Mining to Cross-Entropy Calibration
During training on the 160,500-request v40 corpus (stratified 90% train / 10% hold-out validation split of 16,050 requests across label × short/long, including 1,637 sequences >= 512 tokens and 904 sequences >= 900 tokens, deterministic --seed 42), IronJean v2.6 uses Hybrid Stratified Smart Batching, Async CUDA Prefetching, and adaptive 2×8 (> 1,024t) / 4×4 (> 1,536t) long-sequence sub-batch splitting, completing all 3 epochs in 3,793.78 s (63m 14s, 114.23 samples/s, peak VRAM 12.78 / 19.55 Go, 1.75× faster than v2.5):
| Training Phase | Loss Function | Train Loss | Eval Loss | Eval Accuracy | Eval Precision | Eval Recall | Eval F1-Score | Long-Seq F1 (>= 512t / >= 900t) |
|---|---|---|---|---|---|---|---|---|
| Epoch 1.0 | Focal Loss (γ = 2.0) | 0.027489 | 0.000547 | 99.9439% | 100.0000% | 99.8879% | 99.9439% | 1.0000 / 1.0000 |
| Epoch 2.0 | Focal Loss (γ = 2.0) | 0.000743 | 0.000383 | 99.9439% | 99.9875% | 99.9003% | 99.9439% | 0.9989 / 0.9980 |
| Epoch 3.0 | Cross-Entropy Calibration (ls=0.0) | 0.000142 | 0.000465 | 99.9938% | 99.9875% | 100.0000% | 99.9938% | 1.0000 / 1.0000 |
Behavioral Dynamics:
- Epoch 1.0: Rapid, spike-free structural convergence across HTTP landmarks (
METHOD,URI,HEADERS,BODY) with adaptive VRAM-capped splitting (2×8on343batches> 1,024tand4×4on207batches> 1,536tout of9,029), reaching99.9439%validation Accuracy (eval_loss:0.000547),100.0000%Precision (0FP), and1.0000F1 on both long-sequence validation buckets (>= 512t,N = 1,637;>= 900t,N = 904). - Epoch 2.0: Hard-Example Mining (
train_lossdrops 37× to0.000743,eval_lossdrops to0.000383): Focal Loss concentrates gradient updates on anti-shortcut boundary cases (contrastive technical Markdown/LaTeX/backtick prose, Dotted False-Friends,/{base}/{id}/{word}REST tails, root-URI short keys/?k=v, pure-integer query params, and benign query emails), raising Recall to99.9003%while keeping Precision at99.9875%. - Epoch 3.0: Terminal Calibration & Long-Context Generalization (
train_loss:0.000142in Epoch 3,0.009458global mean): Switching to standard Cross-Entropy (label_smoothing = 0.0) under linear LR decay drives validation Recall to100.0000%(0FN across all16,050hold-out samples), Accuracy & F1 to99.9938%(16,049 / 16,050, only1FP), and both Long-Sequence validation buckets (>= 512t,N = 1,637;>= 900t,N = 904) back to100.00%(F1 = 1.0000)—reaching "Five Nines" (99.9994%Global Accuracy,160,499 / 160,500,1FP,0FN) across the full corpus.
🗿 Benchmark
Tested against internal (max-length = 8192 tokens, token-budgeted batching <= 32,768 tokens, Sliding-Window Early-Exit > 8,000 chars) and external Hugging Face / industry WAF benchmarks (max-length = 4096 tokens, batch_size = 64, default 0.50 classification threshold, Payload-Only mode with scanner UA blocking disabled):
Benchmark dataset | Hugging Face / Source Dataset | Requests | Accuracy | Precision | Recall | F1-Score | TP | TN | FP (FPR) | FN (FNR) | Throughput (Latency) |
|---|---|---|---|---|---|---|---|---|---|---|---|
v40 (Internal) | dataset_v40_rest_150k + 10.5k noise | 160,500 | 99.9994% | 99.9988% | 100.0000% | 99.9994% | 80,250 | 80,249 | 1 (0.0012%) | 0 (0.0000%) | 505.45 req/s(1.98 ms) |
waf-bench | netgoat-ai/WAF-Bench | 77 | 100.00% | 100.00% | 100.00% | 100.00% | 55 | 22 | 0 (0.00%) | 0 (0.00%) | 261.54 req/s(3.82 ms) |
gotestwaf | wallarm/gotestwaf(44 OWASP/API suites) | 822 | 100.00% | 100.00% | 100.00% | 100.00% | 676 | 146 | 0 (0.00%) | 0 (0.00%) | 442.37 req/s(2.26 ms) |
openappsec-attacks | openappsec/waf-comparison-project(73.9K Multi-Vector Attacks) | 73,924 | 99.99% | 100.00% | 99.99% | 100.00% | 73,920 | 0 | 0 (0.00%) | 4 (0.01%) * | 929.92 req/s(1.08 ms) |
shengqin-waf | shengqin/web-attacks | 5,523 | 99.78% | 100.00% | 99.73% | 99.87% | 4,498 | 1,013 | 0 (0.00%) | 12 (0.27%) * | 1,495.89 req/s(0.67 ms) |
http-attack-requests | SecureAI-SE/http-attack-requests | 7,000 | 98.49% | 100.00% | 98.23% | 99.11% | 5,894 | 1,000 | 0 (0.00%) | 106 (1.77%) * | 924.33 req/s(1.08 ms) |
💡 * Notes on External Benchmark Artifacts & Live Gateway Tests:
openappsec-attacks(73,920 / 73,924): Achieves 100.00% onxss(41,888/41,888),traversal(28,314/28,314),sqli(916/916),log4shell(220/220),xxe(70/70), andshellshock(48/48). All 4 remainingcmdexeFNs are bare, operator-free single words (p=ifconfig,p=ipconfigwithout any shell separator) intentionally de-biased to eliminate production prose false positives.shengqin-waf(5,523): Achieves 100.00% Precision (0FP) and99.87%F1. All 12 remaining FNs are upstream Excel spreadsheet formula corruptions (11× /?q=#ERROR!and1× /?q=#NAME?) —0genuine exploits missed.http-attack-requests(7,000): Maintains 100.00% Precision (0FP) while reducing FNs from113(98.39%Acc /99.05%F1 in v2.5) down to106(98.49%Acc /99.11%F1), with the remaining FNs stemming from non-executable wordlist/CSV artifacts (isolated DOM event names without=/<or bare HTML comments).
📐 Input Format (Sequence Template)
Input sequences must conform strictly to the four-landmark template:
METHOD: <HTTP_METHOD> [SEP] URI: <REQUEST_URI> [SEP] HEADERS: <FILTERED_HEADERS> [SEP] BODY: <NORMALIZED_BODY>
METHOD:Standard HTTP verb (GET,POST,PUT,DELETE,PATCH;OPTIONSandHEADare automatically canonicalized toGETorPOSTbyHTTPNormalizer).[SEP]: Delimiter token (50282in ModernBERT tokenizer) mapped to Vectorized Landmark Pooling.URI:Recursively decoded path and parameters (e.g./api/v1/resource?id=10).HEADERS:Pipe-separated key-value pairs formatted byHTTPNormalizer.BODY:Recursively decoded payload, orEMPTY_BODY.
🛠️ Mandatory Pre-Inference Normalization Pipeline
To reproduce the benchmarked 99.9994% Global Accuracy (99.9988% Precision / 100.0000% Recall) and avoid false alarms, incoming HTTP requests must pass through the IronJean Normalization Pipeline before tokenization.
This pipeline strips multi-layer evasion obfuscation, prevents neural overfitting on hostnames/IPs, enforces header length guards, and structures input into canonical HTTP landmarks.
Incoming HTTP Request
│
▼
┌────────────────────────────────────────────────────────┐
│ 1. Multi-Pass Recursive Anti-Evasion (Max Depth = 3) │
│ URL / Base64 / Unicode \u00XX / HTML / Log4j unwrap │
│ Anti-DoS padding compression (>128 chars -> 32) │
└────────────────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────────────────┐
│ 2. Exploit-Aware Network Landmark Anonymization │
│ Host, Referer, Origin, X-Forwarded-* -> <DOMAIN>/<IP>│
│ Preserves Cloud IMDS (169.254.169.254) & OAST hosts │
└────────────────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────────────────┐
│ 3. Header Canonicalization & Flooding Guard (512 max) │
│ Keep target + suspicious non-target headers │
│ Canonicalize healthy User-Agent & Bearer tokens │
│ Cookie: drop telemetry (_ga, __cf_bm), anonymize │
│ session tokens (JSESSIONID=NONE), preserve attacks │
└────────────────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────────────────┐
│ 4. Body & Token Stabilization │
│ Empty/Null -> 'EMPTY_BODY', strip benign HTML5 │
│ <!DOCTYPE html>, normalize benign Windows \r\n->\n, │
│ strip injected [SEP] tokens & healthy JWT sigs │
└────────────────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────────────────┐
│ 5. Landmark Sequence Serialization │
│ OPTIONS/HEAD -> GET (or POST if body present) │
│ METHOD: <M> [SEP] URI: <U> [SEP] HEADERS: <H> ... │
└────────────────────────────────────────────────────────┘
⚗️ Python Normalizer (HTTPNormalizer — Bundled via trust_remote_code=True)
To ensure exact parity with production environments and prevent false alarms, raw requests must be normalized before inference.
Because modeling_ironjean.py imports normalizer_ironjean.py via a relative import (from .normalizer_ironjean import HTTPNormalizer), Hugging Face Hub automatically downloads normalizer_ironjean.py alongside the model weights whenever trust_remote_code=True is enabled:
- Zero-file remote access (from Hugging Face Hub):
HTTPNormalizer = model.normalizer(or directlymodel.serialize_http(...)/classifier.normalizer). - Direct local import:
from normalizer_ironjean import HTTPNormalizer(also re-exported bycore.normalizerand bundled intest_hf.py). - Scanner User-Agent Policy Toggle: Set
HTTPNormalizer.BLOCK_SCANNER_USER_AGENTS = Trueto block offensive scanner banners (sqlmap,Nikto,Nuclei,OpenVAS,ffuf) even without an exploit payload (defaultFalse= Payload-Only mode).
from transformers import AutoModelForSequenceClassification
model = AutoModelForSequenceClassification.from_pretrained(
"Metabaron6/IronJean-v2-ModernBERT-WAF",
trust_remote_code=True
)
HTTPNormalizer = model.normalizer # Automatically fetched from normalizer_ironjean.py on HF Hub
sequence = HTTPNormalizer.serialize_http(
method="POST",
uri="/api/v1/checkout?redirect=%2Fdashboard",
headers={
"Host": "192.168.1.16:8080",
"Cookie": "JSESSIONID=5d41402abc4b2a76b9719d911017c592; _ga=GA1.2.123456789",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
},
body='{"cart_id": 98712, "coupon": "WELCOME10"}'
)
# -> METHOD: POST [SEP] URI: /api/v1/checkout?redirect=/dashboard [SEP] HEADERS: host: <DOMAIN> | cookie: JSESSIONID=NONE | user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) [SEP] BODY: {"cart_id": 98712, "coupon": "WELCOME10"}
💻 Python Quickstart
Prerequisites
- Python:
>= 3.10(Python 3.11or3.12recommended) - PyTorch:
torch >= 2.4.0(with CUDA 12.1+ recommended for hardwarebfloat16and FlashAttention-2 / SDPA acceleration) - Hugging Face Transformers:
transformers >= 4.48.0(mandatory — nativeModernBERTsupport requires4.48.0+) - ONNX Runtime (Optional for
--onnxmode):- CPU:
pip install onnxruntime - GPU (CUDA 13 & cuDNN 9):
pip install onnxruntime-gpu nvidia-cublas nvidia-cuda-runtime nvidia-cufft nvidia-cudnn-cu13
- CPU:
Native Hugging Face Loading (trust_remote_code=True)
Thanks to modeling_ironjean.py and normalizer_ironjean.py (trust_remote_code=True), IronJean's Vectorized Landmark Pooling architecture and HTTPNormalizer pipeline are downloaded and instantiated dynamically from the Hugging Face Hub—without requiring any local Python files or custom PyTorch boilerplate:
pipeline("text-classification", ..., trust_remote_code=True)loadsIronJeanWAFPipeline, which accepts raw HTTP dictionaries ({"method": "GET", "uri": "...", "headers": {...}, "body": None}) or Landmark strings, normalizes them automatically (max_length=8192), and applies syntax-aware Sliding-Window Chunking with Early-Exit for oversized bodies (> 8,000 chars).AutoModelForSequenceClassification.from_pretrained(..., trust_remote_code=True)exposesmodel.normalizer(HTTPNormalizer) andmodel.serialize_http(...)directly on the loaded model instance.
import torch
from transformers import AutoModelForSequenceClassification, AutoTokenizer, pipeline
model_id = "Metabaron6/IronJean-v2-ModernBERT-WAF"
device = "cuda" if torch.cuda.is_available() else "cpu"
# =====================================================================
# Option 1: Native Hugging Face Pipeline (Auto-Normalizes Raw HTTP Dicts)
# =====================================================================
classifier = pipeline(
"text-classification",
model=model_id,
trust_remote_code=True,
device=0 if device == "cuda" else -1
)
# Pass a raw HTTP request dict directly — IronJeanWAFPipeline normalizes it automatically!
result = classifier({
"method": "GET",
"uri": "/products?category=1' UNION SELECT null,password FROM users--",
"headers": {"Host": "api.corporate.net", "User-Agent": "Mozilla/5.0"},
"body": None
})
print("Pipeline Result:", result)
# =====================================================================
# Option 2: Native AutoModel with BFloat16 Acceleration & model.normalizer
# =====================================================================
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForSequenceClassification.from_pretrained(
model_id,
trust_remote_code=True,
dtype=torch.bfloat16 if device == "cuda" else torch.float32
).to(device).eval()
# Access HTTPNormalizer directly from the downloaded HF model (normalizer_ironjean.py)
HTTPNormalizer = model.normalizer
# Optional: set HTTPNormalizer.BLOCK_SCANNER_USER_AGENTS = True for strict scanner-banner blocking
def classify_http_request(raw_sequence: str, threshold: float = 85.0):
# Step 1: Tokenize with up to 8192 context window
inputs = tokenizer(raw_sequence, return_tensors="pt", truncation=True, max_length=8192).to(device)
# Step 2: Vectorized Landmark Pooling inference
with torch.no_grad():
if device == "cuda":
with torch.amp.autocast("cuda", dtype=torch.bfloat16):
outputs = model(**inputs)
else:
outputs = model(**inputs)
probs = torch.softmax(outputs.logits.float(), dim=-1)
attack_prob = probs[0][1].item() * 100.0
is_attack = attack_prob >= threshold
return is_attack, attack_prob
# 2. Format requests using HTTPNormalizer & run inference
# Case A: SQL Injection in URI
sample_attack = HTTPNormalizer.serialize_http(
method="GET",
uri="/api/v1/users?id=1' OR '1'='1",
headers={"Host": "api.corporate.net", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"},
body=None
)
blocked, prob = classify_http_request(sample_attack)
print(f"Attack URI Probability: {prob:.2f}% | Decision: {'🛑 BLOCKED' if blocked else '✅ ALLOWED'}")
# Case B: Benign Business Form with Natural Text / Apostrophe
sample_safe = HTTPNormalizer.serialize_http(
method="POST",
uri="/api/v1/profile",
headers={"Host": "api.corporate.net", "User-Agent": "curl/8.11.1", "Content-Type": "application/json"},
body='{"name": "O\'Connor", "bio": "Software Engineer. It\'s a genuine profile.", "settings": {"theme": "dark"}}'
)
blocked, prob = classify_http_request(sample_safe)
print(f"Safe Request Attack Probability: {prob:.2f}% | Decision: {'🛑 BLOCKED' if blocked else '✅ ALLOWED'}")
# Case C: Malicious Attack Injected Inside User-Agent Header (Log4Shell / SQLi)
# is_healthy_user_agent flags the suspicious pattern, preserves raw payload, and blocks it!
sample_ua_attack = HTTPNormalizer.serialize_http(
method="GET",
uri="/api/v1/users",
headers={"Host": "api.corporate.net", "User-Agent": "Mozilla/5.0' OR '1'='1--"},
body=None
)
blocked, prob = classify_http_request(sample_ua_attack)
print(f"User-Agent Attack Probability: {prob:.2f}% | Decision: {'🛑 BLOCKED' if blocked else '✅ ALLOWED'}")
# Case D: Cookie Anonymization vs Malicious Cookie Injection (WAFFilter Parity)
# Benign telemetry cookies (_ga, __cf_bm) are dropped, session cookie is neutralized to NONE:
sample_cookie_safe = HTTPNormalizer.serialize_http(
method="POST",
uri="/api/v1/checkout",
headers={
"Host": "api.corporate.net",
"Cookie": "JSESSIONID=5d41402abc4b2a76b9719d911017c592; _ga=GA1.2.123456789.1234567890; __cf_bm=abcdef123456",
"User-Agent": "Mozilla/5.0"
},
body="cart_id=98712&item=44"
)
blocked, prob = classify_http_request(sample_cookie_safe)
print(f"Safe Cookie Request Attack Probability: {prob:.2f}% | Decision: {'🛑 BLOCKED' if blocked else '✅ ALLOWED'}")
# Malicious Injection inside Cookie (SQLi preserved and deterministically blocked):
sample_cookie_attack = HTTPNormalizer.serialize_http(
method="GET",
uri="/dashboard",
headers={"Host": "api.corporate.net", "Cookie": "JSESSIONID=1' OR '1'='1--", "User-Agent": "Mozilla/5.0"},
body=None
)
blocked, prob = classify_http_request(sample_cookie_attack)
print(f"Cookie SQLi Attack Probability: {prob:.2f}% | Decision: {'🛑 BLOCKED' if blocked else '✅ ALLOWED'}")
🧪 Live Benchmark Suite & Empirical Validation (OWASP Top 10)
You can run the complete evaluation suite locally or directly from the Hugging Face Hub using test_hf.py across PyTorch SafeTensors and ONNX Runtime (FP32, FP16, INT8) on either GPU (CUDAExecutionProvider) or CPU (CPUExecutionProvider):
# PyTorch SafeTensors (Default: model.safetensors FP32 | --fp16: model.fp16.safetensors FP16)
python test_hf.py --hub
python test_hf.py --hub --fp16 --gpu # SafeTensors FP16 (model.fp16.safetensors, 285 MB, variant='fp16')
python test_hf.py --hub --fp32 --gpu # SafeTensors FP32 (model.safetensors, 569 MB)
python test_hf.py --hub --cpu
# ONNX Runtime GPU (CUDAExecutionProvider — Optimal Latency & VRAM)
python test_hf.py --hub --onnx fp16 --gpu # ~14.00 ms/req (Recommended GPU: 2x lower VRAM, 8-decimal parity)
python test_hf.py --hub --onnx fp32 --gpu # ~14.11 ms/req (Baseline FP32 on CUDA)
# ONNX Runtime CPU (CPUExecutionProvider — Optimal for Java/Tomcat & CPU Servers)
python test_hf.py --hub --onnx int8 --cpu # ~33.47 ms/req (Recommended CPU: Dynamic QUInt8, 254 MB)
python test_hf.py --hub --onnx fp32 --cpu # ~41.06 ms/req (Baseline FP32 on CPU, 569 MB)
# Shorthand Flags & Custom Decision Threshold
python test_hf.py --hub --onnx --fp16 --gpu --threshold 85.0
python test_hf.py --hub --int8 --cpu
⚡ Empirical Runtime Benchmark Summary (13 OWASP & Long-Payload Scenarios + Pipeline Check)
Real Console Output (python test_hf.py --hub --onnx fp16 --gpu — ONNX Runtime FP16, CUDAExecutionProvider, Sliding-Window Enabled, Decision Threshold = 85.0%):
Also reproducible with PyTorch SafeTensors via
python test_hf.py --hub(SafeTensorsFP32, CUDAbfloat16) orpython test_hf.py --hub --fp16 --gpu(SafeTensorsFP16, CUDAfloat16).
====================================================================
🛡️ IRONJEAN-v2.6 HUGGING FACE NATIVE BENCHMARK (ONNX FP16 (model_fp16.onnx))
📦 Model Source: Metabaron6/IronJean-v2-ModernBERT-WAF
⚙️ Architecture: Vectorized Landmark Pooling (trust_remote_code=True)
====================================================================
Loading IronJean-v2.6 via ONNX Runtime (ONNX FP16 (model_fp16.onnx))...
Target Source: Metabaron6/IronJean-v2-ModernBERT-WAF
✓ Config loaded | Target Labels: {0: 'SAFE', 1: 'ATTACK'}
✓ Tokenizer loaded | Vocabulary size: 50280 tokens
✓ Bundled Normalizer resolved: HTTPNormalizer
✓ ONNX Graph loaded: model_fp16.onnx
✓ Successfully initialized on CUDAExecutionProvider.
Starting evaluation suite (max_length=8192, sliding_window=True, decision_threshold=85.0%)...
SCENARIO : ATTACK (Command Injection / OS Cmd) -> [ATTACK BLOCKED] 🛑 (100.00%) 264.49 ms
SCENARIO : BENIGN (Standard REST API Request) -> [SAFE ALLOWED] ✅ (100.00%) 16.43 ms
SCENARIO : ATTACK (Base64 Evasion / Java Deserialization) -> [ATTACK BLOCKED] 🛑 (100.00%) 15.30 ms
SCENARIO : BENIGN (OAuth2 Token Exchange) -> [SAFE ALLOWED] ✅ (100.00%) 14.99 ms
SCENARIO : BENIGN (JSON Form with Natural Apostrophe) -> [SAFE ALLOWED] ✅ (100.00%) 14.62 ms
SCENARIO : ATTACK (SQL Injection UNION SELECT) -> [ATTACK BLOCKED] 🛑 (100.00%) 14.87 ms
SCENARIO : BENIGN (WordPress Registration Form) -> [SAFE ALLOWED] ✅ (100.00%) 15.37 ms
SCENARIO : ATTACK (User-Agent SQL Injection) -> [ATTACK BLOCKED] 🛑 (100.00%) 15.80 ms
SCENARIO : ATTACK (User-Agent Log4Shell JNDI) -> [ATTACK BLOCKED] 🛑 (100.00%) 14.98 ms
SCENARIO : BENIGN (Cookie Anonymization - Session & Telemetry Dropped) -> [SAFE ALLOWED] ✅ (100.00%) 14.93 ms
SCENARIO : ATTACK (Cookie SQL Injection) -> [ATTACK BLOCKED] 🛑 (100.00%) 14.98 ms
SCENARIO : BENIGN (Large 10K+ Tokens JSON Batch - Sliding Window) -> [SAFE ALLOWED] ✅ (100.00%) 337.69 ms [chunks=4/4]
SCENARIO : ATTACK (Needle-in-a-Haystack 10K+ Tokens SQLi @END) -> [ATTACK BLOCKED] 🛑 (100.00%) 315.64 ms [chunks=4/4]
====================================================================
Verifying Hugging Face pipeline('text-classification', trust_remote_code=True):
====================================================================
1. Landmark String : METHOD: GET [SEP] URI: /products?category=1' UNION SELECT null,password FROM users-- [SEP] HEADERS: host: <DOMAIN> [SEP] BODY: EMPTY_BODY
Pipeline Result : [{'label': 'ATTACK', 'score': 0.999999362445222}]
2. Raw HTTP Dict : /api/query?param=eyJAdHlwZSI6ImNvbS5zdW4ucm93c2V0LkpkYmNSb3dTZXRJbXBsIn0= (Auto-decoded by IronJeanWAFPipeline)
Pipeline Result : [{'label': 'ATTACK', 'score': 0.9999983782956141}]
3. 10K+ Tok Haystack: 21553 chars JSON with SQLi @END (Sliding-Window Pipeline chunks[2 994, 2 978, 2 979, 2 981]= 11 932 tokens)
Pipeline Result : [{'label': 'ATTACK', 'score': 0.9999988181607918}]
====================================================================
✅ All ONNX (ONNX FP16 (model_fp16.onnx)) tests completed successfully!
====================================================================
☕ Enterprise Java & Tomcat Integration (ONNX Runtime)
For low-latency production deployments in Java (Spring Boot / Spring Cloud Gateway, Jakarta EE / Tomcat Filter, Quarkus), IronJean WAF provides three ONNX model variants (model.onnx, model_quantized_int8.onnx, model_fp16.onnx) executed via ONNX Runtime and the Deep Java Library (DJL) HuggingFace tokenizer:
- 1:1 Normalization Parity (
WAFInferenceNormalization.java↔HTTPNormalizer): The Java Servlet filter normalizes incomingHttpServletRequestobjects into canonical 4-landmark sequences (METHOD,URI,HEADERS,BODY), validated across 227/227 production Postman anti-regression tests (GET,POST,PUT,PATCH,DELETE,OPTIONSCORS preflights, complex Markdown documentation, nested JSON, XML/SOAP, and multipart uploads) and live e-banking REST API traffic. - Zero-GC Native Tensor Lifecycle & Thread-Safety: Uses
ThreadLocal<Predictor<NDList, NDList>>over a shared thread-safeZooModelinstance, paired with scopedtry (NDManager manager = onnxModel.getNDManager().newSubManager())blocks to deterministically free C++ ONNX tensors immediately after each request without pressuring the JVM Garbage Collector.
📊 ONNX Model Variants: Production Latency, Footprint & Precision Comparison
| ONNX Model Variant | Footprint | Holdout Accuracy(50/50) | Logits & Precision Drift vs. FP32 | Production Server CPU Latency(Seq: 68–83 / 180 tok) | Production GPU Latency(NVIDIA L4 / A100) | RecommendedTarget Hardware |
|---|---|---|---|---|---|---|
model.onnx(FP32) | 569 MB | 100.00%(50/50) | [+6.9434, -5.0604](AttackProb: 0.0006%)0.0000% drift (Baseline Reference) | ~4 – 7 ms / ~9 – 14 ms | ~1.4 – 2.2 ms | Production CPU Server(AVX2 / AVX-512 FMA) & GPU |
model_fp16.onnx(FP16**) | 285 MB(2× smaller) | 100.00%(50/50) | [+6.9383, -5.0571](AttackProb: 0.0006%)< 0.0001% drift (Δlogit = 0.005, virtually lossless) | ~12 – 22 ms(CPU F16C cast overhead) | ~0.8 – 1.4 ms ⚡ | Production GPU Only(NVIDIA Tensor Cores) |
model_quantized_int8.onnx(QUInt8*) | 254 MB(2.2× smaller) | 100.00%(50/50) | [+6.0061, -4.1841](AttackProb: 0.0038%)0.00% classification loss (ΔProb = +0.0032%, Δlogit ≈ 0.9) | ~2 – 4 ms / ~4 – 7 ms ⚡ | CPU-targeted | Production CPU(AVX-512 VNNI / Low-RAM / Long Payloads) |
💡 * Architecture Notes on
INT8&FP16ONNX Exports:
model_quantized_int8.onnx(QUInt8Hybrid Quantization): Uses unsigned 8-bit dynamic quantization (QuantType.QUInt8) restricted to transformerMatMullayers while keeping the token embedding table (/model/embeddings/tok_embeddings/Gather) and the final Landmark Pooling classification head (/classifier/Gemm) in nativeFP32. This prevents AVX2/AVX-512vpmaddubsw16-bit signed accumulator saturation on GeGLU activations and preserves 100.00% (50/50) classification parity with a minimal logit margin reduction (Δlogit ≈ 0.9, shifting benign request probability from0.0006%to0.0038%, both rounding to0.0000).model_fp16.onnx(FP16withkeep_io_types=True): Exported viaonnxruntime.transformers.float16withFP32outputlogitsfor plug-and-play Java DJL compatibility. On x86-64 CPUs lacking nativeAVX512-FP16FMA units,FP16incurs a ~2.3× latency penalty compared toFP32due to continuousF16C(FP16↔FP32) register conversions; reservemodel_fp16.onnxfor NVIDIA Tensor Core GPU deployments (0.8–1.4 ms) and deploymodel.onnx(FP32) ormodel_quantized_int8.onnx(QUInt8) on CPU servers (2–7 ms).
package com.security.waf;
import ai.djl.inference.Predictor;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.NDList;
import ai.djl.ndarray.NDManager;
import ai.djl.repository.zoo.ZooModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ModernBertWafPredictor {
private static final Logger log = LoggerFactory.getLogger(ModernBertWafPredictor.class);
// The loaded ONNX model, thread-safe and shared across the application
private final ZooModel<NDList, NDList> onnxModel;
// ThreadLocal predictor since Predictor objects are NOT thread-safe in DJL
private final ThreadLocal<Predictor<NDList, NDList>> predictorPool;
public ModernBertWafPredictor(ZooModel<NDList, NDList> onnxModel) {
this.onnxModel = onnxModel;
this.predictorPool = ThreadLocal.withInitial(onnxModel::newPredictor);
}
/**
* Executes the WAF inference using dynamic sequence lengths.
*
* @param tokenIds The tokenized HTTP payload, inherently variable in length.
* @return true if the payload is classified as an Attack, false if Safe.
*/
public boolean isMalicious(long[] tokenIds) {
Predictor<NDList, NDList> predictor = predictorPool.get();
int actualSequenceLength = tokenIds.length;
long startTime = System.currentTimeMillis();
// CRITICAL: Try-with-resources to prevent C++ native memory leaks.
// Bypasses the Java Garbage Collector for immediate tensor destruction.
try (NDManager manager = onnxModel.getNDManager().newSubManager()) {
// 1. Construct input_ids with shape [1, actualSequenceLength]
// This perfectly matches the dynamic_axes 'sequence_length' configured in Python
NDArray inputIds = manager.create(new long[][]{ tokenIds });
inputIds.setName("input_ids");
// 2. Construct attention_mask with shape [1, actualSequenceLength]
// Since we use exact sizing instead of padding, all tokens are real.
// Therefore, the mask is simply an array of 1s of the same length.
long[] maskArray = new long[actualSequenceLength];
java.util.Arrays.fill(maskArray, 1L);
NDArray attentionMask = manager.create(new long[][]{ maskArray });
attentionMask.setName("attention_mask");
// 3. Package tensors into an NDList for the ONNX session
NDList inputs = new NDList(inputIds, attentionMask);
// 4. Run native C++ inference
NDList outputs = predictor.predict(inputs);
// 5. Extract logits.
// Shape is [1, 2] (Batch size 1, 2 probability classes: Safe vs Attack)
NDArray logits = outputs.getFirst();
// Apply softmax to convert raw logits to probabilities [0.0 - 1.0]
NDArray probabilities = logits.softmax(1);
// Extract the probability for class 1 (Attack)
float attackProbability = probabilities.getFloat(0, 1);
// Apply custom threshold (0.85 balances aggressive threat detection with dev/scanner tolerance)
float threshold = 0.85f;
boolean isMalicious = attackProbability > threshold;
if (log.isDebugEnabled()) {
//WafLogitAnalyzer.analyzeOnnxOutput(outputs);
long duration = System.currentTimeMillis() - startTime;
log.debug("WAF Inference - SeqLength: {} | AttackProb: {} | Prediction: {} | Execution Time: {} ms",
actualSequenceLength, String.format("%.4f", attackProbability), isMalicious ? "ATTACK" : "SAFE", duration);
}
return isMalicious;
} catch (Exception e) {
log.error("WAF Inference failed. Failsafe activated: blocking request.", e);
// Default deny in security contexts
return true;
}
}
/**
* Called during Tomcat shutdown or application undeploy to release native ONNX resources.
*/
public void close() {
if (predictorPool != null) {
predictorPool.remove();
}
if (onnxModel != null) {
onnxModel.close();
}
}
}
📃 License
Licensed under the Apache License, Version 2.0. Free for academic, personal, and commercial enterprise use.
🖇️ Author
@software{IronJean-v2-ModernBERT-WAF,
author = {Franck Andriano},
title = {IronJean WAF v2.6: Enterprise Web Application Firewall Powered by ModernBERT and Landmark Pooling},
year = {2026},
publisher = {Hugging Face},
url = {https://huggingface.co/Metabaron6/IronJean-v2-ModernBERT-WAF}
}