Skip to content

Commit bfc7d56

Browse files
sethmlarsonEclips4gpshead
authored andcommitted
[CVE-2024-6232] Remove backtracking when parsing tarfile headers
* 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]> Fixes: bsc#1230227 (CVE-2024-6232) Fixes: gh#python#121285 From-PR: gh#python/cpython!123642 Patch: CVE-2024-6232-ReDOS-backtrack-tarfile.patch
1 parent 1036c4b commit bfc7d56

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.
@@ -1363,59 +1366,77 @@ def _proc_pax(self, tarfile):
13631366
else:
13641367
pax_headers = tarfile.pax_headers.copy()
13651368

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

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

1417+
# If no explicit hdrcharset is set, we use UTF-8 as a default.
1418+
if encoding is None:
1419+
encoding = "utf-8"
1420+
1421+
# After parsing the raw headers we can decode them to text.
1422+
for length, raw_keyword, raw_value in raw_headers:
14011423
# Normally, we could just use "utf-8" as the encoding and "strict"
14021424
# as the error handler, but we better not take the risk. For
14031425
# example, GNU tar <= 1.23 is known to store filenames it cannot
14041426
# translate to UTF-8 as raw strings (unfortunately without a
14051427
# hdrcharset=BINARY header).
14061428
# We first try the strict standard encoding, and if that fails we
14071429
# fall back on the user's encoding and error handler.
1408-
keyword = self._decode_pax_field(keyword, "utf-8", "utf-8",
1430+
keyword = self._decode_pax_field(raw_keyword, "utf-8", "utf-8",
14091431
tarfile.errors)
14101432
if keyword in PAX_NAME_FIELDS:
1411-
value = self._decode_pax_field(value, encoding, tarfile.encoding,
1433+
value = self._decode_pax_field(raw_value, encoding, tarfile.encoding,
14121434
tarfile.errors)
14131435
else:
1414-
value = self._decode_pax_field(value, "utf-8", "utf-8",
1436+
value = self._decode_pax_field(raw_value, "utf-8", "utf-8",
14151437
tarfile.errors)
14161438

14171439
pax_headers[keyword] = value
1418-
pos += length
14191440

14201441
# Fetch the next header.
14211442
try:
@@ -1430,7 +1451,7 @@ def _proc_pax(self, tarfile):
14301451

14311452
elif "GNU.sparse.size" in pax_headers:
14321453
# GNU extended sparse format version 0.0.
1433-
self._proc_gnusparse_00(next, pax_headers, buf)
1454+
self._proc_gnusparse_00(next, raw_headers)
14341455

14351456
elif pax_headers.get("GNU.sparse.major") == "1" and pax_headers.get("GNU.sparse.minor") == "0":
14361457
# GNU extended sparse format version 1.0.
@@ -1452,15 +1473,24 @@ def _proc_pax(self, tarfile):
14521473

14531474
return next
14541475

1455-
def _proc_gnusparse_00(self, next, pax_headers, buf):
1476+
def _proc_gnusparse_00(self, next, raw_headers):
14561477
"""Process a GNU tar extended sparse header, version 0.0.
14571478
"""
14581479
offsets = []
1459-
for match in re.finditer(br"\d+ GNU.sparse.offset=(\d+)\n", buf):
1460-
offsets.append(int(match.group(1)))
14611480
numbytes = []
1462-
for match in re.finditer(br"\d+ GNU.sparse.numbytes=(\d+)\n", buf):
1463-
numbytes.append(int(match.group(1)))
1481+
for _, keyword, value in raw_headers:
1482+
if keyword == b"GNU.sparse.offset":
1483+
try:
1484+
offsets.append(int(value.decode()))
1485+
except ValueError:
1486+
raise InvalidHeaderError("invalid header")
1487+
1488+
elif keyword == b"GNU.sparse.numbytes":
1489+
try:
1490+
numbytes.append(int(value.decode()))
1491+
except ValueError:
1492+
raise InvalidHeaderError("invalid header")
1493+
14641494
next.sparse = list(zip(offsets, numbytes))
14651495

14661496
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
@@ -1043,6 +1043,48 @@ def test_pax_number_fields(self):
10431043
finally:
10441044
tar.close()
10451045

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

10471089
class WriteTestBase(TarTest):
10481090
# 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)