team-ljyzipelo

공개
592줄19 KB
1use crate::protocol::*;
2use std::collections::BTreeMap;
3use zlib_rs::{Deflate, DeflateFlush, Inflate, InflateFlush, Status, crc32::crc32};
4
5type Result<T> = std::result::Result<T, ErrorCode>;
6#[derive(Debug)]
7pub struct Member {
8 pub entry: Entry,
9 pub data: Vec<u8>,
10}
11pub struct Catalog {
12 pub format: Format,
13 pub members: Vec<Member>,
14}
15fn part(b: &[u8], at: usize, n: usize) -> Result<&[u8]> {
16 b.get(at..at.checked_add(n).ok_or(ErrorCode::Integrity)?)
17 .ok_or(ErrorCode::Integrity)
18}
19fn u16at(b: &[u8], at: usize) -> Result<u16> {
20 Ok(u16::from_le_bytes(part(b, at, 2)?.try_into().unwrap()))
21}
22fn u32at(b: &[u8], at: usize) -> Result<u32> {
23 Ok(u32::from_le_bytes(part(b, at, 4)?.try_into().unwrap()))
24}
25
26pub fn valid_name(name: &str, directory: bool) -> Result<String> {
27 let name = if directory {
28 name.strip_suffix('/').unwrap_or(name)
29 } else {
30 name
31 };
32 if name.is_empty()
33 || name.len() > 4096
34 || name.starts_with('/')
35 || name.contains('\\')
36 || name
37 .chars()
38 .any(|c| c.is_control() || matches!(c, ':' | '*' | '?' | '"' | '<' | '>' | '|'))
39 {
40 return Err(ErrorCode::UnsafePath);
41 }
42 for component in name.split('/') {
43 if component.is_empty()
44 || matches!(component, "." | "..")
45 || component.ends_with(['.', ' '])
46 || component.len() > 255
47 {
48 return Err(ErrorCode::UnsafePath);
49 }
50 let stem = component.split('.').next().unwrap().to_ascii_uppercase();
51 if matches!(
52 stem.as_str(),
53 "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$"
54 ) || ["COM", "LPT"].iter().any(|p| {
55 stem.strip_prefix(p).is_some_and(|n| {
56 matches!(
57 n,
58 "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"
59 )
60 })
61 }) {
62 return Err(ErrorCode::UnsafePath);
63 }
64 }
65 Ok(name.to_owned())
66}
67pub fn validate_members(members: &[Member]) -> Result<()> {
68 let mut names = BTreeMap::<String, bool>::new();
69 for member in members {
70 let directory = member.entry.kind == EntryKind::Directory;
71 let name = valid_name(&member.entry.name, directory)?.to_lowercase();
72 if names.insert(name, directory).is_some() {
73 return Err(ErrorCode::Conflict);
74 }
75 }
76 for name in names.keys() {
77 let mut parent = name.as_str();
78 while let Some((p, _)) = parent.rsplit_once('/') {
79 if names.get(p) == Some(&false) {
80 return Err(ErrorCode::Conflict);
81 }
82 parent = p;
83 }
84 }
85 Ok(())
86}
87fn bounded_append(output: &mut Vec<u8>, data: &[u8], limit: u64) -> Result<()> {
88 if (output.len() as u64)
89 .checked_add(data.len() as u64)
90 .is_none_or(|n| n > limit)
91 {
92 return Err(ErrorCode::Limit);
93 }
94 output
95 .try_reserve(data.len())
96 .map_err(|_| ErrorCode::Limit)?;
97 output.extend_from_slice(data);
98 Ok(())
99}
100fn inflate(
101 input: &[u8],
102 gzip: bool,
103 limit: u64,
104 check: &mut impl FnMut() -> Result<()>,
105) -> Result<(Vec<u8>, usize)> {
106 let mut stream = Inflate::new(gzip, if gzip { 31 } else { 15 });
107 let mut out = Vec::new();
108 let mut buffer = [0; 65536];
109 loop {
110 check()?;
111 let before_in = stream.total_in();
112 let before_out = stream.total_out();
113 let status = stream
114 .decompress(
115 &input[before_in as usize..],
116 &mut buffer,
117 InflateFlush::NoFlush,
118 )
119 .map_err(|_| ErrorCode::Integrity)?;
120 let written = (stream.total_out() - before_out) as usize;
121 bounded_append(&mut out, &buffer[..written], limit)?;
122 if status == Status::StreamEnd {
123 return Ok((out, stream.total_in() as usize));
124 }
125 if stream.total_in() == before_in && stream.total_out() == before_out {
126 return Err(ErrorCode::Integrity);
127 }
128 }
129}
130fn gzip(input: &[u8], limits: Limits, check: &mut impl FnMut() -> Result<()>) -> Result<Vec<u8>> {
131 let mut at = 0;
132 let mut result = Vec::new();
133 while at < input.len() {
134 if !input[at..].starts_with(&[31, 139, 8]) {
135 return Err(ErrorCode::Integrity);
136 }
137 let (out, used) = inflate(
138 &input[at..],
139 true,
140 limits.output - result.len() as u64,
141 check,
142 )?;
143 if used == 0 {
144 return Err(ErrorCode::Integrity);
145 }
146 bounded_append(&mut result, &out, limits.output)?;
147 at += used;
148 }
149 Ok(result)
150}
151fn tar_string(b: &[u8]) -> Result<String> {
152 let n = b.iter().position(|v| *v == 0).unwrap_or(b.len());
153 if b[n..].iter().any(|v| *v != 0) {
154 return Err(ErrorCode::Integrity);
155 }
156 std::str::from_utf8(&b[..n])
157 .map(str::to_owned)
158 .map_err(|_| ErrorCode::UnsupportedFeature)
159}
160fn octal(b: &[u8]) -> Result<u64> {
161 if b.first().is_some_and(|x| x & 128 != 0) {
162 return Err(ErrorCode::UnsupportedFeature);
163 }
164 let text = std::str::from_utf8(b)
165 .map_err(|_| ErrorCode::Integrity)?
166 .trim_matches(['\0', ' ']);
167 if text.is_empty() {
168 return Ok(0);
169 }
170 u64::from_str_radix(text, 8).map_err(|_| ErrorCode::Integrity)
171}
172fn tar(
173 input: &[u8],
174 limits: Limits,
175 decode: bool,
176 check: &mut impl FnMut() -> Result<()>,
177) -> Result<Vec<Member>> {
178 let mut at = 0;
179 let mut members = Vec::new();
180 let mut total = 0u64;
181 loop {
182 check()?;
183 let header = part(input, at, 512)?;
184 if header.iter().all(|b| *b == 0) {
185 if part(input, at + 512, 512)?.iter().any(|b| *b != 0)
186 || input[at..].iter().any(|b| *b != 0)
187 || input.len() % 512 != 0
188 {
189 return Err(ErrorCode::Integrity);
190 }
191 break;
192 }
193 if members.len() >= limits.entries as usize {
194 return Err(ErrorCode::Limit);
195 }
196 let expected = octal(&header[148..156])?;
197 let checksum = header
198 .iter()
199 .enumerate()
200 .map(|(i, b)| {
201 if (148..156).contains(&i) {
202 32u64
203 } else {
204 *b as u64
205 }
206 })
207 .sum::<u64>();
208 if checksum != expected {
209 return Err(ErrorCode::Integrity);
210 }
211 let mut name = tar_string(&header[..100])?;
212 if &header[257..263] == b"ustar\0" || &header[257..263] == b"ustar " {
213 let prefix = tar_string(&header[345..500])?;
214 if !prefix.is_empty() {
215 name = format!("{prefix}/{name}");
216 }
217 } else if header[257..263].iter().any(|b| *b != 0) {
218 return Err(ErrorCode::UnsupportedFeature);
219 }
220 let kind = match header[156] {
221 0 | b'0' => EntryKind::File,
222 b'5' => EntryKind::Directory,
223 b'1' | b'2' => EntryKind::Link,
224 b'x' | b'g' | b'L' | b'K' => return Err(ErrorCode::UnsupportedFeature),
225 _ => EntryKind::Other,
226 };
227 let size = octal(&header[124..136])?;
228 if kind != EntryKind::File && size != 0 {
229 return Err(ErrorCode::Integrity);
230 }
231 total = total
232 .checked_add(size)
233 .filter(|n| *n <= limits.output)
234 .ok_or(ErrorCode::Limit)?;
235 let size = usize::try_from(size).map_err(|_| ErrorCode::Limit)?;
236 let bytes = part(input, at + 512, size)?;
237 let name = valid_name(&name, kind == EntryKind::Directory)?;
238 let data = if decode { bytes.to_vec() } else { Vec::new() };
239 members.push(Member {
240 entry: Entry {
241 entry_id: members.len() as u32,
242 name,
243 kind,
244 size: size as u64,
245 compressed_size: size as u64,
246 encrypted: false,
247 },
248 data,
249 });
250 at = at
251 .checked_add(512)
252 .and_then(|n| n.checked_add(size.div_ceil(512) * 512))
253 .ok_or(ErrorCode::Integrity)?;
254 }
255 validate_members(&members)?;
256 Ok(members)
257}
258fn zip(
259 input: &[u8],
260 limits: Limits,
261 decode: bool,
262 check: &mut impl FnMut() -> Result<()>,
263) -> Result<Vec<Member>> {
264 if input.len() < 22 {
265 return Err(ErrorCode::Integrity);
266 }
267 let end = (input.len().saturating_sub(65557)..=input.len() - 22)
268 .rev()
269 .find(|&i| {
270 input.get(i..i + 4) == Some(b"PK\x05\x06")
271 && u16at(input, i + 20)
272 .ok()
273 .is_some_and(|n| i + 22 + n as usize == input.len())
274 })
275 .ok_or(ErrorCode::Integrity)?;
276 let count = u16at(input, end + 10)? as usize;
277 if u16at(input, end + 4)? != 0
278 || u16at(input, end + 6)? != 0
279 || count != u16at(input, end + 8)? as usize
280 {
281 return Err(ErrorCode::UnsupportedFeature);
282 }
283 if count == 65535 || u32at(input, end + 12)? == u32::MAX || u32at(input, end + 16)? == u32::MAX
284 {
285 return Err(ErrorCode::UnsupportedFeature);
286 }
287 if count > limits.entries as usize {
288 return Err(ErrorCode::Limit);
289 }
290 let central = u32at(input, end + 16)? as usize;
291 if central.checked_add(u32at(input, end + 12)? as usize) != Some(end) {
292 return Err(ErrorCode::Integrity);
293 }
294 let mut at = central;
295 let mut members = Vec::new();
296 let mut spans = Vec::new();
297 let mut total = 0u64;
298 for id in 0..count {
299 check()?;
300 let h = part(input, at, 46)?;
301 if &h[..4] != b"PK\x01\x02" {
302 return Err(ErrorCode::Integrity);
303 }
304 let flags = u16at(h, 8)?;
305 let method = u16at(h, 10)?;
306 if flags & !0x080f != 0 || !matches!(method, 0 | 8) || u16at(h, 34)? != 0 {
307 return Err(ErrorCode::UnsupportedFeature);
308 }
309 let crc = u32at(h, 16)?;
310 let compressed = u32at(h, 20)? as usize;
311 let size = u32at(h, 24)? as usize;
312 if compressed == u32::MAX as usize || size == u32::MAX as usize {
313 return Err(ErrorCode::UnsupportedFeature);
314 }
315 total = total
316 .checked_add(size as u64)
317 .filter(|n| *n <= limits.output)
318 .ok_or(ErrorCode::Limit)?;
319 let name_len = u16at(h, 28)? as usize;
320 let extra_len = u16at(h, 30)? as usize;
321 let comment_len = u16at(h, 32)? as usize;
322 let raw = part(input, at + 46, name_len)?;
323 if flags & 0x0800 == 0 && !raw.is_ascii() {
324 return Err(ErrorCode::UnsupportedFeature);
325 }
326 let name = std::str::from_utf8(raw).map_err(|_| ErrorCode::Integrity)?;
327 let mode = u32at(h, 38)? >> 16;
328 let kind = match mode & 0xf000 {
329 0xa000 => EntryKind::Link,
330 0x4000 => EntryKind::Directory,
331 0 | 0x8000 => {
332 if name.ends_with('/') {
333 EntryKind::Directory
334 } else {
335 EntryKind::File
336 }
337 }
338 _ => EntryKind::Other,
339 };
340 let name = valid_name(name, kind == EntryKind::Directory)?;
341 let local = u32at(h, 42)? as usize;
342 let lh = part(input, local, 30)?;
343 if &lh[..4] != b"PK\x03\x04" || u16at(lh, 6)? != flags || u16at(lh, 8)? != method {
344 return Err(ErrorCode::Integrity);
345 }
346 let ln = u16at(lh, 26)? as usize;
347 let le = u16at(lh, 28)? as usize;
348 if part(input, local + 30, ln)? != raw {
349 return Err(ErrorCode::Integrity);
350 }
351 if flags & 8 == 0
352 && (u32at(lh, 14)? != crc
353 || u32at(lh, 18)? as usize != compressed
354 || u32at(lh, 22)? as usize != size)
355 {
356 return Err(ErrorCode::Integrity);
357 }
358 let start = local
359 .checked_add(30 + ln + le)
360 .ok_or(ErrorCode::Integrity)?;
361 let packed = part(input, start, compressed)?;
362 let mut stop = start + compressed;
363 if flags & 8 != 0 {
364 if input.get(stop..stop + 4) == Some(b"PK\x07\x08") {
365 stop += 4;
366 }
367 if u32at(input, stop)? != crc
368 || u32at(input, stop + 4)? as usize != compressed
369 || u32at(input, stop + 8)? as usize != size
370 {
371 return Err(ErrorCode::Integrity);
372 }
373 stop += 12;
374 }
375 if stop > central {
376 return Err(ErrorCode::Integrity);
377 }
378 spans.push((local, stop));
379 let encrypted = flags & 1 != 0;
380 let data = if decode && !encrypted {
381 let bytes = if method == 0 {
382 if compressed != size {
383 return Err(ErrorCode::Integrity);
384 }
385 packed.to_vec()
386 } else {
387 let (out, used) = inflate(packed, false, size as u64, check)?;
388 if used != compressed {
389 return Err(ErrorCode::Integrity);
390 }
391 out
392 };
393 if bytes.len() != size || crc32(0, &bytes) != crc {
394 return Err(ErrorCode::Integrity);
395 }
396 bytes
397 } else {
398 Vec::new()
399 };
400 if kind == EntryKind::Directory && size != 0 {
401 return Err(ErrorCode::Integrity);
402 }
403 members.push(Member {
404 entry: Entry {
405 entry_id: id as u32,
406 name,
407 kind,
408 size: size as u64,
409 compressed_size: compressed as u64,
410 encrypted,
411 },
412 data,
413 });
414 at = at
415 .checked_add(46 + name_len + extra_len + comment_len)
416 .ok_or(ErrorCode::Integrity)?;
417 }
418 if at != end {
419 return Err(ErrorCode::Integrity);
420 }
421 spans.sort_unstable();
422 let mut next = 0;
423 for (start, stop) in spans {
424 if start != next {
425 return Err(ErrorCode::Integrity);
426 }
427 next = stop;
428 }
429 if next != central {
430 return Err(ErrorCode::Integrity);
431 }
432 validate_members(&members)?;
433 Ok(members)
434}
435pub fn parse(
436 input: &[u8],
437 limits: Limits,
438 decode: bool,
439 check: &mut impl FnMut() -> Result<()>,
440) -> Result<Catalog> {
441 if !limits.valid() || input.len() as u64 > limits.input {
442 return Err(ErrorCode::Limit);
443 }
444 if input.starts_with(b"PK\x03\x04") || input.starts_with(b"PK\x05\x06") {
445 return Ok(Catalog {
446 format: Format::Zip,
447 members: zip(input, limits, decode, check)?,
448 });
449 }
450 if input.starts_with(&[31, 139]) {
451 let bytes = gzip(input, limits, check)?;
452 if bytes.len() >= 512
453 && (bytes[257..262] == *b"ustar" || bytes[..512].iter().all(|b| *b == 0))
454 {
455 return Ok(Catalog {
456 format: Format::TarGzip,
457 members: tar(&bytes, limits, decode, check)?,
458 });
459 }
460 let len = bytes.len() as u64;
461 return Ok(Catalog {
462 format: Format::Gzip,
463 members: vec![Member {
464 entry: Entry {
465 entry_id: 0,
466 name: "GZip stream".to_owned(),
467 kind: EntryKind::File,
468 size: len,
469 compressed_size: input.len() as u64,
470 encrypted: false,
471 },
472 data: if decode { bytes } else { Vec::new() },
473 }],
474 });
475 }
476 if input.len() >= 512 {
477 return Ok(Catalog {
478 format: Format::Tar,
479 members: tar(input, limits, decode, check)?,
480 });
481 }
482 Err(ErrorCode::UnsupportedFormat)
483}
484fn deflate(input: &[u8], limit: u64, check: &mut impl FnMut() -> Result<()>) -> Result<Vec<u8>> {
485 let mut stream = Deflate::new(6, false, 15);
486 let mut output = Vec::new();
487 let mut buffer = [0; 65536];
488 loop {
489 check()?;
490 let a = stream.total_in();
491 let b = stream.total_out();
492 let status = stream
493 .compress(&input[a as usize..], &mut buffer, DeflateFlush::Finish)
494 .map_err(|_| ErrorCode::Internal)?;
495 bounded_append(
496 &mut output,
497 &buffer[..(stream.total_out() - b) as usize],
498 limit,
499 )?;
500 if status == Status::StreamEnd {
501 return Ok(output);
502 }
503 if a == stream.total_in() && b == stream.total_out() {
504 return Err(ErrorCode::Internal);
505 }
506 }
507}
508fn put16(v: &mut Vec<u8>, n: u16) {
509 v.extend(n.to_le_bytes());
510}
511fn put32(v: &mut Vec<u8>, n: u32) {
512 v.extend(n.to_le_bytes());
513}
514pub fn create_zip(
515 members: &[Member],
516 method: Method,
517 limits: Limits,
518 check: &mut impl FnMut() -> Result<()>,
519) -> Result<Vec<u8>> {
520 if members.len() > limits.entries as usize || members.len() >= 65535 {
521 return Err(ErrorCode::Limit);
522 }
523 validate_members(members)?;
524 let mut out = Vec::new();
525 let mut cd = Vec::new();
526 let mut total = 0u64;
527 for m in members {
528 check()?;
529 total = total
530 .checked_add(m.data.len() as u64)
531 .filter(|n| *n <= limits.output)
532 .ok_or(ErrorCode::Limit)?;
533 if m.entry.kind != EntryKind::File {
534 return Err(ErrorCode::UnsupportedFeature);
535 }
536 let name = m.entry.name.as_bytes();
537 let crc = crc32(0, &m.data);
538 let offset = out.len() as u32;
539 let packed = match method {
540 Method::Store => m.data.clone(),
541 Method::Deflate => deflate(&m.data, limits.output, check)?,
542 };
543 let method = match method {
544 Method::Store => 0,
545 Method::Deflate => 8,
546 };
547 out.extend(b"PK\x03\x04");
548 put16(&mut out, 20);
549 put16(&mut out, 0x0800);
550 put16(&mut out, method);
551 put16(&mut out, 0);
552 put16(&mut out, 33);
553 put32(&mut out, crc);
554 put32(&mut out, packed.len() as u32);
555 put32(&mut out, m.data.len() as u32);
556 put16(&mut out, name.len() as u16);
557 put16(&mut out, 0);
558 out.extend(name);
559 bounded_append(&mut out, &packed, limits.output)?;
560 cd.extend(b"PK\x01\x02");
561 put16(&mut cd, 0x0314);
562 put16(&mut cd, 20);
563 put16(&mut cd, 0x0800);
564 put16(&mut cd, method);
565 put16(&mut cd, 0);
566 put16(&mut cd, 33);
567 put32(&mut cd, crc);
568 put32(&mut cd, packed.len() as u32);
569 put32(&mut cd, m.data.len() as u32);
570 put16(&mut cd, name.len() as u16);
571 put16(&mut cd, 0);
572 put16(&mut cd, 0);
573 put16(&mut cd, 0);
574 put16(&mut cd, 0);
575 put32(&mut cd, 0o100600 << 16);
576 put32(&mut cd, offset);
577 cd.extend(name);
578 }
579 let offset = out.len();
580 bounded_append(&mut out, &cd, limits.output)?;
581 let mut end = Vec::new();
582 end.extend(b"PK\x05\x06");
583 put16(&mut end, 0);
584 put16(&mut end, 0);
585 put16(&mut end, members.len() as u16);
586 put16(&mut end, members.len() as u16);
587 put32(&mut end, cd.len() as u32);
588 put32(&mut end, offset as u32);
589 put16(&mut end, 0);
590 bounded_append(&mut out, &end, limits.output)?;
591 Ok(out)
592}