Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 39a419c

Browse files
committed
Rewrite PAX header parsing to be stricter
1 parent 9a6cc59 commit 39a419c

File tree

2 files changed

+85
-35
lines changed

2 files changed

+85
-35
lines changed

Lib/tarfile.py

Lines changed: 43 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,61 +1435,66 @@ 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-
if (
1441-
# Statement is both a contains check (!=-1) and a bounds check (>0)
1442-
(hdrcharset_offset := buf.find(b" hdrcharset=") - 1) > -1
1443-
# Check that the character before is a digit (0x30-0x39 is 0-9)
1444-
and 0x30 <= buf[hdrcharset_offset] <= 0x39
1445-
):
1446-
match = re.match(br"^\d{1,20} hdrcharset=([^\n]+)\n", buf[hdrcharset_offset:])
1447-
if match is not None:
1448-
pax_headers["hdrcharset"] = match.group(1).decode("utf-8")
1449-
1450-
# For the time being, we don't care about anything other than "BINARY".
1451-
# The only other value that is currently allowed by the standard is
1452-
# "ISO-IR 10646 2000 UTF-8" in other words UTF-8.
1453-
hdrcharset = pax_headers.get("hdrcharset")
1454-
if hdrcharset == "BINARY":
1455-
encoding = tarfile.encoding
1456-
else:
1457-
encoding = "utf-8"
1458-
14591438
# Parse pax header information. A record looks like that:
14601439
# "%d %s=%s\n" % (length, keyword, value). length is the size
14611440
# of the complete record including the length field itself and
1462-
# the newline. keyword and value are both UTF-8 encoded strings.
1463-
regex = re.compile(br"^(\d{1,20}) ([^=]+)=")
1441+
# the newline.
14641442
pos = 0
1465-
while match := regex.match(buf[pos:]):
1466-
length, keyword = match.groups()
1467-
length = int(length)
1468-
if length == 0:
1443+
encoding = "utf-8"
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 3 bytes, one for each of keyword, '=', and '\n'.
1453+
# Value is allowed to be empty.
1454+
if length < 3:
14691455
raise InvalidHeaderError("invalid header")
1470-
value = buf[match.end(2) + pos + 1:match.start(1) + pos + length - 1]
1456+
if pos + length > len(buf):
1457+
raise InvalidHeaderError("invalid header")
1458+
1459+
keyword_and_value = buf[match.end(1) + 1:match.start(1) + length - 1]
1460+
raw_keyword, equals, raw_value = keyword_and_value.partition(b"=")
1461+
1462+
# Check the framing of the header. The last character must be '\n' (0x0A)
1463+
if not raw_keyword or equals != b"=" or buf[match.start(1) + length - 1] != 0x0A:
1464+
raise InvalidHeaderError("invalid header")
1465+
raw_headers.append((length, raw_keyword, raw_value))
1466+
1467+
# Check if the pax header contains a hdrcharset field. This tells us
1468+
# the encoding of the path, linkpath, uname and gname fields. Normally,
1469+
# these fields are UTF-8 encoded but since POSIX.1-2008 tar
1470+
# implementations are allowed to store them as raw binary strings if
1471+
# the translation to UTF-8 fails. For the time being, we don't care about
1472+
# anything other than "BINARY". The only other value that is currently
1473+
# allowed by the standard is "ISO-IR 10646 2000 UTF-8" in other words UTF-8.
1474+
if raw_keyword == b"hdrcharset" and raw_value == b"BINARY":
1475+
encoding = tarfile.encoding
14711476

1477+
pos += length
1478+
1479+
# After parsing the raw headers we can decode them to text.
1480+
for length, raw_keyword, raw_value in raw_headers:
14721481
# Normally, we could just use "utf-8" as the encoding and "strict"
14731482
# as the error handler, but we better not take the risk. For
14741483
# example, GNU tar <= 1.23 is known to store filenames it cannot
14751484
# translate to UTF-8 as raw strings (unfortunately without a
14761485
# hdrcharset=BINARY header).
14771486
# We first try the strict standard encoding, and if that fails we
14781487
# fall back on the user's encoding and error handler.
1479-
keyword = self._decode_pax_field(keyword, "utf-8", "utf-8",
1488+
keyword = self._decode_pax_field(raw_keyword, "utf-8", "utf-8",
14801489
tarfile.errors)
14811490
if keyword in PAX_NAME_FIELDS:
1482-
value = self._decode_pax_field(value, encoding, tarfile.encoding,
1491+
value = self._decode_pax_field(raw_value, encoding, tarfile.encoding,
14831492
tarfile.errors)
14841493
else:
1485-
value = self._decode_pax_field(value, "utf-8", "utf-8",
1494+
value = self._decode_pax_field(raw_value, "utf-8", "utf-8",
14861495
tarfile.errors)
14871496

14881497
pax_headers[keyword] = value
1489-
pos += length
14901498

14911499
# Fetch the next header.
14921500
try:

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, "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

0 commit comments

Comments
 (0)