mirror of
https://github.com/YuJunZhiXue/dsh-purge.git
synced 2026-12-01 03:30:22 +08:00
fix: 发布 1.1.31,演练台进入正式版,回退不再在侧边栏堆分支
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
d2726783a6
commit
da8c1de5bf
57 files changed
+24155
-26
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,380 @@
|
||||
/**
|
||||
* dsh-purge 演练台自举(host 半侧)
|
||||
*
|
||||
* 资产库、工具、预设、技能都在本插件目录内。本文件负责:
|
||||
* 1. 首次把 `presets/redteam` 落到 `$DSH_HOME/.agent-presets/redteam/`
|
||||
* 2. 把技能目录写成 `skills/redteam` 的真实绝对路径
|
||||
* 3. 已有用户预设时只修失效路径 / 旧包名,不整份覆盖
|
||||
*/
|
||||
import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
|
||||
import { homedir } from 'node:os'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { readPresetDefinition } from './preset-composition.js'
|
||||
|
||||
/** Cordis 插件名。 */
|
||||
export const name = 'dsh-purge-redteam'
|
||||
|
||||
/** 与梁神一致:不硬依赖 agentPresets,就绪后软取并声明。 */
|
||||
export const inject = []
|
||||
|
||||
/** 模式下拉里的预设 id(目录名 / registry id)。 */
|
||||
const REDTEAM_PRESET_ID = 'redteam'
|
||||
|
||||
/** 插件根目录(lib/redteam → 上两级)。 */
|
||||
export function packagePaths() {
|
||||
const root = fileURLToPath(new URL('../..', import.meta.url))
|
||||
return {
|
||||
root,
|
||||
presets: join(root, 'presets'),
|
||||
presetDir: join(root, 'presets', 'redteam'),
|
||||
skills: join(root, 'skills', 'redteam'),
|
||||
setupScript: join(root, 'scripts', 'redteam-setup.sh'),
|
||||
}
|
||||
}
|
||||
|
||||
/** 环境数据目录(与 store/tools 用的同一份约定)。 */
|
||||
export function redteamDataDir() {
|
||||
const home = process.env.DSH_HOME || join(homedir(), '.dsh')
|
||||
return join(home, 'redteam')
|
||||
}
|
||||
|
||||
/**
|
||||
* 把随包分发的环境安装脚本落到 `$DSH_HOME/redteam/setup.sh`。
|
||||
*
|
||||
* 市场包用户装完只有 node_modules,仓库不在盘上;预检若只说"从仓库取脚本",
|
||||
* 用户拿不到脚本、首次引导就断了。所以脚本随包走,启动时落一份可执行的副本。
|
||||
* 语义:目标不存在 → 装;已存在但内容不同 → 覆盖(脚本无用户可改状态);
|
||||
* 内容相同 → 不动(避免每次启动都写盘)。
|
||||
*
|
||||
* @returns `{ action: 'installed'|'updated'|'kept'|'missing', path }`
|
||||
*/
|
||||
export function installSetupScript() {
|
||||
const paths = packagePaths()
|
||||
const target = join(redteamDataDir(), 'setup.sh')
|
||||
if (!existsSync(paths.setupScript)) return { action: 'missing', path: target }
|
||||
let wanted
|
||||
try {
|
||||
wanted = readFileSync(paths.setupScript, 'utf8')
|
||||
} catch {
|
||||
return { action: 'missing', path: target }
|
||||
}
|
||||
try {
|
||||
mkdirSync(redteamDataDir(), { recursive: true })
|
||||
if (existsSync(target)) {
|
||||
let current
|
||||
try { current = readFileSync(target, 'utf8') } catch { current = '' }
|
||||
if (current === wanted) {
|
||||
/* 权限可能被外部改掉,这里顺手补回来(脚本要能直接 bash 执行) */
|
||||
try { chmodSync(target, 0o755) } catch { /* 忽略 */ }
|
||||
return { action: 'kept', path: target }
|
||||
}
|
||||
writeFileSync(target, wanted, { encoding: 'utf8', mode: 0o755 })
|
||||
return { action: 'updated', path: target }
|
||||
}
|
||||
writeFileSync(target, wanted, { encoding: 'utf8', mode: 0o755 })
|
||||
return { action: 'installed', path: target }
|
||||
} catch (error) {
|
||||
return { action: 'missing', path: target, error: error && error.message ? error.message : String(error) }
|
||||
}
|
||||
}
|
||||
|
||||
/** 用户 preset 根(与 dsh-agent-presets 的 USER_PRESET_DIR 保持一致)。 */
|
||||
export function userPresetRoot() {
|
||||
const home = process.env.DSH_HOME || join(homedir(), '.dsh')
|
||||
return join(home, '.agent-presets')
|
||||
}
|
||||
|
||||
/**
|
||||
* 预设模板里技能目录的占位符(build.mjs 写进打包预设,落地时才替换)。
|
||||
* 扩展名等都不允许写成别的形式,否则替换会漏。
|
||||
*/
|
||||
const SKILLS_PLACEHOLDER = '{{REDTEAM_SKILLS_DIR}}'
|
||||
|
||||
/** customSkillDirs 里"像本包 skills/ 目录"的那一行(老的绝对路径 / 占位符都算)。 */
|
||||
function isSkillsDirLine(line) {
|
||||
const text = line.trim().replace(/^-\s*/, '')
|
||||
if (text === SKILLS_PLACEHOLDER) return true
|
||||
return /[/\\](dsh-redteam-mode|redteam-bundle)[/\\]skills\/?$/.test(text)
|
||||
|| /[/\\]vendor[/\\]redteam[/\\]skills\/?$/.test(text)
|
||||
|| /[/\\]skills[/\\]redteam\/?$/.test(text)
|
||||
}
|
||||
|
||||
/**
|
||||
* 把预设正文里的技能目录占位符 / 失效的绝对路径渲染成**当前**包内 skills/ 路径。
|
||||
*
|
||||
* 为什么不能只替换占位符:
|
||||
* · 占位符没被替换时,YAML 会把它解析成对象 → `skill-filesystem` 配置校验失败
|
||||
* → **整个预设挂载失败** → 该会话建不了、发不出消息(v0.9.0 真出过这个事故:
|
||||
* 部署时把打包模板直接 cp 进了用户预设目录);
|
||||
* · 包换过位置(npx 缓存换了 hash、profile 重装、从源码包切到市场包)时,上次写下的
|
||||
* 绝对路径会指向不存在的目录 —— 技能"静默变少",比直接报错更难发现。
|
||||
* 两种都在这里就地修正;只有真的改动了才写盘。
|
||||
*/
|
||||
function renderSkillsDir(text, skillsDir) {
|
||||
if (text.includes(SKILLS_PLACEHOLDER)) {
|
||||
return { text: text.split(SKILLS_PLACEHOLDER).join(skillsDir), changed: true, reason: 'placeholder' }
|
||||
}
|
||||
let changed = false
|
||||
const out = text.split('\n').map((line) => {
|
||||
if (!isSkillsDirLine(line)) return line
|
||||
const indent = /^(\s*)/.exec(line)[1]
|
||||
const wanted = indent + '- ' + skillsDir
|
||||
if (line === wanted) return line
|
||||
changed = true
|
||||
return wanted
|
||||
}).join('\n')
|
||||
return { text: out, changed, reason: changed ? 'stale-path' : 'none' }
|
||||
}
|
||||
|
||||
/** 旧组合会把整份预设标 broken(worker-thread 未装 / tools 硬依赖 redteam)。 */
|
||||
function needsCompositionRepair(presetFile) {
|
||||
if (!existsSync(presetFile)) return true
|
||||
try {
|
||||
const text = readFileSync(presetFile, 'utf8')
|
||||
if (!text.includes('id: workflow-ptc')) return true
|
||||
if (/name:\s*'@deepseek-ai\/dsh-workflow-worker-thread'[\s\S]{0,80}?config:\s*\n\s*provider:\s*spawn/.test(text)
|
||||
&& !/name:\s*'@deepseek-ai\/dsh-workflow-worker-thread'\s*\n\s*disabled:\s*true/.test(text)) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
} catch {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
/** 从独立红队包迁进 dsh-purge 后,预设里的工具行包名要跟着改。 */
|
||||
function renderToolsPackage(text) {
|
||||
if (!text.includes('dsh-redteam-mode/tools')) {
|
||||
return { text, changed: false }
|
||||
}
|
||||
return {
|
||||
text: text.split('dsh-redteam-mode/tools').join('dsh-purge/redteam/tools'),
|
||||
changed: true,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 把包内预设落地到用户 preset 根。
|
||||
*
|
||||
* 语义(v0.9.0 起):
|
||||
* · 目标不存在 → 完整安装(占位符替换成真实路径);
|
||||
* · 目标已存在 → **默认不覆盖用户内容,但会自愈**:只要里面还留着
|
||||
* `{{REDTEAM_SKILLS_DIR}}` 或指向不存在的旧包路径,就就地修正(这是唯一必需字段,
|
||||
* 不改就会整个预设挂载失败)。其余内容一律保留 —— 用户可以就地改预设。
|
||||
* · `force: true` 才用包内模板整体覆盖。
|
||||
*
|
||||
* @param options - `{ force?: boolean, log?: (msg: string) => void }`
|
||||
* @returns `{ action: 'installed'|'kept'|'repaired', dir, skillsDir, skills, repaired? }`
|
||||
*/
|
||||
export function installPreset(options = {}) {
|
||||
const paths = packagePaths()
|
||||
const target = join(userPresetRoot(), 'redteam')
|
||||
const log = options.log ?? (() => {})
|
||||
const skillCount = existsSync(paths.skills)
|
||||
? readdirSync(paths.skills).filter((f) => f.endsWith('.md')).length
|
||||
: 0
|
||||
const presetFile = join(target, 'agent.cordis.yml')
|
||||
|
||||
if (existsSync(presetFile) && options.force !== true) {
|
||||
/* 自愈:占位符没替换 / 技能目录指向已失效的旧包路径 → 就地修好 */
|
||||
let text
|
||||
try {
|
||||
text = readFileSync(presetFile, 'utf8')
|
||||
} catch (error) {
|
||||
log(`读取 ${presetFile} 失败:${error && error.message ? error.message : String(error)}`)
|
||||
return { action: 'kept', dir: target, skillsDir: paths.skills, skills: skillCount }
|
||||
}
|
||||
const rendered = renderSkillsDir(text, paths.skills)
|
||||
const tools = renderToolsPackage(rendered.text)
|
||||
const next = tools.text
|
||||
if (rendered.changed || tools.changed) {
|
||||
writeFileSync(presetFile, next.replace(/\r\n/g, '\n').replace(/\r/g, '\n'), 'utf8')
|
||||
log(
|
||||
(rendered.changed
|
||||
? (rendered.reason === 'placeholder'
|
||||
? '预设里还留着 ' + SKILLS_PLACEHOLDER + '(会导致整个预设挂载失败)'
|
||||
: '预设里的技能目录指向已失效的旧包路径')
|
||||
+ `,已就地修正为 ${paths.skills}`
|
||||
: '')
|
||||
+ (tools.changed ? (rendered.changed ? ';' : '') + '工具包名已改为 dsh-purge/redteam/tools' : ''),
|
||||
)
|
||||
return {
|
||||
action: 'repaired', dir: target, skillsDir: paths.skills, skills: skillCount,
|
||||
repaired: [rendered.changed ? rendered.reason : null, tools.changed ? 'tools-package' : null].filter(Boolean).join('+'),
|
||||
}
|
||||
}
|
||||
log(`已存在用户自己的预设 ${target},保留不动(要覆盖:REDTEAM_PRESET_REFRESH=1 启动一次)`)
|
||||
return { action: 'kept', dir: target, skillsDir: paths.skills, skills: skillCount }
|
||||
}
|
||||
|
||||
mkdirSync(target, { recursive: true })
|
||||
for (const file of readdirSync(paths.presetDir)) {
|
||||
const text = readFileSync(join(paths.presetDir, file), 'utf8')
|
||||
const rendered = renderToolsPackage(renderSkillsDir(text, paths.skills).text).text
|
||||
.replace(/\r\n/g, '\n')
|
||||
.replace(/\r/g, '\n')
|
||||
writeFileSync(join(target, file), rendered, 'utf8')
|
||||
}
|
||||
log(`预设已安装到 ${target}(打包技能 ${skillCount} 个:${paths.skills})`)
|
||||
return { action: 'installed', dir: target, skillsDir: paths.skills, skills: skillCount }
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ctx - 插件上下文。
|
||||
*/
|
||||
export function apply(ctx) {
|
||||
const paths = packagePaths()
|
||||
let result
|
||||
try {
|
||||
result = installPreset({
|
||||
force: process.env.REDTEAM_PRESET_REFRESH === '1'
|
||||
|| needsCompositionRepair(join(userPresetRoot(), 'redteam', 'agent.cordis.yml')),
|
||||
log: (msg) => ctx.logger?.info?.('redteam-mode: ' + msg),
|
||||
})
|
||||
} catch (error) {
|
||||
ctx.logger?.error?.('redteam-mode: 预设安装失败:%s', error && error.message ? error.message : String(error))
|
||||
result = { action: 'failed', dir: join(userPresetRoot(), 'redteam'), skillsDir: paths.skills, skills: 0 }
|
||||
}
|
||||
let setupResult
|
||||
try {
|
||||
setupResult = installSetupScript()
|
||||
} catch (error) {
|
||||
setupResult = { action: 'missing', error: error && error.message ? error.message : String(error) }
|
||||
}
|
||||
if (setupResult.action === 'installed' || setupResult.action === 'updated') {
|
||||
ctx.logger?.info?.('redteam-mode: 环境安装脚本已就位 %s(%s)', setupResult.path, setupResult.action)
|
||||
}
|
||||
|
||||
/*
|
||||
* Web 0.1.7+ 模式下拉只认 agent-preset registry.register(),
|
||||
* 扫磁盘 .agent-presets 不会出现在下拉里(梁神同款)。
|
||||
*/
|
||||
const statusFile = join(redteamDataDir(), 'preset-declare.json')
|
||||
const writeStatus = (patch) => {
|
||||
try {
|
||||
mkdirSync(redteamDataDir(), { recursive: true })
|
||||
let prev = {}
|
||||
try { prev = JSON.parse(readFileSync(statusFile, 'utf8')) } catch { /* first */ }
|
||||
writeFileSync(statusFile, JSON.stringify({ ...prev, ...patch, at: new Date().toISOString() }, null, 2), 'utf8')
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
writeStatus({ ok: false, phase: 'apply-start', skillsDir: paths.skills, presetDir: result.dir })
|
||||
|
||||
let releaseDeclared
|
||||
let closed = false
|
||||
const softRegistry = () => {
|
||||
try {
|
||||
if (ctx.agentPresets && typeof ctx.agentPresets.register === 'function') return ctx.agentPresets
|
||||
} catch { /* without inject */ }
|
||||
try {
|
||||
const reg = ctx.get('agentPresets')
|
||||
if (reg && typeof reg.register === 'function') return reg
|
||||
} catch { /* missing */ }
|
||||
return null
|
||||
}
|
||||
const undeclare = async () => {
|
||||
const dispose = releaseDeclared
|
||||
releaseDeclared = undefined
|
||||
if (!dispose) return
|
||||
try { await dispose() } catch (error) {
|
||||
ctx.logger?.warn?.('redteam-mode: undeclare failed: %s', error?.message || String(error))
|
||||
}
|
||||
}
|
||||
const buildDefinition = () => {
|
||||
const fromDisk = join(userPresetRoot(), 'redteam')
|
||||
if (!existsSync(join(fromDisk, 'agent.cordis.yml'))) {
|
||||
installPreset({ force: false, log: () => {} })
|
||||
}
|
||||
const readyDir = existsSync(join(userPresetRoot(), 'redteam', 'agent.cordis.yml'))
|
||||
? join(userPresetRoot(), 'redteam')
|
||||
: paths.presetDir
|
||||
return readPresetDefinition(REDTEAM_PRESET_ID, readyDir)
|
||||
}
|
||||
const registerOnce = (registry) => {
|
||||
let definition
|
||||
try {
|
||||
definition = buildDefinition()
|
||||
} catch (error) {
|
||||
writeStatus({ ok: false, phase: 'read-failed', error: error?.message || String(error) })
|
||||
ctx.logger?.warn?.('redteam-mode: read preset failed: %s', error?.message || String(error))
|
||||
return
|
||||
}
|
||||
writeStatus({
|
||||
ok: false,
|
||||
phase: 'registering',
|
||||
id: definition.id,
|
||||
name: definition.name,
|
||||
plugins: Array.isArray(definition.plugins) ? definition.plugins.length : -1,
|
||||
})
|
||||
Promise.resolve()
|
||||
.then(async () => {
|
||||
await undeclare()
|
||||
releaseDeclared = await registry.register(definition)
|
||||
let broken = null
|
||||
try {
|
||||
const row = (await registry.list()).find((p) => p.id === REDTEAM_PRESET_ID)
|
||||
broken = row?.broken || null
|
||||
} catch { /* ignore */ }
|
||||
writeStatus({
|
||||
ok: !broken,
|
||||
phase: broken ? 'registered-broken' : 'registered',
|
||||
id: definition.id,
|
||||
name: definition.name,
|
||||
plugins: Array.isArray(definition.plugins) ? definition.plugins.length : -1,
|
||||
broken,
|
||||
})
|
||||
if (broken) ctx.logger?.warn?.('redteam-mode: declared but broken: %s', broken)
|
||||
else ctx.logger?.info?.('redteam-mode: declared for mode dropdown: %s', definition.name || REDTEAM_PRESET_ID)
|
||||
})
|
||||
.catch((error) => {
|
||||
writeStatus({ ok: false, phase: 'register-failed', error: error?.message || String(error) })
|
||||
ctx.logger?.warn?.('redteam-mode: register failed: %s', error?.message || String(error))
|
||||
})
|
||||
}
|
||||
|
||||
ctx.effect(() => {
|
||||
let tries = 0
|
||||
const tick = () => {
|
||||
if (closed) return true
|
||||
tries += 1
|
||||
const registry = softRegistry()
|
||||
if (!registry) {
|
||||
writeStatus({ ok: false, phase: 'waiting-registry', tries })
|
||||
return false
|
||||
}
|
||||
registerOnce(registry)
|
||||
return true
|
||||
}
|
||||
let timer
|
||||
if (!tick()) {
|
||||
timer = setInterval(() => {
|
||||
if (tick()) {
|
||||
clearInterval(timer)
|
||||
timer = undefined
|
||||
}
|
||||
}, 400)
|
||||
const stop = setTimeout(() => {
|
||||
if (timer) {
|
||||
clearInterval(timer)
|
||||
timer = undefined
|
||||
writeStatus({ ok: false, phase: 'timeout-waiting-registry', tries })
|
||||
}
|
||||
}, 45000)
|
||||
try { stop.unref?.() } catch { /* ignore */ }
|
||||
}
|
||||
return () => {
|
||||
closed = true
|
||||
if (timer) clearInterval(timer)
|
||||
void undeclare()
|
||||
}
|
||||
}, 'dsh-purge-redteam: declare agent preset')
|
||||
|
||||
ctx.provide('redteamMode', Object.freeze({ paths, preset: result, setup: setupResult }))
|
||||
ctx.logger?.info?.(
|
||||
'redteam-mode: 就绪(数据目录默认 $DSH_HOME/redteam;预设 %s;技能目录 %s)',
|
||||
result.dir, result.skillsDir,
|
||||
)
|
||||
}
|
||||
|
||||
export default { name, inject, apply }
|
||||
@@ -0,0 +1,140 @@
|
||||
/**
|
||||
* IP / 文本归一化工具(纯函数,零依赖)。
|
||||
*
|
||||
* 从 core.js 抽出来的第一批模块之一:这些函数不碰数据库、不依赖 Store 实例,
|
||||
* 却散落在 5000 行的 core.js 里,单测只能连同 SQLite 一起加载。
|
||||
* 抽出来后可以单独测、单独读,也便于 core.js 专注在"事实库语义"上。
|
||||
*
|
||||
* 导出面与原来完全一致(core.js 会原样再导出一次),所以调用方无需改动。
|
||||
*/
|
||||
|
||||
/**
|
||||
* IPv4 → 32 位整数(用于 ORDER BY 的自然排序)。
|
||||
* IPv6 走不了这条路(字符串 split('.') 只会得到一段),返回 null ——
|
||||
* 让 ip_int 保持 NULL,排序退回按 ip 文本,不要编造一个 0 或把地址拼坏。
|
||||
*/
|
||||
export const ipToInt = (ip) => {
|
||||
const text = String(ip || '').trim()
|
||||
if (!/^\d{1,3}(\.\d{1,3}){3}$/.test(text)) return null
|
||||
return text.split('.').reduce((n, o) => (n * 256 + Number(o)) >>> 0, 0)
|
||||
}
|
||||
|
||||
/** 是不是 IPv6 字面量(含 :: 缩写与 IPv4-mapped 写法)。 */
|
||||
export function isIpv6(ip) {
|
||||
const text = String(ip || '').trim()
|
||||
if (!text.includes(':')) return false
|
||||
return /^[0-9a-fA-F:]+(:\d{1,3}(\.\d{1,3}){3})?$/.test(text) && text.split(':').length <= 9
|
||||
}
|
||||
|
||||
/** 把 IPv6 展开成 8 组十六进制(只用于取前 4 组算 /64,不追求完全严谨)。 */
|
||||
export function expandIpv6(ip) {
|
||||
const text = String(ip || '').trim().replace(/^\[|\]$/g, '')
|
||||
const [head, tail] = text.split('::')
|
||||
const left = head === '' ? [] : head.split(':')
|
||||
const right = tail === undefined || tail === '' ? [] : tail.split(':')
|
||||
const missing = 8 - left.length - right.length
|
||||
const groups = left.concat(new Array(Math.max(missing, 0)).fill('0')).concat(right)
|
||||
return groups.map((g) => (g === '' ? '0' : g.toLowerCase()))
|
||||
}
|
||||
|
||||
/**
|
||||
* 这个 IP 属于哪个"段"(资产测绘左侧按 C 段分组)。
|
||||
* · IPv4 → 前三段 + .0/24(保持原行为);
|
||||
* · IPv6 → 前四组 + ::/64(IPv6 的"一个网段"就是 /64,与 IPv4 的 /24 对应);
|
||||
* · 认不出来 → 返回原文,绝不拼出一个像 `2001:db8::1.0/24` 这种四不像。
|
||||
* 曾经的问题是直接 split('.') 拼 ".0/24",IPv6 资产会得到脏 CIDR,
|
||||
* 面板左侧就多出一个假网段、资产归属也错。
|
||||
*/
|
||||
export const cidrOf = (ip) => {
|
||||
const text = String(ip || '').trim()
|
||||
if (/^\d{1,3}(\.\d{1,3}){3}$/.test(text)) return text.split('.').slice(0, 3).join('.') + '.0/24'
|
||||
if (isIpv6(text)) {
|
||||
const groups = expandIpv6(text)
|
||||
return groups.slice(0, 4).join(':') + '::/64'
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断 IP 属于内网还是外网(面板按它分组「内网 C 段 / 外网 C 段」)。
|
||||
* · IPv4:10/8、192.168/16、127/8、169.254/16、172.16-31/12、100.64-127/10(CGNAT);
|
||||
* · IPv6:ULA(fc00::/7)与链路本地(fe80::/10)算内网;
|
||||
* · IPv4-mapped 的 ::ffff:a.b.c.d 剥壳后按 IPv4 判。
|
||||
* @param ip - 待判定地址。
|
||||
* @returns 'internal' | 'external'
|
||||
*/
|
||||
export function scopeOfIp(ip) {
|
||||
const s = String(ip || '')
|
||||
/* IPv6:ULA(fc00::/7)与链路本地(fe80::/10)是内网;IPv4-mapped 的 ::ffff:a.b.c.d 剥壳后按 IPv4 判 */
|
||||
const mapped = /^::ffff:(\d{1,3}(\.\d{1,3}){3})$/i.exec(s)
|
||||
if (mapped !== null) return scopeOfIp(mapped[1])
|
||||
if (/^f[cd][0-9a-f]{2}:/i.test(s) || /^fe[89ab][0-9a-f]:/i.test(s)) return 'internal'
|
||||
if (/^(10\.|192\.168\.|127\.|169\.254\.)/.test(s)) return 'internal'
|
||||
const m = /^172\.(\d{1,3})\./.exec(s)
|
||||
if (m !== null) {
|
||||
const n = Number(m[1])
|
||||
if (n >= 16 && n <= 31) return 'internal'
|
||||
}
|
||||
const c = /^100\.(\d{1,3})\./.exec(s)
|
||||
if (c !== null) {
|
||||
const n = Number(c[1])
|
||||
if (n >= 64 && n <= 127) return 'internal'
|
||||
}
|
||||
return 'external'
|
||||
}
|
||||
|
||||
/** 把任意名字归一化成 slug(全小写、非字母数字转短横线)。 */
|
||||
export function slugify(name) {
|
||||
const s = String(name || '').trim().toLowerCase()
|
||||
.replace(/[^\p{L}\p{N}]+/gu, '-')
|
||||
.replace(/^-+|-+$/g, '')
|
||||
return s === '' ? 'engagement-' + Date.now() : s
|
||||
}
|
||||
|
||||
/**
|
||||
* 把目标(IP / URL / C 段)归一化成攻击文件目录名。
|
||||
* · IP 或 ip:port → 只取 IP(同一 IP 的多个端口归一个文件夹)
|
||||
* · URL → 只取 host(去掉协议、端口、路径)
|
||||
* · C 段 10.0.0.0/24 → 10.0.0.0_24
|
||||
*/
|
||||
export function slugTarget(target) {
|
||||
const raw = String(target || '').trim()
|
||||
if (raw === '') return 'unknown'
|
||||
const ipMatch = /^(\d{1,3}(?:\.\d{1,3}){3})(?::\d+)?$/.exec(raw)
|
||||
if (ipMatch !== null) return ipMatch[1]
|
||||
const urlMatch = /^https?:\/\/([^/?#]+)/i.exec(raw)
|
||||
const hostPort = urlMatch !== null ? urlMatch[1] : raw
|
||||
const host = hostPort.replace(/:(\d+)$/, '')
|
||||
return host.replace(/[^\w.\-]/g, '_').replace(/_+$/, '') || 'unknown'
|
||||
}
|
||||
|
||||
/** 生成知识库条目的稳定标识:组件 + 编号/标题,便于智能体直接引用。 */
|
||||
export function slugPoc(title, cve) {
|
||||
const t = String(title || '').trim()
|
||||
const c = String(cve || '').trim()
|
||||
/* 标题里往往已经写了 CVE,别再拼一遍(否则 code 会变成 xxx-cve-2023-21839-cve-2023-21839) */
|
||||
const flat = (s) => String(s).toLowerCase().replace(/[^a-z0-9]/g, '')
|
||||
const base = (c !== '' && !flat(t).includes(flat(c))) ? c + ' ' + t : t
|
||||
const slug = base.toLowerCase()
|
||||
.replace(/cve[-_ ]?(\d{4})[-_ ]?(\d+)/g, 'cve-$1-$2')
|
||||
.replace(/[^\w\u4e00-\u9fa5.-]+/g, '-')
|
||||
.replace(/-{2,}/g, '-')
|
||||
.replace(/^-+|-+$/g, '')
|
||||
.slice(0, 80)
|
||||
.replace(/-+$/, '')
|
||||
return slug === '' ? 'poc-' + Date.now() : slug
|
||||
}
|
||||
|
||||
/** 按语言给正文一个合适的文件名(智能体可以直接照着运行)。 */
|
||||
export function defaultPocFilename(title, kind, language) {
|
||||
const ext = {
|
||||
python: 'py', py: 'py', go: 'go', java: 'java', bash: 'sh', sh: 'sh', shell: 'sh',
|
||||
js: 'js', node: 'js', php: 'php', ruby: 'rb', powershell: 'ps1', http: 'http', nuclei: 'yaml', yaml: 'yaml',
|
||||
}[String(language || '').toLowerCase()]
|
||||
if (ext) return 'poc.' + ext
|
||||
if (kind === 'template') return 'poc.yaml'
|
||||
return 'poc.txt'
|
||||
}
|
||||
|
||||
/** ISO 时间戳(统一出口,便于测试注入)。 */
|
||||
export const nowIso = () => new Date().toISOString()
|
||||
@@ -0,0 +1,145 @@
|
||||
/**
|
||||
* 迁移:清掉预发布期(≤0.7.0)用「开发版」安装留下的 profile 补丁行。
|
||||
*
|
||||
* 为什么需要它:那些机器在 `$DSH_HOME/profiles/web/cordis.patch.yml` 里手写过
|
||||
* - insert:
|
||||
* - id: redteam-store
|
||||
* name: dsh-redteam-store
|
||||
* config: {…}
|
||||
* - id: redteam-ui
|
||||
* name: dsh-redteam-ui
|
||||
* bundle 补丁在**更早**的层里挂自己的行,改不动后面这一层,于是两套一起挂:
|
||||
* service "redteam" has been registered at <redteam-store>
|
||||
* `dsh web` 起不来(0.7.0 之前报的是 duplicate loader entry id)。
|
||||
*
|
||||
* 做法:按行扫描,删掉这两条**条目本身及其子行**(缩进更深的部分),其它内容原样保留;
|
||||
* 若某个 `- insert:` 的子项被删空,连同那一行一起删。先备份再写回;幂等;支持 --dry-run。
|
||||
*
|
||||
* 用法(本插件内):
|
||||
* node lib/redteam/migrate-legacy-rows.mjs [--profile web] [--dry-run]
|
||||
*/
|
||||
import { copyFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { homedir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
|
||||
const LEGACY_IDS = ['redteam-store', 'redteam-ui']
|
||||
|
||||
const args = process.argv.slice(2)
|
||||
const dryRun = args.includes('--dry-run')
|
||||
const profileArg = args.indexOf('--profile')
|
||||
const profile = profileArg >= 0 ? args[profileArg + 1] : 'web'
|
||||
const dshHome = process.env.DSH_HOME || join(homedir(), '.dsh')
|
||||
const patchPath = join(dshHome, 'profiles', profile, 'cordis.patch.yml')
|
||||
|
||||
if (!existsSync(patchPath)) {
|
||||
console.log(`没有找到 profile 补丁:${patchPath}(无事可做)`)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const indentOf = (line) => (/^[ \t]*/.exec(line) || [''])[0].length
|
||||
const isBlank = (line) => line.trim() === ''
|
||||
|
||||
/**
|
||||
* 删掉一个条目:从 `- id: <legacyId>` 那行开始,连带删除后续**缩进更深**的行
|
||||
* (它自己的 name/config/…),遇到缩进不更深且非空的行就停。
|
||||
*/
|
||||
function removeEntry(lines, legacyId) {
|
||||
const out = []
|
||||
const removed = []
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i]
|
||||
const m = /^[ \t]*-[ \t]+id:[ \t]*(\S+)[ \t]*$/.exec(line)
|
||||
if (m === null || m[1] !== legacyId) { out.push(line); continue }
|
||||
const base = indentOf(line)
|
||||
removed.push(line.trim())
|
||||
let j = i + 1
|
||||
while (j < lines.length) {
|
||||
const next = lines[j]
|
||||
if (isBlank(next)) { j++; continue } /* 条目内的空行也一并吃掉 */
|
||||
if (indentOf(next) <= base) break
|
||||
j++
|
||||
}
|
||||
i = j - 1
|
||||
}
|
||||
return { lines: out, removed }
|
||||
}
|
||||
|
||||
/**
|
||||
* 删掉子项已被删空的 `- insert:` 行(连同它下面只剩注释/空行的块)。
|
||||
*
|
||||
* 注意:块内的**注释不算子项**——预发布期的补丁里 `- insert:` 下面常常先写一段
|
||||
* 说明注释再写 `- id:` 行,删掉 id 行后如果还把注释当子项,就会留下一个
|
||||
* `- insert:` + 注释的悬空块(YAML 解析成 `{insert: null}`,boot 仍会出错)。
|
||||
*/
|
||||
function dropEmptyInserts(lines) {
|
||||
const out = []
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i]
|
||||
if (/^[ \t]*-[ \t]*insert:[ \t]*$/.test(line)) {
|
||||
const base = indentOf(line)
|
||||
let j = i + 1
|
||||
let hasChild = false
|
||||
while (j < lines.length) {
|
||||
const next = lines[j]
|
||||
if (isBlank(next) || next.trim().startsWith('#')) {
|
||||
if (next.trim().startsWith('#') && indentOf(next) <= base) break
|
||||
j++
|
||||
continue
|
||||
}
|
||||
if (indentOf(next) <= base) break
|
||||
hasChild = true
|
||||
break
|
||||
}
|
||||
if (!hasChild) { i = j - 1; continue } /* 整块(含块内注释)一并丢掉 */
|
||||
}
|
||||
out.push(line)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const original = readFileSync(patchPath, 'utf8')
|
||||
let lines = original.split('\n')
|
||||
const removed = []
|
||||
for (const id of LEGACY_IDS) {
|
||||
const res = removeEntry(lines, id)
|
||||
lines = res.lines
|
||||
removed.push(...res.removed)
|
||||
}
|
||||
lines = dropEmptyInserts(lines)
|
||||
/* 补丁文件必须是顶层 YAML 数组:整份被删空时要写回 `[]`,不能留空文件
|
||||
(空文件会让 boot 报 "must be a top-level YAML array of loader patch entries")。 */
|
||||
let text = lines.join('\n')
|
||||
if (text.split('\n').every((l) => l.trim() === '' || l.trim().startsWith('#'))) text = '[]\n'
|
||||
|
||||
if (removed.length === 0 && text === original) {
|
||||
console.log(`✓ ${patchPath} 里没有预发布期的遗留行(无需迁移)`)
|
||||
process.exit(0)
|
||||
}
|
||||
if (removed.length === 0) {
|
||||
/* 没有遗留行、但文件需要清理(例如旧版脚本删空 insert 块时留下的悬空 `- insert:`)。 */
|
||||
if (dryRun) {
|
||||
console.log('[dry-run] 将清理悬空的 `- insert:` 块(文件未改动)')
|
||||
process.exit(0)
|
||||
}
|
||||
const cleaned = `${patchPath}.bak-${Date.now()}`
|
||||
copyFileSync(patchPath, cleaned)
|
||||
writeFileSync(patchPath, text, 'utf8')
|
||||
console.log('✓ 已清理悬空的 `- insert:` 块(它下面只剩注释,YAML 会解析成 null)')
|
||||
console.log(` 备份:${cleaned}`)
|
||||
console.log(' 重启 dsh web 即可。')
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const before = original.split('\n').filter((l) => l.trim() !== '').length
|
||||
const after = text.split('\n').filter((l) => l.trim() !== '').length
|
||||
if (dryRun) {
|
||||
console.log(`[dry-run] 将删除 ${removed.length} 条遗留行,有效行 ${before} → ${after}(文件未改动)`)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const backup = `${patchPath}.bak-${Date.now()}`
|
||||
copyFileSync(patchPath, backup)
|
||||
writeFileSync(patchPath, text, 'utf8')
|
||||
console.log(`✓ 已删除 ${removed.length} 条遗留行(有效行 ${before} → ${after})`)
|
||||
console.log(` 备份:${backup}`)
|
||||
console.log(' 重启 dsh web 即可。')
|
||||
@@ -0,0 +1,541 @@
|
||||
/**
|
||||
* 红队平台适配配置(插件内,无 .ps1)
|
||||
*
|
||||
* 落盘:`$DSH_HOME/redteam/config.json`
|
||||
* 用途:
|
||||
* · Windows / 非 Kali 机器上,由用户填写工具绝对路径或搜索目录;
|
||||
* · preflight / 技能可用性 / nuclei 模板目录 统一走这里;
|
||||
* · 不往官方 `$DSH_HOME/skills` 写任何东西。
|
||||
*
|
||||
* 借鉴 Z3r0:系统配置集中、可在 UI 里改(FOFA / 路径类),而不是只靠 shell 引导。
|
||||
*/
|
||||
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync, statSync } from 'node:fs'
|
||||
import { homedir, platform as osPlatform } from 'node:os'
|
||||
import { delimiter, isAbsolute, join, resolve, sep } from 'node:path'
|
||||
|
||||
/** 配置文件路径。 */
|
||||
export function configPathOf(root) {
|
||||
return join(root || redteamRoot(), 'config.json')
|
||||
}
|
||||
|
||||
export function redteamRoot() {
|
||||
const home = process.env.DSH_HOME || join(homedir(), '.dsh')
|
||||
return join(home, 'redteam')
|
||||
}
|
||||
|
||||
/** 默认工具箱目录。 */
|
||||
export function defaultToolkitDir(root) {
|
||||
return join(root || redteamRoot(), 'toolkit')
|
||||
}
|
||||
|
||||
/**
|
||||
* 内置工具清单:id → 可能的可执行名(含 Windows .exe)。
|
||||
* 用户可在 config.tools[id] 填绝对路径覆盖;也可在 binDirs 里放整包工具目录。
|
||||
*/
|
||||
export const TOOL_CATALOG = [
|
||||
{ id: 'nmap', label: 'Nmap', names: ['nmap.exe', 'nmap'] },
|
||||
{ id: 'nuclei', label: 'Nuclei', names: ['nuclei.exe', 'nuclei'] },
|
||||
{ id: 'masscan', label: 'Masscan', names: ['masscan.exe', 'masscan'] },
|
||||
{ id: 'fscan', label: 'fscan', names: ['fscan.exe', 'fscan'] },
|
||||
{ id: 'gogo', label: 'gogo', names: ['gogo.exe', 'gogo'] },
|
||||
{ id: 'suo5', label: 'suo5', names: ['suo5.exe', 'suo5-windows-amd64.exe', 'suo5-linux-amd64', 'suo5'] },
|
||||
{ id: 'frpc', label: 'frp 客户端', names: ['frpc.exe', 'frpc'] },
|
||||
{ id: 'frps', label: 'frp 服务端', names: ['frps.exe', 'frps'] },
|
||||
{ id: 'chisel', label: 'chisel', names: ['chisel.exe', 'chisel'] },
|
||||
{ id: 'ffuf', label: 'ffuf', names: ['ffuf.exe', 'ffuf'] },
|
||||
{ id: 'httpx', label: 'httpx', names: ['httpx.exe', 'httpx'] },
|
||||
{ id: 'dnsx', label: 'dnsx', names: ['dnsx.exe', 'dnsx'] },
|
||||
{ id: 'subfinder', label: 'subfinder', names: ['subfinder.exe', 'subfinder'] },
|
||||
{ id: 'ksubdomain', label: 'ksubdomain', names: ['ksubdomain.exe', 'ksubdomain'] },
|
||||
{ id: 'impacket', label: 'impacket(目录或入口)', names: ['impacket-secretsdump.exe', 'secretsdump.py', 'impacket'] },
|
||||
]
|
||||
|
||||
const EMPTY = () => ({
|
||||
version: 1,
|
||||
/* auto | windows | linux —— auto 跟 Node process.platform */
|
||||
platform: 'auto',
|
||||
toolkitDir: '',
|
||||
nucleiTemplatesDir: '',
|
||||
/* 额外搜索目录:用户自己的 Kali 工具包 / 绿色版工具夹 */
|
||||
binDirs: [],
|
||||
/* id → 绝对路径;空字符串表示未指定 */
|
||||
tools: Object.fromEntries(TOOL_CATALOG.map((t) => [t.id, ''])),
|
||||
env: {
|
||||
FOFA_KEY: '',
|
||||
REDTEAM_VPS_HOST: '',
|
||||
REDTEAM_VPS_KEY: '',
|
||||
},
|
||||
notes: '',
|
||||
/* 用户确认「暂不配置工具」后允许正常对话 */
|
||||
envAdaptSkip: false,
|
||||
/* 用户在环境适配里保存/文件夹分配过一次 */
|
||||
envAdaptConfigured: false,
|
||||
updated_at: null,
|
||||
})
|
||||
|
||||
function isWinLike(cfg) {
|
||||
const p = (cfg && cfg.platform) || 'auto'
|
||||
if (p === 'windows') return true
|
||||
if (p === 'linux') return false
|
||||
return osPlatform() === 'win32'
|
||||
}
|
||||
|
||||
export function loadPlatformConfig(root) {
|
||||
const base = EMPTY()
|
||||
const file = configPathOf(root)
|
||||
if (!existsSync(file)) return Object.assign({}, base, { path: file, exists: false })
|
||||
try {
|
||||
const raw = JSON.parse(readFileSync(file, 'utf8'))
|
||||
const tools = Object.assign({}, base.tools, raw.tools && typeof raw.tools === 'object' ? raw.tools : {})
|
||||
const env = Object.assign({}, base.env, raw.env && typeof raw.env === 'object' ? raw.env : {})
|
||||
const binDirs = Array.isArray(raw.binDirs)
|
||||
? raw.binDirs.map((x) => String(x || '').trim()).filter(Boolean)
|
||||
: []
|
||||
return {
|
||||
version: Number(raw.version) || 1,
|
||||
platform: ['auto', 'windows', 'linux'].includes(raw.platform) ? raw.platform : 'auto',
|
||||
toolkitDir: typeof raw.toolkitDir === 'string' ? raw.toolkitDir.trim() : '',
|
||||
nucleiTemplatesDir: typeof raw.nucleiTemplatesDir === 'string' ? raw.nucleiTemplatesDir.trim() : '',
|
||||
binDirs,
|
||||
tools,
|
||||
env,
|
||||
notes: typeof raw.notes === 'string' ? raw.notes : '',
|
||||
envAdaptSkip: !!raw.envAdaptSkip,
|
||||
envAdaptConfigured: !!raw.envAdaptConfigured,
|
||||
updated_at: raw.updated_at || null,
|
||||
path: file,
|
||||
exists: true,
|
||||
}
|
||||
} catch (error) {
|
||||
return Object.assign({}, base, {
|
||||
path: file,
|
||||
exists: true,
|
||||
error: error && error.message ? error.message : String(error),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export function savePlatformConfig(patch, root) {
|
||||
const dir = root || redteamRoot()
|
||||
mkdirSync(dir, { recursive: true })
|
||||
const prev = loadPlatformConfig(dir)
|
||||
const next = {
|
||||
version: 1,
|
||||
platform: ['auto', 'windows', 'linux'].includes(patch.platform) ? patch.platform : (prev.platform || 'auto'),
|
||||
toolkitDir: typeof patch.toolkitDir === 'string' ? patch.toolkitDir.trim() : (prev.toolkitDir || ''),
|
||||
nucleiTemplatesDir: typeof patch.nucleiTemplatesDir === 'string'
|
||||
? patch.nucleiTemplatesDir.trim()
|
||||
: (prev.nucleiTemplatesDir || ''),
|
||||
binDirs: Array.isArray(patch.binDirs)
|
||||
? patch.binDirs.map((x) => String(x || '').trim()).filter(Boolean)
|
||||
: (prev.binDirs || []),
|
||||
tools: Object.assign({}, prev.tools || {}, patch.tools && typeof patch.tools === 'object' ? patch.tools : {}),
|
||||
env: Object.assign({}, prev.env || {}, patch.env && typeof patch.env === 'object' ? patch.env : {}),
|
||||
notes: typeof patch.notes === 'string' ? patch.notes : (prev.notes || ''),
|
||||
envAdaptSkip: patch.envAdaptSkip !== undefined ? !!patch.envAdaptSkip : !!prev.envAdaptSkip,
|
||||
envAdaptConfigured: patch.envAdaptConfigured !== undefined
|
||||
? !!patch.envAdaptConfigured
|
||||
: !!prev.envAdaptConfigured,
|
||||
updated_at: new Date().toISOString(),
|
||||
}
|
||||
/* 空 tools 键保留 catalog 全量,方便面板编辑 */
|
||||
for (const t of TOOL_CATALOG) {
|
||||
if (next.tools[t.id] === undefined || next.tools[t.id] === null) next.tools[t.id] = ''
|
||||
else next.tools[t.id] = String(next.tools[t.id]).trim()
|
||||
}
|
||||
const file = configPathOf(dir)
|
||||
writeFileSync(file, JSON.stringify(next, null, 2), 'utf8')
|
||||
return loadPlatformConfig(dir)
|
||||
}
|
||||
|
||||
/** 生效的工具箱根。 */
|
||||
export function toolkitDirOf(cfg, root) {
|
||||
const c = cfg || loadPlatformConfig(root)
|
||||
if (c.toolkitDir) return resolve(c.toolkitDir)
|
||||
return defaultToolkitDir(root)
|
||||
}
|
||||
|
||||
/** 生效的 nuclei 模板目录(可空)。 */
|
||||
export function nucleiTemplatesDirOf(cfg, root) {
|
||||
const c = cfg || loadPlatformConfig(root)
|
||||
if (c.nucleiTemplatesDir && existsSync(c.nucleiTemplatesDir)) return resolve(c.nucleiTemplatesDir)
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 在目录里找可执行名(浅扫一层 + 常见子目录 bin/)。
|
||||
*/
|
||||
function findInDir(dir, names) {
|
||||
if (!dir || !existsSync(dir)) return null
|
||||
const tryOne = (base) => {
|
||||
for (const name of names) {
|
||||
const p = join(base, name)
|
||||
if (existsSync(p)) {
|
||||
try {
|
||||
const st = statSync(p)
|
||||
if (st.isFile()) return p
|
||||
} catch { /* continue */ }
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
const hit = tryOne(dir)
|
||||
if (hit) return hit
|
||||
for (const sub of ['bin', 'Bins', 'tools', 'Tools']) {
|
||||
const nested = tryOne(join(dir, sub))
|
||||
if (nested) return nested
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** PATH 上的 which(仅同步、不 spawn shell)。 */
|
||||
function findOnPath(names, env = process.env) {
|
||||
const pathVar = env.PATH || env.Path || ''
|
||||
const parts = pathVar.split(delimiter).filter(Boolean)
|
||||
for (const part of parts) {
|
||||
const hit = findInDir(part, names)
|
||||
if (hit) return hit
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析单个工具:用户指定路径 → toolkit → binDirs → PATH。
|
||||
* @returns `{ id, label, path, source: 'config'|'toolkit'|'binDir'|'path'|'missing', names }`
|
||||
*/
|
||||
export function resolveTool(id, options = {}) {
|
||||
const root = options.root || redteamRoot()
|
||||
const cfg = options.config || loadPlatformConfig(root)
|
||||
const env = options.env || process.env
|
||||
const def = TOOL_CATALOG.find((t) => t.id === id)
|
||||
if (!def) {
|
||||
return { id, label: id, path: null, source: 'missing', names: [] }
|
||||
}
|
||||
const configured = cfg.tools && typeof cfg.tools[id] === 'string' ? cfg.tools[id].trim() : ''
|
||||
if (configured) {
|
||||
const abs = isAbsolute(configured) ? configured : resolve(configured)
|
||||
if (existsSync(abs)) {
|
||||
return { id, label: def.label, path: abs, source: 'config', names: def.names }
|
||||
}
|
||||
return { id, label: def.label, path: null, source: 'missing', names: def.names, configured: abs, note: 'config 路径不存在:' + abs }
|
||||
}
|
||||
const toolkit = toolkitDirOf(cfg, root)
|
||||
const fromToolkit = findInDir(toolkit, def.names)
|
||||
if (fromToolkit) return { id, label: def.label, path: fromToolkit, source: 'toolkit', names: def.names }
|
||||
|
||||
for (const dir of cfg.binDirs || []) {
|
||||
const hit = findInDir(dir, def.names)
|
||||
if (hit) return { id, label: def.label, path: hit, source: 'binDir', names: def.names, binDir: dir }
|
||||
}
|
||||
|
||||
const fromPath = findOnPath(def.names, env)
|
||||
if (fromPath) return { id, label: def.label, path: fromPath, source: 'path', names: def.names }
|
||||
|
||||
return { id, label: def.label, path: null, source: 'missing', names: def.names }
|
||||
}
|
||||
|
||||
export function resolveAllTools(options = {}) {
|
||||
return TOOL_CATALOG.map((t) => resolveTool(t.id, options))
|
||||
}
|
||||
|
||||
/**
|
||||
* 把配置里的 env 合并进 effectiveEnv(进程 / .env 已有的优先,不覆盖)。
|
||||
*/
|
||||
export function mergeConfigEnv(effectiveEnv, cfg) {
|
||||
const out = Object.assign({}, effectiveEnv || {})
|
||||
const env = (cfg && cfg.env) || {}
|
||||
for (const [k, v] of Object.entries(env)) {
|
||||
if (typeof v !== 'string') continue
|
||||
const val = v.trim()
|
||||
if (val === '') continue
|
||||
if (out[k] === undefined || out[k] === '') out[k] = val
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* 平台摘要:给面板与 preflight 用。
|
||||
*/
|
||||
export function platformSummary(root) {
|
||||
const cfg = loadPlatformConfig(root)
|
||||
const win = isWinLike(cfg)
|
||||
const tools = resolveAllTools({ root, config: cfg })
|
||||
const found = tools.filter((t) => t.path)
|
||||
const missing = tools.filter((t) => !t.path)
|
||||
const toolkit = toolkitDirOf(cfg, root)
|
||||
const nuclei = nucleiTemplatesDirOf(cfg, root)
|
||||
|| (existsSync(join(toolkit, 'nuclei-templates')) ? join(toolkit, 'nuclei-templates') : null)
|
||||
const adapt = envAdaptStatus(root)
|
||||
return {
|
||||
ok: true,
|
||||
config: cfg,
|
||||
runtime: {
|
||||
nodePlatform: osPlatform(),
|
||||
effective: win ? 'windows' : 'linux',
|
||||
windows: win,
|
||||
sep,
|
||||
},
|
||||
toolkitDir: toolkit,
|
||||
toolkitExists: existsSync(toolkit),
|
||||
nucleiTemplatesDir: nuclei,
|
||||
tools: {
|
||||
total: tools.length,
|
||||
found: found.length,
|
||||
missing: missing.length,
|
||||
items: tools,
|
||||
},
|
||||
adapt,
|
||||
hint: adapt.kali
|
||||
? '已检测到 Kali(或同系演练机):工具走 PATH/默认查找,可直接开红队会话。'
|
||||
: (win
|
||||
? '当前按 Windows 适配:建议在 Kali 虚拟机里跑,或在本页填工具路径/整包文件夹自动分配。出网代理看下方「出网状态」。'
|
||||
: '当前按 Linux 适配:可用 setup.sh 装工具箱,也可在本页手填或整包文件夹自动分配。出网代理看下方「出网状态」。'),
|
||||
egress: {
|
||||
http_proxy: process.env.HTTP_PROXY || process.env.http_proxy || '',
|
||||
https_proxy: process.env.HTTPS_PROXY || process.env.https_proxy || '',
|
||||
all_proxy: process.env.ALL_PROXY || process.env.all_proxy || '',
|
||||
no_proxy: process.env.NO_PROXY || process.env.no_proxy || '',
|
||||
note: '只读进程环境;改系统/终端代理后需重启宿主。命令级代理请用技能 cn-proxy-pool,不改本机网络配置。',
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** 探测本机是否 Kali / 同系演练发行版。 */
|
||||
export function detectKali() {
|
||||
if (osPlatform() !== 'linux') {
|
||||
return { kali: false, source: null, detail: '非 Linux 宿主' }
|
||||
}
|
||||
try {
|
||||
const text = readFileSync('/etc/os-release', 'utf8')
|
||||
if (/ID\s*=\s*"?kali"?/i.test(text) || /ID_LIKE\s*=[^\n]*kali/i.test(text) || /NAME\s*=\s*".*Kali/i.test(text)) {
|
||||
return { kali: true, source: 'os-release', detail: 'os-release 标明 Kali' }
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
const markers = [
|
||||
'/usr/share/kali-menu',
|
||||
'/etc/apt/sources.list.d/kali.list',
|
||||
'/usr/share/kali-defaults',
|
||||
]
|
||||
for (const p of markers) {
|
||||
if (existsSync(p)) return { kali: true, source: 'paths', detail: p }
|
||||
}
|
||||
return { kali: false, source: null, detail: null }
|
||||
}
|
||||
|
||||
const NAME_TO_IDS = (() => {
|
||||
const map = new Map()
|
||||
for (const t of TOOL_CATALOG) {
|
||||
for (const name of t.names) {
|
||||
const key = String(name).toLowerCase()
|
||||
if (!map.has(key)) map.set(key, [])
|
||||
map.get(key).push(t.id)
|
||||
}
|
||||
}
|
||||
return map
|
||||
})()
|
||||
|
||||
/**
|
||||
* 在文件夹内递归扫工具名(限深度),返回 id → 绝对路径。
|
||||
*/
|
||||
export function scanFolderForTools(dir, options = {}) {
|
||||
const maxDepth = Math.min(Math.max(Number(options.maxDepth) || 4, 1), 6)
|
||||
const maxFiles = Math.min(Math.max(Number(options.maxFiles) || 8000, 100), 20000)
|
||||
const root = resolve(String(dir || '').trim())
|
||||
const assigned = {}
|
||||
const hits = []
|
||||
if (!root || !existsSync(root)) {
|
||||
return { ok: false, error: '目录不存在:' + root, assigned, hits }
|
||||
}
|
||||
let st
|
||||
try { st = statSync(root) } catch {
|
||||
return { ok: false, error: '无法读取目录:' + root, assigned, hits }
|
||||
}
|
||||
if (!st.isDirectory()) {
|
||||
return { ok: false, error: '不是文件夹:' + root, assigned, hits }
|
||||
}
|
||||
|
||||
let scanned = 0
|
||||
const walk = (base, depth) => {
|
||||
if (scanned >= maxFiles || depth > maxDepth) return
|
||||
let entries
|
||||
try { entries = readdirSync(base, { withFileTypes: true }) } catch { return }
|
||||
for (const ent of entries) {
|
||||
if (scanned >= maxFiles) break
|
||||
const name = ent.name
|
||||
if (!name || name === '.' || name === '..') continue
|
||||
if (name.startsWith('.') || name === 'node_modules' || name === '.git') continue
|
||||
const full = join(base, name)
|
||||
let isDir = false
|
||||
let isFile = false
|
||||
try {
|
||||
if (typeof ent.isDirectory === 'function') {
|
||||
isDir = ent.isDirectory()
|
||||
isFile = ent.isFile()
|
||||
} else {
|
||||
const s = statSync(full)
|
||||
isDir = s.isDirectory()
|
||||
isFile = s.isFile()
|
||||
}
|
||||
} catch { continue }
|
||||
if (isDir) {
|
||||
walk(full, depth + 1)
|
||||
continue
|
||||
}
|
||||
if (!isFile) continue
|
||||
scanned += 1
|
||||
const key = name.toLowerCase()
|
||||
const ids = NAME_TO_IDS.get(key)
|
||||
if (!ids) continue
|
||||
for (const id of ids) {
|
||||
if (assigned[id]) continue
|
||||
assigned[id] = full
|
||||
hits.push({ id, path: full, name })
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(root, 0)
|
||||
|
||||
/* nuclei-templates 目录顺带认一下 */
|
||||
let nucleiTemplatesDir = ''
|
||||
const tryNuclei = [
|
||||
join(root, 'nuclei-templates'),
|
||||
join(root, 'nuclei', 'templates'),
|
||||
]
|
||||
for (const p of tryNuclei) {
|
||||
if (existsSync(p)) {
|
||||
try {
|
||||
if (statSync(p).isDirectory()) { nucleiTemplatesDir = p; break }
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
dir: root,
|
||||
scanned,
|
||||
assigned,
|
||||
hits,
|
||||
nucleiTemplatesDir,
|
||||
assignedCount: Object.keys(assigned).length,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 把整包工具文件夹写入 config:toolkitDir + 匹配到的 tools 路径。
|
||||
*/
|
||||
export function assignToolkitFolder(dir, root) {
|
||||
const scan = scanFolderForTools(dir)
|
||||
if (!scan.ok) return Object.assign({ ok: false }, scan)
|
||||
const prev = loadPlatformConfig(root)
|
||||
const tools = Object.assign({}, prev.tools || {})
|
||||
for (const [id, path] of Object.entries(scan.assigned)) {
|
||||
tools[id] = path
|
||||
}
|
||||
const binDirs = Array.isArray(prev.binDirs) ? prev.binDirs.slice() : []
|
||||
if (!binDirs.includes(scan.dir)) binDirs.unshift(scan.dir)
|
||||
const patch = {
|
||||
toolkitDir: scan.dir,
|
||||
binDirs,
|
||||
tools,
|
||||
envAdaptConfigured: true,
|
||||
envAdaptSkip: false,
|
||||
}
|
||||
if (scan.nucleiTemplatesDir) patch.nucleiTemplatesDir = scan.nucleiTemplatesDir
|
||||
const cfg = savePlatformConfig(patch, root)
|
||||
const summary = platformSummary(root)
|
||||
return {
|
||||
ok: true,
|
||||
assigned: scan.assigned,
|
||||
assignedCount: scan.assignedCount,
|
||||
hits: scan.hits,
|
||||
scanned: scan.scanned,
|
||||
dir: scan.dir,
|
||||
nucleiTemplatesDir: scan.nucleiTemplatesDir || null,
|
||||
config: cfg,
|
||||
tools: summary.tools,
|
||||
adapt: summary.adapt,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 红队发送前环境门禁状态。
|
||||
* Kali → 直接就绪;否则需配置/已分配工具,或用户确认跳过。
|
||||
*/
|
||||
export function envAdaptStatus(root) {
|
||||
const cfg = loadPlatformConfig(root)
|
||||
const kaliInfo = detectKali()
|
||||
const tools = resolveAllTools({ root, config: cfg })
|
||||
const foundItems = tools.filter((t) => t.path)
|
||||
const missingItems = tools.filter((t) => !t.path)
|
||||
const found = foundItems.length
|
||||
const skipped = !!cfg.envAdaptSkip
|
||||
const configured = !!cfg.envAdaptConfigured
|
||||
|| !!(cfg.toolkitDir && String(cfg.toolkitDir).trim())
|
||||
|| (cfg.binDirs && cfg.binDirs.length > 0)
|
||||
|| TOOL_CATALOG.some((t) => cfg.tools && cfg.tools[t.id] && String(cfg.tools[t.id]).trim())
|
||||
|
||||
let reason = 'need-config'
|
||||
let ready = false
|
||||
let message = ''
|
||||
|
||||
if (kaliInfo.kali) {
|
||||
ready = true
|
||||
reason = 'kali'
|
||||
message = '已检测到 Kali,默认直接使用本机工具(PATH / 默认查找)。'
|
||||
} else if (skipped) {
|
||||
ready = true
|
||||
reason = 'skipped'
|
||||
message = '你已确认暂不配置工具,可正常对话(扫描类技能可能不可用)。'
|
||||
} else if (found >= 2 || (configured && found >= 1)) {
|
||||
ready = true
|
||||
reason = configured ? 'configured' : 'tools-found'
|
||||
message = configured
|
||||
? ('已配置工具路径,当前找到 ' + found + '/' + tools.length + ' 个。')
|
||||
: ('本机已能找到 ' + found + ' 个工具,视为可用。')
|
||||
} else {
|
||||
ready = false
|
||||
reason = 'need-config'
|
||||
message = '未检测到 Kali,且工具未配置。请打开 dsh-purge → 环境适配,填写路径或选整包文件夹自动分配;也可确认暂不配置后继续对话。'
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
ready,
|
||||
reason,
|
||||
message,
|
||||
kali: !!kaliInfo.kali,
|
||||
kaliSource: kaliInfo.source,
|
||||
kaliDetail: kaliInfo.detail,
|
||||
skipped,
|
||||
configured,
|
||||
found,
|
||||
missing: missingItems.length,
|
||||
total: tools.length,
|
||||
foundIds: foundItems.map((t) => t.id),
|
||||
missingIds: missingItems.map((t) => t.id),
|
||||
}
|
||||
}
|
||||
|
||||
export function markEnvAdaptSkip(root, skip = true) {
|
||||
savePlatformConfig({ envAdaptSkip: !!skip }, root)
|
||||
return envAdaptStatus(root)
|
||||
}
|
||||
|
||||
export default {
|
||||
TOOL_CATALOG,
|
||||
configPathOf,
|
||||
redteamRoot,
|
||||
loadPlatformConfig,
|
||||
savePlatformConfig,
|
||||
resolveTool,
|
||||
resolveAllTools,
|
||||
platformSummary,
|
||||
mergeConfigEnv,
|
||||
toolkitDirOf,
|
||||
nucleiTemplatesDirOf,
|
||||
detectKali,
|
||||
scanFolderForTools,
|
||||
assignToolkitFolder,
|
||||
envAdaptStatus,
|
||||
markEnvAdaptSkip,
|
||||
}
|
||||
@@ -0,0 +1,444 @@
|
||||
/**
|
||||
* Agent-preset composition reader (adapted from dsh-liangshen).
|
||||
* Parses presets/redteam/{agent.cordis.yml,preset.yml} for registry.register().
|
||||
*/
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join, resolve } from "node:path";
|
||||
|
||||
/**
|
||||
* The redteam preset composition reader: just enough YAML to turn the
|
||||
* bundled `presets/redteam/agent.cordis.yml` — and the flat `preset.yml`
|
||||
* display map beside it — into the declaration the agent-preset registry takes.
|
||||
*
|
||||
* Under 0.1.7 a preset is an ordinary registry declaration instead of a
|
||||
* directory the harness discovers, so this plugin hands `ctx.agentPresets` the
|
||||
* rows of its OWN composition. No YAML package is resolvable from this package
|
||||
* and the harness's reader is not importable from here, so the subset is owned
|
||||
* here; the shipped composition is the only file it must read, and tests fence
|
||||
* it against that whole file. Supported: block maps and sequences, quoted and
|
||||
* plain scalars, single-line flow sequences, literal and folded block scalars,
|
||||
* comments, and `!!js` expressions preserved as data (`{ __jsExpr }`, the shape
|
||||
* the Loader itself hands a plugin).
|
||||
*
|
||||
* Fail-closed: a construct outside the subset — anchors, aliases, tags other
|
||||
* than `!!js`, nested flow collections, multiple documents, tabs — raises
|
||||
* {@link CompositionError} rather than being guessed at, so an unreadable
|
||||
* composition is refused instead of half-declared.
|
||||
*
|
||||
* Relative module names (`name: ./minimal-prompt.mjs`) are resolved against
|
||||
* the preset directory handed to {@link readCompositionRows} and emitted as
|
||||
* file URLs: the registry mounts a declaration under the DECLARING LOADER's
|
||||
* base, so a relative name would otherwise be resolved outside this package.
|
||||
* @module dsh-purge/redteam/preset-composition
|
||||
*/
|
||||
/** A construct outside the supported subset, or malformed YAML. */
|
||||
var CompositionError = class extends Error {
|
||||
constructor(message) {
|
||||
super(message);
|
||||
this.name = "CompositionError";
|
||||
}
|
||||
};
|
||||
const BLANK_OR_COMMENT_RE = /^[ \t]*(?:#.*)?$/;
|
||||
const INTEGER_RE = /^[+-]?\d+$/;
|
||||
const FLOAT_RE = /^[+-]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][+-]?\d+)?$/;
|
||||
/** The indentation width of one line (its leading spaces). */
|
||||
function indentOf(line) {
|
||||
const match = /^ */.exec(line);
|
||||
return match === null ? 0 : match[0].length;
|
||||
}
|
||||
/**
|
||||
* The indentation of one structurally significant line. A tab there is
|
||||
* forbidden by YAML; block-scalar content is verbatim and never measured here.
|
||||
*/
|
||||
function significantIndent(line, lineNumber) {
|
||||
const leading = /^[ \t]*/.exec(line)?.[0] ?? "";
|
||||
if (leading.includes(" ")) throw new CompositionError(`line ${String(lineNumber)}: tabs must not be used for indentation`);
|
||||
return leading.length;
|
||||
}
|
||||
/** Advance past blank and comment-only lines. */
|
||||
function skipInsignificant(cursor) {
|
||||
while (cursor.index < cursor.lines.length && BLANK_OR_COMMENT_RE.test(cursor.lines[cursor.index] ?? "")) cursor.index += 1;
|
||||
}
|
||||
/** Whether a line at `indent` opens a block sequence entry. */
|
||||
function isSequenceEntry(line, indent) {
|
||||
if (line[indent] !== "-") return false;
|
||||
return line.length === indent + 1 || line[indent + 1] === " ";
|
||||
}
|
||||
/** The index of the quote that closes a quoted scalar starting at index 0. */
|
||||
function closingQuote(text) {
|
||||
const quote = text[0];
|
||||
for (let index = 1; index < text.length; index += 1) {
|
||||
const char = text[index];
|
||||
if (quote === "\"" && char === "\\") {
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (quote === "'" && char === "'" && text[index + 1] === "'") {
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (char === quote) return index;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
/** Resolve one quoted scalar, or return the text unchanged when unquoted. */
|
||||
function unquote(text) {
|
||||
const trimmed = text.trim();
|
||||
if (trimmed.startsWith("\"")) {
|
||||
const end = closingQuote(trimmed);
|
||||
if (end !== trimmed.length - 1) throw new CompositionError(`unterminated double-quoted scalar: ${trimmed}`);
|
||||
return trimmed.slice(1, end).replace(/\\(u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|.)/g, (_, escape) => {
|
||||
switch (escape[0]) {
|
||||
case "n": return "\n";
|
||||
case "t": return " ";
|
||||
case "r": return "\r";
|
||||
case "0": return "\0";
|
||||
case "u":
|
||||
case "x": return String.fromCharCode(Number.parseInt(escape.slice(1), 16));
|
||||
default: return escape;
|
||||
}
|
||||
});
|
||||
}
|
||||
if (trimmed.startsWith("'")) {
|
||||
const end = closingQuote(trimmed);
|
||||
if (end !== trimmed.length - 1) throw new CompositionError(`unterminated single-quoted scalar: ${trimmed}`);
|
||||
return trimmed.slice(1, end).replaceAll("''", "'");
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
/** Split one block-map line into its key and the raw text after the colon. */
|
||||
function matchKeyEntry(text) {
|
||||
if (text.startsWith("'") || text.startsWith("\"")) {
|
||||
const end = closingQuote(text);
|
||||
if (end === -1) return void 0;
|
||||
const after = text.slice(end + 1).trimStart();
|
||||
if (!after.startsWith(":")) return void 0;
|
||||
return {
|
||||
key: unquote(text.slice(0, end + 1)),
|
||||
rest: after.slice(1).trim()
|
||||
};
|
||||
}
|
||||
for (let index = 0; index < text.length; index += 1) {
|
||||
const char = text[index];
|
||||
if (char === "#" && index > 0 && text[index - 1] === " ") break;
|
||||
if (char === ":" && (index + 1 === text.length || text[index + 1] === " ")) return {
|
||||
key: text.slice(0, index),
|
||||
rest: text.slice(index + 1).trim()
|
||||
};
|
||||
}
|
||||
}
|
||||
/** Resolve a plain scalar to the value YAML's JSON schema would produce. */
|
||||
function plainScalar(text) {
|
||||
const comment = text.indexOf(" #");
|
||||
const value = (comment === -1 ? text : text.slice(0, comment)).trim();
|
||||
if (value === "" || value === "~" || value === "null" || value === "Null" || value === "NULL") return null;
|
||||
if (value === "true" || value === "True" || value === "TRUE") return true;
|
||||
if (value === "false" || value === "False" || value === "FALSE") return false;
|
||||
if (INTEGER_RE.test(value)) return Number(value);
|
||||
if (FLOAT_RE.test(value)) return Number(value);
|
||||
return value;
|
||||
}
|
||||
/**
|
||||
* Read one single-line flow sequence (`['mcp__*']`) into its scalar items.
|
||||
* Nested flow collections are outside the subset and refused.
|
||||
*/
|
||||
function flowSequence(text) {
|
||||
const end = text.lastIndexOf("]");
|
||||
if (end === -1) throw new CompositionError(`unterminated flow sequence: ${text}`);
|
||||
const tail = text.slice(end + 1).trim();
|
||||
if (tail !== "" && !tail.startsWith("#")) throw new CompositionError(`unexpected content after a flow sequence: ${tail}`);
|
||||
const body = text.slice(1, end);
|
||||
if (body.trim() === "") return [];
|
||||
const items = [];
|
||||
for (const raw of body.split(",")) {
|
||||
const item = raw.trim();
|
||||
if (item === "") throw new CompositionError(`empty item in a flow sequence: ${text}`);
|
||||
if (item.startsWith("[") || item.startsWith("{")) throw new CompositionError(`nested flow collections are not supported: ${item}`);
|
||||
items.push(inlineScalar(item));
|
||||
}
|
||||
return items;
|
||||
}
|
||||
/** Resolve the text that follows a colon or a dash on one line. */
|
||||
function inlineScalar(text) {
|
||||
const value = text.trim();
|
||||
if (value.startsWith("!!js")) {
|
||||
const expression = value.slice(4).trim();
|
||||
if (expression === "") throw new CompositionError("!!js requires an expression");
|
||||
return { __jsExpr: unquote(expression) };
|
||||
}
|
||||
if (value.startsWith("'") || value.startsWith("\"")) {
|
||||
const end = closingQuote(value);
|
||||
if (end === -1) throw new CompositionError(`unterminated quoted scalar: ${value}`);
|
||||
const tail = value.slice(end + 1).trim();
|
||||
if (tail !== "" && !tail.startsWith("#")) throw new CompositionError(`unexpected content after a quoted scalar: ${tail}`);
|
||||
return unquote(value.slice(0, end + 1));
|
||||
}
|
||||
if (value.startsWith("[")) return flowSequence(value);
|
||||
if (value.startsWith("{")) throw new CompositionError(`flow mappings are not supported: ${value}`);
|
||||
if (value.startsWith("|") || value.startsWith(">")) throw new CompositionError(`block scalars need their own line: ${value}`);
|
||||
if (value.startsWith("!") || value.startsWith("&") || value.startsWith("*")) throw new CompositionError(`unsupported YAML node: ${value}`);
|
||||
return plainScalar(value);
|
||||
}
|
||||
/**
|
||||
* Read one literal (`|`) or folded (`>`) block scalar, consuming its lines.
|
||||
* @param cursor - line cursor positioned on the line that follows the header.
|
||||
* @param parentIndent - indentation of the node that owns the scalar.
|
||||
* @param header - the header text (`|-`, `>+2`, ...) possibly with a comment.
|
||||
* @returns the scalar text after indentation stripping and chomping.
|
||||
*/
|
||||
function blockScalar(cursor, parentIndent, header) {
|
||||
const style = header[0];
|
||||
const indicators = header.slice(1).split("#")[0]?.trim() ?? "";
|
||||
let explicitIndent;
|
||||
let chomp = "clip";
|
||||
for (const char of indicators) if (char === "-") chomp = "strip";
|
||||
else if (char === "+") chomp = "keep";
|
||||
else if (char >= "1" && char <= "9") explicitIndent = Number(char);
|
||||
else throw new CompositionError(`unsupported block scalar header: ${header}`);
|
||||
const body = [];
|
||||
let blockIndent;
|
||||
let trailing = 0;
|
||||
while (cursor.index < cursor.lines.length) {
|
||||
const line = cursor.lines[cursor.index] ?? "";
|
||||
if (line.trim() === "") {
|
||||
body.push("");
|
||||
trailing += 1;
|
||||
cursor.index += 1;
|
||||
continue;
|
||||
}
|
||||
const indent = indentOf(line);
|
||||
if (indent <= parentIndent) break;
|
||||
if (blockIndent === void 0) blockIndent = explicitIndent === void 0 ? indent : parentIndent + explicitIndent;
|
||||
if (indent < blockIndent) break;
|
||||
body.push(line.slice(blockIndent));
|
||||
trailing = 0;
|
||||
cursor.index += 1;
|
||||
}
|
||||
const lines = body.slice(0, body.length - trailing);
|
||||
if (style === ">") {
|
||||
let folded = "";
|
||||
let blank = 0;
|
||||
let started = false;
|
||||
for (const line of lines) {
|
||||
if (line === "") {
|
||||
blank += 1;
|
||||
continue;
|
||||
}
|
||||
if (!started) {
|
||||
folded = line;
|
||||
started = true;
|
||||
blank = 0;
|
||||
continue;
|
||||
}
|
||||
folded += blank === 0 ? " " + line : "\n".repeat(blank) + line;
|
||||
blank = 0;
|
||||
}
|
||||
if (chomp === "strip") return folded;
|
||||
if (chomp === "keep") return folded + "\n".repeat(trailing + 1);
|
||||
return folded === "" ? "" : folded + "\n";
|
||||
}
|
||||
const text = lines.join("\n");
|
||||
if (chomp === "strip") return text;
|
||||
if (chomp === "keep") return text + "\n".repeat(trailing + 1);
|
||||
return text === "" ? "" : text + "\n";
|
||||
}
|
||||
/** Resolve the value of one entry whose line has already been consumed. */
|
||||
function parseValue(cursor, parentIndent, rest) {
|
||||
if (rest !== "") {
|
||||
if (rest.startsWith("|") || rest.startsWith(">")) return blockScalar(cursor, parentIndent, rest);
|
||||
return inlineScalar(rest);
|
||||
}
|
||||
skipInsignificant(cursor);
|
||||
const line = cursor.lines[cursor.index];
|
||||
if (line === void 0 || indentOf(line) <= parentIndent) return null;
|
||||
return parseNode(cursor, parentIndent + 1);
|
||||
}
|
||||
/** Parse a block map whose keys sit at exactly `indent`. */
|
||||
function parseMap(cursor, indent) {
|
||||
const map = {};
|
||||
while (true) {
|
||||
skipInsignificant(cursor);
|
||||
const line = cursor.lines[cursor.index];
|
||||
if (line === void 0) break;
|
||||
const lineIndent = significantIndent(line, cursor.index + 1);
|
||||
if (lineIndent < indent) break;
|
||||
if (lineIndent > indent) throw new CompositionError(`line ${String(cursor.index + 1)}: unexpected indentation`);
|
||||
if (isSequenceEntry(line, indent)) break;
|
||||
const entry = matchKeyEntry(line.slice(indent));
|
||||
if (entry === void 0) throw new CompositionError(`line ${String(cursor.index + 1)}: expected "key: value", got "${line.trim()}"`);
|
||||
if (Object.hasOwn(map, entry.key)) throw new CompositionError(`line ${String(cursor.index + 1)}: duplicate key "${entry.key}"`);
|
||||
cursor.index += 1;
|
||||
map[entry.key] = parseValue(cursor, indent, entry.rest);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
/** Parse a block sequence whose dashes sit at exactly `indent`. */
|
||||
function parseSequence(cursor, indent) {
|
||||
const items = [];
|
||||
while (true) {
|
||||
skipInsignificant(cursor);
|
||||
const line = cursor.lines[cursor.index];
|
||||
if (line === void 0) break;
|
||||
if (significantIndent(line, cursor.index + 1) !== indent || !isSequenceEntry(line, indent)) break;
|
||||
const rest = line.slice(indent + 1);
|
||||
const content = rest.trimStart();
|
||||
if (content === "") {
|
||||
cursor.index += 1;
|
||||
skipInsignificant(cursor);
|
||||
const nested = cursor.lines[cursor.index];
|
||||
const nestedIndent = nested === void 0 ? -1 : significantIndent(nested, cursor.index + 1);
|
||||
items.push(nestedIndent <= indent ? null : parseNode(cursor, indent + 1));
|
||||
continue;
|
||||
}
|
||||
const contentIndent = indent + 1 + (rest.length - content.length);
|
||||
if (matchKeyEntry(content) !== void 0) {
|
||||
cursor.lines[cursor.index] = " ".repeat(contentIndent) + content;
|
||||
items.push(parseMap(cursor, contentIndent));
|
||||
continue;
|
||||
}
|
||||
cursor.index += 1;
|
||||
items.push(parseValue(cursor, indent, content));
|
||||
}
|
||||
return items;
|
||||
}
|
||||
/** Parse the block node that starts at the cursor. */
|
||||
function parseNode(cursor, minIndent) {
|
||||
skipInsignificant(cursor);
|
||||
const line = cursor.lines[cursor.index];
|
||||
if (line === void 0) return null;
|
||||
const indent = significantIndent(line, cursor.index + 1);
|
||||
if (indent < minIndent) return null;
|
||||
return isSequenceEntry(line, indent) ? parseSequence(cursor, indent) : parseMap(cursor, indent);
|
||||
}
|
||||
/** Read one cordis YAML document (an entry list, or the flat map of `preset.yml`). */
|
||||
function readYaml(text) {
|
||||
const cursor = {
|
||||
lines: (text.startsWith("") ? text.slice(1) : text).replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n"),
|
||||
index: 0
|
||||
};
|
||||
const value = parseNode(cursor, 0);
|
||||
skipInsignificant(cursor);
|
||||
const extra = cursor.lines[cursor.index];
|
||||
if (extra !== void 0) throw new CompositionError(`line ${String(cursor.index + 1)}: unexpected content "${extra.trim()}"`);
|
||||
return value;
|
||||
}
|
||||
/** Whether a parsed value is one composition row (a map with a string `name`). */
|
||||
function asRow(value, at) {
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new CompositionError(`${at} is not a plugin row (expected a map with a "name")`);
|
||||
const row = value;
|
||||
if (typeof row.name !== "string" || row.name === "") throw new CompositionError(`${at} names no plugin (a "name" string is required)`);
|
||||
return row;
|
||||
}
|
||||
/**
|
||||
* Rewrite the relative module names of one row list, recursively through the
|
||||
* nested entry lists of group rows, into absolute file URLs.
|
||||
*/
|
||||
function absolutizeRows(rows, baseDir, at = "row") {
|
||||
return rows.map((row, index) => {
|
||||
const label = `${at} ${String(index + 1)}`;
|
||||
const checked = asRow(row, label);
|
||||
const name = checked.name ?? "";
|
||||
const out = { ...checked };
|
||||
if (name.startsWith("./") || name.startsWith("../")) out.name = pathToFileURL(resolve(baseDir, name)).href;
|
||||
if (checked.group === true) {
|
||||
if (!Array.isArray(checked.config)) throw new CompositionError(`group ${label} must hold a list of plugin rows`);
|
||||
out.config = absolutizeRows(checked.config, baseDir, `${label} group`);
|
||||
}
|
||||
return out;
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Read the child plugin rows of one `agent.cordis.yml`.
|
||||
* @param text - the raw composition document.
|
||||
* @param baseDir - directory a relative row `name` resolves against (the preset's own directory).
|
||||
* @returns the row list to hand the registry, relative names resolved to file URLs.
|
||||
* @throws {CompositionError} on malformed YAML or a row the registry would reject.
|
||||
*/
|
||||
function readCompositionRows(text, baseDir) {
|
||||
const value = readYaml(text);
|
||||
if (!Array.isArray(value)) throw new CompositionError("agent.cordis.yml must be a top-level list of plugin rows");
|
||||
return absolutizeRows(value, baseDir);
|
||||
}
|
||||
/** Read the single-line display scalars of one `preset.yml`. */
|
||||
function readPresetMetadata(text) {
|
||||
const value = readYaml(text);
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new CompositionError("preset.yml must be a mapping");
|
||||
const record = value;
|
||||
const metadata = {};
|
||||
for (const key of ["name", "description"]) {
|
||||
const field = record[key];
|
||||
if (field === void 0 || field === null) continue;
|
||||
if (typeof field !== "string" || field.includes("\n")) throw new CompositionError(`preset.yml: ${key} must be a single-line string`);
|
||||
metadata[key] = field;
|
||||
}
|
||||
const order = record["order"];
|
||||
if (order !== void 0 && order !== null) {
|
||||
if (typeof order !== "number" || !Number.isFinite(order)) throw new CompositionError("preset.yml: order must be a number");
|
||||
metadata.order = order;
|
||||
}
|
||||
return metadata;
|
||||
}
|
||||
/**
|
||||
* Build the registry declaration of one preset directory.
|
||||
* @param id - preset identity the roster keys the declaration by.
|
||||
* @param dir - absolute preset directory holding `agent.cordis.yml` and `preset.yml`.
|
||||
* @returns the definition to submit to `ctx.agentPresets.register`.
|
||||
* @throws {CompositionError} when either file is missing, unreadable, or unparsable.
|
||||
*/
|
||||
function readPresetDefinition(id, dir) {
|
||||
const read = (name) => {
|
||||
try {
|
||||
return readFileSync(join(dir, name), "utf8");
|
||||
} catch (error) {
|
||||
throw new CompositionError(`${name} is unreadable: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
};
|
||||
return {
|
||||
id,
|
||||
...readPresetMetadata(read("preset.yml")),
|
||||
plugins: readCompositionRows(read("agent.cordis.yml"), dir)
|
||||
};
|
||||
}
|
||||
/** The overlay table: settings field to composition row and config key. */
|
||||
function overrideTargets(overrides) {
|
||||
return [["tool-catalog", { ...overrides.presentation === void 0 ? {} : { presentation: overrides.presentation } }], ["guard", {
|
||||
...overrides.guardEnabled === void 0 ? {} : { enabled: overrides.guardEnabled },
|
||||
...overrides.guardSensitivity === void 0 ? {} : { sensitivity: overrides.guardSensitivity },
|
||||
...overrides.guardStallReasoningChars === void 0 ? {} : { stallReasoningChars: overrides.guardStallReasoningChars },
|
||||
...overrides.guardGlobalStallCap === void 0 ? {} : { globalStallCap: overrides.guardGlobalStallCap },
|
||||
...overrides.guardEchoFailures === void 0 ? {} : { echoFailures: overrides.guardEchoFailures }
|
||||
}]];
|
||||
}
|
||||
/**
|
||||
* Apply the settings overlay to one parsed row list.
|
||||
*
|
||||
* Rows are addressed by their `id`, and only a row the composition actually
|
||||
* carries is touched: the overlay narrows the shipped configuration, it never
|
||||
* invents a mount the preset did not have. The shipped composition declares
|
||||
* every key the overlay writes, so leaving a key absent only matters for a
|
||||
* composition that dropped it.
|
||||
* @param rows - the parsed composition rows.
|
||||
* @param overrides - the operator's settings-surface choices.
|
||||
* @returns a new row list with the overlay applied.
|
||||
*/
|
||||
function applyPresetOverrides(rows, overrides) {
|
||||
const table = overrideTargets(overrides);
|
||||
return rows.map((row) => {
|
||||
const target = table.find(([id]) => id === row.id);
|
||||
if (target === void 0) return row;
|
||||
const [, patch] = target;
|
||||
if (Object.keys(patch).length === 0) return row;
|
||||
const config = row.config;
|
||||
if (typeof config !== "object" || config === null || Array.isArray(config)) return row;
|
||||
return {
|
||||
...row,
|
||||
config: {
|
||||
...config,
|
||||
...patch
|
||||
}
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export { CompositionError, readCompositionRows, readPresetDefinition };
|
||||
@@ -0,0 +1,209 @@
|
||||
/**
|
||||
* 报告复现工具(纯函数,零依赖)。
|
||||
*
|
||||
* 目标:让报告里**每一条得分**都有"可照做"的复现入口,而不是只有一句
|
||||
* "没有原始请求记录"。数据其实都在库里(攻击步骤的 tool、目标 URL、证据文本),
|
||||
* 这里把它整理成 Yakit 能重放的报文与终端能直接跑的命令。
|
||||
*
|
||||
* 两条底线:
|
||||
* · **合成的东西必须标注来源**(`synthesized: true`)—— 推断出来的请求与真实抓包
|
||||
* 在可信度上不是一回事,报告里要能一眼分辨,不能让验收人把推断当实证。
|
||||
* · 合成只在"信息足够"时做:有 URL 或有明确的 curl/httpie 命令才合成,
|
||||
* 否则宁可留空并给补录指引,不编造。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 从 target 里解析出 scheme / host / port / path,用于补全合成请求。
|
||||
*
|
||||
* 必须显式处理 IPv6 的方括号写法:`http://[2001:db8::1]:8080/x` 里
|
||||
* "IPv6 地址内部的冒号" 与 "端口分隔冒号" 混在一起,用一条正则一起抓会错位
|
||||
* (实测把 host 解析成 `2001:db8:`、path 变成 `:8080/x`,
|
||||
* 合成出来的报文首行成了 `GET :8080/x HTTP/1.1`)。
|
||||
* 所以分两步:先按方括号取 authority,再按"最后一个冒号"剥端口。
|
||||
*
|
||||
* @param target - 形如 `http://h:8080/p` / `10.0.0.5:6379` / `[::1]:22` 的字符串。
|
||||
* @returns `{ scheme, host, port, path, authority }`;解析不出返回 null。
|
||||
*/
|
||||
function parseTarget(target) {
|
||||
const t = String(target || '').trim()
|
||||
if (t === '') return null
|
||||
const url = /^([a-z][a-z0-9+.-]*):\/\/([^/?#\s]+)([^?#\s]*)?/i.exec(t)
|
||||
if (url !== null) {
|
||||
const scheme = url[1].toLowerCase()
|
||||
const authority = url[2]
|
||||
const path = url[3] && url[3] !== '' ? url[3] : '/'
|
||||
/* 方括号 IPv6:[2001:db8::1]:8080 → host 2001:db8::1, port 8080 */
|
||||
const bracket = /^\[([^\]]+)\](?::(\d{1,5}))?$/.exec(authority)
|
||||
if (bracket !== null) {
|
||||
return {
|
||||
scheme, host: bracket[1], port: bracket[2] === undefined ? (scheme === 'https' ? 443 : 80) : Number(bracket[2]),
|
||||
path, authority, ipv6: true,
|
||||
}
|
||||
}
|
||||
const portMatch = /:(\d{1,5})$/.exec(authority)
|
||||
const host = portMatch === null ? authority : authority.slice(0, -portMatch[0].length)
|
||||
return {
|
||||
scheme, host,
|
||||
port: portMatch === null ? (scheme === 'https' ? 443 : 80) : Number(portMatch[1]),
|
||||
path, authority, ipv6: false,
|
||||
}
|
||||
}
|
||||
/* 没写协议:host[:port],同样要先认方括号 */
|
||||
const bracket = /^\[([^\]]+)\](?::(\d{1,5}))?$/.exec(t)
|
||||
if (bracket !== null) {
|
||||
return { scheme: null, host: bracket[1], port: bracket[2] === undefined ? null : Number(bracket[2]), path: null, authority: t, ipv6: true }
|
||||
}
|
||||
const bare = /^([^\s/?#:]+)(?::(\d{1,5}))?$/.exec(t)
|
||||
if (bare !== null) {
|
||||
return { scheme: null, host: bare[1], port: bare[2] === undefined ? null : Number(bare[2]), path: null, authority: t, ipv6: false }
|
||||
}
|
||||
/* 认不出的形态(带路径的裸主机等):只取第一段当主机,其余留给调用方 */
|
||||
const head = /^([^\s/?#]+)/.exec(t)
|
||||
if (head === null) return null
|
||||
return { scheme: null, host: head[1], port: null, path: null, authority: t, ipv6: false }
|
||||
}
|
||||
|
||||
/** 这条命令看起来是什么工具(用于决定能不能直接当复现命令用)。 */
|
||||
function commandKind(tool) {
|
||||
const t = String(tool || '').trim()
|
||||
if (t === '') return null
|
||||
if (/^curl\b/i.test(t)) return 'curl'
|
||||
if (/^http(ie| x)?\b/i.test(t) || /^http\s/i.test(t)) return 'httpie'
|
||||
if (/^(nuclei|ffuf|feroxbuster|gobuster|dirsearch|sqlmap|hydra|nmap|masscan|fscan|gogo)\b/i.test(t)) return 'scanner'
|
||||
if (/^(msfconsole|use\s|set\s)/i.test(t)) return 'msf'
|
||||
if (/^(python|python3|java|go run|node)\b/i.test(t)) return 'script'
|
||||
return 'other'
|
||||
}
|
||||
|
||||
/**
|
||||
* 从一条 curl 命令里抽出 URL 与方法(用于补一份可重放的 HTTP 报文)。
|
||||
* 只做保守解析:抽不出就返回 null,不猜。
|
||||
*/
|
||||
function parseCurl(tool) {
|
||||
const t = String(tool || '').trim()
|
||||
if (!/^curl\b/i.test(t)) return null
|
||||
const urlMatch = /(https?:\/\/[^\s'"]+)/i.exec(t)
|
||||
if (urlMatch === null) return null
|
||||
const methodMatch = /(?:-X|--request)\s+([A-Z]+)/i.exec(t)
|
||||
const dataMatch = /(?:-d|--data(?:-raw|-binary|-urlencode)?)\s+(?:'([^']*)'|"([^"]*)"|(\S+))/i.exec(t)
|
||||
const headerMatches = Array.from(t.matchAll(/(?:-H|--header)\s+(?:'([^']*)'|"([^"]*)")/gi))
|
||||
.map((m) => m[1] !== undefined ? m[1] : m[2])
|
||||
.filter((x) => typeof x === 'string' && x.includes(':'))
|
||||
const cookieMatch = /(?:-b|--cookie)\s+(?:'([^']*)'|"([^"]*)"|(\S+))/i.exec(t)
|
||||
const data = dataMatch === null ? null : (dataMatch[1] ?? dataMatch[2] ?? dataMatch[3] ?? null)
|
||||
const method = methodMatch !== null ? methodMatch[1].toUpperCase() : (data === null ? 'GET' : 'POST')
|
||||
return {
|
||||
url: urlMatch[1], method, data,
|
||||
headers: headerMatches,
|
||||
cookie: cookieMatch === null ? null : (cookieMatch[1] ?? cookieMatch[2] ?? cookieMatch[3] ?? null),
|
||||
insecure: /(^|\s)-k(\s|$)|--insecure/.test(t),
|
||||
followRedirect: /(^|\s)-L(\s|$)|--location/.test(t),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 合成一条可粘进 Yakit Repeater 的 HTTP 报文。
|
||||
* @param options - `{ url, method, data, headers, cookie, insecure, followRedirect }`
|
||||
* @returns 报文文本,信息不足时返回 null。
|
||||
*/
|
||||
function buildHttpRequest(options = {}) {
|
||||
const target = parseTarget(options.url)
|
||||
if (target === null) return null
|
||||
const scheme = target.scheme || 'http'
|
||||
/* IPv6 的 Host 头必须带方括号(RFC 3986),否则是非法头 */
|
||||
const hostText = target.ipv6 ? '[' + target.host + ']' : target.host
|
||||
const defaultPort = scheme === 'https' ? 443 : 80
|
||||
const hostHeader = (target.port !== null && target.port !== defaultPort)
|
||||
? hostText + ':' + target.port
|
||||
: hostText
|
||||
const path = options.path !== undefined && options.path !== null && options.path !== ''
|
||||
? options.path
|
||||
: (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 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)
|
||||
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')
|
||||
}
|
||||
if (body !== '' && !hasHeader('Content-Length')) headers.push('Content-Length: ' + Buffer.byteLength(body, 'utf8'))
|
||||
if (!hasHeader('Connection')) headers.push('Connection: close')
|
||||
return [lines[0], ...headers, '', body].join('\r\n')
|
||||
}
|
||||
|
||||
/**
|
||||
* 合成一条"可直接在终端跑"的复现命令。
|
||||
* 优先用真实的 curl 命令(原样保留,最可信);否则按 URL/方法拼一条。
|
||||
*/
|
||||
function buildCurlCommand(options = {}) {
|
||||
const raw = String(options.tool || '').trim()
|
||||
if (commandKind(raw) === 'curl') return raw /* 真实命令原样给出,别改 */
|
||||
const target = parseTarget(options.url)
|
||||
if (target === null) return null
|
||||
const scheme = target.scheme || 'http'
|
||||
const hostText = target.ipv6 ? '[' + target.host + ']' : target.host
|
||||
const defaultPort = scheme === 'https' ? 443 : 80
|
||||
const hostPart = target.port !== null && target.port !== defaultPort
|
||||
? hostText + ':' + target.port
|
||||
: hostText
|
||||
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, "'\\''") + "'")
|
||||
parts.push("'" + url + "'")
|
||||
return parts.join(' ')
|
||||
}
|
||||
|
||||
/**
|
||||
* 用本条得分**已经记录的信息**填充动作模板里的占位符。
|
||||
*
|
||||
* 为什么值得做:数据库/终端/隧道这类得分项的模板长这样
|
||||
* `mysql -h <host> -u <user> -p -e "..."`
|
||||
* 而这条得分自己就知道 host(target)与账号(挂载的凭据)。把已知部分填进去,
|
||||
* 一线拿到报告就能跑;剩下没填的占位符**保持原样并如实报告**,不猜。
|
||||
*
|
||||
* @param template - 含 `<占位符>` 的命令模板。
|
||||
* @param values - `{ host, port, user, pass, url, listen }` 等已知值。
|
||||
* @returns `{ cmd, filled, remaining }`:填充后的命令 + 填了哪些 + 还剩哪些占位符。
|
||||
*/
|
||||
function fillTemplate(template, values = {}) {
|
||||
let cmd = String(template || '')
|
||||
const filled = []
|
||||
const table = [
|
||||
[/<host>/gi, values.host],
|
||||
[/<ip>/gi, values.host],
|
||||
[/<port>/gi, values.port],
|
||||
[/<user(name)?>/gi, values.user],
|
||||
[/<账号>/g, values.user],
|
||||
[/<用户名>/g, values.user],
|
||||
[/<pass(word)?>/gi, values.pass],
|
||||
[/<口令>/g, values.pass],
|
||||
[/<密钥>/g, values.pass],
|
||||
[/<pwd>/gi, values.pass],
|
||||
[/<url>/gi, values.url],
|
||||
[/<域名>/g, values.host],
|
||||
[/<目标IP>/g, values.host],
|
||||
[/<内网IP>/g, values.host],
|
||||
[/<端口>/g, values.port],
|
||||
[/<listen端口>/g, values.port],
|
||||
[/<u>/g, values.user],
|
||||
[/<p>/g, values.pass],
|
||||
]
|
||||
for (const [re, value] of table) {
|
||||
if (value === undefined || value === null || String(value) === '') continue
|
||||
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))
|
||||
/* 记录填了什么,报告里要如实说明(模板被改过,读者需要知道哪些是补进去的) */
|
||||
filled.push(re.source.replace(/[\\<>?()/]|gi$/g, '') + ' → ' + String(value))
|
||||
}
|
||||
const remaining = Array.from(new Set(Array.from(cmd.matchAll(/<[^>\s]{1,24}>/g)).map((m) => m[0])))
|
||||
return { cmd, filled, remaining }
|
||||
}
|
||||
|
||||
export { parseTarget, commandKind, parseCurl, buildHttpRequest, buildCurlCommand, fillTemplate }
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,930 @@
|
||||
/**
|
||||
* 计分规则:判定口径 + 默认得分点(零依赖,只用 node: 内置模块)。
|
||||
*
|
||||
* 从 core.js 抽出来的模块,也是本项目**最该单独读的一份代码**:
|
||||
* 面板 / 报告 / 攻击链三处总分必须一致,靠的就是这里的 applyScoreCaps 与
|
||||
* evaluateScoreBoard 是**唯一实现**(此前三处各写一遍,已经漂移出
|
||||
* "报告不看 enabled""攻击链丢了档位分值"两个真实事故)。
|
||||
*
|
||||
* 分工:
|
||||
* · applyScoreCaps —— 给定命中行,标出哪条计分、哪条被封顶/超上限;
|
||||
* · evaluateScoreBoard —— 把"读元数据 + 调 applyScoreCaps + 回填标记"包成一个入口;
|
||||
* · DEFAULT_SCORE_POINTS —— 规则文档展开后的得分点定义(src/rule/cap/dedup_scope)。
|
||||
*/
|
||||
|
||||
/* targetHasIpv6Host 要判定 IPv6 字面量:复用 ip-utils 的同一份实现,避免两套正则漂移 */
|
||||
import { isIpv6 } from './ip-utils.js'
|
||||
|
||||
/* ------------------------------------------------------------------ 判定规则 */
|
||||
|
||||
/* ------------------------------------------------------------------ 判定规则 */
|
||||
|
||||
/**
|
||||
* 什么算"真隧道"(算边界突破/内网突破的凭证):**必须跨越了靶标边界**,
|
||||
* 即通道的一端在目标侧。三种情况:
|
||||
* · target-outbound:目标主动连出到我的服务器(反弹 shell 落地、目标上跑 frp/Stowaway 客户端)
|
||||
* · target-http:经目标 WebShell/HTTP 通道(suo5、Neo-ReGeorg、reGeorg、自研 HTTP 隧道)
|
||||
* · target-agent:经目标上已控进程/会话转发的隧道(SSH -R 由目标发起等)
|
||||
* 不算的:self-only —— 只在自己 VPS / 自建服务器上开的代理或服务端,没碰到目标。
|
||||
*/
|
||||
const TUNNEL_ENTRY_KINDS = {
|
||||
'target-outbound': '目标主动连出(反弹 shell / 目标上跑 frp 客户端)',
|
||||
'target-http': '经目标 WebShell/HTTP 通道(suo5 / Neo-ReGeorg)',
|
||||
'target-agent': '经目标已控进程/会话转发(SSH -R 等)',
|
||||
'self-only': '只在自己 VPS/自建服务器上(不算突破)',
|
||||
}
|
||||
export { TUNNEL_ENTRY_KINDS }
|
||||
|
||||
/** 这条隧道算不算"跨越了靶标边界"。未声明(老数据/没填)返回 null,界面按"待确认"显示。 */
|
||||
export function tunnelIsLegit(entryKind) {
|
||||
const k = String(entryKind || '').trim()
|
||||
if (k === '') return null
|
||||
return k !== 'self-only'
|
||||
}
|
||||
|
||||
/**
|
||||
* 账号/权限类得分点:**自己注册、自己创建的账号不算拿到权限**(演练得分针对"拿到别人已有的")。
|
||||
* 这些得分点命中时会要求声明 self_created,避免把自助注册当成战果。
|
||||
*/
|
||||
const ACCOUNT_POINT_CODES = ['web-account-user', 'web-account-admin', 'server-shell', 'db-access', 'internal-pivot', 'core-system']
|
||||
export { ACCOUNT_POINT_CODES }
|
||||
|
||||
/**
|
||||
* 按「服务」封顶的得分点:**同一个资产的同一个端口只算一次分**。
|
||||
*
|
||||
* · 账号类(web-account-user / web-account-admin)——拿到最高权限账号即该服务拿满:
|
||||
* 普通账号 10 分、管理员 20 分,同一服务上再刷几个账号都不再累加
|
||||
* (两种账号算**同一类**:先拿普通账号、后拿管理员,只有管理员那条计分,总分按最高那条算)。
|
||||
* · 数据库类(db-access)——同口径:一个库权限拿满,同服务再刷第二个库账号不重复计分。
|
||||
*
|
||||
* 其它得分点(webshell/rce/sensitive-data/boundary/…)仍然不设上限,按命中次数累加。
|
||||
*/
|
||||
const SERVICE_CAPPED_POINT_CODES = ['web-account-user', 'web-account-admin', 'db-access']
|
||||
export { SERVICE_CAPPED_POINT_CODES }
|
||||
|
||||
/**
|
||||
* 从 target 里解析端口:`http://h:8080/x`、`10.0.0.5:6379`、`10.0.0.5:22`。
|
||||
* 没有端口或解析不出返回 null(**不要编造 80/443**,否则会把不同服务并成一个)。
|
||||
*/
|
||||
export function parseTargetPort(target) {
|
||||
const t = String(target || '').trim()
|
||||
if (t === '') return null
|
||||
const url = /^[a-z][a-z0-9+.-]*:\/\/([^/?#\s]+)/i.exec(t)
|
||||
const authority = url !== null ? url[1] : (/^([^\s/?#]+)/.exec(t) || [])[1]
|
||||
if (!authority) return null
|
||||
const m = /:(\d{1,5})$/.exec(authority)
|
||||
if (m === null) return null
|
||||
const n = Number(m[1])
|
||||
return Number.isInteger(n) && n > 0 && n <= 65535 ? n : null
|
||||
}
|
||||
|
||||
/** 库列的 port 值(老库可能是 null/0/空串)。 */
|
||||
function normalizePort(value) {
|
||||
if (value === null || value === undefined || value === '') return null
|
||||
const n = Number(value)
|
||||
return Number.isInteger(n) && n > 0 && n <= 65535 ? n : null
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 target 里取「服务标识」:host[:port]。
|
||||
* · 端口取显式写的那个;没写就按协议推默认端口(http→80、https→443、其它→不推断),
|
||||
* 这样 `http://h/x` 与 `http://h:80/y` 会归到同一个服务;
|
||||
* · 路径/参数/查询串一律丢掉(`http://h:8080/a/b?c=1` → `h:8080`)。
|
||||
* 解析不出 host 时返回 null。
|
||||
*/
|
||||
function targetAuthority(target) {
|
||||
const t = String(target || '').trim()
|
||||
if (t === '') return null
|
||||
const url = /^([a-z][a-z0-9+.-]*):\/\/([^/?#\s]+)/i.exec(t)
|
||||
const scheme = url !== null ? url[1].toLowerCase() : null
|
||||
const authority = url !== null ? url[2] : (/^([^\s/?#]+)/.exec(t) || [])[1]
|
||||
if (!authority) return null
|
||||
const host = authority.replace(/:\d{1,5}$/, '').toLowerCase()
|
||||
if (host === '') return null
|
||||
let port = parseTargetPort(t)
|
||||
/* 没写端口时按协议补默认端口:避免同一个服务的两种写法被算成两个服务而被重复计分 */
|
||||
if (port === null) {
|
||||
if (scheme === 'http') port = 80
|
||||
else if (scheme === 'https') port = 443
|
||||
}
|
||||
return port === null ? host : host + ':' + port
|
||||
}
|
||||
|
||||
/**
|
||||
* 「服务」键:得分封顶的粒度 = 同一个资产的同一个端口。
|
||||
* · target 能解析出 host[:port] → 就用它(`t10.20.30.40:3306`)——
|
||||
* 同一个服务可能由不同的人记分,有的带 asset_id、有的只写 target,
|
||||
* 以目标为准才能把它们归到一起;
|
||||
* · target 解析不出(缺失/只写了名字)→ 退到资产:有端口用 `a<id>:<port>`,
|
||||
* 没端口记 `a<id>:0`(该资产的未知端口);
|
||||
* · 两样都没有 → null(拿不到服务信息,这条不参与封顶)。
|
||||
*/
|
||||
export function scoreServiceKey(hit = {}) {
|
||||
const authority = targetAuthority(hit.target)
|
||||
if (authority !== null) return 't' + authority
|
||||
const assetId = hit.asset_id === null || hit.asset_id === undefined || hit.asset_id === '' ? null : Number(hit.asset_id)
|
||||
if (assetId === null) return null
|
||||
const port = normalizePort(hit.port)
|
||||
return 'a' + assetId + ':' + (port === null ? 0 : port)
|
||||
}
|
||||
|
||||
/** 「服务」的可读标签,给告警/报告用(如 `10.1.2.3:8080`)。 */
|
||||
export function serviceLabel(hit = {}, assetIp) {
|
||||
const ip = assetIp || hit.asset_ip || ''
|
||||
const port = normalizePort(hit.port) ?? parseTargetPort(hit.target)
|
||||
if (ip !== '') return port === null ? ip : ip + ':' + port
|
||||
/* 没有资产 id 时用 target 的 host[:port](去掉路径与参数,别把整条 URL 当服务名);
|
||||
端口来自库列而 target 里没写时补上,便于一眼看出是哪个服务。 */
|
||||
const authority = targetAuthority(hit.target)
|
||||
if (authority === null) return hit.target ? String(hit.target) : '(未标注服务)'
|
||||
if (port !== null && !/:\d{1,5}$/.test(authority)) return authority + ':' + port
|
||||
return authority
|
||||
}
|
||||
|
||||
/**
|
||||
* 得分封顶与去重的**唯一实现**(数据驱动,v0.11.0 起)。
|
||||
*
|
||||
* 判定字段来自得分点本身(`score_point.rule / cap / dedup_scope`),不再靠代码里的硬编码名单:
|
||||
* · `dedup_scope = service` —— 同一(资产, 端口)只算分值最高的一条;
|
||||
* · `dedup_scope = system` —— 同一(资产, 端口, 系统名)只算最高权限一条,
|
||||
* 用于"同一个系统只计算一次最高权限分"(邮箱/OA/集权系统等);
|
||||
* · `dedup_scope = target` —— 整个目标只算一次(突破网络边界、IPv6 加成);
|
||||
* · `dedup_scope = none` —— 不去重,按台/卡/节点数累加(算力卡等)。
|
||||
* 之后按 `rule` 分组累计,超过该规则 `cap` 的部分标 `capped`(cap = 0 表示不设上限)。
|
||||
*
|
||||
* `self_created = 1`(自己注册/自建的账号)本来就不计分,既不参与竞争也不占位。
|
||||
*
|
||||
* @param {Array} rows - 命中行(需带 code / points / asset_id / port / target / recorded_at;
|
||||
* 可选 system_key 供 system 口径使用)
|
||||
* @param {Map|Object|null} pointsByCode - code → `{rule, cap, dedup_scope, points}`;
|
||||
* 省略时退化为"每个 code 自成一组、只去重不封顶"(兼容旧调用)
|
||||
* @returns {{capped:number, items:Array, caps:Map}} 打过标记的行 + 被封顶条数 + 各规则上限用量
|
||||
*/
|
||||
export function applyScoreCaps(rows = [], pointsByCode = null, nameByAsset = null) {
|
||||
const metaOf = (r) => {
|
||||
const m = pointsByCode === null || pointsByCode === undefined
|
||||
? undefined
|
||||
: (typeof pointsByCode.get === 'function' ? pointsByCode.get(r.code) : pointsByCode[r.code])
|
||||
const rule = m && m.rule !== null && m.rule !== undefined ? Number(m.rule) : null
|
||||
const legacyScope = legacyCapGroup(r.code)
|
||||
return {
|
||||
group: rule === null ? 'code:' + String(r.code || '') : 'rule:' + rule,
|
||||
cap: m && Number(m.cap) > 0 ? Number(m.cap) : 0,
|
||||
scope: (m && m.dedup_scope) || legacyScope || 'none',
|
||||
rule,
|
||||
}
|
||||
}
|
||||
const flagged = (rows || []).map((r) => {
|
||||
const m = metaOf(r)
|
||||
return {
|
||||
...r, capped: false, capped_by_id: null, capped_reason_kind: null,
|
||||
service_key: null, cap_group: m.group, dedup_scope: m.scope, rule: m.rule, rule_cap: m.cap,
|
||||
}
|
||||
})
|
||||
|
||||
/* ① 计分口径去重:同一口径键内只保留分值最高的一条(同分取更早记的) */
|
||||
const buckets = new Map()
|
||||
for (const r of flagged) {
|
||||
if (Number(r.self_created) === 1) continue
|
||||
const scope = r.dedup_scope
|
||||
if (scope === 'none' || scope === null || scope === undefined) continue
|
||||
let key
|
||||
if (scope === 'target') key = 'target'
|
||||
else if (scope === 'system') key = 'sys:' + String(systemKeyOf(r, nameByAsset) || '')
|
||||
else {
|
||||
/* `service` 口径必须有真正的服务键(`t<host[:port]>` / `a<id>:<port>`)。
|
||||
拿不到服务信息时**不参与去重**,而不是退回"每条自成一键" —— 后者会让
|
||||
`svc:#hit7` 这种键把同一口径的命中全部互相顶掉:实测 62 条无 target 的
|
||||
terminal-access 命中里 61 条被判 dedup 不计分、只留 1 条,等于静默吃掉成果。
|
||||
宁可少封顶也不能错封:认不出服务就各算各的。 */
|
||||
const svc = scoreServiceKey(r)
|
||||
if (svc === null || svc === undefined || String(svc) === '') continue
|
||||
key = 'svc:' + String(svc)
|
||||
}
|
||||
if (key === '' || key === 'svc:null' || key === 'sys:null') continue
|
||||
const k = r.cap_group + '|' + key
|
||||
if (!buckets.has(k)) buckets.set(k, [])
|
||||
buckets.get(k).push(r)
|
||||
}
|
||||
let capped = 0
|
||||
for (const list of buckets.values()) {
|
||||
if (list.length < 2) continue
|
||||
const best = pickBestHit(list)
|
||||
for (const r of list) {
|
||||
if (r === best) continue
|
||||
r.capped = true
|
||||
r.capped_by_id = best.id
|
||||
r.capped_by_points = Number(best.points) || 0
|
||||
r.capped_by_evidence = best.evidence || null
|
||||
r.capped_reason_kind = 'dedup'
|
||||
capped += 1
|
||||
}
|
||||
}
|
||||
|
||||
/* ② 规则上限:同一 rule 的计分命中累计不得超过 cap(按分值从高到低累计,超出的标 capped) */
|
||||
const caps = new Map()
|
||||
const byRule = new Map()
|
||||
for (const r of flagged) {
|
||||
if (r.capped === true || Number(r.self_created) === 1) continue
|
||||
if (r.rule_cap <= 0) continue
|
||||
if (!byRule.has(r.cap_group)) byRule.set(r.cap_group, [])
|
||||
byRule.get(r.cap_group).push(r)
|
||||
}
|
||||
for (const [group, list] of byRule.entries()) {
|
||||
const cap = list[0].rule_cap
|
||||
const ordered = [...list].sort((a, b) => {
|
||||
const pa = Number(a.points) || 0; const pb = Number(b.points) || 0
|
||||
if (pb !== pa) return pb - pa
|
||||
return Number(a.id) - Number(b.id)
|
||||
})
|
||||
let used = 0; let nCapped = 0
|
||||
for (const r of ordered) {
|
||||
const pts = Number(r.points) || 0
|
||||
if (used + pts > cap) {
|
||||
r.capped = true
|
||||
r.capped_reason_kind = 'cap'
|
||||
r.capped_by_points = null
|
||||
nCapped += 1
|
||||
capped += 1
|
||||
} else {
|
||||
used += pts
|
||||
}
|
||||
}
|
||||
caps.set(group, { rule: list[0].rule, cap, used, capped: nCapped })
|
||||
}
|
||||
return { capped, items: flagged, caps }
|
||||
}
|
||||
|
||||
/**
|
||||
* 参与 `system` 口径去重的"系统键"。
|
||||
*
|
||||
* 规则原文是"同一个系统只计算一次最高权限分"(邮箱、OA、集权系统等)。
|
||||
* 判定顺序:
|
||||
* ① 命中自带的 `system_key`(调用方显式指定,最准);
|
||||
* ② 资产的 `primary_name`(系统名/域名的首选名);资产名往往是同一套系统,最接近"同一个系统";
|
||||
* ③ 退回服务键(资产:端口)。
|
||||
* 三条都拿不到返回 null —— 此时**不参与该口径去重**,宁可不封顶也不要错封。
|
||||
*/
|
||||
function systemKeyOf(hit = {}, nameByAsset = null) {
|
||||
const svc = scoreServiceKey(hit)
|
||||
const svcText = svc === null || svc === undefined ? '' : String(svc)
|
||||
|
||||
/* ① 调用方显式给的 system_key:**只有它带上服务键前缀(t<host[:port]> / a<id>:<port>)才采信**。
|
||||
调用方(listScorePoints / scoreReport / scoreChain)会预造 `资产名|端口` 这种键,
|
||||
资产还没有名字时会退化成 `"|8080"` —— 若直接采信,10.7.7.7:8080 与 10.7.7.8:8080
|
||||
会被并成"同一个系统",把另一台主机的成果白白封顶。
|
||||
不能采信时**继续往下走**,用服务键兜底,而不是丢掉整个 system 口径。 */
|
||||
const explicit = String(hit.system_key || '').trim()
|
||||
if (explicit !== '' && (svcText === '' || explicit.includes(svcText))) {
|
||||
/* 没有服务键可校验时,要求"名字段非空"(避免只认端口的野键把所有服务并在一起) */
|
||||
const head = explicit.split('|')[0]
|
||||
if (svcText !== '' || String(head).trim() !== '') return explicit
|
||||
}
|
||||
|
||||
/* ② 资产名(系统名/域名首选名)+ 服务键 —— **这是 system 口径的主力路径**。
|
||||
规则原文是"同一个系统只计算一次最高权限分",覆盖面是"同一系统 + 同一端口":
|
||||
同一套系统跑在多台主机、多个端口时是不同实例,各自算一次最高权限。
|
||||
⚠️ 真的需要"跨主机、跨端口只算一次"时,应显式给 system_key 并用同一个值
|
||||
(见上 ①)——但那时请自己确认这些命中确实是同一个系统实例。 */
|
||||
const id = hit.asset_id === null || hit.asset_id === undefined || hit.asset_id === '' ? null : Number(hit.asset_id)
|
||||
const nameOf = (assetId) => {
|
||||
if (assetId === null || nameByAsset === null || nameByAsset === undefined) return null
|
||||
const raw = typeof nameByAsset.get === 'function' ? nameByAsset.get(assetId) : nameByAsset[assetId]
|
||||
const text = raw === null || raw === undefined ? '' : String(raw).trim()
|
||||
return text === '' ? null : text
|
||||
}
|
||||
const name = nameOf(id)
|
||||
if (name !== null) return name + '|' + svcText
|
||||
|
||||
/* ③ 退到服务键:同(资产, 端口)只算一次最高权限 —— 与 service 口径等效,
|
||||
这是"同一主机上的系统权限、应用权限、数据库权限按最高权限只得一次分"(G1)的兜底。 */
|
||||
if (svcText !== '') return svcText
|
||||
|
||||
/* ④ 三条都拿不到(没有 asset_id、没有系统名、target 也解析不出 host):
|
||||
退回**本条命中自己的 id** —— 即"互不相同",各算各的。
|
||||
宁可少封顶也不能错封:把两条无从区分的命中判成"同一个系统"会白白吃掉用户的成果。
|
||||
⚠️ 这里**不能**用 Math.random():同一个 hit 在两次调用(面板 / 报告 / 攻击链)里
|
||||
会拿到不同的键,计分口径就不稳定了。 */
|
||||
return '#hit' + String(hit.id ?? '0')
|
||||
}
|
||||
|
||||
/** 从一组同口径命中里挑"计分的那一条":分值最高,同分取更早记的(id 小的)。 */
|
||||
function pickBestHit(list) {
|
||||
return list.reduce((a, b) => {
|
||||
const pa = Number(a.points) || 0; const pb = Number(b.points) || 0
|
||||
if (pb !== pa) return pb > pa ? b : a
|
||||
return Number(b.id) < Number(a.id) ? b : a
|
||||
}, list[0])
|
||||
}
|
||||
|
||||
/** 旧口径分组(兼容 v0.10 及以前:账号类与数据库类按"同资产同端口"封顶)。 */
|
||||
function legacyCapGroup(code) {
|
||||
const c = String(code || '').trim()
|
||||
if (c === 'web-account-user' || c === 'web-account-admin') return 'service'
|
||||
return SERVICE_CAPPED_POINT_CODES.includes(c) ? 'service' : null
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 读取得分点元数据(code → `{ rule, cap, dedup_scope, points, enabled, builtin, src }`)。
|
||||
* 面板 / 报告 / 攻击链三处共用,避免"同一份规则三处各读一遍、字段各漏一个"。
|
||||
* @param db - 靶标库句柄。
|
||||
*/
|
||||
function loadScoreMeta(db) {
|
||||
return new Map(db.prepare('SELECT code, rule, cap, dedup_scope, points, enabled, builtin, src FROM score_point')
|
||||
.all()
|
||||
.map((r) => [String(r.code), {
|
||||
rule: r.rule === null || r.rule === undefined ? null : Number(r.rule),
|
||||
cap: Number(r.cap) || 0,
|
||||
dedup_scope: r.dedup_scope || 'service',
|
||||
points: Number(r.points) || 0,
|
||||
enabled: r.enabled === null || r.enabled === undefined ? 1 : Number(r.enabled),
|
||||
builtin: Number(r.builtin) === 1,
|
||||
src: r.src === null || r.src === undefined ? null : Number(r.src),
|
||||
}]))
|
||||
}
|
||||
|
||||
/**
|
||||
* 资产 id → 系统名(primary_name),`system` 口径要用它把"同一套系统"归到一起。
|
||||
* @param db - 靶标库句柄。
|
||||
*/
|
||||
function loadAssetNames(db) {
|
||||
return new Map(db.prepare('SELECT id, primary_name FROM asset').all()
|
||||
.filter((a) => a.primary_name).map((a) => [Number(a.id), a.primary_name]))
|
||||
}
|
||||
|
||||
/**
|
||||
* 本条命中的**实际分值** = 档位分值 × 倍率。
|
||||
* · 档位分值:命中自带优先(合并版同一条含多档),缺省回落到得分点默认分值;
|
||||
* · 倍率:G5 数据规模翻倍(超 1 亿条 / 10TB,或控制知识库相关系统)×2、
|
||||
* G6 IPv6 成果 ×3。倍率作用在**权限分**上,所以乘在分值里、随上限一起被 cap 约束
|
||||
* (文档要求"上限仍按对应系统类型的原上限计算,不因倍数突破上限")。
|
||||
*/
|
||||
function hitPointsOf(hit = {}, metaByCode = null) {
|
||||
let base = 0
|
||||
if (hit.points !== null && hit.points !== undefined && hit.points !== '') {
|
||||
base = Number(hit.points) || 0
|
||||
} else {
|
||||
const code = hit.code === null || hit.code === undefined ? null : String(hit.code)
|
||||
if (code !== null && metaByCode !== null && metaByCode !== undefined) {
|
||||
const meta = typeof metaByCode.get === 'function' ? metaByCode.get(code) : metaByCode[code]
|
||||
if (meta !== undefined && meta !== null) base = Number(meta.points) || 0
|
||||
}
|
||||
}
|
||||
const mult = Number(hit.multiplier)
|
||||
return Math.round(base * (Number.isFinite(mult) && mult > 0 ? mult : 1))
|
||||
}
|
||||
|
||||
/**
|
||||
* 这个 target 的主机部分是 IPv6 字面量吗(http://[2001:db8::1]:8080/x、2001:db8::1、[::1]:22)。
|
||||
*
|
||||
* 不能用一条粗糙的字符类正则代替:IPv6 里混着十六进制字母(a-f),
|
||||
* 写成 /^\[[0-9a-f:]+\]/ 这类"只看冒号和十六进制"的写法会把带字母的地址漏判
|
||||
* (实测 2001:db8::1 里的 db8 就被漏掉,G6 的 ×3 完全不生效)。
|
||||
* 所以把主机部分交给 isIpv6() 判定 —— 与 cidrOf / scopeOfIp 用同一份实现。
|
||||
*/
|
||||
function targetHasIpv6Host(target) {
|
||||
const text = String(target || "").trim()
|
||||
if (text === "") return false
|
||||
const bracket = /^[a-z][a-z0-9+.-]*:\/\/(\[[^\]]+\])/i.exec(text)
|
||||
if (bracket !== null) return isIpv6(bracket[1].replace(/^\[|\]$/g, ""))
|
||||
const url = /^[a-z][a-z0-9+.-]*:\/\/([^/?#\s]+)/i.exec(text)
|
||||
const authority = url !== null ? url[1] : (/^([^\s/?#]+)/.exec(text) || [])[1]
|
||||
if (!authority) return false
|
||||
/* 裸写 IPv6 想带端口必须加方括号,所以这里去掉方括号后再尝试剥端口 */
|
||||
const host = authority.replace(/^\[|\]$/g, "").replace(/:\d{1,5}$/, "")
|
||||
return isIpv6(host)
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 G5 / G6 的倍率规则算成倍率值(只对权限分生效,且不突破原上限 —— 由 cap 兜住)。
|
||||
* · `ip_version === 6` 或 target 是 IPv6 字面量 → ×3(G6);
|
||||
* · `data_scale === "large"` → ×2(G5:超 1 亿条 或 10TB);
|
||||
* · `data_scale === "knowledge-base"` → ×2(G5:控制知识库相关系统);
|
||||
* · 两者都命中 → 相乘。文档没写禁止叠加,取对演练方有利的解释并**如实标注原因**。
|
||||
* @param hit - 命中参数(ip_version / data_scale / target)。
|
||||
* @returns `{ multiplier, reasons }`
|
||||
*/
|
||||
function scoreMultiplierOf(hit = {}) {
|
||||
const reasons = []
|
||||
let multiplier = 1
|
||||
const target = String(hit.target || "")
|
||||
const ipv6 = Number(hit.ip_version) === 6 || targetHasIpv6Host(target)
|
||||
|| /(^|\/\/)[0-9a-f]{0,4}:[0-9a-f:]+/i.test(target)
|
||||
if (ipv6) { multiplier *= 3; reasons.push("G6 IPv6 成果 ×3") }
|
||||
const scale = String(hit.data_scale || "").trim().toLowerCase()
|
||||
if (scale === "large") { multiplier *= 2; reasons.push("G5 数据规模超 1 亿条 / 10TB ×2") }
|
||||
else if (scale === "knowledge-base" || scale === "kb") { multiplier *= 2; reasons.push("G5 控制知识库相关系统 ×2") }
|
||||
return { multiplier, reasons }
|
||||
}
|
||||
|
||||
/**
|
||||
* **统一的计分评估**:面板 / 报告 / 攻击链都调这一个函数算出"哪条计分、哪条被封顶"。
|
||||
*
|
||||
* 输入为一组"命中行",输出它们的计分标记。调用方只需保证每行带
|
||||
* `{ id, code, points, asset_id, port, target, self_created }` 与**本条命中的实际分值**
|
||||
* (`points` 字段;不要传得分点默认值 —— 合并版里同一条含多档,传默认值会把哪条计分判反)。
|
||||
*
|
||||
* @param db - 靶标库句柄。
|
||||
* @param rows - 命中行数组。
|
||||
* @param options - `{ meta?, names?, enabledOnly? }`:可复用已读好的元数据;`enabledOnly` 为 true
|
||||
* 时"停用得分点"的命中直接标为不计分(报告与面板口径必须一致)。
|
||||
* @returns `{ byId, items, caps, meta, names, disabledIds }`
|
||||
*/
|
||||
function evaluateScoreBoard(db, rows = [], options = {}) {
|
||||
const meta = options.meta || loadScoreMeta(db)
|
||||
const names = options.names || loadAssetNames(db)
|
||||
const prepared = (rows || []).map((h) => {
|
||||
const code = h.code === null || h.code === undefined ? null : String(h.code)
|
||||
const m = code === null ? undefined : meta.get(code)
|
||||
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),
|
||||
rule: m === undefined || m.rule === undefined ? null : m.rule,
|
||||
cap: m === undefined ? 0 : m.cap,
|
||||
dedup_scope: m === undefined ? 'service' : m.dedup_scope,
|
||||
cap_group: m === undefined || m.rule === null || m.rule === undefined ? 'code:' + String(code) : 'rule:' + m.rule,
|
||||
rule_cap: m === undefined ? 0 : m.cap,
|
||||
system_key: [nm || '', normalizePort(h.port) ?? parseTargetPort(h.target) ?? ''].join('|'),
|
||||
})
|
||||
})
|
||||
const evaluated = applyScoreCaps(prepared, meta, names)
|
||||
const byId = new Map(evaluated.items.map((x) => [x.id, x]))
|
||||
const disabledIds = new Set()
|
||||
if (options.enabledOnly === true) {
|
||||
for (const h of prepared) {
|
||||
const m = h.code === null ? undefined : meta.get(h.code)
|
||||
if (m !== undefined && Number(m.enabled) !== 1) disabledIds.add(h.id)
|
||||
}
|
||||
}
|
||||
return { byId, items: evaluated.items, caps: evaluated.caps, meta, names, disabledIds }
|
||||
}
|
||||
|
||||
/**
|
||||
* 这条命中为什么不计分(告警 / 界面 / 报告共用一句话,避免三处口径写歪)。
|
||||
* @param hit - 命中行(带 code / target / port / rule / rule_cap / capped_reason_kind)
|
||||
* @param bestPoints - 去重时被哪条压住(该条的分值)
|
||||
*/
|
||||
export function scoreCapReasonText(hit = {}, bestPoints) {
|
||||
const label = serviceLabel(hit)
|
||||
if (hit.capped_reason_kind === 'cap') {
|
||||
return '「' + label + '」这条不计分:'
|
||||
+ (hit.rule === null || hit.rule === undefined ? '' : '规则 ' + hit.rule + ' ')
|
||||
+ '的**累计得分已达该规则上限(' + (Number(hit.rule_cap) || 0) + ' 分)**——同一规则超出上限的部分不再累加。'
|
||||
+ '把精力换到别的规则或别的资产上,不要在已达上限的规则里继续刷。'
|
||||
}
|
||||
return '「' + label + '」这个目标上的权限已经拿满(计分口径:同一目标只算分值最高的那条'
|
||||
+ (bestPoints === undefined || bestPoints === null ? '' : ',+' + bestPoints + ' 分')
|
||||
+ ')——这条按规则不再计分,只作过程留痕;**换目标或换规则推进,不要在同一个目标上刷同类成果**。'
|
||||
}
|
||||
|
||||
/** 兼容旧名(v0.10 及以前叫 serviceCapReason)。 */
|
||||
export const serviceCapReason = scoreCapReasonText
|
||||
|
||||
|
||||
/**
|
||||
* 数据规模的**粗判门槛**:100 万条/行。
|
||||
* 用途已经从「大量敏感信息得分项」改成 G5 翻倍的量级自检 —— 见 addScoreHit 里的警告。
|
||||
* 文档里 G5 的正式门槛是「超 1 亿条 或 10TB」;这里用更低的一档做"有没有写量级"的粗筛,
|
||||
* 低于它会提示核对,但不阻断记分。
|
||||
*/
|
||||
export const SENSITIVE_DATA_MIN_ROWS = 1000000
|
||||
|
||||
/**
|
||||
* 从证据文本里解析数据量(行/条/记录数)。
|
||||
* 支持「120 万条」「1300万行」「1,200,000 条记录」「2.5万行」「1200000 records」。
|
||||
* **只认带量词(条/行/记录/records/rows)或中文量级(亿/万…)的写法**——
|
||||
* 裸数字不认,否则会把口令里的 `123456`、端口号当成数据量。
|
||||
* 解析不出来返回 null(由调用方提示补齐量级,不猜、不编数)。
|
||||
*/
|
||||
export function parseRowCount(evidence) {
|
||||
const text = String(evidence || '')
|
||||
if (text.trim() === '') return null
|
||||
const units = { 亿: 1e8, 千万: 1e7, 百万: 1e6, 十万: 1e5, 万: 1e4, 千: 1e3 }
|
||||
const nums = []
|
||||
/* 「数字 + 单位 + 条/行/记录」:单位是中文量词,或英文 records/rows/entries */
|
||||
const cn = /(\d[\d,]*(?:\.\d+)?)\s*(亿|千万|百万|十万|万|千)?\s*(条|行|记录|数据|records?|rows?|entries)/gi
|
||||
for (const m of text.matchAll(cn)) {
|
||||
const base = Number(String(m[1]).replace(/,/g, ''))
|
||||
if (!Number.isFinite(base)) continue
|
||||
const mult = m[2] === undefined ? 1 : units[m[2]]
|
||||
nums.push(Math.round(base * mult))
|
||||
}
|
||||
if (nums.length > 0) return Math.max(...nums)
|
||||
/* 只写了「导出 120 万」这类(没写条/行)也认,但必须带中文量级 */
|
||||
for (const m of text.matchAll(/(\d[\d,]*(?:\.\d+)?)\s*(亿|千万|百万|十万|万|千)/g)) {
|
||||
const base = Number(String(m[1]).replace(/,/g, ''))
|
||||
if (Number.isFinite(base)) nums.push(Math.round(base * units[m[2]]))
|
||||
}
|
||||
return nums.length === 0 ? null : Math.max(...nums)
|
||||
}
|
||||
|
||||
/** 千分位展示,告警里读数更直观。 */
|
||||
export function formatRows(n) {
|
||||
return Number(n).toLocaleString('en-US')
|
||||
}
|
||||
|
||||
|
||||
/* ------------------------------------------------------------------ 默认得分点 */
|
||||
|
||||
/**
|
||||
* 得分点 → 交付口径(怎么算拿到、拿什么自证、怎么复现)。
|
||||
*
|
||||
* 为什么单独一张表而不是塞进 `score_point.description`:
|
||||
* 描述是"规则文档的条款"(给智能体判档位用),这张表是"给验收人看的复现口径",
|
||||
* 两者受众不同、详略也不同。报告与界面按 code 取这里的说明,
|
||||
* 规则文档更新时不必动这张表,反之亦然。
|
||||
*
|
||||
* 字段:
|
||||
* · need —— 判定标准:满足什么才算拿到这一项(给验收人对账用)
|
||||
* · proof —— 自证材料:该附什么证据(G7 的证明材料要求)
|
||||
* · replay —— 复现入口:用哪条请求 / 哪条命令重放("可复现"最直接的答案)
|
||||
* · script —— 一线可直接照做的动作(尽量是可复制执行的)
|
||||
*/
|
||||
export const SCORE_CONFIRM = {
|
||||
'domain-control': {
|
||||
need: '目标域名解析记录被改为我方可控(NS/A 记录生效),或域名管理后台可操作',
|
||||
proof: '管理后台截图 + 改记录前后的 dig/nslookup 对比',
|
||||
replay: 'nslookup <域名> <我方 NS>;或后台操作请求原文',
|
||||
script: 'dig NS <域名> @8.8.8.8\ndig <域名> @<我方NS>',
|
||||
},
|
||||
'terminal-access': {
|
||||
need: '能对终端下发指令并取回执行结果(不是"发现了一台设备")',
|
||||
proof: '被控终端执行 id/hostname 的回显 + 与目标单位的关系证明(G7)',
|
||||
replay: '远控会话里执行 id;或木马/远控的 agent 上线记录',
|
||||
script: 'id; whoami; hostname',
|
||||
},
|
||||
'server-host': {
|
||||
need: '在主机上执行了命令并拿到回显(WebShell / 反弹 Shell / 远控均可)',
|
||||
proof: '命令回显(id / hostname)+ WebShell 连接要素或会话记录',
|
||||
replay: 'WebShell 请求原文(可直接重放);或反弹 Shell 的监听记录',
|
||||
script: 'id; uname -a; cat /etc/passwd | head',
|
||||
},
|
||||
'db-credential': {
|
||||
need: '用账号成功连上数据库并执行了查询(未授权访问也算:能连上即成立)',
|
||||
proof: '登录成功后的查询回显(select user(), version())+ 账号权限级别',
|
||||
replay: 'mysql -h <host> -P <port> -u <user> -p\'<pass>\' -e "select user(),version()"',
|
||||
script: 'mysql -h <host> -u <user> -p -e "select user(),version(),current_user()"',
|
||||
},
|
||||
'web-app': {
|
||||
need: '以目标已有账号登录进系统(普通或管理员),并访问了受保护页面',
|
||||
proof: '登录后的页面内容/回显 + 会话 Cookie 或 Token(证明不是只拿到口令)',
|
||||
replay: '登录请求原文(含见证 Cookie/Token)+ 一次带会话的受保护页面请求',
|
||||
script: 'curl -i -s -X POST <登录URL> -d "username=<u>&password=<p>" -c cookie.txt\ncurl -s -b cookie.txt <受保护页面>',
|
||||
},
|
||||
'central-system': {
|
||||
need: '登录进堡垒机/域控/SSO/终端管理后台等集权系统并取得管理权限',
|
||||
proof: '管理后台页面截图 + 能体现"可管控下属节点"的操作(登录 20% 托管节点或 20 台)',
|
||||
replay: '登录请求原文 + 一次管控操作(如列举托管主机)的请求与响应',
|
||||
script: 'curl -s -b cookie.txt "<管控列表接口>"',
|
||||
},
|
||||
'bigdata-system': {
|
||||
need: '获得大数据平台(Hadoop/Spark/ES 等)管理或普通权限',
|
||||
proof: '平台管理页/接口回显 + 可访问的数据规模(条数或容量)',
|
||||
replay: '平台接口请求原文(如 ES _cat/indices、YARN /ws/v1/cluster/apps)',
|
||||
script: 'curl -s "<平台接口>" | head -50',
|
||||
},
|
||||
netdev: {
|
||||
need: '登录网络设备(防火墙/路由器/交换机/VPN/网闸)并取得权限',
|
||||
proof: '设备管理页截图 + 路由表或连接量截图(G7 明确要求)',
|
||||
replay: '设备登录请求原文 + 读取路由表的命令回显',
|
||||
script: 'show ip route # 或 display ip routing-table',
|
||||
},
|
||||
'netdev-redirect': {
|
||||
need: '借助该设备实际改变了流量走向(策略/路由/DNS 改动生效)',
|
||||
proof: '改动前后的路由表或策略对比 + 我方节点收到流量的证据',
|
||||
replay: '策略配置请求原文 + 我方可控节点上的抓包/访问日志',
|
||||
script: 'tcpdump -ni any port <端口> -c 10',
|
||||
},
|
||||
'netdev-implant': {
|
||||
need: '设备上植入了可执行的远控/持久化,**并且**借助它完成了后续攻击',
|
||||
proof: '远控进程或持久化项的证据 + 经该设备发起的后续成果记录',
|
||||
replay: '植入动作的请求/命令原文 + 后续经由该设备的访问日志',
|
||||
script: '',
|
||||
},
|
||||
iiot: {
|
||||
need: '获得工业互联网系统管理权限,或批量控制其下的互联设备',
|
||||
proof: '管理后台截图 + 被控设备清单与数量',
|
||||
replay: '登录请求原文 + 设备列表接口响应',
|
||||
script: '',
|
||||
},
|
||||
'cloud-platform': {
|
||||
need: '云管理平台管理员权限;或通过 ak/sk 批量控制云上节点(≥100 个才计节点分)',
|
||||
proof: '平台管理页截图;ak/sk 场景需给出被控节点清单与数量、或管理员证明(新增节点/改权限)',
|
||||
replay: '平台接口请求原文(列举实例、创建用户等)',
|
||||
script: 'curl -s -H "Authorization: Bearer <token>" "<平台/实例列表接口>"',
|
||||
},
|
||||
'iot-platform': {
|
||||
need: '获得物联网管控平台权限,或按其连接点批量控制设备',
|
||||
proof: '平台管理页截图 + 连接点/设备数量',
|
||||
replay: '平台登录与设备列表接口原文',
|
||||
script: '',
|
||||
},
|
||||
'iot-corenet': {
|
||||
need: '从物联网端点设备横向进入核心网,并控制了业务生产等重要系统',
|
||||
proof: '路径说明(哪个端点→核心网→哪个系统)+ 该系统的控制证据',
|
||||
replay: '从端点发起的横向动作命令 + 核心网系统的登录/操作请求',
|
||||
script: '',
|
||||
},
|
||||
secdev: {
|
||||
need: '获得非集权类安全设备(IPS/IDS/审计/WAF)管理员权限',
|
||||
proof: '设备管理页截图 + 能体现策略可控的操作',
|
||||
replay: '登录请求原文 + 一条策略读取接口响应',
|
||||
script: '',
|
||||
},
|
||||
'file-storage': {
|
||||
need: '获得文件存储系统后台权限(FTP/NAS/网盘/对象存储),或拿到其普通账号',
|
||||
proof: '目录列举截图 + 可读文件清单(数据成果另有计分,见 G2)',
|
||||
replay: '列举目录的请求原文(FTP LIST / S3 ListObjects / WebDAV PROPFIND)',
|
||||
script: 'curl -s "<存储接口>" | head -50',
|
||||
},
|
||||
'ai-agent': {
|
||||
need: '控制模型智能体/skill 等 agent 工具,并**实际驱动它执行了动作**',
|
||||
proof: '对话或调用记录 + 被驱动执行的动作与其结果(区间分按控制深度研判)',
|
||||
replay: '驱动 agent 的请求原文 + 它执行动作的回显',
|
||||
script: '',
|
||||
},
|
||||
'model-compute': {
|
||||
need: '获得算力管理平台/训练数据与知识库系统的系统管理权限',
|
||||
proof: '管理后台截图 + 能体现算力调度或数据可读写的操作',
|
||||
replay: '平台登录与调度/数据接口原文',
|
||||
script: '',
|
||||
},
|
||||
'model-data': {
|
||||
need: '获得模型相关数据系统管理员权限(可影响训练/推理/运营或窃取篡改权重)',
|
||||
proof: '管理后台截图 + 可读写的模型/数据集清单',
|
||||
replay: '平台接口原文(列举模型、下载权重)',
|
||||
script: '',
|
||||
},
|
||||
'computepower-admin': {
|
||||
need: '获得算力基础设施管理员权限',
|
||||
proof: '管理后台截图 + 可调度资源证明',
|
||||
replay: '平台登录与资源列表接口原文',
|
||||
script: '',
|
||||
},
|
||||
'computepower-cards': {
|
||||
need: '实际取得算力卡资源(10 分/卡)或卡池化平台控制权',
|
||||
proof: '卡资源清单(数量)+ 能提交任务或独占卡的证据',
|
||||
replay: 'nvidia-smi 回显 / 平台卡列表接口',
|
||||
script: 'nvidia-smi -L',
|
||||
},
|
||||
'boundary-logical': {
|
||||
need: '从靶标侧建立了通往内网的通道,并能**实际访问内网目标**',
|
||||
proof: '隧道登记(入口必须是目标侧)+ 经隧道访问内网目标的回显/截图(G7)',
|
||||
replay: '经隧道访问内网目标的那条命令与回显;隧道搭建命令',
|
||||
script: 'curl --socks5-hostname 127.0.0.1:<端口> http://<内网IP>/ -i',
|
||||
},
|
||||
'boundary-strong': {
|
||||
need: '突破网闸类强隔离,进入强隔离业务内网并实际访问到内网目标',
|
||||
proof: '网闸类隔离设备的控制截图 + 能访问内网的截图证明(G7)',
|
||||
replay: '经强隔离通道访问内网目标的命令与回显',
|
||||
script: '',
|
||||
},
|
||||
'boundary-physical': {
|
||||
need: '突破物理隔离/进入核心生产网并实际访问到目标',
|
||||
proof: '防火墙/VPN/多网卡主机/网闸的控制截图 + 能访问内网的截图(G7)',
|
||||
replay: '进入核心网后访问目标的命令与回显',
|
||||
script: '',
|
||||
},
|
||||
'boundary-supply': {
|
||||
need: '借助供应链运维通道或云服务进入主防单位内网(按情形分别计分)',
|
||||
proof: '供应链/云侧的控制证据 + 进入主防单位内网的证明;写明属于哪种情形',
|
||||
replay: '从供应链通道进入内网的命令与回显',
|
||||
script: '',
|
||||
},
|
||||
}
|
||||
|
||||
/** 取某个得分点的交付口径;没有专门条目时返回 null(报告会退回只显示 evidence)。 */
|
||||
export function scoreConfirmOf(code) {
|
||||
const key = String(code || '').trim()
|
||||
return SCORE_CONFIRM[key] === undefined ? null : SCORE_CONFIRM[key]
|
||||
}
|
||||
|
||||
export const DEDUP_SCOPES = ['service', 'system', 'target', 'none']
|
||||
|
||||
/**
|
||||
* 一条得分点的完整定义(工厂函数,避免 22 个对象重复字段)。
|
||||
*
|
||||
* 两个编号各司其职,**不要混用**:
|
||||
* · `src` —— 《突破入侵类得分规则(合并版)》里的"原序号"(合并行写首个原序号),
|
||||
* 只用于与原表逐条对账,出现在文档与代码注释里;
|
||||
* · `rule` —— 本实现内部的**上限分组键**(`applyScoreCaps` 按它累计 cap)。
|
||||
* 它必须**唯一**:历史上曾直接用原序号当分组键,导致 16/17 合并行与
|
||||
* 19 的两个子项共用同一个键 —— 一条命中会把另一条的上限吃掉,
|
||||
* 而且 `rule` 编号出现重复(两个 19)与空号(6/17/20/21),
|
||||
* 模型读到"规则 19 已达上限"时分不清是哪一条。
|
||||
* 现在统一为 1..N 连续唯一,与数组顺序一一对应。
|
||||
*/
|
||||
const sp = (src, rule, tier, code, name, category, points, cap, dedup_scope, description) => ({
|
||||
src, rule, tier, code, name, category, points, cap, dedup_scope, description,
|
||||
})
|
||||
|
||||
/* ── 通用规则(G1–G8,横切全部条目;不单独计分,写进说明与提示词)────────────
|
||||
G1 权限取高只计一次 | G2 数据成果另行计分 | G3 上限针对单个防守单位 |
|
||||
G4 设备按台(个)计分 | G5 数据规模翻倍 | G6 IPv6 ×3(不突破原上限)|
|
||||
G7 证明材料要求 | G8 兜底:其他系统由专项组研判后给分。
|
||||
完整原文见 docs/得分规则-合并版.md。 */
|
||||
export const SCORE_GENERAL_RULES = [
|
||||
{ code: 'G1', name: '权限取高、只计一次', detail: '同一系统、同一主机、同一数据库上取得多种权限时,只按最高权限计一次分(既获取管理员又获取普通权限的,只给管理员权限分)。' },
|
||||
{ code: 'G2', name: '数据成果另行计分', detail: '邮件数据、业务数据、数据资产等成果按数据重要程度单独计分,不与权限分混算。' },
|
||||
{ code: 'G3', name: '上限口径', detail: '各项分值上限针对单个防守单位及其所有下属机构,达到上限后不再累计。' },
|
||||
{ code: 'G4', name: '设备/终端按台(个)计分', detail: '打印机、wifi 路由器 5 分/台;PC、Pad、手机、摄像头、电子大屏 10 分/台;云上主机、容器、托管互联设备、物联网连接点等按 10 分/台(个)。批量控制按"被控节点"折算。' },
|
||||
{ code: 'G5', name: '数据规模翻倍', detail: '含大量数据系统(重要数据量超 1 亿条或 10TB)得分翻倍;控制知识库相关系统得分翻倍。不含系统产生的普通日志数据。' },
|
||||
{ code: 'G6', name: 'IPv6 倍数', detail: '利用 IPv6 取得的成果分数 ×3,但上限仍按对应系统类型的原上限计算,不因倍数突破上限。' },
|
||||
{ code: 'G7', name: '证明材料', detail: '突破网络边界须提供隔离设备控制截图、能访问内网的截图证明等;控制的手机、Pad 等终端设备应能证明与目标单位的关系;网络设备权限需提供路由表等证据或连接量截图。' },
|
||||
{ code: 'G8', name: '兜底条款', detail: '其他系统、服务器、设备等权限不预设分值,由专项组研判后给分。' },
|
||||
]
|
||||
|
||||
/**
|
||||
* 默认得分点 —— **严格对齐《突破入侵类得分规则(合并版)》,共 22 项**
|
||||
* (一、获取权限 18 条 + 二、突破网络边界 4 条;其中"同一行的不同计费单位"拆为独立得分点,如算力基础设施的管理员权限与算力卡)。
|
||||
*
|
||||
* 与上一版的区别:不再按"同一规则内的权限档位"拆条 —— 一条 = 合并版里的一行
|
||||
* (`tier` 字段写清该条的档位/子项),只有**计费单位不同**的多档才保留子项
|
||||
* (如算力基础设施的"管理员权限"与"算力卡 10 分/卡")。
|
||||
*
|
||||
* 字段含义:
|
||||
* · src 合并版里的"原序号"(用于与原表逐条对账);
|
||||
* · group 界面分组:GENERAL = 控制一般系统,WEB = 控制 Web 应用系统,
|
||||
* CENTRAL = 控制集权系统,BIGDATA = 控制大数据系统,
|
||||
* NETINFRA = 控制网络基础设施,STORAGE = 文件存储类系统,
|
||||
* MODEL = 控制模型相关系统,BOUNDARY = 突破网络边界;
|
||||
* · points 单次分值(一条内多档时取该条的主档,说明里写清各档);
|
||||
* · cap 该条上限(0 = 不设上限);dedup_scope 计分口径。
|
||||
*/
|
||||
export const SCORE_GROUPS = [
|
||||
{ code: 'GENERAL', name: '控制一般系统' },
|
||||
{ code: 'WEB', name: '控制 Web 应用系统' },
|
||||
{ code: 'CENTRAL', name: '控制集权系统' },
|
||||
{ code: 'BIGDATA', name: '控制大数据系统' },
|
||||
{ code: 'NETINFRA', name: '控制网络基础设施' },
|
||||
{ code: 'STORAGE', name: '文件存储类系统' },
|
||||
{ code: 'MODEL', name: '控制模型相关系统' },
|
||||
{ code: 'BOUNDARY', name: '突破网络边界' },
|
||||
]
|
||||
|
||||
export const DEFAULT_SCORE_POINTS = [
|
||||
/* ══ 一、获取权限(18 条)══════════════════════════════════════════════ */
|
||||
|
||||
/* 1 域名控制权限 */
|
||||
sp(1, 1, '一级 50 / 二级 20 分/个', 'domain-control', '域名控制权限', 'GENERAL', 50, 400, 'system',
|
||||
'**一级域名 50 分/个,二级域名 20 分/个**,按域名类型给分;本项上限 400 分(G3)。\n'
|
||||
+ '记分时在 evidence 里写明域名与其类型;拿到二级域名时把单次分值调整为 20。'),
|
||||
|
||||
/* 2 终端权限 */
|
||||
sp(2, 2, '5 / 10 分/台', 'terminal-access', '终端权限(手机、Pad、PC、打印机、摄像头、wifi 路由器等)', 'GENERAL', 10, 600, 'system',
|
||||
'**打印机、wifi 路由器 5 分/台;PC、Pad、手机、摄像头、电子大屏 10 分/台**(G4),按台累加;本项上限 600 分(G3)。\n'
|
||||
+ '控制的终端设备需能证明与目标单位的关系(G7);拿到 5 分档设备时把单次分值调整为 5。\n'
|
||||
+ '钓鱼获取的终端同样按本项计分,在 evidence 里写明目标人员角色(普通办公 / IT 运维 / 业务运营)。'),
|
||||
|
||||
/* 3 服务器主机权限 */
|
||||
sp(3, 3, '普通 10 / 管理员 50 分/个', 'server-host', '服务器主机权限(含 webshell 权限)', 'GENERAL', 50, 600, 'system',
|
||||
'**普通权限 10 分/个,管理员权限 50 分/个**;本项上限 600 分(G3)。\n'
|
||||
+ '同一主机只按最高权限计一次(G1)——拿到 root/SYSTEM 后同主机不再累加普通权限。\n'
|
||||
+ '获取 1 台服务器主机不扣分;拿到普通权限时把单次分值调整为 10。'),
|
||||
|
||||
/* 4 数据库连接账号密码 */
|
||||
sp(4, 4, '普通 10 / 管理员 50 / 未授权 10 分/个', 'db-credential', '数据库连接账号密码(含 SQL 注入)', 'GENERAL', 50, 400, 'system',
|
||||
'**普通用户权限 10 分/个,管理员权限 50 分/个;redis 和其他空密码、未授权访问成果统一 10 分/个**;本项上限 400 分(G3)。\n'
|
||||
+ '同一数据库的同等权限(含管理员)只得一次分;同一主机上的系统权限、应用权限、数据库权限按最高权限只得一次分(G1)。\n'
|
||||
+ '数据成果单独计分(G2);拿到普通权限/未授权时把单次分值调整为 10。'),
|
||||
|
||||
/* 5、6 邮箱与业务生产系统(原表两项共用规则与上限) */
|
||||
sp(5, 5, '管理员 100 / 普通 50 分/个', 'web-app', '邮箱系统 / 办公自动化与业务生产系统权限', 'WEB', 100, 2000, 'system',
|
||||
'**管理员权限 100 分/个,普通用户权限 50 分/个;同一个系统只计算一次最高权限分**(G1);本项上限 2000 分(G3)。\n'
|
||||
+ '本项合并原表第 5、6 项(规则与上限完全相同),记分时在 evidence 里写明是哪类系统:\n'
|
||||
+ '· **邮箱系统**;\n'
|
||||
+ '· **办公自动化与业务生产系统**(办公 OA、ERP、直报即时通讯、财务系统、业务生产系统、数据仓库等被控或瘫痪后影响行业或单位业务生产、运行管理、日常办公的系统)。\n'
|
||||
+ '邮件数据按重要程度再单独计分(G2);拿到普通用户权限时把单次分值调整为 50。'),
|
||||
|
||||
/* 7 集权系统 */
|
||||
sp(7, 6, '管理员 500 / 普通 50 分/个', 'central-system', '集权系统权限(运维 / 身份 / 组网 / 终端管理后台)', 'CENTRAL', 500, 4000, 'system',
|
||||
'**系统管理员权限 500 分/个,普通权限 50 分/个**;同一权限只给一次分,即获取管理员和普通权限只给管理员权限分(G1);本项上限 4000 分(G3)。\n'
|
||||
+ '集权系统包括四类:\n'
|
||||
+ '· **运维集权类**:堡垒机、集中监控、统一资源发布等;\n'
|
||||
+ '· **身份权限管理类**:SSO、4A、IAM 等;\n'
|
||||
+ '· **组网集权类**:域控、证书认证、SDWAN 统一控制器等;\n'
|
||||
+ '· **终端主机管理后台类**:终端管理软件后台、零信任控制中心等。\n'
|
||||
+ '⚠️ 集权系统**托管的主机、终端等设备跨类引用"控制一般系统"的分值**(如 PC、移动终端 10 分/台,G4)——'
|
||||
+ '**不要按集权系统最高档 500 分算**,那会严重偏高;批量控制需提供证明:至少登录托管节点数量的 20%,最多登录 20 台即可。'),
|
||||
|
||||
/* 8 大数据系统 */
|
||||
sp(8, 7, '管理员 1000 / 普通 100 分/个', 'bigdata-system', '大数据系统权限', 'BIGDATA', 1000, 4000, 'system',
|
||||
'**管理员权限 1000 分,普通权限 100 分/个**;同一权限只给一次分,既获取管理员和普通权限只给管理员权限分(G1);本项上限 4000 分(G3)。\n'
|
||||
+ '数据单独计分(G2);**有效数据量小于 5 亿条或 1TB 的按普通数据库计算**(即改用第 4 项分值)。'),
|
||||
|
||||
/* 9 网络设备权限 */
|
||||
sp(9, 8, '普通 100 / 管理员 200 / 加成 200·1000 分', 'netdev', '网络设备权限(防火墙、路由器、交换机、网闸、光闸、摆渡机、VPN 等)', 'NETINFRA', 200, 2000, 'service',
|
||||
'**普通用户权限 100 分,管理员权限 200 分**;本项上限 2000 分(G3)。需提供路由表等证据或连接量截图(G7)。\n'
|
||||
+ '在同一台设备上做到下列动作**再加分**(按做到的那一档记分):\n'
|
||||
+ '· 借助该设备进行**网络重定向或业务劫持**:+200 分;\n'
|
||||
+ '· 在该设备上**植入远控程序并成功进行后续攻击**:1000 分。\n'
|
||||
+ '拿到普通权限或加成分时,把单次分值按实际档位调整。'),
|
||||
|
||||
/* 10 工业互联网系统 */
|
||||
sp(10, 9, '管理员 200 / 设备 10 分/个', 'iiot', '工业互联网系统权限', 'NETINFRA', 200, 2000, 'system',
|
||||
'**管理后台管理员权限 200 分;托管的互联设备 10 分/个**(G4);本项上限 2000 分(G3)。\n'
|
||||
+ '含车联网、智能制造、远程诊断、智能交通等。设备按个累加时用另起的命中记录(分值调为 10)。'),
|
||||
|
||||
/* 11 云管理平台 */
|
||||
sp(11, 10, '管理员 500 / 节点 10 分/台', 'cloud-platform', '云管理平台控制权(含 PaaS 云平台,如 K8S、红帽 OpenShift 等)', 'NETINFRA', 500, 2000, 'system',
|
||||
'**管理员权限 500 分;云上主机、容器 10 分/台**(G4);本项上限 2000 分(G3)。云上业务系统按重要系统规则单独计分。\n'
|
||||
+ '通过 ak/sk 批量控制默认**只计算被控节点分数、不计算管理员分数**,除非提供证明具有管理员权限(如新增云上节点、用户权限管理等)。\n'
|
||||
+ '⚠️ **节点数量小于 100 的按普通 Web 应用给分,节点不给分**(即走第 5、6 项口径)。'),
|
||||
|
||||
/* 12 物联网设备管控平台 */
|
||||
sp(12, 11, '平台 200 / 连接点 10 / 核心网 +5000 分', 'iot-platform', '物联网设备管控平台权限', 'NETINFRA', 200, 2000, 'system',
|
||||
'**带控制功能的物联网平台 200 分;按平台上连接点数计算 10 分/台**(G4);本项上限 2000 分(G3)。\n'
|
||||
+ '**通过物联网端点设备打入核心网并控制业务生产等重要系统的,单独加 5000 分**(不受本项 2000 分上限约束,单独记一条命中)。'),
|
||||
|
||||
/* 13 安全设备 */
|
||||
sp(13, 12, '管理员 200 分', 'secdev', '安全设备权限(IPS、IDS、审计设备、WAF 等非集权类安全设备)', 'NETINFRA', 200, 1000, 'service',
|
||||
'**管理员权限 200 分**;本项上限 1000 分(G3)。仅限非集权类安全设备(集权类走第 7 项)。'),
|
||||
|
||||
/* 14 文件存储类系统 */
|
||||
sp(14, 13, '管理员 50 / 普通 10 分/个', 'file-storage', '文件存储类系统权限(FTP、对象存储、企业 NAS、企业网盘等)', 'STORAGE', 50, 500, 'system',
|
||||
'**管理员权限 50 分/个;普通用户权限、空系统或只含有测试数据的系统 10 分/个**;本项上限 500 分(G3)。\n'
|
||||
+ '含 FTP、对象存储(按系统计分)、企业 NAS、企业网盘等;数据单独计分(G2)。拿到普通权限时把单次分值调整为 10。'),
|
||||
|
||||
/* 15 模型智能体 / agent 工具 */
|
||||
sp(15, 14, '100–500 分/个', 'ai-agent', '模型智能体、skill 等 agent 工具(并能操作 agent 进行攻击)', 'MODEL', 100, 4000, 'service',
|
||||
'**100–500 分/个**,区间分,按控制与操作深度研判;本项上限 4000 分(G3)。\n'
|
||||
+ '含模型智能体、skill 等 agent 工具;记分时在 evidence 里写明控制/操作深度,并按研判档位调整单次分值。'),
|
||||
|
||||
/* 16、17 算力管理平台 + 训练数据/知识库系统(原表两项规则逐字相同) */
|
||||
sp(16, 15, '系统管理权限 500 分/个', 'model-compute', '算力管理平台权限 / 训练数据与知识库系统权限', 'MODEL', 500, 4000, 'system',
|
||||
'**获取系统管理权限 500 分/个**;本项上限 4000 分(G3)。\n'
|
||||
+ '本项合并原表第 16、17 项(规则逐字相同),记分时在 evidence 里写明是哪类系统:\n'
|
||||
+ '· **算力管理平台**(可管控调度算力资源等);\n'
|
||||
+ '· **训练数据、知识库等相关系统**(可窃取篡改训练数据或知识库、实施数据投毒等)。\n'
|
||||
+ '含大量数据系统(超 1 亿条或 10TB)**得分翻倍**、控制知识库相关系统**得分翻倍**(G5)。'),
|
||||
|
||||
/* 18 模型相关数据系统 */
|
||||
sp(18, 16, '系统管理员权限 500 分/个', 'model-data', '模型相关数据系统权限', 'MODEL', 500, 4000, 'system',
|
||||
'**获取系统管理员权限 500 分/个**;本项上限 4000 分(G3)。\n'
|
||||
+ '可干扰模型训练、推理、运营服务,窃取篡改模型权重文件等。\n'
|
||||
+ '⚠️ 与第 16、17 项的差异**不可抹平**:本项**没有"控制知识库相关系统得分翻倍"**,但有"数据资产成果参照数据评分"(G2);'
|
||||
+ '超大数据规模系统(超 1 亿条或超 10TB)得分翻倍(G5)。'),
|
||||
|
||||
/* 19 算力基础设施(权限与算力卡两种计费单位,保留两条) */
|
||||
sp(19, 17, '管理员 500 分/个', 'computepower-admin', '算力基础设施 · 管理员权限', 'MODEL', 500, 2000, 'system',
|
||||
'**管理员权限 500 分/个**;本项上限 2000 分(含路径分,G3)。\n'
|
||||
+ '本项与「算力基础设施 · 算力卡资源」同属第 19 项、共用 2000 分上限,三项(管理员权限 / 大量算力卡资源 / 算力卡池化平台)可分别得分但受本条总上限约束。'),
|
||||
sp(19, 18, '10 分/卡', 'computepower-cards', '算力基础设施 · 算力卡资源 / 算力卡池化平台', 'MODEL', 10, 2000, 'none',
|
||||
'**10 分/卡**,按卡累加(G4);获取大量算力卡资源得分、获取算力卡池化平台直接得分,各上限 2000 分,且与「管理员权限」共用第 19 项总上限 2000 分。\n'
|
||||
+ '记分时在 evidence 里写明卡数或平台名称。'),
|
||||
|
||||
/* ══ 二、突破网络边界(4 项,整个目标单位同一类边界只给一次分)══════════ */
|
||||
|
||||
sp(22, 19, '1000 分', 'boundary-logical', '进入逻辑隔离业务内网', 'BOUNDARY', 1000, 0, 'target',
|
||||
'**1000 分**。适用范围:整个目标单位突破同一类网络边界只给一次分。\n'
|
||||
+ '证明材料(G7):防火墙隔离设备的控制截图、能访问内网的截图证明等。'),
|
||||
sp(23, 20, '10000 分', 'boundary-strong', '进入逻辑强隔离业务内网', 'BOUNDARY', 10000, 0, 'target',
|
||||
'**10000 分**。适用范围:整个目标单位突破同一类网络边界只给一次分。\n'
|
||||
+ '证明材料(G7):网闸类隔离设备的控制截图、能访问内网的截图证明等。'),
|
||||
sp(24, 21, '30000 分', 'boundary-physical', '进入物理隔离内网、核心生产网', 'BOUNDARY', 30000, 0, 'target',
|
||||
'**30000 分**。适用范围:整个目标单位突破同一类网络边界只给一次分。\n'
|
||||
+ '证明材料(G7):防火墙、VPN、多网卡主机、网络设备、网闸类隔离设备的控制截图,能访问内网的截图证明等。\n'
|
||||
+ '如铁路调度专网、银行核心账务网、电力生产控制大区、运营商信令网、能源生产物联网等。'),
|
||||
sp(25, 22, '1000 分(最多 3000)', 'boundary-supply', '借助供应链运维通道或云服务进入内网', 'BOUNDARY', 1000, 3000, 'service',
|
||||
'按三种情形计分:\n'
|
||||
+ '· 进入**同一主防单位内网**:1000 分;\n'
|
||||
+ '· 借助**一家**供应链单位或云服务进入**多家**主防单位内网:1000 分/每家主防单位;\n'
|
||||
+ '· 借助**多家**供应链单位或云服务进入**一家**主防单位内网不同网络区域:1000 分/个,最多 3000 分。\n'
|
||||
+ '记分时在 evidence 里写明属于哪种情形、涉及哪家主防单位/哪个网络区域。'),
|
||||
|
||||
/* ══ 附加成果加成(依附于上面某条权限,但**独立计分、独立上限**)══════════
|
||||
这些条目不是「再拿一个系统权限」,而是「在已拿到的权限上又做到了某件事」(文档里的 +N 分)。
|
||||
压在基础条目里会共用它的 rule 上限、被基础分吃掉,所以拆成独立得分点。 */
|
||||
|
||||
/* 9 网络设备加成:能够借助该设备进行网络重定向或业务劫持 +200 分 */
|
||||
sp(9, 23, '重定向 / 业务劫持 +200 分', 'netdev-redirect', '网络设备 · 借助该设备进行网络重定向或业务劫持', 'NETINFRA', 200, 2000, 'none',
|
||||
'**在原「网络设备权限」分之上另加 200 分**(文档第 9 项)。\n'
|
||||
+ '适用:改路由/策略把流量引向我方可控节点、DNS 劫持、业务流量劫持等实际生效的重定向。\n'
|
||||
+ '需要提供证据(G7):路由表、策略配置或连接量截图;evidence 里写清重定向方向与验证方式。'),
|
||||
|
||||
/* 9 网络设备加成:能在设备上植入远控程序并成功进行后续攻击 1000 分 */
|
||||
sp(9, 24, '植入远控 + 后续攻击 1000 分', 'netdev-implant', '网络设备 · 植入远控程序并成功进行后续攻击', 'NETINFRA', 1000, 2000, 'none',
|
||||
'**在原「网络设备权限」分之上另加 1000 分**(文档第 9 项)。\n'
|
||||
+ '需要证明「植入成功 **且** 借它完成了后续攻击」两件事:远控进程/持久化证据 + 经该设备发起的后续成果。'),
|
||||
|
||||
/* 12 物联网:通过端点设备打入核心网并控制业务生产等重要系统,单独加 5000 分 */
|
||||
sp(12, 25, '核心网 +5000 分', 'iot-corenet', '物联网 · 经端点设备打入核心网并控制重要系统', 'NETINFRA', 5000, 5000, 'none',
|
||||
'**文档第 12 项明确「单独加 5000 分」**,不占该条 2000 分的上限。\n'
|
||||
+ '适用:从物联网端点设备横向进入核心网,并控制业务生产等重要系统;\n'
|
||||
+ 'evidence 里写清:从哪个端点进、核心网里控了什么系统、拿到了什么权限。'),
|
||||
]
|
||||
|
||||
/* ------------------------------------------------------------------ 内部辅助的导出 */
|
||||
|
||||
/**
|
||||
* 下面这些原本是 core.js 里的模块级函数(不对外导出),拆出来之后 core.js 需要用到,
|
||||
* 所以显式导出。它们不属于"给别人用的 API",改签名前先看 core.js 的用法。
|
||||
*/
|
||||
export {
|
||||
normalizePort, targetAuthority, systemKeyOf, pickBestHit, legacyCapGroup,
|
||||
targetHasIpv6Host, evaluateScoreBoard, loadScoreMeta, loadAssetNames, hitPointsOf,
|
||||
scoreMultiplierOf,
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
/**
|
||||
* 技能可用性自检(零依赖,tools 与 UI 共用的**唯一一份**判定逻辑)
|
||||
*
|
||||
* 为什么要有它:技能正文里写着"本机路径 / 环境变量 / VPS 地址",但**技能能列出来 ≠ 能跑**。
|
||||
* 缺 `FOFA_KEY`、工具没落到 `$DSH_HOME/redteam/toolkit/`、VPS 还是占位符,都要等真正动手
|
||||
* 才发现,那时候人已经在靶场里了。这里把判定收成一份:
|
||||
* · 智能体侧 —— `redteam_preflight` 开工前跑一次,缺什么直接找用户要;
|
||||
* · 面板侧 —— 「技能库」页签给每个技能标出可用性状态。
|
||||
*
|
||||
* 判定维度(都是能从技能正文里客观读出来的):
|
||||
* ① 技能文件是否存在、正文能否加载;
|
||||
* ② 必需环境变量(`os.environ["X"]` / `process.env.X`;带默认值的 `os.environ.get("X", "…")` 不算必需);
|
||||
* ③ 正文里引用的本机路径(toolkit / bin / local 下的绝对路径、`$DSH_HOME`、`~/`);
|
||||
* ④ 外部基础设施占位符(如 `<你的VPS_IP>` 没填)。
|
||||
*
|
||||
* 不判定:语义正确性、权限、目标可达性 —— 那些只有真打一次才知道。
|
||||
*/
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import { homedir } from 'node:os'
|
||||
import { resolve } from 'node:path'
|
||||
|
||||
/** 解析 $DSH_HOME / ${DSH_HOME} / ~(技能正文里几种写法都有)。 */
|
||||
export function expandSkillPath(p, env = process.env) {
|
||||
const dshHome = env.DSH_HOME || resolve(homedir(), '.dsh')
|
||||
let out = String(p).trim()
|
||||
out = out.replace(/\$\{DSH_HOME\}/g, dshHome).replace(/\$DSH_HOME/g, dshHome)
|
||||
if (out.startsWith('~/')) out = resolve(homedir(), out.slice(2))
|
||||
/* Windows 技能正文偶发混用正斜杠 */
|
||||
if (/^[A-Za-z]:\//.test(out)) out = out.replace(/\//g, '\\')
|
||||
return out
|
||||
}
|
||||
|
||||
/** 从技能正文里抽出"必需但没有设"的环境变量名。 */
|
||||
export function requiredEnvOf(content) {
|
||||
const names = new Set()
|
||||
const body = String(content || '')
|
||||
/* Node 侧:process.env.X(没有默认值这一说) */
|
||||
for (const m of body.matchAll(/process\.env\.([A-Z][A-Z0-9_]{2,})/g)) names.add(m[1])
|
||||
/* Python 侧:os.environ["X"] 必需;os.environ.get("X", "默认") 有兜底,不算必需 */
|
||||
for (const m of body.matchAll(/os\.environ(?:\.get)?[\[(]\s*["']([A-Z][A-Z0-9_]{2,})["']\s*(,)?/g)) {
|
||||
if (m[2] === undefined) names.add(m[1])
|
||||
}
|
||||
/* shell 侧:${X:?必填} 是显式必需;裸 $X 不判定(技能里大量出现 $TARGET 这类占位) */
|
||||
for (const m of body.matchAll(/\$\{([A-Z][A-Z0-9_]{2,}):\?/g)) names.add(m[1])
|
||||
return Array.from(names)
|
||||
}
|
||||
|
||||
/** 正文里引用的、可判定存在性的本机路径(toolkit / bin / local 下的绝对路径)。 */
|
||||
export function referencedPathsOf(content) {
|
||||
const out = new Set()
|
||||
const body = String(content || '')
|
||||
/* Unix / $DSH_HOME / ~ */
|
||||
for (const m of body.matchAll(/(?:~|\$DSH_HOME|\/home\/[^\s"'`,)]+?)\/[\w./\u4e00-\u9fa5-]+/g)) {
|
||||
const raw = m[0].replace(/[,。;、:))\]]+$/, '')
|
||||
if (!/\/(toolkit|bin|local)\//.test(raw)) continue
|
||||
if (/[<>{}*|]/.test(raw)) continue
|
||||
out.add(raw)
|
||||
}
|
||||
/* Windows:D:\…\toolkit\… 或 $DSH_HOME\redteam\toolkit\… */
|
||||
for (const m of body.matchAll(/(?:[A-Za-z]:\\|\$DSH_HOME\\)[^\s"'`,)]+/g)) {
|
||||
const raw = m[0].replace(/[,。;、:))\]]+$/, '')
|
||||
if (!/\\(toolkit|bin|local)\\/i.test(raw) && !/\\nuclei-templates/i.test(raw)) continue
|
||||
if (/[<>{}*]/.test(raw)) continue
|
||||
out.add(raw)
|
||||
}
|
||||
return Array.from(out)
|
||||
}
|
||||
|
||||
/** 从某个技能根里读同名技能的正文(读不到返回 null)。 */
|
||||
export function readSkillFromRoot(root, name) {
|
||||
if (typeof root !== 'string' || root === '') return null
|
||||
for (const dir of [root, resolve(root, String(name || ''))]) {
|
||||
for (const file of [resolve(dir, String(name || '') + '.md'), resolve(dir, 'SKILL.md')]) {
|
||||
try { if (existsSync(file)) return { path: file, content: readFileSync(file, 'utf8') } } catch { /* 继续试下一个 */ }
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查一个技能的可用性。
|
||||
*
|
||||
* @param skill - `{ name, description?, content?, path?, root? }`(content 是技能正文,root 是它来自哪个技能根)。
|
||||
* @param options - `{ env?: NodeJS.ProcessEnv, sameNameIn?: string[] }`。
|
||||
* `sameNameIn` 是**其它也注册了同名技能**的根目录:同名技能会按根顺序择优,被排在后面的那份
|
||||
* 会被"盖住"。这里用它兜底识别"实际加载的是随包占位符版本、而你自己的已配置版本排在后面"的情况。
|
||||
* @returns `{ name, status: 'available'|'broken'|'unknown', problems, needs_user, checked, shadowed_by? }`
|
||||
* status='unknown' 表示"正文读不到,判不了"(例如只有元数据、正文加载失败的远端技能)。
|
||||
*/
|
||||
export function checkSkill(skill, options = {}) {
|
||||
const env = options.env || process.env
|
||||
const name = skill && skill.name ? String(skill.name) : '(未命名)'
|
||||
const content = skill && typeof skill.content === 'string' ? skill.content : ''
|
||||
const file = skill && typeof skill.path === 'string' ? skill.path : null
|
||||
const root = skill && typeof skill.root === 'string' ? skill.root : null
|
||||
const problems = []
|
||||
const needsUser = []
|
||||
|
||||
if (content.trim() === '') {
|
||||
return {
|
||||
name,
|
||||
status: 'unknown',
|
||||
problems: ['技能正文读不到(只有元数据):无法判断可用性,需要时用 `skill` 工具实际加载一次'],
|
||||
needs_user: [],
|
||||
checked: { file, env: [], paths: [] },
|
||||
}
|
||||
}
|
||||
if (file !== null && !existsSync(file)) problems.push('技能文件不存在:' + file)
|
||||
|
||||
const envNames = requiredEnvOf(content)
|
||||
const missingEnv = envNames.filter((n) => !env[n])
|
||||
for (const n of missingEnv) problems.push('缺环境变量 ' + n + '(在「环境适配」填写,或写进 `$DSH_HOME/.env` 后重启当前宿主)')
|
||||
|
||||
const paths = referencedPathsOf(content)
|
||||
const missingPaths = paths.filter((p) => !existsSync(expandSkillPath(p, env)))
|
||||
if (missingPaths.length > 0) {
|
||||
problems.push('引用的本机路径不存在:' + missingPaths.slice(0, 6).join('、')
|
||||
+ (missingPaths.length > 6 ? ' 等 ' + missingPaths.length + ' 处' : ''))
|
||||
}
|
||||
|
||||
/* 外部基础设施占位符:技能里出现 `<你的VPS_IP>` 这类说明还没配。
|
||||
但**已经配好的部署不该被误报**:只要 REDTEAM_VPS_HOST 有值,
|
||||
技能正文里的占位符就只是文档写法(实际命令会用配置值替换),不再算缺口。
|
||||
判定顺序必须是"先看配置、再看占位符",否则配好 VPS 的机器上
|
||||
这几个技能会永远显示 broken(模板占位符与真实配置混在一起)。 */
|
||||
const vpsConfigured = typeof env.REDTEAM_VPS_HOST === 'string' && env.REDTEAM_VPS_HOST.trim() !== ''
|
||||
const placeholders = []
|
||||
if (!vpsConfigured) {
|
||||
if (content.includes('<你的VPS_IP>') || content.includes('<VPS_IP>')) placeholders.push('VPS 地址')
|
||||
if (content.includes('<你的VPS_主机名>') || content.includes('<VPS 主机名>')) placeholders.push('VPS 主机名')
|
||||
}
|
||||
for (const p of placeholders) {
|
||||
problems.push(p + '还是占位符(技能里写的是占位符,说明本机/本环境还没配)')
|
||||
needsUser.push(p)
|
||||
}
|
||||
for (const n of missingEnv) needsUser.push('环境变量 ' + n)
|
||||
|
||||
/* 兜底:同名技能在别的根里有一份"问题更少"的版本(通常是用户自己配过的那份,
|
||||
但被排在前面的随包占位符版本盖住了)。这时如实说明,而不是让用户以为环境没配。 */
|
||||
let shadowed = null
|
||||
for (const other of Array.isArray(options.sameNameIn) ? options.sameNameIn : []) {
|
||||
if (other === root) continue
|
||||
const alt = readSkillFromRoot(other, name)
|
||||
if (alt === null || alt.content === content) continue
|
||||
const verdict = checkSkill({ name, content: alt.content, path: alt.path }, { env })
|
||||
if (verdict.status === 'available' || verdict.problems.length < problems.length) {
|
||||
shadowed = { root: other, path: alt.path, status: verdict.status }
|
||||
problems.push('注意:`' + other + '` 里还有一份同名技能(' + verdict.status + '),'
|
||||
+ '但按技能根顺序当前加载的是这一份(上面这些缺口来自这一份);'
|
||||
+ '要让已配置的那份生效,需把它排到技能根顺序的前面')
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
name,
|
||||
status: problems.length === 0 ? 'available' : 'broken',
|
||||
problems,
|
||||
needs_user: Array.from(new Set(needsUser)),
|
||||
...(shadowed === null ? {} : { shadowed_by: shadowed.root, shadowed_path: shadowed.path }),
|
||||
checked: { file, env: envNames, missing_env: missingEnv, paths, missing_paths: missingPaths },
|
||||
}
|
||||
}
|
||||
|
||||
/** 汇总一批技能的状态(面板顶部标签与 preflight 的返回值都用它)。 */
|
||||
export function summarizeSkills(results) {
|
||||
const out = { total: results.length, available: 0, broken: 0, unknown: 0 }
|
||||
for (const r of results) out[r.status] = (out[r.status] || 0) + 1
|
||||
return out
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* RedTeam 资产库 —— Cordis Host 插件壳
|
||||
*
|
||||
* 职责:把 {@link RedteamStore} 发布为进程级服务 `ctx.redteam`,供
|
||||
* · 客户端界面(经 dsh-redteam-ui 的 HTTP 桥接)
|
||||
* · 各角色智能体的工具行(preset 平面,注入 ctx.redteam)
|
||||
* 共同读取同一份 SQLite 事实库。
|
||||
*
|
||||
* 平面归属:host。资产数据要跨会话被后续漏洞检测/利用/内网智能体共享,
|
||||
* 因此服务实例必须进程级唯一,不能放进 preset。
|
||||
*
|
||||
* 零外部依赖:只用 node: 内置模块,避免 profile 下解析不到 node_modules。
|
||||
*/
|
||||
import { join } from 'node:path'
|
||||
import { homedir } from 'node:os'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { RedteamStore } from './store-core.js'
|
||||
|
||||
/** Cordis 插件名。 */
|
||||
export const name = 'dsh-purge-redteam-store'
|
||||
|
||||
/** 无硬依赖:数据层不依赖其它服务即可激活。 */
|
||||
export const inject = []
|
||||
|
||||
/**
|
||||
* 解析数据根目录:显式配置 > REDTEAM_HOME > $DSH_HOME/redteam。
|
||||
* 组合层通常用 `!!js dshHomePath('redteam')` 直接给出绝对路径。
|
||||
*/
|
||||
function resolveRoot(config) {
|
||||
if (config && typeof config.root === 'string' && config.root.length > 0) return config.root
|
||||
if (process.env.REDTEAM_HOME) return process.env.REDTEAM_HOME
|
||||
const home = process.env.DSH_HOME || join(homedir(), '.dsh')
|
||||
return join(home, 'redteam')
|
||||
}
|
||||
|
||||
/**
|
||||
* 本插件包名与版本(读插件根 package.json:lib/redteam → ../..)。
|
||||
*/
|
||||
function readSelfPackage() {
|
||||
for (const rel of ['../../package.json', '../package.json']) {
|
||||
try {
|
||||
const pkg = JSON.parse(readFileSync(new URL(rel, import.meta.url), 'utf8'))
|
||||
if (pkg && typeof pkg.name === 'string' && typeof pkg.version === 'string') {
|
||||
return {
|
||||
name: pkg.name,
|
||||
version: pkg.version,
|
||||
description: typeof pkg.description === 'string' ? pkg.description : '',
|
||||
homepage: typeof pkg.homepage === 'string' ? pkg.homepage : null,
|
||||
}
|
||||
}
|
||||
} catch { /* 换下一个候选 */ }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ctx - 插件上下文。
|
||||
* @param config - `{ root?: string }`。
|
||||
*/
|
||||
export function apply(ctx, config = {}) {
|
||||
const root = resolveRoot(config)
|
||||
const store = new RedteamStore(root)
|
||||
/* 包身份挂在 store 上:界面桥接层(redteam-ui)的版本显示与更新逻辑都从这里读,
|
||||
不用在生成物里硬编码版本号。 */
|
||||
const self = readSelfPackage()
|
||||
if (self !== null) {
|
||||
try { store.plugin = Object.freeze(self) } catch { /* 忽略 */ }
|
||||
}
|
||||
|
||||
// 服务随 fiber 卸载而关闭:所有 SQLite 句柄在同一处释放。
|
||||
ctx.effect(() => () => store.close())
|
||||
|
||||
ctx.provide('redteam', store)
|
||||
}
|
||||
|
||||
export { RedteamStore }
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,864 @@
|
||||
/**
|
||||
* RedTeam 控制台 —— Host 半侧
|
||||
*
|
||||
* 职责:为浏览器半侧提供一条 Package 私有的 HTTP 桥接 `POST /redteam/api`:
|
||||
* · 资产库相关 op 转交 `ctx.redteam`(dsh-redteam-store 发布的进程级服务);
|
||||
* · 会话连通性 op(probeSessions)在 host 侧真实发起 TCP/HTTP 探测;
|
||||
* · 技能目录 op(skillCatalog / skillRead)直接读 `ctx.skills`,按红队 preset
|
||||
* 的 standing scope 取目录——技能由 DSH 原生 skill 体系管理($DSH_HOME/skills、
|
||||
* 项目 .dsh/skills、.agents/skills),控制台只做浏览。
|
||||
*
|
||||
* 为什么走 webServer 而不是 typert/@Remote:本包与 store 包都刻意保持零外部依赖
|
||||
* (profile 下解析不到 node_modules),具名路由是最小且稳定的接缝。
|
||||
* 跨源请求由 Origin/Host 校验挡住(同源 POST 才放行)。
|
||||
*/
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { resolve, join } from 'node:path'
|
||||
import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, realpathSync } from 'node:fs'
|
||||
import { spawn } from 'node:child_process'
|
||||
import { dispatch, dispatchAsync } from './store-core.js'
|
||||
/* 技能可用性判定与 redteam_preflight 共用同一份实现(环境变量 / 本机路径 / 占位符) */
|
||||
import { checkSkill, summarizeSkills } from './skill-availability.js'
|
||||
import { loadPlatformConfig, mergeConfigEnv, redteamRoot, envAdaptStatus } from './platform-config.js'
|
||||
|
||||
/**
|
||||
* 本包自带技能目录候选。
|
||||
* 桌面端经 profile/node_modules 符号链接加载时,单靠 import.meta.url 拼相对路径
|
||||
* 可能指到不存在的位置(空格路径、未解析的 junction);所以多路探测并 realpath。
|
||||
* 不从 index.js 引 packagePaths,避免与 cordis 插件入口互相拖拽。
|
||||
*/
|
||||
function resolvePluginSkillsDir() {
|
||||
const home = process.env.DSH_HOME || ''
|
||||
const candidates = []
|
||||
try {
|
||||
const root = fileURLToPath(new URL('../..', import.meta.url))
|
||||
candidates.push(join(root, 'skills', 'redteam'))
|
||||
} catch { /* ignore */ }
|
||||
try {
|
||||
candidates.push(resolve(fileURLToPath(new URL('../../skills/redteam/', import.meta.url))))
|
||||
} catch { /* ignore */ }
|
||||
if (home) {
|
||||
for (const profile of ['desktop', 'web', 'headless']) {
|
||||
candidates.push(join(home, 'profiles', profile, 'node_modules', 'dsh-purge', 'skills', 'redteam'))
|
||||
}
|
||||
/* 不扫官方 $DSH_HOME/skills:技能只认本包 skills/redteam(与上游插件包内分发一致)。 */
|
||||
}
|
||||
for (const raw of candidates) {
|
||||
if (!raw) continue
|
||||
try {
|
||||
if (!existsSync(raw)) continue
|
||||
const real = realpathSync(raw)
|
||||
const md = readdirSync(real).filter((f) => f.endsWith('.md'))
|
||||
if (md.length > 0 || /skills[/\\]redteam$/i.test(real) || /[/\\]skills$/i.test(real)) return real
|
||||
} catch { /* try next */ }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const PLUGIN_SKILLS_DIR = resolvePluginSkillsDir()
|
||||
/** 目录比较要规范化:注册表给的是 `/a/b/skills`,URL 拼出来可能带结尾斜杠。 */
|
||||
const sameDir = (a, b) => {
|
||||
if (a === null || b === null) return false
|
||||
try {
|
||||
const left = existsSync(a) ? realpathSync(a) : resolve(a)
|
||||
const right = existsSync(b) ? realpathSync(b) : resolve(b)
|
||||
return left === right
|
||||
} catch {
|
||||
try { return resolve(a) === resolve(b) } catch { return false }
|
||||
}
|
||||
}
|
||||
|
||||
/** Cordis 插件名。 */
|
||||
export const name = 'dsh-purge-redteam-ui'
|
||||
|
||||
/**
|
||||
* 硬依赖只留资产库 + HTTP。
|
||||
* skills / agentPresets 在桌面端时常序更晚或名称不同;写成硬依赖会导致整条
|
||||
* `/redteam/api` 挂不上,界面里技能库/知识库/SQLite 全部读不到。
|
||||
*/
|
||||
export const inject = ['redteam', 'webServer']
|
||||
|
||||
/** 请求体上限(资产导入可能较大)。 */
|
||||
const MAX_BODY_BYTES = 8 * 1024 * 1024
|
||||
|
||||
/* ------------------------------------------------------------------ 版本与更新 */
|
||||
|
||||
/** 运行 shell 命令,带超时;返回 `{ code, stdout, stderr, timedOut }`。 */
|
||||
function run(command, args, options = {}) {
|
||||
return new Promise((resolvePromise) => {
|
||||
let child
|
||||
try {
|
||||
/* ⚠️ 两个都踩过:
|
||||
· env 必须显式传 process.env —— spawn 默认给的是空环境,空 PATH 下
|
||||
npm/pnpm 会直接 `spawn npm ENOENT`(版本检查永远失败);
|
||||
· cwd 必须是**真实存在**的目录 —— 传一个不存在的路径同样是 ENOENT
|
||||
(报错长得像"命令找不到",很容易误判)。 */
|
||||
const cwd = typeof options.cwd === 'string' && options.cwd !== '' && existsSync(options.cwd) ? options.cwd : undefined
|
||||
child = spawn(command, args, {
|
||||
cwd,
|
||||
env: options.env || process.env,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
})
|
||||
} catch (error) {
|
||||
resolvePromise({ code: -1, stdout: '', stderr: error && error.message ? error.message : String(error) })
|
||||
return
|
||||
}
|
||||
let stdout = ''
|
||||
let stderr = ''
|
||||
let settled = false
|
||||
const done = (value) => { if (!settled) { settled = true; resolvePromise(value) } }
|
||||
const timer = setTimeout(() => {
|
||||
try { child.kill('SIGKILL') } catch { /* 忽略 */ }
|
||||
done({ code: -1, stdout: stdout, stderr: stderr, timedOut: true })
|
||||
}, Math.max(Number(options.timeoutMs) || 30000, 1000))
|
||||
child.stdout.on('data', (c) => { stdout += c.toString('utf8') })
|
||||
child.stderr.on('data', (c) => { stderr += c.toString('utf8') })
|
||||
child.on('error', (error) => { clearTimeout(timer); done({ code: -1, stdout: stdout, stderr: String((error && error.message) || error) }) })
|
||||
child.on('close', (code) => { clearTimeout(timer); done({ code: code === null ? -1 : code, stdout: stdout, stderr: stderr }) })
|
||||
})
|
||||
}
|
||||
|
||||
/** 本插件包身份(由 store 壳读取 package.json 后挂上;读不到则报"未知版本")。 */
|
||||
function pluginIdentity(ctx) {
|
||||
const store = ctx.redteam
|
||||
const info = store && store.plugin ? store.plugin : null
|
||||
return {
|
||||
name: (info && info.name) || 'dsh-purge',
|
||||
version: (info && info.version) || null,
|
||||
description: (info && info.description) || '',
|
||||
homepage: (info && info.homepage) || null,
|
||||
}
|
||||
}
|
||||
|
||||
/** profile 目录:DSH 的 `ctx.baseUrl` 就是它(loader.internal.import(name, profileDir) 的 base)。 */
|
||||
function profileDirOf(ctx) {
|
||||
try {
|
||||
if (typeof ctx.baseUrl === 'string' && ctx.baseUrl.length > 0) return ctx.baseUrl
|
||||
} catch { /* 忽略 */ }
|
||||
const home = process.env.DSH_HOME || join(process.env.HOME || '', '.dsh')
|
||||
return join(home, 'profiles', 'web')
|
||||
}
|
||||
|
||||
/** 读 profile 的 package.json(依赖声明 + dsh.profile.bundles)。 */
|
||||
function readProfilePackage(dir) {
|
||||
try {
|
||||
return JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'))
|
||||
} catch { return null }
|
||||
}
|
||||
|
||||
/** 包管理器:profile 里有 pnpm-lock / pnpm-workspace 就用 pnpm,否则 npm。 */
|
||||
function packageManagerOf(dir) {
|
||||
if (existsSync(join(dir, 'pnpm-lock.yaml')) || existsSync(join(dir, 'pnpm-workspace.yaml'))) return 'pnpm'
|
||||
return 'npm'
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新前置检查:装的是不是发布版(profile 里能不能解析到这个包名)、
|
||||
* 有没有智能体正在跑(更新要重启 dsh web,会把它们打断)。
|
||||
*/
|
||||
async function updatePreflight(ctx) {
|
||||
const dir = profileDirOf(ctx)
|
||||
const pkg = pluginIdentity(ctx)
|
||||
const profilePkg = readProfilePackage(dir)
|
||||
const deps = (profilePkg && profilePkg.dependencies) || {}
|
||||
const declared = typeof deps[pkg.name] === 'string' ? deps[pkg.name] : null
|
||||
const installedDir = join(dir, 'node_modules', pkg.name)
|
||||
const blockers = []
|
||||
const notes = []
|
||||
|
||||
/* ① 开发态(源码软链):profile 里没有这个包名 → 不能用包管理器更新 */
|
||||
const devLinked = declared === null && !existsSync(join(installedDir, 'package.json'))
|
||||
if (devLinked) {
|
||||
blockers.push('当前是**开发态安装**(profile 依赖里没有 ' + pkg.name + ',是源码软链/手动挂载的),包管理器更新不适用。')
|
||||
notes.push('开发态请在本仓库升级:`git pull && npm run build:client`,再重启 DeepSeek Harness。')
|
||||
}
|
||||
|
||||
/* ② 有智能体在跑:重启会打断它们 */
|
||||
let running = []
|
||||
try {
|
||||
const subagents = ctx.get('subagents')
|
||||
const sessions = ctx.get('sessions')
|
||||
if (subagents !== undefined && subagents !== null && sessions !== undefined && sessions !== null && typeof sessions.list === 'function') {
|
||||
const roots = sessions.list().filter((s) => {
|
||||
const header = s && s.header
|
||||
return header && (header.parentSession === undefined || header.parentSession === null)
|
||||
})
|
||||
for (const root of roots) {
|
||||
try {
|
||||
const kids = await subagents.listChildren(root.id)
|
||||
for (const k of Array.isArray(kids) ? kids : []) {
|
||||
if (k && k.kind === 'child' && k.activity === 'running') running.push({ session: String(root.id), label: k.label || String(k.id) })
|
||||
}
|
||||
} catch { /* 单个会话读不到不影响其它 */ }
|
||||
}
|
||||
}
|
||||
} catch { /* 注册表不可用就不挡(只是少了一层保护) */ }
|
||||
if (running.length > 0) {
|
||||
blockers.push('有 ' + running.length + ' 个智能体正在跑(' + running.map((r) => r.label).join('、') + '):更新要重启当前宿主,会打断它们。请等它们结束。')
|
||||
}
|
||||
return { dir, declared, packageManager: packageManagerOf(dir), devLinked, running, blockers, notes }
|
||||
}
|
||||
|
||||
/** 到 npm registry 查最新版本(走包管理器,避免自带网络栈)。 */
|
||||
async function checkLatest(ctx, dir, name) {
|
||||
const pm = packageManagerOf(dir)
|
||||
const args = pm === 'pnpm' ? ['view', name, 'version', '--json'] : ['view', name, 'version', '--json']
|
||||
const r = await run(pm, args, { cwd: dir, timeoutMs: 60000 })
|
||||
if (r.code !== 0) {
|
||||
return { ok: false, error: '查询最新版本失败(' + pm + ' view):' + String(r.stderr || r.stdout || '').trim().slice(0, 400) }
|
||||
}
|
||||
const raw = String(r.stdout || '').trim().replace(/^"|"$/g, '')
|
||||
const latest = raw.split('\n').map((x) => x.trim().replace(/^"|"$/g, '')).filter(Boolean).pop() || null
|
||||
return { ok: latest !== null, latest, registry: pm }
|
||||
}
|
||||
|
||||
/** `a < b`(只比较数字段,够用;预发布后缀按"更旧"处理)。 */
|
||||
function versionLess(a, b) {
|
||||
const parse = (v) => String(v || '').split('-')[0].split('.').map((x) => Number(x) || 0)
|
||||
const [x, y] = [parse(a), parse(b)]
|
||||
for (let i = 0; i < Math.max(x.length, y.length); i += 1) {
|
||||
if ((x[i] || 0) < (y[i] || 0)) return true
|
||||
if ((x[i] || 0) > (y[i] || 0)) return false
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* 重启脚本:等旧进程退出 + 端口释放,再按同样的参数把 dsh web 拉起来。
|
||||
*
|
||||
* 生成的是一个**自包含的 node 脚本**(不是 shell 脚本),它做三件事:
|
||||
* ① 等旧 pid 退出(最多 60 秒);
|
||||
* ② 等端口不再被监听(最多 30 秒,用 net 探测,不依赖 ss/lsof);
|
||||
* ③ spawn(command, ARGS_ARRAY) 以 argv 数组拉起新进程。
|
||||
*
|
||||
* 为什么不用 shell:原实现把命令与参数拼成 shell 串,需要一套手写引号转义
|
||||
* (单引号里套单引号、双引号再转义),任何一处漏掉就是命令注入 ——
|
||||
* 而这段脚本正是"由程序生成、以用户身份执行"的,最不该有注入面。
|
||||
* argv 数组交给 spawn 之后 shell 完全不参与,转义问题从根上消失。
|
||||
*
|
||||
* @param pid - 当前进程 pid(等它退出)。
|
||||
* @param port - dsh web 端口(等它释放)。
|
||||
* @param command - 可执行文件(通常是 process.argv[0])。
|
||||
* @param args - 参数数组(process.argv.slice(1))。
|
||||
* @param logPath - 日志文件路径(追加写)。
|
||||
* @param cwd - 新进程的工作目录。
|
||||
* @returns 脚本正文。
|
||||
*/
|
||||
function restartScript(pid, port, command, args, logPath, cwd) {
|
||||
const payload = {
|
||||
oldPid: Number(pid),
|
||||
port: Number(port) || 0,
|
||||
command: String(command),
|
||||
args: args.map((a) => String(a)),
|
||||
log: String(logPath),
|
||||
cwd: String(cwd),
|
||||
}
|
||||
return [
|
||||
'#!/usr/bin/env node',
|
||||
'/* 由 RedTeam 控制台的「自动更新」生成:等旧 dsh web 退出后,按原 argv 把它重新拉起。',
|
||||
' 参数以数组形式传给 spawn —— shell 不参与,因此不存在引号转义与命令注入问题。 */',
|
||||
"'use strict'",
|
||||
'const { spawn } = require("node:child_process")',
|
||||
'const { appendFileSync, mkdirSync } = require("node:fs")',
|
||||
'const { connect } = require("node:net")',
|
||||
'const { dirname } = require("node:path")',
|
||||
'const CFG = ' + JSON.stringify(payload, null, 2),
|
||||
'',
|
||||
'const log = (msg) => {',
|
||||
' const line = "[" + new Date().toISOString() + "] " + msg + "\\n"',
|
||||
' try { mkdirSync(dirname(CFG.log), { recursive: true }); appendFileSync(CFG.log, line) } catch (e) { /* 日志写不进去不该影响重启 */ }',
|
||||
'}',
|
||||
'',
|
||||
'const sleep = (ms) => new Promise((r) => setTimeout(r, ms))',
|
||||
'',
|
||||
'/** 旧进程还在吗(kill -0 的等价物)。 */',
|
||||
'const alive = (pid) => { try { process.kill(pid, 0); return true } catch (e) { return false } }',
|
||||
'',
|
||||
'/** 端口还有人在听吗(不依赖 ss/lsof)。 */',
|
||||
'const portBusy = (port) => new Promise((resolve) => {',
|
||||
' if (!port) { resolve(false); return }',
|
||||
' const sock = connect({ host: "127.0.0.1", port: port })',
|
||||
' let done = false',
|
||||
' const finish = (busy) => { if (!done) { done = true; try { sock.destroy() } catch (e) {} resolve(busy) } }',
|
||||
' sock.setTimeout(800)',
|
||||
' sock.on("connect", () => finish(true))',
|
||||
' sock.on("timeout", () => finish(false))',
|
||||
' sock.on("error", () => finish(false))',
|
||||
'})',
|
||||
'',
|
||||
'async function main() {',
|
||||
' log("等待旧进程 pid=" + CFG.oldPid + " 退出…")',
|
||||
' for (let i = 0; i < 60; i += 1) {',
|
||||
' if (!alive(CFG.oldPid)) break',
|
||||
' await sleep(1000)',
|
||||
' }',
|
||||
' for (let i = 0; i < 30; i += 1) {',
|
||||
' if (!(await portBusy(CFG.port))) break',
|
||||
' await sleep(1000)',
|
||||
' }',
|
||||
' log("启动:" + CFG.command + " " + CFG.args.join(" "))',
|
||||
' const child = spawn(CFG.command, CFG.args, {',
|
||||
' cwd: CFG.cwd,',
|
||||
' detached: true,',
|
||||
' stdio: ["ignore", "ignore", "ignore"],',
|
||||
' env: process.env,',
|
||||
' })',
|
||||
' child.unref()',
|
||||
' log("已拉起新进程 pid=" + child.pid)',
|
||||
'}',
|
||||
'',
|
||||
'main().catch((error) => { log("重启失败:" + (error && error.message ? error.message : String(error))) })',
|
||||
'',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
/** 应用更新:装新版本 + 生成重启脚本 + 让当前进程退出。 */
|
||||
async function applyUpdate(ctx, dir, name, targetVersion) {
|
||||
const pm = packageManagerOf(dir)
|
||||
const spec = targetVersion ? name + '@' + targetVersion : name
|
||||
const args = pm === 'pnpm' ? ['add', spec] : ['install', spec, '--save']
|
||||
const r = await run(pm, args, { cwd: dir, timeoutMs: 300000 })
|
||||
if (r.code !== 0) {
|
||||
return { ok: false, error: '安装失败(' + pm + ' ' + args.join(' ') + '):' + String(r.stderr || r.stdout || '').trim().slice(0, 1200) }
|
||||
}
|
||||
/* 重启:拿当前进程的启动命令原样再来一遍 */
|
||||
const argv = process.argv.slice()
|
||||
const command = argv[0]
|
||||
const rest = argv.slice(1)
|
||||
const port = (() => {
|
||||
try { return String(ctx.webServer.port) } catch { return '3080' }
|
||||
})()
|
||||
const root = (() => {
|
||||
try { return ctx.redteam.root } catch { return join(process.env.DSH_HOME || '.', 'redteam') }
|
||||
})()
|
||||
mkdirSync(root, { recursive: true })
|
||||
const logPath = join(root, 'update.log')
|
||||
const scriptPath = join(root, 'restart-dsh-web.sh')
|
||||
writeFileSync(scriptPath, restartScript(process.pid, port, command, rest, logPath, process.cwd()), { encoding: 'utf8', mode: 0o755 })
|
||||
const child = spawn(process.execPath, [scriptPath], { detached: true, stdio: 'ignore' })
|
||||
child.unref()
|
||||
/* 给浏览器留出收到响应的窗口,然后退出 —— 新进程由脚本按原命令行拉起 */
|
||||
setTimeout(() => { process.exit(0) }, 1200).unref()
|
||||
return {
|
||||
ok: true, installed: spec, packageManager: pm,
|
||||
restart: { script: scriptPath, log: logPath, port, command: [command].concat(rest).join(' '), pid: process.pid },
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/** 读取完整请求体;超过上限即中断。 */
|
||||
function readBody(req) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks = []
|
||||
let size = 0
|
||||
req.on('data', (chunk) => {
|
||||
size += chunk.length
|
||||
if (size > MAX_BODY_BYTES) {
|
||||
reject(new Error('request body too large'))
|
||||
req.destroy()
|
||||
return
|
||||
}
|
||||
chunks.push(chunk)
|
||||
})
|
||||
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
|
||||
req.on('error', reject)
|
||||
})
|
||||
}
|
||||
|
||||
/** 统一的 JSON 响应。 */
|
||||
function sendJson(res, status, value) {
|
||||
const body = JSON.stringify(value)
|
||||
res.writeHead(status, {
|
||||
'content-type': 'application/json; charset=utf-8',
|
||||
'cache-control': 'no-store',
|
||||
'content-length': Buffer.byteLength(body),
|
||||
})
|
||||
res.end(body)
|
||||
}
|
||||
|
||||
/** 技能可用性缓存:`{ at, scope, byName: Map }`;30 秒内复用。 */
|
||||
let skillAvailabilityCache = null
|
||||
const SKILL_AVAILABILITY_TTL_MS = 30000
|
||||
|
||||
/**
|
||||
* 安全取 Cordis 服务:未 inject 时 ctx.get / 点属性都会抛,不能让它冒泡成 400。
|
||||
*/
|
||||
function softService(ctx, name) {
|
||||
if (!ctx) return undefined
|
||||
try {
|
||||
if (typeof ctx.get === 'function') return ctx.get(name)
|
||||
} catch { /* not injected */ }
|
||||
try {
|
||||
return ctx[name]
|
||||
} catch { /* proxy throw */ }
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* 逐个技能的可用性(读正文 → 共享判定模块)。
|
||||
* @param skillsSvc - 已取得的 skills 服务(可为 null)。
|
||||
* @param list - `skills.list()` 的返回(SkillSummary[])。
|
||||
* @param scope - 当前作用域。
|
||||
* @param force - true 时跳过快取缓存。
|
||||
*/
|
||||
async function skillAvailabilityOf(skillsSvc, list, scope, force) {
|
||||
const now = Date.now()
|
||||
if (!force && skillAvailabilityCache !== null
|
||||
&& now - skillAvailabilityCache.at < SKILL_AVAILABILITY_TTL_MS
|
||||
&& skillAvailabilityCache.size === list.length) {
|
||||
return { at: skillAvailabilityCache.at, cached: true, byName: skillAvailabilityCache.byName }
|
||||
}
|
||||
const rootsWith = new Map()
|
||||
for (const x of list) {
|
||||
const dir = x.resourceBase && x.resourceBase.kind === 'directory' ? x.resourceBase.path : null
|
||||
if (dir === null) continue
|
||||
if (!rootsWith.has(x.name)) rootsWith.set(x.name, [])
|
||||
if (!rootsWith.get(x.name).includes(dir)) rootsWith.get(x.name).push(dir)
|
||||
}
|
||||
const byName = new Map()
|
||||
for (const summary of list) {
|
||||
let def
|
||||
try {
|
||||
def = skillsSvc && typeof skillsSvc.get === 'function'
|
||||
? await skillsSvc.get(summary.name, { scope })
|
||||
: undefined
|
||||
} catch { def = undefined }
|
||||
const path = def && typeof def.path === 'string'
|
||||
? def.path
|
||||
: (summary.resourceBase && summary.resourceBase.kind === 'directory' ? summary.resourceBase.path : null)
|
||||
const root = summary.resourceBase && summary.resourceBase.kind === 'directory' ? summary.resourceBase.path : null
|
||||
const verdict = checkSkill({ name: summary.name, content: def && def.content, path, root },
|
||||
{ env: mergeConfigEnv(process.env, loadPlatformConfig(redteamRoot())), sameNameIn: rootsWith.get(summary.name) || [] })
|
||||
byName.set(summary.name, verdict)
|
||||
}
|
||||
skillAvailabilityCache = { at: now, size: list.length, byName }
|
||||
return { at: now, cached: false, byName }
|
||||
}
|
||||
|
||||
/**
|
||||
* 技能目录:桌面端默认读本包 `skills/redteam/*.md`;
|
||||
* 仅当 skills + agentPresets 都可用时才走原生注册表。
|
||||
*/
|
||||
async function handleSkillOp(ctx, request) {
|
||||
if (request.op !== 'skillCatalog' && request.op !== 'skillRead') return undefined
|
||||
|
||||
/* 桌面端绝不能让 "without inject" 冒泡:一律 softService + 文件兜底。 */
|
||||
const skillsSvc = softService(ctx, 'skills')
|
||||
const presetsSvc = softService(ctx, 'agentPresets')
|
||||
|
||||
let scope = null
|
||||
let registryReady = false
|
||||
if (skillsSvc && typeof skillsSvc.list === 'function' && presetsSvc) {
|
||||
const standing = presetsSvc.standingKeyFor
|
||||
if (typeof standing === 'function') {
|
||||
try {
|
||||
scope = await standing.call(presetsSvc, 'redteam')
|
||||
registryReady = scope != null
|
||||
} catch {
|
||||
registryReady = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!registryReady) {
|
||||
return handleSkillOpFromPluginDir(request)
|
||||
}
|
||||
|
||||
if (request.op === 'skillCatalog') {
|
||||
let list = []
|
||||
try {
|
||||
list = await skillsSvc.list({ scope })
|
||||
} catch {
|
||||
list = []
|
||||
}
|
||||
if (!Array.isArray(list) || list.length === 0) {
|
||||
return handleSkillOpFromPluginDir(request)
|
||||
}
|
||||
const availability = await skillAvailabilityOf(skillsSvc, list, scope, request.refresh === true)
|
||||
const pluginDir = resolvePluginSkillsDir()
|
||||
const bySource = new Map()
|
||||
const byDir = new Map()
|
||||
const items = list.map((s) => {
|
||||
const dir = s.resourceBase && s.resourceBase.kind === 'directory' ? s.resourceBase.path : null
|
||||
const name = dir === null ? '(非文件系统来源)' : dir
|
||||
byDir.set(name, (byDir.get(name) || 0) + 1)
|
||||
bySource.set(s.source, (bySource.get(s.source) || 0) + 1)
|
||||
const avail = availability.byName.get(s.name)
|
||||
return {
|
||||
name: s.name,
|
||||
description: s.description,
|
||||
whenToUse: s.whenToUse || '',
|
||||
provider: s.provider,
|
||||
source: s.source,
|
||||
dir: dir,
|
||||
modelInvocable: s.invocation ? s.invocation.modelInvocable !== false : true,
|
||||
userInvocable: s.invocation ? s.invocation.userInvocable !== false : true,
|
||||
fromPlugin: sameDir(dir, pluginDir),
|
||||
availability: avail ? avail.status : 'unknown',
|
||||
problems: avail ? avail.problems : ['未检查'],
|
||||
needs_user: avail ? avail.needs_user : [],
|
||||
}
|
||||
})
|
||||
const availSummary = summarizeSkills(Array.from(availability.byName.values()))
|
||||
return {
|
||||
ok: true,
|
||||
total: items.length,
|
||||
fromPlugin: items.filter((x) => x.fromPlugin).length,
|
||||
availability: {
|
||||
summary: availSummary,
|
||||
checked_at: availability.at,
|
||||
cached: availability.cached,
|
||||
broken: Array.from(availability.byName.values()).filter((x) => x.status === 'broken')
|
||||
.map((x) => ({ name: x.name, problems: x.problems, needs_user: x.needs_user })),
|
||||
note: '可用性 = 技能文件存在 + 正文能加载 + 必需环境变量已设置 + 正文引用的本机路径存在 + 没有未填的基础设施占位符。',
|
||||
},
|
||||
bySource: Array.from(bySource, ([k, n]) => ({ key: k, n })).sort((a, b) => b.n - a.n),
|
||||
byDir: Array.from(byDir, ([k, n]) => ({ key: k, n })).sort((a, b) => b.n - a.n),
|
||||
note: '技能由 DSH 原生注册表管理。本插件自带 ' + items.filter((x) => x.fromPlugin).length + ' 个。',
|
||||
items,
|
||||
}
|
||||
}
|
||||
if (typeof request.name !== 'string' || request.name.length === 0) {
|
||||
return { ok: false, error: 'name required' }
|
||||
}
|
||||
try {
|
||||
const skill = await skillsSvc.get(request.name, { scope })
|
||||
if (skill !== undefined) {
|
||||
return {
|
||||
ok: true,
|
||||
name: skill.name,
|
||||
description: skill.description,
|
||||
whenToUse: skill.whenToUse || '',
|
||||
provider: skill.provider,
|
||||
source: skill.source,
|
||||
path: skill.path || null,
|
||||
content: skill.content || '',
|
||||
}
|
||||
}
|
||||
} catch { /* fall through */ }
|
||||
return handleSkillOpFromPluginDir(request)
|
||||
}
|
||||
|
||||
/** 从本包 skills/redteam 目录拼一份技能目录,并做真实可用性检查(不依赖宿主 skills 注入)。 */
|
||||
function handleSkillOpFromPluginDir(request) {
|
||||
const dir = resolvePluginSkillsDir() || PLUGIN_SKILLS_DIR
|
||||
if (!dir || !existsSync(dir)) {
|
||||
return { ok: false, error: '本包 skills/redteam 目录不存在,且宿主 skills 服务不可用' }
|
||||
}
|
||||
const files = readdirSync(dir).filter((f) => f.endsWith('.md'))
|
||||
const parseMeta = (text) => {
|
||||
const out = { description: '', whenToUse: '' }
|
||||
const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)
|
||||
if (!m) {
|
||||
const first = String(text || '').split(/\r?\n/).find((l) => l.trim()) || ''
|
||||
out.description = first.replace(/^#\s*/, '').trim()
|
||||
return out
|
||||
}
|
||||
for (const line of m[1].split(/\r?\n/)) {
|
||||
const kv = /^(\w+)\s*:\s*(.*)$/.exec(line)
|
||||
if (!kv) continue
|
||||
if (kv[1] === 'description') out.description = kv[2].trim().replace(/^['"]|['"]$/g, '')
|
||||
if (kv[1] === 'when_to_use' || kv[1] === 'whenToUse') out.whenToUse = kv[2].trim().replace(/^['"]|['"]$/g, '')
|
||||
}
|
||||
return out
|
||||
}
|
||||
/* 环境变量:进程 + 平台 config.json(空字段不覆盖) */
|
||||
const cfg = loadPlatformConfig(redteamRoot())
|
||||
const checkEnv = mergeConfigEnv(process.env, cfg)
|
||||
|
||||
if (request.op === 'skillCatalog') {
|
||||
const byName = new Map()
|
||||
const items = files.map((file) => {
|
||||
const name = file.replace(/\.md$/i, '')
|
||||
const path = join(dir, file)
|
||||
let description = ''
|
||||
let whenToUse = ''
|
||||
let content = ''
|
||||
try {
|
||||
content = readFileSync(path, 'utf8')
|
||||
const meta = parseMeta(content)
|
||||
description = meta.description
|
||||
whenToUse = meta.whenToUse
|
||||
} catch { /* ignore */ }
|
||||
const verdict = checkSkill(
|
||||
{ name, content, path, root: dir },
|
||||
{ env: checkEnv },
|
||||
)
|
||||
byName.set(name, verdict)
|
||||
return {
|
||||
name,
|
||||
description,
|
||||
whenToUse,
|
||||
provider: 'dsh-purge',
|
||||
source: 'plugin',
|
||||
dir,
|
||||
modelInvocable: true,
|
||||
userInvocable: true,
|
||||
fromPlugin: true,
|
||||
availability: verdict.status,
|
||||
problems: verdict.problems,
|
||||
needs_user: verdict.needs_user,
|
||||
}
|
||||
}).sort((a, b) => a.name.localeCompare(b.name))
|
||||
const availSummary = summarizeSkills(Array.from(byName.values()))
|
||||
return {
|
||||
ok: true,
|
||||
total: items.length,
|
||||
fromPlugin: items.length,
|
||||
availability: {
|
||||
summary: availSummary,
|
||||
checked_at: Date.now(),
|
||||
cached: false,
|
||||
broken: Array.from(byName.values()).filter((x) => x.status === 'broken')
|
||||
.map((x) => ({ name: x.name, problems: x.problems, needs_user: x.needs_user })),
|
||||
note: '按本包技能文件自检(含环境适配 config.json)。缺密钥/工具会标为不可用,可在「环境适配」补全后点「重查可用性」。',
|
||||
},
|
||||
bySource: [{ key: 'plugin', n: items.length }],
|
||||
byDir: [{ key: dir, n: items.length }],
|
||||
note: '本包 skills/redteam 共 ' + items.length + ' 个技能;可用性已按正文与本机配置检查。',
|
||||
items,
|
||||
}
|
||||
}
|
||||
if (typeof request.name !== 'string' || request.name.length === 0) {
|
||||
return { ok: false, error: 'name required' }
|
||||
}
|
||||
const file = join(dir, request.name.endsWith('.md') ? request.name : (request.name + '.md'))
|
||||
if (!existsSync(file)) return { ok: false, error: 'skill not found: ' + request.name }
|
||||
let content = ''
|
||||
try { content = readFileSync(file, 'utf8') } catch (error) {
|
||||
return { ok: false, error: error && error.message ? error.message : String(error) }
|
||||
}
|
||||
const meta = parseMeta(content)
|
||||
return {
|
||||
ok: true,
|
||||
name: request.name.replace(/\.md$/i, ''),
|
||||
description: meta.description,
|
||||
whenToUse: meta.whenToUse,
|
||||
provider: 'dsh-purge',
|
||||
source: 'plugin',
|
||||
path: file,
|
||||
content,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 智能体并发状态(「智能体」页签用):直接读 subagents 注册表里"真正在跑"的子会话。
|
||||
* 与工具层的 `redteam_agent_slot` 同一套口径,但这里只读不占位。
|
||||
* @param ctx - 插件上下文。
|
||||
* @param request - `{ op: 'agentsStatus' }`。
|
||||
* @returns JSON 结果,或 undefined 表示不是这个 op。
|
||||
*/
|
||||
async function handleAgentsOp(ctx, request) {
|
||||
if (request.op !== 'agentsStatus') return undefined
|
||||
const max = (() => {
|
||||
const raw = Number(process.env.REDTEAM_MAX_AGENTS)
|
||||
return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : 3
|
||||
})()
|
||||
const subagents = ctx.get('subagents')
|
||||
const sessions = ctx.get('sessions')
|
||||
if (subagents === undefined || subagents === null || sessions === undefined || sessions === null || typeof sessions.list !== 'function') {
|
||||
return { ok: false, error: 'subagents / sessions 注册表不可用:读不到并发占用。', max }
|
||||
}
|
||||
const children = []
|
||||
try {
|
||||
const roots = sessions.list().filter((s) => {
|
||||
const header = s && s.header
|
||||
return header && (header.parentSession === undefined || header.parentSession === null)
|
||||
})
|
||||
for (const root of roots) {
|
||||
try {
|
||||
const kids = await subagents.listChildren(root.id)
|
||||
for (const k of Array.isArray(kids) ? kids : []) {
|
||||
if (k && k.kind === 'child') children.push({ parent: String(root.id), label: k.label || String(k.id), activity: k.activity, mode: k.mode })
|
||||
}
|
||||
} catch { /* 单个会话读不到就跳过 */ }
|
||||
}
|
||||
} catch (error) {
|
||||
return { ok: false, error: '列子会话失败:' + (error && error.message ? error.message : String(error)), max }
|
||||
}
|
||||
const running = children.filter((c) => c.activity === 'running')
|
||||
return {
|
||||
ok: true, max, used: running.length, free: Math.max(max - running.length, 0),
|
||||
running: running.slice(0, 20), total_children: children.length,
|
||||
note: '同一会话(靶标)同时最多 ' + max + ' 个执行智能体;默认顺序派活。',
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 版本与更新类 op(面板右上角的「版本 + 自动更新」用)。
|
||||
* 不碰资产库,直接操作 profile 与 npm/pnpm;全部在 host 侧执行。
|
||||
* @param ctx - 插件上下文。
|
||||
* @param request - `{ op: 'version' | 'updateCheck' | 'updateApply', target? }`。
|
||||
* @returns JSON 结果,或 undefined 表示不是更新类 op。
|
||||
*/
|
||||
async function handleUpdateOp(ctx, request) {
|
||||
if (!['version', 'updateCheck', 'updateApply'].includes(request.op)) return undefined
|
||||
const pkg = pluginIdentity(ctx)
|
||||
const pre = await updatePreflight(ctx)
|
||||
if (request.op === 'version') {
|
||||
const check = pre.devLinked ? null : await checkLatest(ctx, pre.dir, pkg.name)
|
||||
return {
|
||||
ok: true,
|
||||
plugin: pkg,
|
||||
install: {
|
||||
mode: pre.devLinked ? 'dev' : 'package',
|
||||
dir: pre.dir,
|
||||
declared: pre.declared,
|
||||
packageManager: pre.packageManager,
|
||||
},
|
||||
latest: check && check.ok ? check.latest : null,
|
||||
updateAvailable: check && check.ok && pkg.version ? versionLess(pkg.version, check.latest) : false,
|
||||
/* 本地版本比 registry 还新:本机跑的是尚未发布的开发版本。
|
||||
不区分这一种,"检查更新"会一直显示"已是最新",把"这个版本根本没发出去"藏起来。 */
|
||||
localAhead: check && check.ok && pkg.version ? versionLess(check.latest, pkg.version) : false,
|
||||
check_error: check && check.ok === false ? check.error : undefined,
|
||||
blockers: pre.blockers,
|
||||
notes: pre.notes,
|
||||
running_agents: pre.running,
|
||||
}
|
||||
}
|
||||
if (request.op === 'updateCheck') {
|
||||
const check = await checkLatest(ctx, pre.dir, pkg.name)
|
||||
if (check.ok !== true) return { ok: false, error: check.error, current: pkg.version, install: { mode: pre.devLinked ? 'dev' : 'package' } }
|
||||
const localAhead = pkg.version ? versionLess(check.latest, pkg.version) : false
|
||||
return {
|
||||
ok: true, current: pkg.version, latest: check.latest,
|
||||
updateAvailable: pkg.version ? versionLess(pkg.version, check.latest) : true,
|
||||
localAhead,
|
||||
install: { mode: pre.devLinked ? 'dev' : 'package', dir: pre.dir, packageManager: pre.packageManager },
|
||||
blockers: pre.blockers,
|
||||
notes: pre.notes.concat(localAhead
|
||||
? ['本机版本(' + pkg.version + ')比 npm 上的最新版(' + check.latest + ')还新:'
|
||||
+ '当前跑的是尚未发布的开发版本,包管理器更新不适用(要回退版本请显式指定)。']
|
||||
: []),
|
||||
running_agents: pre.running,
|
||||
}
|
||||
}
|
||||
/* updateApply */
|
||||
if (pre.blockers.length > 0) {
|
||||
return { ok: false, error: '现在不能更新:' + pre.blockers.join(' '), blockers: pre.blockers, notes: pre.notes }
|
||||
}
|
||||
/* target 会被原样拼进 `npm install <target>`:不校验就等于把"装任意包并重启进程"
|
||||
暴露给浏览器侧输入。只接受纯 semver(可带 v 前缀),其余一律拒绝并说清原因。 */
|
||||
const rawTarget = typeof request.target === 'string' ? request.target.trim() : ''
|
||||
if (rawTarget !== '' && !/^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(rawTarget)) {
|
||||
return {
|
||||
ok: false,
|
||||
current: pkg.version,
|
||||
error: 'updateApply 的 target 必须是纯版本号(如 0.11.0),收到 ' + JSON.stringify(rawTarget)
|
||||
+ '。不接受包名、路径、URL 或 npm 参数 —— 它会原样传给包管理器,等于允许远程指定安装内容。',
|
||||
}
|
||||
}
|
||||
const result = await applyUpdate(ctx, pre.dir, pkg.name, rawTarget || null)
|
||||
if (result.ok !== true) return Object.assign({ current: pkg.version }, result)
|
||||
return Object.assign({ current: pkg.version, latest: request.target || null }, result, {
|
||||
note: '已安装,正在重启当前宿主(页面会在几秒内断开,重启完成后刷新即可看到新版本)。重启日志:' + result.restart.log,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ctx - 插件上下文(已保证 redteam / webServer / skills / agentPresets 可用)。
|
||||
*/
|
||||
export function apply(ctx) {
|
||||
const store = ctx.redteam
|
||||
|
||||
/* 红队会话发送后的硬兜底:环境未就绪则 reject 首步,避免直接开干 */
|
||||
try {
|
||||
if (!ctx.__dshpEnvAdaptPreStep) {
|
||||
ctx.__dshpEnvAdaptPreStep = true
|
||||
const root = store && store.root ? store.root : redteamRoot()
|
||||
const hook = async (payload, next) => {
|
||||
try {
|
||||
const agent = payload && payload.agent
|
||||
const header = agent && agent.session && agent.session.header
|
||||
const preset = header && header.agentPreset
|
||||
if (preset === 'redteam') {
|
||||
const turn = Number(payload && payload.turn) || 0
|
||||
const step = Number(payload && payload.step) || 0
|
||||
if (turn <= 1 && step <= 1) {
|
||||
const status = envAdaptStatus(root)
|
||||
if (!status.ready) {
|
||||
return {
|
||||
kind: 'reject',
|
||||
reason: status.message
|
||||
|| '环境未适配:请打开 dsh-purge → 环境适配配置工具,或确认暂不配置后再发送。',
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch { /* 门禁异常不阻断 */ }
|
||||
return next()
|
||||
}
|
||||
const install = () => {
|
||||
try { ctx.on('agent/pre-step', hook, { global: true, prepend: true }) } catch { /* ignore */ }
|
||||
}
|
||||
install()
|
||||
queueMicrotask(install)
|
||||
setTimeout(install, 800)
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
|
||||
ctx.effect(() => ctx.webServer.register({
|
||||
kind: 'exact',
|
||||
path: '/redteam/api',
|
||||
handler: async (req, res) => {
|
||||
if (req.method !== 'POST') {
|
||||
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'
|
||||
if (!loopback) {
|
||||
const origin = req.headers.origin
|
||||
const host = req.headers.host
|
||||
if (typeof origin !== 'string' || origin === '') {
|
||||
sendJson(res, 403, { ok: false, error: 'request without Origin is only accepted from loopback' })
|
||||
return
|
||||
}
|
||||
let originHost = null
|
||||
try { originHost = new URL(origin).host } catch { originHost = null }
|
||||
if (originHost === null || originHost !== host) {
|
||||
sendJson(res, 403, { ok: false, error: 'cross-origin request rejected' })
|
||||
return
|
||||
}
|
||||
}
|
||||
try {
|
||||
const raw = await readBody(req)
|
||||
const request = raw.trim() ? JSON.parse(raw) : {}
|
||||
const agentsResult = await handleAgentsOp(ctx, request)
|
||||
if (agentsResult !== undefined) {
|
||||
sendJson(res, 200, agentsResult)
|
||||
return
|
||||
}
|
||||
const updateResult = await handleUpdateOp(ctx, request)
|
||||
if (updateResult !== undefined) {
|
||||
sendJson(res, 200, updateResult)
|
||||
return
|
||||
}
|
||||
let skillResult
|
||||
try {
|
||||
skillResult = await handleSkillOp(ctx, request)
|
||||
} catch (skillErr) {
|
||||
/* 桌面端 inject 缺失时绝不 400:直接文件兜底 */
|
||||
if (request && (request.op === 'skillCatalog' || request.op === 'skillRead')) {
|
||||
skillResult = handleSkillOpFromPluginDir(request)
|
||||
if (!skillResult || skillResult.ok === false) {
|
||||
skillResult = {
|
||||
ok: false,
|
||||
error: '技能读取失败:' + (skillErr && skillErr.message ? skillErr.message : String(skillErr)),
|
||||
}
|
||||
}
|
||||
} else {
|
||||
throw skillErr
|
||||
}
|
||||
}
|
||||
sendJson(res, 200, skillResult === undefined ? await dispatchAsync(store, request) : skillResult)
|
||||
} catch (error) {
|
||||
sendJson(res, 400, { ok: false, error: error && error.message ? error.message : String(error) })
|
||||
}
|
||||
},
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* 写库前的校验与规范化(零依赖)。
|
||||
*
|
||||
* 从 core.js 抽出来的模块:这些函数决定"什么值允许进库",
|
||||
* 是安全边界所在(路径穿越、非法枚举),值得单独一处、单独读、单独测。
|
||||
*/
|
||||
|
||||
import { resolve, sep } from 'node:path'
|
||||
|
||||
export const WEBSHELL_TYPES = ['behinder', 'godzilla', 'antSword', 'antsword', 'custom']
|
||||
export const WEBSHELL_STATUSES = ['online', 'offline', 'dead', 'unknown']
|
||||
|
||||
/**
|
||||
* 规范化马类型:大小写不敏感、允许中文别名(冰蝎/哥斯拉/蚁剑)。
|
||||
* 认不出就抛错而不是静默存原文 —— 面板的"用户连不上"红标、会话页的连接口令复制
|
||||
* 都按这个字段判断,存进去一个拼错的值不会报错,只会让这两处判定静默失效。
|
||||
* @param value - 原始值(可为空)。
|
||||
* @returns 规范化后的值或 null(空值合法 = 未声明)。
|
||||
*/
|
||||
export function normalizeShellType(value) {
|
||||
const raw = value === undefined || value === null ? '' : String(value).trim()
|
||||
if (raw === '') return null
|
||||
const lower = raw.toLowerCase()
|
||||
if (/behinder|冰蝎/.test(lower)) return 'behinder'
|
||||
if (/godzilla|哥斯拉/.test(lower)) return 'godzilla'
|
||||
if (/antsword|蚁剑/.test(lower)) return 'antSword'
|
||||
if (lower === 'custom' || lower === 'custom-shell' || /自定义|自研/.test(raw)) return 'custom'
|
||||
throw new Error("webshell shell_type 非法:" + JSON.stringify(value)
|
||||
+ '。交付要求是**冰蝎马(behinder)/ 哥斯拉马(godzilla)**(用户要能自己连上);'
|
||||
+ '其它类型请填 custom(只作临时中转,面板会标"用户连不上")。')
|
||||
}
|
||||
|
||||
/** 规范化马状态(界面按 online/offline/unknown 三态显示)。 */
|
||||
export function normalizeShellStatus(value) {
|
||||
const raw = String(value === undefined || value === null ? '' : value).trim().toLowerCase()
|
||||
const aliases = { up: 'online', alive: 'online', down: 'offline', failed: 'offline', removed: 'dead' }
|
||||
const normalized = aliases[raw] || raw
|
||||
if (normalized === '') return 'online'
|
||||
if (!WEBSHELL_STATUSES.includes(normalized)) {
|
||||
throw new Error("webshell status 非法:" + JSON.stringify(value) + "。合法值只有 " + WEBSHELL_STATUSES.join(" / ") + "。")
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 路径必须在允许的根目录内(防目录穿越)。
|
||||
*
|
||||
* 为什么需要:`readAttackFile` / `pocGet` 读的是**数据库里的 path 列**,
|
||||
* 而那个列是智能体自己经 `addAttackFile` / `savePoc` 写进去的 —— 也就是不可信输入。
|
||||
* 一旦填成 `/etc/passwd` 或 `~/.ssh/id_rsa`,面板点一下就把文件读到浏览器里了。
|
||||
* `deletePoc` 早有 startsWith 防护,读路径与写路径却漏了,这里补成一处共用实现。
|
||||
* @param target - 待校验的路径。
|
||||
* @param allowedRoots - 允许的根目录(数组)。
|
||||
* @returns 规范化后的绝对路径。
|
||||
* @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 okFlag = roots.some((root) => abs === root || abs.startsWith(root + sep))
|
||||
if (!okFlag) {
|
||||
throw new Error("path outside allowed roots: " + abs
|
||||
+ "(允许的根:" + roots.join(", ") + ")。这条记录的文件路径不在本靶标目录内,已拒绝读取。")
|
||||
}
|
||||
return abs
|
||||
}
|
||||
@@ -405,18 +405,42 @@ async function rewindOneSession(ctx, controller, sessionId) {
|
||||
if (!childId) return { ok: false, error: "回退会话创建失败" };
|
||||
|
||||
await disarmRewoundSession(ctx, childId);
|
||||
// 宿主只能 fork / create,不能在原会话里截断。不收起旧会话的话,每退一次侧边栏就多一条。
|
||||
const archived = await hideRewoundSource(ctx, sessionId);
|
||||
|
||||
const rec = rememberDraft(childId, plan.text, sessionId);
|
||||
return {
|
||||
ok: true,
|
||||
sessionId: childId,
|
||||
parentId: sessionId,
|
||||
archived,
|
||||
text: rec.text,
|
||||
cut: plan.mode,
|
||||
at: rec.at,
|
||||
};
|
||||
}
|
||||
|
||||
async function hideRewoundSource(ctx, sessionId) {
|
||||
if (!sessionId) return false;
|
||||
const registry = service(ctx, "workspaceRegistry");
|
||||
const workspaces = service(ctx, "workspaces");
|
||||
const target = typeof registry?.archiveSession === "function"
|
||||
? registry
|
||||
: (typeof workspaces?.archiveSession === "function" ? workspaces : null);
|
||||
let hidden = false;
|
||||
if (target) {
|
||||
await target.archiveSession(sessionId, { stopActivity: true });
|
||||
hidden = true;
|
||||
}
|
||||
const listed = findWorkspace(ctx, sessionId);
|
||||
const entity = listed?.id && typeof registry?.get === "function" ? registry.get(listed.id) : null;
|
||||
if (entity && typeof entity.detachSession === "function") {
|
||||
await entity.detachSession(sessionId);
|
||||
hidden = true;
|
||||
}
|
||||
return hidden;
|
||||
}
|
||||
|
||||
export async function analyzeRewind(ctx, sessionId) {
|
||||
if (!sessionId) return { ok: false, error: "没有当前会话" };
|
||||
try {
|
||||
|
||||
Reference in new issue
Block a user