Files
zigp2p/docs/mwp/REQUEST_ID_AND_NONCE_DESIGN.md
2026-02-13 16:37:30 -03:00

165 lines
6.7 KiB
Markdown

# Request ID and Replay Protection Design
This document explains the roles of `request_id` and replay protection in the zigp2p protocol, their distinct purposes, and how they work together to provide security.
## Overview
The zigp2p protocol uses a layered replay protection architecture:
1. **Noise AEAD** (primary): Transport-level authentication prevents replay and forgery
2. **Per-peer msg_id dedup**: Application-level dedup keyed by (peer_prefix, msg_id, msg_type)
3. **Wire envelope** (non-DHT messages): Random salt + timestamp prepended to custom messages
4. **Sequence windows** (ordered types): Sliding window for topology_update, data_chunk, etc.
5. **Timestamp validation** (where available): Rejects stale/future messages
---
## Request ID (DHT Layer)
### Purpose
Request IDs are used in the **DHT (Distributed Hash Table) layer** to correlate requests with their responses.
### Location
- Defined in: `src/network/dht.zig`
- Used in: `DhtFindNode`, `DhtStore`, `DhtFindValue`, and their response messages
- Generated by: `DhtCoordinator.getNextRequestId()`
### Characteristics
- **Type**: `u64` (64-bit unsigned integer)
- **Scope**: DHT operations only
- **Generation**: Randomized starting point + monotonic increment
- **Thread-safety**: Atomic operations for concurrent generation
- **Purpose**: Match DHT responses to their originating requests
### Why Randomized Initialization?
Prior to the fix, `request_id` was initialized to 1 and incremented sequentially. When multiple nodes started simultaneously, they would all generate the same sequence (1, 2, 3, ...). With per-peer dedup this is no longer a problem (different peers can reuse msg_ids), but randomization is still good practice to avoid correlation.
---
## Replay Protection (Protocol Layer)
### Purpose
Replay protection prevents attackers from replaying captured messages to cause duplicate processing.
### Location
- Defined in: `src/protocol/replay_protection.zig`
- Checked by: `ReplayProtector.checkMessage()`
- Tracked in: `seen_messages` hash map (keyed by `PeerMessageKey`)
### Architecture: Per-Peer Message ID Dedup
The replay protector uses **per-peer, per-type** dedup. The dedup key is:
```zig
const PeerMessageKey = struct {
peer_id_prefix: [16]u8, // First 16 bytes of 32-byte peer ID
msg_id: u64,
msg_type: u8,
};
```
This means:
- **Same msg_id from different peers**: Accepted (each peer has independent ID space)
- **Same msg_id from same peer, same type**: Rejected as `DuplicateMessageId`
- **Same msg_id from same peer, different type**: Accepted (request/response pairs share IDs)
### checkMessage Signature
```zig
pub fn checkMessage(
self: *ReplayProtector,
msg_id: u64, // Per-peer message identifier
timestamp: i64, // Sender's timestamp (for staleness check)
sequence: u64, // Ordered message sequence (0 = unordered)
peer_id: [32]u8, // Source peer identity
msg_type: u8, // Message type discriminator
) !void
```
### Defense Layers (ordered by check priority)
1. **Timestamp validation**: Rejects messages older than TTL (10s) or further than clock skew (5s) into the future
2. **Per-peer msg_id dedup**: Rejects duplicate (peer_prefix, msg_id, msg_type) tuples
3. **Sequence windows**: For ordered types, rejects out-of-window or replayed sequences
### Why No Global Nonce?
An earlier design tracked nonces globally across all peers (`seen_nonces` HashMap). This was removed because:
- **Cross-peer false positives**: Two different peers sending identical content would collide
- **Redundant with Noise AEAD**: In production, Noise prevents wire-level replay
- **Masked per-peer dedup bugs**: Global nonce caught replays before per-peer dedup, hiding test issues
- **Single point of memory growth**: One HashMap growing with all traffic across all peers
Per-peer dedup is the correct granularity — each peer's ID space is independent.
---
## Wire Envelope (Non-DHT Messages)
Non-DHT, non-file-transfer messages get a 16-byte wire envelope:
```
[app_id:1][salt:8 LE][timestamp:8 LE][payload:N]
```
### Noise ON (Production)
The salt, timestamp, app_id, and payload are hashed together using a **per-session SipHash-2-4 key** derived from the Noise handshake hash. This produces a replay nonce bound to the specific Noise session — an attacker who captures traffic cannot forge envelopes without the session key.
### Noise OFF (Dev/Testing Only)
Without a shared secret, the raw 8-byte salt is used as the replay nonce. This stops passive replay (exact byte replay) but provides no authentication. **Not secure for production.**
---
## MWP Protocol Nonces
The **Mutual Witness Protocol (MWP)** uses a different kind of nonce for **rendezvous coordination**, not replay protection.
- **Type**: `[32]u8` (256-bit random value)
- **Purpose**: Compute shared rendezvous parameters (time, port) between peers
- **Generation**: Cryptographically random per publication
- **Tracking**: Not tracked for replay — serves coordination only
---
## Summary Table
| Aspect | DHT Request ID | Replay Protection | Wire Envelope | MWP Nonce |
|--------|---------------|-------------------|---------------|-----------|
| **Size** | 64 bits | Per-peer msg_id (64 bits) | 128 bits (salt+ts) | 256 bits |
| **Layer** | DHT Application | Protocol | Transport | MWP Application |
| **Purpose** | Request/response correlation | Duplicate detection | Session-bound replay nonce | Rendezvous coordination |
| **Scope** | Per-DHT-node | Per-peer, per-type | Per-session (Noise) | Per-publication |
| **Tracking** | In `pending_responses` | In `seen_messages` | Via `checkMessage` | Not tracked |
---
## Message Path Security Summary
| Message Path | Replay Protection | Timestamp Check | Noise AEAD |
|---|---|---|---|
| DHT (app_id=0x02) | wire_nonce+wire_timestamp → processMessage → per-peer msg_id dedup | Yes (wire_timestamp) | Yes |
| Non-DHT custom (app_id != 0x01/0x02) | wire envelope → handleNetworkMessageImpl → per-peer msg_id dedup | Yes (wire_timestamp) | Yes |
| File transfer (app_id=0x01) | Own piece hashing + session tracking | No | Yes |
| Internal protocol msgs | processMessage → per-peer msg_id dedup + sequence windows | No-op (receiver clock) | Yes |
---
## Related Files
- `src/network/dht.zig` - DHT request ID generation and tracking
- `src/protocol/replay_protection.zig` - Per-peer message dedup and sequence windows
- `src/p2p/messaging.zig` - Wire envelope send/receive, `handleNetworkMessageImpl`
- `src/protocol/handler.zig` - `processMessage` with replay checks
- `src/protocol/message.zig` - `getIdForReplay`, `getTimestamp`, `getSequence`
- `src/protocol/encryption.zig` - Encryption nonce tracking (separate system, orthogonal)
- `src/mwp/types.zig` - MWP nonce for rendezvous coordination