mirror of
https://github.com/YuJunZhiXue/dsh-purge.git
synced 2026-11-28 11:00:22 +08:00
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:
1 parent
71d3a55884
commit
f806b048ac
48 files changed
+890
-1652
No files matched your search
@@ -0,0 +1,28 @@
|
||||
import { closeSync, fsyncSync, openSync, renameSync, unlinkSync, writeSync } from 'node:fs'
|
||||
|
||||
/**
|
||||
* 先写临时文件、fsync、再 rename。
|
||||
* 直接 writeFileSync 覆盖原文件时,写到一半崩溃会留下半截 JSON;读侧又会把解析错
|
||||
* 吞成默认值,用户的设置就无声消失了。
|
||||
*/
|
||||
export function atomicWriteFileSync(file, text) {
|
||||
const tmp = file + '.tmp-' + process.pid + '-' + Date.now().toString(36)
|
||||
const fd = openSync(tmp, 'w')
|
||||
try {
|
||||
writeSync(fd, text)
|
||||
try { fsyncSync(fd) } catch { /* 部分文件系统不支持,忽略 */ }
|
||||
} catch (error) {
|
||||
try { closeSync(fd) } catch { /* ignore */ }
|
||||
try { unlinkSync(tmp) } catch { /* ignore */ }
|
||||
throw error
|
||||
}
|
||||
try {
|
||||
closeSync(fd)
|
||||
} catch { /* ignore */ }
|
||||
try {
|
||||
renameSync(tmp, file)
|
||||
} catch (error) {
|
||||
try { unlinkSync(tmp) } catch { /* ignore */ }
|
||||
throw error
|
||||
}
|
||||
}
|
||||
+101
-22
@@ -664,11 +664,34 @@ body[data-ds-dark-theme] .rt-scope-testing,.dshp-dock[data-theme="dusk"] .rt-sco
|
||||
try { return String(window.location.hash || '') === '#redteam-full' } catch { return false }
|
||||
}
|
||||
|
||||
const api = (req) => fetch('/redteam/api', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(req),
|
||||
}).then((res) => res.json())
|
||||
/* 与宿主半侧其它接口同一套约定:有超时、判 res.ok、非 JSON 响应给出可读错误。
|
||||
直接 res.json() 时后端回 HTML/空体只会抛 "Unexpected token '<'",状态码也丢了。 */
|
||||
const API_TIMEOUT_MS = 120000
|
||||
const api = (req) => {
|
||||
const ctrl = new AbortController()
|
||||
const timer = setTimeout(() => ctrl.abort(), API_TIMEOUT_MS)
|
||||
return fetch('/redteam/api', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(req),
|
||||
signal: ctrl.signal,
|
||||
})
|
||||
.then((res) => res.text().then((text) => {
|
||||
let data = null
|
||||
try { data = text ? JSON.parse(text) : null } catch { throw new Error(res.status + ' non-json: ' + text.slice(0, 120)) }
|
||||
if (!res.ok) throw new Error((data && data.error) || (res.status + ' ' + res.statusText))
|
||||
return data
|
||||
}))
|
||||
.finally(() => clearTimeout(timer))
|
||||
}
|
||||
/* 每次加载取号,异步回来先比号:切靶标后旧响应直接丢弃,别盖掉新靶标的数据。 */
|
||||
const useLoadSeq = () => {
|
||||
const ref = React.useRef(0)
|
||||
return {
|
||||
take: () => ++ref.current,
|
||||
live: (my) => my === ref.current,
|
||||
}
|
||||
}
|
||||
|
||||
let ui = { open: true, tab: 'assets' }
|
||||
const subs = new Set()
|
||||
@@ -708,15 +731,30 @@ body[data-ds-dark-theme] .rt-scope-testing,.dshp-dock[data-theme="dusk"] .rt-sco
|
||||
'vuln-scan': '漏洞发现', exploit: '漏洞利用', internal: '内网渗透',
|
||||
}
|
||||
|
||||
const fmt = (s) => (s ? String(s).replace('T', ' ').slice(0, 16) : '—')
|
||||
/* 服务端时间一律是 toISOString()(UTC),直接截串会让东八区早 8 小时。 */
|
||||
const pad2 = (n) => String(n).padStart(2, '0')
|
||||
const asLocal = (s) => {
|
||||
const d = new Date(s)
|
||||
return Number.isNaN(d.getTime()) ? null : d
|
||||
}
|
||||
const fmt = (s) => {
|
||||
if (!s) return '—'
|
||||
const d = asLocal(s)
|
||||
if (d === null) return String(s).replace('T', ' ').slice(0, 16)
|
||||
return d.getFullYear() + '-' + pad2(d.getMonth() + 1) + '-' + pad2(d.getDate())
|
||||
+ ' ' + pad2(d.getHours()) + ':' + pad2(d.getMinutes())
|
||||
}
|
||||
const shotCache = new Map()
|
||||
const shotLoading = new Map()
|
||||
/* base64 常驻内存:只留最近 200 张,避免跨靶标无限累积。 */
|
||||
const SHOT_CACHE_LIMIT = 200
|
||||
const shotSrc = (eng, id) => shotCache.get(eng + ':' + id) || null
|
||||
const loadShot = (eng, id) => {
|
||||
const key = eng + ':' + id
|
||||
if (shotCache.has(key) || shotLoading.has(key)) return
|
||||
const p = api({ op: 'shotData', engagement: eng, id: id }).then((r) => {
|
||||
shotCache.set(key, r && r.base64 ? 'data:' + (r.mime || 'image/png') + ';base64,' + r.base64 : '')
|
||||
while (shotCache.size > SHOT_CACHE_LIMIT) shotCache.delete(shotCache.keys().next().value)
|
||||
shotLoading.delete(key)
|
||||
const snap = Object.assign({}, ui)
|
||||
for (const f of Array.from(subs)) {
|
||||
@@ -729,7 +767,8 @@ body[data-ds-dark-theme] .rt-scope-testing,.dshp-dock[data-theme="dusk"] .rt-sco
|
||||
const ShotImage = ({ eng, shot, height }) => {
|
||||
const [zoom, setZoom] = React.useState(false)
|
||||
const src = shotSrc(eng, shot.id)
|
||||
if (src === null) { loadShot(eng, shot.id); }
|
||||
/* 拉图放在 effect 里:render 期间发请求 + 写外部 store 会让同一帧重复触发。 */
|
||||
React.useEffect(() => { if (src === null) loadShot(eng, shot.id) }, [eng, shot.id, src])
|
||||
const card = shot.kind === 'card'
|
||||
return h('div', { className: 'rt-shot' },
|
||||
src === null
|
||||
@@ -766,8 +805,14 @@ body[data-ds-dark-theme] .rt-scope-testing,.dshp-dock[data-theme="dusk"] .rt-sco
|
||||
}
|
||||
/** 发现时间在列表里只留「月-日 时:分」:整行宽度紧张,完整时间进悬浮提示 */
|
||||
const fmtShort = (s) => {
|
||||
const t = String(s || '').replace('T', ' ')
|
||||
return t.length >= 16 ? t.slice(5, 16) : (t || '—')
|
||||
if (!s) return '—'
|
||||
const d = asLocal(s)
|
||||
if (d === null) {
|
||||
const t = String(s).replace('T', ' ')
|
||||
return t.length >= 16 ? t.slice(5, 16) : t
|
||||
}
|
||||
return pad2(d.getMonth() + 1) + '-' + pad2(d.getDate())
|
||||
+ ' ' + pad2(d.getHours()) + ':' + pad2(d.getMinutes())
|
||||
}
|
||||
const provLabel = (p) => (p === 'passive' ? '被动' : p === 'active' ? '主动' : '未知')
|
||||
|
||||
@@ -1258,12 +1303,17 @@ body[data-ds-dark-theme] .rt-scope-testing,.dshp-dock[data-theme="dusk"] .rt-sco
|
||||
const [data, setData] = React.useState(null)
|
||||
const [err, setErr] = React.useState(null)
|
||||
const [day, setDay] = React.useState('')
|
||||
const seq = useLoadSeq()
|
||||
React.useEffect(() => {
|
||||
if (!eng) return
|
||||
const my = seq.take()
|
||||
setData(null)
|
||||
api({ op: 'discoveryTimeline', engagement: eng, limit: 200 })
|
||||
.then((r) => { if (!r || r.ok === false) setErr((r && r.error) || '加载失败'); else { setErr(null); setData(r) } },
|
||||
(e) => setErr(String((e && e.message) || e)))
|
||||
.then((r) => {
|
||||
if (!seq.live(my)) return
|
||||
if (!r || r.ok === false) setErr((r && r.error) || '加载失败')
|
||||
else { setErr(null); setData(r) }
|
||||
}, (e) => { if (seq.live(my)) setErr(String((e && e.message) || e)) })
|
||||
}, [eng, refreshKey])
|
||||
if (err) return h('div', { className: 'rt-pane' }, h('div', { className: 'rt-err' }, err))
|
||||
if (!data) return h('div', { className: 'rt-empty' }, '加载中…')
|
||||
@@ -1314,14 +1364,17 @@ body[data-ds-dark-theme] .rt-scope-testing,.dshp-dock[data-theme="dusk"] .rt-sco
|
||||
const [msg, setMsg] = React.useState(null)
|
||||
const [busy, setBusy] = React.useState(false)
|
||||
|
||||
const seq = useLoadSeq()
|
||||
React.useEffect(() => {
|
||||
/* 无靶标也允许:服务端回内置默认,不再报 engagement required */
|
||||
const my = seq.take()
|
||||
api(eng ? { op: 'prompts', engagement: eng } : { op: 'prompts' }).then((r) => {
|
||||
if (!seq.live(my)) return
|
||||
if (!r || r.ok === false) { setMsg({ err: (r && r.error) || '读取失败' }); return }
|
||||
setRoles(r.roles || [])
|
||||
if (r.roles && r.roles.length) setActive((cur) => cur || r.roles[0].role)
|
||||
if (r.builtin) setMsg({ ok: '当前为内置默认提示词(创建靶标后可按靶标保存修改)' })
|
||||
}, (e) => setMsg({ err: String((e && e.message) || e) }))
|
||||
}, (e) => { if (seq.live(my)) setMsg({ err: String((e && e.message) || e) }) })
|
||||
}, [eng, refreshKey])
|
||||
|
||||
React.useEffect(() => {
|
||||
@@ -1897,7 +1950,8 @@ body[data-ds-dark-theme] .rt-scope-testing,.dshp-dock[data-theme="dusk"] .rt-sco
|
||||
|
||||
return h('div', { className: 'rt-main' }, toolbar, conclusion,
|
||||
h('div', { className: 'rt-subtabs' },
|
||||
subTabBtn('vulns', '漏洞', state.total || 0),
|
||||
/* 用实际渲染条数:total 是服务端 COUNT(*),列表被 limit 截断时两者对不上。 */
|
||||
subTabBtn('vulns', '漏洞', (state.items || []).length),
|
||||
subTabBtn('files', '攻击文件', allFiles.length),
|
||||
subTabBtn('creds', '凭据', creds.length),
|
||||
subTabBtn('access', '访问会话', accesses.length),
|
||||
@@ -1951,14 +2005,17 @@ body[data-ds-dark-theme] .rt-scope-testing,.dshp-dock[data-theme="dusk"] .rt-sco
|
||||
const [view, setView] = React.useState('A')
|
||||
const [openId, setOpenId] = React.useState(null)
|
||||
|
||||
const seq = useLoadSeq()
|
||||
const load = () => {
|
||||
if (!eng) return
|
||||
const my = seq.take()
|
||||
setLoading(true)
|
||||
api({ op: 'scoreChain', engagement: eng }).then((r) => {
|
||||
if (!seq.live(my)) return
|
||||
setLoading(false)
|
||||
if (!r || r.ok === false) { setErr((r && r.error) || '读取失败'); return }
|
||||
setErr(null); setData(r)
|
||||
}, (e) => { setLoading(false); setErr(String((e && e.message) || e)) })
|
||||
}, (e) => { if (!seq.live(my)) return; setLoading(false); setErr(String((e && e.message) || e)) })
|
||||
}
|
||||
React.useEffect(load, [eng, refreshKey])
|
||||
|
||||
@@ -2157,21 +2214,28 @@ body[data-ds-dark-theme] .rt-scope-testing,.dshp-dock[data-theme="dusk"] .rt-sco
|
||||
/* 报告按阶段折叠:默认全开,折叠状态按靶标记住(阶段多时便于逐段交付) */
|
||||
const collapse = useCollapse('report:' + eng)
|
||||
|
||||
const seq = useLoadSeq()
|
||||
const load = () => {
|
||||
if (!eng) return
|
||||
const my = seq.take()
|
||||
setBusy(true); setMsg(null)
|
||||
api({ op: 'scoreReport', engagement: eng }).then((r) => {
|
||||
if (!seq.live(my)) return
|
||||
if (!r || r.ok === false) { setBusy(false); setErr((r && r.error) || '生成失败'); return }
|
||||
/* 老 host 只给平铺条目、不给阶段分组(或阶段行缺失):自己按攻击链分组,
|
||||
否则报告页会误报"还没有可交付的成果"。分组数据取自 scoreChain。 */
|
||||
if ((!r.stages || r.stages.length === 0) && (r.items || []).length > 0) {
|
||||
api({ op: 'scoreChain', engagement: eng }).then((c) => {
|
||||
if (!seq.live(my)) return
|
||||
setBusy(false); setErr(null); setData(Object.assign({}, r, { stages: groupByStage(r.items, c) }))
|
||||
}, () => { setBusy(false); setErr(null); setData(r) })
|
||||
}, () => {
|
||||
if (!seq.live(my)) return
|
||||
setBusy(false); setErr(null); setData(r)
|
||||
})
|
||||
return
|
||||
}
|
||||
setBusy(false); setErr(null); setData(r)
|
||||
}, (e) => { setBusy(false); setErr(String((e && e.message) || e)) })
|
||||
}, (e) => { if (!seq.live(my)) return; setBusy(false); setErr(String((e && e.message) || e)) })
|
||||
}
|
||||
React.useEffect(load, [eng, refreshKey])
|
||||
|
||||
@@ -2379,15 +2443,18 @@ body[data-ds-dark-theme] .rt-scope-testing,.dshp-dock[data-theme="dusk"] .rt-sco
|
||||
const collapse = useCollapse('files:' + eng)
|
||||
const [detail, setDetail] = React.useState(null)
|
||||
|
||||
const seq = useLoadSeq()
|
||||
const load = () => {
|
||||
if (!eng) return
|
||||
const my = seq.take()
|
||||
setBusy(true)
|
||||
api({ op: 'attackFiles', engagement: eng }).then((r) => {
|
||||
if (!seq.live(my)) return
|
||||
setBusy(false)
|
||||
if (!r || r.ok === false) { setErr((r && r.error) || '读取失败'); return }
|
||||
setErr(null)
|
||||
setFolders(r.items || [])
|
||||
}, (e) => { setBusy(false); setErr(String((e && e.message) || e)) })
|
||||
}, (e) => { if (!seq.live(my)) return; setBusy(false); setErr(String((e && e.message) || e)) })
|
||||
}
|
||||
React.useEffect(load, [eng, refreshKey])
|
||||
|
||||
@@ -2936,15 +3003,18 @@ body[data-ds-dark-theme] .rt-scope-testing,.dshp-dock[data-theme="dusk"] .rt-sco
|
||||
const [form, setForm] = React.useState(null)
|
||||
const [msg, setMsg] = React.useState(null)
|
||||
|
||||
const seq = useLoadSeq()
|
||||
const load = () => {
|
||||
if (!eng) return
|
||||
const my = seq.take()
|
||||
setBusy(true)
|
||||
api({ op: 'scores', engagement: eng }).then((r) => {
|
||||
if (!seq.live(my)) return
|
||||
setBusy(false)
|
||||
if (!r || r.ok === false) { setErr((r && r.error) || '读取失败'); return }
|
||||
setErr(null)
|
||||
setData(r)
|
||||
}, (e) => { setBusy(false); setErr(String((e && e.message) || e)) })
|
||||
}, (e) => { if (!seq.live(my)) return; setBusy(false); setErr(String((e && e.message) || e)) })
|
||||
}
|
||||
React.useEffect(load, [eng, refreshKey])
|
||||
|
||||
@@ -2993,7 +3063,7 @@ body[data-ds-dark-theme] .rt-scope-testing,.dshp-dock[data-theme="dusk"] .rt-sco
|
||||
}, (e) => { setBusy(false); setMsg({ err: String((e && e.message) || e) }) })
|
||||
}
|
||||
|
||||
const summary = (data && data.summary) || { achievedPoints: 0, pointCount: 0, hitPointCount: 0, hitCount: 0, selfCreatedHits: 0, serviceCappedHits: 0 }
|
||||
const summary = (data && data.summary) || { achievedPoints: 0, pointCount: 0, hitPointCount: 0, hitCount: 0, countedHits: 0, selfCreatedHits: 0, serviceCappedHits: 0 }
|
||||
const items = (data && data.items) || []
|
||||
|
||||
/* 按合并版的 8 个类别分组渲染(后端 ruleGroups 已排好序、组内按分值升序)。
|
||||
@@ -3308,7 +3378,9 @@ body[data-ds-dark-theme] .rt-scope-testing,.dshp-dock[data-theme="dusk"] .rt-sco
|
||||
}, (e) => { if (my === seq.current) setErr(String((e && e.message) || e)) })
|
||||
.finally(() => { if (my === seq.current) inflight.current = false })
|
||||
}
|
||||
React.useEffect(() => { seq.current += 1; load() }, [eng, refreshKey])
|
||||
/* 切靶标/刷新时把在途标记复位:旧请求的 finally 因序号不符不会清,
|
||||
不复位的话这里会永久早退,5 秒轮询也全空转。 */
|
||||
React.useEffect(() => { seq.current += 1; inflight.current = false; load() }, [eng, refreshKey])
|
||||
React.useEffect(() => {
|
||||
if (!eng || !auto) return undefined
|
||||
const timer = setInterval(load, 5000)
|
||||
@@ -3430,13 +3502,16 @@ body[data-ds-dark-theme] .rt-scope-testing,.dshp-dock[data-theme="dusk"] .rt-sco
|
||||
const [msg, setMsg] = React.useState(null)
|
||||
const [copied, setCopied] = React.useState(null)
|
||||
|
||||
const seq = useLoadSeq()
|
||||
const load = () => {
|
||||
if (!eng) return
|
||||
const my = seq.take()
|
||||
api({ op: 'sessions', engagement: eng }).then((r) => {
|
||||
if (!seq.live(my)) return
|
||||
if (!r || r.ok === false) { setErr((r && r.error) || '读取失败'); return }
|
||||
setErr(null)
|
||||
setData(r)
|
||||
}, (e) => setErr(String((e && e.message) || e)))
|
||||
}, (e) => { if (seq.live(my)) setErr(String((e && e.message) || e)) })
|
||||
}
|
||||
React.useEffect(load, [eng, refreshKey])
|
||||
|
||||
@@ -3671,16 +3746,20 @@ body[data-ds-dark-theme] .rt-scope-testing,.dshp-dock[data-theme="dusk"] .rt-sco
|
||||
const [concurrency, setConcurrency] = React.useState(null)
|
||||
const [busy, setBusy] = React.useState(false)
|
||||
|
||||
const seq = useLoadSeq()
|
||||
const load = () => {
|
||||
const my = seq.take()
|
||||
setBusy(true)
|
||||
api({ op: eng ? 'prompts' : 'bootstrap', engagement: eng || undefined }).then((r) => {
|
||||
if (!seq.live(my)) return
|
||||
setBusy(false)
|
||||
if (!r || r.ok === false) { setErr((r && r.error) || '读取失败'); return }
|
||||
setErr(null)
|
||||
if (r.roles) setRoles(r.roles)
|
||||
}, (e) => { setBusy(false); setErr(String((e && e.message) || e)) })
|
||||
}, (e) => { if (!seq.live(my)) return; setBusy(false); setErr(String((e && e.message) || e)) })
|
||||
/* 并发名额按"当前跑着的子智能体"算;host 侧读 subagents 注册表 */
|
||||
api({ op: 'agentsStatus' }).then((r) => {
|
||||
if (!seq.live(my)) return
|
||||
if (r && r.ok !== false) setConcurrency(r)
|
||||
}, () => {})
|
||||
}
|
||||
|
||||
+10
-2
@@ -8,7 +8,7 @@
|
||||
*/
|
||||
import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
|
||||
import { homedir } from 'node:os'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { readPresetDefinition } from './preset-composition.js'
|
||||
import { scheduleClearOwnedSelectedDefault } from '../preset-default.js'
|
||||
@@ -557,7 +557,15 @@ export function apply(ctx) {
|
||||
Promise.resolve()
|
||||
.then(async () => {
|
||||
await undeclare()
|
||||
releaseDeclared = await registry.register(definition)
|
||||
const release = await registry.register(definition)
|
||||
/* 注册是异步的:cleanup 已经跑过(closed=true)时,这里再赋值就会把预设
|
||||
永远留在宿主里——没人再来释放它。当场撤掉。 */
|
||||
if (closed) {
|
||||
try { await release() } catch { /* 已随宿主卸载 */ }
|
||||
writeStatus({ ok: false, phase: 'closed-during-register' })
|
||||
return
|
||||
}
|
||||
releaseDeclared = release
|
||||
let broken = null
|
||||
try {
|
||||
const row = (await registry.list()).find((p) => p.id === REDTEAM_PRESET_ID)
|
||||
|
||||
@@ -9,9 +9,10 @@
|
||||
*
|
||||
* 借鉴 Z3r0:系统配置集中、可在 UI 里改(FOFA / 路径类),而不是只靠 shell 引导。
|
||||
*/
|
||||
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, statSync, writeFileSync } from 'node:fs'
|
||||
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, statSync } from "node:fs"
|
||||
import { homedir, platform as osPlatform } from 'node:os'
|
||||
import { delimiter, isAbsolute, join, resolve, sep } from 'node:path'
|
||||
import { atomicWriteFileSync } from './atomic-write.js'
|
||||
|
||||
/** 配置文件路径。 */
|
||||
export function configPathOf(root) {
|
||||
@@ -145,7 +146,7 @@ export function savePlatformConfig(patch, root) {
|
||||
else next.tools[t.id] = String(next.tools[t.id]).trim()
|
||||
}
|
||||
const file = configPathOf(dir)
|
||||
writeFileSync(file, JSON.stringify(next, null, 2), 'utf8')
|
||||
atomicWriteFileSync(file, JSON.stringify(next, null, 2))
|
||||
return loadPlatformConfig(dir)
|
||||
}
|
||||
|
||||
|
||||
@@ -121,11 +121,13 @@ function buildHttpRequest(options = {}) {
|
||||
: (target.path || '/')
|
||||
const method = String(options.method || (options.data === undefined || options.data === null ? 'GET' : 'POST')).toUpperCase()
|
||||
const lines = [method + ' ' + path + ' HTTP/1.1', 'Host: ' + hostHeader]
|
||||
const headers = Array.isArray(options.headers) ? options.headers.slice() : []
|
||||
const headers = (Array.isArray(options.headers) ? options.headers.slice() : [])
|
||||
/* 头值里的换行会把一条报文拆成两条:Cookie 尤其常见(多行 cookie 导出)。 */
|
||||
.map((h) => String(h).replace(/[\r\n]+/g, ' '))
|
||||
const hasHeader = (name) => headers.some((h) => String(h).toLowerCase().startsWith(name.toLowerCase() + ':'))
|
||||
if (!hasHeader('User-Agent')) headers.push('User-Agent: Mozilla/5.0')
|
||||
if (!hasHeader('Accept')) headers.push('Accept: */*')
|
||||
if (options.cookie && !hasHeader('Cookie')) headers.push('Cookie: ' + options.cookie)
|
||||
if (options.cookie && !hasHeader('Cookie')) headers.push('Cookie: ' + String(options.cookie).replace(/[\r\n]+/g, ' '))
|
||||
const body = options.data === undefined || options.data === null ? '' : String(options.data)
|
||||
if (body !== '' && !hasHeader('Content-Type')) {
|
||||
headers.push(/^\{.*\}$/.test(body.trim()) ? 'Content-Type: application/json' : 'Content-Type: application/x-www-form-urlencoded')
|
||||
@@ -153,8 +155,8 @@ function buildCurlCommand(options = {}) {
|
||||
const url = scheme + '://' + hostPart + (options.path || target.path || '/')
|
||||
const parts = ['curl -i -s' + (options.insecure ? ' -k' : '') + (options.followRedirect ? ' -L' : '')]
|
||||
if (options.method && String(options.method).toUpperCase() !== 'GET') parts.push('-X ' + String(options.method).toUpperCase())
|
||||
if (options.cookie) parts.push("-b '" + options.cookie + "'")
|
||||
if (options.data !== undefined && options.data !== null && options.data !== '') parts.push("-d '" + String(options.data).replace(/'/g, "'\\''") + "'")
|
||||
if (options.cookie) parts.push("-b '" + String(options.cookie).replace(/[\r\n]/g, ' ').replace(/'/g, "'\\''") + "'")
|
||||
if (options.data !== undefined && options.data !== null && options.data !== '') parts.push("-d '" + String(options.data).replace(/[\r\n]+/g, ' ').replace(/'/g, "'\\''") + "'")
|
||||
parts.push("'" + url + "'")
|
||||
return parts.join(' ')
|
||||
}
|
||||
@@ -194,13 +196,15 @@ function fillTemplate(template, values = {}) {
|
||||
[/<u>/g, values.user],
|
||||
[/<p>/g, values.pass],
|
||||
]
|
||||
for (const [re, value] of table) {
|
||||
if (value === undefined || value === null || String(value) === '') continue
|
||||
for (const [re, rawValue] of table) {
|
||||
if (rawValue === undefined || rawValue === null || String(rawValue) === '') continue
|
||||
/* 凭据/域名来自数据库,换行会把一条命令拆成两条。 */
|
||||
const value = String(rawValue).replace(/[\r\n]+/g, ' ')
|
||||
const needle = new RegExp(re.source, re.flags.replace('g', ''))
|
||||
if (!needle.test(cmd)) continue
|
||||
cmd = cmd.replace(new RegExp(re.source, re.flags), String(value))
|
||||
cmd = cmd.replace(new RegExp(re.source, re.flags), value)
|
||||
/* 记录填了什么,报告里要如实说明(模板被改过,读者需要知道哪些是补进去的) */
|
||||
filled.push(re.source.replace(/[\\<>?()/]|gi$/g, '') + ' → ' + String(value))
|
||||
filled.push(re.source.replace(/[\\<>?()/]|gi$/g, '') + ' → ' + value)
|
||||
}
|
||||
const remaining = Array.from(new Set(Array.from(cmd.matchAll(/<[^>\s]{1,24}>/g)).map((m) => m[0])))
|
||||
return { cmd, filled, remaining }
|
||||
|
||||
@@ -441,8 +441,12 @@ function evaluateScoreBoard(db, rows = [], options = {}) {
|
||||
const nm = h.asset_id === null || h.asset_id === undefined ? null : names.get(Number(h.asset_id))
|
||||
return Object.assign({}, h, {
|
||||
code,
|
||||
/* points 必须是"本条命中的实际分值"(见上方说明) */
|
||||
points: hitPointsOf(h, meta),
|
||||
/* points 必须是"本条命中的实际分值"(见上方说明):调用方传进来的已经乘过倍率,
|
||||
这里不能再乘一次,否则 G5/G6 的 ×2/×3 会变成 ×4/×9(合法命中还会被顶上限判成 0 分)。
|
||||
只有没传 points 的行才回落到 hitPointsOf 现算。 */
|
||||
points: (h.points !== null && h.points !== undefined && h.points !== '')
|
||||
? (Number(h.points) || 0)
|
||||
: hitPointsOf(h, meta),
|
||||
rule: m === undefined || m.rule === undefined ? null : m.rule,
|
||||
cap: m === undefined ? 0 : m.cap,
|
||||
dedup_scope: m === undefined ? 'service' : m.dedup_scope,
|
||||
|
||||
@@ -8,8 +8,9 @@
|
||||
* 生效顺序:settings.json → 环境变量 `REDTEAM_MAX_AGENTS` → 默认 3。
|
||||
* 工具侧(redteam_agent_slot 闸门)与面板侧(「智能体」页)读的是同一份,避免两处口径漂移。
|
||||
*/
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { existsSync, mkdirSync, readFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { atomicWriteFileSync } from './atomic-write.js'
|
||||
|
||||
/** 默认并发上限(用户口径:整个项目默认 3 个执行智能体)。 */
|
||||
export const DEFAULT_MAX_AGENTS = 3
|
||||
@@ -35,7 +36,7 @@ export function readSettings(root) {
|
||||
export function writeSettings(root, patch) {
|
||||
const next = Object.assign({}, readSettings(root), patch)
|
||||
mkdirSync(String(root || '.'), { recursive: true })
|
||||
writeFileSync(settingsPathOf(root), JSON.stringify(next, null, 2) + '\n', 'utf8')
|
||||
atomicWriteFileSync(settingsPathOf(root), JSON.stringify(next, null, 2) + '\n')
|
||||
return next
|
||||
}
|
||||
|
||||
|
||||
+81
-36
@@ -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'
|
||||
|
||||
@@ -26,7 +26,7 @@ import {
|
||||
platformSummary,
|
||||
toolkitDirOf,
|
||||
} from './platform-config.js'
|
||||
import { maxAgentsOf, DEFAULT_MAX_AGENTS, MAX_AGENTS_LIMIT } from './settings.js'
|
||||
import { maxAgentsOf } from './settings.js'
|
||||
import { EvidenceLedger, UnknownRegistry } from './evidence-ledger.mjs'
|
||||
|
||||
/**
|
||||
@@ -180,11 +180,6 @@ function sessionInfoOf(exec) {
|
||||
return { id: id, parentId: parentId, session: session }
|
||||
}
|
||||
|
||||
/** 会话 id(兼容旧调用点)。 */
|
||||
function sessionOf(exec) {
|
||||
return sessionInfoOf(exec).id
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析"根会话":一路沿 parentSession 走到最顶层的会话 id。
|
||||
* 主会话派出的子智能体因此共享同一个绑定键,而**不同主会话之间天然隔离**。
|
||||
@@ -491,7 +486,7 @@ export function apply(ctx) {
|
||||
},
|
||||
output: { schema: { type: 'string' }, render: (_args, value) => text(value) },
|
||||
async execute(args, exec) {
|
||||
const list = store.listEngagements()
|
||||
const list = store.listEngagements({ stats: true })
|
||||
const wanted = typeof args.engagement === 'string' ? args.engagement.trim() : ''
|
||||
if (wanted === '') {
|
||||
return JSON.stringify({
|
||||
@@ -1125,7 +1120,7 @@ export function apply(ctx) {
|
||||
output: { schema: { type: 'string' }, render: (_args, value) => text(value) },
|
||||
async execute(args, exec) {
|
||||
const id = resolveEngagement(store, exec, args.engagement)
|
||||
const result = store.listVulns(id, { ...args, engagement: undefined, limit: Math.min(Number(args.limit) || 50, 200) })
|
||||
const result = store.listVulns(id, { ...args, engagement: undefined, evidenceLimit: 20000, limit: Math.min(Number(args.limit) || 50, 200) })
|
||||
return JSON.stringify({ ok: true, engagement: id, total: result.total, items: result.items, stats: store.vulnStats(id) }, null, 2)
|
||||
},
|
||||
})))
|
||||
|
||||
+24
-22
@@ -18,7 +18,9 @@ import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, realpa
|
||||
import { homedir } from 'node:os'
|
||||
import { spawn, execFileSync } from 'node:child_process'
|
||||
import { request as httpsRequest } from 'node:https'
|
||||
import { dispatch, dispatchAsync } from './store-core.js'
|
||||
import { dispatchAsync } from './store-core.js'
|
||||
import { assertPathWithin } from './validate.js'
|
||||
import { validSkillName } from '../skills.js'
|
||||
/* 技能可用性判定与 redteam_preflight 共用同一份实现(环境变量 / 本机路径 / 占位符) */
|
||||
import { checkSkill, officialSkillSummaries, skillLibraryOf, summarizeSkills } from './skill-availability.js'
|
||||
import { maxAgentsOf, maxAgentsSourceOf, saveMaxAgents, DEFAULT_MAX_AGENTS, MAX_AGENTS_LIMIT } from './settings.js'
|
||||
@@ -876,7 +878,10 @@ function handleSkillOpFromPluginDir(request) {
|
||||
if (typeof request.name !== 'string' || request.name.length === 0) {
|
||||
return { ok: false, error: '缺少 name 参数' }
|
||||
}
|
||||
const file = join(dir, request.name.endsWith('.md') ? request.name : (request.name + '.md'))
|
||||
/* name 会直接拼进路径:必须挡掉 `../` 与绝对路径(这条兜底路径曾能读任意 *.md)。 */
|
||||
const skillName = request.name.replace(/\.md$/i, '')
|
||||
if (!validSkillName(skillName)) return { ok: false, error: '技能名不合法: ' + request.name }
|
||||
const file = assertPathWithin(join(dir, skillName + '.md'), [dir])
|
||||
if (!existsSync(file)) return { ok: false, error: '技能不存在: ' + request.name }
|
||||
let content = ''
|
||||
try { content = readFileSync(file, 'utf8') } catch (error) {
|
||||
@@ -885,7 +890,7 @@ function handleSkillOpFromPluginDir(request) {
|
||||
const meta = parseMeta(content)
|
||||
return {
|
||||
ok: true,
|
||||
name: request.name.replace(/\.md$/i, ''),
|
||||
name: skillName,
|
||||
description: meta.description,
|
||||
whenToUse: meta.whenToUse,
|
||||
provider: 'dsh-purge',
|
||||
@@ -1084,34 +1089,31 @@ export function apply(ctx) {
|
||||
sendJson(res, 405, { ok: false, error: 'POST only' })
|
||||
return
|
||||
}
|
||||
/* 来源校验:本机回环一律放行(官方桌面端 Origin 常是 app:// / file://,
|
||||
旧逻辑会把 Origin.host 判空后直接 403,导致技能库/知识库/SQL 全挂)。
|
||||
非回环才要求 Origin 与 Host 同源。 */
|
||||
const remote = req.socket && req.socket.remoteAddress ? String(req.socket.remoteAddress) : ''
|
||||
const loopback = remote === '127.0.0.1' || remote === '::1' || remote === '::ffff:127.0.0.1'
|
||||
/* 来源校验:**不能**因为 remoteAddress 是回环就放行 —— 浏览器访问本机服务时
|
||||
它本来就是 127.0.0.1,等于任何网页都能 POST 进来改数据(CSRF)。
|
||||
以 Origin 与 Host 是否一致为准;桌面端 Origin 是 app:// 或 null,仅在 Host 为本机时放行。 */
|
||||
const host = typeof req.headers.host === 'string' ? req.headers.host : ''
|
||||
const hostLocal = /^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/i.test(host)
|
||||
const site = String(req.headers['sec-fetch-site'] || '').toLowerCase()
|
||||
const origin = req.headers.origin
|
||||
const originOk = (() => {
|
||||
if (loopback) return true
|
||||
/* 官方桌面端:Origin 常为 app:// / null,Host 仍是 127.0.0.1:port */
|
||||
if (hostLocal) {
|
||||
if (origin === undefined || origin === '' || origin === 'null') return true
|
||||
if (typeof origin === 'string' && /^app:/i.test(origin)) return true
|
||||
try {
|
||||
const oh = new URL(origin).host
|
||||
if (oh === host || oh === '' ) return true
|
||||
} catch { /* fall through */ }
|
||||
}
|
||||
if (typeof origin !== 'string' || origin === '') return false
|
||||
let originHost = null
|
||||
try { originHost = new URL(origin).host } catch { originHost = null }
|
||||
return originHost !== null && originHost === host
|
||||
/* 浏览器自己标的跨站请求直接拒(也覆盖 sandbox iframe 的 Origin: null)。 */
|
||||
if (site === 'cross-site' || site === 'same-site') return false
|
||||
if (origin === undefined || origin === '') return true /* 非浏览器客户端(curl / 脚本) */
|
||||
if (origin === 'null') return hostLocal && (site === '' || site === 'none')
|
||||
if (/^app:/i.test(String(origin))) return hostLocal
|
||||
try { return new URL(origin).host === host } catch { return false }
|
||||
})()
|
||||
if (!originOk) {
|
||||
sendJson(res, 403, { ok: false, error: 'cross-origin request rejected' })
|
||||
return
|
||||
}
|
||||
/* 只收 JSON:跨站"简单请求"(text/plain 表单)过不了这一关。 */
|
||||
const ctype = String(req.headers['content-type'] || '').toLowerCase()
|
||||
if (!ctype.includes('application/json')) {
|
||||
sendJson(res, 415, { ok: false, error: 'content-type must be application/json' })
|
||||
return
|
||||
}
|
||||
try {
|
||||
const raw = await readBody(req)
|
||||
const request = raw.trim() ? JSON.parse(raw) : {}
|
||||
|
||||
+24
-3
@@ -5,7 +5,28 @@
|
||||
* 是安全边界所在(路径穿越、非法枚举),值得单独一处、单独读、单独测。
|
||||
*/
|
||||
|
||||
import { resolve, sep } from 'node:path'
|
||||
import { basename, dirname, join, resolve, sep } from 'node:path'
|
||||
import { realpathSync } from 'node:fs'
|
||||
|
||||
/**
|
||||
* 对最近一个存在的祖先目录做 realpath,再拼回不存在的尾部。
|
||||
* 只比字符串前缀时,靶标目录里一个指向外部的软链接/junction 就能穿过去。
|
||||
*/
|
||||
function realish(p) {
|
||||
let cur = p
|
||||
const rest = []
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
try {
|
||||
return join(realpathSync(cur), ...rest)
|
||||
} catch {
|
||||
const parent = dirname(cur)
|
||||
if (parent === cur) break
|
||||
rest.unshift(basename(cur))
|
||||
cur = parent
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
export const WEBSHELL_TYPES = ['behinder', 'godzilla', 'antSword', 'antsword', 'custom']
|
||||
export const WEBSHELL_STATUSES = ['online', 'offline', 'dead', 'unknown']
|
||||
@@ -56,8 +77,8 @@ export function normalizeShellStatus(value) {
|
||||
* @throws 越界时抛错(调用方按"查不到"处理,不要静默返回内容)。
|
||||
*/
|
||||
export function assertPathWithin(target, allowedRoots) {
|
||||
const abs = resolve(String(target || ""))
|
||||
const roots = (allowedRoots || []).filter((r) => typeof r === "string" && r !== "").map((r) => resolve(r))
|
||||
const abs = realish(resolve(String(target || "")))
|
||||
const roots = (allowedRoots || []).filter((r) => typeof r === "string" && r !== "").map((r) => realish(resolve(r)))
|
||||
const okFlag = roots.some((root) => abs === root || abs.startsWith(root + sep))
|
||||
if (!okFlag) {
|
||||
throw new Error("path outside allowed roots: " + abs
|
||||
|
||||
Reference in new issue
Block a user