--- title: LLM Threat Shield emoji: ⚡ colorFrom: red colorTo: purple sdk: gradio sdk_version: 5.9.1 python_version: '3.11' app_file: app.py pinned: false license: mit --- # ⚡ LLM Threat Shield > Real-time adversarial attack detection for LLM systems — 4 fine-tuned DistilBERT classifiers covering OWASP LLM Top 10. --- ## What It Does Paste any LLM prompt, user message, model output, or retrieved document. Get an instant threat verdict with calibrated confidence scores. ``` Input text │ ├──▶ 💉 Prompt Injection detector ──▶ INJECTION 94% 🔴 HIGH ├──▶ 🔓 Jailbreak detector ──▶ SAFE 8% 🟢 CLEAN ├──▶ ☣️ Insecure Output detector ──▶ SAFE 3% 🟢 CLEAN └──▶ 🕵️ Indirect Injection detector ──▶ CLEAN 2% 🟢 CLEAN Overall: 🔴 CRITICAL — high-confidence attack detected ``` --- ## Architecture ``` ┌──────────────────────────────────────────────────────────────────────┐ │ Gradio Frontend │ │ 8 tabs: Injection │ Jailbreak │ Insecure │ Indirect │ PII │ │ │ Scan All │ Model Health │ Adversarial Tests │ └───────────────────────┬──────────────────────────────────────────────┘ │ ┌───────▼────────┐ │ preprocess() │ NFKC normalize, strip control chars └───────┬────────┘ │ ┌─────────────┼──────────────┬────────────────┐ ▼ ▼ ▼ ▼ ┌────────────┐ ┌───────────┐ ┌──────────────┐ ┌──────────────┐ │DistilBERT │ │DistilBERT │ │ DistilBERT │ │ DistilBERT │ │ Injection │ │ Jailbreak │ │Insecure Output│ │ Indirect │ └─────┬──────┘ └─────┬─────┘ └──────┬───────┘ └──────┬───────┘ │ │ │ │ └──────────────┴───────────────┴─────────────────┘ │ ┌──────────▼──────────┐ │ _score() + T=1.5 │ temperature calibration │ softmax(logits/T) │ softens overconfident scores └──────────┬──────────┘ │ ┌──────────▼──────────┐ │ severity verdict │ 🔴 HIGH / 🟡 MED / 🟠 LOW / 🟢 CLEAN └─────────────────────┘ ``` --- ## Threat Coverage | Tab | Threat | OWASP | Labels | |---|---|---|---| | 💉 Prompt Injection | Instruction override, system prompt extraction, role hijacking | LLM01 | `INJECTION` / `LEGIT` | | 🔓 Jailbreak | DAN prompts, developer mode, persona bypass, rule negation | LLM01 | `JAILBREAK` / `SAFE` | | ☣️ Insecure Output | XSS, SQL injection, command injection, path traversal, SSTI | LLM02 | `MALICIOUS` / `SAFE` | | 🕵️ Indirect Injection | RAG poisoning, HTML comment smuggling, document injection | LLM01 | `INDIRECT` / `CLEAN` | | 🔏 PII Scanner | Credit cards, SSNs, emails, phones, API keys, passports, IPs | — | regex-based | | 🔍 Scan All | All 4 ML detectors + PII in one pass, unified threat report | — | — | | 📊 Model Health | Live F1/precision/recall benchmark, 10 examples per model | — | — | | 🧪 Adversarial Tests | 9 bypass tests for obfuscation resistance | — | — | --- ## Models | Model | HF Hub | Base | Version | |---|---|---|---| | Prompt Injection | [`Builder117/distilbert-prompt-injection`](https://huggingface.co/Builder117/distilbert-prompt-injection) | distilbert-base-uncased | v3 | | Jailbreak | [`Builder117/distilbert-jailbreak`](https://huggingface.co/Builder117/distilbert-jailbreak) | distilbert-base-uncased | v2 | | Insecure Output | [`Builder117/distilbert-insecure-output`](https://huggingface.co/Builder117/distilbert-insecure-output) | distilbert-base-uncased | v2 | | Indirect Injection | [`Builder117/distilbert-indirect-injection`](https://huggingface.co/Builder117/distilbert-indirect-injection) | distilbert-base-uncased | v2 | --- ## Training Data Combined datasets published on HF Hub — versioned, citable, ready to use directly in training: | Model | Dataset | Size | |---|---|---| | Prompt Injection | [`Builder117/llm-threat-injection-dataset`](https://huggingface.co/datasets/Builder117/llm-threat-injection-dataset) | ~2,370 | | Jailbreak | [`Builder117/llm-threat-jailbreak-dataset`](https://huggingface.co/datasets/Builder117/llm-threat-jailbreak-dataset) | ~3,092 | | Insecure Output | [`Builder117/llm-threat-insecure-output-dataset`](https://huggingface.co/datasets/Builder117/llm-threat-insecure-output-dataset) | ~5,080 | | Indirect Injection | [`Builder117/llm-threat-indirect-injection-dataset`](https://huggingface.co/datasets/Builder117/llm-threat-indirect-injection-dataset) | ~575+ | Each dataset has `train` / `test` splits (85/15, stratified) and a `source` column tracking which upstream dataset each row came from. ### Prompt Injection (v3) | Source | Examples | Notes | |---|---|---| | `deepset/prompt-injections` | ~660 | Public, labeled | | `JasperLS/prompt-injections` | ~500 | Public, labeled | | `fmops/prompt-injection` | ~800 | Public, labeled | | `Harelix/prompt-injection-mixed-attacks-2024` | ~400 | Public, labeled | | Synthetic hard negatives | 10 | Benign imperatives that caused FP | | **Total** | **~2,370** | | ### Jailbreak (v2) | Source | Examples | Notes | |---|---|---| | `rubend18/ChatGPT-Jailbreak-Prompts` | ~80 | DAN, roleplay | | `jackhhao/jailbreak-classification` | ~1,500 | Labeled jailbreak/benign | | `TrustAIRLab/in-the-wild-jailbreak-prompts` | ~1,000 | Real-world jailbreaks | | `markush1/LLM-Jailbreak-Classifier-Dataset` | ~500 | Labeled | | Synthetic hard negatives | 12 | Legit creative/roleplay to fix FP | | **Total** | **~3,092** | | ### Insecure Output (v2) | Source | Examples | Notes | |---|---|---| | `FredZhang7/sqli-attack-dataset` | ~4,000 | SQL injection attacks | | `Multilingual-Multimodal-NLP/xss-dataset` | ~1,000 | XSS payloads | | Synthetic malicious (XSS, SQLi, CMDi, LFI, SSTI, XXE) | 45 | Hand-crafted payloads | | Synthetic safe (parameterized SQL, sanitized code) | 35 | Safe counterexamples | | **Total** | **~5,080** | | > v1 had only **41 synthetic examples** — root cause of "everything shows LOW". ### Indirect Injection (v2) | Source | Examples | Notes | |---|---|---| | `structuredlabs/indirect-prompt-injection` | varies | Indirect injection specific | | `deepset/prompt-injections` (repurposed) | ~150 + benign | Wrapped in document context | | Synthetic: 15 contexts × 20 injection payloads | 300 | Inline poisoned documents | | Synthetic: 15 contexts × 5 suffix injections | 75 | Suffix-hidden injections | | Clean documents (augmented) | 50 | Benign retrieved content | | **Total** | **~575+** | | > v1 had only **20 synthetic examples**. --- ## PII Patterns Regex-based, no model required. Tightened patterns to reduce false positives: | Entity | Pattern | Notes | |---|---|---| | Credit Card | `(?:\d{4}[\s\-]){3}\d{4}` or `\d{16}` | Requires grouping — avoids plain number strings | | SSN | `\d{3}-\d{2}-\d{4}` | Standard US format | | Email | `[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}` | | | Phone | `(?:\+?1[\s\-]?)?\(?\d{3}\)?[\s\-]?\d{3}[\s\-]?\d{4}` | US/intl | | IP Address | `(?:\d{1,3}\.){3}\d{1,3}` | | | Passport | `[A-Z]{2}\d{7,9}` | 2 letters + 7–9 digits (tightened) | | API Key | `(?:sk\|pk\|api\|key)[-_][A-Za-z0-9]{20,}` | Common prefixes | --- ## Confidence Calibration Raw softmax scores from fine-tuned classifiers are overconfident (scores cluster near 0.0 or 1.0). Temperature scaling softens this: ``` calibrated = softmax(logits / T) T = 1.5 ``` **Effect of temperature on a score of 0.95 raw:** ``` T = 1.0 → 0.950 (overconfident, no change) T = 1.2 → 0.920 T = 1.5 → 0.880 ← used T = 2.0 → 0.820 ``` T=1.5 chosen to reduce false HIGH verdicts while preserving detection signal. --- ## Severity Thresholds ``` Score Verdict ───────────────────────────────────────── ≥ 0.90 → 🔴 HIGH — very likely attack ≥ 0.70 → 🟡 MEDIUM — probable attack ≥ 0.50 → 🟠 LOW — weak signal, review < 0.50 → 🟢 CLEAN — no threat detected ``` --- ## Preprocessing Pipeline Every input is normalised through 7 steps before reaching any model: 1. **NFKC Unicode normalisation** — converts fullwidth chars (`Ignore` → `Ignore`), ligatures, and compatibility variants to ASCII 2. **Zero-width character stripping** — removes U+200B, U+200C, U+200D, U+FEFF, U+2060 (invisible chars used to break tokenisation) 3. **Control character removal** — strips null bytes, BEL, ESC, and other non-printable control chars 4. **Leet-speak translation** — `0→o`, `1→i`, `3→e`, `4→a`, `5→s`, `7→t`, `@→a`, `$→s`, `!→i` 5. **Excess whitespace collapse** — normalises multiple spaces between word chars to single space 6. **Truncation** — 2000 chars max before tokenizer (tokenizer further truncates to 512 tokens) 7. **Strip + trim** ## Sliding Window Inference Inputs longer than 512 chars are scored twice to catch suffix-buried attacks: ``` score(text[:512]) ← catches attacks at document start score(text[-512:]) ← catches attacks buried at end (suffix attack) final score = max(both segments) ``` ## Rate Limiting Max 10 requests per 60 seconds per tab, tracked via `gr.State` session timestamp list. No external dependency. Resets on page refresh. --- ## Known Limitations | Attack Type | Status | |---|---| | Direct injection (clear text) | ✅ Detected | | Jailbreak via DAN / developer mode | ✅ Detected | | XSS / SQLi in LLM output | ✅ Detected | | RAG document poisoning | ✅ Detected | | Unicode fullwidth obfuscation (`Ignore`) | ✅ Fixed (NFKC normalisation) | | Zero-width char insertion | ✅ Fixed (regex strip) | | Leet speak (`1gn0r3`) | ✅ Fixed (translate table) | | Suffix injection (attack buried past 512 tokens) | ✅ Fixed (sliding window) | | Base64-encoded payloads | ❌ Not decoded | | Multilingual attacks | ❌ English only | --- ## Evaluation **CLI (Kaggle / local):** ```bash python training/eval_benchmark.py # Loads public HF datasets, runs inference on all 4 models # Prints F1/precision/recall per model, saves benchmark_results.json # Exits 1 if any model F1 < 0.80 ``` **In-app (no install):** - `📊 Model Health` tab — runs 10 held-out examples per model (5 attack + 5 clean), shows F1/precision/recall/accuracy with ✅/❌ vs F1 ≥ 0.80 - `🧪 Adversarial Tests` tab — 9 bypass tests (fullwidth unicode, zero-width, leet, mixed case, suffix attack, DAN jailbreak, clean baselines), click-to-run --- ## Logging Predictions logged to `/data/predictions.csv` (HF persistent storage) or `/tmp/predictions.csv` (fallback). ``` ts, detector, input_hash, score, severity 2026-06-21T10:23:01Z, injection, a3f1b2c4d5e6f7a8, 0.941, 🔴 HIGH ``` Input is SHA-256 hashed (first 16 hex chars) — no raw text stored. --- ## Quick Start (local) ```bash git clone https://huggingface.co/spaces/Builder117/LLM_Threat_Shield cd LLM_Threat_Shield pip install transformers torch gradio HF_TOKEN=hf_... python app.py ``` --- ## Retrain Training scripts in `training/`. See `training/RUN_IN_COLAB.md` for full instructions. ```bash # In Google Colab (T4 GPU, ~45 min total) !python training/train_injection_v3.py !python training/train_jailbreak_v2.py !python training/train_insecure_v2.py !python training/train_indirect_v2.py ``` Each script pulls public datasets, combines with synthetic examples, trains 6 epochs with early stopping on F1, and auto-pushes to Hub. --- ## Tech Stack - **Classifiers:** DistilBERT (distilbert-base-uncased), fine-tuned via HuggingFace Trainer - **Inference:** `transformers.pipeline("text-classification", top_k=None)` - **Calibration:** Temperature scaling T=1.5 - **Frontend:** Gradio 5 (Blocks, dark theme, custom CSS) - **Storage:** HF Spaces persistent `/data` volume - **Training:** Google Colab T4 GPU