Details
print(f" ⢠PATH_MAX symlink resolution bug bypassed security checks")
print(f" ⢠File created outside intended cache directory")
print(f" ⢠Same vulnerability pattern as TensorFlow get_file()")
print(f"\nš COMPARISON RESULTS:")
print(f" ā
Python with filter='data': BLOCKED exploit")
print(f" ā ļø Keras get_file(): ALLOWED exploit")
else:
print(f"ā
No exploit files detected")
print(f"Possible reasons:")
print(f" ⢠Keras version includes security patches")
print(f" ⢠Platform-specific path handling prevented exploit")
print(f" ⢠Archive extraction path differed from expected")
Show what Keras actually extracted (safely)
print(f"\n=== KERAS EXTRACTION ANALYSIS ===")
try:
if 'extracted_path' in locals() and pathlib.Path(extracted_path).exists():
keras_path = pathlib.Path(extracted_path)
print(f"Keras extracted to: {keras_path}")
# Safely list contents
try:
contents = [item.name for item in keras_path.iterdir()]
print(f"Top-level contents: {contents}")
# Count symlinks (indicates our exploit structure was created)
symlink_count = 0
for item in keras_path.iterdir():
try:
if item.is_symlink():
symlink_count += 1
except PermissionError:
continue
print(f"Symlinks created: {symlink_count}")
if symlink_count > 0:
print(f"ā PATH_MAX symlink chain was extracted")
except PermissionError:
print(f"Permission errors in extraction directory (expected with symlink corruption)")
except Exception as e:
print(f"Could not analyze Keras extraction: {e}")
print(f"\n=== REMEDIATION ===")
print(f"To fix this vulnerability, Keras should use:")
print(f"```python")
print(f"tarfile.extractall(path, filter='data') # Safe")
print(f"```")
print(f"Instead of:")
print(f"```python")
print(f"tarfile.extractall(path) # Vulnerable")
print(f"```")
Cleanup
print(f"\n=== CLEANUP ===")
try:
os.unlink("keras_dataset.tgz")
print(f"ā Removed malicious tar file")
except:
pass
print("PoC completed!")
### Environment Setup
- **Python**: 3.8+ (tested on multiple versions)
- **Keras**: Standalone Keras or TensorFlow.Keras
- **Platform**: Linux, macOS, Windows (path handling varies)
### Exploitation Steps
1. **Create malicious tar archive** with PATH_MAX symlink chain
2. **Host archive** on accessible HTTP server
3. **Call `keras.utils.get_file()`** with `extract=True`
4. **Observe directory traversal** - files written outside cache directory
### Key Exploit Components
- **Deep symlink chain**: 16+ nested symlinks with long directory names
- **PATH_MAX overflow**: Final symlink path exceeding system limits
- **Traversal payload**: Relative path traversal (`../../../target/file`)
- **Legitimate disguise**: Archive contains valid-looking dataset files
### Demonstration Results
**Vulnerable behavior:**
- Files extracted outside intended `cache_dir/datasets/` location
- Security filtering bypassed completely
- No error or warning messages generated
**Expected secure behavior:**
- Extraction blocked or confined to cache directory
- Security warnings for suspicious archive contents
## Impact
### Vulnerability Classification
- **Type**: Directory Traversal / Path Traversal (CWE-22)
- **Severity**: High
- **CVSS Components**: Network accessible, no authentication required, impacts confidentiality and integrity
### Who Is Impacted
**Direct Impact:**
- Applications using `keras.utils.get_file()` with `extract=True`
- Machine learning pipelines downloading and extracting datasets
- Automated ML training systems processing external archives
**Attack Scenarios:**
1. **Malicious datasets**: Attacker hosts compromised ML dataset
2. **Supply chain**: Legitimate dataset repositories compromised
3. **Model poisoning**: Extraction writes malicious files alongside training data
4. **System compromise**: Configuration files, executables written to system directories
**Affected Environments:**
- Research environments downloading public datasets
- Production ML systems with automated dataset fetching
- Educational platforms using Keras for tutorials
- CI/CD pipelines training models with external data
### Risk Assessment
**High Risk Factors:**
- Common usage pattern in ML workflows
- No user awareness of extraction security
- Silent failure mode (no warnings)
- Cross-platform vulnerability
**Potential Consequences:**
- Arbitrary file write on target system
- Configuration file tampering
- Code injection via overwritten scripts
- Data exfiltration through planted files
- System compromise in containerized environments
## Recommended Fix
### Immediate Mitigation
Replace the vulnerable extraction code with:
```python
# Secure implementation
if zipfile.is_zipfile(file_path):
# Zip archive - implement similar filtering
archive.extractall(path, members=filter_safe_paths(archive))
else:
# Tar archive with proper security filter
archive.extractall(path, members=filter_safe_paths(archive), filter="data")
Long-term Solution
- Add `filter="data"` parameter to all
tarfile.extractall()calls - Implement comprehensive path validation before extraction
- Add extraction logging for security monitoring
- Consider sandboxed extraction for untrusted archives
- Update documentation to warn about archive security risks
Backward Compatibility
The fix maintains full backward compatibility as filter="data" is the recommended secure default for Python 3.12+.
References
- [Python tarfile security documentation](https://docs.python.org/3/library/tarfile.html#extraction-filters)
- [CVE-2007-4559](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2007-4559) - Related tarfile vulnerability
- [OWASP Path Traversal](https://owasp.org/www-community/attacks/Path_Traversal)
Note: Reported in Huntr as well, but didn't get response
https://huntr.com/bounties/f94f5beb-54d8-4e6a-8bac-86d9aee103f4