Skip to content

Commit ade4b51

Browse files
fix: raise clear errors on corrupt or malicious DOCX parsing
1 parent e454546 commit ade4b51

1 file changed

Lines changed: 15 additions & 3 deletions

File tree

src/docx/opc/phys_pkg.py

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
"""Provides a general interface to a `physical` OPC package, such as a zip file."""
22

33
import os
4-
from zipfile import ZIP_DEFLATED, ZipFile, is_zipfile
4+
import zlib
5+
from zipfile import ZIP_DEFLATED, BadZipFile, ZipFile, is_zipfile
56

67
from docx.opc.exceptions import PackageNotFoundError
78
from docx.opc.packuri import CONTENT_TYPES_URI
@@ -73,14 +74,25 @@ class _ZipPkgReader(PhysPkgReader):
7374

7475
def __init__(self, pkg_file):
7576
super(_ZipPkgReader, self).__init__()
76-
self._zipf = ZipFile(pkg_file, "r")
77+
try:
78+
self._zipf = ZipFile(pkg_file, "r")
79+
except (BadZipFile, zlib.error, EOFError, RuntimeError):
80+
raise PackageNotFoundError(
81+
"Package not found or not a valid zip archive: '%s'" % pkg_file
82+
)
7783

7884
def blob_for(self, pack_uri):
7985
"""Return blob corresponding to `pack_uri`.
8086
8187
Raises |ValueError| if no matching member is present in zip archive.
8288
"""
83-
return self._zipf.read(pack_uri.membername)
89+
try:
90+
return self._zipf.read(pack_uri.membername)
91+
except (KeyError, zlib.error, EOFError, RuntimeError):
92+
raise ValueError(
93+
"Could not read member '%s' from package (corrupt or missing?)"
94+
% pack_uri.membername
95+
)
8496

8597
def close(self):
8698
"""Close the zip archive, releasing any resources it is using."""

0 commit comments

Comments
 (0)