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