-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathzipfile.py
More file actions
104 lines (90 loc) · 3.08 KB
/
zipfile.py
File metadata and controls
104 lines (90 loc) · 3.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import io
import sys
import shutil
import pathlib
import tempfile
import typing
import zlib
import zipfile
class OpenFileRecorder:
"""Record files which are opened using sys.audit()"""
_record_open_files: typing.ClassVar[bool] = False
_recorded_files: typing.ClassVar[set[pathlib.Path]] = set()
@staticmethod
def _sys_audit_record_open(event, args):
if event == "open" and OpenFileRecorder._record_open_files:
OpenFileRecorder._recorded_files.add(pathlib.Path(args[0]))
@property
def paths(self) -> set[pathlib.Path]:
return OpenFileRecorder._recorded_files.copy()
def __enter__(self):
if OpenFileRecorder._record_open_files:
raise RuntimeError("OpenFileRecorder already recording")
OpenFileRecorder._record_open_files = True
OpenFileRecorder._recorded_files.clear()
return self
def __exit__(self, *_):
OpenFileRecorder._recorded_files.clear()
OpenFileRecorder._record_open_files = False
sys.addaudithook(OpenFileRecorder._sys_audit_record_open)
def FuzzerRunOne(FuzzerInput):
try:
with zipfile.ZipFile(io.BytesIO(FuzzerInput), strict_timestamps=False) as zf:
for info in zf.infolist():
info.filename
info.date_time
info.compress_type
info.comment
info.extra
info.create_system
info.create_version
info.extract_version
info.reserved
info.flag_bits
info.volume
info.internal_attr
info.external_attr
info.header_offset
info.CRC
info.compress_size
info.file_size
except zipfile.BadZipFile:
return
# zipfile raises 'NotImplementedError' for
# ZIP versions that aren't supported.
except NotImplementedError as e:
if "zip file version" in str(e):
return
raise
except UnicodeDecodeError:
return
# Assert that all files created by ZIP are
# relative to the extraction directory.
with tempfile.TemporaryDirectory() as tmp_dir, OpenFileRecorder() as record:
try:
with zipfile.ZipFile(io.BytesIO(FuzzerInput)) as zf:
zf.extractall(path=tmp_dir)
except (
zipfile.BadZipFile,
zlib.error,
NotImplementedError,
UnicodeDecodeError,
UnicodeEncodeError,
RuntimeError,
ValueError,
EOFError,
OverflowError,
):
return
except OSError as e:
if "Invalid data stream" in str(e):
return
elif "File name too long" in str(e):
return
raise
finally:
shutil.rmtree(tmp_dir)
# Assert that every opened file is a subdirectory
# of the extraction directory.
for filepath in record.paths:
assert pathlib.Path(filepath).is_relative_to(tmp_dir), f"{filepath} is not relative to {tmp_dir}"