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
//! Shared minimal DER TLV walker.
//!
//! Used by CMS SignedData eContent extraction (for the AS-REP DH branch's
//! KDC-DH-Key-Info) and by CMS EnvelopedData decryption (for the AS-REP
//! encKeyPack branch's ReplyKeyPack).  Both walk fixed CMS shapes over
//! already-signed-by-the-KDC data, so a full ASN.1 typed decoder is overkill
//! for what we need to peel — a hand-walk keeps the diff auditable and
//! avoids pulling in a second CMS layer beside the encode-side `der` stack.

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

/// Read one DER TLV.  Returns `(value, rest)`.
pub(crate) fn tlv_split(bytes: &[u8]) -> Result<(&[u8], &[u8])> {
    if bytes.is_empty() {
        return Err(Error::AsRepParse("TLV: empty input".into()));
    }
    // Multi-byte tag (rare here) — but if present, keep reading tag bytes.
    let mut idx = 1;
    if bytes[0] & 0x1F == 0x1F {
        while idx < bytes.len() && bytes[idx] & 0x80 != 0 {
            idx += 1;
        }
        if idx >= bytes.len() {
            return Err(Error::AsRepParse("TLV: truncated tag".into()));
        }
        idx += 1;
    }
    if idx >= bytes.len() {
        return Err(Error::AsRepParse("TLV: no length byte".into()));
    }
    let (len, len_consumed) = read_der_length(&bytes[idx..])?;
    let value_start = idx + len_consumed;
    let value_end = value_start
        .checked_add(len)
        .ok_or_else(|| Error::AsRepParse("TLV: length overflow".into()))?;
    if value_end > bytes.len() {
        return Err(Error::AsRepParse(format!(
            "TLV: value truncated (need {value_end}, have {})",
            bytes.len()
        )));
    }
    Ok((&bytes[value_start..value_end], &bytes[value_end..]))
}

/// Read a single TLV and assert the first tag byte matches `expected_tag`.
///
/// The CMS/PKINIT shapes we walk here only use single-byte tags (tag numbers
/// < 31), so checking the leading byte is sufficient.
pub(crate) fn tlv_expect_tag(bytes: &[u8], expected_tag: u8) -> Result<(&[u8], &[u8])> {
    let first = bytes
        .first()
        .copied()
        .ok_or_else(|| Error::AsRepParse("TLV: empty".into()))?;
    if first != expected_tag {
        return Err(Error::AsRepParse(format!(
            "TLV: expected tag 0x{expected_tag:02X}, got 0x{first:02X}"
        )));
    }
    tlv_split(bytes)
}

/// Parse a DER length header.  Returns `(length_value, bytes_consumed)`.
pub(crate) fn read_der_length(bytes: &[u8]) -> Result<(usize, usize)> {
    let first = *bytes
        .first()
        .ok_or_else(|| Error::AsRepParse("length: empty".into()))?;
    if first & 0x80 == 0 {
        return Ok((first as usize, 1));
    }
    let n = (first & 0x7F) as usize;
    if n == 0 || n > 4 {
        return Err(Error::AsRepParse(format!("length: bad long-form n={n}")));
    }
    if bytes.len() < 1 + n {
        return Err(Error::AsRepParse("length: truncated long-form".into()));
    }
    let mut v: usize = 0;
    for &b in &bytes[1..1 + n] {
        v = (v << 8) | b as usize;
    }
    Ok((v, 1 + n))
}

/// Given a DER-encoded CMS ContentInfo (id-signedData), return the eContent
/// OCTET STRING payload (e.g. the KDC-DH-Key-Info DER, or an inner
/// ReplyKeyPack when a nested SignedData sits inside the EnvelopedData
/// per RFC 4556 §3.2.3.2).
///
/// Structural walk:
/// ```text
/// ContentInfo ::= SEQUENCE { contentType OID, content [0] EXPLICIT ANY }
/// SignedData  ::= SEQUENCE { version, digestAlgs, encapContentInfo, ...}
/// EncapCI     ::= SEQUENCE { eContentType OID, [0] EXPLICIT OCTET STRING OPT }
/// ```
///
/// KDC signature verification against the KDC's cert chain is a 0.2 concern;
/// this helper trusts the eContent for now.
pub(crate) fn extract_signed_data_econtent(content_info: &[u8]) -> Result<Vec<u8>> {
    let (seq_body, _) = tlv_expect_tag(content_info, 0x30)?;
    let (_oid, after_oid) = tlv_split(seq_body)?;
    let (ctx0_body, _) = tlv_expect_tag(after_oid, 0xA0)?;
    let (sd_body, _) = tlv_expect_tag(ctx0_body, 0x30)?;
    let (_ver, after_ver) = tlv_split(sd_body)?;
    let (_da, after_da) = tlv_split(after_ver)?;
    let (encap_body, _) = tlv_expect_tag(after_da, 0x30)?;
    let (_ecid, after_ecid) = tlv_split(encap_body)?;
    let (ctx0_econtent, _) = tlv_expect_tag(after_ecid, 0xA0)?;
    let (econtent_body, _) = tlv_expect_tag(ctx0_econtent, 0x04)?;
    Ok(econtent_body.to_vec())
}

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

    #[test]
    fn tlv_split_short_form() {
        // SEQUENCE (5 bytes) containing OCTET STRING (3 bytes) "abc"
        let seq = [0x30u8, 0x05, 0x04, 0x03, b'a', b'b', b'c'];
        let (body, rest) = tlv_split(&seq).unwrap();
        assert_eq!(body, &[0x04, 0x03, b'a', b'b', b'c']);
        assert!(rest.is_empty());
    }

    #[test]
    fn tlv_split_long_form_length() {
        // OCTET STRING with long-form length: 04 81 80 <128 bytes>
        let mut blob = vec![0x04, 0x81, 0x80];
        blob.extend(std::iter::repeat(0x41).take(128));
        let (body, rest) = tlv_split(&blob).unwrap();
        assert_eq!(body.len(), 128);
        assert!(rest.is_empty());
    }

    #[test]
    fn tlv_expect_tag_rejects_mismatch() {
        let seq = [0x30u8, 0x00];
        let err = tlv_expect_tag(&seq, 0x04).unwrap_err();
        assert!(matches!(err, Error::AsRepParse(_)));
    }
}