aws_lc_rs/
lib.rs

1// Copyright 2015-2016 Brian Smith.
2// SPDX-License-Identifier: ISC
3// Modifications copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
4// SPDX-License-Identifier: Apache-2.0 OR ISC
5#![cfg_attr(not(clippy), allow(unexpected_cfgs))]
6#![cfg_attr(not(clippy), allow(unknown_lints))]
7#![allow(clippy::doc_markdown)]
8//! A [*ring*](https://github.com/briansmith/ring)-compatible crypto library using the cryptographic
9//! operations provided by [*AWS-LC*](https://github.com/aws/aws-lc). It uses either the
10//! auto-generated [*aws-lc-sys*](https://crates.io/crates/aws-lc-sys) or
11//! [*aws-lc-fips-sys*](https://crates.io/crates/aws-lc-fips-sys)
12//! Foreign Function Interface (FFI) crates found in this repository for invoking *AWS-LC*.
13//!
14//! # Build
15//!
16//! `aws-lc-rs` is available through [crates.io](https://crates.io/crates/aws-lc-rs). It can
17//! be added to your project in the [standard way](https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html)
18//! using `Cargo.toml`:
19//!
20//! ```toml
21//! [dependencies]
22//! aws-lc-rs = "1"
23//! ```
24//! Consuming projects will need a C/C++ compiler to build.
25//!
26//! **Non-FIPS builds (default):**
27//! * CMake is **never** required
28//! * Bindgen is **never** required (pre-generated bindings are provided)
29//! * Go is **never** required
30//!
31//! **FIPS builds:** Require **CMake**, **Go**, and potentially **bindgen** depending on the target platform.
32//!
33//! See our [User Guide](https://aws.github.io/aws-lc-rs/) for guidance on installing build requirements.
34//!
35//! # Feature Flags
36//!
37//! #### alloc (default)
38//!
39//! Allows implementation to allocate values of arbitrary size. (The meaning of this feature differs
40//! from the "alloc" feature of *ring*.) Currently, this is required by the `io::writer` module.
41//!
42//! #### ring-io (default)
43//!
44//! Enable feature to access the  `io`  module.
45//!
46//! #### ring-sig-verify (default)
47//!
48//! Enable feature to preserve compatibility with ring's `signature::VerificationAlgorithm::verify`
49//! function. This adds a requirement on `untrusted = "0.7.1"`.
50//!
51//! #### fips
52//!
53//! Enable this feature to have aws-lc-rs use the [*aws-lc-fips-sys*](https://crates.io/crates/aws-lc-fips-sys)
54//! crate for the cryptographic implementations. The aws-lc-fips-sys crate provides bindings to the
55//! latest version of the AWS-LC-FIPS module that has completed FIPS validation testing by an
56//! accredited lab and has been submitted to NIST for certification. This will continue to be the
57//! case as we periodically submit new versions of the AWS-LC-FIPS module to NIST for certification.
58//! Currently, aws-lc-fips-sys binds to
59//! [AWS-LC-FIPS 3.0.x](https://github.com/aws/aws-lc/tree/fips-2024-09-27).
60//!
61//! Consult with your local FIPS compliance team to determine the version of AWS-LC-FIPS module that you require. Consumers
62//! needing to remain on a previous version of the AWS-LC-FIPS module should pin to specific versions of aws-lc-rs to avoid
63//! automatically being upgraded to a newer module version.
64//! (See [cargo's documentation](https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html)
65//! on how to specify dependency versions.)
66//!
67//! | AWS-LC-FIPS module | aws-lc-rs |
68//! |--------------------|-----------|
69//! | 2.0.x              | \<1.12.0  |
70//! | 3.0.x              | *latest*  |
71//!
72//! Refer to the
73//! [NIST Cryptographic Module Validation Program's Modules In Progress List](https://csrc.nist.gov/Projects/cryptographic-module-validation-program/modules-in-process/Modules-In-Process-List)
74//! for the latest status of the static or dynamic AWS-LC Cryptographic Module. Please see the
75//! [FIPS.md in the aws-lc repository](https://github.com/aws/aws-lc/blob/main/crypto/fipsmodule/FIPS.md)
76//! for relevant security policies and information on supported operating environments.
77//! We will also update our release notes and documentation to reflect any changes in FIPS certification status.
78//!
79//! #### non-fips
80//!
81//! Enable this feature to guarantee that the non-FIPS [*aws-lc-sys*](https://crates.io/crates/aws-lc-sys)
82//! crate is used for cryptographic implementations. This feature is mutually exclusive with the `fips`
83//! feature - enabling both will result in a compile-time error. Use this feature when you need a
84//! compile-time guarantee that your build is using the non-FIPS cryptographic module.
85//!
86//! #### asan
87//!
88//! Performs an "address sanitizer" build. This can be used to help detect memory leaks. See the
89//! ["Address Sanitizer" section](https://doc.rust-lang.org/beta/unstable-book/compiler-flags/sanitizer.html#addresssanitizer)
90//! of the [Rust Unstable Book](https://doc.rust-lang.org/beta/unstable-book/).
91//!
92//! #### bindgen
93//!
94//! Causes `aws-lc-sys` or `aws-lc-fips-sys` to generates fresh bindings for AWS-LC instead of using
95//! the pre-generated bindings. This feature requires `libclang` to be installed. See the
96//! [requirements](https://rust-lang.github.io/rust-bindgen/requirements.html)
97//! for [rust-bindgen](https://github.com/rust-lang/rust-bindgen)
98//!
99//! #### prebuilt-nasm
100//!
101//! Enables the use of crate provided prebuilt NASM objects under certain conditions. This only affects builds for
102//! Windows x86-64 platforms. This feature is ignored if the "fips" feature is also enabled.
103//!
104//! Use of prebuilt NASM objects is prevented if either of the following conditions are true:
105//! * The NASM assembler is detected in the build environment
106//! * `AWS_LC_SYS_PREBUILT_NASM` environment variable is set with a value of `0`
107//!
108//! Be aware that [features are additive](https://doc.rust-lang.org/cargo/reference/features.html#feature-unification);
109//! by enabling this feature, it is enabled for all crates within the same build.
110//!
111//! # Use of prebuilt NASM objects
112//!
113//! Prebuilt NASM objects are **only** applicable to Windows x86-64 platforms. They are **never** used on any other platform (Linux, macOS, etc.).
114//!
115//! For Windows x86 and x86-64, NASM is required for assembly code compilation. On these platforms,
116//! we recommend that you install [the NASM assembler](https://www.nasm.us/). **If NASM is
117//! detected in the build environment, it is always used** to compile the assembly files. Prebuilt NASM objects are only used as a fallback.
118//!
119//! If a NASM assembler is not available, and the "fips" feature is not enabled, then the build fails unless one of the following conditions are true:
120//!
121//! * You are building for `x86-64` and either:
122//!    * The `AWS_LC_SYS_PREBUILT_NASM` environment variable is found and has a value of "1"; OR
123//!    * `AWS_LC_SYS_PREBUILT_NASM` is *not found* in the environment AND the "prebuilt-nasm" feature has been enabled.
124//!
125//! If the above cases apply, then the crate provided prebuilt NASM objects will be used for the build. To prevent usage of prebuilt NASM
126//! objects, install NASM in the build environment and/or set the variable `AWS_LC_SYS_PREBUILT_NASM` to `0` in the build environment to prevent their use.
127//!
128//! ## About prebuilt NASM objects
129//!
130//! Prebuilt NASM objects are generated using automation similar to the crate provided pregenerated bindings. See the repository's
131//! [GitHub workflow configuration](https://github.com/aws/aws-lc-rs/blob/main/.github/workflows/sys-bindings-generator.yml) for more information.
132//! The prebuilt NASM objects are checked into the repository
133//! and are [available for inspection](https://github.com/aws/aws-lc-rs/tree/main/aws-lc-sys/builder/prebuilt-nasm).
134//! For each PR submitted,
135//! [CI verifies](https://github.com/aws/aws-lc-rs/blob/main/.github/workflows/tests.yml)
136//! that the NASM objects newly built from source match the NASM objects currently in the repository.
137//!
138//! # *ring*-compatibility
139//!
140//! Although this library attempts to be fully compatible with *ring* (v0.16.x), there are a few places where our
141//! behavior is observably different.
142//!
143//! * Our implementation requires the `std` library. We currently do not support a
144//!   [`#![no_std]`](https://docs.rust-embedded.org/book/intro/no-std.html) build.
145//! * `aws-lc-rs` supports the platforms supported by `aws-lc-sys` and AWS-LC. See the
146//!   [Platform Support](https://aws.github.io/aws-lc-rs/platform_support.html) page in our User Guide.
147//! * `Ed25519KeyPair::from_pkcs8` and `Ed25519KeyPair::from_pkcs8_maybe_unchecked` both support
148//!   parsing of v1 or v2 PKCS#8 documents. If a v2 encoded key is provided to either function,
149//!   public key component, if present, will be verified to match the one derived from the encoded
150//!   private key.
151//!
152//! # Post-Quantum Cryptography
153//!
154//! Details on the post-quantum algorithms supported by aws-lc-rs can be found at
155//! [PQREADME](https://github.com/aws/aws-lc/tree/main/crypto/fipsmodule/PQREADME.md).
156//!
157//! # Motivation
158//!
159//! Rust developers increasingly need to deploy applications that meet US and Canadian government
160//! cryptographic requirements. We evaluated how to deliver FIPS validated cryptography in idiomatic
161//! and performant Rust, built around our AWS-LC offering. We found that the popular ring (v0.16)
162//! library fulfilled much of the cryptographic needs in the Rust community, but it did not meet the
163//! needs of developers with FIPS requirements. Our intention is to contribute a drop-in replacement
164//! for ring that provides FIPS support and is compatible with the ring API. Rust developers with
165//! prescribed cryptographic requirements can seamlessly integrate aws-lc-rs into their applications
166//! and deploy them into AWS Regions.
167
168#![warn(missing_docs)]
169#![warn(clippy::exhaustive_enums)]
170#![cfg_attr(aws_lc_rs_docsrs, feature(doc_cfg))]
171
172extern crate alloc;
173#[cfg(feature = "fips")]
174extern crate aws_lc_fips_sys as aws_lc;
175#[cfg(not(feature = "fips"))]
176extern crate aws_lc_sys as aws_lc;
177
178pub mod aead;
179pub mod agreement;
180pub mod cmac;
181pub mod constant_time;
182pub mod digest;
183pub mod error;
184pub mod hkdf;
185pub mod hmac;
186#[cfg(feature = "ring-io")]
187pub mod io;
188pub mod key_wrap;
189pub mod pbkdf2;
190pub mod pkcs8;
191pub mod rand;
192pub mod signature;
193pub mod test;
194
195mod bn;
196mod buffer;
197mod cbb;
198mod cbs;
199pub mod cipher;
200mod debug;
201mod ec;
202mod ed25519;
203pub mod encoding;
204mod endian;
205mod evp_pkey;
206mod fips;
207mod hex;
208pub mod iv;
209pub mod kdf;
210#[allow(clippy::module_name_repetitions)]
211pub mod kem;
212#[cfg(all(feature = "unstable", not(feature = "fips")))]
213mod pqdsa;
214mod ptr;
215pub mod rsa;
216pub mod tls_prf;
217pub mod unstable;
218
219pub(crate) use debug::derive_debug_via_id;
220// TODO: Uncomment when MSRV >= 1.64
221// use core::ffi::CStr;
222use std::ffi::CStr;
223
224use crate::aws_lc::{
225    CRYPTO_library_init, ERR_error_string, ERR_get_error, FIPS_mode, ERR_GET_FUNC, ERR_GET_LIB,
226    ERR_GET_REASON,
227};
228use std::sync::Once;
229
230static START: Once = Once::new();
231
232#[inline]
233/// Initialize the *AWS-LC* library. (This should generally not be needed.)
234pub fn init() {
235    START.call_once(|| unsafe {
236        CRYPTO_library_init();
237    });
238}
239
240#[cfg(feature = "fips")]
241/// Panics if the underlying implementation is not FIPS, otherwise it returns.
242///
243/// # Panics
244/// Panics if the underlying implementation is not FIPS.
245pub fn fips_mode() {
246    try_fips_mode().unwrap();
247}
248
249/// Indicates whether the underlying implementation is FIPS.
250///
251/// # Errors
252/// Return an error if the underlying implementation is not FIPS, otherwise Ok.
253pub fn try_fips_mode() -> Result<(), &'static str> {
254    init();
255    match unsafe { FIPS_mode() } {
256        1 => Ok(()),
257        _ => Err("FIPS mode not enabled!"),
258    }
259}
260
261#[cfg(feature = "fips")]
262/// Panics if the underlying implementation is not using CPU jitter entropy, otherwise it returns.
263///
264/// # Panics
265/// Panics if the underlying implementation is not using CPU jitter entropy.
266pub fn fips_cpu_jitter_entropy() {
267    try_fips_cpu_jitter_entropy().unwrap();
268}
269
270/// Indicates whether the underlying implementation is FIPS.
271///
272/// # Errors
273/// Return an error if the underlying implementation is not using CPU jitter entropy, otherwise Ok.
274pub fn try_fips_cpu_jitter_entropy() -> Result<(), &'static str> {
275    init();
276    // TODO: Delete once FIPS_is_entropy_cpu_jitter() available on FIPS branch
277    // https://github.com/aws/aws-lc/pull/2088
278    #[cfg(feature = "fips")]
279    if aws_lc::CFG_CPU_JITTER_ENTROPY() {
280        Ok(())
281    } else {
282        Err("FIPS CPU Jitter Entropy not enabled!")
283    }
284    #[cfg(not(feature = "fips"))]
285    match unsafe { aws_lc::FIPS_is_entropy_cpu_jitter() } {
286        1 => Ok(()),
287        _ => Err("FIPS CPU Jitter Entropy not enabled!"),
288    }
289}
290
291#[allow(dead_code)]
292unsafe fn dump_error() {
293    let err = ERR_get_error();
294    let lib = ERR_GET_LIB(err);
295    let reason = ERR_GET_REASON(err);
296    let func = ERR_GET_FUNC(err);
297    let mut buffer = [0u8; 256];
298    ERR_error_string(err, buffer.as_mut_ptr().cast());
299    let error_msg = CStr::from_bytes_with_nul_unchecked(&buffer);
300    eprintln!("Raw Error -- {error_msg:?}\nErr: {err}, Lib: {lib}, Reason: {reason}, Func: {func}");
301}
302
303mod sealed {
304    /// Traits that are designed to only be implemented internally in *aws-lc-rs*.
305    //
306    // Usage:
307    // ```
308    // use crate::sealed;
309    //
310    // pub trait MyType: sealed::Sealed {
311    //     // [...]
312    // }
313    //
314    // impl sealed::Sealed for MyType {}
315    // ```
316    pub trait Sealed {}
317}
318
319#[cfg(test)]
320mod tests {
321    use crate::{dump_error, init};
322
323    #[test]
324    fn test_init() {
325        init();
326    }
327
328    #[test]
329    fn test_dump() {
330        unsafe {
331            dump_error();
332        }
333    }
334
335    #[cfg(not(feature = "fips"))]
336    #[test]
337    fn test_fips() {
338        assert!({ crate::try_fips_mode().is_err() });
339        // Re-enable with fixed test after upstream has merged RAGDOLL
340        //assert!({ crate::try_fips_cpu_jitter_entropy().is_ok() });
341    }
342
343    #[test]
344    // FIPS mode is disabled for an ASAN build
345    #[cfg(feature = "fips")]
346    fn test_fips() {
347        #[cfg(not(feature = "asan"))]
348        crate::fips_mode();
349        if aws_lc::CFG_CPU_JITTER_ENTROPY() {
350            crate::fips_cpu_jitter_entropy();
351        }
352    }
353}