crypto-profile 0.9.0

Named cryptographic profiles over the AWS-LC FIPS module: algorithm types, per-module capabilities and a conformance suite
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
//! The crate's refusals.
use crate::algorithm::{Algorithm, SignatureAlgorithm, TlsVersion};
use crate::capability::Approval;
use crate::peer_certificate::PeerCertificateViolation;
use crate::profile::{Options, Profile};
use std::fmt;

/// A family of algorithms in a TLS policy or a profile.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Family {
    /// Protocol versions.
    Version,
    /// Cipher suites.
    CipherSuite,
    /// Key-exchange groups.
    KxGroup,
    /// Signature schemes.
    SignatureScheme,
    /// Key algorithms.
    KeyAlgorithm,
}

/// Why a certificate signing request could not be produced.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum CsrError {
    /// A subject alternative name or distinguished-name value is not valid for its type.
    InvalidName,
    /// The request parameters were refused.
    InvalidParams,
    /// Signing the request failed.
    Signing,
}

/// Bounded identity of a peer verifier, independent of certificates and trust anchors.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PeerVerifierIdentity {
    /// An owned verifier or completion policy.
    Owned {
        /// The certificate rule, absent for default-off policies.
        rule: Option<crate::PeerCertificateRuleId>,
        /// Canonical handshake-scheme mask, with bit positions from scheme preference order.
        handshake_schemes: u16,
    },
    /// A verifier whose policy identity cannot be established.
    Opaque,
}

/// Why a TLS configuration step was refused.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum TlsError {
    /// The provider refused the policy's protocol versions.
    ProtocolVersions,
    /// The private key was refused.
    PrivateKey,
    /// A process-default provider is already installed.
    DefaultProviderInstalled,
    /// The certificate chain is empty, or its end-entity certificate does not carry the key.
    KeyMismatch,
    /// A rule-bearing policy requires a completion builder that installs its owned verifier.
    StrictBuilderRequired {
        /// The applicable strict completion entry point in `tls`.
        entry_point: &'static str,
    },
    /// The completion policy and verifier have incompatible identities.
    IncompatiblePeerVerifier {
        /// The completion policy's identity.
        expected: PeerVerifierIdentity,
        /// The supplied verifier's identity.
        actual: PeerVerifierIdentity,
    },
    /// A peer certificate failed its profile's certificate rule.
    PeerCertificate {
        /// The governing profile.
        profile: Profile,
        /// The bounded refusal descriptor.
        violation: PeerCertificateViolation,
    },
}

impl fmt::Display for TlsError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ProtocolVersions => f.write_str("the provider refused the protocol versions"),
            Self::PrivateKey => f.write_str("the private key was refused"),
            Self::DefaultProviderInstalled => {
                f.write_str("a process-default provider is already installed")
            }
            Self::KeyMismatch => {
                f.write_str("the certificate chain is empty or does not carry the key")
            }
            Self::IncompatiblePeerVerifier { expected, actual } => {
                write!(
                    f,
                    "the peer verifier {actual:?} is incompatible with {expected:?}"
                )
            }
            Self::StrictBuilderRequired { entry_point } => {
                write!(f, "the peer certificate rule requires tls::{entry_point}")
            }
            Self::PeerCertificate { profile, violation } => {
                write!(f, "the {profile} peer certificate was refused: {violation}")
            }
        }
    }
}

impl std::error::Error for TlsError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::PeerCertificate { violation, .. } => Some(violation),
            Self::IncompatiblePeerVerifier { .. }
            | Self::StrictBuilderRequired { .. }
            | Self::ProtocolVersions
            | Self::PrivateKey
            | Self::DefaultProviderInstalled
            | Self::KeyMismatch => None,
        }
    }
}

/// A refusal from one of the crate's operations. It never carries key or plaintext material.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum CryptoError {
    /// The algorithm is not available on this backend's module.
    Unavailable(Algorithm),
    /// A TLS policy names nothing in this family.
    PolicyEmpty(Family),
    /// A TLS policy names this algorithm more than once.
    PolicyDuplicate(Algorithm),
    /// A provider does not carry exactly a policy's algorithms.
    PolicyDrift,
    /// A TLS policy lists a version but names nothing in this family usable with it.
    PolicyVersionUnusable {
        /// The listed version.
        version: TlsVersion,
        /// The family with nothing usable at that version.
        family: Family,
    },
    /// The process is not running the AWS-LC FIPS module, or a provider is not FIPS.
    NotFips,
    /// Key generation failed.
    KeyGeneration(Algorithm),
    /// A private key was refused.
    PrivateKey,
    /// A signature did not verify.
    Verify,
    /// Signing failed.
    Sign,
    /// A certificate signing request could not be produced.
    Csr(CsrError),
    /// A TLS configuration step was refused.
    Tls(TlsError),
    /// The random generator failed.
    Random,
    /// The AEAD key was refused.
    AeadKey,
    /// AEAD sealing failed.
    AeadSeal,
    /// The AEAD ciphertext did not authenticate.
    AeadOpen,
    /// A sealed-box plaintext is empty.
    SealPlaintext,
    /// A sealed blob is shorter than a header, one byte and a tag.
    SealBlob,
    /// A sealed blob carries an unknown version.
    SealVersion,
    /// A sealed blob's ephemeral key is not an uncompressed P-384 point.
    SealEphemeralKey,
    /// A sealing public key is not a canonical P-384 SubjectPublicKeyInfo.
    SealPublicKey,
    /// A sealing private key is not a P-384 PKCS#8 key.
    SealPrivateKey,
    /// A sealed blob does not open under this key, domain and AAD.
    SealOpen,
    /// A cryptographic primitive failed.
    Primitive,
    /// A profile, narrowed by its options, names nothing in a family.
    EmptyProfile {
        /// The profile.
        profile: Profile,
        /// The options it was narrowed by.
        options: Options,
        /// The family left empty.
        category: Family,
    },
    /// A key algorithm the profile does not admit.
    KeyNotInProfile {
        /// The profile.
        profile: Profile,
        /// The refused key algorithm.
        algorithm: SignatureAlgorithm,
    },
    /// An algorithm the running module does not approve.
    NotApproved {
        /// The first algorithm found not approved.
        algorithm: Algorithm,
        /// Its approval.
        approval: Approval,
    },
}

impl fmt::Display for CryptoError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CryptoError::Unavailable(a) => {
                write!(f, "{a:?} is not available on this backend's module")
            }
            CryptoError::PolicyEmpty(fam) => write!(f, "the TLS policy names no {fam:?}"),
            CryptoError::PolicyDuplicate(a) => write!(f, "the TLS policy names {a:?} twice"),
            CryptoError::PolicyVersionUnusable { version, family } => write!(
                f,
                "the TLS policy lists {version:?} but names no {family:?} usable with it"
            ),
            CryptoError::PolicyDrift => {
                f.write_str("the provider does not carry exactly the policy's algorithms")
            }
            CryptoError::NotFips => {
                f.write_str("the AWS-LC FIPS module is not active, or the provider is not FIPS")
            }
            CryptoError::KeyGeneration(a) => write!(f, "key generation for {a:?} failed"),
            CryptoError::PrivateKey => f.write_str("the private key was refused"),
            CryptoError::Verify => f.write_str("the signature does not verify"),
            CryptoError::Sign => f.write_str("signing failed"),
            CryptoError::Csr(e) => write!(f, "the certificate signing request failed: {e:?}"),
            CryptoError::Tls(e) => write!(f, "the TLS configuration was refused: {e:?}"),
            CryptoError::Random => f.write_str("the random generator failed"),
            CryptoError::AeadKey => f.write_str("the AEAD key was refused"),
            CryptoError::AeadSeal => f.write_str("AEAD sealing failed"),
            CryptoError::AeadOpen => f.write_str("the AEAD ciphertext does not authenticate"),
            CryptoError::SealPlaintext => f.write_str("the sealed plaintext is empty"),
            CryptoError::SealBlob => f.write_str("the sealed blob is too short"),
            CryptoError::SealVersion => f.write_str("the sealed blob has an unknown version"),
            CryptoError::SealEphemeralKey => {
                f.write_str("the sealed blob's ephemeral key is not an uncompressed P-384 point")
            }
            CryptoError::SealPublicKey => {
                f.write_str("the sealing public key is not a canonical P-384 SubjectPublicKeyInfo")
            }
            CryptoError::SealPrivateKey => {
                f.write_str("the sealing private key is not a P-384 PKCS#8 key")
            }
            CryptoError::SealOpen => {
                f.write_str("the sealed blob does not open under this key, domain and AAD")
            }
            CryptoError::Primitive => f.write_str("a cryptographic primitive failed"),
            CryptoError::EmptyProfile {
                profile,
                options,
                category,
            } => {
                write!(
                    f,
                    "the {profile} profile, with {options}, names no {category:?}"
                )
            }
            CryptoError::KeyNotInProfile { profile, algorithm } => {
                write!(f, "the {profile} profile does not admit {algorithm} keys")
            }
            CryptoError::NotApproved {
                algorithm,
                approval,
            } => {
                write!(
                    f,
                    "{algorithm:?} is not approved by the running module: {approval:?}"
                )
            }
        }
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::algorithm::{Algorithm, KxGroup, SignatureAlgorithm, TlsSignatureScheme};
    use crate::capability::Approval;
    use crate::profile::{Options, Profile};

    #[test]
    fn display_texts_are_pinned() {
        assert_eq!(
            CryptoError::Random.to_string(),
            "the random generator failed"
        );
        assert_eq!(
            CryptoError::NotFips.to_string(),
            "the AWS-LC FIPS module is not active, or the provider is not FIPS"
        );
        assert_eq!(
            CryptoError::Unavailable(Algorithm::Signature(SignatureAlgorithm::MlDsa87)).to_string(),
            "Signature(MlDsa87) is not available on this backend's module"
        );
        assert_eq!(
            CryptoError::PolicyEmpty(Family::KxGroup).to_string(),
            "the TLS policy names no KxGroup"
        );
        assert_eq!(
            CryptoError::PolicyVersionUnusable {
                version: TlsVersion::Tls12,
                family: Family::KxGroup
            }
            .to_string(),
            "the TLS policy lists Tls12 but names no KxGroup usable with it"
        );
        assert_eq!(
            CryptoError::PolicyDuplicate(Algorithm::Scheme(TlsSignatureScheme::Ed25519))
                .to_string(),
            "the TLS policy names Scheme(Ed25519) twice"
        );
        assert_eq!(
            CryptoError::Csr(CsrError::InvalidName).to_string(),
            "the certificate signing request failed: InvalidName"
        );
        assert_eq!(
            CryptoError::Tls(TlsError::PrivateKey).to_string(),
            "the TLS configuration was refused: PrivateKey"
        );
    }

    #[test]
    fn profile_display_texts_are_pinned() {
        let pq = Options {
            pq_key_exchange_required: true,
            peer_certificates_match_profile: false,
        };
        let table: [(CryptoError, &str); 5] = [
            (
                CryptoError::EmptyProfile {
                    profile: Profile::Cnsa1,
                    options: pq,
                    category: Family::KxGroup,
                },
                "the cnsa1 profile, with post-quantum key exchange required, names no KxGroup",
            ),
            (
                CryptoError::EmptyProfile {
                    profile: Profile::Cnsa2,
                    options: Options::default(),
                    category: Family::KeyAlgorithm,
                },
                "the cnsa2 profile, with no options, names no KeyAlgorithm",
            ),
            (
                CryptoError::KeyNotInProfile {
                    profile: Profile::Bsi,
                    algorithm: SignatureAlgorithm::Rsa3072Sha384,
                },
                "the bsi profile does not admit rsa3072-sha384 keys",
            ),
            (
                CryptoError::NotApproved {
                    algorithm: Algorithm::Kx(KxGroup::X25519),
                    approval: Approval::Unverified,
                },
                "Kx(X25519) is not approved by the running module: Unverified",
            ),
            (
                CryptoError::NotApproved {
                    algorithm: Algorithm::Signature(SignatureAlgorithm::MlDsa87),
                    approval: Approval::AlgorithmTested { cavp: "A7855 (x)" },
                },
                "Signature(MlDsa87) is not approved by the running module: AlgorithmTested { cavp: \"A7855 (x)\" }",
            ),
        ];
        for (e, text) in table {
            assert_eq!(e.to_string(), text);
        }
    }

    #[test]
    fn every_other_display_text_is_pinned() {
        let table: [(CryptoError, &str); 16] = [
            (
                CryptoError::PolicyDrift,
                "the provider does not carry exactly the policy's algorithms",
            ),
            (
                CryptoError::KeyGeneration(Algorithm::Signature(SignatureAlgorithm::Ed25519)),
                "key generation for Signature(Ed25519) failed",
            ),
            (CryptoError::PrivateKey, "the private key was refused"),
            (CryptoError::Verify, "the signature does not verify"),
            (CryptoError::Sign, "signing failed"),
            (CryptoError::AeadKey, "the AEAD key was refused"),
            (CryptoError::AeadSeal, "AEAD sealing failed"),
            (
                CryptoError::AeadOpen,
                "the AEAD ciphertext does not authenticate",
            ),
            (CryptoError::SealPlaintext, "the sealed plaintext is empty"),
            (CryptoError::SealBlob, "the sealed blob is too short"),
            (
                CryptoError::SealVersion,
                "the sealed blob has an unknown version",
            ),
            (
                CryptoError::SealEphemeralKey,
                "the sealed blob's ephemeral key is not an uncompressed P-384 point",
            ),
            (
                CryptoError::SealPublicKey,
                "the sealing public key is not a canonical P-384 SubjectPublicKeyInfo",
            ),
            (
                CryptoError::SealPrivateKey,
                "the sealing private key is not a P-384 PKCS#8 key",
            ),
            (
                CryptoError::SealOpen,
                "the sealed blob does not open under this key, domain and AAD",
            ),
            (CryptoError::Primitive, "a cryptographic primitive failed"),
        ];
        for (e, text) in table {
            assert_eq!(e.to_string(), text);
        }
    }
}