# TFLite-Micro Attack Detection Models

Four int8-quantized TensorFlow Lite models designed to run on ESP32-S3 (Heltec V4) alongside the existing drone classifier. Each model detects a different category of wireless/protocol attack.

## Requirements

- Python 3.8+
- TensorFlow 2.x (2.10+ recommended)
- NumPy, scikit-learn

```bash
pip install tensorflow numpy scikit-learn
```

## Quick Start

```bash
# Build all 4 models (generate data + train + export)
chmod +x build_all.sh
./build_all.sh

# Or build individually:
python rf_attack_classifier/generate_synthetic_data.py
python rf_attack_classifier/train.py
```

---

## Model 1: RF Attack Classifier

**Directory:** `rf_attack_classifier/`

| Property | Value |
|----------|-------|
| Input tensor | `int8[1, 64]` |
| Output tensor | `int8[1, 6]` |
| Classes | `normal`, `deauth`, `beacon_flood`, `evil_twin`, `pmkid`, `arp_spoof` |
| Training samples | 50,000 (balanced) |
| Target size | < 200 KB |
| Architecture | Dense(128) → BN → Dropout → Dense(64) → BN → Dropout → Dense(6, softmax) |
| Expected accuracy | > 95% on synthetic data |

**Feature vector (64 elements):**
- [0-5] Frame type histogram (mgmt, ctrl, data, beacon, deauth, eapol)
- [6-11] Frame subtype histogram
- [12-15] Rate statistics (fps mean/std/min/max)
- [16-19] BSSID diversity metrics
- [20-23] SSID statistics
- [24-27] RSSI statistics
- [28-31] Per-BSSID RSSI variance
- [32-35] Timing features (IAT stats, burst ratio)
- [36-39] Sequence number features
- [40-43] Source address diversity
- [44-47] ARP features
- [48-51] EAPOL features
- [52-55] Channel features
- [56-59] Payload features
- [60-63] Derived features (entropy, periodicity, confidence, noise floor)

**Attack signatures:**
- **Deauth flood:** High deauth frame ratio (>0.2), frame rate >150 fps, burst ratio >0.4
- **Beacon flood:** Unique BSSIDs >50, SSID entropy >3.5, beacon ratio >0.4
- **Evil twin:** Per-BSSID RSSI variance >10, sudden jumps >3, high concentration index
- **PMKID capture:** EAPOL rate >0.05, PMKID pattern score >0.45, incomplete handshakes >0.3
- **ARP spoofing:** ARP rate >3, gratuitous ARP ratio >0.3, duplicate IP-MAC >2

---

## Model 2: MAVLink Anomaly Detector

**Directory:** `mavlink_anomaly/`

| Property | Value |
|----------|-------|
| Input tensor | `int8[1, 48]` |
| Output tensor | `int8[1, 4]` |
| Classes | `normal`, `cmd_injection`, `gps_spoof`, `waypoint_tamper` |
| Training samples | 40,000 (balanced) |
| Target size | < 150 KB |
| Architecture | Dense(96) → BN → Dropout → Dense(48) → BN → Dropout → Dense(4, softmax) |
| Expected accuracy | > 95% on synthetic data |

**Feature vector (48 elements):**
- [0-7] Message type histogram (heartbeat, gps, attitude, command, mission, etc.)
- [8-11] Timing statistics
- [12-15] Heartbeat features
- [16-19] System/component ID features
- [20-23] Sequence number features
- [24-27] GPS position deltas
- [28-31] GPS velocity features
- [32-35] GPS quality features
- [36-39] Attitude rate features
- [40-43] Command features
- [44-47] Mission protocol features

**Attack signatures:**
- **Command injection:** Command rate >0.5, unexpected sysid ratio >0.12, restricted commands >0.15
- **GPS spoofing:** Position deltas >0.001 deg, speed >15 m/s, impossible accel count >2
- **Waypoint tampering:** Mission items without preceding MISSION_COUNT, sequence violations >0.15

---

## Model 3: LoRa Mesh Attack Detector

**Directory:** `lora_mesh_attack/`

| Property | Value |
|----------|-------|
| Input tensor | `int8[1, 32]` |
| Output tensor | `int8[1, 5]` |
| Classes | `normal`, `jam_constant`, `jam_sweep`, `replay`, `spoof` |
| Training samples | 30,000 (balanced) |
| Target size | < 100 KB |
| Architecture | Dense(64) → BN → Dropout → Dense(32) → BN → Dropout → Dense(5, softmax) |
| Expected accuracy | > 95% on synthetic data |

**Feature vector (32 elements):**
- [0-3] Packet rates (rx, tx, ack, beacon)
- [4-7] Error rates (CRC, timeout, dropped, retry)
- [8-11] Per-channel RSSI (4 channels)
- [12-15] RSSI statistics (mean, std, min, max)
- [16-19] Duplicate packet features
- [20-23] Timing features
- [24-27] Node identity features
- [28-31] Channel/RF features (active channels, noise floor, SNR)

**Attack signatures:**
- **Constant jamming:** All-channel RSSI > -55 dBm, rx rate near 0, CRC errors >0.3, SNR < 3
- **Sweep jamming:** High inter-channel RSSI variance (std >8), rotating channel degradation
- **Replay:** Duplicate packet ID ratio >0.15, duplicate timestamps >0.18
- **Node spoofing:** Known node from unexpected direction (>0.3), ID conflict count >1

---

## Model 4: Protocol Fingerprint Anomaly

**Directory:** `protocol_anomaly/`

| Property | Value |
|----------|-------|
| Input tensor | `int8[1, 48]` |
| Output tensor | `int8[1, 4]` |
| Classes | `normal`, `dns_tunnel`, `c2_beacon`, `port_scan` |
| Training samples | 40,000 (balanced) |
| Target size | < 300 KB |
| Architecture | Dense(128) → BN → Dense(64) → BN → Dense(32) → BN → Dense(4, softmax) |
| Expected accuracy | > 95% on synthetic data |

**Feature vector (48 elements):**
- [0-5] Packet size histogram (6 buckets)
- [6-9] Packet size statistics
- [10-17] Inter-arrival time statistics and distribution
- [18-21] Port features
- [22-25] Connection features
- [26-33] DNS features (rates, label lengths, subdomain depth, TXT/NXDOMAIN ratios)
- [34-37] Payload entropy/composition
- [38-41] Traffic direction features
- [42-45] Protocol mix (TCP/UDP/ICMP)
- [46-47] Derived scores

**Attack signatures:**
- **DNS tunneling:** DNS label length mean >20, subdomain depth >3, TXT ratio >0.08, few unique domains
- **C2 beaconing:** Periodicity score >0.65, IAT std <5s, few dst ports (<4), short connections
- **Port scanning:** Unique dst ports >50, incomplete connections >0.6, tiny packets, IAT <0.015s

---

## ESP32-S3 Deployment

### SPIFFS Upload

Copy `.tflite` files to the SPIFFS partition:

```
data/
  rf_attack_classifier.tflite
  mavlink_anomaly.tflite
  lora_mesh_attack.tflite
  protocol_anomaly.tflite
```

### Input Normalization

Each model requires StandardScaler normalization before inference. The `scaler_params.npz` file contains `mean` and `scale` arrays. On ESP32:

```c
// Normalize input feature vector
for (int i = 0; i < NUM_FEATURES; i++) {
    normalized[i] = (raw[i] - scaler_mean[i]) / scaler_scale[i];
}

// Quantize to int8 using TFLite input quantization params
for (int i = 0; i < NUM_FEATURES; i++) {
    input_int8[i] = (int8_t)(normalized[i] / input_scale + input_zero_point);
}
```

### Memory Budget

| Model | Size | Input | Output | Total per inference |
|-------|------|-------|--------|-------------------|
| RF Attack | ~25 KB | 64 B | 6 B | ~50 KB |
| MAVLink | ~15 KB | 48 B | 4 B | ~35 KB |
| LoRa Mesh | ~8 KB | 32 B | 5 B | ~20 KB |
| Protocol | ~30 KB | 48 B | 4 B | ~55 KB |
| **Total** | **~78 KB** | | | **~160 KB** |

ESP32-S3 has 512 KB SRAM — running all 4 models plus the drone classifier is feasible with careful arena allocation. Use a shared TFLite Micro arena of ~80 KB, loading models sequentially.

### Inference Frequency

Recommended inference intervals:
- RF Attack: every 500ms (real-time threat)
- MAVLink: every 1s (telemetry stream)
- LoRa Mesh: every 2s (mesh health)
- Protocol: every 5s (network behavior)

### Output Interpretation

Each model outputs class probabilities as int8 values. Dequantize and apply threshold:

```c
float prob = (output_int8[class_idx] - output_zero_point) * output_scale;
if (prob > ALERT_THRESHOLD) {
    trigger_alert(model_id, class_idx, prob);
}
```

Recommended alert thresholds: 0.7 for warning, 0.85 for critical.
