/ Модель

Характеристики

Контекст
8 192 токена
Параметры
149 млн
Лицензия
Apache 2.0
Архитектура
modernbert · dense
Базовая модель
ModernBERT-base
Библиотека
transformers
Опубликована
11 окт 2026

IronJean-v2-ModernBERT-WAF

Классификация текстаТекст → label3 профессии

Дообученный на ModernBERT англоязычный классификатор для выявления вредоносных HTTP-запросов к REST API и веб-приложениям.

386скачиваний за 30 дней2лайкавеса обновлены22 ноя 2026

Бенчмарки

Как модель справилась с задачами пользователей ailist и что о ней публикуют открытые лидерборды

Публичные оценки

Из открытых лидербордов. Сравнивайте результаты одного теста при одинаковых условиях — отсутствие оценки не значит, что модель хуже.

В подключённых источниках результатов для этой модели пока нет.

Что умеет модель

Описание составлено по карточке модели и метаданным Hugging Face

IronJean WAF v2.6 — англоязычный классификатор HTTP-запросов для обнаружения атак на REST API и современные серверные приложения. Модель разработана Metabaron6 на базе encoder-модели ModernBERT-base и дообучена для классификации запросов как безопасных или вредоносных. В карточке указаны архитектура ModernBERT, 149 млн параметров и контекст до 8192 токенов; модель принимает текстовое представление HTTP-запроса и выдаёт результат классификации.

Модель рассчитана на проверку REST/JSON, GraphQL, XML/SOAP, форм и multipart-запросов, а также данных OAuth2/JWT. В README описаны нормализация для противодействия обходам, обработка длинных тел с помощью скользящих окон и адаптация под API по Swagger или OpenAPI. Автор приводит высокие результаты на собственных и внешних тестах, однако это заявления карточки и не являются независимой гарантией качества в конкретной среде.

Репозиторий содержит веса Safetensors и ONNX; для использования заявлены Transformers и ONNX Runtime. Лицензия — Apache-2.0. Это специализированный английский классификатор для задач веб-безопасности; его следует оценивать и калибровать на трафике целевого приложения.

Сценарии применения

  • классификация HTTP-запросов как безопасных или вредоносных
  • обнаружение SQL-инъекций в запросах API
  • выявление XSS и попыток обхода фильтров
  • проверка длинных JSON-тел запросов на атаки
  • фильтрация запросов на шлюзе REST API

Ограничения

Карточка описывает целевую область как англоязычную; качество на других языках не подтверждено. Заявленные результаты тестов приведены автором README и сами по себе не гарантируют такую же точность на реальном трафике.

Для каких профессий подходит3

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

🛡️ IronJean v2.6 ModernBERT WAF - Vectorized Landmark Pooling

Hugging Face Model Live Playground Architecture Context Window Inference Runtime

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 native IronJeanWAFPipeline chunking for oversized HTTP bodies (> 8,000 chars, up to 32 overlapping 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 _NormalizedLandmarkStr sentinel guaranteeing single-pass normalization.
  • Upgraded HTTPNormalizer v2.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, >= 3 consecutive &#x..; / &#..; → printable ASCII 32..126 incl. < and >), extends &lt;... 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 as C:\temp), introduces Content-Type-aware decode_plus handling (preserving literal + in JSON/XML/Multipart/User-Agent and C++ in queries), bounds slash-delimited Base64 scanning to O(k) linear complexity (eliminating O(k²) CPU DoS), and enforces 1:1 normalize_sequence() ↔ serialize_http() round-trip parity.
  • Upgraded test_hf.py v2.6:
    • Integrates IronJeanWAFClassifier.build_sliding_windows as 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,469 unique tokens / 11,932 processed tokens across 4 chunks) Benign JSON Batch and a 21.5 KB (21,553 chars) Needle-in-a-Haystack SQLi @END test (plus a 3rd pipeline() check), and hardens cross-platform Linux/Windows CUDAExecutionProvider detection.
  • Contrastive Technical Markdown/LaTeX Immunity & URI Rebalancing v40:
    • Adds 50/50 contrastive technical documentation blocks inside structured text/markdown and text/plain bodies 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 (1 FP, 0 FN) internally and 100.00% Precision (0 FP) across all 5 external WAF benchmarks (including shengqin-waf 0 FP / 0 genuine exploits missed).

🆕 News notes v2.5 - 18/11/2026 (continued)

  • Upgraded model Safetensors FP16 (model.fp16.safetensors):
    • Dual Hugging Face SafeTensors Release (FP32 + FP16): Now exports both the master FP32 checkpoint (model.safetensors, 568.5 MB) and a native half-precision FP16 checkpoint (model.fp16.safetensors, 284.2 MB, loadable via variant="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).
  • Upgraded HTTPNormalizer v2.5 New 2025–2026 Critical CVEs & Runtime/Parser Anti-Evasion:
    • CVE-2026-114938 (Java4Shell — HotSpot JVM AVX-512 decodeBlock Intrinsic Underflow RCE)
    • CVE-2026-29000 (PHP2Shell — PHP Engine rfc1867 Multipart & PHP_SESSION_UPLOAD_PROGRESS Heap/UAF RCE)
    • CVE-2025-24813 (Apache Tomcat Partial PUT + Content-Range .session / /session Deserialization RCE)
    • CVE-2026-21876 (OWASP CRS Multipart Content-Type: charset=... Smuggling & UTF-7 / IBM037 Evasion)
    • 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.py v2.5:
    • Default SafeTensors FP16 (--fp16) vs. Explicit ONNX (--onnx --fp16): Running python test_hf.py --fp16 now benchmarks SafeTensors FP16 (model.fp16.safetensors, variant="fp16") by default (symmetrical with --fp32 for model.safetensors), while passing --onnx --fp16 (or --onnx fp16) targets ONNX Runtime FP16 (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_modules prior to from_pretrained(..., trust_remote_code=True).

🆕 News notes v2.5 - 17/11/2026 (continued)

  • Upgraded HTTPNormalizer v2.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 (\uFFFD rejection) 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 (including OPTIONS CORS preflights and multipart/form-data file uploads).
  • Upgraded test_hf.py v2.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_64 and site-packages/nvidia/cudnn/bin) via os.add_dll_directory() and PATH prior to initializing onnxruntime-gpu, seamlessly activating CUDAExecutionProvider on 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 IronJeanWAFPipeline verification block to execute across both native Hugging Face pipeline() and ONNX Runtime sessions on Landmark strings and raw HTTP dictionaries.

🆕 News notes v2.5 - 11/11/2026

  • Upgraded HTTPNormalizer v2.5: Pre-compiled LRU regex engine (maxsize=2048), multi-block/double-encoded MySQL /*!...*/ comment unwrapping, UTF-16LE/ASCII hex SQL literal decoding (0x...), standalone WAITFOR DELAY canonicalization, strengthened Cookie/Redirect/CMD guards, and strict key=value raw-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-5 loss — 99.9985% confidence), 100.00% on v34b (160,500/160,500 at 719.25 req/s), waf-bench (77/77), gotestwaf (822/822), and openappsec-attacks (73,924/73,924), 99.93% on shengqin-waf (0 FP at 0.85 prod threshold), and 100.00% Precision (0 FP) on http-attack-requests.
  • Terminal Phase of Training (v34 → v34b): Early low-LR warmup alignment of the classification head combined with lossless Cookie: exploit preservation (HTTPNormalizer v2.5) eliminated contradictory [SEP] header signals and late Focal Loss (γ = 2.0) gradient spikes—driving eval_loss 4.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/ONNX landmark_pool kernel across training and Hugging Face trust_remote_code=True, with interactive TensorBoard logs published in ./runs.

🆕 News notes v2.4 - 7/11/2026

  • Upgraded HTTPNormalizer v2.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 &amp; before numeric or named HTML/XSS entities (&amp;#0000106, &amp;lt;, &amp;colon;), supports truncated HTML5 &perio with 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 %c0n dot-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, standalone CONCAT(...) with SQL introspection functions (database(), version(), user(), information_schema), long hex literals (0x[0-9a-f]{24,}), boolean OR/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/net test 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).
  • Fixed ONNX Exporter (export_onnx.py) for FP16 (model_fp16.onnx) & Dynamic INT8 (model_quantized_int8.onnx):
    • FP16 RoPE Cast Graph Fix: Replaced legacy onnxconverter_common.float16—which mutated ModernBERT's Rotary Position Embedding node (/model/layers.*/attn/rotary_emb/Cast_1) without updating downstream ValueInfoProto signatures (ORT_FAIL: Type (tensor(float16)) ... does not match expected type (tensor(float)))—with ONNX Runtime's transformer-aware onnxruntime.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/O logits in tensor(float) (FP32) for direct Java DJL compatibility.
    • Lossless Dynamic INT8 Quantization (100% Holdout Parity on CPU): Fixed the weight/logit collapse caused by naive QuantType.QInt8 dynamic quantization on ModernBERT (where multiplying unsigned uint8 activations by signed int8 weights overflows AVX2 vpmaddubsw 16-bit accumulators on high-amplitude GeGLU layers, while quantizing Gather and Gemm degrades token embeddings and Landmark Pooling logits). Switching to weight_type=QuantType.QUInt8 (32-bit accumulation), restricting quantization to op_types_to_quantize=['MatMul'] (keeping token embeddings in FP32), and excluding the final Landmark classification head (nodes_to_exclude=['/classifier/Gemm']) restores 100.00% (50/50) Holdout accuracy at a 254 MB footprint (~2–4 ms production CPU latency alongside native FP32).
  • Macro-Topological URI Prefix & Query-Key De-Biasing (v33 Dataset): 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 (0 FP, 0 FN) on the 160,500-request v33 corpus, 100.00% on waf-bench (77/77), 100.00% on gotestwaf (822/822), 100.00% on openappsec-attacks (73,924/73,924), 99.73% on shengqin-waf (1 FP / 0.10% FPR), and 98.46% on http-attack-requests with 100.00% Precision (0 FP / 0.00% FPR).

🆕 News notes v2.3 - 31/10/2026

  • Upgraded HTTPNormalizer v2.3: Now bundled via trust_remote_code=True. Added in-distribution OPTIONS / HEAD verb canonicalization (GET when EMPTY_BODY, POST if a body is present) and Origin authority anonymization for zero-false-positive CORS preflight inspection, smart Windows CRLF (\r\n → \n) body normalization (preserving multipart/form-data and CRLF/Smuggling payloads), recursive [SEP] landmark anti-collision filtering across URI/HEADERS/BODY, deep payload inspection across non-target HTTP headers (Accept-Encoding, Accept with MIME wildcard stripping, Cache-Control, Connection), 100% deterministic User-Agent canonicalization (canonicalize_healthy_user_agent) with a configurable BLOCK_SCANNER_USER_AGENTS toggle, 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 CRLF command 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 HTTPNormalizer v2.2: Added authority IP normalization (Host/Referer → <DOMAIN>, local LAN IPs), exploit-aware <DOMAIN>/<IP> guards, and recursive \u00XX Unicode 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%), and ai-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) and Content-Type formats (JSON objects/arrays, XML/SOAP, Form, Multipart, gRPC).
  • Markdown & HTML5 False-Positive Immunity: Native support for text/markdown (technical prose, code blocks) and text/html documents without false alarms.
  • Upgraded HTTPNormalizer v2.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, and BODY.
  • 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 under AutoModelForSequenceClassification and pipeline("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 OPTIONS and HEAD requests to METHOD: GET (or POST if 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,000 characters are segmented into overlapping windows (7,600-char window, 1,200-char overlap / 6,400-char stride, up to 32 chunks / ~205 KB+), each prefixed by the original METHOD, URI, and HEADERS landmarks. 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 past 205 KB.
  • Syntax-Aware Boundary Snapping & Balanced Container Wrapping: Automatically detects JSON, XML, FORM, and TEXT bodies, 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 _NormalizedLandmarkStr sentinel guarantees single-pass HTTPNormalizer execution 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 peak 2 × 10⁻⁵ with 10% warmup down to 0) to sharpen output probabilities without compressing OOD logit margins—driving validation Recall to 100.00% (0 FN), 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 PhaseLoss FunctionTrain LossEval LossEval AccuracyEval PrecisionEval RecallEval F1-ScoreLong-Seq F1 (>= 512t / >= 900t)
Epoch 1.0Focal Loss (γ = 2.0)0.0274890.00054799.9439%100.0000%99.8879%99.9439%1.0000 / 1.0000
Epoch 2.0Focal Loss (γ = 2.0)0.0007430.00038399.9439%99.9875%99.9003%99.9439%0.9989 / 0.9980
Epoch 3.0Cross-Entropy Calibration (ls=0.0)0.0001420.00046599.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×8 on 343 batches > 1,024t and 4×4 on 207 batches > 1,536t out of 9,029), reaching 99.9439% validation Accuracy (eval_loss: 0.000547), 100.0000% Precision (0 FP), and 1.0000 F1 on both long-sequence validation buckets (>= 512t, N = 1,637; >= 900t, N = 904).
  • Epoch 2.0: Hard-Example Mining (train_loss drops 37× to 0.000743, eval_loss drops to 0.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 to 99.9003% while keeping Precision at 99.9875%.
  • Epoch 3.0: Terminal Calibration & Long-Context Generalization (train_loss: 0.000142 in Epoch 3, 0.009458 global mean): Switching to standard Cross-Entropy (label_smoothing = 0.0) under linear LR decay drives validation Recall to 100.0000% (0 FN across all 16,050 hold-out samples), Accuracy & F1 to 99.9938% (16,049 / 16,050, only 1 FP), and both Long-Sequence validation buckets (>= 512t, N = 1,637; >= 900t, N = 904) back to 100.00% (F1 = 1.0000)—reaching "Five Nines" (99.9994% Global Accuracy, 160,499 / 160,500, 1 FP, 0 FN) 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 datasetHugging Face / Source DatasetRequestsAccuracyPrecisionRecallF1-ScoreTPTNFP (FPR)FN (FNR)Throughput (Latency)
v40 (Internal)dataset_v40_rest_150k + 10.5k noise160,50099.9994%99.9988%100.0000%99.9994%80,25080,2491 (0.0012%)0 (0.0000%)505.45 req/s(1.98 ms)
waf-benchnetgoat-ai/WAF-Bench77100.00%100.00%100.00%100.00%55220 (0.00%)0 (0.00%)261.54 req/s(3.82 ms)
gotestwafwallarm/gotestwaf(44 OWASP/API suites)822100.00%100.00%100.00%100.00%6761460 (0.00%)0 (0.00%)442.37 req/s(2.26 ms)
openappsec-attacksopenappsec/waf-comparison-project(73.9K Multi-Vector Attacks)73,92499.99%100.00%99.99%100.00%73,92000 (0.00%)4 (0.01%) *929.92 req/s(1.08 ms)
shengqin-wafshengqin/web-attacks5,52399.78%100.00%99.73%99.87%4,4981,0130 (0.00%)12 (0.27%) *1,495.89 req/s(0.67 ms)
http-attack-requestsSecureAI-SE/http-attack-requests7,00098.49%100.00%98.23%99.11%5,8941,0000 (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% on xss (41,888/41,888), traversal (28,314/28,314), sqli (916/916), log4shell (220/220), xxe (70/70), and shellshock (48/48). All 4 remaining cmdexe FNs are bare, operator-free single words (p=ifconfig, p=ipconfig without any shell separator) intentionally de-biased to eliminate production prose false positives.
  • shengqin-waf (5,523): Achieves 100.00% Precision (0 FP) and 99.87% F1. All 12 remaining FNs are upstream Excel spreadsheet formula corruptions (11× /?q=#ERROR! and 1× /?q=#NAME?) — 0 genuine exploits missed.
  • http-attack-requests (7,000): Maintains 100.00% Precision (0 FP) while reducing FNs from 113 (98.39% Acc / 99.05% F1 in v2.5) down to 106 (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; OPTIONS and HEAD are automatically canonicalized to GET or POST by HTTPNormalizer).
  • [SEP]: Delimiter token (50282 in 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 by HTTPNormalizer.
  • BODY: Recursively decoded payload, or EMPTY_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 directly model.serialize_http(...) / classifier.normalizer).
  • Direct local import: from normalizer_ironjean import HTTPNormalizer (also re-exported by core.normalizer and bundled in test_hf.py).
  • Scanner User-Agent Policy Toggle: Set HTTPNormalizer.BLOCK_SCANNER_USER_AGENTS = True to block offensive scanner banners (sqlmap, Nikto, Nuclei, OpenVAS, ffuf) even without an exploit payload (default False = 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.11 or 3.12 recommended)
  • PyTorch: torch >= 2.4.0 (with CUDA 12.1+ recommended for hardware bfloat16 and FlashAttention-2 / SDPA acceleration)
  • Hugging Face Transformers: transformers >= 4.48.0 (mandatory — native ModernBERT support requires 4.48.0+)
  • ONNX Runtime (Optional for --onnx mode):
    • CPU: pip install onnxruntime
    • GPU (CUDA 13 & cuDNN 9): pip install onnxruntime-gpu nvidia-cublas nvidia-cuda-runtime nvidia-cufft nvidia-cudnn-cu13

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) loads IronJeanWAFPipeline, 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) exposes model.normalizer (HTTPNormalizer) and model.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 (SafeTensors FP32, CUDA bfloat16) or python test_hf.py --hub --fp16 --gpu (SafeTensors FP16, CUDA float16).

====================================================================
🛡️  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 incoming HttpServletRequest objects into canonical 4-landmark sequences (METHOD, URI, HEADERS, BODY), validated across 227/227 production Postman anti-regression tests (GET, POST, PUT, PATCH, DELETE, OPTIONS CORS 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-safe ZooModel instance, paired with scoped try (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 VariantFootprintHoldout Accuracy(50/50)Logits & Precision Drift vs. FP32Production Server CPU Latency(Seq: 68–83 / 180 tok)Production GPU Latency(NVIDIA L4 / A100)RecommendedTarget Hardware
model.onnx(FP32)569 MB100.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 msProduction 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-targetedProduction CPU(AVX-512 VNNI / Low-RAM / Long Payloads)

💡 * Architecture Notes on INT8 & FP16 ONNX Exports:

  • model_quantized_int8.onnx (QUInt8 Hybrid Quantization): Uses unsigned 8-bit dynamic quantization (QuantType.QUInt8) restricted to transformer MatMul layers while keeping the token embedding table (/model/embeddings/tok_embeddings/Gather) and the final Landmark Pooling classification head (/classifier/Gemm) in native FP32. This prevents AVX2/AVX-512 vpmaddubsw 16-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 from 0.0006% to 0.0038%, both rounding to 0.0000).
  • model_fp16.onnx (FP16 with keep_io_types=True): Exported via onnxruntime.transformers.float16 with FP32 output logits for plug-and-play Java DJL compatibility. On x86-64 CPUs lacking native AVX512-FP16 FMA units, FP16 incurs a ~2.3× latency penalty compared to FP32 due to continuous F16C (FP16 ↔ FP32) register conversions; reserve model_fp16.onnx for NVIDIA Tensor Core GPU deployments (0.8–1.4 ms) and deploy model.onnx (FP32) or model_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}
}

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм · transformers · text-classification

Можно запустить

Подбираем GPU…

Класс архитектуры
IronJeanWAFClassifier
Ревизия весов
3153366

0 моделей