| 1 |
//! Implementation of the AES decryption for zip files. |
| 2 |
//! |
| 3 |
//! This was implemented according to the [WinZip specification](https://www.winzip.com/win/en/aes_info.html). |
| 4 |
//! Note that using CRC with AES depends on the used encryption specification, AE-1 or AE-2. |
| 5 |
//! If the file is marked as encrypted with AE-2 the CRC field is ignored, even if it isn't set to 0. |
| 6 |
|
| 7 |
use crate::aes_ctr::AesCipher; |
| 8 |
use crate::types::AesMode; |
| 9 |
use crate::{aes_ctr, result::ZipError}; |
| 10 |
use constant_time_eq::constant_time_eq; |
| 11 |
use hmac::{Hmac, Mac}; |
| 12 |
use rand::RngCore; |
| 13 |
use sha1::Sha1; |
| 14 |
use std::io::{self, Error, ErrorKind, Read, Write}; |
| 15 |
use zeroize::{Zeroize, Zeroizing}; |
| 16 |
|
| 17 |
/// The length of the password verifcation value in bytes |
| 18 |
pub const PWD_VERIFY_LENGTH: usize = 2; |
| 19 |
/// The length of the authentication code in bytes |
| 20 |
const AUTH_CODE_LENGTH: usize = 10; |
| 21 |
/// The number of iterations used with PBKDF2 |
| 22 |
const ITERATION_COUNT: u32 = 1000; |
| 23 |
|
| 24 |
enum Cipher { |
| 25 |
Aes128(Box<aes_ctr::AesCtrZipKeyStream<aes_ctr::Aes128>>), |
| 26 |
Aes192(Box<aes_ctr::AesCtrZipKeyStream<aes_ctr::Aes192>>), |
| 27 |
Aes256(Box<aes_ctr::AesCtrZipKeyStream<aes_ctr::Aes256>>), |
| 28 |
} |
| 29 |
|
| 30 |
impl Cipher { |
| 31 |
/// Create a `Cipher` depending on the used `AesMode` and the given `key`. |
| 32 |
/// |
| 33 |
/// # Panics |
| 34 |
/// |
| 35 |
/// This panics if `key` doesn't have the correct size for the chosen aes mode. |
| 36 |
fn from_mode(aes_mode: AesMode, key: &[u8]) -> Self { |
| 37 |
match aes_mode { |
| 38 |
AesMode::Aes128 => Cipher::Aes128(Box::new(aes_ctr::AesCtrZipKeyStream::< |
| 39 |
aes_ctr::Aes128, |
| 40 |
>::new(key))), |
| 41 |
AesMode::Aes192 => Cipher::Aes192(Box::new(aes_ctr::AesCtrZipKeyStream::< |
| 42 |
aes_ctr::Aes192, |
| 43 |
>::new(key))), |
| 44 |
AesMode::Aes256 => Cipher::Aes256(Box::new(aes_ctr::AesCtrZipKeyStream::< |
| 45 |
aes_ctr::Aes256, |
| 46 |
>::new(key))), |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
fn crypt_in_place(&mut self, target: &mut [u8]) { |
| 51 |
match self { |
| 52 |
Self::Aes128(cipher) => cipher.crypt_in_place(target), |
| 53 |
Self::Aes192(cipher) => cipher.crypt_in_place(target), |
| 54 |
Self::Aes256(cipher) => cipher.crypt_in_place(target), |
| 55 |
} |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
// An aes encrypted file starts with a salt, whose length depends on the used aes mode |
| 60 |
// followed by a 2 byte password verification value |
| 61 |
// then the variable length encrypted data |
| 62 |
// and lastly a 10 byte authentication code |
| 63 |
pub struct AesReader<R> { |
| 64 |
reader: R, |
| 65 |
aes_mode: AesMode, |
| 66 |
data_length: u64, |
| 67 |
} |
| 68 |
|
| 69 |
impl<R: Read> AesReader<R> { |
| 70 |
pub const fn new(reader: R, aes_mode: AesMode, compressed_size: u64) -> AesReader<R> { |
| 71 |
let data_length = compressed_size |
| 72 |
- (PWD_VERIFY_LENGTH + AUTH_CODE_LENGTH + aes_mode.salt_length()) as u64; |
| 73 |
|
| 74 |
Self { |
| 75 |
reader, |
| 76 |
aes_mode, |
| 77 |
data_length, |
| 78 |
} |
| 79 |
} |
| 80 |
|
| 81 |
/// Read the AES header bytes and validate the password. |
| 82 |
/// |
| 83 |
/// Even if the validation succeeds, there is still a 1 in 65536 chance that an incorrect |
| 84 |
/// password was provided. |
| 85 |
/// It isn't possible to check the authentication code in this step. This will be done after |
| 86 |
/// reading and decrypting the file. |
| 87 |
pub fn validate(mut self, password: &[u8]) -> Result<AesReaderValid<R>, ZipError> { |
| 88 |
let salt_length = self.aes_mode.salt_length(); |
| 89 |
let key_length = self.aes_mode.key_length(); |
| 90 |
|
| 91 |
let mut salt = vec![0; salt_length]; |
| 92 |
self.reader.read_exact(&mut salt)?; |
| 93 |
|
| 94 |
// next are 2 bytes used for password verification |
| 95 |
let mut pwd_verification_value = vec![0; PWD_VERIFY_LENGTH]; |
| 96 |
self.reader.read_exact(&mut pwd_verification_value)?; |
| 97 |
|
| 98 |
// derive a key from the password and salt |
| 99 |
// the length depends on the aes key length |
| 100 |
let derived_key_len = 2 * key_length + PWD_VERIFY_LENGTH; |
| 101 |
let mut derived_key: Box<[u8]> = vec![0; derived_key_len].into_boxed_slice(); |
| 102 |
|
| 103 |
// use PBKDF2 with HMAC-Sha1 to derive the key |
| 104 |
pbkdf2::pbkdf2::<Hmac<Sha1>>(password, &salt, ITERATION_COUNT, &mut derived_key) |
| 105 |
.map_err(|e| Error::new(ErrorKind::InvalidInput, e))?; |
| 106 |
let decrypt_key = &derived_key[0..key_length]; |
| 107 |
let hmac_key = &derived_key[key_length..key_length * 2]; |
| 108 |
let pwd_verify = &derived_key[derived_key_len - 2..]; |
| 109 |
|
| 110 |
// the last 2 bytes should equal the password verification value |
| 111 |
if pwd_verification_value != pwd_verify { |
| 112 |
// wrong password |
| 113 |
return Err(ZipError::InvalidPassword); |
| 114 |
} |
| 115 |
|
| 116 |
let cipher = Cipher::from_mode(self.aes_mode, decrypt_key); |
| 117 |
let hmac = Hmac::<Sha1>::new_from_slice(hmac_key).unwrap(); |
| 118 |
|
| 119 |
Ok(AesReaderValid { |
| 120 |
reader: self.reader, |
| 121 |
data_remaining: self.data_length, |
| 122 |
cipher, |
| 123 |
hmac, |
| 124 |
finalized: false, |
| 125 |
}) |
| 126 |
} |
| 127 |
|
| 128 |
/// Read the AES header bytes and returns the verification value and salt. |
| 129 |
/// |
| 130 |
/// # Returns |
| 131 |
/// |
| 132 |
/// the verification value and the salt |
| 133 |
pub fn get_verification_value_and_salt( |
| 134 |
mut self, |
| 135 |
) -> io::Result<([u8; PWD_VERIFY_LENGTH], Vec<u8>)> { |
| 136 |
let salt_length = self.aes_mode.salt_length(); |
| 137 |
|
| 138 |
let mut salt = vec![0; salt_length]; |
| 139 |
self.reader.read_exact(&mut salt)?; |
| 140 |
|
| 141 |
// next are 2 bytes used for password verification |
| 142 |
let mut pwd_verification_value = [0; PWD_VERIFY_LENGTH]; |
| 143 |
self.reader.read_exact(&mut pwd_verification_value)?; |
| 144 |
Ok((pwd_verification_value, salt)) |
| 145 |
} |
| 146 |
} |
| 147 |
|
| 148 |
/// A reader for aes encrypted files, which has already passed the first password check. |
| 149 |
/// |
| 150 |
/// There is a 1 in 65536 chance that an invalid password passes that check. |
| 151 |
/// After the data has been read and decrypted an HMAC will be checked and provide a final means |
| 152 |
/// to check if either the password is invalid or if the data has been changed. |
| 153 |
pub struct AesReaderValid<R: Read> { |
| 154 |
reader: R, |
| 155 |
data_remaining: u64, |
| 156 |
cipher: Cipher, |
| 157 |
hmac: Hmac<Sha1>, |
| 158 |
finalized: bool, |
| 159 |
} |
| 160 |
|
| 161 |
impl<R: Read> Read for AesReaderValid<R> { |
| 162 |
/// This implementation does not fulfill all requirements set in the trait documentation. |
| 163 |
/// |
| 164 |
/// ```txt |
| 165 |
/// "If an error is returned then it must be guaranteed that no bytes were read." |
| 166 |
/// ``` |
| 167 |
/// |
| 168 |
/// Whether this applies to errors that occur while reading the encrypted data depends on the |
| 169 |
/// underlying reader. If the error occurs while verifying the HMAC, the reader might become |
| 170 |
/// practically unusable, since its position after the error is not known. |
| 171 |
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { |
| 172 |
if self.data_remaining == 0 { |
| 173 |
return Ok(0); |
| 174 |
} |
| 175 |
|
| 176 |
// get the number of bytes to read, compare as u64 to make sure we can read more than |
| 177 |
// 2^32 bytes even on 32 bit systems. |
| 178 |
let bytes_to_read = self.data_remaining.min(buf.len() as u64) as usize; |
| 179 |
let read = self.reader.read(&mut buf[0..bytes_to_read])?; |
| 180 |
self.data_remaining -= read as u64; |
| 181 |
|
| 182 |
// Update the hmac with the encrypted data |
| 183 |
self.hmac.update(&buf[0..read]); |
| 184 |
|
| 185 |
// decrypt the data |
| 186 |
self.cipher.crypt_in_place(&mut buf[0..read]); |
| 187 |
|
| 188 |
// if there is no data left to read, check the integrity of the data |
| 189 |
if self.data_remaining == 0 { |
| 190 |
assert!( |
| 191 |
!self.finalized, |
| 192 |
"Tried to use an already finalized HMAC. This is a bug!" |
| 193 |
); |
| 194 |
self.finalized = true; |
| 195 |
|
| 196 |
// Zip uses HMAC-Sha1-80, which only uses the first half of the hash |
| 197 |
// see https://www.winzip.com/win/en/aes_info.html#auth-faq |
| 198 |
let mut read_auth_code = [0; AUTH_CODE_LENGTH]; |
| 199 |
self.reader.read_exact(&mut read_auth_code)?; |
| 200 |
let computed_auth_code = &self.hmac.finalize_reset().into_bytes()[0..AUTH_CODE_LENGTH]; |
| 201 |
|
| 202 |
// use constant time comparison to mitigate timing attacks |
| 203 |
if !constant_time_eq(computed_auth_code, &read_auth_code) { |
| 204 |
return Err( |
| 205 |
Error::new( |
| 206 |
ErrorKind::InvalidData, |
| 207 |
"Invalid authentication code, this could be due to an invalid password or errors in the data" |
| 208 |
) |
| 209 |
); |
| 210 |
} |
| 211 |
} |
| 212 |
|
| 213 |
Ok(read) |
| 214 |
} |
| 215 |
} |
| 216 |
|
| 217 |
impl<R: Read> AesReaderValid<R> { |
| 218 |
/// Consumes this decoder, returning the underlying reader. |
| 219 |
pub fn into_inner(self) -> R { |
| 220 |
self.reader |
| 221 |
} |
| 222 |
} |
| 223 |
|
| 224 |
pub struct AesWriter<W> { |
| 225 |
writer: W, |
| 226 |
cipher: Cipher, |
| 227 |
hmac: Hmac<Sha1>, |
| 228 |
buffer: Zeroizing<Vec<u8>>, |
| 229 |
encrypted_file_header: Option<Vec<u8>>, |
| 230 |
} |
| 231 |
|
| 232 |
impl<W: Write> AesWriter<W> { |
| 233 |
pub fn new(writer: W, aes_mode: AesMode, password: &[u8]) -> io::Result<Self> { |
| 234 |
let salt_length = aes_mode.salt_length(); |
| 235 |
let key_length = aes_mode.key_length(); |
| 236 |
|
| 237 |
let mut encrypted_file_header = Vec::with_capacity(salt_length + 2); |
| 238 |
|
| 239 |
let mut salt = vec![0; salt_length]; |
| 240 |
rand::thread_rng().fill_bytes(&mut salt); |
| 241 |
encrypted_file_header.write_all(&salt)?; |
| 242 |
|
| 243 |
// Derive a key from the password and salt. The length depends on the aes key length |
| 244 |
let derived_key_len = 2 * key_length + PWD_VERIFY_LENGTH; |
| 245 |
let mut derived_key: Zeroizing<Vec<u8>> = Zeroizing::new(vec![0; derived_key_len]); |
| 246 |
|
| 247 |
// Use PBKDF2 with HMAC-Sha1 to derive the key. |
| 248 |
pbkdf2::pbkdf2::<Hmac<Sha1>>(password, &salt, ITERATION_COUNT, &mut derived_key) |
| 249 |
.map_err(|e| Error::new(ErrorKind::InvalidInput, e))?; |
| 250 |
let encryption_key = &derived_key[0..key_length]; |
| 251 |
let hmac_key = &derived_key[key_length..key_length * 2]; |
| 252 |
|
| 253 |
let pwd_verify = derived_key[derived_key_len - 2..].to_vec(); |
| 254 |
encrypted_file_header.write_all(&pwd_verify)?; |
| 255 |
|
| 256 |
let cipher = Cipher::from_mode(aes_mode, encryption_key); |
| 257 |
let hmac = Hmac::<Sha1>::new_from_slice(hmac_key).unwrap(); |
| 258 |
|
| 259 |
Ok(Self { |
| 260 |
writer, |
| 261 |
cipher, |
| 262 |
hmac, |
| 263 |
buffer: Default::default(), |
| 264 |
encrypted_file_header: Some(encrypted_file_header), |
| 265 |
}) |
| 266 |
} |
| 267 |
|
| 268 |
pub fn finish(mut self) -> io::Result<W> { |
| 269 |
self.write_encrypted_file_header()?; |
| 270 |
|
| 271 |
// Zip uses HMAC-Sha1-80, which only uses the first half of the hash |
| 272 |
// see https://www.winzip.com/win/en/aes_info.html#auth-faq |
| 273 |
let computed_auth_code = &self.hmac.finalize_reset().into_bytes()[0..AUTH_CODE_LENGTH]; |
| 274 |
self.writer.write_all(computed_auth_code)?; |
| 275 |
|
| 276 |
Ok(self.writer) |
| 277 |
} |
| 278 |
|
| 279 |
/// The AES encryption specification requires some metadata being written at the start of the |
| 280 |
/// file data section, but this can only be done once the extra data writing has been finished |
| 281 |
/// so we can't do it when the writer is constructed. |
| 282 |
fn write_encrypted_file_header(&mut self) -> io::Result<()> { |
| 283 |
if let Some(header) = self.encrypted_file_header.take() { |
| 284 |
self.writer.write_all(&header)?; |
| 285 |
} |
| 286 |
|
| 287 |
Ok(()) |
| 288 |
} |
| 289 |
} |
| 290 |
|
| 291 |
impl<W: Write> Write for AesWriter<W> { |
| 292 |
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { |
| 293 |
self.write_encrypted_file_header()?; |
| 294 |
|
| 295 |
// Fill the internal buffer and encrypt it in-place. |
| 296 |
self.buffer.extend_from_slice(buf); |
| 297 |
self.cipher.crypt_in_place(&mut self.buffer[..]); |
| 298 |
|
| 299 |
// Update the hmac with the encrypted data. |
| 300 |
self.hmac.update(&self.buffer[..]); |
| 301 |
|
| 302 |
// Write the encrypted buffer to the inner writer. We need to use `write_all` here as if |
| 303 |
// we only write parts of the data we can't easily reverse the keystream in the cipher |
| 304 |
// implementation. |
| 305 |
self.writer.write_all(&self.buffer[..])?; |
| 306 |
|
| 307 |
// Zeroize the backing memory before clearing the buffer to prevent cleartext data from |
| 308 |
// being left in memory. |
| 309 |
self.buffer.zeroize(); |
| 310 |
self.buffer.clear(); |
| 311 |
|
| 312 |
Ok(buf.len()) |
| 313 |
} |
| 314 |
|
| 315 |
fn flush(&mut self) -> io::Result<()> { |
| 316 |
self.writer.flush() |
| 317 |
} |
| 318 |
} |
| 319 |
|
| 320 |
#[cfg(all(test, feature = "aes-crypto"))] |
| 321 |
mod tests { |
| 322 |
use std::io::{self, Read, Write}; |
| 323 |
|
| 324 |
use crate::{ |
| 325 |
aes::{AesReader, AesWriter}, |
| 326 |
result::ZipError, |
| 327 |
types::AesMode, |
| 328 |
}; |
| 329 |
|
| 330 |
/// Checks whether `AesReader` can successfully decrypt what `AesWriter` produces. |
| 331 |
fn roundtrip(aes_mode: AesMode, password: &[u8], plaintext: &[u8]) -> Result<bool, ZipError> { |
| 332 |
let mut buf = io::Cursor::new(vec![]); |
| 333 |
let mut read_buffer = vec![]; |
| 334 |
|
| 335 |
{ |
| 336 |
let mut writer = AesWriter::new(&mut buf, aes_mode, password)?; |
| 337 |
writer.write_all(plaintext)?; |
| 338 |
writer.finish()?; |
| 339 |
} |
| 340 |
|
| 341 |
// Reset cursor position to the beginning. |
| 342 |
buf.set_position(0); |
| 343 |
|
| 344 |
{ |
| 345 |
let compressed_length = buf.get_ref().len() as u64; |
| 346 |
let mut reader = |
| 347 |
AesReader::new(&mut buf, aes_mode, compressed_length).validate(password)?; |
| 348 |
reader.read_to_end(&mut read_buffer)?; |
| 349 |
} |
| 350 |
|
| 351 |
Ok(plaintext == read_buffer) |
| 352 |
} |
| 353 |
|
| 354 |
#[test] |
| 355 |
fn crypt_aes_256_0_byte() { |
| 356 |
let plaintext = &[]; |
| 357 |
let password = b"some super secret password"; |
| 358 |
assert!(roundtrip(AesMode::Aes256, password, plaintext).expect("could encrypt and decrypt")); |
| 359 |
} |
| 360 |
|
| 361 |
#[test] |
| 362 |
fn crypt_aes_128_5_byte() { |
| 363 |
let plaintext = b"asdf\n"; |
| 364 |
let password = b"some super secret password"; |
| 365 |
|
| 366 |
assert!(roundtrip(AesMode::Aes128, password, plaintext).expect("could encrypt and decrypt")); |
| 367 |
} |
| 368 |
|
| 369 |
#[test] |
| 370 |
fn crypt_aes_192_5_byte() { |
| 371 |
let plaintext = b"asdf\n"; |
| 372 |
let password = b"some super secret password"; |
| 373 |
|
| 374 |
assert!(roundtrip(AesMode::Aes192, password, plaintext).expect("could encrypt and decrypt")); |
| 375 |
} |
| 376 |
|
| 377 |
#[test] |
| 378 |
fn crypt_aes_256_5_byte() { |
| 379 |
let plaintext = b"asdf\n"; |
| 380 |
let password = b"some super secret password"; |
| 381 |
|
| 382 |
assert!(roundtrip(AesMode::Aes256, password, plaintext).expect("could encrypt and decrypt")); |
| 383 |
} |
| 384 |
|
| 385 |
#[test] |
| 386 |
fn crypt_aes_128_40_byte() { |
| 387 |
let plaintext = b"Lorem ipsum dolor sit amet, consectetur\n"; |
| 388 |
let password = b"some super secret password"; |
| 389 |
|
| 390 |
assert!(roundtrip(AesMode::Aes128, password, plaintext).expect("could encrypt and decrypt")); |
| 391 |
} |
| 392 |
|
| 393 |
#[test] |
| 394 |
fn crypt_aes_192_40_byte() { |
| 395 |
let plaintext = b"Lorem ipsum dolor sit amet, consectetur\n"; |
| 396 |
let password = b"some super secret password"; |
| 397 |
|
| 398 |
assert!(roundtrip(AesMode::Aes192, password, plaintext).expect("could encrypt and decrypt")); |
| 399 |
} |
| 400 |
|
| 401 |
#[test] |
| 402 |
fn crypt_aes_256_40_byte() { |
| 403 |
let plaintext = b"Lorem ipsum dolor sit amet, consectetur\n"; |
| 404 |
let password = b"some super secret password"; |
| 405 |
|
| 406 |
assert!(roundtrip(AesMode::Aes256, password, plaintext).expect("could encrypt and decrypt")); |
| 407 |
} |
| 408 |
} |