clm-kernel 0.0.16

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Reticulum Link Transport for CLM Layer 3 Mesh.
//! Canonical Path: kernel/clm_rust_core/src/mesh/reticulum_transport.rs
//!
//! Implements:
//! - Single-roundtrip ephemeral Link handshake (X25519 ECDH + HKDF-SHA256)
//! - Authenticated AES-256-GCM session encryption with Perfect Forward Secrecy (PFS)
//! - Initiator anonymity (packets omit sender identity)
//! - Clean session teardown with key zeroization

use aes_gcm::{
    aead::{Aead, KeyInit, Payload},
    Aes256Gcm, Key, Nonce,
};
use rand::rngs::OsRng;
use rand::RngCore;
use sha2::{Digest, Sha256};
use thiserror::Error;
use x25519_dalek::{PublicKey as X25519PublicKey, StaticSecret as X25519StaticSecret};
use zeroize::Zeroize;

#[derive(Error, Debug)]
pub enum ReticulumTransportError {
    #[error("Session is closed")]
    SessionClosed,

    #[error("Session not established — handshake incomplete")]
    NotEstablished,

    #[error("Encrypted frame too short")]
    FrameTooShort,

    #[error("Decryption / AEAD authentication failed: {0}")]
    AeadError(String),
}

/// Standard HMAC-SHA256 (RFC 2104)
pub fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32] {
    let mut k = [0u8; 64];
    if key.len() > 64 {
        let hash = Sha256::digest(key);
        k[..32].copy_from_slice(&hash);
    } else {
        k[..key.len()].copy_from_slice(key);
    }

    let mut ipad = [0x36u8; 64];
    let mut opad = [0x5cu8; 64];
    for i in 0..64 {
        ipad[i] ^= k[i];
        opad[i] ^= k[i];
    }

    let mut inner = Sha256::new();
    inner.update(ipad);
    inner.update(data);
    let inner_hash = inner.finalize();

    let mut outer = Sha256::new();
    outer.update(opad);
    outer.update(inner_hash);
    let outer_hash = outer.finalize();

    let mut out = [0u8; 32];
    out.copy_from_slice(&outer_hash);
    out
}

/// Standard HKDF-SHA256 Extract-and-Expand (RFC 5869) for 32-byte key
pub fn hkdf_sha256_32(salt: &[u8], ikm: &[u8], info: &[u8]) -> [u8; 32] {
    let prk = hmac_sha256(salt, ikm);
    let mut msg = Vec::with_capacity(info.len() + 1);
    msg.extend_from_slice(info);
    msg.push(0x01);
    hmac_sha256(&prk, &msg)
}

pub struct ReticulumLinkSession {
    pub destination_hash: [u8; 16],
    pub is_initiator: bool,
    pub link_id: [u8; 16],

    ephemeral_secret: Option<X25519StaticSecret>,
    pub ephemeral_public: [u8; 32],
    derived_key: Option<[u8; 32]>,
    cipher: Option<Aes256Gcm>,
    seq: u32,
    pub is_closed: bool,
}

impl ReticulumLinkSession {
    /// Creates a new unestablished session with an ephemeral X25519 keypair.
    pub fn new(destination_hash: [u8; 16], is_initiator: bool, link_id: Option<[u8; 16]>) -> Self {
        let mut rng = OsRng;
        let mut lid = [0u8; 16];
        if let Some(id) = link_id {
            lid = id;
        } else {
            rng.fill_bytes(&mut lid);
        }

        let secret = X25519StaticSecret::random_from_rng(rng);
        let public = X25519PublicKey::from(&secret).to_bytes();

        Self {
            destination_hash,
            is_initiator,
            link_id: lid,
            ephemeral_secret: Some(secret),
            ephemeral_public: public,
            derived_key: None,
            cipher: None,
            seq: 0,
            is_closed: false,
        }
    }

    /// Completes the handshake with the peer's ephemeral public key.
    pub fn complete_handshake(&mut self, peer_pub_bytes: &[u8; 32]) -> Result<(), ReticulumTransportError> {
        if self.is_closed {
            return Err(ReticulumTransportError::SessionClosed);
        }
        let secret = self
            .ephemeral_secret
            .take()
            .ok_or(ReticulumTransportError::SessionClosed)?;

        let peer_pub = X25519PublicKey::from(*peer_pub_bytes);
        let shared_secret = secret.diffie_hellman(&peer_pub);

        let key_bytes = hkdf_sha256_32(&self.link_id, shared_secret.as_bytes(), b"clm:reticulum:link:session");
        let key = Key::<Aes256Gcm>::from_slice(&key_bytes);
        self.cipher = Some(Aes256Gcm::new(key));
        self.derived_key = Some(key_bytes);

        Ok(())
    }

    /// Encrypts plaintext payload using AES-256-GCM with associated data = link_id.
    /// Framing: [12-byte nonce (4B seq + 8B random)] + [ciphertext + 16B tag]
    pub fn encrypt(&mut self, plaintext: &[u8]) -> Result<Vec<u8>, ReticulumTransportError> {
        if self.is_closed {
            return Err(ReticulumTransportError::SessionClosed);
        }
        let cipher = self
            .cipher
            .as_ref()
            .ok_or(ReticulumTransportError::NotEstablished)?;

        self.seq = self.seq.wrapping_add(1);
        let mut nonce_bytes = [0u8; 12];
        nonce_bytes[..4].copy_from_slice(&self.seq.to_be_bytes());
        OsRng.fill_bytes(&mut nonce_bytes[4..]);

        let nonce = Nonce::from_slice(&nonce_bytes);
        let payload = Payload {
            msg: plaintext,
            aad: &self.link_id,
        };

        let ciphertext = cipher
            .encrypt(nonce, payload)
            .map_err(|e| ReticulumTransportError::AeadError(format!("{:?}", e)))?;

        let mut frame = Vec::with_capacity(12 + ciphertext.len());
        frame.extend_from_slice(&nonce_bytes);
        frame.extend_from_slice(&ciphertext);
        Ok(frame)
    }

    /// Decrypts and authenticates AES-256-GCM frame.
    pub fn decrypt(&self, frame: &[u8]) -> Result<Vec<u8>, ReticulumTransportError> {
        if self.is_closed {
            return Err(ReticulumTransportError::SessionClosed);
        }
        let cipher = self
            .cipher
            .as_ref()
            .ok_or(ReticulumTransportError::NotEstablished)?;

        if frame.len() < 12 + 16 {
            return Err(ReticulumTransportError::FrameTooShort);
        }

        let nonce = Nonce::from_slice(&frame[..12]);
        let ciphertext = &frame[12..];

        let payload = Payload {
            msg: ciphertext,
            aad: &self.link_id,
        };

        cipher
            .decrypt(nonce, payload)
            .map_err(|e| ReticulumTransportError::AeadError(format!("{:?}", e)))
    }

    /// Zeroizes session keys and enforces Perfect Forward Secrecy (INV-L3-RET-355-02).
    pub fn close(&mut self) {
        if let Some(mut k) = self.derived_key.take() {
            k.zeroize();
        }
        self.ephemeral_secret = None;
        self.cipher = None;
        self.is_closed = true;
    }

    pub fn derived_key(&self) -> Option<&[u8; 32]> {
        self.derived_key.as_ref()
    }
}

/// Helper to establish an initiator and responder pair.
pub fn establish_link_pair(dest_hash: [u8; 16]) -> (ReticulumLinkSession, ReticulumLinkSession) {
    let mut lid = [0u8; 16];
    OsRng.fill_bytes(&mut lid);

    let mut initiator = ReticulumLinkSession::new(dest_hash, true, Some(lid));
    let mut responder = ReticulumLinkSession::new(dest_hash, false, Some(lid));

    let init_pub = initiator.ephemeral_public;
    let resp_pub = responder.ephemeral_public;

    initiator.complete_handshake(&resp_pub).unwrap();
    responder.complete_handshake(&init_pub).unwrap();

    (initiator, responder)
}

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

    #[test]
    fn test_link_handshake_and_encryption() {
        let dest = [0x77u8; 16];
        let (mut initiator, responder) = establish_link_pair(dest);

        assert_eq!(initiator.derived_key().unwrap(), responder.derived_key().unwrap());

        let msg = b"Rust native conversational MCard frame";
        let encrypted = initiator.encrypt(msg).unwrap();

        // Initiator anonymity check: plaintext not visible
        assert!(!encrypted.windows(msg.len()).any(|w| w == msg));

        let decrypted = responder.decrypt(&encrypted).unwrap();
        assert_eq!(decrypted, msg);

        // PFS check
        initiator.close();
        assert!(initiator.is_closed);
        assert!(initiator.derived_key().is_none());
        assert!(initiator.encrypt(b"fail").is_err());
    }
}