Advanced Web Application Firewall · Group AA3 · Model Engineering College
This directory contains the complete RL model for NexusWAF. The agent learns an adaptive enforcement policy — deciding when to invoke the ML classifier, block immediately, or allow requests — based on the risk signals from the fast lexical/grammar layers.
Model: Dueling Deep Q-Network (DQN)
State: 15-dimensional feature vector from RequestContext
Actions: 7 discrete (allow, invoke ML, block, log, adjust threshold, rate-limit)
Training: 3-stage curriculum · 50 epochs · ~89K samples
nexus-ml/
├── configs/
│ └── config.yaml # All hyperparameters (edit this)
├── data/
│ ├── raw/ # Place downloaded datasets here
│ └── processed/ # Auto-generated by prepare_data.py
├── src/
│ ├── preprocessing/
│ │ ├── lexical_scanner.py # Python mirror of nexus-lexical (Rust)
│ │ ├── http_parser.py # Parsers for CSIC, Apache logs, payloads
│ │ └── feature_extractor.py # ParsedRequest → 15-dim state vector
│ ├── environment/
│ │ └── waf_env.py # Gymnasium RL environment (MDP)
│ ├── model/
│ │ └── dueling_dqn.py # DuelingDQN + ReplayBuffer + DQNAgent
│ ├── training/
│ │ └── trainer.py # Training loop, curriculum, checkpointing
│ ├── evaluation/
│ │ └── evaluator.py # Test-set evaluation + plots
│ └── integration/
│ └── policy_service.py # gRPC/REST server for Rust pipeline
├── scripts/
│ ├── prepare_data.py # STEP 1: data pipeline
│ ├── train.py # STEP 2: training
│ └── evaluate.py # STEP 3: evaluation
├── tests/
│ └── test_smoke.py # Run without torch to verify correctness
└── requirements.txt
cd nexus-ml/
pip install -r requirements.txtpython tests/test_smoke.pyAll 13 tests should pass. This verifies the preprocessing logic before you install the full PyTorch stack.
Option A: With real datasets (recommended for production)
Place these files in data/raw/:
| File | Source |
|---|---|
csic_normalTrafico.txt |
CSIC 2010 — HTTP DATASET CSIC 2010 |
csic_anomalousTrafico.txt |
Same download |
juice_shop_access.log |
docker run -p 3000:3000 bkimminich/juice-shop then run OWASP ZAP scan |
nginx_benign.log |
Your production Apache/Nginx access.log |
sqli_payloads.txt |
SecLists |
xss_payloads.txt |
SecLists XSS |
path_traversal.txt |
PayloadsAllTheThings |
cmd_injection.txt |
PayloadsAllTheThings |
Option B: Synthetic data (for development, no downloads needed)
Just run the script — it auto-generates 20,000 synthetic samples if no real data is found.
python scripts/prepare_data.pyOutput:
data/processed/train.npz (~62K samples)
data/processed/val.npz (~13K samples)
data/processed/test.npz (~13K samples)
data/processed/scaler.pkl
data/processed/stats.json
python scripts/train.pyThis runs 3 curriculum stages (50 epochs total). Training on CPU takes ~30–60 minutes depending on dataset size. On GPU: ~5–10 minutes.
Monitor live:
tensorboard --logdir logs/tensorboardOpen http://localhost:6006 to see loss, reward, precision, recall curves.
Resume interrupted training:
python scripts/train.py --resume checkpoints/ckpt_epoch025_r68.50.ptpython scripts/evaluate.pyProduces:
- Console report with all 8 metrics vs. static baseline
results/confusion_matrix.pngresults/per_attack_recall.pngresults/action_distribution.pngresults/evaluation_report.json
python src/integration/policy_service.py \
--checkpoint checkpoints/best.pt \
--port 50052 \
--feedback-log data/live/policy_events.jsonl \
--online-train \
--online-save checkpoints/live-online.ptThis starts the gRPC policy endpoint that nexus-core now calls directly.
Gateway request outcomes are also streamed back into this service over gRPC and
appended to data/live/policy_events.jsonl for retraining / online fine-tuning.
Optional REST fallback for manual testing:
python src/integration/policy_service.py \
--checkpoint checkpoints/best.pt \
--rest \
--port 50053Quick REST smoke test:
curl -X POST http://localhost:50053/decide \
-H "Content-Type: application/json" \
-d '{"features": [0.8, 0.1, 1.0, 0.0, 0.0, 0.0, 0.05, 0.1, 0.05, 0.0, 0.3, 0.1, 0.0, 0.4, 0.3]}'
# → {"action_id": 2, "action_name": "block_immediate", "confidence": 0.91, ...}All hyperparameters are in configs/config.yaml. Key settings:
training:
learning_rate: 3.0e-4 # Reduce to 1e-4 if training unstable
batch_size: 256 # Increase to 512 if GPU available
curriculum:
stage1_epochs: 10 # Easy cases only
stage2_epochs: 15 # Add ambiguous
stage3_epochs: 25 # Full adversarial
reward:
false_positive: -1.5 # Increase penalty to reduce FPR
false_negative: -2.0 # Increase penalty to increase recall| Index | Feature | Range | Source |
|---|---|---|---|
| 0 | risk_score |
[0,1] | Cumulative from lexical+grammar layers |
| 1 | threat_tag_count |
[0,1] | Normalised count of distinct tags |
| 2 | has_sqli |
{0,1} | SQLi pattern matched |
| 3 | has_xss |
{0,1} | XSS pattern matched |
| 4 | has_path_traversal |
{0,1} | Path traversal matched |
| 5 | has_cmd_injection |
{0,1} | Command injection matched |
| 6 | body_length_norm |
[0,1] | Body size / 8192 |
| 7 | uri_length_norm |
[0,1] | URI length / 2048 |
| 8 | query_param_count_norm |
[0,1] | Param count / 20 |
| 9 | rate_limited |
{0,1} | Rate limiter triggered |
| 10 | recent_attack_rate |
[0,1] | Attacks / total (last 100 requests) |
| 11 | p95_latency_norm |
[0,1] | Current P95 latency / budget |
| 12 | has_referer |
{0,1} | Referer header present |
| 13 | content_type_encoded |
[0,1] | 0=none 1=json 2=form 3=multi... |
| 14 | grammar_risk |
[0,1] | Extra risk from grammar analysis |
| Metric | Target | What it means |
|---|---|---|
| Precision | ≥ 0.92 | Of all blocks, ≥92% are real attacks |
| Recall | ≥ 0.90 | ≥90% of attacks are caught |
| FPR | ≤ 0.05 | ≤5% of legitimate requests blocked |
| F1 | ≥ 0.91 | Harmonic mean of P and R |
| ML invocation | ≤ 30% | Agent skips ML for obvious cases |
The policy service runs alongside the ML microservice (Phase 4). The Rust side
now calls it via gRPC and also batches live request outcomes back into the same
service for feedback ingestion. The PolicyLayer at priority 35:
- Builds the 15-dim state vector from
RequestContext - Calls
grpc://policy-service:50052PolicyService.Decide - Maps
action_idto pipeline behaviour:0(allow_no_ml): skip ML layer, return Allow1(invoke_ml): proceed to ML layer2(block_immediate): return Block immediately3(log_and_allow): tag for GPS, return Allow4/5(threshold): updatectx.meta["risk_threshold"]6(rate_limit): add IP to soft rate-limit list
- After the request completes,
nexus-gatewaybatches the policy features, action taken, final verdict, tags, and ML outcome back intoPolicyService.ReportEventsfor live dataset growth and optional online fine-tuning