| 1 | use crate::protocol::ErrorCode; |
| 2 | use aes::{ |
| 3 | Aes256, |
| 4 | cipher::{BlockEncrypt, KeyInit}, |
| 5 | }; |
| 6 | use hmac::{Hmac, Mac}; |
| 7 | use sha1::Sha1; |
| 8 | use subtle::ConstantTimeEq; |
| 9 | use zeroize::{Zeroize, Zeroizing}; |
| 10 | |
| 11 | type Result<T> = std::result::Result<T, ErrorCode>; |
| 12 | type Sha1Mac = Hmac<Sha1>; |
| 13 | |
| 14 | fn keys(password: &[u8], salt: &[u8]) -> Zeroizing<[u8; 66]> { |
| 15 | let mut result = Zeroizing::new([0; 66]); |
| 16 | pbkdf2::pbkdf2_hmac::<Sha1>(password, salt, 1000, result.as_mut()); |
| 17 | result |
| 18 | } |
| 19 | fn ctr(bytes: &mut [u8], key: &[u8], check: &mut impl crate::resources::Monitor) -> Result<()> { |
| 20 | let cipher = Aes256::new_from_slice(key).map_err(|_| ErrorCode::Internal)?; |
| 21 | for (index, chunk) in bytes.chunks_mut(16).enumerate() { |
| 22 | if index % 4096 == 0 { |
| 23 | check.check()?; |
| 24 | } |
| 25 | // WinZip은 1부터 시작하는 리틀엔디언 카운터를 사용함. |
| 26 | let mut block = ((index as u128) + 1).to_le_bytes().into(); |
| 27 | cipher.encrypt_block(&mut block); |
| 28 | for (byte, mask) in chunk.iter_mut().zip(block.iter()) { |
| 29 | *byte ^= mask; |
| 30 | } |
| 31 | block.as_mut_slice().zeroize(); |
| 32 | } |
| 33 | Ok(()) |
| 34 | } |
| 35 | fn authenticate( |
| 36 | key: &[u8], |
| 37 | bytes: &[u8], |
| 38 | check: &mut impl crate::resources::Monitor, |
| 39 | ) -> Result<Sha1Mac> { |
| 40 | let mut mac = <Sha1Mac as Mac>::new_from_slice(key).map_err(|_| ErrorCode::Internal)?; |
| 41 | for chunk in bytes.chunks(65536) { |
| 42 | check.check()?; |
| 43 | mac.update(chunk); |
| 44 | } |
| 45 | Ok(mac) |
| 46 | } |
| 47 | pub(crate) fn aes_encrypt( |
| 48 | packed: &[u8], |
| 49 | password: &[u8], |
| 50 | check: &mut impl crate::resources::Monitor, |
| 51 | ) -> Result<Vec<u8>> { |
| 52 | check.check()?; |
| 53 | let mut salt = [0; 16]; |
| 54 | random(&mut salt)?; |
| 55 | let key = keys(password, &salt); |
| 56 | let mut bytes = packed.to_vec(); |
| 57 | ctr(&mut bytes, &key[..32], check)?; |
| 58 | let mac = authenticate(&key[32..64], &bytes, check)? |
| 59 | .finalize() |
| 60 | .into_bytes(); |
| 61 | let mut result = Vec::with_capacity(bytes.len() + 28); |
| 62 | result.extend(salt); |
| 63 | result.extend(&key[64..]); |
| 64 | result.extend(bytes); |
| 65 | result.extend(&mac[..10]); |
| 66 | Ok(result) |
| 67 | } |
| 68 | pub(crate) fn random(bytes: &mut [u8]) -> Result<()> { |
| 69 | #[cfg(target_os = "linux")] |
| 70 | { |
| 71 | use std::io::Read; |
| 72 | std::fs::File::open("/dev/urandom") |
| 73 | .and_then(|mut file| file.read_exact(bytes)) |
| 74 | .map_err(|_| ErrorCode::Io) |
| 75 | } |
| 76 | #[cfg(windows)] |
| 77 | { |
| 78 | #[link(name = "bcrypt")] |
| 79 | unsafe extern "system" { |
| 80 | fn BCryptGenRandom( |
| 81 | algorithm: *mut core::ffi::c_void, |
| 82 | buffer: *mut u8, |
| 83 | length: u32, |
| 84 | flags: u32, |
| 85 | ) -> i32; |
| 86 | } |
| 87 | let len = u32::try_from(bytes.len()).map_err(|_| ErrorCode::Limit)?; |
| 88 | if unsafe { BCryptGenRandom(std::ptr::null_mut(), bytes.as_mut_ptr(), len, 2) } >= 0 { |
| 89 | Ok(()) |
| 90 | } else { |
| 91 | Err(ErrorCode::Io) |
| 92 | } |
| 93 | } |
| 94 | #[cfg(not(any(target_os = "linux", windows)))] |
| 95 | { |
| 96 | let _ = bytes; |
| 97 | Err(ErrorCode::UnsupportedFeature) |
| 98 | } |
| 99 | } |
| 100 | const CRC_TABLE: [u32; 256] = { |
| 101 | let mut table = [0; 256]; |
| 102 | let mut i = 0; |
| 103 | while i < 256 { |
| 104 | let mut crc = i as u32; |
| 105 | let mut bit = 0; |
| 106 | while bit < 8 { |
| 107 | crc = (crc >> 1) ^ (0xedb88320 & 0u32.wrapping_sub(crc & 1)); |
| 108 | bit += 1; |
| 109 | } |
| 110 | table[i] = crc; |
| 111 | i += 1; |
| 112 | } |
| 113 | table |
| 114 | }; |
| 115 | pub(crate) enum Decryptor { |
| 116 | Plain, |
| 117 | Zip(Zeroizing<[u32; 3]>), |
| 118 | Aes { |
| 119 | cipher: Aes256, |
| 120 | counter: u128, |
| 121 | mask: [u8; 16], |
| 122 | used: usize, |
| 123 | }, |
| 124 | } |
| 125 | fn zip_update(key: &mut [u32; 3], byte: u8) { |
| 126 | key[0] = (key[0] >> 8) ^ CRC_TABLE[((key[0] as u8) ^ byte) as usize]; |
| 127 | key[1] = key[1] |
| 128 | .wrapping_add(key[0] & 255) |
| 129 | .wrapping_mul(134775813) |
| 130 | .wrapping_add(1); |
| 131 | key[2] = (key[2] >> 8) ^ CRC_TABLE[((key[2] as u8) ^ ((key[1] >> 24) as u8)) as usize]; |
| 132 | } |
| 133 | impl Decryptor { |
| 134 | pub fn prepare( |
| 135 | file: &mut std::fs::File, |
| 136 | offset: u64, |
| 137 | length: u64, |
| 138 | password: &[u8], |
| 139 | aes: bool, |
| 140 | verifier: u8, |
| 141 | check: &mut impl crate::resources::Monitor, |
| 142 | ) -> Result<(Self, u64, u64)> { |
| 143 | use std::io::{Read, Seek, SeekFrom}; |
| 144 | file.seek(SeekFrom::Start(offset)) |
| 145 | .map_err(|_| ErrorCode::Io)?; |
| 146 | if aes { |
| 147 | if length < 28 { |
| 148 | return Err(ErrorCode::Integrity); |
| 149 | } |
| 150 | let mut header = [0; 18]; |
| 151 | file.read_exact(&mut header) |
| 152 | .map_err(|_| ErrorCode::Integrity)?; |
| 153 | let key = keys(password, &header[..16]); |
| 154 | if !bool::from(key[64..].ct_eq(&header[16..])) { |
| 155 | return Err(ErrorCode::WrongPassword); |
| 156 | } |
| 157 | let mut mac = |
| 158 | <Sha1Mac as Mac>::new_from_slice(&key[32..64]).map_err(|_| ErrorCode::Internal)?; |
| 159 | let mut remaining = length - 28; |
| 160 | let mut buffer = [0; 65536]; |
| 161 | while remaining != 0 { |
| 162 | check.check()?; |
| 163 | let n = remaining.min(buffer.len() as u64) as usize; |
| 164 | file.read_exact(&mut buffer[..n]) |
| 165 | .map_err(|_| ErrorCode::Integrity)?; |
| 166 | mac.update(&buffer[..n]); |
| 167 | remaining -= n as u64; |
| 168 | crate::resources::completed(Ok(()), check)?; |
| 169 | } |
| 170 | let mut tag = [0; 10]; |
| 171 | file.read_exact(&mut tag) |
| 172 | .map_err(|_| ErrorCode::Integrity)?; |
| 173 | mac.verify_truncated_left(&tag) |
| 174 | .map_err(|_| ErrorCode::Integrity)?; |
| 175 | let cipher = Aes256::new_from_slice(&key[..32]).map_err(|_| ErrorCode::Internal)?; |
| 176 | Ok(( |
| 177 | Self::Aes { |
| 178 | cipher, |
| 179 | counter: 1, |
| 180 | mask: [0; 16], |
| 181 | used: 16, |
| 182 | }, |
| 183 | offset + 18, |
| 184 | length - 28, |
| 185 | )) |
| 186 | } else { |
| 187 | if length < 12 { |
| 188 | return Err(ErrorCode::Integrity); |
| 189 | } |
| 190 | let mut key = Zeroizing::new([0x12345678, 0x23456789, 0x34567890]); |
| 191 | for &b in password { |
| 192 | zip_update(&mut key, b); |
| 193 | } |
| 194 | let mut decoder = Self::Zip(key); |
| 195 | let mut header = [0; 12]; |
| 196 | file.read_exact(&mut header) |
| 197 | .map_err(|_| ErrorCode::Integrity)?; |
| 198 | decoder.apply(&mut header); |
| 199 | if header[11] != verifier { |
| 200 | return Err(ErrorCode::WrongPassword); |
| 201 | } |
| 202 | header.zeroize(); |
| 203 | Ok((decoder, offset + 12, length - 12)) |
| 204 | } |
| 205 | } |
| 206 | pub fn apply(&mut self, bytes: &mut [u8]) { |
| 207 | match self { |
| 208 | Self::Plain => {} |
| 209 | Self::Zip(key) => { |
| 210 | for byte in bytes { |
| 211 | let temp = key[2] | 2; |
| 212 | *byte ^= (temp.wrapping_mul(temp ^ 1) >> 8) as u8; |
| 213 | zip_update(key, *byte); |
| 214 | } |
| 215 | } |
| 216 | Self::Aes { |
| 217 | cipher, |
| 218 | counter, |
| 219 | mask, |
| 220 | used, |
| 221 | } => { |
| 222 | for byte in bytes { |
| 223 | if *used == 16 { |
| 224 | let mut block = counter.to_le_bytes().into(); |
| 225 | cipher.encrypt_block(&mut block); |
| 226 | mask.copy_from_slice(&block); |
| 227 | block.as_mut_slice().zeroize(); |
| 228 | *counter += 1; |
| 229 | *used = 0; |
| 230 | } |
| 231 | *byte ^= mask[*used]; |
| 232 | *used += 1; |
| 233 | } |
| 234 | } |
| 235 | } |
| 236 | } |
| 237 | } |
| 238 | impl Drop for Decryptor { |
| 239 | fn drop(&mut self) { |
| 240 | if let Self::Aes { mask, counter, .. } = self { |
| 241 | mask.zeroize(); |
| 242 | counter.zeroize(); |
| 243 | } |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | pub(crate) fn aes_encrypt_file( |
| 248 | input: &mut std::fs::File, |
| 249 | length: u64, |
| 250 | output: &mut std::fs::File, |
| 251 | password: &[u8], |
| 252 | check: &mut impl crate::resources::Monitor, |
| 253 | ) -> Result<()> { |
| 254 | use std::io::{Read, Write}; |
| 255 | check.check()?; |
| 256 | let mut salt = [0; 16]; |
| 257 | random(&mut salt)?; |
| 258 | let key = keys(password, &salt); |
| 259 | output.write_all(&salt).map_err(crate::space::io_error)?; |
| 260 | output |
| 261 | .write_all(&key[64..]) |
| 262 | .map_err(crate::space::io_error)?; |
| 263 | let mut cipher = Decryptor::Aes { |
| 264 | cipher: Aes256::new_from_slice(&key[..32]).map_err(|_| ErrorCode::Internal)?, |
| 265 | counter: 1, |
| 266 | mask: [0; 16], |
| 267 | used: 16, |
| 268 | }; |
| 269 | let mut mac = |
| 270 | <Sha1Mac as Mac>::new_from_slice(&key[32..64]).map_err(|_| ErrorCode::Internal)?; |
| 271 | let mut remaining = length; |
| 272 | let mut buffer = Zeroizing::new([0; 65536]); |
| 273 | while remaining != 0 { |
| 274 | check.check()?; |
| 275 | let n = remaining.min(buffer.len() as u64) as usize; |
| 276 | input |
| 277 | .read_exact(&mut buffer[..n]) |
| 278 | .map_err(crate::space::io_error)?; |
| 279 | cipher.apply(&mut buffer[..n]); |
| 280 | mac.update(&buffer[..n]); |
| 281 | crate::space::ensure(output, n as u64)?; |
| 282 | output |
| 283 | .write_all(&buffer[..n]) |
| 284 | .map_err(crate::space::io_error)?; |
| 285 | remaining -= n as u64; |
| 286 | crate::resources::completed(Ok(()), check)?; |
| 287 | } |
| 288 | output |
| 289 | .write_all(&mac.finalize().into_bytes()[..10]) |
| 290 | .map_err(crate::space::io_error)?; |
| 291 | Ok(()) |
| 292 | } |
| 293 | |
| 294 | /// 7-Zip AES 키 유도의 반복 상한(2^24회). 7-Zip 기본값은 2^19회이며, 더 큰 값은 |
| 295 | /// 키 유도만으로 오래 걸리게 만드는 입력으로 보고 거부함. |
| 296 | const SEVEN_ZIP_MAX_CYCLES: u8 = 24; |
| 297 | |
| 298 | /// 7zAES 코더 속성: 반복 지수, 솔트와 CBC 초기 벡터. |
| 299 | #[derive(Clone, PartialEq, Eq)] |
| 300 | pub(crate) struct SevenZipAes { |
| 301 | cycles: u8, |
| 302 | salt: Vec<u8>, |
| 303 | iv: [u8; 16], |
| 304 | } |
| 305 | impl SevenZipAes { |
| 306 | pub fn parse(properties: &[u8]) -> Result<Self> { |
| 307 | let first = *properties.first().ok_or(ErrorCode::Integrity)?; |
| 308 | let cycles = first & 0x3f; |
| 309 | let (salt, iv) = if first & 0xc0 == 0 { |
| 310 | if properties.len() != 1 { |
| 311 | return Err(ErrorCode::Integrity); |
| 312 | } |
| 313 | (&[][..], &[][..]) |
| 314 | } else { |
| 315 | let second = *properties.get(1).ok_or(ErrorCode::Integrity)?; |
| 316 | let salt = ((first >> 7) & 1) as usize + (second >> 4) as usize; |
| 317 | let iv = ((first >> 6) & 1) as usize + (second & 15) as usize; |
| 318 | if properties.len() != 2 + salt + iv { |
| 319 | return Err(ErrorCode::Integrity); |
| 320 | } |
| 321 | (&properties[2..2 + salt], &properties[2 + salt..]) |
| 322 | }; |
| 323 | // 0x3f는 해시 없이 암호를 키로 쓰는 방식이므로 반복 상한과 함께 거부함. |
| 324 | if cycles > SEVEN_ZIP_MAX_CYCLES { |
| 325 | return Err(ErrorCode::UnsupportedFeature); |
| 326 | } |
| 327 | let mut padded = [0; 16]; |
| 328 | padded[..iv.len()].copy_from_slice(iv); |
| 329 | Ok(Self { |
| 330 | cycles, |
| 331 | salt: salt.to_vec(), |
| 332 | iv: padded, |
| 333 | }) |
| 334 | } |
| 335 | /// 같은 키를 유도하는 속성인지. 초기 벡터는 폴더마다 다를 수 있음. |
| 336 | pub fn same_key(&self, other: &Self) -> bool { |
| 337 | self.cycles == other.cycles && self.salt == other.salt |
| 338 | } |
| 339 | /// SHA-256(솔트 || UTF-16LE 암호 || 8바이트 카운터)를 2^cycles회 이어 계산함. |
| 340 | pub fn key( |
| 341 | &self, |
| 342 | password: &[u8], |
| 343 | check: &mut impl crate::resources::Monitor, |
| 344 | ) -> Result<Zeroizing<[u8; 32]>> { |
| 345 | use sha2::{Digest, Sha256}; |
| 346 | let text = std::str::from_utf8(password).map_err(|_| ErrorCode::WrongPassword)?; |
| 347 | let mut block = Zeroizing::new(Vec::with_capacity(self.salt.len() + text.len() * 4 + 8)); |
| 348 | block.extend_from_slice(&self.salt); |
| 349 | for unit in text.encode_utf16() { |
| 350 | block.extend_from_slice(&unit.to_le_bytes()); |
| 351 | } |
| 352 | let counter_at = block.len(); |
| 353 | block.extend_from_slice(&[0; 8]); |
| 354 | let mut hash = Sha256::new(); |
| 355 | for round in 0..1u64 << self.cycles { |
| 356 | if round % 65536 == 0 { |
| 357 | crate::resources::completed(Ok(()), check)?; |
| 358 | } |
| 359 | block[counter_at..].copy_from_slice(&round.to_le_bytes()); |
| 360 | hash.update(&block[..]); |
| 361 | } |
| 362 | let mut key = Zeroizing::new([0; 32]); |
| 363 | key.copy_from_slice(&hash.finalize()); |
| 364 | Ok(key) |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | /// 7zAES(AES-256-CBC) 묶음 스트림을 읽으며 복호화함. 마지막 블록의 채움 바이트는 |
| 369 | /// 코더 출력 크기에서 잘라 냄. |
| 370 | pub(crate) struct SevenZipReader<R> { |
| 371 | input: R, |
| 372 | cipher: Aes256, |
| 373 | previous: [u8; 16], |
| 374 | buffer: Zeroizing<[u8; 4096]>, |
| 375 | start: usize, |
| 376 | end: usize, |
| 377 | remaining: u64, |
| 378 | } |
| 379 | impl<R: std::io::Read> SevenZipReader<R> { |
| 380 | /// `packed`는 암호문 크기, `size`는 복호화 뒤 다음 코더에 넘길 크기임. |
| 381 | pub fn new( |
| 382 | input: R, |
| 383 | packed: u64, |
| 384 | size: u64, |
| 385 | properties: &SevenZipAes, |
| 386 | key: &[u8; 32], |
| 387 | ) -> Result<Self> { |
| 388 | if packed % 16 != 0 || size > packed { |
| 389 | return Err(ErrorCode::Integrity); |
| 390 | } |
| 391 | Ok(Self { |
| 392 | input, |
| 393 | cipher: Aes256::new_from_slice(key).map_err(|_| ErrorCode::Internal)?, |
| 394 | previous: properties.iv, |
| 395 | buffer: Zeroizing::new([0; 4096]), |
| 396 | start: 0, |
| 397 | end: 0, |
| 398 | remaining: size, |
| 399 | }) |
| 400 | } |
| 401 | } |
| 402 | impl<R: std::io::Read> std::io::Read for SevenZipReader<R> { |
| 403 | fn read(&mut self, output: &mut [u8]) -> std::io::Result<usize> { |
| 404 | use aes::cipher::BlockDecrypt; |
| 405 | if self.remaining == 0 || output.is_empty() { |
| 406 | return Ok(0); |
| 407 | } |
| 408 | if self.start == self.end { |
| 409 | let wanted = self.remaining.min(self.buffer.len() as u64) as usize; |
| 410 | let length = wanted.div_ceil(16) * 16; |
| 411 | let mut filled = 0; |
| 412 | while filled < length { |
| 413 | match self.input.read(&mut self.buffer[filled..length]) { |
| 414 | Ok(0) => return Err(std::io::ErrorKind::UnexpectedEof.into()), |
| 415 | Ok(n) => filled += n, |
| 416 | Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {} |
| 417 | Err(error) => return Err(error), |
| 418 | } |
| 419 | } |
| 420 | for chunk in self.buffer[..length].chunks_exact_mut(16) { |
| 421 | let mut block = aes::Block::clone_from_slice(chunk); |
| 422 | let cipher_text: [u8; 16] = block.into(); |
| 423 | self.cipher.decrypt_block(&mut block); |
| 424 | for ((byte, plain), mask) in chunk.iter_mut().zip(block.iter()).zip(&self.previous) |
| 425 | { |
| 426 | *byte = plain ^ mask; |
| 427 | } |
| 428 | block.as_mut_slice().zeroize(); |
| 429 | self.previous = cipher_text; |
| 430 | } |
| 431 | self.start = 0; |
| 432 | self.end = wanted; |
| 433 | } |
| 434 | let n = output.len().min(self.end - self.start); |
| 435 | output[..n].copy_from_slice(&self.buffer[self.start..self.start + n]); |
| 436 | self.start += n; |
| 437 | self.remaining -= n as u64; |
| 438 | Ok(n) |
| 439 | } |
| 440 | } |
| 441 | impl<R> Drop for SevenZipReader<R> { |
| 442 | fn drop(&mut self) { |
| 443 | self.previous.zeroize(); |
| 444 | } |
| 445 | } |