Exploit database

GH-3fe66e6f92ee5022da68d0d97d1e74b4

taptap/cve-2025-59489

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2025-59489

2 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files10
taptap/cve-2025-59489Revision 00d8bbee5656

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

unity_vulnerability_checker.py

Python · 31,764 bytes
#!/usr/bin/env python3
"""
Unity CVE-2025-59489 漏洞检测工具
检测 Android APK 文件是否包含受影响的 Unity Runtime 版本
"""

import logging
import re
import zipfile
from concurrent.futures import ProcessPoolExecutor, as_completed
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, Literal, Optional, Tuple

# Constants
MAX_APK_SIZE_MB = 1024  # Maximum APK file size in MB
MAX_DATA_FILE_READ_SIZE = 51200  # Read first 50KB from data files

# 未打补丁的特征字符串(用于对比验证)
VULNERABLE_MARKERS = [
    b"xrsdk-pre-init-library",  # 原始未修复版本的字符串
]

# Unity patcher 工具通过破坏 XR SDK 字符串来修复漏洞
PATCH_MARKERS = [
    b"8rsdk-pre-init-library",  # Unity patcher 将 "xrsdk" 改为 "8rsdk" 来禁用 XR SDK
]


@dataclass
class VulnerabilityCheckResult:
    """Unity 漏洞检测结果"""

    status: Literal["positive", "negative", "inconclusive"]
    """检测状态:positive=受影响, negative=安全, inconclusive=无法确定"""

    reason: Optional[str] = None
    """结果原因代码,如 'not_unity', 'patched_version', 'affected_no_official_patch' 等"""

    version: Optional[str] = None
    """Unity 版本号,如 '2021.3.45f2'"""

    is_unity: bool = False
    """是否为 Unity 应用"""

    has_patch: Optional[bool] = None
    """是否有官方补丁(None=未知, True=有补丁, False=无补丁)"""

    message: Optional[str] = None
    """用户友好的描述信息"""

    recommendation: Optional[str] = None
    """建议操作"""

    error: Optional[str] = None
    """错误信息(如果检测失败)"""

    @property
    def is_vulnerable(self) -> bool:
        """是否确认受影响"""
        return self.status == "positive"

    @property
    def is_safe(self) -> bool:
        """是否确认安全"""
        return self.status == "negative"

    @property
    def is_uncertain(self) -> bool:
        """是否无法确定"""
        return self.status == "inconclusive"

    def to_dict(self) -> dict:
        """转换为字典(用于 JSON 序列化等)"""
        return {
            "status": self.status,
            "reason": self.reason,
            "version": self.version,
            "is_unity": self.is_unity,
            "has_patch": self.has_patch,
            "message": self.message,
            "recommendation": self.recommendation,
            "error": self.error,
        }


class UnityVulnerabilityChecker:
    """Unity Runtime 漏洞检测器"""

    # 根据 Unity 官方公告的修复版本映射表
    # 格式:{major: {minor: {"patch": X, "type": "f"/"b"/"a", "build": Y}}}
    # 简化版:{major: {minor: patch}},默认 type="f",build=1
    PATCHED_VERSIONS = {
        6000: {
            3: {"patch": 0, "type": "b", "build": 4},
            2: {"patch": 6, "type": "f", "build": 2},
            1: {"patch": 17, "type": "f", "build": 1},
            0: {"patch": 58, "type": "f", "build": 2},
        },
        2023: {2: 22, 1: 22},
        2022: {
            3: {"patch": 62, "type": "f", "build": 2},  # 2022.3.62f2 (LTS)
            2: 23,
            1: 25,
        },
        2021: {
            3: {"patch": 45, "type": "f", "build": 2},  # 2021.3.45f2 (LTS)
            2: 20,
            1: 29,
        },
        2020: {3: 49, 2: 8, 1: 18},
        2019: {4: 41, 3: 17, 2: 23, 1: 15},
    }

    def __init__(self, verbose: bool = False):
        self.verbose = verbose
        self.logger = logging.getLogger(__name__)
        if verbose:
            self.logger.setLevel(logging.DEBUG)
            if not self.logger.handlers:
                handler = logging.StreamHandler()
                formatter = logging.Formatter("[%(levelname)s] %(message)s")
                handler.setFormatter(formatter)
                self.logger.addHandler(handler)
        else:
            self.logger.setLevel(logging.WARNING)

        # 检测结果的详细信息
        self.last_check_reason = None  # 检测结果原因
        self.last_check_details = {}  # 检测详细信息(版本号等)

    def check_apk(self, apk_path: str) -> VulnerabilityCheckResult:
        """
        检测 APK 文件的漏洞状态

        Args:
            apk_path: APK 文件路径

        Returns:
            VulnerabilityCheckResult 对象,包含详细的检测结果信息
        """
        # 重置检测状态
        self.last_check_reason = None
        self.last_check_details = {}

        try:
            apk_file = Path(apk_path)
            if not apk_file.exists():
                self._log(f"文件不存在:{apk_path}")
                return self._build_result(
                    status="inconclusive",
                    reason="file_not_found",
                    message="文件不存在",
                )

            # Validate file size
            file_size_mb = apk_file.stat().st_size / (1024 * 1024)
            if file_size_mb > MAX_APK_SIZE_MB:
                self._log(
                    f"文件过大:{file_size_mb:.1f}MB (当前限制 {MAX_APK_SIZE_MB}MB)"
                )
                self._log(
                    f"提示:如需处理更大的文件,可修改代码中的 MAX_APK_SIZE_MB 常量"
                )
                return self._build_result(
                    status="inconclusive",
                    reason="file_too_large",
                    message=f"文件过大 ({file_size_mb:.1f}MB,限制 {MAX_APK_SIZE_MB}MB)",
                )

            with zipfile.ZipFile(apk_path, "r") as apk:
                # 步骤 1: 检查是否为 Unity 应用
                if not self._is_unity_app(apk):
                    self._log("非 Unity 应用")
                    return self._build_result(
                        status="negative",
                        reason="not_unity",
                        is_unity=False,
                        message="非 Unity 应用",
                    )

                self._log("检测到 Unity 应用")
                self.last_check_details["is_unity"] = True

                # 步骤 2: 检查是否使用 Unity patcher 工具打过补丁
                if self._is_patched_by_tool(apk):
                    self._log("检测到 Unity patcher 工具补丁标识")
                    return self._build_result(
                        status="negative",
                        reason="patched_by_tool",
                        is_unity=True,
                        message="已使用 Unity patcher 工具修复",
                    )

                # 步骤 3: 提取 Unity 版本
                version_str = self._extract_unity_version(apk)
                if not version_str:
                    self._log("无法提取 Unity 版本信息")
                    return self._build_result(
                        status="inconclusive",
                        reason="version_not_found",
                        is_unity=True,
                        message="Unity 应用但无法提取版本,可能被加壳或混淆",
                        recommendation="建议人工复核",
                    )

                self._log(f"检测到 Unity 版本:{version_str}")
                self.last_check_details["version"] = version_str

                # 步骤 4: 判断版本是否受影响
                status = self._check_vulnerability(version_str)
                
                # 根据不同状态设置详细信息
                if status == "negative":
                    return self._build_result(
                        status="negative",
                        reason=self.last_check_reason or "patched_version",
                        version=version_str,
                        is_unity=True,
                        has_patch=True,
                        message=f"已修复版本 ({version_str})",
                    )
                elif status == "positive":
                    return self._build_result(
                        status="positive",
                        reason="vulnerable_version",
                        version=version_str,
                        is_unity=True,
                        has_patch=True,
                        message=f"该版本受 CVE-2025-59489 影响 ({version_str})",
                        recommendation="升级到最新修复版本",
                    )
                else:  # inconclusive
                    # 检查是否是 2017/2018 无补丁的情况
                    if self.last_check_reason == "affected_no_official_patch":
                        return self._build_result(
                            status="inconclusive",
                            reason="affected_no_official_patch",
                            version=version_str,
                            is_unity=True,
                            has_patch=False,
                            message=f"该版本受影响但 Unity 官方未提供补丁 ({version_str})",
                            recommendation="建议升级到 Unity 2019.1+ 并重新构建",
                        )
                    else:
                        return self._build_result(
                            status="inconclusive",
                            reason="version_unknown",
                            version=version_str,
                            is_unity=True,
                            message=f"无法判断版本 {version_str} 的安全状态",
                        )

        except zipfile.BadZipFile:
            self._log(f"无效的 APK 文件:{apk_path}")
            return self._build_result(
                status="inconclusive",
                reason="invalid_apk",
                message="无效的 APK 文件",
            )
        except Exception as e:
            self._log(f"处理出错:{str(e)}")
            return self._build_result(
                status="inconclusive",
                reason="error",
                error=str(e),
                message=f"处理出错: {str(e)}",
            )

    def _is_unity_app(self, apk: zipfile.ZipFile) -> bool:
        """检查是否为 Unity 应用"""
        unity_indicators = [
            "lib/arm64-v8a/libunity.so",
            "lib/armeabi-v7a/libunity.so",
            "lib/x86/libunity.so",
            "lib/x86_64/libunity.so",
        ]

        file_list = apk.namelist()

        # 检查是否存在 libunity.so
        has_libunity = any(indicator in file_list for indicator in unity_indicators)

        # 附加检查:Unity 核心资源文件(更严格的规则)
        unity_core_assets = [
            "assets/bin/Data/globalgamemanagers",
            "assets/bin/Data/level0",
            "assets/bin/Data/sharedassets0.assets",
            "assets/bin/Data/resources.assets",
        ]
        has_unity_assets = any(asset in file_list for asset in unity_core_assets)

        return has_libunity or has_unity_assets

    def _is_patched_by_tool(self, apk: zipfile.ZipFile) -> bool:
        """
        检查 APK 是否使用 Unity patcher 工具打过补丁

        Unity patcher 工具的工作原理:
        将 libunity.so 中的 "xrsdk-pre-init-library" 字符串破坏为 "8rsdk-pre-init-library"
        来禁用 XR SDK 预初始化功能,从而修复 CVE-2025-59489 漏洞。

        检测方法:
        检查 libunity.so 中是否包含补丁特征字符串 "8rsdk-pre-init-library"

        Returns:
            True: 检测到补丁标识,应用已修复
            False: 未检测到补丁标识
        """
        file_list = apk.namelist()

        # 检查 libunity.so 中的补丁特征
        lib_paths = [
            "lib/arm64-v8a/libunity.so",
            "lib/armeabi-v7a/libunity.so",
            "lib/x86_64/libunity.so",
            "lib/x86/libunity.so",
        ]

        for lib_path in lib_paths:
            if lib_path not in file_list:
                continue

            try:
                # 读取 so 文件
                # XR SDK 字符串通常在文件后半部分,读取整个文件以确保检测准确
                lib_data = apk.read(lib_path)

                # 检查是否包含补丁特征 (8rsdk-pre-init-library)
                has_patched_marker = any(marker in lib_data for marker in PATCH_MARKERS)

                if has_patched_marker:
                    self._log(f"在 {lib_path} 中发现补丁特征: 8rsdk-pre-init-library")
                    return True

                # 额外验证:如果找到原始的 xrsdk 字符串,说明未打补丁
                has_vulnerable_marker = any(
                    marker in lib_data for marker in VULNERABLE_MARKERS
                )
                if has_vulnerable_marker:
                    self._log(
                        f"在 {lib_path} 中发现原始字符串 (未打补丁): xrsdk-pre-init-library"
                    )
                    # 继续检查其他架构的 so 文件

            except KeyError:
                continue
            except Exception as e:
                self._log(f"检查补丁标识时出错 ({lib_path}): {str(e)}")
                continue

        return False

    def _extract_unity_version(self, apk: zipfile.ZipFile) -> Optional[str]:
        """从 APK 中提取 Unity 版本号"""

        # 方法 1: 从 libunity.so 中提取(最可靠)
        lib_paths = [
            "lib/arm64-v8a/libunity.so",
            "lib/armeabi-v7a/libunity.so",
            "lib/x86_64/libunity.so",
            "lib/x86/libunity.so",
        ]

        for lib_path in lib_paths:
            try:
                self._log(f"检查 {lib_path}")
                lib_data = apk.read(lib_path)
                version = self._extract_version_from_binary(lib_data)
                if version:
                    return version
            except KeyError:
                continue

        # 方法 2: 从 Unity 数据文件中提取
        data_paths = [
            "assets/bin/Data/globalgamemanagers",
            "assets/bin/Data/globalgamemanagers.assets",
            "assets/bin/Data/data.unity3d",
            "assets/bin/Data/mainData",
        ]

        for data_path in data_paths:
            try:
                self._log(f"检查 {data_path}")
                data = apk.read(data_path)
                # 只读取前 50KB 以提高性能
                version = self._extract_version_from_binary(
                    data[:MAX_DATA_FILE_READ_SIZE]
                )
                if version:
                    return version
            except KeyError:
                continue

        return None

    def _extract_version_from_binary(self, data: bytes) -> Optional[str]:
        """从二进制数据中提取 Unity 版本号"""
        # Unity 版本号格式示例:
        # - 标准格式:2019.4.40f1, 2022.3.15f1
        # - 新格式:6000.0.23f1, 6000.2.6f2
        # - 无后缀:2019.4.40, 6000.0.23

        # 优先匹配带后缀的完整版本号
        patterns_with_suffix = [
            rb"(6\d{3}\.\d+\.\d+[a-z]\d+)",  # 6000.x.xf1
            rb"(20(?:1[7-9]|2[0-3])\.\d+\.\d+[a-z]\d+)",  # 2019.x.xf1
        ]

        # 备选:无后缀版本(优先级较低)
        patterns_no_suffix = [
            rb"(6\d{3}\.\d+\.\d+)",  # 6000.x.x
            rb"(20(?:1[7-9]|2[0-3])\.\d+\.\d+)",  # 2019.x.x
        ]

        # 先尝试带后缀的版本
        all_versions = []
        for pattern in patterns_with_suffix:
            matches = re.findall(pattern, data)
            if matches:
                versions = [m.decode("utf-8", errors="ignore") for m in matches]
                all_versions.extend(versions)

        # 如果没找到带后缀的,再找无后缀的
        if not all_versions:
            for pattern in patterns_no_suffix:
                matches = re.findall(pattern, data)
                if matches:
                    versions = [m.decode("utf-8", errors="ignore") for m in matches]
                    all_versions.extend(versions)

        if not all_versions:
            return None

        # 过滤出有效版本并选择最可能的真实版本
        valid_versions = [v for v in all_versions if self._is_valid_unity_version(v)]
        if not valid_versions:
            return None

        # 选择策略:返回最可能的真实版本
        return self._select_most_likely_version(valid_versions)

    def _select_most_likely_version(self, versions: list[str]) -> str:
        """
        从多个版本号中选择最可能的真实版本

        策略:
        1. 统计每个版本出现的次数
        2. 优先选择出现次数最多的版本
        3. 如果次数相同,优先选择:
           - 带完整后缀的版本 (f1, b2 等)
           - 较新的版本
           - patch 号较大的版本
        4. 过滤明显异常的版本 (如过旧的 alpha/beta 版本)
        """
        from collections import Counter

        # 统计版本出现次数
        version_counts = Counter(versions)

        # 按出现次数、版本完整性、版本号排序
        def version_priority(v: str) -> tuple:
            count = version_counts[v]
            parsed = self._parse_version(v)
            if not parsed:
                return (-1, 0, 0, 0, "")

            major = parsed["major"]
            minor = parsed["minor"]
            patch = parsed["patch"]
            version_type = parsed.get("type", "")

            # 评分标准
            # 1. 出现次数(越多越可能是真实版本)
            # 2. 是否有版本类型后缀(f/b/a)
            # 3. 版本新旧程度(major.minor.patch)
            has_suffix = 1 if version_type else 0

            # 过滤异常版本:过旧的 alpha 版本可能是兼容性标识
            # 例如:2018.3.0a1 出现在 2021 版本中,很可能是最低兼容版本标识
            is_suspicious = 0
            if version_type == "a" and patch == 0:
                # 检查是否有其他更新的版本
                for other_v in versions:
                    other_parsed = self._parse_version(other_v)
                    if other_parsed and other_parsed["major"] > major:
                        is_suspicious = 1
                        break

            return (
                -count,  # 出现次数越多越好(负数是为了降序)
                is_suspicious,  # 可疑版本排后面
                -has_suffix,  # 有后缀的优先
                -major,  # 版本越新越好
                -minor,
                -patch,
            )

        sorted_versions = sorted(version_counts.keys(), key=version_priority)
        return sorted_versions[0]

    def _is_valid_unity_version(self, version: str) -> bool:
        """验证版本号格式是否合理"""
        parsed = self._parse_version(version)
        if not parsed:
            return False

        major = parsed["major"]
        # Unity 版本号应该在合理范围内
        return (2017 <= major <= 2030) or (6000 <= major <= 6999)

    def _check_vulnerability(
        self, version_str: str
    ) -> Literal["positive", "negative", "inconclusive"]:
        """判断版本是否受 CVE-2025-59489 影响"""
        parsed = self._parse_version(version_str)
        if not parsed:
            return "inconclusive"

        major = parsed["major"]
        minor = parsed["minor"]
        patch = parsed["patch"]
        version_type = parsed.get("type", "f")
        build = parsed.get("build", 1)

        # 规则 1: Unity 2017.1 之前的版本不受影响
        if major < 2017:
            return "negative"

        if major == 2017 and minor == 0:
            return "negative"

        # 规则 2: 检查是否为已修复版本
        if self._is_patched_version(major, minor, patch, version_type, build):
            self._log(f"版本 {version_str} 已修复")
            return "negative"

        # 规则 3: Unity 2017.1 - 2018.4 受影响但无官方补丁
        if major in (2017, 2018):
            self._log(f"版本 {version_str} 受 CVE-2025-59489 影响,但 Unity 官方未提供补丁")
            self.last_check_reason = "affected_no_official_patch"
            self.last_check_details["has_patch"] = False
            self.last_check_details["recommendation"] = "upgrade_unity_version"
            return "inconclusive"

        # 规则 4: Unity 2019.1+ 或 6000-6999 受影响(有补丁但当前版本未修复)
        if (2019 <= major <= 2023) or (6000 <= major <= 6999):
            self._log(f"版本 {version_str} 受影响(需更新到修复版本)")
            return "positive"

        return "inconclusive"

    def _parse_version(self, version: str) -> Optional[Dict[str, Any]]:
        """解析 Unity 版本号(支持 f/b/a 后缀)"""
        # 匹配格式:2019.4.40f1 或 6000.0.23b4 或 2019.4.40
        pattern = r"^(\d+)\.(\d+)\.(\d+)(?:([a-z])(\d+))?$"
        match = re.match(pattern, version)

        if match:
            return {
                "major": int(match.group(1)),
                "minor": int(match.group(2)),
                "patch": int(match.group(3)),
                "type": match.group(4) if match.group(4) else "f",  # f/b/a
                "build": int(match.group(5)) if match.group(5) else 1,
            }
        return None

    def _is_patched_version(
        self,
        major: int,
        minor: int,
        patch: int,
        version_type: str = "f",
        build: int = 1,
    ) -> bool:
        """检查是否为已修复版本(支持 beta/alpha 版本比较)"""
        if major not in self.PATCHED_VERSIONS:
            return False

        if minor not in self.PATCHED_VERSIONS[major]:
            return False

        min_version_info = self.PATCHED_VERSIONS[major][minor]

        # 兼容旧格式(直接是 patch 数字)
        if isinstance(min_version_info, int):
            return patch >= min_version_info

        # 新格式(包含 type 和 build 信息)
        min_patch = min_version_info["patch"]
        min_type = min_version_info.get("type", "f")
        min_build = min_version_info.get("build", 1)

        # 比较 patch 版本号
        if patch > min_patch:
            return True
        if patch < min_patch:
            return False

        # patch 相同,比较类型优先级:f > b > a
        type_priority = {"f": 3, "b": 2, "a": 1}
        current_priority = type_priority.get(version_type, 0)
        min_priority = type_priority.get(min_type, 0)

        if current_priority > min_priority:
            return True
        if current_priority < min_priority:
            return False

        # 类型相同,比较 build 号
        return build >= min_build

    def _build_result(
        self,
        status: Literal["positive", "negative", "inconclusive"],
        reason: Optional[str] = None,
        version: Optional[str] = None,
        is_unity: bool = False,
        has_patch: Optional[bool] = None,
        message: Optional[str] = None,
        recommendation: Optional[str] = None,
        error: Optional[str] = None,
    ) -> VulnerabilityCheckResult:
        """构建检测结果对象"""
        # 同步到实例变量(保持向后兼容)
        self.last_check_reason = reason
        if version:
            self.last_check_details["version"] = version
        if has_patch is not None:
            self.last_check_details["has_patch"] = has_patch
        if recommendation:
            self.last_check_details["recommendation"] = recommendation
        if error:
            self.last_check_details["error"] = error
        
        return VulnerabilityCheckResult(
            status=status,
            reason=reason,
            version=version,
            is_unity=is_unity,
            has_patch=has_patch,
            message=message,
            recommendation=recommendation,
            error=error,
        )

    def _log(self, message: str):
        """输出日志"""
        self.logger.debug(message)


def check_unity_vulnerability(
    apk_path: str, verbose: bool = False
) -> VulnerabilityCheckResult:
    """
    检测 APK 文件是否受 Unity CVE-2025-59489 漏洞影响

    Args:
        apk_path: APK 文件路径
        verbose: 是否输出详细日志

    Returns:
        VulnerabilityCheckResult: 包含详细检测结果的对象
            - result.status: "positive" | "negative" | "inconclusive"
            - result.is_vulnerable: 是否确认受影响
            - result.is_safe: 是否确认安全
            - result.version: Unity 版本号
            - result.message: 用户友好的描述
            - result.recommendation: 建议操作

    Example:
        >>> result = check_unity_vulnerability("game.apk")
        >>> if result.is_vulnerable:
        ...     print(f"受影响: {result.version}")
        ...     print(f"建议: {result.recommendation}")
        >>> elif result.is_safe:
        ...     print(f"安全: {result.message}")
    """
    checker = UnityVulnerabilityChecker(verbose=verbose)
    return checker.check_apk(apk_path)


# ==================== 批量检测功能 ====================


def batch_check(
    apk_dir: str, verbose: bool = False, max_workers: int = 4
) -> Dict[str, VulnerabilityCheckResult]:
    """
    批量检测目录下所有 APK 文件(支持并行处理)

    Args:
        apk_dir: 包含 APK 文件的目录
        verbose: 是否输出详细日志
        max_workers: 最大并行工作进程数

    Returns:
        {文件名:检测结果对象} 的字典
    """
    results = {}
    apk_files = list(Path(apk_dir).glob("*.apk"))
    print(f"找到 {len(apk_files)} 个 APK 文件")

    if not apk_files:
        return results

    # Use sequential processing for small batches or when verbose
    if len(apk_files) <= 3 or verbose:
        checker = UnityVulnerabilityChecker(verbose=verbose)
        for apk_path in apk_files:
            print(f"\n检测:{apk_path.name}")
            result = checker.check_apk(str(apk_path))
            results[apk_path.name] = result

            # 输出结果
            status_emoji = {
                "positive": "❌ 受影响",
                "negative": "✅ 安全",
                "inconclusive": "❓ 无法确定",
            }
            print(f"结果:{status_emoji[result.status]}")
    else:
        # Parallel processing for larger batches
        print(f"使用 {max_workers} 个并行进程...")

        def check_single_apk(apk_path: Path) -> Tuple[str, VulnerabilityCheckResult]:
            checker = UnityVulnerabilityChecker(verbose=False)
            result = checker.check_apk(str(apk_path))
            return (apk_path.name, result)

        with ProcessPoolExecutor(max_workers=max_workers) as executor:
            future_to_apk = {
                executor.submit(check_single_apk, apk): apk for apk in apk_files
            }

            for future in as_completed(future_to_apk):
                apk = future_to_apk[future]
                try:
                    apk_name, result = future.result()
                    results[apk_name] = result
                    status_emoji = {
                        "positive": "❌",
                        "negative": "✅",
                        "inconclusive": "❓",
                    }
                    print(f"{status_emoji[result.status]} {apk_name}")
                except Exception as e:
                    print(f"❌ {apk.name} - 处理出错:{e}")
                    # 创建一个表示错误的结果对象
                    error_result = VulnerabilityCheckResult(
                        status="inconclusive",
                        reason="error",
                        error=str(e),
                        message=f"处理出错: {str(e)}",
                    )
                    results[apk.name] = error_result

    return results


# ==================== 命令行接口 ====================

if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(
        description="Unity CVE-2025-59489 漏洞检测工具",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
使用示例:
  单文件检测:
    python unity_vulnerability_checker.py game.apk
    python unity_vulnerability_checker.py game.apk -v

  批量检测:
    python unity_vulnerability_checker.py --batch /path/to/apks
    python unity_vulnerability_checker.py --batch /path/to/apks -j 8

  查看帮助:
    python unity_vulnerability_checker.py --help
        """,
    )

    parser.add_argument("apk_path", nargs="?", help="APK 文件路径")
    parser.add_argument(
        "--batch", metavar="DIR", help="批量检测目录(扫描所有 .apk 文件)"
    )
    parser.add_argument("-v", "--verbose", action="store_true", help="输出详细日志")
    parser.add_argument(
        "-j",
        "--jobs",
        type=int,
        default=4,
        metavar="N",
        help="并行处理的进程数(默认:4)",
    )

    args = parser.parse_args()

    # Configure logging for the main script
    logging.basicConfig(
        format="%(message)s",
        level=logging.DEBUG if args.verbose else logging.INFO,
    )

    if args.batch:
        # 批量检测模式
        results = batch_check(args.batch, args.verbose, args.jobs)

        # 统计结果
        print("\n" + "=" * 50)
        print("统计结果:")
        positive = sum(1 for r in results.values() if r.status == "positive")
        negative = sum(1 for r in results.values() if r.status == "negative")
        inconclusive = sum(1 for r in results.values() if r.status == "inconclusive")

        print(f"  受影响:  {positive} 个")
        print(f"  安全:    {negative} 个")
        print(f"  无法确定:{inconclusive} 个")

    elif args.apk_path:
        # 单文件检测模式
        result = check_unity_vulnerability(args.apk_path, verbose=args.verbose)

        print("\n" + "=" * 50)
        print(f"APK 文件:{args.apk_path}")
        print(f"检测结果:{result.status}")

        # 根据状态显示详细信息
        if result.is_vulnerable:
            print(f"\n⚠️  {result.message}")
            if result.recommendation:
                print(f"建议:{result.recommendation}")

        elif result.is_safe:
            print(f"\n✅ {result.message}")

        else:  # inconclusive
            # 特殊处理:无官方补丁
            if result.reason == "affected_no_official_patch":
                print(f"\n⚠️  {result.message}")
                print(f"\n说明:该应用使用的 Unity 版本受 CVE-2025-59489 影响,但 Unity 官方未为 2017-2018 版本提供安全补丁。")
                print(f"\n建议:")
                print(f"  1. 升级到 Unity 2019.1+ 并重新构建应用")
                print(f"  2. 使用 Unity 官方工具: https://unity.com/security/sept-2025-01/remediation")
                print(f"  3. 联系 Unity 官方获取技术支持")
                print(f"\n处理建议:请开发者自行决定升级方案")
            # 特殊处理:文件过大
            elif result.reason == "file_too_large":
                print(f"\n⚠️  {result.message} - 修改代码第 15 行 MAX_APK_SIZE_MB 为更大值")
            # 其他无法确定的情况
            else:
                print(f"\n❓ {result.message}")
                if result.recommendation:
                    print(f"建议:{result.recommendation}")
                if result.error:
                    print(f"错误: {result.error}")

    else:
        parser.print_help()