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