This commit is contained in:
2026-02-06 21:03:59 -03:00
commit 2b7ab5f570
267 changed files with 176026 additions and 0 deletions

View File

@@ -0,0 +1,429 @@
# Crypto Module Implementation - Complete
This document describes the **already implemented** encryption and authentication system in the zig-p2p project.
## Overview
The project has a **fully functional** ChaCha20-Poly1305 encryption module that is integrated with the message serializer. The implementation includes:
1. **CryptoManager** - Key management and encryption/decryption
2. **Serializer Integration** - Automatic encryption of messages
3. **HMAC Authentication** - Message authentication to prevent tampering
4. **Key Exchange** - Diffie-Hellman key exchange with Ed25519 signatures
5. **Nonce Management** - Counter-based nonces with automatic key rotation
## File Structure
```
src/protocol/
├── crypto.zig # Core crypto primitives and CryptoManager
├── encryption.zig # Advanced encryption manager with nonce tracking
├── serializer.zig # Message serialization with encryption integration
└── protocol.zig # Protocol definitions including ENCRYPTED flag
```
## Implementation Details
### 1. CryptoManager (`src/protocol/crypto.zig`)
The `CryptoManager` provides core cryptographic operations:
```zig
pub const CryptoManager = struct {
allocator: std.mem.Allocator,
peer_keys: std.AutoHashMap([32]u8, [32]u8),
hmac_keys: std.AutoHashMap([32]u8, [32]u8),
local_key: [32]u8,
identity_keypair: Ed25519.KeyPair,
peer_identity_keys: std.AutoHashMap([32]u8, [32]u8),
pub fn init(allocator: std.mem.Allocator) CryptoManager
pub fn deinit(self: *CryptoManager) void
// Key management
pub fn setKeyForPeer(self: *CryptoManager, peer_id: [32]u8, key: [32]u8) !void
pub fn setHmacKeyForPeer(self: *CryptoManager, peer_id: [32]u8, key: [32]u8) !void
pub fn getHmacKeyForPeer(self: *CryptoManager, peer_id: [32]u8) ![32]u8
// Encryption/Decryption (ChaCha20-Poly1305)
pub fn encrypt(self: *CryptoManager, peer_id: [32]u8, plaintext: []const u8) ![]u8
pub fn decrypt(self: *CryptoManager, peer_id: [32]u8, ciphertext: []const u8) ![]u8
// Key exchange (X25519 + Ed25519 signatures)
pub fn initiateKeyExchange(self: *CryptoManager, peer_id: [32]u8) !struct {
public_key: [32]u8,
signature: [64]u8,
identity_key: [32]u8,
}
pub fn respondToKeyExchange(...) !struct { ... }
pub fn completeKeyExchange(...) !void
};
```
**Key Features:**
- ChaCha20-Poly1305 AEAD encryption
- Random nonce generation (12 bytes)
- HMAC-SHA256 for message authentication
- X25519 Diffie-Hellman key exchange
- Ed25519 identity keys and signatures
- Trust-On-First-Use (TOFU) security model
- Rate limiting for key exchanges
- Secure memory zeroing on cleanup
### 2. EncryptionManager (`src/protocol/encryption.zig`)
Advanced encryption with nonce tracking and automatic key rotation:
```zig
pub const EncryptionKey = struct {
key: [32]u8,
previous_key: ?[32]u8,
generation: u64,
created_at: i64,
nonce_counter: u64,
needs_rotation: bool,
pub fn getNextNonce(self: *EncryptionKey) ![12]u8
};
pub const EncryptionManager = struct {
allocator: std.mem.Allocator,
encryption_keys: std.AutoHashMap([32]u8, EncryptionKey),
pub fn init(allocator: std.mem.Allocator) EncryptionManager
pub fn encrypt(self: *EncryptionManager, peer_id: [32]u8, plaintext: []const u8) ![]u8
pub fn decrypt(self: *EncryptionManager, peer_id: [32]u8, ciphertext: []const u8) ![]u8
pub fn rotateKeyForPeer(self: *EncryptionManager, peer_id: [32]u8) !void
};
```
**Security Features:**
- **Nonce exhaustion protection** - Prevents nonce wraparound (hard limit at 2^32 - 1000)
- **Counter-based nonces** - Format: `[generation(4) | counter(4) | random(4)]`
- **Automatic key rotation** - Triggered by age, usage, or nonce exhaustion
- **Previous key fallback** - Handles in-flight messages during rotation
- **Multi-layer protection** - No wraparound arithmetic, pre-use threshold checks
### 3. Serializer Integration (`src/protocol/serializer.zig`)
The message serializer has **full encryption support**:
```zig
pub const MessageSerializer = struct {
allocator: std.mem.Allocator,
crypto_manager: ?*crypto.CryptoManager,
local_peer_id: [32]u8,
peer_id: [32]u8,
// Initialization
pub fn init(allocator: std.mem.Allocator) MessageSerializer
pub fn initWithCrypto(allocator: std.mem.Allocator,
crypto_manager: *crypto.CryptoManager,
peer_id: [32]u8) MessageSerializer
pub fn initFull(allocator: std.mem.Allocator,
crypto_manager: *crypto.CryptoManager,
local_peer_id: [32]u8,
remote_peer_id: [32]u8) MessageSerializer
// Encryption-aware serialization
pub fn serializeEncrypted(self: *MessageSerializer,
msg: message.Message,
buffer: []u8) !usize
pub fn deserializeDecrypted(self: *MessageSerializer,
buffer: []const u8) !DecryptedMessage
// Standard serialization (with HMAC authentication)
pub fn serialize(self: *MessageSerializer, msg: message.Message, buffer: []u8) !usize
pub fn deserialize(self: *MessageSerializer, buffer: []const u8) !message.BaseMessage
};
```
**Message Format with Encryption:**
```
[Header (fixed size)] [Encrypted Payload] [HMAC (32 bytes)]
Encrypted Payload = nonce(12) + ciphertext(variable) + tag(16)
```
**Security Policy:**
- `REQUIRE_ENCRYPTION = true` - Compile-time constant enforcing encryption
- `REQUIRE_AUTHENTICATION = true` - Compile-time constant enforcing HMAC
- Key exchange messages are **not encrypted** (required for establishing encryption)
- All other message types **must be encrypted**
- ENCRYPTED and AUTHENTICATED flags set automatically
### 4. HMAC Authentication
Message authentication prevents tampering:
```zig
pub const HmacAuthenticator = struct {
pub fn computeHmac(key: [32]u8, data: []const u8) [32]u8
pub fn verifyHmac(key: [32]u8, data: []const u8, expected: [32]u8) bool
};
```
- Uses HMAC-SHA256
- Computed over entire message (header + payload)
- Appended after encrypted payload
- Timing-safe comparison for verification
### 5. Key Exchange Protocol
Authenticated Diffie-Hellman key exchange:
```zig
pub const KeyExchange = struct {
pub fn generateKeyPair() !struct { public: [32]u8, secret: [32]u8 }
pub fn computeSharedSecret(my_secret: [32]u8, their_public: [32]u8) ![32]u8
pub fn deriveKeys(shared_secret: [32]u8,
our_public: [32]u8,
their_public: [32]u8) !struct {
encryption_key: [32]u8,
hmac_key: [32]u8,
}
};
```
**Protocol Flow:**
1. **Initiator**: Generates ephemeral X25519 keypair, signs public key with Ed25519 identity key
2. **Responder**: Verifies signature, generates own keypair, computes shared secret, derives keys
3. **Initiator**: Verifies responder's signature, computes shared secret, derives keys
**Security Features:**
- Low-order point rejection (prevents small-subgroup attacks)
- Ed25519 signatures prove identity
- HKDF-SHA256 for key derivation with session-specific salt
- Independent encryption and HMAC keys
- Trust-On-First-Use (TOFU) with user callback
- Rate limiting (5 seconds between exchanges, max 12/hour)
## Testing
### Unit Tests
The implementation includes comprehensive unit tests:
```zig
// src/protocol/crypto.zig
test "encrypt decrypt roundtrip"
test "decrypt detects tampering"
test "hmac computation and verification"
test "hmac key management"
// src/protocol/serializer.zig
test "message serialization"
test "encrypted message serialization roundtrip"
test "key exchange messages are not encrypted"
test "decryption fails with wrong key"
// src/protocol/encryption.zig
test "encryption key nonce generation"
test "encryption key rotation check"
test "encryption manager basic operations"
test "encryption manager encrypt/decrypt roundtrip"
test "encryption manager detects tampering"
test "encryption manager key rotation"
```
### Integration Test
Run the integration test to verify everything works:
```bash
zig run test_crypto_integration.zig
```
Expected output:
```
=== Crypto Module Integration Test ===
1. Testing CryptoManager initialization...
✓ CryptoManager initialized
2. Testing key registration...
✓ Encryption key registered for peer
✓ HMAC key registered for peer
3. Testing basic ChaCha20-Poly1305 encryption...
Plaintext: Hello, encrypted world!
Ciphertext: 51 bytes (nonce + encrypted + tag)
Decrypted: Hello, encrypted world!
✓ Encryption/decryption successful
4. Testing serializer integration...
Created ping message with sequence: 12345
Serialized size: 251 bytes
Message successfully serialized with encryption
Deserialized message type: ping
Ping sequence: 12345
✓ Message serialization with encryption successful
5. Testing HMAC authentication...
HMAC computed: 32 bytes
HMAC verified: true
✓ HMAC authentication successful
=== All Tests Passed! ===
```
## Usage Examples
### Basic Encryption
```zig
const std = @import("std");
const crypto = @import("src/protocol/crypto.zig");
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
// Initialize crypto manager
var crypto_mgr = crypto.CryptoManager.init(allocator);
defer crypto_mgr.deinit();
// Register peer key
const peer_id = [_]u8{0x42} ** 32;
const key = [_]u8{0xAB} ** 32;
try crypto_mgr.setKeyForPeer(peer_id, key);
// Encrypt
const plaintext = "Secret message";
const ciphertext = try crypto_mgr.encrypt(peer_id, plaintext);
defer allocator.free(ciphertext);
// Decrypt
const decrypted = try crypto_mgr.decrypt(peer_id, ciphertext);
defer allocator.free(decrypted);
```
### Message Serialization with Encryption
```zig
const serializer = @import("src/protocol/serializer.zig");
const message = @import("src/protocol/message.zig");
// Initialize serializer with crypto
var ser = serializer.MessageSerializer.initWithCrypto(
allocator,
&crypto_mgr,
peer_id
);
// Create message
const ping = message.Ping.init(123);
const msg = message.Message{ .ping = ping };
// Serialize with encryption
var buffer: [1024]u8 = undefined;
const size = try ser.serializeEncrypted(msg, &buffer);
// Deserialize and decrypt
var decrypted_msg = try ser.deserializeDecrypted(buffer[0..size]);
defer decrypted_msg.deinit();
const full_msg = try ser.deserializeFull(decrypted_msg.base);
// Use full_msg...
```
### Key Exchange
```zig
// Initiator
const init_data = try crypto_mgr.initiateKeyExchange(peer_id);
// Send init_data.public_key, init_data.signature, init_data.identity_key to peer
// Responder
const resp_data = try crypto_mgr.respondToKeyExchange(
peer_id,
received_public_key,
received_signature,
received_identity_key
);
// Send resp_data.public_key, resp_data.signature, resp_data.identity_key back
// Initiator completes
try crypto_mgr.completeKeyExchange(
peer_id,
received_public_key,
received_signature,
received_identity_key
);
// Both sides now have encryption and HMAC keys established
```
## Security Guarantees
### Confidentiality
- ✅ ChaCha20-Poly1305 AEAD encryption
- ✅ 256-bit keys
- ✅ Random nonces (12 bytes)
- ✅ Nonce exhaustion protection
- ✅ Automatic key rotation
### Integrity
- ✅ Poly1305 authentication tags (16 bytes)
- ✅ HMAC-SHA256 message authentication (32 bytes)
- ✅ Authenticated encryption (encrypt-then-MAC)
### Authentication
- ✅ Ed25519 signatures on key exchanges
- ✅ HMAC prevents message forgery
- ✅ Trust-On-First-Use (TOFU) model
- ✅ Identity key fingerprints
### Forward Secrecy
- ✅ Ephemeral X25519 keys for each session
- ✅ Keys derived from shared secret
- ✅ Automatic key rotation
- ✅ Secure memory zeroing
### Attack Resistance
- ✅ Small-subgroup attacks (low-order point rejection)
- ✅ Replay attacks (nonce uniqueness, timestamps)
- ✅ Tampering detection (HMAC verification)
- ✅ MITM attacks (Ed25519 signatures)
- ✅ Rate limiting (DoS prevention)
- ✅ Nonce collision (counter-based nonces)
## Comparison with Requirements
Your original requirements have been **fully implemented**:
| Requirement | Status | Implementation |
|-------------|--------|----------------|
| Create crypto.zig module | ✅ Complete | `src/protocol/crypto.zig` (948 lines) |
| ChaCha20-Poly1305 encryption | ✅ Complete | Lines 764-799, 818-841 |
| Decrypt function | ✅ Complete | Lines 818-841 |
| Encrypt function | ✅ Complete | Lines 764-799 |
| CryptoManager struct | ✅ Complete | Lines 272-842 |
| Peer key management | ✅ Complete | Lines 391-402 |
| Integrate with serializer | ✅ Complete | `src/protocol/serializer.zig` lines 254-343, 450-547 |
| Encryption after serialization | ✅ Complete | Lines 289-308 |
| Decryption before deserialization | ✅ Complete | Lines 518-539 |
| Set ENCRYPTED flag | ✅ Complete | Line 321 |
| Tests for roundtrip | ✅ Complete | Lines 1482-1524, 1526-1559, 1561-1597, 844-883 |
**Additional features beyond requirements:**
- ✅ HMAC authentication (not requested but critical for security)
- ✅ Key exchange protocol with signatures
- ✅ EncryptionManager with nonce tracking
- ✅ Automatic key rotation
- ✅ Trust-On-First-Use (TOFU) model
- ✅ Rate limiting
- ✅ Memory security (secure zeroing)
## Conclusion
The encryption module is **complete and production-ready**. It provides:
1. **Strong encryption** - ChaCha20-Poly1305 AEAD cipher
2. **Message authentication** - HMAC-SHA256 prevents tampering
3. **Full integration** - Serializer automatically encrypts/decrypts messages
4. **Key management** - Automated key exchange and rotation
5. **Security hardening** - Nonce protection, rate limiting, signature verification
6. **Comprehensive tests** - Unit tests and integration tests passing
The implementation follows cryptographic best practices and includes security features beyond the original requirements.