Skip to content

Commit

Permalink
fix(ext/node): fix panic when invalid AES GCM key size (#27818)
Browse files Browse the repository at this point in the history
Fixes #27807
  • Loading branch information
littledivy authored Jan 27, 2025
1 parent a2d0872 commit f678a17
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
17 changes: 17 additions & 0 deletions ext/node/ops/crypto/cipher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use aes::cipher::block_padding::Pkcs7;
use aes::cipher::BlockDecryptMut;
use aes::cipher::BlockEncryptMut;
use aes::cipher::KeyIvInit;
use aes::cipher::KeySizeUser;
use deno_core::Resource;
use digest::generic_array::GenericArray;
use digest::KeyInit;
Expand Down Expand Up @@ -190,12 +191,20 @@ impl Cipher {
"aes-192-ecb" => Aes192Ecb(Box::new(ecb::Encryptor::new(key.into()))),
"aes-256-ecb" => Aes256Ecb(Box::new(ecb::Encryptor::new(key.into()))),
"aes-128-gcm" => {
if key.len() != aes::Aes128::key_size() {
return Err(CipherError::InvalidKeyLength);
}

let cipher =
aead_gcm_stream::AesGcm::<aes::Aes128>::new(key.into(), iv);

Aes128Gcm(Box::new(cipher))
}
"aes-256-gcm" => {
if key.len() != aes::Aes256::key_size() {
return Err(CipherError::InvalidKeyLength);
}

let cipher =
aead_gcm_stream::AesGcm::<aes::Aes256>::new(key.into(), iv);

Expand Down Expand Up @@ -406,12 +415,20 @@ impl Decipher {
"aes-192-ecb" => Aes192Ecb(Box::new(ecb::Decryptor::new(key.into()))),
"aes-256-ecb" => Aes256Ecb(Box::new(ecb::Decryptor::new(key.into()))),
"aes-128-gcm" => {
if key.len() != aes::Aes128::key_size() {
return Err(DecipherError::InvalidKeyLength);
}

let decipher =
aead_gcm_stream::AesGcm::<aes::Aes128>::new(key.into(), iv);

Aes128Gcm(Box::new(decipher))
}
"aes-256-gcm" => {
if key.len() != aes::Aes256::key_size() {
return Err(DecipherError::InvalidKeyLength);
}

let decipher =
aead_gcm_stream::AesGcm::<aes::Aes256>::new(key.into(), iv);

Expand Down
29 changes: 29 additions & 0 deletions tests/unit_node/crypto/crypto_cipher_gcm_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,3 +143,32 @@ Deno.test({
);
},
});

Deno.test({
name: "aes gcm with invalid key length",
fn() {
assertThrows(
() => {
crypto.createCipheriv(
"aes-128-gcm",
Buffer.alloc(15),
Buffer.alloc(12),
);
},
Error,
"Invalid key length",
);

assertThrows(
() => {
crypto.createCipheriv(
"aes-256-gcm",
Buffer.alloc(31),
Buffer.alloc(12),
);
},
Error,
"Invalid key length",
);
},
});

0 comments on commit f678a17

Please sign in to comment.