Skip to main content

ic_core/
module.rs

1//! The module's error state, where every crate can see it.
2//!
3//! A cryptographic module that finds itself wrong -- a known-answer test that
4//! fails, corruption detected by its host -- must stop producing output, and
5//! must not start again until it is restarted. `ic_fips` runs the tests and
6//! holds the rest of the module's state, but the primitive crates cannot
7//! depend on it: it depends on them. So the one fact they all need lives
8//! here, below them, as a flag that can be set and never cleared.
9//!
10//! Once [`enter_error_state`] has been called, every operation in this
11//! library that can report an error reports
12//! [`ErrorKind::ModuleErrorState`] and does nothing else: encryption and decryption, signing and verification,
13//! key generation and agreement, MACs made from a key, key derivation and
14//! random generation. The operations that return `bool` return `false`.
15//!
16//! # What this does not gate
17//!
18//! What has no error to return cannot refuse, and goes on working in the
19//! error state:
20//!
21//! - Hash functions and XOFs: `Sha256::new`, `update` and `finalize`, and
22//!   BLAKE2 with or without a key.
23//! - KMAC, whose constructor and `mac` are infallible. Only `verify` refuses.
24//! - A MAC object's `update` and `finalize`, once it exists. HMAC, CMAC and
25//!   Poly1305 refuse where they are made, in `Mac::new`.
26//! - ML-KEM's `keygen_deterministic` and `encapsulate_deterministic`, the
27//!   interfaces that take their randomness as arguments.
28//!
29//! One thing that could refuse is left ungated on purpose: a block cipher
30//! object's `encrypt_block`, `decrypt_block` and `encrypt_blocks`. They are
31//! the inner loop of every mode, and every mode refuses at its own entry, as
32//! does `BlockCipher::new`; a check per block would be paid by all of them
33//! to stop only raw single-block use of a key made before the failure.
34//!
35//! Parsing and encoding, which use no key, are not gated either.
36//!
37//! Nor does anything here require the self-tests to have run. A primitive
38//! called before `ic_fips::initialize` works; only a module that has failed
39//! refuses. `ic_fips::check` remains the gate for that and for approved
40//! mode.
41//!
42//! # Cost
43//!
44//! One relaxed load of one byte per operation.
45
46use crate::{Error, ErrorKind, Result};
47use core::sync::atomic::{AtomicBool, Ordering};
48
49static FAILED: AtomicBool = AtomicBool::new(false);
50
51/// Put the module into its error state.
52///
53/// There is no way back short of restarting the process, by design: nothing
54/// in this library clears the flag. Applications call
55/// `ic_fips::enter_error_state`, which calls this.
56pub fn enter_error_state() {
57    FAILED.store(true, Ordering::SeqCst);
58}
59
60/// Pass on the result of a conditional self-test, entering the error state
61/// if it failed.
62///
63/// A conditional self-test is one a module runs on its own work as it goes:
64/// the pairwise consistency test on a key pair it has just generated. Its
65/// input is the module's own output, never a caller's, so a failure is not
66/// something a peer can cause -- it means this module computed two things
67/// that should agree and do not, and nothing it computes afterwards can be
68/// vouched for.
69///
70/// Key generation wraps its test in this. The test functions themselves do
71/// not enter the state, so that they can be shown rejecting a mismatched
72/// pair without ending the process that shows it.
73pub fn conditional_self_test(result: Result<()>) -> Result<()> {
74    if result.is_err() {
75        enter_error_state();
76    }
77    result
78}
79
80/// Whether the module is in its error state.
81#[inline]
82#[must_use = "whether the module has failed; discarding it gates nothing"]
83pub fn in_error_state() -> bool {
84    FAILED.load(Ordering::Relaxed)
85}
86
87/// `Ok(())` unless the module is in its error state.
88///
89/// The first line of every operation that can refuse:
90///
91/// ```
92/// fn service() -> ic_core::Result<()> {
93///     ic_core::module::operational()?;
94///     // ...
95///     Ok(())
96/// }
97/// # service().unwrap();
98/// ```
99#[inline]
100pub fn operational() -> Result<()> {
101    if in_error_state() {
102        return Err(Error::new(
103            ErrorKind::ModuleErrorState,
104            "module in error state",
105        ));
106    }
107    Ok(())
108}