| 1 | import io |
| 2 | from pathlib import Path |
| 3 | import stat |
| 4 | import zipfile |
| 5 | |
| 6 | |
| 7 | ROOT = Path(__file__).resolve().parents[2] |
| 8 | FIXTURES = Path(__file__).resolve().parent / "fixtures" |
| 9 | STAMP = (2024, 1, 1, 0, 0, 0) |
| 10 | PAYLOAD = b"zipelo-safe-test-payload\n" |
| 11 | MAX_SAMPLE_BYTES = 16 * 1024 |
| 12 | |
| 13 | |
| 14 | def archive(entries): |
| 15 | output = io.BytesIO() |
| 16 | with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_STORED) as zipped: |
| 17 | for name, content, mode in entries: |
| 18 | info = zipfile.ZipInfo(name, STAMP) |
| 19 | info.create_system = 3 |
| 20 | info.external_attr = mode << 16 |
| 21 | zipped.writestr(info, content) |
| 22 | result = output.getvalue() |
| 23 | if len(result) > MAX_SAMPLE_BYTES: |
| 24 | raise ValueError("안전 샘플 크기 제한을 초과함") |
| 25 | return result |
| 26 | |
| 27 | |
| 28 | def build_samples(): |
| 29 | regular = stat.S_IFREG | 0o600 |
| 30 | normal = archive([ |
| 31 | ("hello.txt", PAYLOAD, regular), |
| 32 | ("한글/빈파일.txt", b"", regular), |
| 33 | ]) |
| 34 | corrupted = bytearray(normal) |
| 35 | corrupted[normal.index(PAYLOAD)] ^= 1 |
| 36 | return { |
| 37 | "normal.zip": normal, |
| 38 | "traversal.zip": archive([("../escape.txt", PAYLOAD, regular)]), |
| 39 | "backslash-traversal.zip": archive([("..\\escape.txt", PAYLOAD, regular)]), |
| 40 | "case-collision.zip": archive([ |
| 41 | ("Readme.txt", b"first", regular), |
| 42 | ("README.TXT", b"second", regular), |
| 43 | ]), |
| 44 | "parent-collision.zip": archive([ |
| 45 | ("folder", b"first", regular), |
| 46 | ("folder/child.txt", b"second", regular), |
| 47 | ]), |
| 48 | "symlink.zip": archive([ |
| 49 | ("link", b"../sentinel.txt", stat.S_IFLNK | 0o777), |
| 50 | ]), |
| 51 | "bad-crc.zip": bytes(corrupted), |
| 52 | "truncated.zip": normal[:-12], |
| 53 | } |
| 54 | |
| 55 | |
| 56 | def main(): |
| 57 | # 샘플은 해제하지 않고 지정된 테스트 폴더에만 생성함. |
| 58 | if FIXTURES.is_symlink() or FIXTURES.parent != ROOT / "tests" / "security": |
| 59 | raise ValueError("샘플 경로가 안전하지 않음") |
| 60 | FIXTURES.mkdir(exist_ok=True) |
| 61 | for name, content in build_samples().items(): |
| 62 | path = FIXTURES / name |
| 63 | if path.exists() or path.is_symlink(): |
| 64 | if path.is_symlink() or path.read_bytes() != content: |
| 65 | raise FileExistsError(f"기존 샘플을 덮어쓰지 않음: {name}") |
| 66 | else: |
| 67 | with path.open("xb") as output: |
| 68 | output.write(content) |
| 69 | print(f"{name}: {len(content)} bytes") |
| 70 | |
| 71 | |
| 72 | if __name__ == "__main__": |
| 73 | main() |