team-ljyzipelo

공개
718줄23 KB
1use crate::{
2 archive::{self, Member, MetadataBudget},
3 crypto,
4 protocol::*,
5 spool,
6};
7use std::{
8 fs::File,
9 io::{Read, Seek, SeekFrom, Write},
10};
11use zeroize::Zeroizing;
12use zlib_rs::{Inflate, InflateFlush, Status, crc32::crc32};
13
14type Result<T> = std::result::Result<T, ErrorCode>;
15const CHUNK: usize = 65536;
16pub(crate) const RATIO: u64 = 1000;
17
18pub(crate) fn ratio(output: u64, input: u64) -> Result<()> {
19 if output as u128 > input as u128 * RATIO as u128 {
20 Err(ErrorCode::Limit)
21 } else {
22 Ok(())
23 }
24}
25fn at(file: &mut File, offset: u64, bytes: &mut [u8]) -> Result<()> {
26 file.seek(SeekFrom::Start(offset))
27 .map_err(|_| ErrorCode::Io)?;
28 file.read_exact(bytes).map_err(|_| ErrorCode::Integrity)
29}
30fn bytes(file: &mut File, offset: u64, size: usize) -> Result<Vec<u8>> {
31 let mut result = vec![0; size];
32 at(file, offset, &mut result)?;
33 Ok(result)
34}
35fn u16at(b: &[u8], at: usize) -> u16 {
36 u16::from_le_bytes(b[at..at + 2].try_into().unwrap())
37}
38fn u32at(b: &[u8], at: usize) -> u32 {
39 u32::from_le_bytes(b[at..at + 4].try_into().unwrap())
40}
41fn u64at(b: &[u8], at: usize) -> u64 {
42 u64::from_le_bytes(b[at..at + 8].try_into().unwrap())
43}
44fn add(a: u64, b: u64) -> Result<u64> {
45 a.checked_add(b).ok_or(ErrorCode::Integrity)
46}
47fn io<T>(v: std::io::Result<T>) -> Result<T> {
48 v.map_err(|_| ErrorCode::Io)
49}
50
51pub(crate) struct Catalog {
52 pub format: Format,
53 pub members: Vec<Member>,
54 pub offsets: Vec<u64>,
55 pub data: File,
56}
57impl Catalog {
58 pub fn open(
59 source: &mut File,
60 len: u64,
61 limits: Limits,
62 decode: bool,
63 password: Option<&[u8]>,
64 check: &mut impl FnMut() -> Result<()>,
65 ) -> Result<Self> {
66 let mut magic = [0; 6];
67 let n = len.min(6) as usize;
68 at(source, 0, &mut magic[..n])?;
69 if magic.starts_with(b"7z\xbc\xaf\x27\x1c") {
70 let bounded = limits.legacy();
71 if len > bounded.input {
72 return Err(ErrorCode::Limit);
73 }
74 let input = bytes(source, 0, len as usize)?;
75 let catalog = archive::parse_with_password(&input, bounded, decode, password, check)?;
76 let mut data = spool::temporary()?;
77 let mut members = catalog.members;
78 let mut offsets = Vec::new();
79 for m in &mut members {
80 offsets.push(io(data.stream_position())?);
81 io(data.write_all(&m.data))?;
82 m.data.clear();
83 m.data.shrink_to_fit();
84 }
85 return Ok(Self {
86 format: Format::SevenZip,
87 members,
88 offsets,
89 data,
90 });
91 }
92 if magic.starts_with(b"PK\x03\x04")
93 || magic.starts_with(b"PK\x05\x06")
94 || magic.starts_with(b"PK\x06\x06")
95 {
96 return zip(source, len, limits, decode, password, check);
97 }
98 if magic.starts_with(&[31, 139]) {
99 let mut data = spool::temporary()?;
100 io(source.rewind())?;
101 let expanded = inflate(
102 source,
103 len,
104 true,
105 limits.output,
106 Some(len),
107 &mut data,
108 check,
109 )?
110 .0;
111 let mut header = [0; 512];
112 if expanded >= 512 {
113 at(&mut data, 0, &mut header)?;
114 if matches!(&header[257..263], b"ustar\0" | b"ustar ") {
115 return tar(data, expanded, limits, Format::TarGzip, check);
116 }
117 }
118 return Ok(Self {
119 format: Format::Gzip,
120 members: vec![Member {
121 entry: Entry {
122 entry_id: 0,
123 name: "GZip stream".to_owned(),
124 kind: EntryKind::File,
125 size: expanded,
126 compressed_size: len,
127 encrypted: false,
128 },
129 data: Vec::new(),
130 }],
131 offsets: vec![0],
132 data,
133 });
134 }
135 if len >= 512 {
136 return tar(io(source.try_clone())?, len, limits, Format::Tar, check);
137 }
138 Err(ErrorCode::UnsupportedFormat)
139 }
140}
141
142fn tar(
143 mut data: File,
144 len: u64,
145 limits: Limits,
146 format: Format,
147 check: &mut impl FnMut() -> Result<()>,
148) -> Result<Catalog> {
149 let mut cursor = 0u64;
150 let mut total = 0u64;
151 let mut members = Vec::new();
152 let mut offsets = Vec::new();
153 let mut metadata = MetadataBudget::default();
154 loop {
155 check()?;
156 let mut header = [0; 512];
157 if add(cursor, 512)? > len {
158 return Err(ErrorCode::Integrity);
159 }
160 at(&mut data, cursor, &mut header)?;
161 if header.iter().all(|b| *b == 0) {
162 if add(cursor, 1024)? > len || len % 512 != 0 {
163 return Err(ErrorCode::Integrity);
164 }
165 let mut buffer = Zeroizing::new([0; CHUNK]);
166 let mut remaining = len - cursor - 512;
167 while remaining != 0 {
168 check()?;
169 let n = remaining.min(CHUNK as u64) as usize;
170 io(data.read_exact(&mut buffer[..n]))?;
171 if buffer[..n].iter().any(|b| *b != 0) {
172 return Err(ErrorCode::Integrity);
173 }
174 remaining -= n as u64;
175 }
176 break;
177 }
178 if members.len() >= limits.entries as usize {
179 return Err(ErrorCode::Limit);
180 }
181 let sum = header
182 .iter()
183 .enumerate()
184 .map(|(i, b)| {
185 if (148..156).contains(&i) {
186 32
187 } else {
188 *b as u64
189 }
190 })
191 .sum::<u64>();
192 if sum != archive::octal(&header[148..156])? {
193 return Err(ErrorCode::Integrity);
194 }
195 let mut name = archive::tar_string(&header[..100])?;
196 if matches!(&header[257..263], b"ustar\0" | b"ustar ") {
197 let prefix = archive::tar_string(&header[345..500])?;
198 if !prefix.is_empty() {
199 name = format!("{prefix}/{name}");
200 }
201 } else if header[257..263].iter().any(|b| *b != 0) {
202 return Err(ErrorCode::UnsupportedFeature);
203 }
204 let kind = match header[156] {
205 0 | b'0' => EntryKind::File,
206 b'5' => EntryKind::Directory,
207 b'1' | b'2' => EntryKind::Link,
208 b'x' | b'g' | b'L' | b'K' => return Err(ErrorCode::UnsupportedFeature),
209 _ => EntryKind::Other,
210 };
211 let size = archive::octal(&header[124..136])?;
212 if kind != EntryKind::File && size != 0 {
213 return Err(ErrorCode::Integrity);
214 }
215 total = total
216 .checked_add(size)
217 .filter(|n| *n <= limits.output)
218 .ok_or(ErrorCode::Limit)?;
219 let start = add(cursor, 512)?;
220 cursor = add(
221 start,
222 size.checked_add(511).ok_or(ErrorCode::Integrity)? / 512 * 512,
223 )?;
224 if cursor > len {
225 return Err(ErrorCode::Integrity);
226 }
227 metadata.charge(&name)?;
228 let name = archive::valid_name(&name, kind == EntryKind::Directory)?;
229 offsets.push(start);
230 members.push(Member {
231 entry: Entry {
232 entry_id: members.len() as u32,
233 name,
234 kind,
235 size,
236 compressed_size: size,
237 encrypted: false,
238 },
239 data: Vec::new(),
240 });
241 }
242 archive::validate_members(&members)?;
243 Ok(Catalog {
244 format,
245 members,
246 offsets,
247 data,
248 })
249}
250
251// 각 ZIP 항목과 각 GZip 멤버의 실제 해제량에 압축비와 누적 총량을 적용함.
252fn inflate(
253 input: &mut impl Read,
254 length: u64,
255 gzip: bool,
256 limit: u64,
257 ratio_base: Option<u64>,
258 output: &mut File,
259 check: &mut impl FnMut() -> Result<()>,
260) -> Result<(u64, u32)> {
261 let mut remaining = length;
262 let mut buffer = Zeroizing::new([0; CHUNK]);
263 let mut plain = Zeroizing::new([0; CHUNK]);
264 let mut have = 0;
265 let mut used = 0;
266 let mut total = 0u64;
267 let mut crc = 0;
268 loop {
269 let mut stream = Inflate::new(gzip, if gzip { 31 } else { 15 });
270 loop {
271 check()?;
272 if used == have && remaining != 0 {
273 have = input
274 .read(&mut buffer[..remaining.min(CHUNK as u64) as usize])
275 .map_err(|_| ErrorCode::Io)?;
276 if have == 0 {
277 return Err(ErrorCode::Integrity);
278 }
279 remaining -= have as u64;
280 used = 0;
281 }
282 let a = stream.total_in();
283 let b = stream.total_out();
284 let status = stream
285 .decompress(&buffer[used..have], &mut plain[..], InflateFlush::NoFlush)
286 .map_err(|_| ErrorCode::Integrity)?;
287 used += (stream.total_in() - a) as usize;
288 let n = (stream.total_out() - b) as usize;
289 total = total
290 .checked_add(n as u64)
291 .filter(|n| *n <= limit)
292 .ok_or(ErrorCode::Limit)?;
293 if let Some(base) = ratio_base {
294 ratio(total, base)?;
295 }
296 crc = crc32(crc, &plain[..n]);
297 io(output.write_all(&plain[..n]))?;
298 if status == Status::StreamEnd {
299 if gzip {
300 ratio(stream.total_out(), stream.total_in())?;
301 }
302 break;
303 }
304 if a == stream.total_in() && b == stream.total_out() {
305 return Err(ErrorCode::Integrity);
306 }
307 }
308 if remaining == 0 && used == have {
309 break;
310 }
311 if !gzip {
312 return Err(ErrorCode::Integrity);
313 }
314 }
315 Ok((total, crc))
316}
317
318struct Packed {
319 offset: u64,
320 size: u64,
321 method: u16,
322 crc: Option<u32>,
323 flags: u16,
324 verifier: u8,
325 aes: bool,
326}
327
328fn extra(bytes: &[u8]) -> Result<(Option<archive::AesExtra>, Option<Vec<u8>>)> {
329 let mut at = 0;
330 let mut aes = Vec::new();
331 let mut large = None;
332 while at < bytes.len() {
333 if bytes.len() - at < 4 {
334 return Err(ErrorCode::Integrity);
335 }
336 let tag = u16at(bytes, at);
337 let len = u16at(bytes, at + 2) as usize;
338 let end = at + 4 + len;
339 if end > bytes.len() {
340 return Err(ErrorCode::Integrity);
341 }
342 if tag == 1 {
343 if large.is_some() {
344 return Err(ErrorCode::Integrity);
345 }
346 large = Some(bytes[at + 4..end].to_vec());
347 } else {
348 aes.extend_from_slice(&bytes[at..end]);
349 }
350 at = end;
351 }
352 Ok((archive::aes_extra(&aes)?, large))
353}
354fn large_value(value: u32, extra: &mut &[u8]) -> Result<u64> {
355 if value != u32::MAX {
356 return Ok(value as u64);
357 }
358 if extra.len() < 8 {
359 return Err(ErrorCode::Integrity);
360 }
361 let result = u64at(extra, 0);
362 *extra = &extra[8..];
363 Ok(result)
364}
365fn zip(
366 source: &mut File,
367 len: u64,
368 limits: Limits,
369 decode: bool,
370 password: Option<&[u8]>,
371 check: &mut impl FnMut() -> Result<()>,
372) -> Result<Catalog> {
373 if len < 22 {
374 return Err(ErrorCode::Integrity);
375 }
376 let tail_at = len.saturating_sub(65557);
377 let tail = bytes(source, tail_at, (len - tail_at) as usize)?;
378 let end = (0..=tail.len() - 22)
379 .rev()
380 .find(|&i| {
381 &tail[i..i + 4] == b"PK\x05\x06" && i + 22 + u16at(&tail, i + 20) as usize == tail.len()
382 })
383 .ok_or(ErrorCode::Integrity)?;
384 let h = &tail[end..];
385 if u16at(h, 4) != 0 || u16at(h, 6) != 0 {
386 return Err(ErrorCode::UnsupportedFeature);
387 }
388 let mut count = u16at(h, 10) as u64;
389 if count != u16at(h, 8) as u64 {
390 return Err(ErrorCode::UnsupportedFeature);
391 }
392 let mut central_size = u32at(h, 12) as u64;
393 let mut central = u32at(h, 16) as u64;
394 let mut central_end = tail_at + end as u64;
395 let required_zip64 =
396 count == u16::MAX as u64 || central_size == u32::MAX as u64 || central == u32::MAX as u64;
397 let locator = if central_end >= 20 {
398 bytes(source, central_end - 20, 20)?
399 } else {
400 Vec::new()
401 };
402 // 중앙 디렉터리 주석의 동일 서명을 locator로 오인하지 않음
403 let has_locator =
404 locator.starts_with(b"PK\x06\x07") && add(central, central_size)? != central_end;
405 if required_zip64 || has_locator {
406 if locator.len() != 20 {
407 return Err(ErrorCode::Integrity);
408 }
409 if &locator[..4] != b"PK\x06\x07" || u32at(&locator, 4) != 0 || u32at(&locator, 16) != 1 {
410 return Err(ErrorCode::UnsupportedFeature);
411 }
412 let offset = u64at(&locator, 8);
413 if add(offset, 56)? > central_end - 20 {
414 return Err(ErrorCode::Integrity);
415 }
416 let large = bytes(source, offset, 56)?;
417 if &large[..4] != b"PK\x06\x06"
418 || u64at(&large, 4) < 44
419 || add(offset, add(12, u64at(&large, 4))?)? != central_end - 20
420 {
421 return Err(ErrorCode::Integrity);
422 }
423 if u32at(&large, 16) != 0
424 || u32at(&large, 20) != 0
425 || u64at(&large, 24) != u64at(&large, 32)
426 {
427 return Err(ErrorCode::UnsupportedFeature);
428 }
429 let (n, size, start) = (u64at(&large, 32), u64at(&large, 40), u64at(&large, 48));
430 if (count != u16::MAX as u64 && count != n)
431 || (central_size != u32::MAX as u64 && central_size != size)
432 || (central != u32::MAX as u64 && central != start)
433 {
434 return Err(ErrorCode::Integrity);
435 }
436 (count, central_size, central, central_end) = (n, size, start, offset);
437 }
438 if count > limits.entries as u64 {
439 return Err(ErrorCode::Limit);
440 }
441 if add(central, central_size)? != central_end {
442 return Err(ErrorCode::Integrity);
443 }
444 let mut cursor = central;
445 let mut total = 0u64;
446 let mut metadata = MetadataBudget::default();
447 let mut members = Vec::new();
448 let mut packed = Vec::new();
449 let mut spans = Vec::new();
450 for id in 0..count {
451 check()?;
452 if add(cursor, 46)? > central_end {
453 return Err(ErrorCode::Integrity);
454 }
455 let h = bytes(source, cursor, 46)?;
456 if &h[..4] != b"PK\x01\x02" {
457 return Err(ErrorCode::Integrity);
458 }
459 let flags = u16at(&h, 8);
460 let method = u16at(&h, 10);
461 if flags & !0x080f != 0 || !matches!(method, 0 | 8 | 99) || u16at(&h, 34) != 0 {
462 return Err(ErrorCode::UnsupportedFeature);
463 }
464 let crc = u32at(&h, 16);
465 let (nn, ne, nc) = (
466 u16at(&h, 28) as u64,
467 u16at(&h, 30) as u64,
468 u16at(&h, 32) as u64,
469 );
470 let next = add(cursor, 46 + nn + ne + nc)?;
471 if next > central_end {
472 return Err(ErrorCode::Integrity);
473 }
474 if nn > 4096 {
475 return Err(ErrorCode::UnsafePath);
476 }
477 let raw = bytes(source, cursor + 46, nn as usize)?;
478 if flags & 0x0800 == 0 && !raw.is_ascii() {
479 return Err(ErrorCode::UnsupportedFeature);
480 }
481 let name = std::str::from_utf8(&raw).map_err(|_| ErrorCode::Integrity)?;
482 let (aes, large) = extra(&bytes(source, cursor + 46 + nn, ne as usize)?)?;
483 let mut large = large.as_deref().unwrap_or(&[]);
484 let size = large_value(u32at(&h, 24), &mut large)?;
485 let compressed = large_value(u32at(&h, 20), &mut large)?;
486 let local = large_value(u32at(&h, 42), &mut large)?;
487 if u16at(&h, 34) == 65535 && (large.len() < 4 || u32at(large, 0) != 0) {
488 return Err(ErrorCode::UnsupportedFeature);
489 }
490 let encrypted = flags & 1 != 0;
491 if (method == 99) != aes.is_some()
492 || (method == 99 && !encrypted)
493 || (aes.is_some_and(|a| a.version == 2) && crc != 0)
494 {
495 return Err(ErrorCode::Integrity);
496 }
497 let overhead = if !encrypted {
498 0
499 } else if aes.is_some() {
500 28
501 } else {
502 12
503 };
504 let payload = compressed
505 .checked_sub(overhead)
506 .ok_or(ErrorCode::Integrity)?;
507 ratio(size, payload)?;
508 total = total
509 .checked_add(size)
510 .filter(|n| *n <= limits.output)
511 .ok_or(ErrorCode::Limit)?;
512 let mode = u32at(&h, 38) >> 16;
513 let kind = match mode & 0xf000 {
514 0xa000 => EntryKind::Link,
515 0x4000 => EntryKind::Directory,
516 0 | 0x8000 => {
517 if name.ends_with('/') {
518 EntryKind::Directory
519 } else {
520 EntryKind::File
521 }
522 }
523 _ => EntryKind::Other,
524 };
525 if kind == EntryKind::Directory && size != 0 {
526 return Err(ErrorCode::Integrity);
527 }
528 metadata.charge(name)?;
529 let name = archive::valid_name(name, kind == EntryKind::Directory)?;
530 if add(local, 30)? > central {
531 return Err(ErrorCode::Integrity);
532 }
533 let lh = bytes(source, local, 30)?;
534 if &lh[..4] != b"PK\x03\x04"
535 || u16at(&lh, 6) != flags
536 || u16at(&lh, 8) != method
537 || u16at(&lh, 10) != u16at(&h, 12)
538 {
539 return Err(ErrorCode::Integrity);
540 }
541 let (ln, le) = (u16at(&lh, 26) as u64, u16at(&lh, 28) as u64);
542 let start = add(local, 30 + ln + le)?;
543 if start > central || ln != nn {
544 return Err(ErrorCode::Integrity);
545 }
546 if bytes(source, local + 30, ln as usize)? != raw {
547 return Err(ErrorCode::Integrity);
548 }
549 let (local_aes, local_large) = extra(&bytes(source, local + 30 + ln, le as usize)?)?;
550 if local_aes != aes {
551 return Err(ErrorCode::Integrity);
552 }
553 let size_zip64 = u32at(&h, 20) == u32::MAX
554 || u32at(&h, 24) == u32::MAX
555 || u32at(&lh, 18) == u32::MAX
556 || u32at(&lh, 22) == u32::MAX;
557 if flags & 8 == 0 {
558 let mut values = local_large.as_deref().unwrap_or(&[]);
559 let local_size = large_value(u32at(&lh, 22), &mut values)?;
560 let local_compressed = large_value(u32at(&lh, 18), &mut values)?;
561 if u32at(&lh, 14) != crc || local_size != size || local_compressed != compressed {
562 return Err(ErrorCode::Integrity);
563 }
564 }
565 let mut stop = add(start, compressed)?;
566 if stop > central {
567 return Err(ErrorCode::Integrity);
568 }
569 if flags & 8 != 0 {
570 let descriptor_len = if size_zip64 { 20 } else { 12 };
571 if add(stop, descriptor_len)? > central {
572 return Err(ErrorCode::Integrity);
573 }
574 let signature = bytes(source, stop, 4)?;
575 if signature == b"PK\x07\x08" {
576 stop = add(stop, 4)?;
577 }
578 if add(stop, descriptor_len)? > central {
579 return Err(ErrorCode::Integrity);
580 }
581 let d = bytes(source, stop, descriptor_len as usize)?;
582 let (pc, ps) = if size_zip64 {
583 (u64at(&d, 4), u64at(&d, 12))
584 } else {
585 (u32at(&d, 4) as u64, u32at(&d, 8) as u64)
586 };
587 if u32at(&d, 0) != crc || pc != compressed || ps != size {
588 return Err(ErrorCode::Integrity);
589 }
590 stop += descriptor_len;
591 }
592 spans.push((local, stop));
593 packed.push(Packed {
594 offset: start,
595 size: compressed,
596 method: aes.map_or(method, |a| a.method),
597 crc: if aes.is_some_and(|a| a.version == 2) {
598 None
599 } else {
600 Some(crc)
601 },
602 flags,
603 verifier: if flags & 8 != 0 {
604 (u16at(&h, 12) >> 8) as u8
605 } else {
606 (crc >> 24) as u8
607 },
608 aes: aes.is_some(),
609 });
610 members.push(Member {
611 entry: Entry {
612 entry_id: id as u32,
613 name,
614 kind,
615 size,
616 compressed_size: compressed,
617 encrypted,
618 },
619 data: Vec::new(),
620 });
621 cursor = next;
622 }
623 if cursor != central_end {
624 return Err(ErrorCode::Integrity);
625 }
626 spans.sort_unstable();
627 let mut next = 0;
628 for (a, b) in spans {
629 if a != next {
630 return Err(ErrorCode::Integrity);
631 }
632 next = b;
633 }
634 if next != central {
635 return Err(ErrorCode::Integrity);
636 }
637 archive::validate_members(&members)?;
638 let mut data = spool::temporary()?;
639 let mut offsets = Vec::new();
640 for (member, packed) in members.iter().zip(packed) {
641 check()?;
642 offsets.push(io(data.stream_position())?);
643 if !decode {
644 continue;
645 }
646 let (decoder, start, length) = if packed.flags & 1 != 0 {
647 crypto::Decryptor::prepare(
648 source,
649 packed.offset,
650 packed.size,
651 password.ok_or(ErrorCode::WrongPassword)?,
652 packed.aes,
653 packed.verifier,
654 check,
655 )?
656 } else {
657 (crypto::Decryptor::Plain, packed.offset, packed.size)
658 };
659 io(source.seek(SeekFrom::Start(start)))?;
660 let mut reader = Decoded {
661 reader: source.take(length),
662 decoder,
663 };
664 let (size, crc) = if packed.method == 8 {
665 inflate(
666 &mut reader,
667 length,
668 false,
669 member.entry.size,
670 Some(length),
671 &mut data,
672 check,
673 )?
674 } else {
675 let mut buffer = Zeroizing::new([0; CHUNK]);
676 let mut total = 0u64;
677 let mut crc = 0;
678 loop {
679 check()?;
680 let n = io(reader.read(&mut buffer[..]))?;
681 if n == 0 {
682 break;
683 }
684 total = total
685 .checked_add(n as u64)
686 .filter(|n| *n <= member.entry.size)
687 .ok_or(ErrorCode::Integrity)?;
688 crc = crc32(crc, &buffer[..n]);
689 io(data.write_all(&buffer[..n]))?;
690 }
691 (total, crc)
692 };
693 if size != member.entry.size || packed.crc.is_some_and(|c| c != crc) {
694 return Err(ErrorCode::Integrity);
695 }
696 }
697 Ok(Catalog {
698 format: Format::Zip,
699 members,
700 offsets,
701 data,
702 })
703}
704struct Decoded<R> {
705 reader: R,
706 decoder: crypto::Decryptor,
707}
708impl<R: Read> Read for Decoded<R> {
709 fn read(&mut self, output: &mut [u8]) -> std::io::Result<usize> {
710 let n = self.reader.read(output)?;
711 self.decoder.apply(&mut output[..n]);
712 Ok(n)
713 }
714}
715
716#[cfg(test)]
717#[path = "../../../tests/rust-archive-worker/streaming_bounds.rs"]
718mod bounds;