Skip to content

Commit d449caf

Browse files
sethmlarsonEclips4gpshead
authored
[3.11] gh-121285: Remove backtracking when parsing tarfile headers (GH-121286) (#123639)
* 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: Kirill Podoprigora <kirill.bast9@mail.ru> Co-authored-by: Gregory P. Smith <greg@krypto.org>
1 parent 795f259 commit d449caf

File tree

3 files changed

+111
-38
lines changed

3 files changed

+111
-38
lines changed

Lib/tarfile.py

+67-38
Original file line numberDiff line numberDiff line change
@@ -842,6 +842,9 @@ def data_filter(member, dest_path):
842842
# Sentinel for replace() defaults, meaning "don't change the attribute"
843843
_KEEP = object()
844844

845+
# Header length is digits followed by a space.
846+
_header_length_prefix_re = re.compile(br"([0-9]{1,20}) ")
847+
845848
class TarInfo(object):
846849
"""Informational class which holds the details about an
847850
archive member given by a tar header block.
@@ -1411,59 +1414,76 @@ def _proc_pax(self, tarfile):
14111414
else:
14121415
pax_headers = tarfile.pax_headers.copy()
14131416

1414-
# Check if the pax header contains a hdrcharset field. This tells us
1415-
# the encoding of the path, linkpath, uname and gname fields. Normally,
1416-
# these fields are UTF-8 encoded but since POSIX.1-2008 tar
1417-
# implementations are allowed to store them as raw binary strings if
1418-
# the translation to UTF-8 fails.
1419-
match = re.search(br"\d+ hdrcharset=([^\n]+)\n", buf)
1420-
if match is not None:
1421-
pax_headers["hdrcharset"] = match.group(1).decode("utf-8")
1422-
1423-
# For the time being, we don't care about anything other than "BINARY".
1424-
# The only other value that is currently allowed by the standard is
1425-
# "ISO-IR 10646 2000 UTF-8" in other words UTF-8.
1426-
hdrcharset = pax_headers.get("hdrcharset")
1427-
if hdrcharset == "BINARY":
1428-
encoding = tarfile.encoding
1429-
else:
1430-
encoding = "utf-8"
1431-
14321417
# Parse pax header information. A record looks like that:
14331418
# "%d %s=%s\n" % (length, keyword, value). length is the size
14341419
# of the complete record including the length field itself and
1435-
# the newline. keyword and value are both UTF-8 encoded strings.
1436-
regex = re.compile(br"(\d+) ([^=]+)=")
1420+
# the newline.
14371421
pos = 0
1438-
while True:
1439-
match = regex.match(buf, pos)
1440-
if not match:
1441-
break
1422+
encoding = None
1423+
raw_headers = []
1424+
while len(buf) > pos and buf[pos] != 0x00:
1425+
if not (match := _header_length_prefix_re.match(buf, pos)):
1426+
raise InvalidHeaderError("invalid header")
1427+
try:
1428+
length = int(match.group(1))
1429+
except ValueError:
1430+
raise InvalidHeaderError("invalid header")
1431+
# Headers must be at least 5 bytes, shortest being '5 x=\n'.
1432+
# Value is allowed to be empty.
1433+
if length < 5:
1434+
raise InvalidHeaderError("invalid header")
1435+
if pos + length > len(buf):
1436+
raise InvalidHeaderError("invalid header")
14421437

1443-
length, keyword = match.groups()
1444-
length = int(length)
1445-
if length == 0:
1438+
header_value_end_offset = match.start(1) + length - 1 # Last byte of the header
1439+
keyword_and_value = buf[match.end(1) + 1:header_value_end_offset]
1440+
raw_keyword, equals, raw_value = keyword_and_value.partition(b"=")
1441+
1442+
# Check the framing of the header. The last character must be '\n' (0x0A)
1443+
if not raw_keyword or equals != b"=" or buf[header_value_end_offset] != 0x0A:
14461444
raise InvalidHeaderError("invalid header")
1447-
value = buf[match.end(2) + 1:match.start(1) + length - 1]
1445+
raw_headers.append((length, raw_keyword, raw_value))
1446+
1447+
# Check if the pax header contains a hdrcharset field. This tells us
1448+
# the encoding of the path, linkpath, uname and gname fields. Normally,
1449+
# these fields are UTF-8 encoded but since POSIX.1-2008 tar
1450+
# implementations are allowed to store them as raw binary strings if
1451+
# the translation to UTF-8 fails. For the time being, we don't care about
1452+
# anything other than "BINARY". The only other value that is currently
1453+
# allowed by the standard is "ISO-IR 10646 2000 UTF-8" in other words UTF-8.
1454+
# Note that we only follow the initial 'hdrcharset' setting to preserve
1455+
# the initial behavior of the 'tarfile' module.
1456+
if raw_keyword == b"hdrcharset" and encoding is None:
1457+
if raw_value == b"BINARY":
1458+
encoding = tarfile.encoding
1459+
else: # This branch ensures only the first 'hdrcharset' header is used.
1460+
encoding = "utf-8"
1461+
1462+
pos += length
14481463

1464+
# If no explicit hdrcharset is set, we use UTF-8 as a default.
1465+
if encoding is None:
1466+
encoding = "utf-8"
1467+
1468+
# After parsing the raw headers we can decode them to text.
1469+
for length, raw_keyword, raw_value in raw_headers:
14491470
# Normally, we could just use "utf-8" as the encoding and "strict"
14501471
# as the error handler, but we better not take the risk. For
14511472
# example, GNU tar <= 1.23 is known to store filenames it cannot
14521473
# translate to UTF-8 as raw strings (unfortunately without a
14531474
# hdrcharset=BINARY header).
14541475
# We first try the strict standard encoding, and if that fails we
14551476
# fall back on the user's encoding and error handler.
1456-
keyword = self._decode_pax_field(keyword, "utf-8", "utf-8",
1477+
keyword = self._decode_pax_field(raw_keyword, "utf-8", "utf-8",
14571478
tarfile.errors)
14581479
if keyword in PAX_NAME_FIELDS:
1459-
value = self._decode_pax_field(value, encoding, tarfile.encoding,
1480+
value = self._decode_pax_field(raw_value, encoding, tarfile.encoding,
14601481
tarfile.errors)
14611482
else:
1462-
value = self._decode_pax_field(value, "utf-8", "utf-8",
1483+
value = self._decode_pax_field(raw_value, "utf-8", "utf-8",
14631484
tarfile.errors)
14641485

14651486
pax_headers[keyword] = value
1466-
pos += length
14671487

14681488
# Fetch the next header.
14691489
try:
@@ -1478,7 +1498,7 @@ def _proc_pax(self, tarfile):
14781498

14791499
elif "GNU.sparse.size" in pax_headers:
14801500
# GNU extended sparse format version 0.0.
1481-
self._proc_gnusparse_00(next, pax_headers, buf)
1501+
self._proc_gnusparse_00(next, raw_headers)
14821502

14831503
elif pax_headers.get("GNU.sparse.major") == "1" and pax_headers.get("GNU.sparse.minor") == "0":
14841504
# GNU extended sparse format version 1.0.
@@ -1500,15 +1520,24 @@ def _proc_pax(self, tarfile):
15001520

15011521
return next
15021522

1503-
def _proc_gnusparse_00(self, next, pax_headers, buf):
1523+
def _proc_gnusparse_00(self, next, raw_headers):
15041524
"""Process a GNU tar extended sparse header, version 0.0.
15051525
"""
15061526
offsets = []
1507-
for match in re.finditer(br"\d+ GNU.sparse.offset=(\d+)\n", buf):
1508-
offsets.append(int(match.group(1)))
15091527
numbytes = []
1510-
for match in re.finditer(br"\d+ GNU.sparse.numbytes=(\d+)\n", buf):
1511-
numbytes.append(int(match.group(1)))
1528+
for _, keyword, value in raw_headers:
1529+
if keyword == b"GNU.sparse.offset":
1530+
try:
1531+
offsets.append(int(value.decode()))
1532+
except ValueError:
1533+
raise InvalidHeaderError("invalid header")
1534+
1535+
elif keyword == b"GNU.sparse.numbytes":
1536+
try:
1537+
numbytes.append(int(value.decode()))
1538+
except ValueError:
1539+
raise InvalidHeaderError("invalid header")
1540+
15121541
next.sparse = list(zip(offsets, numbytes))
15131542

15141543
def _proc_gnusparse_01(self, next, pax_headers):

Lib/test/test_tarfile.py

+42
Original file line numberDiff line numberDiff line change
@@ -1208,6 +1208,48 @@ def test_pax_number_fields(self):
12081208
finally:
12091209
tar.close()
12101210

1211+
def test_pax_header_bad_formats(self):
1212+
# The fields from the pax header have priority over the
1213+
# TarInfo.
1214+
pax_header_replacements = (
1215+
b" foo=bar\n",
1216+
b"0 \n",
1217+
b"1 \n",
1218+
b"2 \n",
1219+
b"3 =\n",
1220+
b"4 =a\n",
1221+
b"1000000 foo=bar\n",
1222+
b"0 foo=bar\n",
1223+
b"-12 foo=bar\n",
1224+
b"000000000000000000000000036 foo=bar\n",
1225+
)
1226+
pax_headers = {"foo": "bar"}
1227+
1228+
for replacement in pax_header_replacements:
1229+
with self.subTest(header=replacement):
1230+
tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
1231+
encoding="iso8859-1")
1232+
try:
1233+
t = tarfile.TarInfo()
1234+
t.name = "pax" # non-ASCII
1235+
t.uid = 1
1236+
t.pax_headers = pax_headers
1237+
tar.addfile(t)
1238+
finally:
1239+
tar.close()
1240+
1241+
with open(tmpname, "rb") as f:
1242+
data = f.read()
1243+
self.assertIn(b"11 foo=bar\n", data)
1244+
data = data.replace(b"11 foo=bar\n", replacement)
1245+
1246+
with open(tmpname, "wb") as f:
1247+
f.truncate()
1248+
f.write(data)
1249+
1250+
with self.assertRaisesRegex(tarfile.ReadError, r"method tar: ReadError\('invalid header'\)"):
1251+
tarfile.open(tmpname, encoding="iso8859-1")
1252+
12111253

12121254
class WriteTestBase(TarTest):
12131255
# Put all write tests in here that are supposed to be tested
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)