8000 gh-121285: Remove backtracking when parsing tarfile headers (GH-121286) · python/cpython@34ddb64 · GitHub
[go: up one dir, main page]

Skip to content

Commit 34ddb64

Browse files
sethmlarsonEclips4gpshead
authored
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 Co-authored-by: Kirill Podoprigora <kirill.bast9@mail.ru> Co-authored-by: Gregory P. Smith <greg@krypto.org>
1 parent 0cba289 commit 34ddb64

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
@@ -845,6 +845,9 @@ def data_filter(member, dest_path):
845845
# Sentinel for replace() defaults, meaning "don't change the attribute"
846846
_KEEP = object()
847847

848+
# Header length is digits followed by a space.
849+
_header_length_prefix_re = re.compile(br"([0-9]{1,20}) ")
850+
848851
class TarInfo(object):
849852
"""Informational class which holds the details about an
850853
archive member given by a tar header block.
@@ -1432,55 +1435,76 @@ def _proc_pax(self, tarfile):
14321435
else:
14331436
pax_headers = tarfile.pax_headers.copy()
14341437

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

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

14821507
pax_headers[keyword] = value
1483-
pos += length
14841508

14851509
# Fetch the next header.
14861510
try:
@@ -1495,7 +1519,7 @@ def _proc_pax(self, tarfile):
14951519

14961520
elif "GNU.sparse.size" in pax_headers:
14971521
# GNU extended sparse format version 0.0.
1498-
self._proc_gnusparse_00(next, pax_headers, buf)
1522+
self._proc_gnusparse_00(next, raw_headers)
14991523

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

15181542
return next
15191543

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

15311564
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
@@ -1261,6 +1261,48 @@ def test_pax_number_fields(self):
12611261
finally:
12621262
tar.close()
12631263

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

12651307
class WriteTestBase(TarTest):
12661308
# 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