Skip to content

donate-cpu: keep extracted package files inside the temp folder - #8973

Open
Nussu06 wants to merge 6 commits into
cppcheck-opensource:mainfrom
Nussu06:donate-cpu-unpack-containment
Open

Nussu06 wants to merge 6 commits into
cppcheck-opensource:mainfrom
Nussu06:donate-cpu-unpack-containment

Conversation

@Nussu06

@Nussu06 Nussu06 commented Oct 28, 2026

Copy link
Copy Markdown
Contributor

unpack_package in tools/donate_cpu_lib.py only skips archive members whose name starts with '/' or '..', so a package tarball containing pkg/../../outside/x.c, or a symlink pkg/inc.h pointing at another directory followed by pkg/inc.h/x.c, writes source files outside work_path/temp when donate-cpu.py, test-my-pr.py or compare-valueflow-options.py unpack it on Python before 3.14 (3.14 refuses these by default, but the uncaught OutsideDestinationError aborts the run). Each member's destination, and the target of symlink and hardlink members, is now resolved with realpath and skipped unless it stays inside the temp folder, and filter='data' is passed where tarfile supports it; links that stay inside the package, such as include/a.h -> ../src/a.h, are still extracted. Added test_unpack_package_outside_temp, which fails on main with Python 3.9 and 3.12 and passes with the fix on 3.9, 3.12 and 3.14, and bumped CLIENT_VERSION to 1.4.1. I don't have Trac access, so could you create a ticket for this? I'll update the title once there is a number.

@danmar

danmar commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator

I suggest you rebase and see if CI will become green. There are compiler errors that might have been fixed.

@Nussu06
Nussu06 force-pushed the donate-cpu-unpack-containment branch from a90349e to c24476b Compare November 13, 2026 18:33
@Nussu06

Nussu06 commented Nov 13, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto current main, it applied cleanly and donate_cpu_lib_test.py still passes locally. Let's see what CI says now. Separately, could one of you create a Trac ticket for this? I don't have access, and I'll put the number in the title once it exists.

@dmcppcheck dmcppcheck left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

The fix is incomplete when Python has no tarfile.data_filter, which is the case it is meant for. The new realpath check runs on the member from the loop, but extraction still calls tf.extract(member.name, ...). Extracting by name looks up the last member with that name in the archive, so a harmless first entry can pass the check while a later entry with the same name, such as a hardlink or symlink that points outside temp, gets extracted. Hardlinks also defeat the realpath check of later members: realpath cannot tell that a file inside temp is a hardlink to a file outside it, and a later regular-file member that writes through that path writes to the outside file. On Python versions with data_filter (3.12 here), the filter still catches this. The fix is to pass the member object to tf.extract. Apart from that I found no new problems.

Comments

# Comment By Where Status
1 extract(member.name) extracts the last member with that name, not the one that was checked AI review tools/donate_cpu_lib.py:409 🆕 New

@Nussu06, please fix, resolve or reply to the open and new comments: #1.

Testing

  • I did not build cppcheck or testrunner. The PR only changes tools/donate_cpu_lib.py and its Python test, so no C++ code is affected.
  • PYTHONPATH=tools python3 -m pytest -Werror -q test/tools/donate_cpu_lib_test.py in pr/ with Python 3.12.3: 3 passed.
  • The same test file run against base/: test_unpack_package_outside_temp fails as expected, and the other 2 pass.
  • I checked how name lookup behaves with duplicate member names, which is what the finding depends on:
# scratch/dup.py
import io, tarfile, tempfile, os
d = tempfile.mkdtemp(); p = os.path.join(d, 'x.tar')
with tarfile.open(p, 'w') as tf:
    for c in (b'first\n', b'second\n'):
        i = tarfile.TarInfo('a.c'); i.size = len(c); tf.addfile(i, io.BytesIO(c))
with tarfile.open(p) as tf:
    for m in tf:
        tf.extract(m.name, d, filter='data')
        print(open(os.path.join(d, 'a.c')).read().strip())
        break

python3 -I dup.py prints second. On the first loop iteration, tf.extract(m.name) extracted the second member, not the one the loop was on.

  • I did not reproduce a full escape from temp. The impact on Python versions without data_filter comes from reading the code: the check runs on one member while another member with the same name is extracted.

Automated review of c24476b by Claude. The pull request was built and tested locally.

Comment thread tools/donate_cpu_lib.py Outdated
continue
try:
tf.extract(member.name, temp_path)
tf.extract(member.name, temp_path, **extract_args)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

The safety check above validates member, but tf.extract(member.name, ...) goes through getmember(name), which returns the last member with that name in the archive. A tarball can contain a harmless pkg/a.c first and a later pkg/a.c that is a hardlink or symlink pointing outside temp. The first entry passes the check, and extracting it creates the later, unchecked link. The later entry is then skipped, but by that point the link has already been created.

With filter='data' the filter still rejects the link, but on Python versions without tarfile.data_filter (the case this PR protects) nothing stops it. A hardlink is also invisible to the realpath check, so a later regular-file member that writes through that path (for example through a directory symlink that stays inside temp) writes into the file outside temp.

Passing the member object fixes this:

tf.extract(member, temp_path, **extract_args)

It would be worth adding a duplicate-name case to test_unpack_package_outside_temp.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, extracting by name picks up the last entry with that name, so the check and the extraction could be looking at different members. It now passes the member object to tf.extract. I added test_unpack_package_duplicate_name, which has a regular pkg/sym.c followed by a same-named symlink to a file outside temp, and the same for a hardlink. It fails with the old code on Python 3.10.11 (no data_filter) and passes with the fix on 3.10 and 3.11. The Trac ticket is still open on my side, if someone can create one I'll put the number in the title.

@dmcppcheck dmcppcheck left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

On Python versions without tarfile.data_filter, which this PR is meant to protect, a symlink that points outside temp can still be created. The symlink target is resolved against os.path.dirname(member_path), but member_path has already gone through realpath. If the archive first creates pkg/inc.h as a symlink to a deep path inside temp, a second pkg/inc.h symlink to ../../outside is checked against that deep directory and looks inside temp. tarfile then replaces the link at temp/pkg/inc.h, so the new link resolves relative to temp/pkg and points outside. Later members that write through the link are still skipped. But cppcheck follows directory symlinks (stat in cli/filelister.cpp), so donate-cpu would analyse files outside the package, and their results would be uploaded. I found no other new problems, and the earlier comment about extracting by name is fixed.

Comments

# Comment By Where Status
1 extract(member.name) extracts the last member with that name, not the checked one AI review general ✅ Fixed
2 Symlink target is resolved from the realpath of an existing link, so a replacing symlink can point outside temp AI review tools/donate_cpu_lib.py:386 🆕 New

@Nussu06, please fix, resolve or reply to the open and new comments: #2.

Testing

  • I did not build cppcheck or testrunner, because the PR only changes tools/donate_cpu_lib.py and its Python test.
  • PYTHONPATH=tools python3 -m pytest -q test/tools/donate_cpu_lib_test.py in pr/ with Python 3.12.3: 4 passed. They also pass with tarfile.data_filter deleted, to simulate an older Python.
  • I reproduced the symlink escape with Python 3.12 and data_filter removed:
# scratch/esc.py  — run: python3 -I esc.py /work/pr/tools nofilter
import io, os, sys, tarfile, tempfile
sys.path.insert(0, sys.argv[1])
if len(sys.argv) > 2:
    del tarfile.data_filter   # simulate Python without extraction filters
import donate_cpu_lib as d
w = tempfile.mkdtemp(); out = os.path.join(w, 'outside'); os.mkdir(out)
open(os.path.join(out, 'secret.c'), 'w').write('int secret;\n')
tgz = os.path.join(w, 'p.tgz')
def add(tf, name, link=None):
    i = tarfile.TarInfo(name); data = b'int x;\n'
    if link: i.type = tarfile.SYMTYPE; i.linkname = link; data = b''
    else: i.size = len(data)
    tf.addfile(i, io.BytesIO(data))
with tarfile.open(tgz, 'w:gz') as tf:
    add(tf, 'pkg/main.c')
    add(tf, 'pkg/inc.h', 'a/b/c')            # inside temp
    add(tf, 'pkg/inc.h', '../../outside')    # checked relative to temp/pkg/a/b, created in temp/pkg
tp, found = d.unpack_package(w, tgz)
l = os.path.join(tp, 'pkg', 'inc.h')
print('link:', os.readlink(l) if os.path.islink(l) else None, '->', os.path.realpath(l))
print('listing via temp:', os.listdir(l) if os.path.isdir(l) else None)

Output without the filter:

extracted 3 of 3 files (skipped 0)
link: ../../outside -> /tmp/tmpbyf2t84d/outside
listing via temp: ['secret.c']

With filter='data' (the normal 3.12 run), the second link is rejected and temp/pkg/inc.h stays a/b/c.


Automated review of 998d32a by Claude. The pull request was built and tested locally.

Comment thread tools/donate_cpu_lib.py Outdated
member_path = os.path.realpath(os.path.join(temp_path, member.name))
link_path = None
if member.issym():
link_path = os.path.realpath(os.path.join(os.path.dirname(member_path), member.linkname))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

member_path has already gone through realpath. If an earlier member created a symlink with the same name (for example pkg/inc.h -> a/b/c), os.path.dirname(member_path) is temp/pkg/a/b, not temp/pkg. tarfile's makelink unlinks the old link and creates the new one at temp/pkg/inc.h, so its relative target resolves from temp/pkg.

Example: a second member pkg/inc.h -> ../../outside passes this check, because from the deep directory it resolves to temp/outside. On disk it points to work_path/outside. I reproduced this with data_filter removed: all 3 members were extracted, and os.listdir(temp/pkg/inc.h) listed the files in the outside folder. cppcheck follows directory symlinks when it scans temp (stat in cli/filelister.cpp), so files outside the package would be analysed and reported.

Resolve the link target from the real parent directory of the unresolved destination instead:

parent = os.path.realpath(os.path.dirname(os.path.join(temp_path, member.name)))
link_path = os.path.realpath(os.path.join(parent, member.linkname))

This case could be added to test_unpack_package_duplicate_name.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, realpath on the destination follows the earlier pkg/inc.h link, so the target was resolved from temp/pkg/a/b instead of temp/pkg. The link target is now resolved from the realpath of the unresolved parent directory, as you suggested. I added the pkg/inc.h -> a/b/c followed by pkg/inc.h -> ../../outside case to test_unpack_package_duplicate_name. The test file passes on 3.10.11 (no data_filter) and 3.11, but my Windows box can't create symlinks, so that new case only really exercises the code on the Linux CI runs. A Trac ticket is still needed for the title, could one of you create it?

@dmcppcheck dmcppcheck left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

On Python versions without tarfile.data_filter, a symlink that points outside temp can still be created. The check resolves the link target with realpath when the link is extracted. Components of the target that don't exist yet are then normalised as plain text, but a later member can turn them into a symlink. For example, pkg/l.h -> d.h/../../outside is checked while d.h doesn't exist yet, so it looks like temp/outside. A later pkg/d.h -> . passes its own check. After both are extracted, l.h resolves to work_path/outside. With filter='data' (Python 3.12.3 here) the link is rewritten and stays inside temp. I found no other new problems. The two earlier findings (extracting by name, and resolving the target through an existing link) are fixed.

Comments

# Comment By Where Status
1 extract(member.name) extracts the last member with that name, not the checked one AI review general ✅ Fixed
2 Symlink target resolved through realpath of an existing same-named link can point outside temp AI review tools/donate_cpu_lib.py:386 ✅ Fixed
3 Symlink target checked with realpath before later members exist; a later symlink can redirect it outside temp AI review tools/donate_cpu_lib.py:388 🆕 New

@Nussu06, please fix, resolve or reply to the open and new comments: #3.

Testing

  • I did not build cppcheck or testrunner: the PR only changes tools/donate_cpu_lib.py and its Python test.
  • PYTHONPATH=tools python3 -m pytest -q test/tools/donate_cpu_lib_test.py in pr/ with Python 3.12.3: 4 passed.
  • Escape through a symlink that is created later. I deleted tarfile.data_filter to simulate an older Python:
# scratch/esc2.py — run: python3 -I esc2.py /work/pr/tools nofilter
import io, os, sys, tarfile, tempfile
sys.path.insert(0, sys.argv[1])
if len(sys.argv) > 2:
    del tarfile.data_filter
import donate_cpu_lib as d
w = tempfile.mkdtemp(); out = os.path.join(w, 'outside'); os.mkdir(out)
open(os.path.join(out, 'secret.c'), 'w').write('int secret;\n')
tgz = os.path.join(w, 'p.tgz')
def add(tf, name, link=None):
    i = tarfile.TarInfo(name); data = b'int x;\n'
    if link: i.type = tarfile.SYMTYPE; i.linkname = link; data = b''
    else: i.size = len(data)
    tf.addfile(i, io.BytesIO(data))
with tarfile.open(tgz, 'w:gz') as tf:
    add(tf, 'pkg/main.c')
    add(tf, 'pkg/l.h', 'd.h/../../outside')   # d.h does not exist yet -> checked as temp/outside
    add(tf, 'pkg/d.h', '.')                    # inside temp
tp, found = d.unpack_package(w, tgz)
l = os.path.join(tp, 'pkg', 'l.h')
print('link:', os.readlink(l) if os.path.islink(l) else None, '->', os.path.realpath(l))
print('listing via temp:', os.listdir(l) if os.path.isdir(l) else None)

Output without the filter:

extracted 3 of 3 files (skipped 0)
link: d.h/../../outside -> /tmp/tmp62_2fkdw/outside
listing via temp: ['secret.c']

Output with the filter (python3 -I esc2.py /work/pr/tools): the link is rewritten to ../outside -> .../temp/outside, so nothing escapes.


Automated review of 904ee65 by Claude. The pull request was built and tested locally.

Comment thread tools/donate_cpu_lib.py
if member.issym():
# resolve from the directory the link is created in, not through an existing link with the same name
link_parent = os.path.realpath(os.path.dirname(os.path.join(temp_path, member.name)))
link_path = os.path.realpath(os.path.join(link_parent, member.linkname))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

This realpath only resolves the link target as it is on disk right now. Components that don't exist yet are normalised as plain text, but a later member of the archive can make one of them a symlink. Example:

pkg/l.h -> d.h/../../outside   # d.h missing: checked as temp/outside, passes
pkg/d.h -> .                   # temp/pkg, passes

After extraction, temp/pkg/l.h resolves to work_path/outside. I reproduced this with tarfile.data_filter deleted: all 3 members were extracted, and os.listdir(temp/pkg/l.h) listed the outside folder. cppcheck follows directory symlinks when it scans temp, so files outside the package would be analysed.

Checking each member when it is extracted can't catch this, because the target can change after the check. There are two options. One is to reject symlinks whose linkname is absolute or has a .. component. The other is a pass after extraction that removes every symlink under temp whose realpath is outside temp_path. That pass needs to loop until nothing more is removed, because removing one link can change what another resolves to.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, the per-member check can't cover this since the target can still change after the check.

I went with the second option rather than rejecting every '..' in linkname, because in-tree links like include/a.h -> ../src/a.h are common in real packages and I'd rather keep extracting them. After the extraction loop, __remove_escaping_links() walks temp and unlinks every symlink whose realpath is outside temp_path, repeating until a pass finds nothing, and the removed ones move from the extracted to the skipped count. Writes through such a link were already prevented, since each member's own destination is resolved with realpath at the time it is extracted, so this only has to deal with the links themselves.

Added test_unpack_package_link_redirected_later with your pkg/l.h -> d.h/../../outside plus pkg/d.h -> . case, and an in-tree pkg/include/main.c -> ../src/main.c to show those survive. It fails on main (l.h resolving to work_path/outside) and passes with the fix on 3.9.6, 3.10, 3.12 and 3.14, both with filter='data' and with tarfile.data_filter removed. pylint --py-version 3.7 is clean apart from the pre-existing psutil import warning.

Still no Trac ticket for this one, could someone create it so I can put the number in the title?

@dmcppcheck dmcppcheck left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

I found no new escape from temp. The three earlier findings (extracting by name, resolving the target through an existing link, and a link redirected by a later member) are fixed. I checked each one with crafted archives, both with and without tarfile.data_filter.

One remaining problem is that the run can still abort. The PR adds except tarfile.TarError so that filter errors don't stop the run. But a hardlink member whose target is neither on disk nor in the archive raises a bare KeyError from tarfile._find_link_target. That error escapes unpack_package and stops donate-cpu. This is not new: base crashes on the same input. Since the PR is changing this except list anyway, it would be easy to catch it here too.

Comments

# Comment By Where Status
1 Rebase so CI may become green @danmar general 💬 Answered: Author rebased onto current main
2 extract(member.name) extracts the last member with that name, not the checked one AI review tools/donate_cpu_lib.py:409 ✅ Fixed
3 Symlink target resolved through realpath of an existing same-named link can point outside temp AI review tools/donate_cpu_lib.py:386 ✅ Fixed
4 Symlink checked before later members exist can be redirected outside temp by a later link AI review tools/donate_cpu_lib.py:415 ✅ Fixed
5 KeyError from a hardlink to a missing member still escapes and aborts the run AI review tools/donate_cpu_lib.py:446 🆕 New

@Nussu06, please fix, resolve or reply to the open and new comments: #5.

Testing

  • I did not build cppcheck or testrunner, because the PR only changes tools/donate_cpu_lib.py and its Python test.
  • PYTHONPATH=tools python3 -m pytest -q test/tools/donate_cpu_lib_test.py with Python 3.12.3: 5 passed in pr/. In base/, only the 2 original tests exist, and both pass.
  • Escape attempts: I ran scratch/t.py against pr/, both normally and with tarfile.data_filter deleted to simulate an older Python. After unpacking, the script walks temp following links and checks that nothing resolves outside it or shares an inode with the outside file. These cases found no escapes, and the outside folder was unchanged:
    • a chain of links that is redirected later;
    • writing a file through a redirected link;
    • a hardlink through a redirected link (without the filter only);
    • removing one link changing what another resolves to;
    • creating a link through a directory symlink.
  • Uncaught KeyError (also on base):
# scratch/kerr.py — python3 -I kerr.py /work/pr/tools   (add any 2nd arg to delete data_filter)
import io, os, sys, tarfile, tempfile
sys.path.insert(0, sys.argv[1])
if len(sys.argv) > 2: del tarfile.data_filter
import donate_cpu_lib as d
w = tempfile.mkdtemp(); tgz = os.path.join(w, 'p.tgz')
with tarfile.open(tgz, 'w:gz') as tf:
    i = tarfile.TarInfo('pkg/main.c'); i.size = 7; tf.addfile(i, io.BytesIO(b'int x;\n'))
    i = tarfile.TarInfo('pkg/copy.c'); i.type = tarfile.LNKTYPE; i.linkname = 'pkg/missing.c'; tf.addfile(i)
print(d.unpack_package(w, tgz))

The output is the same for pr and base, with and without the filter:

KeyError: "linkname 'pkg/missing.c' not found"

Automated review of a2f33a2 by Claude. The pull request was built and tested locally.

Comment thread tools/donate_cpu_lib.py Outdated
pass
except AttributeError:
pass
except tarfile.TarError:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

A hardlink member whose linkname is neither on disk nor in the archive still aborts the run. For example, pkg/copy.c as a hardlink to pkg/missing.c passes the realpath check because the path is inside temp. Then os.link fails, and tarfile falls back to _find_link_target, which raises a bare KeyError. On Python 3.12.3 this happens both with filter='data' and without the filter. None of these handlers catches KeyError, so unpack_package raises and donate-cpu stops.

This also happens on base, so the PR doesn't cause it. But the PR adds except tarfile.TarError so that filter errors don't abort the run, and this is the same kind of problem. Adding KeyError here would fix it:

                    except (tarfile.TarError, KeyError):
                        pass

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, os.link fails on the missing target and tarfile's fallback lookup raises a bare KeyError, which none of the handlers caught. That except now reads (tarfile.TarError, KeyError), so the member is skipped and the rest of the archive is still unpacked. Added test_unpack_package_hardlink_missing_target with your pkg/copy.c -> pkg/missing.c case. It raises KeyError out of unpack_package without the change and passes with it on 3.12 and 3.14, both with filter='data' and with tarfile.data_filter removed.

A Trac ticket is still missing for this PR, could one of you create it so I can put the number in the title?

@dmcppcheck dmcppcheck left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

On Python without tarfile.data_filter, which is the case this PR is for, a symlink that points outside temp can still be left behind. __remove_escaping_links gives up quietly when it can't remove a link. An archive can cause that on purpose: it creates the links and then adds a directory member with a header-like name and mode 0555. os.remove then fails with EACCES, the function returns, and temp/pkg/x.h/l.h still points to the outside folder. cppcheck would scan that folder. I found no other new problems. The fixes for all earlier comments are in the code, and the PR's tests pass.

Comments

# Comment By Where Status
1 Rebase so CI may become green @danmar general 💬 Answered: Author rebased onto current main
2 extract(member.name) extracts the last member with that name, not the checked one AI review tools/donate_cpu_lib.py:409 ✅ Fixed
3 Symlink target resolved through realpath of an existing same-named link can point outside temp AI review tools/donate_cpu_lib.py:386 ✅ Fixed
4 Symlink checked before later members exist can be redirected outside temp by a later link AI review tools/donate_cpu_lib.py:415 ✅ Fixed
5 KeyError from a hardlink to a missing member escapes and aborts the run AI review tools/donate_cpu_lib.py:446 ✅ Fixed
6 Escaping link is left in place when its folder is read-only (archive can set dir mode 0555) AI review tools/donate_cpu_lib.py:379 🆕 New

@Nussu06, please fix, resolve or reply to the open and new comments: #6.

Testing

  • I did not build cppcheck or testrunner, because the PR only changes tools/donate_cpu_lib.py and its Python test.
  • PYTHONPATH=tools python3 -m pytest -q test/tools/donate_cpu_lib_test.py in pr/ with Python 3.12.3: 6 passed.
  • Escape through a read-only directory. I ran this as a non-root user. Deleting tarfile.data_filter simulates an older Python.
# scratch/ro.py — python3 -I ro.py /work/pr/tools nofilter
import io, os, sys, tarfile, tempfile
sys.path.insert(0, sys.argv[1])
if len(sys.argv) > 2: del tarfile.data_filter
import donate_cpu_lib as d
w = tempfile.mkdtemp(); out = os.path.join(w, 'outside'); os.mkdir(out)
open(os.path.join(out, 'secret.c'), 'w').write('int secret;\n')
tgz = os.path.join(w, 'p.tgz')
def add(tf, name, link=None, dirmode=None):
    i = tarfile.TarInfo(name); data = b'int x;\n'
    if dirmode is not None: i.type = tarfile.DIRTYPE; i.mode = dirmode; data = b''
    elif link: i.type = tarfile.SYMTYPE; i.linkname = link; data = b''
    else: i.size = len(data)
    tf.addfile(i, io.BytesIO(data))
with tarfile.open(tgz, 'w:gz') as tf:
    add(tf, 'pkg/main.c')
    add(tf, 'pkg/x.h/l.h', 'd.h/../../../outside')
    add(tf, 'pkg/x.h/d.h', '.')
    add(tf, 'pkg/x.h', dirmode=0o555)   # makes the folder read-only after the links exist
tp, found = d.unpack_package(w, tgz)
l = os.path.join(tp, 'pkg', 'x.h', 'l.h')
print('link:', os.readlink(l) if os.path.islink(l) else None, '->', os.path.realpath(l))
print('listing via temp:', os.listdir(l) if os.path.isdir(l) else None)

Output:

extracted 4 of 4 files (skipped 0)
link: d.h/../../../outside -> /tmp/tmp0fg9uw9e/outside
listing via temp: ['secret.c']
  • Control run. The same archive with mode 0o755 gives extracted 3 of 4 files (skipped 1), and the link is removed. So the read-only directory is what defeats the cleanup.
  • With filter='data' (the normal 3.12 run), the link is rewritten to ../../outside, which resolves to temp/outside, so nothing escapes.

Automated review of 407f7f3 by Claude. The pull request was built and tested locally.

Comment thread tools/donate_cpu_lib.py Outdated
os.rmdir(path)
removed += 1
except OSError:
return removed

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

When neither os.remove nor os.rmdir works, the function returns quietly and the escaping link stays. An archive can cause that on purpose. A directory member with a header-like name, such as pkg/x.h with mode 0o555, passes the extension filter and is extracted after the links. tarfile then applies the mode to the folder that already exists, so the links in it can no longer be removed.

I reproduced this on Python 3.12 with tarfile.data_filter deleted, as a non-root user. The archive is pkg/x.h/l.h -> d.h/../../../outside, then pkg/x.h/d.h -> ., then the directory pkg/x.h with mode 0555. The output is extracted 4 of 4 files (skipped 0), and os.listdir(temp/pkg/x.h/l.h) lists the outside folder. With mode 0755 the link is removed.

Possible fixes:

  • On PermissionError, add the write bit to the parent folder (os.chmod(parent, stat.S_IMODE(os.lstat(parent).st_mode) | stat.S_IWUSR)) and try again, as __handle_remove_readonly already does.
  • Or don't extract directory members at all, since they get created anyway when their files are extracted.
  • If a link still can't be removed, fail the unpack, for example by removing temp or returning source_found=False, instead of going on with an escaping link.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, a directory member named like a header gets extracted after the links and its mode makes the folder read-only, so the quiet return left the link in place. When removing a link fails, __remove_escaping_links now adds the owner write bit to the parent folder (same as __handle_remove_readonly does) and retries. If that still fails it raises, and unpack_package prints the error and returns source_found=False, so the callers skip the package instead of scanning through an escaping link.

Added test_unpack_package_link_in_readonly_dir with your pkg/x.h/l.h, pkg/x.h/d.h and 0555 pkg/x.h case. It fails without the change on 3.12 with tarfile.data_filter removed (l.h left resolving to work_path/outside) and passes with it on 3.12 and 3.14, both with the filter and with data_filter removed. pylint --py-version 3.7 is still 10/10.

This PR still has no Trac ticket, could one of you create it so I can put the number in the title?

@dmcppcheck dmcppcheck left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

On Python without tarfile.data_filter, a symlink that points outside temp can still be left behind. __remove_escaping_links uses os.walk without an onerror handler, so it quietly skips any folder it can't list. An archive can produce such a folder: a directory member with a header-like name and mode 0311 (write and search, but no read) causes it. The escaping link inside that folder is never seen, and the unpack reports success. I checked the impact for a non-root user: cppcheck can't list that folder either, so it would not scan the outside files through it. The cleanup step still doesn't do what the PR says, though: escaping links that can't be removed should make the unpack fail. Making os.walk raise fixes it, because the existing except OSError then returns source_found=False. I found no other new problems, and the fixes for all earlier comments are in the code.

Comments

# Comment By Where Status
1 Rebase so CI may become green @danmar general 💬 Answered: Author rebased onto current main
2 extract(member.name) extracts the last member with that name, not the checked one AI review tools/donate_cpu_lib.py:409 ✅ Fixed
3 Symlink target resolved through realpath of an existing same-named link can point outside temp AI review tools/donate_cpu_lib.py:386 ✅ Fixed
4 Symlink checked before later members exist can be redirected outside temp by a later link AI review tools/donate_cpu_lib.py:423 ✅ Fixed
5 KeyError from a hardlink to a missing member escapes and aborts the run AI review tools/donate_cpu_lib.py:446 ✅ Fixed
6 Escaping link left in place when its folder is read-only (dir member mode 0555) AI review tools/donate_cpu_lib.py:379 ✅ Fixed
7 os.walk skips folders it can't list, so escaping links in a mode-0311 folder are not found and the unpack succeeds AI review tools/donate_cpu_lib.py:372 🆕 New

@Nussu06, please fix, resolve or reply to the open and new comments: #7.

Testing

  • I did not build cppcheck or testrunner, because the PR only changes tools/donate_cpu_lib.py and its Python test.
  • PYTHONPATH=tools python3 -m pytest -q test/tools/donate_cpu_lib_test.py in pr/ with Python 3.12.3: 7 passed.
  • Hardlink fallback to a skipped symlink member: a hardlink pkg/h.h -> pkg/s.h, where pkg/s.h is a skipped symlink to the outside folder. Nothing was left behind, with or without the filter.
  • Escaping link left in an unreadable folder (new finding). I ran this as a non-root user (uid 1000). Deleting data_filter simulates an older Python:
# scratch/t.py — python3 -I t.py /work/pr/tools nofilter
import io, os, sys, tarfile, tempfile
sys.path.insert(0, sys.argv[1])
if len(sys.argv) > 2: del tarfile.data_filter
import donate_cpu_lib as d
w = tempfile.mkdtemp(); out = os.path.join(w, 'outside'); os.mkdir(out)
open(os.path.join(out, 'secret.c'), 'w').write('int secret;\n')
tgz = os.path.join(w, 'p.tgz')
def add(tf, name, link=None, typ=tarfile.SYMTYPE, dirmode=None):
    i = tarfile.TarInfo(name); data = b'int x;\n'
    if dirmode is not None: i.type = tarfile.DIRTYPE; i.mode = dirmode; data = b''
    elif link: i.type = typ; i.linkname = link; data = b''
    else: i.size = len(data)
    tf.addfile(i, io.BytesIO(data))
with tarfile.open(tgz, 'w:gz') as tf:
    add(tf, 'pkg/main.c')
    add(tf, 'pkg/q.h/l.h', 'd.h/../../../outside')
    add(tf, 'pkg/q.h/d.h', '.')
    add(tf, 'pkg/q.h', dirmode=0o311)   # write+search, no read
tp, found = d.unpack_package(w, tgz)
print(found)
l = os.path.join(tp, 'pkg', 'q.h', 'l.h')
print(os.readlink(l), os.listdir(l))

Output:

extracted 4 of 4 files (skipped 0)
True
d.h/../../../outside ['secret.c']

The unpack succeeds, and temp/pkg/q.h/l.h still resolves to the outside folder. With filter='data', the link is rewritten to stay inside temp.

  • Older problem, also on base: after the archive above, __remove_tree on the next run leaves temp/pkg behind without an error. __handle_remove_readonly only acts on folders without write permission, and q.h is writable but not readable. The next os.mkdir(temp_path) would then fail. The same thing happens on base, so I am not reporting it as a finding of this PR.

Automated review of e521de5 by Claude. The pull request was built and tested locally.

Comment thread tools/donate_cpu_lib.py
removed = 0
while True:
links = []
for root, dirs, files in os.walk(real_temp_path):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

os.walk quietly skips any folder that it can't list, because no onerror is passed. An archive can create such a folder with a directory member that has a header-like name, for example pkg/q.h with mode 0o311 (write and search, but no read). It is extracted after pkg/q.h/l.h -> d.h/../../../outside and pkg/q.h/d.h -> .. The walk then never sees l.h, so it is neither removed nor reported, and unpack_package returns source_found=True.

I reproduced this on Python 3.12 with tarfile.data_filter deleted, as a non-root user. The output is extracted 4 of 4 files (skipped 0), and os.listdir(temp/pkg/q.h/l.h) lists the outside folder.

The impact is limited, because cppcheck can't list that folder either. Still, the function no longer does what its comment and the PR say: it should make the unpack fail when a link can't be dealt with. Making the walk raise fixes this, because the existing except OSError in unpack_package then returns source_found=False:

def __raise(e):
    raise e
...
for root, dirs, files in os.walk(real_temp_path, onerror=__raise):

Another option is to add the owner read and execute bits to folders the walk can't list, the same way the write bit is added for removal.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants