| 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 FnMut() -> Result<()>) -> 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()?; |
| 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 FnMut() -> Result<()>, |
| 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()?; |
| 43 | mac.update(chunk); |
| 44 | } |
| 45 | Ok(mac) |
| 46 | } |
| 47 | pub(crate) fn aes_decrypt( |
| 48 | packed: &[u8], |
| 49 | password: &[u8], |
| 50 | check: &mut impl FnMut() -> Result<()>, |
| 51 | ) -> Result<Zeroizing<Vec<u8>>> { |
| 52 | if packed.len() < 28 { |
| 53 | return Err(ErrorCode::Integrity); |
| 54 | } |
| 55 | check()?; |
| 56 | let key = keys(password, &packed[..16]); |
| 57 | if !bool::from(key[64..].ct_eq(&packed[16..18])) { |
| 58 | return Err(ErrorCode::WrongPassword); |
| 59 | } |
| 60 | let end = packed.len() - 10; |
| 61 | // 인증이 성공하기 전에는 복호화나 압축 해제를 시작하지 않음. |
| 62 | authenticate(&key[32..64], &packed[18..end], check)? |
| 63 | .verify_truncated_left(&packed[end..]) |
| 64 | .map_err(|_| ErrorCode::Integrity)?; |
| 65 | let mut bytes = Zeroizing::new(packed[18..end].to_vec()); |
| 66 | ctr(&mut bytes, &key[..32], check)?; |
| 67 | Ok(bytes) |
| 68 | } |
| 69 | pub(crate) fn aes_encrypt( |
| 70 | packed: &[u8], |
| 71 | password: &[u8], |
| 72 | check: &mut impl FnMut() -> Result<()>, |
| 73 | ) -> Result<Vec<u8>> { |
| 74 | check()?; |
| 75 | let mut salt = [0; 16]; |
| 76 | random(&mut salt)?; |
| 77 | let key = keys(password, &salt); |
| 78 | let mut bytes = packed.to_vec(); |
| 79 | ctr(&mut bytes, &key[..32], check)?; |
| 80 | let mac = authenticate(&key[32..64], &bytes, check)? |
| 81 | .finalize() |
| 82 | .into_bytes(); |
| 83 | let mut result = Vec::with_capacity(bytes.len() + 28); |
| 84 | result.extend(salt); |
| 85 | result.extend(&key[64..]); |
| 86 | result.extend(bytes); |
| 87 | result.extend(&mac[..10]); |
| 88 | Ok(result) |
| 89 | } |
| 90 | pub(crate) fn random(bytes: &mut [u8]) -> Result<()> { |
| 91 | #[cfg(target_os = "linux")] |
| 92 | { |
| 93 | use std::io::Read; |
| 94 | std::fs::File::open("/dev/urandom") |
| 95 | .and_then(|mut file| file.read_exact(bytes)) |
| 96 | .map_err(|_| ErrorCode::Io) |
| 97 | } |
| 98 | #[cfg(windows)] |
| 99 | { |
| 100 | #[link(name = "bcrypt")] |
| 101 | unsafe extern "system" { |
| 102 | fn BCryptGenRandom( |
| 103 | algorithm: *mut core::ffi::c_void, |
| 104 | buffer: *mut u8, |
| 105 | length: u32, |
| 106 | flags: u32, |
| 107 | ) -> i32; |
| 108 | } |
| 109 | let len = u32::try_from(bytes.len()).map_err(|_| ErrorCode::Limit)?; |
| 110 | if unsafe { BCryptGenRandom(std::ptr::null_mut(), bytes.as_mut_ptr(), len, 2) } >= 0 { |
| 111 | Ok(()) |
| 112 | } else { |
| 113 | Err(ErrorCode::Io) |
| 114 | } |
| 115 | } |
| 116 | #[cfg(not(any(target_os = "linux", windows)))] |
| 117 | { |
| 118 | let _ = bytes; |
| 119 | Err(ErrorCode::UnsupportedFeature) |
| 120 | } |
| 121 | } |
| 122 | const CRC_TABLE: [u32; 256] = { |
| 123 | let mut table = [0; 256]; |
| 124 | let mut i = 0; |
| 125 | while i < 256 { |
| 126 | let mut crc = i as u32; |
| 127 | let mut bit = 0; |
| 128 | while bit < 8 { |
| 129 | crc = (crc >> 1) ^ (0xedb88320 & 0u32.wrapping_sub(crc & 1)); |
| 130 | bit += 1; |
| 131 | } |
| 132 | table[i] = crc; |
| 133 | i += 1; |
| 134 | } |
| 135 | table |
| 136 | }; |
| 137 | pub(crate) fn zipcrypto_decrypt( |
| 138 | packed: &[u8], |
| 139 | password: &[u8], |
| 140 | verifier: u8, |
| 141 | check: &mut impl FnMut() -> Result<()>, |
| 142 | ) -> Result<Zeroizing<Vec<u8>>> { |
| 143 | if packed.len() < 12 { |
| 144 | return Err(ErrorCode::Integrity); |
| 145 | } |
| 146 | let mut key = Zeroizing::new([0x12345678u32, 0x23456789, 0x34567890]); |
| 147 | for &byte in password { |
| 148 | zip_update(&mut key, byte); |
| 149 | } |
| 150 | let mut out = Zeroizing::new(Vec::with_capacity(packed.len() - 12)); |
| 151 | for (index, &byte) in packed.iter().enumerate() { |
| 152 | if index % 65536 == 0 { |
| 153 | check()?; |
| 154 | } |
| 155 | let temp = key[2] | 2; |
| 156 | let plain = byte ^ ((temp.wrapping_mul(temp ^ 1) >> 8) as u8); |
| 157 | zip_update(&mut key, plain); |
| 158 | if index == 11 && plain != verifier { |
| 159 | return Err(ErrorCode::WrongPassword); |
| 160 | } |
| 161 | if index >= 12 { |
| 162 | out.push(plain); |
| 163 | } |
| 164 | } |
| 165 | Ok(out) |
| 166 | } |
| 167 | |
| 168 | pub(crate) enum Decryptor { |
| 169 | Plain, |
| 170 | Zip(Zeroizing<[u32; 3]>), |
| 171 | Aes { |
| 172 | cipher: Aes256, |
| 173 | counter: u128, |
| 174 | mask: [u8; 16], |
| 175 | used: usize, |
| 176 | }, |
| 177 | } |
| 178 | fn zip_update(key: &mut [u32; 3], byte: u8) { |
| 179 | key[0] = (key[0] >> 8) ^ CRC_TABLE[((key[0] as u8) ^ byte) as usize]; |
| 180 | key[1] = key[1] |
| 181 | .wrapping_add(key[0] & 255) |
| 182 | .wrapping_mul(134775813) |
| 183 | .wrapping_add(1); |
| 184 | key[2] = (key[2] >> 8) ^ CRC_TABLE[((key[2] as u8) ^ ((key[1] >> 24) as u8)) as usize]; |
| 185 | } |
| 186 | impl Decryptor { |
| 187 | pub fn prepare( |
| 188 | file: &mut std::fs::File, |
| 189 | offset: u64, |
| 190 | length: u64, |
| 191 | password: &[u8], |
| 192 | aes: bool, |
| 193 | verifier: u8, |
| 194 | check: &mut impl FnMut() -> Result<()>, |
| 195 | ) -> Result<(Self, u64, u64)> { |
| 196 | use std::io::{Read, Seek, SeekFrom}; |
| 197 | file.seek(SeekFrom::Start(offset)) |
| 198 | .map_err(|_| ErrorCode::Io)?; |
| 199 | if aes { |
| 200 | if length < 28 { |
| 201 | return Err(ErrorCode::Integrity); |
| 202 | } |
| 203 | let mut header = [0; 18]; |
| 204 | file.read_exact(&mut header) |
| 205 | .map_err(|_| ErrorCode::Integrity)?; |
| 206 | let key = keys(password, &header[..16]); |
| 207 | if !bool::from(key[64..].ct_eq(&header[16..])) { |
| 208 | return Err(ErrorCode::WrongPassword); |
| 209 | } |
| 210 | let mut mac = |
| 211 | <Sha1Mac as Mac>::new_from_slice(&key[32..64]).map_err(|_| ErrorCode::Internal)?; |
| 212 | let mut remaining = length - 28; |
| 213 | let mut buffer = [0; 65536]; |
| 214 | while remaining != 0 { |
| 215 | check()?; |
| 216 | let n = remaining.min(buffer.len() as u64) as usize; |
| 217 | file.read_exact(&mut buffer[..n]) |
| 218 | .map_err(|_| ErrorCode::Integrity)?; |
| 219 | mac.update(&buffer[..n]); |
| 220 | remaining -= n as u64; |
| 221 | } |
| 222 | let mut tag = [0; 10]; |
| 223 | file.read_exact(&mut tag) |
| 224 | .map_err(|_| ErrorCode::Integrity)?; |
| 225 | mac.verify_truncated_left(&tag) |
| 226 | .map_err(|_| ErrorCode::Integrity)?; |
| 227 | let cipher = Aes256::new_from_slice(&key[..32]).map_err(|_| ErrorCode::Internal)?; |
| 228 | Ok(( |
| 229 | Self::Aes { |
| 230 | cipher, |
| 231 | counter: 1, |
| 232 | mask: [0; 16], |
| 233 | used: 16, |
| 234 | }, |
| 235 | offset + 18, |
| 236 | length - 28, |
| 237 | )) |
| 238 | } else { |
| 239 | if length < 12 { |
| 240 | return Err(ErrorCode::Integrity); |
| 241 | } |
| 242 | let mut key = Zeroizing::new([0x12345678, 0x23456789, 0x34567890]); |
| 243 | for &b in password { |
| 244 | zip_update(&mut key, b); |
| 245 | } |
| 246 | let mut decoder = Self::Zip(key); |
| 247 | let mut header = [0; 12]; |
| 248 | file.read_exact(&mut header) |
| 249 | .map_err(|_| ErrorCode::Integrity)?; |
| 250 | decoder.apply(&mut header); |
| 251 | if header[11] != verifier { |
| 252 | return Err(ErrorCode::WrongPassword); |
| 253 | } |
| 254 | header.zeroize(); |
| 255 | Ok((decoder, offset + 12, length - 12)) |
| 256 | } |
| 257 | } |
| 258 | pub fn apply(&mut self, bytes: &mut [u8]) { |
| 259 | match self { |
| 260 | Self::Plain => {} |
| 261 | Self::Zip(key) => { |
| 262 | for byte in bytes { |
| 263 | let temp = key[2] | 2; |
| 264 | *byte ^= (temp.wrapping_mul(temp ^ 1) >> 8) as u8; |
| 265 | zip_update(key, *byte); |
| 266 | } |
| 267 | } |
| 268 | Self::Aes { |
| 269 | cipher, |
| 270 | counter, |
| 271 | mask, |
| 272 | used, |
| 273 | } => { |
| 274 | for byte in bytes { |
| 275 | if *used == 16 { |
| 276 | let mut block = counter.to_le_bytes().into(); |
| 277 | cipher.encrypt_block(&mut block); |
| 278 | mask.copy_from_slice(&block); |
| 279 | block.as_mut_slice().zeroize(); |
| 280 | *counter += 1; |
| 281 | *used = 0; |
| 282 | } |
| 283 | *byte ^= mask[*used]; |
| 284 | *used += 1; |
| 285 | } |
| 286 | } |
| 287 | } |
| 288 | } |
| 289 | } |
| 290 | impl Drop for Decryptor { |
| 291 | fn drop(&mut self) { |
| 292 | if let Self::Aes { mask, counter, .. } = self { |
| 293 | mask.zeroize(); |
| 294 | counter.zeroize(); |
| 295 | } |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | pub(crate) fn aes_encrypt_file( |
| 300 | input: &mut std::fs::File, |
| 301 | length: u64, |
| 302 | output: &mut std::fs::File, |
| 303 | password: &[u8], |
| 304 | check: &mut impl FnMut() -> Result<()>, |
| 305 | ) -> Result<()> { |
| 306 | use std::io::{Read, Write}; |
| 307 | check()?; |
| 308 | let mut salt = [0; 16]; |
| 309 | random(&mut salt)?; |
| 310 | let key = keys(password, &salt); |
| 311 | output.write_all(&salt).map_err(crate::space::io_error)?; |
| 312 | output |
| 313 | .write_all(&key[64..]) |
| 314 | .map_err(crate::space::io_error)?; |
| 315 | let mut cipher = Decryptor::Aes { |
| 316 | cipher: Aes256::new_from_slice(&key[..32]).map_err(|_| ErrorCode::Internal)?, |
| 317 | counter: 1, |
| 318 | mask: [0; 16], |
| 319 | used: 16, |
| 320 | }; |
| 321 | let mut mac = |
| 322 | <Sha1Mac as Mac>::new_from_slice(&key[32..64]).map_err(|_| ErrorCode::Internal)?; |
| 323 | let mut remaining = length; |
| 324 | let mut buffer = Zeroizing::new([0; 65536]); |
| 325 | while remaining != 0 { |
| 326 | check()?; |
| 327 | let n = remaining.min(buffer.len() as u64) as usize; |
| 328 | input |
| 329 | .read_exact(&mut buffer[..n]) |
| 330 | .map_err(crate::space::io_error)?; |
| 331 | cipher.apply(&mut buffer[..n]); |
| 332 | mac.update(&buffer[..n]); |
| 333 | output |
| 334 | .write_all(&buffer[..n]) |
| 335 | .map_err(crate::space::io_error)?; |
| 336 | remaining -= n as u64; |
| 337 | } |
| 338 | output |
| 339 | .write_all(&mac.finalize().into_bytes()[..10]) |
| 340 | .map_err(crate::space::io_error)?; |
| 341 | Ok(()) |
| 342 | } |