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
454
455
456
457
458
459
460
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

//! Cryptographic algorithms commonly encountered in X.509 certificates.

use {
    crate::{
        rfc5280::{AlgorithmIdentifier, AlgorithmParameter},
        X509CertificateError as Error,
    },
    bcder::{ConstOid, Oid},
    ring::{digest, signature},
    std::convert::TryFrom,
};

/// SHA-256 digest algorithm.
///
/// 2.16.840.1.101.3.4.2.1
const OID_SHA256: ConstOid = Oid(&[96, 134, 72, 1, 101, 3, 4, 2, 1]);

/// SHA-512 digest algorithm.
///
/// 2.16.840.1.101.3.4.2.3
const OID_SHA512: ConstOid = Oid(&[96, 134, 72, 1, 101, 3, 4, 2, 3]);

/// RSA+SHA-1 encryption.
///
/// 1.2.840.113549.1.1.5
const OID_SHA1_RSA: ConstOid = Oid(&[42, 134, 72, 134, 247, 13, 1, 1, 5]);

/// RSA+SHA-256 encryption.
///
/// 1.2.840.113549.1.1.11
const OID_SHA256_RSA: ConstOid = Oid(&[42, 134, 72, 134, 247, 13, 1, 1, 11]);

/// RSA+SHA-512 encryption.
///
/// 1.2.840.113549.1.1.13
const OID_SHA512_RSA: ConstOid = Oid(&[42, 134, 72, 134, 247, 13, 1, 1, 13]);

/// RSAES-PKCS1-v1_5
///
/// 1.2.840.113549.1.1.1
const OID_RSAES_PKCS_V15: ConstOid = Oid(&[42, 134, 72, 134, 247, 13, 1, 1, 1]);

/// RSA encryption.
///
/// 1.2.840.113549.1.1.1
const OID_RSA: ConstOid = Oid(&[42, 134, 72, 134, 247, 13, 1, 1, 1]);

/// ECDSA with SHA-256.
///
/// 1.2.840.10045.4.3.2
pub(crate) const OID_ECDSA_SHA256: ConstOid = Oid(&[42, 134, 72, 206, 61, 4, 3, 2]);

/// ECDSA with SHA-384.
///
/// 1.2.840.10045.4.3.2
pub(crate) const OID_ECDSA_SHA384: ConstOid = Oid(&[42, 134, 72, 206, 61, 4, 3, 3]);

/// Elliptic curve public key cryptography.
///
/// 1.2.840.10045.2.1
pub(crate) const OID_EC_PUBLIC_KEY: ConstOid = Oid(&[42, 134, 72, 206, 61, 2, 1]);

/// ED25519 key agreement.
///
/// 1.3.101.110
const OID_ED25519_KEY_AGREEMENT: ConstOid = Oid(&[43, 101, 110]);

/// Edwards curve digital signature algorithm.
///
/// 1.3.101.112
const OID_ED25519_SIGNATURE_ALGORITHM: ConstOid = Oid(&[43, 101, 112]);

/// Elliptic curve identifier for secp256r1.
///
/// 1.2.840.10045.3.1.7
pub(crate) const OID_EC_SECP256R1: ConstOid = Oid(&[42, 134, 72, 206, 61, 3, 1, 7]);

/// Elliptic curve identifier for secp384r1.
///
/// 1.3.132.0.34
pub(crate) const OID_EC_SECP384R1: ConstOid = Oid(&[43, 129, 4, 0, 34]);

/// A hashing algorithm used for digesting data.
///
/// Instances can be converted to and from [Oid] via `From`/`Into`
/// implementations.
///
/// They can also be converted to and from The ASN.1 [AlgorithmIdentifier],
/// which is commonly used to represent them in X.509 certificates.
///
/// Instances can be converted into a [digest::Context] capable of computing
/// digests via `From`/`Into`.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum DigestAlgorithm {
    /// SHA-256.
    ///
    /// Corresponds to OID 2.16.840.1.101.3.4.2.1.
    Sha256,
    /// SHA-512.
    ///
    /// Corresponds to OID 2.16.840.1.101.3.4.2.3.
    Sha512,
}

impl From<DigestAlgorithm> for Oid {
    fn from(alg: DigestAlgorithm) -> Self {
        Oid(match alg {
            DigestAlgorithm::Sha256 => OID_SHA256.as_ref(),
            DigestAlgorithm::Sha512 => OID_SHA512.as_ref(),
        }
        .into())
    }
}

impl TryFrom<&Oid> for DigestAlgorithm {
    type Error = Error;

    fn try_from(v: &Oid) -> Result<Self, Self::Error> {
        if v == &OID_SHA256 {
            Ok(Self::Sha256)
        } else if v == &OID_SHA512 {
            Ok(Self::Sha512)
        } else {
            Err(Error::UnknownDigestAlgorithm(format!("{}", v)))
        }
    }
}

impl TryFrom<&AlgorithmIdentifier> for DigestAlgorithm {
    type Error = Error;

    fn try_from(v: &AlgorithmIdentifier) -> Result<Self, Self::Error> {
        Self::try_from(&v.algorithm)
    }
}

impl From<DigestAlgorithm> for AlgorithmIdentifier {
    fn from(alg: DigestAlgorithm) -> Self {
        Self {
            algorithm: alg.into(),
            parameters: None,
        }
    }
}

impl From<DigestAlgorithm> for digest::Context {
    fn from(alg: DigestAlgorithm) -> Self {
        digest::Context::new(match alg {
            DigestAlgorithm::Sha256 => &digest::SHA256,
            DigestAlgorithm::Sha512 => &digest::SHA512,
        })
    }
}

impl DigestAlgorithm {
    /// Obtain an object that can be used to digest content using this algorithm.
    pub fn digester(&self) -> digest::Context {
        digest::Context::from(*self)
    }
}

/// An algorithm used to digitally sign content.
///
/// Instances can be converted to/from [Oid] via `From`/`Into`.
///
/// Similarly, instances can be converted to/from an ASN.1
/// [AlgorithmIdentifier].
///
/// It is also possible to obtain a [signature::VerificationAlgorithm] from
/// an instance. This type can perform actual cryptographic verification
/// that was signed with this algorithm.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum SignatureAlgorithm {
    /// SHA-1 with RSA encryption.
    ///
    /// Corresponds to OID 1.2.840.113549.1.1.5.
    Sha1Rsa,

    /// SHA-256 with RSA encryption.
    ///
    /// Corresponds to OID 1.2.840.113549.1.1.11.
    Sha256Rsa,

    /// SHA-512 with RSA encryption.
    ///
    /// Corresponds to OID 1.2.840.113549.1.1.13.
    Sha512Rsa,

    /// RSAES-PKCS1-v1_5 encryption scheme.
    ///
    /// Corresponds to OID 1.2.840.113549.1.1.1.
    RsaesPkcsV15,

    /// ECDSA with SHA-256.
    ///
    /// Corresponds to OID 1.2.840.10045.4.3.2.
    EcdsaSha256,

    /// ECDSA with SHA-384.
    ///
    /// Corresponds to OID 1.2.840.10045.4.3.3.
    EcdsaSha384,

    /// ED25519
    ///
    /// Corresponds to OID 1.3.101.112.
    Ed25519,
}

impl SignatureAlgorithm {
    /// Attempt to resolve the verification algorithm using info about the signing key algorithm.
    ///
    /// Only specific combinations of methods are supported. e.g. you can only use
    /// RSA verification with RSA signing keys. Same for ECDSA and ED25519.
    pub fn resolve_verification_algorithm(
        &self,
        key_algorithm: KeyAlgorithm,
    ) -> Result<&'static dyn signature::VerificationAlgorithm, Error> {
        match key_algorithm {
            KeyAlgorithm::Rsa => match self {
                Self::Sha1Rsa => Ok(&signature::RSA_PKCS1_2048_8192_SHA1_FOR_LEGACY_USE_ONLY),
                Self::Sha256Rsa => Ok(&signature::RSA_PKCS1_2048_8192_SHA256),
                Self::Sha512Rsa => Ok(&signature::RSA_PKCS1_2048_8192_SHA512),
                Self::RsaesPkcsV15 => {
                    Ok(&signature::RSA_PKCS1_1024_8192_SHA256_FOR_LEGACY_USE_ONLY)
                }
                alg => Err(Error::UnsupportedSignatureVerification(key_algorithm, *alg)),
            },
            KeyAlgorithm::Ed25519 => match self {
                Self::Ed25519 => Ok(&signature::ED25519),
                alg => Err(Error::UnsupportedSignatureVerification(key_algorithm, *alg)),
            },
            KeyAlgorithm::Ecdsa(curve) => match curve {
                EcdsaCurve::Secp256r1 => match self {
                    Self::EcdsaSha256 => Ok(&signature::ECDSA_P256_SHA256_ASN1),
                    Self::EcdsaSha384 => Ok(&signature::ECDSA_P256_SHA384_ASN1),
                    alg => Err(Error::UnsupportedSignatureVerification(key_algorithm, *alg)),
                },
                EcdsaCurve::Secp384r1 => match self {
                    Self::EcdsaSha256 => Ok(&signature::ECDSA_P384_SHA256_ASN1),
                    Self::EcdsaSha384 => Ok(&signature::ECDSA_P384_SHA384_ASN1),
                    alg => Err(Error::UnsupportedSignatureVerification(key_algorithm, *alg)),
                },
            },
        }
    }
}

impl From<SignatureAlgorithm> for Oid {
    fn from(alg: SignatureAlgorithm) -> Self {
        Oid(match alg {
            SignatureAlgorithm::Sha1Rsa => OID_SHA1_RSA.as_ref(),
            SignatureAlgorithm::Sha256Rsa => OID_SHA256_RSA.as_ref(),
            SignatureAlgorithm::Sha512Rsa => OID_SHA512_RSA.as_ref(),
            SignatureAlgorithm::RsaesPkcsV15 => OID_RSAES_PKCS_V15.as_ref(),
            SignatureAlgorithm::EcdsaSha256 => OID_ECDSA_SHA256.as_ref(),
            SignatureAlgorithm::EcdsaSha384 => OID_ECDSA_SHA384.as_ref(),
            SignatureAlgorithm::Ed25519 => OID_ED25519_SIGNATURE_ALGORITHM.as_ref(),
        }
        .into())
    }
}

impl TryFrom<&Oid> for SignatureAlgorithm {
    type Error = Error;

    fn try_from(v: &Oid) -> Result<Self, Self::Error> {
        if v == &OID_SHA1_RSA {
            Ok(Self::Sha1Rsa)
        } else if v == &OID_SHA256_RSA {
            Ok(Self::Sha256Rsa)
        } else if v == &OID_SHA512_RSA {
            Ok(Self::Sha512Rsa)
        } else if v == &OID_RSAES_PKCS_V15 {
            Ok(Self::RsaesPkcsV15)
        } else if v == &OID_ECDSA_SHA256 {
            Ok(Self::EcdsaSha256)
        } else if v == &OID_ECDSA_SHA384 {
            Ok(Self::EcdsaSha384)
        } else if v == &OID_ED25519_SIGNATURE_ALGORITHM {
            Ok(Self::Ed25519)
        } else {
            Err(Error::UnknownSignatureAlgorithm(format!("{}", v)))
        }
    }
}

impl TryFrom<&AlgorithmIdentifier> for SignatureAlgorithm {
    type Error = Error;

    fn try_from(v: &AlgorithmIdentifier) -> Result<Self, Self::Error> {
        Self::try_from(&v.algorithm)
    }
}

impl From<SignatureAlgorithm> for AlgorithmIdentifier {
    fn from(alg: SignatureAlgorithm) -> Self {
        Self {
            algorithm: alg.into(),
            parameters: None,
        }
    }
}

/// Represents a known curve used with ECDSA.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum EcdsaCurve {
    Secp256r1,
    Secp384r1,
}

impl EcdsaCurve {
    /// Obtain all variants of this type.
    pub fn all() -> &'static [Self] {
        &[Self::Secp256r1, Self::Secp384r1]
    }

    /// Obtain the OID representing this elliptic curve.
    pub fn as_signature_oid(&self) -> Oid {
        Oid(match self {
            Self::Secp256r1 => OID_EC_SECP256R1.as_ref().into(),
            Self::Secp384r1 => OID_EC_SECP384R1.as_ref().into(),
        })
    }
}

impl TryFrom<&Oid> for EcdsaCurve {
    type Error = Error;

    fn try_from(v: &Oid) -> Result<Self, Self::Error> {
        if v == &OID_EC_SECP256R1 {
            Ok(Self::Secp256r1)
        } else if v == &OID_EC_SECP384R1 {
            Ok(Self::Secp384r1)
        } else {
            Err(Error::UnknownEllipticCurve(format!("{}", v)))
        }
    }
}

impl From<EcdsaCurve> for &'static signature::EcdsaSigningAlgorithm {
    fn from(curve: EcdsaCurve) -> Self {
        match curve {
            EcdsaCurve::Secp256r1 => &signature::ECDSA_P256_SHA256_ASN1_SIGNING,
            EcdsaCurve::Secp384r1 => &signature::ECDSA_P384_SHA384_ASN1_SIGNING,
        }
    }
}

/// Cryptographic algorithm used by a private key.
///
/// Instances can be converted to/from the underlying ASN.1 type and
/// OIDs.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum KeyAlgorithm {
    /// RSA
    ///
    /// Corresponds to OID 1.2.840.113549.1.1.1.
    Rsa,

    /// Corresponds to OID 1.2.840.10045.2.1
    ///
    /// The inner OID tracks the curve / parameter in use.
    Ecdsa(EcdsaCurve),

    /// Corresponds to OID 1.3.101.110
    Ed25519,
}

impl TryFrom<&Oid> for KeyAlgorithm {
    type Error = Error;

    fn try_from(v: &Oid) -> Result<Self, Self::Error> {
        if v == &OID_RSA {
            Ok(Self::Rsa)
        } else if v == &OID_EC_PUBLIC_KEY {
            // Default to an arbitrary elliptic curve when just the OID is given to us.
            Ok(Self::Ecdsa(EcdsaCurve::Secp384r1))
        // ED25519 appears to use the signature algorithm OID for private key
        // identification, so we need to accept both.
        } else if v == &OID_ED25519_KEY_AGREEMENT || v == &OID_ED25519_SIGNATURE_ALGORITHM {
            Ok(Self::Ed25519)
        } else {
            Err(Error::UnknownKeyAlgorithm(format!("{}", v)))
        }
    }
}

impl From<KeyAlgorithm> for Oid {
    fn from(alg: KeyAlgorithm) -> Self {
        Oid(match alg {
            KeyAlgorithm::Rsa => OID_RSA.as_ref(),
            KeyAlgorithm::Ecdsa(_) => OID_EC_PUBLIC_KEY.as_ref(),
            KeyAlgorithm::Ed25519 => OID_ED25519_KEY_AGREEMENT.as_ref(),
        }
        .into())
    }
}

impl TryFrom<&AlgorithmIdentifier> for KeyAlgorithm {
    type Error = Error;

    fn try_from(v: &AlgorithmIdentifier) -> Result<Self, Self::Error> {
        // This will obtain a generic instance with defaults for configurable
        // parameters. So check for and apply parameters.
        let ka = Self::try_from(&v.algorithm)?;

        let ka = if let Some(params) = &v.parameters {
            match ka {
                Self::Ecdsa(_) => {
                    let curve_oid = params.decode_oid()?;
                    let curve = EcdsaCurve::try_from(&curve_oid)?;

                    Ok(Self::Ecdsa(curve))
                }
                Self::Ed25519 => {
                    // NULL is meaningless. Just a placeholder. Allow it through.
                    if params.as_slice() == [0x05, 0x00] {
                        Ok(ka)
                    } else {
                        Err(Error::UnhandledKeyAlgorithmParameters("on ED25519"))
                    }
                }
                Self::Rsa => {
                    // NULL is meaningless. Just a placeholder. Allow it through.
                    if params.as_slice() == [0x05, 0x00] {
                        Ok(ka)
                    } else {
                        Err(Error::UnhandledKeyAlgorithmParameters("on RSA"))
                    }
                }
            }?
        } else {
            ka
        };

        Ok(ka)
    }
}

impl From<KeyAlgorithm> for AlgorithmIdentifier {
    fn from(alg: KeyAlgorithm) -> Self {
        let parameters = match alg {
            KeyAlgorithm::Ed25519 => None,
            KeyAlgorithm::Rsa => None,
            KeyAlgorithm::Ecdsa(curve) => {
                Some(AlgorithmParameter::from_oid(curve.as_signature_oid()))
            }
        };

        Self {
            algorithm: alg.into(),
            parameters,
        }
    }
}