Skip to content

Truly independent web browser

LibCrypto+LibWeb: Wrap only the AES-CTR counter's length bits

Shannon Booth8ad19f25a83a
diff --git a/Libraries/LibCrypto/Rust/src/lib.rs b/Libraries/LibCrypto/Rust/src/lib.rs
index e73d58e7d1c..617e3b8c508 100644
--- a/Libraries/LibCrypto/Rust/src/lib.rs
+++ b/Libraries/LibCrypto/Rust/src/lib.rs
@@ -361,7 +361,50 @@ pub fn aes_cbc_cipher(encrypt: bool, key: &[u8], input: &[u8], iv: &[u8]) -> Res
Ok(bytes)
}
-pub fn aes_ctr_cipher(encrypt: bool, key: &[u8], input: &[u8], counter: &[u8]) -> Result<Vec<u8>, BackendError> {
+/// Increments only the low `counter_length` bits of the counter block, modulo 2^counter_length, as the standard
+/// incrementing function of NIST SP 800-38A Appendix B.1 does.
+pub fn aes_ctr_cipher(
+ encrypt: bool,
+ key: &[u8],
+ input: &[u8],
+ counter: &[u8],
+ counter_length: u8,
+) -> Result<Vec<u8>, BackendError> {
+ let counter_block: [u8; 16] = counter.try_into().map_err(|_| BackendError)?;
+ if counter_length == 0 || counter_length > 128 {
+ return Err(BackendError);
+ }
+
+ // The native cipher increments the whole block, so split the input where the low bits wrap around.
+ let mask = u128::MAX >> (128 - u32::from(counter_length));
+ let mut block = u128::from_be_bytes(counter_block);
+ let mut output = Vec::with_capacity(input.len());
+ let mut remaining = input;
+ while !remaining.is_empty() {
+ let blocks_until_wrap = (mask - (block & mask)).checked_add(1);
+ let segment_length = match blocks_until_wrap.and_then(|blocks| blocks.checked_mul(16)) {
+ Some(bytes) if bytes < remaining.len() as u128 => bytes as usize,
+ _ => remaining.len(),
+ };
+ let (segment, rest) = remaining.split_at(segment_length);
+ output.extend(aes_ctr_cipher_whole_block_counter(
+ encrypt,
+ key,
+ segment,
+ &block.to_be_bytes(),
+ )?);
+ remaining = rest;
+ block &= !mask;
+ }
+ Ok(output)
+}
+
+fn aes_ctr_cipher_whole_block_counter(
+ encrypt: bool,
+ key: &[u8],
+ input: &[u8],
+ counter: &[u8],
+) -> Result<Vec<u8>, BackendError> {
// SAFETY: Inputs and output are borrowed for the synchronous native call.
let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
ffi::crypto_aes_ctr_cipher(
diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs
index dab1f624fd3..729da73b305 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs
@@ -3524,9 +3524,14 @@ impl AlgorithmMethods for AesCtr {
// value of the counter block, the length member of normalizedAlgorithm as the input parameter m to the
// standard counter block incrementing function defined in Appendix B.1 of [NIST-SP800-38A] and plaintext as
// the input plaintext.
- let ciphertext =
- libcrypto_rust::aes_ctr_cipher(true, key.byte_handle_bytes(), plaintext.as_slice(), counter.as_slice())
- .map(Bytes::new);
+ let ciphertext = libcrypto_rust::aes_ctr_cipher(
+ true,
+ key.byte_handle_bytes(),
+ plaintext.as_slice(),
+ counter.as_slice(),
+ normalized_algorithm.length,
+ )
+ .map(Bytes::new);
if ciphertext.is_err() {
return Err(dom_error("OperationError", b"Encryption failed"));
}
@@ -3574,6 +3579,7 @@ impl AlgorithmMethods for AesCtr {
key.byte_handle_bytes(),
ciphertext.as_slice(),
counter.as_slice(),
+ normalized_algorithm.length,
)
.map(Bytes::new);
if plaintext.is_err() {
diff --git a/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-AESCTR-counter-length.txt b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-AESCTR-counter-length.txt
new file mode 100644
index 00000000000..746cf359c53
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-AESCTR-counter-length.txt
@@ -0,0 +1,7 @@
+length 8, first block is E(counter): true
+length 8, second block is E(wrapped): true
+length 8, second block is E(carried): false
+length 8, third block is E(wrapped + 1): true
+length 128, second block is E(carried): true
+length 128, all ones wraps to zero: true
+length 4, round trip: true
diff --git a/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-AESCTR-counter-length.html b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-AESCTR-counter-length.html
new file mode 100644
index 00000000000..ca235d3aee7
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-AESCTR-counter-length.html
@@ -0,0 +1,64 @@
+<!doctype html>
+<script src="../include.js"></script>
+<script>
+ function hex(buffer) {
+ return Array.from(new Uint8Array(buffer), byte => byte.toString(16).padStart(2, "0")).join("");
+ }
+
+ async function keystreamBlocks(key, counter, length, blockCount) {
+ const keystream = await crypto.subtle.encrypt(
+ { name: "AES-CTR", counter, length },
+ key,
+ new Uint8Array(16 * blockCount)
+ );
+ const blocks = [];
+ for (let i = 0; i < blockCount; ++i)
+ blocks.push(hex(keystream.slice(16 * i, 16 * (i + 1))));
+ return blocks;
+ }
+
+ async function encryptBlock(key, counterBlock) {
+ const ecb = await crypto.subtle.encrypt(
+ { name: "AES-CTR", counter: counterBlock, length: 128 },
+ key,
+ new Uint8Array(16)
+ );
+ return hex(ecb);
+ }
+
+ promiseTest(async () => {
+ const key = await crypto.subtle.importKey("raw", new Uint8Array(16), "AES-CTR", false, ["encrypt", "decrypt"]);
+
+ // The low 8 bits wrap after the first block, so the second counter block keeps its upper bits.
+ const counter = new Uint8Array(16).fill(0xab);
+ counter[15] = 0xff;
+ const wrapped = new Uint8Array(counter);
+ wrapped[15] = 0x00;
+ const carried = new Uint8Array(counter);
+ carried[14] = 0xac;
+ carried[15] = 0x00;
+
+ const blocks = await keystreamBlocks(key, counter, 8, 3);
+ const next = new Uint8Array(wrapped);
+ next[15] = 0x01;
+ println(`length 8, first block is E(counter): ${blocks[0] === (await encryptBlock(key, counter))}`);
+ println(`length 8, second block is E(wrapped): ${blocks[1] === (await encryptBlock(key, wrapped))}`);
+ println(`length 8, second block is E(carried): ${blocks[1] === (await encryptBlock(key, carried))}`);
+ println(`length 8, third block is E(wrapped + 1): ${blocks[2] === (await encryptBlock(key, next))}`);
+
+ // With the full 128 bits as the counter, the increment carries into every byte.
+ const fullBlocks = await keystreamBlocks(key, counter, 128, 2);
+ println(`length 128, second block is E(carried): ${fullBlocks[1] === (await encryptBlock(key, carried))}`);
+
+ // A counter of all ones wraps to zero with length 128.
+ const ones = new Uint8Array(16).fill(0xff);
+ const onesBlocks = await keystreamBlocks(key, ones, 128, 2);
+ println(`length 128, all ones wraps to zero: ${onesBlocks[1] === (await encryptBlock(key, new Uint8Array(16)))}`);
+
+ // Decryption uses the same counter blocks.
+ const plaintext = new Uint8Array(40).map((_, i) => i);
+ const ciphertext = await crypto.subtle.encrypt({ name: "AES-CTR", counter, length: 4 }, key, plaintext);
+ const decrypted = await crypto.subtle.decrypt({ name: "AES-CTR", counter, length: 4 }, key, ciphertext);
+ println(`length 4, round trip: ${hex(decrypted) === hex(plaintext)}`);
+ });
+</script>