team-ljyzipelo

공개
141줄5.9 KB
1import hashlib
2import io
3import json
4from pathlib import Path
5import stat
6import struct
7import warnings
8import zipfile
9
10
11DIRECTORY = Path(__file__).resolve().parent
12ROOT = DIRECTORY.parents[1]
13FIXTURES = DIRECTORY / "fixtures"
14STAMP = (2024, 1, 1, 0, 0, 0)
15REGULAR = stat.S_IFREG | 0o600
16PAYLOAD = b"zipelo-extraction-content\n"
17MAX_SAMPLE_BYTES = 4096
18UNIX_FIELD_REFERENCE = "https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT"
19
20
21def archive(entries, compression=zipfile.ZIP_STORED):
22 output = io.BytesIO()
23 with zipfile.ZipFile(output, "w") as zipped, warnings.catch_warnings():
24 warnings.filterwarnings("ignore", message="Duplicate name:", category=UserWarning)
25 for name, content, mode, extra in entries:
26 info = zipfile.ZipInfo(name, STAMP)
27 info.create_system = 3
28 info.external_attr = mode << 16
29 if stat.S_ISDIR(mode):
30 info.external_attr |= 0x10
31 info.extra = extra
32 info.compress_type = compression
33 zipped.writestr(info, content)
34 result = output.getvalue()
35 if len(result) > MAX_SAMPLE_BYTES:
36 raise ValueError("작은 수용 샘플의 크기 상한을 넘음")
37 return result
38
39
40def regular(name, content=PAYLOAD):
41 return (name, content, REGULAR, b"")
42
43
44def mutate_field(data, local_offset, central_offset, value):
45 changed = bytearray(data)
46 central = data.index(b"PK\x01\x02")
47 struct.pack_into("<I", changed, local_offset, value)
48 struct.pack_into("<I", changed, central + central_offset, value)
49 return bytes(changed)
50
51
52def build_samples():
53 normal = [
54 regular("hello.txt"),
55 ("nested/", b"", stat.S_IFDIR | 0o700, b""),
56 regular("nested/data.bin", bytes(range(32))),
57 regular("nested/empty.txt", b""),
58 ]
59 single = archive([regular("payload.txt")], zipfile.ZIP_DEFLATED)
60 stored = archive([regular("payload.txt")])
61 bad_payload = bytearray(stored)
62 bad_payload[stored.index(PAYLOAD)] ^= 1
63 bad_crc = struct.unpack_from("<I", single, 14)[0] ^ 1
64 mismatch = bytearray(single)
65 struct.pack_into("<I", mismatch, 22, len(PAYLOAD) + 1)
66 # UNIX 링크 대상 이름은 NUL 없이 12바이트 고정 필드 뒤에 저장함.
67 link_target = b"../sentinel.txt"
68 unix_data = struct.pack("<IIHH", 0, 0, 0, 0) + link_target
69 unix_extra = struct.pack("<HH", 0x000D, len(unix_data)) + unix_data
70 return {
71 "normal-stored.zip": archive(normal),
72 "normal-deflated.zip": archive(normal, zipfile.ZIP_DEFLATED),
73 "traversal.zip": archive([regular("../escape.txt")]),
74 "backslash-traversal.zip": archive([regular("..\\escape.txt")]),
75 "absolute-posix.zip": archive([regular("/escape.txt")]),
76 "absolute-drive.zip": archive([regular("C:/escape.txt")]),
77 "absolute-unc.zip": archive([regular("//server/share/escape.txt")]),
78 "duplicate.zip": archive([regular("same.txt", b"one"), regular("same.txt", b"two")]),
79 "file-before-child.zip": archive([regular("node", b"one"), regular("node/child", b"two")]),
80 "child-before-file.zip": archive([regular("node/child", b"one"), regular("node", b"two")]),
81 "case-distinct.zip": archive([regular("Readme.txt", b"first"), regular("README.TXT", b"second")]),
82 "linux-names.zip": archive([regular("CON", b"one"), regular("name:stream", b"two")]),
83 "symlink.zip": archive([("link", link_target, stat.S_IFLNK | 0o777, b"")]),
84 "unix-hardlink.zip": archive([("link", b"", REGULAR, unix_extra)]),
85 "special-fifo.zip": archive([("pipe", b"", stat.S_IFIFO | 0o600, b"")]),
86 "bad-payload-crc.zip": bytes(bad_payload),
87 "bad-header-crc.zip": mutate_field(single, 14, 16, bad_crc),
88 "length-smaller.zip": mutate_field(single, 22, 24, len(PAYLOAD) - 1),
89 "length-larger.zip": mutate_field(single, 22, 24, len(PAYLOAD) + 1),
90 "local-central-length.zip": bytes(mismatch),
91 "truncated.zip": single[:-12],
92 "cumulative.zip": archive([regular("first.bin", bytes(range(8))), regular("second.bin", bytes(range(8, 16)))]),
93 }
94
95
96def build_manifest(samples):
97 entries = []
98 for name, data in sorted(samples.items()):
99 entries.append({"file": name, "bytes": len(data), "sha256": hashlib.sha256(data).hexdigest()})
100 return {
101 "schema_version": 1,
102 "source": "자체 생성한 작은 ZIP 샘플이며 디스크 해제를 수행하지 않음",
103 "unix_link_reference": UNIX_FIELD_REFERENCE,
104 "unix_link_section": "4.5.7, 0x000d 링크 메타데이터의 거부 검사. 모든 ZIP 링크 방언을 대표하지 않음",
105 "normal_files": {
106 "hello.txt": {"bytes": len(PAYLOAD), "sha256": hashlib.sha256(PAYLOAD).hexdigest()},
107 "nested/data.bin": {"bytes": 32, "sha256": hashlib.sha256(bytes(range(32))).hexdigest()},
108 "nested/empty.txt": {"bytes": 0, "sha256": hashlib.sha256(b"").hexdigest()},
109 },
110 "samples": entries,
111 }
112
113
114def write_new(path, content):
115 if path.is_symlink():
116 raise ValueError("샘플 경로의 링크를 허용하지 않음")
117 if path.exists():
118 if path.read_bytes() != content:
119 raise ValueError("기존 샘플을 덮어쓰지 않음")
120 return
121 with path.open("xb") as output:
122 output.write(content)
123
124
125def main():
126 if DIRECTORY != ROOT / "tests" / "extraction":
127 raise ValueError("프로젝트 tests 아래 경로가 필요함")
128 for path in (FIXTURES, *FIXTURES.parents):
129 if path.is_symlink():
130 raise ValueError("샘플 경로의 링크를 허용하지 않음")
131 FIXTURES.mkdir(exist_ok=True)
132 samples = build_samples()
133 for name, content in samples.items():
134 write_new(FIXTURES / name, content)
135 manifest = json.dumps(build_manifest(samples), ensure_ascii=False, indent=4) + "\n"
136 write_new(DIRECTORY / "fixtures.json", manifest.encode("utf-8"))
137 print(f"해제 샘플 {len(samples)}개, {sum(map(len, samples.values()))}바이트")
138
139
140if __name__ == "__main__":
141 main()