team-ljyzipelo

공개
712줄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 if count == u16::MAX as u64 || central_size == u32::MAX as u64 || central == u32::MAX as u64 {
396 if central_end < 20 {
397 return Err(ErrorCode::Integrity);
398 }
399 let locator = bytes(source, central_end - 20, 20)?;
400 if &locator[..4] != b"PK\x06\x07" || u32at(&locator, 4) != 0 || u32at(&locator, 16) != 1 {
401 return Err(ErrorCode::UnsupportedFeature);
402 }
403 let offset = u64at(&locator, 8);
404 if add(offset, 56)? > central_end - 20 {
405 return Err(ErrorCode::Integrity);
406 }
407 let large = bytes(source, offset, 56)?;
408 if &large[..4] != b"PK\x06\x06"
409 || u64at(&large, 4) < 44
410 || add(offset, add(12, u64at(&large, 4))?)? != central_end - 20
411 {
412 return Err(ErrorCode::Integrity);
413 }
414 if u32at(&large, 16) != 0
415 || u32at(&large, 20) != 0
416 || u64at(&large, 24) != u64at(&large, 32)
417 {
418 return Err(ErrorCode::UnsupportedFeature);
419 }
420 let (n, size, start) = (u64at(&large, 32), u64at(&large, 40), u64at(&large, 48));
421 if (count != u16::MAX as u64 && count != n)
422 || (central_size != u32::MAX as u64 && central_size != size)
423 || (central != u32::MAX as u64 && central != start)
424 {
425 return Err(ErrorCode::Integrity);
426 }
427 (count, central_size, central, central_end) = (n, size, start, offset);
428 }
429 if count > limits.entries as u64 {
430 return Err(ErrorCode::Limit);
431 }
432 if add(central, central_size)? != central_end {
433 return Err(ErrorCode::Integrity);
434 }
435 let mut cursor = central;
436 let mut total = 0u64;
437 let mut metadata = MetadataBudget::default();
438 let mut members = Vec::new();
439 let mut packed = Vec::new();
440 let mut spans = Vec::new();
441 for id in 0..count {
442 check()?;
443 if add(cursor, 46)? > central_end {
444 return Err(ErrorCode::Integrity);
445 }
446 let h = bytes(source, cursor, 46)?;
447 if &h[..4] != b"PK\x01\x02" {
448 return Err(ErrorCode::Integrity);
449 }
450 let flags = u16at(&h, 8);
451 let method = u16at(&h, 10);
452 if flags & !0x080f != 0 || !matches!(method, 0 | 8 | 99) || u16at(&h, 34) != 0 {
453 return Err(ErrorCode::UnsupportedFeature);
454 }
455 let crc = u32at(&h, 16);
456 let (nn, ne, nc) = (
457 u16at(&h, 28) as u64,
458 u16at(&h, 30) as u64,
459 u16at(&h, 32) as u64,
460 );
461 let next = add(cursor, 46 + nn + ne + nc)?;
462 if next > central_end {
463 return Err(ErrorCode::Integrity);
464 }
465 if nn > 4096 {
466 return Err(ErrorCode::UnsafePath);
467 }
468 let raw = bytes(source, cursor + 46, nn as usize)?;
469 if flags & 0x0800 == 0 && !raw.is_ascii() {
470 return Err(ErrorCode::UnsupportedFeature);
471 }
472 let name = std::str::from_utf8(&raw).map_err(|_| ErrorCode::Integrity)?;
473 let (aes, large) = extra(&bytes(source, cursor + 46 + nn, ne as usize)?)?;
474 let central_zip64 = large.is_some();
475 let mut large = large.as_deref().unwrap_or(&[]);
476 let size = large_value(u32at(&h, 24), &mut large)?;
477 let compressed = large_value(u32at(&h, 20), &mut large)?;
478 let local = large_value(u32at(&h, 42), &mut large)?;
479 if u16at(&h, 34) == 65535 && (large.len() < 4 || u32at(large, 0) != 0) {
480 return Err(ErrorCode::UnsupportedFeature);
481 }
482 let encrypted = flags & 1 != 0;
483 if (method == 99) != aes.is_some()
484 || (method == 99 && !encrypted)
485 || (aes.is_some_and(|a| a.version == 2) && crc != 0)
486 {
487 return Err(ErrorCode::Integrity);
488 }
489 let overhead = if !encrypted {
490 0
491 } else if aes.is_some() {
492 28
493 } else {
494 12
495 };
496 let payload = compressed
497 .checked_sub(overhead)
498 .ok_or(ErrorCode::Integrity)?;
499 ratio(size, payload)?;
500 total = total
501 .checked_add(size)
502 .filter(|n| *n <= limits.output)
503 .ok_or(ErrorCode::Limit)?;
504 let mode = u32at(&h, 38) >> 16;
505 let kind = match mode & 0xf000 {
506 0xa000 => EntryKind::Link,
507 0x4000 => EntryKind::Directory,
508 0 | 0x8000 => {
509 if name.ends_with('/') {
510 EntryKind::Directory
511 } else {
512 EntryKind::File
513 }
514 }
515 _ => EntryKind::Other,
516 };
517 if kind == EntryKind::Directory && size != 0 {
518 return Err(ErrorCode::Integrity);
519 }
520 metadata.charge(name)?;
521 let name = archive::valid_name(name, kind == EntryKind::Directory)?;
522 if add(local, 30)? > central {
523 return Err(ErrorCode::Integrity);
524 }
525 let lh = bytes(source, local, 30)?;
526 if &lh[..4] != b"PK\x03\x04"
527 || u16at(&lh, 6) != flags
528 || u16at(&lh, 8) != method
529 || u16at(&lh, 10) != u16at(&h, 12)
530 {
531 return Err(ErrorCode::Integrity);
532 }
533 let (ln, le) = (u16at(&lh, 26) as u64, u16at(&lh, 28) as u64);
534 let start = add(local, 30 + ln + le)?;
535 if start > central || ln != nn {
536 return Err(ErrorCode::Integrity);
537 }
538 if bytes(source, local + 30, ln as usize)? != raw {
539 return Err(ErrorCode::Integrity);
540 }
541 let (local_aes, local_large) = extra(&bytes(source, local + 30 + ln, le as usize)?)?;
542 if local_aes != aes {
543 return Err(ErrorCode::Integrity);
544 }
545 let zip64 = central_zip64
546 || local_large.is_some()
547 || u32at(&h, 20) == u32::MAX
548 || u32at(&h, 24) == u32::MAX
549 || u32at(&lh, 18) == u32::MAX
550 || u32at(&lh, 22) == u32::MAX;
551 if flags & 8 == 0 {
552 let mut values = local_large.as_deref().unwrap_or(&[]);
553 let local_size = large_value(u32at(&lh, 22), &mut values)?;
554 let local_compressed = large_value(u32at(&lh, 18), &mut values)?;
555 if u32at(&lh, 14) != crc || local_size != size || local_compressed != compressed {
556 return Err(ErrorCode::Integrity);
557 }
558 }
559 let mut stop = add(start, compressed)?;
560 if stop > central {
561 return Err(ErrorCode::Integrity);
562 }
563 if flags & 8 != 0 {
564 let descriptor_len = if zip64 { 20 } else { 12 };
565 if add(stop, descriptor_len)? > central {
566 return Err(ErrorCode::Integrity);
567 }
568 let signature = bytes(source, stop, 4)?;
569 if signature == b"PK\x07\x08" {
570 stop = add(stop, 4)?;
571 }
572 if add(stop, descriptor_len)? > central {
573 return Err(ErrorCode::Integrity);
574 }
575 let d = bytes(source, stop, descriptor_len as usize)?;
576 let (pc, ps) = if zip64 {
577 (u64at(&d, 4), u64at(&d, 12))
578 } else {
579 (u32at(&d, 4) as u64, u32at(&d, 8) as u64)
580 };
581 if u32at(&d, 0) != crc || pc != compressed || ps != size {
582 return Err(ErrorCode::Integrity);
583 }
584 stop += descriptor_len;
585 }
586 spans.push((local, stop));
587 packed.push(Packed {
588 offset: start,
589 size: compressed,
590 method: aes.map_or(method, |a| a.method),
591 crc: if aes.is_some_and(|a| a.version == 2) {
592 None
593 } else {
594 Some(crc)
595 },
596 flags,
597 verifier: if flags & 8 != 0 {
598 (u16at(&h, 12) >> 8) as u8
599 } else {
600 (crc >> 24) as u8
601 },
602 aes: aes.is_some(),
603 });
604 members.push(Member {
605 entry: Entry {
606 entry_id: id as u32,
607 name,
608 kind,
609 size,
610 compressed_size: compressed,
611 encrypted,
612 },
613 data: Vec::new(),
614 });
615 cursor = next;
616 }
617 if cursor != central_end {
618 return Err(ErrorCode::Integrity);
619 }
620 spans.sort_unstable();
621 let mut next = 0;
622 for (a, b) in spans {
623 if a != next {
624 return Err(ErrorCode::Integrity);
625 }
626 next = b;
627 }
628 if next != central {
629 return Err(ErrorCode::Integrity);
630 }
631 archive::validate_members(&members)?;
632 let mut data = spool::temporary()?;
633 let mut offsets = Vec::new();
634 for (member, packed) in members.iter().zip(packed) {
635 check()?;
636 offsets.push(io(data.stream_position())?);
637 if !decode {
638 continue;
639 }
640 let (decoder, start, length) = if packed.flags & 1 != 0 {
641 crypto::Decryptor::prepare(
642 source,
643 packed.offset,
644 packed.size,
645 password.ok_or(ErrorCode::WrongPassword)?,
646 packed.aes,
647 packed.verifier,
648 check,
649 )?
650 } else {
651 (crypto::Decryptor::Plain, packed.offset, packed.size)
652 };
653 io(source.seek(SeekFrom::Start(start)))?;
654 let mut reader = Decoded {
655 reader: source.take(length),
656 decoder,
657 };
658 let (size, crc) = if packed.method == 8 {
659 inflate(
660 &mut reader,
661 length,
662 false,
663 member.entry.size,
664 Some(length),
665 &mut data,
666 check,
667 )?
668 } else {
669 let mut buffer = Zeroizing::new([0; CHUNK]);
670 let mut total = 0u64;
671 let mut crc = 0;
672 loop {
673 check()?;
674 let n = io(reader.read(&mut buffer[..]))?;
675 if n == 0 {
676 break;
677 }
678 total = total
679 .checked_add(n as u64)
680 .filter(|n| *n <= member.entry.size)
681 .ok_or(ErrorCode::Integrity)?;
682 crc = crc32(crc, &buffer[..n]);
683 io(data.write_all(&buffer[..n]))?;
684 }
685 (total, crc)
686 };
687 if size != member.entry.size || packed.crc.is_some_and(|c| c != crc) {
688 return Err(ErrorCode::Integrity);
689 }
690 }
691 Ok(Catalog {
692 format: Format::Zip,
693 members,
694 offsets,
695 data,
696 })
697}
698struct Decoded<R> {
699 reader: R,
700 decoder: crypto::Decryptor,
701}
702impl<R: Read> Read for Decoded<R> {
703 fn read(&mut self, output: &mut [u8]) -> std::io::Result<usize> {
704 let n = self.reader.read(output)?;
705 self.decoder.apply(&mut output[..n]);
706 Ok(n)
707 }
708}
709
710#[cfg(test)]
711#[path = "../../../tests/rust-archive-worker/streaming_bounds.rs"]
712mod bounds;