Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions ssh-key/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ dsa = { version = "0.7", optional = true, default-features = false, features = [
ed25519-dalek = { version = "3", optional = true, default-features = false }
hex = { version = "0.4", optional = true, default-features = false, features = ["alloc"] }
hmac = { version = "0.13", optional = true }
ml-dsa = { version = "0.1", optional = true, default-features = false, features = ["alloc", "zeroize"] }
ml-dsa = { version = "0.1", optional = true, default-features = false, features = ["zeroize"] }
p256 = { version = "0.14", optional = true, default-features = false, features = ["ecdsa"] }
p384 = { version = "0.14", optional = true, default-features = false, features = ["ecdsa"] }
p521 = { version = "0.14", optional = true, default-features = false, features = ["ecdsa"] }
Expand All @@ -49,7 +49,7 @@ getrandom = { version = "0.4", features = ["sys_rng"] }

[features]
default = ["ecdsa", "rand_core", "sha2", "std"]
alloc = ["encoding/alloc", "signature/alloc", "zeroize/alloc", ]
alloc = ["encoding/alloc", "ml-dsa?/alloc", "signature/alloc", "zeroize/alloc"]
std = ["alloc"]

crypto = ["ed25519", "p256", "p384", "p521", "rsa"] # NOTE: `dsa` is obsolete/weak
Expand All @@ -75,7 +75,7 @@ sha2 = ["dep:sha2"]
tdes = ["cipher/tdes", "encryption"]

# Composite signatures from draft-ietf-sshm-composite-sigs-01
unstable-mldsa = ["dep:ml-dsa", "ml-dsa/rand_core", "alloc", "rand_core", "sha2", "signature/rand_core"]
unstable-mldsa = ["dep:ml-dsa", "ml-dsa/rand_core", "rand_core", "sha2", "signature/rand_core"]
unstable-mldsa-ed25519 = ["unstable-mldsa", "ed25519"]
unstable-mldsa-p384 = ["unstable-mldsa", "p384"]

Expand Down
22 changes: 14 additions & 8 deletions ssh-key/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,18 +71,18 @@ methods with a type that implements `AssociatedHashAlg`.

### Supported Signature Algorithms

| Name | Decode | Encode | Cert | Keygen | Sign | Verify | Feature | `no_std` |
|--------------------------------------|--------|--------|------|--------|------|--------|-----------|----------|
| `ecdsa‑sha2‑nistp256` | ✅ | ✅ | ✅ | ✅️ | ✅️ | ✅️ | `p256` | heapless |
| `ecdsa‑sha2‑nistp384` | ✅ | ✅ | ✅ | ✅️ | ✅️ | ✅️ | `p384` | heapless |
| `ecdsa‑sha2‑nistp521` | ✅ | ✅ | ✅ | ✅️️ | ✅️ ️ | ✅️️ | `p521` | heapless |
| Name | Decode | Encode | Cert | Keygen | Sign | Verify | Feature | Alloc? |
|--------------------------------------|--------|--------|------|--------|------|--------|--------------------------|----------|
| `ecdsa‑sha2‑nistp256` | ✅ | ✅ | ✅ | ✅️ | ✅️ | ✅️ | `p256` | `no_alloc` |
| `ecdsa‑sha2‑nistp384` | ✅ | ✅ | ✅ | ✅️ | ✅️ | ✅️ | `p384` | `no_alloc` |
| `ecdsa‑sha2‑nistp521` | ✅ | ✅ | ✅ | ✅️️ | ✅️ ️ | ✅️️ | `p521` | `no_alloc` |
| `ssh‑dsa` | ✅ | ✅ | ✅ | ✅ | ✅️ | ✅️ | `dsa` | `alloc` ️ |
| `ssh‑ed25519` | ✅ | ✅ | ✅ | ✅️ | ✅️ | ✅ | `ed25519` | heapless |
| `ssh‑ed25519` | ✅ | ✅ | ✅ | ✅️ | ✅️ | ✅ | `ed25519` | `no_alloc` |
| `ssh‑rsa` | ✅ | ✅ | ✅ | ✅️ | ✅️ | ✅ | `rsa` | `alloc` |
| `sk‑ecdsa‑sha2‑nistp256@openssh.com` | ✅ | ✅ | ✅ | ⛔ | ⛔️ | ✅️ | ⛔ | `alloc` |
| `sk‑ssh‑ed25519@openssh.com` | ✅ | ✅ | ✅ | ⛔ | ⛔️ | ✅️️ | `ed25519` | `alloc` |
| `ssh‑mldsa44‑ed25519` | ✅ | ✅ | ✅ | ✅️ | ✅️ | ✅️ | `unstable-mldsa-ed25519` | `alloc` |
| `ssh‑mldsa87‑p384` | ✅ | ✅ | ✅ | ✅️ | ✅️ | ✅️ | `unstable-mldsa-p384` | `alloc` |
| `ssh‑mldsa44‑ed25519` | ✅ | ✅ | ✅ | ✅️ | ✅️ | ✅️ | `unstable-mldsa-ed25519` | `no_alloc` |
| `ssh‑mldsa87‑p384` | ✅ | ✅ | ✅ | ✅️ | ✅️ | ✅️ | `unstable-mldsa-p384` | `no_alloc` |

By default *no SSH signature algorithms are enabled* and you will get an
`Error::AlgorithmUnsupported` error if you try to use them.
Expand All @@ -99,6 +99,12 @@ at least one of `ed25519` or `p384`. The `unstable-mldsa-ed25519` and
`unstable-mldsa-p384` features enable the corresponding pair. For example,
`crypto` together with `unstable-mldsa` enables both composites.

With default features disabled, both composites support key generation, OpenSSH
key encoding and decoding, and signing and verification with `Signature`.
Heapless builds store the public key and signature bytes inline. ML-DSA also
uses stack space for its working buffers. Certificates and `SshSig` require
the `alloc` feature.

## License

Licensed under either of:
Expand Down
2 changes: 1 addition & 1 deletion ssh-key/src/algorithm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -432,7 +432,7 @@ impl EcdsaCurve {
}

/// Get the number of bytes needed to encode a field element for this curve.
#[cfg(feature = "alloc")]
#[cfg(any(feature = "alloc", feature = "unstable-mldsa"))]
pub(crate) const fn field_size(self) -> usize {
match self {
EcdsaCurve::NistP256 => 32,
Expand Down
72 changes: 53 additions & 19 deletions ssh-key/src/composite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,42 +44,72 @@ compile_error!("the `unstable-mldsa` feature requires `ed25519` or `p384`");
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 alloc::vec::Vec;
use ml_dsa::{ExpandedSigningKey, MlDsaParams, VerifyingKey};
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: Vec<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> {
const PREFIX: &[u8] = b"CompositeAlgorithmSignatures2025";
let ctx_len = u8::try_from(ctx.len()).map_err(|_| Error::Crypto)?;
let digest = Sha512::digest(message);
let mut bytes =
Vec::with_capacity(PREFIX.len() + label.len() + 1 + ctx.len() + digest.len());
bytes.extend_from_slice(PREFIX);
bytes.extend_from_slice(label);
bytes.push(ctx_len);
bytes.extend_from_slice(ctx);
bytes.extend_from_slice(&digest);
Ok(Self { label, bytes })
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.
Expand All @@ -89,9 +119,11 @@ impl<'a> CompositeMessage<'a> {
classical: &impl Signer<S>,
) -> Result<(ml_dsa::Signature<P>, S)> {
let pq_sig = pq
.sign_deterministic(&self.bytes, self.label)
.sign_deterministic(self.as_bytes(), self.label)
.map_err(|_| Error::Crypto)?;
let classical_sig = classical
.try_sign(self.as_bytes())
.map_err(|_| Error::Crypto)?;
let classical_sig = classical.try_sign(&self.bytes).map_err(|_| Error::Crypto)?;
Ok((pq_sig, classical_sig))
}

Expand All @@ -103,9 +135,11 @@ impl<'a> CompositeMessage<'a> {
rng: &mut R,
) -> Result<(ml_dsa::Signature<P>, S)> {
let pq_sig = pq
.sign_randomized(&self.bytes, self.label, rng)
.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)?;
let classical_sig = classical.try_sign(&self.bytes).map_err(|_| Error::Crypto)?;
Ok((pq_sig, classical_sig))
}

Expand All @@ -117,11 +151,11 @@ impl<'a> CompositeMessage<'a> {
classical_key: impl FnOnce() -> Result<V>,
classical_sig: &S,
) -> Result<()> {
if !pq.verify_with_context(&self.bytes, self.label, pq_sig) {
if !pq.verify_with_context(self.as_bytes(), self.label, pq_sig) {
return Err(Error::Signature);
}
classical_key()?
.verify(&self.bytes, classical_sig)
.verify(self.as_bytes(), classical_sig)
.map_err(|_| Error::Signature)
}
}
66 changes: 35 additions & 31 deletions ssh-key/src/composite/mldsa44_ed25519.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ mod keys;
pub use keys::{MlDsa44Ed25519Keypair, MlDsa44Ed25519PrivateKey, MlDsa44Ed25519PublicKey};

use super::CompositeMessage;
use crate::{Error, Result, Signature};
use alloc::vec::Vec;
use crate::{Algorithm, Error, Result, Signature};
use encoding::Writer;
use ml_dsa::{EncodedSignature, MlDsa44};
use rand_core::TryCryptoRng;
use signature::{RandomizedSigner, Signer, Verifier};
Expand All @@ -16,28 +16,29 @@ const LABEL: &[u8] = b"COMPSIG-MLDSA44-Ed25519-SHA512";
/// SSH encodes this pair as the raw ML-DSA signature followed by the raw Ed25519 signature.
fn encode_signature(
(pq, ed25519): (ml_dsa::Signature<MlDsa44>, ed25519_dalek::Signature),
) -> Vec<u8> {
let mut bytes = Vec::with_capacity(MlDsa44Ed25519PublicKey::SIGNATURE_SIZE);
bytes.extend_from_slice(&pq.encode());
bytes.extend_from_slice(&ed25519.to_bytes());
bytes
) -> Result<Signature> {
Signature::new_with(
Algorithm::MlDsa44Ed25519,
MlDsa44Ed25519PublicKey::SIGNATURE_SIZE,
|out| {
out.write(&pq.encode())?;
out.write(&ed25519.to_bytes())
},
)
}

impl MlDsa44Ed25519Keypair {
fn sign_with_ctx(&self, msg: &[u8], ctx: &[u8]) -> Result<Vec<u8>> {
fn sign_with_ctx(&self, msg: &[u8], ctx: &[u8]) -> Result<Signature> {
let message = CompositeMessage::new(LABEL, msg, ctx)?;
let pq = ml_dsa::SigningKey::<MlDsa44>::from_seed(&self.private.mldsa);
let classical = ed25519_dalek::SigningKey::from(self.private.ed25519());
Ok(encode_signature(
message.sign(pq.expanded_key(), &classical)?,
))
encode_signature(message.sign(pq.expanded_key(), &classical)?)
}
}

impl Signer<Signature> for MlDsa44Ed25519Keypair {
fn try_sign(&self, msg: &[u8]) -> signature::Result<Signature> {
let bytes = self.sign_with_ctx(msg, &[])?;
Ok(Signature::new(self.algorithm(), bytes)?)
Ok(self.sign_with_ctx(msg, &[])?)
}
}

Expand All @@ -51,10 +52,7 @@ impl RandomizedSigner<Signature> for MlDsa44Ed25519Keypair {
let pq = ml_dsa::SigningKey::<MlDsa44>::from_seed(&self.private.mldsa);
let classical = ed25519_dalek::SigningKey::from(self.private.ed25519());
let signatures = message.sign_with_rng(pq.expanded_key(), &classical, rng)?;
Ok(Signature::new(
self.algorithm(),
encode_signature(signatures),
)?)
Ok(encode_signature(signatures)?)
}
}

Expand Down Expand Up @@ -125,8 +123,14 @@ mod tests {
/// concatenation order and the seed split.
#[test]
fn kat_key_expansion() {
use encoding::Encode;

assert_eq!(kat_keypair().public, kat_public_key());
assert_eq!(kat_public_key().to_bytes(), KAT_PK);
let mut encoded = [0; 4 + KAT_PK.len()];
kat_public_key()
.encode(&mut encoded.as_mut_slice())
.unwrap();
assert_eq!(&encoded[4..], KAT_PK);
}

#[test]
Expand Down Expand Up @@ -157,7 +161,7 @@ mod tests {
#[test]
fn kat_both_signature_components_must_verify() {
let public = kat_public_key();
let mut mixed = KAT_S.to_vec();
let mut mixed: [u8; KAT_S.len()] = KAT_S.try_into().unwrap();
let split = mixed.len() - ed25519_dalek::SIGNATURE_LENGTH;
mixed[split..].copy_from_slice(&KAT_S_WITH_CONTEXT[split..]);

Expand All @@ -173,7 +177,7 @@ mod tests {
// Digest of the deterministic signature produced by the original composite signer.
let signature = kat_keypair().sign_with_ctx(KAT_M, &[]).unwrap();
assert_eq!(
Sha256::digest(&signature).as_slice(),
Sha256::digest(signature.as_bytes()).as_slice(),
hex_literal::hex!("911a3b7d12da493561f37234b0f21c2b3edf5d03c01d858a4dbb31ad85e60211")
);
}
Expand All @@ -189,7 +193,7 @@ mod tests {

keypair
.public
.verify_with_ctx(KAT_M, ctx, &signature)
.verify_with_ctx(KAT_M, ctx, signature.as_bytes())
.expect("own signature should verify");
}
}
Expand All @@ -214,7 +218,7 @@ mod tests {

#[test]
fn tampered_message_is_rejected() {
let mut msg = KAT_M.to_vec();
let mut msg: [u8; KAT_M.len()] = KAT_M.try_into().unwrap();
msg[0] ^= 1;
assert!(kat_public_key().verify_with_ctx(&msg, &[], KAT_S).is_err());
}
Expand Down Expand Up @@ -242,22 +246,22 @@ mod tests {
fn wrong_encoded_length_is_rejected() {
use encoding::{Decode, Encode, Reader as _};

let mut encoded = Vec::new();
KAT_PK.encode(&mut encoded).unwrap();
let mut encoded = [0; 4 + KAT_PK.len() + 1];
KAT_PK.encode(&mut encoded.as_mut_slice()).unwrap();

assert!(
MlDsa44Ed25519PublicKey::decode(&mut encoded.as_slice().into_decoder().unwrap())
.is_ok()
MlDsa44Ed25519PublicKey::decode(
&mut encoded[..4 + KAT_PK.len()].into_decoder().unwrap()
)
.is_ok()
);

// Append a trailing byte and grow the length prefix to cover it.
let mut over_long = encoded.clone();
over_long.push(0);
// Grow the length prefix to cover the trailing byte.
let len = u32::try_from(KAT_PK.len() + 1).unwrap();
over_long[..4].copy_from_slice(&len.to_be_bytes());
encoded[..4].copy_from_slice(&len.to_be_bytes());

assert!(
MlDsa44Ed25519PublicKey::decode(&mut over_long.as_slice().into_decoder().unwrap())
MlDsa44Ed25519PublicKey::decode(&mut encoded.as_slice().into_decoder().unwrap())
.is_err()
);
}
Expand Down
Loading