pompelmi 0.35.5 → 1.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/.claude/settings.local.json +45 -0
- package/LICENSE +12 -18
- package/README.md +174 -181
- package/eslint.config.mjs +8 -0
- package/package.json +26 -251
- package/src/ClamAVDatabaseUpdater.js +48 -0
- package/src/ClamAVInstaller.js +49 -0
- package/src/ClamAVScanner.js +37 -0
- package/src/ClamdScanner.js +81 -0
- package/src/InstallerCommand.js +11 -0
- package/src/config.js +22 -0
- package/src/constants.js +3 -0
- package/src/favicon.ico +0 -0
- package/src/grapefruit.png +0 -0
- package/src/index.js +5 -0
- package/test_out.txt +74 -0
- package/CHANGELOG.md +0 -71
- package/dist/pompelmi.audit.cjs +0 -128
- package/dist/pompelmi.audit.cjs.map +0 -1
- package/dist/pompelmi.audit.esm.js +0 -107
- package/dist/pompelmi.audit.esm.js.map +0 -1
- package/dist/pompelmi.browser.cjs +0 -1549
- package/dist/pompelmi.browser.cjs.map +0 -1
- package/dist/pompelmi.browser.esm.js +0 -1523
- package/dist/pompelmi.browser.esm.js.map +0 -1
- package/dist/pompelmi.cjs +0 -2591
- package/dist/pompelmi.cjs.map +0 -1
- package/dist/pompelmi.esm.js +0 -2525
- package/dist/pompelmi.esm.js.map +0 -1
- package/dist/pompelmi.hooks.cjs +0 -75
- package/dist/pompelmi.hooks.cjs.map +0 -1
- package/dist/pompelmi.hooks.esm.js +0 -72
- package/dist/pompelmi.hooks.esm.js.map +0 -1
- package/dist/pompelmi.policy-packs.cjs +0 -240
- package/dist/pompelmi.policy-packs.cjs.map +0 -1
- package/dist/pompelmi.policy-packs.esm.js +0 -232
- package/dist/pompelmi.policy-packs.esm.js.map +0 -1
- package/dist/pompelmi.quarantine.cjs +0 -317
- package/dist/pompelmi.quarantine.cjs.map +0 -1
- package/dist/pompelmi.quarantine.esm.js +0 -293
- package/dist/pompelmi.quarantine.esm.js.map +0 -1
- package/dist/pompelmi.react.cjs +0 -1580
- package/dist/pompelmi.react.cjs.map +0 -1
- package/dist/pompelmi.react.esm.js +0 -1553
- package/dist/pompelmi.react.esm.js.map +0 -1
- package/dist/types/audit.d.ts +0 -84
- package/dist/types/browser-index.d.ts +0 -29
- package/dist/types/config.d.ts +0 -143
- package/dist/types/engines/dynamic-taint.d.ts +0 -102
- package/dist/types/engines/hybrid-orchestrator.d.ts +0 -65
- package/dist/types/engines/hybrid-taint-integration.d.ts +0 -129
- package/dist/types/engines/taint-policies.d.ts +0 -84
- package/dist/types/hipaa-compliance.d.ts +0 -110
- package/dist/types/hooks.d.ts +0 -89
- package/dist/types/index.d.ts +0 -29
- package/dist/types/magic.d.ts +0 -7
- package/dist/types/node/scanDir.d.ts +0 -30
- package/dist/types/policy-packs.d.ts +0 -98
- package/dist/types/policy.d.ts +0 -12
- package/dist/types/presets.d.ts +0 -72
- package/dist/types/quarantine/index.d.ts +0 -18
- package/dist/types/quarantine/storage.d.ts +0 -77
- package/dist/types/quarantine/types.d.ts +0 -78
- package/dist/types/quarantine/workflow.d.ts +0 -97
- package/dist/types/react-index.d.ts +0 -13
- package/dist/types/risk.d.ts +0 -18
- package/dist/types/scan/remote.d.ts +0 -12
- package/dist/types/scan.d.ts +0 -17
- package/dist/types/scanners/common-heuristics.d.ts +0 -14
- package/dist/types/scanners/zip-bomb-guard.d.ts +0 -9
- package/dist/types/scanners/zipTraversalGuard.d.ts +0 -19
- package/dist/types/src/audit.d.ts +0 -84
- package/dist/types/src/browser-index.d.ts +0 -29
- package/dist/types/src/config.d.ts +0 -143
- package/dist/types/src/engines/dynamic-taint.d.ts +0 -102
- package/dist/types/src/engines/hybrid-orchestrator.d.ts +0 -65
- package/dist/types/src/engines/hybrid-taint-integration.d.ts +0 -129
- package/dist/types/src/engines/taint-policies.d.ts +0 -84
- package/dist/types/src/hipaa-compliance.d.ts +0 -110
- package/dist/types/src/hooks.d.ts +0 -89
- package/dist/types/src/index.d.ts +0 -29
- package/dist/types/src/magic.d.ts +0 -7
- package/dist/types/src/node/scanDir.d.ts +0 -30
- package/dist/types/src/policy-packs.d.ts +0 -98
- package/dist/types/src/policy.d.ts +0 -12
- package/dist/types/src/presets.d.ts +0 -72
- package/dist/types/src/quarantine/index.d.ts +0 -18
- package/dist/types/src/quarantine/storage.d.ts +0 -77
- package/dist/types/src/quarantine/types.d.ts +0 -78
- package/dist/types/src/quarantine/workflow.d.ts +0 -97
- package/dist/types/src/react-index.d.ts +0 -13
- package/dist/types/src/risk.d.ts +0 -18
- package/dist/types/src/scan/remote.d.ts +0 -12
- package/dist/types/src/scan.d.ts +0 -17
- package/dist/types/src/scanners/common-heuristics.d.ts +0 -14
- package/dist/types/src/scanners/zip-bomb-guard.d.ts +0 -11
- package/dist/types/src/scanners/zipTraversalGuard.d.ts +0 -19
- package/dist/types/src/stream.d.ts +0 -10
- package/dist/types/src/types/decompilation.d.ts +0 -96
- package/dist/types/src/types/taint-tracking.d.ts +0 -495
- package/dist/types/src/types.d.ts +0 -48
- package/dist/types/src/useFileScanner.d.ts +0 -15
- package/dist/types/src/utils/advanced-detection.d.ts +0 -21
- package/dist/types/src/utils/batch-scanner.d.ts +0 -62
- package/dist/types/src/utils/cache-manager.d.ts +0 -95
- package/dist/types/src/utils/export.d.ts +0 -51
- package/dist/types/src/utils/performance-metrics.d.ts +0 -68
- package/dist/types/src/utils/threat-intelligence.d.ts +0 -96
- package/dist/types/src/validate.d.ts +0 -7
- package/dist/types/src/verdict.d.ts +0 -2
- package/dist/types/src/yara/browser.d.ts +0 -7
- package/dist/types/src/yara/index.d.ts +0 -17
- package/dist/types/src/yara/node.d.ts +0 -2
- package/dist/types/src/yara/remote.d.ts +0 -10
- package/dist/types/src/yara-bridge.d.ts +0 -3
- package/dist/types/src/zip.d.ts +0 -13
- package/dist/types/stream.d.ts +0 -10
- package/dist/types/types/decompilation.d.ts +0 -96
- package/dist/types/types/taint-tracking.d.ts +0 -495
- package/dist/types/types.d.ts +0 -48
- package/dist/types/useFileScanner.d.ts +0 -15
- package/dist/types/utils/advanced-detection.d.ts +0 -21
- package/dist/types/utils/batch-scanner.d.ts +0 -62
- package/dist/types/utils/cache-manager.d.ts +0 -95
- package/dist/types/utils/export.d.ts +0 -51
- package/dist/types/utils/performance-metrics.d.ts +0 -68
- package/dist/types/utils/threat-intelligence.d.ts +0 -96
- package/dist/types/validate.d.ts +0 -7
- package/dist/types/verdict.d.ts +0 -2
- package/dist/types/yara/browser.d.ts +0 -7
- package/dist/types/yara/index.d.ts +0 -17
- package/dist/types/yara/node.d.ts +0 -2
- package/dist/types/yara/remote.d.ts +0 -10
- package/dist/types/yara-bridge.d.ts +0 -3
- package/dist/types/zip.d.ts +0 -13
|
@@ -1,1523 +0,0 @@
|
|
|
1
|
-
import { createHash } from 'crypto';
|
|
2
|
-
import { createInflateRaw } from 'zlib';
|
|
3
|
-
|
|
4
|
-
const MB$1 = 1024 * 1024;
|
|
5
|
-
const DEFAULT_POLICY = {
|
|
6
|
-
includeExtensions: ["zip", "png", "jpg", "jpeg", "pdf"],
|
|
7
|
-
allowedMimeTypes: ["application/zip", "image/png", "image/jpeg", "application/pdf", "text/plain"],
|
|
8
|
-
maxFileSizeBytes: 20 * MB$1,
|
|
9
|
-
timeoutMs: 5000,
|
|
10
|
-
concurrency: 4,
|
|
11
|
-
failClosed: true,
|
|
12
|
-
};
|
|
13
|
-
function definePolicy(input = {}) {
|
|
14
|
-
const p = { ...DEFAULT_POLICY, ...input };
|
|
15
|
-
if (!Array.isArray(p.includeExtensions))
|
|
16
|
-
throw new TypeError("includeExtensions must be string[]");
|
|
17
|
-
if (!Array.isArray(p.allowedMimeTypes))
|
|
18
|
-
throw new TypeError("allowedMimeTypes must be string[]");
|
|
19
|
-
if (!(Number.isFinite(p.maxFileSizeBytes) && p.maxFileSizeBytes > 0))
|
|
20
|
-
throw new TypeError("maxFileSizeBytes must be > 0");
|
|
21
|
-
if (!(Number.isFinite(p.timeoutMs) && p.timeoutMs > 0))
|
|
22
|
-
throw new TypeError("timeoutMs must be > 0");
|
|
23
|
-
if (!(Number.isInteger(p.concurrency) && p.concurrency > 0))
|
|
24
|
-
throw new TypeError("concurrency must be > 0");
|
|
25
|
-
return p;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
/**
|
|
29
|
-
* Policy packs for Pompelmi.
|
|
30
|
-
*
|
|
31
|
-
* Pre-configured, named policies for common upload scenarios. Each pack
|
|
32
|
-
* defines the file type allowlist, size limits, and timeout appropriate for
|
|
33
|
-
* its use case.
|
|
34
|
-
*
|
|
35
|
-
* All packs are built on `definePolicy` and are fully overridable:
|
|
36
|
-
*
|
|
37
|
-
* ```ts
|
|
38
|
-
* import { POLICY_PACKS } from 'pompelmi/policy-packs';
|
|
39
|
-
*
|
|
40
|
-
* // Use a pack as-is:
|
|
41
|
-
* const policy = POLICY_PACKS['images-only'];
|
|
42
|
-
*
|
|
43
|
-
* // Or override individual fields:
|
|
44
|
-
* import { definePolicy } from 'pompelmi';
|
|
45
|
-
* const custom = definePolicy({ ...POLICY_PACKS['documents-only'], maxFileSizeBytes: 5 * 1024 * 1024 });
|
|
46
|
-
* ```
|
|
47
|
-
*
|
|
48
|
-
* These packs are *deterministic* and *descriptor-based* — they do not
|
|
49
|
-
* depend on any external threat intelligence feed.
|
|
50
|
-
*
|
|
51
|
-
* @module policy-packs
|
|
52
|
-
*/
|
|
53
|
-
const KB = 1024;
|
|
54
|
-
const MB = 1024 * KB;
|
|
55
|
-
// ── Policy packs ──────────────────────────────────────────────────────────────
|
|
56
|
-
/**
|
|
57
|
-
* Documents-only policy.
|
|
58
|
-
*
|
|
59
|
-
* Appropriate for: document management APIs, PDF/Office file upload endpoints,
|
|
60
|
-
* data import pipelines.
|
|
61
|
-
*
|
|
62
|
-
* Allowed: PDF, Word (.docx/.doc), Excel (.xlsx/.xls), PowerPoint (.pptx/.ppt),
|
|
63
|
-
* CSV, plain text, JSON, YAML, ODT/ODS/ODP (OpenDocument).
|
|
64
|
-
* Max size: 25 MB.
|
|
65
|
-
*/
|
|
66
|
-
const DOCUMENTS_ONLY = definePolicy({
|
|
67
|
-
includeExtensions: [
|
|
68
|
-
"pdf",
|
|
69
|
-
"doc",
|
|
70
|
-
"docx",
|
|
71
|
-
"xls",
|
|
72
|
-
"xlsx",
|
|
73
|
-
"ppt",
|
|
74
|
-
"pptx",
|
|
75
|
-
"odt",
|
|
76
|
-
"ods",
|
|
77
|
-
"odp",
|
|
78
|
-
"csv",
|
|
79
|
-
"txt",
|
|
80
|
-
"json",
|
|
81
|
-
"yaml",
|
|
82
|
-
"yml",
|
|
83
|
-
"md",
|
|
84
|
-
],
|
|
85
|
-
allowedMimeTypes: [
|
|
86
|
-
"application/pdf",
|
|
87
|
-
"application/msword",
|
|
88
|
-
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
89
|
-
"application/vnd.ms-excel",
|
|
90
|
-
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
91
|
-
"application/vnd.ms-powerpoint",
|
|
92
|
-
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
|
93
|
-
"application/vnd.oasis.opendocument.text",
|
|
94
|
-
"application/vnd.oasis.opendocument.spreadsheet",
|
|
95
|
-
"application/vnd.oasis.opendocument.presentation",
|
|
96
|
-
"text/csv",
|
|
97
|
-
"text/plain",
|
|
98
|
-
"application/json",
|
|
99
|
-
"text/yaml",
|
|
100
|
-
"text/markdown",
|
|
101
|
-
],
|
|
102
|
-
maxFileSizeBytes: 25 * MB,
|
|
103
|
-
timeoutMs: 10000,
|
|
104
|
-
concurrency: 4,
|
|
105
|
-
failClosed: true,
|
|
106
|
-
});
|
|
107
|
-
/**
|
|
108
|
-
* Images-only policy.
|
|
109
|
-
*
|
|
110
|
-
* Appropriate for: avatar uploads, product image APIs, content platforms with
|
|
111
|
-
* user-generated imagery.
|
|
112
|
-
*
|
|
113
|
-
* Allowed: JPEG, PNG, GIF, WebP, AVIF, TIFF, BMP, ICO.
|
|
114
|
-
* Max size: 10 MB.
|
|
115
|
-
* Note: SVG is intentionally excluded — inline SVGs can contain scripts.
|
|
116
|
-
*/
|
|
117
|
-
const IMAGES_ONLY = definePolicy({
|
|
118
|
-
includeExtensions: ["jpg", "jpeg", "png", "gif", "webp", "avif", "tiff", "tif", "bmp", "ico"],
|
|
119
|
-
allowedMimeTypes: [
|
|
120
|
-
"image/jpeg",
|
|
121
|
-
"image/png",
|
|
122
|
-
"image/gif",
|
|
123
|
-
"image/webp",
|
|
124
|
-
"image/avif",
|
|
125
|
-
"image/tiff",
|
|
126
|
-
"image/bmp",
|
|
127
|
-
"image/x-icon",
|
|
128
|
-
"image/vnd.microsoft.icon",
|
|
129
|
-
],
|
|
130
|
-
maxFileSizeBytes: 10 * MB,
|
|
131
|
-
timeoutMs: 5000,
|
|
132
|
-
concurrency: 8,
|
|
133
|
-
failClosed: true,
|
|
134
|
-
});
|
|
135
|
-
/**
|
|
136
|
-
* Strict public-upload policy.
|
|
137
|
-
*
|
|
138
|
-
* Appropriate for: anonymous or low-trust upload endpoints, public APIs,
|
|
139
|
-
* any surface exposed to untrusted users.
|
|
140
|
-
*
|
|
141
|
-
* Aggressive size limit (5 MB), short timeout, fail-closed, narrow MIME
|
|
142
|
-
* allowlist. Only allows plain images and PDF.
|
|
143
|
-
*/
|
|
144
|
-
const STRICT_PUBLIC_UPLOAD = definePolicy({
|
|
145
|
-
includeExtensions: ["jpg", "jpeg", "png", "webp", "pdf"],
|
|
146
|
-
allowedMimeTypes: ["image/jpeg", "image/png", "image/webp", "application/pdf"],
|
|
147
|
-
maxFileSizeBytes: 5 * MB,
|
|
148
|
-
timeoutMs: 4000,
|
|
149
|
-
concurrency: 2,
|
|
150
|
-
failClosed: true,
|
|
151
|
-
});
|
|
152
|
-
/**
|
|
153
|
-
* Conservative default policy.
|
|
154
|
-
*
|
|
155
|
-
* A hardened version of the built-in `DEFAULT_POLICY` suitable for
|
|
156
|
-
* production without further customisation. Stricter size limit and
|
|
157
|
-
* shorter timeout than the permissive default.
|
|
158
|
-
*/
|
|
159
|
-
const CONSERVATIVE_DEFAULT = definePolicy({
|
|
160
|
-
includeExtensions: ["zip", "png", "jpg", "jpeg", "pdf", "txt", "csv", "docx", "xlsx"],
|
|
161
|
-
allowedMimeTypes: [
|
|
162
|
-
"application/zip",
|
|
163
|
-
"image/png",
|
|
164
|
-
"image/jpeg",
|
|
165
|
-
"application/pdf",
|
|
166
|
-
"text/plain",
|
|
167
|
-
"text/csv",
|
|
168
|
-
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
169
|
-
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
170
|
-
],
|
|
171
|
-
maxFileSizeBytes: 10 * MB,
|
|
172
|
-
timeoutMs: 8000,
|
|
173
|
-
concurrency: 4,
|
|
174
|
-
failClosed: true,
|
|
175
|
-
});
|
|
176
|
-
/**
|
|
177
|
-
* Archives policy.
|
|
178
|
-
*
|
|
179
|
-
* Appropriate for: endpoints that accept ZIP, tar, or compressed archives.
|
|
180
|
-
* Combines a generous size allowance with a longer timeout for deep inspection.
|
|
181
|
-
*
|
|
182
|
-
* NOTE: Pair this policy with `createZipBombGuard()` to defend against
|
|
183
|
-
* decompression-bomb attacks:
|
|
184
|
-
*
|
|
185
|
-
* ```ts
|
|
186
|
-
* import { composeScanners, createZipBombGuard, CommonHeuristicsScanner } from 'pompelmi';
|
|
187
|
-
* const scanner = composeScanners(
|
|
188
|
-
* [['zipGuard', createZipBombGuard()], ['heuristics', CommonHeuristicsScanner]]
|
|
189
|
-
* );
|
|
190
|
-
* ```
|
|
191
|
-
*/
|
|
192
|
-
const ARCHIVES = definePolicy({
|
|
193
|
-
includeExtensions: ["zip", "tar", "gz", "tgz", "bz2", "xz", "7z", "rar"],
|
|
194
|
-
allowedMimeTypes: [
|
|
195
|
-
"application/zip",
|
|
196
|
-
"application/x-tar",
|
|
197
|
-
"application/gzip",
|
|
198
|
-
"application/x-bzip2",
|
|
199
|
-
"application/x-xz",
|
|
200
|
-
"application/x-7z-compressed",
|
|
201
|
-
"application/x-rar-compressed",
|
|
202
|
-
],
|
|
203
|
-
maxFileSizeBytes: 100 * MB,
|
|
204
|
-
timeoutMs: 30000,
|
|
205
|
-
concurrency: 2,
|
|
206
|
-
failClosed: true,
|
|
207
|
-
});
|
|
208
|
-
/**
|
|
209
|
-
* Named map of all built-in policy packs.
|
|
210
|
-
*
|
|
211
|
-
* ```ts
|
|
212
|
-
* import { POLICY_PACKS } from 'pompelmi/policy-packs';
|
|
213
|
-
* const policy = POLICY_PACKS['strict-public-upload'];
|
|
214
|
-
* ```
|
|
215
|
-
*/
|
|
216
|
-
const POLICY_PACKS = {
|
|
217
|
-
"documents-only": DOCUMENTS_ONLY,
|
|
218
|
-
"images-only": IMAGES_ONLY,
|
|
219
|
-
"strict-public-upload": STRICT_PUBLIC_UPLOAD,
|
|
220
|
-
"conservative-default": CONSERVATIVE_DEFAULT,
|
|
221
|
-
archives: ARCHIVES,
|
|
222
|
-
};
|
|
223
|
-
/**
|
|
224
|
-
* Look up a policy pack by name.
|
|
225
|
-
* Throws if the name is not recognised.
|
|
226
|
-
*/
|
|
227
|
-
function getPolicyPack(name) {
|
|
228
|
-
const policy = POLICY_PACKS[name];
|
|
229
|
-
if (!policy)
|
|
230
|
-
throw new Error(`Unknown policy pack: '${name}'. Valid names: ${Object.keys(POLICY_PACKS).join(", ")}`);
|
|
231
|
-
return policy;
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
function hasAsciiToken(buf, token) {
|
|
235
|
-
// Use latin1 so we can safely search binary
|
|
236
|
-
return buf.indexOf(token, 0, "latin1") !== -1;
|
|
237
|
-
}
|
|
238
|
-
function startsWith(buf, bytes) {
|
|
239
|
-
if (buf.length < bytes.length)
|
|
240
|
-
return false;
|
|
241
|
-
for (let i = 0; i < bytes.length; i++)
|
|
242
|
-
if (buf[i] !== bytes[i])
|
|
243
|
-
return false;
|
|
244
|
-
return true;
|
|
245
|
-
}
|
|
246
|
-
function isPDF(buf) {
|
|
247
|
-
// %PDF-
|
|
248
|
-
return startsWith(buf, [0x25, 0x50, 0x44, 0x46, 0x2d]);
|
|
249
|
-
}
|
|
250
|
-
function isOleCfb(buf) {
|
|
251
|
-
// D0 CF 11 E0 A1 B1 1A E1
|
|
252
|
-
const sig = [0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1];
|
|
253
|
-
return startsWith(buf, sig);
|
|
254
|
-
}
|
|
255
|
-
function isZipLike$1(buf) {
|
|
256
|
-
// PK\x03\x04
|
|
257
|
-
return startsWith(buf, [0x50, 0x4b, 0x03, 0x04]);
|
|
258
|
-
}
|
|
259
|
-
function isPeExecutable(buf) {
|
|
260
|
-
// "MZ"
|
|
261
|
-
return startsWith(buf, [0x4d, 0x5a]);
|
|
262
|
-
}
|
|
263
|
-
/** OOXML macro hint via filename token in ZIP container */
|
|
264
|
-
function hasOoxmlMacros(buf) {
|
|
265
|
-
if (!isZipLike$1(buf))
|
|
266
|
-
return false;
|
|
267
|
-
return hasAsciiToken(buf, "vbaProject.bin");
|
|
268
|
-
}
|
|
269
|
-
/** PDF risky features (/JavaScript, /OpenAction, /AA, /Launch) */
|
|
270
|
-
function pdfRiskTokens(buf) {
|
|
271
|
-
const tokens = ["/JavaScript", "/OpenAction", "/AA", "/Launch"];
|
|
272
|
-
return tokens.filter((t) => hasAsciiToken(buf, t));
|
|
273
|
-
}
|
|
274
|
-
const CommonHeuristicsScanner = {
|
|
275
|
-
async scan(input) {
|
|
276
|
-
const buf = Buffer.from(input);
|
|
277
|
-
const matches = [];
|
|
278
|
-
// Office macros (OLE / OOXML)
|
|
279
|
-
if (isOleCfb(buf)) {
|
|
280
|
-
matches.push({ rule: "office_ole_container", severity: "suspicious" });
|
|
281
|
-
}
|
|
282
|
-
if (hasOoxmlMacros(buf)) {
|
|
283
|
-
matches.push({ rule: "office_ooxml_macros", severity: "suspicious" });
|
|
284
|
-
}
|
|
285
|
-
// PDF risky tokens
|
|
286
|
-
if (isPDF(buf)) {
|
|
287
|
-
const toks = pdfRiskTokens(buf);
|
|
288
|
-
if (toks.length) {
|
|
289
|
-
matches.push({
|
|
290
|
-
rule: "pdf_risky_actions",
|
|
291
|
-
severity: "suspicious",
|
|
292
|
-
meta: { tokens: toks },
|
|
293
|
-
});
|
|
294
|
-
}
|
|
295
|
-
}
|
|
296
|
-
// Executable header
|
|
297
|
-
if (isPeExecutable(buf)) {
|
|
298
|
-
matches.push({ rule: "pe_executable_signature", severity: "suspicious" });
|
|
299
|
-
}
|
|
300
|
-
// EICAR test file
|
|
301
|
-
const EICAR_NEEDLE = "X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!";
|
|
302
|
-
if (hasAsciiToken(buf, EICAR_NEEDLE)) {
|
|
303
|
-
matches.push({
|
|
304
|
-
rule: "eicar_test_file",
|
|
305
|
-
severity: "high",
|
|
306
|
-
meta: { note: "EICAR standard antivirus test file detected" },
|
|
307
|
-
});
|
|
308
|
-
}
|
|
309
|
-
return matches;
|
|
310
|
-
},
|
|
311
|
-
};
|
|
312
|
-
|
|
313
|
-
function toScanFn(s) {
|
|
314
|
-
return (typeof s === "function" ? s : s.scan);
|
|
315
|
-
}
|
|
316
|
-
/** Map a Match's severity field to a Verdict for stopOn comparison. */
|
|
317
|
-
function matchToVerdict(m) {
|
|
318
|
-
const s = m.severity;
|
|
319
|
-
if (s === "critical" || s === "high" || s === "malicious")
|
|
320
|
-
return "malicious";
|
|
321
|
-
if (s === "medium" || s === "low" || s === "suspicious" || s === "info")
|
|
322
|
-
return "suspicious";
|
|
323
|
-
return "clean";
|
|
324
|
-
}
|
|
325
|
-
/** Highest verdict across all matches in the list. */
|
|
326
|
-
function highestSeverity(matches) {
|
|
327
|
-
if (matches.length === 0)
|
|
328
|
-
return null;
|
|
329
|
-
if (matches.some((m) => matchToVerdict(m) === "malicious"))
|
|
330
|
-
return "malicious";
|
|
331
|
-
if (matches.some((m) => matchToVerdict(m) === "suspicious"))
|
|
332
|
-
return "suspicious";
|
|
333
|
-
return "clean";
|
|
334
|
-
}
|
|
335
|
-
const SEVERITY_RANK = { malicious: 2, suspicious: 1, clean: 0 };
|
|
336
|
-
function shouldStop(matches, stopOn) {
|
|
337
|
-
if (!stopOn)
|
|
338
|
-
return false;
|
|
339
|
-
const highest = highestSeverity(matches);
|
|
340
|
-
if (!highest)
|
|
341
|
-
return false;
|
|
342
|
-
return SEVERITY_RANK[highest] >= SEVERITY_RANK[stopOn];
|
|
343
|
-
}
|
|
344
|
-
async function runWithTimeout(fn, timeoutMs) {
|
|
345
|
-
if (!timeoutMs)
|
|
346
|
-
return fn();
|
|
347
|
-
return new Promise((resolve, reject) => {
|
|
348
|
-
const timer = setTimeout(() => reject(new Error("scanner timeout")), timeoutMs);
|
|
349
|
-
fn().then((v) => {
|
|
350
|
-
clearTimeout(timer);
|
|
351
|
-
resolve(v);
|
|
352
|
-
}, (e) => {
|
|
353
|
-
clearTimeout(timer);
|
|
354
|
-
reject(e);
|
|
355
|
-
});
|
|
356
|
-
});
|
|
357
|
-
}
|
|
358
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
359
|
-
function composeScanners(...args) {
|
|
360
|
-
const first = args[0];
|
|
361
|
-
const rest = args.slice(1);
|
|
362
|
-
// ── Named-scanner array form ──────────────────────────────────────────────
|
|
363
|
-
if (Array.isArray(first) &&
|
|
364
|
-
(first.length === 0 || (Array.isArray(first[0]) && typeof first[0][0] === "string"))) {
|
|
365
|
-
const entries = first;
|
|
366
|
-
const opts = rest.length > 0 &&
|
|
367
|
-
!Array.isArray(rest[0]) &&
|
|
368
|
-
typeof rest[0] !== "function" &&
|
|
369
|
-
!(typeof rest[0] === "object" && rest[0] !== null && "scan" in rest[0])
|
|
370
|
-
? rest[0]
|
|
371
|
-
: {};
|
|
372
|
-
return async (input, ctx) => {
|
|
373
|
-
const all = [];
|
|
374
|
-
if (opts.parallel) {
|
|
375
|
-
// Parallel execution — collect all results then return
|
|
376
|
-
const results = await Promise.allSettled(entries.map(([_name, scanner]) => runWithTimeout(() => toScanFn(scanner)(input, ctx), opts.timeoutMsPerScanner)));
|
|
377
|
-
for (let i = 0; i < results.length; i++) {
|
|
378
|
-
const result = results[i];
|
|
379
|
-
if (result.status === "fulfilled" && Array.isArray(result.value)) {
|
|
380
|
-
const matches = opts.tagSourceName
|
|
381
|
-
? result.value.map((m) => ({
|
|
382
|
-
...m,
|
|
383
|
-
meta: { ...m.meta, _sourceName: entries[i][0] },
|
|
384
|
-
}))
|
|
385
|
-
: result.value;
|
|
386
|
-
all.push(...matches);
|
|
387
|
-
}
|
|
388
|
-
}
|
|
389
|
-
}
|
|
390
|
-
else {
|
|
391
|
-
// Sequential execution with optional stopOn short-circuit
|
|
392
|
-
for (const [name, scanner] of entries) {
|
|
393
|
-
try {
|
|
394
|
-
const out = await runWithTimeout(() => toScanFn(scanner)(input, ctx), opts.timeoutMsPerScanner);
|
|
395
|
-
if (Array.isArray(out)) {
|
|
396
|
-
const matches = opts.tagSourceName
|
|
397
|
-
? out.map((m) => ({ ...m, meta: { ...m.meta, _sourceName: name } }))
|
|
398
|
-
: out;
|
|
399
|
-
all.push(...matches);
|
|
400
|
-
if (shouldStop(all, opts.stopOn))
|
|
401
|
-
break;
|
|
402
|
-
}
|
|
403
|
-
}
|
|
404
|
-
catch {
|
|
405
|
-
// individual scanner failure is non-fatal
|
|
406
|
-
}
|
|
407
|
-
}
|
|
408
|
-
}
|
|
409
|
-
return all;
|
|
410
|
-
};
|
|
411
|
-
}
|
|
412
|
-
// ── Variadic form (backward-compatible) ───────────────────────────────────
|
|
413
|
-
const scanners = [first, ...rest].filter(Boolean);
|
|
414
|
-
return async (input, ctx) => {
|
|
415
|
-
const all = [];
|
|
416
|
-
for (const s of scanners) {
|
|
417
|
-
try {
|
|
418
|
-
const out = await toScanFn(s)(input, ctx);
|
|
419
|
-
if (Array.isArray(out))
|
|
420
|
-
all.push(...out);
|
|
421
|
-
}
|
|
422
|
-
catch {
|
|
423
|
-
// ignore individual scanner failures
|
|
424
|
-
}
|
|
425
|
-
}
|
|
426
|
-
return all;
|
|
427
|
-
};
|
|
428
|
-
}
|
|
429
|
-
function createPresetScanner(preset, opts = {}) {
|
|
430
|
-
const baseScanners = [CommonHeuristicsScanner];
|
|
431
|
-
const dynamicScannerPromises = [];
|
|
432
|
-
// Add decompilation scanners based on preset
|
|
433
|
-
if (preset === "decompilation-basic" ||
|
|
434
|
-
preset === "decompilation-deep" ||
|
|
435
|
-
preset === "malware-analysis" ||
|
|
436
|
-
opts.enableDecompilation) {
|
|
437
|
-
const depth = preset === "decompilation-deep" || preset === "malware-analysis"
|
|
438
|
-
? "deep"
|
|
439
|
-
: preset === "decompilation-basic"
|
|
440
|
-
? "basic"
|
|
441
|
-
: opts.decompilationDepth || "basic";
|
|
442
|
-
let importModule;
|
|
443
|
-
try {
|
|
444
|
-
// Dynamic import to avoid bundling issues - using Function to bypass TypeScript type checking
|
|
445
|
-
importModule = new Function("specifier", "return import(specifier)");
|
|
446
|
-
}
|
|
447
|
-
catch {
|
|
448
|
-
importModule = undefined;
|
|
449
|
-
}
|
|
450
|
-
if (importModule &&
|
|
451
|
-
(!opts.decompilationEngine ||
|
|
452
|
-
opts.decompilationEngine === "binaryninja-hlil" ||
|
|
453
|
-
opts.decompilationEngine === "both")) {
|
|
454
|
-
dynamicScannerPromises.push(importModule("@pompelmi/engine-binaryninja")
|
|
455
|
-
.then((mod) => mod.createBinaryNinjaScanner({
|
|
456
|
-
timeout: opts.decompilationTimeout || opts.timeout || 30000,
|
|
457
|
-
depth,
|
|
458
|
-
pythonPath: opts.pythonPath,
|
|
459
|
-
binaryNinjaPath: opts.binaryNinjaPath,
|
|
460
|
-
}))
|
|
461
|
-
.catch(() => null));
|
|
462
|
-
}
|
|
463
|
-
if (importModule &&
|
|
464
|
-
(!opts.decompilationEngine ||
|
|
465
|
-
opts.decompilationEngine === "ghidra-pcode" ||
|
|
466
|
-
opts.decompilationEngine === "both")) {
|
|
467
|
-
dynamicScannerPromises.push(importModule("@pompelmi/engine-ghidra")
|
|
468
|
-
.then((mod) => mod.createGhidraScanner({
|
|
469
|
-
timeout: opts.decompilationTimeout || opts.timeout || 30000,
|
|
470
|
-
depth,
|
|
471
|
-
ghidraPath: opts.ghidraPath,
|
|
472
|
-
analyzeHeadless: opts.analyzeHeadless,
|
|
473
|
-
}))
|
|
474
|
-
.catch(() => null));
|
|
475
|
-
}
|
|
476
|
-
}
|
|
477
|
-
let composedScannerPromise;
|
|
478
|
-
const getComposedScanner = async () => {
|
|
479
|
-
composedScannerPromise ?? (composedScannerPromise = Promise.all(dynamicScannerPromises).then((dynamicScanners) => composeScanners(...baseScanners, ...dynamicScanners.filter((scanner) => scanner !== null))));
|
|
480
|
-
return composedScannerPromise;
|
|
481
|
-
};
|
|
482
|
-
return async (input, ctx) => {
|
|
483
|
-
const scanner = await getComposedScanner();
|
|
484
|
-
return scanner(input, ctx);
|
|
485
|
-
};
|
|
486
|
-
}
|
|
487
|
-
|
|
488
|
-
/**
|
|
489
|
-
* Advanced threat detection utilities
|
|
490
|
-
* @module utils/advanced-detection
|
|
491
|
-
*/
|
|
492
|
-
/**
|
|
493
|
-
* Enhanced polyglot file detection
|
|
494
|
-
* Detects files that can be interpreted as multiple formats
|
|
495
|
-
*/
|
|
496
|
-
function detectPolyglot(bytes) {
|
|
497
|
-
const matches = [];
|
|
498
|
-
// Check for PDF/ZIP polyglot
|
|
499
|
-
if (isPDFZipPolyglot(bytes)) {
|
|
500
|
-
matches.push({
|
|
501
|
-
rule: "polyglot_pdf_zip",
|
|
502
|
-
severity: "high",
|
|
503
|
-
meta: { description: "File can be interpreted as both PDF and ZIP" },
|
|
504
|
-
});
|
|
505
|
-
}
|
|
506
|
-
// Check for image/script polyglot
|
|
507
|
-
if (isImageScriptPolyglot(bytes)) {
|
|
508
|
-
matches.push({
|
|
509
|
-
rule: "polyglot_image_script",
|
|
510
|
-
severity: "high",
|
|
511
|
-
meta: { description: "Image file contains executable script content" },
|
|
512
|
-
});
|
|
513
|
-
}
|
|
514
|
-
// Check for GIFAR (GIF/JAR polyglot)
|
|
515
|
-
if (isGIFAR(bytes)) {
|
|
516
|
-
matches.push({
|
|
517
|
-
rule: "polyglot_gifar",
|
|
518
|
-
severity: "critical",
|
|
519
|
-
meta: { description: "GIF file contains Java archive" },
|
|
520
|
-
});
|
|
521
|
-
}
|
|
522
|
-
return matches;
|
|
523
|
-
}
|
|
524
|
-
/**
|
|
525
|
-
* Detect obfuscated JavaScript/VBScript
|
|
526
|
-
*/
|
|
527
|
-
function detectObfuscatedScripts(bytes) {
|
|
528
|
-
const matches = [];
|
|
529
|
-
const text = new TextDecoder("utf-8", { fatal: false }).decode(bytes.slice(0, Math.min(64 * 1024, bytes.length)));
|
|
530
|
-
// Check for common obfuscation patterns
|
|
531
|
-
const obfuscationPatterns = [
|
|
532
|
-
/eval\s*\(\s*unescape\s*\(/gi,
|
|
533
|
-
/eval\s*\(\s*atob\s*\(/gi,
|
|
534
|
-
/String\.fromCharCode\s*\(\s*\d+(?:\s*,\s*\d+){10,}/gi,
|
|
535
|
-
/[a-z0-9]{100,}/gi, // Long encoded strings
|
|
536
|
-
/\\x[0-9a-f]{2}/gi, // Hex escapes
|
|
537
|
-
];
|
|
538
|
-
for (const pattern of obfuscationPatterns) {
|
|
539
|
-
if (pattern.test(text)) {
|
|
540
|
-
matches.push({
|
|
541
|
-
rule: "obfuscated_script",
|
|
542
|
-
severity: "medium",
|
|
543
|
-
meta: {
|
|
544
|
-
description: "Detected obfuscated script content",
|
|
545
|
-
pattern: pattern.source,
|
|
546
|
-
},
|
|
547
|
-
});
|
|
548
|
-
break;
|
|
549
|
-
}
|
|
550
|
-
}
|
|
551
|
-
return matches;
|
|
552
|
-
}
|
|
553
|
-
/**
|
|
554
|
-
* Enhanced nested archive detection with depth limits
|
|
555
|
-
*/
|
|
556
|
-
function analyzeNestedArchives(bytes, maxDepth = 10) {
|
|
557
|
-
let depth = 0;
|
|
558
|
-
let currentBytes = bytes;
|
|
559
|
-
while (depth < maxDepth) {
|
|
560
|
-
if (isArchive(currentBytes)) {
|
|
561
|
-
depth++;
|
|
562
|
-
{
|
|
563
|
-
break;
|
|
564
|
-
}
|
|
565
|
-
}
|
|
566
|
-
else {
|
|
567
|
-
break;
|
|
568
|
-
}
|
|
569
|
-
}
|
|
570
|
-
return {
|
|
571
|
-
depth,
|
|
572
|
-
hasExcessiveNesting: depth >= 5,
|
|
573
|
-
};
|
|
574
|
-
}
|
|
575
|
-
// Helper functions
|
|
576
|
-
function isPDFZipPolyglot(bytes) {
|
|
577
|
-
if (bytes.length < 8)
|
|
578
|
-
return false;
|
|
579
|
-
// Check for PDF signature
|
|
580
|
-
const hasPDF = bytes[0] === 0x25 && bytes[1] === 0x50 && bytes[2] === 0x44 && bytes[3] === 0x46;
|
|
581
|
-
// Check for ZIP signature anywhere in the file
|
|
582
|
-
let hasZIP = false;
|
|
583
|
-
for (let i = 0; i < Math.min(bytes.length - 4, 1024); i++) {
|
|
584
|
-
if (bytes[i] === 0x50 &&
|
|
585
|
-
bytes[i + 1] === 0x4b &&
|
|
586
|
-
bytes[i + 2] === 0x03 &&
|
|
587
|
-
bytes[i + 3] === 0x04) {
|
|
588
|
-
hasZIP = true;
|
|
589
|
-
break;
|
|
590
|
-
}
|
|
591
|
-
}
|
|
592
|
-
return hasPDF && hasZIP;
|
|
593
|
-
}
|
|
594
|
-
function isImageScriptPolyglot(bytes) {
|
|
595
|
-
if (bytes.length < 100)
|
|
596
|
-
return false;
|
|
597
|
-
// Check for image signatures
|
|
598
|
-
const isImage = (bytes[0] === 0xff && bytes[1] === 0xd8) || // JPEG
|
|
599
|
-
(bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) || // PNG
|
|
600
|
-
(bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46); // GIF
|
|
601
|
-
if (!isImage)
|
|
602
|
-
return false;
|
|
603
|
-
// Check for script content
|
|
604
|
-
const text = new TextDecoder("utf-8", { fatal: false }).decode(bytes);
|
|
605
|
-
return /<script|javascript:|eval\(|function\s*\(/i.test(text);
|
|
606
|
-
}
|
|
607
|
-
function isGIFAR(bytes) {
|
|
608
|
-
if (bytes.length < 100)
|
|
609
|
-
return false;
|
|
610
|
-
// Check for GIF signature
|
|
611
|
-
const isGIF = bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46;
|
|
612
|
-
// Check for ZIP/JAR signature
|
|
613
|
-
let hasZIP = false;
|
|
614
|
-
for (let i = 0; i < Math.min(bytes.length - 4, 1024); i++) {
|
|
615
|
-
if (bytes[i] === 0x50 &&
|
|
616
|
-
bytes[i + 1] === 0x4b &&
|
|
617
|
-
bytes[i + 2] === 0x03 &&
|
|
618
|
-
bytes[i + 3] === 0x04) {
|
|
619
|
-
hasZIP = true;
|
|
620
|
-
break;
|
|
621
|
-
}
|
|
622
|
-
}
|
|
623
|
-
return isGIF && hasZIP;
|
|
624
|
-
}
|
|
625
|
-
function isArchive(bytes) {
|
|
626
|
-
if (bytes.length < 4)
|
|
627
|
-
return false;
|
|
628
|
-
return (
|
|
629
|
-
// ZIP
|
|
630
|
-
(bytes[0] === 0x50 && bytes[1] === 0x4b && bytes[2] === 0x03 && bytes[3] === 0x04) ||
|
|
631
|
-
// RAR
|
|
632
|
-
(bytes[0] === 0x52 && bytes[1] === 0x61 && bytes[2] === 0x72 && bytes[3] === 0x21) ||
|
|
633
|
-
// 7z
|
|
634
|
-
(bytes[0] === 0x37 && bytes[1] === 0x7a && bytes[2] === 0xbc && bytes[3] === 0xaf) ||
|
|
635
|
-
// tar.gz
|
|
636
|
-
(bytes[0] === 0x1f && bytes[1] === 0x8b));
|
|
637
|
-
}
|
|
638
|
-
|
|
639
|
-
/**
|
|
640
|
-
* Cache management system for scan results
|
|
641
|
-
* @module utils/cache-manager
|
|
642
|
-
*/
|
|
643
|
-
/**
|
|
644
|
-
* LRU cache for scan results with TTL support
|
|
645
|
-
*/
|
|
646
|
-
class ScanCacheManager {
|
|
647
|
-
constructor(options = {}) {
|
|
648
|
-
this.cache = new Map();
|
|
649
|
-
// Statistics
|
|
650
|
-
this.stats = {
|
|
651
|
-
hits: 0,
|
|
652
|
-
misses: 0,
|
|
653
|
-
evictions: 0,
|
|
654
|
-
};
|
|
655
|
-
this.maxSize = options.maxSize ?? 1000;
|
|
656
|
-
this.ttl = options.ttl ?? 3600000; // 1 hour default
|
|
657
|
-
this.enableLRU = options.enableLRU ?? true;
|
|
658
|
-
this.enableStats = options.enableStats ?? false;
|
|
659
|
-
}
|
|
660
|
-
/**
|
|
661
|
-
* Generate cache key from file content
|
|
662
|
-
*/
|
|
663
|
-
generateKey(content, preset) {
|
|
664
|
-
const hash = createHash("sha256")
|
|
665
|
-
.update(content)
|
|
666
|
-
.update(preset || "default")
|
|
667
|
-
.digest("hex");
|
|
668
|
-
return hash;
|
|
669
|
-
}
|
|
670
|
-
/**
|
|
671
|
-
* Check if cache entry is still valid
|
|
672
|
-
*/
|
|
673
|
-
isValid(entry) {
|
|
674
|
-
return Date.now() - entry.timestamp < this.ttl;
|
|
675
|
-
}
|
|
676
|
-
/**
|
|
677
|
-
* Evict oldest or least-used entry when cache is full
|
|
678
|
-
*/
|
|
679
|
-
evict() {
|
|
680
|
-
if (this.cache.size === 0)
|
|
681
|
-
return;
|
|
682
|
-
let targetKey = null;
|
|
683
|
-
let oldestTime = Infinity;
|
|
684
|
-
let lowestAccess = Infinity;
|
|
685
|
-
for (const [key, entry] of this.cache.entries()) {
|
|
686
|
-
if (this.enableLRU) {
|
|
687
|
-
// LRU: evict least recently used
|
|
688
|
-
if (entry.timestamp < oldestTime) {
|
|
689
|
-
oldestTime = entry.timestamp;
|
|
690
|
-
targetKey = key;
|
|
691
|
-
}
|
|
692
|
-
}
|
|
693
|
-
else {
|
|
694
|
-
// LFU: evict least frequently used
|
|
695
|
-
if (entry.accessCount < lowestAccess) {
|
|
696
|
-
lowestAccess = entry.accessCount;
|
|
697
|
-
targetKey = key;
|
|
698
|
-
}
|
|
699
|
-
}
|
|
700
|
-
}
|
|
701
|
-
if (targetKey) {
|
|
702
|
-
this.cache.delete(targetKey);
|
|
703
|
-
if (this.enableStats)
|
|
704
|
-
this.stats.evictions++;
|
|
705
|
-
}
|
|
706
|
-
}
|
|
707
|
-
/**
|
|
708
|
-
* Store scan result in cache
|
|
709
|
-
*/
|
|
710
|
-
set(content, report, preset) {
|
|
711
|
-
const key = this.generateKey(content, preset);
|
|
712
|
-
// Evict if necessary
|
|
713
|
-
if (this.cache.size >= this.maxSize) {
|
|
714
|
-
this.evict();
|
|
715
|
-
}
|
|
716
|
-
this.cache.set(key, {
|
|
717
|
-
report,
|
|
718
|
-
timestamp: Date.now(),
|
|
719
|
-
accessCount: 0,
|
|
720
|
-
});
|
|
721
|
-
}
|
|
722
|
-
/**
|
|
723
|
-
* Retrieve scan result from cache
|
|
724
|
-
*/
|
|
725
|
-
get(content, preset) {
|
|
726
|
-
const key = this.generateKey(content, preset);
|
|
727
|
-
const entry = this.cache.get(key);
|
|
728
|
-
if (!entry) {
|
|
729
|
-
if (this.enableStats)
|
|
730
|
-
this.stats.misses++;
|
|
731
|
-
return null;
|
|
732
|
-
}
|
|
733
|
-
if (!this.isValid(entry)) {
|
|
734
|
-
this.cache.delete(key);
|
|
735
|
-
if (this.enableStats)
|
|
736
|
-
this.stats.misses++;
|
|
737
|
-
return null;
|
|
738
|
-
}
|
|
739
|
-
// Update access tracking
|
|
740
|
-
entry.accessCount++;
|
|
741
|
-
entry.timestamp = Date.now(); // Update for LRU
|
|
742
|
-
if (this.enableStats)
|
|
743
|
-
this.stats.hits++;
|
|
744
|
-
return entry.report;
|
|
745
|
-
}
|
|
746
|
-
/**
|
|
747
|
-
* Check if result exists in cache
|
|
748
|
-
*/
|
|
749
|
-
has(content, preset) {
|
|
750
|
-
const key = this.generateKey(content, preset);
|
|
751
|
-
const entry = this.cache.get(key);
|
|
752
|
-
return entry !== undefined && this.isValid(entry);
|
|
753
|
-
}
|
|
754
|
-
/**
|
|
755
|
-
* Clear entire cache
|
|
756
|
-
*/
|
|
757
|
-
clear() {
|
|
758
|
-
this.cache.clear();
|
|
759
|
-
if (this.enableStats) {
|
|
760
|
-
this.stats.hits = 0;
|
|
761
|
-
this.stats.misses = 0;
|
|
762
|
-
this.stats.evictions = 0;
|
|
763
|
-
}
|
|
764
|
-
}
|
|
765
|
-
/**
|
|
766
|
-
* Remove expired entries
|
|
767
|
-
*/
|
|
768
|
-
prune() {
|
|
769
|
-
let removed = 0;
|
|
770
|
-
for (const [key, entry] of this.cache.entries()) {
|
|
771
|
-
if (!this.isValid(entry)) {
|
|
772
|
-
this.cache.delete(key);
|
|
773
|
-
removed++;
|
|
774
|
-
}
|
|
775
|
-
}
|
|
776
|
-
return removed;
|
|
777
|
-
}
|
|
778
|
-
/**
|
|
779
|
-
* Get cache statistics
|
|
780
|
-
*/
|
|
781
|
-
getStats() {
|
|
782
|
-
const total = this.stats.hits + this.stats.misses;
|
|
783
|
-
const hitRate = total > 0 ? (this.stats.hits / total) * 100 : 0;
|
|
784
|
-
return {
|
|
785
|
-
hits: this.stats.hits,
|
|
786
|
-
misses: this.stats.misses,
|
|
787
|
-
size: this.cache.size,
|
|
788
|
-
hitRate,
|
|
789
|
-
evictions: this.stats.evictions,
|
|
790
|
-
};
|
|
791
|
-
}
|
|
792
|
-
/**
|
|
793
|
-
* Get current cache size
|
|
794
|
-
*/
|
|
795
|
-
get size() {
|
|
796
|
-
return this.cache.size;
|
|
797
|
-
}
|
|
798
|
-
}
|
|
799
|
-
// Export singleton instance for convenience
|
|
800
|
-
let defaultCache = null;
|
|
801
|
-
/**
|
|
802
|
-
* Get or create the default cache instance
|
|
803
|
-
*/
|
|
804
|
-
function getDefaultCache(options) {
|
|
805
|
-
if (!defaultCache) {
|
|
806
|
-
defaultCache = new ScanCacheManager(options);
|
|
807
|
-
}
|
|
808
|
-
return defaultCache;
|
|
809
|
-
}
|
|
810
|
-
|
|
811
|
-
/**
|
|
812
|
-
* Performance monitoring utilities for pompelmi scans
|
|
813
|
-
* @module utils/performance-metrics
|
|
814
|
-
*/
|
|
815
|
-
/**
|
|
816
|
-
* Track performance metrics for a scan operation
|
|
817
|
-
*/
|
|
818
|
-
class PerformanceTracker {
|
|
819
|
-
constructor() {
|
|
820
|
-
this.checkpoints = new Map();
|
|
821
|
-
this.startTime = Date.now();
|
|
822
|
-
}
|
|
823
|
-
/**
|
|
824
|
-
* Mark a checkpoint in the scan process
|
|
825
|
-
*/
|
|
826
|
-
checkpoint(name) {
|
|
827
|
-
this.checkpoints.set(name, Date.now());
|
|
828
|
-
}
|
|
829
|
-
/**
|
|
830
|
-
* Get duration since start or since a specific checkpoint
|
|
831
|
-
*/
|
|
832
|
-
getDuration(since) {
|
|
833
|
-
const now = Date.now();
|
|
834
|
-
if (since && this.checkpoints.has(since)) {
|
|
835
|
-
return now - (this.checkpoints.get(since) ?? now);
|
|
836
|
-
}
|
|
837
|
-
return now - this.startTime;
|
|
838
|
-
}
|
|
839
|
-
/**
|
|
840
|
-
* Generate final metrics report
|
|
841
|
-
*/
|
|
842
|
-
getMetrics(bytesScanned) {
|
|
843
|
-
const totalDuration = this.getDuration();
|
|
844
|
-
const throughput = totalDuration > 0 ? (bytesScanned / totalDuration) * 1000 : 0;
|
|
845
|
-
return {
|
|
846
|
-
totalDurationMs: totalDuration,
|
|
847
|
-
heuristicsDurationMs: this.checkpoints.has("heuristics_end")
|
|
848
|
-
? (this.checkpoints.get("heuristics_end") ?? 0) -
|
|
849
|
-
(this.checkpoints.get("heuristics_start") ?? 0)
|
|
850
|
-
: undefined,
|
|
851
|
-
yaraDurationMs: this.checkpoints.has("yara_end")
|
|
852
|
-
? (this.checkpoints.get("yara_end") ?? 0) - (this.checkpoints.get("yara_start") ?? 0)
|
|
853
|
-
: undefined,
|
|
854
|
-
prepDurationMs: this.checkpoints.has("prep_end")
|
|
855
|
-
? (this.checkpoints.get("prep_end") ?? 0) - this.startTime
|
|
856
|
-
: undefined,
|
|
857
|
-
throughputBps: throughput,
|
|
858
|
-
bytesScanned,
|
|
859
|
-
startedAt: this.startTime,
|
|
860
|
-
completedAt: Date.now(),
|
|
861
|
-
};
|
|
862
|
-
}
|
|
863
|
-
}
|
|
864
|
-
/**
|
|
865
|
-
* Aggregate statistics from multiple scan reports
|
|
866
|
-
*/
|
|
867
|
-
function aggregateScanStats(reports) {
|
|
868
|
-
let cleanCount = 0;
|
|
869
|
-
let suspiciousCount = 0;
|
|
870
|
-
let maliciousCount = 0;
|
|
871
|
-
let totalDuration = 0;
|
|
872
|
-
let totalBytes = 0;
|
|
873
|
-
let validDurationCount = 0;
|
|
874
|
-
for (const report of reports) {
|
|
875
|
-
if (report.verdict === "clean")
|
|
876
|
-
cleanCount++;
|
|
877
|
-
else if (report.verdict === "suspicious")
|
|
878
|
-
suspiciousCount++;
|
|
879
|
-
else if (report.verdict === "malicious")
|
|
880
|
-
maliciousCount++;
|
|
881
|
-
if (report.durationMs !== undefined) {
|
|
882
|
-
totalDuration += report.durationMs;
|
|
883
|
-
validDurationCount++;
|
|
884
|
-
}
|
|
885
|
-
if (report.file?.size !== undefined) {
|
|
886
|
-
totalBytes += report.file.size;
|
|
887
|
-
}
|
|
888
|
-
}
|
|
889
|
-
const avgDuration = validDurationCount > 0 ? totalDuration / validDurationCount : 0;
|
|
890
|
-
const avgThroughput = totalDuration > 0 ? (totalBytes / totalDuration) * 1000 : 0;
|
|
891
|
-
return {
|
|
892
|
-
totalScans: reports.length,
|
|
893
|
-
cleanCount,
|
|
894
|
-
suspiciousCount,
|
|
895
|
-
maliciousCount,
|
|
896
|
-
avgDurationMs: avgDuration,
|
|
897
|
-
avgThroughputBps: avgThroughput,
|
|
898
|
-
totalBytesScanned: totalBytes,
|
|
899
|
-
};
|
|
900
|
-
}
|
|
901
|
-
|
|
902
|
-
/** Mappa veloce estensione -> mime (basic) */
|
|
903
|
-
function guessMimeByExt(name) {
|
|
904
|
-
if (!name)
|
|
905
|
-
return;
|
|
906
|
-
const ext = name.toLowerCase().split(".").pop();
|
|
907
|
-
switch (ext) {
|
|
908
|
-
case "zip":
|
|
909
|
-
return "application/zip";
|
|
910
|
-
case "png":
|
|
911
|
-
return "image/png";
|
|
912
|
-
case "jpg":
|
|
913
|
-
case "jpeg":
|
|
914
|
-
return "image/jpeg";
|
|
915
|
-
case "pdf":
|
|
916
|
-
return "application/pdf";
|
|
917
|
-
case "txt":
|
|
918
|
-
return "text/plain";
|
|
919
|
-
default:
|
|
920
|
-
return;
|
|
921
|
-
}
|
|
922
|
-
}
|
|
923
|
-
/** Heuristica semplice per verdetto */
|
|
924
|
-
function computeVerdict(matches) {
|
|
925
|
-
if (!matches.length)
|
|
926
|
-
return "clean";
|
|
927
|
-
// se la regola contiene 'zip_' lo marchiamo "suspicious"
|
|
928
|
-
const anyHigh = matches.some((m) => (m.tags ?? []).includes("critical") || (m.tags ?? []).includes("high"));
|
|
929
|
-
return anyHigh ? "malicious" : "suspicious";
|
|
930
|
-
}
|
|
931
|
-
/** Converte i Match (heuristics) in YaraMatch-like per uniformare l'output */
|
|
932
|
-
function toYaraMatches(ms) {
|
|
933
|
-
return ms.map((m) => ({
|
|
934
|
-
rule: m.rule,
|
|
935
|
-
namespace: "heuristics",
|
|
936
|
-
tags: ["heuristics"].concat(m.severity ? [m.severity] : []),
|
|
937
|
-
meta: m.meta,
|
|
938
|
-
}));
|
|
939
|
-
}
|
|
940
|
-
/** Scan di bytes (browser/node) usando preset (default: zip-basic) */
|
|
941
|
-
async function scanBytes(input, opts = {}) {
|
|
942
|
-
// Check cache first if enabled
|
|
943
|
-
if (opts.enableCache || opts.config?.performance?.enableCache) {
|
|
944
|
-
const cache = getDefaultCache(opts.config?.performance?.cacheOptions);
|
|
945
|
-
const cached = cache.get(input, opts.preset);
|
|
946
|
-
if (cached) {
|
|
947
|
-
return cached;
|
|
948
|
-
}
|
|
949
|
-
}
|
|
950
|
-
const perfTracker = opts.enablePerformanceTracking || opts.config?.performance?.enablePerformanceTracking
|
|
951
|
-
? new PerformanceTracker()
|
|
952
|
-
: null;
|
|
953
|
-
perfTracker?.checkpoint("prep_start");
|
|
954
|
-
const preset = opts.preset ?? opts.config?.defaultPreset ?? "zip-basic";
|
|
955
|
-
const ctx = {
|
|
956
|
-
...opts.ctx,
|
|
957
|
-
mimeType: opts.ctx?.mimeType ?? guessMimeByExt(opts.ctx?.filename),
|
|
958
|
-
size: opts.ctx?.size ?? input.byteLength,
|
|
959
|
-
};
|
|
960
|
-
perfTracker?.checkpoint("prep_end");
|
|
961
|
-
perfTracker?.checkpoint("heuristics_start");
|
|
962
|
-
const scanFn = createPresetScanner(preset);
|
|
963
|
-
const matchesH = await (typeof scanFn === "function"
|
|
964
|
-
? scanFn
|
|
965
|
-
: scanFn.scan)(input, ctx);
|
|
966
|
-
const allMatches = [...matchesH];
|
|
967
|
-
perfTracker?.checkpoint("heuristics_end");
|
|
968
|
-
// Advanced detection (enabled by default, can be overridden by config)
|
|
969
|
-
const advancedEnabled = opts.enableAdvancedDetection ?? opts.config?.advanced?.enablePolyglotDetection ?? true;
|
|
970
|
-
if (advancedEnabled) {
|
|
971
|
-
perfTracker?.checkpoint("advanced_start");
|
|
972
|
-
// Detect polyglot files
|
|
973
|
-
if (opts.config?.advanced?.enablePolyglotDetection !== false) {
|
|
974
|
-
const polyglotMatches = detectPolyglot(input);
|
|
975
|
-
allMatches.push(...polyglotMatches);
|
|
976
|
-
}
|
|
977
|
-
// Detect obfuscated scripts
|
|
978
|
-
if (opts.config?.advanced?.enableObfuscationDetection !== false) {
|
|
979
|
-
const obfuscatedMatches = detectObfuscatedScripts(input);
|
|
980
|
-
allMatches.push(...obfuscatedMatches);
|
|
981
|
-
}
|
|
982
|
-
// Check for excessive nesting in archives
|
|
983
|
-
if (opts.config?.advanced?.enableNestedArchiveAnalysis !== false) {
|
|
984
|
-
const nestingAnalysis = analyzeNestedArchives(input);
|
|
985
|
-
const maxDepth = opts.config?.advanced?.maxArchiveDepth ?? 5;
|
|
986
|
-
if (nestingAnalysis.hasExcessiveNesting || nestingAnalysis.depth > maxDepth) {
|
|
987
|
-
allMatches.push({
|
|
988
|
-
rule: "excessive_archive_nesting",
|
|
989
|
-
severity: "high",
|
|
990
|
-
meta: {
|
|
991
|
-
description: "Excessive archive nesting detected",
|
|
992
|
-
depth: nestingAnalysis.depth,
|
|
993
|
-
maxAllowed: maxDepth,
|
|
994
|
-
},
|
|
995
|
-
});
|
|
996
|
-
}
|
|
997
|
-
}
|
|
998
|
-
perfTracker?.checkpoint("advanced_end");
|
|
999
|
-
}
|
|
1000
|
-
const matches = toYaraMatches(allMatches);
|
|
1001
|
-
const verdict = computeVerdict(matches);
|
|
1002
|
-
perfTracker ? perfTracker.getDuration() : Date.now();
|
|
1003
|
-
const durationMs = perfTracker ? perfTracker.getDuration() : 0;
|
|
1004
|
-
const report = {
|
|
1005
|
-
ok: verdict === "clean",
|
|
1006
|
-
verdict,
|
|
1007
|
-
matches,
|
|
1008
|
-
reasons: matches.map((m) => m.rule),
|
|
1009
|
-
file: { name: ctx.filename, mimeType: ctx.mimeType, size: ctx.size },
|
|
1010
|
-
durationMs,
|
|
1011
|
-
engine: "heuristics",
|
|
1012
|
-
truncated: false,
|
|
1013
|
-
timedOut: false,
|
|
1014
|
-
};
|
|
1015
|
-
// Add performance metrics if tracking enabled
|
|
1016
|
-
if (perfTracker &&
|
|
1017
|
-
(opts.enablePerformanceTracking || opts.config?.performance?.enablePerformanceTracking)) {
|
|
1018
|
-
report.performanceMetrics = perfTracker.getMetrics(input.byteLength);
|
|
1019
|
-
}
|
|
1020
|
-
// Cache result if enabled
|
|
1021
|
-
if (opts.enableCache || opts.config?.performance?.enableCache) {
|
|
1022
|
-
const cache = getDefaultCache(opts.config?.performance?.cacheOptions);
|
|
1023
|
-
cache.set(input, report, opts.preset);
|
|
1024
|
-
}
|
|
1025
|
-
// Invoke callbacks if configured
|
|
1026
|
-
opts.config?.callbacks?.onScanComplete?.(report);
|
|
1027
|
-
return report;
|
|
1028
|
-
}
|
|
1029
|
-
/** Scan di un file su disco (Node). Import dinamico per non vincolare il bundle browser. */
|
|
1030
|
-
async function scanFile(filePath, opts = {}) {
|
|
1031
|
-
const [{ readFile, stat }, path] = await Promise.all([import('fs/promises'), import('path')]);
|
|
1032
|
-
const [buf, st] = await Promise.all([readFile(filePath), stat(filePath)]);
|
|
1033
|
-
const ctx = {
|
|
1034
|
-
filename: path.basename(filePath),
|
|
1035
|
-
mimeType: guessMimeByExt(filePath),
|
|
1036
|
-
size: st.size,
|
|
1037
|
-
};
|
|
1038
|
-
return scanBytes(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength), { ...opts, ctx });
|
|
1039
|
-
}
|
|
1040
|
-
/** Scan multipli File (browser) usando scanBytes + preset di default */
|
|
1041
|
-
async function scanFiles(files, opts = {}) {
|
|
1042
|
-
const list = Array.from(files);
|
|
1043
|
-
const out = [];
|
|
1044
|
-
for (const f of list) {
|
|
1045
|
-
const buf = new Uint8Array(await f.arrayBuffer());
|
|
1046
|
-
const rep = await scanBytes(buf, {
|
|
1047
|
-
...opts,
|
|
1048
|
-
ctx: { filename: f.name, mimeType: f.type || guessMimeByExt(f.name), size: f.size },
|
|
1049
|
-
});
|
|
1050
|
-
out.push(rep);
|
|
1051
|
-
}
|
|
1052
|
-
return out;
|
|
1053
|
-
}
|
|
1054
|
-
|
|
1055
|
-
const ARCHIVE_BOMB_DETECTED = "ARCHIVE_BOMB_DETECTED";
|
|
1056
|
-
const SIG_LFH = 0x04034b50;
|
|
1057
|
-
const SIG_CEN = 0x02014b50;
|
|
1058
|
-
const DEFAULTS = {
|
|
1059
|
-
maxEntries: 1000,
|
|
1060
|
-
maxTotalUncompressedBytes: 500 * 1024 * 1024,
|
|
1061
|
-
maxPerEntryUncompressedBytes: 100 * 1024 * 1024,
|
|
1062
|
-
maxEntryNameLength: 255,
|
|
1063
|
-
maxCompressionRatio: 100,
|
|
1064
|
-
eocdSearchWindow: 70000,
|
|
1065
|
-
};
|
|
1066
|
-
function r16(buf, off) {
|
|
1067
|
-
return buf.readUInt16LE(off);
|
|
1068
|
-
}
|
|
1069
|
-
function r32(buf, off) {
|
|
1070
|
-
return buf.readUInt32LE(off);
|
|
1071
|
-
}
|
|
1072
|
-
function isZipLike(buf) {
|
|
1073
|
-
return (buf.length >= 4 && buf[0] === 0x50 && buf[1] === 0x4b && buf[2] === 0x03 && buf[3] === 0x04);
|
|
1074
|
-
}
|
|
1075
|
-
function lastIndexOfEOCD(buf, window) {
|
|
1076
|
-
const sig = Buffer.from([0x50, 0x4b, 0x05, 0x06]);
|
|
1077
|
-
const start = Math.max(0, buf.length - window);
|
|
1078
|
-
const idx = buf.lastIndexOf(sig, Math.min(buf.length - sig.length, buf.length - 1));
|
|
1079
|
-
return idx >= start ? idx : -1;
|
|
1080
|
-
}
|
|
1081
|
-
function hasTraversal(name) {
|
|
1082
|
-
return (name.includes("../") || name.includes("..\\") || name.startsWith("/") || /^[A-Za-z]:/.test(name));
|
|
1083
|
-
}
|
|
1084
|
-
function makeBombError() {
|
|
1085
|
-
return Object.assign(new Error("Archive bomb detected: decompression limits exceeded"), {
|
|
1086
|
-
code: ARCHIVE_BOMB_DETECTED,
|
|
1087
|
-
});
|
|
1088
|
-
}
|
|
1089
|
-
/**
|
|
1090
|
-
* Feeds `compressed` into a raw DEFLATE inflate stream and counts the actual
|
|
1091
|
-
* output bytes. Resolves with bombed=true and aborts early if any limit fires:
|
|
1092
|
-
* - decompressed bytes > maxPerEntry
|
|
1093
|
-
* - totalSoFar + decompressed > maxTotal
|
|
1094
|
-
* - decompressed / compressed > maxRatio (ratio measured on real bytes, not headers)
|
|
1095
|
-
*
|
|
1096
|
-
* Malformed DEFLATE is treated as safe (bombed=false, decompressed=0).
|
|
1097
|
-
*/
|
|
1098
|
-
function streamInflate(compressed, maxPerEntry, maxTotal, alreadySeen, maxRatio) {
|
|
1099
|
-
return new Promise((resolve) => {
|
|
1100
|
-
const inf = createInflateRaw();
|
|
1101
|
-
let out = 0;
|
|
1102
|
-
const compBytes = compressed.length;
|
|
1103
|
-
let done = false;
|
|
1104
|
-
const finish = (bombed) => {
|
|
1105
|
-
if (done)
|
|
1106
|
-
return;
|
|
1107
|
-
done = true;
|
|
1108
|
-
inf.destroy();
|
|
1109
|
-
resolve({ decompressed: out, bombed });
|
|
1110
|
-
};
|
|
1111
|
-
inf.on("data", (chunk) => {
|
|
1112
|
-
out += chunk.length;
|
|
1113
|
-
if (out > maxPerEntry ||
|
|
1114
|
-
alreadySeen + out > maxTotal ||
|
|
1115
|
-
(compBytes > 0 && out / compBytes > maxRatio)) {
|
|
1116
|
-
finish(true);
|
|
1117
|
-
}
|
|
1118
|
-
});
|
|
1119
|
-
inf.on("end", () => finish(false));
|
|
1120
|
-
// Malformed DEFLATE stream → not a bomb, just corrupt
|
|
1121
|
-
inf.on("error", () => finish(false));
|
|
1122
|
-
inf.end(compressed);
|
|
1123
|
-
});
|
|
1124
|
-
}
|
|
1125
|
-
function createZipBombGuard(opts = {}) {
|
|
1126
|
-
const cfg = { ...DEFAULTS, ...opts };
|
|
1127
|
-
return {
|
|
1128
|
-
async scan(input) {
|
|
1129
|
-
const buf = Buffer.from(input);
|
|
1130
|
-
const matches = [];
|
|
1131
|
-
if (!isZipLike(buf))
|
|
1132
|
-
return matches;
|
|
1133
|
-
// ── 1. Locate EOCD ──────────────────────────────────────────────────────
|
|
1134
|
-
const eocdPos = lastIndexOfEOCD(buf, cfg.eocdSearchWindow);
|
|
1135
|
-
if (eocdPos < 0 || eocdPos + 22 > buf.length) {
|
|
1136
|
-
matches.push({ rule: "zip_eocd_not_found", severity: "medium" });
|
|
1137
|
-
return matches;
|
|
1138
|
-
}
|
|
1139
|
-
const totalEntries = r16(buf, eocdPos + 10);
|
|
1140
|
-
const cdSize = r32(buf, eocdPos + 12);
|
|
1141
|
-
const cdOffset = r32(buf, eocdPos + 16);
|
|
1142
|
-
if (cdOffset + cdSize > buf.length) {
|
|
1143
|
-
matches.push({ rule: "zip_cd_out_of_bounds", severity: "medium" });
|
|
1144
|
-
return matches;
|
|
1145
|
-
}
|
|
1146
|
-
const lfhIndex = [];
|
|
1147
|
-
let ptr = cdOffset;
|
|
1148
|
-
let seen = 0;
|
|
1149
|
-
while (ptr + 46 <= cdOffset + cdSize && seen < totalEntries) {
|
|
1150
|
-
if (r32(buf, ptr) !== SIG_CEN)
|
|
1151
|
-
break;
|
|
1152
|
-
const cdCompSize = r32(buf, ptr + 20);
|
|
1153
|
-
const fnLen = r16(buf, ptr + 28);
|
|
1154
|
-
const exLen = r16(buf, ptr + 30);
|
|
1155
|
-
const cmLen = r16(buf, ptr + 32);
|
|
1156
|
-
const lfhOffset = r32(buf, ptr + 42);
|
|
1157
|
-
const nameEnd = ptr + 46 + fnLen;
|
|
1158
|
-
if (nameEnd > buf.length)
|
|
1159
|
-
break;
|
|
1160
|
-
const name = buf.toString("utf8", ptr + 46, nameEnd);
|
|
1161
|
-
seen++;
|
|
1162
|
-
lfhIndex.push({ lfhOffset, cdCompSize });
|
|
1163
|
-
if (name.length > cfg.maxEntryNameLength) {
|
|
1164
|
-
matches.push({
|
|
1165
|
-
rule: "zip_entry_name_too_long",
|
|
1166
|
-
severity: "medium",
|
|
1167
|
-
meta: { name, length: name.length },
|
|
1168
|
-
});
|
|
1169
|
-
}
|
|
1170
|
-
if (hasTraversal(name)) {
|
|
1171
|
-
matches.push({ rule: "zip_path_traversal_entry", severity: "medium", meta: { name } });
|
|
1172
|
-
}
|
|
1173
|
-
ptr = nameEnd + exLen + cmLen;
|
|
1174
|
-
}
|
|
1175
|
-
if (seen !== totalEntries) {
|
|
1176
|
-
matches.push({
|
|
1177
|
-
rule: "zip_cd_truncated",
|
|
1178
|
-
severity: "medium",
|
|
1179
|
-
meta: { seen, totalEntries },
|
|
1180
|
-
});
|
|
1181
|
-
}
|
|
1182
|
-
if (seen > cfg.maxEntries) {
|
|
1183
|
-
matches.push({
|
|
1184
|
-
rule: "zip_too_many_entries",
|
|
1185
|
-
severity: "medium",
|
|
1186
|
-
meta: { seen, limit: cfg.maxEntries },
|
|
1187
|
-
});
|
|
1188
|
-
// Return early — decompressing thousands of entries would be a DoS vector
|
|
1189
|
-
return matches;
|
|
1190
|
-
}
|
|
1191
|
-
// ── 3. True streaming decompression — archive bomb detection ────────────
|
|
1192
|
-
// For every DEFLATE entry (method=8) we feed the raw compressed bytes into
|
|
1193
|
-
// zlib.createInflateRaw() and count the bytes that come OUT. We abort the
|
|
1194
|
-
// moment any limit fires; we NEVER trust the header-reported uncompressed
|
|
1195
|
-
// size for the ratio decision.
|
|
1196
|
-
//
|
|
1197
|
-
// For STORED entries (method=0) compressed == uncompressed by spec, so the
|
|
1198
|
-
// byte count is immediate.
|
|
1199
|
-
let totalDecompressed = 0;
|
|
1200
|
-
for (const { lfhOffset, cdCompSize } of lfhIndex) {
|
|
1201
|
-
if (lfhOffset + 30 > buf.length)
|
|
1202
|
-
continue;
|
|
1203
|
-
if (r32(buf, lfhOffset) !== SIG_LFH)
|
|
1204
|
-
continue;
|
|
1205
|
-
const gpbf = r16(buf, lfhOffset + 6);
|
|
1206
|
-
const method = r16(buf, lfhOffset + 8);
|
|
1207
|
-
let lfhCompSz = r32(buf, lfhOffset + 18);
|
|
1208
|
-
const fnLen = r16(buf, lfhOffset + 26);
|
|
1209
|
-
const exLen = r16(buf, lfhOffset + 28);
|
|
1210
|
-
const dataOff = lfhOffset + 30 + fnLen + exLen;
|
|
1211
|
-
// If the data-descriptor flag is set (GPBF bit 3), the LFH sizes are 0.
|
|
1212
|
-
// Fall back to the CD size purely for navigation — not for bomb detection.
|
|
1213
|
-
if ((gpbf & 0x08) !== 0 && lfhCompSz === 0) {
|
|
1214
|
-
lfhCompSz = cdCompSize;
|
|
1215
|
-
}
|
|
1216
|
-
if (dataOff + lfhCompSz > buf.length)
|
|
1217
|
-
continue; // truncated entry — skip
|
|
1218
|
-
if (method === 8 /* DEFLATE */) {
|
|
1219
|
-
const compressed = buf.slice(dataOff, dataOff + lfhCompSz);
|
|
1220
|
-
const { decompressed, bombed } = await streamInflate(compressed, cfg.maxPerEntryUncompressedBytes, cfg.maxTotalUncompressedBytes, totalDecompressed, cfg.maxCompressionRatio);
|
|
1221
|
-
if (bombed)
|
|
1222
|
-
throw makeBombError();
|
|
1223
|
-
totalDecompressed += decompressed;
|
|
1224
|
-
}
|
|
1225
|
-
else if (method === 0 /* STORED */) {
|
|
1226
|
-
// Compressed == uncompressed for stored entries
|
|
1227
|
-
if (lfhCompSz > cfg.maxPerEntryUncompressedBytes)
|
|
1228
|
-
throw makeBombError();
|
|
1229
|
-
totalDecompressed += lfhCompSz;
|
|
1230
|
-
if (totalDecompressed > cfg.maxTotalUncompressedBytes)
|
|
1231
|
-
throw makeBombError();
|
|
1232
|
-
}
|
|
1233
|
-
// Other methods (bzip2=12, lzma=14, zstd=93, …) — skip; no built-in support
|
|
1234
|
-
}
|
|
1235
|
-
return matches;
|
|
1236
|
-
},
|
|
1237
|
-
};
|
|
1238
|
-
}
|
|
1239
|
-
|
|
1240
|
-
/**
|
|
1241
|
-
* Export utilities for scan results
|
|
1242
|
-
* @module utils/export
|
|
1243
|
-
*/
|
|
1244
|
-
/**
|
|
1245
|
-
* Export scan results to various formats
|
|
1246
|
-
*/
|
|
1247
|
-
class ScanResultExporter {
|
|
1248
|
-
/**
|
|
1249
|
-
* Export to JSON format
|
|
1250
|
-
*/
|
|
1251
|
-
toJSON(reports, options = {}) {
|
|
1252
|
-
const data = Array.isArray(reports) ? reports : [reports];
|
|
1253
|
-
if (!options.includeDetails) {
|
|
1254
|
-
// Simplified output
|
|
1255
|
-
const simplified = data.map((r) => ({
|
|
1256
|
-
verdict: r.verdict,
|
|
1257
|
-
file: r.file?.name,
|
|
1258
|
-
matches: r.matches.length,
|
|
1259
|
-
durationMs: r.durationMs,
|
|
1260
|
-
}));
|
|
1261
|
-
return options.prettyPrint ? JSON.stringify(simplified, null, 2) : JSON.stringify(simplified);
|
|
1262
|
-
}
|
|
1263
|
-
return options.prettyPrint ? JSON.stringify(data, null, 2) : JSON.stringify(data);
|
|
1264
|
-
}
|
|
1265
|
-
/**
|
|
1266
|
-
* Export to CSV format
|
|
1267
|
-
*/
|
|
1268
|
-
toCSV(reports, options = {}) {
|
|
1269
|
-
const data = Array.isArray(reports) ? reports : [reports];
|
|
1270
|
-
const headers = [
|
|
1271
|
-
"filename",
|
|
1272
|
-
"verdict",
|
|
1273
|
-
"matches_count",
|
|
1274
|
-
"file_size",
|
|
1275
|
-
"mime_type",
|
|
1276
|
-
"duration_ms",
|
|
1277
|
-
"engine",
|
|
1278
|
-
];
|
|
1279
|
-
if (options.includeDetails) {
|
|
1280
|
-
headers.push("reasons", "match_rules");
|
|
1281
|
-
}
|
|
1282
|
-
const rows = data.map((report) => {
|
|
1283
|
-
const row = [
|
|
1284
|
-
this.escapeCsv(report.file?.name || "unknown"),
|
|
1285
|
-
report.verdict,
|
|
1286
|
-
report.matches.length.toString(),
|
|
1287
|
-
(report.file?.size || 0).toString(),
|
|
1288
|
-
this.escapeCsv(report.file?.mimeType || "unknown"),
|
|
1289
|
-
(report.durationMs || 0).toString(),
|
|
1290
|
-
report.engine || "unknown",
|
|
1291
|
-
];
|
|
1292
|
-
if (options.includeDetails) {
|
|
1293
|
-
row.push(this.escapeCsv((report.reasons || []).join("; ")), this.escapeCsv(report.matches.map((m) => m.rule).join("; ")));
|
|
1294
|
-
}
|
|
1295
|
-
return row.join(",");
|
|
1296
|
-
});
|
|
1297
|
-
return [headers.join(","), ...rows].join("\n");
|
|
1298
|
-
}
|
|
1299
|
-
/**
|
|
1300
|
-
* Export to Markdown format
|
|
1301
|
-
*/
|
|
1302
|
-
toMarkdown(reports, options = {}) {
|
|
1303
|
-
const data = Array.isArray(reports) ? reports : [reports];
|
|
1304
|
-
let md = "# Scan Results\n\n";
|
|
1305
|
-
md += `**Total Scans:** ${data.length}\n\n`;
|
|
1306
|
-
const clean = data.filter((r) => r.verdict === "clean").length;
|
|
1307
|
-
const suspicious = data.filter((r) => r.verdict === "suspicious").length;
|
|
1308
|
-
const malicious = data.filter((r) => r.verdict === "malicious").length;
|
|
1309
|
-
md += "## Summary\n\n";
|
|
1310
|
-
md += `- ✅ Clean: ${clean}\n`;
|
|
1311
|
-
md += `- ⚠️ Suspicious: ${suspicious}\n`;
|
|
1312
|
-
md += `- ❌ Malicious: ${malicious}\n\n`;
|
|
1313
|
-
md += "## Detailed Results\n\n";
|
|
1314
|
-
for (const report of data) {
|
|
1315
|
-
const icon = report.verdict === "clean" ? "✅" : report.verdict === "suspicious" ? "⚠️" : "❌";
|
|
1316
|
-
md += `### ${icon} ${report.file?.name || "Unknown"}\n\n`;
|
|
1317
|
-
md += `- **Verdict:** ${report.verdict}\n`;
|
|
1318
|
-
md += `- **Size:** ${this.formatBytes(report.file?.size || 0)}\n`;
|
|
1319
|
-
md += `- **MIME Type:** ${report.file?.mimeType || "unknown"}\n`;
|
|
1320
|
-
md += `- **Duration:** ${report.durationMs || 0}ms\n`;
|
|
1321
|
-
md += `- **Matches:** ${report.matches.length}\n`;
|
|
1322
|
-
if (options.includeDetails && report.matches.length > 0) {
|
|
1323
|
-
md += "\n**Match Details:**\n";
|
|
1324
|
-
for (const match of report.matches) {
|
|
1325
|
-
md += `- ${match.rule}`;
|
|
1326
|
-
if (match.tags && match.tags.length > 0) {
|
|
1327
|
-
md += ` (${match.tags.join(", ")})`;
|
|
1328
|
-
}
|
|
1329
|
-
md += "\n";
|
|
1330
|
-
}
|
|
1331
|
-
}
|
|
1332
|
-
md += "\n";
|
|
1333
|
-
}
|
|
1334
|
-
return md;
|
|
1335
|
-
}
|
|
1336
|
-
/**
|
|
1337
|
-
* Export to SARIF format (Static Analysis Results Interchange Format)
|
|
1338
|
-
* Useful for CI/CD integration
|
|
1339
|
-
*/
|
|
1340
|
-
toSARIF(reports, options = {}) {
|
|
1341
|
-
const data = Array.isArray(reports) ? reports : [reports];
|
|
1342
|
-
const results = data.flatMap((report) => {
|
|
1343
|
-
if (report.verdict === "clean")
|
|
1344
|
-
return [];
|
|
1345
|
-
return report.matches.map((match) => ({
|
|
1346
|
-
ruleId: match.rule,
|
|
1347
|
-
level: report.verdict === "malicious" ? "error" : "warning",
|
|
1348
|
-
message: {
|
|
1349
|
-
text: `${match.rule} detected in ${report.file?.name || "unknown file"}`,
|
|
1350
|
-
},
|
|
1351
|
-
locations: [
|
|
1352
|
-
{
|
|
1353
|
-
physicalLocation: {
|
|
1354
|
-
artifactLocation: {
|
|
1355
|
-
uri: report.file?.name || "unknown",
|
|
1356
|
-
},
|
|
1357
|
-
},
|
|
1358
|
-
},
|
|
1359
|
-
],
|
|
1360
|
-
properties: {
|
|
1361
|
-
tags: match.tags,
|
|
1362
|
-
metadata: match.meta,
|
|
1363
|
-
},
|
|
1364
|
-
}));
|
|
1365
|
-
});
|
|
1366
|
-
const sarif = {
|
|
1367
|
-
version: "2.1.0",
|
|
1368
|
-
$schema: "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",
|
|
1369
|
-
runs: [
|
|
1370
|
-
{
|
|
1371
|
-
tool: {
|
|
1372
|
-
driver: {
|
|
1373
|
-
name: "Pompelmi",
|
|
1374
|
-
version: "0.29.0",
|
|
1375
|
-
informationUri: "https://pompelmi.github.io/pompelmi/",
|
|
1376
|
-
},
|
|
1377
|
-
},
|
|
1378
|
-
results,
|
|
1379
|
-
},
|
|
1380
|
-
],
|
|
1381
|
-
};
|
|
1382
|
-
return options.prettyPrint ? JSON.stringify(sarif, null, 2) : JSON.stringify(sarif);
|
|
1383
|
-
}
|
|
1384
|
-
/**
|
|
1385
|
-
* Export to HTML format
|
|
1386
|
-
*/
|
|
1387
|
-
toHTML(reports, options = {}) {
|
|
1388
|
-
const data = Array.isArray(reports) ? reports : [reports];
|
|
1389
|
-
const clean = data.filter((r) => r.verdict === "clean").length;
|
|
1390
|
-
const suspicious = data.filter((r) => r.verdict === "suspicious").length;
|
|
1391
|
-
const malicious = data.filter((r) => r.verdict === "malicious").length;
|
|
1392
|
-
let html = `<!DOCTYPE html>
|
|
1393
|
-
<html lang="en">
|
|
1394
|
-
<head>
|
|
1395
|
-
<meta charset="UTF-8">
|
|
1396
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
1397
|
-
<title>Pompelmi Scan Results</title>
|
|
1398
|
-
<style>
|
|
1399
|
-
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 1200px; margin: 0 auto; padding: 20px; }
|
|
1400
|
-
.summary { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; margin: 20px 0; }
|
|
1401
|
-
.card { padding: 20px; border-radius: 8px; text-align: center; }
|
|
1402
|
-
.clean { background: #d4edda; color: #155724; }
|
|
1403
|
-
.suspicious { background: #fff3cd; color: #856404; }
|
|
1404
|
-
.malicious { background: #f8d7da; color: #721c24; }
|
|
1405
|
-
.result { border: 1px solid #ddd; border-radius: 8px; padding: 15px; margin: 10px 0; }
|
|
1406
|
-
.result h3 { margin-top: 0; }
|
|
1407
|
-
.badge { display: inline-block; padding: 4px 8px; border-radius: 4px; font-size: 0.8em; margin: 2px; }
|
|
1408
|
-
table { width: 100%; border-collapse: collapse; }
|
|
1409
|
-
th, td { padding: 8px; text-align: left; border-bottom: 1px solid #ddd; }
|
|
1410
|
-
</style>
|
|
1411
|
-
</head>
|
|
1412
|
-
<body>
|
|
1413
|
-
<h1>🛡️ Pompelmi Scan Results</h1>
|
|
1414
|
-
<div class="summary">
|
|
1415
|
-
<div class="card clean"><h2>${clean}</h2><p>Clean Files</p></div>
|
|
1416
|
-
<div class="card suspicious"><h2>${suspicious}</h2><p>Suspicious Files</p></div>
|
|
1417
|
-
<div class="card malicious"><h2>${malicious}</h2><p>Malicious Files</p></div>
|
|
1418
|
-
</div>
|
|
1419
|
-
<h2>Detailed Results</h2>`;
|
|
1420
|
-
for (const report of data) {
|
|
1421
|
-
const statusClass = report.verdict;
|
|
1422
|
-
html += `<div class="result ${statusClass}">`;
|
|
1423
|
-
html += `<h3>${this.escapeHtml(report.file?.name || "Unknown")}</h3>`;
|
|
1424
|
-
html += `<table>`;
|
|
1425
|
-
html += `<tr><th>Verdict</th><td>${report.verdict.toUpperCase()}</td></tr>`;
|
|
1426
|
-
html += `<tr><th>Size</th><td>${this.formatBytes(report.file?.size || 0)}</td></tr>`;
|
|
1427
|
-
html += `<tr><th>MIME Type</th><td>${this.escapeHtml(report.file?.mimeType || "unknown")}</td></tr>`;
|
|
1428
|
-
html += `<tr><th>Duration</th><td>${report.durationMs || 0}ms</td></tr>`;
|
|
1429
|
-
html += `<tr><th>Matches</th><td>${report.matches.length}</td></tr>`;
|
|
1430
|
-
html += `</table>`;
|
|
1431
|
-
if (options.includeDetails && report.matches.length > 0) {
|
|
1432
|
-
html += `<h4>Match Details:</h4><ul>`;
|
|
1433
|
-
for (const match of report.matches) {
|
|
1434
|
-
html += `<li><strong>${this.escapeHtml(match.rule)}</strong>`;
|
|
1435
|
-
if (match.tags && match.tags.length > 0) {
|
|
1436
|
-
html += ` ${match.tags.map((tag) => `<span class="badge">${this.escapeHtml(tag)}</span>`).join("")}`;
|
|
1437
|
-
}
|
|
1438
|
-
html += `</li>`;
|
|
1439
|
-
}
|
|
1440
|
-
html += `</ul>`;
|
|
1441
|
-
}
|
|
1442
|
-
html += `</div>`;
|
|
1443
|
-
}
|
|
1444
|
-
html += `</body></html>`;
|
|
1445
|
-
return html;
|
|
1446
|
-
}
|
|
1447
|
-
/**
|
|
1448
|
-
* Export to specified format
|
|
1449
|
-
*/
|
|
1450
|
-
export(reports, format, options = {}) {
|
|
1451
|
-
switch (format) {
|
|
1452
|
-
case "json":
|
|
1453
|
-
return this.toJSON(reports, options);
|
|
1454
|
-
case "csv":
|
|
1455
|
-
return this.toCSV(reports, options);
|
|
1456
|
-
case "markdown":
|
|
1457
|
-
return this.toMarkdown(reports, options);
|
|
1458
|
-
case "html":
|
|
1459
|
-
return this.toHTML(reports, options);
|
|
1460
|
-
case "sarif":
|
|
1461
|
-
return this.toSARIF(reports, options);
|
|
1462
|
-
default:
|
|
1463
|
-
throw new Error(`Unsupported export format: ${format}`);
|
|
1464
|
-
}
|
|
1465
|
-
}
|
|
1466
|
-
escapeCsv(value) {
|
|
1467
|
-
if (value.includes(",") || value.includes('"') || value.includes("\n")) {
|
|
1468
|
-
return `"${value.replace(/"/g, '""')}"`;
|
|
1469
|
-
}
|
|
1470
|
-
return value;
|
|
1471
|
-
}
|
|
1472
|
-
escapeHtml(value) {
|
|
1473
|
-
return value
|
|
1474
|
-
.replace(/&/g, "&")
|
|
1475
|
-
.replace(/</g, "<")
|
|
1476
|
-
.replace(/>/g, ">")
|
|
1477
|
-
.replace(/"/g, """)
|
|
1478
|
-
.replace(/'/g, "'");
|
|
1479
|
-
}
|
|
1480
|
-
formatBytes(bytes) {
|
|
1481
|
-
if (bytes === 0)
|
|
1482
|
-
return "0 Bytes";
|
|
1483
|
-
const k = 1024;
|
|
1484
|
-
const sizes = ["Bytes", "KB", "MB", "GB"];
|
|
1485
|
-
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
|
1486
|
-
return Math.round((bytes / k ** i) * 100) / 100 + " " + sizes[i];
|
|
1487
|
-
}
|
|
1488
|
-
}
|
|
1489
|
-
/**
|
|
1490
|
-
* Quick export helper
|
|
1491
|
-
*/
|
|
1492
|
-
function exportScanResults(reports, format, options) {
|
|
1493
|
-
const exporter = new ScanResultExporter();
|
|
1494
|
-
return exporter.export(reports, format, options);
|
|
1495
|
-
}
|
|
1496
|
-
|
|
1497
|
-
/**
|
|
1498
|
-
* Validates a File by MIME type and size (max 5 MB).
|
|
1499
|
-
*/
|
|
1500
|
-
function validateFile(file) {
|
|
1501
|
-
const maxSize = 5 * 1024 * 1024;
|
|
1502
|
-
const allowedTypes = ["text/plain", "application/json", "text/csv"];
|
|
1503
|
-
if (!allowedTypes.includes(file.type)) {
|
|
1504
|
-
return { valid: false, error: "Unsupported file type" };
|
|
1505
|
-
}
|
|
1506
|
-
if (file.size > maxSize) {
|
|
1507
|
-
return { valid: false, error: "File too large (max 5 MB)" };
|
|
1508
|
-
}
|
|
1509
|
-
return { valid: true };
|
|
1510
|
-
}
|
|
1511
|
-
|
|
1512
|
-
function mapMatchesToVerdict(matches = []) {
|
|
1513
|
-
if (!matches.length)
|
|
1514
|
-
return "clean";
|
|
1515
|
-
const malHints = ["trojan", "ransom", "worm", "spy", "rootkit", "keylog", "botnet"];
|
|
1516
|
-
const tagSet = new Set(matches.flatMap((m) => (m.tags ?? []).map((t) => t.toLowerCase())));
|
|
1517
|
-
const nameHit = (r) => malHints.some((h) => r.toLowerCase().includes(h));
|
|
1518
|
-
const isMal = matches.some((m) => nameHit(m.rule)) || tagSet.has("malware") || tagSet.has("critical");
|
|
1519
|
-
return isMal ? "malicious" : "suspicious";
|
|
1520
|
-
}
|
|
1521
|
-
|
|
1522
|
-
export { ARCHIVES, CONSERVATIVE_DEFAULT, CommonHeuristicsScanner, DEFAULT_POLICY, DOCUMENTS_ONLY, IMAGES_ONLY, POLICY_PACKS, PerformanceTracker, STRICT_PUBLIC_UPLOAD, ScanResultExporter, aggregateScanStats, analyzeNestedArchives, composeScanners, createPresetScanner, createZipBombGuard, definePolicy, detectObfuscatedScripts, detectPolyglot, exportScanResults, getPolicyPack, mapMatchesToVerdict, scanBytes, scanFile, scanFiles, validateFile };
|
|
1523
|
-
//# sourceMappingURL=pompelmi.browser.esm.js.map
|