PentestGPT V2源码研究之工具层设计模式

文章目录

  • 工具层设计模式
    • 一、工具层架构概述
      • [1.1 整体架构图](#1.1 整体架构图)
      • [1.2 核心组件关系](#1.2 核心组件关系)
      • [1.3 工具执行机制](#1.3 工具执行机制)
    • [二、TypedToolInterface - 工具接口定义](#二、TypedToolInterface - 工具接口定义)
      • [2.1 核心结构](#2.1 核心结构)
      • [2.2 接口字段详解](#2.2 接口字段详解)
      • [2.3 ToolParameter - 参数定义](#2.3 ToolParameter - 参数定义)
      • [2.4 ToolPrecondition/Postcondition - 前后置条件](#2.4 ToolPrecondition/Postcondition - 前后置条件)
    • [三、TypedSecurityTool - 工具基类](#三、TypedSecurityTool - 工具基类)
      • [3.1 核心方法](#3.1 核心方法)
      • [3.2 build_command() - 命令构建](#3.2 build_command() - 命令构建)
      • [3.3 get_documentation() - 文档生成](#3.3 get_documentation() - 文档生成)
    • [四、ToolRegistry - 工具注册表(单例模式)](#四、ToolRegistry - 工具注册表(单例模式))
      • [4.1 单例实现](#4.1 单例实现)
      • [4.2 核心功能](#4.2 核心功能)
      • [4.3 模式映射表](#4.3 模式映射表)
    • 五、工具分类体系
      • [5.1 ToolCategory 枚举](#5.1 ToolCategory 枚举)
      • [5.2 各分类工具数量](#5.2 各分类工具数量)
    • 六、工具工厂函数模式
      • [6.1 工厂函数结构](#6.1 工厂函数结构)
      • [6.2 工具工厂函数示例(以 nmap 为例)](#6.2 工具工厂函数示例(以 nmap 为例))
    • 七、Skill(技能)组合引擎
      • [7.1 Skill 设计模式](#7.1 Skill 设计模式)
      • [7.2 SkillStep - 步骤定义](#7.2 SkillStep - 步骤定义)
      • [7.3 SkillEngine - 技能引擎](#7.3 SkillEngine - 技能引擎)
      • [7.4 技能使用示例](#7.4 技能使用示例)
    • 八、扩展工具的方式
      • [8.1 方式一:添加新工具到现有类别](#8.1 方式一:添加新工具到现有类别)
      • [8.2 方式二:创建新的工具类别](#8.2 方式二:创建新的工具类别)
      • [8.3 方式三:创建自定义工具子类](#8.3 方式三:创建自定义工具子类)
    • 九、完整工具使用示例
      • [9.1 获取并使用工具](#9.1 获取并使用工具)
      • [9.2 运行工具(伪代码)](#9.2 运行工具(伪代码))
    • 十、工具层设计模式总结
      • [10.1 使用的设计模式](#10.1 使用的设计模式)
      • [10.2 扩展性设计](#10.2 扩展性设计)
    • 十一、技能系统深度分析
      • [11.1 技能系统架构](#11.1 技能系统架构)
      • [11.2 技能模块全景分析](#11.2 技能模块全景分析)
        • [11.2.1 Active Directory 技能(ad_skills.py)](#11.2.1 Active Directory 技能(ad_skills.py))
        • [11.2.2 Pivoting 技能(pivot_skills.py)](#11.2.2 Pivoting 技能(pivot_skills.py))
        • [11.2.3 Privilege Escalation 技能(privesc_skills.py)](#11.2.3 Privilege Escalation 技能(privesc_skills.py))
        • [11.2.4 Reconnaissance 技能(recon_skills.py)](#11.2.4 Reconnaissance 技能(recon_skills.py))
        • [11.2.5 Web Exploitation 技能(web_skills.py)](#11.2.5 Web Exploitation 技能(web_skills.py))
      • [11.3 参数映射机制深度解析](#11.3 参数映射机制深度解析)
      • [11.4 条件执行机制](#11.4 条件执行机制)
      • [11.5 回退逻辑设计](#11.5 回退逻辑设计)
      • [11.6 结果聚合策略](#11.6 结果聚合策略)
      • [11.7 技能注册与发现](#11.7 技能注册与发现)
      • [11.8 设计模式总结](#11.8 设计模式总结)
      • [11.9 设计合理性评估](#11.9 设计合理性评估)
      • [11.10 改进建议](#11.10 改进建议)
      • [11.11 与其他层的集成](#11.11 与其他层的集成)
    • 附录:相关文件索引

工具层设计模式

一、工具层架构概述

1.1 整体架构图

工具层 Tools Layer
Skill Engine
Tool Registry
TypedSecurityTool
TypedToolInterface
Categories
Skills

1.2 核心组件关系

组件 文件路径 职责
TypedToolInterface base.py:117 工具的类型化接口定义
TypedSecurityTool base.py:146 类型化工具基类
ToolRegistry registry.py:76 工具注册表(单例模式)
SkillEngine skill.py:67 技能组合引擎
Categories categories/*.py 6 大类工具工厂函数

1.3 工具执行机制

工具层采用声明式设计,Python 代码仅定义工具接口和命令模板,实际执行由 Claude Code CLI 完成:
build command
terminal_execute
输出
TypedSecurityTool
CLI 命令字符串
Claude Code SDK
系统 CLI 工具
结果解析

执行流程

  1. 命令构建 :工具调用 build_command() 将参数填充到 command_template,生成完整 CLI 命令(如 nmap -sV -p 80 192.168.1.1
  2. 委托执行 :Claude Code 代理通过 SDK 的 terminal_execute 能力在系统上执行该命令
  3. 结果返回:命令输出被捕获并返回给上层进行解析和处理

关键特性

  • 框架无关:工具定义不依赖任何特定执行引擎
  • 系统工具依赖 :实际功能由系统安装的 CLI 工具提供(通过 Dockerfile 安装 Kali 工具集)
  • 安全隔离:Claude Code 负责权限管理和执行环境控制

实现示例 (来自 base.py:191-210):

python 复制代码
def build_command(self, **kwargs: Any) -> str:
    """从模板构建 CLI 命令。"""
    template = self.interface.command_template
    for param in self.interface.input_schema:
        key = param.name
        value = kwargs.get(key, param.default)
        if value is not None:
            template = template.replace(f"{{{key}}}", str(value))
    return template

二、TypedToolInterface - 工具接口定义

2.1 核心结构

位于 base.py:117-143

python 复制代码
class TypedToolInterface(BaseModel):
    """
    安全工具的类型化接口定义。
    
    捕获工具的完整模式,包括输入、输出、前置条件、后置条件
    以及用于构建 CLI 调用的命令模板。
    """

2.2 接口字段详解

python 复制代码
# excalibur/tools/base.py:117-143
class TypedToolInterface(BaseModel):
    name: str                    # 工具名称(如 "nmap", "sqlmap")
    category: ToolCategory       # 工具类别枚举
    description: str             # 工具功能描述
    input_schema: list[ToolParameter]   # 输入参数定义列表
    output_schema: list[ToolOutputField] # 输出字段定义列表
    preconditions: list[ToolPrecondition]  # 执行前置条件
    postconditions: list[ToolPostcondition] # 执行后置条件
    command_template: str        # CLI 命令模板,支持 {param_name} 占位符
    timeout: int = 300           # 超时时间(秒)

2.3 ToolParameter - 参数定义

python 复制代码
# excalibur/tools/base.py:46-68
class ToolParameter(BaseModel):
    name: str                    # 参数名称
    type: str = "string"         # 参数数据类型
    required: bool = False       # 是否必需参数
    default: Any = None          # 默认值
    description: str             # 参数描述
    validation_pattern: str | None   # 验证正则表达式
    choices: list[str] | None        # 允许值列表(枚举类型)

2.4 ToolPrecondition/Postcondition - 前后置条件

python 复制代码
# excalibur/tools/base.py:86-115
class ToolPrecondition(BaseModel):
    """
    工具执行前必须满足的条件。
    
    check_type: 检查类型
        - "port_open": 端口是否开放
        - "service_running": 服务是否运行
        - "file_exists": 文件是否存在
        - "host_reachable": 主机是否可达
        - "root_access": 是否需要 root 权限
    """

class ToolPostcondition(BaseModel):
    """
    工具执行后产生的效果。
    
    effect_type: 效果类型
        - "discovers_services": 发现服务
        - "gains_access": 获得访问权限
        - "reveals_data": 揭示数据
    """

三、TypedSecurityTool - 工具基类

3.1 核心方法

位于 base.py:146-271

python 复制代码
class TypedSecurityTool:
    """
    类型化安全工具的基类。
    
    执行委托给 Claude Code 后端。此类提供命令构建、文档生成和序列化功能。
    """

3.2 build_command() - 命令构建

python 复制代码
# excalibur/tools/base.py:191-210
def build_command(self, **kwargs: Any) -> str:
    """
    从模板和提供的参数构建 CLI 命令。
    
    将命令模板中的 {param_name} 占位符替换为实际值。
    缺失的可选参数使用其默认值替换;缺失的必需参数保持原样。
    
    示例:
        >>> tool = nmap_tool()
        >>> tool.build_command(target="192.168.1.1", ports="80,443")
        "nmap -sV -T4 -p 80,443 --script=default 192.168.1.1"
    """

3.3 get_documentation() - 文档生成

python 复制代码
# excalibur/tools/base.py:212-262
def get_documentation(self) -> str:
    """
    返回此工具的人类可读文档。
    
    生成格式化的文档字符串,包含:
    - 工具名称、类别、描述
    - 参数列表(类型、是否必需、默认值)
    - 输出字段
    - 前置条件、后置条件
    - 命令模板
    """

四、ToolRegistry - 工具注册表(单例模式)

4.1 单例实现

位于 registry.py:257-278

python 复制代码
# excalibur/tools/registry.py:261-278
def get_registry() -> ToolRegistry:
    """
    获取(或创建)全局工具注册表单例。
    
    使用单例模式确保整个应用程序只有一个工具注册表实例。
    首次调用时创建实例,后续调用返回现有实例。
    """
    global _global_registry
    if _global_registry is None:
        _global_registry = ToolRegistry()
    return _global_registry

4.2 核心功能

python 复制代码
# excalibur/tools/registry.py:76-191
class ToolRegistry:
    """
    类型化安全工具的注册表管理和访问系统。
    
    支持按类别注册、查找、按渗透测试模式过滤和文档生成。
    """
方法 说明
register(tool) 注册单个工具
_register_all_tools() 自动注册所有内置工具
get(name) 根据名称获取工具
list_tools() 列出所有工具名称
list_tools_by_category(category) 按类别列出工具
get_tools_for_mode(mode) 按渗透测试模式获取相关工具

4.3 模式映射表

python 复制代码
# excalibur/tools/registry.py:42-73
_MODE_CATEGORY_MAP = {
    "recon": [ToolCategory.RECONNAISSANCE],
    "web": [ToolCategory.WEB_EXPLOITATION],
    "network": [ToolCategory.NETWORK_EXPLOITATION],
    "credentials": [ToolCategory.CREDENTIAL_ATTACKS],
    "ad": [ToolCategory.ACTIVE_DIRECTORY],
    "privesc": [ToolCategory.PRIVILEGE_ESCALATION],
    "full": [...all categories...],
}

五、工具分类体系

5.1 ToolCategory 枚举

python 复制代码
# excalibur/tools/base.py:24-43
class ToolCategory(str, Enum):
    RECONNAISSANCE = "reconnaissance"      # 信息收集
    WEB_EXPLOITATION = "web_exploitation"  # Web 漏洞利用
    NETWORK_EXPLOITATION = "network_exploitation"  # 网络漏洞利用
    CREDENTIAL_ATTACKS = "credential_attacks"  # 凭证攻击
    ACTIVE_DIRECTORY = "active_directory"  # Active Directory
    PRIVILEGE_ESCALATION = "privilege_escalation"  # 权限提升

5.2 各分类工具数量

类别 文件路径 工具数量
Reconnaissance categories/reconnaissance.py 8
Web Exploitation categories/web_exploitation.py 8
Network Exploitation categories/network_exploitation.py 8
Credential Attacks categories/credential_attacks.py 5
Active Directory categories/active_directory.py 6
Privilege Escalation categories/privilege_escalation.py 6

六、工具工厂函数模式

6.1 工厂函数结构

每个分类文件都遵循相同的工厂函数模式:

python 复制代码
# excalibur/tools/categories/reconnaissance.py:791-802
def get_reconnaissance_tools() -> list[TypedSecurityTool]:
    """Return all reconnaissance tools."""
    return [
        nmap_tool(),           # 工厂函数调用
        masscan_tool(),
        gobuster_tool(),
        ffuf_tool(),
        feroxbuster_tool(),
        nikto_tool(),
        whatweb_tool(),
        enum4linux_tool(),
    ]

6.2 工具工厂函数示例(以 nmap 为例)

python 复制代码
# excalibur/tools/categories/reconnaissance.py:20-136
def nmap_tool() -> TypedSecurityTool:
    """Nmap network scanner for host discovery and service enumeration."""
    return TypedSecurityTool(
        interface=TypedToolInterface(
            name="nmap",
            category=ToolCategory.RECONNAISSANCE,
            description=(
                "Network exploration and security auditing tool. "
                "Discovers hosts, open ports, running services..."
            ),
            input_schema=[
                ToolParameter(
                    name="target",
                    type="string",
                    required=True,
                    description="Target IP, hostname, CIDR range...",
                    validation_pattern=r"^[\w.\-/:\[\],\s]+$",
                ),
                # ... 更多参数定义
            ],
            output_schema=[
                ToolOutputField(
                    name="open_ports",
                    type="list[int]",
                    description="List of discovered open ports",
                ),
                # ... 更多输出字段
            ],
            preconditions=[
                ToolPrecondition(
                    description="Target host must be reachable",
                    check_type="host_reachable",
                    parameters={"target": "{target}"},
                ),
            ],
            postconditions=[
                ToolPostcondition(
                    description="Discovers open ports and running services",
                    effect_type="discovers_services",
                ),
            ],
            command_template=(
                "nmap {scan_type} {timing} "
                "-p {ports} --script={scripts} "
                "-oN {output_file} {extra_flags} {target}"
            ),
            timeout=600,
        )
    )

七、Skill(技能)组合引擎

7.1 Skill 设计模式

位于 skill.py:44-65

python 复制代码
class Skill(BaseModel):
    """
    组合的多工具工作流定义。
    
    技能是一个高级抽象,将多个工具按特定顺序组合成一个完整的操作流程。
    例如:"full_port_scan" 技能可能包含:端口扫描 -> 服务识别 -> 结果整理
    """

7.2 SkillStep - 步骤定义

python 复制代码
# excalibur/tools/skill.py:23-42
class SkillStep(BaseModel):
    """
    技能工作流中的单个步骤。
    
    Attributes:
        tool_name: 要执行的工具名称(必须在工具注册表中注册)
        parameter_mapping: 技能级输入参数到工具参数的映射字典
            例如:{"target": "host", "ports": "port_list"}
        condition: 执行此步骤前需要满足的条件表达式
            例如:"port_open(80)"
    """

7.3 SkillEngine - 技能引擎

python 复制代码
# excalibur/tools/skill.py:67-205
class SkillEngine:
    """
    技能注册、检索和文档生成引擎。
    
    负责管理所有已注册的技能,提供技能查找、列表展示和文档生成功能。
    """

7.4 技能使用示例

python 复制代码
# 创建一个完整的端口扫描技能
full_port_scan = Skill(
    name="full_port_scan",
    description="完整的端口扫描流程:快速扫描 -> 详细扫描 -> 服务识别",
    tool_sequence=[
        SkillStep(
            tool_name="masscan",
            parameter_mapping={"target": "target", "ports": "all_ports"},
            condition=None,
        ),
        SkillStep(
            tool_name="nmap",
            parameter_mapping={"target": "target", "ports": "{masscan.ports}"},
            condition="open_ports_found",
        ),
    ],
    fallback_logic="如果快速扫描失败,使用 nmap 进行完整扫描",
    result_aggregation="merge",
)

八、扩展工具的方式

8.1 方式一:添加新工具到现有类别

python 复制代码
# 在 categories/reconnaissance.py 中添加新工具:
def my_custom_tool() -> TypedSecurityTool:
    """My custom reconnaissance tool."""
    return TypedSecurityTool(
        interface=TypedToolInterface(
            name="mytool",
            category=ToolCategory.RECONNAISSANCE,
            description="My custom tool description",
            input_schema=[
                ToolParameter(name="target", type="string", required=True),
                # ... 其他参数
            ],
            output_schema=[
                ToolOutputField(name="result", type="string"),
            ],
            command_template="mytool {target}",
        )
    )

# 在 get_reconnaissance_tools() 中添加:
def get_reconnaissance_tools() -> list[TypedSecurityTool]:
    return [
        nmap_tool(),
        # ... 其他工具
        my_custom_tool(),  # 新增
    ]

8.2 方式二:创建新的工具类别

python 复制代码
# 1. 在 base.py 的 ToolCategory 中添加新类别:
class ToolCategory(str, Enum):
    RECONNAISSANCE = "reconnaissance"
    # ... 现有类别
    CLOUD_SECURITY = "cloud_security"  # 新增

# 2. 创建新的分类文件 categories/cloud_security.py
def get_cloud_security_tools() -> list[TypedSecurityTool]:
    return [
        aws_audit_tool(),
        azure_scan_tool(),
    ]

# 3. 在 registry.py 的 _register_all_tools() 中添加:
def _register_all_tools(self) -> None:
    all_tool_factories = [
        # ... 现有工厂函数
        get_cloud_security_tools,  # 新增
    ]

8.3 方式三:创建自定义工具子类

python 复制代码
# excalibur/tools/base.py:146-271
class TypedSecurityTool:
    """
    类型化安全工具的基类。
    
    可以继承此类并覆盖方法来定制行为。
    """
python 复制代码
# 创建自定义工具子类
class CustomNmap(TypedSecurityTool):
    """Customized nmap tool with extended features."""
    
    def build_command(self, **kwargs: Any) -> str:
        """Override to add custom flags."""
        template = super().build_command(**kwargs)
        if kwargs.get("aggressive"):
            template += " --aggressive"
        return template
    
    def get_documentation(self) -> str:
        """Override to add custom documentation sections."""
        doc = super().get_documentation()
        doc += "\n\n## Custom Features\n- Aggressive mode support"
        return doc

九、完整工具使用示例

9.1 获取并使用工具

python 复制代码
from excalibur.tools.registry import get_registry
from excalibur.tools.base import ToolCategory

# 获取全局注册表
registry = get_registry()

# 方式 1: 通过名称获取工具
nmap = registry.get("nmap")
if nmap:
    # 构建命令
    cmd = nmap.build_command(target="192.168.1.1", ports="80,443")
    print(f"Command: {cmd}")
    
    # 获取文档
    doc = nmap.get_documentation()
    print(doc)

# 方式 2: 按类别获取所有工具
recon_tools = registry.list_tools_by_category(ToolCategory.RECONNAISSANCE)
for tool in recon_tools:
    print(f"{tool.name}: {tool.interface.description[:50]}...")

# 方式 3: 按模式获取相关工具
web_tools = registry.get_tools_for_mode("web")
for tool in web_tools:
    print(f"Web tool: {tool.name}")

9.2 运行工具(伪代码)

python 复制代码
async def run_tool(tool_name: str, **params):
    """
    运行指定工具。
    
    实际执行由 Claude Code 后端处理,这里展示逻辑流程。
    """
    registry = get_registry()
    tool = registry.get(tool_name)
    
    if not tool:
        raise ValueError(f"Tool {tool_name} not found")
    
    # 检查前置条件
    for precondition in tool.interface.preconditions:
        if not await check_precondition(precondition, params):
            print(f"Precondition failed: {precondition.description}")
            return None
    
    # 构建命令
    command = tool.build_command(**params)
    
    # 执行命令(由后端处理)
    result = await backend.execute(command, timeout=tool.interface.timeout)
    
    # 解析结果
    parsed_result = parse_tool_output(result, tool.interface.output_schema)
    
    return parsed_result

十、工具层设计模式总结

10.1 使用的设计模式

模式 应用位置 说明
单例模式 ToolRegistry 全局唯一的工具注册表
工厂方法模式 get_*_tools() 每个分类的工厂函数创建工具实例
策略模式 build_command(), get_documentation() 可被覆盖的方法提供不同实现
组合模式 Skill 技能由多个步骤组成,每个步骤是一个工具

10.2 扩展性设计

python 复制代码
# 工具层的设计充分考虑了扩展性:

# 1. TypedToolInterface 使用 Pydantic BaseModel
#    - 自动序列化/反序列化
#    - 类型验证
#    - 易于添加新字段

# 2. ToolRegistry 支持动态注册
#    - 可以运行时添加新工具
#    - 支持自定义工具子类

# 3. SkillEngine 提供高级抽象
#    - 将多个工具组合成工作流
#    - 支持参数映射和条件执行

# 4. 分类清晰,易于维护
#    - 6 大类别对应不同的安全领域
#    - 每个类别有独立的工厂函数

十一、技能系统深度分析

11.1 技能系统架构

技能系统建立在声明式定义 + AI 驱动执行的架构之上,将多步骤渗透测试工作流抽象为可复用的高级组件。
执行层 Execution Layer
定义层 Definition Layer
读取定义
提供工具
Skill
SkillStep
ToolRegistry
ExcaliburAgent
Claude Code AI
Tool Execution

核心组件

组件 文件 职责
Skill skill.py:44 工作流定义:名称、描述、步骤序列、回退逻辑、结果聚合
SkillStep skill.py:23 单个步骤:工具名、参数映射、执行条件
SkillEngine skill.py:67 技能注册、查找、文档生成(不执行
ExcaliburAgent core/agent.py:64 AI 驱动执行,读取技能定义并调用工具

关键设计决策

  • 定义与执行分离:Skill 仅是数据模型,实际执行由 AI 动态决定
  • 无状态引擎:SkillEngine 不维护执行状态,仅作为技能仓库
  • AI 作为执行器:Claude Code 理解技能语义,自主决定执行顺序和参数传递

11.2 技能模块全景分析

Excalibur 包含 5 个技能模块,共定义 13 个技能

模块 文件 技能数量 技能列表
Active Directory ad_skills.py 3 kerberoasting, pass_the_hash, asrep_roasting
Pivoting pivot_skills.py 2 network_pivot, credential_spray
Privilege Escalation privesc_skills.py 2 linux_enum, windows_enum
Reconnaissance recon_skills.py 3 full_port_scan, service_enumeration, web_discovery
Web Exploitation web_skills.py 3 sqli_chain, auth_bypass, file_inclusion
11.2.1 Active Directory 技能(ad_skills.py)

1. kerberoasting

  • 目标:提取并破解服务账号的 Kerberos TGS 票据
  • 步骤序列
    1. impacket(GetUserSPNs)→ 枚举 SPN 并请求 TGS
    2. hashcat(条件:获取到 TGS 哈希)→ 破解哈希
    3. crackmapexec(条件:hashcat 成功破解)→ 验证凭据
  • 参数映射特点:技能级参数(domain, username, password, dc_ip, target)映射到 impacket 脚本参数;后续步骤使用上一步的输出字段(tgs_hash_file, cracked_user, cracked_pass)
  • 回退策略:Rubeus(Windows)或 john(替代破解器)
  • 结果聚合:sequential(顺序传递)

2. pass_the_hash

  • 目标:使用 NTLM 哈希进行横向移动
  • 步骤序列
    1. impacket(secretsdump)→ 提取哈希
    2. crackmapexec(条件:提取到哈希)→ 验证哈希并识别管理员访问
    3. evil_winrm(条件:确认管理员访问)→ 建立 shell
  • 参数传递:ntlm_hash 从步骤1传递到步骤2和3;target_range 用于批量验证
  • 回退策略:psexec/wmiexec/smbexec;mimikatz(权限不足时)
  • 设计亮点:条件链式依赖,确保只有有效哈希才用于后续步骤

3. asrep_roasting

  • 目标:提取并破解 AS-REP 哈希(无需预认证账户)
  • 步骤序列
    1. impacket(GetNPUsers)→ 识别无预认证账户并提取哈希
    2. hashcat(条件:获取到 AS-REP 哈希)→ 破解
  • 回退策略:kerbrute 用户枚举 → 重新运行;Rubeus(Windows)
  • 简化设计:仅2步,适合快速攻击
11.2.2 Pivoting 技能(pivot_skills.py)

1. network_pivot

  • 目标:通过被控主机建立隧道并扫描内网
  • 步骤序列
    1. chisel → 建立 SOCKS 代理隧道
    2. proxychains(条件:隧道建立成功)→ 配置代理
    3. nmap(条件:代理配置完成)→ 通过隧道扫描内网
  • 参数映射:pivot_host, listen_port, tunnel_spec → chisel;internal_range → nmap
  • 回退:SSH 动态端口转发、socat、nmap 直接配置 SOCKS

2. credential_spray

  • 目标:凭证喷洒攻击(避免账户锁定)
  • 步骤序列
    1. kerbrute → 枚举有效 AD 用户名
    2. crackmapexec(条件:发现有效用户名)→ SMB 喷洒
    3. hydra(条件:SMB 喷洒失败且其他服务可用)→ 多服务喷洒
  • 设计特点:多工具协作,条件分支处理不同结果
  • 安全考虑:回退逻辑中强调避免账户锁定
11.2.3 Privilege Escalation 技能(privesc_skills.py)

1. linux_enum

  • 目标:自动化 Linux 权限提升枚举
  • 步骤序列
    1. linpeas → 全面枚举(SUID、cron、capabilities 等)
    2. pspy(条件:发现 cron 相关向量)→ 监控进程
  • 结果聚合:merge(合并输出)
  • 回退:手动检查命令列表(非常详细)

2. windows_enum

  • 目标:自动化 Windows 权限提升枚举
  • 步骤序列
    1. winpeas → 枚举令牌权限、服务、凭据等
    2. seatbelt(条件:发现感兴趣的项目)→ 详细安全检查
  • 聚合策略:merge
  • 回退:手动命令清单(whoami /priv, wmic, reg query 等)
11.2.4 Reconnaissance 技能(recon_skills.py)

1. full_port_scan

  • 目标:全端口发现(快速 + 详细)
  • 步骤序列
    1. masscan → 快速全端口扫描
    2. nmap(条件:发现开放端口)→ 详细服务版本扫描
  • 聚合:merge
  • 回退:无 root 时使用 nmap -sS

2. service_enumeration

  • 目标:服务版本检测和指纹识别
  • 步骤序列
    1. nmap → 版本检测和默认脚本
    2. whatweb(条件:检测到 HTTP/HTTPS)→ Web 技术指纹
    3. enum4linux(条件:检测到 SMB)→ SMB 枚举
  • 设计:并行条件分支(HTTP 和 SMB 可同时触发)

3. web_discovery

  • 目标:Web 内容发现和参数模糊测试
  • 步骤序列
    1. whatweb → 技术指纹
    2. feroxbuster → 递归目录扫描
    3. ffuf(条件:发现应用端点)→ 参数和 vhost 模糊测试
  • 回退:gobuster, ffuf 独立使用
11.2.5 Web Exploitation 技能(web_skills.py)

1. sqli_chain

  • 目标:端到端 SQL 注入利用
  • 步骤序列
    1. nuclei → 模板扫描(SQLi 指示器)
    2. sqlmap(条件:检测到潜在 SQLi)→ 自动检测和利用
    3. sqlmap(条件:确认漏洞)→ 数据转储
  • 注意:两次使用 sqlmap,第二次复用第一次的 injectable_url 参数
  • 回退:提高 risk/level,手动 wfuzz

2. auth_bypass

  • 目标:认证绕过(模糊测试 + 命令注入测试)
  • 步骤序列
    1. wfuzz → 登录表单绕过载荷测试
    2. nuclei(条件:发现响应变化)→ 默认凭据和已知绕过
    3. commix(条件:参数可注入)→ 命令注入测试
  • 条件判断:基于"interesting response variations"等主观标准

3. file_inclusion

  • 目标:文件包含漏洞利用(LFI/RFI → 命令执行)
  • 步骤序列
    1. ffuf → 发现文件包含参数
    2. wfuzz(条件:发现接受文件路径的参数)→ 确认 LFI
    3. commix(条件:LFI 确认且可利用)→ 日志投毒或 wrapper 利用
  • 攻击链:参数发现 → 漏洞确认 → 命令执行

11.3 参数映射机制深度解析

技能参数映射是技能级抽象工具级实现之间的桥梁:

python 复制代码
# 示例:kerberoasting 技能的参数映射
SkillStep(
    tool_name="impacket",
    parameter_mapping={
        "script": "script",          # 技能参数 script → 工具参数 script
        "domain": "domain",          # 技能参数 domain → 工具参数 domain
        "username": "username",      # 技能参数 username → 工具参数 username
        "password": "password",      # 技能参数 password → 工具参数 password
        "dc_ip": "dc_ip",            # 技能参数 dc_ip → 工具参数 dc_ip
        "target": "target",          # 技能参数 target → 工具参数 target
    },
)

映射规则

  1. 直接映射 :技能参数名与工具参数名相同(如 "domain": "domain"
  2. 重命名映射 :技能参数名与工具参数名不同(如 "dc_ip": "dc_ip" 实际是相同名,但可不同)
  3. 上一步输出引用 :后续步骤可使用前一步的输出字段作为参数值(如 "hash_file": "tgs_hash_file" 中的 tgs_hash_file 是 impacket 的输出字段)

执行时的参数解析(伪代码):

python 复制代码
# 当 AI 调用技能步骤时:
skill_inputs = {"domain": "corp.local", "username": "admin", ...}
mapped_params = {}
for skill_param, tool_param in step.parameter_mapping.items():
    if skill_param in skill_inputs:
        mapped_params[tool_param] = skill_inputs[skill_param]
    # 如果工具参数值引用前一步输出,从上一步结果中获取
    if tool_param in previous_step_outputs:
        mapped_params[tool_param] = previous_step_outputs[tool_param]
command = tool.build_command(**mapped_params)

设计优势

  • 解耦:技能定义者无需了解工具内部参数名,只需映射
  • 灵活性:同一技能可适配不同工具(如 hashcat → john)
  • 可读性:参数映射清晰展示数据流向

11.4 条件执行机制

条件字段condition: str | None 是自由文本描述,如:

  • "GetUserSPNs retrieved at least one TGS hash"
  • "hashcat cracked at least one Kerberos hash"
  • "masscan found at least one open port"

条件评估

  • 无内置评估器:条件字符串不参与实际执行决策
  • AI 语义理解:Claude Code AI 读取条件文本,根据上下文判断是否满足
  • 依赖输出解析:AI 必须解析前一步的工具输出,判断条件是否成立

示例执行流程(kerberoasting):

  1. AI 执行 impacket GetUserSPNs,捕获输出
  2. AI 分析输出,判断是否包含 TGS 哈希(如 "$krb5tgs$23$*..." 格式)
  3. 如果满足条件 "GetUserSPNs retrieved at least one TGS hash",则执行 hashcat
  4. AI 等待 hashcat 完成,检查输出是否包含破解的明文密码
  5. 如果满足条件 "hashcat cracked at least one Kerberos hash",则执行 crackmapexec 验证

条件设计缺陷

  • 非结构化:自由文本无法被机器解析,完全依赖 AI 理解

  • 歧义性:如"interesting response variations"无客观标准

  • 无法验证:注册时无法检查条件语法或语义

  • 建议改进 :定义结构化条件对象,如:

    python 复制代码
    class Condition(BaseModel):
        type: str  # "has_output", "output_contains", "count_gt", etc.
        field: str  # 输出字段名
        operator: str  # ">", "==", "contains", "regex_match"
        value: Any

11.5 回退逻辑设计

回退字段fallback_logic: str 是纯描述性文本,如:

"If impacket GetUserSPNs fails, try Rubeus kerberoast from a domain-joined Windows host. If hashcat is too slow, fall back to john with the krb5tgs format."

回退触发

  • AI 检测到工具执行失败(非零退出码、错误输出、超时)
  • AI 读取 fallback_logic 文本,理解备用方案
  • AI 自主决定是否实施回退,以及选择哪种回退路径

回退类型

  1. 工具替换:impacket → Rubeus(不同工具实现相同功能)
  2. 参数调整:hashcat → john(不同参数,相同目的)
  3. 策略变更:kerbrute 失败 → 改用 LDAP 枚举
  4. 手动干预:建议手动检查命令列表

设计缺陷

  • 不可执行:回退逻辑是文本,不是可执行代码

  • 无优先级:多个回退选项无排序,AI 需自行判断

  • 无状态管理:回退后是否继续后续步骤?是否重置状态?未定义

  • 建议改进 :将回退定义为备选步骤序列:

    python 复制代码
    fallback_steps: list[SkillStep] = []  # 结构化回退步骤
    fallback_condition: str | None = None  # 触发回退的条件

11.6 结果聚合策略

聚合字段result_aggregation: str 支持两个值:

  • "sequential"(默认):步骤结果依次传递,后一步可访问前一步输出
  • "merge":合并所有步骤的输出

实际实现

  • 框架未实现SkillEngine 无聚合逻辑,仅存储字段值
  • AI 负责聚合:Claude Code 在对话上下文中维护步骤输出,自主决定如何组合

使用模式

  • sequential:常见于攻击链,后一步依赖前一步结果(如 kerberoasting)
  • merge:用于枚举类技能,所有步骤输出都重要(如 linux_enum)

缺失功能

  • result_aggregation="filter""deduplicate" 选项
  • 无结构化结果对象,输出仅为原始文本
  • 建议:实现 SkillExecutor 类,提供 execute(inputs) -> SkillResult 方法,内部处理聚合

11.7 技能注册与发现

注册方式

python 复制代码
# excalibur/tools/skills/__init__.py
def get_all_skills() -> list:
    skills = []
    skills.extend(get_recon_skills())
    skills.extend(get_web_skills())
    skills.extend(get_privesc_skills())
    skills.extend(get_ad_skills())
    skills.extend(get_pivot_skills())
    return skills

注册时机

  • 技能在模块导入时未自动注册到 SkillEngine
  • 需要显式调用 engine.register_skills(get_all_skills())
  • 当前代码中未找到 SkillEngine 的实际使用位置(搜索结果显示仅文档生成)

发现机制

  • SkillEngine.list_skills() 返回所有已注册技能名称
  • SkillEngine.get_skill_documentation(name) 生成人类可读文档
  • 文档包含步骤、参数映射、条件、回退逻辑

11.8 设计模式总结

技能系统应用了以下设计模式:

模式 应用位置 说明
组合模式 Skill 技能由多个 SkillStep 组合而成,SkillStep 可嵌套(通过参数引用)
声明式编程 所有技能定义 使用数据模型(Pydantic)描述工作流,而非命令式代码
工厂方法 get_*_skills() 每个模块提供工厂函数创建技能实例
策略模式 result_aggregation 不同聚合策略可互换(虽未实现)
模板方法 parameter_mapping 定义参数转换的"模板",具体映射由子类(各技能)提供

11.9 设计合理性评估

优点
  1. 关注点分离清晰

    • 工具层(TypedToolInterface)定义"能做什么"
    • 技能层(Skill)定义"如何组合工具"
    • 执行层(Agent)决定"何时执行"
    • 各层职责单一,易于维护
  2. 高度可重用性

    • 技能封装常见攻击链,避免重复定义
    • 参数映射允许技能适配不同场景
    • 回退逻辑提供备用方案指导
  3. 自文档化

    • SkillEngine.get_skill_documentation() 自动生成 Markdown 文档
    • 技能描述、步骤、参数映射、条件、回退全部包含
    • 便于安全人员理解和手动执行
  4. AI 友好设计

    • 自由文本条件、回退逻辑适合 LLM 语义理解
    • 无硬编码执行流程,AI 可灵活调整
    • 适合非确定性渗透测试场景
  5. 类型安全

    • Pydantic 模型确保数据结构有效
    • 字段类型、默认值、验证规则明确
    • IDE 支持自动补全和类型检查
  6. 扩展性强

    • 新技能只需添加新 Skill 实例
    • 无需修改 SkillEngine 或 Agent
    • 支持运行时动态注册
设计缺陷
  1. 条件系统不完整

    • ❌ 条件为自由文本,无语法和语义验证
    • ❌ 无条件评估引擎,依赖 AI 主观判断
    • ❌ 无法在注册时验证条件引用字段是否存在
    • ✅ 优点:灵活,AI 可理解复杂上下文
    • 🔧 改进:定义结构化条件 DSL 或 JSON Schema
  2. 回退逻辑不可执行

    • ❌ 回退仅为描述性文本,AI 可能忽略或误解
    • ❌ 无回退优先级和选择策略
    • ❌ 回退失败后是否继续?无定义
    • ✅ 优点:提供人类可读的备用方案
    • 🔧 改进:fallback_steps: list[SkillStep] + fallback_condition
  3. 结果聚合未实现

    • result_aggregation 字段存在但无实际聚合逻辑
    • ❌ 无结果对象,输出仅为原始文本
    • ❌ 步骤间结果传递依赖 AI 维护上下文
    • ✅ 优点:不强制聚合,AI 可根据需要提取信息
    • 🔧 改进:实现 SkillExecutor,提供 execute() 返回结构化结果
  4. 参数映射静态化

    • ❌ 仅支持简单键值映射,不支持动态计算
    • ❌ 无法实现条件参数(如 target = dc_ip if is_dc else target
    • ❌ 无法引用环境变量或全局状态
    • ✅ 优点:简单直观,易于理解
    • 🔧 改进:支持 lambda 表达式或模板字符串(如 "{previous_step.output_file}"
  5. 缺少执行引擎

    • SkillEngine 仅有注册和文档功能,无 execute() 方法
    • ❌ 技能无法程序化运行,必须通过 AI 代理
    • ❌ 无法单元测试技能逻辑(需模拟 AI)
    • ✅ 优点:保持框架简洁,避免重复造轮子(AI 已是通用执行器)
    • 🔧 改进:添加 SkillExecutor 类,支持确定性执行(用于测试和自动化)
  6. 条件与输出耦合

    • ❌ 条件引用工具输出字段(如 "tgs_hash_file"),但未在 SkillStep 中定义输出模式
    • ❌ 工具输出字段在 TypedToolInterface.output_schema 中定义,但技能步骤未关联
    • ❌ 参数映射中的字段名(如 "tgs_hash_file")需与工具输出字段完全匹配,无类型检查
    • 🔧 改进:在 SkillStep 中添加 output_mapping 字段,明确指定从工具输出中提取哪些字段
  7. 循环依赖风险

    • ❌ 技能步骤可引用前一步的输出,但无循环检测
    • ❌ 参数映射可形成环(如 A → B → C → A),导致死锁
    • 🔧 改进:注册时验证 DAG(有向无环图)结构
  8. 超时和错误处理缺失

    • ❌ SkillStep 无超时设置,继承工具的全局超时
    • ❌ 步骤失败后是否继续?仅依赖回退逻辑
    • ❌ 无重试机制(如网络超时自动重试)
    • 🔧 改进:添加 retry_count, timeout_override 字段

11.10 改进建议

短期改进(无需破坏性变更)
  1. 增强文档生成

    • SkillEngine.get_skill_documentation() 中显示每个步骤的预期输入/输出
    • 添加技能依赖图(哪些技能可组合使用)
    • 生成 Mermaid 流程图可视化技能工作流
  2. 添加验证方法

    python 复制代码
    class SkillEngine:
        def validate_skill(self, skill: Skill, registry: ToolRegistry) -> list[str]:
            """验证技能定义的有效性,返回错误列表"""
            errors = []
            for step in skill.tool_sequence:
                if not registry.get(step.tool_name):
                    errors.append(f"Tool '{step.tool_name}' not registered")
                # 检查参数映射字段是否在工具输入模式中
                # 检查条件字段是否引用有效输出
            return errors
  3. 丰富元数据

    python 复制代码
    class Skill(BaseModel):
        tags: list[str] = []  # 如 ["ad", "kerberoasting", "cracking"]
        estimated_duration: int | None = None  # 预估执行时间(秒)
        required_privileges: list[str] = []  # 如 ["domain_user", "local_admin"]
        success_criteria: str | None = None  # 成功标准(用于自动化验证)
中期改进(向后兼容)
  1. 结构化条件

    python 复制代码
    class Condition(BaseModel):
        type: str  # "tool_output_contains", "output_count_gt", "previous_step_succeeded"
        tool_name: str | None = None  # 引用哪个工具的输出
        field: str | None = None  # 输出字段名
        operator: str | None = None  # "contains", ">", "==", "regex"
        value: Any = None
    
    class SkillStep(BaseModel):
        condition: str | Condition | None = None  # 支持两种格式
  2. 可编程回退

    python 复制代码
    class FallbackStrategy(BaseModel):
        trigger: str  # "on_failure", "on_timeout", "on_condition"
        steps: list[SkillStep]  # 回退步骤序列
        max_retries: int = 1
    
    class Skill(BaseModel):
        fallback: FallbackStrategy | None = None
  3. 结果聚合实现

    python 复制代码
    class SkillResult(BaseModel):
        success: bool
        steps: list[dict[str, Any]]  # 每步的输出
        aggregated_output: dict[str, Any]  # 聚合后的结果
        errors: list[str]
    
    class SkillExecutor:
        async def execute(self, skill: Skill, inputs: dict) -> SkillResult:
            # 实现确定性执行逻辑
            pass
长期改进(架构升级)
  1. 完整执行引擎

    • 实现 SkillExecutor 类,支持同步/异步执行
    • 提供事件钩子(on_step_start, on_step_complete, on_skill_complete
    • 支持暂停/恢复/取消操作
    • 集成追踪器(Tracer)记录执行轨迹
  2. 技能组合(Skill Composition)

    • 支持技能嵌套:一个技能可调用另一个技能作为步骤
    • 定义技能接口(输入/输出模式),实现类型安全组合
    • 示例:post_exploitation 技能组合 privesc + pivot + lateral_movement
  3. 条件 DSL

    • 设计领域特定语言,如:"output.tgs_hash_file.length > 0""previous_step.success and 'TGS' in output"
    • 实现条件解释器,支持变量、运算符、函数
    • 提供条件调试工具(可视化条件求值过程)
  4. 测试框架

    • 为技能添加单元测试支持
    • 模拟工具输出,验证条件评估和参数映射
    • 集成测试:运行技能并验证最终结果
    • 性能测试:测量技能执行时间和资源消耗

11.11 与其他层的集成

技能系统与 Excalibur 其他层的交互:
AgentController
SkillEngine
Skill
ToolRegistry
TypedSecurityTool
Claude Code CLI
Memory/State
Planner/EGATS
EventBus

集成点

  1. AgentController 调用 SkillEngine.get_skill() 获取技能定义,传递给 AI
  2. AI 解析技能,调用 ToolRegistry.get() 获取工具实例
  3. 工具 通过 build_command() 生成命令,由 Claude Code 执行
  4. SessionStore 记录技能执行历史,支持恢复
  5. Tracer 跟踪技能步骤的执行耗时和状态

当前缺失

  • AgentController 未直接使用 SkillEngine(仅作为知识库)
  • 技能执行结果未持久化到会话(仅 walkthrough 记录文本)
  • 无技能执行指标(成功率、平均时长、工具使用频率)

附录:相关文件索引

文件 路径 功能
TypedToolInterface excalibur/tools/base.py:117 工具接口定义
TypedSecurityTool excalibur/tools/base.py:146 工具基类
ToolRegistry excalibur/tools/registry.py:76 工具注册表(单例)
SkillEngine excalibur/tools/skill.py:67 技能组合引擎
Reconnaissance Tools excalibur/tools/categories/reconnaissance.py 侦察工具(8 个)
Web Exploitation Tools excalibur/tools/categories/web_exploitation.py Web 工具(8 个)
Network Exploitation Tools excalibur/tools/categories/network_exploitation.py 网络工具(8 个)
Credential Attack Tools excalibur/tools/categories/credential_attacks.py 凭证攻击工具(5 个)
Active Directory Tools excalibur/tools/categories/active_directory.py AD 工具(6 个)
Privilege Escalation Tools excalibur/tools/categories/privilege_escalation.py 权限提升工具(6 个)
相关推荐
yinghuoAI20262 小时前
电商视觉进入“无人区”:萤火AI如何用三把“手术刀”重构设计 workflow
设计模式·新媒体运营·产品运营·流量运营·用户运营·内容运营·设计规范
sg_knight3 小时前
设计模式实战:观察者模式(Observer)
python·观察者模式·设计模式
Yu_Lijing5 小时前
基于C++的《Head First设计模式》笔记——MVC模式
c++·笔记·设计模式
无籽西瓜a5 小时前
【西瓜带你学设计模式 | 第十期 - 外观模式】外观模式 —— 子系统封装实现、优缺点与适用场景
java·后端·设计模式·软件工程·外观模式
han_5 小时前
JavaScript设计模式(八):命令模式实现与应用
前端·javascript·设计模式
无籽西瓜a6 小时前
【西瓜带你学设计模式 | 第九期 - 代理模式】代理模式 —— 静态与动态代理实现、优缺点与适用场景
java·后端·设计模式·软件工程·代理模式
砍光二叉树6 小时前
【设计模式】行为型-访问者模式
设计模式·访问者模式
砍光二叉树6 小时前
【设计模式】行为型-状态模式
设计模式·状态模式
是糖糖啊1 天前
Google Stitch 用 AI 将想法秒变高保真 UI,并一键导出 Figma / 代码
设计模式·产品经理·产品