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,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Quarantine snapshot shared by the audit feed, the status tool and the client
|
|
3
|
+
* dialog: current size, retention, and a few recent entries.
|
|
4
|
+
*
|
|
5
|
+
* @module dsh-vigil/quarantine-view
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { formatBytes } from './util.js'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* @param {any} quarantine quarantine facade
|
|
12
|
+
* @returns {{ count: number, bytes: number, ttlDays: number, maxEntries: number, dir: string, entries: Array<object> }}
|
|
13
|
+
*/
|
|
14
|
+
export function quarantineView(quarantine) {
|
|
15
|
+
try {
|
|
16
|
+
const stats = quarantine?.stats?.() ?? {}
|
|
17
|
+
const entries = typeof quarantine?.entries === 'function' ? quarantine.entries() : []
|
|
18
|
+
return {
|
|
19
|
+
count: Number(stats.count) || 0,
|
|
20
|
+
bytes: Number(stats.bytes) || 0,
|
|
21
|
+
ttlDays: Number(stats.ttlDays) || 7,
|
|
22
|
+
maxEntries: Number(stats.maxEntries) || 0,
|
|
23
|
+
dir: typeof stats.dir === 'string' ? stats.dir : '',
|
|
24
|
+
entries: (Array.isArray(entries) ? entries : []).slice(-8).map(entry => ({
|
|
25
|
+
id: entry?.id ?? null,
|
|
26
|
+
kind: typeof entry?.kind === 'string' ? entry.kind : null,
|
|
27
|
+
originalPath: typeof entry?.originalPath === 'string' ? entry.originalPath : null,
|
|
28
|
+
bytes: Number(entry?.bytes) || 0,
|
|
29
|
+
createdAt: typeof entry?.createdAt === 'string' ? entry.createdAt : null,
|
|
30
|
+
})),
|
|
31
|
+
}
|
|
32
|
+
} catch {
|
|
33
|
+
return { count: 0, bytes: 0, ttlDays: 7, maxEntries: 0, dir: '', entries: [] }
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* @param {ReturnType<typeof quarantineView>} view
|
|
39
|
+
* @returns {string}
|
|
40
|
+
*/
|
|
41
|
+
export function describeQuarantineView(view) {
|
|
42
|
+
if (view.count === 0) return '隔离区:空'
|
|
43
|
+
return `隔离区:${view.count} 项,${formatBytes(view.bytes)},保留 ${view.ttlDays} 天`
|
|
44
|
+
}
|
|
@@ -0,0 +1,423 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rule packs: the data half of the built-in rules.
|
|
3
|
+
*
|
|
4
|
+
* The matching engines stay in `sentinel/rules.js` and `audit/rules.js`; the
|
|
5
|
+
* *data* they match with (credential paths, secret shapes, egress APIs,
|
|
6
|
+
* privilege keywords, …) lives here and can be replaced without shipping a new
|
|
7
|
+
* plugin version:
|
|
8
|
+
*
|
|
9
|
+
* 1. the shipped pack `<pluginDir>/rules/*.yaml`;
|
|
10
|
+
* 2. the operator pack `<DSH_HOME>/vigil/rules/*.yaml` (or `rules.dir`),
|
|
11
|
+
* applied after the shipped one — later files win.
|
|
12
|
+
*
|
|
13
|
+
* Any parse/compile failure keeps the previous pack (fail-safe: a broken rule
|
|
14
|
+
* file must never silently weaken the rules). Rule packs are plain data; they
|
|
15
|
+
* cannot add code execution, and every pattern is compiled as a RegExp.
|
|
16
|
+
*
|
|
17
|
+
* @module rules/pack
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { createHash } from 'node:crypto'
|
|
21
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
|
|
22
|
+
import { dirname, join } from 'node:path'
|
|
23
|
+
import { fileURLToPath } from 'node:url'
|
|
24
|
+
import { parseYaml } from './yaml.js'
|
|
25
|
+
|
|
26
|
+
/** Directory holding the shipped packs (`<package>/rules`). */
|
|
27
|
+
const SHIPPED_RULES_DIR = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'rules')
|
|
28
|
+
|
|
29
|
+
/** @typedef {{ re: RegExp, label?: string, kind?: string, detail?: string, api?: string, source: string }} CompiledPattern */
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Built-in defaults. Kept in sync with behaviour that shipped before rule packs
|
|
33
|
+
* existed: with no YAML present the plugin behaves exactly as before.
|
|
34
|
+
* @returns {any}
|
|
35
|
+
*/
|
|
36
|
+
export function defaultPack() {
|
|
37
|
+
return {
|
|
38
|
+
sentinel: {
|
|
39
|
+
credentialPatterns: [
|
|
40
|
+
{ source: '(?:^|[\\\\/\\s"=])\\.ssh(?:[\\\\/\\s"]|$)', flags: 'i', label: 'SSH 目录' },
|
|
41
|
+
{ source: '\\bid_(?:rsa|dsa|ecdsa|ed25519)(?:\\.pub)?\\b', flags: 'i', label: 'SSH 私钥' },
|
|
42
|
+
{ source: '\\.aws[\\\\/](?:credentials|config)\\b', flags: 'i', label: 'AWS 凭据文件' },
|
|
43
|
+
{ source: '\\.git-credentials\\b', flags: 'i', label: 'Git 凭据文件' },
|
|
44
|
+
{ source: '\\.npmrc\\b', flags: 'i', label: 'npm 凭据文件' },
|
|
45
|
+
{ source: '\\.gnupg\\b', flags: 'i', label: 'GPG 密钥目录' },
|
|
46
|
+
{ source: '\\b(?:Login Data|key4\\.db|logins\\.json|cookies\\.sqlite)\\b', flags: 'i', label: '浏览器凭据库' },
|
|
47
|
+
{ source: '\\.(?:pem|p12|pfx)\\b', flags: 'i', label: '证书/私钥文件' },
|
|
48
|
+
{ source: '(?:^|[\\\\/\\s"=])\\.env(?:\\.[\\w-]+)?(?:[\\\\/\\s"]|$)', flags: 'i', label: '.env 环境变量文件' },
|
|
49
|
+
{ source: '(?:^|[\\\\/\\s"=])\\.netrc\\b', flags: 'i', label: '.netrc 凭据文件' },
|
|
50
|
+
{ source: '[\\\\/]\\.docker[\\\\/]config\\.json', flags: 'i', label: 'Docker 凭据文件' },
|
|
51
|
+
{ source: '[\\\\/]\\.kube[\\\\/]config\\b', flags: 'i', label: 'Kubernetes 凭据文件' },
|
|
52
|
+
{ source: '[\\\\/]\\.config[\\\\/]gh[\\\\/]hosts\\.yml', flags: 'i', label: 'GitHub CLI 凭据' },
|
|
53
|
+
{ source: '[\\\\/]\\.config[\\\\/]gcloud[\\\\/]application_default_credentials\\.json', flags: 'i', label: 'GCloud 凭据' },
|
|
54
|
+
],
|
|
55
|
+
persistence: [{
|
|
56
|
+
source: '(?:\\.bashrc|\\.bash_profile|\\.zshrc|\\.zprofile|\\.profile|Microsoft[\\\\/]Windows[\\\\/]Start Menu[\\\\/]Programs[\\\\/]Startup|HKCU[\\\\/:]Software[\\\\/]Microsoft[\\\\/]Windows[\\\\/]CurrentVersion[\\\\/]Run|HKEY_CURRENT_USER[\\\\/]Software[\\\\/]Microsoft[\\\\/]Windows[\\\\/]CurrentVersion[\\\\/]Run|\\\\\\\\CurrentVersion\\\\\\\\Run\\b|launchd|systemd\\/system|ScheduledTasks)',
|
|
57
|
+
flags: 'i',
|
|
58
|
+
}],
|
|
59
|
+
// Fallback subset of the shipped destructive-operation patterns; the full
|
|
60
|
+
// list lives in rules/sentinel.yaml so it can be updated without a release.
|
|
61
|
+
destructiveSystemPatterns: [
|
|
62
|
+
{ source: '(?:^|[\\s;&|(])format(?:\\.com)?\\s+[a-z]:', flags: 'i', label: '格式化磁盘' },
|
|
63
|
+
{ source: '(?:^|[\\s;&|(])diskpart(?:\\.exe)?\\b', flags: 'i', label: '磁盘分区工具' },
|
|
64
|
+
{ source: '(?:^|[\\s;&|(])reg(?:\\.exe)?\\s+(?:delete|import|restore|load|unload)\\b', flags: 'i', label: '注册表删除/导入' },
|
|
65
|
+
{ source: '(?:vssadmin(?:\\.exe)?\\s+(?:delete\\s+shadows|resize\\s+shadowstorage)|wmic[^\\n]*shadowcopy[^\\n]*delete|Win32_ShadowCopy[^\\n]*(?:Remove|Delete)|wbadmin[^\\n]*delete|Disable-ComputerRestore)', flags: 'i', label: '卷影副本/备份删除' },
|
|
66
|
+
{ source: '(?:^|[\\s;&|(])mkfs(?:\\.\\w+)?\\b', flags: 'i', label: 'Linux 文件系统格式化' },
|
|
67
|
+
],
|
|
68
|
+
destructiveDataPatterns: [
|
|
69
|
+
{ source: '\\b(?:DROP\\s+(?:DATABASE|SCHEMA|TABLE)|TRUNCATE\\s+TABLE)\\b', flags: 'i', label: 'SQL 删库/删表' },
|
|
70
|
+
{ source: 'docker\\s+(?:system\\s+prune|volume\\s+(?:rm|prune)|rm\\s+-f)', flags: 'i', label: 'Docker/容器清理与卷删除' },
|
|
71
|
+
{ source: 'kubectl\\s+delete\\s+(?:namespace|ns|pvc|pv|deployment)', flags: 'i', label: 'Kubernetes/Helm 资源删除' },
|
|
72
|
+
{ source: 'git\\s+(?:push[^\\n]*(?:--force\\b|-f\\b)|reset\\s+--hard|filter-branch)', flags: 'i', label: 'Git 历史销毁' },
|
|
73
|
+
],
|
|
74
|
+
},
|
|
75
|
+
audit: {
|
|
76
|
+
credentialPaths: [
|
|
77
|
+
{ source: '(?:~|\\$HOME|%USERPROFILE%|\\$\\{?HOME\\}?)[\\\\/]\\.ssh\\b', label: 'SSH 目录' },
|
|
78
|
+
{ source: '[\\\\/]\\.ssh[\\\\/]', label: 'SSH 目录' },
|
|
79
|
+
{ source: '[\\\\/]\\.aws[\\\\/]credentials\\b', label: 'AWS 凭据' },
|
|
80
|
+
{ source: '[\\\\/]\\.npmrc\\b', label: 'npm 凭据' },
|
|
81
|
+
{ source: '[\\\\/]\\.git-credentials\\b', label: 'Git 凭据' },
|
|
82
|
+
{ source: '[\\\\/]\\.netrc\\b', label: 'netrc 凭据' },
|
|
83
|
+
{ source: '\\bid_(?:rsa|ed25519|ecdsa|dsa)\\b', label: 'SSH 私钥' },
|
|
84
|
+
{ source: '[\\/]\\.env(?:\\.(?:local|production|development|test|staging|preview))?\\b', label: '.env 文件' },
|
|
85
|
+
{ source: '[\\x27"]\\.env(?:\\.(?:local|production|development|test|staging|preview))?[\\x27"]', label: '.env 文件' },
|
|
86
|
+
{ source: '[\\x27"`][^\\x27"`\\n]*\\.(?:pem|key|pfx|p12)[\\x27"`]', label: '私钥/证书文件' },
|
|
87
|
+
{ source: '%APPDATA%[\\\\/][^\\x27"`\\n]*(?:credential|token|secret|\\.ssh|\\.aws|\\.npmrc)', flags: 'i', label: 'AppData 凭据' },
|
|
88
|
+
{ source: '[\\\\/]\\.docker[\\\\/]config\\.json', label: 'Docker 凭据' },
|
|
89
|
+
{ source: '[\\\\/]\\.kube[\\\\/]config\\b', label: 'Kubernetes 凭据' },
|
|
90
|
+
{ source: '[\\\\/]\\.config[\\\\/]gh[\\\\/]hosts\\.yml', label: 'GitHub CLI 凭据' },
|
|
91
|
+
],
|
|
92
|
+
secretTokens: [
|
|
93
|
+
{ kind: 'AWS Access Key', source: '\\b(?:AKIA|ASIA)[0-9A-Z]{16}\\b' },
|
|
94
|
+
{ kind: 'OpenAI API Key', source: '\\bsk-[A-Za-z0-9_-]{20,}\\b' },
|
|
95
|
+
{ kind: 'GitHub Token', source: '\\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}\\b|\\bgithub_pat_[A-Za-z0-9_]{30,}\\b' },
|
|
96
|
+
{ kind: 'Slack Token', source: '\\bxox[baprs]-[A-Za-z0-9-]{10,}\\b' },
|
|
97
|
+
{ kind: 'Google API Key', source: '\\bAIza[0-9A-Za-z_-]{30,}\\b' },
|
|
98
|
+
{ kind: 'GitLab Token', source: '\\bglpat-[A-Za-z0-9_-]{20,}\\b' },
|
|
99
|
+
{ kind: 'JWT', source: '\\beyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\b' },
|
|
100
|
+
],
|
|
101
|
+
privilegePatterns: [
|
|
102
|
+
{ detail: 'danger-full-access 权限模式', source: '\\bdanger-full-access\\b' },
|
|
103
|
+
{ detail: 'dangerously-skip-permissions', source: '\\bdangerously-skip-permissions\\b', flags: 'i' },
|
|
104
|
+
{ detail: 'bypassPermissions / bypass-permissions', source: '\\bbypassPermissions\\b|\\bbypass[-_]permissions\\b' },
|
|
105
|
+
{ detail: 'approval = never/off', source: '\\bapproval\\s*[:=]\\s*[\'"]?(?:never|off|false|allow)\\b', flags: 'i' },
|
|
106
|
+
{ detail: 'sandbox 被关闭', source: '\\bsandbox\\s*[:=]\\s*[\'"]?(?:false|off|none|disabled)\\b', flags: 'i' },
|
|
107
|
+
{ detail: 'permission-presets 被改写', source: '\\bpermission[-_]?presets?\\s*[:=]\\s*[\'"]?(?:danger|full|unrestricted|bypass|allow-all)', flags: 'i' },
|
|
108
|
+
{ detail: '--no-sandbox', source: '--no-sandbox\\b' },
|
|
109
|
+
],
|
|
110
|
+
// Patch files use `key: value`; the generic privilege patterns above match
|
|
111
|
+
// `=` too, but patch scanning wants its own YAML-shaped set.
|
|
112
|
+
patchPrivilegePatterns: [
|
|
113
|
+
{ detail: 'danger-full-access 权限模式', source: 'danger-full-access', flags: 'i' },
|
|
114
|
+
{ detail: 'dangerously-skip-permissions', source: 'dangerously-skip-permissions', flags: 'i' },
|
|
115
|
+
{ detail: 'bypassPermissions', source: 'bypassPermissions|bypass[-_]permissions', flags: 'i' },
|
|
116
|
+
{ detail: 'approval = never/off', source: 'approval\\s*:\\s*[\'"]?(?:never|off|false|allow)\\b', flags: 'i' },
|
|
117
|
+
{ detail: 'sandbox 被关闭', source: 'sandbox\\s*:\\s*[\'"]?(?:false|off|none|disabled)\\b', flags: 'i' },
|
|
118
|
+
{ detail: 'permission-presets 被改写', source: 'permission[-_]?presets?\\s*:\\s*[\'"]?(?:danger|full|unrestricted|bypass)', flags: 'i' },
|
|
119
|
+
],
|
|
120
|
+
egressPatterns: [
|
|
121
|
+
{ api: 'fetch', source: '\\bfetch\\s*\\(' },
|
|
122
|
+
{ api: 'http(s).request', source: '\\bhttps?\\.\\s*(?:request|get)\\s*\\(' },
|
|
123
|
+
{ api: 'axios', source: '\\baxios(?:\\.\\w+)?\\s*\\(' },
|
|
124
|
+
{ api: 'undici', source: '\\bundici\\s*\\.\\s*(?:request|fetch|stream|connect|Pool|Agent)\\b' },
|
|
125
|
+
{ api: 'WebSocket', source: '\\bnew\\s+WebSocket\\s*\\(' },
|
|
126
|
+
{ api: 'net.Socket', source: '\\bnew\\s+(?:net\\.)?Socket\\s*\\(' },
|
|
127
|
+
{ api: 'net.connect', source: '\\bnet\\s*\\.\\s*(?:connect|createConnection)\\s*\\(' },
|
|
128
|
+
{ api: 'XMLHttpRequest', source: '\\bnew\\s+XMLHttpRequest\\s*\\(|\\bnew\\s+window\\.XMLHttpRequest\\s*\\(' },
|
|
129
|
+
{ api: 'EventSource', source: '\\bnew\\s+EventSource\\s*\\(' },
|
|
130
|
+
{ api: 'navigator.sendBeacon', source: '\\bnavigator\\s*\\.\\s*sendBeacon\\s*\\(' },
|
|
131
|
+
{ api: 'tls.connect', source: '\\btls\\s*\\.\\s*connect\\s*\\(' },
|
|
132
|
+
{ api: 'dgram', source: '\\bdgram\\s*\\.\\s*createSocket\\s*\\(' },
|
|
133
|
+
{ api: 'dns 解析', source: '\\bdns\\s*\\.\\s*(?:resolve\\d?|lookup|resolveTxt|resolveSrv)\\s*\\(' },
|
|
134
|
+
{ api: 'Worker(远程脚本)', source: '\\bnew\\s+(?:Shared)?Worker\\s*\\(\\s*[\'"`](?:https?:)?\\/\\/' },
|
|
135
|
+
{ api: 'serviceWorker.register', source: '\\bserviceWorker\\s*\\.\\s*register\\s*\\(' },
|
|
136
|
+
// `const send = fetch` keeps the capability while hiding the callee name.
|
|
137
|
+
{ api: 'fetch (别名)', source: '=\\s*(?:window\\s*\\.\\s*)?fetch\\s*(?:[;,\\n)]|$)' },
|
|
138
|
+
],
|
|
139
|
+
},
|
|
140
|
+
sources: [],
|
|
141
|
+
warnings: [],
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Compile one pattern entry, honouring an explicit flags string.
|
|
147
|
+
* @param {any} entry
|
|
148
|
+
* @param {string} file
|
|
149
|
+
* @returns {CompiledPattern}
|
|
150
|
+
*/
|
|
151
|
+
function compilePattern(entry, file) {
|
|
152
|
+
if (!entry || typeof entry !== 'object' || typeof entry.source !== 'string' || entry.source === '') {
|
|
153
|
+
throw new Error(`${file}: 规则缺少 source 字符串`)
|
|
154
|
+
}
|
|
155
|
+
const flags = typeof entry.flags === 'string' ? entry.flags : ''
|
|
156
|
+
if (!/^[imsu]*$/.test(flags)) throw new Error(`${file}: 不支持的正则 flags "${flags}"`)
|
|
157
|
+
let compiled
|
|
158
|
+
try {
|
|
159
|
+
compiled = new RegExp(entry.source, flags)
|
|
160
|
+
} catch (error) {
|
|
161
|
+
throw new Error(`${file}: 正则无效(${error instanceof Error ? error.message : String(error)})`)
|
|
162
|
+
}
|
|
163
|
+
return {
|
|
164
|
+
re: compiled,
|
|
165
|
+
label: typeof entry.label === 'string' ? entry.label : undefined,
|
|
166
|
+
kind: typeof entry.kind === 'string' ? entry.kind : undefined,
|
|
167
|
+
detail: typeof entry.detail === 'string' ? entry.detail : undefined,
|
|
168
|
+
api: typeof entry.api === 'string' ? entry.api : undefined,
|
|
169
|
+
source: entry.source,
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Sections a pack file may define, with their per-entry required field. */
|
|
174
|
+
const SECTIONS = {
|
|
175
|
+
credentialPatterns: 'sentinel',
|
|
176
|
+
persistence: 'sentinel',
|
|
177
|
+
destructiveSystemPatterns: 'sentinel',
|
|
178
|
+
destructiveDataPatterns: 'sentinel',
|
|
179
|
+
credentialPaths: 'audit',
|
|
180
|
+
secretTokens: 'audit',
|
|
181
|
+
privilegePatterns: 'audit',
|
|
182
|
+
patchPrivilegePatterns: 'audit',
|
|
183
|
+
egressPatterns: 'audit',
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Apply one parsed pack document to the working pack.
|
|
188
|
+
* @param {any} document
|
|
189
|
+
* @param {string} file
|
|
190
|
+
* @param {any} target
|
|
191
|
+
*/
|
|
192
|
+
function applyDocument(document, file, target) {
|
|
193
|
+
if (!document || typeof document !== 'object' || Array.isArray(document)) {
|
|
194
|
+
throw new Error(`${file}: 规则包必须是对象`)
|
|
195
|
+
}
|
|
196
|
+
if (document.schema !== undefined && document.schema !== 1) {
|
|
197
|
+
throw new Error(`${file}: 不支持的 schema ${String(document.schema)}`)
|
|
198
|
+
}
|
|
199
|
+
const append = document.append === true
|
|
200
|
+
for (const [section, group] of Object.entries(SECTIONS)) {
|
|
201
|
+
if (!(section in document)) continue
|
|
202
|
+
const raw = document[section]
|
|
203
|
+
if (!Array.isArray(raw)) throw new Error(`${file}: ${section} 必须是列表`)
|
|
204
|
+
const compiled = raw.map(entry => compilePattern(entry, file))
|
|
205
|
+
target[group][section] = append && Array.isArray(target[group][section])
|
|
206
|
+
? [...target[group][section], ...compiled]
|
|
207
|
+
: compiled
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Current pack (compiled). */
|
|
212
|
+
let currentPack = compileDefaultPack()
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* @returns {any} built-in defaults with the shipped YAML packs applied
|
|
216
|
+
*/
|
|
217
|
+
function compileDefaultPack() {
|
|
218
|
+
const pack = {
|
|
219
|
+
sentinel: {
|
|
220
|
+
credentialPatterns: [],
|
|
221
|
+
persistence: [],
|
|
222
|
+
destructiveSystemPatterns: [],
|
|
223
|
+
destructiveDataPatterns: [],
|
|
224
|
+
},
|
|
225
|
+
audit: {},
|
|
226
|
+
sources: [],
|
|
227
|
+
warnings: [],
|
|
228
|
+
}
|
|
229
|
+
const raw = defaultPack()
|
|
230
|
+
// The shipped YAML is the source of truth. The in-code catalog is only an
|
|
231
|
+
// emergency fallback for a bare checkout where `rules/` is absent; a normal
|
|
232
|
+
// release never merges both copies.
|
|
233
|
+
for (const name of shippedPackNames()) {
|
|
234
|
+
const file = join(SHIPPED_RULES_DIR, name)
|
|
235
|
+
try {
|
|
236
|
+
applyDocument(parseYaml(readFileSync(file, 'utf8')), file, pack)
|
|
237
|
+
pack.sources.push(file)
|
|
238
|
+
} catch (error) {
|
|
239
|
+
pack.warnings.push(`${file}: ${error instanceof Error ? error.message : String(error)}`)
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
if (pack.sources.length === 0) {
|
|
243
|
+
pack.warnings.push('未找到内置规则 YAML(rules/*.yaml),已退回代码内置规则;请检查安装包是否完整')
|
|
244
|
+
applyDocument({
|
|
245
|
+
schema: 1,
|
|
246
|
+
credentialPatterns: raw.sentinel.credentialPatterns,
|
|
247
|
+
persistence: raw.sentinel.persistence,
|
|
248
|
+
destructiveSystemPatterns: raw.sentinel.destructiveSystemPatterns,
|
|
249
|
+
destructiveDataPatterns: raw.sentinel.destructiveDataPatterns,
|
|
250
|
+
credentialPaths: raw.audit.credentialPaths,
|
|
251
|
+
secretTokens: raw.audit.secretTokens,
|
|
252
|
+
privilegePatterns: raw.audit.privilegePatterns,
|
|
253
|
+
patchPrivilegePatterns: raw.audit.patchPrivilegePatterns,
|
|
254
|
+
egressPatterns: raw.audit.egressPatterns,
|
|
255
|
+
}, 'builtin-fallback', pack)
|
|
256
|
+
}
|
|
257
|
+
return pack
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** @returns {string[]} */
|
|
261
|
+
function shippedPackNames() {
|
|
262
|
+
try {
|
|
263
|
+
return readdirSync(SHIPPED_RULES_DIR).filter(name => /\.ya?ml$/i.test(name)).sort()
|
|
264
|
+
} catch {
|
|
265
|
+
return []
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** @returns {any} the active compiled rule pack */
|
|
270
|
+
export function getRulePack() {
|
|
271
|
+
return currentPack
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* Reset the pack to the built-in defaults (used by tests and by a failed load).
|
|
276
|
+
* @returns {any}
|
|
277
|
+
*/
|
|
278
|
+
export function resetRulePack() {
|
|
279
|
+
currentPack = compileDefaultPack()
|
|
280
|
+
return currentPack
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
/** Hash a pack file for the pin lock. */
|
|
285
|
+
export function hashPackFile(file) {
|
|
286
|
+
return createHash('sha256').update(readFileSync(file)).digest('hex')
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* List a pack directory with per-file hashes.
|
|
291
|
+
* @param {string} dir
|
|
292
|
+
* @returns {{ dir: string, exists: boolean, names: string[], files: Record<string,string>, error?: string }}
|
|
293
|
+
*/
|
|
294
|
+
export function describePackDir(dir) {
|
|
295
|
+
/** @type {Record<string,string>} */
|
|
296
|
+
const files = {}
|
|
297
|
+
const names = []
|
|
298
|
+
try {
|
|
299
|
+
if (typeof dir !== 'string' || dir === '' || !existsSync(dir) || !statSync(dir).isDirectory()) {
|
|
300
|
+
return { dir: String(dir ?? ''), exists: false, names, files }
|
|
301
|
+
}
|
|
302
|
+
for (const name of readdirSync(dir).filter(item => /\.ya?ml$/i.test(item)).sort()) {
|
|
303
|
+
files[name] = hashPackFile(join(dir, name))
|
|
304
|
+
names.push(name)
|
|
305
|
+
}
|
|
306
|
+
return { dir, exists: true, names, files }
|
|
307
|
+
} catch (error) {
|
|
308
|
+
return { dir: String(dir ?? ''), exists: false, names, files, error: error instanceof Error ? error.message : String(error) }
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** @param {string} lockPath @returns {any|null} */
|
|
313
|
+
export function readRuleLock(lockPath) {
|
|
314
|
+
if (typeof lockPath !== 'string' || lockPath === '') return null
|
|
315
|
+
try {
|
|
316
|
+
const parsed = JSON.parse(readFileSync(lockPath, 'utf8'))
|
|
317
|
+
return parsed && typeof parsed === 'object' && parsed.files && typeof parsed.files === 'object' ? parsed : null
|
|
318
|
+
} catch {
|
|
319
|
+
return null
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* Trust the current external pack contents by writing a hash lock. Any later
|
|
325
|
+
* change to those files is rejected on load until the operator pins again.
|
|
326
|
+
* @param {{ externalDir?: string, lockPath?: string }} [options]
|
|
327
|
+
* @returns {{ ok: boolean, lockPath?: string, files?: string[], error?: string }}
|
|
328
|
+
*/
|
|
329
|
+
export function pinRulePack(options = {}) {
|
|
330
|
+
const externalDir = typeof options.externalDir === 'string' ? options.externalDir : ''
|
|
331
|
+
const lockPath = typeof options.lockPath === 'string' ? options.lockPath : ''
|
|
332
|
+
if (externalDir === '' || lockPath === '') return { ok: false, error: '缺少规则目录或锁文件路径' }
|
|
333
|
+
const info = describePackDir(externalDir)
|
|
334
|
+
if (!info.exists) return { ok: false, error: `规则目录不可读取:${externalDir}` }
|
|
335
|
+
try {
|
|
336
|
+
mkdirSync(dirname(lockPath), { recursive: true })
|
|
337
|
+
writeFileSync(lockPath, `${JSON.stringify({ v: 1, dir: info.dir, pinnedAt: new Date().toISOString(), files: info.files }, null, 2)}\n`)
|
|
338
|
+
return { ok: true, lockPath, files: info.names }
|
|
339
|
+
} catch (error) {
|
|
340
|
+
return { ok: false, error: error instanceof Error ? error.message : String(error) }
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* Compare the external pack directory against the lock.
|
|
346
|
+
* @param {{ externalDir?: string, lockPath?: string }} [options]
|
|
347
|
+
*/
|
|
348
|
+
export function verifyRulePack(options = {}) {
|
|
349
|
+
const lock = readRuleLock(typeof options.lockPath === 'string' ? options.lockPath : '')
|
|
350
|
+
const info = describePackDir(typeof options.externalDir === 'string' ? options.externalDir : '')
|
|
351
|
+
if (!lock) return { ok: false, state: 'unlocked', error: '规则锁不存在(先运行 vigil_rules action=pin)', dir: info.dir, files: info.names }
|
|
352
|
+
const mismatched = info.names.filter(name => lock.files[name] !== undefined && lock.files[name] !== info.files[name])
|
|
353
|
+
const unlisted = info.names.filter(name => lock.files[name] === undefined)
|
|
354
|
+
const missing = Object.keys(lock.files).filter(name => !info.names.includes(name))
|
|
355
|
+
return {
|
|
356
|
+
ok: mismatched.length === 0 && unlisted.length === 0 && missing.length === 0,
|
|
357
|
+
state: mismatched.length || unlisted.length || missing.length ? 'drift' : 'ok',
|
|
358
|
+
lockDir: lock.dir,
|
|
359
|
+
dir: info.dir,
|
|
360
|
+
mismatched,
|
|
361
|
+
unlisted,
|
|
362
|
+
missing,
|
|
363
|
+
files: info.names,
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* Load the operator pack directory over the shipped/default pack. Any error
|
|
369
|
+
* aborts that file and keeps what was already loaded; warnings are reported
|
|
370
|
+
* through `vigil_status` and the log. When `lockPath` is given, every external
|
|
371
|
+
* file must match the pinned hash or it is skipped.
|
|
372
|
+
*
|
|
373
|
+
* @param {{ externalDir?: string, lockPath?: string, logger?: { warn?: (message: string) => void } }} [options]
|
|
374
|
+
* @returns {{ ok: boolean, sources: string[], warnings: string[] }}
|
|
375
|
+
*/
|
|
376
|
+
export function reloadRulePack(options = {}) {
|
|
377
|
+
const base = compileDefaultPack()
|
|
378
|
+
/** @type {string[]} */
|
|
379
|
+
const warnings = [...base.warnings]
|
|
380
|
+
const dirs = []
|
|
381
|
+
if (typeof options.externalDir === 'string' && options.externalDir !== '') dirs.push(options.externalDir)
|
|
382
|
+
const lock = readRuleLock(typeof options.lockPath === 'string' ? options.lockPath : '')
|
|
383
|
+
for (const dir of dirs) {
|
|
384
|
+
let names = []
|
|
385
|
+
try {
|
|
386
|
+
if (!existsSync(dir) || !statSync(dir).isDirectory()) continue
|
|
387
|
+
names = readdirSync(dir).filter(name => /\.ya?ml$/i.test(name)).sort()
|
|
388
|
+
} catch (error) {
|
|
389
|
+
warnings.push(`${dir}: 目录不可读取(${error instanceof Error ? error.message : String(error)})`)
|
|
390
|
+
continue
|
|
391
|
+
}
|
|
392
|
+
if (names.length === 0) continue
|
|
393
|
+
if (lock && lock.dir !== dir) {
|
|
394
|
+
warnings.push(`${dir}: 规则锁属于其他目录(${lock.dir}),已跳过该目录`)
|
|
395
|
+
continue
|
|
396
|
+
}
|
|
397
|
+
for (const name of names) {
|
|
398
|
+
const file = join(dir, name)
|
|
399
|
+
if (lock) {
|
|
400
|
+
const expected = lock.files[name]
|
|
401
|
+
if (typeof expected !== 'string') {
|
|
402
|
+
warnings.push(`${file}: 未在规则锁中登记,已跳过(vigil_rules action=pin 可重新固定)`)
|
|
403
|
+
continue
|
|
404
|
+
}
|
|
405
|
+
if (hashPackFile(file) !== expected) {
|
|
406
|
+
warnings.push(`${file}: 内容与规则锁不一致,已跳过(如为可信修改,请重新 pin)`)
|
|
407
|
+
continue
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
try {
|
|
411
|
+
const document = parseYaml(readFileSync(file, 'utf8'))
|
|
412
|
+
applyDocument(document, file, base)
|
|
413
|
+
base.sources.push(file)
|
|
414
|
+
} catch (error) {
|
|
415
|
+
warnings.push(`${file}: ${error instanceof Error ? error.message : String(error)}`)
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
currentPack = base
|
|
420
|
+
currentPack.warnings = warnings
|
|
421
|
+
for (const warning of warnings) options.logger?.warn?.(`[dsh-vigil] 规则包:${warning}`)
|
|
422
|
+
return { ok: warnings.length === 0, sources: base.sources, warnings }
|
|
423
|
+
}
|