torrentdht 0.1.1

DHT discovery with mTLS handshake handoff; optional BitTorrent when the host opts in
Documentation
//! Encrypted credential exchange over the established mTLS stream.

use chacha20poly1305::aead::{Aead, KeyInit};
use chacha20poly1305::{ChaCha20Poly1305, Nonce};
use hkdf::Hkdf;
use sha2::Sha256;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};

use crate::error::{Error, Result};

const MAX_FRAME: usize = 64 * 1024;
const NONCE_LEN: usize = 12;
const KEY_LEN: usize = 32;

/// Who owns credential exchange after handshake approval.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CredentialMode {
    /// Crate seals credentials with ChaCha20-Poly1305 over the TLS stream.
    SealedChannel,
    /// Host project performs exchange on the TLS stream after approval.
    HostManaged,
}

/// Opaque credential blob exchanged after approval.
#[derive(Debug, Clone, Default)]
pub struct CredentialBundle {
    pub bytes: Vec<u8>,
}

impl CredentialBundle {
    pub fn empty() -> Self {
        Self { bytes: Vec::new() }
    }

    pub fn new(bytes: impl Into<Vec<u8>>) -> Self {
        Self {
            bytes: bytes.into(),
        }
    }
}

/// Length-prefixed encrypted frames on an already-authenticated TLS stream.
///
/// Uses distinct directional AEAD keys so initiator and acceptor never encrypt
/// under the same `(key, nonce)` pair.
pub struct CredentialChannel<'a, S> {
    stream: &'a mut S,
    send_cipher: ChaCha20Poly1305,
    recv_cipher: ChaCha20Poly1305,
    send_counter: u64,
    recv_counter: u64,
}

impl<'a, S> CredentialChannel<'a, S>
where
    S: AsyncRead + AsyncWrite + Unpin,
{
    /// Derive directional channel keys from handshake key + transcript salt.
    ///
    /// `initiator` must match the TLS dial role: both peers derive the same
    /// i2a / a2i keys, then each uses the opposite key for receive.
    pub fn new(
        stream: &'a mut S,
        handshake_key: &[u8],
        salt: &[u8],
        initiator: bool,
    ) -> Result<Self> {
        if handshake_key.is_empty() {
            return Err(Error::Secure("handshake key must not be empty".into()));
        }
        let (i2a, a2i) = derive_directional_keys(handshake_key, salt)?;
        let (send_key, recv_key) = if initiator {
            (i2a, a2i)
        } else {
            (a2i, i2a)
        };
        let send_cipher = ChaCha20Poly1305::new_from_slice(&send_key)
            .map_err(|err| Error::Secure(format!("cipher init: {err}")))?;
        let recv_cipher = ChaCha20Poly1305::new_from_slice(&recv_key)
            .map_err(|err| Error::Secure(format!("cipher init: {err}")))?;
        Ok(Self {
            stream,
            send_cipher,
            recv_cipher,
            send_counter: 0,
            recv_counter: 0,
        })
    }

    pub async fn send_sealed(&mut self, plaintext: &[u8]) -> Result<()> {
        if plaintext.len() > MAX_FRAME {
            return Err(Error::Secure("credential frame too large".into()));
        }
        let nonce = counter_nonce(self.send_counter);
        self.send_counter = self
            .send_counter
            .checked_add(1)
            .ok_or_else(|| Error::Secure("credential send counter exhausted".into()))?;
        let ciphertext = self
            .send_cipher
            .encrypt(Nonce::from_slice(&nonce), plaintext)
            .map_err(|err| Error::Secure(format!("seal credentials: {err}")))?;
        let len = (ciphertext.len() as u32).to_be_bytes();
        self.stream.write_all(&len).await?;
        self.stream.write_all(&ciphertext).await?;
        self.stream.flush().await?;
        Ok(())
    }

    pub async fn recv_sealed(&mut self) -> Result<Vec<u8>> {
        let mut len_buf = [0u8; 4];
        self.stream.read_exact(&mut len_buf).await?;
        let len = u32::from_be_bytes(len_buf) as usize;
        if len == 0 || len > MAX_FRAME + 16 {
            return Err(Error::Secure("invalid credential frame length".into()));
        }
        let mut ciphertext = vec![0u8; len];
        self.stream.read_exact(&mut ciphertext).await?;
        let nonce = counter_nonce(self.recv_counter);
        self.recv_counter = self
            .recv_counter
            .checked_add(1)
            .ok_or_else(|| Error::Secure("credential recv counter exhausted".into()))?;
        self.recv_cipher
            .decrypt(Nonce::from_slice(&nonce), ciphertext.as_ref())
            .map_err(|_| Error::Secure("credential decrypt failed".into()))
    }

    /// Default bilateral exchange: send local, receive remote.
    pub async fn exchange(
        &mut self,
        local: &CredentialBundle,
    ) -> Result<CredentialBundle> {
        self.send_sealed(&local.bytes).await?;
        let remote = self.recv_sealed().await?;
        Ok(CredentialBundle::new(remote))
    }

    /// Host-managed path: expose raw sealed send/recv only.
    pub fn as_raw_stream(&mut self) -> &mut S {
        self.stream
    }
}

fn derive_directional_keys(handshake_key: &[u8], salt: &[u8]) -> Result<([u8; KEY_LEN], [u8; KEY_LEN])> {
    let hk = Hkdf::<Sha256>::new(Some(salt), handshake_key);
    let mut okm = [0u8; KEY_LEN * 2];
    hk.expand(b"credential-channel-v2", &mut okm)
        .map_err(|_| Error::Secure("hkdf expand failed".into()))?;
    let mut i2a = [0u8; KEY_LEN];
    let mut a2i = [0u8; KEY_LEN];
    i2a.copy_from_slice(&okm[..KEY_LEN]);
    a2i.copy_from_slice(&okm[KEY_LEN..]);
    if constant_time_eq_slice(&i2a, &a2i) {
        return Err(Error::Secure(
            "directional credential keys collided (refusing to proceed)".into(),
        ));
    }
    Ok((i2a, a2i))
}

fn constant_time_eq_slice(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    let mut diff = 0u8;
    for (x, y) in a.iter().zip(b.iter()) {
        diff |= x ^ y;
    }
    diff == 0
}

fn counter_nonce(counter: u64) -> [u8; NONCE_LEN] {
    let mut nonce = [0u8; NONCE_LEN];
    nonce[4..].copy_from_slice(&counter.to_be_bytes());
    nonce
}

/// Framing helpers for the pre-credential handshake offer exchange (still over TLS).
pub async fn write_frame<S: AsyncWrite + Unpin>(stream: &mut S, payload: &[u8]) -> Result<()> {
    if payload.len() > MAX_FRAME {
        return Err(Error::Secure("handshake frame too large".into()));
    }
    let len = (payload.len() as u32).to_be_bytes();
    stream.write_all(&len).await?;
    stream.write_all(payload).await?;
    stream.flush().await?;
    Ok(())
}

pub async fn read_frame<S: AsyncRead + Unpin>(stream: &mut S) -> Result<Vec<u8>> {
    let mut len_buf = [0u8; 4];
    stream.read_exact(&mut len_buf).await?;
    let len = u32::from_be_bytes(len_buf) as usize;
    if len > MAX_FRAME {
        return Err(Error::Secure("handshake frame too large".into()));
    }
    let mut buf = vec![0u8; len];
    if len > 0 {
        stream.read_exact(&mut buf).await?;
    }
    Ok(buf)
}

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

    #[tokio::test]
    async fn sealed_roundtrip_on_memory() {
        let key = b"test-handshake-key";
        let salt = b"salt";
        let (mut a, mut b) = tokio::io::duplex(4096);
        let t1 = tokio::spawn(async move {
            let mut ch = CredentialChannel::new(&mut a, key, salt, true).unwrap();
            ch.send_sealed(b"hello").await.unwrap();
            ch.recv_sealed().await.unwrap()
        });
        let t2 = tokio::spawn(async move {
            let mut ch = CredentialChannel::new(&mut b, key, salt, false).unwrap();
            let got = ch.recv_sealed().await.unwrap();
            ch.send_sealed(b"world").await.unwrap();
            got
        });
        assert_eq!(t1.await.unwrap(), b"world");
        assert_eq!(t2.await.unwrap(), b"hello");
    }

    #[test]
    fn directional_keys_differ() {
        let (i2a, a2i) = derive_directional_keys(b"key", b"salt").expect("keys");
        assert_ne!(i2a, a2i);
    }

    #[test]
    fn first_frame_ciphertexts_differ_by_direction() {
        let key = b"test-handshake-key";
        let salt = b"salt";
        let (i2a, a2i) = derive_directional_keys(key, salt).unwrap();
        let plain = b"same-plaintext";
        let nonce = counter_nonce(0);
        let c_i2a = ChaCha20Poly1305::new_from_slice(&i2a)
            .unwrap()
            .encrypt(Nonce::from_slice(&nonce), plain.as_ref())
            .unwrap();
        let c_a2i = ChaCha20Poly1305::new_from_slice(&a2i)
            .unwrap()
            .encrypt(Nonce::from_slice(&nonce), plain.as_ref())
            .unwrap();
        assert_ne!(
            c_i2a, c_a2i,
            "initiator and acceptor must not share (key, nonce) for counter 0"
        );
    }

    #[tokio::test]
    async fn same_role_both_sides_fails_decrypt() {
        let key = b"test-handshake-key";
        let salt = b"salt";
        let (mut a, mut b) = tokio::io::duplex(4096);
        let t1 = tokio::spawn(async move {
            let mut ch = CredentialChannel::new(&mut a, key, salt, true).unwrap();
            ch.send_sealed(b"hello").await.unwrap();
        });
        let t2 = tokio::spawn(async move {
            // Wrong: both sides claim initiator → recv key mismatch.
            let mut ch = CredentialChannel::new(&mut b, key, salt, true).unwrap();
            ch.recv_sealed().await
        });
        t1.await.unwrap();
        assert!(t2.await.unwrap().is_err());
    }
}