Skip to main content

openszigno_core/decrypt/
keys.rs

1//! Recipient key loading and certificate matching.
2//!
3//! This is the half of the `encrypt` transform that never touches a CMS
4//! message: loading the recipient's own RSA private key (PKCS#8, DER or PEM,
5//! plain or passphrase protected), reading the certificate that names it, and
6//! deciding whether a CMS `RecipientIdentifier` names that certificate, by
7//! `issuerAndSerialNumber` or by `subjectKeyIdentifier`.
8
9use der::asn1::OctetString;
10use der::{Decode, Encode};
11use rsa::RsaPrivateKey;
12use x509_cert::Certificate;
13use zeroize::Zeroizing;
14
15use cms::enveloped_data::RecipientIdentifier;
16use const_oid::ObjectIdentifier;
17
18use crate::{Error, ErrorCode};
19
20/// X.509 `id-ce-subjectKeyIdentifier`.
21const ID_CE_SUBJECT_KEY_IDENTIFIER: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.5.29.14");
22
23/// The recipient private key `extract` decrypts with, together with the
24/// certificate that lets a `RecipientInfo` be recognised as naming it.
25///
26/// The key bytes never leave this type: it has no accessor for them, no
27/// `Debug` that could print them, and every error raised while loading it is
28/// a fixed string that quotes nothing.
29pub struct RecipientKey {
30    /// Visible to the rest of `decrypt` only for the RSA key-transport
31    /// unwrap in `cms::unwrap_key`, which needs the key itself rather than
32    /// anything this module could compute from it.
33    pub(super) private: RsaPrivateKey,
34    /// DER of the certificate's `issuer` field, for `issuerAndSerialNumber`.
35    issuer_der: Vec<u8>,
36    /// DER of the certificate's `serialNumber`, for `issuerAndSerialNumber`.
37    serial_der: Vec<u8>,
38    /// The certificate's `subjectKeyIdentifier` octets, when it has that
39    /// extension. A recipient named by SKI cannot be matched without it.
40    subject_key_identifier: Option<Vec<u8>>,
41}
42
43impl std::fmt::Debug for RecipientKey {
44    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        formatter
46            .debug_struct("RecipientKey")
47            .finish_non_exhaustive()
48    }
49}
50
51impl RecipientKey {
52    /// Load a recipient key from PKCS#8 bytes and the certificate that
53    /// identifies it.
54    ///
55    /// `key` is PKCS#8 in DER or PEM, plain (`PRIVATE KEY`) or passphrase
56    /// protected (`ENCRYPTED PRIVATE KEY`). A PEM file may hold the
57    /// certificate alongside the key, in which case `certificate` may be
58    /// `None`. `passphrase` is only consulted for an encrypted key.
59    ///
60    /// Errors carry a stable code and a fixed message. They never quote the
61    /// key, the passphrase, the certificate, or anything derived from them,
62    /// and they do not distinguish "wrong passphrase" from "not a PKCS#8
63    /// file", because both are answered the same way: check the inputs.
64    pub fn load(
65        key: &[u8],
66        passphrase: Option<&[u8]>,
67        certificate: Option<&[u8]>,
68    ) -> Result<Self, Error> {
69        let private = load_private_key(key, passphrase)?;
70        let certificate = match certificate {
71            Some(bytes) => parse_certificate(bytes)?,
72            None => certificate_in_pem(key)?.ok_or_else(|| {
73                Error::new(
74                    ErrorCode::DecryptionCertificateRequired,
75                    "a decryption certificate is required: the key file carries no certificate, so the recipient it belongs to cannot be recognised",
76                )
77            })?,
78        };
79        Self::new(private, &certificate)
80    }
81
82    fn new(private: RsaPrivateKey, certificate: &Certificate) -> Result<Self, Error> {
83        use rsa::pkcs8::DecodePublicKey as _;
84
85        let spki = &certificate.tbs_certificate.subject_public_key_info;
86        let certificate_key = rsa::RsaPublicKey::from_public_key_der(
87            &spki.to_der().map_err(|_| invalid_certificate())?,
88        )
89        .map_err(|_| {
90            Error::new(
91                ErrorCode::InvalidDecryptionCertificate,
92                "the decryption certificate does not carry an RSA public key",
93            )
94        })?;
95        if rsa::RsaPublicKey::from(&private) != certificate_key {
96            return Err(Error::new(
97                ErrorCode::DecryptionKeyMismatch,
98                "the decryption certificate does not belong to the decryption key",
99            ));
100        }
101        Ok(Self {
102            issuer_der: certificate
103                .tbs_certificate
104                .issuer
105                .to_der()
106                .map_err(|_| invalid_certificate())?,
107            serial_der: certificate
108                .tbs_certificate
109                .serial_number
110                .to_der()
111                .map_err(|_| invalid_certificate())?,
112            subject_key_identifier: subject_key_identifier(certificate)?,
113            private,
114        })
115    }
116
117    /// Whether a CMS `RecipientIdentifier` names this key's certificate.
118    pub(super) fn matches(&self, rid: &RecipientIdentifier) -> bool {
119        match rid {
120            RecipientIdentifier::IssuerAndSerialNumber(named) => {
121                match (named.issuer.to_der(), named.serial_number.to_der()) {
122                    (Ok(issuer), Ok(serial)) => {
123                        issuer == self.issuer_der && serial == self.serial_der
124                    }
125                    _ => false,
126                }
127            }
128            RecipientIdentifier::SubjectKeyIdentifier(identifier) => self
129                .subject_key_identifier
130                .as_deref()
131                .is_some_and(|known| known == identifier.0.as_bytes()),
132        }
133    }
134
135    /// A key that is never asked to decrypt anything, for tests that only
136    /// need a `RecipientKey` value to exist.
137    #[cfg(test)]
138    pub(super) fn unusable_for_tests() -> Self {
139        // A textbook-sized key: it is never asked to decrypt anything here,
140        // and embedding a full-size one would only slow the suite.
141        RecipientKey {
142            private: rsa::RsaPrivateKey::from_components(
143                rsa::BigUint::from(3233u32),
144                rsa::BigUint::from(17u32),
145                rsa::BigUint::from(413u32),
146                vec![rsa::BigUint::from(61u32), rsa::BigUint::from(53u32)],
147            )
148            .expect("the textbook RSA key builds"),
149            issuer_der: Vec::new(),
150            serial_der: Vec::new(),
151            subject_key_identifier: None,
152        }
153    }
154}
155
156fn invalid_certificate() -> Error {
157    Error::new(
158        ErrorCode::InvalidDecryptionCertificate,
159        "the decryption certificate is not a readable X.509 certificate",
160    )
161}
162
163fn invalid_key() -> Error {
164    Error::new(
165        ErrorCode::InvalidDecryptionKey,
166        "the decryption key could not be read: it must be an RSA private key in PKCS#8 DER or PEM form, and a passphrase must be supplied for an encrypted one",
167    )
168}
169
170/// Read an RSA private key from PKCS#8 DER or PEM, decrypting it first when it
171/// is a passphrase-protected `EncryptedPrivateKeyInfo`.
172fn load_private_key(bytes: &[u8], passphrase: Option<&[u8]>) -> Result<RsaPrivateKey, Error> {
173    use rsa::pkcs8::DecodePrivateKey as _;
174
175    let der: Zeroizing<Vec<u8>> = match pem_blocks(bytes) {
176        Some(blocks) => {
177            let (label, body) = blocks
178                .into_iter()
179                .find(|(label, _)| label == "PRIVATE KEY" || label == "ENCRYPTED PRIVATE KEY")
180                .ok_or_else(invalid_key)?;
181            match label.as_str() {
182                "ENCRYPTED PRIVATE KEY" => decrypt_pkcs8(&body, passphrase)?,
183                _ => Zeroizing::new(body),
184            }
185        }
186        None => match RsaPrivateKey::from_pkcs8_der(bytes) {
187            Ok(key) => return Ok(key),
188            Err(_) => decrypt_pkcs8(bytes, passphrase)?,
189        },
190    };
191    RsaPrivateKey::from_pkcs8_der(&der).map_err(|_| invalid_key())
192}
193
194fn decrypt_pkcs8(der: &[u8], passphrase: Option<&[u8]>) -> Result<Zeroizing<Vec<u8>>, Error> {
195    let passphrase = passphrase.ok_or_else(invalid_key)?;
196    let encrypted = pkcs8::EncryptedPrivateKeyInfo::try_from(der).map_err(|_| invalid_key())?;
197    let document = encrypted.decrypt(passphrase).map_err(|_| invalid_key())?;
198    Ok(Zeroizing::new(document.as_bytes().to_vec()))
199}
200
201/// Every PEM block in `bytes` as `(label, DER body)`, or `None` when the input
202/// is not PEM at all.
203///
204/// A malformed block inside otherwise-PEM input is skipped rather than
205/// reported, so that a certificate bundle with a trailing comment still loads;
206/// the caller fails on "no usable block" instead.
207fn pem_blocks(bytes: &[u8]) -> Option<Vec<(String, Vec<u8>)>> {
208    let text = std::str::from_utf8(bytes).ok()?;
209    if !text.contains("-----BEGIN ") {
210        return None;
211    }
212    let mut blocks = Vec::new();
213    let mut rest = text;
214    while let Some(start) = rest.find("-----BEGIN ") {
215        let after = &rest[start..];
216        let Some(header_end) = after.find("-----\n").or_else(|| after.find("-----\r\n")) else {
217            break;
218        };
219        let label = after["-----BEGIN ".len()..header_end].to_owned();
220        let footer = format!("-----END {label}-----");
221        let Some(end) = after.find(&footer) else {
222            break;
223        };
224        let block = &after[..end + footer.len()];
225        if let Ok((_, body)) = pem_rfc7468::decode_vec(block.as_bytes()) {
226            blocks.push((label, body));
227        }
228        rest = &after[end + footer.len()..];
229    }
230    Some(blocks)
231}
232
233/// The first `CERTIFICATE` block of a PEM key file, if there is one.
234fn certificate_in_pem(bytes: &[u8]) -> Result<Option<Certificate>, Error> {
235    let Some(blocks) = pem_blocks(bytes) else {
236        return Ok(None);
237    };
238    match blocks.iter().find(|(label, _)| label == "CERTIFICATE") {
239        Some((_, body)) => Ok(Some(
240            Certificate::from_der(body).map_err(|_| invalid_certificate())?,
241        )),
242        None => Ok(None),
243    }
244}
245
246fn parse_certificate(bytes: &[u8]) -> Result<Certificate, Error> {
247    if let Some(blocks) = pem_blocks(bytes) {
248        let (_, body) = blocks
249            .into_iter()
250            .find(|(label, _)| label == "CERTIFICATE")
251            .ok_or_else(invalid_certificate)?;
252        return Certificate::from_der(&body).map_err(|_| invalid_certificate());
253    }
254    Certificate::from_der(bytes).map_err(|_| invalid_certificate())
255}
256
257fn subject_key_identifier(certificate: &Certificate) -> Result<Option<Vec<u8>>, Error> {
258    let Some(extensions) = certificate.tbs_certificate.extensions.as_ref() else {
259        return Ok(None);
260    };
261    let Some(extension) = extensions
262        .iter()
263        .find(|extension| extension.extn_id == ID_CE_SUBJECT_KEY_IDENTIFIER)
264    else {
265        return Ok(None);
266    };
267    let octets = OctetString::from_der(extension.extn_value.as_bytes())
268        .map_err(|_| invalid_certificate())?;
269    Ok(Some(octets.as_bytes().to_vec()))
270}
271
272#[cfg(test)]
273mod tests {
274    //! Unit tests for key loading, PEM scanning, and certificate parsing.
275
276    use super::*;
277
278    /// PEM armour, assembled at run time.
279    ///
280    /// A finished `BEGIN ... PRIVATE KEY` line never appears as a literal in
281    /// this repository. A secret scanner cannot tell a real key block from a
282    /// test string that only looks like one, and this project does not
283    /// allowlist scanner rules, so the only safe amount of key-shaped text in
284    /// the tree is none. See `SECURITY.md`.
285    fn armour(label: &str, body: &str) -> String {
286        let begin = format!("-----{}{label}-----", "BEGIN ");
287        match body {
288            // A header with no terminator at all.
289            "" => begin,
290            _ => format!("{begin}\n{body}\n-----{}{label}-----\n", "END "),
291        }
292    }
293
294    /// The same, with the closing line left off.
295    fn unterminated(label: &str, body: &str) -> String {
296        format!("{}\n{body}\n", armour(label, ""))
297    }
298
299    #[test]
300    fn input_that_is_not_pem_at_all_is_recognised_as_der() {
301        assert!(pem_blocks(b"\x30\x82\x01\x00").is_none());
302        assert!(pem_blocks(b"plain text with no armour").is_none());
303    }
304
305    /// The label every armour test uses, spelled apart from its delimiters.
306    const PRIVATE_KEY: &str = "PRIVATE KEY";
307    const CERTIFICATE: &str = "CERTIFICATE";
308
309    #[test]
310    fn a_truncated_or_unreadable_pem_block_is_skipped_rather_than_reported() {
311        // A header with no terminator, an unterminated block, and a block
312        // whose body is not base64: each leaves the file with no usable block,
313        // which the caller turns into one "unreadable key" answer.
314        for input in [
315            armour(PRIVATE_KEY, ""),
316            unterminated(PRIVATE_KEY, "AAAA"),
317            armour(PRIVATE_KEY, "!!!!"),
318        ] {
319            let blocks = pem_blocks(input.as_bytes()).expect("the input looks like PEM");
320            assert!(blocks.is_empty(), "{input:?} yields no usable block");
321        }
322        assert_eq!(
323            load_private_key(armour(PRIVATE_KEY, "").as_bytes(), None)
324                .expect_err("no block means no key")
325                .code(),
326            ErrorCode::InvalidDecryptionKey
327        );
328    }
329
330    #[test]
331    fn a_certificate_that_is_neither_pem_nor_der_is_reported_as_such() {
332        for input in [
333            b"not a certificate".to_vec(),
334            // PEM that holds no certificate block at all.
335            armour(PRIVATE_KEY, "").into_bytes(),
336        ] {
337            assert_eq!(
338                parse_certificate(&input)
339                    .expect_err("this is not a certificate")
340                    .code(),
341                ErrorCode::InvalidDecryptionCertificate
342            );
343        }
344        assert!(
345            certificate_in_pem(b"\x30\x00")
346                .expect("DER input carries no PEM certificate")
347                .is_none()
348        );
349        assert_eq!(
350            certificate_in_pem(armour(CERTIFICATE, "AAAA").as_bytes())
351                .expect_err("the block is not a certificate")
352                .code(),
353            ErrorCode::InvalidDecryptionCertificate
354        );
355    }
356
357    #[test]
358    fn the_key_type_never_prints_its_key() {
359        let rendered = format!("{:?}", RecipientKey::unusable_for_tests());
360        assert_eq!(rendered, "RecipientKey { .. }");
361    }
362}