From 8ed613570c484639126f8cb721e4b938d190dc7b Mon Sep 17 00:00:00 2001 From: Yun Seongmin Date: Fri, 27 Nov 2026 22:12:45 +0900 Subject: [PATCH] gh-162741: Fix tarfile errors="strict" failing on names cut mid-character With errors="strict", tarfile could not read an archive whose ustar name, linkname, uname or gname field holds a value cut in the middle of a multibyte character, even when a GNU longname or longlink header or a pax header (extended or global) replaces that field. Such fields are written for paths longer than 100 bytes, for example by tarfile itself with GNU_FORMAT and by GNU tar and bsdtar in the gnu and pax formats. TarInfo._frombuf() now keeps the decoding error of a text field and stores the field decoded with "surrogateescape" in the meantime. The error is forgotten when the field is replaced. Otherwise it is raised once the member has been read, as before: before any later error and without skipping the member. All headers read for the member are checked, so a subclass whose _proc_member() returns a new object still gets the error. The fields of GNU longname, longlink and pax headers themselves are not used and are no longer checked. Error handlers that do not raise give the same results as before. --- Lib/tarfile.py | 169 +++++++++++---- Lib/test/test_tarfile.py | 197 ++++++++++++++++++ ...-11-27-22-12-28.gh-issue-162741.RpUSTI.rst | 5 + 3 files changed, 332 insertions(+), 39 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2026-11-27-22-12-28.gh-issue-162741.RpUSTI.rst diff --git a/Lib/tarfile.py b/Lib/tarfile.py index ca6aea8396aaa1e..4e4977fdd245ca2 100644 --- a/Lib/tarfile.py +++ b/Lib/tarfile.py @@ -170,6 +170,47 @@ def nts(s, encoding, errors): s = s[:p] return s.decode(encoding, errors) +def _nts_deferred(tarinfo, keyword, s, encoding, errors): + """Like nts(), but a decoding error is not raised yet, because a GNU + longname or the pax header keyword may replace the field. Until + then the field holds the value decoded with "surrogateescape". + """ + try: + return nts(s, encoding, errors) + except UnicodeDecodeError as exc: + try: + value = nts(s, encoding, "surrogateescape") + except UnicodeError: + raise exc from None + tarinfo._decode_errors = (getattr(tarinfo, "_decode_errors", ()) + + ((keyword, exc),)) + return value + +def _read_member(tarinfo, tarfile, dircheck): + """Read the next member with tarinfo._fromtarfile(), and raise the first + decoding error of a header field that was not replaced, as nts() + would have: before any later error and without skipping the member. + """ + offset = tarfile.offset + tarfile._member_headers = headers = [] + try: + member = tarinfo._fromtarfile(tarfile, dircheck=dircheck) + except Exception: + _check_headers(tarfile, headers, offset) + raise + finally: + tarfile._member_headers = None + _check_headers(tarfile, headers + [member], offset) + return member + +def _check_headers(tarfile, headers, offset): + """Raise the first decoding error left in headers. + """ + for header in headers: + if getattr(header, "_decode_errors", None): + tarfile.offset = offset + TarInfo._check_decode_errors(header) + def nti(s): """Convert a number field to a python number. """ @@ -983,6 +1024,7 @@ class TarInfo(object): sparse = 'Sparse member information.', _sparse_structs = None, _link_target = None, + _decode_errors = None, ) def __init__(self, name=""): @@ -1342,7 +1384,9 @@ def frombuf(cls, buf, encoding, errors): To support the old v7 tar format AREGTYPE headers are transformed to DIRTYPE headers if their name ends in '/'. """ - return cls._frombuf(buf, encoding, errors) + obj = cls._frombuf(buf, encoding, errors) + obj._check_decode_errors() + return obj @classmethod def _frombuf(cls, buf, encoding, errors, *, dircheck=True): @@ -1352,6 +1396,10 @@ def _frombuf(cls, buf, encoding, errors, *, dircheck=True): be normalized to ``DIRTYPE`` if the name ends in a trailing slash. ``dircheck`` must be set to ``False`` if this function is called on a follow-up header such as ``GNUTYPE_LONGNAME``. + + Decoding errors of text fields that "surrogateescape" can decode are + kept in the object; frombuf() and fromtarfile() raise them unless + the fields are replaced. """ if len(buf) == 0: raise EmptyHeaderError("empty header") @@ -1365,43 +1413,48 @@ def _frombuf(cls, buf, encoding, errors, *, dircheck=True): raise InvalidHeaderError("bad checksum") obj = cls() - obj.name = nts(buf[0:100], encoding, errors) - obj.mode = nti(buf[100:108]) - obj.uid = nti(buf[108:116]) - obj.gid = nti(buf[116:124]) - obj.size = nti(buf[124:136]) - obj.mtime = nti(buf[136:148]) - obj.chksum = chksum - obj.type = buf[156:157] - obj.linkname = nts(buf[157:257], encoding, errors) - obj.uname = nts(buf[265:297], encoding, errors) - obj.gname = nts(buf[297:329], encoding, errors) - obj.devmajor = nti(buf[329:337]) - obj.devminor = nti(buf[337:345]) - prefix = nts(buf[345:500], encoding, errors) - - # Old V7 tar format represents a directory as a regular - # file with a trailing slash. - if dircheck and obj.type == AREGTYPE and obj.name.endswith("/"): - obj.type = DIRTYPE - - # The old GNU sparse format occupies some of the unused - # space in the buffer for up to 4 sparse structures. - # Save them for later processing in _proc_sparse(). - if obj.type == GNUTYPE_SPARSE: - pos = 386 - structs = [] - for i in range(4): - try: - offset = nti(buf[pos:pos + 12]) - numbytes = nti(buf[pos + 12:pos + 24]) - except ValueError: - break - structs.append((offset, numbytes)) - pos += 24 - isextended = bool(buf[482]) - origsize = nti(buf[483:495]) - obj._sparse_structs = (structs, isextended, origsize) + try: + obj.name = _nts_deferred(obj, "path", buf[0:100], encoding, errors) + obj.mode = nti(buf[100:108]) + obj.uid = nti(buf[108:116]) + obj.gid = nti(buf[116:124]) + obj.size = nti(buf[124:136]) + obj.mtime = nti(buf[136:148]) + obj.chksum = chksum + obj.type = buf[156:157] + obj.linkname = _nts_deferred(obj, "linkpath", buf[157:257], encoding, errors) + obj.uname = _nts_deferred(obj, "uname", buf[265:297], encoding, errors) + obj.gname = _nts_deferred(obj, "gname", buf[297:329], encoding, errors) + obj.devmajor = nti(buf[329:337]) + obj.devminor = nti(buf[337:345]) + prefix = _nts_deferred(obj, "path", buf[345:500], encoding, errors) + + # Old V7 tar format represents a directory as a regular + # file with a trailing slash. + if dircheck and obj.type == AREGTYPE and obj.name.endswith("/"): + obj.type = DIRTYPE + + # The old GNU sparse format occupies some of the unused + # space in the buffer for up to 4 sparse structures. + # Save them for later processing in _proc_sparse(). + if obj.type == GNUTYPE_SPARSE: + pos = 386 + structs = [] + for i in range(4): + try: + offset = nti(buf[pos:pos + 12]) + numbytes = nti(buf[pos + 12:pos + 24]) + except ValueError: + break + structs.append((offset, numbytes)) + pos += 24 + isextended = bool(buf[482]) + origsize = nti(buf[483:495]) + obj._sparse_structs = (structs, isextended, origsize) + except Exception: + # nts() would have raised the error of a field before. + obj._check_decode_errors() + raise # Remove redundant slashes from directories. if obj.isdir(): @@ -1417,16 +1470,23 @@ def fromtarfile(cls, tarfile): """Return the next TarInfo object from TarFile object tarfile. """ - return cls._fromtarfile(tarfile) + return _read_member(cls, tarfile, dircheck=True) @classmethod def _fromtarfile(cls, tarfile, *, dircheck=True): """ See dircheck documentation in _frombuf(). """ + headers = getattr(tarfile, "_member_headers", None) + if headers is None: + # Called by a fromtarfile() override of a subclass. + return _read_member(cls, tarfile, dircheck=dircheck) buf = tarfile.fileobj.read(BLOCKSIZE) obj = cls._frombuf(buf, tarfile.encoding, tarfile.errors, dircheck=dircheck) obj.offset = tarfile.fileobj.tell() - BLOCKSIZE + # Check every header, because _proc_member() of a subclass may + # return a new object that was created from the fields of obj. + headers.append(obj) return obj._proc_member(tarfile) #-------------------------------------------------------------------------- @@ -1479,6 +1539,8 @@ def _proc_gnulong(self, tarfile): """Process the blocks that hold a GNU longname or longlink member. """ + # The fields of this header are not used. + self._forget_decode_error() buf = _safe_read(tarfile.fileobj, self._block(self.size)) # Fetch the next header and process it. @@ -1492,8 +1554,10 @@ def _proc_gnulong(self, tarfile): next.offset = self.offset if self.type == GNUTYPE_LONGNAME: next.name = nts(buf, tarfile.encoding, tarfile.errors) + next._forget_decode_error("path") elif self.type == GNUTYPE_LONGLINK: next.linkname = nts(buf, tarfile.encoding, tarfile.errors) + next._forget_decode_error("linkpath") # Remove redundant slashes from directories. This is to be consistent # with frombuf(). @@ -1534,6 +1598,8 @@ def _proc_pax(self, tarfile): """Process an extended or global header as described in POSIX.1-2008. """ + # The fields of this header are not used. + self._forget_decode_error() # Read the header information. buf = _safe_read(tarfile.fileobj, self._block(self.size)) @@ -1715,6 +1781,7 @@ def _apply_pax_info(self, pax_headers, encoding, errors): for keyword, value in pax_headers.items(): if keyword == "GNU.sparse.name": setattr(self, "path", value) + self._forget_decode_error("path") elif keyword == "GNU.sparse.size": setattr(self, "size", int(value)) elif keyword == "GNU.sparse.realsize": @@ -1728,9 +1795,30 @@ def _apply_pax_info(self, pax_headers, encoding, errors): if keyword == "path": value = value.rstrip("/") setattr(self, keyword, value) + if keyword in PAX_NAME_FIELDS: + self._forget_decode_error(keyword) self.pax_headers = pax_headers.copy() + def _forget_decode_error(self, keyword=None): + """Forget the decoding error of a header field that was replaced, + or of all fields if keyword is None. + """ + if errors := getattr(self, "_decode_errors", None): + errors = tuple(item for item in errors + if keyword is not None and item[0] != keyword) + if errors: + self._decode_errors = errors + else: + del self._decode_errors + + def _check_decode_errors(self): + """Raise the first decoding error of a header field that was not + replaced. + """ + if errors := getattr(self, "_decode_errors", None): + raise errors[0][1] from None + def _decode_pax_field(self, value, encoding, fallback_encoding, fallback_errors): """Decode a single field from a pax record. """ @@ -1825,6 +1913,9 @@ class TarFile(object): extraction_filter = None # The default filter for extraction. + _member_headers = None # The headers read for the member that + # TarInfo.fromtarfile() is reading. + def __init__(self, name=None, mode="r", fileobj=None, format=None, tarinfo=None, dereference=None, ignore_zeros=None, encoding=None, errors="surrogateescape", pax_headers=None, debug=None, diff --git a/Lib/test/test_tarfile.py b/Lib/test/test_tarfile.py index 1927ff227d5356f..cffa9fc6c12e855 100644 --- a/Lib/test/test_tarfile.py +++ b/Lib/test/test_tarfile.py @@ -2853,6 +2853,14 @@ def test_create_pax_header(self): + bytes(100) + b'ustar\x0000' + bytes(247)) +def _replace_field(buf, offset, start, end, value): + # Replace a field of the header block at offset, and the checksum. + header = buf[offset:offset + tarfile.BLOCKSIZE] + header[start:end] = value.ljust(end - start, b"\0") + header[148:156] = b"%06o\0 " % tarfile.calc_chksums(header)[0] + buf[offset:offset + tarfile.BLOCKSIZE] = header + + class UnicodeTest: def test_iso8859_1_filename(self): @@ -2972,6 +2980,30 @@ def test_unicode_longname4(self): self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "012345\xff\xff") self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "0123456\xff\xff", ValueError) + def test_strict_invalid_name(self): + header = bytearray(tarfile.TarInfo("name").tobuf(self.format)) + _replace_field(header, 0, 0, 100, b"bad\xff") + frombuf = tarfile.TarInfo.frombuf + with self.assertRaises(UnicodeDecodeError) as cm: + frombuf(header, "utf-8", "strict") + self.assertEqual(cm.exception.object, b"bad\xff") + # The uname cannot be decoded with "surrogateescape" either. + utf7 = bytearray(header) + _replace_field(utf7, 0, 265, 297, b"+A") + with self.assertRaises(UnicodeDecodeError) as cm: + frombuf(utf7, "utf-7", "strict") + self.assertEqual(cm.exception.object, b"bad\xff") + + # The name is decoded before the mode. + _replace_field(header, 0, 100, 108, b"bad") + self.assertRaises(UnicodeDecodeError, frombuf, header, "utf-8", + "strict") + buf = tarfile.TarInfo("first").tobuf(self.format) + header + for ignore_zeros in (False, True): + with tarfile.open(fileobj=io.BytesIO(buf), errors="strict", + ignore_zeros=ignore_zeros) as tar: + self.assertRaises(UnicodeDecodeError, tar.getmembers) + def _test_ustar_name(self, name, exc=None): with tarfile.open(tmpname, "w", format=self.format, encoding="utf-8") as tar: t = tarfile.TarInfo(name) @@ -3030,6 +3062,129 @@ def test_bad_pax_header(self): except KeyError: self.fail("unable to read bad GNU tar pax header") + def test_strict_longname_cut_mid_character(self): + # The name and linkname fields of the header after a GNU longname + # and longlink hold their first 100 bytes, here cut mid-character. + t = tarfile.TarInfo("a" * 99 + "\xe4") + t.type = tarfile.SYMTYPE + t.linkname = "b" * 99 + "\uac00" + fobj = io.BytesIO() + with tarfile.open(fileobj=fobj, mode="w", format=self.format, + encoding="utf-8") as tar: + tar.addfile(t) + tar.addfile(tarfile.TarInfo("last")) + # The fields of the longname header itself are not used. + buf = bytearray(fobj.getvalue()) + _replace_field(buf, 0, 265, 297, b"\xff") + + for mode in ("r:", "r|"): + with self.subTest(mode=mode): + with tarfile.open(fileobj=io.BytesIO(buf), mode=mode, + encoding="utf-8", errors="strict") as tar: + names = [(m.name, m.linkname) for m in tar] + self.assertEqual(names, [(t.name, t.linkname), ("last", "")]) + + def test_strict_invalid_fields(self): + # The longname itself and the fields that the longname or the pax + # header do not replace are still decoded with the errors handler. + def header(name, uname): + t = tarfile.TarInfo(name) + t.uname = uname + return t.tobuf(self.format, "utf-8", "surrogateescape") + + invalid = "a" * 100 + "\udcff" + cut = "a" * 99 + "\xe4" + pax = tarfile.TarInfo(cut).tobuf(tarfile.PAX_FORMAT) + for case, buf, value in ( + ("longname", header(invalid, ""), b"a" * 100 + b"\xff"), + ("uname", header(cut, "\udcff"), b"\xff"), + ("longname and uname", header(invalid, "\udcff"), b"\xff"), + ("pax and uname", pax[:-tarfile.BLOCKSIZE] + + header(cut, "\udcff")[-tarfile.BLOCKSIZE:], b"\xff")): + with self.subTest(case=case): + with self.assertRaises(UnicodeDecodeError) as cm: + tarfile.open(fileobj=io.BytesIO(buf), encoding="utf-8", + errors="strict") + self.assertEqual(cm.exception.object, value) + + def test_strict_invalid_field_read_again(self): + t = tarfile.TarInfo("a" * 99 + "\xe4") + t.uname = "\udcff" + buf = (tarfile.TarInfo("first").tobuf(self.format) + + t.tobuf(self.format, "utf-8", "surrogateescape") + + tarfile.TarInfo("last").tobuf(self.format)) + with tarfile.open(fileobj=io.BytesIO(buf), encoding="utf-8", + errors="strict") as tar: + # The member is not skipped. + for _ in range(2): + with self.assertRaises(UnicodeDecodeError) as cm: + tar.getmembers() + self.assertEqual(cm.exception.object, b"\xff") + + def test_strict_subclasses(self): + # Subclasses that override private methods read valid archives as + # before, and still get the errors of the fields that are not + # replaced, although maybe not for the fields that are replaced. + class NewObject(tarfile.TarInfo): + def __init__(self, name=""): + pass + + def _proc_member(self, tarfile): + member = super()._proc_member(tarfile) + new = type(self).__new__(type(self)) + for attr in "name", "type", "uname", "offset_data": + setattr(new, attr, getattr(member, attr)) + return new + + class OldFromtarfile(tarfile.TarInfo): + # fromtarfile() as written before _fromtarfile() existed. + @classmethod + def fromtarfile(cls, tf): + buf = tf.fileobj.read(tarfile.BLOCKSIZE) + obj = cls.frombuf(buf, tf.encoding, tf.errors) + obj.offset = tf.fileobj.tell() - tarfile.BLOCKSIZE + return obj._proc_member(tf) + + class OwnFromtarfile(tarfile.TarInfo): + @classmethod + def _fromtarfile(cls, tf, *, dircheck=True): + buf = tf.fileobj.read(tarfile.BLOCKSIZE) + obj = cls._frombuf(buf, tf.encoding, tf.errors, + dircheck=dircheck) + obj.offset = tf.fileobj.tell() - tarfile.BLOCKSIZE + return obj._proc_member(tf) + + name = "a" * 99 + "\xe4" + valid = (tarfile.TarInfo("b" * 101).tobuf(self.format) + + tarfile.TarInfo(name).tobuf(tarfile.PAX_FORMAT)) + invalid = {} + for case, t in (("ustar", tarfile.TarInfo("a")), + ("longname", tarfile.TarInfo(name))): + t.uname = "\udcff" + invalid[case] = t.tobuf(self.format, "utf-8", "surrogateescape") + for tarinfo in NewObject, OldFromtarfile, OwnFromtarfile: + for errors in "surrogateescape", "strict": + with self.subTest(tarinfo=tarinfo, errors=errors): + with tarfile.open(fileobj=io.BytesIO(valid), + encoding="utf-8", errors=errors, + tarinfo=tarinfo) as tar: + self.assertEqual(tar.getnames(), ["b" * 101, name]) + for case, buf in invalid.items(): + with self.subTest(tarinfo=tarinfo, case=case): + with self.assertRaises(UnicodeDecodeError): + tarfile.open(fileobj=io.BytesIO(buf), encoding="utf-8", + errors="strict", tarinfo=tarinfo) + + # Neither when fromtarfile() of a subclass is called directly. + buf = (tarfile.TarInfo("first").tobuf(self.format) + + invalid["longname"]) + with tarfile.open(fileobj=io.BytesIO(buf), encoding="utf-8", + errors="strict") as tar: + for _ in range(2): + tar.fileobj.seek(tar.offset) + self.assertRaises(UnicodeDecodeError, + OldFromtarfile.fromtarfile, tar) + class PAXUnicodeTest(UnicodeTest, unittest.TestCase): @@ -3050,6 +3205,48 @@ def test_binary_header(self): except KeyError: self.fail("unable to read POSIX.1-2008 binary header") + def test_strict_ustar_fields_cut_mid_character(self): + # Other implementations store the full values in the pax header and + # their first bytes in the ustar fields, possibly mid-character. + t = tarfile.TarInfo("a" * 99 + "\xe4") + t.type = tarfile.SYMTYPE + t.linkname = "b" * 99 + "\uac00" + t.uname = "u" * 31 + "\xe4" + t.gname = "g" * 31 + "\xe4" + pax = bytearray(t.tobuf(tarfile.PAX_FORMAT)) + ustar = t.tobuf(tarfile.GNU_FORMAT, "utf-8", "strict") + # The fields of the pax header itself are not used. + _replace_field(pax, 0, 0, 100, b"PaxHeaders/\xe4") + buf = pax[:-tarfile.BLOCKSIZE] + ustar[-tarfile.BLOCKSIZE:] + buf += tarfile.TarInfo("last").tobuf() + + with tarfile.open(fileobj=io.BytesIO(buf), encoding="utf-8", + errors="strict") as tar: + names = [(m.name, m.linkname, m.uname, m.gname) for m in tar] + self.assertEqual(names, [(t.name, t.linkname, t.uname, t.gname), + ("last", "", "", "")]) + + def test_strict_path_cut_mid_character(self): + name = "a" * 99 + "\xe4" + ustar = tarfile.TarInfo(name).tobuf( + tarfile.GNU_FORMAT, "utf-8", "strict")[-tarfile.BLOCKSIZE:] + sparse = tarfile.TarInfo("sparse") + sparse.pax_headers = {"GNU.sparse.name": name} + prefix = bytearray(tarfile.TarInfo("a").tobuf(tarfile.USTAR_FORMAT)) + _replace_field(prefix, 0, 345, 500, name.encode()[:100]) + for case, pax, header, path in ( + ("global path", + tarfile.TarInfo.create_pax_global_header({"path": name}), + ustar, name), + ("GNU.sparse.name", + sparse.tobuf(self.format)[:-tarfile.BLOCKSIZE], ustar, name), + ("ustar prefix", tarfile.TarInfo(name + "/a").tobuf( + self.format)[:-tarfile.BLOCKSIZE], prefix, name + "/a")): + with self.subTest(case=case): + with tarfile.open(fileobj=io.BytesIO(pax + header), + encoding="utf-8", errors="strict") as tar: + self.assertEqual(tar.getnames(), [path]) + class AppendTestBase: # Test append mode (cp. patch #1652681). diff --git a/Misc/NEWS.d/next/Library/2026-11-27-22-12-28.gh-issue-162741.RpUSTI.rst b/Misc/NEWS.d/next/Library/2026-11-27-22-12-28.gh-issue-162741.RpUSTI.rst new file mode 100644 index 000000000000000..81f55dba14fc143 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-27-22-12-28.gh-issue-162741.RpUSTI.rst @@ -0,0 +1,5 @@ +Fix :mod:`tarfile` failing to read an archive with ``errors="strict"`` when a +name, link name, user or group name in a ustar header is cut in the middle of +a multibyte character but is replaced by a GNU long name or a pax header. +Such archives are written for paths longer than 100 bytes, for example with +:data:`~tarfile.GNU_FORMAT`.