33import logging
44import zipfile
55
6- logger = logging . getLogger ( __name__ )
6+ from django . conf import settings
77
8- # Zip bomb protection limits
9- MAX_ZIP_MEMBERS = 1000
10- MAX_ZIP_MEMBER_SIZE = 512 * 1024 * 1024 # 512 MB per member (uncompressed)
11- MAX_ZIP_TOTAL_SIZE = 1 * 1024 * 1024 * 1024 # 1 GB total (uncompressed)
12- MAX_ZIP_RATIO = 100 # max compression ratio (uncompressed / compressed)
8+ logger = logging .getLogger (__name__ )
139
1410
1511def safe_open_zip (file ):
@@ -32,32 +28,32 @@ def safe_open_zip(file):
3228
3329 infos = zf .infolist ()
3430
35- if len (infos ) > MAX_ZIP_MEMBERS :
31+ if len (infos ) > settings . MAX_ZIP_MEMBERS :
3632 zf .close ()
37- msg = f"Zip file contains { len (infos )} members, exceeding the limit of { MAX_ZIP_MEMBERS } ."
33+ msg = f"Zip file contains { len (infos )} members, exceeding the limit of { settings . MAX_ZIP_MEMBERS } ."
3834 raise ValueError (msg )
3935
4036 total_size = 0
4137 for info in infos :
42- if info .file_size > MAX_ZIP_MEMBER_SIZE :
38+ if info .file_size > settings . MAX_ZIP_MEMBER_SIZE :
4339 zf .close ()
4440 msg = (
4541 f"Zip member '{ info .filename } ' has uncompressed size { info .file_size } bytes, "
46- f"exceeding the per-member limit of { MAX_ZIP_MEMBER_SIZE } bytes."
42+ f"exceeding the per-member limit of { settings . MAX_ZIP_MEMBER_SIZE } bytes."
4743 )
4844 raise ValueError (msg )
49- if info .compress_size > 0 and (info .file_size / info .compress_size ) > MAX_ZIP_RATIO :
45+ if info .compress_size > 0 and (info .file_size / info .compress_size ) > settings . MAX_ZIP_RATIO :
5046 zf .close ()
5147 ratio = info .file_size / info .compress_size
5248 msg = (
5349 f"Zip member '{ info .filename } ' has a compression ratio of "
54- f"{ ratio :.1f} :1, exceeding the limit of { MAX_ZIP_RATIO } :1."
50+ f"{ ratio :.1f} :1, exceeding the limit of { settings . MAX_ZIP_RATIO } :1."
5551 )
5652 raise ValueError (msg )
5753 total_size += info .file_size
58- if total_size > MAX_ZIP_TOTAL_SIZE :
54+ if total_size > settings . MAX_ZIP_TOTAL_SIZE :
5955 zf .close ()
60- msg = f"Zip file total uncompressed size exceeds the limit of { MAX_ZIP_TOTAL_SIZE } bytes."
56+ msg = f"Zip file total uncompressed size exceeds the limit of { settings . MAX_ZIP_TOTAL_SIZE } bytes."
6157 raise ValueError (msg )
6258
6359 return zf
0 commit comments