| 1 | """세 도구의 ZIP64 원본과 단일 볼륨 확장 필드 조합을 생성함.""" |
| 2 | import ctypes as c |
| 3 | import importlib.util |
| 4 | import io |
| 5 | import json |
| 6 | from pathlib import Path |
| 7 | import struct |
| 8 | import subprocess |
| 9 | import sys |
| 10 | import zipfile |
| 11 | |
| 12 | NAME = "payload.bin" |
| 13 | PAYLOAD = b"ZIP64 corpus payload\n" |
| 14 | |
| 15 | |
| 16 | def module(name, path): |
| 17 | spec = importlib.util.spec_from_file_location(name, path) |
| 18 | result = importlib.util.module_from_spec(spec) |
| 19 | spec.loader.exec_module(result) |
| 20 | return result |
| 21 | |
| 22 | |
| 23 | def python_zip(force=False, pipe=False): |
| 24 | class Pipe(io.BytesIO): |
| 25 | def seek(self, *args): |
| 26 | raise io.UnsupportedOperation() |
| 27 | |
| 28 | output = Pipe() if pipe else io.BytesIO() |
| 29 | with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_STORED) as archive: |
| 30 | with archive.open(NAME, "w", force_zip64=force) as target: |
| 31 | target.write(PAYLOAD) |
| 32 | return output.getvalue() |
| 33 | |
| 34 | |
| 35 | def libarchive_zip(): |
| 36 | reference = module( |
| 37 | "archive_reference", |
| 38 | Path(__file__).resolve().parents[1] / "rust-archive-worker/seven_zip_reference.py", |
| 39 | ) |
| 40 | lib = reference.library() |
| 41 | lib.archive_write_set_format_zip.argtypes = [c.c_void_p] |
| 42 | lib.archive_write_set_format_zip.restype = c.c_int |
| 43 | lib.archive_version_string.restype = c.c_char_p |
| 44 | archive = lib.archive_write_new() |
| 45 | buffer = c.create_string_buffer(65536) |
| 46 | used = c.c_size_t() |
| 47 | entry = lib.archive_entry_new() |
| 48 | |
| 49 | def check(value): |
| 50 | assert value == 0, lib.archive_error_string(archive) |
| 51 | |
| 52 | try: |
| 53 | check(lib.archive_write_set_format_zip(archive)) |
| 54 | check(lib.archive_write_set_format_option(archive, b"zip", b"zip64", b"1")) |
| 55 | check(lib.archive_write_set_format_option(archive, b"zip", b"compression", b"store")) |
| 56 | check(lib.archive_write_open_memory(archive, buffer, len(buffer), c.byref(used))) |
| 57 | lib.archive_entry_set_pathname(entry, NAME.encode()) |
| 58 | lib.archive_entry_set_filetype(entry, 0o100000) |
| 59 | lib.archive_entry_set_perm(entry, 0o600) |
| 60 | lib.archive_entry_set_size(entry, len(PAYLOAD)) |
| 61 | lib.archive_entry_set_mtime(entry, 0, 0) |
| 62 | check(lib.archive_write_header(archive, entry)) |
| 63 | assert lib.archive_write_data(archive, PAYLOAD, len(PAYLOAD)) == len(PAYLOAD) |
| 64 | check(lib.archive_write_close(archive)) |
| 65 | return buffer.raw[:used.value], lib.archive_version_string().decode() |
| 66 | finally: |
| 67 | lib.archive_entry_free(entry) |
| 68 | lib.archive_write_free(archive) |
| 69 | |
| 70 | |
| 71 | def variant(original, central_mask, end_mask, local64=False): |
| 72 | # 중앙 확장 필드는 원래 크기, 압축 크기, 오프셋, 디스크 순서임. |
| 73 | end = bytearray(original[-22:]) |
| 74 | central_at = struct.unpack_from("<I", end, 16)[0] |
| 75 | body = bytearray(original[:central_at]) |
| 76 | central = bytearray(original[central_at:-22]) |
| 77 | assert struct.unpack_from("<H", central, 30)[0] == 0 |
| 78 | assert struct.unpack_from("<H", central, 32)[0] == 0 |
| 79 | if local64: |
| 80 | name_len = struct.unpack_from("<H", body, 26)[0] |
| 81 | packed, size = struct.unpack_from("<II", body, 18) |
| 82 | struct.pack_into("<II", body, 18, 0xffffffff, 0xffffffff) |
| 83 | struct.pack_into("<H", body, 28, 20) |
| 84 | body[30 + name_len:30 + name_len] = struct.pack("<HHQQ", 1, 16, size, packed) |
| 85 | struct.pack_into("<H", body, 4, 45) |
| 86 | struct.pack_into("<H", central, 6, 45) |
| 87 | extra = bytearray() |
| 88 | for bit, offset, field_type in [(0, 24, "I"), (1, 20, "I"), (2, 42, "I"), (3, 34, "H")]: |
| 89 | if central_mask & (1 << bit): |
| 90 | value = struct.unpack_from("<" + field_type, central, offset)[0] |
| 91 | struct.pack_into("<" + field_type, central, offset, 0xffff if bit == 3 else 0xffffffff) |
| 92 | extra += struct.pack("<I" if bit == 3 else "<Q", value) |
| 93 | if extra: |
| 94 | central += struct.pack("<HH", 1, len(extra)) + extra |
| 95 | struct.pack_into("<H", central, 30, len(extra) + 4) |
| 96 | central_at = len(body) |
| 97 | directory = body + central |
| 98 | record = struct.pack( |
| 99 | "<4sQHHIIQQQQ", b"PK\x06\x06", 44, 45, 45, 0, 0, 1, 1, len(central), central_at |
| 100 | ) |
| 101 | locator = struct.pack("<4sIQI", b"PK\x06\x07", 0, len(directory), 1) |
| 102 | struct.pack_into("<II", end, 12, len(central), central_at) |
| 103 | # EOCD의 디스크 두 필드, 항목 수 두 필드, 크기와 오프셋을 독립 확장함. |
| 104 | for bit, offset, field_type in [(0, 4, "H"), (1, 6, "H"), (2, 8, "H"), |
| 105 | (3, 10, "H"), (4, 12, "I"), (5, 16, "I")]: |
| 106 | if end_mask & (1 << bit): |
| 107 | struct.pack_into("<" + field_type, end, offset, 0xffff if field_type == "H" else 0xffffffff) |
| 108 | return bytes(directory + record + locator + end) |
| 109 | |
| 110 | |
| 111 | def generate(root): |
| 112 | root = Path(root) |
| 113 | root.mkdir(mode=0o700, parents=True, exist_ok=False) |
| 114 | cases = [] |
| 115 | |
| 116 | def add(identifier, data, producer, payload=PAYLOAD): |
| 117 | path = root / (identifier + ".zip") |
| 118 | path.write_bytes(data) |
| 119 | with zipfile.ZipFile(path) as reference: |
| 120 | names = reference.namelist() |
| 121 | assert len(names) == 1 |
| 122 | assert reference.read(names[0]) == payload, identifier |
| 123 | assert reference.testzip() is None, identifier |
| 124 | cases.append((identifier, names[0], payload.hex(), producer)) |
| 125 | |
| 126 | original = python_zip() |
| 127 | add("python-classic", original, "Python zipfile") |
| 128 | add("python-force-local", python_zip(True), "Python zipfile force_zip64") |
| 129 | add("python-force-descriptor", python_zip(True, True), "Python zipfile force_zip64 unseekable") |
| 130 | native, version = libarchive_zip() |
| 131 | assert b"PK\x06\x07" in native |
| 132 | add("libarchive-force", native, version + " zip64=1") |
| 133 | (root / NAME).write_bytes(PAYLOAD) |
| 134 | subprocess.run( |
| 135 | ["zip", "-q", "-fz", "infozip-native.zip", NAME], |
| 136 | cwd=root, capture_output=True, check=True, |
| 137 | ) |
| 138 | info = (root / "infozip-native.zip").read_bytes() |
| 139 | assert struct.unpack_from("<II", info, 18) == (0xffffffff, 0xffffffff) |
| 140 | assert b"PK\x06\x07" in info |
| 141 | add("infozip-force", info, "Info-ZIP -fz regular file") |
| 142 | for central in range(16): |
| 143 | for end in range(64): |
| 144 | add(f"fields-c{central:02x}-e{end:02x}", variant(original, central, end), |
| 145 | "Python zipfile + APPNOTE field substitution") |
| 146 | add(f"local64-c{central:02x}", variant(original, central, 0, True), |
| 147 | "Python zipfile + local size pair + central field substitution") |
| 148 | expanded = variant(original, central, 0) |
| 149 | add(f"central-only-c{central:02x}", expanded[:-98] + expanded[-22:], |
| 150 | "Python zipfile + central fields without ZIP64 end records") |
| 151 | previous = module( |
| 152 | "previous_zip64", |
| 153 | Path(__file__).resolve().parents[1] / "rust-archive-worker/hardening_cases.py", |
| 154 | ) |
| 155 | for kind in ["locator64", "offset64-descriptor", "offset64-descriptor-unsigned"]: |
| 156 | directory = root / kind |
| 157 | directory.mkdir() |
| 158 | previous.generate(directory, kind, 20) |
| 159 | add("previous-" + kind, (directory / "input").read_bytes(), "PR74 regression", bytes(20)) |
| 160 | add("previous-eocd-disk", variant(original, 0, 3), "EOCD disk sentinel regression") |
| 161 | add("previous-central-disk", variant(original, 8, 0), "central disk sentinel regression") |
| 162 | (root / "cases.tsv").write_text( |
| 163 | "".join("\t".join(row[:3]) + "\n" for row in cases), encoding="utf-8" |
| 164 | ) |
| 165 | (root / "provenance.json").write_text(json.dumps({ |
| 166 | "python": sys.version, |
| 167 | "libarchive": version, |
| 168 | "infozip": subprocess.check_output(["zip", "-v"], text=True).splitlines()[:3], |
| 169 | "cases": [{"id": row[0], "producer": row[3]} for row in cases], |
| 170 | }, indent=4) + "\n", encoding="utf-8") |
| 171 | print(f"Python reference CRC/content: {len(cases)} passed") |
| 172 | |
| 173 | |
| 174 | if __name__ == "__main__": |
| 175 | generate(sys.argv[1]) |