Skip to content

Commit

Permalink
Improve MAC validation
Browse files Browse the repository at this point in the history
  • Loading branch information
dani-garcia committed Nov 17, 2023
1 parent a55c2d7 commit 6a9e96c
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 5 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/bitwarden/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ pbkdf2 = { version = ">=0.12.1, <0.13", default-features = false }
argon2 = { version = ">=0.5.0, <0.6", features = [
"alloc",
], default-features = false }
subtle = ">=2.5.0, <3.0"
rand = ">=0.8.5, <0.9"
num-bigint = ">=0.4, <0.5"
num-traits = ">=0.2.15, <0.3"
Expand Down
11 changes: 6 additions & 5 deletions crates/bitwarden/src/crypto/aes_ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use aes::cipher::{
};
use hmac::Mac;
use rand::RngCore;
use subtle::ConstantTimeEq;

use crate::{
crypto::{EncString, PbkdfSha256Hmac, PBKDF_SHA256_HMAC_OUT_SIZE},
Expand Down Expand Up @@ -48,8 +49,8 @@ pub fn decrypt_aes256_hmac(
mac_key: GenericArray<u8, U32>,
key: GenericArray<u8, U32>,
) -> Result<Vec<u8>> {
let res = validate_mac(&mac_key, iv, &data)?;
if res != *mac {
let res = generate_mac(&mac_key, iv, &data)?;
if res.ct_ne(mac).into() {
return Err(CryptoError::InvalidMac.into());
}
decrypt_aes256(iv, data, key)
Expand Down Expand Up @@ -82,7 +83,7 @@ pub fn encrypt_aes256_hmac(
key: GenericArray<u8, U32>,
) -> Result<EncString> {
let (iv, data) = encrypt_aes256_internal(data_dec, key);
let mac = validate_mac(&mac_key, &iv, &data)?;
let mac = generate_mac(&mac_key, &iv, &data)?;

Ok(EncString::AesCbc256_HmacSha256_B64 { iv, mac, data })
}
Expand All @@ -101,8 +102,8 @@ fn encrypt_aes256_internal(data_dec: &[u8], key: GenericArray<u8, U32>) -> ([u8;
(iv, data)
}

/// Validate a MAC using HMAC-SHA256.
fn validate_mac(mac_key: &[u8], iv: &[u8], data: &[u8]) -> Result<[u8; 32]> {
/// Generate a MAC using HMAC-SHA256.
fn generate_mac(mac_key: &[u8], iv: &[u8], data: &[u8]) -> Result<[u8; 32]> {
let mut hmac = PbkdfSha256Hmac::new_from_slice(mac_key).expect("HMAC can take key of any size");
hmac.update(iv);
hmac.update(data);
Expand Down

0 comments on commit 6a9e96c

Please sign in to comment.