team-ljyzipelo

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