Skip to content

Commit 1b14072

Browse files
committed
CVE-2024-5262 Remove backtracking when parsing tarfile headers (pythonGH-121286)
Patched from: https://github.com/python/cpython/commit/7d1f50cd92ff7e10a1c15a8f591dde8a6843a64d.patch Had one reject, hand updated it.
1 parent 9dcc3b1 commit 1b14072

File tree

3 files changed

+113
-38
lines changed

3 files changed

+113
-38
lines changed

Lib/tarfile.py

Lines changed: 69 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -722,6 +722,11 @@ def __init__(self, tarfile, tarinfo):
722722
#------------------
723723
# Exported Classes
724724
#------------------
725+
726+
# Header length is digits followed by a space.
727+
_header_length_prefix_re = re.compile(br"([0-9]{1,20}) ")
728+
729+
725730
class TarInfo(object):
726731
"""Informational class which holds the details about an
727732
archive member given by a tar header block.
@@ -1202,59 +1207,76 @@ def _proc_pax(self, tarfile):
12021207
else:
12031208
pax_headers = tarfile.pax_headers.copy()
12041209

1205-
# Check if the pax header contains a hdrcharset field. This tells us
1206-
# the encoding of the path, linkpath, uname and gname fields. Normally,
1207-
# these fields are UTF-8 encoded but since POSIX.1-2008 tar
1208-
# implementations are allowed to store them as raw binary strings if
1209-
# the translation to UTF-8 fails.
1210-
match = re.search(br"\d+ hdrcharset=([^\n]+)\n", buf)
1211-
if match is not None:
1212-
pax_headers["hdrcharset"] = match.group(1).decode("utf-8")
1213-
1214-
# For the time being, we don't care about anything other than "BINARY".
1215-
# The only other value that is currently allowed by the standard is
1216-
# "ISO-IR 10646 2000 UTF-8" in other words UTF-8.
1217-
hdrcharset = pax_headers.get("hdrcharset")
1218-
if hdrcharset == "BINARY":
1219-
encoding = tarfile.encoding
1220-
else:
1221-
encoding = "utf-8"
1222-
12231210
# Parse pax header information. A record looks like that:
12241211
# "%d %s=%s\n" % (length, keyword, value). length is the size
12251212
# of the complete record including the length field itself and
1226-
# the newline. keyword and value are both UTF-8 encoded strings.
1227-
regex = re.compile(br"(\d+) ([^=]+)=")
1213+
# the newline.
12281214
pos = 0
1229-
while True:
1230-
match = regex.match(buf, pos)
1231-
if not match:
1232-
break
1215+
encoding = None
1216+
raw_headers = []
1217+
while len(buf) > pos and buf[pos] != 0x00:
1218+
if not (match := _header_length_prefix_re.match(buf, pos)):
1219+
raise InvalidHeaderError("invalid header")
1220+
try:
1221+
length = int(match.group(1))
1222+
except ValueError:
1223+
raise InvalidHeaderError("invalid header")
1224+
# Headers must be at least 5 bytes, shortest being '5 x=\n'.
1225+
# Value is allowed to be empty.
1226+
if length < 5:
1227+
raise InvalidHeaderError("invalid header")
1228+
if pos + length > len(buf):
1229+
raise InvalidHeaderError("invalid header")
12331230

1234-
length, keyword = match.groups()
1235-
length = int(length)
1236-
if length == 0:
1231+
header_value_end_offset = match.start(1) + length - 1 # Last byte of the header
1232+
keyword_and_value = buf[match.end(1) + 1:header_value_end_offset]
1233+
raw_keyword, equals, raw_value = keyword_and_value.partition(b"=")
1234+
1235+
# Check the framing of the header. The last character must be '\n' (0x0A)
1236+
if not raw_keyword or equals != b"=" or buf[header_value_end_offset] != 0x0A:
12371237
raise InvalidHeaderError("invalid header")
1238-
value = buf[match.end(2) + 1:match.start(1) + length - 1]
1238+
raw_headers.append((length, raw_keyword, raw_value))
1239+
1240+
# Check if the pax header contains a hdrcharset field. This tells us
1241+
# the encoding of the path, linkpath, uname and gname fields. Normally,
1242+
# these fields are UTF-8 encoded but since POSIX.1-2008 tar
1243+
# implementations are allowed to store them as raw binary strings if
1244+
# the translation to UTF-8 fails. For the time being, we don't care about
1245+
# anything other than "BINARY". The only other value that is currently
1246+
# allowed by the standard is "ISO-IR 10646 2000 UTF-8" in other words UTF-8.
1247+
# Note that we only follow the initial 'hdrcharset' setting to preserve
1248+
# the initial behavior of the 'tarfile' module.
1249+
if raw_keyword == b"hdrcharset" and encoding is None:
1250+
if raw_value == b"BINARY":
1251+
encoding = tarfile.encoding
1252+
else: # This branch ensures only the first 'hdrcharset' header is used.
1253+
encoding = "utf-8"
1254+
1255+
pos += length
12391256

1257+
# If no explicit hdrcharset is set, we use UTF-8 as a default.
1258+
if encoding is None:
1259+
encoding = "utf-8"
1260+
1261+
# After parsing the raw headers we can decode them to text.
1262+
for length, raw_keyword, raw_value in raw_headers:
12401263
# Normally, we could just use "utf-8" as the encoding and "strict"
12411264
# as the error handler, but we better not take the risk. For
12421265
# example, GNU tar <= 1.23 is known to store filenames it cannot
12431266
# translate to UTF-8 as raw strings (unfortunately without a
12441267
# hdrcharset=BINARY header).
12451268
# We first try the strict standard encoding, and if that fails we
12461269
# fall back on the user's encoding and error handler.
1247-
keyword = self._decode_pax_field(keyword, "utf-8", "utf-8",
1270+
keyword = self._decode_pax_field(raw_keyword, "utf-8", "utf-8",
12481271
tarfile.errors)
12491272
if keyword in PAX_NAME_FIELDS:
1250-
value = self._decode_pax_field(value, encoding, tarfile.encoding,
1273+
value = self._decode_pax_field(raw_value, encoding, tarfile.encoding,
12511274
tarfile.errors)
12521275
else:
1253-
value = self._decode_pax_field(value, "utf-8", "utf-8",
1276+
value = self._decode_pax_field(raw_value, "utf-8", "utf-8",
12541277
tarfile.errors)
12551278

12561279
pax_headers[keyword] = value
1257-
pos += length
12581280

12591281
# Fetch the next header.
12601282
try:
@@ -1269,7 +1291,7 @@ def _proc_pax(self, tarfile):
12691291

12701292
elif "GNU.sparse.size" in pax_headers:
12711293
# GNU extended sparse format version 0.0.
1272-
self._proc_gnusparse_00(next, pax_headers, buf)
1294+
self._proc_gnusparse_00(next, raw_headers)
12731295

12741296
elif pax_headers.get("GNU.sparse.major") == "1" and pax_headers.get("GNU.sparse.minor") == "0":
12751297
# GNU extended sparse format version 1.0.
@@ -1291,15 +1313,24 @@ def _proc_pax(self, tarfile):
12911313

12921314
return next
12931315

1294-
def _proc_gnusparse_00(self, next, pax_headers, buf):
1316+
def _proc_gnusparse_00(self, next, raw_headers):
12951317
"""Process a GNU tar extended sparse header, version 0.0.
12961318
"""
12971319
offsets = []
1298-
for match in re.finditer(br"\d+ GNU.sparse.offset=(\d+)\n", buf):
1299-
offsets.append(int(match.group(1)))
13001320
numbytes = []
1301-
for match in re.finditer(br"\d+ GNU.sparse.numbytes=(\d+)\n", buf):
1302-
numbytes.append(int(match.group(1)))
1321+
for _, keyword, value in raw_headers:
1322+
if keyword == b"GNU.sparse.offset":
1323+
try:
1324+
offsets.append(int(value.decode()))
1325+
except ValueError:
1326+
raise InvalidHeaderError("invalid header")
1327+
1328+
elif keyword == b"GNU.sparse.numbytes":
1329+
try:
1330+
numbytes.append(int(value.decode()))
1331+
except ValueError:
1332+
raise InvalidHeaderError("invalid header")
1333+
13031334
next.sparse = list(zip(offsets, numbytes))
13041335

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

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

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