Skip to content
154 changes: 154 additions & 0 deletions test/tools/donate_cpu_lib_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

import io
import tarfile

from donate_cpu_lib import *

def _test_library_includes(tmpdir, libs, content, libinc_obj=None):
Expand Down Expand Up @@ -66,3 +69,154 @@ def test_match_multiple_time(tmpdir):
# there was a bug that we would only match each library once successfully
_test_library_includes(tmpdir, ['posix', 'gnu', 'bsd', 'zlib'], '#include <zlib.h>', libinc)
_test_library_includes(tmpdir, ['posix', 'gnu', 'bsd', 'zlib'], '#include <zlib.h>', libinc)

def _add_tar_member(tf, name, linkname=None, linktype=tarfile.SYMTYPE, dirmode=None):
info = tarfile.TarInfo(name)
data = b''
if dirmode is not None:
info.type = tarfile.DIRTYPE
info.mode = dirmode
elif linkname is not None:
info.type = linktype
info.linkname = linkname
else:
data = b'int x;\n'
info.size = len(data)
tf.addfile(info, io.BytesIO(data))

def test_unpack_package_outside_temp(tmpdir):
work_path = str(tmpdir)
outside_path = os.path.join(work_path, 'outside')
os.mkdir(outside_path)
tgz = os.path.join(work_path, 'temp.tgz')
with tarfile.open(tgz, 'w:gz') as tf:
_add_tar_member(tf, 'pkg/main.c')
_add_tar_member(tf, 'pkg/../../outside/dotdot.c')
_add_tar_member(tf, 'pkg/inc.h', linkname=outside_path)
_add_tar_member(tf, 'pkg/inc.h/symlink.c')

temp_path, source_found = unpack_package(work_path, tgz)
assert source_found
assert os.path.isfile(os.path.join(temp_path, 'pkg', 'main.c'))
assert os.listdir(outside_path) == []

def test_unpack_package_duplicate_name(tmpdir):
work_path = str(tmpdir)
outside_path = os.path.join(work_path, 'outside')
os.mkdir(outside_path)
outside_file = os.path.join(outside_path, 'target.c')
with open(outside_file, 'w', encoding='utf-8') as f:
f.write('int y;\n')
tgz = os.path.join(work_path, 'temp.tgz')
with tarfile.open(tgz, 'w:gz') as tf:
# a harmless member followed by a link with the same name that points outside temp
_add_tar_member(tf, 'pkg/sym.c')
_add_tar_member(tf, 'pkg/sym.c', linkname=outside_file)
_add_tar_member(tf, 'pkg/hard.c')
_add_tar_member(tf, 'pkg/hard.c', linkname='../outside/target.c', linktype=tarfile.LNKTYPE)
# a link inside temp followed by a same-named link that only looks inside when resolved through the first one
_add_tar_member(tf, 'pkg/inc.h', linkname='a/b/c')
_add_tar_member(tf, 'pkg/inc.h', linkname='../../outside')

temp_path, source_found = unpack_package(work_path, tgz)
assert source_found
for name in ('sym.c', 'hard.c'):
path = os.path.join(temp_path, 'pkg', name)
assert os.path.isfile(path)
assert not os.path.islink(path)
assert not os.path.samefile(path, outside_file)
real_temp_path = os.path.realpath(temp_path)
inc_path = os.path.realpath(os.path.join(temp_path, 'pkg', 'inc.h'))
assert os.path.commonpath([real_temp_path, inc_path]) == real_temp_path
assert os.listdir(outside_path) == ['target.c']

def test_unpack_package_link_redirected_later(tmpdir):
work_path = str(tmpdir)
outside_path = os.path.join(work_path, 'outside')
os.mkdir(outside_path)
with open(os.path.join(outside_path, 'secret.c'), 'w', encoding='utf-8') as f:
f.write('int secret;\n')
tgz = os.path.join(work_path, 'temp.tgz')
with tarfile.open(tgz, 'w:gz') as tf:
_add_tar_member(tf, 'pkg/src/main.c')
# 'd.h' does not exist yet, so this target is resolved as temp/outside and looks harmless
_add_tar_member(tf, 'pkg/l.h', linkname='d.h/../../outside')
# turns the missing component into a link, which redirects 'l.h' out of temp
_add_tar_member(tf, 'pkg/d.h', linkname='.')
# a link that stays inside the package is still extracted
_add_tar_member(tf, 'pkg/include/main.c', linkname='../src/main.c')

temp_path, source_found = unpack_package(work_path, tgz)
assert source_found
real_temp_path = os.path.realpath(temp_path)
for name in ('l.h', 'd.h'):
path = os.path.join(temp_path, 'pkg', name)
if os.path.lexists(path):
assert os.path.commonpath([real_temp_path, os.path.realpath(path)]) == real_temp_path
inc_path = os.path.join(temp_path, 'pkg', 'include', 'main.c')
if os.path.islink(inc_path):
assert os.path.samefile(inc_path, os.path.join(temp_path, 'pkg', 'src', 'main.c'))
assert os.listdir(outside_path) == ['secret.c']

def test_unpack_package_hardlink_missing_target(tmpdir):
work_path = str(tmpdir)
tgz = os.path.join(work_path, 'temp.tgz')
with tarfile.open(tgz, 'w:gz') as tf:
_add_tar_member(tf, 'pkg/main.c')
# the target is neither on disk nor in the archive, so tarfile raises KeyError instead of OSError
_add_tar_member(tf, 'pkg/copy.c', linkname='pkg/missing.c', linktype=tarfile.LNKTYPE)

temp_path, source_found = unpack_package(work_path, tgz)
assert source_found
assert os.path.isfile(os.path.join(temp_path, 'pkg', 'main.c'))
assert not os.path.lexists(os.path.join(temp_path, 'pkg', 'copy.c'))

def test_unpack_package_link_in_readonly_dir(tmpdir):
work_path = str(tmpdir)
outside_path = os.path.join(work_path, 'outside')
os.mkdir(outside_path)
with open(os.path.join(outside_path, 'secret.c'), 'w', encoding='utf-8') as f:
f.write('int secret;\n')
tgz = os.path.join(work_path, 'temp.tgz')
with tarfile.open(tgz, 'w:gz') as tf:
_add_tar_member(tf, 'pkg/main.c')
# redirected out of temp by the next member, like in test_unpack_package_link_redirected_later
_add_tar_member(tf, 'pkg/x.h/l.h', linkname='d.h/../../../outside')
_add_tar_member(tf, 'pkg/x.h/d.h', linkname='.')
# a directory member with a header-like name makes the folder read-only after the links exist
_add_tar_member(tf, 'pkg/x.h', dirmode=0o555)

temp_path, source_found = unpack_package(work_path, tgz)
assert source_found
assert os.path.isfile(os.path.join(temp_path, 'pkg', 'main.c'))
real_temp_path = os.path.realpath(temp_path)
for name in ('l.h', 'd.h'):
path = os.path.join(temp_path, 'pkg', 'x.h', name)
if os.path.lexists(path):
assert os.path.commonpath([real_temp_path, os.path.realpath(path)]) == real_temp_path
assert os.listdir(outside_path) == ['secret.c']

def test_unpack_package_link_in_unreadable_dir(tmpdir):
work_path = str(tmpdir)
outside_path = os.path.join(work_path, 'outside')
os.mkdir(outside_path)
with open(os.path.join(outside_path, 'secret.c'), 'w', encoding='utf-8') as f:
f.write('int secret;\n')
tgz = os.path.join(work_path, 'temp.tgz')
with tarfile.open(tgz, 'w:gz') as tf:
_add_tar_member(tf, 'pkg/main.c')
# redirected out of temp by the next member, like in test_unpack_package_link_redirected_later
_add_tar_member(tf, 'pkg/q.h/l.h', linkname='d.h/../../../outside')
_add_tar_member(tf, 'pkg/q.h/d.h', linkname='.')
# a directory member with a header-like name makes the folder unlistable after the links exist
_add_tar_member(tf, 'pkg/q.h', dirmode=0o311)

temp_path, source_found = unpack_package(work_path, tgz)
assert source_found
assert os.path.isfile(os.path.join(temp_path, 'pkg', 'main.c'))
real_temp_path = os.path.realpath(temp_path)
for name in ('l.h', 'd.h'):
path = os.path.join(temp_path, 'pkg', 'q.h', name)
if os.path.lexists(path):
assert os.path.commonpath([real_temp_path, os.path.realpath(path)]) == real_temp_path
assert os.listdir(outside_path) == ['secret.c']
97 changes: 93 additions & 4 deletions tools/donate_cpu_lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
# Version scheme (MAJOR.MINOR.PATCH) should orientate on "Semantic Versioning" https://semver.org/
# Every change in this script should result in increasing the version number accordingly (exceptions may be cosmetic
# changes)
CLIENT_VERSION = "1.4.0"
CLIENT_VERSION = "1.4.1"

# Timeout for analysis with Cppcheck in seconds
CPPCHECK_TIMEOUT = 30 * 60
Expand Down Expand Up @@ -344,10 +344,77 @@ def download_package(work_path, package, bandwidth_limit):
return destfile


def __is_inside_path(base_path, path):
try:
return os.path.commonpath([base_path, path]) == base_path
except ValueError:
# paths are on different drives
return False


def __remove_link(path):
try:
os.remove(path)
except OSError:
# a directory symlink on Windows
os.rmdir(path)


def __find_escaping_links(real_temp_path):
# Returns the links below real_temp_path that resolve outside of it, and whether a folder had to
# be made readable to list it. Raises OSError for a folder that cannot be listed even then.
import stat
fixed = False

def onerror(e):
# a directory member extracted after the links can have made its folder unreadable
nonlocal fixed
mode = stat.S_IMODE(os.lstat(e.filename).st_mode)
missing = (stat.S_IRUSR | stat.S_IXUSR) & ~mode
if not missing:
raise e
os.chmod(e.filename, mode | missing)
fixed = True

links = []
for root, dirs, files in os.walk(real_temp_path, onerror=onerror):
for name in dirs + files:
path = os.path.join(root, name)
if os.path.islink(path) and not __is_inside_path(real_temp_path, os.path.realpath(path)):
links.append(path)
return links, fixed


def __remove_escaping_links(real_temp_path):
# A link that still pointed inside real_temp_path when it was extracted can be redirected
# by a link that is extracted later, so all links are checked again afterwards. Removing a
# link changes what the remaining ones resolve to, so this is repeated until nothing is left.
# Raises OSError if a folder cannot be listed or a link cannot be removed.
import stat
removed = 0
while True:
links, fixed = __find_escaping_links(real_temp_path)
if fixed:
# a folder that was skipped by the walk is readable now, so look at its content as well
continue
if not links:
return removed
for path in links:
try:
__remove_link(path)
except OSError:
# a directory member extracted after the link can have made its folder read-only
parent = os.path.dirname(path)
os.chmod(parent, stat.S_IMODE(os.lstat(parent).st_mode) | stat.S_IWUSR)
__remove_link(path)
removed += 1


def unpack_package(work_path, tgz, cpp_only=False, c_only=False, skip_files=None):
temp_path = os.path.join(work_path, 'temp')
__remove_tree(temp_path)
os.mkdir(temp_path)
real_temp_path = os.path.realpath(temp_path)

header_endings = ('.hpp', '.h++', '.hxx', '.hh', '.h')
cpp_source_endings = ('.cpp', '.c++', '.cxx', '.cc', '.tpp', '.txx', '.ipp', '.ixx', '.qml')
Expand All @@ -367,10 +434,21 @@ def unpack_package(work_path, tgz, cpp_only=False, c_only=False, skip_files=None
total = 0
extracted = 0
skipped = 0
# Python versions with extraction filters reject members that leave temp_path as well
extract_args = {'filter': 'data'} if hasattr(tarfile, 'data_filter') else {}
for member in tf:
total += 1
if member.name.startswith(('/', '..')):
# Skip dangerous file names
member_path = os.path.realpath(os.path.join(temp_path, member.name))
link_path = None
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?

elif member.islnk():
link_path = os.path.realpath(os.path.join(temp_path, member.linkname))
if not __is_inside_path(real_temp_path, member_path) or \
(link_path is not None and not __is_inside_path(real_temp_path, link_path)):
# Skip dangerous file names and links pointing outside of temp_path
# print('skipping dangerous file: ' + member.name)
skipped += 1
continue
Expand All @@ -388,14 +466,25 @@ def unpack_package(work_path, tgz, cpp_only=False, c_only=False, skip_files=None
skipped += 1
continue
try:
tf.extract(member.name, temp_path)
tf.extract(member, temp_path, **extract_args)
if is_source:
source_found = True
extracted += 1
except OSError:
pass
except AttributeError:
pass
except (tarfile.TarError, KeyError):
# KeyError: hardlink to a member that is neither on disk nor in the archive
pass
try:
removed = __remove_escaping_links(real_temp_path)
except OSError as e:
# do not analyse a package with a link pointing outside of temp_path
print('Failed to remove link pointing outside of {}: {}'.format(temp_path, e))
return temp_path, False
extracted -= removed
skipped += removed
print('extracted {} of {} files (skipped {}{})'.format(extracted, total, skipped, (' / only headers' if (extracted and not source_found) else '')))
return temp_path, source_found

Expand Down
Loading