Security Utils Security API Documentation

⚠️ CRITICAL SECURITY MODULE ⚠️

THIS MODULE PROVIDES FOUNDATIONAL SECURITY UTILITIES

1. API Functions

1.1 Secure Memory Operations

secure_zero_memory(buffer: &mut [u8])

Security Contract:

Critical Requirements:

secure_compare(a: &[u8], b: &[u8]) -> bool

Security Contract:

Attack Resistance:

1.2 Random Number Generation

secure_random_bytes(length: usize) -> Result<Vec<u8>>

Security Contract:

Critical Requirements:

secure_random_u32() -> Result<u32>

Security Contract:

1.3 Validation Utilities

validate_key_size(algorithm: &str, key_size: usize) -> Result<()>

Security Contract:

Key Size Requirements:

AES: 128, 192, 256 bits only
RSA: >= 2048 bits
ECC: >= 256 bits
Ed25519: exactly 256 bits

validate_nonce_uniqueness(nonce: &[u8], cache: &NonceCache) -> Result<()>

Security Contract:

1.4 Constant-Time Operations

ct_select(condition: bool, a: u8, b: u8) -> u8

Security Contract:

ct_copy(condition: bool, dest: &mut [u8], src: &[u8])

Security Contract:

2. Attack Resistance Matrix

Attack Vector Protection Mechanism Implementation
Timing Attacks Constant-time operations Bitwise ops, no branches
Memory Disclosure Secure zeroing Compiler barriers
RNG Prediction CSPRNG usage OS entropy sources
Compiler Optimization Volatile operations Memory barriers
Side Channels Constant memory access No secret-dependent indexing

3. Implementation Examples

Python Example

import os
import ctypes
from typing import Union

class SecurityUtils:
    @staticmethod
    def secure_zero_memory(data: Union[bytes, bytearray, memoryview]) -> None:
        """Securely zero memory, preventing optimization."""
        if isinstance(data, bytes):
            raise TypeError("Cannot modify immutable bytes")
        
        # Use ctypes to ensure memory is actually zeroed
        size = len(data)
        if size > 0:
            ctypes.memset(ctypes.addressof(ctypes.c_char.from_buffer(data)), 0, size)
    
    @staticmethod
    def secure_compare(a: bytes, b: bytes) -> bool:
        """Constant-time comparison."""
        if len(a) != len(b):
            return False
        
        result = 0
        for x, y in zip(a, b):
            result |= x ^ y
        
        return result == 0
    
    @staticmethod
    def secure_random_bytes(length: int) -> bytes:
        """Generate cryptographically secure random bytes."""
        if length < 0:
            raise ValueError("Length must be non-negative")
        
        return os.urandom(length)

Rust Example

use std::sync::atomic::{AtomicPtr, Ordering};
use getrandom::getrandom;

pub struct SecurityUtils;

impl SecurityUtils {
    pub fn secure_zero_memory(buffer: &mut [u8]) {
        unsafe {
            // Use volatile write to prevent optimization
            let ptr = buffer.as_mut_ptr();
            let len = buffer.len();
            
            for i in 0..len {
                std::ptr::write_volatile(ptr.add(i), 0);
            }
            
            // Compiler barrier
            std::sync::atomic::compiler_fence(Ordering::SeqCst);
        }
    }
    
    pub fn secure_compare(a: &[u8], b: &[u8]) -> bool {
        if a.len() != b.len() {
            return false;
        }
        
        let mut result = 0u8;
        for (x, y) in a.iter().zip(b.iter()) {
            result |= x ^ y;
        }
        
        result == 0
    }
    
    pub fn secure_random_bytes(length: usize) -> Result<Vec<u8>, Error> {
        let mut buffer = vec![0u8; length];
        getrandom(&mut buffer)?;
        Ok(buffer)
    }
}

4. Common Vulnerabilities

4.1 Optimization Removal

// VULNERABLE - Compiler may optimize out
fn bad_zero_memory(buffer: &mut [u8]) {
    for b in buffer {
        *b = 0;  // May be removed if buffer not used after
    }
}

// SECURE - Uses volatile operations
fn secure_zero_memory(buffer: &mut [u8]) {
    unsafe {
        let ptr = buffer.as_mut_ptr();
        for i in 0..buffer.len() {
            std::ptr::write_volatile(ptr.add(i), 0);
        }
    }
}

4.2 Timing Leaks

# VULNERABLE - Early return leaks timing
def bad_compare(a: bytes, b: bytes) -> bool:
    if len(a) != len(b):
        return False
    for i in range(len(a)):
        if a[i] != b[i]:
            return False  # Timing leak!
    return True

# SECURE - Constant time
def secure_compare(a: bytes, b: bytes) -> bool:
    if len(a) != len(b):
        return False
    result = 0
    for x, y in zip(a, b):
        result |= x ^ y
    return result == 0

5. Performance Considerations

Operation Time Complexity Security Impact
secure_zero_memory O(n) Must not be optimized
secure_compare O(n) Always full comparison
secure_random_bytes O(n) May block for entropy
ct_select O(1) No branching allowed

6. Security Checklist

7. References

Security Analysis

Threat Model: Security Utilities Threat Model

This component provides critical security infrastructure. For comprehensive security analysis including:

See the dedicated threat model documentation for complete details.