team-ljyzipelo

공개

ZIP 본문 안의 가짜 중앙 목록 후보를 제외함

작성자
시로사키 하나
작성 시각
커밋
7642a63a07606bcddce9471f5f303eea68094c0b
부모
16d8f5e
이 시점의 파일 보기

변경된 파일 3개

+248-9
수정experiments/rust-archive-worker/src/zip_recovery.rs+101-9
@@ -191,13 +191,89 @@ fn directory_span(
191191 Ok(true)
192192}
193193
194추가: struct EndRecord {
195추가: index: usize,
196추가: at: u64,
197추가: directory: u64,
198추가: directory_end: u64,
199추가: }
200추가:
201추가: fn metadata_overlaps_member(
202추가: source: &mut File,
203추가: owner: &EndRecord,
204추가: nested: &EndRecord,
205추가: check: &mut impl Monitor,
206추가: ) -> Result<bool> {
207추가: let mut at = owner.directory;
208추가: while at < owner.directory_end {
209추가: check.check()?;
210추가: let h = bytes(source, at, 46, owner.directory_end)?;
211추가: let nn = u16at(&h, 28) as usize;
212추가: let ne = u16at(&h, 30) as usize;
213추가: let next = add(at, 46 + nn as u64 + ne as u64 + u16at(&h, 32) as u64)?;
214추가: let offset = u32at(&h, 42) as u64;
215추가: let packed = u32at(&h, 20);
216추가: let size = u32at(&h, 24);
217추가: if nn > 0
218추가: && nn <= 4096
219추가: && packed > 0
220추가: && packed != u32::MAX
221추가: && size != u32::MAX
222추가: && offset.checked_add(30).is_some_and(|n| n <= owner.directory)
223추가: {
224추가: let local = bytes(source, offset, 30, owner.directory)?;
225추가: let start = add(
226추가: offset,
227추가: 30 + u16at(&local, 26) as u64 + u16at(&local, 28) as u64,
228추가: )?;
229추가: let stop = add(start, packed as u64)?;
230추가: let overlaps = (start < nested.directory_end && nested.directory < stop)
231추가: || (start < nested.at + 22 && nested.at < stop);
232추가: let flags = u16at(&h, 8);
233추가: if overlaps
234추가: && stop <= owner.directory
235추가: && nn == u16at(&local, 26) as usize
236추가: && flags == u16at(&local, 6)
237추가: && u16at(&h, 10) == u16at(&local, 8)
238추가: && bytes(source, at + 46, nn, owner.directory_end)?
239추가: == bytes(source, offset + 30, nn, owner.directory)?
240추가: {
241추가: // 두 목록이 주장한 범위보다 로컬 필드와 일치한 본문 경계를 우선함.
242추가: if flags & 8 == 0 {
243추가: if packed == u32at(&local, 18) && size == u32at(&local, 22) {
244추가: return Ok(true);
245추가: }
246추가: } else if stop.checked_add(12).is_some_and(|n| n <= owner.directory) {
247추가: let descriptor = bytes(source, stop, 12, owner.directory)?;
248추가: let skip = if &descriptor[..4] == b"PK\x07\x08" {
249추가: 4
250추가: } else {
251추가: 0
252추가: };
253추가: if (stop + skip + 12) <= owner.directory {
254추가: let d = bytes(source, stop + skip, 12, owner.directory)?;
255추가: if u32at(&d, 0) == u32at(&h, 16)
256추가: && u32at(&d, 4) == packed
257추가: && u32at(&d, 8) == size
258추가: {
259추가: return Ok(true);
260추가: }
261추가: }
262추가: }
263추가: }
264추가: }
265추가: at = next;
266추가: }
267추가: Ok(false)
268추가: }
269추가:
194270fn end_record(
195271 source: &mut File,
196272 tail: &[u8],
197273 tail_at: u64,
198274 check: &mut impl Monitor,
199275) -> Result<Option<usize>> {
200삭제: let mut selected: Option<(usize, u64)> = None;
276추가: let mut selected: Option<EndRecord> = None;
201277 for end in (0..=tail.len() - 22).rev() {
202278 if &tail[end..end + 4] != b"PK\x05\x06"
203279 || end + 22 + u16at(tail, end + 20) as usize != tail.len()
@@ -233,16 +309,32 @@ fn end_record(
233309 if !directory_span(source, offset, stop, check)? {
234310 continue;
235311 }
236삭제: let comment_at = at + 22;
237삭제: // 선행 후보의 중앙 목록이나 주석에 속한 후행 목록은 선택하지 않음.
238삭제: if selected.is_none_or(|(nested_end, nested_directory)| {
239삭제: (offset < nested_directory && nested_directory < stop)
240삭제: || (comment_at <= nested_directory && end + 22 <= nested_end)
241삭제: }) {
242삭제: selected = Some((end, offset));
312추가: let current = EndRecord {
313추가: index: end,
314추가: at,
315추가: directory: offset,
316추가: directory_end: stop,
317추가: };
318추가: if let Some(previous) = &selected {
319추가: let current_in_member = metadata_overlaps_member(source, previous, &current, check)?;
320추가: let previous_in_member = metadata_overlaps_member(source, &current, previous, check)?;
321추가: if current_in_member && previous_in_member {
322추가: return Err(ErrorCode::Integrity);
323추가: }
324추가: if current_in_member {
325추가: continue;
326추가: }
327추가: // 본문 안의 메타데이터를 제거한 뒤 중앙 주석과 파일 주석의 소속을 비교함.
328추가: if !previous_in_member
329추가: && !(offset < previous.directory && previous.directory < stop)
330추가: && !(at + 22 <= previous.directory && end + 22 <= previous.index)
331추가: {
332추가: continue;
333추가: }
243334 }
335추가: selected = Some(current);
244336 }
245삭제: Ok(selected.map(|(end, _)| end))
337추가: Ok(selected.map(|record| record.index))
246338}
247339
248340fn central(
추가tests/rust-archive-worker/payload_eocd.py+104-0
@@ -0,0 +1,104 @@
1추가: import hashlib
2추가: import io
3추가: import json
4추가: from pathlib import Path
5추가: import struct
6추가: import sys
7추가: import zipfile
8추가:
9추가:
10추가: class StreamingBuffer(io.BytesIO):
11추가: def seekable(self):
12추가: return False
13추가:
14추가: def seek(self, *args):
15추가: raise io.UnsupportedOperation("seek")
16추가:
17추가:
18추가: def create(folder, variant):
19추가: descriptor = bool(variant & 1)
20추가: damaged_payload_header = bool(variant & 2)
21추가: forged_empty_member = bool(variant & 32)
22추가: first_data = b"" if forged_empty_member else b"first content"
23추가: nested_comment = bool(variant & 4) or forged_empty_member
24추가: padding = 13 if variant & 8 else 0
25추가:
26추가: def archive(payload):
27추가: buffer = StreamingBuffer() if descriptor else io.BytesIO()
28추가: with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_STORED) as writer:
29추가: members = [("first.txt", first_data), ("second.bin", payload)]
30추가: for name, data in members:
31추가: info = zipfile.ZipInfo(name, (2024, 1, 1, 0, 0, 0))
32추가: writer.writestr(info, data)
33추가: return bytearray(buffer.getvalue())
34추가:
35추가: original = archive(b"")
36추가: real_end = len(original) - 22
37추가: directory = struct.unpack_from("<I", original, real_end + 16)[0]
38추가: first_len = 46 + sum(struct.unpack_from("<HHH", original, directory + 28))
39추가: payload_size = padding + first_len + 22
40추가: original = archive(bytes(payload_size))
41추가: real_end = len(original) - 22
42추가: directory = struct.unpack_from("<I", original, real_end + 16)[0]
43추가: local = struct.unpack_from("<I", original, directory + first_len + 42)[0]
44추가: name_len, extra_len = struct.unpack_from("<HH", original, local + 26)
45추가: data_at = local + 30 + name_len + extra_len
46추가: fake_cd = original[directory : directory + first_len]
47추가: fake_end = bytearray(original[real_end : real_end + 22])
48추가: comment_cd_bytes = fake_cd
49추가: if forged_empty_member:
50추가: comment_cd_bytes = bytearray(46)
51추가: comment_cd_bytes[:4] = b"PK\x01\x02"
52추가: local_flags = struct.unpack_from("<H", original, directory + 6)[0]
53추가: struct.pack_into("<H", comment_cd_bytes, 8, local_flags)
54추가: struct.pack_into("<I", comment_cd_bytes, 42, directory)
55추가: comment_size = len(comment_cd_bytes) + 22 if nested_comment else 0
56추가: struct.pack_into(
57추가: "<HHIIH",
58추가: fake_end,
59추가: 8,
60추가: 1,
61추가: 1,
62추가: first_len,
63추가: data_at + padding,
64추가: len(original) + comment_size - data_at - payload_size,
65추가: )
66추가: payload = bytes(padding) + fake_cd + fake_end
67추가: original = archive(payload)
68추가: if nested_comment:
69추가: comment_cd = len(original)
70추가: comment_end = bytearray(original[-22:])
71추가: struct.pack_into(
72추가: "<HHIIH", comment_end, 8, 1, 1, len(comment_cd_bytes), comment_cd, 0
73추가: )
74추가: struct.pack_into("<H", original, real_end + 20, comment_size)
75추가: original.extend(comment_cd_bytes + comment_end)
76추가: damaged = local if damaged_payload_header else 0
77추가: original[damaged : damaged + 4] = b"BAD!"
78추가: if variant & 16:
79추가: struct.pack_into("<I", original, local + 14, 0x12345678)
80추가: (folder / "damaged.zip").write_bytes(original)
81추가: expected = {
82추가: "first.txt": hashlib.sha256(first_data).hexdigest(),
83추가: "second.bin": hashlib.sha256(payload).hexdigest(),
84추가: }
85추가: (folder / "expected.json").write_text(json.dumps(expected), encoding="utf-8")
86추가:
87추가:
88추가: def verify(folder):
89추가: expected = json.loads((folder / "expected.json").read_text(encoding="utf-8"))
90추가: with zipfile.ZipFile(folder / "recovered.zip") as archive:
91추가: assert len(archive.infolist()) == len(expected)
92추가: assert set(archive.namelist()) == set(expected)
93추가: assert archive.testzip() is None
94추가: for name, digest in expected.items():
95추가: assert hashlib.sha256(archive.read(name)).hexdigest() == digest, name
96추가:
97추가:
98추가: if __name__ == "__main__":
99추가: if sys.argv[1] == "create":
100추가: create(Path(sys.argv[2]), int(sys.argv[3]))
101추가: elif sys.argv[1] == "verify":
102추가: verify(Path(sys.argv[2]))
103추가: else:
104추가: raise ValueError("unknown mode")
수정tests/rust-archive-worker/recovery.rs+43-0
@@ -727,3 +727,46 @@ fn nested_directory_in_central_entry_comment_is_not_an_outer_archive() {
727727 assert_full_comment_recovery(&input, &format!("central-comment/{wraps_real_end}"));
728728 }
729729}
730추가:
731추가: #[test]
732추가: fn fake_directory_and_eocd_in_member_payload_cannot_hide_members() {
733추가: let helper = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
734추가: .join("../../tests/rust-archive-worker/payload_eocd.py");
735추가: for variant in (0..32).chain([32]) {
736추가: let s = Scratch::new();
737추가: let generated = Command::new("python3")
738추가: .arg("-B")
739추가: .arg(&helper)
740추가: .arg("create")
741추가: .arg(&s.0)
742추가: .arg(variant.to_string())
743추가: .output()
744추가: .unwrap();
745추가: assert!(generated.status.success(), "{generated:?}");
746추가: let input = fs::read(s.0.join("damaged.zip")).unwrap();
747추가: let events = execute(start(&s));
748추가: let terminal = terminal(&events);
749추가: assert_eq!(terminal.error, ErrorCode::None, "variant {variant}");
750추가: assert_eq!(terminal.outcome, Outcome::Completed);
751추가: assert_eq!(terminal.publication, Publication::Complete);
752추가: assert_eq!(terminal.created_count, 1);
753추가: let summary = recovery_end(&events);
754추가: assert!(summary.complete());
755추가: assert_eq!(summary.mode, RecoveryMode::CentralDirectory);
756추가: assert_eq!(summary.known_entries, Some(2));
757추가: assert_eq!(summary.verified_entries, 2);
758추가: assert_eq!(
759추가: summary.source_sha256,
760추가: <[u8; 32]>::from(Sha256::digest(&input))
761추가: );
762추가: assert_eq!(fs::read(s.0.join("damaged.zip")).unwrap(), input);
763추가: let checked = Command::new("python3")
764추가: .arg("-B")
765추가: .arg(&helper)
766추가: .arg("verify")
767추가: .arg(&s.0)
768추가: .output()
769추가: .unwrap();
770추가: assert!(checked.status.success(), "variant {variant}: {checked:?}");
771추가: }
772추가: }