fix protocol+tests: replay protection rework, wire envelope nonce auth,

flaky e2e test deadlines, build imports
This commit is contained in:
2026-02-13 16:37:30 -03:00
parent c94d189d42
commit 6ec1346cfd
22 changed files with 2275 additions and 786 deletions

View File

@@ -1,15 +1,16 @@
# Request ID and Nonce Design
# Request ID and Replay Protection Design
This document explains the roles of `request_id` and `nonce` in the zigp2p protocol, their distinct purposes, and how they work together to provide security.
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 two different identifiers that serve complementary but distinct security purposes:
The zigp2p protocol uses a layered replay protection architecture:
1. **Request ID** (`request_id`): Application-layer correlation identifier for DHT messages
2. **Nonce**: Cryptographic replay protection identifier at the protocol layer
Understanding the difference between these two is crucial for proper protocol implementation.
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
---
@@ -35,255 +36,129 @@ Request IDs are used in the **DHT (Distributed Hash Table) layer** to correlate
### Why Randomized Initialization?
Prior to the fix, `request_id` was initialized to 1 and incremented sequentially:
```zig
next_request_id: std.atomic.Value(u64) = std.atomic.Value(u64).init(1)
```
**Problem**: When multiple nodes started simultaneously, they would all generate the same sequence (1, 2, 3, ...). This caused **false positive replay attacks** at the protocol layer because the replay protection system tracked nonces globally.
**Solution**: Initialize with a random value:
```zig
var random_start: u64 = undefined;
std.crypto.random.bytes(std.mem.asBytes(&random_start));
random_start |= 1; // Ensure non-zero
dht.next_request_id.store(random_start, .monotonic);
```
This ensures each node starts from a different point in the u64 space, making collisions astronomically unlikely.
### Example Usage
```zig
// Sending a FIND_NODE request
const request_id = self.getNextRequestId();
const find_msg = DhtFindNode{
.request_id = request_id,
.target_id = target,
.sender_id = self.local_id,
.auth = auth,
};
// Later, match the response
if (response.request_id == expected_request_id) {
// Handle response
}
```
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.
---
## Nonce (Protocol Layer)
## Replay Protection (Protocol Layer)
### Purpose
Nonces are used for **cryptographic replay protection** at the protocol layer to prevent attackers from replaying captured messages.
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_nonces` hash map
- Tracked in: `seen_messages` hash map (keyed by `PeerMessageKey`)
### Characteristics
### Architecture: Per-Peer Message ID Dedup
- **Type**: `u64` (64-bit unsigned integer) in replay protection
- **Scope**: All protocol messages
- **Generation**: Varies by layer (often derived from `request_id`)
- **Uniqueness**: Must be globally unique across all peers
- **Lifetime**: Tracked for `message_ttl` duration (default: 300 seconds)
The replay protector uses **per-peer, per-type** dedup. The dedup key is:
### How Nonce Replay Protection Works
```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,
timestamp: i64,
nonce: u64, // ← This must be unique globally
sequence: u64,
peer_id: [32]u8,
msg_type: u8,
) !void {
// Check nonce uniqueness
if (try self.isDuplicateNonce(nonce, timestamp)) {
return ReplayError.DuplicateNonce;
}
// Record nonce as seen
try self.seen_nonces.put(nonce, timestamp);
}
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
```
### Important: Global Nonce Tracking
### Defense Layers (ordered by check priority)
The nonce is tracked **globally** across all peers:
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
```zig
fn isDuplicateNonce(self: *ReplayProtector, nonce: u64, timestamp: i64) !bool {
if (self.seen_nonces.get(nonce)) |seen_timestamp| {
// Nonce was seen before - reject as replay
return true;
}
return false;
}
### 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]
```
This means:
- **Same nonce from different peers = Replay attack detected**
- **Same nonce at different times = Replay attack detected**
### Noise ON (Production)
This is why randomizing `request_id` initialization is critical.
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 with a different purpose.
### Purpose
MWP nonces provide **unbiasable shared randomness** for rendezvous coordination between peers attempting to connect.
### Location
- Defined in: `src/mwp/types.zig`
- Used in: `MeetingPublication`
- Generated during: Publication creation
### Characteristics
The **Mutual Witness Protocol (MWP)** uses a different kind of nonce for **rendezvous coordination**, not replay protection.
- **Type**: `[32]u8` (256-bit random value)
- **Scope**: MWP meeting point protocol only
- **Generation**: Cryptographically random for each publication
- **Purpose**: Compute shared rendezvous parameters
### How MWP Nonces Work
```zig
pub const MeetingPublication = struct {
peer_id: [32]u8,
addresses: []const Address,
nonce: [32]u8, // ← Random nonce for mutual witness
timestamp: i64,
ttl: u32,
sequence: u64,
signature: [64]u8,
};
```
When two peers want to connect:
1. **Alice** publishes with `nonce_A` (32 random bytes)
2. **Bob** publishes with `nonce_B` (32 random bytes)
3. Both compute shared parameters:
```zig
shared_randomness = hash(sort(nonce_A, nonce_B))
rendezvous_time = computed from timestamps
port_hint = derived from shared_randomness
```
### Why MWP Nonces Are Different
MWP nonces serve a **coordination** purpose, not replay protection:
- They ensure neither peer can bias the connection parameters
- They're included in DHT publications (not protocol messages)
- They're 256 bits (not 64 bits) for stronger randomness guarantees
- They don't need to be globally unique across the network
- **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 | Protocol Nonce | MWP Nonce |
|--------|---------------|----------------|-----------|
| **Size** | 64 bits | 64 bits | 256 bits |
| **Layer** | DHT Application | Protocol | MWP Application |
| **Purpose** | Request/response correlation | Replay protection | Rendezvous coordination |
| **Scope** | Per-DHT-node | Global (all peers) | Per-publication |
| **Generation** | Random start + increment | Derived/random | Cryptographically random |
| **Collision** | Must avoid globally | Must avoid globally | Only needs local uniqueness |
| **Tracking** | In `pending_responses` | In `seen_nonces` | Not tracked |
| 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 |
---
## The Bug and Fix
## Message Path Security Summary
### The Problem
Before the fix, the DHT layer used:
```zig
next_request_id: std.atomic.Value(u64) = std.atomic.Value(u64).init(1)
```
**Scenario**:
1. Bootstrap node starts (request_id counter = 1)
2. Node 2 starts (request_id counter = 1)
3. Node 3 starts (request_id counter = 1)
4. Node 2 sends FIND_NODE to bootstrap (nonce = 1)
5. Node 3 sends FIND_NODE to bootstrap (nonce = 1)
6. Bootstrap node sees **duplicate nonce** → `DuplicateNonce` error
**Error Log**:
```
error: SECURITY: Replay attack detected: DuplicateNonce (msg_id=64, peer_hint=d95e8842)
warning: DHT: Failed to process message: error.DuplicateNonce
```
### The Fix
Initialize with random starting value:
```zig
pub fn init(allocator: Allocator, routing_table: *KademliaRoutingTable, local_id: NodeId) DhtCoordinator {
var random_start: u64 = undefined;
std.crypto.random.bytes(std.mem.asBytes(&random_start));
random_start |= 1; // Ensure non-zero
var dht = DhtCoordinator{ /* ... */ };
dht.next_request_id.store(random_start, .monotonic);
return dht;
}
```
**Result**:
- Each node starts from a different random point in the u64 space
- Probability of collision: ~1 in 2^64 (effectively zero)
- No more false positive replay detections
---
## Best Practices
1. **Always randomize initial counters** when they're used as nonces
2. **Understand the scope** of your identifiers (per-peer vs global)
3. **Use appropriate sizes**: 64 bits for efficiency, 256 bits for strong randomness
4. **Don't reuse** protocol-layer nonces across different security contexts
5. **Log carefully**: Only log hints (first 4 bytes) of peer IDs for privacy
| 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` - Protocol nonce replay detection
- `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
- `src/protocol/handler.zig` - Message processing with replay checks
- `src/protocol/encryption.zig` - Encryption nonce tracking (separate system)
---
## Encryption Layer Nonces
Note: There's also a third nonce system in the **encryption layer** (`src/protocol/encryption.zig`):
- **Purpose**: Ensure unique initialization vectors for ChaCha20-Poly1305
- **Size**: 12 bytes (96 bits)
- **Structure**: 4-byte generation + 8-byte counter
- **Tracking**: Per-peer nonce tracker with sliding window
This is orthogonal to the request_id and protocol nonce systems and serves purely cryptographic purposes.