ssh-key 0.7.0

Pure Rust implementation of SSH key file format decoders/encoders as described in RFC4251/RFC4253 and OpenSSH key formats, as well as "sshsig" signatures and certificates (including certificate validation and certificate authority support), with further support for the `authorized_keys` and `known_hosts` file formats.
Documentation
//! Composite signature algorithms.
//!
//! Composite algorithms pair a post-quantum signature scheme with a classical one as specified in
//! [draft-ietf-sshm-composite-sigs]. A signature is only valid if *both* component signatures verify.
//!
//! Both components sign the same message representative `M'`, which binds a domain-separation prefix,
//! the algorithm label, and the composite context string to a SHA-512 digest of the message.
//!
//! ```text
//! M' = PREFIX || LABEL || u8(ctx.len()) || ctx || SHA512(msg)
//! ```
//!
//! `PREFIX` is the ASCII string `CompositeAlgorithmSignatures2025`. SSH requires an empty composite
//! context, so the length byte is zero. For `ssh-mldsa44-ed25519`, `LABEL` is the ASCII string
//! `COMPSIG-MLDSA44-Ed25519-SHA512`. ML-DSA-44 also uses `LABEL` as its FIPS 204 context when
//! signing `M'`. Ed25519 signs `M'` directly.
//!
//! Keys and signatures place the post-quantum component first. For `ssh-mldsa44-ed25519`, the
//! raw values inside the SSH `string` fields have the following layouts (sizes in bytes).
//!
//! ```text
//! public key  (1344) = mldsa_pk   (1312) || ed25519_pk   (32)
//! private key   (64) = mldsa_seed   (32) || ed25519_seed (32)
//! signature   (2484) = mldsa_sig  (2420) || ed25519_sig  (64)
//! ```
//!
//! For `ssh-mldsa87-p384`, ML-DSA-87 uses `COMPSIG-MLDSA87-ECDSA-P384-SHA512` as its label
//! and FIPS 204 context. ECDSA signs `M'` with P-384 and SHA-384. The uncompressed SEC1 point
//! `Q` has its own SSH string length prefix. The private scalar and both ECDSA signature
//! components use SSH `mpint` encoding.
//!
//! ```text
//! public key  = mldsa_pk   (2592) || string Q
//! private key = mldsa_seed   (32) || mpint d
//! signature   = mldsa_sig  (4627) || mpint r || mpint s
//! ```
//!
//! [draft-ietf-sshm-composite-sigs]: https://www.ietf.org/archive/id/draft-ietf-sshm-composite-sigs-01.html

#[cfg(not(any(feature = "ed25519", feature = "p384")))]
compile_error!("the `mldsa` feature requires `ed25519` or `p384`");

#[cfg(feature = "ed25519")]
mod mldsa44_ed25519;
#[cfg(feature = "p384")]
mod mldsa87_p384;
#[cfg(not(feature = "alloc"))]
mod signature_data;

#[cfg(feature = "ed25519")]
pub use mldsa44_ed25519::{
    MlDsa44Ed25519Keypair, MlDsa44Ed25519PrivateKey, MlDsa44Ed25519PublicKey,
};
#[cfg(feature = "p384")]
pub use mldsa87_p384::{MlDsa87P384Keypair, MlDsa87P384PrivateKey, MlDsa87P384PublicKey};
#[cfg(not(feature = "alloc"))]
pub(crate) use signature_data::SignatureData;

use crate::{Error, Result};
use encoding::Writer;
use ml_dsa::{EncodedVerifyingKey, ExpandedSigningKey, MlDsaParams, VerifyingKey};
use rand_core::TryCryptoRng;
use sha2::{Digest, Sha512};
use signature::{Signer, Verifier};

#[cfg(feature = "alloc")]
type PublicKeyBytes<P> = alloc::boxed::Box<EncodedVerifyingKey<P>>;
#[cfg(not(feature = "alloc"))]
type PublicKeyBytes<P> = EncodedVerifyingKey<P>;

fn derive_public_key<P: MlDsaParams>(seed: &ml_dsa::Seed) -> PublicKeyBytes<P> {
    let key = ml_dsa::SigningKey::<P>::from_seed(seed);
    #[cfg(feature = "alloc")]
    {
        key.as_ref().encode().into()
    }
    #[cfg(not(feature = "alloc"))]
    {
        signature::Keypair::verifying_key(&key).encode()
    }
}

const PREFIX: &[u8] = b"CompositeAlgorithmSignatures2025";
const MLDSA87_P384_LABEL: &[u8] = b"COMPSIG-MLDSA87-ECDSA-P384-SHA512";
// P-384 has the longest label. The context has a one-byte length, and SHA-512 produces 64 bytes.
const MAX_MESSAGE_LEN: usize = PREFIX.len() + MLDSA87_P384_LABEL.len() + 1 + 255 + 64;

/// The message representative shared by both components, and the label ML-DSA also uses as
/// its FIPS 204 context. Each SSH algorithm defines its own key and signature encodings.
struct CompositeMessage<'a> {
    label: &'a [u8],
    bytes: [u8; MAX_MESSAGE_LEN],
    len: usize,
}

impl<'a> CompositeMessage<'a> {
    /// M' = prefix || label || len(ctx) || ctx || SHA512(message).
    fn new(label: &'a [u8], message: &[u8], ctx: &[u8]) -> Result<Self> {
        let ctx_len = u8::try_from(ctx.len()).map_err(|_| Error::Crypto)?;
        let mut bytes = [0u8; MAX_MESSAGE_LEN];
        let mut out = bytes.as_mut_slice();
        out.write(PREFIX)?;
        out.write(label)?;
        out.write(&[ctx_len])?;
        out.write(ctx)?;
        out.write(&Sha512::digest(message))?;
        let len = MAX_MESSAGE_LEN - out.len();
        Ok(Self { label, bytes, len })
    }

    fn as_bytes(&self) -> &[u8] {
        &self.bytes[..self.len]
    }

    /// Sign with deterministic ML-DSA and the classical signer.
    fn sign<P: MlDsaParams, S>(
        &self,
        pq: &ExpandedSigningKey<P>,
        classical: &impl Signer<S>,
    ) -> Result<(ml_dsa::Signature<P>, S)> {
        let pq_sig = pq
            .sign_deterministic(self.as_bytes(), self.label)
            .map_err(|_| Error::Crypto)?;
        let classical_sig = classical
            .try_sign(self.as_bytes())
            .map_err(|_| Error::Crypto)?;
        Ok((pq_sig, classical_sig))
    }

    /// Hedge the ML-DSA signature with caller-provided randomness.
    fn sign_with_rng<P: MlDsaParams, S, R: TryCryptoRng + ?Sized>(
        &self,
        pq: &ExpandedSigningKey<P>,
        classical: &impl Signer<S>,
        rng: &mut R,
    ) -> Result<(ml_dsa::Signature<P>, S)> {
        let pq_sig = pq
            .sign_randomized(self.as_bytes(), self.label, rng)
            .map_err(|_| Error::Crypto)?;
        let classical_sig = classical
            .try_sign(self.as_bytes())
            .map_err(|_| Error::Crypto)?;
        Ok((pq_sig, classical_sig))
    }

    /// Require both components to verify over the same representative.
    fn verify<P: MlDsaParams, S, V: Verifier<S>>(
        &self,
        pq: &VerifyingKey<P>,
        pq_sig: &ml_dsa::Signature<P>,
        classical_key: impl FnOnce() -> Result<V>,
        classical_sig: &S,
    ) -> Result<()> {
        if !pq.verify_with_context(self.as_bytes(), self.label, pq_sig) {
            return Err(Error::Signature);
        }
        classical_key()?
            .verify(self.as_bytes(), classical_sig)
            .map_err(|_| Error::Signature)
    }
}