Skip to content

Commit b38be2e

Browse files
gh-157190: Follow symlinks when extracting tarfile hard links (GH-157191)
1 parent fd569ea commit b38be2e

2 files changed

Lines changed: 23 additions & 1 deletion

File tree

Lib/tarfile.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2815,7 +2815,11 @@ def makelink_with_filter(self, tarinfo, targetpath,
28152815
if os.path.lexists(targetpath):
28162816
# Avoid FileExistsError on following os.link.
28172817
os.unlink(targetpath)
2818-
os.link(tarinfo._link_target, targetpath)
2818+
# Resolve the target so the hard link points to the file
2819+
# itself. Otherwise os.link() may duplicate a symlink to a
2820+
# shallower location, where its relative target escapes the
2821+
# destination directory. (CVE-2026-82049)
2822+
os.link(os.path.realpath(tarinfo._link_target), targetpath)
28192823
return
28202824
except symlink_exception:
28212825
keyerror_to_extracterror = True

Lib/test/test_tarfile.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4655,6 +4655,24 @@ def test_sneaky_hardlink_fallback_deep(self):
46554655
self.expect_file("a/b/s", symlink_to=os.path.join('..', 'escape'))
46564656
self.expect_file("s", symlink_to=os.path.join('..', 'escape'))
46574657

4658+
@symlink_test
4659+
@os_helper.skip_unless_hardlink
4660+
def test_sneaky_hardlink_relocation(self):
4661+
with ArchiveMaker() as arc:
4662+
arc.add("a/escape", content="decoy")
4663+
arc.add("a/b/s", symlink_to=os.path.join("..", "escape"))
4664+
arc.add("s", hardlink_to=os.path.join("a", "b", "s"))
4665+
4666+
for filter in 'data', 'tar':
4667+
with self.subTest(filter), self.check_context(arc.open(), filter):
4668+
self.expect_file("a/escape", content="decoy")
4669+
if os_helper.can_symlink():
4670+
self.expect_file("a/b/s", symlink_to=os.path.join('..', 'escape'))
4671+
else:
4672+
self.expect_file("a/b/s", content="decoy")
4673+
self.expect_file("s", content="decoy")
4674+
self.assertFalse((self.destdir / "s").is_symlink())
4675+
46584676
@symlink_test
46594677
def test_exfiltration_via_symlink(self):
46604678
# (CVE-2025-4138)

0 commit comments

Comments
 (0)