synta-certificate 0.2.6

X.509 certificate structures for synta ASN.1 library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
//! OpenSSL-backed [`crate::Pkcs12Decryptor`] and [`crate::CmsEncryptor`] implementations.

use crate::crypto::utils::split_alg_id;
use synta::{Decoder, Encoding, ObjectIdentifier, TagClass};

use crate::crypto::{CmsDecryptor, CmsEncryptor, Encryptor, Pkcs12Decryptor};
use crate::pkcs12_types::{
    ID_AES128_CBC, ID_AES192_CBC, ID_AES256_CBC, ID_DES_EDE3_CBC, ID_HMAC_WITH_SHA1,
    ID_HMAC_WITH_SHA256, ID_HMAC_WITH_SHA384, ID_HMAC_WITH_SHA512, ID_PBES2,
    ID_PBE_WITH_SHAAND3_KEY_TRIPLE_DES_CBC, ID_PBKDF2,
};

#[cfg(feature = "deprecated-pkcs12-algorithms")]
use crate::pkcs12_types::PBEParameter;

use crate::pkcs12_types::{Pbes2Params, Pbkdf2Params};

use native_ossl::cipher::CipherAlg;
use native_ossl::digest::DigestAlg;

/// Error type for [`OpensslDecryptor`].
#[derive(Debug)]
pub enum OpensslDecryptorError {
    /// ASN.1 parse error while decoding algorithm parameters.
    Parse(synta::Error),
    /// The algorithm or cipher OID is not supported.
    UnsupportedAlgorithm(String),
    /// OpenSSL reported an error during key derivation or decryption.
    Openssl(native_ossl::error::ErrorStack),
}

impl std::fmt::Display for OpensslDecryptorError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            OpensslDecryptorError::Parse(e) => {
                write!(f, "algorithm parameter parse error: {:?}", e)
            }
            OpensslDecryptorError::UnsupportedAlgorithm(s) => {
                write!(f, "unsupported algorithm: {}", s)
            }
            OpensslDecryptorError::Openssl(e) => write!(f, "OpenSSL error: {}", e),
        }
    }
}

impl std::error::Error for OpensslDecryptorError {}

impl From<synta::Error> for OpensslDecryptorError {
    fn from(e: synta::Error) -> Self {
        OpensslDecryptorError::Parse(e)
    }
}

impl From<native_ossl::error::ErrorStack> for OpensslDecryptorError {
    fn from(e: native_ossl::error::ErrorStack) -> Self {
        OpensslDecryptorError::Openssl(e)
    }
}

/// OpenSSL-backed PKCS#12 decryptor.
pub struct OpensslDecryptor;

impl Pkcs12Decryptor for OpensslDecryptor {
    type Error = OpensslDecryptorError;

    fn decrypt(
        &self,
        algorithm_der: &[u8],
        ciphertext: &[u8],
        password: &[u8],
    ) -> Result<Vec<u8>, OpensslDecryptorError> {
        // Decode the outer AlgorithmIdentifier OID to dispatch.
        let (oid, _, _params) = split_alg_id(algorithm_der, OpensslDecryptorError::from)?;

        if oid.components() == ID_PBES2 {
            return decrypt_pbes2(algorithm_der, ciphertext, password);
        }

        #[cfg(feature = "deprecated-pkcs12-algorithms")]
        if oid.components() == ID_PBE_WITH_SHAAND3_KEY_TRIPLE_DES_CBC {
            return decrypt_pkcs12_pbe_3des(algorithm_der, ciphertext, password);
        }

        Err(OpensslDecryptorError::UnsupportedAlgorithm(format!(
            "OID {:?}{}",
            oid.components(),
            if cfg!(not(feature = "deprecated-pkcs12-algorithms"))
                && oid.components() == ID_PBE_WITH_SHAAND3_KEY_TRIPLE_DES_CBC
            {
                " (3DES; enable 'deprecated-pkcs12-algorithms' feature to support legacy archives)"
            } else {
                ""
            }
        )))
    }
}

impl CmsDecryptor for OpensslDecryptor {
    type Error = OpensslDecryptorError;

    /// Decrypt CMS `EncryptedData` content using a raw symmetric key.
    ///
    /// Supports the AES-CBC family (`id-aes128-cbc`, `id-aes192-cbc`,
    /// `id-aes256-cbc`) and, when the `deprecated-pkcs12-algorithms` feature
    /// is enabled, `des-ede3-cbc`.  The IV is the OCTET STRING parameter of
    /// the `AlgorithmIdentifier`.
    fn decrypt(
        &self,
        algorithm_der: &[u8],
        ciphertext: &[u8],
        key: &[u8],
    ) -> Result<Vec<u8>, OpensslDecryptorError> {
        let (oid, _, params_der) = split_alg_id(algorithm_der, OpensslDecryptorError::from)?;
        let (cipher, expected_key_len) = oid_to_cipher(oid.components())?;

        if key.len() != expected_key_len {
            return Err(OpensslDecryptorError::UnsupportedAlgorithm(format!(
                "key length mismatch: expected {} bytes for {:?}, got {}",
                expected_key_len,
                oid.components(),
                key.len()
            )));
        }

        let iv = decode_octet_string_content(params_der)?;
        let mut ctx = cipher.decrypt(key, iv, None)?;
        let block = cipher.block_size();
        let mut plaintext = vec![0u8; ciphertext.len() + block];
        let n = ctx.update(ciphertext, &mut plaintext)?;
        let m = ctx.finalize(&mut plaintext[n..])?;
        plaintext.truncate(n + m);
        Ok(plaintext)
    }
}

// ── CMS Encryption ───────────────────────────────────────────────────────────

/// Error type for [`OpensslEncryptor`].
#[derive(Debug)]
pub enum OpensslEncryptorError {
    /// The cipher OID is not supported or the key length is wrong.
    UnsupportedAlgorithm(String),
    /// OpenSSL reported an error during IV generation or encryption.
    Openssl(native_ossl::error::ErrorStack),
    /// ASN.1 encoding error while building the `AlgorithmIdentifier`.
    Encode(synta::Error),
}

impl std::fmt::Display for OpensslEncryptorError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            OpensslEncryptorError::UnsupportedAlgorithm(s) => {
                write!(f, "unsupported algorithm: {}", s)
            }
            OpensslEncryptorError::Openssl(e) => write!(f, "OpenSSL error: {}", e),
            OpensslEncryptorError::Encode(e) => write!(f, "ASN.1 encode error: {:?}", e),
        }
    }
}

impl std::error::Error for OpensslEncryptorError {}

impl From<native_ossl::error::ErrorStack> for OpensslEncryptorError {
    fn from(e: native_ossl::error::ErrorStack) -> Self {
        OpensslEncryptorError::Openssl(e)
    }
}

impl From<synta::Error> for OpensslEncryptorError {
    fn from(e: synta::Error) -> Self {
        OpensslEncryptorError::Encode(e)
    }
}

/// OpenSSL-backed [`Encryptor`] and [`CmsEncryptor`].
///
/// Supports the AES-CBC family (`id-aes128-cbc`, `id-aes192-cbc`,
/// `id-aes256-cbc`) and, when the `deprecated-pkcs12-algorithms` feature is
/// enabled, `des-ede3-cbc`.
///
/// A fresh cryptographically random IV is generated for every call to
/// [`Encryptor::encrypt`] using `native_ossl::rand::Rand::bytes`.
pub struct OpensslEncryptor;

impl Encryptor for OpensslEncryptor {
    type Error = OpensslEncryptorError;

    fn encrypt(
        &self,
        alg_oid: &[u32],
        plaintext: &[u8],
        key: &[u8],
    ) -> Result<(Vec<u8>, Vec<u8>), OpensslEncryptorError> {
        let (cipher, expected_key_len) = oid_to_cipher(alg_oid)
            .map_err(|e| OpensslEncryptorError::UnsupportedAlgorithm(e.to_string()))?;

        if key.len() != expected_key_len {
            return Err(OpensslEncryptorError::UnsupportedAlgorithm(format!(
                "key length mismatch: expected {} bytes for {:?}, got {}",
                expected_key_len,
                alg_oid,
                key.len()
            )));
        }

        let iv_len = cipher.iv_len();
        let iv = if iv_len > 0 {
            native_ossl::rand::Rand::bytes(iv_len)?
        } else {
            Vec::new()
        };

        let mut ctx = cipher.encrypt(key, &iv, None)?;
        let block = cipher.block_size();
        let mut ciphertext = vec![0u8; plaintext.len() + block];
        let n = ctx.update(plaintext, &mut ciphertext)?;
        let m = ctx.finalize(&mut ciphertext[n..])?;
        ciphertext.truncate(n + m);

        let algorithm_identifier_der = build_alg_id_der(alg_oid, &iv)?;
        Ok((algorithm_identifier_der, ciphertext))
    }
}

impl CmsEncryptor for OpensslEncryptor {
    fn create_encrypted_data(
        &self,
        content_type_oid: &[u32],
        enc_alg_oid: &[u32],
        plaintext: &[u8],
        key: &[u8],
    ) -> Result<Vec<u8>, OpensslEncryptorError> {
        use crate::cms_rfc5652_types::{EncryptedContentInfo, EncryptedData};
        use synta::{Decoder, Encoding as SyntaEncoding, Integer, OctetStringRef};

        let (enc_alg_id_der, ciphertext) = self.encrypt(enc_alg_oid, plaintext, key)?;

        let content_type = ObjectIdentifier::new(content_type_oid).map_err(|_| {
            OpensslEncryptorError::UnsupportedAlgorithm(format!(
                "invalid content-type OID: {:?}",
                content_type_oid
            ))
        })?;
        let content_encryption_algorithm: crate::AlgorithmIdentifier<'_> =
            Decoder::new(&enc_alg_id_der, SyntaEncoding::Der).decode()?;

        let ed = EncryptedData {
            version: Integer::from_i64(0),
            encrypted_content_info: EncryptedContentInfo {
                content_type,
                content_encryption_algorithm,
                encrypted_content: Some(OctetStringRef::new(&ciphertext)),
            },
            unprotected_attrs: None,
        };

        Ok(ed.to_der()?)
    }
}

// ── Helpers ─────────────────────────────────────────────────────────────────

/// Build a DER-encoded `AlgorithmIdentifier` SEQUENCE for a CBC-family cipher:
/// `SEQUENCE { OID, OCTET STRING(iv) }`.
pub(super) fn build_alg_id_der(
    alg_oid: &[u32],
    iv: &[u8],
) -> Result<Vec<u8>, OpensslEncryptorError> {
    use synta::{Element, ObjectIdentifier, OctetStringRef};

    let oid = ObjectIdentifier::new(alg_oid).map_err(|_| {
        OpensslEncryptorError::UnsupportedAlgorithm(format!("invalid algorithm OID: {:?}", alg_oid))
    })?;
    Ok(crate::AlgorithmIdentifier {
        algorithm: oid,
        parameters: Some(Element::OctetString(OctetStringRef::new(iv))),
    }
    .to_der()?)
}

/// Map an HMAC PRF OID to its `DigestAlg`.
pub(super) fn oid_to_digest(oid: &[u32]) -> Result<DigestAlg, OpensslDecryptorError> {
    let name: &std::ffi::CStr = if oid == ID_HMAC_WITH_SHA1 {
        c"SHA1"
    } else if oid == ID_HMAC_WITH_SHA256 {
        c"SHA2-256"
    } else if oid == ID_HMAC_WITH_SHA384 {
        c"SHA2-384"
    } else if oid == ID_HMAC_WITH_SHA512 {
        c"SHA2-512"
    } else {
        return Err(OpensslDecryptorError::UnsupportedAlgorithm(format!(
            "unsupported HMAC PRF OID: {:?}",
            oid
        )));
    };
    DigestAlg::fetch(name, None).map_err(Into::into)
}

pub(super) fn oid_to_cipher(oid: &[u32]) -> Result<(CipherAlg, usize), OpensslDecryptorError> {
    if oid == ID_AES128_CBC {
        Ok((CipherAlg::fetch(c"AES-128-CBC", None)?, 16))
    } else if oid == ID_AES192_CBC {
        Ok((CipherAlg::fetch(c"AES-192-CBC", None)?, 24))
    } else if oid == ID_AES256_CBC {
        Ok((CipherAlg::fetch(c"AES-256-CBC", None)?, 32))
    } else if oid == ID_DES_EDE3_CBC {
        #[cfg(not(feature = "deprecated-pkcs12-algorithms"))]
        return Err(OpensslDecryptorError::UnsupportedAlgorithm(
            "3DES-EDE-CBC is deprecated (RFC 9126); enable the \
             'deprecated-pkcs12-algorithms' feature to read legacy archives"
                .into(),
        ));
        #[cfg(feature = "deprecated-pkcs12-algorithms")]
        Ok((CipherAlg::fetch(c"DES-EDE3-CBC", None)?, 24))
    } else {
        Err(OpensslDecryptorError::UnsupportedAlgorithm(format!(
            "unsupported PBES2 cipher OID: {:?}",
            oid
        )))
    }
}

/// Extract the content of an OCTET STRING TLV; return the raw content bytes.
pub(super) fn decode_octet_string_content(der: &[u8]) -> Result<&[u8], OpensslDecryptorError> {
    let mut dec = Decoder::new(der, Encoding::Der);
    let tag = dec.read_tag()?;
    if tag.class() != TagClass::Universal || tag.number() != 4 {
        return Err(OpensslDecryptorError::UnsupportedAlgorithm(
            "expected OCTET STRING for cipher IV parameter".into(),
        ));
    }
    let len = dec.read_length()?.definite()?;
    let pos = dec.position();
    Ok(&der[pos..pos + len])
}

// ── PBES2 (RFC 8018 §6.2) ───────────────────────────────────────────────────

fn decrypt_pbes2(
    algorithm_der: &[u8],
    ciphertext: &[u8],
    password: &[u8],
) -> Result<Vec<u8>, OpensslDecryptorError> {
    use native_ossl::kdf::Pbkdf2Builder;

    // `algorithm_der` is the full AlgorithmIdentifier for id-PBES2.
    // The parameters field is PBES2-params.  Split off the params bytes.
    let (_oid, _, params_der) = split_alg_id(algorithm_der, OpensslDecryptorError::from)?;

    let mut pdec = Decoder::new(params_der, Encoding::Der);
    let pbes2: Pbes2Params = pdec.decode()?;

    // key_derivation_func: RawDer carrying the AlgorithmIdentifier for PBKDF2.
    let (kdf_oid, _, kdf_params_der) = split_alg_id(
        pbes2.key_derivation_func.as_bytes(),
        OpensslDecryptorError::from,
    )?;

    if kdf_oid.components() != ID_PBKDF2 {
        return Err(OpensslDecryptorError::UnsupportedAlgorithm(format!(
            "unsupported PBES2 KDF OID: {:?}",
            kdf_oid.components()
        )));
    }

    let mut kp_dec = Decoder::new(kdf_params_der, Encoding::Der);
    let kdf_params: Pbkdf2Params = kp_dec.decode()?;

    // Determine the PRF digest (default: HMAC-SHA1 if absent, per RFC 8018).
    let prf_md = if let Some(prf_raw) = &kdf_params.prf {
        let (prf_oid, _, _) = split_alg_id(prf_raw.as_bytes(), OpensslDecryptorError::from)?;
        oid_to_digest(prf_oid.components())?
    } else {
        DigestAlg::fetch(c"SHA1", None)?
    };

    // encryption_scheme: RawDer carrying the AlgorithmIdentifier for the cipher.
    let (enc_oid, _, enc_params_der) = split_alg_id(
        pbes2.encryption_scheme.as_bytes(),
        OpensslDecryptorError::from,
    )?;

    let (cipher, key_len) = oid_to_cipher(enc_oid.components())?;

    // IV is the sole parameter of the encryption scheme: an OCTET STRING.
    let iv = decode_octet_string_content(enc_params_der)?;

    // Derive key via PBKDF2.
    let salt = kdf_params.salt.as_bytes();
    let iter = kdf_params.iteration_count.as_u64().map_err(|_| {
        OpensslDecryptorError::UnsupportedAlgorithm(
            "PBKDF2 iteration count is out of u64 range".into(),
        )
    })?;
    let iter_u32 = u32::try_from(iter).unwrap_or(u32::MAX);

    let key = Pbkdf2Builder::new(&prf_md, password, salt)
        .iterations(iter_u32)
        .derive_to_vec(key_len)?;

    // Decrypt.
    let mut ctx = cipher.decrypt(&key, iv, None)?;
    let block = cipher.block_size();
    let mut plaintext = vec![0u8; ciphertext.len() + block];
    let n = ctx.update(ciphertext, &mut plaintext)?;
    let m = ctx.finalize(&mut plaintext[n..])?;
    plaintext.truncate(n + m);
    Ok(plaintext)
}

// ── Legacy PKCS#12-KDF 3DES (RFC 7292 Appendix C) ───────────────────────────

#[cfg(feature = "deprecated-pkcs12-algorithms")]
fn decrypt_pkcs12_pbe_3des(
    algorithm_der: &[u8],
    ciphertext: &[u8],
    password: &[u8],
) -> Result<Vec<u8>, OpensslDecryptorError> {
    use native_ossl::kdf::{Pkcs12KdfBuilder, Pkcs12KdfId};

    let (_oid, _, params_der) = split_alg_id(algorithm_der, OpensslDecryptorError::from)?;

    let mut pdec = Decoder::new(params_der, Encoding::Der);
    let pbe: PBEParameter = pdec.decode()?;

    let salt = pbe.salt.as_bytes();
    let iter = pbe.iteration_count.as_i64().map_err(|_| {
        OpensslDecryptorError::UnsupportedAlgorithm(
            "PBE iteration count is out of i64 range".into(),
        )
    })?;
    let iter_u32 = u32::try_from(iter).unwrap_or(2048);

    let sha1 = DigestAlg::fetch(c"SHA1", None)?;

    // Derive 24-byte key (id=1) and 8-byte IV (id=2) via PKCS12-KDF.
    let key = Pkcs12KdfBuilder::new(&sha1, password, salt, Pkcs12KdfId::Key)
        .iterations(iter_u32)
        .derive_to_vec(24)?;
    let iv = Pkcs12KdfBuilder::new(&sha1, password, salt, Pkcs12KdfId::Iv)
        .iterations(iter_u32)
        .derive_to_vec(8)?;

    let cipher = CipherAlg::fetch(c"DES-EDE3-CBC", None)?;
    let mut ctx = cipher.decrypt(&key, &iv, None)?;
    let block = cipher.block_size();
    let mut plaintext = vec![0u8; ciphertext.len() + block];
    let n = ctx.update(ciphertext, &mut plaintext)?;
    let m = ctx.finalize(&mut plaintext[n..])?;
    plaintext.truncate(n + m);
    Ok(plaintext)
}