Skip to content

Commit d6b69f2

Browse files
ambvjdevries3133
andauthored
[3.10] bpo-39039: tarfile raises descriptive exception from zlib.error (GH-27766) (GH-28613)
* 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 <58614260+jdevries3133@users.noreply.github.com>
1 parent 1cb17be commit d6b69f2

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
@@ -2349,6 +2349,15 @@ def next(self):
23492349
raise ReadError(str(e)) from None
23502350
except SubsequentHeaderError as e:
23512351
raise ReadError(str(e)) from None
2352+
except Exception as e:
2353+
try:
2354+
import zlib
2355+
if isinstance(e, zlib.error):
2356+
raise ReadError(f'zlib error: {e}') from None
2357+
else:
2358+
raise e
2359+
except ImportError:
2360+
raise e
23522361
break
23532362

23542363
if tarinfo is not None:

Lib/test/test_tarfile.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,10 @@
1919
import gzip
2020
except ImportError:
2121
gzip = None
22+
try:
23+
import zlib
24+
except ImportError:
25+
zlib = None
2226
try:
2327
import bz2
2428
except ImportError:
@@ -687,6 +691,16 @@ def test_parallel_iteration(self):
687691
self.assertEqual(m1.offset, m2.offset)
688692
self.assertEqual(m1.get_info(), m2.get_info())
689693

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

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)