@guava-parity/guard-scanner 5.1.0
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 +21 -0
- package/README.md +250 -0
- package/SECURITY.md +45 -0
- package/SKILL.md +141 -0
- package/docs/THREAT_TAXONOMY.md +308 -0
- package/hooks/guard-scanner/HOOK.md +93 -0
- package/hooks/guard-scanner/handler.ts +5 -0
- package/hooks/guard-scanner/plugin.ts +308 -0
- package/openclaw.plugin.json +55 -0
- package/package.json +58 -0
- package/src/cli.js +170 -0
- package/src/html-template.js +239 -0
- package/src/ioc-db.js +54 -0
- package/src/patterns.js +249 -0
- package/src/quarantine.js +41 -0
- package/src/runtime-guard.js +346 -0
- package/src/scanner.js +1045 -0
package/src/scanner.js
ADDED
|
@@ -0,0 +1,1045 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* guard-scanner v2.1.0 ā Agent Skill Security Scanner š”ļø
|
|
4
|
+
*
|
|
5
|
+
* @security-manifest
|
|
6
|
+
* env-read: []
|
|
7
|
+
* env-write: []
|
|
8
|
+
* network: none
|
|
9
|
+
* fs-read: [scan target directory (user-specified)]
|
|
10
|
+
* fs-write: [JSON/SARIF/HTML reports to scan directory]
|
|
11
|
+
* exec: none
|
|
12
|
+
* purpose: Static analysis of agent skill files for threat patterns
|
|
13
|
+
*
|
|
14
|
+
* Based on GuavaGuard v9.0.0 (OSS extraction)
|
|
15
|
+
* 20 threat categories ⢠Snyk ToxicSkills + OWASP MCP Top 10
|
|
16
|
+
* Zero dependencies ⢠CLI + JSON + SARIF + HTML output
|
|
17
|
+
* Plugin API for custom detection rules
|
|
18
|
+
*
|
|
19
|
+
* Born from a real 3-day agent identity hijack (2026-02-12)
|
|
20
|
+
*
|
|
21
|
+
* License: MIT
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
const fs = require('fs');
|
|
25
|
+
const path = require('path');
|
|
26
|
+
const os = require('os');
|
|
27
|
+
const crypto = require('crypto');
|
|
28
|
+
|
|
29
|
+
const { PATTERNS } = require('./patterns.js');
|
|
30
|
+
const { KNOWN_MALICIOUS } = require('./ioc-db.js');
|
|
31
|
+
const { generateHTML } = require('./html-template.js');
|
|
32
|
+
|
|
33
|
+
// ===== CONFIGURATION =====
|
|
34
|
+
const VERSION = '5.0.8';
|
|
35
|
+
|
|
36
|
+
const THRESHOLDS = {
|
|
37
|
+
normal: { suspicious: 30, malicious: 80 },
|
|
38
|
+
strict: { suspicious: 20, malicious: 60 },
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
// File classification
|
|
42
|
+
const CODE_EXTENSIONS = new Set(['.js', '.ts', '.mjs', '.cjs', '.py', '.sh', '.bash', '.ps1', '.rb', '.go', '.rs', '.php', '.pl']);
|
|
43
|
+
const DOC_EXTENSIONS = new Set(['.md', '.txt', '.rst', '.adoc']);
|
|
44
|
+
const DATA_EXTENSIONS = new Set(['.json', '.yaml', '.yml', '.toml', '.xml', '.csv']);
|
|
45
|
+
const BINARY_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.ico', '.woff', '.woff2', '.ttf', '.eot', '.wasm', '.wav', '.mp3', '.mp4', '.webm', '.ogg', '.pdf', '.zip', '.tar', '.gz', '.bz2', '.7z', '.exe', '.dll', '.so', '.dylib']);
|
|
46
|
+
const GENERATED_REPORT_FILES = new Set(['guard-scanner-report.json', 'guard-scanner-report.html', 'guard-scanner.sarif']);
|
|
47
|
+
|
|
48
|
+
// Severity weights for risk scoring
|
|
49
|
+
const SEVERITY_WEIGHTS = { CRITICAL: 40, HIGH: 15, MEDIUM: 5, LOW: 2 };
|
|
50
|
+
|
|
51
|
+
class GuardScanner {
|
|
52
|
+
constructor(options = {}) {
|
|
53
|
+
this.verbose = options.verbose || false;
|
|
54
|
+
this.selfExclude = options.selfExclude || false;
|
|
55
|
+
this.strict = options.strict || false;
|
|
56
|
+
this.summaryOnly = options.summaryOnly || false;
|
|
57
|
+
this.quiet = options.quiet || false;
|
|
58
|
+
this.checkDeps = options.checkDeps || false;
|
|
59
|
+
this.soulLock = options.soulLock || false;
|
|
60
|
+
this.scannerDir = path.resolve(__dirname);
|
|
61
|
+
this.thresholds = this.strict ? THRESHOLDS.strict : THRESHOLDS.normal;
|
|
62
|
+
this.findings = [];
|
|
63
|
+
this.stats = { scanned: 0, clean: 0, low: 0, suspicious: 0, malicious: 0 };
|
|
64
|
+
this.ignoredSkills = new Set();
|
|
65
|
+
this.ignoredPatterns = new Set();
|
|
66
|
+
this.customRules = [];
|
|
67
|
+
|
|
68
|
+
// Plugin API: load plugins
|
|
69
|
+
if (options.plugins && Array.isArray(options.plugins)) {
|
|
70
|
+
for (const plugin of options.plugins) {
|
|
71
|
+
this.loadPlugin(plugin);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Custom rules file (legacy compat)
|
|
76
|
+
if (options.rulesFile) {
|
|
77
|
+
this.loadCustomRules(options.rulesFile);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Plugin API: load a plugin module
|
|
82
|
+
loadPlugin(pluginPath) {
|
|
83
|
+
try {
|
|
84
|
+
const plugin = require(path.resolve(pluginPath));
|
|
85
|
+
if (plugin.patterns && Array.isArray(plugin.patterns)) {
|
|
86
|
+
for (const p of plugin.patterns) {
|
|
87
|
+
if (p.id && p.regex && p.severity && p.cat && p.desc) {
|
|
88
|
+
this.customRules.push(p);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
if (!this.summaryOnly) {
|
|
92
|
+
console.log(`š Plugin loaded: ${plugin.name || pluginPath} (${plugin.patterns.length} rule(s))`);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
} catch (e) {
|
|
96
|
+
console.error(`ā ļø Failed to load plugin ${pluginPath}: ${e.message}`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Custom rules from JSON file
|
|
101
|
+
loadCustomRules(rulesFile) {
|
|
102
|
+
try {
|
|
103
|
+
const content = fs.readFileSync(rulesFile, 'utf-8');
|
|
104
|
+
const rules = JSON.parse(content);
|
|
105
|
+
if (!Array.isArray(rules)) {
|
|
106
|
+
console.error(`ā ļø Custom rules file must be a JSON array`);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
for (const rule of rules) {
|
|
110
|
+
if (!rule.id || !rule.pattern || !rule.severity || !rule.cat || !rule.desc) {
|
|
111
|
+
console.error(`ā ļø Skipping invalid rule: ${JSON.stringify(rule).substring(0, 80)}`);
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
try {
|
|
115
|
+
const flags = rule.flags || 'gi';
|
|
116
|
+
this.customRules.push({
|
|
117
|
+
id: rule.id,
|
|
118
|
+
cat: rule.cat,
|
|
119
|
+
regex: new RegExp(rule.pattern, flags),
|
|
120
|
+
severity: rule.severity,
|
|
121
|
+
desc: rule.desc,
|
|
122
|
+
codeOnly: rule.codeOnly || false,
|
|
123
|
+
docOnly: rule.docOnly || false,
|
|
124
|
+
all: !rule.codeOnly && !rule.docOnly
|
|
125
|
+
});
|
|
126
|
+
} catch (e) {
|
|
127
|
+
console.error(`ā ļø Invalid regex in rule ${rule.id}: ${e.message}`);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
if (!this.summaryOnly && this.customRules.length > 0) {
|
|
131
|
+
console.log(`š Loaded ${this.customRules.length} custom rule(s) from ${rulesFile}`);
|
|
132
|
+
}
|
|
133
|
+
} catch (e) {
|
|
134
|
+
console.error(`ā ļø Failed to load custom rules: ${e.message}`);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// Load .guava-guard-ignore / .guard-scanner-ignore from scan directory
|
|
139
|
+
loadIgnoreFile(scanDir) {
|
|
140
|
+
const ignorePaths = [
|
|
141
|
+
path.join(scanDir, '.guard-scanner-ignore'),
|
|
142
|
+
path.join(scanDir, '.guava-guard-ignore'),
|
|
143
|
+
];
|
|
144
|
+
for (const ignorePath of ignorePaths) {
|
|
145
|
+
if (!fs.existsSync(ignorePath)) continue;
|
|
146
|
+
const lines = fs.readFileSync(ignorePath, 'utf-8').split('\n');
|
|
147
|
+
for (const line of lines) {
|
|
148
|
+
const trimmed = line.trim();
|
|
149
|
+
if (!trimmed || trimmed.startsWith('#')) continue;
|
|
150
|
+
if (trimmed.startsWith('pattern:')) {
|
|
151
|
+
this.ignoredPatterns.add(trimmed.replace('pattern:', '').trim());
|
|
152
|
+
} else {
|
|
153
|
+
this.ignoredSkills.add(trimmed);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
if (this.verbose && (this.ignoredSkills.size || this.ignoredPatterns.size)) {
|
|
157
|
+
console.log(`š Loaded ignore file: ${this.ignoredSkills.size} skills, ${this.ignoredPatterns.size} patterns`);
|
|
158
|
+
}
|
|
159
|
+
break; // use first found
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
scanDirectory(dir) {
|
|
164
|
+
if (!fs.existsSync(dir)) {
|
|
165
|
+
console.error(`ā Directory not found: ${dir}`);
|
|
166
|
+
process.exit(2);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
this.loadIgnoreFile(dir);
|
|
170
|
+
|
|
171
|
+
const skills = fs.readdirSync(dir).filter(f => {
|
|
172
|
+
const p = path.join(dir, f);
|
|
173
|
+
return fs.statSync(p).isDirectory();
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
if (!this.quiet) {
|
|
177
|
+
console.log(`\nš”ļø guard-scanner v${VERSION}`);
|
|
178
|
+
console.log(`${'ā'.repeat(54)}`);
|
|
179
|
+
console.log(`š Scanning: ${dir}`);
|
|
180
|
+
console.log(`š¦ Skills found: ${skills.length}`);
|
|
181
|
+
if (this.strict) console.log(`ā” Strict mode enabled`);
|
|
182
|
+
console.log();
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
for (const skill of skills) {
|
|
186
|
+
const skillPath = path.join(dir, skill);
|
|
187
|
+
|
|
188
|
+
// Self-exclusion
|
|
189
|
+
if (this.selfExclude && path.resolve(skillPath) === this.scannerDir) {
|
|
190
|
+
if (!this.summaryOnly && !this.quiet) console.log(`āļø ${skill} ā SELF (excluded)`);
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// Ignore list
|
|
195
|
+
if (this.ignoredSkills.has(skill)) {
|
|
196
|
+
if (!this.summaryOnly && !this.quiet) console.log(`āļø ${skill} ā IGNORED`);
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
this.scanSkill(skillPath, skill);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
if (!this.quiet) this.printSummary();
|
|
204
|
+
return this.findings;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
scanSkill(skillPath, skillName) {
|
|
208
|
+
this.stats.scanned++;
|
|
209
|
+
const skillFindings = [];
|
|
210
|
+
|
|
211
|
+
// Check 1: Known malicious skill name
|
|
212
|
+
if (KNOWN_MALICIOUS.typosquats.includes(skillName.toLowerCase())) {
|
|
213
|
+
skillFindings.push({
|
|
214
|
+
severity: 'CRITICAL', id: 'KNOWN_TYPOSQUAT', cat: 'malicious-code',
|
|
215
|
+
desc: `Known malicious/typosquat skill name`,
|
|
216
|
+
file: 'SKILL NAME', line: 0
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// Check 2: Scan all files
|
|
221
|
+
const files = this.getFiles(skillPath);
|
|
222
|
+
for (const file of files) {
|
|
223
|
+
const ext = path.extname(file).toLowerCase();
|
|
224
|
+
const relFile = path.relative(skillPath, file);
|
|
225
|
+
|
|
226
|
+
if (relFile.includes('node_modules/') || relFile.includes('node_modules\\')) continue;
|
|
227
|
+
if (relFile.startsWith('.git/') || relFile.startsWith('.git\\')) continue;
|
|
228
|
+
if (BINARY_EXTENSIONS.has(ext)) continue;
|
|
229
|
+
if (this.isSelfNoisePath(skillName, relFile)) continue;
|
|
230
|
+
|
|
231
|
+
let content;
|
|
232
|
+
try { content = fs.readFileSync(file, 'utf-8'); } catch { continue; }
|
|
233
|
+
if (content.length > 500000) continue;
|
|
234
|
+
|
|
235
|
+
const fileType = this.classifyFile(ext, relFile);
|
|
236
|
+
|
|
237
|
+
// IoC checks
|
|
238
|
+
if (!this.isSelfThreatCorpus(skillName, relFile)) {
|
|
239
|
+
this.checkIoCs(content, relFile, skillFindings);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// Pattern checks (context-aware)
|
|
243
|
+
this.checkPatterns(content, relFile, fileType, skillFindings);
|
|
244
|
+
|
|
245
|
+
// Custom rules / plugins
|
|
246
|
+
if (this.customRules.length > 0) {
|
|
247
|
+
this.checkPatterns(content, relFile, fileType, skillFindings, this.customRules);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// Hardcoded secret detection
|
|
251
|
+
const baseName = path.basename(relFile).toLowerCase();
|
|
252
|
+
const skipSecretCheck = baseName.endsWith('-lock.json') || baseName === 'package-lock.json' ||
|
|
253
|
+
baseName === 'yarn.lock' || baseName === 'pnpm-lock.yaml' ||
|
|
254
|
+
baseName === '_meta.json' || baseName === '.package-lock.json';
|
|
255
|
+
if (fileType === 'code' && !skipSecretCheck) {
|
|
256
|
+
this.checkHardcodedSecrets(content, relFile, skillFindings);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// Lightweight JS data flow analysis
|
|
260
|
+
if ((ext === '.js' || ext === '.mjs' || ext === '.cjs' || ext === '.ts') && content.length < 200000) {
|
|
261
|
+
this.checkJSDataFlow(content, relFile, skillFindings);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// Check 3: Structural checks
|
|
266
|
+
this.checkStructure(skillPath, skillName, skillFindings);
|
|
267
|
+
|
|
268
|
+
// Check 4: Dependency chain scanning
|
|
269
|
+
if (this.checkDeps) {
|
|
270
|
+
this.checkDependencies(skillPath, skillName, skillFindings);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// Check 5: Hidden files detection
|
|
274
|
+
this.checkHiddenFiles(skillPath, skillName, skillFindings);
|
|
275
|
+
|
|
276
|
+
// Check 6: Cross-file analysis
|
|
277
|
+
this.checkCrossFile(skillPath, skillName, skillFindings);
|
|
278
|
+
|
|
279
|
+
// Check 7: Skill manifest validation (v1.1)
|
|
280
|
+
this.checkSkillManifest(skillPath, skillName, skillFindings);
|
|
281
|
+
|
|
282
|
+
// Check 8: Code complexity metrics (v1.1)
|
|
283
|
+
this.checkComplexity(skillPath, skillName, skillFindings);
|
|
284
|
+
|
|
285
|
+
// Check 9: Config impact analysis (v1.1)
|
|
286
|
+
this.checkConfigImpact(skillPath, skillName, skillFindings);
|
|
287
|
+
|
|
288
|
+
// Filter ignored patterns
|
|
289
|
+
const filteredFindings = skillFindings.filter(f => !this.ignoredPatterns.has(f.id));
|
|
290
|
+
|
|
291
|
+
// Calculate risk
|
|
292
|
+
const risk = this.calculateRisk(filteredFindings);
|
|
293
|
+
const verdict = this.getVerdict(risk);
|
|
294
|
+
|
|
295
|
+
this.stats[verdict.stat]++;
|
|
296
|
+
|
|
297
|
+
if (!this.summaryOnly && !this.quiet) {
|
|
298
|
+
console.log(`${verdict.icon} ${skillName} ā ${verdict.label} (risk: ${risk})`);
|
|
299
|
+
|
|
300
|
+
if (this.verbose && filteredFindings.length > 0) {
|
|
301
|
+
const byCat = {};
|
|
302
|
+
for (const f of filteredFindings) {
|
|
303
|
+
(byCat[f.cat] = byCat[f.cat] || []).push(f);
|
|
304
|
+
}
|
|
305
|
+
for (const [cat, findings] of Object.entries(byCat)) {
|
|
306
|
+
console.log(` š ${cat}`);
|
|
307
|
+
for (const f of findings) {
|
|
308
|
+
const icon = f.severity === 'CRITICAL' ? 'š' : f.severity === 'HIGH' ? 'š“' : f.severity === 'MEDIUM' ? 'š”' : 'āŖ';
|
|
309
|
+
const loc = f.line ? `${f.file}:${f.line}` : f.file;
|
|
310
|
+
console.log(` ${icon} [${f.severity}] ${f.desc} ā ${loc}`);
|
|
311
|
+
if (f.sample) console.log(` āā "${f.sample}"`);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
if (filteredFindings.length > 0) {
|
|
318
|
+
this.findings.push({ skill: skillName, risk, verdict: verdict.label, findings: filteredFindings });
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
classifyFile(ext, relFile) {
|
|
323
|
+
if (CODE_EXTENSIONS.has(ext)) return 'code';
|
|
324
|
+
if (DOC_EXTENSIONS.has(ext)) return 'doc';
|
|
325
|
+
if (DATA_EXTENSIONS.has(ext)) return 'data';
|
|
326
|
+
const base = path.basename(relFile).toLowerCase();
|
|
327
|
+
if (base === 'skill.md' || base === 'readme.md') return 'skill-doc';
|
|
328
|
+
return 'other';
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
isSelfNoisePath(skillName, relFile) {
|
|
332
|
+
if (skillName !== 'guard-scanner') return false;
|
|
333
|
+
return /^test\//.test(relFile)
|
|
334
|
+
|| /^dist\/__tests__\//.test(relFile)
|
|
335
|
+
|| /^ts-src\/__tests__\//.test(relFile)
|
|
336
|
+
|| /^docs\//.test(relFile)
|
|
337
|
+
|| relFile === 'ROADMAP-RESEARCH.md'
|
|
338
|
+
|| relFile === 'CHANGELOG.md';
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
isSelfThreatCorpus(skillName, relFile) {
|
|
342
|
+
if (skillName !== 'guard-scanner') return false;
|
|
343
|
+
return /(^|\/)(ioc-db|patterns)\.(js|ts)$/.test(relFile);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
checkIoCs(content, relFile, findings) {
|
|
347
|
+
const contentLower = content.toLowerCase();
|
|
348
|
+
|
|
349
|
+
for (const ip of KNOWN_MALICIOUS.ips) {
|
|
350
|
+
if (content.includes(ip)) {
|
|
351
|
+
findings.push({ severity: 'CRITICAL', id: 'IOC_IP', cat: 'malicious-code', desc: `Known malicious IP: ${ip}`, file: relFile });
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
for (const url of KNOWN_MALICIOUS.urls) {
|
|
356
|
+
if (contentLower.includes(url.toLowerCase())) {
|
|
357
|
+
findings.push({ severity: 'CRITICAL', id: 'IOC_URL', cat: 'malicious-code', desc: `Known malicious URL: ${url}`, file: relFile });
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
for (const domain of KNOWN_MALICIOUS.domains) {
|
|
362
|
+
const domainRegex = new RegExp(`(?:https?://|[\\s'"\`(]|^)${domain.replace(/\./g, '\\.')}`, 'gi');
|
|
363
|
+
if (domainRegex.test(content)) {
|
|
364
|
+
findings.push({ severity: 'HIGH', id: 'IOC_DOMAIN', cat: 'exfiltration', desc: `Suspicious domain: ${domain}`, file: relFile });
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
for (const fname of KNOWN_MALICIOUS.filenames) {
|
|
369
|
+
if (contentLower.includes(fname.toLowerCase())) {
|
|
370
|
+
findings.push({ severity: 'CRITICAL', id: 'IOC_FILE', cat: 'suspicious-download', desc: `Known malicious filename: ${fname}`, file: relFile });
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
for (const user of KNOWN_MALICIOUS.usernames) {
|
|
375
|
+
if (contentLower.includes(user.toLowerCase())) {
|
|
376
|
+
findings.push({ severity: 'HIGH', id: 'IOC_USER', cat: 'malicious-code', desc: `Known malicious username: ${user}`, file: relFile });
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
checkPatterns(content, relFile, fileType, findings, patterns = PATTERNS) {
|
|
382
|
+
for (const pattern of patterns) {
|
|
383
|
+
// Soul Lock: skip identity-hijack/memory-poisoning patterns unless --soul-lock is enabled
|
|
384
|
+
if (pattern.soulLock && !this.soulLock) continue;
|
|
385
|
+
if (pattern.codeOnly && fileType !== 'code') continue;
|
|
386
|
+
if (pattern.docOnly && fileType !== 'doc' && fileType !== 'skill-doc') continue;
|
|
387
|
+
if (!pattern.all && !pattern.codeOnly && !pattern.docOnly) continue;
|
|
388
|
+
|
|
389
|
+
pattern.regex.lastIndex = 0;
|
|
390
|
+
const matches = content.match(pattern.regex);
|
|
391
|
+
if (!matches) continue;
|
|
392
|
+
|
|
393
|
+
pattern.regex.lastIndex = 0;
|
|
394
|
+
const idx = content.search(pattern.regex);
|
|
395
|
+
const lineNum = idx >= 0 ? content.substring(0, idx).split('\n').length : null;
|
|
396
|
+
|
|
397
|
+
let adjustedSeverity = pattern.severity;
|
|
398
|
+
if ((fileType === 'doc' || fileType === 'skill-doc') && pattern.all && !pattern.docOnly) {
|
|
399
|
+
if (adjustedSeverity === 'HIGH') adjustedSeverity = 'MEDIUM';
|
|
400
|
+
else if (adjustedSeverity === 'MEDIUM') adjustedSeverity = 'LOW';
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
findings.push({
|
|
404
|
+
severity: adjustedSeverity,
|
|
405
|
+
id: pattern.id,
|
|
406
|
+
cat: pattern.cat,
|
|
407
|
+
desc: pattern.desc,
|
|
408
|
+
file: relFile,
|
|
409
|
+
line: lineNum,
|
|
410
|
+
matchCount: matches.length,
|
|
411
|
+
sample: matches[0].substring(0, 80)
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
// Entropy-based secret detection
|
|
417
|
+
checkHardcodedSecrets(content, relFile, findings) {
|
|
418
|
+
const assignmentRegex = /(?:api[_-]?key|secret|token|password|credential|auth)\s*[:=]\s*['"]([a-zA-Z0-9_\-+/=]{16,})['"]|['"]([a-zA-Z0-9_\-+/=]{32,})['"]/gi;
|
|
419
|
+
let match;
|
|
420
|
+
while ((match = assignmentRegex.exec(content)) !== null) {
|
|
421
|
+
const value = match[1] || match[2];
|
|
422
|
+
if (!value) continue;
|
|
423
|
+
|
|
424
|
+
if (/^[A-Z_]+$/.test(value)) continue;
|
|
425
|
+
if (/^(true|false|null|undefined|none|default|example|test|placeholder|your[_-])/i.test(value)) continue;
|
|
426
|
+
if (/^x{4,}|\.{4,}|_{4,}|0{8,}$/i.test(value)) continue;
|
|
427
|
+
if (/^projects\/|^gs:\/\/|^https?:\/\//i.test(value)) continue;
|
|
428
|
+
if (/^[a-z]+-[a-z]+-[a-z0-9]+$/i.test(value)) continue;
|
|
429
|
+
|
|
430
|
+
const entropy = this.shannonEntropy(value);
|
|
431
|
+
if (entropy > 3.5 && value.length >= 20) {
|
|
432
|
+
const lineNum = content.substring(0, match.index).split('\n').length;
|
|
433
|
+
findings.push({
|
|
434
|
+
severity: 'HIGH', id: 'SECRET_ENTROPY', cat: 'secret-detection',
|
|
435
|
+
desc: `High-entropy string (possible leaked secret, entropy=${entropy.toFixed(1)})`,
|
|
436
|
+
file: relFile, line: lineNum,
|
|
437
|
+
sample: value.substring(0, 8) + '...' + value.substring(value.length - 4)
|
|
438
|
+
});
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
shannonEntropy(str) {
|
|
444
|
+
const freq = {};
|
|
445
|
+
for (const c of str) freq[c] = (freq[c] || 0) + 1;
|
|
446
|
+
const len = str.length;
|
|
447
|
+
let entropy = 0;
|
|
448
|
+
for (const count of Object.values(freq)) {
|
|
449
|
+
const p = count / len;
|
|
450
|
+
if (p > 0) entropy -= p * Math.log2(p);
|
|
451
|
+
}
|
|
452
|
+
return entropy;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
checkStructure(skillPath, skillName, findings) {
|
|
456
|
+
const skillMd = path.join(skillPath, 'SKILL.md');
|
|
457
|
+
if (!fs.existsSync(skillMd)) {
|
|
458
|
+
findings.push({ severity: 'LOW', id: 'STRUCT_NO_SKILLMD', cat: 'structural', desc: 'No SKILL.md found', file: skillName });
|
|
459
|
+
return;
|
|
460
|
+
}
|
|
461
|
+
const content = fs.readFileSync(skillMd, 'utf-8');
|
|
462
|
+
if (content.length < 50) {
|
|
463
|
+
findings.push({ severity: 'MEDIUM', id: 'STRUCT_TINY_SKILLMD', cat: 'structural', desc: 'Suspiciously short SKILL.md (< 50 chars)', file: 'SKILL.md' });
|
|
464
|
+
}
|
|
465
|
+
const scriptsDir = path.join(skillPath, 'scripts');
|
|
466
|
+
if (fs.existsSync(scriptsDir)) {
|
|
467
|
+
const scripts = fs.readdirSync(scriptsDir).filter(f => CODE_EXTENSIONS.has(path.extname(f).toLowerCase()));
|
|
468
|
+
if (scripts.length > 0 && !content.includes('scripts/')) {
|
|
469
|
+
findings.push({ severity: 'MEDIUM', id: 'STRUCT_UNDOCUMENTED_SCRIPTS', cat: 'structural', desc: `${scripts.length} script(s) in scripts/ not referenced in SKILL.md`, file: 'scripts/' });
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
checkDependencies(skillPath, skillName, findings) {
|
|
475
|
+
const pkgPath = path.join(skillPath, 'package.json');
|
|
476
|
+
if (!fs.existsSync(pkgPath)) return;
|
|
477
|
+
|
|
478
|
+
let pkg;
|
|
479
|
+
try { pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')); } catch { return; }
|
|
480
|
+
|
|
481
|
+
const allDeps = { ...pkg.dependencies, ...pkg.devDependencies, ...pkg.optionalDependencies };
|
|
482
|
+
|
|
483
|
+
const RISKY_PACKAGES = new Set([
|
|
484
|
+
'node-ipc', 'colors', 'faker', 'event-stream', 'ua-parser-js', 'coa', 'rc',
|
|
485
|
+
]);
|
|
486
|
+
|
|
487
|
+
for (const [dep, version] of Object.entries(allDeps)) {
|
|
488
|
+
if (RISKY_PACKAGES.has(dep)) {
|
|
489
|
+
findings.push({ severity: 'HIGH', id: 'DEP_RISKY', cat: 'dependency-chain', desc: `Known risky dependency: ${dep}@${version}`, file: 'package.json' });
|
|
490
|
+
}
|
|
491
|
+
if (typeof version === 'string' && (version.startsWith('git+') || version.startsWith('http') || version.startsWith('github:') || version.includes('.tar.gz'))) {
|
|
492
|
+
findings.push({ severity: 'HIGH', id: 'DEP_REMOTE', cat: 'dependency-chain', desc: `Remote/git dependency: ${dep}@${version}`, file: 'package.json' });
|
|
493
|
+
}
|
|
494
|
+
if (version === '*' || version === 'latest') {
|
|
495
|
+
findings.push({ severity: 'MEDIUM', id: 'DEP_WILDCARD', cat: 'dependency-chain', desc: `Wildcard version: ${dep}@${version}`, file: 'package.json' });
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
const RISKY_SCRIPTS = ['preinstall', 'postinstall', 'preuninstall', 'postuninstall', 'prepare'];
|
|
500
|
+
if (pkg.scripts) {
|
|
501
|
+
for (const scriptName of RISKY_SCRIPTS) {
|
|
502
|
+
if (pkg.scripts[scriptName]) {
|
|
503
|
+
const cmd = pkg.scripts[scriptName];
|
|
504
|
+
findings.push({ severity: 'HIGH', id: 'DEP_LIFECYCLE', cat: 'dependency-chain', desc: `Lifecycle script "${scriptName}": ${cmd.substring(0, 80)}`, file: 'package.json' });
|
|
505
|
+
if (/curl|wget|node\s+-e|eval|exec|bash\s+-c/i.test(cmd)) {
|
|
506
|
+
findings.push({ severity: 'CRITICAL', id: 'DEP_LIFECYCLE_EXEC', cat: 'dependency-chain', desc: `Lifecycle script "${scriptName}" downloads/executes code`, file: 'package.json', sample: cmd.substring(0, 80) });
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
// āā v1.1: Skill Manifest Validation āā
|
|
514
|
+
// Checks SKILL.md frontmatter for dangerous tool declarations,
|
|
515
|
+
// overly broad file scope, and sensitive env requirements
|
|
516
|
+
checkSkillManifest(skillPath, skillName, findings) {
|
|
517
|
+
const skillMd = path.join(skillPath, 'SKILL.md');
|
|
518
|
+
if (!fs.existsSync(skillMd)) return;
|
|
519
|
+
|
|
520
|
+
let content;
|
|
521
|
+
try { content = fs.readFileSync(skillMd, 'utf-8'); } catch { return; }
|
|
522
|
+
|
|
523
|
+
// Parse YAML frontmatter (lightweight, no dependency)
|
|
524
|
+
const fmMatch = content.match(/^---\n([\s\S]*?)\n---/);
|
|
525
|
+
if (!fmMatch) return;
|
|
526
|
+
const fm = fmMatch[1];
|
|
527
|
+
|
|
528
|
+
// Check 1: Dangerous binary requirements
|
|
529
|
+
const DANGEROUS_BINS = new Set([
|
|
530
|
+
'sudo', 'rm', 'rmdir', 'chmod', 'chown', 'kill', 'pkill',
|
|
531
|
+
'curl', 'wget', 'nc', 'ncat', 'socat', 'ssh', 'scp',
|
|
532
|
+
'dd', 'mkfs', 'fdisk', 'mount', 'umount',
|
|
533
|
+
'iptables', 'ufw', 'firewall-cmd',
|
|
534
|
+
'docker', 'kubectl', 'systemctl',
|
|
535
|
+
]);
|
|
536
|
+
const binsMatch = fm.match(/bins:\s*\n((?:\s+-\s+[^\n]+\n?)*)/i);
|
|
537
|
+
if (binsMatch) {
|
|
538
|
+
const bins = binsMatch[1].match(/- ([^\n]+)/g) || [];
|
|
539
|
+
for (const binLine of bins) {
|
|
540
|
+
const bin = binLine.replace(/^-\s*/, '').trim().toLowerCase();
|
|
541
|
+
if (DANGEROUS_BINS.has(bin)) {
|
|
542
|
+
findings.push({
|
|
543
|
+
severity: 'HIGH', id: 'MANIFEST_DANGEROUS_BIN',
|
|
544
|
+
cat: 'sandbox-validation',
|
|
545
|
+
desc: `SKILL.md requires dangerous binary: ${bin}`,
|
|
546
|
+
file: 'SKILL.md'
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
// Check 2: Overly broad file scope
|
|
553
|
+
const filesMatch = fm.match(/files:\s*\[([^\]]+)\]/i) || fm.match(/files:\s*\n((?:\s+-\s+[^\n]+\n?)*)/i);
|
|
554
|
+
if (filesMatch) {
|
|
555
|
+
const filesStr = filesMatch[1];
|
|
556
|
+
if (/\*\*\/\*|\*\.\*|\"\*\"/i.test(filesStr)) {
|
|
557
|
+
findings.push({
|
|
558
|
+
severity: 'HIGH', id: 'MANIFEST_BROAD_FILES',
|
|
559
|
+
cat: 'sandbox-validation',
|
|
560
|
+
desc: 'SKILL.md declares overly broad file scope (e.g. **/*)',
|
|
561
|
+
file: 'SKILL.md'
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
// Check 3: Sensitive env requirements
|
|
567
|
+
const SENSITIVE_ENV_PATTERNS = /(?:SECRET|PASSWORD|CREDENTIAL|PRIVATE_KEY|AWS_SECRET|GITHUB_TOKEN)/i;
|
|
568
|
+
const envMatch = fm.match(/env:\s*\n((?:\s+-\s+[^\n]+\n?)*)/i);
|
|
569
|
+
if (envMatch) {
|
|
570
|
+
const envVars = envMatch[1].match(/- ([^\n]+)/g) || [];
|
|
571
|
+
for (const envLine of envVars) {
|
|
572
|
+
const envVar = envLine.replace(/^-\s*/, '').trim();
|
|
573
|
+
if (SENSITIVE_ENV_PATTERNS.test(envVar)) {
|
|
574
|
+
findings.push({
|
|
575
|
+
severity: 'HIGH', id: 'MANIFEST_SENSITIVE_ENV',
|
|
576
|
+
cat: 'sandbox-validation',
|
|
577
|
+
desc: `SKILL.md requires sensitive env var: ${envVar}`,
|
|
578
|
+
file: 'SKILL.md'
|
|
579
|
+
});
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
// Check 4: exec or network declared without justification
|
|
585
|
+
if (/exec:\s*(?:true|yes|enabled|'\*'|"\*")/i.test(fm)) {
|
|
586
|
+
findings.push({
|
|
587
|
+
severity: 'MEDIUM', id: 'MANIFEST_EXEC_DECLARED',
|
|
588
|
+
cat: 'sandbox-validation',
|
|
589
|
+
desc: 'SKILL.md declares exec capability',
|
|
590
|
+
file: 'SKILL.md'
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
if (/network:\s*(?:true|yes|enabled|'\*'|"\*"|all|any)/i.test(fm)) {
|
|
594
|
+
findings.push({
|
|
595
|
+
severity: 'MEDIUM', id: 'MANIFEST_NETWORK_DECLARED',
|
|
596
|
+
cat: 'sandbox-validation',
|
|
597
|
+
desc: 'SKILL.md declares unrestricted network access',
|
|
598
|
+
file: 'SKILL.md'
|
|
599
|
+
});
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
// āā v1.1: Code Complexity Metrics āā
|
|
604
|
+
// Detects excessive file length, deep nesting, and eval/exec density
|
|
605
|
+
checkComplexity(skillPath, skillName, findings) {
|
|
606
|
+
const files = this.getFiles(skillPath);
|
|
607
|
+
const MAX_LINES = 1000;
|
|
608
|
+
const MAX_NESTING = 5;
|
|
609
|
+
const MAX_EVAL_DENSITY = 0.02; // 2% of lines
|
|
610
|
+
|
|
611
|
+
for (const file of files) {
|
|
612
|
+
const ext = path.extname(file).toLowerCase();
|
|
613
|
+
if (!CODE_EXTENSIONS.has(ext)) continue;
|
|
614
|
+
|
|
615
|
+
const relFile = path.relative(skillPath, file);
|
|
616
|
+
if (relFile.includes('node_modules') || relFile.startsWith('.git')) continue;
|
|
617
|
+
|
|
618
|
+
let content;
|
|
619
|
+
try { content = fs.readFileSync(file, 'utf-8'); } catch { continue; }
|
|
620
|
+
|
|
621
|
+
const lines = content.split('\n');
|
|
622
|
+
|
|
623
|
+
// Check 1: Excessive file length
|
|
624
|
+
if (lines.length > MAX_LINES) {
|
|
625
|
+
findings.push({
|
|
626
|
+
severity: 'MEDIUM', id: 'COMPLEXITY_LONG_FILE',
|
|
627
|
+
cat: 'complexity',
|
|
628
|
+
desc: `File exceeds ${MAX_LINES} lines (${lines.length} lines)`,
|
|
629
|
+
file: relFile
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
// Check 2: Deep nesting (brace tracking)
|
|
634
|
+
let maxDepth = 0;
|
|
635
|
+
let currentDepth = 0;
|
|
636
|
+
let deepestLine = 0;
|
|
637
|
+
for (let i = 0; i < lines.length; i++) {
|
|
638
|
+
const line = lines[i];
|
|
639
|
+
// Count opening/closing braces outside strings (simplified)
|
|
640
|
+
for (const ch of line) {
|
|
641
|
+
if (ch === '{') currentDepth++;
|
|
642
|
+
if (ch === '}') currentDepth = Math.max(0, currentDepth - 1);
|
|
643
|
+
}
|
|
644
|
+
if (currentDepth > maxDepth) {
|
|
645
|
+
maxDepth = currentDepth;
|
|
646
|
+
deepestLine = i + 1;
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
if (maxDepth > MAX_NESTING) {
|
|
650
|
+
findings.push({
|
|
651
|
+
severity: 'MEDIUM', id: 'COMPLEXITY_DEEP_NESTING',
|
|
652
|
+
cat: 'complexity',
|
|
653
|
+
desc: `Deep nesting detected: ${maxDepth} levels (max recommended: ${MAX_NESTING})`,
|
|
654
|
+
file: relFile, line: deepestLine
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
// Check 3: eval/exec density
|
|
659
|
+
const evalPattern = /\b(?:eval|exec|execSync|spawn|Function)\s*\(/g;
|
|
660
|
+
const evalMatches = content.match(evalPattern) || [];
|
|
661
|
+
const density = lines.length > 0 ? evalMatches.length / lines.length : 0;
|
|
662
|
+
if (density > MAX_EVAL_DENSITY && evalMatches.length >= 3) {
|
|
663
|
+
findings.push({
|
|
664
|
+
severity: 'HIGH', id: 'COMPLEXITY_EVAL_DENSITY',
|
|
665
|
+
cat: 'complexity',
|
|
666
|
+
desc: `High eval/exec density: ${evalMatches.length} calls in ${lines.length} lines (${(density * 100).toFixed(1)}%)`,
|
|
667
|
+
file: relFile
|
|
668
|
+
});
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
// āā v1.1: Config Impact Analysis āā
|
|
674
|
+
// Detects modifications to openclaw.json and dangerous configuration changes
|
|
675
|
+
checkConfigImpact(skillPath, skillName, findings) {
|
|
676
|
+
const files = this.getFiles(skillPath);
|
|
677
|
+
|
|
678
|
+
for (const file of files) {
|
|
679
|
+
const ext = path.extname(file).toLowerCase();
|
|
680
|
+
if (!CODE_EXTENSIONS.has(ext) && ext !== '.json') continue;
|
|
681
|
+
|
|
682
|
+
const relFile = path.relative(skillPath, file);
|
|
683
|
+
if (relFile.includes('node_modules') || relFile.startsWith('.git')) continue;
|
|
684
|
+
|
|
685
|
+
let content;
|
|
686
|
+
try { content = fs.readFileSync(file, 'utf-8'); } catch { continue; }
|
|
687
|
+
|
|
688
|
+
// Check 1: openclaw.json reference + write operation in same file
|
|
689
|
+
// Handles both direct and variable-based patterns (e.g. writeFileSync(configPath))
|
|
690
|
+
const hasConfigRef = /openclaw\.json/i.test(content);
|
|
691
|
+
const hasWriteOp = /(?:writeFileSync|writeFile|fs\.write)\s*\(/i.test(content);
|
|
692
|
+
if (hasConfigRef && hasWriteOp) {
|
|
693
|
+
// Find the write line for location info
|
|
694
|
+
const clines = content.split('\n');
|
|
695
|
+
let writeLine = 0;
|
|
696
|
+
for (let i = 0; i < clines.length; i++) {
|
|
697
|
+
if (/(?:writeFileSync|writeFile|fs\.write)\s*\(/i.test(clines[i])) {
|
|
698
|
+
writeLine = i + 1;
|
|
699
|
+
break;
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
findings.push({
|
|
703
|
+
severity: 'CRITICAL', id: 'CFG_WRITE_DETECTED',
|
|
704
|
+
cat: 'config-impact',
|
|
705
|
+
desc: 'Code writes to openclaw.json',
|
|
706
|
+
file: relFile, line: writeLine,
|
|
707
|
+
sample: writeLine > 0 ? clines[writeLine - 1].trim().substring(0, 80) : ''
|
|
708
|
+
});
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
// Check 2: Dangerous config key modifications
|
|
712
|
+
const DANGEROUS_CONFIG_KEYS = [
|
|
713
|
+
{ regex: /exec\.approvals?\s*[:=]\s*['"]?(off|false|disabled|none)/gi, id: 'CFG_EXEC_APPROVAL_OFF', desc: 'Disables exec approval requirement', severity: 'CRITICAL' },
|
|
714
|
+
{ regex: /tools\.exec\.host\s*[:=]\s*['"]gateway['"]/gi, id: 'CFG_EXEC_HOST_GATEWAY', desc: 'Sets exec host to gateway (bypasses sandbox)', severity: 'CRITICAL' },
|
|
715
|
+
{ regex: /hooks\s*\.\s*internal\s*\.\s*entries\s*[:=]/gi, id: 'CFG_HOOKS_INTERNAL', desc: 'Modifies internal hook entries', severity: 'HIGH' },
|
|
716
|
+
{ regex: /network\.allowedDomains\s*[:=]\s*\[?\s*['"]\*['"]/gi, id: 'CFG_NET_WILDCARD', desc: 'Sets network allowedDomains to wildcard', severity: 'HIGH' },
|
|
717
|
+
];
|
|
718
|
+
|
|
719
|
+
for (const check of DANGEROUS_CONFIG_KEYS) {
|
|
720
|
+
check.regex.lastIndex = 0;
|
|
721
|
+
if (check.regex.test(content)) {
|
|
722
|
+
findings.push({
|
|
723
|
+
severity: check.severity, id: check.id,
|
|
724
|
+
cat: 'config-impact',
|
|
725
|
+
desc: check.desc,
|
|
726
|
+
file: relFile
|
|
727
|
+
});
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
checkHiddenFiles(skillPath, skillName, findings) {
|
|
734
|
+
try {
|
|
735
|
+
const entries = fs.readdirSync(skillPath);
|
|
736
|
+
for (const entry of entries) {
|
|
737
|
+
if (entry.startsWith('.') && entry !== '.guard-scanner-ignore' && entry !== '.guava-guard-ignore' && entry !== '.gitignore' && entry !== '.git') {
|
|
738
|
+
const fullPath = path.join(skillPath, entry);
|
|
739
|
+
const stat = fs.statSync(fullPath);
|
|
740
|
+
if (stat.isFile()) {
|
|
741
|
+
const ext = path.extname(entry).toLowerCase();
|
|
742
|
+
if (CODE_EXTENSIONS.has(ext) || ext === '' || ext === '.sh') {
|
|
743
|
+
findings.push({ severity: 'MEDIUM', id: 'STRUCT_HIDDEN_EXEC', cat: 'structural', desc: `Hidden executable file: ${entry}`, file: entry });
|
|
744
|
+
}
|
|
745
|
+
} else if (stat.isDirectory() && entry !== '.git') {
|
|
746
|
+
findings.push({ severity: 'LOW', id: 'STRUCT_HIDDEN_DIR', cat: 'structural', desc: `Hidden directory: ${entry}/`, file: entry });
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
} catch { }
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
checkJSDataFlow(content, relFile, findings) {
|
|
754
|
+
const lines = content.split('\n');
|
|
755
|
+
const imports = new Map();
|
|
756
|
+
const sensitiveReads = [];
|
|
757
|
+
const networkCalls = [];
|
|
758
|
+
const execCalls = [];
|
|
759
|
+
|
|
760
|
+
for (let i = 0; i < lines.length; i++) {
|
|
761
|
+
const line = lines[i];
|
|
762
|
+
const lineNum = i + 1;
|
|
763
|
+
|
|
764
|
+
const reqMatch = line.match(/(?:const|let|var)\s+(?:{[^}]+}|\w+)\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/);
|
|
765
|
+
if (reqMatch) {
|
|
766
|
+
const varMatch = line.match(/(?:const|let|var)\s+({[^}]+}|\w+)/);
|
|
767
|
+
if (varMatch) imports.set(varMatch[1].trim(), reqMatch[1]);
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
if (/(?:readFileSync|readFile)\s*\([^)]*(?:\.env|\.ssh|id_rsa|\.clawdbot|\.openclaw(?!\/workspace))/i.test(line)) {
|
|
771
|
+
sensitiveReads.push({ line: lineNum, text: line.trim() });
|
|
772
|
+
}
|
|
773
|
+
if (/process\.env\.[A-Z_]*(?:KEY|SECRET|TOKEN|PASSWORD|CREDENTIAL)/i.test(line)) {
|
|
774
|
+
sensitiveReads.push({ line: lineNum, text: line.trim() });
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
if (/(?:fetch|axios|request|http\.request|https\.request|got)\s*\(/i.test(line) ||
|
|
778
|
+
/\.post\s*\(|\.put\s*\(|\.patch\s*\(/i.test(line)) {
|
|
779
|
+
networkCalls.push({ line: lineNum, text: line.trim() });
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
if (/(?:exec|execSync|spawn|spawnSync|execFile)\s*\(/i.test(line)) {
|
|
783
|
+
execCalls.push({ line: lineNum, text: line.trim() });
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
if (sensitiveReads.length > 0 && networkCalls.length > 0) {
|
|
788
|
+
findings.push({
|
|
789
|
+
severity: 'CRITICAL', id: 'AST_CRED_TO_NET', cat: 'data-flow',
|
|
790
|
+
desc: `Data flow: secret read (L${sensitiveReads[0].line}) ā network call (L${networkCalls[0].line})`,
|
|
791
|
+
file: relFile, line: sensitiveReads[0].line,
|
|
792
|
+
sample: sensitiveReads[0].text.substring(0, 60)
|
|
793
|
+
});
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
if (sensitiveReads.length > 0 && execCalls.length > 0) {
|
|
797
|
+
findings.push({
|
|
798
|
+
severity: 'HIGH', id: 'AST_CRED_TO_EXEC', cat: 'data-flow',
|
|
799
|
+
desc: `Data flow: secret read (L${sensitiveReads[0].line}) ā command exec (L${execCalls[0].line})`,
|
|
800
|
+
file: relFile, line: sensitiveReads[0].line,
|
|
801
|
+
sample: sensitiveReads[0].text.substring(0, 60)
|
|
802
|
+
});
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
const importedModules = new Set([...imports.values()]);
|
|
806
|
+
if (importedModules.has('child_process') && (importedModules.has('https') || importedModules.has('http') || importedModules.has('node-fetch'))) {
|
|
807
|
+
findings.push({ severity: 'HIGH', id: 'AST_SUSPICIOUS_IMPORTS', cat: 'data-flow', desc: 'Suspicious import combination: child_process + network module', file: relFile });
|
|
808
|
+
}
|
|
809
|
+
if (importedModules.has('fs') && importedModules.has('child_process') && (importedModules.has('https') || importedModules.has('http'))) {
|
|
810
|
+
findings.push({ severity: 'CRITICAL', id: 'AST_EXFIL_TRIFECTA', cat: 'data-flow', desc: 'Exfiltration trifecta: fs + child_process + network', file: relFile });
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
for (let i = 0; i < lines.length; i++) {
|
|
814
|
+
const line = lines[i];
|
|
815
|
+
if (/`[^`]*\$\{.*(?:env|key|token|secret|password).*\}[^`]*`\s*(?:\)|,)/i.test(line) &&
|
|
816
|
+
/(?:fetch|request|axios|http|url)/i.test(line)) {
|
|
817
|
+
findings.push({ severity: 'CRITICAL', id: 'AST_SECRET_IN_URL', cat: 'data-flow', desc: 'Secret interpolated into URL/request', file: relFile, line: i + 1, sample: line.trim().substring(0, 80) });
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
checkCrossFile(skillPath, skillName, findings) {
|
|
823
|
+
const files = this.getFiles(skillPath);
|
|
824
|
+
const allContent = {};
|
|
825
|
+
|
|
826
|
+
for (const file of files) {
|
|
827
|
+
const ext = path.extname(file).toLowerCase();
|
|
828
|
+
if (BINARY_EXTENSIONS.has(ext)) continue;
|
|
829
|
+
const relFile = path.relative(skillPath, file);
|
|
830
|
+
if (relFile.includes('node_modules') || relFile.startsWith('.git')) continue;
|
|
831
|
+
try {
|
|
832
|
+
const content = fs.readFileSync(file, 'utf-8');
|
|
833
|
+
if (content.length < 500000) allContent[relFile] = content;
|
|
834
|
+
} catch { }
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
const skillMd = allContent['SKILL.md'] || '';
|
|
838
|
+
const codeFileRefs = skillMd.match(/(?:scripts?\/|\.\/)[a-zA-Z0-9_\-./]+\.(js|py|sh|ts)/gi) || [];
|
|
839
|
+
for (const ref of codeFileRefs) {
|
|
840
|
+
const cleanRef = ref.replace(/^\.\//, '');
|
|
841
|
+
if (!allContent[cleanRef] && !files.some(f => path.relative(skillPath, f) === cleanRef)) {
|
|
842
|
+
findings.push({ severity: 'MEDIUM', id: 'XFILE_PHANTOM_REF', cat: 'structural', desc: `SKILL.md references non-existent file: ${cleanRef}`, file: 'SKILL.md' });
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
const base64Fragments = [];
|
|
847
|
+
for (const [file, content] of Object.entries(allContent)) {
|
|
848
|
+
const matches = content.match(/[A-Za-z0-9+/]{20,}={0,2}/g) || [];
|
|
849
|
+
for (const m of matches) {
|
|
850
|
+
if (m.length > 40) base64Fragments.push({ file, fragment: m.substring(0, 30) });
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
if (base64Fragments.length > 3 && new Set(base64Fragments.map(f => f.file)).size > 1) {
|
|
854
|
+
findings.push({ severity: 'HIGH', id: 'XFILE_FRAGMENT_B64', cat: 'obfuscation', desc: `Base64 fragments across ${new Set(base64Fragments.map(f => f.file)).size} files`, file: skillName });
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
if (/(?:read|load|source|import)\s+(?:the\s+)?(?:script|file|code)\s+(?:from|at|in)\s+(?:scripts?\/)/gi.test(skillMd)) {
|
|
858
|
+
const hasExec = Object.values(allContent).some(c => /(?:eval|exec|spawn)\s*\(/i.test(c));
|
|
859
|
+
if (hasExec) {
|
|
860
|
+
findings.push({ severity: 'MEDIUM', id: 'XFILE_LOAD_EXEC', cat: 'data-flow', desc: 'SKILL.md references script files that contain exec/eval', file: 'SKILL.md' });
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
calculateRisk(findings) {
|
|
866
|
+
if (findings.length === 0) return 0;
|
|
867
|
+
|
|
868
|
+
let score = 0;
|
|
869
|
+
for (const f of findings) {
|
|
870
|
+
score += SEVERITY_WEIGHTS[f.severity] || 0;
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
const ids = new Set(findings.map(f => f.id));
|
|
874
|
+
const cats = new Set(findings.map(f => f.cat));
|
|
875
|
+
|
|
876
|
+
if (cats.has('credential-handling') && cats.has('exfiltration')) score = Math.round(score * 2);
|
|
877
|
+
if (cats.has('credential-handling') && findings.some(f => f.id === 'MAL_CHILD' || f.id === 'MAL_EXEC')) score = Math.round(score * 1.5);
|
|
878
|
+
if (cats.has('obfuscation') && (cats.has('malicious-code') || cats.has('credential-handling'))) score = Math.round(score * 2);
|
|
879
|
+
if (ids.has('DEP_LIFECYCLE_EXEC')) score = Math.round(score * 2);
|
|
880
|
+
if (ids.has('PI_BIDI') && findings.length > 1) score = Math.round(score * 1.5);
|
|
881
|
+
if (cats.has('leaky-skills') && (cats.has('exfiltration') || cats.has('malicious-code'))) score = Math.round(score * 2);
|
|
882
|
+
if (cats.has('memory-poisoning')) score = Math.round(score * 1.5);
|
|
883
|
+
if (cats.has('prompt-worm')) score = Math.round(score * 2);
|
|
884
|
+
if (cats.has('cve-patterns')) score = Math.max(score, 70);
|
|
885
|
+
if (cats.has('persistence') && (cats.has('malicious-code') || cats.has('credential-handling') || cats.has('memory-poisoning'))) score = Math.round(score * 1.5);
|
|
886
|
+
if (cats.has('identity-hijack')) score = Math.round(score * 2);
|
|
887
|
+
if (cats.has('identity-hijack') && (cats.has('persistence') || cats.has('memory-poisoning'))) score = Math.max(score, 90);
|
|
888
|
+
if (ids.has('IOC_IP') || ids.has('IOC_URL') || ids.has('KNOWN_TYPOSQUAT')) score = 100;
|
|
889
|
+
|
|
890
|
+
// v1.1 categories
|
|
891
|
+
if (cats.has('config-impact')) score = Math.round(score * 2);
|
|
892
|
+
if (cats.has('config-impact') && cats.has('sandbox-validation')) score = Math.max(score, 70);
|
|
893
|
+
if (cats.has('complexity') && (cats.has('malicious-code') || cats.has('obfuscation'))) score = Math.round(score * 1.5);
|
|
894
|
+
|
|
895
|
+
// v2.1 PII exposure amplifiers
|
|
896
|
+
if (cats.has('pii-exposure') && cats.has('exfiltration')) score = Math.round(score * 3);
|
|
897
|
+
if (cats.has('pii-exposure') && (ids.has('SHADOW_AI_OPENAI') || ids.has('SHADOW_AI_ANTHROPIC') || ids.has('SHADOW_AI_GENERIC'))) score = Math.round(score * 2.5);
|
|
898
|
+
if (cats.has('pii-exposure') && cats.has('credential-handling')) score = Math.round(score * 2);
|
|
899
|
+
|
|
900
|
+
return Math.min(100, score);
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
getVerdict(risk) {
|
|
904
|
+
if (risk >= this.thresholds.malicious) return { icon: 'š“', label: 'MALICIOUS', stat: 'malicious' };
|
|
905
|
+
if (risk >= this.thresholds.suspicious) return { icon: 'š”', label: 'SUSPICIOUS', stat: 'suspicious' };
|
|
906
|
+
if (risk > 0) return { icon: 'š¢', label: 'LOW RISK', stat: 'low' };
|
|
907
|
+
return { icon: 'š¢', label: 'CLEAN', stat: 'clean' };
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
getFiles(dir) {
|
|
911
|
+
const results = [];
|
|
912
|
+
try {
|
|
913
|
+
const entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
914
|
+
for (const entry of entries) {
|
|
915
|
+
const fullPath = path.join(dir, entry.name);
|
|
916
|
+
if (entry.isDirectory()) {
|
|
917
|
+
if (entry.name === '.git' || entry.name === 'node_modules') continue;
|
|
918
|
+
results.push(...this.getFiles(fullPath));
|
|
919
|
+
} else {
|
|
920
|
+
const baseName = entry.name.toLowerCase();
|
|
921
|
+
if (GENERATED_REPORT_FILES.has(baseName)) continue;
|
|
922
|
+
results.push(fullPath);
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
} catch { }
|
|
926
|
+
return results;
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
printSummary() {
|
|
930
|
+
const total = this.stats.scanned;
|
|
931
|
+
const safe = this.stats.clean + this.stats.low;
|
|
932
|
+
console.log(`\n${'ā'.repeat(54)}`);
|
|
933
|
+
console.log(`š guard-scanner v${VERSION} Scan Summary`);
|
|
934
|
+
console.log(`${'ā'.repeat(54)}`);
|
|
935
|
+
console.log(` Scanned: ${total}`);
|
|
936
|
+
console.log(` š¢ Clean: ${this.stats.clean}`);
|
|
937
|
+
console.log(` š¢ Low Risk: ${this.stats.low}`);
|
|
938
|
+
console.log(` š” Suspicious: ${this.stats.suspicious}`);
|
|
939
|
+
console.log(` š“ Malicious: ${this.stats.malicious}`);
|
|
940
|
+
console.log(` Safety Rate: ${total ? Math.round(safe / total * 100) : 0}%`);
|
|
941
|
+
console.log(`${'ā'.repeat(54)}`);
|
|
942
|
+
|
|
943
|
+
if (this.stats.malicious > 0) {
|
|
944
|
+
console.log(`\nā ļø CRITICAL: ${this.stats.malicious} malicious skill(s) detected!`);
|
|
945
|
+
console.log(` Review findings with --verbose and remove if confirmed.`);
|
|
946
|
+
} else if (this.stats.suspicious > 0) {
|
|
947
|
+
console.log(`\nā” ${this.stats.suspicious} suspicious skill(s) found ā review recommended.`);
|
|
948
|
+
} else {
|
|
949
|
+
console.log(`\nā
All clear! No threats detected.`);
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
toJSON() {
|
|
954
|
+
const recommendations = [];
|
|
955
|
+
for (const skillResult of this.findings) {
|
|
956
|
+
const skillRecs = [];
|
|
957
|
+
const cats = new Set(skillResult.findings.map(f => f.cat));
|
|
958
|
+
|
|
959
|
+
if (cats.has('prompt-injection')) skillRecs.push('š Contains prompt injection patterns.');
|
|
960
|
+
if (cats.has('malicious-code')) skillRecs.push('š Contains potentially malicious code.');
|
|
961
|
+
if (cats.has('credential-handling') && cats.has('exfiltration')) skillRecs.push('š CRITICAL: Credential access + exfiltration. DO NOT INSTALL.');
|
|
962
|
+
if (cats.has('dependency-chain')) skillRecs.push('š¦ Suspicious dependency chain.');
|
|
963
|
+
if (cats.has('obfuscation')) skillRecs.push('š Code obfuscation detected.');
|
|
964
|
+
if (cats.has('secret-detection')) skillRecs.push('š Possible hardcoded secrets.');
|
|
965
|
+
if (cats.has('leaky-skills')) skillRecs.push('š§ LEAKY SKILL: Secrets pass through LLM context.');
|
|
966
|
+
if (cats.has('memory-poisoning')) skillRecs.push('š§ MEMORY POISONING: Agent memory modification attempt.');
|
|
967
|
+
if (cats.has('prompt-worm')) skillRecs.push('šŖ± PROMPT WORM: Self-replicating instructions.');
|
|
968
|
+
if (cats.has('data-flow')) skillRecs.push('š Suspicious data flow patterns.');
|
|
969
|
+
if (cats.has('persistence')) skillRecs.push('ā° PERSISTENCE: Creates scheduled tasks.');
|
|
970
|
+
if (cats.has('cve-patterns')) skillRecs.push('šØ CVE PATTERN: Matches known exploits.');
|
|
971
|
+
if (cats.has('identity-hijack')) skillRecs.push('š IDENTITY HIJACK: Agent soul file tampering. DO NOT INSTALL.');
|
|
972
|
+
if (cats.has('sandbox-validation')) skillRecs.push('š SANDBOX: Skill requests dangerous capabilities.');
|
|
973
|
+
if (cats.has('complexity')) skillRecs.push('š§© COMPLEXITY: Excessive code complexity may hide malicious behavior.');
|
|
974
|
+
if (cats.has('config-impact')) skillRecs.push('āļø CONFIG IMPACT: Modifies OpenClaw configuration. DO NOT INSTALL.');
|
|
975
|
+
if (cats.has('pii-exposure')) skillRecs.push('š PII EXPOSURE: Handles personally identifiable information. Review data handling.');
|
|
976
|
+
|
|
977
|
+
if (skillRecs.length > 0) recommendations.push({ skill: skillResult.skill, actions: skillRecs });
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
return {
|
|
981
|
+
timestamp: new Date().toISOString(),
|
|
982
|
+
scanner: `guard-scanner v${VERSION}`,
|
|
983
|
+
mode: this.strict ? 'strict' : 'normal',
|
|
984
|
+
stats: this.stats,
|
|
985
|
+
thresholds: this.thresholds,
|
|
986
|
+
findings: this.findings,
|
|
987
|
+
recommendations,
|
|
988
|
+
iocVersion: '2026-02-12',
|
|
989
|
+
};
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
toSARIF(scanDir) {
|
|
993
|
+
const rules = [];
|
|
994
|
+
const ruleIndex = {};
|
|
995
|
+
const results = [];
|
|
996
|
+
|
|
997
|
+
for (const skillResult of this.findings) {
|
|
998
|
+
for (const f of skillResult.findings) {
|
|
999
|
+
if (!ruleIndex[f.id]) {
|
|
1000
|
+
ruleIndex[f.id] = rules.length;
|
|
1001
|
+
rules.push({
|
|
1002
|
+
id: f.id, name: f.id,
|
|
1003
|
+
shortDescription: { text: f.desc },
|
|
1004
|
+
defaultConfiguration: { level: f.severity === 'CRITICAL' ? 'error' : f.severity === 'HIGH' ? 'error' : f.severity === 'MEDIUM' ? 'warning' : 'note' },
|
|
1005
|
+
properties: { tags: ['security', f.cat], 'security-severity': f.severity === 'CRITICAL' ? '9.0' : f.severity === 'HIGH' ? '7.0' : f.severity === 'MEDIUM' ? '4.0' : '1.0' }
|
|
1006
|
+
});
|
|
1007
|
+
}
|
|
1008
|
+
const normalizedFile = String(f.file || '')
|
|
1009
|
+
.replaceAll('\\', '/')
|
|
1010
|
+
.replace(/^\/+/, '');
|
|
1011
|
+
const artifactUri = `${skillResult.skill}/${normalizedFile}`;
|
|
1012
|
+
const fingerprintSeed = `${f.id}|${artifactUri}|${f.line || 0}|${(f.sample || '').slice(0, 200)}`;
|
|
1013
|
+
const lineHash = crypto.createHash('sha256').update(fingerprintSeed).digest('hex').slice(0, 24);
|
|
1014
|
+
|
|
1015
|
+
results.push({
|
|
1016
|
+
ruleId: f.id, ruleIndex: ruleIndex[f.id],
|
|
1017
|
+
level: f.severity === 'CRITICAL' ? 'error' : f.severity === 'HIGH' ? 'error' : f.severity === 'MEDIUM' ? 'warning' : 'note',
|
|
1018
|
+
message: { text: `[${skillResult.skill}] ${f.desc}${f.sample ? ` ā "${f.sample}"` : ''}` },
|
|
1019
|
+
partialFingerprints: {
|
|
1020
|
+
primaryLocationLineHash: lineHash
|
|
1021
|
+
},
|
|
1022
|
+
locations: [{ physicalLocation: { artifactLocation: { uri: artifactUri, uriBaseId: '%SRCROOT%' }, region: f.line ? { startLine: f.line } : undefined } }]
|
|
1023
|
+
});
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
return {
|
|
1028
|
+
version: '2.1.0',
|
|
1029
|
+
$schema: 'https://json.schemastore.org/sarif-2.1.0.json',
|
|
1030
|
+
runs: [{
|
|
1031
|
+
tool: { driver: { name: 'guard-scanner', version: VERSION, informationUri: 'https://github.com/koatora20/guard-scanner', rules } },
|
|
1032
|
+
results,
|
|
1033
|
+
invocations: [{ executionSuccessful: true, endTimeUtc: new Date().toISOString() }]
|
|
1034
|
+
}]
|
|
1035
|
+
};
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
toHTML() {
|
|
1039
|
+
return generateHTML(VERSION, this.stats, this.findings);
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
const { scanToolCall, RUNTIME_CHECKS, getCheckStats, LAYER_NAMES } = require('./runtime-guard.js');
|
|
1044
|
+
|
|
1045
|
+
module.exports = { GuardScanner, VERSION, THRESHOLDS, SEVERITY_WEIGHTS, scanToolCall, RUNTIME_CHECKS, getCheckStats, LAYER_NAMES };
|