]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-39039: tarfile raises descriptive exception from zlib.error (GH-27766)
authorJack DeVries <58614260+jdevries3133@users.noreply.github.com>
Wed, 29 Sep 2021 09:25:48 +0000 (05:25 -0400)
committerGitHub <noreply@github.com>
Wed, 29 Sep 2021 09:25:48 +0000 (11:25 +0200)
* 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

Lib/tarfile.py
Lib/test/test_tarfile.py
Misc/NEWS.d/next/Library/2021-08-18-10-36-14.bpo-39039.A63LYh.rst [new file with mode: 0644]

index 18d415adf5441847c72ae8916ecd6ff6ff5e8ef8..c1ee1222e09b5af9e76f024a5a16ff5037b9979b 100755 (executable)
@@ -2349,6 +2349,15 @@ class TarFile(object):
                     raise ReadError(str(e)) from None
             except SubsequentHeaderError as e:
                 raise ReadError(str(e)) from None
+            except Exception as e:
+                try:
+                    import zlib
+                    if isinstance(e, zlib.error):
+                        raise ReadError(f'zlib error: {e}') from None
+                    else:
+                        raise e
+                except ImportError:
+                    raise e
             break
 
         if tarinfo is not None:
index cfdda24a269f560cd9614e5009e556bbf55fef7b..e4b5c52bf1eaf4ae8039d3369c76574c46a49c58 100644 (file)
@@ -19,6 +19,10 @@ try:
     import gzip
 except ImportError:
     gzip = None
+try:
+    import zlib
+except ImportError:
+    zlib = None
 try:
     import bz2
 except ImportError:
@@ -687,6 +691,16 @@ class MiscReadTestBase(CommonReadTest):
                 self.assertEqual(m1.offset, m2.offset)
                 self.assertEqual(m1.get_info(), m2.get_info())
 
+    @unittest.skipIf(zlib is None, "requires zlib")
+    def test_zlib_error_does_not_leak(self):
+        # bpo-39039: tarfile.open allowed zlib exceptions to bubble up when
+        # parsing certain types of invalid data
+        with unittest.mock.patch("tarfile.TarInfo.fromtarfile") as mock:
+            mock.side_effect = zlib.error
+            with self.assertRaises(tarfile.ReadError):
+                tarfile.open(self.tarname)
+
+
 class MiscReadTest(MiscReadTestBase, unittest.TestCase):
     test_fail_comp = None
 
diff --git a/Misc/NEWS.d/next/Library/2021-08-18-10-36-14.bpo-39039.A63LYh.rst b/Misc/NEWS.d/next/Library/2021-08-18-10-36-14.bpo-39039.A63LYh.rst
new file mode 100644 (file)
index 0000000..7250055
--- /dev/null
@@ -0,0 +1,2 @@
+tarfile.open raises :exc:`~tarfile.ReadError` when a zlib error occurs
+during file extraction.