fix: 全仓审计加固与死代码清理,版本 1.1.87

- 回滚/备份:空 bak 改名 .bad 跳过;升级刷新 bak 补上单数 marker 补丁;统一原子写
- 补丁命中:optional 命中不符记软失败;#42 插入型替换加探针防重复插入
- Windows:进程枚举改用 | 分隔 + UTF-8,修复中文路径换包不杀旧进程;换包失败拉起原版
- 安全:asar 解包防越界;红队路径校验 realpath 防空 symlink;更新仅 https;报告回放去换行注入
- 提示词钩子:停用后 rewriteFn 返回原装配文本并清理 assemble guard;缓存签名纳入红队/策略/override
- 红队:listEngagements 默认不算统计;listVulns/报告支持 evidenceLimit
- 子代理名额占位即时生效并回退;--apply 有失败项退出码 1
- 清理:删除 lib/mnemon-settings.js 及 13 处死代码/未使用 import;移除 test 目录与 test 脚本
This commit is contained in:
叫我小杨同学 committed 2026-11-01 21:47:03 +08:00
1 parent b46c952584
commit 1a8195b4d4
48 files changed
+890 -1652

No files matched your search

+81 -36
View File
@@ -8,12 +8,12 @@
import { DatabaseSync } from 'node:sqlite'
import { connect as tcpConnect } from 'node:net'
import { createHash } from 'node:crypto'
import { homedir } from 'node:os'
import { homedir, tmpdir } from 'node:os'
import {
mkdirSync, readFileSync, writeFileSync, readdirSync, existsSync, rmSync, statSync,
copyFileSync,
} from 'node:fs'
import { join, basename, isAbsolute } from 'node:path'
import { join, basename, isAbsolute, resolve } from 'node:path'
/* ── 拆分出去的模块(对外 API 不变:下面把它们原样再导出一次)──────────────
动机是"一个文件 5600 行、改表结构要翻过 500 行计分逻辑":
@@ -158,6 +158,16 @@ const SCOPE_SQL = `CASE
THEN 'internal' ELSE 'external' END`
/**
* 证据导入的**源**路径:相对路径按 root 解析,绝对路径必须落在 root 或系统临时目录内。
* 只校验写目标是不够的 —— 接口传一个绝对路径就能把本机任意文件复制进证据目录再读回。
*/
function assertSourcePath(root, raw) {
const text = String(raw || '').trim()
const abs = isAbsolute(text) ? resolve(text) : resolve(root, text)
return assertPathWithin(abs, [root, tmpdir()])
}
/* ------------------------------------------------------------------ 元数据 */
function readMeta(path) {
@@ -940,7 +950,8 @@ export class RedteamStore {
}
/* ---------- 路径 ---------- */
dirOf(id) { return join(this.engagementsDir, id) }
/* id 来自请求体(dispatch 的 req.engagement),拼路径前必须挡住 `..` 出去。 */
dirOf(id) { return assertPathWithin(join(this.engagementsDir, id), [this.engagementsDir]) }
metaPathOf(id) { return join(this.dirOf(id), 'engagement.yaml') }
dbPathOf(id) { return join(this.dirOf(id), 'assets.db') }
promptsDirOf(id) { return join(this.dirOf(id), 'agents') }
@@ -980,16 +991,21 @@ export class RedteamStore {
}
/* ---------- 靶标生命周期 ---------- */
listEngagements() {
listEngagements(options = {}) {
mkdirSync(this.engagementsDir, { recursive: true })
const withStats = options.stats === true
const out = []
for (const entry of readdirSync(this.engagementsDir, { withFileTypes: true })) {
if (!entry.isDirectory()) continue
const meta = readMeta(this.metaPathOf(entry.name)) || {}
let stats = null
try {
if (existsSync(this.dbPathOf(entry.name))) stats = this.stats(entry.name)
} catch { /* 库损坏时仍列出靶标 */ }
/* 只有面板 bootstrap 要统计。工具调用解析靶标名每次都开库 + 13 条 COUNT,
靶标一多就把每个工具步拖慢;默认不带。 */
if (withStats) {
try {
if (existsSync(this.dbPathOf(entry.name))) stats = this.stats(entry.name)
} catch { /* 库损坏时仍列出靶标 */ }
}
out.push({
id: entry.name, name: meta.target_name || entry.name,
scope: meta.scope_cidrs || [], status: meta.status || 'active',
@@ -1503,6 +1519,7 @@ export class RedteamStore {
const ids = doomed.map((r) => r.id)
const ph = ids.map(() => '?').join(',')
const hits = db.prepare(`SELECT * FROM score_hit WHERE point_id IN (${ph})`).all(...ids)
let archived = hits.length === 0
if (hits.length > 0) {
/* 存档:放靶标目录的 runs/ 下,与其它证据同处一地 */
try {
@@ -1515,8 +1532,11 @@ export class RedteamStore {
reason: '按《突破入侵类得分规则(合并版)》重构:旧得分项整套作废',
points: doomed, hits,
}, null, 2), 'utf8')
} catch { /* 存档失败不阻断清理,但要照实记账 */ }
archived = true
} catch { /* 存档失败:下面不删,下次启动再试(删了就永久丢证据) */ }
}
/* 没存下来就不删:宁可旧得分项多留一轮,也不能静默丢证据。 */
if (!archived) throw new Error('legacy score archive failed; purge skipped')
db.prepare(`DELETE FROM score_hit WHERE point_id IN (${ph})`).run(...ids)
db.prepare(`DELETE FROM score_point WHERE id IN (${ph})`).run(...ids)
purgedPoints = doomed.length
@@ -1884,8 +1904,15 @@ export class RedteamStore {
+ '删掉会让面板缺一条规则、报告少一类成果(下次启动还会自动补回来)。'
+ '要让它不参与计分,请改用「停用」。')
}
db.prepare('DELETE FROM score_hit WHERE point_id = ?').run(pid)
db.prepare('DELETE FROM score_point WHERE id = ?').run(pid)
db.exec('BEGIN')
try {
db.prepare('DELETE FROM score_hit WHERE point_id = ?').run(pid)
db.prepare('DELETE FROM score_point WHERE id = ?').run(pid)
db.exec('COMMIT')
} catch (error) {
db.exec('ROLLBACK')
throw error
}
return { deleted: pid }
}
@@ -2184,15 +2211,28 @@ export class RedteamStore {
FROM vuln v LEFT JOIN asset a ON a.id = v.asset_id ${clause}
ORDER BY CASE v.severity WHEN 'critical' THEN 0 WHEN 'high' THEN 1 WHEN 'medium' THEN 2 WHEN 'low' THEN 3 ELSE 4 END,
v.id DESC LIMIT ?`).all(...args, limit)
/* 详情里要直接展示原始请求/响应,这里一并带上(请求体可能很大,做长度保护) */
const eviStmt = db.prepare(`SELECT id, label, method, url, status, request, response, note, captured_by, captured_at
FROM http_evidence WHERE vuln_id = ? ORDER BY id`)
const clipped = (t) => (t === null || t === undefined ? null : (String(t).length > 60000 ? String(t).slice(0, 60000) + "\n… (truncated)" : String(t)))
for (const item of items) {
item.http_evidence = eviStmt.all(item.id).map((e) => Object.assign({}, e, {
request: clipped(e.request), response: clipped(e.response),
}))
/* 详情里要直接展示原始请求/响应,这里一并带上(请求体可能很大,做长度保护)。
一次 IN 取完再分组,避免每条漏洞各查一次(limit=200 时就是 200 次查询)。 */
/* 列表要展示证据是否存在与摘要,但不必把完整报文都端上来:全文走 httpEvidence /
报告链路按需取。200 条 × 数条证据 × 60k 字符会把面板主线程卡死。
报告生成(store-core report/reportTargets)显式传 evidenceLimit:60000 拿全文。 */
const evidenceLimit = Math.min(Number(f.evidenceLimit) || 8000, 60000)
const clipped = (t) => (t === null || t === undefined ? null : (String(t).length > evidenceLimit ? String(t).slice(0, evidenceLimit) + "\n… (truncated)" : String(t)))
const eviByVuln = new Map()
const ids = items.map((it) => Number(it.id)).filter((n) => Number.isInteger(n))
if (ids.length > 0) {
const ph = ids.map(() => '?').join(',')
const rows = db.prepare(`SELECT id, vuln_id, label, method, url, status, request, response, note, captured_by, captured_at
FROM http_evidence WHERE vuln_id IN (${ph}) ORDER BY id`).all(...ids)
for (const e of rows) {
const key = Number(e.vuln_id)
if (!eviByVuln.has(key)) eviByVuln.set(key, [])
eviByVuln.get(key).push(Object.assign({}, e, {
request: clipped(e.request), response: clipped(e.response),
}))
}
}
for (const item of items) item.http_evidence = eviByVuln.get(Number(item.id)) || []
return { total, items }
}
@@ -4198,12 +4238,16 @@ export class RedteamStore {
return { id: stepId, seq: seq, stage_code: stageCode, point_id: pointId, hit: hit, score_hint: scoreHint, stage_hint: stageWarning }
}
listChain(id) {
return this.db(id).prepare(`SELECT s.*, a.ip AS asset_ip, v.title AS vuln_title, v.severity AS vuln_severity, v.cve AS vuln_cve
/* limit 默认 5000 防止超长靶标把整张表一次读进内存;导出/报告传 0 表示不截断。 */
listChain(id, limit = 5000) {
const cap = Number(limit) > 0 ? Math.floor(Number(limit)) : 0
const sql = `SELECT s.*, a.ip AS asset_ip, v.title AS vuln_title, v.severity AS vuln_severity, v.cve AS vuln_cve
FROM attack_step s
LEFT JOIN asset a ON a.id = s.asset_id
LEFT JOIN vuln v ON v.id = s.vuln_id
ORDER BY s.seq, s.id`).all()
ORDER BY s.seq, s.id` + (cap > 0 ? ' LIMIT ?' : '')
const stmt = this.db(id).prepare(sql)
return cap > 0 ? stmt.all(cap) : stmt.all()
}
/* ---------- 攻击文件(只收录实际生效的脚本/POC/EXP) ---------- */
@@ -4248,7 +4292,7 @@ export class RedteamStore {
if (typeof shot.data_base64 === 'string' && shot.data_base64.trim() !== '') {
buf = Buffer.from(shot.data_base64.replace(/^data:[^,]+,/, ''), 'base64')
} else if (typeof shot.path === 'string' && shot.path.trim() !== '') {
const src = isAbsolute(shot.path) ? shot.path : join(this.dirOf(id), shot.path)
const src = assertSourcePath(this.dirOf(id), shot.path)
if (!existsSync(src)) throw new Error('shot source not found: ' + shot.path)
buf = readFileSync(src)
} else {
@@ -4424,7 +4468,7 @@ export class RedteamStore {
if (typeof f.content === 'string' && f.content.length > 0) {
writeFileSync(filePath, f.content, 'utf8')
} else if (typeof f.path === 'string' && f.path.length > 0) {
const src = isAbsolute(f.path) ? f.path : join(this.dirOf(id), f.path)
const src = assertSourcePath(this.dirOf(id), f.path)
if (!existsSync(src)) throw new Error('source path not found: ' + f.path)
copyFileSync(src, filePath)
} else {
@@ -4619,7 +4663,7 @@ export class RedteamStore {
/* 正文:优先用传入 content,其次从 path 读;两者都没有则只登记元数据 */
let content = typeof p.content === 'string' ? p.content : ''
if (content === '' && typeof p.path === 'string' && p.path.length > 0) {
const src = isAbsolute(p.path) ? p.path : join(this.pocsDirOf(), p.path)
const src = assertSourcePath(this.pocsDirOf(), p.path)
if (!existsSync(src)) throw new Error('poc content or existing path required: ' + p.path)
content = readFileSync(src, 'utf8')
}
@@ -4871,13 +4915,13 @@ export class RedteamStore {
reportTargets(id, options = {}) {
const meta = readMeta(this.metaPathOf(id)) || {}
const includeAll = options.all === true
const allVulns = this.listVulns(id, { limit: 2000 }).items
const allVulns = this.listVulns(id, { limit: 2000, evidenceLimit: 60000 }).items
const severityOrder = { critical: 0, high: 1, medium: 2, low: 3, info: 4 }
const isResult = (v) => v.status === 'confirmed' || v.status === 'exploited'
const isReal = (v) => v.severity === 'critical' || v.severity === 'high' || v.severity === 'medium'
const vulns = (includeAll ? allVulns : allVulns.filter((v) => isResult(v) && isReal(v)))
.slice().sort((a, b) => (severityOrder[a.severity] ?? 9) - (severityOrder[b.severity] ?? 9))
const chain = this.listChain(id)
const chain = this.listChain(id, 0)
const creds = this.listCredentials(id, {})
const access = this.listAccess(id, {})
const files = this.listAttackFiles(id, {})
@@ -5004,10 +5048,10 @@ export class RedteamStore {
report(id, options = {}) {
const meta = readMeta(this.metaPathOf(id)) || {}
const includeAll = options.all === true
const chain = this.listChain(id)
const chain = this.listChain(id, 0)
const creds = this.listCredentials(id, {})
const access = this.listAccess(id, {})
const allVulns = this.listVulns(id, { limit: 2000 }).items
const allVulns = this.listVulns(id, { limit: 2000, evidenceLimit: 60000 }).items
const severityOrder = { critical: 0, high: 1, medium: 2, low: 3, info: 4 }
const isResult = (v) => v.status === 'confirmed' || v.status === 'exploited'
const isReal = (v) => v.severity === 'critical' || v.severity === 'high' || v.severity === 'medium'
@@ -5186,16 +5230,17 @@ export class RedteamStore {
const db = this.db(id)
const counts = { segments: 0, assets: 0, ports: 0, services: 0, fingerprints: 0, names: 0, edges: 0 }
let runId = null
if (bundle.scan) {
const r = db.prepare(`INSERT INTO scan_run(agent_session_id, tool, argv, started_at, status)
VALUES(?,?,?,?,'completed')`).run(
bundle.scan.agent_session_id ?? null, bundle.scan.tool ?? null,
bundle.scan.argv ? JSON.stringify(bundle.scan.argv) : null, nowIso(),
)
runId = Number(r.lastInsertRowid)
}
/* BEGIN 必须在写 scan_run 之前:它在事务外的话,导入中途失败回滚会留下孤儿扫描记录。 */
db.exec('BEGIN')
try {
if (bundle.scan) {
const r = db.prepare(`INSERT INTO scan_run(agent_session_id, tool, argv, started_at, status)
VALUES(?,?,?,?,'completed')`).run(
bundle.scan.agent_session_id ?? null, bundle.scan.tool ?? null,
bundle.scan.argv ? JSON.stringify(bundle.scan.argv) : null, nowIso(),
)
runId = Number(r.lastInsertRowid)
}
for (const seg of bundle.segments || []) { this.#upsertSegment(db, seg); counts.segments++ }
for (const a of bundle.assets || []) {
const provenance = a.provenance || 'active'