clm-kernel 0.0.11

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! WireGuard key exchange and tunnel establishment for Sprint 140.1.
//!
//! Provides X25519 keypair generation, hex encoding for mDNS announcement,
//! and userspace WireGuard tunnel establishment using `boringtun`-style
//! peer configuration. The keypair uses `x25519-dalek` which is the standard
//! Rust implementation of Curve25519 Diffie-Hellman key exchange — the same
//! curve used by WireGuard for session key agreement.

use x25519_dalek::{PublicKey, StaticSecret};
use rand::rngs::OsRng;
use serde::{Serialize, Deserialize};
use std::net::SocketAddr;

/// WireGuard keypair for a PKC node.
///
/// The private key is 32 bytes of random data on Curve25519.
/// The public key is the corresponding X25519 public key.
/// The public key is announced via mDNS so peers can establish tunnels.
#[derive(Clone, Serialize, Deserialize)]
pub struct WgKeypair {
    private_key: [u8; 32],
    public_key: [u8; 32],
}

impl WgKeypair {
    /// Generate a new WireGuard keypair using the OS CSPRNG.
    pub fn generate() -> Self {
        let secret = StaticSecret::random_from_rng(OsRng);
        let public = PublicKey::from(&secret);
        Self {
            private_key: secret.to_bytes(),
            public_key: public.to_bytes(),
        }
    }

    /// Generate a WireGuard keypair from a deterministic 32-byte seed.
    /// Used for testing — production code should use `generate()`.
    pub fn from_seed(seed: &[u8; 32]) -> Self {
        let secret = StaticSecret::from(*seed);
        let public = PublicKey::from(&secret);
        Self {
            private_key: secret.to_bytes(),
            public_key: public.to_bytes(),
        }
    }

    /// Returns the public key as a 64-character hex string for mDNS announcement.
    pub fn public_key_hex(&self) -> String {
        hex::encode(self.public_key)
    }

    /// Returns the private key as a 64-character hex string.
    /// Used for debugging and testing only — never log or expose in production.
    pub fn private_key_hex(&self) -> String {
        hex::encode(self.private_key)
    }

    /// Returns the raw 32-byte public key.
    pub fn public_key_bytes(&self) -> &[u8; 32] {
        &self.public_key
    }

    /// Returns the raw 32-byte private key.
    pub fn private_key_bytes(&self) -> &[u8; 32] {
        &self.private_key
    }

    /// Perform X25519 Diffie-Hellman with a peer's public key to derive
    /// a shared secret. This shared secret is the basis for the WireGuard
    /// session key.
    pub fn diffie_hellman(&self, peer_public_key: &[u8; 32]) -> [u8; 32] {
        let secret = StaticSecret::from(self.private_key);
        let peer_public = PublicKey::from(*peer_public_key);
        let shared = secret.diffie_hellman(&peer_public);
        shared.to_bytes()
    }
}

impl std::fmt::Debug for WgKeypair {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WgKeypair")
            .field("public_key", &self.public_key_hex())
            .field("private_key", &"[REDACTED]")
            .finish()
    }
}

/// Parse a 64-character hex string into a 32-byte public key.
pub fn parse_public_key_hex(hex_str: &str) -> Result<[u8; 32], String> {
    let bytes = hex::decode(hex_str).map_err(|e| format!("Invalid hex: {}", e))?;
    if bytes.len() != 32 {
        return Err(format!("Public key must be 32 bytes, got {}", bytes.len()));
    }
    let mut arr = [0u8; 32];
    arr.copy_from_slice(&bytes);
    Ok(arr)
}

/// A WireGuard tunnel to a peer PKC node.
///
/// In the userspace implementation, the tunnel represents an established
/// WireGuard session with a peer. The `virtual_ip` is the peer's address
/// within the WireGuard overlay network.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WgTunnel {
    pub interface_name: String,
    pub peer_addr: SocketAddr,
    pub virtual_ip: String,
    pub peer_public_key: String,
}

/// Establish a WireGuard tunnel to a peer.
///
/// This performs the X25519 key exchange and creates a `WgTunnel` record
/// representing the established session. In a full implementation, this
/// would create a TUN device and start the WireGuard handshake. For now,
/// it performs the cryptographic key exchange and records the tunnel
/// metadata for the QUIC transport layer (Sprint 140.2) to use.
///
/// # Arguments
/// * `peer_ip` - The peer's IP address (for the UDP endpoint)
/// * `peer_port` - The peer's WireGuard UDP port
/// * `peer_wg_pubkey_hex` - The peer's WireGuard public key as hex
/// * `local_keypair` - This node's WireGuard keypair
/// * `local_virtual_ip` - This node's virtual IP in the overlay
/// * `peer_virtual_ip` - The peer's virtual IP in the overlay
pub fn establish_wireguard_tunnel(
    peer_ip: &str,
    peer_port: u16,
    peer_wg_pubkey_hex: &str,
    local_keypair: &WgKeypair,
    _local_virtual_ip: &str,
    peer_virtual_ip: &str,
) -> Result<WgTunnel, String> {
    let peer_public_key = parse_public_key_hex(peer_wg_pubkey_hex)?;

    // Perform X25519 Diffie-Hellman key exchange
    let _shared_secret = local_keypair.diffie_hellman(&peer_public_key);

    // Parse peer address
    let peer_addr: SocketAddr = format!("{}:{}", peer_ip, peer_port)
        .parse()
        .map_err(|e| format!("Invalid peer address {}:{}: {}", peer_ip, peer_port, e))?;

    // Generate interface name based on peer public key hash
    let interface_name = format!("wg{}", &peer_wg_pubkey_hex[..8]);

    Ok(WgTunnel {
        interface_name,
        peer_addr,
        virtual_ip: peer_virtual_ip.to_string(),
        peer_public_key: peer_wg_pubkey_hex.to_string(),
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_keypair_generation_produces_32_byte_keys() {
        let kp = WgKeypair::generate();
        assert_eq!(kp.public_key_bytes().len(), 32);
        assert_eq!(kp.private_key_bytes().len(), 32);
    }

    #[test]
    fn test_public_key_hex_is_64_chars() {
        let kp = WgKeypair::generate();
        let hex = kp.public_key_hex();
        assert_eq!(hex.len(), 64);
        // Verify it's valid hex
        assert!(hex.chars().all(|c| c.is_ascii_hexdigit()));
    }

    #[test]
    fn test_deterministic_generation_from_seed() {
        let seed = [42u8; 32];
        let kp1 = WgKeypair::from_seed(&seed);
        let kp2 = WgKeypair::from_seed(&seed);
        assert_eq!(kp1.public_key_hex(), kp2.public_key_hex());
        assert_eq!(kp1.private_key_hex(), kp2.private_key_hex());
    }

    #[test]
    fn test_different_seeds_produce_different_keypairs() {
        let kp1 = WgKeypair::from_seed(&[1u8; 32]);
        let kp2 = WgKeypair::from_seed(&[2u8; 32]);
        assert_ne!(kp1.public_key_hex(), kp2.public_key_hex());
    }

    #[test]
    fn test_diffie_hellman_produces_shared_secret() {
        let alice = WgKeypair::generate();
        let bob = WgKeypair::generate();

        let alice_shared = alice.diffie_hellman(bob.public_key_bytes());
        let bob_shared = bob.diffie_hellman(alice.public_key_bytes());

        // Both parties should derive the same shared secret
        assert_eq!(alice_shared, bob_shared);
        // Shared secret should be 32 bytes
        assert_eq!(alice_shared.len(), 32);
        // Shared secret should not be all zeros
        assert!(alice_shared.iter().any(|&b| b != 0));
    }

    #[test]
    fn test_parse_public_key_hex_valid() {
        let kp = WgKeypair::generate();
        let hex = kp.public_key_hex();
        let parsed = parse_public_key_hex(&hex).unwrap();
        assert_eq!(parsed, *kp.public_key_bytes());
    }

    #[test]
    fn test_parse_public_key_hex_invalid_length() {
        let result = parse_public_key_hex("abc123");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("32 bytes"));
    }

    #[test]
    fn test_parse_public_key_hex_invalid_hex() {
        let result = parse_public_key_hex(&"zz".repeat(32));
        assert!(result.is_err());
    }

    #[test]
    fn test_establish_wireguard_tunnel() {
        let alice = WgKeypair::from_seed(&[1u8; 32]);
        let bob = WgKeypair::from_seed(&[2u8; 32]);

        let tunnel = establish_wireguard_tunnel(
            "127.0.0.1",
            51820,
            &bob.public_key_hex(),
            &alice,
            "10.0.0.1",
            "10.0.0.2",
        ).unwrap();

        assert_eq!(tunnel.peer_addr, "127.0.0.1:51820".parse().unwrap());
        assert_eq!(tunnel.virtual_ip, "10.0.0.2");
        assert_eq!(tunnel.peer_public_key, bob.public_key_hex());
        assert!(tunnel.interface_name.starts_with("wg"));
    }

    #[test]
    fn test_establish_wireguard_tunnel_invalid_pubkey() {
        let kp = WgKeypair::generate();
        let result = establish_wireguard_tunnel(
            "127.0.0.1",
            51820,
            "invalid",
            &kp,
            "10.0.0.1",
            "10.0.0.2",
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_establish_wireguard_tunnel_invalid_addr() {
        let alice = WgKeypair::from_seed(&[1u8; 32]);
        let bob = WgKeypair::from_seed(&[2u8; 32]);

        let result = establish_wireguard_tunnel(
            "999.999.999.999",
            51820,
            &bob.public_key_hex(),
            &alice,
            "10.0.0.1",
            "10.0.0.2",
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_debug_does_not_leak_private_key() {
        let kp = WgKeypair::generate();
        let debug_str = format!("{:?}", kp);
        assert!(debug_str.contains("[REDACTED]"));
        assert!(!debug_str.contains(&kp.private_key_hex()));
    }
}