team-ljyzipelo

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