Skip to content

Commit 7bff4d3

Browse files
ambvjdevries3133
andauthored
[3.9] bpo-39039: tarfile raises descriptive exception from zlib.error (GH-27766) (GH-28614)
* during tarfile parsing, a zlib error indicates invalid data * tarfile.open now raises a descriptive exception from the zlib error * this makes it clear to the user that they may be trying to open a corrupted tar file. (cherry picked from commit b6fe857) Co-authored-by: Jack DeVries <[email protected]>
1 parent c6b5cea commit 7bff4d3

File tree

3 files changed

+25
-0
lines changed

3 files changed

+25
-0
lines changed

Lib/tarfile.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2345,6 +2345,15 @@ def next(self):
23452345
raise ReadError(str(e))
23462346
except SubsequentHeaderError as e:
23472347
raise ReadError(str(e))
2348+
except Exception as e:
2349+
try:
2350+
import zlib
2351+
if isinstance(e, zlib.error):
2352+
raise ReadError(f'zlib error: {e}')
2353+
else:
2354+
raise e
2355+
except ImportError:
2356+
raise e
23482357
break
23492358

23502359
if tarinfo is not None:

Lib/test/test_tarfile.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@
1818
import gzip
1919
except ImportError:
2020
gzip = None
21+
try:
22+
import zlib
23+
except ImportError:
24+
zlib = None
2125
try:
2226
import bz2
2327
except ImportError:
@@ -686,6 +690,16 @@ def test_parallel_iteration(self):
686690
self.assertEqual(m1.offset, m2.offset)
687691
self.assertEqual(m1.get_info(), m2.get_info())
688692

693+
@unittest.skipIf(zlib is None, "requires zlib")
694+
def test_zlib_error_does_not_leak(self):
695+
# bpo-39039: tarfile.open allowed zlib exceptions to bubble up when
696+
# parsing certain types of invalid data
697+
with unittest.mock.patch("tarfile.TarInfo.fromtarfile") as mock:
698+
mock.side_effect = zlib.error
699+
with self.assertRaises(tarfile.ReadError):
700+
tarfile.open(self.tarname)
701+
702+
689703
class MiscReadTest(MiscReadTestBase, unittest.TestCase):
690704
test_fail_comp = None
691705

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
tarfile.open raises :exc:`~tarfile.ReadError` when a zlib error occurs
2+
during file extraction.

0 commit comments

Comments
 (0)