8000 00437: [3.8] gh-121285: Remove backtracking when parsing tarfile head… · fedora-python/cpython@3209abb · GitHub
[go: up one dir, main page]

Skip to content

Commit 3209abb

Browse files
sethmlarsonEclips4gpsheadfrenzymadness
committed
00437: [3.8] pythongh-121285: Remove backtracking when parsing tarfile headers (pythonGH-121286) (python#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> Co-authored-by: Lumír Balhar <lbalhar@redhat.com>
1 parent f75f869 commit 3209abb

File tree

3 files changed

+111
-37
lines changed

3 files changed

+111
-37
lines changed

Lib/tarfile.py

Lines changed: 67 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -846,6 +846,9 @@ def data_filter(member, dest_path):
846846
# Sentinel for replace() defaults, meaning "don't change the attribute"
847847
_KEEP = object()
848848

849+
# Header length is digits followed by a space.
850+
_header_length_prefix_re = re.compile(br"([0-9]{1,20}) ")
851+
849852
class TarInfo(object):
850853
"""Informational class which holds the details about an
851854
archive member given by a tar header block.
@@ -1371,59 +1374,77 @@ def _proc_pax(self, tarfile):
13711374
else:
13721375
pax_headers = tarfile.pax_headers.copy()
13731376

1374-
# Check if the pax header contains a hdrcharset field. This tells us
1375-
# the encoding of the path, linkpath, uname and gname fields. Normally,
1376-
# these fields are UTF-8 encoded but since POSIX.1-2008 tar
1377-
# implementations are allowed to store them as raw binary strings if
1378-
# the translation to UTF-8 fails.
1379-
match = re.search(br"\d+ hdrcharset=([^\n]+)\n", buf)
1380-
if match is not None:
1381-
pax_headers["hdrcharset"] = match.group(1).decode("utf-8")
1382-
1383-
# For the time being, we don't care about anything other than "BINARY".
1384-
# The only other value that is currently allowed by the standard is
1385-
# "ISO-IR 10646 2000 UTF-8" in other words UTF-8.
1386-
hdrcharset = pax_headers.get("hdrcharset")
1387-
if hdrcharset == "BINARY":
1388-
encoding = tarfile.encoding
1389-
else:
1390-
encoding = "utf-8"
1391-
13921377
# Parse pax header information. A record looks like that:
13931378
# "%d %s=%s\n" % (length, keyword, value). length is the size
13941379
# of the complete record including the length field itself and
1395-
# the newline. keyword and value are both UTF-8 encoded strings.
1396-
regex = re.compile(br"(\d+) ([^=]+)=")
1380+
# the newline.
13971381
pos = 0
1398-
while True:
1399-
match = regex.match(buf, pos)
1382+
encoding = None
1383+
raw_headers = []
1384+
while len(buf) > pos and buf[pos] != 0x00:
1385+
match = _header_length_prefix_re.match(buf, pos)
14001386
if not match:
1401-
break
1387+
raise InvalidHeaderError("invalid header")
1388+
try:
1389+
length = int(match.group(1))
1390+
except ValueError:
1391+
raise InvalidHeaderError("invalid header")
1392+
# Headers must be at least 5 bytes, shortest being '5 x=\n'.
1393+
# Value is allowed to be empty.
1394+
if length < 5:
1395+
raise InvalidHeaderError("invalid header")
1396+
if pos + length > len(buf):
1397+
raise InvalidHeaderError("invalid header")
14021398

1403-
length, keyword = match.groups()
1404-
length = int(length)
1405-
if length == 0:
1399+
header_value_end_offset = match.start(1) + length - 1 # Last byte of the header
1400+
keyword_and_value = buf[match.end(1) + 1:header_value_end_offset]
1401+
raw_keyword, equals, raw_value = keyword_and_value.partition(b"=")
1402+
1403+
# Check the framing of the header. The last character must be '\n' (0x0A)
1404+
if not raw_keyword or equals != b"=" or buf[header_value_end_offset] != 0x0A:
14061405
raise InvalidHeaderError("invalid header")
1407-
value = buf[match.end(2) + 1:match.start(1) + length - 1]
1406+
raw_headers.append((length, raw_keyword, raw_value))
1407+
1408+
# Check if the pax header contains a hdrcharset field. This tells us
1409+
# the encoding of the path, linkpath, uname and gname fields. Normally,
1410+
# these fields are UTF-8 encoded but since POSIX.1-2008 tar
1411+
# implementations are allowed to store them as raw binary strings if
1412+
# the translation to UTF-8 fails. For the time being, we don't care about
1413+
# anything other than "BINARY". The only other value that is currently
1414+
# allowed by the standard is "ISO-IR 10646 2000 UTF-8" in other words UTF-8.
1415+
# Note that we only follow the initial 'hdrcharset' setting to preserve
1416+
# the initial behavior of the 'tarfile' module.
1417+
if raw_keyword == b"hdrcharset" and encoding is None:
1418+
if raw_value == b"BINARY":
1419+
encoding = tarfile.encoding
1420+
else: # This branch ensures only the first 'hdrcharset' header is used.
1421+
encoding = "utf-8"
1422+
1423+
pos += length
14081424

1425+
# If no explicit hdrcharset is set, we use UTF-8 as a default.
1426+
if encoding is None:
1427+
encoding = "utf-8"
1428+
1429+
# After parsing the raw headers we can decode them to text.
1430+
for length, raw_keyword, raw_value in raw_headers:
14091431
# Normally, we could just use "utf-8" as the encoding and "strict"
14101432
# as the error handler, but we better not take the risk. For
14111433
# example, GNU tar <= 1.23 is known to store filenames it cannot
14121434
# translate to UTF-8 as raw strings (unfortunately without a
14131435
# hdrcharset=BINARY header).
14141436
# We first try the strict standard encoding, and if that fails we
14151437
# fall back on the user's encoding and error handler.
1416-
keyword = self._decode_pax_field(keyword, "utf-8", "utf-8",
1438+
keyword = self._decode_pax_field(raw_keyword, "utf-8", "utf-8",
14171439
tarfile.errors)
14181440
if keyword in PAX_NAME_FIELDS:
1419-
value = self._decode_pax_field(value, encoding, tarfile.encoding,
1441+
value = self._decode_pax_field(raw_value, encoding, tarfile.encoding,
14201442
tarfile.errors)
14211443
else:
1422-
value = self._decode_pax_field(value, "utf-8", "utf-8",
1444+
value = self._decode_pax_field(raw_value, "utf-8", "utf-8",
14231445
tarfile.errors)
14241446

14251447
pax_headers[keyword] = value
1426-
pos += length
14271448

14281449
# Fetch the next header.
14291450
try:
@@ -1438,7 +1459,7 @@ def _proc_pax(self, tarfile):
14381459

14391460
elif "GNU.sparse.size" in pax_headers:
14401461
# GNU extended sparse format version 0.0.
1441-
self._proc_gnusparse_00(next, pax_headers, buf)
1462+
self._proc_gnusparse_00(next, raw_headers)
14421463

14431464
elif pax_headers.get("GNU.sparse.major") == "1" and pax_headers.get("GNU.sparse.minor") == "0":
14441465
# GNU extended sparse format version 1.0.
@@ -1460,15 +1481,24 @@ def _proc_pax(self, tarfile):
14601481

14611482
return next
14621483

1463-
def _proc_gnusparse_00(self, next, pax_headers, buf):
1484+
def _proc_gnusparse_00(self, next, raw_headers):
14641485
"""Process a GNU tar extended sparse header, version 0.0.
14651486
"""
14661487
offsets = []
1467-
for match in re.finditer(br"\d+ GNU.sparse.offset=(\d+)\n", buf):
1468-
offsets.append(int(match.group(1)))
14691488
numbytes = []
1470-
for match in re.finditer(br"\d+ GNU.sparse.numbytes=(\d+)\n", buf):
1471-
numbytes.append(int(match.group(1)))
1489+
for _, keyword, value in raw_headers:
1490+
if keyword == b"GNU.sparse.offset":
1491+
try:
1492+
offsets.append(int(value.decode()))
1493+
except ValueError:
1494+
raise InvalidHeaderError("invalid header")
1495+
1496+
elif keyword == b"GNU.sparse.numbytes":
1497+
try:
1498+
numbytes.append(int(value.decode()))
1499+
except ValueError:
1500+
raise InvalidHeaderError("invalid header")
1501+
14721502
next.sparse = list(zip(offsets, numbytes))
14731503

14741504
def _proc_gnusparse_01(self, next, pax_headers):

Lib/test/test_tarfile.py

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

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

10501092
class WriteTestBase(TarTest):
10511093
# Put all write tests in here that are supposed to be tested
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Remove backtracking from tarfile header parsing for ``hdrcharset``, PAX, and
2+
GNU sparse headers.

0 commit comments

Comments
 (0)
0