Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

Sign: decide Windows store keys in code every platform builds (#690)

jcl-bitd5b5687f7903
diff --git a/crates/sign/src/keys.rs b/crates/sign/src/keys.rs
index c9ea6cb21..a32190fb9 100644
--- a/crates/sign/src/keys.rs
+++ b/crates/sign/src/keys.rs
@@ -302,6 +302,15 @@ pub enum PublicKey {
},
}
+/// The private key a platform key store (the Windows certificate store, through CNG) must
+/// hold to sign for a certificate, see [`PublicKey::store_signing_key`].
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum StoreKey {
+ Rsa,
+ /// ECDSA with a key of this many bits.
+ Ecdsa(u32),
+}
+
impl PublicKey {
/// The `subjectPublicKey` BIT STRING contents — what OCSP's `issuerKeyHash` covers
/// (RFC 6960 §4.1.1). RSA keys are re-encoded; EC points are the stored bytes.
@@ -383,6 +392,48 @@ impl PublicKey {
}
}
+ // The two decisions below are what `windows.rs` asks of a key. They live here, with every
+ // variant named and no `_` arm, so that a new variant fails to compile on every platform
+ // rather than only in the Windows-only module (#386 added six and broke the Windows build).
+
+ /// The key a platform key store must hold to sign for this public key, or `None` when
+ /// PdfCraft doesn't sign with this kind of key (it only verifies P-521, brainpool and
+ /// Ed25519 signatures), so the store's identity is skipped.
+ pub fn store_signing_key(&self) -> Option<StoreKey> {
+ match self {
+ PublicKey::Rsa { .. } => Some(StoreKey::Rsa),
+ PublicKey::P256(_) => Some(StoreKey::Ecdsa(256)),
+ PublicKey::P384(_) => Some(StoreKey::Ecdsa(384)),
+ PublicKey::P521(_)
+ | PublicKey::BrainpoolP256(_)
+ | PublicKey::BrainpoolP384(_)
+ | PublicKey::BrainpoolP512(_)
+ | PublicKey::Ed25519(_)
+ | PublicKey::Unsupported { .. } => None,
+ }
+ }
+
+ /// A key store's signature as a CMS signature carries it: RSA unchanged, ECDSA's fixed-size
+ /// `r ‖ s` (what CNG returns) as a DER `ECDSA-Sig-Value`. Keys [`Self::store_signing_key`]
+ /// rejects give [`SignError::Unsupported`].
+ pub fn store_signature_der(&self, raw: &[u8]) -> Result<Vec<u8>, SignError> {
+ match self {
+ PublicKey::Rsa { .. } => Ok(raw.to_vec()),
+ PublicKey::P256(_) => p256::ecdsa::Signature::from_slice(raw)
+ .map(|s| s.to_der().as_bytes().to_vec())
+ .map_err(|e| SignError::Crypto(format!("the key store returned an invalid P-256 signature: {e}"))),
+ PublicKey::P384(_) => p384::ecdsa::Signature::from_slice(raw)
+ .map(|s| s.to_der().as_bytes().to_vec())
+ .map_err(|e| SignError::Crypto(format!("the key store returned an invalid P-384 signature: {e}"))),
+ PublicKey::P521(_)
+ | PublicKey::BrainpoolP256(_)
+ | PublicKey::BrainpoolP384(_)
+ | PublicKey::BrainpoolP512(_)
+ | PublicKey::Ed25519(_)
+ | PublicKey::Unsupported { .. } => Err(SignError::Unsupported(format!("signing with {} keys", self.describe()))),
+ }
+ }
+
/// Check `sig` over a message whose digest (with `alg`) is `digest`. Encodings are read
/// leniently (see [`crate::rsa_pad`], [`ecdsa_rs`]); the cryptographic check never is.
/// `Err(Unsupported)` means "can't tell", as opposed to `Ok(false)`: "doesn't match".
diff --git a/crates/sign/src/windows.rs b/crates/sign/src/windows.rs
index 0e49823e6..1ea1b7f44 100644
--- a/crates/sign/src/windows.rs
+++ b/crates/sign/src/windows.rs
@@ -6,7 +6,7 @@ use std::sync::Arc;
use rustls_cng::key::{AlgorithmGroup, NCryptKey, SignaturePadding};
use rustls_cng::store::{CertStore, CertStoreType};
-use crate::keys::{DigestAlg, ExternalKey, PrivateKey, PublicKey};
+use crate::keys::{DigestAlg, ExternalKey, PrivateKey, PublicKey, StoreKey};
use crate::{Certificate, DigitalId, SignError};
struct WindowsKey {
@@ -23,17 +23,7 @@ impl ExternalKey for WindowsKey {
.key
.sign(&digest, padding)
.map_err(|e| SignError::Crypto(format!("the Windows certificate store didn't sign (key use may have been cancelled): {e}")))?;
- match &self.public {
- PublicKey::Rsa { .. } => Ok(raw),
- PublicKey::P256(_) => p256::ecdsa::Signature::from_slice(&raw)
- .map(|s| s.to_der().as_bytes().to_vec())
- .map_err(|e| SignError::Crypto(format!("CNG returned an invalid P-256 signature: {e}"))),
- PublicKey::P384(_) => p384::ecdsa::Signature::from_slice(&raw)
- .map(|s| s.to_der().as_bytes().to_vec())
- .map_err(|e| SignError::Crypto(format!("CNG returned an invalid P-384 signature: {e}"))),
- // `identities` lists only RSA, P-256 and P-384 store keys; anything else can't sign here.
- _ => Err(SignError::Unsupported("signing with this key type through the Windows certificate store".into())),
- }
+ self.public.store_signature_der(&raw)
}
}
@@ -65,11 +55,13 @@ pub fn identities() -> Result<Vec<DigitalId>, SignError> {
let Ok(certificate) = Certificate::parse(context.as_der()) else { continue };
// Enumeration must not open permission or PIN dialogs. Signing may prompt later.
let Ok(mut key) = context.acquire_key(true) else { continue };
- let supported = match &certificate.public_key {
- PublicKey::Rsa { .. } => key.algorithm_group().is_ok_and(|a| a == AlgorithmGroup::Rsa),
- PublicKey::P256(_) => key.algorithm_group().is_ok_and(|a| a == AlgorithmGroup::Ecdsa) && key.bits().is_ok_and(|bits| bits == 256),
- PublicKey::P384(_) => key.algorithm_group().is_ok_and(|a| a == AlgorithmGroup::Ecdsa) && key.bits().is_ok_and(|bits| bits == 384),
- _ => false,
+ // P-521, brainpool and Ed25519 certificates parse (to verify with) but aren't signed with.
+ let supported = match certificate.public_key.store_signing_key() {
+ Some(StoreKey::Rsa) => key.algorithm_group().is_ok_and(|a| a == AlgorithmGroup::Rsa),
+ Some(StoreKey::Ecdsa(want)) => {
+ key.algorithm_group().is_ok_and(|a| a == AlgorithmGroup::Ecdsa) && key.bits().is_ok_and(|bits| bits == want)
+ }
+ None => false,
};
if !supported {
continue;
diff --git a/crates/sign/tests/store_keys.rs b/crates/sign/tests/store_keys.rs
new file mode 100644
index 000000000..e93092735
--- /dev/null
+++ b/crates/sign/tests/store_keys.rs
@@ -0,0 +1,89 @@
+//! What the Windows certificate store (`src/windows.rs`, built only on Windows) may sign with,
+//! checked on every platform: which certificate keys it lists, and how a CNG signature becomes
+//! the one a CMS signature carries.
+
+use p256::ecdsa::signature::hazmat::PrehashSigner;
+use pdfcraft_sign::keys::{DigestAlg, Scheme, StoreKey};
+use pdfcraft_sign::{PublicKey, SignError};
+
+/// One key of every kind, with what the store must hold to sign for it.
+fn every_kind() -> Vec<(PublicKey, Option<StoreKey>)> {
+ let point = vec![4u8; 65];
+ let keys = vec![
+ (PublicKey::Rsa { n: vec![0xc5; 256], e: vec![1, 0, 1] }, Some(StoreKey::Rsa)),
+ (PublicKey::P256(point.clone()), Some(StoreKey::Ecdsa(256))),
+ (PublicKey::P384(point.clone()), Some(StoreKey::Ecdsa(384))),
+ (PublicKey::P521(point.clone()), None),
+ (PublicKey::BrainpoolP256(point.clone()), None),
+ (PublicKey::BrainpoolP384(point.clone()), None),
+ (PublicKey::BrainpoolP512(point.clone()), None),
+ (PublicKey::Ed25519(vec![7; 32]), None),
+ (PublicKey::Unsupported { what: "elliptic curve 1.3.132.0.10".into(), spki: Vec::new() }, None),
+ ];
+ // Every variant is named, with no `_` arm: a new one stops this test compiling until it is
+ // listed above with the answer the store should give.
+ for (key, _) in &keys {
+ match key {
+ PublicKey::Rsa { .. }
+ | PublicKey::P256(_)
+ | PublicKey::P384(_)
+ | PublicKey::P521(_)
+ | PublicKey::BrainpoolP256(_)
+ | PublicKey::BrainpoolP384(_)
+ | PublicKey::BrainpoolP512(_)
+ | PublicKey::Ed25519(_)
+ | PublicKey::Unsupported { .. } => {}
+ }
+ }
+ keys
+}
+
+#[test]
+fn the_store_signs_only_with_rsa_p256_and_p384() {
+ for (key, want) in every_kind() {
+ assert_eq!(key.store_signing_key(), want, "{}", key.describe());
+ if want.is_none() {
+ // Skipped when listing, and refused (not a panic) if one ever reached signing.
+ let refused = key.store_signature_der(&[0; 64]);
+ assert!(matches!(refused, Err(SignError::Unsupported(_))), "{}: {refused:?}", key.describe());
+ }
+ }
+}
+
+#[test]
+fn cng_signatures_become_cms_signatures_that_verify() {
+ let msg = b"hello";
+
+ let k = p256::ecdsa::SigningKey::from_slice(&[0x11; 32]).unwrap();
+ let public = PublicKey::P256(k.verifying_key().to_sec1_point(false).as_bytes().to_vec());
+ let digest = DigestAlg::Sha256.digest(&[msg]);
+ let s: p256::ecdsa::Signature = k.sign_prehash(&digest).unwrap();
+ // CNG returns r ‖ s, 32 bytes each for P-256.
+ let der = public.store_signature_der(&s.to_bytes()).unwrap();
+ assert_eq!(der.first(), Some(&0x30), "a DER SEQUENCE");
+ assert!(public.verify(Scheme::Ecdsa, DigestAlg::Sha256, &digest, &der).unwrap());
+
+ let k = p384::ecdsa::SigningKey::from_slice(&[0x22; 48]).unwrap();
+ let public = PublicKey::P384(k.verifying_key().to_sec1_point(false).as_bytes().to_vec());
+ let digest = DigestAlg::Sha384.digest(&[msg]);
+ let s: p384::ecdsa::Signature = k.sign_prehash(&digest).unwrap();
+ let der = public.store_signature_der(&s.to_bytes()).unwrap();
+ assert!(public.verify(Scheme::Ecdsa, DigestAlg::Sha384, &digest, &der).unwrap());
+
+ // RSA PKCS #1 v1.5 signatures are already what CMS carries.
+ let rsa = PublicKey::Rsa { n: vec![0xc5; 256], e: vec![1, 0, 1] };
+ assert_eq!(rsa.store_signature_der(&[9; 256]).unwrap(), vec![9; 256]);
+}
+
+#[test]
+fn a_malformed_cng_signature_is_an_error() {
+ // Wrong lengths, and right lengths whose r and s are zero or not below the group order.
+ let p256: [&[u8]; 5] = [&[], &[1; 63], &[1; 65], &[0; 64], &[0xff; 64]];
+ let p384: [&[u8]; 5] = [&[], &[1; 95], &[1; 97], &[0; 96], &[0xff; 96]];
+ for (key, bad) in [(PublicKey::P256(Vec::new()), p256), (PublicKey::P384(Vec::new()), p384)] {
+ for raw in bad {
+ let got = key.store_signature_der(raw);
+ assert!(matches!(got, Err(SignError::Crypto(_))), "{}, {} bytes: {got:?}", key.describe(), raw.len());
+ }
+ }
+}