yomnafarag95/IEEE_Paper
GitHub: yomnafarag95/IEEE_Paper
RAG-Shield 是针对 RAG pipeline 中 prompt injection 攻击的三层集成防御系统,通过异常检测、意图分类与行为监控协同实现低延迟、高精度的实时防护。
Stars: 0 | Forks: 0
# RAG-Shield:针对 RAG Pipeline 中 Prompt Injection 的三层集成防御机制
[](LICENSE)
[](https://www.python.org)
[](logs/)
[](logs/)
[](logs/)
## 概述
**RAG-Shield** 是一个生产就绪的三层集成防御系统,旨在检测并拦截
检索增强生成 (RAG) pipeline 中的 prompt injection 攻击。
它针对**直接** prompt injection(HackAPrompt)、通过检索文档进行的**间接**注入(InjecAgent),
以及金融数据泄露和对抗性规避行为。
### 关键结果(最终评估)
| 指标 | 数值 |
|:------------------------|:---------:|
| ADR 拦截率 | **91.59%** |
| ADR 检测率 | **94.39%** |
| 对抗性规避 ADR | **100%** |
| 误报率 (FPR) | **2.13%** |
| F1 (拦截) | **0.956** |
| AUC-ROC (综合) | **0.963** |
| 平均延迟 (CPU) | ~2,456 ms |
## 架构
```
User Query + Retrieved Chunks
|
+-----v------+
| LAYER 1 | Anomaly Detection
| IsoForest | MiniLM embeddings, ECOD, OCSVM
| ECOD/OCSVM | Hard block at score >= 0.85
+-----+------+
|
+-----v-----------+
| LAYER 2 | Intent Classification
| DeBERTa-v3 ONNX | 86M params, INT8 quantised
| XLM-RoBERTa | Multilingual fallback (560M)
| INT8 quantised | Applied to query AND document chunks
+-----+------------+
|
+-----v----------------+
| LAYER 3 | Semantic / Behavioural Monitor
| Schema Validator | 9 injection-pattern regex rules
| Boundary Tracker | JWT, AWS key, PII exfil detection
| Fine-tuned Cross-Enc | ms-marco-MiniLM (2,000 pair tuned)
+-----+-----------------+
|
+-----v--------------------+
| META-AGGREGATOR | Logistic Regression (CV)
| 10-dim evidence vector | Isotonic probability calibration
| SHA-256 data integrity | Block >= 0.45 | Monitor >= 0.15
+-----+--------------------+
|
ALLOW / MONITOR / BLOCK
```
## 快速开始
```
# 克隆并安装
git clone https://github.com/yomnafarag95/rag-defense-system.git
cd rag-defense-system
pip install -r requirements.txt
# 下载数据集(首次运行时自动获取)
python data_loader.py
# 训练 meta-aggregator(可选 – 不包含预训练权重)
python train_meta_aggregator.py
# 运行 Streamlit 应用
streamlit run app.py
# 使用 Docker 运行
docker build -t rag-shield .
docker run -p 8501:8501 rag-shield
# 全面评估
python eval_suite.py --mode all
# 评估报告包含 headline metrics 的 confidence_intervals_95
# Ablation study
python ablation_study.py
```
## 仓库结构
```
app.py Streamlit interactive interface
orchestrator.py Main pipeline controller (meta-aggregator)
layer1_anomaly.py Isolation Forest + ECOD + OCSVM ensemble
layer2_classifier.py DeBERTa-v3 ONNX INT8 classifier
layer2_multilingual.py XLM-RoBERTa multilingual fallback
layer3_enhanced.py Schema validator + boundary tracker + cross-encoder
layer3_semantic.py Cross-encoder consistency scoring (base)
train_meta_aggregator.py Meta-aggregator training script
generate_l3_pairs.py Training pair generation for L3 fine-tuning
ablation_study.py Per-layer ablation experiments
eval_suite.py Full evaluation suite (standard/benign/evasion)
bootstrap_ci.py Bootstrap confidence intervals
compare_baselines.py Baseline comparison (keyword, BERT, DeBERTa)
fn_analysis.py False negative deep-dive analysis
diagnose_fpr.py False positive root-cause analysis
latency_breakdown.py Per-layer latency profiling
config.py Thresholds, paths, and settings
data_loader.py Dataset download and preprocessing utilities
split_helper.py Deterministic hash-based train/test splitting
keyword_detector.py Keyword blocklist baseline
canary_manager.py Canary token injection and monitoring
obfuscation_decoder.py Base64 / Unicode obfuscation decoder
quantize_onnx.py INT8 quantisation for DeBERTa ONNX
requirements.txt Python dependencies
Dockerfile Docker container configuration
data/ Datasets (not committed -- see data_loader.py)
models/ Trained weights (not committed -- too large)
logs/ Evaluation results and curve plots
```
## 消融实验
| 配置 | ADR | FPR | Precision | F1 |
|:-------------------|:-----:|:-----:|:---------:|:-----:|
| 仅 L1 | 0.435 | 0.110 | 0.483 | 0.458 |
| 仅 L2 | 0.527 | 0.005 | 0.958 | 0.680 |
| 仅 L3 | 1.000 | 0.121 | 0.662 | 0.796 |
| L1 + L2 | 0.641 | 0.114 | 0.571 | 0.604 |
| **完整 pipeline** | **0.916** | **0.021** | **1.000** | **0.956** |
单独使用 L2 获得了最高的 precision (0.958)。L1+L2 组合最大化了召回率(ADR 比单独使用 L2 提高了 21.1%),
证实了两者在检测覆盖范围上具有互补性。文档分块扫描使 L2 的贡献翻倍。
## 基准对比
| 方法 | ADR | FPR | F1 | 延迟 |
|:------------------|:-----:|:-----:|:-----:|:-------:|
| 关键词黑名单 | 0.41 | 0.03 | 0.570 | <5 ms |
| 单个 BERT | 0.58 | 0.08 | 0.650 | 120 ms |
| 单独 DeBERTa | 0.66 | 0.00 | 0.795 | 167 ms |
| 仅异常检测 (L1) | 0.67 | 0.00 | 0.802 | 25 ms |
| **RAG-Shield** | **0.916** | **0.021** | **0.956** | ~2,456 ms (CPU) |
RAG-Shield 是唯一一种在所有攻击类型(直接注入、间接注入、金融数据泄露和对抗性规避)中
实现 Precision = 1.000 并保持极具竞争力的 ADR 的方法。
## 数据集
| 划分 | 来源 | 数量 |
|:------------------------|:----------------------------|:-----:|
| 攻击 | InjecAgent | 62 |
| 攻击 | HackAPrompt 留存集 (seed=42) | 69 |
| **总攻击数** | | **131** |
| 正常 | 多领域企业 QA | 553 |
| 规避 | 手工构造的探测样本 | 7 |
| Meta-aggregator 训练集 | Pipeline 执行日志 | 1,294 |
正常查询涵盖 HR、金融、IT 和医疗 QA —— 刻意采用多领域设计以对
基于 MITRE 训练的 Layer 1 进行压力测试。所有训练/测试集划分均使用确定性的 SHA-256 哈希算法(无随机数种子依赖),以防止数据泄露。
## 延迟
| 组件 | 平均值 | P95 |
|:---------------------|:------:|:-----:|
| Sentence Embedding | 15 ms | 17 ms |
| L1 集成 | 13 ms | 18 ms |
| L2 DeBERTa (ONNX) | 167 ms | 197 ms|
| L3 Cross-Encoder | 33 ms | 36 ms |
| Meta-Aggregator | <1 ms | <1 ms |
| **完整流程 (CPU)** | **~2,456 ms** | -- |
| GPU (预估) | ~80-120 ms | -- |
内存:总计约 2.1 GB(MiniLM 90 MB + DeBERTa 740 MB + XLM-RoBERTa 1.1 GB + Cross-encoder 130 MB)。
INT8 量化可将模型大小缩小 4 倍,且准确率损失不到 2%。
## 已知局限性
| 问题 | 当前数值 | 计划修复方案 |
|:--------------------------------|:-------------:|:-------------------------------------|
| 跨语言 ADR | 0.391 | 微调多语言分类器 |
| CPU 推理延迟 | ~2,456 ms | 部署 GPU -> ~80-120 ms |
| 规避样本集大小 | n=7 | 扩充至 n>=50 以实现可靠的 CI |
| 白盒对抗性 | 尚未运行 | 替代梯度 pipeline |
## 引用
```
@inproceedings{algendy2026ragshield,
title = {RAG-Shield: A Three-Layer Ensemble Defence Against
Prompt Injection in RAG Pipelines},
author = {Algendy, Yasmeen and Algendy, Yomna},
booktitle = {Proceedings of the International Telecommunications
Conference (ITC-Egypt 2026)},
year = {2026},
publisher = {IEEE}
}
```
## 致谢
HuggingFace Transformers · PyOD · scikit-learn · Sentence-Transformers ·
InjecAgent · HackAPrompt · ITC-Egypt 2026 审稿人
Queen's University · 计算机学院 · 金斯顿, 安大略省, 加拿大
已录用 · ITC-Egypt 2026 · IEEE
已录用 · ITC-Egypt 2026 · IEEE
标签:Apex, CNCF毕业项目, Kubernetes, Naabu, RAG系统, 内容安全, 大模型安全, 异常检测, 机器学习, 请求拦截, 逆向工具