Repository navigation
Expand file tree
/
Copy pathzipcheck.py
More file actions
741 lines (662 loc) · 29.2 KB
/
Copy pathzipcheck.py
File metadata and controls
741 lines (662 loc) · 29.2 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
#!/usr/bin/env python3
"""zipcheck: inspect zip/tar archives for hostile members WITHOUT extracting anything.
Only headers are read. For compressed tar streams the decompressed byte count is
hard-capped. Nothing is ever written to disk and no archived content is executed.
Exit codes: 0 clean, 1 findings, 2 usage or input error (archive could not be fully inspected).
"""
import argparse
import bz2
import json
import os
import re
import stat
import struct
import sys
import tarfile
import zipfile
import zlib
try:
import lzma
except ImportError: # pragma: no cover
lzma = None
__version__ = "1.0.0"
SEVERITIES = {"low": 1, "medium": 2, "high": 3}
SEV_NAMES = {1: "LOW", 2: "MEDIUM", 3: "HIGH"}
MIB = 1024 * 1024
DEFAULT_MAX_TOTAL = 1024 * MIB # declared uncompressed bytes
DEFAULT_MAX_RATIO = 100 # uncompressed / compressed
DEFAULT_MAX_MEMBERS = 10000
DEFAULT_MAX_SCAN = 1024 * MIB # decompressed bytes read from a tar stream
DEFAULT_SCAN_MEMBERS = 200000 # hard cap on members enumerated
DEFAULT_MAX_FINDINGS = 1000
RATIO_FLOOR = 1 * MIB # ratio rules ignore outputs smaller than this
MAX_HEADER_READ = 16 * MIB # a single tar header read larger than this is refused
MAX_CD_BYTES = 64 * MIB # zip central directory size cap
MAX_LINK_TARGET = 4096
LZMA_MEMLIMIT = 256 * MIB
ARCHIVE_EXTS = (".zip", ".tar", ".gz", ".tgz", ".bz2", ".tbz", ".tbz2", ".xz", ".txz",
".7z", ".rar", ".jar", ".war", ".ear", ".whl", ".cab", ".z", ".zst")
WIN_RESERVED = {"CON", "PRN", "AUX", "NUL"} | {"COM%d" % i for i in range(1, 10)} | \
{"LPT%d" % i for i in range(1, 10)}
WIN_BAD_CHARS = set('<>:"|?*')
SPOOF_CHARS = set(range(0x202A, 0x202F)) | set(range(0x2066, 0x206A)) | \
{0x200B, 0x200C, 0x200D, 0x200E, 0x200F, 0x061C, 0x2060, 0xFEFF}
DRIVE_RE = re.compile(r"^[A-Za-z]:")
class ScanLimit(Exception):
"""The decompressed-byte cap was reached."""
class ArchiveError(Exception):
"""The archive could not be read or is not a supported format."""
class Member(object):
__slots__ = ("index", "name", "kind", "size", "csize", "mode", "target",
"encrypted", "offset", "target_note")
def __init__(self, index, name, kind, size=0, csize=None, mode=None, target=None,
encrypted=False, offset=None, target_note=None):
self.index = index
self.name = name
self.kind = kind # file dir symlink hardlink device special
self.size = size
self.csize = csize
self.mode = mode
self.target = target
self.encrypted = encrypted
self.offset = offset
self.target_note = target_note
def safe(text, limit=200):
"""Printable, terminal-safe rendering of an attacker-controlled string."""
out = []
for ch in str(text):
o = ord(ch)
if ch == "\\":
out.append("\\\\")
elif o < 32 or o == 127 or 0x80 <= o <= 0x9F or o in SPOOF_CHARS or 0xD800 <= o <= 0xDFFF:
out.append("\\x%02x" % o if o < 256 else "\\u%04x" % o if o < 0x10000 else "\\U%08x" % o)
else:
out.append(ch)
if len(out) > limit:
out.append("...")
break
return "".join(out)
def parse_size(text):
m = re.match(r"^\s*(\d+)\s*([kKmMgG]?)[bB]?\s*$", text)
if not m:
raise argparse.ArgumentTypeError("bad size %r (use e.g. 500M, 2G, 1048576)" % text)
mult = {"": 1, "k": 1024, "m": MIB, "g": 1024 * MIB}[m.group(2).lower()]
return int(m.group(1)) * mult
def positive_int(text):
try:
v = int(text)
except ValueError:
raise argparse.ArgumentTypeError("not an integer: %r" % text)
if v < 1:
raise argparse.ArgumentTypeError("must be >= 1")
return v
# ---------------------------------------------------------------- analysis
def components(name):
"""Split on both separators; extraction on Windows treats backslash as one."""
return name.replace("\\", "/").split("/")
def norm_key(name):
return "/".join(c for c in components(name) if c not in ("", "."))
def walk_depth(parts, start=0):
"""Return (final_depth, escaped) walking path components from depth `start`."""
depth = start
escaped = False
for p in parts:
if p in ("", "."):
continue
if p == "..":
depth -= 1
if depth < 0:
escaped = True
else:
depth += 1
return depth, escaped
def link_escapes(member_name, target, hard):
"""Does a link target leave the extraction root? Returns (bool, reason)."""
if target is None:
return False, ""
t = target.replace("\\", "/")
if t.startswith("/"):
return True, "absolute target"
if DRIVE_RE.match(t):
return True, "drive-letter target"
start = 0
if not hard:
dparts = [c for c in components(member_name)[:-1] if c not in ("", ".")]
start, esc = walk_depth(dparts)
if esc:
return True, "link sits outside the root"
_d, escaped = walk_depth(t.split("/"), start)
if escaped:
return True, "target climbs above the extraction root"
return False, ""
class Analyzer(object):
def __init__(self, opts, archive_size):
self.opts = opts
self.archive_size = archive_size
self.findings = []
self.dropped = 0
self.count = 0
self.total = 0
self.names = {} # normalized name -> first index
self.lower = {} # casefolded name -> (first index, original key)
self.symlinks = {} # normalized name -> escapes?
self.offsets = {}
self.nested = 0
self.bomb_ratio_flagged = False
def add(self, rule, sev, detail, m=None):
if len(self.findings) >= self.opts.max_findings:
self.dropped += 1
return
self.findings.append({
"rule": rule,
"severity": SEV_NAMES[sev],
"member": None if m is None else m.name,
"index": None if m is None else m.index,
"detail": detail,
})
# -- per member
def feed(self, m):
self.count += 1
if m.kind in ("file",):
self.total += max(0, m.size)
self.check_name(m)
self.check_kind(m)
self.check_dupes(m)
self.check_symlink_pass(m)
self.check_size(m)
if m.kind in ("file", "symlink", "hardlink") and m.name.lower().endswith(ARCHIVE_EXTS):
self.nested += 1
self.add("nested-archive", 1, "member looks like another archive (not opened)", m)
if m.encrypted:
self.add("encrypted-member", 1, "encrypted member: contents cannot be inspected", m)
def check_name(self, m):
name = m.name
if name == "":
self.add("empty-name", 2, "member has an empty name", m)
return
s = name.replace("\\", "/")
if s.startswith("/"):
self.add("absolute-path", 3, "absolute path (or UNC path) would write outside the target", m)
if DRIVE_RE.match(s):
self.add("drive-letter", 3, "Windows drive-letter path would write outside the target", m)
parts = s.split("/")
_d, escaped = walk_depth(parts)
if escaped:
self.add("path-traversal", 3, "'..' components climb above the extraction root", m)
elif ".." in parts:
self.add("dotdot-component", 1, "contains '..' but stays inside the root", m)
# Windows names
for i, comp in enumerate(parts):
if i == 0 and DRIVE_RE.match(comp):
comp = comp[2:]
if comp in ("", ".", ".."):
continue
stem = comp.split(".")[0].rstrip(" ").upper()
if stem in WIN_RESERVED:
self.add("windows-reserved-name", 2,
"component %r is a reserved Windows device name" % safe(comp, 60), m)
bad = sorted(set(c for c in comp if c in WIN_BAD_CHARS))
if bad:
self.add("windows-invalid-name", 1,
"component %r has characters invalid on Windows (%s); ':' can mean an alternate data stream"
% (safe(comp, 60), "".join(bad)), m)
elif comp.endswith(".") or comp.endswith(" "):
self.add("windows-invalid-name", 1,
"component %r ends in a dot or space, which Windows silently strips" % safe(comp, 60), m)
if len(comp.encode("utf-8", "surrogatepass")) > 255:
self.add("long-name", 1, "a path component is longer than 255 bytes", m)
if len(name.encode("utf-8", "surrogatepass")) > 4096:
self.add("long-name", 1, "path is longer than 4096 bytes", m)
self.check_chars(name, "name", m)
if m.target is not None:
self.check_chars(m.target, "link target", m)
def check_chars(self, text, what, m):
ctrl = []
spoof = []
for ch in text:
o = ord(ch)
if o < 32 or o == 127 or 0x80 <= o <= 0x9F:
ctrl.append("U+%04X" % o)
elif o in SPOOF_CHARS:
spoof.append("U+%04X" % o)
if ctrl:
self.add("control-char", 2, "%s contains control characters: %s" % (what, ", ".join(ctrl[:8])), m)
if spoof:
self.add("spoofing-char", 2,
"%s contains bidi-override or invisible characters: %s" % (what, ", ".join(spoof[:8])), m)
def check_kind(self, m):
mode = m.mode
if m.kind == "device":
self.add("device-file", 3, "character/block device node", m)
elif m.kind == "special":
self.add("special-file", 2, "FIFO, socket or unknown member type", m)
if mode is not None:
if mode & 0o4000:
self.add("setuid", 3, "setuid bit set (mode %o)" % (mode & 0o7777), m)
if mode & 0o2000 and m.kind != "dir":
self.add("setgid", 3, "setgid bit set (mode %o)" % (mode & 0o7777), m)
elif mode & 0o2000:
self.add("setgid", 1, "setgid bit set on a directory (mode %o)" % (mode & 0o7777), m)
if m.kind in ("symlink", "hardlink"):
hard = m.kind == "hardlink"
if m.target_note:
self.add("link-unreadable", 2, m.target_note, m)
elif m.target is None or m.target == "":
self.add("empty-link-target", 2, "%s without a target" % m.kind, m)
else:
esc, why = link_escapes(m.name, m.target, hard)
if esc:
self.add("hardlink-escape" if hard else "symlink-escape", 3,
"%s -> %r: %s" % (m.kind, safe(m.target, 120), why), m)
if m.kind == "symlink":
self.symlinks[norm_key(m.name)] = esc
def check_dupes(self, m):
key = norm_key(m.name)
if key in self.names:
self.add("duplicate-name", 2,
"same path as member #%d; extractors differ on which one wins" % self.names[key], m)
else:
self.names[key] = m.index
fold = key.casefold()
prev = self.lower.get(fold)
if prev is not None and prev[1] != key:
self.add("case-collision", 1,
"differs only by case from member #%d (collides on case-insensitive filesystems)" % prev[0], m)
elif prev is None:
self.lower[fold] = (m.index, key)
if m.offset is not None:
if m.offset in self.offsets and m.kind != "dir":
self.add("overlapping-entries", 3,
"shares its data offset with member #%d (overlap/zip-quine bomb pattern)" % self.offsets[m.offset], m)
else:
self.offsets.setdefault(m.offset, m.index)
def check_symlink_pass(self, m):
if not self.symlinks:
return
parts = [c for c in components(m.name) if c not in ("", ".")]
for i in range(1, len(parts)):
pre = "/".join(parts[:i])
if pre in self.symlinks:
if self.symlinks[pre]:
self.add("write-through-symlink", 3,
"path passes through symlink %r that points outside the root" % safe(pre, 80), m)
else:
self.add("write-through-symlink", 2,
"path passes through symlink %r; extraction could be redirected" % safe(pre, 80), m)
return
def check_size(self, m):
if m.kind != "file" or m.csize is None:
return
if m.size >= RATIO_FLOOR:
if m.csize == 0 or m.size / float(m.csize) > self.opts.max_ratio:
self.add("bomb-member-ratio", 3,
"declared %d bytes from %d compressed (ratio over %d)"
% (m.size, m.csize, self.opts.max_ratio), m)
def finish(self, truncated=False):
o = self.opts
if self.total > o.max_total:
self.add("bomb-total-size", 3, "declared uncompressed total %d bytes exceeds limit %d"
% (self.total, o.max_total))
if self.archive_size > 0 and self.total >= RATIO_FLOOR and \
self.total / float(self.archive_size) > o.max_ratio:
self.add("bomb-ratio", 3, "overall ratio %.0f:1 (%d bytes from a %d byte archive) exceeds %d:1"
% (self.total / float(self.archive_size), self.total, self.archive_size, o.max_ratio))
if self.count > o.max_members:
self.add("bomb-member-count", 2, "%d members%s exceeds limit %d"
% (self.count, "+" if truncated else "", o.max_members))
if self.nested:
self.add("nested-archives", 1, "%d member(s) look like archives; scan them separately" % self.nested)
# ---------------------------------------------------------------- readers
def eocd_info(f, size):
"""(entries, cd_size) from the zip end-of-central-directory, or None if not found."""
tail_len = min(size, 65536 + 22 + 20 + 56)
f.seek(size - tail_len)
tail = f.read(tail_len)
pos = tail.rfind(b"PK\x05\x06")
if pos < 0 or len(tail) - pos < 22:
return None
_sig, _d, _cd, _n_this, entries, cd_size, _off, _clen = struct.unpack("<4s4H2LH", tail[pos:pos + 22])
if entries == 0xFFFF or cd_size == 0xFFFFFFFF:
loc = tail.rfind(b"PK\x06\x07", 0, pos)
if loc >= 0 and len(tail) - loc >= 20:
_s, _disk, z64_off, _n = struct.unpack("<4sLQL", tail[loc:loc + 20])
if 0 <= z64_off < size:
f.seek(z64_off)
rec = f.read(56)
if len(rec) == 56 and rec[:4] == b"PK\x06\x06":
entries = struct.unpack("<Q", rec[32:40])[0]
cd_size = struct.unpack("<Q", rec[40:48])[0]
return entries, cd_size
def scan_zip(path, size, opts, an):
"""Feed members into the analyzer. Returns True if the scan was truncated."""
with open(path, "rb") as f:
info = eocd_info(f, size)
if info is not None:
entries, cd_size = info
if cd_size > MAX_CD_BYTES or entries > opts.scan_members:
an.count = entries if entries <= 10 ** 12 else 10 ** 12
an.add("scan-truncated", 2,
"central directory declares %d entries / %d bytes; not enumerated (limit %d entries)"
% (entries, cd_size, opts.scan_members))
return True
try:
zf = zipfile.ZipFile(path)
except zipfile.BadZipFile as e:
raise ArchiveError("bad zip file: %s" % e)
except (UnicodeDecodeError, ValueError, NotImplementedError) as e:
raise ArchiveError("unreadable zip directory: %s" % e)
with zf:
for idx, zi in enumerate(zf.infolist()):
unix = zi.create_system == 3
mode = (zi.external_attr >> 16) & 0xFFFF if unix else None
fmt = stat.S_IFMT(mode) if mode else 0
name = getattr(zi, "orig_filename", zi.filename)
target = None
note = None
if fmt == stat.S_IFLNK:
kind = "symlink"
if zi.flag_bits & 1:
note = "encrypted symlink: target unreadable"
elif zi.file_size > MAX_LINK_TARGET:
note = "symlink target is over %d bytes" % MAX_LINK_TARGET
else:
try:
with zf.open(zi) as fh:
target = fh.read(MAX_LINK_TARGET + 1).decode("utf-8", "replace")
except Exception as e: # corrupt data, bad CRC, unsupported method
note = "symlink target unreadable (%s)" % type(e).__name__
elif fmt in (stat.S_IFCHR, stat.S_IFBLK):
kind = "device"
elif fmt in (stat.S_IFIFO, stat.S_IFSOCK):
kind = "special"
elif fmt == stat.S_IFDIR or name.endswith("/"):
kind = "dir"
else:
kind = "file"
an.feed(Member(idx, name, kind, size=zi.file_size, csize=zi.compress_size, mode=mode,
target=target, encrypted=bool(zi.flag_bits & 1), offset=zi.header_offset,
target_note=note))
if idx + 1 >= opts.scan_members:
an.add("scan-truncated", 2, "stopped after %d members (limit)" % opts.scan_members)
return True
return False
class _Decomp(object):
"""Forward-only, byte-capped decompressing reader with seek/tell for tarfile."""
def __init__(self, raw, kind, cap):
self.raw = raw
self.kind = kind
self.cap = cap
self.pos = 0
self.pending = b""
self.d = None
self.members = 0
self.finished = False
def _new(self):
if self.kind == "gz":
return zlib.decompressobj(wbits=31)
if self.kind == "bz2":
return bz2.BZ2Decompressor()
return lzma.LZMADecompressor(memlimit=LZMA_MEMLIMIT)
def tell(self):
return self.pos
def _fill(self, n):
out = []
got = 0
while got < n and not self.finished:
if self.d is None:
if not self.pending:
self.pending = self.raw.read(65536)
if not self.pending:
self.finished = True
break
if self.members and self.kind == "gz" and not self.pending.startswith(b"\x1f\x8b"):
self.finished = True # trailing garbage after the last gzip member
break
self.d = self._new()
want = n - got
try:
if self.kind == "gz":
chunk = self.d.decompress(self.pending, want)
self.pending = self.d.unconsumed_tail
if self.d.eof:
self.pending = self.d.unused_data
self.d = None
self.members += 1
elif not chunk and not self.pending:
more = self.raw.read(65536)
if not more:
raise ArchiveError("truncated gzip stream")
self.pending = more
else:
if self.d.needs_input:
data = self.pending or self.raw.read(65536)
self.pending = b""
if not data:
raise ArchiveError("truncated %s stream" % self.kind)
else:
data = b""
chunk = self.d.decompress(data, want)
if self.d.eof:
self.pending = self.d.unused_data
self.d = None
self.members += 1
except ArchiveError:
raise
except (zlib.error, OSError, EOFError, ValueError) as e:
raise ArchiveError("corrupt %s stream: %s" % (self.kind, e))
except Exception as e: # lzma.LZMAError and friends
raise ArchiveError("corrupt %s stream: %s" % (self.kind, e))
if chunk:
out.append(chunk)
got += len(chunk)
data = b"".join(out)
self.pos += len(data)
if self.pos > self.cap:
raise ScanLimit()
return data
def read(self, n=-1):
if n is None or n < 0 or n > MAX_HEADER_READ:
raise ArchiveError("oversized tar header read refused")
return self._fill(n)
def seek(self, target, whence=0):
if whence != 0:
raise ArchiveError("unsupported seek")
if target < self.pos:
raise ArchiveError("backward seek in a compressed stream")
left = target - self.pos
while left > 0:
chunk = self._fill(min(left, 1 * MIB))
if not chunk:
break
left -= len(chunk)
return self.pos
class _Plain(object):
"""Seekable plain file with a limit on a single read, for uncompressed tar."""
def __init__(self, raw):
self.raw = raw
def read(self, n=-1):
if n is None or n < 0 or n > MAX_HEADER_READ:
raise ArchiveError("oversized tar header read refused")
return self.raw.read(n)
def seek(self, pos, whence=0):
return self.raw.seek(pos, whence)
def tell(self):
return self.raw.tell()
def detect_format(path):
with open(path, "rb") as f:
head = f.read(512)
if head[:4] in (b"PK\x03\x04", b"PK\x05\x06", b"PK\x07\x08"):
return "zip"
if head[:2] == b"\x1f\x8b":
return "tar.gz"
if head[:3] == b"BZh":
return "tar.bz2"
if head[:6] == b"\xfd7zXZ\x00":
return "tar.xz"
if head[257:262] == b"ustar":
return "tar"
if zipfile.is_zipfile(path):
return "zip"
if len(head) >= 512:
try:
tarfile.TarInfo.frombuf(head[:512], "utf-8", "surrogateescape")
return "tar"
except Exception:
pass
return None
def tar_kind(ti):
if ti.isdir():
return "dir"
if ti.issym():
return "symlink"
if ti.islnk():
return "hardlink"
if ti.ischr() or ti.isblk():
return "device"
if ti.isreg():
return "file"
return "special"
def scan_tar(path, fmt, opts, an):
truncated = False
with open(path, "rb") as raw:
if fmt == "tar":
reader = _Plain(raw)
else:
kind = {"tar.gz": "gz", "tar.bz2": "bz2", "tar.xz": "xz"}[fmt]
if kind == "xz" and lzma is None:
raise ArchiveError("this Python has no lzma support")
reader = _Decomp(raw, kind, opts.max_scan)
try:
try:
tf = tarfile.open(fileobj=reader, mode="r:")
except tarfile.ReadError as e:
raise ArchiveError("not a readable tar archive: %s" % e)
idx = 0
while True:
try:
ti = tf.next()
except tarfile.ReadError as e:
if idx == 0:
raise ArchiveError("not a readable tar archive: %s" % e)
raise ArchiveError("tar stream damaged after member %d: %s" % (idx, e))
except (UnicodeError, ValueError, OverflowError, struct.error) as e:
raise ArchiveError("bad tar header after member %d: %s" % (idx, e))
if ti is None:
break
kind_ = tar_kind(ti)
target = ti.linkname if kind_ in ("symlink", "hardlink") else None
an.feed(Member(idx, ti.name, kind_, size=ti.size if kind_ == "file" else 0,
mode=ti.mode, target=target))
idx += 1
if idx >= opts.scan_members:
an.add("scan-truncated", 2, "stopped after %d members (limit)" % opts.scan_members)
truncated = True
break
except ScanLimit:
an.add("scan-truncated", 2,
"stopped after reading %d decompressed bytes (limit; use --max-scan to raise)" % opts.max_scan)
truncated = True
return truncated
def inspect(path, opts):
"""Inspect one archive; returns a report dict. Never raises for hostile input."""
rep = {"path": path, "format": None, "size": None, "members": 0,
"uncompressed_declared": 0, "findings": [], "dropped_findings": 0,
"truncated": False, "error": None}
try:
st = os.stat(path)
if not stat.S_ISREG(st.st_mode):
raise ArchiveError("not a regular file")
rep["size"] = st.st_size
if st.st_size == 0:
raise ArchiveError("empty file")
fmt = detect_format(path)
if fmt is None:
raise ArchiveError("unrecognised archive format (supported: zip, tar, tar.gz, tar.bz2, tar.xz)")
rep["format"] = fmt
an = Analyzer(opts, st.st_size)
truncated = False
try:
if fmt == "zip":
truncated = scan_zip(path, st.st_size, opts, an)
else:
truncated = scan_tar(path, fmt, opts, an)
except ArchiveError as e:
rep["error"] = str(e)
except (OSError, EOFError, zlib.error) as e:
rep["error"] = "read error: %s" % (e.__class__.__name__,)
except MemoryError:
rep["error"] = "out of memory while reading headers"
an.finish(truncated)
rep["members"] = an.count
rep["uncompressed_declared"] = an.total
rep["truncated"] = truncated
rep["findings"] = an.findings
rep["dropped_findings"] = an.dropped
except ArchiveError as e:
rep["error"] = str(e)
except OSError as e:
rep["error"] = "cannot open: %s" % (e.strerror or e.__class__.__name__)
return rep
def filter_findings(rep, minsev):
rep["findings"] = [f for f in rep["findings"] if SEVERITIES[f["severity"].lower()] >= minsev]
return rep
# ---------------------------------------------------------------- output
def render_text(reports, out):
for rep in reports:
out.write("%s: %s, %s members, %s bytes declared uncompressed\n" % (
safe(rep["path"]), rep["format"] or "unknown format", rep["members"], rep["uncompressed_declared"]))
if rep["error"]:
out.write(" ERROR %s\n" % safe(rep["error"]))
if not rep["findings"] and not rep["error"]:
out.write(" clean\n")
for f in rep["findings"]:
where = ""
if f["member"] is not None:
where = "[#%d %s] " % (f["index"], safe(f["member"], 120))
out.write(" %-6s %-22s %s%s\n" % (f["severity"], f["rule"], where, safe(f["detail"], 300)))
if rep["dropped_findings"]:
out.write(" ... %d more findings not shown (--max-findings)\n" % rep["dropped_findings"])
def build_parser():
p = argparse.ArgumentParser(
prog="zipcheck",
description="Inspect zip/tar/tar.gz/tar.bz2/tar.xz archives for zip-slip, hostile links, special "
"files, setuid bits, decompression bombs and odd names, without extracting anything.",
epilog="Exit codes: 0 clean, 1 findings, 2 usage or input error.")
p.add_argument("archives", nargs="+", metavar="ARCHIVE")
p.add_argument("--json", action="store_true", help="machine-readable output")
p.add_argument("--max-total", type=parse_size, default=DEFAULT_MAX_TOTAL,
help="flag if declared uncompressed total exceeds this (default 1G)")
p.add_argument("--max-ratio", type=positive_int, default=DEFAULT_MAX_RATIO,
help="flag compression ratio above N:1 (default 100)")
p.add_argument("--max-members", type=positive_int, default=DEFAULT_MAX_MEMBERS,
help="flag more than N members (default 10000)")
p.add_argument("--max-scan", type=parse_size, default=DEFAULT_MAX_SCAN,
help="hard cap on decompressed bytes read from a tar stream (default 1G)")
p.add_argument("--scan-members", type=positive_int, default=DEFAULT_SCAN_MEMBERS,
help="hard cap on members enumerated (default 200000)")
p.add_argument("--max-findings", type=positive_int, default=DEFAULT_MAX_FINDINGS,
help="keep at most N findings per archive (default 1000)")
p.add_argument("--min-severity", choices=sorted(SEVERITIES), default="low",
help="only report findings at or above this severity (default low)")
p.add_argument("--version", action="version", version="zipcheck " + __version__)
return p
def main(argv=None):
parser = build_parser()
try:
opts = parser.parse_args(argv)
except SystemExit as e:
return 2 if e.code not in (0, None) else 0
minsev = SEVERITIES[opts.min_severity]
reports = [filter_findings(inspect(p, opts), minsev) for p in opts.archives]
any_error = any(r["error"] for r in reports)
any_findings = any(r["findings"] for r in reports)
code = 2 if any_error else (1 if any_findings else 0)
if opts.json:
json.dump({"tool": "zipcheck", "version": __version__, "exit_code": code,
"archives": reports}, sys.stdout, indent=2)
sys.stdout.write("\n")
else:
render_text(reports, sys.stdout)
return code
if __name__ == "__main__":
sys.exit(main())