garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /crypto/src/rsa.rs

raw

//! RSA signatures checked (RFC 8017): PKCS#1 v1.5, which certificates are
//! mostly signed with, and PSS, which TLS 1.3 servers sign their handshake
//! with. Checking only: Pinnacle signs nothing with RSA. Keys of 2048 to
//! 4096 bits.

use crate::bignum::{Modulus, Num};
use crate::sha2::{Sha256, Sha384, Sha512};

/// The hash a signature covers.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Hash {
    Sha256,
    Sha384,
    Sha512,
}

impl Hash {
    pub fn size(self) -> usize {
        match self {
            Hash::Sha256 => 32,
            Hash::Sha384 => 48,
            Hash::Sha512 => 64,
        }
    }

    /// The digest of the parts, in the first [`size`](Self::size) bytes.
    pub fn digest(self, parts: &[&[u8]]) -> [u8; 64] {
        let mut out = [0u8; 64];
        match self {
            Hash::Sha256 => {
                let mut h = Sha256::new();
                parts.iter().for_each(|p| h.update(p));
                out[..32].copy_from_slice(&h.finish());
            }
            Hash::Sha384 => {
                let mut h = Sha384::new();
                parts.iter().for_each(|p| h.update(p));
                out[..48].copy_from_slice(&h.finish());
            }
            Hash::Sha512 => {
                let mut h = Sha512::new();
                parts.iter().for_each(|p| h.update(p));
                out = h.finish();
            }
        }
        out
    }

    /// The DER DigestInfo before the digest, as PKCS#1 v1.5 wraps it.
    fn digest_info(self) -> &'static [u8] {
        match self {
            Hash::Sha256 => &[
                0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01,
                0x05, 0x00, 0x04, 0x20,
            ],
            Hash::Sha384 => &[
                0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02,
                0x05, 0x00, 0x04, 0x30,
            ],
            Hash::Sha512 => &[
                0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03,
                0x05, 0x00, 0x04, 0x40,
            ],
        }
    }
}

/// The longest key: 4096 bits.
const MAX: usize = 512;

/// An RSA public key.
#[derive(Clone)]
pub struct PublicKey {
    modulus: Modulus,
    exponent: Num,
    /// The modulus's length in bytes, and in bits.
    size: usize,
    bits: usize,
}

impl PublicKey {
    /// From the modulus and exponent, big-endian. `None` for a key under
    /// 2048 bits or over 4096, or an even modulus.
    pub fn new(n: &[u8], e: &[u8]) -> Option<PublicKey> {
        Self::with_minimum(n, e, 2048)
    }

    /// As [`new`](Self::new), with keys from `min_bits` up: fewer than 2048
    /// only to replay old traces in tests.
    pub fn with_minimum(n: &[u8], e: &[u8], min_bits: usize) -> Option<PublicKey> {
        let n = Num::from_be_bytes(n)?;
        let bits = n.bits();
        if !(min_bits..=MAX * 8).contains(&bits) {
            return None;
        }
        let exponent = Num::from_be_bytes(e)?;
        if exponent.bits() < 2 || exponent.bits() > 64 {
            return None;
        }
        Some(PublicKey {
            modulus: Modulus::new(n)?,
            exponent,
            size: bits.div_ceil(8),
            bits,
        })
    }

    /// signature^e mod n, as `size` bytes: the encoded message.
    fn open(&self, signature: &[u8]) -> Option<[u8; MAX]> {
        if signature.len() != self.size {
            return None;
        }
        let s = Num::from_be_bytes(signature)?;
        if s >= self.modulus.n {
            return None;
        }
        let m = &self.modulus;
        let opened = m.from_mont(&m.pow(&m.to_mont(&s), &self.exponent));
        let mut out = [0u8; MAX];
        opened.to_be_bytes(&mut out[..self.size]);
        Some(out)
    }

    /// Whether `signature` is this key's PKCS#1 v1.5 signature of `message`.
    pub fn verify_pkcs1(&self, hash: Hash, message: &[u8], signature: &[u8]) -> bool {
        let Some(em) = self.open(signature) else {
            return false;
        };
        let em = &em[..self.size];
        let info = hash.digest_info();
        let digest = hash.digest(&[message]);
        let t_len = info.len() + hash.size();
        if self.size < t_len + 11 {
            return false;
        }
        let pad = self.size - t_len - 3;
        em[0] == 0
            && em[1] == 1
            && em[2..2 + pad].iter().all(|&b| b == 0xff)
            && em[2 + pad] == 0
            && &em[3 + pad..3 + pad + info.len()] == info
            && em[3 + pad + info.len()..] == digest[..hash.size()]
    }

    /// Whether `signature` is this key's PSS signature of `message`, with
    /// MGF1 of the same hash and a salt as long as the hash (as TLS 1.3
    /// has it).
    pub fn verify_pss(&self, hash: Hash, message: &[u8], signature: &[u8]) -> bool {
        let Some(opened) = self.open(signature) else {
            return false;
        };
        let h_len = hash.size();
        let s_len = h_len;
        let em_bits = self.bits - 1;
        let em_len = em_bits.div_ceil(8);
        // The encoded message is the opened one's last em_len bytes.
        let em = &opened[self.size - em_len..self.size];
        if self.size > em_len && opened[0] != 0 {
            return false;
        }
        if em_len < h_len + s_len + 2 || em[em_len - 1] != 0xbc {
            return false;
        }
        let db_len = em_len - h_len - 1;
        let (masked, h) = (&em[..db_len], &em[db_len..em_len - 1]);
        let top = 8 * em_len - em_bits;
        if top > 0 && masked[0] >> (8 - top) != 0 {
            return false;
        }
        let mut db = [0u8; MAX];
        let db = &mut db[..db_len];
        db.copy_from_slice(masked);
        // MGF1: the hash of `h` and a counter, block after block.
        for (counter, chunk) in db.chunks_mut(h_len).enumerate() {
            let mask = hash.digest(&[h, &(counter as u32).to_be_bytes()]);
            for (d, m) in chunk.iter_mut().zip(mask) {
                *d ^= m;
            }
        }
        db[0] &= 0xff >> top;
        let ps = db_len - s_len - 1;
        if db[..ps].iter().any(|&b| b != 0) || db[ps] != 1 {
            return false;
        }
        let salt = &db[ps + 1..];
        let digest = hash.digest(&[message]);
        let expected = hash.digest(&[&[0u8; 8], &digest[..h_len], salt]);
        crate::equal(&expected[..h_len], h)
    }
}