| 1 | use crate::protocol::*; |
| 2 | use std::collections::{BTreeMap, BTreeSet}; |
| 3 | use zlib_rs::{Deflate, DeflateFlush, Inflate, InflateFlush, Status, crc32::crc32}; |
| 4 | |
| 5 | type Result<T> = std::result::Result<T, ErrorCode>; |
| 6 | pub const MAX_PATH_DEPTH: usize = 64; |
| 7 | pub const MAX_METADATA_BYTES: usize = 8 * 1024 * 1024; |
| 8 | pub const MAX_OUTPUT_NODES: usize = 32_768; |
| 9 | |
| 10 | #[derive(Default)] |
| 11 | pub(crate) struct MetadataBudget { |
| 12 | bytes: usize, |
| 13 | nodes: usize, |
| 14 | } |
| 15 | impl MetadataBudget { |
| 16 | pub(crate) fn charge(&mut self, name: &str) -> Result<()> { |
| 17 | // 이름 복제와 인덱스 노드 비용을 할당 전에 계산함. |
| 18 | let cost = name |
| 19 | .len() |
| 20 | .checked_mul(4) |
| 21 | .and_then(|n| n.checked_add(256)) |
| 22 | .ok_or(ErrorCode::Limit)?; |
| 23 | self.bytes = self |
| 24 | .bytes |
| 25 | .checked_add(cost) |
| 26 | .filter(|n| *n <= MAX_METADATA_BYTES) |
| 27 | .ok_or(ErrorCode::Limit)?; |
| 28 | self.nodes = self |
| 29 | .nodes |
| 30 | .checked_add(1) |
| 31 | .filter(|n| *n <= MAX_OUTPUT_NODES) |
| 32 | .ok_or(ErrorCode::Limit)?; |
| 33 | Ok(()) |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | #[derive(Debug)] |
| 38 | pub struct Member { |
| 39 | pub entry: Entry, |
| 40 | pub data: Vec<u8>, |
| 41 | } |
| 42 | pub struct Catalog { |
| 43 | pub format: Format, |
| 44 | pub members: Vec<Member>, |
| 45 | } |
| 46 | fn part(b: &[u8], at: usize, n: usize) -> Result<&[u8]> { |
| 47 | b.get(at..at.checked_add(n).ok_or(ErrorCode::Integrity)?) |
| 48 | .ok_or(ErrorCode::Integrity) |
| 49 | } |
| 50 | fn u16at(b: &[u8], at: usize) -> Result<u16> { |
| 51 | Ok(u16::from_le_bytes(part(b, at, 2)?.try_into().unwrap())) |
| 52 | } |
| 53 | fn u32at(b: &[u8], at: usize) -> Result<u32> { |
| 54 | Ok(u32::from_le_bytes(part(b, at, 4)?.try_into().unwrap())) |
| 55 | } |
| 56 | |
| 57 | pub fn valid_name(name: &str, directory: bool) -> Result<String> { |
| 58 | let name = if directory { |
| 59 | name.strip_suffix('/').unwrap_or(name) |
| 60 | } else { |
| 61 | name |
| 62 | }; |
| 63 | if name.is_empty() |
| 64 | || name.len() > 4096 |
| 65 | || name.starts_with('/') |
| 66 | || name.contains('\\') |
| 67 | || name |
| 68 | .chars() |
| 69 | .any(|c| c.is_control() || matches!(c, ':' | '*' | '?' | '"' | '<' | '>' | '|')) |
| 70 | { |
| 71 | return Err(ErrorCode::UnsafePath); |
| 72 | } |
| 73 | if name.split('/').count() > MAX_PATH_DEPTH { |
| 74 | return Err(ErrorCode::Limit); |
| 75 | } |
| 76 | for component in name.split('/') { |
| 77 | if component.is_empty() |
| 78 | || matches!(component, "." | "..") |
| 79 | || component.ends_with(['.', ' ']) |
| 80 | || component.len() > 255 |
| 81 | { |
| 82 | return Err(ErrorCode::UnsafePath); |
| 83 | } |
| 84 | let stem = component.split('.').next().unwrap().to_ascii_uppercase(); |
| 85 | if matches!( |
| 86 | stem.as_str(), |
| 87 | "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$" |
| 88 | ) || ["COM", "LPT"].iter().any(|p| { |
| 89 | stem.strip_prefix(p).is_some_and(|n| { |
| 90 | matches!( |
| 91 | n, |
| 92 | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³" |
| 93 | ) |
| 94 | }) |
| 95 | }) { |
| 96 | return Err(ErrorCode::UnsafePath); |
| 97 | } |
| 98 | } |
| 99 | Ok(name.to_owned()) |
| 100 | } |
| 101 | pub fn validate_members(members: &[Member]) -> Result<()> { |
| 102 | let mut names = BTreeMap::<String, bool>::new(); |
| 103 | let mut budget = MetadataBudget::default(); |
| 104 | for member in members { |
| 105 | budget.charge(&member.entry.name)?; |
| 106 | let directory = member.entry.kind == EntryKind::Directory; |
| 107 | let name = valid_name(&member.entry.name, directory)?.to_lowercase(); |
| 108 | if names.insert(name, directory).is_some() { |
| 109 | return Err(ErrorCode::Conflict); |
| 110 | } |
| 111 | } |
| 112 | for name in names.keys() { |
| 113 | let mut parent = name.as_str(); |
| 114 | while let Some((p, _)) = parent.rsplit_once('/') { |
| 115 | if names.get(p) == Some(&false) { |
| 116 | return Err(ErrorCode::Conflict); |
| 117 | } |
| 118 | parent = p; |
| 119 | } |
| 120 | } |
| 121 | Ok(()) |
| 122 | } |
| 123 | pub(crate) fn output_directories(members: &[Member]) -> Result<BTreeSet<String>> { |
| 124 | validate_members(members)?; |
| 125 | let mut budget = MetadataBudget::default(); |
| 126 | let mut dirs = BTreeSet::new(); |
| 127 | for member in members { |
| 128 | budget.charge(&member.entry.name)?; |
| 129 | if member.entry.kind == EntryKind::Directory && !dirs.contains(member.entry.name.as_str()) { |
| 130 | dirs.insert(member.entry.name.clone()); |
| 131 | } |
| 132 | let mut name = member.entry.name.as_str(); |
| 133 | while let Some((parent, _)) = name.rsplit_once('/') { |
| 134 | if !dirs.contains(parent) { |
| 135 | budget.charge(parent)?; |
| 136 | dirs.insert(parent.to_owned()); |
| 137 | } |
| 138 | name = parent; |
| 139 | } |
| 140 | } |
| 141 | Ok(dirs) |
| 142 | } |
| 143 | |
| 144 | fn bounded_append(output: &mut Vec<u8>, data: &[u8], limit: u64) -> Result<()> { |
| 145 | if (output.len() as u64) |
| 146 | .checked_add(data.len() as u64) |
| 147 | .is_none_or(|n| n > limit) |
| 148 | { |
| 149 | return Err(ErrorCode::Limit); |
| 150 | } |
| 151 | output |
| 152 | .try_reserve(data.len()) |
| 153 | .map_err(|_| ErrorCode::Limit)?; |
| 154 | output.extend_from_slice(data); |
| 155 | Ok(()) |
| 156 | } |
| 157 | fn inflate( |
| 158 | input: &[u8], |
| 159 | gzip: bool, |
| 160 | limit: u64, |
| 161 | check: &mut impl FnMut() -> Result<()>, |
| 162 | ) -> Result<(Vec<u8>, usize)> { |
| 163 | let mut stream = Inflate::new(gzip, if gzip { 31 } else { 15 }); |
| 164 | let mut out = Vec::new(); |
| 165 | let mut buffer = [0; 65536]; |
| 166 | loop { |
| 167 | check()?; |
| 168 | let before_in = stream.total_in(); |
| 169 | let before_out = stream.total_out(); |
| 170 | let status = stream |
| 171 | .decompress( |
| 172 | &input[before_in as usize..], |
| 173 | &mut buffer, |
| 174 | InflateFlush::NoFlush, |
| 175 | ) |
| 176 | .map_err(|_| ErrorCode::Integrity)?; |
| 177 | let written = (stream.total_out() - before_out) as usize; |
| 178 | bounded_append(&mut out, &buffer[..written], limit)?; |
| 179 | if status == Status::StreamEnd { |
| 180 | return Ok((out, stream.total_in() as usize)); |
| 181 | } |
| 182 | if stream.total_in() == before_in && stream.total_out() == before_out { |
| 183 | return Err(ErrorCode::Integrity); |
| 184 | } |
| 185 | } |
| 186 | } |
| 187 | fn gzip(input: &[u8], limits: Limits, check: &mut impl FnMut() -> Result<()>) -> Result<Vec<u8>> { |
| 188 | let mut at = 0; |
| 189 | let mut result = Vec::new(); |
| 190 | while at < input.len() { |
| 191 | if !input[at..].starts_with(&[31, 139, 8]) { |
| 192 | return Err(ErrorCode::Integrity); |
| 193 | } |
| 194 | let (out, used) = inflate( |
| 195 | &input[at..], |
| 196 | true, |
| 197 | limits.output - result.len() as u64, |
| 198 | check, |
| 199 | )?; |
| 200 | if used == 0 { |
| 201 | return Err(ErrorCode::Integrity); |
| 202 | } |
| 203 | bounded_append(&mut result, &out, limits.output)?; |
| 204 | at += used; |
| 205 | } |
| 206 | Ok(result) |
| 207 | } |
| 208 | pub(crate) fn tar_string(b: &[u8]) -> Result<String> { |
| 209 | let n = b.iter().position(|v| *v == 0).unwrap_or(b.len()); |
| 210 | if b[n..].iter().any(|v| *v != 0) { |
| 211 | return Err(ErrorCode::Integrity); |
| 212 | } |
| 213 | std::str::from_utf8(&b[..n]) |
| 214 | .map(str::to_owned) |
| 215 | .map_err(|_| ErrorCode::UnsupportedFeature) |
| 216 | } |
| 217 | pub(crate) fn octal(b: &[u8]) -> Result<u64> { |
| 218 | if b.first().is_some_and(|x| x & 128 != 0) { |
| 219 | return Err(ErrorCode::UnsupportedFeature); |
| 220 | } |
| 221 | let text = std::str::from_utf8(b) |
| 222 | .map_err(|_| ErrorCode::Integrity)? |
| 223 | .trim_matches(['\0', ' ']); |
| 224 | if text.is_empty() { |
| 225 | return Ok(0); |
| 226 | } |
| 227 | u64::from_str_radix(text, 8).map_err(|_| ErrorCode::Integrity) |
| 228 | } |
| 229 | fn tar( |
| 230 | input: &[u8], |
| 231 | limits: Limits, |
| 232 | decode: bool, |
| 233 | check: &mut impl FnMut() -> Result<()>, |
| 234 | ) -> Result<Vec<Member>> { |
| 235 | let mut at = 0; |
| 236 | let mut members = Vec::new(); |
| 237 | let mut total = 0u64; |
| 238 | let mut metadata = MetadataBudget::default(); |
| 239 | loop { |
| 240 | check()?; |
| 241 | let header = part(input, at, 512)?; |
| 242 | if header.iter().all(|b| *b == 0) { |
| 243 | if part(input, at + 512, 512)?.iter().any(|b| *b != 0) |
| 244 | || input[at..].iter().any(|b| *b != 0) |
| 245 | || input.len() % 512 != 0 |
| 246 | { |
| 247 | return Err(ErrorCode::Integrity); |
| 248 | } |
| 249 | break; |
| 250 | } |
| 251 | if members.len() >= limits.entries as usize { |
| 252 | return Err(ErrorCode::Limit); |
| 253 | } |
| 254 | let expected = octal(&header[148..156])?; |
| 255 | let checksum = header |
| 256 | .iter() |
| 257 | .enumerate() |
| 258 | .map(|(i, b)| { |
| 259 | if (148..156).contains(&i) { |
| 260 | 32u64 |
| 261 | } else { |
| 262 | *b as u64 |
| 263 | } |
| 264 | }) |
| 265 | .sum::<u64>(); |
| 266 | if checksum != expected { |
| 267 | return Err(ErrorCode::Integrity); |
| 268 | } |
| 269 | let mut name = tar_string(&header[..100])?; |
| 270 | if &header[257..263] == b"ustar\0" || &header[257..263] == b"ustar " { |
| 271 | let prefix = tar_string(&header[345..500])?; |
| 272 | if !prefix.is_empty() { |
| 273 | name = format!("{prefix}/{name}"); |
| 274 | } |
| 275 | } else if header[257..263].iter().any(|b| *b != 0) { |
| 276 | return Err(ErrorCode::UnsupportedFeature); |
| 277 | } |
| 278 | let kind = match header[156] { |
| 279 | 0 | b'0' => EntryKind::File, |
| 280 | b'5' => EntryKind::Directory, |
| 281 | b'1' | b'2' => EntryKind::Link, |
| 282 | b'x' | b'g' | b'L' | b'K' => return Err(ErrorCode::UnsupportedFeature), |
| 283 | _ => EntryKind::Other, |
| 284 | }; |
| 285 | let size = octal(&header[124..136])?; |
| 286 | if kind != EntryKind::File && size != 0 { |
| 287 | return Err(ErrorCode::Integrity); |
| 288 | } |
| 289 | total = total |
| 290 | .checked_add(size) |
| 291 | .filter(|n| *n <= limits.output) |
| 292 | .ok_or(ErrorCode::Limit)?; |
| 293 | let size = usize::try_from(size).map_err(|_| ErrorCode::Limit)?; |
| 294 | let bytes = part(input, at + 512, size)?; |
| 295 | metadata.charge(&name)?; |
| 296 | let name = valid_name(&name, kind == EntryKind::Directory)?; |
| 297 | let data = if decode { bytes.to_vec() } else { Vec::new() }; |
| 298 | members.push(Member { |
| 299 | entry: Entry { |
| 300 | entry_id: members.len() as u32, |
| 301 | name, |
| 302 | kind, |
| 303 | size: size as u64, |
| 304 | compressed_size: size as u64, |
| 305 | encrypted: false, |
| 306 | }, |
| 307 | data, |
| 308 | }); |
| 309 | at = at |
| 310 | .checked_add(512) |
| 311 | .and_then(|n| n.checked_add(size.div_ceil(512) * 512)) |
| 312 | .ok_or(ErrorCode::Integrity)?; |
| 313 | } |
| 314 | validate_members(&members)?; |
| 315 | Ok(members) |
| 316 | } |
| 317 | #[derive(Clone, Copy, PartialEq, Eq)] |
| 318 | pub(crate) struct AesExtra { |
| 319 | pub version: u16, |
| 320 | pub method: u16, |
| 321 | } |
| 322 | pub(crate) fn aes_extra(extra: &[u8]) -> Result<Option<AesExtra>> { |
| 323 | let mut at = 0; |
| 324 | let mut found = None; |
| 325 | while at < extra.len() { |
| 326 | let tag = u16at(extra, at)?; |
| 327 | let len = u16at(extra, at + 2)? as usize; |
| 328 | let value = part(extra, at + 4, len)?; |
| 329 | if tag == 1 { |
| 330 | return Err(ErrorCode::UnsupportedFeature); |
| 331 | } |
| 332 | if tag == 0x9901 { |
| 333 | if found.is_some() || len < 7 { |
| 334 | return Err(ErrorCode::Integrity); |
| 335 | } |
| 336 | let version = u16at(value, 0)?; |
| 337 | let method = u16at(value, 5)?; |
| 338 | if !matches!(version, 1 | 2) |
| 339 | || &value[2..4] != b"AE" |
| 340 | || value[4] != 3 |
| 341 | || !matches!(method, 0 | 8) |
| 342 | { |
| 343 | return Err(ErrorCode::UnsupportedFeature); |
| 344 | } |
| 345 | found = Some(AesExtra { version, method }); |
| 346 | } |
| 347 | at += 4 + len; |
| 348 | } |
| 349 | Ok(found) |
| 350 | } |
| 351 | /// ZIP 항목 이름을 해석함. |
| 352 | /// |
| 353 | /// - UTF-8 플래그(비트 11)가 있으면 이름은 UTF-8이어야 하며 아니면 손상으로 봄. |
| 354 | /// - 플래그가 없으면 CRC가 원래 이름과 맞는 Info-ZIP Unicode Path 확장 필드(0x7075)를 먼저 씀. |
| 355 | /// CRC가 다르거나 버전이 1이 아니면 APPNOTE 4.6.9에 따라 무시함. |
| 356 | /// - 그다음 이름 바이트가 UTF-8로 유효하면 그대로 씀. Linux와 macOS 도구가 이렇게 기록함. |
| 357 | /// - 그 밖의 바이트(CP437, CP949 등)는 코드 페이지를 추측하지 않고 지원하지 않음으로 거부함. |
| 358 | /// |
| 359 | /// 어느 경우든 결과는 호출자가 `valid_name`으로 다시 검사함. |
| 360 | pub(crate) fn zip_name(raw: &[u8], flags: u16, extra: &[u8]) -> Result<String> { |
| 361 | if flags & 0x0800 != 0 { |
| 362 | return std::str::from_utf8(raw) |
| 363 | .map(str::to_owned) |
| 364 | .map_err(|_| ErrorCode::Integrity); |
| 365 | } |
| 366 | let mut at = 0; |
| 367 | let mut unicode = None; |
| 368 | while at < extra.len() { |
| 369 | let tag = u16at(extra, at)?; |
| 370 | let len = u16at(extra, at + 2)? as usize; |
| 371 | let value = part(extra, at + 4, len)?; |
| 372 | if tag == 0x7075 { |
| 373 | if unicode.is_some() || len < 5 { |
| 374 | return Err(ErrorCode::Integrity); |
| 375 | } |
| 376 | unicode = Some(value); |
| 377 | } |
| 378 | at += 4 + len; |
| 379 | } |
| 380 | if let Some(value) = unicode |
| 381 | && value[0] == 1 |
| 382 | && u32::from_le_bytes(value[1..5].try_into().unwrap()) == crc32(0, raw) |
| 383 | { |
| 384 | return std::str::from_utf8(&value[5..]) |
| 385 | .map(str::to_owned) |
| 386 | .map_err(|_| ErrorCode::Integrity); |
| 387 | } |
| 388 | std::str::from_utf8(raw) |
| 389 | .map(str::to_owned) |
| 390 | .map_err(|_| ErrorCode::UnsupportedFeature) |
| 391 | } |
| 392 | fn zip( |
| 393 | input: &[u8], |
| 394 | limits: Limits, |
| 395 | decode: bool, |
| 396 | password: Option<&[u8]>, |
| 397 | check: &mut impl FnMut() -> Result<()>, |
| 398 | ) -> Result<Vec<Member>> { |
| 399 | if input.len() < 22 { |
| 400 | return Err(ErrorCode::Integrity); |
| 401 | } |
| 402 | let end = (input.len().saturating_sub(65557)..=input.len() - 22) |
| 403 | .rev() |
| 404 | .find(|&i| { |
| 405 | input.get(i..i + 4) == Some(b"PK\x05\x06") |
| 406 | && u16at(input, i + 20) |
| 407 | .ok() |
| 408 | .is_some_and(|n| i + 22 + n as usize == input.len()) |
| 409 | }) |
| 410 | .ok_or(ErrorCode::Integrity)?; |
| 411 | let count = u16at(input, end + 10)? as usize; |
| 412 | if u16at(input, end + 4)? != 0 |
| 413 | || u16at(input, end + 6)? != 0 |
| 414 | || count != u16at(input, end + 8)? as usize |
| 415 | { |
| 416 | return Err(ErrorCode::UnsupportedFeature); |
| 417 | } |
| 418 | if count == 65535 || u32at(input, end + 12)? == u32::MAX || u32at(input, end + 16)? == u32::MAX |
| 419 | { |
| 420 | return Err(ErrorCode::UnsupportedFeature); |
| 421 | } |
| 422 | if count > limits.entries as usize { |
| 423 | return Err(ErrorCode::Limit); |
| 424 | } |
| 425 | let central = u32at(input, end + 16)? as usize; |
| 426 | if central.checked_add(u32at(input, end + 12)? as usize) != Some(end) { |
| 427 | return Err(ErrorCode::Integrity); |
| 428 | } |
| 429 | let mut at = central; |
| 430 | let mut members = Vec::new(); |
| 431 | let mut spans = Vec::new(); |
| 432 | let mut total = 0u64; |
| 433 | let mut metadata = MetadataBudget::default(); |
| 434 | for id in 0..count { |
| 435 | check()?; |
| 436 | let h = part(input, at, 46)?; |
| 437 | if &h[..4] != b"PK\x01\x02" { |
| 438 | return Err(ErrorCode::Integrity); |
| 439 | } |
| 440 | let flags = u16at(h, 8)?; |
| 441 | let method = u16at(h, 10)?; |
| 442 | if flags & !0x080f != 0 || !matches!(method, 0 | 8 | 99) || u16at(h, 34)? != 0 { |
| 443 | return Err(ErrorCode::UnsupportedFeature); |
| 444 | } |
| 445 | let crc = u32at(h, 16)?; |
| 446 | let compressed = u32at(h, 20)? as usize; |
| 447 | let size = u32at(h, 24)? as usize; |
| 448 | if compressed == u32::MAX as usize || size == u32::MAX as usize { |
| 449 | return Err(ErrorCode::UnsupportedFeature); |
| 450 | } |
| 451 | total = total |
| 452 | .checked_add(size as u64) |
| 453 | .filter(|n| *n <= limits.output) |
| 454 | .ok_or(ErrorCode::Limit)?; |
| 455 | let name_len = u16at(h, 28)? as usize; |
| 456 | let extra_len = u16at(h, 30)? as usize; |
| 457 | let comment_len = u16at(h, 32)? as usize; |
| 458 | let extra = aes_extra(part(input, at + 46 + name_len, extra_len)?)?; |
| 459 | let encrypted = flags & 1 != 0; |
| 460 | if (method == 99) != extra.is_some() || (method == 99 && !encrypted) { |
| 461 | return Err(ErrorCode::Integrity); |
| 462 | } |
| 463 | if extra.is_some_and(|e| e.version == 2) && crc != 0 { |
| 464 | return Err(ErrorCode::Integrity); |
| 465 | } |
| 466 | let raw = part(input, at + 46, name_len)?; |
| 467 | let name = zip_name(raw, flags, part(input, at + 46 + name_len, extra_len)?)?; |
| 468 | let name = name.as_str(); |
| 469 | let mode = u32at(h, 38)? >> 16; |
| 470 | let kind = match mode & 0xf000 { |
| 471 | 0xa000 => EntryKind::Link, |
| 472 | 0x4000 => EntryKind::Directory, |
| 473 | 0 | 0x8000 => { |
| 474 | if name.ends_with('/') { |
| 475 | EntryKind::Directory |
| 476 | } else { |
| 477 | EntryKind::File |
| 478 | } |
| 479 | } |
| 480 | _ => EntryKind::Other, |
| 481 | }; |
| 482 | metadata.charge(name)?; |
| 483 | let name = valid_name(name, kind == EntryKind::Directory)?; |
| 484 | let local = u32at(h, 42)? as usize; |
| 485 | let lh = part(input, local, 30)?; |
| 486 | if &lh[..4] != b"PK\x03\x04" || u16at(lh, 6)? != flags || u16at(lh, 8)? != method { |
| 487 | return Err(ErrorCode::Integrity); |
| 488 | } |
| 489 | let ln = u16at(lh, 26)? as usize; |
| 490 | let le = u16at(lh, 28)? as usize; |
| 491 | if aes_extra(part(input, local + 30 + ln, le)?)? != extra |
| 492 | || u16at(lh, 10)? != u16at(h, 12)? |
| 493 | || part(input, local + 30, ln)? != raw |
| 494 | { |
| 495 | return Err(ErrorCode::Integrity); |
| 496 | } |
| 497 | if flags & 8 == 0 |
| 498 | && (u32at(lh, 14)? != crc |
| 499 | || u32at(lh, 18)? as usize != compressed |
| 500 | || u32at(lh, 22)? as usize != size) |
| 501 | { |
| 502 | return Err(ErrorCode::Integrity); |
| 503 | } |
| 504 | let start = local |
| 505 | .checked_add(30 + ln + le) |
| 506 | .ok_or(ErrorCode::Integrity)?; |
| 507 | let packed = part(input, start, compressed)?; |
| 508 | let mut stop = start + compressed; |
| 509 | if flags & 8 != 0 { |
| 510 | if input.get(stop..stop + 4) == Some(b"PK\x07\x08") { |
| 511 | stop += 4; |
| 512 | } |
| 513 | if u32at(input, stop)? != crc |
| 514 | || u32at(input, stop + 4)? as usize != compressed |
| 515 | || u32at(input, stop + 8)? as usize != size |
| 516 | { |
| 517 | return Err(ErrorCode::Integrity); |
| 518 | } |
| 519 | stop += 12; |
| 520 | } |
| 521 | if stop > central { |
| 522 | return Err(ErrorCode::Integrity); |
| 523 | } |
| 524 | spans.push((local, stop)); |
| 525 | if encrypted && compressed < if extra.is_some() { 28 } else { 12 } { |
| 526 | return Err(ErrorCode::Integrity); |
| 527 | } |
| 528 | let data = if decode { |
| 529 | let decrypted; |
| 530 | let packed = if encrypted { |
| 531 | let password = password.ok_or(ErrorCode::WrongPassword)?; |
| 532 | decrypted = if extra.is_some() { |
| 533 | crate::crypto::aes_decrypt(packed, password, check)? |
| 534 | } else { |
| 535 | let verifier = if flags & 8 != 0 { |
| 536 | (u16at(h, 12)? >> 8) as u8 |
| 537 | } else { |
| 538 | (crc >> 24) as u8 |
| 539 | }; |
| 540 | crate::crypto::zipcrypto_decrypt(packed, password, verifier, check)? |
| 541 | }; |
| 542 | decrypted.as_slice() |
| 543 | } else { |
| 544 | packed |
| 545 | }; |
| 546 | let actual_method = extra.map_or(method, |e| e.method); |
| 547 | let bytes = if actual_method == 0 { |
| 548 | if packed.len() != size { |
| 549 | return Err(ErrorCode::Integrity); |
| 550 | } |
| 551 | packed.to_vec() |
| 552 | } else { |
| 553 | let (out, used) = inflate(packed, false, size as u64, check)?; |
| 554 | if used != packed.len() { |
| 555 | return Err(ErrorCode::Integrity); |
| 556 | } |
| 557 | out |
| 558 | }; |
| 559 | if bytes.len() != size |
| 560 | || (extra.is_none_or(|e| e.version == 1) && crc32(0, &bytes) != crc) |
| 561 | { |
| 562 | return Err(ErrorCode::Integrity); |
| 563 | } |
| 564 | bytes |
| 565 | } else { |
| 566 | Vec::new() |
| 567 | }; |
| 568 | if kind == EntryKind::Directory && size != 0 { |
| 569 | return Err(ErrorCode::Integrity); |
| 570 | } |
| 571 | members.push(Member { |
| 572 | entry: Entry { |
| 573 | entry_id: id as u32, |
| 574 | name, |
| 575 | kind, |
| 576 | size: size as u64, |
| 577 | compressed_size: compressed as u64, |
| 578 | encrypted, |
| 579 | }, |
| 580 | data, |
| 581 | }); |
| 582 | at = at |
| 583 | .checked_add(46 + name_len + extra_len + comment_len) |
| 584 | .ok_or(ErrorCode::Integrity)?; |
| 585 | } |
| 586 | if at != end { |
| 587 | return Err(ErrorCode::Integrity); |
| 588 | } |
| 589 | spans.sort_unstable(); |
| 590 | let mut next = 0; |
| 591 | for (start, stop) in spans { |
| 592 | if start != next { |
| 593 | return Err(ErrorCode::Integrity); |
| 594 | } |
| 595 | next = stop; |
| 596 | } |
| 597 | if next != central { |
| 598 | return Err(ErrorCode::Integrity); |
| 599 | } |
| 600 | validate_members(&members)?; |
| 601 | Ok(members) |
| 602 | } |
| 603 | pub fn parse( |
| 604 | input: &[u8], |
| 605 | limits: Limits, |
| 606 | decode: bool, |
| 607 | check: &mut impl FnMut() -> Result<()>, |
| 608 | ) -> Result<Catalog> { |
| 609 | parse_with_password(input, limits, decode, None, check) |
| 610 | } |
| 611 | pub fn parse_with_password( |
| 612 | input: &[u8], |
| 613 | limits: Limits, |
| 614 | decode: bool, |
| 615 | password: Option<&[u8]>, |
| 616 | check: &mut impl FnMut() -> Result<()>, |
| 617 | ) -> Result<Catalog> { |
| 618 | if !limits.valid() { |
| 619 | return Err(ErrorCode::Limit); |
| 620 | } |
| 621 | let limits = limits.legacy(); |
| 622 | if input.len() as u64 > limits.input { |
| 623 | return Err(ErrorCode::Limit); |
| 624 | } |
| 625 | if input.starts_with(b"7z\xbc\xaf\x27\x1c") { |
| 626 | return Ok(Catalog { |
| 627 | format: Format::SevenZip, |
| 628 | members: crate::seven_zip::parse(input, limits, decode, check)?, |
| 629 | }); |
| 630 | } |
| 631 | if input.starts_with(b"PK\x03\x04") || input.starts_with(b"PK\x05\x06") { |
| 632 | return Ok(Catalog { |
| 633 | format: Format::Zip, |
| 634 | members: zip(input, limits, decode, password, check)?, |
| 635 | }); |
| 636 | } |
| 637 | if input.starts_with(&[31, 139]) { |
| 638 | let bytes = gzip(input, limits, check)?; |
| 639 | if bytes.len() >= 512 && matches!(&bytes[257..263], b"ustar\0" | b"ustar ") { |
| 640 | return Ok(Catalog { |
| 641 | format: Format::TarGzip, |
| 642 | members: tar(&bytes, limits, decode, check)?, |
| 643 | }); |
| 644 | } |
| 645 | let len = bytes.len() as u64; |
| 646 | return Ok(Catalog { |
| 647 | format: Format::Gzip, |
| 648 | members: vec![Member { |
| 649 | entry: Entry { |
| 650 | entry_id: 0, |
| 651 | name: "GZip stream".to_owned(), |
| 652 | kind: EntryKind::File, |
| 653 | size: len, |
| 654 | compressed_size: input.len() as u64, |
| 655 | encrypted: false, |
| 656 | }, |
| 657 | data: if decode { bytes } else { Vec::new() }, |
| 658 | }], |
| 659 | }); |
| 660 | } |
| 661 | if input.len() >= 512 { |
| 662 | return Ok(Catalog { |
| 663 | format: Format::Tar, |
| 664 | members: tar(input, limits, decode, check)?, |
| 665 | }); |
| 666 | } |
| 667 | Err(ErrorCode::UnsupportedFormat) |
| 668 | } |
| 669 | fn deflate(input: &[u8], limit: u64, check: &mut impl FnMut() -> Result<()>) -> Result<Vec<u8>> { |
| 670 | let mut stream = Deflate::new(6, false, 15); |
| 671 | let mut output = Vec::new(); |
| 672 | let mut buffer = [0; 65536]; |
| 673 | loop { |
| 674 | check()?; |
| 675 | let a = stream.total_in(); |
| 676 | let b = stream.total_out(); |
| 677 | let status = stream |
| 678 | .compress(&input[a as usize..], &mut buffer, DeflateFlush::Finish) |
| 679 | .map_err(|_| ErrorCode::Internal)?; |
| 680 | bounded_append( |
| 681 | &mut output, |
| 682 | &buffer[..(stream.total_out() - b) as usize], |
| 683 | limit, |
| 684 | )?; |
| 685 | if status == Status::StreamEnd { |
| 686 | return Ok(output); |
| 687 | } |
| 688 | if a == stream.total_in() && b == stream.total_out() { |
| 689 | return Err(ErrorCode::Internal); |
| 690 | } |
| 691 | } |
| 692 | } |
| 693 | fn put16(v: &mut Vec<u8>, n: u16) { |
| 694 | v.extend(n.to_le_bytes()); |
| 695 | } |
| 696 | fn put32(v: &mut Vec<u8>, n: u32) { |
| 697 | v.extend(n.to_le_bytes()); |
| 698 | } |
| 699 | pub fn create_zip( |
| 700 | members: &[Member], |
| 701 | method: Method, |
| 702 | limits: Limits, |
| 703 | check: &mut impl FnMut() -> Result<()>, |
| 704 | ) -> Result<Vec<u8>> { |
| 705 | create_zip_with_password(members, method, limits, None, check) |
| 706 | } |
| 707 | pub fn create_zip_with_password( |
| 708 | members: &[Member], |
| 709 | method: Method, |
| 710 | limits: Limits, |
| 711 | password: Option<&[u8]>, |
| 712 | check: &mut impl FnMut() -> Result<()>, |
| 713 | ) -> Result<Vec<u8>> { |
| 714 | if !limits.valid() { |
| 715 | return Err(ErrorCode::Limit); |
| 716 | } |
| 717 | let limits = limits.legacy(); |
| 718 | if members.len() > limits.entries as usize || members.len() >= 65535 { |
| 719 | return Err(ErrorCode::Limit); |
| 720 | } |
| 721 | validate_members(members)?; |
| 722 | let mut out = Vec::new(); |
| 723 | let mut cd = Vec::new(); |
| 724 | let mut total = 0u64; |
| 725 | for m in members { |
| 726 | check()?; |
| 727 | total = total |
| 728 | .checked_add(m.data.len() as u64) |
| 729 | .filter(|n| *n <= limits.output) |
| 730 | .ok_or(ErrorCode::Limit)?; |
| 731 | if m.entry.kind != EntryKind::File { |
| 732 | return Err(ErrorCode::UnsupportedFeature); |
| 733 | } |
| 734 | let name = m.entry.name.as_bytes(); |
| 735 | let crc = if password.is_some() { |
| 736 | 0 |
| 737 | } else { |
| 738 | crc32(0, &m.data) |
| 739 | }; |
| 740 | let offset = out.len() as u32; |
| 741 | let packed = match method { |
| 742 | Method::Store => m.data.clone(), |
| 743 | Method::Deflate => deflate(&m.data, limits.output, check)?, |
| 744 | }; |
| 745 | let method = match method { |
| 746 | Method::Store => 0, |
| 747 | Method::Deflate => 8, |
| 748 | }; |
| 749 | let mut extra = Vec::new(); |
| 750 | let flags = if password.is_some() { 0x0801 } else { 0x0800 }; |
| 751 | let version = if password.is_some() { 51 } else { 20 }; |
| 752 | let (method, packed) = if let Some(password) = password { |
| 753 | put16(&mut extra, 0x9901); |
| 754 | put16(&mut extra, 7); |
| 755 | put16(&mut extra, 2); |
| 756 | extra.extend(b"AE"); |
| 757 | extra.push(3); |
| 758 | put16(&mut extra, method); |
| 759 | (99, crate::crypto::aes_encrypt(&packed, password, check)?) |
| 760 | } else { |
| 761 | (method, packed) |
| 762 | }; |
| 763 | out.extend(b"PK\x03\x04"); |
| 764 | put16(&mut out, version); |
| 765 | put16(&mut out, flags); |
| 766 | put16(&mut out, method); |
| 767 | put16(&mut out, 0); |
| 768 | put16(&mut out, 33); |
| 769 | put32(&mut out, crc); |
| 770 | put32(&mut out, packed.len() as u32); |
| 771 | put32(&mut out, m.data.len() as u32); |
| 772 | put16(&mut out, name.len() as u16); |
| 773 | put16(&mut out, extra.len() as u16); |
| 774 | out.extend(name); |
| 775 | out.extend(&extra); |
| 776 | bounded_append(&mut out, &packed, limits.output)?; |
| 777 | cd.extend(b"PK\x01\x02"); |
| 778 | put16(&mut cd, 0x0314); |
| 779 | put16(&mut cd, version); |
| 780 | put16(&mut cd, flags); |
| 781 | put16(&mut cd, method); |
| 782 | put16(&mut cd, 0); |
| 783 | put16(&mut cd, 33); |
| 784 | put32(&mut cd, crc); |
| 785 | put32(&mut cd, packed.len() as u32); |
| 786 | put32(&mut cd, m.data.len() as u32); |
| 787 | put16(&mut cd, name.len() as u16); |
| 788 | put16(&mut cd, extra.len() as u16); |
| 789 | put16(&mut cd, 0); |
| 790 | put16(&mut cd, 0); |
| 791 | put16(&mut cd, 0); |
| 792 | put32(&mut cd, 0o100600 << 16); |
| 793 | put32(&mut cd, offset); |
| 794 | cd.extend(name); |
| 795 | cd.extend(&extra); |
| 796 | } |
| 797 | let offset = out.len(); |
| 798 | bounded_append(&mut out, &cd, limits.output)?; |
| 799 | let mut end = Vec::new(); |
| 800 | end.extend(b"PK\x05\x06"); |
| 801 | put16(&mut end, 0); |
| 802 | put16(&mut end, 0); |
| 803 | put16(&mut end, members.len() as u16); |
| 804 | put16(&mut end, members.len() as u16); |
| 805 | put32(&mut end, cd.len() as u32); |
| 806 | put32(&mut end, offset as u32); |
| 807 | put16(&mut end, 0); |
| 808 | bounded_append(&mut out, &end, limits.output)?; |
| 809 | Ok(out) |
| 810 | } |