379 lines
12 KiB
Zig
379 lines
12 KiB
Zig
//! Cryptographic Security Attack Tests
|
|
//!
|
|
//! Tests resistance to various cryptographic attacks including timing attacks,
|
|
//! nonce reuse, key reuse, and tampering detection.
|
|
|
|
const std = @import("std");
|
|
const testing = std.testing;
|
|
const protocol = @import("protocol");
|
|
const CryptoManager = protocol.crypto.CryptoManager;
|
|
const CryptoError = protocol.crypto.CryptoError;
|
|
|
|
test "crypto: timing attack resistance" {
|
|
const allocator = testing.allocator;
|
|
var crypto = CryptoManager.init(allocator);
|
|
defer crypto.deinit();
|
|
|
|
const peer_id = [_]u8{0x01} ** 32;
|
|
const key = [_]u8{0x42} ** 32;
|
|
try crypto.setKeyForPeer(peer_id, key);
|
|
|
|
const plaintext = "Secret message for timing test that is reasonably long";
|
|
|
|
// Measure encryption time multiple times
|
|
const num_samples = 100;
|
|
var times: [num_samples]i64 = undefined;
|
|
|
|
for (×) |*t| {
|
|
const start = std.time.nanoTimestamp();
|
|
const ct = try crypto.encrypt(peer_id, plaintext);
|
|
defer allocator.free(ct);
|
|
t.* = std.time.nanoTimestamp() - start;
|
|
}
|
|
|
|
// Calculate mean
|
|
var sum: i64 = 0;
|
|
for (times) |t| sum += t;
|
|
const mean = @divTrunc(sum, times.len);
|
|
|
|
// Calculate variance
|
|
var variance: i64 = 0;
|
|
for (times) |t| {
|
|
const diff = t - mean;
|
|
variance += diff * diff;
|
|
}
|
|
variance = @divTrunc(variance, times.len);
|
|
|
|
const std_dev = std.math.sqrt(@as(f64, @floatFromInt(variance)));
|
|
const mean_f = @as(f64, @floatFromInt(mean));
|
|
const coefficient_of_variation = std_dev / mean_f;
|
|
|
|
// For constant-time implementation, coefficient of variation should be small
|
|
// Allow reasonable variance due to system noise
|
|
std.debug.print("Timing: mean={d}ns, stddev={d:.2}ns, CV={d:.4}\n", .{ mean, std_dev, coefficient_of_variation });
|
|
|
|
// CV should be less than 0.5 for good constant-time implementation
|
|
try testing.expect(coefficient_of_variation < 0.5);
|
|
}
|
|
|
|
test "crypto: nonce never repeats" {
|
|
const allocator = testing.allocator;
|
|
var crypto = CryptoManager.init(allocator);
|
|
defer crypto.deinit();
|
|
|
|
const peer_id = [_]u8{0x01} ** 32;
|
|
const key = [_]u8{0x42} ** 32;
|
|
try crypto.setKeyForPeer(peer_id, key);
|
|
|
|
var nonces = std.AutoHashMap([12]u8, void).init(allocator);
|
|
defer nonces.deinit();
|
|
|
|
const num_encryptions = 1000;
|
|
|
|
for (0..num_encryptions) |_| {
|
|
const ct = try crypto.encrypt(peer_id, "test message");
|
|
defer allocator.free(ct);
|
|
|
|
// Extract nonce (first 12 bytes)
|
|
const nonce = ct[0..12].*;
|
|
|
|
// Verify nonce is unique
|
|
const result = try nonces.getOrPut(nonce);
|
|
if (result.found_existing) {
|
|
std.debug.print("CRITICAL: Nonce reuse detected!\n", .{});
|
|
return error.NonceReused;
|
|
}
|
|
}
|
|
|
|
std.debug.print("Successfully verified {} unique nonces\n", .{num_encryptions});
|
|
}
|
|
|
|
test "crypto: tampering detection" {
|
|
const allocator = testing.allocator;
|
|
var crypto = CryptoManager.init(allocator);
|
|
defer crypto.deinit();
|
|
|
|
const peer_id = [_]u8{0x01} ** 32;
|
|
const key = [_]u8{0x42} ** 32;
|
|
try crypto.setKeyForPeer(peer_id, key);
|
|
|
|
const plaintext = "This is a secret message that must not be tampered with";
|
|
const ciphertext = try crypto.encrypt(peer_id, plaintext);
|
|
defer allocator.free(ciphertext);
|
|
|
|
// Try tampering with different parts of the ciphertext
|
|
const tamper_positions = [_]usize{ 12, 20, 30, ciphertext.len - 1 };
|
|
|
|
for (tamper_positions) |pos| {
|
|
var tampered = try allocator.dupe(u8, ciphertext);
|
|
defer allocator.free(tampered);
|
|
|
|
// Flip a bit
|
|
tampered[pos] ^= 0x01;
|
|
|
|
// Attempt to decrypt - should fail
|
|
const result = crypto.decrypt(peer_id, tampered);
|
|
|
|
if (result) |decrypted| {
|
|
allocator.free(decrypted);
|
|
std.debug.print("CRITICAL: Tampering not detected at position {}\n", .{pos});
|
|
return error.TamperingNotDetected;
|
|
} else |err| {
|
|
// Expected - tampering should be detected
|
|
try testing.expectEqual(CryptoError.DecryptionFailed, err);
|
|
}
|
|
}
|
|
|
|
std.debug.print("All tampering attempts correctly detected\n", .{});
|
|
}
|
|
|
|
test "crypto: authentication tag verification" {
|
|
const allocator = testing.allocator;
|
|
var crypto = CryptoManager.init(allocator);
|
|
defer crypto.deinit();
|
|
|
|
const peer_id = [_]u8{0x01} ** 32;
|
|
const key = [_]u8{0x42} ** 32;
|
|
try crypto.setKeyForPeer(peer_id, key);
|
|
|
|
const plaintext = "Authenticated message";
|
|
const ciphertext = try crypto.encrypt(peer_id, plaintext);
|
|
defer allocator.free(ciphertext);
|
|
|
|
// The last 16 bytes are the authentication tag
|
|
try testing.expect(ciphertext.len >= 28); // nonce(12) + data + tag(16)
|
|
|
|
// Create a version with incorrect tag
|
|
var bad_tag = try allocator.dupe(u8, ciphertext);
|
|
defer allocator.free(bad_tag);
|
|
|
|
// Corrupt the tag
|
|
const tag_start = bad_tag.len - 16;
|
|
bad_tag[tag_start] ^= 0xFF;
|
|
|
|
// Should fail to decrypt
|
|
try testing.expectError(CryptoError.DecryptionFailed, crypto.decrypt(peer_id, bad_tag));
|
|
}
|
|
|
|
test "crypto: key separation between peers" {
|
|
const allocator = testing.allocator;
|
|
var crypto = CryptoManager.init(allocator);
|
|
defer crypto.deinit();
|
|
|
|
const peer1_id = [_]u8{0x01} ** 32;
|
|
const peer2_id = [_]u8{0x02} ** 32;
|
|
|
|
const key1 = [_]u8{0x42} ** 32;
|
|
const key2 = [_]u8{0x43} ** 32;
|
|
|
|
try crypto.setKeyForPeer(peer1_id, key1);
|
|
try crypto.setKeyForPeer(peer2_id, key2);
|
|
|
|
const plaintext = "Message encrypted for peer1";
|
|
|
|
// Encrypt for peer1
|
|
const ct = try crypto.encrypt(peer1_id, plaintext);
|
|
defer allocator.free(ct);
|
|
|
|
// Try to decrypt with peer2's key - should fail
|
|
const result = crypto.decrypt(peer2_id, ct);
|
|
|
|
if (result) |decrypted| {
|
|
allocator.free(decrypted);
|
|
std.debug.print("CRITICAL: Key separation violated!\n", .{});
|
|
return error.KeySeparationViolated;
|
|
} else |err| {
|
|
// Expected - wrong key should fail
|
|
try testing.expectEqual(CryptoError.DecryptionFailed, err);
|
|
}
|
|
|
|
// Decrypt with correct key should work
|
|
const correct_plaintext = try crypto.decrypt(peer1_id, ct);
|
|
defer allocator.free(correct_plaintext);
|
|
|
|
try testing.expectEqualSlices(u8, plaintext, correct_plaintext);
|
|
}
|
|
|
|
test "crypto: encrypt-decrypt stress test" {
|
|
const allocator = testing.allocator;
|
|
var crypto = CryptoManager.init(allocator);
|
|
defer crypto.deinit();
|
|
|
|
const peer_id = [_]u8{0x01} ** 32;
|
|
const key = [_]u8{0x42} ** 32;
|
|
try crypto.setKeyForPeer(peer_id, key);
|
|
|
|
// Test with various message sizes
|
|
const sizes = [_]usize{ 0, 1, 16, 100, 1000, 10000 };
|
|
|
|
for (sizes) |size| {
|
|
const plaintext = try allocator.alloc(u8, size);
|
|
defer allocator.free(plaintext);
|
|
|
|
// Fill with pattern
|
|
for (plaintext, 0..) |*byte, i| {
|
|
byte.* = @intCast(i % 256);
|
|
}
|
|
|
|
// Encrypt
|
|
const ciphertext = try crypto.encrypt(peer_id, plaintext);
|
|
defer allocator.free(ciphertext);
|
|
|
|
// Verify ciphertext size
|
|
const expected_size = 12 + size + 16; // nonce + plaintext + tag
|
|
try testing.expectEqual(expected_size, ciphertext.len);
|
|
|
|
// Decrypt
|
|
const decrypted = try crypto.decrypt(peer_id, ciphertext);
|
|
defer allocator.free(decrypted);
|
|
|
|
// Verify
|
|
try testing.expectEqualSlices(u8, plaintext, decrypted);
|
|
}
|
|
|
|
std.debug.print("Successfully tested {} different message sizes\n", .{sizes.len});
|
|
}
|
|
|
|
test "crypto: invalid ciphertext handling" {
|
|
const allocator = testing.allocator;
|
|
var crypto = CryptoManager.init(allocator);
|
|
defer crypto.deinit();
|
|
|
|
const peer_id = [_]u8{0x01} ** 32;
|
|
const key = [_]u8{0x42} ** 32;
|
|
try crypto.setKeyForPeer(peer_id, key);
|
|
|
|
// Test various invalid ciphertexts
|
|
const invalid_ciphertexts = [_][]const u8{
|
|
"", // Empty
|
|
"x", // Too short
|
|
"0123456789AB", // Less than minimum (28 bytes)
|
|
"0123456789ABCDEF0123456", // Less than minimum
|
|
};
|
|
|
|
for (invalid_ciphertexts) |invalid_ct| {
|
|
const result = crypto.decrypt(peer_id, invalid_ct);
|
|
|
|
try testing.expectError(CryptoError.InvalidCiphertext, result);
|
|
}
|
|
}
|
|
|
|
test "crypto: no key error handling" {
|
|
const allocator = testing.allocator;
|
|
var crypto = CryptoManager.init(allocator);
|
|
defer crypto.deinit();
|
|
|
|
const peer_id = [_]u8{0x01} ** 32;
|
|
const unknown_peer = [_]u8{0xFF} ** 32;
|
|
|
|
const key = [_]u8{0x42} ** 32;
|
|
try crypto.setKeyForPeer(peer_id, key);
|
|
|
|
// Try to encrypt for unknown peer
|
|
const encrypt_result = crypto.encrypt(unknown_peer, "test");
|
|
try testing.expectError(CryptoError.NoKeyForPeer, encrypt_result);
|
|
|
|
// Try to decrypt from unknown peer
|
|
const fake_ciphertext = [_]u8{0} ** 28;
|
|
const decrypt_result = crypto.decrypt(unknown_peer, &fake_ciphertext);
|
|
try testing.expectError(CryptoError.NoKeyForPeer, decrypt_result);
|
|
}
|
|
|
|
test "crypto: deterministic encryption verification" {
|
|
const allocator = testing.allocator;
|
|
var crypto = CryptoManager.init(allocator);
|
|
defer crypto.deinit();
|
|
|
|
const peer_id = [_]u8{0x01} ** 32;
|
|
const key = [_]u8{0x42} ** 32;
|
|
try crypto.setKeyForPeer(peer_id, key);
|
|
|
|
const plaintext = "Same message encrypted twice";
|
|
|
|
// Encrypt twice
|
|
const ct1 = try crypto.encrypt(peer_id, plaintext);
|
|
defer allocator.free(ct1);
|
|
|
|
const ct2 = try crypto.encrypt(peer_id, plaintext);
|
|
defer allocator.free(ct2);
|
|
|
|
// Ciphertexts should be DIFFERENT (due to random nonce)
|
|
// This prevents traffic analysis
|
|
if (std.mem.eql(u8, ct1, ct2)) {
|
|
std.debug.print("WARNING: Ciphertexts are identical (deterministic encryption)\n", .{});
|
|
// This is a security issue but not necessarily a test failure
|
|
// since it depends on nonce generation
|
|
} else {
|
|
std.debug.print("GOOD: Ciphertexts differ (non-deterministic encryption)\n", .{});
|
|
}
|
|
|
|
// Both should decrypt to same plaintext
|
|
const pt1 = try crypto.decrypt(peer_id, ct1);
|
|
defer allocator.free(pt1);
|
|
|
|
const pt2 = try crypto.decrypt(peer_id, ct2);
|
|
defer allocator.free(pt2);
|
|
|
|
try testing.expectEqualSlices(u8, plaintext, pt1);
|
|
try testing.expectEqualSlices(u8, plaintext, pt2);
|
|
}
|
|
|
|
test "crypto: memory cleanup verification" {
|
|
// Verify that sensitive data is properly cleaned up
|
|
const allocator = testing.allocator;
|
|
|
|
{
|
|
var crypto = CryptoManager.init(allocator);
|
|
defer crypto.deinit();
|
|
|
|
const peer_id = [_]u8{0x01} ** 32;
|
|
const key = [_]u8{0x42} ** 32;
|
|
try crypto.setKeyForPeer(peer_id, key);
|
|
|
|
const plaintext = "Sensitive data that should be cleaned up";
|
|
const ct = try crypto.encrypt(peer_id, plaintext);
|
|
defer allocator.free(ct);
|
|
|
|
const decrypted = try crypto.decrypt(peer_id, ct);
|
|
defer allocator.free(decrypted);
|
|
|
|
// Verify decryption worked
|
|
try testing.expectEqualSlices(u8, plaintext, decrypted);
|
|
}
|
|
|
|
// After scope, all memory should be freed
|
|
// Testing allocator will detect leaks
|
|
std.debug.print("Memory cleanup verification passed\n", .{});
|
|
}
|
|
|
|
test "crypto: concurrent encryption safety" {
|
|
// Note: This tests that encryption is thread-safe at the API level
|
|
// Full thread safety would require actual concurrent access
|
|
const allocator = testing.allocator;
|
|
|
|
var crypto = CryptoManager.init(allocator);
|
|
defer crypto.deinit();
|
|
|
|
const peer_id = [_]u8{0x01} ** 32;
|
|
const key = [_]u8{0x42} ** 32;
|
|
try crypto.setKeyForPeer(peer_id, key);
|
|
|
|
// Simulate multiple "concurrent" encryptions
|
|
const num_operations = 10;
|
|
var ciphertexts: [num_operations][]u8 = undefined;
|
|
|
|
for (&ciphertexts, 0..) |*ct, i| {
|
|
const msg = try std.fmt.allocPrint(allocator, "Message {}", .{i});
|
|
defer allocator.free(msg);
|
|
|
|
ct.* = try crypto.encrypt(peer_id, msg);
|
|
}
|
|
|
|
// Clean up
|
|
for (ciphertexts) |ct| {
|
|
allocator.free(ct);
|
|
}
|
|
|
|
std.debug.print("Concurrent encryption API test passed\n", .{});
|
|
}
|