/
stream_unzip.py
610 lines (463 loc) · 21.5 KB
/
stream_unzip.py
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
from functools import partial
from struct import Struct
import asyncio
import bz2
import zlib
from Crypto.Cipher import AES
from Crypto.Hash import HMAC, SHA1
from Crypto.Util import Counter
from Crypto.Protocol.KDF import PBKDF2
from stream_inflate import stream_inflate64
def stream_unzip(zipfile_chunks, password=None, chunk_size=65536, allow_zip64=True):
local_file_header_signature = b'PK\x03\x04'
local_file_header_struct = Struct('<H2sHHHIIIHH')
zip64_compressed_size = 0xFFFFFFFF
zip64_size_signature = b'\x01\x00'
aes_extra_signature = b'\x01\x99'
central_directory_signature = b'PK\x01\x02'
end_of_central_directory_signature = b'PK\x05\x06'
unsigned_short = Struct('<H')
unsigned_long_long = Struct('<Q')
dd_optional_signature = b'PK\x07\x08'
dd_struct_32 = Struct('<0sIII4s')
dd_struct_32_with_sig = Struct('<4sIII4s')
dd_struct_64 = Struct('<0sIQQ4s')
dd_struct_64_with_sig = Struct('<4sIQQ4s')
def next_or_truncated_error(it):
try:
return next(it)
except StopIteration:
raise TruncatedDataError from None
def get_byte_readers(iterable):
# Return functions to return/"replace" bytes from/to the iterable
# - _yield_all: yields chunks as they come up (often for a "body")
# - _get_num: returns a single `bytes` of a given length
# - _return_num_unused: puts a number of "unused" bytes "back", to be retrieved by a yield/get call
# - _return_bytes_unused: return a bytes instance "back" into the stream, to be retrieved later
# - _get_offset_from_start: get the zero-indexed offset from the start of the stream
chunk = b''
offset = 0
offset_from_start = 0
queue = list() # Will typically have at most 1 element, so a list is fine
it = iter(iterable)
def _next():
try:
return queue.pop(0)
except IndexError:
return (next_or_truncated_error(it), 0)
def _yield_num(num):
nonlocal chunk, offset, offset_from_start
while num:
if offset == len(chunk):
chunk, offset = _next()
to_yield = min(num, len(chunk) - offset, chunk_size)
offset = offset + to_yield
num -= to_yield
offset_from_start += to_yield
yield chunk[offset - to_yield:offset]
def _yield_all():
try:
yield from _yield_num(float('inf'))
except TruncatedDataError:
pass
def _get_num(num):
return b''.join(_yield_num(num))
def _return_num_unused(num_unused):
nonlocal offset, offset_from_start
offset -= num_unused
offset_from_start -= num_unused
def _return_bytes_unused(bytes_unused):
nonlocal chunk, offset, offset_from_start
queue.insert(0, (chunk, offset))
chunk = bytes_unused
offset = 0
offset_from_start -= len(bytes_unused)
def _get_offset_from_start():
return offset_from_start
return _yield_all, _get_num, _return_num_unused, _return_bytes_unused, _get_offset_from_start
def get_decompressor_none(num_bytes):
num_decompressed = 0
num_unused = 0
def _decompress(compressed_chunk):
nonlocal num_decompressed, num_unused
to_yield = min(len(compressed_chunk), num_bytes - num_decompressed)
num_decompressed += to_yield
num_unused = len(compressed_chunk) - to_yield
yield compressed_chunk[:to_yield]
def _is_done():
return num_decompressed == num_bytes
def _num_unused():
return num_unused
return _decompress, _is_done, _num_unused
def get_decompressor_deflate():
dobj = zlib.decompressobj(wbits=-zlib.MAX_WBITS)
def _decompress_single(compressed_chunk):
try:
return dobj.decompress(compressed_chunk, chunk_size)
except zlib.error as e:
raise DeflateError() from e
def _decompress(compressed_chunk):
uncompressed_chunk = _decompress_single(compressed_chunk)
if uncompressed_chunk:
yield uncompressed_chunk
while dobj.unconsumed_tail and not dobj.eof:
uncompressed_chunk = _decompress_single(dobj.unconsumed_tail)
if uncompressed_chunk:
yield uncompressed_chunk
def _is_done():
return dobj.eof
def _num_unused():
return len(dobj.unused_data)
return _decompress, _is_done, _num_unused
def get_decompressor_deflate64():
uncompressed_chunks, is_done, num_bytes_unconsumed = stream_inflate64()
def _decompress(compressed_chunk):
yield from uncompressed_chunks((compressed_chunk,))
return _decompress, is_done, num_bytes_unconsumed
def get_decompressor_bz2():
dobj = bz2.BZ2Decompressor()
def _decompress_single(compressed_chunk):
try:
return dobj.decompress(compressed_chunk, chunk_size)
except OSError as e:
raise BZ2Error() from e
def _decompress(compressed_chunk):
uncompressed_chunk = _decompress_single(compressed_chunk)
if uncompressed_chunk:
yield uncompressed_chunk
while not dobj.eof:
uncompressed_chunk = _decompress_single(b'')
if not uncompressed_chunk:
break
yield uncompressed_chunk
def _is_done():
return dobj.eof
def _num_unused():
return len(dobj.unused_data)
return _decompress, _is_done, _num_unused
def yield_file(yield_all, get_num, return_num_unused, return_bytes_unused, get_offset_from_start):
def get_flag_bits(flags):
for b in flags:
for i in range(8):
yield (b >> i) & 1
def parse_extra(extra):
extra_offset = 0
while extra_offset <= len(extra) - 4:
extra_signature = extra[extra_offset:extra_offset+2]
extra_offset += 2
extra_data_size, = unsigned_short.unpack(extra[extra_offset:extra_offset+2])
extra_offset += 2
extra_data = extra[extra_offset:extra_offset+extra_data_size]
extra_offset += extra_data_size
yield (extra_signature, extra_data)
def get_extra_value(extra, if_true, signature, exception_if_missing, min_length, exception_if_too_short):
value = None
if if_true:
try:
value = extra[signature]
except KeyError:
if exception_if_missing:
raise exception_if_missing()
else:
if len(value) < min_length:
raise exception_if_too_short()
return value
def decrypt_weak_decompress(chunks, decompress, is_done, num_unused):
key_0 = 305419896
key_1 = 591751049
key_2 = 878082192
crc32 = zlib.crc32
bytes_c = bytes
def update_keys(byte):
nonlocal key_0, key_1, key_2
key_0 = ~crc32(bytes_c((byte,)), ~key_0) & 0xFFFFFFFF
key_1 = (key_1 + (key_0 & 0xFF)) & 0xFFFFFFFF
key_1 = ((key_1 * 134775813) + 1) & 0xFFFFFFFF
key_2 = ~crc32(bytes_c((key_1 >> 24,)), ~key_2) & 0xFFFFFFFF
def decrypt(chunk):
chunk = bytearray(chunk)
for i, byte in enumerate(chunk):
temp = key_2 | 2
byte ^= ((temp * (temp ^ 1)) >> 8) & 0xFF
update_keys(byte)
chunk[i] = byte
return bytes(chunk)
for byte in password:
update_keys(byte)
encryption_header = decrypt(get_num(12))
check_password_byte = \
(mod_time >> 8) if has_data_descriptor else \
(crc_32_expected >> 24)
if encryption_header[11] != check_password_byte:
raise IncorrectZipCryptoPasswordError()
while not is_done():
yield from decompress(decrypt(next_or_truncated_error(chunks)))
return_num_unused(num_unused())
def decrypt_aes_decompress(chunks, decompress, is_done, num_unused, key_length_raw):
try:
key_length, salt_length = {1: (16, 8), 2: (24, 12), 3: (32, 16)}[key_length_raw]
except KeyError:
raise InvalidAESKeyLengthError(key_length_raw)
salt = get_num(salt_length)
password_verification_length = 2
keys = PBKDF2(password, salt, 2 * key_length + password_verification_length, 1000)
if keys[-password_verification_length:] != get_num(password_verification_length):
raise IncorrectAESPasswordError()
decrypter = AES.new(
keys[:key_length], AES.MODE_CTR,
counter=Counter.new(nbits=128, little_endian=True)
)
hmac = HMAC.new(keys[key_length:key_length*2], digestmod=SHA1)
while not is_done():
chunk = next_or_truncated_error(chunks)
yield from decompress(decrypter.decrypt(chunk))
hmac.update(chunk[:len(chunk) - num_unused()])
return_num_unused(num_unused())
if get_num(10) != hmac.digest()[:10]:
raise HMACIntegrityError()
def decrypt_none_decompress(chunks, decompress, is_done, num_unused):
while not is_done():
yield from decompress(next_or_truncated_error(chunks))
return_num_unused(num_unused())
def read_data_and_count_and_crc32(chunks):
offset_1 = None
offset_2 = None
crc_32_actual = zlib.crc32(b'')
l = 0
def _iter():
nonlocal offset_1, offset_2, crc_32_actual, l
offset_1 = get_offset_from_start()
for chunk in chunks:
crc_32_actual = zlib.crc32(chunk, crc_32_actual)
l += len(chunk)
yield chunk
offset_2 = get_offset_from_start()
return _iter(), lambda: offset_2 - offset_1, lambda: crc_32_actual, lambda: l
def checked_from_local_header(chunks, is_aes_2_encrypted, get_crc_32, get_compressed_size, get_uncompressed_size):
yield from chunks
crc_32_data = get_crc_32()
compressed_size_data = get_compressed_size()
uncompressed_size_data = get_uncompressed_size()
if not is_aes_2_encrypted and crc_32_expected != crc_32_data:
raise CRC32IntegrityError()
if compressed_size_data != compressed_size:
raise CompressedSizeIntegrityError()
if uncompressed_size_data != uncompressed_size:
raise UncompressedSizeIntegrityError()
def checked_from_data_descriptor(chunks, is_sure_zip64, is_aes_2_encrypted, get_crc_32, get_compressed_size, get_uncompressed_size):
# The format of the data descriptor is unfortunately not known with absolute certainty in all cases
# so we we use a heuristic to detect it - using the known crc32 value, compressed size, uncompressed
# size of the data, and possible signature of the next section in the stream. There are 4 possible
# formats, and we choose the longest one that matches
#
# Strongly inspired by Mark Adler's unzip - see his reasoning for this at
# https://github.com/madler/unzip/commit/af0d07f95809653b669d88aa0f424c6d5aa48ba0
yield from chunks
crc_32_data = get_crc_32()
compressed_size_data = get_compressed_size()
uncompressed_size_data = get_uncompressed_size()
best_matches = (False, False, False, False, False)
must_treat_as_zip64 = is_sure_zip64 or compressed_size_data > 0xFFFFFFFF or uncompressed_size_data > 0xFFFFFFFF
checks = ((
(dd_struct_64_with_sig, dd_optional_signature),
(dd_struct_64, b''),
) if allow_zip64 else ()) + ((
(dd_struct_32_with_sig, dd_optional_signature),
(dd_struct_32, b''),
) if not must_treat_as_zip64 else ())
dd = get_num(checks[0][0].size)
for dd_struct, expected_signature in checks:
signature_dd, crc_32_dd, compressed_size_dd, uncompressed_size_dd, next_signature = dd_struct.unpack(dd[:dd_struct.size])
matches = (
signature_dd == expected_signature,
is_aes_2_encrypted or crc_32_dd == crc_32_data,
compressed_size_dd == compressed_size_data,
uncompressed_size_dd == uncompressed_size_data,
next_signature in (local_file_header_signature, central_directory_signature),
)
best_matches = max(best_matches, matches, key=lambda t: t.count(True))
if best_matches == (True, True, True, True, True):
break
if not best_matches[0]:
raise UnexpectedSignatureError()
if not best_matches[1]:
raise CRC32IntegrityError()
if not best_matches[2]:
raise CompressedSizeIntegrityError()
if not best_matches[3]:
raise UncompressedSizeIntegrityError()
if not best_matches[4]:
raise UnexpectedSignatureError(next_signature)
return_bytes_unused(dd[dd_struct.size - 4:]) # 4 is the length of next signature we have already taken
version, flags, compression_raw, mod_time, mod_date, crc_32_expected, compressed_size_raw, uncompressed_size_raw, file_name_len, extra_field_len = \
local_file_header_struct.unpack(get_num(local_file_header_struct.size))
flag_bits = tuple(get_flag_bits(flags))
if (
flag_bits[4] # Enhanced deflating
or flag_bits[5] # Compressed patched
or flag_bits[6] # Strong encrypted
or flag_bits[13] # Masked header values
):
raise UnsupportedFlagsError(flag_bits)
file_name = get_num(file_name_len)
extra = dict(parse_extra(get_num(extra_field_len)))
is_weak_encrypted = flag_bits[0] and compression_raw != 99
is_aes_encrypted = flag_bits[0] and compression_raw == 99
aes_extra = get_extra_value(extra, is_aes_encrypted, aes_extra_signature, MissingAESExtraError, 7, TruncatedAESExtraError)
is_aes_2_encrypted = is_aes_encrypted and aes_extra[0:2] == b'\x02\x00'
if is_weak_encrypted and password is None:
raise MissingZipCryptoPasswordError()
if is_aes_encrypted and password is None:
raise MissingAESPasswordError()
compression = \
unsigned_short.unpack(aes_extra[5:7])[0] if is_aes_encrypted else \
compression_raw
if compression not in (0, 8, 9, 12):
raise UnsupportedCompressionTypeError(compression)
has_data_descriptor = flag_bits[3]
might_be_zip64 = compressed_size_raw == zip64_compressed_size and uncompressed_size_raw == zip64_compressed_size
zip64_extra = get_extra_value(extra, might_be_zip64, zip64_size_signature, False, 16, TruncatedZip64ExtraError)
is_sure_zip64 = bool(zip64_extra)
if not allow_zip64 and is_sure_zip64:
raise UnsupportedZip64Error()
compressed_size = \
None if has_data_descriptor and compression in (8, 9, 12) else \
unsigned_long_long.unpack(zip64_extra[8:16])[0] if is_sure_zip64 else \
compressed_size_raw
uncompressed_size = \
None if has_data_descriptor and compression in (8, 9, 12) else \
unsigned_long_long.unpack(zip64_extra[:8])[0] if is_sure_zip64 else \
uncompressed_size_raw
decompressor = \
get_decompressor_none(uncompressed_size) if compression == 0 else \
get_decompressor_deflate() if compression == 8 else \
get_decompressor_deflate64() if compression == 9 else \
get_decompressor_bz2()
decompressed_bytes = \
decrypt_weak_decompress(yield_all(), *decompressor) if is_weak_encrypted else \
decrypt_aes_decompress(yield_all(), *decompressor, key_length_raw=aes_extra[4]) if is_aes_encrypted else \
decrypt_none_decompress(yield_all(), *decompressor)
counted_decompressed_bytes, get_compressed_size, get_crc_32_actual, get_uncompressed_size = read_data_and_count_and_crc32(decompressed_bytes)
checked_bytes = \
checked_from_data_descriptor(counted_decompressed_bytes, is_sure_zip64, is_aes_2_encrypted, get_crc_32_actual, get_compressed_size, get_uncompressed_size) if has_data_descriptor else \
checked_from_local_header(counted_decompressed_bytes, is_aes_2_encrypted, get_crc_32_actual, get_compressed_size, get_uncompressed_size)
return file_name, uncompressed_size, checked_bytes
def all():
yield_all, get_num, return_num_unused, return_bytes_unused, get_offset_from_start = get_byte_readers(zipfile_chunks)
while True:
signature = get_num(len(local_file_header_signature))
if signature == local_file_header_signature:
yield yield_file(yield_all, get_num, return_num_unused, return_bytes_unused, get_offset_from_start)
elif signature in (central_directory_signature, end_of_central_directory_signature):
for _ in yield_all():
pass
break
else:
raise UnexpectedSignatureError(signature)
for file_name, file_size, unzipped_chunks in all():
yield file_name, file_size, unzipped_chunks
for _ in unzipped_chunks:
raise UnfinishedIterationError()
async def async_stream_unzip(chunks, *args, **kwargs):
async def to_async_iterable(sync_iterable):
# asyncio.to_thread is not available until Python 3.9, and StopIteration doesn't get
# propagated by run_in_executor, so we use a sentinel to detect the end of the iterable
done = object()
it = iter(sync_iterable)
# contextvars are not available until Python 3.7
try:
import contextvars
except ImportError:
get_args = lambda: (next, it, done)
else:
get_args = lambda: (contextvars.copy_context().run, next, it, done)
while True:
value = await loop.run_in_executor(None, *get_args())
if value is done:
break
yield value
def to_sync_iterable(async_iterable):
# The built-in aiter and anext functions are not available until Python 3.10
async_it = async_iterable.__aiter__()
while True:
try:
value = asyncio.run_coroutine_threadsafe(async_it.__anext__(), loop).result()
except StopAsyncIteration:
break
yield value
# get_running_loop is preferred, but isn't available until Python 3.7
try:
loop = asyncio.get_running_loop()
except:
loop = asyncio.get_event_loop()
unzipped_chunks = stream_unzip(to_sync_iterable(chunks), *args, **kwargs)
async for name, size, chunks in to_async_iterable(unzipped_chunks):
yield name, size, to_async_iterable(chunks)
class UnzipError(Exception):
pass
class InvalidOperationError(UnzipError):
pass
class UnfinishedIterationError(InvalidOperationError):
pass
class UnzipValueError(UnzipError, ValueError):
pass
class DataError(UnzipValueError):
pass
class UncompressError(UnzipValueError):
pass
class DeflateError(UncompressError):
pass
class BZ2Error(UncompressError):
pass
class UnsupportedFeatureError(DataError):
pass
class UnsupportedFlagsError(UnsupportedFeatureError):
pass
class UnsupportedCompressionTypeError(UnsupportedFeatureError):
pass
class UnsupportedZip64Error(UnsupportedFeatureError):
pass
class TruncatedDataError(DataError):
pass
class UnexpectedSignatureError(DataError):
pass
class MissingExtraError(DataError):
pass
class MissingAESExtraError(MissingExtraError):
pass
class TruncatedExtraError(DataError):
pass
class TruncatedZip64ExtraError(TruncatedExtraError):
pass
class TruncatedAESExtraError(TruncatedExtraError):
pass
class InvalidExtraError(TruncatedExtraError):
pass
class InvalidAESKeyLengthError(TruncatedExtraError):
pass
class IntegrityError(DataError):
pass
class HMACIntegrityError(IntegrityError):
pass
class CRC32IntegrityError(IntegrityError):
pass
class SizeIntegrityError(IntegrityError):
pass
class UncompressedSizeIntegrityError(SizeIntegrityError):
pass
class CompressedSizeIntegrityError(SizeIntegrityError):
pass
class PasswordError(UnzipValueError):
pass
class MissingPasswordError(UnzipValueError):
pass
class MissingZipCryptoPasswordError(MissingPasswordError):
pass
class MissingAESPasswordError(MissingPasswordError):
pass
class IncorrectPasswordError(PasswordError):
pass
class IncorrectZipCryptoPasswordError(IncorrectPasswordError):
pass
class IncorrectAESPasswordError(IncorrectPasswordError):
pass