[3.8] gh-121285: Remove backtracking when parsing tarfile headers (GH… · python/cpython@7d1f50c · GitHub
Skip to content

Commit 7d1f50c

Browse files
sethmlarsonEclips4gpshead
authored
[3.8] gh-121285: Remove backtracking when parsing tarfile headers (GH-121286) (#123642)
* Remove backtracking when parsing tarfile headers * Rewrite PAX header parsing to be stricter * Optimize parsing of GNU extended sparse headers v0.0 (cherry picked from commit 34ddb64) Co-authored-by: Seth Michael Larson <seth@python.org> Co-authored-by: Kirill Podoprigora <kirill.bast9@mail.ru> Co-authored-by: Gregory P. Smith <greg@krypto.org>
1 parent 7bc367e commit 7d1f50c

3 files changed

Lines changed: 111 additions & 38 deletions

File tree

Lib/tarfile.py

Lines changed: 67 additions & 38 deletions

Lib/test/test_tarfile.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1047,6 +1047,48 @@ def test_pax_number_fields(self):
10471047
finally:
10481048
tar.close()
10491049

1050+
def test_pax_header_bad_formats(self):
1051+
# The fields from the pax header have priority over the
1052+
# TarInfo.
1053+
pax_header_replacements = (
1054+
b" foo=bar\n",
1055+
b"0 \n",
1056+
b"1 \n",
1057+
b"2 \n",
1058+
b"3 =\n",
1059+
b"4 =a\n",
1060+
b"1000000 foo=bar\n",
1061+
b"0 foo=bar\n",
1062+
b"-12 foo=bar\n",
1063+
b"000000000000000000000000036 foo=bar\n",
1064+
)
1065+
pax_headers = {"foo": "bar"}
1066+
1067+
for replacement in pax_header_replacements:
1068+
with self.subTest(header=replacement):
1069+
tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
1070+
encoding="iso8859-1")
1071+
try:
1072+
t = tarfile.TarInfo()
1073+
t.name = "pax" # non-ASCII
1074+
t.uid = 1
1075+
t.pax_headers = pax_headers
1076+
tar.addfile(t)
1077+
finally:
1078+
tar.close()
1079+
1080+
with open(tmpname, "rb") as f:
1081+
data = f.read()
1082+
self.assertIn(b"11 foo=bar\n", data)
1083+
data = data.replace(b"11 foo=bar\n", replacement)
1084+
1085+
with open(tmpname, "wb") as f:
1086+
f.truncate()
1087+
f.write(data)
1088+
1089+
with self.assertRaisesRegex(tarfile.ReadError, r"file could not be opened successfully"):
1090+
tarfile.open(tmpname, encoding="iso8859-1")
1091+
10501092

10511093
class WriteTestBase(TarTest):
10521094
# Put all write tests in here that are supposed to be tested
Lines changed: 2 additions & 0 deletions

0 commit comments

Comments
 (0)