dsh-vigil 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +188 -0
- package/client.js +4652 -0
- package/cordis.patch.yml +7 -0
- package/docs/DETAIL.md +66 -0
- package/icon.png +0 -0
- package/illustrations/notice.png +0 -0
- package/illustrations/warning.png +0 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +75 -0
- package/rules/audit.yaml +130 -0
- package/rules/manifest.json +7 -0
- package/rules/sentinel.yaml +289 -0
- package/src/alert-route.js +194 -0
- package/src/approval.js +398 -0
- package/src/artwork-route.js +87 -0
- package/src/audit/ast.js +213 -0
- package/src/audit/install-scan.js +127 -0
- package/src/audit/lexer.js +307 -0
- package/src/audit/narrative.js +320 -0
- package/src/audit/rules.js +1440 -0
- package/src/audit/scan.js +880 -0
- package/src/audit-clear-route.js +89 -0
- package/src/audit-feed.js +265 -0
- package/src/audit-log.js +887 -0
- package/src/config-schema.js +194 -0
- package/src/config.js +580 -0
- package/src/delete/command-kinds.js +46 -0
- package/src/delete/lex.js +46 -0
- package/src/delete/parser-posix.js +1427 -0
- package/src/delete/parser-pwsh.js +1729 -0
- package/src/delete/parser.js +2082 -0
- package/src/delete/policy.js +680 -0
- package/src/delete/quarantine.js +417 -0
- package/src/index.js +1134 -0
- package/src/install-scan-route.js +58 -0
- package/src/install-watch.js +389 -0
- package/src/integrity.js +509 -0
- package/src/live-config.js +88 -0
- package/src/quarantine-route.js +74 -0
- package/src/quarantine-view.js +44 -0
- package/src/rules/pack.js +423 -0
- package/src/rules/update.js +341 -0
- package/src/rules/yaml.js +186 -0
- package/src/sage-action-route.js +63 -0
- package/src/sage-provision.js +716 -0
- package/src/sentinel/guard.js +392 -0
- package/src/sentinel/hook.js +546 -0
- package/src/sentinel/rules.js +488 -0
- package/src/sentinel/sage-load.js +79 -0
- package/src/sentinel/sage.js +550 -0
- package/src/tools.js +727 -0
- package/src/update-check.js +339 -0
- package/src/util.js +400 -0
- package/threats/README.md +25 -0
|
@@ -0,0 +1,488 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-specific runtime rules (FR-2.3), applied to a tool call's arguments.
|
|
3
|
+
*
|
|
4
|
+
* These rules complement the Sage engine instead of duplicating it. Sage works
|
|
5
|
+
* on command semantics; the rules here focus on Harness-specific threat surfaces
|
|
6
|
+
* (credential material, dsh config tampering, plugin installation, egress
|
|
7
|
+
* destinations, persistence) and on *tool arguments* other than shell text.
|
|
8
|
+
*
|
|
9
|
+
* Every rule returns a finding with a decision kind (`allow` is never produced;
|
|
10
|
+
* rules only ask or deny). The caller merges findings by taking the strictest.
|
|
11
|
+
*
|
|
12
|
+
* @module dsh-vigil/sentinel-rules
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { basename } from 'node:path'
|
|
16
|
+
import { isWithin, resolvePath, scrubHome, truncate } from '../util.js'
|
|
17
|
+
import { getRulePack } from '../rules/pack.js'
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @typedef {object} RuleFinding
|
|
21
|
+
* @property {string} ruleId
|
|
22
|
+
* @property {'ask'|'deny'} kind
|
|
23
|
+
* @property {string} reason
|
|
24
|
+
* @property {string} [evidence]
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Credential-shaped path fragments, loaded from the rule pack so the data can
|
|
29
|
+
* be updated without shipping a new plugin (`rules/sentinel.yaml`).
|
|
30
|
+
* @returns {Array<{ pattern: RegExp, label: string }>}
|
|
31
|
+
*/
|
|
32
|
+
function credentialPatterns() {
|
|
33
|
+
return getRulePack().sentinel.credentialPatterns.map(item => ({ pattern: item.re, label: item.label ?? item.source }))
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** @returns {RegExp|null} */
|
|
37
|
+
function persistencePattern() {
|
|
38
|
+
return getRulePack().sentinel.persistence[0]?.re ?? null
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Destructive-operation patterns for one group, loaded from the rule pack so the
|
|
43
|
+
* list can be updated without shipping a new plugin (`rules/sentinel.yaml`).
|
|
44
|
+
* @param {'destructiveSystemPatterns'|'destructiveDataPatterns'} section
|
|
45
|
+
* @returns {Array<{ pattern: RegExp, label: string }>}
|
|
46
|
+
*/
|
|
47
|
+
function destructivePatterns(section) {
|
|
48
|
+
return (getRulePack().sentinel[section] ?? []).map(item => ({ pattern: item.re, label: item.label ?? item.source }))
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Network-client invocations that can upload data. */
|
|
52
|
+
const NETWORK_CLIENT = /\b(?:curl|wget|Invoke-WebRequest|Invoke-RestMethod|iwr|irm|Start-BitsTransfer|scp|sftp|rsync|ftp)\b/i
|
|
53
|
+
const UPLOAD_FLAG = /(?:^|\s)(?:-d|--data(?:-binary|-raw)?|-F|--form|-T|--upload-file|-X\s*(?:POST|PUT)|--post-data|--post-file|-method\s+(?:post|put)|-infile(?:[:\s]|$)|-body(?:[:\s]|$))\b/i
|
|
54
|
+
const DOWNLOAD_TO_SHELL = /\b(?:curl|wget|Invoke-WebRequest|iwr|Start-BitsTransfer)\b[\s\S]{0,400}?\|\s*(?:sh|bash|zsh|dash|fish|python[0-9.]*|node|perl|ruby|iex|Invoke-Expression)\b/i
|
|
55
|
+
const DOWNLOAD_INVOKE = /(?:DownloadString|DownloadData|DownloadFile)\s*\(|Invoke-Expression|\biex\b/i
|
|
56
|
+
/**
|
|
57
|
+
* Encoded/obfuscated execution. A bare `-e` is deliberately NOT matched: it is
|
|
58
|
+
* the ordinary inline-code flag of node/python/ruby, and matching it made every
|
|
59
|
+
* `node -e ...` a false positive.
|
|
60
|
+
*/
|
|
61
|
+
const ENCODED_COMMAND = /(?:^|\s)(?:-enc|-encodedcommand|--encoded-command)\b|\bFromBase64String\b|\bbase64\s+(?:-d|--decode|-D)\b/i
|
|
62
|
+
const WRITE_VERB = /\b(?:Set-Content|Add-Content|Out-File|New-Item|echo|printf|tee|sed\s+-i|>\s|>>\s|copy\b|Copy-Item|mkdir|New-ItemProperty|Set-ItemProperty|reg\s+add|Invoke-Expression)\b/i
|
|
63
|
+
/** Verbs that destroy or relocate configuration without writing new content. */
|
|
64
|
+
const DESTRUCTIVE_COMMAND = /\b(?:rm|rmdir|del|erase|rd|Remove-Item|mv|Move-Item|ren|Rename-Item)\b/i
|
|
65
|
+
const SHELL_TOOL = /^(?:pwsh|powershell|bash|sh|zsh|shell|exec|terminal|terminal_exec|run_command|run_shell|command|process|spawn|jobs?_(?:start|run|exec))$/i
|
|
66
|
+
const WRITE_TOOL = /^(?:write|write_file|edit|edit_file|patch|apply_patch|create_file|multi_edit|update_file)$/i
|
|
67
|
+
const DELETE_TOOL = /^(?:delete_file|delete|remove_file|remove|unlink|move_file|move|rename|trash)$/i
|
|
68
|
+
const MANAGER_TOOL = /^(?:plugin_manager|plugin-manager|dsh_plugin_manager|plugin_management)$/i
|
|
69
|
+
const WEB_TOOL = /^(?:web_fetch|web_search|fetch|fetch_url)$/i
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Precompiled host matcher from configuration.
|
|
73
|
+
* @param {string[]} hosts
|
|
74
|
+
* @returns {(url: string) => string|null}
|
|
75
|
+
*/
|
|
76
|
+
function makeHostMatcher(hosts) {
|
|
77
|
+
const list = hosts.map(host => host.toLowerCase())
|
|
78
|
+
return url => {
|
|
79
|
+
let hostname = ''
|
|
80
|
+
try {
|
|
81
|
+
hostname = new URL(url).hostname.toLowerCase()
|
|
82
|
+
} catch {
|
|
83
|
+
const match = /^(?:[a-z]+:\/\/)?([^/:?#\s]+)/i.exec(url)
|
|
84
|
+
hostname = match ? match[1].toLowerCase() : ''
|
|
85
|
+
}
|
|
86
|
+
if (hostname === '') return null
|
|
87
|
+
for (const host of list) {
|
|
88
|
+
if (host.endsWith('.')) {
|
|
89
|
+
if (hostname.startsWith(host)) return host
|
|
90
|
+
} else if (hostname === host || hostname.endsWith(`.${host}`)) {
|
|
91
|
+
return host
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return null
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Extract URL-looking strings from arbitrary text.
|
|
100
|
+
* @param {string} text
|
|
101
|
+
* @returns {string[]}
|
|
102
|
+
*/
|
|
103
|
+
export function extractUrls(text) {
|
|
104
|
+
if (typeof text !== 'string') return []
|
|
105
|
+
const matches = text.match(/\b(?:https?|ftp):\/\/[^\s"'`<>]+/gi) ?? []
|
|
106
|
+
return [...new Set(matches.map(url => url.replace(/[),.;]+$/, '')))]
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Extract the shell command text from a tool call's arguments, if any.
|
|
111
|
+
* @param {string} toolName
|
|
112
|
+
* @param {Record<string, any>} args
|
|
113
|
+
* @returns {string|null}
|
|
114
|
+
*/
|
|
115
|
+
export function commandTextOf(toolName, args) {
|
|
116
|
+
if (!args || typeof args !== 'object') return null
|
|
117
|
+
for (const key of ['command', 'cmd', 'script', 'shell', 'commandLine', 'command_line']) {
|
|
118
|
+
const value = args[key]
|
|
119
|
+
if (typeof value === 'string' && value.trim() !== '') return value
|
|
120
|
+
}
|
|
121
|
+
// Some shell tools accept an argv array instead of a single string.
|
|
122
|
+
for (const key of ['args', 'argv']) {
|
|
123
|
+
const value = args[key]
|
|
124
|
+
if (Array.isArray(value) && value.every(item => typeof item === 'string')) return value.join(' ')
|
|
125
|
+
}
|
|
126
|
+
return null
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* The list of path-like values in a tool call.
|
|
131
|
+
* @param {Record<string, any>} args
|
|
132
|
+
* @returns {string[]}
|
|
133
|
+
*/
|
|
134
|
+
export function pathsOf(args) {
|
|
135
|
+
if (!args || typeof args !== 'object') return []
|
|
136
|
+
/** @type {string[]} */
|
|
137
|
+
const paths = []
|
|
138
|
+
for (const key of ['path', 'file_path', 'filePath', 'target', 'targetPath', 'destination', 'destination_path', 'source', 'paths', 'files']) {
|
|
139
|
+
const value = args[key]
|
|
140
|
+
if (typeof value === 'string' && value.trim() !== '') paths.push(value)
|
|
141
|
+
else if (Array.isArray(value)) {
|
|
142
|
+
for (const item of value) if (typeof item === 'string' && item.trim() !== '') paths.push(item)
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return paths
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* @param {string} value
|
|
150
|
+
* @returns {string}
|
|
151
|
+
*/
|
|
152
|
+
function evidence(value) {
|
|
153
|
+
return truncate(scrubHome(String(value)).replace(/\s+/g, ' ').trim(), 180)
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Inspect one tool call with the dsh-specific rules.
|
|
158
|
+
*
|
|
159
|
+
* @param {{ name: string, arguments?: unknown, agent?: { id?: string } }} exec
|
|
160
|
+
* @param {any} config resolved configuration
|
|
161
|
+
* @param {{ cwd: string, pluginDir?: string }} context
|
|
162
|
+
* @returns {{ findings: RuleFinding[], ruleIds: string[], reasons: string[] }}
|
|
163
|
+
*/
|
|
164
|
+
export function inspectToolCall(exec, config, context) {
|
|
165
|
+
// `sentinel.enabled: false` disables these rules even when the deletion guard
|
|
166
|
+
// keeps the shared pre-execute listener mounted.
|
|
167
|
+
if (config?.sentinel?.enabled === false) return { findings: [], ruleIds: [], reasons: [] }
|
|
168
|
+
/** @type {RuleFinding[]} */
|
|
169
|
+
const findings = []
|
|
170
|
+
const toolName = typeof exec?.name === 'string' ? exec.name : ''
|
|
171
|
+
const args = exec?.arguments && typeof exec.arguments === 'object' ? /** @type {Record<string, any>} */ (exec.arguments) : {}
|
|
172
|
+
const sentinel = config?.sentinel ?? {}
|
|
173
|
+
const dshHome = config?.paths?.dshHome ?? ''
|
|
174
|
+
const quarantineDir = config?.paths?.quarantineDir ?? ''
|
|
175
|
+
const hostMatcher = makeHostMatcher(sentinel.suspiciousHosts ?? [])
|
|
176
|
+
const allowMatcher = makeHostMatcher(sentinel.allowedHosts ?? [])
|
|
177
|
+
const command = commandTextOf(toolName, args)
|
|
178
|
+
const paths = pathsOf(args)
|
|
179
|
+
// Text that *reaches* credential material or a destination. Write/edit tool
|
|
180
|
+
// content is deliberately excluded: writing a file that mentions `~/.ssh` is
|
|
181
|
+
// not reading a key, and blocking documentation/tests would be noise.
|
|
182
|
+
const accessText = [
|
|
183
|
+
command ?? '',
|
|
184
|
+
paths.join(' '),
|
|
185
|
+
typeof args.url === 'string' ? args.url : '',
|
|
186
|
+
].join('\n').trim()
|
|
187
|
+
const combinedText = [
|
|
188
|
+
accessText,
|
|
189
|
+
typeof args.content === 'string' ? args.content : '',
|
|
190
|
+
typeof args.new_string === 'string' ? args.new_string : '',
|
|
191
|
+
typeof args.prompt === 'string' ? args.prompt : '',
|
|
192
|
+
].join('\n').trim()
|
|
193
|
+
|
|
194
|
+
/** @param {RuleFinding} finding */
|
|
195
|
+
const add = finding => findings.push(finding)
|
|
196
|
+
|
|
197
|
+
/** Resolve one argument path against the effective working directory. */
|
|
198
|
+
const resolveForCheck = value => {
|
|
199
|
+
try {
|
|
200
|
+
return resolvePath(String(value), context.cwd)
|
|
201
|
+
} catch {
|
|
202
|
+
return ''
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const isShell = SHELL_TOOL.test(toolName)
|
|
207
|
+
const isWrite = WRITE_TOOL.test(toolName)
|
|
208
|
+
const isDelete = DELETE_TOOL.test(toolName)
|
|
209
|
+
const isManager = MANAGER_TOOL.test(toolName)
|
|
210
|
+
const isWeb = WEB_TOOL.test(toolName)
|
|
211
|
+
const credentialRules = credentialPatterns()
|
|
212
|
+
const persistenceRule = persistencePattern()
|
|
213
|
+
|
|
214
|
+
// ---- VG-RT-01: credential material is touched ---------------------------
|
|
215
|
+
if (sentinel.credentialReads !== 'allow' && accessText !== '') {
|
|
216
|
+
const hits = credentialRules.filter(item => item.pattern.test(accessText))
|
|
217
|
+
if (hits.length > 0) {
|
|
218
|
+
const labels = hits.map(hit => hit.label).join('、')
|
|
219
|
+
add({
|
|
220
|
+
ruleId: 'VG-RT-01',
|
|
221
|
+
kind: sentinel.credentialReads === 'deny' ? 'deny' : 'ask',
|
|
222
|
+
reason: `该调用会触达凭证材料(${labels}),可能泄露私钥或令牌`,
|
|
223
|
+
evidence: evidence(accessText),
|
|
224
|
+
})
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// ---- VG-RT-02: credentials leave the machine ----------------------------
|
|
229
|
+
if (sentinel.credentialExfil !== 'allow') {
|
|
230
|
+
const touchesCredential = credentialRules.some(item => item.pattern.test(accessText))
|
|
231
|
+
const exfilMechanism = UPLOAD_FLAG.test(command ?? '')
|
|
232
|
+
|| /\|\s*(?:sh|bash)\b/i.test(command ?? '')
|
|
233
|
+
// scp/sftp copy the file to another host without an explicit upload flag.
|
|
234
|
+
|| /\b(?:scp|sftp)\b/i.test(command ?? '')
|
|
235
|
+
if (touchesCredential && NETWORK_CLIENT.test(command ?? accessText) && exfilMechanism) {
|
|
236
|
+
add({
|
|
237
|
+
ruleId: 'VG-RT-02',
|
|
238
|
+
kind: sentinel.credentialExfil === 'deny' ? 'deny' : 'ask',
|
|
239
|
+
reason: '该调用同时读取凭证并向外发送数据,疑似凭据外泄',
|
|
240
|
+
evidence: evidence(command ?? accessText),
|
|
241
|
+
})
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// ---- VG-RT-03: remote code is downloaded and executed -------------------
|
|
246
|
+
const dynamicRemoteCode = sentinel.dynamicRemoteCode
|
|
247
|
+
?? (sentinel.denyDynamicRemoteCode === false ? 'allow' : 'deny')
|
|
248
|
+
if (dynamicRemoteCode !== 'allow') {
|
|
249
|
+
const downloadToShell = DOWNLOAD_TO_SHELL.test(command ?? '')
|
|
250
|
+
const downloadInvoke = DOWNLOAD_INVOKE.test(command ?? '') && /\b(?:curl|wget|Invoke-WebRequest|iwr|http)\b/i.test(command ?? '')
|
|
251
|
+
if (downloadToShell || downloadInvoke) {
|
|
252
|
+
add({
|
|
253
|
+
ruleId: 'VG-RT-03',
|
|
254
|
+
kind: dynamicRemoteCode === 'ask' ? 'ask' : 'deny',
|
|
255
|
+
reason: dynamicRemoteCode === 'ask'
|
|
256
|
+
? '该命令会从网络下载脚本并立即执行,是否允许?'
|
|
257
|
+
: '该命令会从网络下载脚本并立即执行,dsh-vigil 默认拒绝此类动态远程代码',
|
|
258
|
+
evidence: evidence(command ?? ''),
|
|
259
|
+
})
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// ---- VG-RT-04/05/06: egress destinations --------------------------------
|
|
264
|
+
if (isShell || isWeb) {
|
|
265
|
+
const urls = extractUrls(accessText)
|
|
266
|
+
for (const url of urls) {
|
|
267
|
+
const suspicious = hostMatcher(url)
|
|
268
|
+
if (suspicious) {
|
|
269
|
+
add({
|
|
270
|
+
ruleId: 'VG-RT-04',
|
|
271
|
+
kind: 'deny',
|
|
272
|
+
reason: `目标是已知的文件分享/隧道站点(${suspicious}),数据外发风险高`,
|
|
273
|
+
evidence: evidence(url),
|
|
274
|
+
})
|
|
275
|
+
continue
|
|
276
|
+
}
|
|
277
|
+
if (allowMatcher(url)) continue
|
|
278
|
+
const isUpload = UPLOAD_FLAG.test(combinedText) || (isWeb && /[?&](?:data|content|token)=/i.test(url))
|
|
279
|
+
if (isUpload && sentinel.postToUnknownHost !== 'allow') {
|
|
280
|
+
add({
|
|
281
|
+
ruleId: 'VG-RT-05',
|
|
282
|
+
kind: sentinel.postToUnknownHost === 'deny' ? 'deny' : 'ask',
|
|
283
|
+
reason: '该调用会向非白名单主机发送数据,可能包含敏感信息',
|
|
284
|
+
evidence: evidence(url),
|
|
285
|
+
})
|
|
286
|
+
} else if (!isUpload && sentinel.downloadToUnknownHost !== 'allow' && NETWORK_CLIENT.test(combinedText)) {
|
|
287
|
+
add({
|
|
288
|
+
ruleId: 'VG-RT-06',
|
|
289
|
+
kind: sentinel.downloadToUnknownHost === 'deny' ? 'deny' : 'ask',
|
|
290
|
+
reason: '该调用会从非白名单主机下载内容',
|
|
291
|
+
evidence: evidence(url),
|
|
292
|
+
})
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// ---- VG-RT-07: dsh configuration tampering ------------------------------
|
|
298
|
+
if (sentinel.configTamper !== 'allow' && dshHome) {
|
|
299
|
+
const configNames = /\b(?:cordis\.patch\.yml|cordis\.yml|cordis\.yaml|settings\.json|permission-presets|sandbox-policy)\b/i
|
|
300
|
+
const touchesDshConfig = paths.some(path => isWithin(dshHome, resolveForCheck(path)))
|
|
301
|
+
const commandMutates = typeof command === 'string' && (WRITE_VERB.test(command) || DESTRUCTIVE_COMMAND.test(command))
|
|
302
|
+
const commandTargetsProfile = Boolean(command) && configNames.test(/** @type {string} */ (command))
|
|
303
|
+
&& commandMutates
|
|
304
|
+
&& (/** @type {string} */ (command).includes(dshHome) || /profiles[\\/]/.test(/** @type {string} */ (command)) || /\.dsh\b/.test(/** @type {string} */ (command)))
|
|
305
|
+
// Only the *access* text counts: a document that merely mentions a config
|
|
306
|
+
// path in its body is data, not a mutation of that path.
|
|
307
|
+
const writesPrivilegedConfig = accessText.includes(dshHome)
|
|
308
|
+
&& configNames.test(accessText)
|
|
309
|
+
&& (isWrite || isDelete || commandMutates)
|
|
310
|
+
if ((isManager && /\b(?:config|patch|apply|set)\b/i.test(JSON.stringify(args))) || touchesDshConfig && (isWrite || isDelete) || commandTargetsProfile || writesPrivilegedConfig) {
|
|
311
|
+
// Editing a project's own package.json must stay allowed; only dsh's own
|
|
312
|
+
// profile configuration is protected.
|
|
313
|
+
const pathInDsh = paths.some(path => isWithin(dshHome, resolveForCheck(path)))
|
|
314
|
+
const onlyProjectPackage = !pathInDsh && !commandTargetsProfile && !writesPrivilegedConfig
|
|
315
|
+
if (!onlyProjectPackage) {
|
|
316
|
+
add({
|
|
317
|
+
ruleId: 'VG-RT-07',
|
|
318
|
+
kind: sentinel.configTamper === 'deny' ? 'deny' : 'ask',
|
|
319
|
+
reason: '该调用会修改 dsh 的配置、沙箱或审批策略,dsh-vigil 不允许代理自行改动安全配置',
|
|
320
|
+
evidence: evidence(accessText),
|
|
321
|
+
})
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// ---- VG-RT-08: plugin installation / removal ----------------------------
|
|
327
|
+
if (isManager && sentinel.dshPluginInstall !== 'allow') {
|
|
328
|
+
const serialized = JSON.stringify(args)
|
|
329
|
+
const action = typeof args.action === 'string' ? args.action.toLowerCase() : ''
|
|
330
|
+
const installLike = /install|enable|update|upgrade|add/.test(action) || /install|enable/.test(serialized)
|
|
331
|
+
const removeLike = /remove|uninstall|delete|disable/.test(action) || /remove|uninstall/.test(serialized)
|
|
332
|
+
if (installLike || removeLike) {
|
|
333
|
+
add({
|
|
334
|
+
ruleId: 'VG-RT-08',
|
|
335
|
+
kind: sentinel.dshPluginInstall === 'deny' ? 'deny' : 'ask',
|
|
336
|
+
reason: installLike
|
|
337
|
+
? '该调用会安装或更新插件;请先用 vigil_scan 审计其风险面'
|
|
338
|
+
: '该调用会移除/禁用插件;请确认要移除的对象',
|
|
339
|
+
evidence: evidence(serialized),
|
|
340
|
+
})
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// ---- VG-RT-09: persistence writes ---------------------------------------
|
|
345
|
+
if (sentinel.persistenceWrites !== 'allow' && (isWrite || isShell || isDelete) && persistenceRule?.test(accessText)) {
|
|
346
|
+
add({
|
|
347
|
+
ruleId: 'VG-RT-09',
|
|
348
|
+
kind: sentinel.persistenceWrites === 'deny' ? 'deny' : 'ask',
|
|
349
|
+
reason: '该调用会写入开机自启/登录脚本等持久化位置',
|
|
350
|
+
evidence: evidence(combinedText),
|
|
351
|
+
})
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// ---- VG-RT-10: encoded or obfuscated command ----------------------------
|
|
355
|
+
if (sentinel.encodedCommand !== 'allow' && isShell && command && ENCODED_COMMAND.test(command)) {
|
|
356
|
+
add({
|
|
357
|
+
ruleId: 'VG-RT-10',
|
|
358
|
+
kind: sentinel.encodedCommand === 'deny' ? 'deny' : 'ask',
|
|
359
|
+
reason: '命令使用 base64/编码形式执行,内容无法被静态审阅',
|
|
360
|
+
evidence: evidence(command),
|
|
361
|
+
})
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// ---- VG-RT-13: forced move silently overwrites the destination ----------
|
|
365
|
+
if (isShell && typeof command === 'string'
|
|
366
|
+
&& /\b(?:Move-Item|mv|move)\b[^\n;|&]*?\s(?:-Force|-f)\b/i.test(command)) {
|
|
367
|
+
add({
|
|
368
|
+
ruleId: 'VG-RT-13',
|
|
369
|
+
kind: 'ask',
|
|
370
|
+
reason: '移动并强制覆盖目标位置会静默销毁目标原有内容',
|
|
371
|
+
evidence: evidence(command),
|
|
372
|
+
})
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// ---- VG-RT-14: irreversible system destruction --------------------------
|
|
376
|
+
// Disk/partition/boot, registry, shadow copies, event logs, security controls,
|
|
377
|
+
// trust store, accounts and system permission files. Data-driven from the rule
|
|
378
|
+
// pack so new patterns ship through a rules update instead of a plugin release.
|
|
379
|
+
const destructiveText = [command ?? '', paths.join(' ')].join('\n').trim()
|
|
380
|
+
const systemDestructive = sentinel.destructiveSystem ?? 'deny'
|
|
381
|
+
if (destructiveText !== '' && systemDestructive !== 'allow') {
|
|
382
|
+
const hits = destructivePatterns('destructiveSystemPatterns').filter(item => item.pattern.test(destructiveText))
|
|
383
|
+
if (hits.length > 0) {
|
|
384
|
+
const labels = [...new Set(hits.map(hit => hit.label))].slice(0, 4).join('、')
|
|
385
|
+
add({
|
|
386
|
+
ruleId: 'VG-RT-14',
|
|
387
|
+
kind: systemDestructive === 'ask' ? 'ask' : 'deny',
|
|
388
|
+
reason: `该调用会执行不可逆的系统破坏性操作(${labels})`,
|
|
389
|
+
evidence: evidence(command ?? destructiveText),
|
|
390
|
+
})
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// ---- VG-RT-15: large-scale data destruction -----------------------------
|
|
395
|
+
// Databases, containers, cloud resources, git history and availability
|
|
396
|
+
// actions; default ask because these are sometimes legitimate operator work.
|
|
397
|
+
const dataDestructive = sentinel.destructiveData ?? 'ask'
|
|
398
|
+
if (destructiveText !== '' && dataDestructive !== 'allow') {
|
|
399
|
+
const hits = destructivePatterns('destructiveDataPatterns').filter(item => item.pattern.test(destructiveText))
|
|
400
|
+
if (hits.length > 0) {
|
|
401
|
+
const labels = [...new Set(hits.map(hit => hit.label))].slice(0, 4).join('、')
|
|
402
|
+
add({
|
|
403
|
+
ruleId: 'VG-RT-15',
|
|
404
|
+
kind: dataDestructive === 'deny' ? 'deny' : 'ask',
|
|
405
|
+
reason: `该调用会大规模销毁数据或影响服务可用性(${labels})`,
|
|
406
|
+
evidence: evidence(command ?? destructiveText),
|
|
407
|
+
})
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
// ---- VG-RT-12: Windows device path target --------------------------------
|
|
412
|
+
// `Move-Item x -Destination \\.\NUL` (or CON/COM1/…) destroys data without
|
|
413
|
+
// showing up as a delete; treat any device-path target as a denial.
|
|
414
|
+
if (isShell || isWrite || isDelete) {
|
|
415
|
+
const device = /(?:^|[\s'"=])\\\\\.\\(?:NUL|CON|AUX|PRN|COM[1-9]|LPT[1-9])\b/i.exec(accessText)
|
|
416
|
+
if (device) {
|
|
417
|
+
add({
|
|
418
|
+
ruleId: 'VG-RT-12',
|
|
419
|
+
kind: 'deny',
|
|
420
|
+
reason: '目标指向 Windows 设备路径(如 \\\\.\\NUL),写入/移动会直接销毁数据',
|
|
421
|
+
evidence: evidence(device[0]),
|
|
422
|
+
})
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
// ---- VG-RT-11: dsh-vigil state tampering --------------------------------
|
|
427
|
+
// Reads are allowed: inspecting the quarantine (manifest, size) is legitimate.
|
|
428
|
+
// Only a call that *targets* the quarantine with a write/delete is denied.
|
|
429
|
+
if (quarantineDir) {
|
|
430
|
+
const pathInQuarantine = paths.some(path => isWithin(quarantineDir, resolveForCheck(path)))
|
|
431
|
+
const shellMutatesQuarantine = isShell && typeof command === 'string'
|
|
432
|
+
&& (WRITE_VERB.test(command) || DESTRUCTIVE_COMMAND.test(command))
|
|
433
|
+
&& command.includes(quarantineDir)
|
|
434
|
+
if (((isDelete || isWrite) && pathInQuarantine) || shellMutatesQuarantine) {
|
|
435
|
+
add({
|
|
436
|
+
ruleId: 'VG-RT-11',
|
|
437
|
+
kind: 'deny',
|
|
438
|
+
reason: '该调用会改动隔离区内容(恢复/永久删除请使用 vigil_quarantine 工具)',
|
|
439
|
+
evidence: evidence(accessText),
|
|
440
|
+
})
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
const ruleIds = [...new Set(findings.map(finding => finding.ruleId))]
|
|
445
|
+
const reasons = findings.map(finding => finding.reason)
|
|
446
|
+
return { findings, ruleIds, reasons }
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/**
|
|
450
|
+
* @param {string} toolName
|
|
451
|
+
* @returns {boolean} whether the tool can mutate the filesystem / spawn a shell
|
|
452
|
+
*/
|
|
453
|
+
export function isRelevantTool(toolName) {
|
|
454
|
+
return SHELL_TOOL.test(toolName)
|
|
455
|
+
|| WRITE_TOOL.test(toolName)
|
|
456
|
+
|| DELETE_TOOL.test(toolName)
|
|
457
|
+
|| MANAGER_TOOL.test(toolName)
|
|
458
|
+
|| WEB_TOOL.test(toolName)
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* @param {string} toolName
|
|
463
|
+
* @returns {boolean}
|
|
464
|
+
*/
|
|
465
|
+
export function isShellTool(toolName) {
|
|
466
|
+
return SHELL_TOOL.test(toolName)
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* @param {string} toolName
|
|
471
|
+
* @returns {boolean}
|
|
472
|
+
*/
|
|
473
|
+
export function isDeleteTool(toolName) {
|
|
474
|
+
return DELETE_TOOL.test(toolName)
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/**
|
|
478
|
+
* @param {string} toolName
|
|
479
|
+
* @returns {boolean}
|
|
480
|
+
*/
|
|
481
|
+
export function isWriteTool(toolName) {
|
|
482
|
+
return WRITE_TOOL.test(toolName)
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/** @returns {string} the base file name of a path (for persistence checks) */
|
|
486
|
+
export function baseName(value) {
|
|
487
|
+
return basename(String(value))
|
|
488
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Loading helper for the provisioned Sage engine.
|
|
3
|
+
*
|
|
4
|
+
* Shared by the adapter (`sage.js`) and the provisioning module so the install
|
|
5
|
+
* verification and the live engine go through exactly the same loader:
|
|
6
|
+
*
|
|
7
|
+
* - Sage 0.15's `dist/clients/amsi-spawn.js` calls a bare `require()` from an
|
|
8
|
+
* ESM file (its connectors ship an esbuild bundle where that resolves;
|
|
9
|
+
* importing the npm package directly on plain Node does not). A temporary
|
|
10
|
+
* global `require` shim supplies the CommonJS resolver while the module and
|
|
11
|
+
* its imports initialize.
|
|
12
|
+
* - Verification also loads and validates the rule set, so a broken upstream
|
|
13
|
+
* release is detected before the runtime swaps onto it.
|
|
14
|
+
*
|
|
15
|
+
* @module dsh-vigil/sage-load
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { createRequire } from 'node:module'
|
|
19
|
+
import { pathToFileURL } from 'node:url'
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Install the CommonJS resolver as a global for the duration of one import.
|
|
23
|
+
* @returns {() => void} restore function
|
|
24
|
+
*/
|
|
25
|
+
function installRequireShim() {
|
|
26
|
+
const previous = /** @type {any} */ (globalThis).require
|
|
27
|
+
if (typeof previous === 'function') return () => {}
|
|
28
|
+
try {
|
|
29
|
+
/** @type {any} */ (globalThis).require = createRequire(import.meta.url)
|
|
30
|
+
} catch {
|
|
31
|
+
return () => {}
|
|
32
|
+
}
|
|
33
|
+
return () => {
|
|
34
|
+
try {
|
|
35
|
+
delete /** @type {any} */ (globalThis).require
|
|
36
|
+
} catch {
|
|
37
|
+
// non-configurable global: leave it in place
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Import one Sage entry after installing the require shim.
|
|
44
|
+
* @param {string} specifier absolute path or bare specifier
|
|
45
|
+
* @returns {Promise<any>}
|
|
46
|
+
*/
|
|
47
|
+
export async function importSageModule(specifier) {
|
|
48
|
+
const restore = installRequireShim()
|
|
49
|
+
try {
|
|
50
|
+
return await import(specifier)
|
|
51
|
+
} finally {
|
|
52
|
+
restore()
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Load the engine and its rule set from an installed tree and report what was
|
|
58
|
+
* found. Used after a download/update and by the adapter's first import.
|
|
59
|
+
* @param {{ modulePath: string|null, threatsDir: string|null }} location
|
|
60
|
+
* @returns {Promise<{ ok: boolean, rules: number, error: string|null, module: any|null }>}
|
|
61
|
+
*/
|
|
62
|
+
export async function verifySageModule(location) {
|
|
63
|
+
if (!location?.modulePath) return { ok: false, rules: 0, error: '缺少 Sage 引擎路径', module: null }
|
|
64
|
+
if (!location?.threatsDir) return { ok: false, rules: 0, error: '缺少 Sage 规则目录', module: null }
|
|
65
|
+
let module
|
|
66
|
+
try {
|
|
67
|
+
module = await importSageModule(pathToFileURL(location.modulePath).href)
|
|
68
|
+
} catch (error) {
|
|
69
|
+
return { ok: false, rules: 0, error: `引擎加载失败:${error instanceof Error ? error.message : String(error)}`, module: null }
|
|
70
|
+
}
|
|
71
|
+
try {
|
|
72
|
+
const threats = await module.loadThreats(location.threatsDir)
|
|
73
|
+
const rules = Array.isArray(threats) ? threats.length : 0
|
|
74
|
+
if (rules === 0) return { ok: false, rules: 0, error: '规则集为空', module }
|
|
75
|
+
return { ok: true, rules, error: null, module }
|
|
76
|
+
} catch (error) {
|
|
77
|
+
return { ok: false, rules: 0, error: `规则加载失败:${error instanceof Error ? error.message : String(error)}`, module }
|
|
78
|
+
}
|
|
79
|
+
}
|