Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve MAC validation #333

Merged
merged 4 commits into from
Nov 23, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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