pkix-path 0.6.0

RFC 5280 X.509 certificate path validation — pure Rust, no_std
Documentation
//! Ed521 (EdDSA over curve E-521), as specified by ICP-Brasil.
//!
//! # ⚠ DO NOT USE THIS FOR ANYTHING ELSE
//!
//! **This module exists to verify one certificate and should not be
//! used for any other purpose.** It is the least-validated code in this
//! workspace by a wide margin, and that is not a solvable problem with
//! the material available.
//!
//! Every other primitive added to this crate was checked against either
//! an independent implementation or a published test vector with
//! intermediate values. This one has neither:
//!
//! - **No published test vectors exist.** DOC-ICP-01.01 specifies the
//!   parameters completely and publishes no examples. RFC 8032 covers
//!   Ed25519 and Ed448 only, so its vectors do not apply.
//! - **No second Rust implementation exists** to differential-test
//!   against, and no OpenSSL support.
//! - **Exactly one real signature exercises it**: the `AC Raiz
//!   Brasileira v7` certificate in
//!   `third_party/trust-stores/br-icpbrasil/`. One signature proves the
//!   happy path and nothing else.
//!
//! So the **edge cases are untested**: the identity point, small-order
//! points, non-canonical `y >= p` encodings, cofactor behaviour, points
//! off the curve, and malleability of `S` are covered by argument and by
//! reading RFC 8032, not by a vector that would catch getting them
//! wrong. A general-purpose EdDSA implementation needs all of that
//! covered before anyone relies on it, and this is not one.
//!
//! It is behind the `ed521` feature, off by default and outside the
//! `rustcrypto` umbrella, for exactly that reason. It is here for
//! completeness of the vendored corpus -- so that no certificate in
//! `third_party/trust-stores/` is refused for an algorithm nobody
//! looked at -- and the one certificate it verifies is the only place it
//! will ever appear.
//!
//! # What Ed521 is
//!
//! EdDSA (RFC 8032's construction) over **E-521**, an untwisted Edwards
//! curve. ICP-Brasil's `AC Raiz Brasileira v7` root is signed with it:
//! the first official Brazilian root CA on E-521, per Kryptus, whose
//! kNET HSMs the ITI operates.
//!
//! # Where the parameters come from
//!
//! DOC-ICP-01.01 ("Padrões e Algoritmos Criptográficos da ICP-Brasil"),
//! section **"Parâmetros para a curva E521"**, which gives the full
//! RFC 8032 parameter table and states the construction is
//! "PureEdDSA e HashEdDSA, conforme RFC 8032":
//!
//! | parameter | value |
//! |---|---|
//! | `p` | `2^521 - 1` |
//! | `a` | 1 (so the curve is `x² + y² = 1 + d·x²·y²`, untwisted) |
//! | `d` | `-376014` |
//! | `b` | 528, so a key is 66 octets and a signature 132 |
//! | GF(p) encoding | 527-bit **little-endian** |
//! | `H(x)` | `SHAKE256(dom5(phflag, context) ‖ x, 132)` |
//! | `phflag` | 0, i.e. PureEdDSA; `PH` is the identity |
//! | cofactor | 4 (the document gives `c = 2`, its base-2 logarithm) |
//! | `B` | `(X, 12)` |
//! | `L` | the order of E-521, 519 bits |
//! | `dom5(x,y)` | `"SigEd521" ‖ octet(x) ‖ octet(OLEN(y)) ‖ y` |
//!
//! The parameters here are checked rather than trusted: this module's
//! tests recompute that `B` satisfies the curve equation and that
//! `[L]B` is the identity.
//!
//! # The OID, and why it is cited from the certificate
//!
//! The signature algorithm is `1.3.6.1.4.1.44588.2.1`. **DOC-ICP-01.01
//! never gives that number** -- it names the algorithm only
//! symbolically, as `id-Ed521`. The binding to that arc appears in
//! third-party code (the `edgetk` tool and the `kya-icp` monitor), which
//! is weak evidence for a normative claim.
//!
//! What makes it solid is the certificate: `AC Raiz Brasileira v7`
//! declares `1.3.6.1.4.1.44588.2.1` and its signature verifies as
//! Ed521 under these parameters. A wrong algorithm would not verify, so
//! the binding is established by the artifact rather than by the
//! documentation.
//!
//! # Verification
//!
//! RFC 8032 §5.2.7, with E-521's parameters substituted. Given a public
//! key `A`, a signature split into `R ‖ S`, and a message `M`:
//!
//! 1. decode `A` and `R` as compressed Edwards points, reject `S >= L`;
//! 2. `k = SHAKE256(dom5(0, "") ‖ R ‖ A ‖ M, 132)` read little-endian,
//!    reduced mod `L`;
//! 3. accept iff `[S]B = R + [k]A`.

use crypto_bigint::modular::ConstMontyForm;
use crypto_bigint::{NonZero, U576, const_monty_params};

// `p = 2^521 - 1`, carried in a 576-bit integer because 521 is not a
// machine-word multiple. DOC-ICP-01.01, `p`. The macro takes its own
// doc string, so this is a plain comment.
const_monty_params!(FieldP, U576, PARAM_P, "E-521's field modulus, 2^521 - 1");

const PARAM_P: &str = PP;
const PP: &str = "00000000000001ffffffffffffffffffffffffffffffffffffffffffffffffff\
        ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\
        ffffffffffffffff";

/// The order of E-521. DOC-ICP-01.01, `L`.
const PARAM_L: U576 = U576::from_be_hex(
    "000000000000007fffffffffffffffffffffffffffffffffffffffffffffffff\
        fffffffffffffffd15b6c64746fc85f736b8af5e7ec53f04fbd8c4569a8f1f45\
        40ea2435f5180d6b",
);

/// `d = -376014`, reduced. DOC-ICP-01.01, `d`.
const PARAM_D_NEG: U576 = U576::from_u64(376014);

/// `B`'s affine coordinates. DOC-ICP-01.01, `B`.
const PARAM_BX: U576 = U576::from_be_hex(
    "00000000000000752cb45c48648b189df90cb2296b2878a3bfd9f42fc6c818ec\
        8bf3c9c0c6203913f6ecc5ccc72434b1ae949d568fc99c6059d0fb13364838aa\
        302a940a2f19ba6c",
);
const PARAM_BY: U576 = U576::from_u64(12);

/// A field element modulo `p`.
type Fe = ConstMontyForm<FieldP, { U576::LIMBS }>;

fn fe(v: &U576) -> Fe {
    Fe::new(v)
}

/// `x^e mod p`, used for both inversion (`e = p-2`) and the square root
/// (`e = (p+1)/4`, valid because `p ≡ 3 mod 4`).
fn fe_pow(x: Fe, e: &U576) -> Fe {
    x.pow_amm(e)
}

fn fe_inv(x: Fe) -> Fe {
    // Fermat rather than a gcd: `p` is prime, and this module values
    // being obviously correct over being fast.
    let e = p_minus(2);
    fe_pow(x, &e)
}

fn p_minus(k: u64) -> U576 {
    U576::from_be_hex(PP).wrapping_sub(&U576::from_u64(k))
}

/// An affine point on `x² + y² = 1 + d·x²·y²`.
#[derive(Clone, Copy)]
struct Point {
    x: Fe,
    y: Fe,
}

impl Point {
    /// The neutral element, `(0, 1)`.
    fn identity() -> Self {
        Self {
            x: fe(&U576::ZERO),
            y: fe(&U576::ONE),
        }
    }

    fn eq(&self, other: &Self) -> bool {
        self.x == other.x && self.y == other.y
    }

    /// Untwisted Edwards addition, the `a = 1` formulas:
    ///
    /// ```text
    /// x3 = (x1·y2 + x2·y1) / (1 + d·x1·x2·y1·y2)
    /// y3 = (y1·y2 - x1·x2) / (1 - d·x1·x2·y1·y2)
    /// ```
    ///
    /// Affine with an inversion per addition. That is slow and it is the
    /// right trade here: this runs once per certificate, and a
    /// projective implementation would add the completeness questions
    /// this module has no vectors to check.
    fn add(&self, other: &Self) -> Self {
        let d = fe(&U576::ZERO) - fe(&PARAM_D_NEG);
        let one = fe(&U576::ONE);
        let t = d * self.x * other.x * self.y * other.y;
        let x3 = (self.x * other.y + other.x * self.y) * fe_inv(one + t);
        let y3 = (self.y * other.y - self.x * other.x) * fe_inv(one - t);
        Self { x: x3, y: y3 }
    }

    /// `[k]self`, double-and-add over the bits of `k`.
    ///
    /// Not constant-time. Verification handles only public values -- the
    /// key, the signature and the message -- so there is no secret for a
    /// timing channel to leak. Signing would need otherwise, which is
    /// one more reason this module does not sign.
    fn mul(&self, k: &U576) -> Self {
        let mut acc = Self::identity();
        let mut base = *self;
        for i in 0..U576::BITS {
            if bool::from(k.bit(i)) {
                acc = acc.add(&base);
            }
            base = base.add(&base);
        }
        acc
    }
}

/// Decode a 66-octet compressed point, RFC 8032 §5.2.3's shape with
/// `a = 1`.
///
/// The encoding is little-endian per DOC-ICP-01.01's "527-bit
/// codificação little-endian", with `x`'s sign in the top bit of the
/// last octet -- bit `b-1 = 527`.
///
/// Returns `None` for a non-canonical `y >= p`, for a `y` with no
/// corresponding `x` on the curve, and for the `x = 0` case with the
/// sign bit set, which RFC 8032 rejects because it encodes a point twice.
fn decompress(enc: &[u8; 66]) -> Option<Point> {
    let sign = (enc[65] >> 7) & 1;

    let mut le = *enc;
    le[65] &= 0x7f; // clear bit 527, the sign
    let mut be = le;
    be.reverse();
    let mut wide = [0u8; 72];
    wide[6..].copy_from_slice(&be);
    let y_int = U576::from_be_slice(&wide);
    if y_int >= U576::from_be_hex(PP) {
        return None; // non-canonical
    }

    let y = fe(&y_int);
    let one = fe(&U576::ONE);
    let d = fe(&U576::ZERO) - fe(&PARAM_D_NEG);
    // x² = (1 - y²) / (1 - d·y²)
    let num = one - y * y;
    let den = one - d * y * y;
    if den == fe(&U576::ZERO) {
        return None;
    }
    let x2 = num * fe_inv(den);

    // p ≡ 3 (mod 4), so a square root is x2^((p+1)/4).
    let exp = U576::from_be_hex(PP)
        .wrapping_add(&U576::ONE)
        .shr_vartime(2);
    let mut x = fe_pow(x2, &exp);
    if x * x != x2 {
        return None; // y does not correspond to a curve point
    }

    let x_canon = x.retrieve();
    let x_is_odd = bool::from(x_canon.is_odd());
    if x_canon == U576::ZERO && sign == 1 {
        return None;
    }
    if x_is_odd != (sign == 1) {
        x = fe(&U576::ZERO) - x;
    }
    Some(Point { x, y })
}

/// Verify an Ed521 signature, RFC 8032 §5.2.7 over E-521.
///
/// `signature` is `R ‖ S`, 66 octets each. `public_key` is the
/// compressed `A`.
///
/// # ⚠
///
/// See the module docs: this is validated by one real signature and no
/// test vectors, and its edge cases are untested. Do not use it outside
/// verifying the ICP-Brasil `AC Raiz v7` certificate.
#[must_use]
pub fn verify(public_key: &[u8; 66], signature: &[u8; 132], message: &[u8]) -> bool {
    use shake::digest::{ExtendableOutput, Update, XofReader};

    let mut r_enc = [0u8; 66];
    let mut s_enc = [0u8; 66];
    r_enc.copy_from_slice(&signature[..66]);
    s_enc.copy_from_slice(&signature[66..]);

    // Step 1: decode A and R, and reject S outside [0, L).
    let Some(a_point) = decompress(public_key) else {
        return false;
    };
    let Some(r_point) = decompress(&r_enc) else {
        return false;
    };
    let s_int = {
        let mut be = s_enc;
        be.reverse();
        let mut wide = [0u8; 72];
        wide[6..].copy_from_slice(&be);
        U576::from_be_slice(&wide)
    };
    if s_int >= PARAM_L {
        // RFC 8032 §5.2.7: S must be reduced. Accepting an unreduced S
        // would make signatures malleable.
        return false;
    }

    // Step 2: k = H(dom5(0, "") ‖ R ‖ A ‖ M) mod L, read little-endian.
    //
    // dom5 per DOC-ICP-01.01: "SigEd521" ‖ octet(phflag) ‖
    // octet(OLEN(context)) ‖ context. phflag is 0 for PureEdDSA and the
    // context is empty for X.509, so the prefix is the ten octets
    // "SigEd521".
    let mut xof = shake::Shake256::default();
    xof.update(b"SigEd521");
    xof.update(&[0u8]); // phflag = 0, PureEdDSA
    xof.update(&[0u8]); // OLEN(context) = 0
    xof.update(&r_enc);
    xof.update(public_key);
    xof.update(message);
    let mut h = [0u8; 132];
    xof.finalize_xof().read(&mut h);

    // 132 octets is wider than U576, so the reduction is done on the
    // value's own width before narrowing: fold the high octets in by
    // Horner's method modulo L.
    let k = reduce_mod_l(&h);

    // Step 3: [S]B = R + [k]A.
    let b_point = Point {
        x: fe(&PARAM_BX),
        y: fe(&PARAM_BY),
    };
    let lhs = b_point.mul(&s_int);
    let rhs = r_point.add(&a_point.mul(&k));
    lhs.eq(&rhs)
}

/// Reduce a 132-octet little-endian integer modulo `L`.
///
/// `H` is wider than `U576`, so it cannot simply be loaded. The octets
/// are folded in from the most significant end, `acc = acc·256 + byte`
/// with a reduction each step, which is Horner's method on base 256 and
/// avoids needing a 1056-bit integer type.
fn reduce_mod_l(h_le: &[u8; 132]) -> U576 {
    let mut acc = U576::ZERO;
    let two56 = U576::from_u64(256);
    for byte in h_le.iter().rev() {
        // acc = acc * 256 + byte, mod L
        let l = NonZero::new(PARAM_L).expect("L is non-zero");
        acc = acc.mul_mod(&two56, &l);
        let add = U576::from_u64(u64::from(*byte));
        acc = acc.add_mod(&add, &l);
    }
    acc
}

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

    /// The parameters are recomputed rather than trusted.
    ///
    /// `B` must satisfy `x² + y² = 1 + d·x²·y²`, and `[L]B` must be the
    /// identity. Both would fail on a mistranscribed constant, which is
    /// the failure mode this module is most exposed to given it has no
    /// vectors.
    #[test]
    fn the_base_point_is_on_the_curve_and_has_order_l() {
        let b = Point {
            x: fe(&PARAM_BX),
            y: fe(&PARAM_BY),
        };
        let one = fe(&U576::ONE);
        let d = fe(&U576::ZERO) - fe(&PARAM_D_NEG);
        let lhs = b.x * b.x + b.y * b.y;
        let rhs = one + d * b.x * b.x * b.y * b.y;
        assert_eq!(lhs, rhs, "B must satisfy the E-521 curve equation");

        let lb = b.mul(&PARAM_L);
        assert!(
            lb.eq(&Point::identity()),
            "[L]B must be the identity, i.e. B generates the order-L subgroup"
        );
    }
}