[3.9] bpo-39017: Avoid infinite loop in the tarfile module (GH-21454) (GH-21482)



Avoid infinite loop when reading specially crafted TAR files using the tarfile module
(CVE-2019-20907).
(cherry picked from commit 5a8d121a1f3ef5ad7c105ee378cc79a3eac0c7d4)


Co-authored-by: Rishi <rishi_devan@mail.com>

Automerge-Triggered-By: @encukou
diff --git a/Lib/test/test_tarfile.py b/Lib/test/test_tarfile.py
index d60d35b..3ddeb97 100644
--- a/Lib/test/test_tarfile.py
+++ b/Lib/test/test_tarfile.py
@@ -429,6 +429,13 @@
                 with self.assertRaisesRegex(tarfile.ReadError, "unexpected end of data"):
                     tar.extractfile(t).read()
 
+    def test_length_zero_header(self):
+        # bpo-39017 (CVE-2019-20907): reading a zero-length header should fail
+        # with an exception
+        with self.assertRaisesRegex(tarfile.ReadError, "file could not be opened successfully"):
+            with tarfile.open(support.findfile('recursion.tar')) as tar:
+                pass
+
 class MiscReadTestBase(CommonReadTest):
     def requires_name_attribute(self):
         pass