def add_filter(info: tarfile.TarInfo) -> Optional[tarfile.TarInfo]: """Filter files targeted to be added to tarfile. Args: info: Information on the file targeted to be added Returns: None: if file is not to be added TarInfo: when file is to be added. Modified as needed. Notes: exclude is captured from parent """ if not (info.isfile() or info.isdir() or info.issym()): return None if _exclude_matcher(info.name, exclude): return None # Workaround https://bugs.python.org/issue32713. Fixed in Python 3.7 if info.mtime < 0 or info.mtime > 8 ** 11 - 1: info.mtime = int(info.mtime) # do not leak client information to service info.uid = 0 info.uname = info.gname = "root" if sys.platform == "win32": info.mode = info.mode & 0o755 | 0o111 return info
def sanitize_tarinfo(tarinfo: tarfile.TarInfo): path = Path(tarinfo.name) # Ban absolute paths if path.is_absolute(): return False # Ban paths containing .. that would go outside try: base = Path("fake_path") base.joinpath(path).relative_to(base) except ValueError as e: logger.warning(f"Unsafe path {path}") return False # Ban links that would point somewhere outside if tarinfo.islnk() or tarinfo.issym(): try: base = Path("fake_path") link = path.parent / tarinfo.linkname base.joinpath(link).relative_to(base) except ValueError as e: logger.warning(f"Unsafe path {path}") return False return True
def _is_file_type_forbidden(tarinfo: tarfile.TarInfo) -> bool: return (tarinfo.islnk() or tarinfo.isblk() or tarinfo.ischr() or tarinfo.isdev() or tarinfo.isfifo() or tarinfo.issym() or tarinfo.islnk())
def _member_is_safe(member: tarfile.TarInfo) -> bool: if member.isfile(): return getattr(member, 'sparse', None) is None return member.isdir() or member.issym() or member.islnk()
def strip_prefix(self, prefix: str, member: tarfile.TarInfo): member.name = self.strip_slash(prefix, member.name) # Strip hardlinks if member.islnk() and not member.issym(): member.linkname = self.strip_slash(prefix, member.linkname)
def _member_is_safe(member: tarfile.TarInfo) -> bool: return ( member.isfile() or member.isdir() or member.issym() or member.islnk() )