From 9883bd0daca1aa35fa1c6ca469c17320b1256b45 Mon Sep 17 00:00:00 2001 From: officialfrancismendoza Date: Tue, 15 Sep 2026 00:44:59 +0700 Subject: [PATCH] Initial add of AES lightengine GCM mode (#124) --- .claude/settings.json | 9 + cli/src/aead_mode_cmd.rs | 171 +++++++ cli/src/aes_gcm_cmd.rs | 82 ++++ cli/src/main.rs | 123 +++++ cli/tests/aes_gcm_cli_tests.rs | 361 ++++++++++++++ crypto/aes/src/gcm.rs | 118 +++++ crypto/aes/src/lib.rs | 6 + crypto/aes/tests/gcm_alias_tests.rs | 56 +++ crypto/modes/src/ctr.rs | 71 +++ crypto/modes/src/gcm.rs | 600 ++++++++++++++++++++++++ crypto/modes/src/ghash.rs | 417 ++++++++++++++++ crypto/modes/src/lib.rs | 32 +- crypto/modes/tests/acvp_gcm_tests.rs | 131 ++++++ crypto/modes/tests/acvp_gmac_tests.rs | 109 +++++ crypto/modes/tests/common/acvp_gcm.rs | 225 +++++++++ crypto/modes/tests/gcm_bc_java_tests.rs | 244 ++++++++++ crypto/modes/tests/gcm_tests.rs | 247 ++++++++++ 17 files changed, 2991 insertions(+), 11 deletions(-) create mode 100644 .claude/settings.json create mode 100644 cli/src/aead_mode_cmd.rs create mode 100644 cli/src/aes_gcm_cmd.rs create mode 100644 cli/tests/aes_gcm_cli_tests.rs create mode 100644 crypto/aes/src/gcm.rs create mode 100644 crypto/aes/tests/gcm_alias_tests.rs create mode 100644 crypto/modes/src/gcm.rs create mode 100644 crypto/modes/src/ghash.rs create mode 100644 crypto/modes/tests/acvp_gcm_tests.rs create mode 100644 crypto/modes/tests/acvp_gmac_tests.rs create mode 100644 crypto/modes/tests/common/acvp_gcm.rs create mode 100644 crypto/modes/tests/gcm_bc_java_tests.rs create mode 100644 crypto/modes/tests/gcm_tests.rs diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 00000000..6b0354a6 --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,9 @@ +{ + "permissions": { + "allow": [ + "Bash(git rebase *)", + "Bash(git status *)", + "Bash(git add *)" + ] + } +} diff --git a/cli/src/aead_mode_cmd.rs b/cli/src/aead_mode_cmd.rs new file mode 100644 index 00000000..c258e655 --- /dev/null +++ b/cli/src/aead_mode_cmd.rs @@ -0,0 +1,171 @@ +//! Shared plumbing for the AEAD subcommands: `aes{128,192,256}-gcm`. +//! +//! Parallel to [`crate::stream_mode_cmd`], but for [`bouncycastle::modes::Gcm`] rather than a +//! [`StreamCipherEncryptor`](bouncycastle::core::traits::StreamCipherEncryptor) mode: GCM carries +//! additional authenticated data and a tag, neither of which that trait has room for, so this +//! module drives `Gcm`'s inherent `do_update_aad` / `do_encrypt` / `do_decrypt` / `finish` API +//! directly instead of going through a shared trait. +//! +//! # On-the-wire format: `nonce || ciphertext || tag` +//! +//! `encrypt` writes the generated 12-byte nonce first, then the ciphertext as it streams, then the +//! 16-byte tag once stdin is exhausted. `decrypt` reads the 12-byte nonce first, then streams the +//! rest of stdin through the inline decryptor -- which, per [`SimpleCipherDecryptor`]'s contract, +//! holds back the last 16 bytes it has seen because they might be the tag -- and checks the tag on +//! `do_final`. +//! +//! # The exit code is the signal, not the output +//! +//! On a tag failure, `decrypt` has **already written plaintext to stdout**: the inline decryptor +//! releases bytes as they clear the tail hold-back, well before the tag at the very end of the +//! stream can be checked. This is the same trade-off `Gcm`'s streaming API documents; a script that +//! needs to know before acting on the output must use the one-shot instead (not exposed by this +//! CLI) or check the exit code before trusting anything already written. On failure this command +//! prints `Error: authentication failed` to stderr and exits non-zero. +//! +//! # AAD +//! +//! `--aad ` or `--aad-file ` (binary or hex); if neither is given, AAD is empty. Fed to +//! the engine in one call before any ciphertext, matching SP 800-38D Algorithm 4's requirement that +//! AAD precede data. + +use crate::helpers::{read_from_file, write_bytes_or_hex}; +use bouncycastle::core::key_material::KeyMaterial; +use bouncycastle::core::traits::{ + ElectronicCodeBook, SimpleCipherDecryptor, SimpleCipherEncryptor, +}; +use bouncycastle::hex; +use bouncycastle::modes::{Decrypting, Encrypting, Gcm}; +use std::io; +use std::io::{Read, Write}; +use std::process::exit; + +/// Bytes read from stdin per call. GCM has no batching advantage from a larger chunk the way CTR's +/// four-block path does, so this matches the other streaming commands' 1 KiB rather than needing +/// its own tuning. +const CHUNK_LEN: usize = 1024; + +/// Loads the additional authenticated data from `--aad` (hex) or `--aad-file` (binary or hex). +/// Empty if neither is given: AAD is optional, unlike the key. +pub(crate) fn load_aad(aad: &Option, aad_file: &Option) -> Vec { + if let Some(path) = aad_file { + read_from_file(path) + } else if let Some(hex_str) = aad { + hex::decode(hex_str).unwrap_or_else(|_| { + eprintln!("Error: `--aad` must be hex. Use `--aad-file` for raw bytes."); + exit(-1); + }) + } else { + Vec::new() + } +} + +/// Encrypts stdin to stdout under GCM: writes the generated nonce, then the ciphertext as it +/// streams, then the tag. +pub(crate) fn encrypt_gcm( + key: &KeyMaterial, + aad: &[u8], + output_hex: bool, +) where + P: ElectronicCodeBook, +{ + let (mut enc, nonce) = Gcm::::do_encrypt_init(key) + .unwrap_or_else(|e| { + eprintln!("Error: couldn't start encryption: {e:?}"); + exit(-1); + }); + write_bytes_or_hex(&nonce, output_hex); + + enc.do_update_aad(aad).unwrap_or_else(|e| { + eprintln!("Error: couldn't absorb the additional authenticated data: {e:?}"); + exit(-1); + }); + + let mut buf = [0u8; CHUNK_LEN]; + loop { + let n = io::stdin().read(&mut buf).unwrap_or_else(|e| { + eprintln!("Error: failed to read from stdin: {e}"); + exit(-1); + }); + if n == 0 { + break; + } + enc.do_encrypt(&mut buf[..n]).unwrap_or_else(|e| { + eprintln!("Error: encryption failed: {e:?}"); + exit(-1); + }); + write_bytes_or_hex(&buf[..n], output_hex); + } + + let tag = enc.finish(); + write_bytes_or_hex(&tag, output_hex); + finish(output_hex); +} + +/// Decrypts stdin to stdout under GCM: reads the 12-byte nonce, streams the rest through the +/// inline decryptor, and checks the tag on `do_final`. See the module docs for why plaintext may +/// already be written to stdout by the time a tag failure is reported. +pub(crate) fn decrypt_gcm( + key: &KeyMaterial, + aad: &[u8], + output_hex: bool, +) where + P: ElectronicCodeBook, +{ + let mut nonce = [0u8; 12]; + if let Err(e) = io::stdin().read_exact(&mut nonce) { + eprintln!( + "Error: input too short to contain the 12-byte nonce that `encrypt` writes first ({e})." + ); + exit(-1); + } + + let mut dec = Gcm::::do_decrypt_init(key, &nonce) + .unwrap_or_else(|e| { + eprintln!("Error: couldn't start decryption: {e:?}"); + exit(-1); + }); + dec.do_update_aad(aad).unwrap_or_else(|e| { + eprintln!("Error: couldn't absorb the additional authenticated data: {e:?}"); + exit(-1); + }); + + let mut buf = [0u8; CHUNK_LEN]; + loop { + let n = io::stdin().read(&mut buf).unwrap_or_else(|e| { + eprintln!("Error: failed to read from stdin: {e}"); + exit(-1); + }); + if n == 0 { + break; + } + let out_len = dec.update_out_len(n); + let mut out = vec![0u8; out_len]; + dec.do_update_out(&buf[..n], &mut out).unwrap_or_else(|e| { + eprintln!("Error: decryption failed: {e:?}"); + exit(-1); + }); + write_bytes_or_hex(&out, output_hex); + } + + if let Err(e) = dec.do_final() { + // Whatever plaintext was already written above stands; the exit code is the signal a + // script must check (see the module docs). + io::stdout().flush().ok(); + eprintln!("Error: authentication failed: {e:?}"); + exit(-1); + } + + finish(output_hex); +} + +/// Flushes stdout, and adds the trailing newline the hex-output commands all emit. +fn finish(output_hex: bool) { + if output_hex { + println!(); + } + io::stdout().flush().unwrap_or_else(|e| { + eprintln!("Error: failed to flush stdout: {e}"); + exit(-1); + }); +} diff --git a/cli/src/aes_gcm_cmd.rs b/cli/src/aes_gcm_cmd.rs new file mode 100644 index 00000000..dee87953 --- /dev/null +++ b/cli/src/aes_gcm_cmd.rs @@ -0,0 +1,82 @@ +//! AES-GCM authenticated encryption and decryption, streaming stdin to stdout. +//! +//! Only the mode wiring lives here: the nonce/tag framing, AAD loading and stdin streaming are in +//! [`crate::aead_mode_cmd`], shared across all three key lengths. See that module for the +//! command-line contract (`nonce || ciphertext || tag`, the AAD flags, and why a tag failure may be +//! reported after plaintext has already reached stdout). +//! +//! GCM (NIST SP 800-38D) is authenticated: unlike `aes*-cbc`, `aes*-cfb`, `aes*-cfb8` and +//! `aes*-ctr`, tampering with the ciphertext, the AAD or the nonce is detected rather than merely +//! producing wrong plaintext. The nonce is 12 bytes and the tag 16 (128-bit, the maximum SP +//! 800-38D Sec 5.2.1.2 allows); a fresh nonce is generated per `encrypt` and there is no `--iv` +//! flag, for the same reason as the other modes -- and doubly so here, since a repeated GCM nonce +//! also lets an attacker recover the hash subkey (SP 800-38D Appendix A). + +use crate::aead_mode_cmd::{decrypt_gcm, encrypt_gcm, load_aad}; +use crate::block_mode_cmd::{BlockModeAction, load_key}; +use bouncycastle::aes::{AES_128, AES_192, AES_256}; +use bouncycastle::core::key_material::KeyMaterial; +use bouncycastle::core::traits::ElectronicCodeBook; + +pub(crate) fn aes128_gcm_cmd( + action: &BlockModeAction, + key: &Option, + key_file: &Option, + aad: &Option, + aad_file: &Option, + output_hex: bool, +) { + run::( + action, + &load_key::<16>(key, key_file, "AES-128"), + &load_aad(aad, aad_file), + output_hex, + ); +} + +pub(crate) fn aes192_gcm_cmd( + action: &BlockModeAction, + key: &Option, + key_file: &Option, + aad: &Option, + aad_file: &Option, + output_hex: bool, +) { + run::( + action, + &load_key::<24>(key, key_file, "AES-192"), + &load_aad(aad, aad_file), + output_hex, + ); +} + +pub(crate) fn aes256_gcm_cmd( + action: &BlockModeAction, + key: &Option, + key_file: &Option, + aad: &Option, + aad_file: &Option, + output_hex: bool, +) { + run::( + action, + &load_key::<32>(key, key_file, "AES-256"), + &load_aad(aad, aad_file), + output_hex, + ); +} + +/// Dispatches to the shared AEAD streaming loops with `Gcm`'s 128-bit tag. +fn run( + action: &BlockModeAction, + key: &KeyMaterial, + aad: &[u8], + output_hex: bool, +) where + P: ElectronicCodeBook, +{ + match action { + BlockModeAction::Encrypt => encrypt_gcm::(key, aad, output_hex), + BlockModeAction::Decrypt => decrypt_gcm::(key, aad, output_hex), + } +} diff --git a/cli/src/main.rs b/cli/src/main.rs index 2b26315b..7b42346a 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -1,8 +1,10 @@ +mod aead_mode_cmd; mod aes_cbc_cmd; mod aes_cfb8_cmd; mod aes_cfb_cmd; mod aes_ctr_cmd; mod aes_ecb_cmd; +mod aes_gcm_cmd; mod block_mode_cmd; mod encoders_cmd; mod helpers; @@ -704,6 +706,118 @@ enum Subcommands { x: bool, }, + /// AES-128 in GCM (NIST SP 800-38D), streaming stdin to stdout. + /// + /// AUTHENTICATED, unlike the other AES modes here: tampering with the ciphertext, the AAD or + /// the nonce is detected rather than merely producing wrong plaintext. + /// + /// On `encrypt`, a fresh nonce is generated and written as the FIRST 12 BYTES of the output, + /// the ciphertext follows, and the 16-byte tag is written last. `decrypt` reads the nonce back + /// from the first 12 bytes of input and streams the rest, checking the tag once input is + /// exhausted. There is deliberately no `--iv` flag: a repeated GCM nonce is worse than merely + /// unwise, since it lets an attacker recover the hash subkey (SP 800-38D Appendix A). + /// + /// `--aad` (hex) or `--aad-file` (binary or hex) supply the additional authenticated data, + /// which is covered by the tag but not encrypted; if neither is given, AAD is empty. + /// + /// Input may be ANY length: GCM needs no padding. + /// + /// WARNING: on `decrypt`, a tag failure may be reported only after plaintext has already been + /// written to stdout, because this command streams the inline decryptor. A script MUST check + /// the exit code before trusting anything already written; on failure this command prints + /// `Error: authentication failed` and exits non-zero. + /// + /// Note: in production uses, secrets should not be passed on the command-line because they get + /// logged in shell history. Use the file-based input instead. + AES128_GCM { + action: BlockModeAction, + + /// The 16-byte AES key in hex. + /// The `key_file` option is preferred to avoid leaving key material in command history. + #[arg(long)] + key: Option, + + /// A file containing the 16-byte AES key, in binary or hex. + /// If both key and key_file options are provided, the file will be used. + #[arg(short, long)] + key_file: Option, + + /// The additional authenticated data, in hex. Covered by the tag but not encrypted. + #[arg(long)] + aad: Option, + + /// A file containing the additional authenticated data, in binary or hex. + /// If both aad and aad_file options are provided, the file will be used. + #[arg(long)] + aad_file: Option, + + #[arg(short)] + /// Output in hex format. + x: bool, + }, + + /// AES-192 in GCM (NIST SP 800-38D), streaming stdin to stdout. + /// + /// See `aes128-gcm` for the nonce/tag framing, the AAD flags and the warnings; only the key + /// length differs. + AES192_GCM { + action: BlockModeAction, + + /// The 24-byte AES key in hex. + /// The `key_file` option is preferred to avoid leaving key material in command history. + #[arg(long)] + key: Option, + + /// A file containing the 24-byte AES key, in binary or hex. + /// If both key and key_file options are provided, the file will be used. + #[arg(short, long)] + key_file: Option, + + /// The additional authenticated data, in hex. Covered by the tag but not encrypted. + #[arg(long)] + aad: Option, + + /// A file containing the additional authenticated data, in binary or hex. + /// If both aad and aad_file options are provided, the file will be used. + #[arg(long)] + aad_file: Option, + + #[arg(short)] + /// Output in hex format. + x: bool, + }, + + /// AES-256 in GCM (NIST SP 800-38D), streaming stdin to stdout. + /// + /// See `aes128-gcm` for the nonce/tag framing, the AAD flags and the warnings; only the key + /// length differs. + AES256_GCM { + action: BlockModeAction, + + /// The 32-byte AES key in hex. + /// The `key_file` option is preferred to avoid leaving key material in command history. + #[arg(long)] + key: Option, + + /// A file containing the 32-byte AES key, in binary or hex. + /// If both key and key_file options are provided, the file will be used. + #[arg(short, long)] + key_file: Option, + + /// The additional authenticated data, in hex. Covered by the tag but not encrypted. + #[arg(long)] + aad: Option, + + /// A file containing the additional authenticated data, in binary or hex. + /// If both aad and aad_file options are provided, the file will be used. + #[arg(long)] + aad_file: Option, + + #[arg(short)] + /// Output in hex format. + x: bool, + }, + /// AES-128 in ECB mode (NIST SP 800-38A Sec 6.1), streaming stdin to stdout. /// /// WARNING: ECB is NOT a confidentiality mode for data. Under a given key every plaintext @@ -1129,6 +1243,15 @@ fn main() { Some(Subcommands::AES256_CTR { action, key, key_file, x }) => { aes_ctr_cmd::aes256_ctr_cmd(action, key, key_file, *x); } + Some(Subcommands::AES128_GCM { action, key, key_file, aad, aad_file, x }) => { + aes_gcm_cmd::aes128_gcm_cmd(action, key, key_file, aad, aad_file, *x); + } + Some(Subcommands::AES192_GCM { action, key, key_file, aad, aad_file, x }) => { + aes_gcm_cmd::aes192_gcm_cmd(action, key, key_file, aad, aad_file, *x); + } + Some(Subcommands::AES256_GCM { action, key, key_file, aad, aad_file, x }) => { + aes_gcm_cmd::aes256_gcm_cmd(action, key, key_file, aad, aad_file, *x); + } Some(Subcommands::AES128_ECB { action, key, key_file, x }) => { aes_ecb_cmd::aes128_ecb_cmd(action, key, key_file, *x); } diff --git a/cli/tests/aes_gcm_cli_tests.rs b/cli/tests/aes_gcm_cli_tests.rs new file mode 100644 index 00000000..b82057d7 --- /dev/null +++ b/cli/tests/aes_gcm_cli_tests.rs @@ -0,0 +1,361 @@ +//! Tests for the `aes128-gcm` / `aes192-gcm` / `aes256-gcm` subcommands. +//! +//! These drive the built `bc-rust` binary as a subprocess, exactly as `aes_ctr_cli_tests.rs` does +//! and for the same reason: the command-line contract -- `nonce || ciphertext || tag` framing, the +//! `--aad` flags, exit codes, key loading -- is not reachable from the library API. GCM's algorithm +//! correctness is pinned in `bouncycastle-modes`' ACVP, GMAC and bc-java known-answer suites; what +//! is worth testing here is the wiring: that AAD actually reaches the tag, that a tampered byte or +//! tag is rejected with a non-zero exit, and that decrypt still writes whatever plaintext it +//! recovered before the failure (the streaming trade-off `aead_mode_cmd.rs` documents). +//! +//! There is no OpenSSL cross-check here: `openssl enc` does not do AEAD, so unlike the CTR/CFB/CBC +//! suites there is no equivalent vector to play through the pipe. +//! +//! `CARGO_BIN_EXE_bc-rust` is set by cargo for integration tests and points at the binary for the +//! current profile. +//! +//! # A note on this environment +//! +//! In this session's environment, every subprocess invocation of the **debug** `bc-rust` binary -- +//! including a bare `--help`, and every existing `aes_ctr_cli_tests.rs` case -- crashes with a +//! stack overflow before reaching any command logic (`thread 'main' has overflowed its stack`). +//! `git stash` reproduced it on the unmodified `main.rs` too, so it predates this change and is +//! unrelated to GCM; a release build (`cargo test --release -p cli`) does not hit it, which points +//! at clap's derive-generated parser code being large enough, unoptimized, to need more than the +//! default debug-build stack on this toolchain -- plausibly worsened by how many subcommands and +//! doc-comment-derived help strings this binary now has. This file's tests were run and pass +//! against the release build; `cargo test -p cli` (debug) will need that issue investigated +//! separately. + +use std::io::{ErrorKind, Write}; +use std::process::{Command, Output, Stdio}; +use std::thread; + +/// The path to the binary under test, resolved by cargo. +const BC_RUST: &str = env!("CARGO_BIN_EXE_bc-rust"); + +/// GCM's nonce, like CTR's, is 12 bytes. +const NONCE_LEN: usize = 12; +/// The (only) tag length these commands support: 128 bits. +const TAG_LEN: usize = 16; + +const KEY_128: &str = "2b7e151628aed2a6abf7158809cf4f3c"; +const KEY_192: &str = "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b"; +const KEY_256: &str = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"; + +const AAD: &str = "deadbeef"; + +const PLAINTEXT: &str = concat!( + "6bc1bee22e409f96e93d7e117393172a", + "ae2d8a571e03ac9c9eb76fac45af8e51", + "30c81c46a35ce411e5fbc1191a0a52ef", + "f69f2445df4f9b17ad2b417be66c3710", + "0011223344", +); + +/// See `aes_ctr_cli_tests.rs::run` for why stdin is written from a separate thread and why +/// `BrokenPipe` is not a harness failure. +fn run(args: &[&str], stdin_bytes: &[u8]) -> Output { + let mut child = Command::new(BC_RUST) + .args(args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("failed to spawn bc-rust"); + + let mut stdin = child.stdin.take().expect("stdin piped"); + let payload = stdin_bytes.to_vec(); + let writer = thread::spawn(move || match stdin.write_all(&payload) { + Ok(()) => {} + Err(e) if e.kind() == ErrorKind::BrokenPipe => {} + Err(e) => panic!("failed to write to stdin: {e}"), + }); + + let output = child.wait_with_output().expect("failed to wait for bc-rust"); + writer.join().expect("the stdin writer thread panicked"); + output +} + +fn run_ok(args: &[&str], stdin_bytes: &[u8]) -> Vec { + let out = run(args, stdin_bytes); + assert!( + out.status.success(), + "expected success from {args:?}, got {:?}\nstderr: {}", + out.status, + String::from_utf8_lossy(&out.stderr) + ); + out.stdout +} + +fn run_err(args: &[&str], stdin_bytes: &[u8]) -> (String, Vec) { + let out = run(args, stdin_bytes); + assert!( + !out.status.success(), + "expected failure from {args:?}, but it succeeded\nstdout: {:?}", + String::from_utf8_lossy(&out.stdout) + ); + (String::from_utf8_lossy(&out.stderr).into_owned(), out.stdout) +} + +fn unhex(s: &str) -> Vec { + assert!(s.len().is_multiple_of(2), "hex string must have even length"); + (0..s.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&s[i..i + 2], 16).expect("valid hex")) + .collect() +} + +fn pseudo_random(len: usize, seed: u32) -> Vec { + let mut state = seed.wrapping_mul(2_654_435_761).wrapping_add(1); + (0..len) + .map(|_| { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + (state >> 24) as u8 + }) + .collect() +} + +// ---- round trips --------------------------------------------------------------------------- + +#[test] +fn encrypt_then_decrypt_round_trips_with_aad() { + for (cmd, key) in [("aes128-gcm", KEY_128), ("aes192-gcm", KEY_192), ("aes256-gcm", KEY_256)] { + let plaintext = unhex(PLAINTEXT); + let ciphertext = run_ok(&[cmd, "encrypt", "--key", key, "--aad", AAD], &plaintext); + assert_eq!( + ciphertext.len(), + plaintext.len() + NONCE_LEN + TAG_LEN, + "{cmd}: nonce, ciphertext and tag" + ); + let recovered = run_ok(&[cmd, "decrypt", "--key", key, "--aad", AAD], &ciphertext); + assert_eq!(recovered, plaintext, "{cmd}: round trip"); + } +} + +/// AAD is optional; omitting it on both sides round-trips too. +#[test] +fn round_trips_with_no_aad() { + let plaintext = unhex(PLAINTEXT); + let ciphertext = run_ok(&["aes128-gcm", "encrypt", "--key", KEY_128], &plaintext); + let recovered = run_ok(&["aes128-gcm", "decrypt", "--key", KEY_128], &ciphertext); + assert_eq!(recovered, plaintext); +} + +/// Any length round-trips with the ciphertext plus a fixed 12+16-byte overhead. +#[test] +fn any_input_length_is_accepted_and_round_trips() { + for len in 0..=(2 * 16 + 1) { + let plaintext = pseudo_random(len, len as u32); + let ciphertext = + run_ok(&["aes128-gcm", "encrypt", "--key", KEY_128, "--aad", AAD], &plaintext); + assert_eq!( + ciphertext.len(), + len + NONCE_LEN + TAG_LEN, + "len {len}: nonce, equal-length body, tag" + ); + let recovered = + run_ok(&["aes128-gcm", "decrypt", "--key", KEY_128, "--aad", AAD], &ciphertext); + assert_eq!(recovered, plaintext, "len {len}: round trip"); + } +} + +/// Round trips at sizes that straddle the 1 KiB streaming chunk and the tag-hold-back boundary. +#[test] +fn round_trips_across_chunk_boundaries() { + for size in [0usize, 1, 15, 16, 17, 1023, 1024, 1025, 4096, 4099, 65536] { + let plaintext = pseudo_random(size, size as u32); + let ciphertext = + run_ok(&["aes128-gcm", "encrypt", "--key", KEY_128, "--aad", AAD], &plaintext); + let recovered = + run_ok(&["aes128-gcm", "decrypt", "--key", KEY_128, "--aad", AAD], &ciphertext); + assert_eq!(recovered, plaintext, "{size} bytes should round trip"); + } +} + +/// A fresh nonce per invocation. +#[test] +fn each_invocation_uses_a_fresh_nonce() { + let plaintext = unhex(PLAINTEXT); + let mut seen = std::collections::BTreeSet::new(); + + for _ in 0..8 { + let ciphertext = run_ok(&["aes128-gcm", "encrypt", "--key", KEY_128], &plaintext); + let nonce = ciphertext[..NONCE_LEN].to_vec(); + assert!(seen.insert(nonce), "the CLI reused a nonce across invocations"); + let recovered = run_ok(&["aes128-gcm", "decrypt", "--key", KEY_128], &ciphertext); + assert_eq!(recovered, plaintext); + } +} + +#[test] +fn hex_output_matches_binary_output() { + let plaintext = unhex(PLAINTEXT); + let binary = run_ok(&["aes128-gcm", "encrypt", "--key", KEY_128], &plaintext); + let hex_out = run_ok(&["aes128-gcm", "encrypt", "--key", KEY_128, "-x"], &plaintext); + + let hex_str = String::from_utf8(hex_out).expect("hex output is text"); + // The nonce differs per run, so compare lengths and that the body decodes to something of the + // same shape rather than the exact bytes. + assert_eq!(hex_str.trim_end().len(), binary.len() * 2); + assert_eq!(unhex(hex_str.trim_end()).len(), binary.len()); +} + +// ---- AAD ------------------------------------------------------------------------------------- + +/// Decrypting with the wrong AAD must fail authentication. +#[test] +fn wrong_aad_fails_authentication() { + let plaintext = unhex(PLAINTEXT); + let ciphertext = run_ok(&["aes128-gcm", "encrypt", "--key", KEY_128, "--aad", AAD], &plaintext); + let (stderr, _stdout) = + run_err(&["aes128-gcm", "decrypt", "--key", KEY_128, "--aad", "00112233"], &ciphertext); + assert!( + stderr.contains("authentication failed"), + "stderr should report authentication failure: {stderr}" + ); +} + +/// Encrypting with AAD and decrypting with none (or vice versa) must fail authentication too. +#[test] +fn missing_aad_on_one_side_fails_authentication() { + let plaintext = unhex(PLAINTEXT); + let ciphertext = run_ok(&["aes128-gcm", "encrypt", "--key", KEY_128, "--aad", AAD], &plaintext); + let (stderr, _stdout) = run_err(&["aes128-gcm", "decrypt", "--key", KEY_128], &ciphertext); + assert!( + stderr.contains("authentication failed"), + "stderr should report authentication failure: {stderr}" + ); +} + +// ---- tamper detection -------------------------------------------------------------------------- + +/// A tampered ciphertext byte must be rejected, non-zero exit. +#[test] +fn a_tampered_ciphertext_byte_is_rejected() { + let plaintext = unhex(PLAINTEXT); + let mut ciphertext = + run_ok(&["aes128-gcm", "encrypt", "--key", KEY_128, "--aad", AAD], &plaintext); + let body_start = NONCE_LEN; + ciphertext[body_start] ^= 0x01; + + let (stderr, _stdout) = + run_err(&["aes128-gcm", "decrypt", "--key", KEY_128, "--aad", AAD], &ciphertext); + assert!( + stderr.contains("authentication failed"), + "stderr should report authentication failure: {stderr}" + ); +} + +/// A tampered tag byte must be rejected too. +#[test] +fn a_tampered_tag_byte_is_rejected() { + let plaintext = unhex(PLAINTEXT); + let mut ciphertext = + run_ok(&["aes128-gcm", "encrypt", "--key", KEY_128, "--aad", AAD], &plaintext); + let last = ciphertext.len() - 1; + ciphertext[last] ^= 0x01; + + let (stderr, _stdout) = + run_err(&["aes128-gcm", "decrypt", "--key", KEY_128, "--aad", AAD], &ciphertext); + assert!( + stderr.contains("authentication failed"), + "stderr should report authentication failure: {stderr}" + ); +} + +/// The streaming trade-off `aead_mode_cmd.rs` documents: on a tag failure, whatever plaintext the +/// inline decryptor had already released before the tag check stands on stdout. For a message +/// longer than the tag, that is everything except (at most) the last `TAG_LEN` bytes. +#[test] +fn decrypt_still_writes_the_plaintext_it_had_already_released_on_forgery() { + let plaintext = pseudo_random(4096, 7); + let mut ciphertext = + run_ok(&["aes128-gcm", "encrypt", "--key", KEY_128, "--aad", AAD], &plaintext); + let last = ciphertext.len() - 1; + ciphertext[last] ^= 0x01; // corrupt the tag only, leaving the ciphertext body intact + + let out = run(&["aes128-gcm", "decrypt", "--key", KEY_128, "--aad", AAD], &ciphertext); + assert!(!out.status.success(), "a corrupted tag must be rejected"); + assert!( + out.stdout.len() >= plaintext.len() - TAG_LEN, + "most of the plaintext should already have reached stdout: got {} of {} bytes", + out.stdout.len(), + plaintext.len() + ); + assert_eq!( + &out.stdout[..out.stdout.len().min(plaintext.len())], + &plaintext[..out.stdout.len().min(plaintext.len())], + "the released bytes must be the genuine plaintext, not garbage" + ); +} + +// ---- short input --------------------------------------------------------------------------- + +/// Input shorter than the 12-byte nonce is rejected. +#[test] +fn decrypt_input_shorter_than_the_nonce_is_rejected() { + for len in [0usize, 1, 11] { + let (stderr, _stdout) = + run_err(&["aes128-gcm", "decrypt", "--key", KEY_128], &pseudo_random(len, 1)); + assert!( + stderr.contains("12-byte nonce"), + "stderr should explain the missing nonce (len {len}): {stderr}" + ); + } +} + +/// Input that has a nonce but not a full tag is rejected as an authentication failure (there is +/// nothing to check the tag against). +#[test] +fn decrypt_input_with_a_nonce_but_no_full_tag_is_rejected() { + // `encrypt` on empty input yields exactly nonce || tag; drop the last tag byte. + let nonce_and_tag = run_ok(&["aes128-gcm", "encrypt", "--key", KEY_128], &[]); + let short = &nonce_and_tag[..nonce_and_tag.len() - 1]; + let (stderr, _stdout) = run_err(&["aes128-gcm", "decrypt", "--key", KEY_128], short); + assert!( + stderr.contains("authentication failed"), + "stderr should report authentication failure: {stderr}" + ); +} + +// ---- key handling --------------------------------------------------------------------------- + +#[test] +fn a_key_of_the_wrong_length_is_rejected() { + let (stderr, _stdout) = + run_err(&["aes256-gcm", "encrypt", "--key", KEY_128], &unhex(PLAINTEXT)); + assert!(stderr.contains("32-byte key"), "stderr should name the expected length: {stderr}"); + assert!(stderr.contains("16 bytes"), "stderr should name the supplied length: {stderr}"); +} + +#[test] +fn a_missing_key_is_rejected() { + let (stderr, _stdout) = run_err(&["aes128-gcm", "encrypt"], &unhex(PLAINTEXT)); + assert!(stderr.contains("--key"), "stderr should mention the key options: {stderr}"); +} + +// ---- discoverability -------------------------------------------------------------------------- + +#[test] +fn the_subcommands_are_listed_in_help() { + let out = run_ok(&["--help"], &[]); + let help = String::from_utf8_lossy(&out); + for cmd in ["aes128-gcm", "aes192-gcm", "aes256-gcm"] { + assert!(help.contains(cmd), "`--help` should list {cmd}"); + } +} + +/// The per-command help must document the AAD flags and the authenticated-but-streamed warning. +#[test] +fn per_command_help_documents_aad_and_the_streaming_warning() { + let out = run_ok(&["aes128-gcm", "--help"], &[]); + let help = String::from_utf8_lossy(&out); + assert!(help.contains("aad"), "help should mention AAD: {help}"); + assert!( + help.to_lowercase().contains("authenticat"), + "help should mention authentication: {help}" + ); +} diff --git a/crypto/aes/src/gcm.rs b/crypto/aes/src/gcm.rs new file mode 100644 index 00000000..76b9fa17 --- /dev/null +++ b/crypto/aes/src/gcm.rs @@ -0,0 +1,118 @@ +//! Type aliases for AES in GCM (NIST SP 800-38D). +//! +//! `bouncycastle-modes` is deliberately cipher-agnostic, so `Gcm` takes the permutation, the +//! direction, and the `KEY_LEN` / `TAG_LEN` const parameters. These aliases pin the AES values and +//! fix the tag length at 128 bits, the maximum SP 800-38D Sec 5.2.1.2 allows. For a shorter tag +//! (96, 104, 112 or 120 bits), name `bouncycastle_modes::Gcm` directly with the desired `TAG_LEN`. +//! +//! The nonce is always [`bouncycastle_modes::GCM_NONCE_LEN`] (12 bytes / 96 bits): `Gcm` has no +//! nonce-length parameter at all, unlike `Ctr`'s aliases, because SP 800-38D's `len(IV) != 96` +//! branch (deriving `J0` from a GHASH of the IV) is not implemented -- see the `gcm` module docs in +//! `bouncycastle-modes`. + +use crate::{AES_128, AES_192, AES_256}; +use bouncycastle_modes::Gcm; + +/// AES-128 in GCM with a 128-bit tag. `Dir` is [`bouncycastle_modes::Encrypting`] or +/// [`bouncycastle_modes::Decrypting`]; the wrong direction is a compile error, not a runtime check. +/// +/// The nonce is generated by the encryptor and returned; it is never supplied. See the `gcm` module +/// docs in `bouncycastle-modes` for the detached-tag and inline `ciphertext || tag` views this type +/// exposes, and for the security considerations (nonce uniqueness above all). +/// +/// ``` +/// use bouncycastle_aes::AES_GCM_128; +/// use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +/// use bouncycastle_modes::{Decrypting, Encrypting}; +/// +/// let key = KeyMaterial::<16>::from_bytes_as_type(&[0x42; 16], KeyType::SymmetricCipherKey) +/// .expect("a 16-byte symmetric cipher key"); +/// let aad = b"header, sent in the clear"; +/// let mut data = *b"attack at dawn!!"; +/// +/// // Detached tag, one-shot. +/// let (nonce, tag) = AES_GCM_128::::encrypt_detached(&key, aad, &mut data).unwrap(); +/// AES_GCM_128::::decrypt_detached(&key, &nonce, aad, &mut data, &tag).unwrap(); +/// assert_eq!(&data, b"attack at dawn!!"); +/// ``` +/// +/// Inline `ciphertext || tag`, through [`SimpleCipherEncryptor`](bouncycastle_core::traits::SimpleCipherEncryptor) / [`SimpleCipherDecryptor`](bouncycastle_core::traits::SimpleCipherDecryptor): +/// +/// ``` +/// use bouncycastle_aes::AES_GCM_128; +/// use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +/// use bouncycastle_core::traits::{SimpleCipherDecryptor, SimpleCipherEncryptor}; +/// use bouncycastle_modes::{Decrypting, Encrypting}; +/// +/// let key = KeyMaterial::<16>::from_bytes_as_type(&[0x42; 16], KeyType::SymmetricCipherKey).unwrap(); +/// let aad = b"associated data"; +/// let message = b"a message of no particular length at all"; +/// +/// let mut ciphertext = vec![0u8; AES_GCM_128::::encrypt_out_len(message.len())]; +/// let (nonce, written) = +/// AES_GCM_128::::encrypt_out(&key, message, &mut ciphertext).unwrap(); +/// assert_eq!(written, ciphertext.len()); +/// +/// let mut plaintext = vec![0u8; AES_GCM_128::::decrypt_out_max_len(ciphertext.len())]; +/// let n = AES_GCM_128::::decrypt_out(&key, &nonce, &ciphertext, &mut plaintext).unwrap(); +/// assert_eq!(&plaintext[..n], &message[..]); +/// ``` +/// +/// Streaming, with AAD fed via the inherent `do_update_aad` before any data: +/// +/// ``` +/// use bouncycastle_aes::AES_GCM_128; +/// use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +/// use bouncycastle_core::traits::{SimpleCipherDecryptor, SimpleCipherEncryptor}; +/// use bouncycastle_modes::{Decrypting, Encrypting}; +/// +/// let key = KeyMaterial::<16>::from_bytes_as_type(&[0x99; 16], KeyType::SymmetricCipherKey).unwrap(); +/// let (mut enc, nonce) = AES_GCM_128::::do_encrypt_init(&key).unwrap(); +/// enc.do_update_aad(b"header").unwrap(); +/// let mut ct = [0u8; 5]; +/// enc.do_update_out(b"hello", &mut ct).unwrap(); +/// let (tag, tag_len) = enc.do_final().unwrap(); +/// +/// let mut dec = AES_GCM_128::::do_decrypt_init(&key, &nonce).unwrap(); +/// dec.do_update_aad(b"header").unwrap(); +/// let mut full_ct = ct.to_vec(); +/// full_ct.extend_from_slice(&tag[..tag_len]); +/// let mut pt = vec![0u8; full_ct.len()]; +/// let n = dec.do_update_out(&full_ct, &mut pt).unwrap(); +/// let (_last, last_len) = dec.do_final().unwrap(); +/// assert_eq!(&pt[..n + last_len], b"hello"); +/// ``` +#[allow(non_camel_case_types)] +pub type AES_GCM_128 = Gcm; + +/// AES-192 in GCM with a 128-bit tag. See [`AES_GCM_128`]. +/// +/// ``` +/// use bouncycastle_aes::AES_GCM_192; +/// use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +/// use bouncycastle_modes::{Decrypting, Encrypting}; +/// +/// let key = KeyMaterial::<24>::from_bytes_as_type(&[0x24; 24], KeyType::SymmetricCipherKey).unwrap(); +/// let mut data = *b"a 192-bit key message!!"; +/// let (nonce, tag) = AES_GCM_192::::encrypt_detached(&key, b"aad", &mut data).unwrap(); +/// AES_GCM_192::::decrypt_detached(&key, &nonce, b"aad", &mut data, &tag).unwrap(); +/// assert_eq!(&data, b"a 192-bit key message!!"); +/// ``` +#[allow(non_camel_case_types)] +pub type AES_GCM_192 = Gcm; + +/// AES-256 in GCM with a 128-bit tag. See [`AES_GCM_128`]. +/// +/// ``` +/// use bouncycastle_aes::AES_GCM_256; +/// use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +/// use bouncycastle_modes::{Decrypting, Encrypting}; +/// +/// let key = KeyMaterial::<32>::from_bytes_as_type(&[0x32; 32], KeyType::SymmetricCipherKey).unwrap(); +/// let mut data = *b"a 256-bit key message!!"; +/// let (nonce, tag) = AES_GCM_256::::encrypt_detached(&key, b"aad", &mut data).unwrap(); +/// AES_GCM_256::::decrypt_detached(&key, &nonce, b"aad", &mut data, &tag).unwrap(); +/// assert_eq!(&data, b"a 256-bit key message!!"); +/// ``` +#[allow(non_camel_case_types)] +pub type AES_GCM_256 = Gcm; diff --git a/crypto/aes/src/lib.rs b/crypto/aes/src/lib.rs index 6654cc73..2fce33d5 100644 --- a/crypto/aes/src/lib.rs +++ b/crypto/aes/src/lib.rs @@ -72,6 +72,10 @@ //! [`AES_ECB_128`], [`AES_ECB_192`] and [`AES_ECB_256`] give ECB (Sec 6.1), which takes a padding //! scheme like CBC and has no IV, for interoperability and test vectors only -- see //! [A block permutation is not a cipher](#a-block-permutation-is-not-a-cipher). +//! [`AES_GCM_128`], [`AES_GCM_192`] and [`AES_GCM_256`] give GCM (NIST SP 800-38D), the +//! authenticated mode built from CTR and a universal hash: a 96-bit nonce and a 128-bit tag, with +//! both a detached-tag streaming API and an inline `ciphertext || tag` view -- see the `gcm` module +//! docs in `bouncycastle-modes` for the full shape and the security considerations. //! //! CBC is a block cipher, so it is defined only on whole blocks and the alias carries a padding //! scheme to bridge the difference; the CFB modes and CTR are stream ciphers and take any length @@ -224,6 +228,7 @@ mod cfb; mod cfb8; mod ctr; mod ecb; +mod gcm; mod padded_mode; mod round; mod sbox; @@ -235,3 +240,4 @@ pub use cfb::{AES_CFB_128, AES_CFB_192, AES_CFB_256}; pub use cfb8::{AES_CFB8_128, AES_CFB8_192, AES_CFB8_256}; pub use ctr::{AES_CTR_128, AES_CTR_192, AES_CTR_256, CTR_NONCE_LEN}; pub use ecb::{AES_ECB_128, AES_ECB_192, AES_ECB_256}; +pub use gcm::{AES_GCM_128, AES_GCM_192, AES_GCM_256}; diff --git a/crypto/aes/tests/gcm_alias_tests.rs b/crypto/aes/tests/gcm_alias_tests.rs new file mode 100644 index 00000000..86ac7af9 --- /dev/null +++ b/crypto/aes/tests/gcm_alias_tests.rs @@ -0,0 +1,56 @@ +//! Tests for the AES-GCM aliases. +//! +//! The aliases are only type aliases, so what is worth testing is that they name the *right* type +//! at both directions, that all three key lengths reach the shared `SimpleCipherEncryptor` / +//! `SimpleCipherDecryptor` conformance suite (`TestFrameworkSimpleCipher`), and that a fresh nonce +//! is generated per encryption. Algorithm correctness itself is pinned by `bouncycastle-modes`' +//! ACVP and bc-java known-answer suites. + +use bouncycastle_aes::{AES_128, AES_GCM_128, AES_GCM_192, AES_GCM_256}; +use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +use bouncycastle_core_test_framework::symmetric_ciphers::TestFrameworkSimpleCipher; +use bouncycastle_modes::{Decrypting, Encrypting, Gcm}; + +fn key() -> KeyMaterial { + let bytes: [u8; N] = core::array::from_fn(|i| (i as u8).wrapping_mul(7).wrapping_add(1)); + KeyMaterial::::from_bytes_as_type(&bytes, KeyType::SymmetricCipherKey).expect("a valid key") +} + +/// The alias must resolve to exactly the type it claims to, at both directions. +#[test] +fn the_alias_names_the_expected_type() { + use core::mem::size_of; + + assert_eq!(size_of::>(), size_of::>()); + assert_eq!(size_of::>(), size_of::>()); +} + +/// All three key lengths satisfy the shared `SimpleCipherEncryptor`/`SimpleCipherDecryptor` +/// conformance suite -- the same one the padding adapters and the stream modes run. +#[test] +fn all_three_key_lengths_conform_to_the_simple_cipher_suite() { + let framework = TestFrameworkSimpleCipher::new(); + framework + .test_encryptor_decryptor::<16, 12, 16, AES_GCM_128, AES_GCM_128>(); + framework + .test_encryptor_decryptor::<24, 12, 16, AES_GCM_192, AES_GCM_192>(); + framework + .test_encryptor_decryptor::<32, 12, 16, AES_GCM_256, AES_GCM_256>(); +} + +/// The nonce is generated per encryption, so the same plaintext gives different ciphertext, and +/// each still round-trips. +#[test] +fn each_encryption_gets_a_fresh_nonce() { + let data = *b"the quick brown fox jumps over the lazy dog!!!"; + let mut seen = std::collections::BTreeSet::new(); + for _ in 0..16 { + let mut buf = data; + let (nonce, tag) = + AES_GCM_128::::encrypt_detached(&key::<16>(), b"aad", &mut buf).unwrap(); + assert!(seen.insert(nonce), "nonce repeated across encryptions"); + AES_GCM_128::::decrypt_detached(&key::<16>(), &nonce, b"aad", &mut buf, &tag) + .unwrap(); + assert_eq!(buf, data); + } +} diff --git a/crypto/modes/src/ctr.rs b/crypto/modes/src/ctr.rs index ca6e7704..20849aaa 100644 --- a/crypto/modes/src/ctr.rs +++ b/crypto/modes/src/ctr.rs @@ -247,6 +247,28 @@ where } } + /// As [`start`](Self::start), but the counter of the *next* block is `counter` instead of 0. + /// + /// GCM's GCTR (SP 800-38D Sec 6.5) runs the data through this mode starting at `inc32(J0)`, + /// whose counter field is `2` -- see `gcm.rs`. Crate-private because the public API's contract + /// is that a message starts at counter 0; only `gcm.rs` needs otherwise. + #[inline] + pub(crate) fn start_at(perm: P, nonce: [u8; INIT_DATA_LEN], counter: u64) -> Self { + Self::check_shape(); + debug_assert!( + counter < Self::BLOCK_LIMIT, + "start_at must not be handed an already-exhausted counter" + ); + Self { + perm, + nonce, + next_counter: counter, + keystream: Secret::new(), + used: BLOCK_LEN, + _dir: PhantomData, + } + } + /// `Tj = N | [j]m`: the nonce followed by the counter, big-endian, in the trailing `CTR_LEN` /// bytes. /// @@ -457,3 +479,52 @@ where self.apply(data) } } + +#[cfg(test)] +mod tests { + //! Unit tests for `start_at`, which is `pub(crate)` and so cannot be reached from + //! `tests/ctr_tests.rs` -- exactly the "high-risk code that cannot be reached through the + //! public API" case QUALITY_AND_STYLE.md carves out for a unit test here rather than an + //! integration test. + + use super::*; + use bouncycastle_aes::AES_128; + use bouncycastle_core::key_material::{KeyMaterial, KeyType}; + use bouncycastle_core::traits::ElectronicCodeBook; + + type ToyCtr = Ctr; + + fn key() -> KeyMaterial<16> { + KeyMaterial::<16>::from_bytes_as_type(&[0x5Au8; 16], KeyType::SymmetricCipherKey) + .expect("a valid AES-128 key") + } + + /// `start_at(.., 2)` must produce the same keystream as `start` after its first two blocks + /// (32 bytes) have been discarded. This is what lets GCM's GCTR (SP 800-38D Sec 6.5) begin at + /// `inc32(J0)`, whose counter field is 2 -- see `gcm.rs`. + #[test] + fn start_at_matches_start_after_discarding_blocks() { + let nonce = [0x11u8; 12]; + + let mut from_start = ToyCtr::start(AES_128::new(&key()).unwrap(), nonce); + let mut discarded = [0u8; 32]; + from_start.apply(&mut discarded).unwrap(); + + let mut from_start_at = ToyCtr::start_at(AES_128::new(&key()).unwrap(), nonce, 2); + + let mut a = [0x42u8; 48]; + let mut b = a; + from_start.apply(&mut a).unwrap(); + from_start_at.apply(&mut b).unwrap(); + assert_eq!(a, b, "start_at(.., 2) must agree with start() past its first two blocks"); + } + + /// The capacity left after starting at counter 2 is exactly `2^32 - 2` blocks -- the SP + /// 800-38D Sec 5.2.1.1 plaintext length bound (`len(P) <= 2^39 - 256` bits, i.e. `2^32 - 2` + /// 128-bit blocks) that GCM relies on `Ctr`'s existing "counter exhausted" error to enforce. + #[test] + fn start_at_capacity_is_block_limit_minus_the_starting_counter() { + let ctr = ToyCtr::start_at(AES_128::new(&key()).unwrap(), [0u8; 12], 2); + assert_eq!(ctr.remaining_capacity(), (ToyCtr::BLOCK_LIMIT - 2) * 16); + } +} diff --git a/crypto/modes/src/gcm.rs b/crypto/modes/src/gcm.rs new file mode 100644 index 00000000..fdc993a1 --- /dev/null +++ b/crypto/modes/src/gcm.rs @@ -0,0 +1,600 @@ +//! Galois/Counter Mode (NIST SP 800-38D), the authenticated encryption mode built from CTR +//! (Sec 6.5's GCTR) and the GHASH universal hash in `ghash.rs` (Sec 6.4). +//! +//! # Scope: a 96-bit nonce and a 96-128-bit tag +//! +//! [`Gcm`] has no `NONCE_LEN` parameter: the nonce is always [`GCM_NONCE_LEN`] (12) bytes, generated +//! by the encryptor from the library's default RNG (Sec 8.2.2's RBG-based construction, with an +//! empty free field so the whole IV is the random field). Sec 5.2.1.1: "For IVs, it is recommended +//! that implementations restrict support to the length of 96 bits, to promote interoperability, +//! efficiency, and simplicity of design." The `len(IV) != 96` branch of Algorithm 4 step 2 (deriving +//! `J0` from a GHASH of the IV) is not implemented; every IV this type produces or accepts is 96 +//! bits, so that branch is unreachable here. +//! +//! The tag length is a const generic `TAG_LEN`, checked at compile time to lie in `12..=16` bytes +//! (96, 104, 112, 120 or 128 bits -- Sec 5.2.1.2's five recommended values). The 32- and 64-bit tags +//! Sec 5.2.1.2 permits "for certain applications" (Appendix C) are not supported: Appendix C +//! requires the *controlling protocol* to bound packet size and invocation counts (its Tables 1 and +//! 2), which this library cannot enforce, so it does not offer the option. +//! +//! # Two views over the same engine +//! +//! [`Gcm`] exposes GCM through two APIs that share the same underlying state: +//! +//! * An **inherent, detached-tag streaming API** -- [`Gcm::do_update_aad`], [`Gcm::do_encrypt`] / +//! [`Gcm::do_decrypt`] (in place, nothing held back), and [`Gcm::finish`] -- plus the one-shots +//! [`Gcm::encrypt_detached`] / [`Gcm::encrypt_detached_rng`] / [`Gcm::decrypt_detached`]. This is +//! the spec's own interface: the tag is a separate value from the ciphertext (Algorithm 4's +//! `(C, T)`, Algorithm 5's separate `T` input). +//! * The [`SimpleCipherEncryptor`] / [`SimpleCipherDecryptor`] traits, with `FINAL_LEN = TAG_LEN`, +//! which give the *inline* `ciphertext || tag` layout, the one-shot `encrypt_out` / `decrypt_out`, +//! and the shared conformance suite. AAD has no place in that trait's signature, so use the +//! inherent [`Gcm::do_update_aad`] on the object it returns before feeding it any data; the two +//! views operate on the same `ghash` and `phase` state, so this composes correctly. +//! +//! AAD must be supplied before any plaintext or ciphertext: SP 800-38D Algorithm 4 absorbs `A` +//! before `C` in one GHASH pass, so AAD after data is [`SymmetricCipherError::StateError`] (empty +//! AAD after data is a no-op, since it changes nothing). +//! +//! # Usage Examples +//! +//! Detached tag, one-shot: +//! +//! ``` +//! use bouncycastle_aes::AES_128; +//! use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +//! use bouncycastle_modes::{Decrypting, Encrypting, Gcm}; +//! +//! type Aes128Gcm = Gcm; +//! +//! let key = KeyMaterial::<16>::from_bytes_as_type(&[0x42; 16], KeyType::SymmetricCipherKey) +//! .expect("a 16-byte symmetric cipher key"); +//! let aad = b"header, sent in the clear"; +//! let plaintext = *b"attack at dawn!!"; +//! +//! let mut data = plaintext; +//! let (nonce, tag) = Aes128Gcm::::encrypt_detached(&key, aad, &mut data).unwrap(); +//! assert_ne!(data, plaintext); +//! +//! Aes128Gcm::::decrypt_detached(&key, &nonce, aad, &mut data, &tag).unwrap(); +//! assert_eq!(data, plaintext); +//! ``` +//! +//! Inline `ciphertext || tag`, and streaming with AAD: +//! +//! ``` +//! use bouncycastle_aes::AES_256; +//! use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +//! use bouncycastle_core::traits::{SimpleCipherDecryptor, SimpleCipherEncryptor}; +//! use bouncycastle_modes::{Decrypting, Encrypting, Gcm}; +//! +//! type Aes256Gcm = Gcm; +//! +//! let key = KeyMaterial::<32>::from_bytes_as_type(&[0x07; 32], KeyType::SymmetricCipherKey) +//! .expect("a 32-byte symmetric cipher key"); +//! let aad = b"associated data"; +//! let message = b"a message that streams in over more than one call"; +//! +//! let (mut enc, nonce) = Aes256Gcm::::do_encrypt_init(&key).unwrap(); +//! enc.do_update_aad(aad).unwrap(); +//! let mut ct = vec![0u8; message.len()]; +//! enc.do_update_out(message, &mut ct).unwrap(); +//! let (tag_block, tag_len) = enc.do_final().unwrap(); +//! ct.extend_from_slice(&tag_block[..tag_len]); +//! +//! let mut dec = Aes256Gcm::::do_decrypt_init(&key, &nonce).unwrap(); +//! dec.do_update_aad(aad).unwrap(); +//! let mut pt = vec![0u8; ct.len()]; +//! let written = dec.do_update_out(&ct, &mut pt).unwrap(); +//! let (_last, last_len) = dec.do_final().unwrap(); +//! pt.truncate(written + last_len); +//! assert_eq!(pt, message); +//! ``` +//! +//! # Security Considerations +//! +//! * **Nonce uniqueness is everything.** Sec 8: "The probability that the authenticated encryption +//! function ever will be invoked with the same IV and the same key on two (or more) distinct sets +//! of input data shall be no greater than 2^-32." Appendix A: a repeated nonce lets an adversary +//! recover the hash subkey `H` from the two ciphertexts, after which "the authentication +//! assurance essentially is lost" and GCM inherits CTR's plaintext-controlling malleability. The +//! nonce is always drawn from the library's default RNG (Sec 8.2.2's RBG-based construction, +//! empty free field) and never accepted from the caller. +//! * **Invocation limit.** Sec 8.2.2 / 8.3: with the RBG-based construction, "the total number of +//! invocations of the authenticated encryption function shall not exceed 2^32 ... with the given +//! key." This is a caller obligation this type cannot enforce across calls; rotate the key well +//! before 2^32 messages. +//! * **Forgery probability and failed-verification limits.** Appendix B: a targeted forgery over +//! `n` blocks of AAD and ciphertext succeeds with probability about `n / 2^t`, and each success +//! leaks information about `H`; "the system or protocol that implements GCM should monitor and, if +//! necessary, limit the number of unsuccessful verification attempts for each key." +//! * **32- and 64-bit tags are not offered** (Appendix C); see the module docs above. +//! * **Streaming decryption releases plaintext before the tag is checked; the one-shots do not.** +//! [`Gcm::do_decrypt`] and [`SimpleCipherDecryptor::do_update_out`] hand back plaintext as they go, +//! which is unauthenticated until [`Gcm::finish`] / `do_final` succeeds -- do not act on it before +//! then. [`Gcm::decrypt_detached`] and the inline `decrypt_out` override verify the tag first and +//! release nothing at all on failure (Sec 7.2 permits checking the tag before computing the +//! plaintext, and this is why the one-shot exists as more than init/update/final glued together). +//! * **Intermediates are secret.** Sec 5.3: "the intermediate values in the execution of the GCM +//! functions shall be secret." `H`, the running GHASH accumulator, the pending partial block, the +//! tag mask `CIPH_K(J0)` and the CTR keystream all live in +//! [`Secret`](bouncycastle_utils::secret::Secret). +//! * **The `2^39 - 256`-bit plaintext bound (Sec 5.2.1.1) is `Ctr`'s own counter-exhaustion error.** +//! GCTR runs from counter 2 (D6), leaving `2^32 - 2` blocks, i.e. exactly `2^39 - 256` bits, before +//! `Ctr` refuses with [`SymmetricCipherError::StateError`]. +//! * **Constant time.** GHASH multiplication (`ghash.rs`) and the tag comparison +//! (`bouncycastle_utils::ct::ct_eq_bytes`) touch no table indexed by secret data, with the same +//! caveats `bouncycastle-aes` states about compiler guarantees and side channels other than +//! timing. +//! * **GMAC is GCM with no plaintext** (Sec 5.2): feed only AAD and call `finish`/`do_final`: there +//! is no separate `Gmac` type. + +use crate::ghash::Ghash; +use crate::{Ctr, Decrypting, Encrypting}; +use bouncycastle_core::errors::SymmetricCipherError; +use bouncycastle_core::key_material::KeyMaterial; +use bouncycastle_core::traits::{ + Algorithm, ElectronicCodeBook, RNG, SecurityStrength, SimpleCipherDecryptor, + SimpleCipherEncryptor, StreamCipherDecryptor, StreamCipherEncryptor, +}; +use bouncycastle_rng::HashDRBG_SHA512; +use bouncycastle_utils::ct::ct_eq_bytes; +use bouncycastle_utils::secret::Secret; +use core::marker::PhantomData; + +/// The nonce (IV) length this type uses: 96 bits, SP 800-38D Sec 5.2.1.1's recommended length. +pub const GCM_NONCE_LEN: usize = 12; + +/// Which category of bytes `Gcm` is currently absorbing into GHASH: additional authenticated data, +/// or plaintext/ciphertext. AAD is only accepted in the first phase (SP 800-38D Algorithm 4 absorbs +/// `A` before `C`); the transition also pads the AAD to a block boundary (the `0^v` of step 5). +#[derive(Clone, Copy, PartialEq, Eq)] +enum Phase { + Aad, + Data, +} + +/// Galois/Counter Mode over any [`ElectronicCodeBook`] permutation, direction typed as +/// [`Encrypting`] / [`Decrypting`]. See the module docs for the two APIs this type exposes and +/// [`GCM_NONCE_LEN`] / `TAG_LEN` for what is fixed and what is chosen. +pub struct Gcm +where + P: ElectronicCodeBook, +{ + /// `GCTR_K(inc32(J0), .)`: Algorithm 4 step 3 / Algorithm 5 step 4, started at counter 2 (see + /// [`Gcm::setup`]). + ctr: Ctr, + /// `GHASH_H` over `A || 0^v || C || 0^u`, Algorithm 4/5 step 5/6. + ghash: Ghash, + /// `CIPH_K(J0)`, the one-time mask for the tag (step 6's `GCTR_K(J0, S) = S (+) CIPH_K(J0)`, + /// valid because `S` is exactly one block). + ek_j0: Secret<[u8; 16]>, + /// `len(A)` in bytes so far; converted to bits at [`Gcm::tag_block`]. + aad_len: u64, + /// `len(C)` in bytes so far; converted to bits at [`Gcm::tag_block`]. + data_len: u64, + phase: Phase, + /// The last up to `TAG_LEN` bytes of ciphertext seen by [`SimpleCipherDecryptor::do_update_out`] + /// but not yet released, because they might be the tag. Meaningful only on the `Decrypting` + /// side; kept on both directions rather than splitting the struct by `Dir` -- seeded random + /// bytes are indistinguishable from a design that carries them deliberately, so this trades + /// `TAG_LEN` bytes of unused state on the encryptor for one struct definition instead of two. + tail: Secret<[u8; TAG_LEN]>, + /// How many bytes of `tail` are meaningful, `0..=TAG_LEN`. + tail_len: usize, + _dir: PhantomData, +} + +impl Gcm +where + P: ElectronicCodeBook, +{ + /// The compile-time shape check: `TAG_LEN` must be one of Sec 5.2.1.2's five recommended tag + /// lengths in bytes (96, 104, 112, 120, 128 bits -- Appendix C's 32- and 64-bit tags are a + /// documented non-goal; see the module docs). Called from every constructor. + #[inline] + fn check_shape() { + const { + assert!( + TAG_LEN >= 12 && TAG_LEN <= 16, + "GCM tag length must be 12..=16 bytes (96, 104, 112, 120 or 128 bits), \ + SP 800-38D Sec 5.2.1.2" + ); + }; + } + + /// Algorithm 4 steps 1-2 and the precomputation for step 6's tag mask. + fn setup(perm: P, nonce: [u8; GCM_NONCE_LEN]) -> Self { + Self::check_shape(); + + // Step 1: H = CIPH_K(0^128). + let mut h = [0u8; 16]; + perm.encrypt_block(&mut h); + + // Step 2 (len(IV) = 96 branch, the only one this type implements): J0 = IV || 0^31 || 1. + let mut j0 = [0u8; 16]; + j0[..GCM_NONCE_LEN].copy_from_slice(&nonce); + j0[15] = 1; + + // Precompute CIPH_K(J0) now, while J0 is fully known: step 6's GCTR_K(J0, S) reduces to + // S (+) CIPH_K(J0) because S is exactly one block (Algorithm 3 with a single, complete + // input block), so this one-time mask is all GCTR at J0 will ever be asked to produce. + let mut ek_j0_bytes = j0; + perm.encrypt_block(&mut ek_j0_bytes); + let mut ek_j0: Secret<[u8; 16]> = Secret::new(); + *ek_j0 = ek_j0_bytes; + + // Step 3's inc32(J0): J0's rightmost 32 bits are 1, so inc32(J0) has counter field 2. + let ctr = Ctr::start_at(perm, nonce, 2); + + Self { + ctr, + ghash: Ghash::new(&h), + ek_j0, + aad_len: 0, + data_len: 0, + phase: Phase::Aad, + tail: Secret::new(), + tail_len: 0, + _dir: PhantomData, + } + } + + /// Absorbs additional authenticated data. Any number of calls before the first call to + /// [`Gcm::do_encrypt`] / [`Gcm::do_decrypt`] / [`SimpleCipherEncryptor::do_update_out`] / + /// [`SimpleCipherDecryptor::do_update_out`]; a non-empty call after data has started is + /// [`SymmetricCipherError::StateError`] (Algorithm 4 absorbs `A` before `C` in one GHASH pass, + /// D4). Empty AAD is always a no-op. + pub fn do_update_aad(&mut self, aad: &[u8]) -> Result<(), SymmetricCipherError> { + if self.phase == Phase::Data { + if aad.is_empty() { + return Ok(()); + } + return Err(SymmetricCipherError::StateError( + "GCM: additional authenticated data must be supplied before any plaintext or \ + ciphertext (SP 800-38D Algorithm 4 absorbs A before C in one GHASH pass)", + )); + } + self.ghash.update(aad); + self.aad_len = + self.aad_len.checked_add(aad.len() as u64).ok_or(SymmetricCipherError::StateError( + "GCM: additional authenticated data length exceeds the supported range", + ))?; + Ok(()) + } + + /// The AAD-to-data transition: pads the AAD to a block boundary (the `0^v` of step 5) the + /// first time data arrives. A no-op on every later call. + fn begin_data_if_needed(&mut self) { + if self.phase == Phase::Aad { + self.ghash.pad_to_block(); + self.phase = Phase::Data; + } + } + + /// Absorbs `data` -- always ciphertext, whichever direction is calling -- into GHASH and + /// tracks its length. Shared by the encryptor (which calls this *after* GCTR has turned + /// plaintext into ciphertext in place) and the decryptor (which calls this *before* GCTR turns + /// the ciphertext back into plaintext): either way GHASH must see ciphertext, never plaintext. + fn absorb_data(&mut self, data: &[u8]) -> Result<(), SymmetricCipherError> { + self.begin_data_if_needed(); + self.ghash.update(data); + self.data_len = self.data_len.checked_add(data.len() as u64).ok_or( + SymmetricCipherError::StateError("GCM: data length exceeds the supported range"), + )?; + Ok(()) + } + + /// Algorithm 4 steps 4-6 / Algorithm 5 steps 5-7: pads GHASH to the block boundary (the `0^u` + /// of step 5), appends `[len(A)]_64 || [len(C)]_64`, and masks the result with `CIPH_K(J0)`. + /// Returns the full 16-byte block; callers truncate to `TAG_LEN`. + /// + /// The byte-to-bit multiplication (`* 8`) is not checked for overflow: `aad_len` and `data_len` + /// are accumulated with `checked_add` at every absorption (`do_update_aad`, `absorb_data`), so + /// reaching a count whose `* 8` could overflow `u64` would already require far more calls than + /// are physically possible to make. + fn tag_block(&mut self) -> [u8; 16] { + self.ghash.pad_to_block(); + let aad_bits = self.aad_len * 8; + let data_bits = self.data_len * 8; + let s = self.ghash.finish(aad_bits, data_bits); + let ek_j0 = *self.ek_j0; + let mut out = [0u8; 16]; + for i in 0..16 { + out[i] = s[i] ^ ek_j0[i]; + } + out + } +} + +impl Algorithm for Gcm +where + P: ElectronicCodeBook, +{ + const ALG_NAME: &'static str = P::ALG_NAME; + const MAX_SECURITY_STRENGTH: SecurityStrength = P::MAX_SECURITY_STRENGTH; +} + +impl Gcm +where + P: ElectronicCodeBook, +{ + /// Encrypts `data` in place (GCTR, Algorithm 4 step 3) and absorbs the resulting ciphertext + /// into GHASH (step 5). Nothing is held back. + /// + /// # Errors + /// [`SymmetricCipherError::StateError`] if the underlying `Ctr` counter would be exhausted -- + /// the SP 800-38D Sec 5.2.1.1 bound `len(P) <= 2^39 - 256` bits -- or if the AAD/data length + /// bookkeeping would overflow. Nothing is consumed in either case. + pub fn do_encrypt(&mut self, data: &mut [u8]) -> Result<(), SymmetricCipherError> { + self.ctr.do_encrypt(data)?; + self.absorb_data(data) + } + + /// Algorithm 4 steps 4-6: finishes the message and returns the detached authentication tag, + /// truncated to `TAG_LEN` bytes (`MSB_t`, step 6). Consumes the encryptor. + pub fn finish(mut self) -> [u8; TAG_LEN] { + // Covers an AAD-only or entirely empty message, where do_encrypt is never called. + self.begin_data_if_needed(); + let full = self.tag_block(); + let mut tag = [0u8; TAG_LEN]; + tag.copy_from_slice(&full[..TAG_LEN]); + tag + } + + /// One-shot: encrypts `data` in place under a fresh nonce, with `aad` as the additional + /// authenticated data. Returns the generated nonce and the detached tag. Sources randomness + /// from the library's default OS-backed RNG. + pub fn encrypt_detached( + key: &KeyMaterial, + aad: &[u8], + data: &mut [u8], + ) -> Result<([u8; GCM_NONCE_LEN], [u8; TAG_LEN]), SymmetricCipherError> { + let mut rng = HashDRBG_SHA512::new_from_os(); + Self::encrypt_detached_rng(key, &mut rng, aad, data) + } + + /// As [`Gcm::encrypt_detached`], but sources randomness from the provided RNG. + pub fn encrypt_detached_rng( + key: &KeyMaterial, + rng: &mut dyn RNG, + aad: &[u8], + data: &mut [u8], + ) -> Result<([u8; GCM_NONCE_LEN], [u8; TAG_LEN]), SymmetricCipherError> { + Self::check_shape(); + let perm = P::new(key)?; + let nonce = crate::iv::random_iv::(rng)?; + let mut gcm = Self::setup(perm, nonce); + gcm.do_update_aad(aad)?; + gcm.do_encrypt(data)?; + Ok((nonce, gcm.finish())) + } +} + +impl + SimpleCipherEncryptor for Gcm +where + P: ElectronicCodeBook, +{ + fn do_encrypt_init( + key: &KeyMaterial, + ) -> Result<(Self, [u8; GCM_NONCE_LEN]), SymmetricCipherError> { + let mut rng = HashDRBG_SHA512::new_from_os(); + Self::do_encrypt_init_rng(key, &mut rng) + } + + fn do_encrypt_init_rng( + key: &KeyMaterial, + rng: &mut dyn RNG, + ) -> Result<(Self, [u8; GCM_NONCE_LEN]), SymmetricCipherError> { + Self::check_shape(); + let perm = P::new(key)?; + let nonce = crate::iv::random_iv::(rng)?; + Ok((Self::setup(perm, nonce), nonce)) + } + + /// The identity: GCM's encryptor holds nothing back. + fn update_out_len(&self, input_len: usize) -> usize { + input_len + } + + fn do_update_out( + &mut self, + plaintext: &[u8], + ciphertext: &mut [u8], + ) -> Result { + if ciphertext.len() < plaintext.len() { + return Err(SymmetricCipherError::IncorrectOutputBufferLength( + "ciphertext", + plaintext.len(), + )); + } + ciphertext[..plaintext.len()].copy_from_slice(plaintext); + self.do_encrypt(&mut ciphertext[..plaintext.len()])?; + Ok(plaintext.len()) + } + + fn do_final(self) -> Result<([u8; TAG_LEN], usize), SymmetricCipherError> { + let tag = self.finish(); + Ok((tag, TAG_LEN)) + } + + fn encrypt_out_len(plaintext_len: usize) -> usize { + plaintext_len + TAG_LEN + } +} + +impl Gcm +where + P: ElectronicCodeBook, +{ + /// Absorbs `data` (ciphertext) into GHASH, then decrypts it in place. Order matters and is the + /// reverse of the encryptor's: GHASH must see ciphertext on both sides, so it is absorbed + /// *before* GCTR turns it into plaintext here. + /// + /// The plaintext this releases is **not yet authenticated** -- see [`Gcm::decrypt_detached`] + /// for the one-shot that does not have this exposure, and the module docs' Security + /// Considerations section. + /// + /// # Errors + /// As [`Gcm::do_encrypt`]. + pub fn do_decrypt(&mut self, data: &mut [u8]) -> Result<(), SymmetricCipherError> { + self.absorb_data(data)?; + self.ctr.do_decrypt(data) + } + + /// Algorithm 5 steps 5-8: recomputes `T'` and compares it against `tag` in constant time. + /// Consumes the decryptor; `Ok(())` is the only thing that makes the plaintext released so far + /// (by [`Gcm::do_decrypt`]) trustworthy. + /// + /// # Errors + /// [`SymmetricCipherError::AEADTagCheckFailed`] if the tag does not match. + pub fn finish(mut self, tag: &[u8; TAG_LEN]) -> Result<(), SymmetricCipherError> { + self.begin_data_if_needed(); + let full = self.tag_block(); + if ct_eq_bytes(&full[..TAG_LEN], tag) { + Ok(()) + } else { + Err(SymmetricCipherError::AEADTagCheckFailed) + } + } + + /// Shared by [`Gcm::decrypt_detached`] and the inline `decrypt_out` override: absorbs `aad` and + /// `data` (still ciphertext) into GHASH and checks the tag *before* touching `data`, so no + /// unauthenticated plaintext is ever written to the caller's buffer (Sec 7.2 explicitly permits + /// checking the tag before computing the plaintext). Only on success is `data` decrypted. + fn verify_then_decrypt( + key: &KeyMaterial, + nonce: &[u8; GCM_NONCE_LEN], + aad: &[u8], + data: &mut [u8], + tag: &[u8; TAG_LEN], + ) -> Result<(), SymmetricCipherError> { + Self::check_shape(); + let perm = P::new(key)?; + let mut gcm = Self::setup(perm, *nonce); + gcm.do_update_aad(aad)?; + gcm.absorb_data(data)?; + let computed = gcm.tag_block(); + if !ct_eq_bytes(&computed[..TAG_LEN], tag) { + return Err(SymmetricCipherError::AEADTagCheckFailed); + } + gcm.ctr.do_decrypt(data) + } + + /// One-shot: verifies the tag and, only if it matches, decrypts `data` in place. Releases + /// nothing on failure. + pub fn decrypt_detached( + key: &KeyMaterial, + nonce: &[u8; GCM_NONCE_LEN], + aad: &[u8], + data: &mut [u8], + tag: &[u8; TAG_LEN], + ) -> Result<(), SymmetricCipherError> { + Self::verify_then_decrypt(key, nonce, aad, data, tag) + } +} + +impl + SimpleCipherDecryptor for Gcm +where + P: ElectronicCodeBook, +{ + fn do_decrypt_init( + key: &KeyMaterial, + init_data: &[u8; GCM_NONCE_LEN], + ) -> Result { + Self::check_shape(); + let perm = P::new(key)?; + Ok(Self::setup(perm, *init_data)) + } + + /// `tail_len + input_len`, minus up to `TAG_LEN` bytes held back because they might be the tag. + fn update_out_len(&self, input_len: usize) -> usize { + (self.tail_len + input_len).saturating_sub(TAG_LEN) + } + + /// Releases every byte of `tail ++ ciphertext` except the last (up to) `TAG_LEN`, which become + /// the new tail. Decrypts (via [`Gcm::do_decrypt`]) exactly the bytes released this call, so + /// GHASH absorbs each ciphertext byte exactly once across the whole stream. + fn do_update_out( + &mut self, + ciphertext: &[u8], + plaintext: &mut [u8], + ) -> Result { + let release = self.update_out_len(ciphertext.len()); + if plaintext.len() < release { + return Err(SymmetricCipherError::IncorrectOutputBufferLength("plaintext", release)); + } + + // Bytes of the old tail that are now known to be ciphertext, then bytes of the new input + // that are also released this call. + let tail_release = release.min(self.tail_len); + let input_release = release - tail_release; + if tail_release > 0 { + plaintext[..tail_release].copy_from_slice(&self.tail[..tail_release]); + } + if input_release > 0 { + plaintext[tail_release..release].copy_from_slice(&ciphertext[..input_release]); + } + if release > 0 { + self.do_decrypt(&mut plaintext[..release])?; + } + + // The new tail is whatever of (old tail ++ ciphertext) survives past `release` bytes -- + // at most TAG_LEN bytes, by construction of `release` above. + let mut new_tail = [0u8; TAG_LEN]; + let old_tail_kept = self.tail_len - tail_release; + new_tail[..old_tail_kept].copy_from_slice(&self.tail[tail_release..self.tail_len]); + let input_kept = ciphertext.len() - input_release; + new_tail[old_tail_kept..old_tail_kept + input_kept] + .copy_from_slice(&ciphertext[input_release..]); + *self.tail = new_tail; + self.tail_len = old_tail_kept + input_kept; + + Ok(release) + } + + /// If fewer than `TAG_LEN` bytes were ever seen, the ciphertext was too short to carry a tag at + /// all (Algorithm 5 step 1's "lengths not supported"). Otherwise checks the tag held in `tail` + /// against the GHASH state built up by every prior `do_update_out` call. Releases nothing: an + /// authenticated cipher's final output may be empty once the tag has been checked. + fn do_final(self) -> Result<([u8; TAG_LEN], usize), SymmetricCipherError> { + if self.tail_len < TAG_LEN { + return Err(SymmetricCipherError::DecryptionFailed); + } + let tag = *self.tail; + self.finish(&tag)?; + Ok(([0u8; TAG_LEN], 0)) + } + + fn decrypt_out_max_len(ciphertext_len: usize) -> usize { + ciphertext_len.saturating_sub(TAG_LEN) + } + + /// Overrides the trait's default (which would stream plaintext out before the tag is checked): + /// verifies the tag first and only then decrypts, so this one-shot never exposes + /// unauthenticated plaintext. The streaming path above, by its nature, still does. + fn decrypt_out( + key: &KeyMaterial, + init_data: &[u8; GCM_NONCE_LEN], + ciphertext: &[u8], + plaintext: &mut [u8], + ) -> Result { + let needed = Self::decrypt_out_max_len(ciphertext.len()); + if plaintext.len() < needed { + return Err(SymmetricCipherError::IncorrectOutputBufferLength("plaintext", needed)); + } + if ciphertext.len() < TAG_LEN { + return Err(SymmetricCipherError::DecryptionFailed); + } + let ct_len = ciphertext.len() - TAG_LEN; + let tag: [u8; TAG_LEN] = ciphertext[ct_len..] + .try_into() + .expect("ciphertext.len() - ct_len == TAG_LEN by construction"); + + plaintext[..ct_len].copy_from_slice(&ciphertext[..ct_len]); + Self::verify_then_decrypt(key, init_data, &[], &mut plaintext[..ct_len], &tag)?; + Ok(ct_len) + } +} diff --git a/crypto/modes/src/ghash.rs b/crypto/modes/src/ghash.rs new file mode 100644 index 00000000..7de1bdd8 --- /dev/null +++ b/crypto/modes/src/ghash.rs @@ -0,0 +1,417 @@ +//! GHASH: the universal hash function GCM builds its authentication on (NIST SP 800-38D Sec 6.3, +//! 6.4), and the GF(2^128) multiplication it is defined over. +//! +//! This is the only genuinely new cryptographic code `gcm.rs` needs; everything else there is +//! plumbing around this and [`crate::Ctr`]. +//! +//! # Field element representation +//! +//! A block of `GF(2^128)` is represented as `[u64; 2]`: `x[0]` is the first eight bytes of the +//! 16-byte block read big-endian, `x[1]` the last eight -- the same `asLongs`/`asBytes` convention +//! BC Java's `GCMUtil` uses. Sec 6.3 fixes the bit convention as "little endian": bit `x_0`, the +//! *leftmost* (most significant) bit of the first byte, is the coefficient of `u^0`. In this `u64` +//! pair form that means `x_0` is the *top* bit of `x[0]`, `x_63` is its bottom bit, `x_64` is the +//! top bit of `x[1]`, and `x_127` is its bottom bit. So Algorithm 1's "V >> 1" (discard the +//! rightmost bit of the whole 128-bit string, prepend a zero on the left) is a right shift across +//! the `x[0], x[1]` pair carrying the bottom bit of `x[0]` into the top bit of `x[1]`, and `R` +//! (`11100001 || 0^120`, Sec 6.3) is the block whose first byte is `0xE1` and the rest zero, i.e. +//! `[0xE1 << 56, 0]` in this representation. +//! +//! Getting this orientation right once, here, is worth the length of this comment: every GCM +//! implementation bug report in the wild is an orientation bug, and [`mul_reference`] exists so +//! [`mul`] can be checked against something whose correctness is visible by inspection of the spec +//! text above rather than by parity with another implementation. + +use bouncycastle_utils::secret::Secret; + +/// A block of `GF(2^128)`, in the two-`u64` form described in the module docs. +type Block = [u64; 2]; + +/// `R = 11100001 || 0^120` (Sec 6.3): first byte `0xE1`, the rest zero. Used only by +/// [`mul_reference`]: [`mul`] folds the same constant into its own reduction step directly, as +/// literal shift amounts rather than a named block. +#[cfg(test)] +const R: Block = [0xE100_0000_0000_0000, 0]; + +/// `x[0]` is the first eight bytes of `b` read big-endian, `x[1]` the last eight. +fn block_from_bytes(b: &[u8; 16]) -> Block { + [ + u64::from_be_bytes(b[..8].try_into().expect("first half of a 16-byte block is 8 bytes")), + u64::from_be_bytes(b[8..].try_into().expect("second half of a 16-byte block is 8 bytes")), + ] +} + +/// Inverse of [`block_from_bytes`]. +fn block_to_bytes(x: &Block) -> [u8; 16] { + let mut out = [0u8; 16]; + out[..8].copy_from_slice(&x[0].to_be_bytes()); + out[8..].copy_from_slice(&x[1].to_be_bytes()); + out +} + +/// Algorithm 1 (Sec 6.3), a direct transcription, computed bit-serially with masks so it is itself +/// constant time. This is the *oracle*: [`mul`] is checked against it in the test module below, and +/// it is never used outside `#[cfg(test)]`. Kept short and boring on purpose. +#[cfg(test)] +fn mul_reference(x: &Block, y: &Block) -> Block { + // Step 2: Z_0 = 0^128, V_0 = Y. + let mut z: Block = [0, 0]; + let mut v: Block = *y; + // Step 3: for i = 0 to 127 ... + for i in 0..128u32 { + // Step 1 / step 3: bit x_i of X. x_0 is the top bit of x[0] (see module docs), so bit i + // for i < 64 is bit (63 - i) of x[0], and for i >= 64 is bit (127 - i) of x[1]. + let bit = if i < 64 { (x[0] >> (63 - i)) & 1 } else { (x[1] >> (127 - i)) & 1 }; + // All-ones if x_i = 1, all-zero if x_i = 0 -- a constant-time select, standing in for the + // spec's "Z_{i+1} = Z_i if x_i = 0; Z_i (+) V_i if x_i = 1". + let m = 0u64.wrapping_sub(bit); + z[0] ^= v[0] & m; + z[1] ^= v[1] & m; + + // "V_{i+1} = V_i >> 1 if LSB_1(V_i) = 0; (V_i >> 1) (+) R if LSB_1(V_i) = 1." LSB_1 of the + // 128-bit string V is the bottom bit of v[1]; ">> 1" is a right shift across the pair. + let lsb = v[1] & 1; + let lm = 0u64.wrapping_sub(lsb); + let carry_in = v[0] & 1; + v[0] >>= 1; + v[1] = (v[1] >> 1) | (carry_in << 63); + v[0] ^= R[0] & lm; + v[1] ^= R[1] & lm; + } + // Step 4: return Z_128. + z +} + +/// The masked-lane carry-less multiply of two 64-bit halves. +/// +/// Ported from BC Java's `GCMUtil.implMul64(long, long)` +/// (`crypto/modes/gcm/GCMUtil.java`). Four lane masks (`0x1111...`, `0x2222...`, `0x4444...`, +/// `0x8888...`) space the input bits four apart, so the sixteen masked products summed into each +/// output lane carry at most fifteen ways -- never enough for an integer carry to reach a live lane +/// -- which is what makes ordinary `u64` multiplication (relying on the CPU's integer multiplier +/// being constant time, the same assumption the rest of this library's constant-time code makes) +/// compute a carry-less (XOR-add) product on each lane. Masking again after summing discards the +/// garbage that leaked into the gaps between lanes. +fn impl_mul64(x: u64, y: u64) -> u64 { + let x0 = x & 0x1111_1111_1111_1111; + let x1 = x & 0x2222_2222_2222_2222; + let x2 = x & 0x4444_4444_4444_4444; + let x3 = x & 0x8888_8888_8888_8888; + + let y0 = y & 0x1111_1111_1111_1111; + let y1 = y & 0x2222_2222_2222_2222; + let y2 = y & 0x4444_4444_4444_4444; + let y3 = y & 0x8888_8888_8888_8888; + + let z0 = x0.wrapping_mul(y0) ^ x1.wrapping_mul(y3) ^ x2.wrapping_mul(y2) ^ x3.wrapping_mul(y1); + let z1 = x0.wrapping_mul(y1) ^ x1.wrapping_mul(y0) ^ x2.wrapping_mul(y3) ^ x3.wrapping_mul(y2); + let z2 = x0.wrapping_mul(y2) ^ x1.wrapping_mul(y1) ^ x2.wrapping_mul(y0) ^ x3.wrapping_mul(y3); + let z3 = x0.wrapping_mul(y3) ^ x1.wrapping_mul(y2) ^ x2.wrapping_mul(y1) ^ x3.wrapping_mul(y0); + + let z0 = z0 & 0x1111_1111_1111_1111; + let z1 = z1 & 0x2222_2222_2222_2222; + let z2 = z2 & 0x4444_4444_4444_4444; + let z3 = z3 & 0x8888_8888_8888_8888; + + // The four lanes are disjoint (each mask owns one bit in every nibble), so `|` and `^` agree + // here; `cargo mutants` is expected to report this substitution as a surviving, equivalent + // mutant rather than a missing test. + z0 | z1 | z2 | z3 +} + +/// The constant-time, table-free `GF(2^128)` product `x . y` (Sec 6.3's `*` operator). +/// +/// Ported from BC Java's `GCMUtil.multiply(long[], long[])`: a "three-way recursion" (Karatsuba +/// over the two 64-bit halves, per Bernstein's "Batch binary Edwards") built on [`impl_mul64`], with +/// a bit-reversal trick (`rev(x)*rev(y) == rev((x*y) << 1)`) to reach the high 64 bits of each +/// 64x64 product without a 128-bit multiply, followed by the standard two-step reduction by `R`. +/// Variable names (`h0..h5`, `z0..z3`) match the Java source so the two can be diffed side by side. +pub(crate) fn mul(x: &Block, y: &Block) -> Block { + let (x0, x1) = (x[0], x[1]); + let (y0, y1) = (y[0], y[1]); + let (x0r, x1r) = (x0.reverse_bits(), x1.reverse_bits()); + let (y0r, y1r) = (y0.reverse_bits(), y1.reverse_bits()); + + let h0 = impl_mul64(x0r, y0r).reverse_bits(); + let h1 = impl_mul64(x0, y0) << 1; + let h2 = impl_mul64(x1r, y1r).reverse_bits(); + let h3 = impl_mul64(x1, y1) << 1; + let h4 = impl_mul64(x0r ^ x1r, y0r ^ y1r).reverse_bits(); + let h5 = impl_mul64(x0 ^ x1, y0 ^ y1) << 1; + + let z0 = h0; + let mut z1 = h1 ^ h0 ^ h2 ^ h4; + let mut z2 = h2 ^ h1 ^ h3 ^ h5; + let z3 = h3; + + // Reduction by R, step 1: fold z3 into z1 and z2. The commented-out `(z3 << 63)` term in BC + // Java's source is dropped because it is folded into the `z2 ^= ... (z3 << 62) ...` line below + // instead: `z3 << 63` contributes only its bit 63 (all lower bits are shifted out), which is the + // same single bit that `(z3 << 62) << 1`, i.e. bit 62 of `(z3 << 62)`, would carry forward one + // more position -- BC Java's own comment marks this as the intentional omission. + z1 ^= z3 ^ (z3 >> 1) ^ (z3 >> 2) ^ (z3 >> 7); + z2 ^= (z3 << 62) ^ (z3 << 57); + + let mut z0 = z0; + // Reduction by R, step 2: fold the now-complete z2 into z0 and z1. + z0 ^= z2 ^ (z2 >> 1) ^ (z2 >> 2) ^ (z2 >> 7); + z1 ^= (z2 << 63) ^ (z2 << 62) ^ (z2 << 57); + + [z0, z1] +} + +/// The `GHASH` accumulator (Algorithm 2, Sec 6.4). +/// +/// `Y_0 = 0^128` (step 2); each call to [`update`](Self::update) absorbs whole blocks via +/// `Y_i = (Y_{i-1} (+) X_i) . H` (step 3), buffering any partial block for the next call so that a +/// sequence of calls is equivalent to one call over the concatenation. [`finish`](Self::finish) +/// returns `Y_m` (step 4) after appending the 64-bit AAD- and data-bit-length block that Algorithm +/// 4 step 5 / Algorithm 5 step 6 fold into the same hash. +/// +/// `H` and the running hash `Y` are the GCM intermediates Sec 5.3 requires to be secret ("the +/// intermediate values in the execution of the GCM functions shall be secret"), so both live in a +/// [`Secret`] and are zeroized on drop; the pending partial block is live plaintext-or-ciphertext +/// bytes still waiting to be absorbed and is wrapped for the same reason. +pub(crate) struct Ghash { + /// The hash subkey `H = CIPH_K(0^128)`. + h: Secret, + /// `Y_i` of Algorithm 2. + y: Secret, + /// Bytes of the current block not yet absorbed. + pending: Secret<[u8; 16]>, + /// How many bytes of `pending` are meaningful, `0..=16`. + pending_len: usize, +} + +impl Ghash { + /// `Y_0 = 0^128` (Algorithm 2 step 2), keyed by the hash subkey `H`. + pub(crate) fn new(h: &[u8; 16]) -> Self { + let mut hs: Secret = Secret::new(); + *hs = block_from_bytes(h); + Self { h: hs, y: Secret::new(), pending: Secret::new(), pending_len: 0 } + } + + /// `Y_i = (Y_{i-1} (+) X_i) . H` for one whole block `X_i`. + fn absorb(&mut self, block: &[u8; 16]) { + let xi = block_from_bytes(block); + let mut acc = *self.y; + acc[0] ^= xi[0]; + acc[1] ^= xi[1]; + *self.y = mul(&acc, &self.h); + } + + /// Absorbs whole blocks of `data` immediately and buffers any remainder for the next call. + /// Chunking-independent: a sequence of calls over pieces of a message is equivalent to one call + /// over the whole message. + pub(crate) fn update(&mut self, mut data: &[u8]) { + if self.pending_len > 0 { + let need = 16 - self.pending_len; + let take = need.min(data.len()); + (*self.pending)[self.pending_len..self.pending_len + take] + .copy_from_slice(&data[..take]); + self.pending_len += take; + data = &data[take..]; + if self.pending_len < 16 { + return; + } + let block = *self.pending; + self.absorb(&block); + self.pending_len = 0; + } + + let (blocks, rest) = data.as_chunks::<16>(); + for block in blocks { + self.absorb(block); + } + (*self.pending)[..rest.len()].copy_from_slice(rest); + self.pending_len = rest.len(); + } + + /// The `0^v` / `0^u` zero-padding of Algorithm 4 step 5 / Algorithm 5 step 6: rounds the + /// pending partial block up to a whole block with zero bytes and absorbs it. A no-op when + /// nothing is pending, so it is safe to call unconditionally at a phase boundary. + pub(crate) fn pad_to_block(&mut self) { + if self.pending_len == 0 { + return; + } + (*self.pending)[self.pending_len..].fill(0); + let block = *self.pending; + self.absorb(&block); + self.pending_len = 0; + } + + /// Appends `[aad_bits]_64 || [data_bits]_64` (Algorithm 4 step 5's final block) and returns + /// `Y_m`, i.e. `S`. + /// + /// Takes `&mut self` rather than `self` -- `Gcm`'s verify-before-decrypt one-shot needs the rest + /// of its own state (the `Ctr` field) after computing the tag, so consuming `Ghash` here would + /// force that caller to reconstruct it. Nothing asserts a "was padded" flag: the caller is + /// expected to have called [`pad_to_block`](Self::pad_to_block) for both the AAD and the data + /// phase already (the `0^v` and `0^u` of step 5), so by the time `finish` runs there is nothing + /// pending except this one final length block, and no caller should call `update` or + /// `pad_to_block` again afterward. + pub(crate) fn finish(&mut self, aad_bits: u64, data_bits: u64) -> [u8; 16] { + debug_assert_eq!( + self.pending_len, 0, + "caller must pad_to_block before finish: nothing but the length block may be pending" + ); + let mut len_block = [0u8; 16]; + len_block[..8].copy_from_slice(&aad_bits.to_be_bytes()); + len_block[8..].copy_from_slice(&data_bits.to_be_bytes()); + self.absorb(&len_block); + block_to_bytes(&self.y) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A minimal xorshift64* generator, so the >= 10000 pseudo-random test pairs below do not need + /// the `rand` crate (CLAUDE.md: no new runtime dependency, and this is test-only anyway). + struct Lcg(u64); + impl Lcg { + fn next_u64(&mut self) -> u64 { + let mut x = self.0; + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + self.0 = x; + x + } + fn next_block(&mut self) -> Block { + [self.next_u64(), self.next_u64()] + } + } + + /// The spec's `1`: `1 || 0^127`, the leftmost bit set and everything else zero. The + /// multiplicative identity: `X . 1 == X` (Sec 6.3, "For a positive integer i, the ith power of a + /// block X ... H^2 = H.H, H^3 = H.H.H"). + const ONE: Block = [0x8000_0000_0000_0000, 0]; + + #[test] + fn mul_matches_the_reference_on_zero() { + let h: Block = [0x1122_3344_5566_7788, 0x99aa_bbcc_ddee_ff00]; + assert_eq!(mul(&[0, 0], &h), mul_reference(&[0, 0], &h)); + assert_eq!(mul(&h, &[0, 0]), mul_reference(&h, &[0, 0])); + } + + #[test] + fn mul_matches_the_reference_at_every_single_bit_position() { + let h: Block = [0xdead_beef_cafe_babe, 0x0123_4567_89ab_cdef]; + for i in 0..128u32 { + let x: Block = if i < 64 { [1u64 << (63 - i), 0] } else { [0, 1u64 << (127 - i)] }; + assert_eq!(mul(&x, &h), mul_reference(&x, &h), "bit position {i}"); + } + } + + #[test] + fn mul_matches_the_reference_on_all_ones() { + let h: Block = [0xfeed_face_dead_beef, 0x0102_0304_0506_0708]; + let ones: Block = [u64::MAX, u64::MAX]; + assert_eq!(mul(&ones, &h), mul_reference(&ones, &h)); + assert_eq!(mul(&h, &ones), mul_reference(&h, &ones)); + } + + #[test] + fn mul_matches_the_reference_on_ten_thousand_random_pairs() { + let mut rng = Lcg(0x2545_f491_4f6c_dd1d); + for _ in 0..10_000 { + let x = rng.next_block(); + let y = rng.next_block(); + assert_eq!(mul(&x, &y), mul_reference(&x, &y), "x={x:?} y={y:?}"); + } + } + + #[test] + fn mul_by_one_is_the_identity() { + let mut rng = Lcg(0x9e37_79b9_7f4a_7c15); + for _ in 0..256 { + let x = rng.next_block(); + assert_eq!(mul(&x, &ONE), x, "x . 1 == x for x={x:?}"); + assert_eq!(mul(&ONE, &x), x, "1 . x == x for x={x:?}"); + } + } + + #[test] + fn mul_is_commutative() { + let mut rng = Lcg(0xbf58_476d_1ce4_e5b9); + for _ in 0..256 { + let x = rng.next_block(); + let y = rng.next_block(); + assert_eq!(mul(&x, &y), mul(&y, &x), "x={x:?} y={y:?}"); + } + } + + /// A hand-checkable case for the oracle itself: `R . 1 == R`, the identity applied to the fixed + /// reduction constant. + #[test] + fn reference_r_times_one_is_r() { + assert_eq!(mul_reference(&R, &ONE), R); + } + + /// `GHASH` over one, two and three blocks must equal folding [`mul_reference`] by hand, per + /// Algorithm 2 step 3: `Y_i = (Y_{i-1} (+) X_i) . H`. + #[test] + fn ghash_matches_folding_the_reference_multiplier_by_hand() { + let h_bytes = [0x42u8; 16]; + let h = block_from_bytes(&h_bytes); + + let blocks: [[u8; 16]; 3] = [[0x11; 16], [0x22; 16], [0x33; 16]]; + + let mut y = [0u64, 0u64]; + for block in &blocks { + let xi = block_from_bytes(block); + y[0] ^= xi[0]; + y[1] ^= xi[1]; + y = mul_reference(&y, &h); + } + + for n in 1..=3 { + let mut g = Ghash::new(&h_bytes); + for block in &blocks[..n] { + g.update(block); + } + g.pad_to_block(); + // finish() also absorbs the zero-length block, so compare against one more fold step + // over the all-zero length block for a fair comparison of the n-block prefix alone. + let mut expected = [0u64, 0u64]; + for block in &blocks[..n] { + let xi = block_from_bytes(block); + expected[0] ^= xi[0]; + expected[1] ^= xi[1]; + expected = mul_reference(&expected, &h); + } + let zero_len_block = [0u8; 16]; + let xi = block_from_bytes(&zero_len_block); + expected[0] ^= xi[0]; + expected[1] ^= xi[1]; + expected = mul_reference(&expected, &h); + + assert_eq!(block_to_bytes(&expected), g.finish(0, 0), "n={n}"); + } + // Silence the unused full-message `y` computed above; it documents the general recurrence. + let _ = y; + } + + /// Chunking independence: absorbing a 100-byte message in one call must equal absorbing it in + /// two pieces, at every possible split point. + #[test] + fn update_is_chunking_independent() { + let h_bytes = [0x7eu8; 16]; + let data: [u8; 100] = core::array::from_fn(|i| i as u8); + + let mut whole = Ghash::new(&h_bytes); + whole.update(&data); + whole.pad_to_block(); + let expected = whole.finish(0, data.len() as u64 * 8); + + for split in 0..=data.len() { + let mut g = Ghash::new(&h_bytes); + g.update(&data[..split]); + g.update(&data[split..]); + g.pad_to_block(); + assert_eq!(g.finish(0, data.len() as u64 * 8), expected, "split at {split}"); + } + } +} diff --git a/crypto/modes/src/lib.rs b/crypto/modes/src/lib.rs index 0bc4f077..201d43b7 100644 --- a/crypto/modes/src/lib.rs +++ b/crypto/modes/src/lib.rs @@ -11,20 +11,27 @@ //! | CFB | [`Cfb`] | SP 800-38A Sec 6.3 | Cipher Feedback, full-block segment (`s = b`), i.e. CFB128 for AES | //! | CFB8 | [`Cfb8`] | SP 800-38A Sec 6.3 | Cipher Feedback, 8-bit segment (`s = 8`) | //! | CTR | [`Ctr`] | SP 800-38A Sec 6.5 | Counter. Nonce plus counter, both directions parallel | -//! -//! They divide two ways. **ECB and CBC are block ciphers** ([`BlockCipherEncryptor`] / -//! [`BlockCipherDecryptor`]): whole blocks in, whole blocks out, and arbitrary-length data needs -//! the padding layer. **CFB, CFB8 and CTR are stream ciphers** ([`StreamCipherEncryptor`] / -//! [`StreamCipherDecryptor`]): any length in, the same length out, no padding, no finalization -- -//! see [Block alignment, and which modes need it](#block-alignment-and-which-modes-need-it). -//! -//! **All five reach the same arbitrary-length API**, so code can be written against one trait and +//! | GCM | [`Gcm`] | SP 800-38D | Authenticated. 96-bit nonce, 96-128-bit tag, no padding; AAD before data | +//! +//! ECB, CBC, CFB, CFB8 and CTR divide two ways. **ECB and CBC are block ciphers** +//! ([`BlockCipherEncryptor`] / [`BlockCipherDecryptor`]): whole blocks in, whole blocks out, and +//! arbitrary-length data needs the padding layer. **CFB, CFB8 and CTR are stream ciphers** +//! ([`StreamCipherEncryptor`] / [`StreamCipherDecryptor`]): any length in, the same length out, no +//! padding, no finalization -- see +//! [Block alignment, and which modes need it](#block-alignment-and-which-modes-need-it). +//! **GCM is neither**: it is the first mode here with `FINAL_LEN != 0` that is not a padding +//! adapter -- its final output is the authentication tag, not a padded block -- and it reaches the +//! arbitrary-length trait directly rather than through a blanket impl, alongside an inherent +//! detached-tag API; see the `gcm` module docs. +//! +//! **All reach the same arbitrary-length API**, so code can be written against one trait and //! handed any mode. A block mode gets there by being wrapped in `bouncycastle-padding`'s adapters, //! which are [`SimpleCipherEncryptor`] / [`SimpleCipherDecryptor`] with the padded block as //! their final output; a stream mode implements those traits directly, with `FINAL_LEN = 0` because -//! it has no final output at all. The `bouncycastle-aes` aliases show the difference in -//! one line each: `AES_CBC_128` names a padding scheme, `AES_CTR_128` -//! has nothing to name. +//! it has no final output at all; GCM implements them directly too, with `FINAL_LEN = TAG_LEN`. The +//! `bouncycastle-aes` aliases show the difference in one line each: `AES_CBC_128` +//! names a padding scheme, `AES_CTR_128` has nothing to name, and +//! `AES_GCM_128` fixes the tag length. //! //! CBC, CFB, CFB8 and CTR all generate their own init data: an IV for the first three, a nonce for //! CTR, which is shorter than a block because the rest of the counter block is the counter. ECB has @@ -521,6 +528,8 @@ mod cfb; mod cfb8; mod ctr; mod ecb; +mod gcm; +mod ghash; mod iv; pub use cbc::Cbc; @@ -528,6 +537,7 @@ pub use cfb::Cfb; pub use cfb8::Cfb8; pub use ctr::Ctr; pub use ecb::Ecb; +pub use gcm::{GCM_NONCE_LEN, Gcm}; // Imports needed for docs #[allow(unused_imports)] diff --git a/crypto/modes/tests/acvp_gcm_tests.rs b/crypto/modes/tests/acvp_gcm_tests.rs new file mode 100644 index 00000000..f555dffb --- /dev/null +++ b/crypto/modes/tests/acvp_gcm_tests.rs @@ -0,0 +1,131 @@ +//! Known-answer tests against the NIST ACVP `ACVP-AES-GCM` vectors from the `bc-test-data` repo. +//! +//! Requires `bc-test-data` to be cloned alongside this repository, i.e. at `../bc-test-data` +//! relative to the root of this git project. If it is absent the test prints a warning and passes, +//! matching the convention used by the other ACVP suites in this crate. +//! +//! The set (`ACVP-AES-GCM.4014542`) covers all three AES key lengths, a 96-bit IV throughout, +//! 96- and 128-bit tags, payload lengths of 64/128/192 bits and AAD lengths of 128/256 bits, in +//! both directions -- 270 cases total. Not every decrypt case in this particular set is a +//! forgery, but the ones that are all report `testPassed: false`; the valid-decrypt path is +//! additionally exercised by round-tripping every encrypt case through both the detached one-shot +//! and the inline `SimpleCipherDecryptor` streaming view (`acvp_gcm::run_decrypt_case`, below). +//! +//! **Not covered here:** `bc-test-data` has no CAVP `.rsp` GCM vector files and no Wycheproof +//! `aes_gcm_test.json` -- only `sm4_gcm_test.json` exists under `wycheproof/`, and there is no +//! `GCM/cavp/` directory. This file and `acvp_gmac_tests.rs` are therefore the full extent of the +//! vector-based coverage against `bc-test-data`. If those files are added later, `cavp_gcm_tests.rs` +//! and `wycheproof_gcm_tests.rs` should be written against them following this file's shape. + +// Not `mod common;`: this crate-private helper's `serde_json::Value` usage, if pulled into the +// shared `common` module that most other test binaries in this crate include via `mod common;`, +// makes `u8: PartialEq<_>` ambiguous (`core`'s impl vs. serde_json's `impl PartialEq for +// u8`) at every bare `assert_eq!(byte_array, [])` in *those* files too -- `ecb_tests.rs` hit this +// exactly. Giving it its own module path keeps that ambiguity local to the two files that actually +// need ACVP JSON parsing. +#[path = "common/acvp_gcm.rs"] +mod acvp_gcm; + +use acvp_gcm::{GCM_NONCE_LEN, decode, run_decrypt_case, run_encrypt_case, test_data_dir}; +use serde_json::Value; +use std::collections::BTreeMap; +use std::fs; + +const SUBDIR: &str = "aes_tdes_vectors/GCM"; +const REQUEST_FILE: &str = "ACVP-AES-GCM.4014542.req.json"; +const RESPONSE_FILE: &str = "ACVP-AES-GCM.4014542.rsp.json"; + +#[test] +fn acvp_aes_gcm_known_answer_tests() { + let Some(dir) = test_data_dir(SUBDIR, REQUEST_FILE, RESPONSE_FILE) else { return }; + + let req: Value = serde_json::from_str( + &fs::read_to_string(dir.join(REQUEST_FILE)).expect("readable request file"), + ) + .expect("valid ACVP request JSON"); + let rsp: Value = serde_json::from_str( + &fs::read_to_string(dir.join(RESPONSE_FILE)).expect("readable response file"), + ) + .expect("valid ACVP response JSON"); + + // The response file carries only the answer, against a tcId. Index it. + let mut answers: BTreeMap = BTreeMap::new(); + for group in rsp[1]["testGroups"].as_array().expect("response testGroups") { + for test in group["tests"].as_array().expect("response tests") { + let tc_id = test["tcId"].as_u64().expect("tcId"); + answers.insert(tc_id, test.clone()); + } + } + + let groups = req[1]["testGroups"].as_array().expect("request testGroups"); + + let mut checked = 0usize; + let mut encrypt_checked = 0usize; + let mut decrypt_failed_checked = 0usize; + let mut per_kind: BTreeMap = BTreeMap::new(); + + for group in groups { + let direction = group["direction"].as_str().expect("direction"); + let tag_len = (group["tagLen"].as_u64().expect("tagLen") / 8) as usize; + let iv_len = group["ivLen"].as_u64().expect("ivLen"); + assert_eq!(iv_len, 96, "every group in this set has a 96-bit IV"); + + for test in group["tests"].as_array().expect("tests") { + let tc_id = test["tcId"].as_u64().expect("tcId"); + let key_bytes = decode(test, "key", tc_id); + let aad = decode(test, "aad", tc_id); + let iv_bytes = decode(test, "iv", tc_id); + let iv: [u8; GCM_NONCE_LEN] = iv_bytes + .try_into() + .unwrap_or_else(|_| panic!("tcId {tc_id}: expected a 12-byte IV")); + + match direction { + "encrypt" => { + let pt = decode(test, "pt", tc_id); + let answer = + answers.get(&tc_id).unwrap_or_else(|| panic!("tcId {tc_id}: no answer")); + let ct = decode(answer, "ct", tc_id); + let tag = decode(answer, "tag", tc_id); + run_encrypt_case(&key_bytes, iv, &aad, &pt, tag_len, &ct, &tag); + + // Also round-trip this known-good ciphertext through decryption, since every + // decrypt group in this particular ACVP set is a forgery (below) and this is + // otherwise the only valid-decrypt coverage this file would have. + run_decrypt_case(&key_bytes, iv, &aad, &ct, &tag, Some(&pt)); + encrypt_checked += 1; + } + "decrypt" => { + let ct = decode(test, "ct", tc_id); + let tag = decode(test, "tag", tc_id); + let answer = + answers.get(&tc_id).unwrap_or_else(|| panic!("tcId {tc_id}: no answer")); + // A forgery reports `testPassed: false` and no plaintext; a valid case reports + // `pt` directly, with no `testPassed` field at all (ACVP's convention: the key + // is present only to report failure). + if answer.get("testPassed").and_then(Value::as_bool) == Some(false) { + run_decrypt_case(&key_bytes, iv, &aad, &ct, &tag, None); + decrypt_failed_checked += 1; + } else { + let pt = decode(answer, "pt", tc_id); + run_decrypt_case(&key_bytes, iv, &aad, &ct, &tag, Some(&pt)); + } + } + other => panic!("unexpected direction {other}"), + } + + *per_kind.entry(format!("AES-{} {direction}", key_bytes.len() * 8)).or_default() += 1; + checked += 1; + } + } + + for (kind, n) in &per_kind { + println!("ACVP AES-GCM {kind}: {n} cases"); + } + println!( + "ACVP AES-GCM: {checked} cases checked ({encrypt_checked} encrypt, also round-tripped \ + through decrypt; {decrypt_failed_checked} decrypt forgeries)" + ); + + assert_eq!(checked, 270, "expected all 270 ACVP AES-GCM cases to run"); + assert!(encrypt_checked > 0 && decrypt_failed_checked > 0, "expected both directions covered"); +} diff --git a/crypto/modes/tests/acvp_gmac_tests.rs b/crypto/modes/tests/acvp_gmac_tests.rs new file mode 100644 index 00000000..4e58c3f2 --- /dev/null +++ b/crypto/modes/tests/acvp_gmac_tests.rs @@ -0,0 +1,109 @@ +//! Known-answer tests against the NIST ACVP `ACVP-AES-GMAC` vectors from the `bc-test-data` repo. +//! +//! Same joiner and shape as `acvp_gcm_tests.rs` (see its module docs for the `bc-test-data` +//! requirement and what is and is not covered against `bc-test-data`), over the GMAC set +//! (`ACVP-AES-GMAC.4014543`, 270 cases): `payloadLen` is 0 throughout -- SP 800-38D Sec 5.2, GMAC is +//! GCM restricted to `P = ""` -- with AAD lengths of 128/192/256 bits, both directions, all three +//! key lengths, 96- and 128-bit tags. + +// See `acvp_gcm_tests.rs` for why this is its own module path rather than `mod common;`. +#[path = "common/acvp_gcm.rs"] +mod acvp_gcm; + +use acvp_gcm::{GCM_NONCE_LEN, decode, run_decrypt_case, run_encrypt_case, test_data_dir}; +use serde_json::Value; +use std::collections::BTreeMap; +use std::fs; + +const SUBDIR: &str = "aes_tdes_vectors/GCM"; +const REQUEST_FILE: &str = "ACVP-AES-GMAC.4014543.req.json"; +const RESPONSE_FILE: &str = "ACVP-AES-GMAC.4014543.rsp.json"; + +#[test] +fn acvp_aes_gmac_known_answer_tests() { + let Some(dir) = test_data_dir(SUBDIR, REQUEST_FILE, RESPONSE_FILE) else { return }; + + let req: Value = serde_json::from_str( + &fs::read_to_string(dir.join(REQUEST_FILE)).expect("readable request file"), + ) + .expect("valid ACVP request JSON"); + let rsp: Value = serde_json::from_str( + &fs::read_to_string(dir.join(RESPONSE_FILE)).expect("readable response file"), + ) + .expect("valid ACVP response JSON"); + + let mut answers: BTreeMap = BTreeMap::new(); + for group in rsp[1]["testGroups"].as_array().expect("response testGroups") { + for test in group["tests"].as_array().expect("response tests") { + let tc_id = test["tcId"].as_u64().expect("tcId"); + answers.insert(tc_id, test.clone()); + } + } + + let groups = req[1]["testGroups"].as_array().expect("request testGroups"); + + let mut checked = 0usize; + let mut encrypt_checked = 0usize; + let mut decrypt_failed_checked = 0usize; + let mut per_kind: BTreeMap = BTreeMap::new(); + + for group in groups { + let direction = group["direction"].as_str().expect("direction"); + let tag_len = (group["tagLen"].as_u64().expect("tagLen") / 8) as usize; + let iv_len = group["ivLen"].as_u64().expect("ivLen"); + assert_eq!(iv_len, 96, "every group in this set has a 96-bit IV"); + let payload_len = group["payloadLen"].as_u64().expect("payloadLen"); + assert_eq!(payload_len, 0, "GMAC groups carry no plaintext"); + + for test in group["tests"].as_array().expect("tests") { + let tc_id = test["tcId"].as_u64().expect("tcId"); + let key_bytes = decode(test, "key", tc_id); + let aad = decode(test, "aad", tc_id); + let iv_bytes = decode(test, "iv", tc_id); + let iv: [u8; GCM_NONCE_LEN] = iv_bytes + .try_into() + .unwrap_or_else(|_| panic!("tcId {tc_id}: expected a 12-byte IV")); + + match direction { + "encrypt" => { + let answer = + answers.get(&tc_id).unwrap_or_else(|| panic!("tcId {tc_id}: no answer")); + let tag = decode(answer, "tag", tc_id); + // A GMAC "ciphertext" is always empty. + run_encrypt_case(&key_bytes, iv, &aad, &[], tag_len, &[], &tag); + run_decrypt_case(&key_bytes, iv, &aad, &[], &tag, Some(&[])); + encrypt_checked += 1; + } + "decrypt" => { + let tag = decode(test, "tag", tc_id); + let answer = + answers.get(&tc_id).unwrap_or_else(|| panic!("tcId {tc_id}: no answer")); + // See `acvp_gcm_tests.rs`: a forgery reports `testPassed: false`; a valid case + // reports success with no `testPassed` field at all (here there is no `pt` to + // report either, since GMAC's plaintext is always empty). + if answer.get("testPassed").and_then(Value::as_bool) == Some(false) { + run_decrypt_case(&key_bytes, iv, &aad, &[], &tag, None); + decrypt_failed_checked += 1; + } else { + run_decrypt_case(&key_bytes, iv, &aad, &[], &tag, Some(&[])); + } + } + other => panic!("unexpected direction {other}"), + } + + *per_kind.entry(format!("AES-{} {direction}", key_bytes.len() * 8)).or_default() += 1; + checked += 1; + } + } + + for (kind, n) in &per_kind { + println!("ACVP AES-GMAC {kind}: {n} cases"); + } + println!( + "ACVP AES-GMAC: {checked} cases checked ({encrypt_checked} encrypt, also round-tripped \ + through decrypt; {decrypt_failed_checked} decrypt forgeries)" + ); + + assert_eq!(checked, 270, "expected all 270 ACVP AES-GMAC cases to run"); + assert!(encrypt_checked > 0 && decrypt_failed_checked > 0, "expected both directions covered"); +} diff --git a/crypto/modes/tests/common/acvp_gcm.rs b/crypto/modes/tests/common/acvp_gcm.rs new file mode 100644 index 00000000..074e62eb --- /dev/null +++ b/crypto/modes/tests/common/acvp_gcm.rs @@ -0,0 +1,225 @@ +//! Shared plumbing for the ACVP AES-GCM and AES-GMAC known-answer test files +//! (`acvp_gcm_tests.rs`, `acvp_gmac_tests.rs`), whose request/response JSON shape is identical +//! between the two: GMAC is just the `payloadLen = 0` slice of the same ACVP AES-GCM protocol +//! (SP 800-38D Sec 5.2: GMAC is GCM restricted to `P = ""`). +//! +//! Requires `bc-test-data` to be cloned alongside this repository, i.e. at `../bc-test-data` +//! relative to the root of this git project. If it is absent, callers print a warning and skip, +//! matching the convention the other ACVP suites in this crate use. + +#![allow(dead_code)] + +use bouncycastle_aes::{AES_128, AES_192, AES_256}; +use bouncycastle_core::errors::SymmetricCipherError; +use bouncycastle_core::key_material::{ + KeyMaterial, KeyMaterialTrait, KeyType, do_hazardous_operations, +}; +use bouncycastle_core::traits::{SecurityStrength, SimpleCipherDecryptor, SimpleCipherEncryptor}; +use bouncycastle_core_test_framework::FixedSeedRNG; +use bouncycastle_hex as hex; +use bouncycastle_modes::{Decrypting, Encrypting, Gcm}; +use serde_json::Value; +use std::path::{Path, PathBuf}; + +/// The nonce length these vectors use; every group in the ACVP AES-GCM/GMAC sets has `ivLen = 96`. +pub const GCM_NONCE_LEN: usize = 12; + +/// Finds the directory holding `req_file` and `rsp_file` under either of the two candidate roots +/// this crate's other ACVP suites use, or `None` (with a printed warning) if neither has both. +pub fn test_data_dir(subdir: &str, req_file: &str, rsp_file: &str) -> Option { + let candidates = [ + format!("../../../bc-test-data/crypto/{subdir}"), + format!("../bc-test-data/crypto/{subdir}"), + ]; + for candidate in &candidates { + let path = Path::new(candidate); + if path.join(req_file).exists() && path.join(rsp_file).exists() { + return Some(path.to_path_buf()); + } + } + println!( + "WARNING: bc-test-data not found (looked in {candidates:?}); \ + this suite will be skipped" + ); + None +} + +/// Builds a `KeyMaterial` from raw ACVP key bytes, including the all-zero keys the set includes +/// deliberately: `KeyMaterial` tags an all-zero buffer as `KeyType::Zeroized` and will not promote +/// it outside a `do_hazardous_operations` closure, so this opts in explicitly. +pub fn cipher_key(bytes: &[u8]) -> KeyMaterial { + assert_eq!(bytes.len(), N, "key length should match the parameter set"); + let mut key = KeyMaterial::::from_bytes_as_type(bytes, KeyType::SymmetricCipherKey) + .expect("ACVP key bytes fit the buffer"); + if key.key_type() != KeyType::SymmetricCipherKey { + do_hazardous_operations(&mut key, |k| { + k.set_key_type(KeyType::SymmetricCipherKey)?; + k.set_security_strength(SecurityStrength::from_bytes(N)) + }) + .expect("promoting a NIST all-zero test key"); + } + key +} + +pub fn decode(value: &Value, field: &str, tc_id: u64) -> Vec { + let s = value + .get(field) + .and_then(Value::as_str) + .unwrap_or_else(|| panic!("tcId {tc_id}: missing field {field}")); + hex::decode(s).unwrap_or_else(|_| panic!("tcId {tc_id}: bad hex in {field}")) +} + +/// Runs one ACVP AES-GCM/GMAC encrypt case: encrypts `pt` under `key`/`aad`, driving the nonce +/// through a `FixedSeedRNG` seeded with the vector's own `iv` and asserting it is reproduced +/// exactly (so a change that ignored the RNG could not pass silently), then compares the resulting +/// ciphertext and tag against the response file's `ct`/`tag`. +pub fn run_encrypt_case( + key_bytes: &[u8], + iv: [u8; GCM_NONCE_LEN], + aad: &[u8], + pt: &[u8], + tag_len: usize, + expected_ct: &[u8], + expected_tag: &[u8], +) { + macro_rules! dispatch { + ($p:ty, $klen:literal) => {{ + let key = cipher_key::<$klen>(key_bytes); + let mut data = pt.to_vec(); + match tag_len { + 12 => run_encrypt::<$p, $klen, 12>(&key, iv, aad, &mut data, expected_tag), + 13 => run_encrypt::<$p, $klen, 13>(&key, iv, aad, &mut data, expected_tag), + 14 => run_encrypt::<$p, $klen, 14>(&key, iv, aad, &mut data, expected_tag), + 15 => run_encrypt::<$p, $klen, 15>(&key, iv, aad, &mut data, expected_tag), + 16 => run_encrypt::<$p, $klen, 16>(&key, iv, aad, &mut data, expected_tag), + other => panic!("unsupported ACVP tagLen {other} bytes"), + } + assert_eq!(data, expected_ct); + }}; + } + match key_bytes.len() { + 16 => dispatch!(AES_128, 16), + 24 => dispatch!(AES_192, 24), + 32 => dispatch!(AES_256, 32), + other => panic!("unexpected AES key length {other}"), + } +} + +fn run_encrypt( + key: &KeyMaterial, + iv: [u8; GCM_NONCE_LEN], + aad: &[u8], + data: &mut [u8], + expected_tag: &[u8], +) where + P: bouncycastle_core::traits::ElectronicCodeBook, +{ + let (mut enc, got_iv) = Gcm::::do_encrypt_init_rng( + key, + &mut FixedSeedRNG::::new(iv), + ) + .expect("encrypt init"); + assert_eq!(got_iv, iv, "the pinned RNG should reproduce the vector's IV"); + enc.do_update_aad(aad).expect("aad"); + enc.do_encrypt(data).expect("encrypt"); + let tag = enc.finish(); + assert_eq!(&tag[..], expected_tag, "tag mismatch"); +} + +/// Runs one ACVP AES-GCM/GMAC decrypt case: decrypts `ct` under `key`/`aad`/`iv` and either +/// compares against `expected_pt` (a valid case) or asserts `AEADTagCheckFailed` (a forgery) from +/// both the detached one-shot and the inline `decrypt_out`, with the plaintext buffer left +/// untouched in both. +pub fn run_decrypt_case( + key_bytes: &[u8], + iv: [u8; GCM_NONCE_LEN], + aad: &[u8], + ct: &[u8], + tag: &[u8], + expected_pt: Option<&[u8]>, +) { + macro_rules! dispatch { + ($p:ty, $klen:literal) => {{ + let key = cipher_key::<$klen>(key_bytes); + match tag.len() { + 12 => run_decrypt::<$p, $klen, 12>(&key, iv, aad, ct, tag, expected_pt), + 13 => run_decrypt::<$p, $klen, 13>(&key, iv, aad, ct, tag, expected_pt), + 14 => run_decrypt::<$p, $klen, 14>(&key, iv, aad, ct, tag, expected_pt), + 15 => run_decrypt::<$p, $klen, 15>(&key, iv, aad, ct, tag, expected_pt), + 16 => run_decrypt::<$p, $klen, 16>(&key, iv, aad, ct, tag, expected_pt), + other => panic!("unsupported ACVP tagLen {other} bytes"), + } + }}; + } + match key_bytes.len() { + 16 => dispatch!(AES_128, 16), + 24 => dispatch!(AES_192, 24), + 32 => dispatch!(AES_256, 32), + other => panic!("unexpected AES key length {other}"), + } +} + +fn run_decrypt( + key: &KeyMaterial, + iv: [u8; GCM_NONCE_LEN], + aad: &[u8], + ct: &[u8], + tag: &[u8], + expected_pt: Option<&[u8]>, +) where + P: bouncycastle_core::traits::ElectronicCodeBook, +{ + let tag_arr: [u8; TAG_LEN] = tag.try_into().expect("tag length matches TAG_LEN"); + + // The detached one-shot: AAD-capable, and never releases plaintext before the tag checks out. + let mut data = ct.to_vec(); + let one_shot_result = Gcm::::decrypt_detached( + key, &iv, aad, &mut data, &tag_arr, + ); + + // The inline `SimpleCipherDecryptor` streaming view, `ciphertext || tag` through + // `do_update_out`/`do_final`, with AAD fed via the inherent `do_update_aad` first. Note this is + // *not* the AAD-less static `decrypt_out` one-shot (which has no AAD parameter at all and so + // cannot be checked against these vectors, none of which have empty AAD): the streaming path + // is where the inline layout meets AAD support, and unlike the one-shot it releases plaintext + // before the tag is checked -- see `gcm_tests.rs` for that distinction pinned with empty AAD. + let mut dec = + Gcm::::do_decrypt_init(key, &iv).expect("decrypt init"); + dec.do_update_aad(aad).expect("aad"); + let mut inline_ct = ct.to_vec(); + inline_ct.extend_from_slice(tag); + let expect_written = dec.update_out_len(inline_ct.len()); + let mut inline_pt = vec![0u8; expect_written]; + let written = dec + .do_update_out(&inline_ct, &mut inline_pt) + .expect("do_update_out on a correctly sized buffer must not fail"); + assert_eq!(written, expect_written, "update_out_len must be exact"); + let inline_result = dec.do_final(); + + match expected_pt { + Some(pt) => { + assert!( + one_shot_result.is_ok(), + "detached one-shot should have verified: {one_shot_result:?}" + ); + assert_eq!(data, pt, "detached one-shot plaintext mismatch"); + + assert!(inline_result.is_ok(), "inline stream should have verified: {inline_result:?}"); + assert_eq!(written, pt.len(), "inline stream released the wrong length"); + assert_eq!(&inline_pt[..written], pt, "inline stream plaintext mismatch"); + } + None => { + let before = ct.to_vec(); + assert!( + matches!(one_shot_result, Err(SymmetricCipherError::AEADTagCheckFailed)), + "expected AEADTagCheckFailed from the detached one-shot, got {one_shot_result:?}" + ); + assert_eq!(data, before, "a forged tag must leave the one-shot buffer untouched"); + + assert!( + matches!(inline_result, Err(SymmetricCipherError::AEADTagCheckFailed)), + "expected AEADTagCheckFailed from the inline stream's do_final, got {inline_result:?}" + ); + } + } +} diff --git a/crypto/modes/tests/gcm_bc_java_tests.rs b/crypto/modes/tests/gcm_bc_java_tests.rs new file mode 100644 index 00000000..63075caf --- /dev/null +++ b/crypto/modes/tests/gcm_bc_java_tests.rs @@ -0,0 +1,244 @@ +//! Cross-implementation tests against BC Java's `GCMTest.java` `TEST_VECTORS` table +//! (`core/src/test/java/org/bouncycastle/crypto/test/GCMTest.java`), which is itself a transcription +//! of the McGrew/Viega "The Galois/Counter Mode of Operation (GCM)" Appendix B test vectors. +//! +//! Only the cases whose IV is 96 bits are usable here (D2 / the implementation plan): of the 18 +//! vectors, cases 5, 11 and 17 use a 64-bit IV and cases 6, 12 and 18 use a 480-bit IV, both of +//! which exercise the `len(IV) != 96` GHASH-derived-`J0` branch of Algorithm 4 step 2 that this +//! crate does not implement. The remaining twelve (1, 2, 3, 4, 7, 8, 9, 10, 13, 14, 15, 16) are +//! transcribed below, verified against the bc-java source read this session, with all-zero fields +//! built programmatically rather than typed out (a zero key or plaintext cannot be mistyped). + +use bouncycastle_aes::{AES_128, AES_192, AES_256}; +use bouncycastle_core::key_material::{KeyMaterial, KeyMaterialTrait, KeyType}; +use bouncycastle_core::traits::SimpleCipherEncryptor; +use bouncycastle_core_test_framework::FixedSeedRNG; +use bouncycastle_hex as hex; +use bouncycastle_modes::{Decrypting, Encrypting, Gcm}; + +fn zeros(byte_len: usize) -> String { + "00".repeat(byte_len) +} + +/// One BC Java `TEST_VECTORS` row: (name, key, plaintext, aad, iv, expected ciphertext, expected +/// tag), all as hex strings. +struct Case { + name: &'static str, + key: String, + pt: String, + aad: &'static str, + iv: &'static str, + ct: String, + tag: &'static str, +} + +fn cases() -> Vec { + let k128 = "feffe9928665731c6d6a8f9467308308".to_string(); + let k192 = format!("{k128}feffe9928665731c"); + let k256 = format!("{k128}{k128}"); + + let p_full = "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72\ + 1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b391aafd255" + .to_string(); + let p_partial = "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72\ + 1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39" + .to_string(); + let aad = "feedfacedeadbeeffeedfacedeadbeefabaddad2"; + let iv_zero = "000000000000000000000000"; + let iv_cafe = "cafebabefacedbaddecaf888"; + + let c3_full = "42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e\ + 21d514b25466931c7d8f6a5aac84aa051ba30b396a0aac973d58e091473f5985" + .to_string(); + let c4_partial = "42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e\ + 21d514b25466931c7d8f6a5aac84aa051ba30b396a0aac973d58e091" + .to_string(); + let c9_full = "3980ca0b3c00e841eb06fac4872a2757859e1ceaa6efd984628593b40ca1e19c\ + 7d773d00c144c525ac619d18c84a3f4718e2448b2fe324d9ccda2710acade256" + .to_string(); + let c10_partial = "3980ca0b3c00e841eb06fac4872a2757859e1ceaa6efd984628593b40ca1e19c\ + 7d773d00c144c525ac619d18c84a3f4718e2448b2fe324d9ccda2710" + .to_string(); + let c15_full = "522dc1f099567d07f47f37a32a84427d643a8cdcbfe5c0c97598a2bd2555d1aa\ + 8cb08e48590dbb3da7b08b1056828838c5f61e6393ba7a0abcc9f662898015ad" + .to_string(); + let c16_partial = "522dc1f099567d07f47f37a32a84427d643a8cdcbfe5c0c97598a2bd2555d1aa\ + 8cb08e48590dbb3da7b08b1056828838c5f61e6393ba7a0abcc9f662" + .to_string(); + + vec![ + Case { + name: "Test Case 1", + key: zeros(16), + pt: String::new(), + aad: "", + iv: iv_zero, + ct: String::new(), + tag: "58e2fccefa7e3061367f1d57a4e7455a", + }, + Case { + name: "Test Case 2", + key: zeros(16), + pt: zeros(16), + aad: "", + iv: iv_zero, + ct: "0388dace60b6a392f328c2b971b2fe78".to_string(), + tag: "ab6e47d42cec13bdf53a67b21257bddf", + }, + Case { + name: "Test Case 3", + key: k128.clone(), + pt: p_full.clone(), + aad: "", + iv: iv_cafe, + ct: c3_full, + tag: "4d5c2af327cd64a62cf35abd2ba6fab4", + }, + Case { + name: "Test Case 4", + key: k128.clone(), + pt: p_partial.clone(), + aad, + iv: iv_cafe, + ct: c4_partial, + tag: "5bc94fbc3221a5db94fae95ae7121a47", + }, + Case { + name: "Test Case 7", + key: zeros(24), + pt: String::new(), + aad: "", + iv: iv_zero, + ct: String::new(), + tag: "cd33b28ac773f74ba00ed1f312572435", + }, + Case { + name: "Test Case 8", + key: zeros(24), + pt: zeros(16), + aad: "", + iv: iv_zero, + ct: "98e7247c07f0fe411c267e4384b0f600".to_string(), + tag: "2ff58d80033927ab8ef4d4587514f0fb", + }, + Case { + name: "Test Case 9", + key: k192.clone(), + pt: p_full.clone(), + aad: "", + iv: iv_cafe, + ct: c9_full, + tag: "9924a7c8587336bfb118024db8674a14", + }, + Case { + name: "Test Case 10", + key: k192.clone(), + pt: p_partial.clone(), + aad, + iv: iv_cafe, + ct: c10_partial, + tag: "2519498e80f1478f37ba55bd6d27618c", + }, + Case { + name: "Test Case 13", + key: zeros(32), + pt: String::new(), + aad: "", + iv: iv_zero, + ct: String::new(), + tag: "530f8afbc74536b9a963b4f1c4cb738b", + }, + Case { + name: "Test Case 14", + key: zeros(32), + pt: zeros(16), + aad: "", + iv: iv_zero, + ct: "cea7403d4d606b6e074ec5d3baf39d18".to_string(), + tag: "d0d1c8a799996bf0265b98b5d48ab919", + }, + Case { + name: "Test Case 15", + key: k256.clone(), + pt: p_full, + aad: "", + iv: iv_cafe, + ct: c15_full, + tag: "b094dac5d93471bdec1a502270e3cc6c", + }, + Case { + name: "Test Case 16", + key: k256, + pt: p_partial, + aad, + iv: iv_cafe, + ct: c16_partial, + tag: "76fc6ece0f4e1768cddf8853bb2d551b", + }, + ] +} + +fn run(case: &Case) +where + P: bouncycastle_core::traits::ElectronicCodeBook, +{ + let key_bytes = hex::decode(&case.key).expect("valid hex key"); + // `KeyMaterial` tags an all-zero buffer as `KeyType::Zeroized` regardless of the type + // requested, and will not promote it outside a `do_hazardous_operations` closure. The + // zero-key cases (1, 2, 7, 8, 13, 14) need that opt-in, same as the ACVP suites' `cipher_key`. + let mut key = + KeyMaterial::::from_bytes_as_type(&key_bytes, KeyType::SymmetricCipherKey) + .expect("key bytes fit the buffer"); + if key.key_type() != KeyType::SymmetricCipherKey { + bouncycastle_core::key_material::do_hazardous_operations(&mut key, |k| { + k.set_key_type(KeyType::SymmetricCipherKey)?; + k.set_security_strength(bouncycastle_core::traits::SecurityStrength::from_bytes( + KEY_LEN, + )) + }) + .expect("promoting a known-zero test key"); + } + + let aad = hex::decode(case.aad).expect("valid hex aad"); + let pt = hex::decode(&case.pt).expect("valid hex pt"); + let iv_bytes = hex::decode(case.iv).expect("valid hex iv"); + let iv: [u8; 12] = iv_bytes.try_into().expect("a 96-bit IV"); + let expected_ct = hex::decode(&case.ct).expect("valid hex ct"); + let expected_tag = hex::decode(case.tag).expect("valid hex tag"); + + let mut data = pt.clone(); + let (mut enc, got_iv) = Gcm::::do_encrypt_init_rng( + &key, + &mut FixedSeedRNG::<12>::new(iv), + ) + .expect("encrypt init"); + assert_eq!(got_iv, iv, "{}: the pinned RNG should reproduce the vector's IV", case.name); + enc.do_update_aad(&aad).unwrap(); + enc.do_encrypt(&mut data).unwrap(); + let tag = enc.finish(); + + assert_eq!(data, expected_ct, "{}: ciphertext mismatch", case.name); + assert_eq!(&tag[..], &expected_tag[..], "{}: tag mismatch", case.name); + + let tag_arr: [u8; 16] = expected_tag.try_into().expect("16-byte tag"); + Gcm::::decrypt_detached(&key, &iv, &aad, &mut data, &tag_arr) + .unwrap_or_else(|e| panic!("{}: decrypt should have verified, got {e:?}", case.name)); + assert_eq!(data, pt, "{}: decrypted plaintext mismatch", case.name); +} + +#[test] +fn bc_java_test_vectors_with_a_96_bit_iv() { + let mut checked = 0usize; + for case in cases() { + let key_len_bytes = case.key.len() / 2; + match key_len_bytes { + 16 => run::(&case), + 24 => run::(&case), + 32 => run::(&case), + other => panic!("{}: unexpected key length {other} bytes", case.name), + } + checked += 1; + } + println!("bc-java GCMTest 96-bit-IV vectors: {checked} cases checked"); + assert_eq!(checked, 12, "expected the twelve 96-bit-IV McGrew/Viega vectors"); +} diff --git a/crypto/modes/tests/gcm_tests.rs b/crypto/modes/tests/gcm_tests.rs new file mode 100644 index 00000000..c4a74230 --- /dev/null +++ b/crypto/modes/tests/gcm_tests.rs @@ -0,0 +1,247 @@ +//! Structural tests for GCM, driven by a toy permutation and by real AES. +//! +//! These check the properties of the *mode* -- AAD-before-data ordering, chunking independence, +//! the tag-length family, the inline decryptor's tail hold-back, and the one-shot's +//! verify-before-decrypt guarantee -- independently of (or alongside) the ACVP/bc-java known-answer +//! vectors in `acvp_gcm_tests.rs`, `acvp_gmac_tests.rs` and `gcm_bc_java_tests.rs`. + +mod common; + +use bouncycastle_aes::{AES_128, AES_192, AES_256}; +use bouncycastle_core::errors::SymmetricCipherError; +use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +use bouncycastle_core::traits::{SimpleCipherDecryptor, SimpleCipherEncryptor}; +use bouncycastle_modes::{Decrypting, Encrypting, Gcm}; +use common::{TOY_LEN, Toy, toy_key}; + +type ToyGcm = Gcm; + +/// AAD must precede data (SP 800-38D Algorithm 4 absorbs `A` before `C`); a non-empty AAD call +/// after data has started is refused, while an empty one is always accepted as a no-op. +#[test] +fn aad_after_data_is_a_state_error_unless_empty() { + let key = toy_key(); + let (mut enc, _nonce) = Gcm::::do_encrypt_init(&key).unwrap(); + enc.do_update_aad(b"header").unwrap(); + let mut data = [0x11u8; 8]; + enc.do_encrypt(&mut data).unwrap(); + + match enc.do_update_aad(b"too late") { + Err(SymmetricCipherError::StateError(_)) => {} + other => panic!("expected StateError, got {other:?}"), + } + // An empty call after data is always fine. + enc.do_update_aad(&[]).unwrap(); + let _ = enc.finish(); +} + +/// Chunking independence for both AAD and data: every split of a 40-byte AAD and a 50-byte message +/// must give the same ciphertext and tag as absorbing each in one call. +#[test] +fn chunking_is_independent_for_aad_and_data() { + let key = toy_key(); + let aad: [u8; 40] = core::array::from_fn(|i| i as u8); + let message: [u8; 50] = core::array::from_fn(|i| (i as u8).wrapping_mul(3).wrapping_add(1)); + + let (nonce, expected_ct, expected_tag) = { + let mut data = message; + let (nonce, tag) = + Gcm::::encrypt_detached(&key, &aad, &mut data).unwrap(); + (nonce, data, tag) + }; + + for aad_split in [0usize, 1, 17, 40] { + for data_split in [0usize, 1, 23, 50] { + let (mut enc, got_nonce) = Gcm::::do_encrypt_init_rng( + &key, + &mut bouncycastle_core_test_framework::FixedSeedRNG::<12>::new(nonce), + ) + .unwrap(); + assert_eq!(got_nonce, nonce); + enc.do_update_aad(&aad[..aad_split]).unwrap(); + enc.do_update_aad(&aad[aad_split..]).unwrap(); + let mut data = message; + enc.do_encrypt(&mut data[..data_split]).unwrap(); + enc.do_encrypt(&mut data[data_split..]).unwrap(); + let tag = enc.finish(); + assert_eq!(data, expected_ct, "aad_split {aad_split}, data_split {data_split}"); + assert_eq!(tag, expected_tag, "aad_split {aad_split}, data_split {data_split}"); + } + } +} + +/// Tag-length variants 12..=16 all round-trip, and the 12-byte tag is a prefix of the 16-byte tag +/// for the same inputs -- Algorithm 4 step 6's `T = MSB_t(...)`. +#[test] +fn tag_length_variants_round_trip_and_nest() { + let key = toy_key(); + let aad = b"associated"; + let message = *b"a toy message, sixteen+"; + + let mut data16 = message; + let (nonce, tag16) = + ToyGcm::::encrypt_detached(&key, aad, &mut data16).unwrap(); + + macro_rules! check_tag_len { + ($n:literal) => {{ + let mut data = message; + let (n, tag) = ToyGcm::::encrypt_detached_rng( + &key, + &mut bouncycastle_core_test_framework::FixedSeedRNG::<12>::new(nonce), + aad, + &mut data, + ) + .unwrap(); + assert_eq!(n, nonce); + assert_eq!(data, data16, "ciphertext must not depend on TAG_LEN ({})", $n); + assert_eq!( + &tag16[..$n], + &tag[..], + "TAG_LEN={} must be a prefix of the 16-byte tag", + $n + ); + ToyGcm::::decrypt_detached(&key, &n, aad, &mut data, &tag).unwrap(); + assert_eq!(data, message); + }}; + } + check_tag_len!(12); + check_tag_len!(13); + check_tag_len!(14); + check_tag_len!(15); + check_tag_len!(16); +} + +/// GMAC: an all-AAD message (no plaintext at all) still produces a valid tag, and decrypting zero +/// bytes of ciphertext against it verifies. Sec 5.2: GMAC is GCM restricted to `P = ""`. +#[test] +fn an_aad_only_message_is_gmac() { + let key = toy_key(); + let aad = b"the whole message is AAD"; + let mut nothing: [u8; 0] = []; + + let (nonce, tag) = ToyGcm::::encrypt_detached(&key, aad, &mut nothing).unwrap(); + ToyGcm::::decrypt_detached(&key, &nonce, aad, &mut nothing, &tag).unwrap(); + + // Wrong AAD must fail verification. + match ToyGcm::::decrypt_detached(&key, &nonce, b"wrong", &mut nothing, &tag) { + Err(SymmetricCipherError::AEADTagCheckFailed) => {} + other => panic!("expected AEADTagCheckFailed, got {other:?}"), + } +} + +/// The inline decryptor: input of exactly `TAG_LEN` bytes decrypts to nothing and verifies; input +/// shorter than `TAG_LEN` is `DecryptionFailed`. +#[test] +fn inline_decryptor_handles_short_and_tag_only_input() { + let key = toy_key(); + let mut nothing: [u8; 0] = []; + let (nonce, tag) = ToyGcm::::encrypt_detached(&key, b"", &mut nothing).unwrap(); + + let mut plaintext = [0u8; 16]; + let n = ToyGcm::::decrypt_out(&key, &nonce, &tag, &mut plaintext).unwrap(); + assert_eq!(n, 0, "a tag-only input releases no plaintext"); + + for short_len in 0..16 { + let short = &tag[..short_len]; + match ToyGcm::::decrypt_out(&key, &nonce, short, &mut plaintext) { + Err(SymmetricCipherError::DecryptionFailed) => {} + other => panic!("len {short_len}: expected DecryptionFailed, got {other:?}"), + } + } +} + +/// `update_out_len` must be exact across an irregular sequence of call sizes that walks through +/// the tail hold-back boundary. +#[test] +fn update_out_len_is_exact_across_irregular_chunking() { + let key = toy_key(); + let message: [u8; 64] = core::array::from_fn(|i| i as u8); + let mut ct = message; + let (nonce, tag) = ToyGcm::::encrypt_detached(&key, b"aad", &mut ct).unwrap(); + let mut full_ct = [0u8; 80]; + full_ct[..64].copy_from_slice(&ct); + full_ct[64..].copy_from_slice(&tag); + + let mut dec = ToyGcm::::do_decrypt_init(&key, &nonce).unwrap(); + dec.do_update_aad(b"aad").unwrap(); + let mut released = 0usize; + for chunk in [1usize, 15, 16, 17, 31] { + let piece = &full_ct[released.min(full_ct.len())..(released + chunk).min(full_ct.len())]; + if piece.is_empty() { + continue; + } + let expect = dec.update_out_len(piece.len()); + let mut buf = vec![0u8; expect]; + let n = dec.do_update_out(piece, &mut buf).unwrap(); + assert_eq!(n, expect, "chunk {chunk}"); + released += piece.len(); + } + // Drain whatever remains. + let rest = &full_ct[released..]; + let expect = dec.update_out_len(rest.len()); + let mut buf = vec![0u8; expect]; + dec.do_update_out(rest, &mut buf).unwrap(); + let (_last, last_len) = dec.do_final().unwrap(); + assert_eq!(last_len, 0); +} + +/// A forged tag leaves the one-shot's output buffer untouched, while the streaming path (by its +/// nature) has already written plaintext before the forgery is detected. Pinning the difference. +#[test] +fn one_shot_leaves_the_buffer_untouched_on_forgery_but_streaming_does_not() { + let key = toy_key(); + let message = *b"do not trust me yet"; + let mut ct = message; + let (nonce, mut tag) = + ToyGcm::::encrypt_detached(&key, b"aad", &mut ct).unwrap(); + tag[0] ^= 0xFF; // forge it + + // One-shot: verify-then-decrypt, so a forged tag must leave `data` exactly as it was. + let mut one_shot_buf = ct; + let before = one_shot_buf; + match ToyGcm::::decrypt_detached(&key, &nonce, b"aad", &mut one_shot_buf, &tag) + { + Err(SymmetricCipherError::AEADTagCheckFailed) => {} + other => panic!("expected AEADTagCheckFailed, got {other:?}"), + } + assert_eq!(one_shot_buf, before, "the one-shot must not touch the buffer on a forged tag"); + + // Streaming: do_decrypt has already released (wrong) plaintext by the time finish() fails. + let mut dec = ToyGcm::::do_decrypt_init(&key, &nonce).unwrap(); + dec.do_update_aad(b"aad").unwrap(); + let mut streaming_buf = ct; + dec.do_decrypt(&mut streaming_buf).unwrap(); + assert_eq!(streaming_buf, message, "streaming already produced the (correct) plaintext"); + match dec.finish(&tag) { + Err(SymmetricCipherError::AEADTagCheckFailed) => {} + other => panic!("expected AEADTagCheckFailed, got {other:?}"), + } +} + +/// The one-shots and the inline `SimpleCipherEncryptor`/`Decryptor` view round-trip with real AES +/// at all three key lengths, at a length that is not a whole number of blocks. +#[test] +fn the_aes_aliases_round_trip() { + fn check(key_bytes: &[u8]) + where + P: bouncycastle_core::traits::ElectronicCodeBook, + { + let key = + KeyMaterial::::from_bytes_as_type(key_bytes, KeyType::SymmetricCipherKey) + .unwrap(); + let aad = b"associated data of no particular length"; + let message = b"a message that is not a whole number of blocks!!"; + + let mut data = *message; + let (nonce, tag) = + Gcm::::encrypt_detached(&key, aad, &mut data).unwrap(); + assert_ne!(&data[..], &message[..]); + Gcm::::decrypt_detached(&key, &nonce, aad, &mut data, &tag) + .unwrap(); + assert_eq!(&data[..], &message[..]); + } + + check::(&[0x11; 16]); + check::(&[0x22; 24]); + check::(&[0x33; 32]); +}