ms-pkca 0.1.0-dev

PKINIT (RFC 4556) client — PA-PK-AS-REQ / PA-PK-AS-REP with X.509 cert + UnPAC-the-hash (pre-alpha)
Documentation
//! Diffie-Hellman groups for PKINIT — RFC 4556 §3.2.1 / RFC 2412 (Oakley).
//!
//! RFC 4556 mandates support for MODP group 2 (Oakley 1024-bit) and recommends
//! group 14 (MODP 2048-bit). Both are hard-coded here as base-16 constants
//! (values lifted straight from RFC 2412 §E.1 / RFC 3526 §3).

use num_bigint_dig::BigUint;
use num_bigint_dig::RandBigInt;

/// Well-known Oakley / MODP groups usable in PKINIT.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DhGroup {
    /// MODP 1024 (Oakley group 2). Legacy but MTI in RFC 4556.
    Modp1024,
    /// MODP 2048 (Oakley group 14). Preferred.
    Modp2048,
}

impl DhGroup {
    pub fn modulus(self) -> BigUint {
        match self {
            DhGroup::Modp1024 => modp1024_p(),
            DhGroup::Modp2048 => modp2048_p(),
        }
    }
    pub fn generator(self) -> BigUint {
        BigUint::from(2u32)
    }
    /// Length in bits of the modulus p.
    pub fn p_bits(self) -> usize {
        match self {
            DhGroup::Modp1024 => 1024,
            DhGroup::Modp2048 => 2048,
        }
    }
}

/// Ephemeral DH key pair.
pub struct DhKeyPair {
    pub group: DhGroup,
    /// Private exponent x (kept in RAM only).
    pub x: BigUint,
    /// Public value y = g^x mod p.
    pub y: BigUint,
}

impl DhKeyPair {
    /// Generate an ephemeral key pair. `x_bits` should be at least 2 * strength;
    /// we default to 256 for group 2, 384 for group 14 (short-exponent optimization,
    /// per RFC 2631 §2.2.1 and common practice).
    pub fn generate(group: DhGroup) -> Self {
        let p = group.modulus();
        let g = group.generator();
        let x_bits = match group {
            DhGroup::Modp1024 => 256,
            DhGroup::Modp2048 => 384,
        };
        let mut rng = rand_core::OsRng;
        // num-bigint-dig RandBigInt wants a rand::Rng, so shim via getrandom.
        let x = gen_random_biguint(&mut rng, x_bits, &p);
        let y = g.modpow(&x, &p);
        DhKeyPair { group, x, y }
    }

    /// Compute shared secret ZZ = peer_y^x mod p.  Returns big-endian bytes
    /// left-padded to the modulus length (per RFC 4556 §3.2.3.1).
    pub fn compute_shared(&self, peer_y: &BigUint) -> Vec<u8> {
        let p = self.group.modulus();
        let zz = peer_y.modpow(&self.x, &p);
        let modulus_bytes = (self.group.p_bits() + 7) / 8;
        let mut out = zz.to_bytes_be();
        if out.len() < modulus_bytes {
            let mut padded = vec![0u8; modulus_bytes - out.len()];
            padded.append(&mut out);
            padded
        } else {
            out
        }
    }
}

fn gen_random_biguint(rng: &mut rand_core::OsRng, bits: usize, upper_bound: &BigUint) -> BigUint {
    use rand_core::RngCore;
    let n_bytes = (bits + 7) / 8;
    loop {
        let mut buf = vec![0u8; n_bytes];
        rng.fill_bytes(&mut buf);
        // Force top bit set so the resulting integer has full bit-length.
        buf[0] |= 0x80;
        let candidate = BigUint::from_bytes_be(&buf);
        if candidate < *upper_bound && candidate > BigUint::from(1u32) {
            return candidate;
        }
    }
}

// Bind the num-bigint-dig `RandBigInt` trait so `use` above doesn't warn if unused later.
#[allow(dead_code)]
fn _touch_randbigint() {
    let _ = std::marker::PhantomData::<dyn RandBigInt>;
}

fn hex_to_biguint(hex: &str) -> BigUint {
    let cleaned: String = hex.chars().filter(|c| !c.is_whitespace()).collect();
    BigUint::parse_bytes(cleaned.as_bytes(), 16).expect("valid hex constant")
}

/// RFC 2412 §E.1 — Oakley Group 2 (MODP 1024).
fn modp1024_p() -> BigUint {
    hex_to_biguint(concat!(
        "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1",
        "29024E088A67CC74020BBEA63B139B22514A08798E3404DD",
        "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245",
        "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED",
        "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381",
        "FFFFFFFFFFFFFFFF"
    ))
}

/// RFC 3526 §3 — MODP Group 14 (2048-bit).
fn modp2048_p() -> BigUint {
    hex_to_biguint(concat!(
        "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1",
        "29024E088A67CC74020BBEA63B139B22514A08798E3404DD",
        "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245",
        "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED",
        "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D",
        "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F",
        "83655D23DCA3AD961C62F356208552BB9ED529077096966D",
        "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B",
        "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9",
        "DE2BCBF6955817183995497CEA956AE515D2261898FA0510",
        "15728E5A8AACAA68FFFFFFFFFFFFFFFF"
    ))
}

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

    #[test]
    fn modulus_bit_length_matches_group() {
        assert_eq!(DhGroup::Modp1024.modulus().bits(), 1024);
        assert_eq!(DhGroup::Modp2048.modulus().bits(), 2048);
    }

    #[test]
    fn keypair_generates_and_agrees() {
        let a = DhKeyPair::generate(DhGroup::Modp1024);
        let b = DhKeyPair::generate(DhGroup::Modp1024);
        let za = a.compute_shared(&b.y);
        let zb = b.compute_shared(&a.y);
        assert_eq!(za, zb);
        assert_eq!(za.len(), 128); // 1024 bits
    }
}