Skip to content

Commit ed3a49e

Browse files
miss-islingtonsethmlarsonEclips4gpshead
authored
[3.13] gh-121285: Remove backtracking when parsing tarfile headers (GH-121286) (#123542)
gh-121285: Remove backtracking when parsing tarfile headers (GH-121286) * 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 <[email protected]> Co-authored-by: Kirill Podoprigora <[email protected]> Co-authored-by: Gregory P. Smith <[email protected]>
1 parent ffb7abe commit ed3a49e

File tree

3 files changed

+112
-35
lines changed

3 files changed

+112
-35
lines changed

Lib/tarfile.py

Lines changed: 68 additions & 35 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.
@@ -1433,55 +1436,76 @@ def _proc_pax(self, tarfile):
14331436
else:
14341437
pax_headers = tarfile.pax_headers.copy()
14351438

1436-
# Check if the pax header contains a hdrcharset field. This tells us
1437-
# the encoding of the path, linkpath, uname and gname fields. Normally,
1438-
# these fields are UTF-8 encoded but since POSIX.1-2008 tar
1439-
# implementations are allowed to store them as raw binary strings if
1440-
# the translation to UTF-8 fails.
1441-
match = re.search(br"\d+ hdrcharset=([^\n]+)\n", buf)
1442-
if match is not None:
1443-
pax_headers["hdrcharset"] = match.group(1).decode("utf-8")
1444-
1445-
# For the time being, we don't care about anything other than "BINARY".
1446-
# The only other value that is currently allowed by the standard is
1447-
# "ISO-IR 10646 2000 UTF-8" in other words UTF-8.
1448-
hdrcharset = pax_headers.get("hdrcharset")
1449-
if hdrcharset == "BINARY":
1450-
encoding = tarfile.encoding
1451-
else:
1452-
encoding = "utf-8"
1453-
14541439
# Parse pax header information. A record looks like that:
14551440
# "%d %s=%s\n" % (length, keyword, value). length is the size
14561441
# of the complete record including the length field itself and
1457-
# the newline. keyword and value are both UTF-8 encoded strings.
1458-
regex = re.compile(br"(\d+) ([^=]+)=")
1442+
# the newline.
14591443
pos = 0
1460-
while match := regex.match(buf, pos):
1461-
length, keyword = match.groups()
1462-
length = int(length)
1463-
if length == 0:
1444+
encoding = None
1445+
raw_headers = []
1446+
while len(buf) > pos and buf[pos] != 0x00:
1447+
if not (match := _header_length_prefix_re.match(buf, pos)):
1448+
raise InvalidHeaderError("invalid header")
1449+
try:
1450+
length = int(match.group(1))
1451+
except ValueError:
1452+
raise InvalidHeaderError("invalid header")
1453+
# Headers must be at least 5 bytes, shortest being '5 x=\n'.
1454+
# Value is allowed to be empty.
1455+
if length < 5:
1456+
raise InvalidHeaderError("invalid header")
1457+
if pos + length > len(buf):
1458+
raise InvalidHeaderError("invalid header")
1459+
1460+
header_value_end_offset = match.start(1) + length - 1 # Last byte of the header
1461+
keyword_and_value = buf[match.end(1) + 1:header_value_end_offset]
1462+
raw_keyword, equals, raw_value = keyword_and_value.partition(b"=")
1463+
1464+
# Check the framing of the header. The last character must be '\n' (0x0A)
1465+
if not raw_keyword or equals != b"=" or buf[header_value_end_offset] != 0x0A:
14641466
raise InvalidHeaderError("invalid header")
1465-
value = buf[match.end(2) + 1:match.start(1) + length - 1]
1467+
raw_headers.append((length, raw_keyword, raw_value))
1468+
1469+
# Check if the pax header contains a hdrcharset field. This tells us
1470+
# the encoding of the path, linkpath, uname and gname fields. Normally,
1471+
# these fields are UTF-8 encoded but since POSIX.1-2008 tar
1472+
# implementations are allowed to store them as raw binary strings if
1473+
# the translation to UTF-8 fails. For the time being, we don't care about
1474+
# anything other than "BINARY". The only other value that is currently
1475+
# allowed by the standard is "ISO-IR 10646 2000 UTF-8" in other words UTF-8.
1476+
# Note that we only follow the initial 'hdrcharset' setting to preserve
1477+
# the initial behavior of the 'tarfile' module.
1478+
if raw_keyword == b"hdrcharset" and encoding is None:
1479+
if raw_value == b"BINARY":
1480+
encoding = tarfile.encoding
1481+
else: # This branch ensures only the first 'hdrcharset' header is used.
1482+
encoding = "utf-8"
14661483

1484+
pos += length
1485+
1486+
# If no explicit hdrcharset is set, we use UTF-8 as a default.
1487+
if encoding is None:
1488+
encoding = "utf-8"
1489+
1490+
# After parsing the raw headers we can decode them to text.
1491+
for length, raw_keyword, raw_value in raw_headers:
14671492
# Normally, we could just use "utf-8" as the encoding and "strict"
14681493
# as the error handler, but we better not take the risk. For
14691494
# example, GNU tar <= 1.23 is known to store filenames it cannot
14701495
# translate to UTF-8 as raw strings (unfortunately without a
14711496
# hdrcharset=BINARY header).
14721497
# We first try the strict standard encoding, and if that fails we
14731498
# fall back on the user's encoding and error handler.
1474-
keyword = self._decode_pax_field(keyword, "utf-8", "utf-8",
1499+
keyword = self._decode_pax_field(raw_keyword, "utf-8", "utf-8",
14751500
tarfile.errors)
14761501
if keyword in PAX_NAME_FIELDS:
1477-
value = self._decode_pax_field(value, encoding, tarfile.encoding,
1502+
value = self._decode_pax_field(raw_value, encoding, tarfile.encoding,
14781503
tarfile.errors)
14791504
else:
1480-
value = self._decode_pax_field(value, "utf-8", "utf-8",
1505+
value = self._decode_pax_field(raw_value, "utf-8", "utf-8",
14811506
tarfile.errors)
14821507

14831508
pax_headers[keyword] = value
1484-
pos += length
14851509

14861510
# Fetch the next header.
14871511
try:
@@ -1496,7 +1520,7 @@ def _proc_pax(self, tarfile):
14961520

14971521
elif "GNU.sparse.size" in pax_headers:
14981522
# GNU extended sparse format version 0.0.
1499-
self._proc_gnusparse_00(next, pax_headers, buf)
1523+
self._proc_gnusparse_00(next, raw_headers)
15001524

15011525
elif pax_headers.get("GNU.sparse.major") == "1" and pax_headers.get("GNU.sparse.minor") == "0":
15021526
# GNU extended sparse format version 1.0.
@@ -1518,15 +1542,24 @@ def _proc_pax(self, tarfile):
15181542

15191543
return next
15201544

1521-
def _proc_gnusparse_00(self, next, pax_headers, buf):
1545+
def _proc_gnusparse_00(self, next, raw_headers):
15221546
"""Process a GNU tar extended sparse header, version 0.0.
15231547
"""
15241548
offsets = []
1525-
for match in re.finditer(br"\d+ GNU.sparse.offset=(\d+)\n", buf):
1526-
offsets.append(int(match.group(1)))
15271549
numbytes = []
1528-
for match in re.finditer(br"\d+ GNU.sparse.numbytes=(\d+)\n", buf):
1529-
numbytes.append(int(match.group(1)))
1550+
for _, keyword, value in raw_headers:
1551+
if keyword == b"GNU.sparse.offset":
1552+
try:
1553+
offsets.append(int(value.decode()))
1554+
except ValueError:
1555+
raise InvalidHeaderError("invalid header")
1556+
1557+
elif keyword == b"GNU.sparse.numbytes":
1558+
try:
1559+
numbytes.append(int(value.decode()))
1560+
except ValueError:
1561+
raise InvalidHeaderError("invalid header")
1562+
15301563
next.sparse = list(zip(offsets, numbytes))
15311564

15321565
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
@@ -1268,6 +1268,48 @@ def test_pax_number_fields(self):
12681268
finally:
12691269
tar.close()
12701270

1271+
def test_pax_header_bad_formats(self):
1272+
# The fields from the pax header have priority over the
1273+
# TarInfo.
1274+
pax_header_replacements = (
1275+
b" foo=bar\n",
1276+
b"0 \n",
1277+
b"1 \n",
1278+
b"2 \n",
1279+
b"3 =\n",
1280+
b"4 =a\n",
1281+
b"1000000 foo=bar\n",
1282+
b"0 foo=bar\n",
1283+
b"-12 foo=bar\n",
1284+
b"000000000000000000000000036 foo=bar\n",
1285+
)
1286+
pax_headers = {"foo": "bar"}
1287+
1288+
for replacement in pax_header_replacements:
1289+
with self.subTest(header=replacement):
1290+
tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
1291+
encoding="iso8859-1")
1292+
try:
1293+
t = tarfile.TarInfo()
1294+
t.name = "pax" # non-ASCII
1295+
t.uid = 1
1296+
t.pax_headers = pax_headers
1297+
tar.addfile(t)
1298+
finally:
1299+
tar.close()
1300+
1301+
with open(tmpname, "rb") as f:
1302+
data = f.read()
1303+
self.assertIn(b"11 foo=bar\n", data)
1304+
data = data.replace(b"11 foo=bar\n", replacement)
1305+
1306+
with open(tmpname, "wb") as f:
1307+
f.truncate()
1308+
f.write(data)
1309+
1310+
with self.assertRaisesRegex(tarfile.ReadError, r"method tar: ReadError\('invalid header'\)"):
1311+
tarfile.open(tmpname, encoding="iso8859-1")
1312+
12711313

12721314
class WriteTestBase(TarTest):
12731315
# 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)