Debian Codegraph @

debian/rust-vendor/zip/src/aes.rs

raw
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::CompressionMethod;
8 use crate::aes_ctr::AesCipher;
9 use crate::result::ZipResult;
10 use crate::types::{AesMode, AesVendorVersion};
11 use crate::{aes_ctr, result::ZipError};
12 use constant_time_eq::constant_time_eq;
13 use hmac::{KeyInit, Mac, SimpleHmacReset};
14 use sha1::Sha1;
15 use std::io::{self, Error, ErrorKind, Read, Write};
16 use zeroize::{Zeroize, Zeroizing};
17
18 /// The length of the password verification value in bytes
19 pub const PWD_VERIFY_LENGTH: usize = 2;
20 /// The length of the authentication code in bytes
21 const AUTH_CODE_LENGTH: usize = 10;
22 /// The number of iterations used with PBKDF2
23 const ITERATION_COUNT: u32 = 1000;
24
25 #[derive(Debug)]
26 enum Cipher {
27 Aes128(Box<aes_ctr::AesCtrZipKeyStream<aes_ctr::Aes128>>),
28 Aes192(Box<aes_ctr::AesCtrZipKeyStream<aes_ctr::Aes192>>),
29 Aes256(Box<aes_ctr::AesCtrZipKeyStream<aes_ctr::Aes256>>),
30 }
31
32 /// Holds the AES information of a file in the zip archive
33 #[derive(Debug)]
34 pub struct AesInfo {
35 /// The AES encryption mode
36 pub aes_mode: AesMode,
37 /// The verification key
38 pub verification_value: [u8; crate::aes::PWD_VERIFY_LENGTH],
39 /// The salt
40 pub salt: Vec<u8>,
41 }
42
43 #[non_exhaustive]
44 #[derive(Clone, Debug, Copy, Eq, PartialEq)]
45 pub(crate) struct AesModeOptions {
46 pub(crate) mode: AesMode,
47 pub(crate) vendor_version: AesVendorVersion,
48 pub(crate) actual_compression_method: CompressionMethod,
49 pub(crate) custom_salt: Option<AesSalt>,
50 }
51
52 impl AesModeOptions {
53 pub(crate) fn new(
54 mode: AesMode,
55 vendor_version: AesVendorVersion,
56 actual_compression_method: CompressionMethod,
57 custom_salt: Option<AesSalt>,
58 ) -> Self {
59 Self {
60 mode,
61 vendor_version,
62 actual_compression_method,
63 custom_salt,
64 }
65 }
66
67 /// Used to create a the `aes_mode` of `ZipFileData`
68 pub(crate) fn to_tuple(self) -> (AesMode, AesVendorVersion, CompressionMethod) {
69 (
70 self.mode,
71 self.vendor_version,
72 self.actual_compression_method,
73 )
74 }
75 }
76
77 /// A custom salt that can be used instead of a randomly generated one when encrypting files with AES.
78 /// This is not recommended, but it can be useful for testing or for reproducible encryption results.
79 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
80 pub enum AesSalt {
81 /// AES 128 salt
82 Aes128([u8; AesMode::Aes128.salt_length()]),
83 /// AES 192 salt
84 Aes192([u8; AesMode::Aes192.salt_length()]),
85 /// AES 256 salt
86 Aes256([u8; AesMode::Aes256.salt_length()]),
87 }
88
89 impl AesSalt {
90 pub(crate) fn mode(&self) -> AesMode {
91 match self {
92 Self::Aes128(_) => AesMode::Aes128,
93 Self::Aes192(_) => AesMode::Aes192,
94 Self::Aes256(_) => AesMode::Aes256,
95 }
96 }
97
98 /// Get the inner salt array and consume it
99 pub(crate) fn into_inner(self) -> Vec<u8> {
100 match self {
101 Self::Aes128(salt) => salt.to_vec(),
102 Self::Aes192(salt) => salt.to_vec(),
103 Self::Aes256(salt) => salt.to_vec(),
104 }
105 }
106
107 pub(crate) fn salt_error(mode: AesMode, err: std::array::TryFromSliceError) -> std::io::Error {
108 std::io::Error::new(
109 std::io::ErrorKind::InvalidInput,
110 format!(
111 "Salt for {mode} must be {} bytes long: {err}",
112 mode.salt_length(),
113 ),
114 )
115 }
116
117 /// Creates a new `CustomSalt` with the given `mode` and `salt`.
118 /// The length of `salt` must be at least the required salt length for the given `mode`, otherwise an error is returned.
119 ///
120 /// # Errors
121 /// Returns an error if the length of `salt` is too short for the given `mode`.
122 pub fn try_new(mode: AesMode, salt: &[u8]) -> Result<Self, std::io::Error> {
123 let custom_salt = match mode {
124 AesMode::Aes128 => {
125 AesSalt::Aes128(salt.try_into().map_err(|e| Self::salt_error(mode, e))?)
126 }
127 AesMode::Aes192 => {
128 AesSalt::Aes192(salt.try_into().map_err(|e| Self::salt_error(mode, e))?)
129 }
130 AesMode::Aes256 => {
131 AesSalt::Aes256(salt.try_into().map_err(|e| Self::salt_error(mode, e))?)
132 }
133 };
134 Ok(custom_salt)
135 }
136 }
137
138 impl Cipher {
139 /// Create a `Cipher` depending on the used `AesMode` and the given `key`.
140 ///
141 /// Returns `ZipError::InvalidPassword` if `key` doesn't have the correct size for the chosen
142 /// AES mode.
143 fn from_mode(aes_mode: AesMode, key: &[u8]) -> ZipResult<Self> {
144 Ok(match aes_mode {
145 AesMode::Aes128 => Cipher::Aes128(Box::new(aes_ctr::AesCtrZipKeyStream::<
146 aes_ctr::Aes128,
147 >::new(key)?)),
148 AesMode::Aes192 => Cipher::Aes192(Box::new(aes_ctr::AesCtrZipKeyStream::<
149 aes_ctr::Aes192,
150 >::new(key)?)),
151 AesMode::Aes256 => Cipher::Aes256(Box::new(aes_ctr::AesCtrZipKeyStream::<
152 aes_ctr::Aes256,
153 >::new(key)?)),
154 })
155 }
156
157 fn crypt_in_place(&mut self, target: &mut [u8]) {
158 match self {
159 Self::Aes128(cipher) => cipher.crypt_in_place(target),
160 Self::Aes192(cipher) => cipher.crypt_in_place(target),
161 Self::Aes256(cipher) => cipher.crypt_in_place(target),
162 }
163 }
164 }
165
166 // An aes encrypted file starts with a salt, whose length depends on the used aes mode
167 // followed by a 2 byte password verification value
168 // then the variable length encrypted data
169 // and lastly a 10 byte authentication code
170 pub struct AesReader<R> {
171 reader: R,
172 aes_mode: AesMode,
173 data_length: u64,
174 }
175
176 impl<R: Read> AesReader<R> {
177 pub const fn new(reader: R, aes_mode: AesMode, compressed_size: u64) -> AesReader<R> {
178 let data_length = compressed_size
179 - (PWD_VERIFY_LENGTH + AUTH_CODE_LENGTH + aes_mode.salt_length()) as u64;
180
181 Self {
182 reader,
183 aes_mode,
184 data_length,
185 }
186 }
187
188 /// Read the AES header bytes and validate the password.
189 ///
190 /// Even if the validation succeeds, there is still a 1 in 65536 chance that an incorrect
191 /// password was provided.
192 /// It isn't possible to check the authentication code in this step. This will be done after
193 /// reading and decrypting the file.
194 pub fn validate(mut self, password: &[u8]) -> Result<AesReaderValid<R>, ZipError> {
195 let salt_length = self.aes_mode.salt_length();
196 let key_length = self.aes_mode.key_length();
197
198 let mut salt = vec![0; salt_length];
199 self.reader.read_exact(&mut salt)?;
200
201 // next are 2 bytes used for password verification
202 let mut pwd_verification_value = vec![0; PWD_VERIFY_LENGTH];
203 self.reader.read_exact(&mut pwd_verification_value)?;
204
205 // derive a key from the password and salt
206 // the length depends on the aes key length
207 let derived_key_len = 2 * key_length + PWD_VERIFY_LENGTH;
208 let mut derived_key: Box<[u8]> = vec![0; derived_key_len].into_boxed_slice();
209
210 // use PBKDF2 with HMAC-Sha1 to derive the key
211 pbkdf2::pbkdf2::<SimpleHmacReset<Sha1>>(password, &salt, ITERATION_COUNT, &mut derived_key)
212 .map_err(|e| Error::new(ErrorKind::InvalidInput, e))?;
213 let decrypt_key = &derived_key[0..key_length];
214 let hmac_key = &derived_key[key_length..key_length * 2];
215 let pwd_verify = &derived_key[derived_key_len - 2..];
216
217 // the last 2 bytes should equal the password verification value
218 if pwd_verification_value != pwd_verify {
219 // wrong password
220 return Err(ZipError::InvalidPassword);
221 }
222
223 let cipher = Cipher::from_mode(self.aes_mode, decrypt_key)?;
224 let hmac = SimpleHmacReset::<Sha1>::new_from_slice(hmac_key).map_err(|e| {
225 ZipError::Io(std::io::Error::other(format!(
226 "Cannot create hmac with key: {e}"
227 )))
228 })?;
229
230 Ok(AesReaderValid {
231 reader: self.reader,
232 data_remaining: self.data_length,
233 cipher,
234 hmac,
235 finalized: false,
236 })
237 }
238
239 /// Read the AES header bytes and returns the verification value and salt.
240 ///
241 /// # Returns
242 ///
243 /// the verification value and the salt
244 pub fn get_verification_value_and_salt(
245 mut self,
246 ) -> io::Result<([u8; PWD_VERIFY_LENGTH], Vec<u8>)> {
247 let salt_length = self.aes_mode.salt_length();
248
249 let mut salt = vec![0; salt_length];
250 self.reader.read_exact(&mut salt)?;
251
252 // next are 2 bytes used for password verification
253 let mut pwd_verification_value = [0; PWD_VERIFY_LENGTH];
254 self.reader.read_exact(&mut pwd_verification_value)?;
255 Ok((pwd_verification_value, salt))
256 }
257 }
258
259 /// A reader for aes encrypted files, which has already passed the first password check.
260 ///
261 /// There is a 1 in 65536 chance that an invalid password passes that check.
262 /// After the data has been read and decrypted an HMAC will be checked and provide a final means
263 /// to check if either the password is invalid or if the data has been changed.
264 #[derive(Debug)]
265 pub struct AesReaderValid<R: Read> {
266 reader: R,
267 data_remaining: u64,
268 cipher: Cipher,
269 hmac: SimpleHmacReset<Sha1>,
270 finalized: bool,
271 }
272
273 impl<R: Read> Read for AesReaderValid<R> {
274 /// This implementation does not fulfill all requirements set in the trait documentation.
275 ///
276 /// ```txt
277 /// "If an error is returned then it must be guaranteed that no bytes were read."
278 /// ```
279 ///
280 /// Whether this applies to errors that occur while reading the encrypted data depends on the
281 /// underlying reader. If the error occurs while verifying the HMAC, the reader might become
282 /// practically unusable, since its position after the error is not known.
283 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
284 if self.data_remaining == 0 {
285 return Ok(0);
286 }
287
288 // get the number of bytes to read, compare as u64 to make sure we can read more than
289 // 2^32 bytes even on 32 bit systems.
290 let bytes_to_read = self.data_remaining.min(buf.len() as u64) as usize;
291 let read = self.reader.read(&mut buf[0..bytes_to_read])?;
292 self.data_remaining -= read as u64;
293
294 // Update the hmac with the encrypted data
295 self.hmac.update(&buf[0..read]);
296
297 // decrypt the data
298 self.cipher.crypt_in_place(&mut buf[0..read]);
299
300 // if there is no data left to read, check the integrity of the data
301 if self.data_remaining == 0 {
302 assert!(
303 !self.finalized,
304 "Tried to use an already finalized HMAC. This is a bug!"
305 );
306 self.finalized = true;
307
308 // Zip uses HMAC-Sha1-80, which only uses the first half of the hash
309 // see https://www.winzip.com/win/en/aes_info.html#auth-faq
310 let mut read_auth_code = [0; AUTH_CODE_LENGTH];
311 self.reader.read_exact(&mut read_auth_code)?;
312 let computed_auth_code = &self.hmac.finalize_reset().into_bytes()[0..AUTH_CODE_LENGTH];
313
314 // use constant time comparison to mitigate timing attacks
315 if !constant_time_eq(computed_auth_code, &read_auth_code) {
316 return Err(Error::new(
317 ErrorKind::InvalidData,
318 "Invalid authentication code, this could be due to an invalid password or errors in the data",
319 ));
320 }
321 }
322
323 Ok(read)
324 }
325 }
326
327 impl<R: Read> AesReaderValid<R> {
328 /// Consumes this decoder, returning the underlying reader.
329 pub fn into_inner(self) -> R {
330 self.reader
331 }
332 }
333
334 pub struct AesWriter<W> {
335 writer: W,
336 cipher: Cipher,
337 hmac: SimpleHmacReset<Sha1>,
338 buffer: Zeroizing<Vec<u8>>,
339 encrypted_file_header: Option<Vec<u8>>,
340 }
341
342 impl<W: Write> AesWriter<W> {
343 /// Creates a new `AesWriter` with the given options.
344 /// Private method to potentially allow more options in the future, for now it is only used to allow passing a custom salt.
345 pub(crate) fn new_with_options(
346 writer: W,
347 aes_mode: AesMode,
348 password: &[u8],
349 custom_salt: Option<AesSalt>,
350 ) -> ZipResult<Self> {
351 let salt_length = aes_mode.salt_length();
352 let key_length = aes_mode.key_length();
353
354 let mut encrypted_file_header = Vec::with_capacity(salt_length + 2);
355
356 let salt = if let Some(customized_salt) = custom_salt {
357 customized_salt.into_inner()
358 } else {
359 // Generate a random salt
360 let mut salt = vec![0; salt_length];
361 getrandom::fill(&mut salt).map_err(|e| ZipError::Io(e.into()))?;
362 salt
363 };
364 encrypted_file_header.write_all(&salt)?;
365
366 // Derive a key from the password and salt. The length depends on the aes key length
367 let derived_key_len = 2 * key_length + PWD_VERIFY_LENGTH;
368 let mut derived_key: Zeroizing<Vec<u8>> = Zeroizing::new(vec![0; derived_key_len]);
369
370 // Use PBKDF2 with HMAC-Sha1 to derive the key.
371 pbkdf2::pbkdf2::<SimpleHmacReset<Sha1>>(password, &salt, ITERATION_COUNT, &mut derived_key)
372 .map_err(|e| Error::new(ErrorKind::InvalidInput, e))?;
373 let encryption_key = &derived_key[0..key_length];
374 let hmac_key = &derived_key[key_length..key_length * 2];
375
376 let pwd_verify = derived_key[derived_key_len - 2..].to_vec();
377 encrypted_file_header.write_all(&pwd_verify)?;
378
379 let cipher = Cipher::from_mode(aes_mode, encryption_key)?;
380 let hmac = SimpleHmacReset::<Sha1>::new_from_slice(hmac_key)
381 .map_err(|e| std::io::Error::other(format!("Cannot create hmac with key: {e}")))?;
382
383 Ok(Self {
384 writer,
385 cipher,
386 hmac,
387 buffer: Zeroizing::default(),
388 encrypted_file_header: Some(encrypted_file_header),
389 })
390 }
391
392 /// Gets a reference to the underlying writer.
393 pub fn get_ref(&self) -> &W {
394 &self.writer
395 }
396
397 /// Gets a mutable reference to the underlying writer.
398 ///
399 /// # Safety
400 ///
401 /// The caller must not corrupt the archive, and must leave it in the same
402 /// cursor position as it was when obtained.
403 pub unsafe fn get_mut(&mut self) -> &mut W {
404 &mut self.writer
405 }
406
407 pub fn finish(mut self) -> io::Result<W> {
408 self.write_encrypted_file_header()?;
409
410 // Zip uses HMAC-Sha1-80, which only uses the first half of the hash
411 // see https://www.winzip.com/win/en/aes_info.html#auth-faq
412 let computed_auth_code = &self.hmac.finalize_reset().into_bytes()[0..AUTH_CODE_LENGTH];
413 self.writer.write_all(computed_auth_code)?;
414
415 Ok(self.writer)
416 }
417
418 /// The AES encryption specification requires some metadata being written at the start of the
419 /// file data section, but this can only be done once the extra data writing has been finished
420 /// so we can't do it when the writer is constructed.
421 fn write_encrypted_file_header(&mut self) -> io::Result<()> {
422 if let Some(header) = self.encrypted_file_header.take() {
423 self.writer.write_all(&header)?;
424 }
425
426 Ok(())
427 }
428 }
429
430 impl<W: Write> Write for AesWriter<W> {
431 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
432 self.write_encrypted_file_header()?;
433
434 // Fill the internal buffer and encrypt it in-place.
435 self.buffer.extend_from_slice(buf);
436 self.cipher.crypt_in_place(&mut self.buffer[..]);
437
438 // Update the hmac with the encrypted data.
439 self.hmac.update(&self.buffer[..]);
440
441 // Write the encrypted buffer to the inner writer. We need to use `write_all` here as if
442 // we only write parts of the data we can't easily reverse the keystream in the cipher
443 // implementation.
444 self.writer.write_all(&self.buffer[..])?;
445
446 // Zeroize the backing memory before clearing the buffer to prevent cleartext data from
447 // being left in memory.
448 self.buffer.zeroize();
449 self.buffer.clear();
450
451 Ok(buf.len())
452 }
453
454 fn flush(&mut self) -> io::Result<()> {
455 self.writer.flush()
456 }
457 }
458
459 #[cfg(all(test, feature = "aes-crypto"))]
460 mod tests {
461 use std::io::{self, Read, Write};
462
463 use crate::{
464 aes::{AesReader, AesWriter},
465 result::ZipError,
466 types::AesMode,
467 };
468
469 /// Checks whether `AesReader` can successfully decrypt what `AesWriter` produces.
470 fn roundtrip(aes_mode: AesMode, password: &[u8], plaintext: &[u8]) -> Result<bool, ZipError> {
471 let mut buf = io::Cursor::new(vec![]);
472 let mut read_buffer = vec![];
473
474 {
475 let mut writer = AesWriter::new_with_options(&mut buf, aes_mode, password, None)?;
476 writer.write_all(plaintext)?;
477 writer.finish()?;
478 }
479
480 // Reset cursor position to the beginning.
481 buf.set_position(0);
482
483 {
484 let compressed_length = buf.get_ref().len() as u64;
485 let mut reader =
486 AesReader::new(&mut buf, aes_mode, compressed_length).validate(password)?;
487 reader.read_to_end(&mut read_buffer)?;
488 }
489
490 Ok(plaintext == read_buffer)
491 }
492
493 #[test]
494 fn crypt_aes_256_0_byte() {
495 let plaintext = &[];
496 let password = b"some super secret password";
497 assert!(
498 roundtrip(AesMode::Aes256, password, plaintext).expect("could encrypt and decrypt")
499 );
500 }
501
502 #[test]
503 fn crypt_aes_128_5_byte() {
504 let plaintext = b"asdf\n";
505 let password = b"some super secret password";
506
507 assert!(
508 roundtrip(AesMode::Aes128, password, plaintext).expect("could encrypt and decrypt")
509 );
510 }
511
512 #[test]
513 fn crypt_aes_192_5_byte() {
514 let plaintext = b"asdf\n";
515 let password = b"some super secret password";
516
517 assert!(
518 roundtrip(AesMode::Aes192, password, plaintext).expect("could encrypt and decrypt")
519 );
520 }
521
522 #[test]
523 fn crypt_aes_256_5_byte() {
524 let plaintext = b"asdf\n";
525 let password = b"some super secret password";
526
527 assert!(
528 roundtrip(AesMode::Aes256, password, plaintext).expect("could encrypt and decrypt")
529 );
530 }
531
532 #[test]
533 fn crypt_aes_128_40_byte() {
534 let plaintext = b"Lorem ipsum dolor sit amet, consectetur\n";
535 let password = b"some super secret password";
536
537 assert!(
538 roundtrip(AesMode::Aes128, password, plaintext).expect("could encrypt and decrypt")
539 );
540 }
541
542 #[test]
543 fn crypt_aes_192_40_byte() {
544 let plaintext = b"Lorem ipsum dolor sit amet, consectetur\n";
545 let password = b"some super secret password";
546
547 assert!(
548 roundtrip(AesMode::Aes192, password, plaintext).expect("could encrypt and decrypt")
549 );
550 }
551
552 #[test]
553 fn crypt_aes_256_40_byte() {
554 let plaintext = b"Lorem ipsum dolor sit amet, consectetur\n";
555 let password = b"some super secret password";
556
557 assert!(
558 roundtrip(AesMode::Aes256, password, plaintext).expect("could encrypt and decrypt")
559 );
560 }
561 }