aiwaf 1.0.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/INSTALLATION.md +144 -0
- package/LICENSE +21 -0
- package/README.md +621 -0
- package/bin/aiwaf.js +349 -0
- package/index.js +62 -0
- package/lib/adonisMiddleware.js +82 -0
- package/lib/anomalyDetector.js +221 -0
- package/lib/blacklistManager.js +134 -0
- package/lib/blockResponses.js +25 -0
- package/lib/csvStore.js +84 -0
- package/lib/dynamicKeyword.js +42 -0
- package/lib/dynamicKeywordStore.js +169 -0
- package/lib/exemptionStore.js +204 -0
- package/lib/exemptions.js +56 -0
- package/lib/fastifyPlugin.js +49 -0
- package/lib/featureUtils.js +183 -0
- package/lib/geoBlocker.js +159 -0
- package/lib/geoPolicy.js +42 -0
- package/lib/geoStore.js +111 -0
- package/lib/hapiPlugin.js +92 -0
- package/lib/headerValidation.js +275 -0
- package/lib/honeypotDetector.js +91 -0
- package/lib/isolationForest.js +117 -0
- package/lib/keywordDetector.js +5 -0
- package/lib/keywordFallbackStore.js +39 -0
- package/lib/koaMiddleware.js +68 -0
- package/lib/middlewareLogger.js +123 -0
- package/lib/middlewarePlan.js +72 -0
- package/lib/modelSecurity.js +17 -0
- package/lib/modelStore.js +129 -0
- package/lib/nestMiddleware.js +12 -0
- package/lib/nextMiddleware.js +78 -0
- package/lib/pathManifest.js +533 -0
- package/lib/pathRules.js +184 -0
- package/lib/rateLimiter.js +153 -0
- package/lib/redisClient.js +35 -0
- package/lib/requestLogStore.js +167 -0
- package/lib/runtimeUtils.js +166 -0
- package/lib/settingsCompat.js +140 -0
- package/lib/sourceAst.js +294 -0
- package/lib/trainingLogic.js +87 -0
- package/lib/uuidDetector.js +46 -0
- package/lib/wafMiddleware.js +459 -0
- package/lib/wasmAdapter.js +480 -0
- package/lib/whois.js +38 -0
- package/package.json +85 -0
- package/resources/model.json +9536 -0
- package/train.js +595 -0
- package/utils/cache.js +3 -0
- package/utils/db.js +11 -0
|
@@ -0,0 +1,480 @@
|
|
|
1
|
+
const fs = require('fs');
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const { pathToFileURL } = require('url');
|
|
4
|
+
const { IsolationForest } = require('./isolationForest');
|
|
5
|
+
console.log(require('../node_modules/aiwaf-wasm/package.json').version);
|
|
6
|
+
let wasmModule = null;
|
|
7
|
+
let wasmLoadAttempted = false;
|
|
8
|
+
let wasmLoadError = null;
|
|
9
|
+
|
|
10
|
+
async function loadWasmFromDisk() {
|
|
11
|
+
const pkgDir = path.join(__dirname, '..', 'node_modules', 'aiwaf-wasm');
|
|
12
|
+
const wasmPath = path.join(pkgDir, 'aiwaf_wasm_bg.wasm');
|
|
13
|
+
const bgPath = path.join(pkgDir, 'aiwaf_wasm_bg.js');
|
|
14
|
+
|
|
15
|
+
if (!fs.existsSync(wasmPath) || !fs.existsSync(bgPath)) {
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const bg = await import(pathToFileURL(bgPath).href);
|
|
20
|
+
const bytes = fs.readFileSync(wasmPath);
|
|
21
|
+
const importObject = { './aiwaf_wasm_bg.js': bg };
|
|
22
|
+
const { instance } = await WebAssembly.instantiate(bytes, importObject);
|
|
23
|
+
|
|
24
|
+
if (typeof bg.__wbg_set_wasm === 'function') {
|
|
25
|
+
bg.__wbg_set_wasm(instance.exports);
|
|
26
|
+
}
|
|
27
|
+
if (instance.exports && typeof instance.exports.__wbindgen_start === 'function') {
|
|
28
|
+
instance.exports.__wbindgen_start();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
return {
|
|
32
|
+
AiwafIsolationForest: bg.IsolationForest,
|
|
33
|
+
IsolationForest: bg.IsolationForest,
|
|
34
|
+
validate_headers: bg.validate_headers,
|
|
35
|
+
validate_headers_with_config: bg.validate_headers_with_config,
|
|
36
|
+
analyze_recent_behavior: bg.analyze_recent_behavior,
|
|
37
|
+
extract_features: bg.extract_features,
|
|
38
|
+
extract_features_batch_with_state: bg.extract_features_batch_with_state,
|
|
39
|
+
finalize_feature_state: bg.finalize_feature_state,
|
|
40
|
+
build_records: bg.build_records,
|
|
41
|
+
rust_payload_from_records: bg.rust_payload_from_records,
|
|
42
|
+
python_feature_from_record: bg.python_feature_from_record,
|
|
43
|
+
python_features_batched: bg.python_features_batched
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function loadWasmFromPackageModule() {
|
|
48
|
+
const pkgDir = path.join(__dirname, '..', 'node_modules', 'aiwaf-wasm');
|
|
49
|
+
const modulePath = path.join(pkgDir, 'aiwaf_wasm.js');
|
|
50
|
+
if (!fs.existsSync(modulePath)) return null;
|
|
51
|
+
try {
|
|
52
|
+
return await import(pathToFileURL(modulePath).href);
|
|
53
|
+
} catch (err) {
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async function loadWasm() {
|
|
59
|
+
if (wasmLoadAttempted) return wasmModule;
|
|
60
|
+
wasmLoadAttempted = true;
|
|
61
|
+
try {
|
|
62
|
+
// Optional dependency: aiwaf-wasm
|
|
63
|
+
// eslint-disable-next-line global-require, import/no-extraneous-dependencies
|
|
64
|
+
const mod = require('aiwaf-wasm');
|
|
65
|
+
if (mod) {
|
|
66
|
+
if (typeof mod.default === 'function') {
|
|
67
|
+
await mod.default();
|
|
68
|
+
} else if (typeof mod.init === 'function') {
|
|
69
|
+
await mod.init();
|
|
70
|
+
}
|
|
71
|
+
wasmModule = mod;
|
|
72
|
+
}
|
|
73
|
+
} catch (err) {
|
|
74
|
+
try {
|
|
75
|
+
const fallback = await loadWasmFromPackageModule() || await loadWasmFromDisk();
|
|
76
|
+
if (fallback) {
|
|
77
|
+
wasmModule = fallback;
|
|
78
|
+
} else {
|
|
79
|
+
wasmLoadError = err;
|
|
80
|
+
wasmModule = null;
|
|
81
|
+
}
|
|
82
|
+
} catch (fallbackErr) {
|
|
83
|
+
wasmLoadError = fallbackErr || err;
|
|
84
|
+
wasmModule = null;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return wasmModule;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function createIsolationForest(opts = {}) {
|
|
91
|
+
const mod = await loadWasm();
|
|
92
|
+
const WasmIsolationForest = mod && (mod.AiwafIsolationForest || mod.IsolationForest);
|
|
93
|
+
if (typeof WasmIsolationForest === 'function') {
|
|
94
|
+
const nTrees = Number.isFinite(Number(opts.nTrees)) ? Number(opts.nTrees) : 100;
|
|
95
|
+
const sampleSize = Number.isFinite(Number(opts.sampleSize)) ? Number(opts.sampleSize) : 256;
|
|
96
|
+
const threshold = Number.isFinite(Number(opts.threshold)) ? Number(opts.threshold) : 0.5;
|
|
97
|
+
const seed = Number.isFinite(Number(opts.seed)) ? Number(opts.seed) : 42;
|
|
98
|
+
const wasmModel = new WasmIsolationForest({
|
|
99
|
+
n_trees: nTrees,
|
|
100
|
+
n_estimators: nTrees,
|
|
101
|
+
sample_size: sampleSize,
|
|
102
|
+
max_samples: sampleSize,
|
|
103
|
+
threshold,
|
|
104
|
+
seed,
|
|
105
|
+
random_state: seed
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
return {
|
|
109
|
+
fit(data) {
|
|
110
|
+
return wasmModel.fit(data);
|
|
111
|
+
},
|
|
112
|
+
retrain(data) {
|
|
113
|
+
if (typeof wasmModel.retrain === 'function') {
|
|
114
|
+
return wasmModel.retrain(data);
|
|
115
|
+
}
|
|
116
|
+
return undefined;
|
|
117
|
+
},
|
|
118
|
+
anomalyScore(point) {
|
|
119
|
+
if (typeof wasmModel.anomaly_score === 'function') {
|
|
120
|
+
return wasmModel.anomaly_score(point);
|
|
121
|
+
}
|
|
122
|
+
if (typeof wasmModel.anomalyScore === 'function') {
|
|
123
|
+
return wasmModel.anomalyScore(point);
|
|
124
|
+
}
|
|
125
|
+
return 0;
|
|
126
|
+
},
|
|
127
|
+
isAnomaly(point, thresh = threshold) {
|
|
128
|
+
if (typeof wasmModel.is_anomaly === 'function') {
|
|
129
|
+
return wasmModel.is_anomaly(point, thresh);
|
|
130
|
+
}
|
|
131
|
+
const score = this.anomalyScore(point);
|
|
132
|
+
return score > thresh;
|
|
133
|
+
},
|
|
134
|
+
scoreSamples(data) {
|
|
135
|
+
if (typeof wasmModel.score_samples === 'function') {
|
|
136
|
+
return wasmModel.score_samples(data);
|
|
137
|
+
}
|
|
138
|
+
return Array.isArray(data) ? data.map(point => this.anomalyScore(point)) : [];
|
|
139
|
+
},
|
|
140
|
+
decisionFunction(data) {
|
|
141
|
+
if (typeof wasmModel.decision_function === 'function') {
|
|
142
|
+
return wasmModel.decision_function(data);
|
|
143
|
+
}
|
|
144
|
+
return this.scoreSamples(data);
|
|
145
|
+
},
|
|
146
|
+
predict(data) {
|
|
147
|
+
if (typeof wasmModel.predict === 'function') {
|
|
148
|
+
return wasmModel.predict(data);
|
|
149
|
+
}
|
|
150
|
+
return this.scoreSamples(data).map(score => (score > threshold ? -1 : 1));
|
|
151
|
+
},
|
|
152
|
+
toJSON() {
|
|
153
|
+
if (typeof wasmModel.to_json === 'function') {
|
|
154
|
+
return wasmModel.to_json();
|
|
155
|
+
}
|
|
156
|
+
return null;
|
|
157
|
+
},
|
|
158
|
+
__aiwafWasm: true
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
return new IsolationForest(opts);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async function createIsolationForestFromJSON(state) {
|
|
166
|
+
const mod = await loadWasm();
|
|
167
|
+
const WasmIsolationForest = mod && (mod.AiwafIsolationForest || mod.IsolationForest);
|
|
168
|
+
if (WasmIsolationForest && typeof WasmIsolationForest.from_json === 'function') {
|
|
169
|
+
try {
|
|
170
|
+
const wasmModel = WasmIsolationForest.from_json(state);
|
|
171
|
+
return {
|
|
172
|
+
fit(data) {
|
|
173
|
+
return wasmModel.fit(data);
|
|
174
|
+
},
|
|
175
|
+
retrain(data) {
|
|
176
|
+
return typeof wasmModel.retrain === 'function' ? wasmModel.retrain(data) : undefined;
|
|
177
|
+
},
|
|
178
|
+
anomalyScore(point) {
|
|
179
|
+
return typeof wasmModel.anomaly_score === 'function' ? wasmModel.anomaly_score(point) : 0;
|
|
180
|
+
},
|
|
181
|
+
isAnomaly(point, thresh = 0.5) {
|
|
182
|
+
if (typeof wasmModel.is_anomaly === 'function') return wasmModel.is_anomaly(point, thresh);
|
|
183
|
+
return this.anomalyScore(point) > thresh;
|
|
184
|
+
},
|
|
185
|
+
scoreSamples(data) {
|
|
186
|
+
return typeof wasmModel.score_samples === 'function' ? wasmModel.score_samples(data) : [];
|
|
187
|
+
},
|
|
188
|
+
decisionFunction(data) {
|
|
189
|
+
return typeof wasmModel.decision_function === 'function' ? wasmModel.decision_function(data) : this.scoreSamples(data);
|
|
190
|
+
},
|
|
191
|
+
predict(data) {
|
|
192
|
+
return typeof wasmModel.predict === 'function' ? wasmModel.predict(data) : [];
|
|
193
|
+
},
|
|
194
|
+
toJSON() {
|
|
195
|
+
return typeof wasmModel.to_json === 'function' ? wasmModel.to_json() : state;
|
|
196
|
+
},
|
|
197
|
+
__aiwafWasm: true
|
|
198
|
+
};
|
|
199
|
+
} catch (err) {
|
|
200
|
+
// Fall back to JS model parsing below.
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return IsolationForest.fromJSON(state);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function normalizeValidationResult(result, fallbackReason) {
|
|
207
|
+
if (result === null || result === undefined || result === true || result === 0) return null;
|
|
208
|
+
if (result === false) return fallbackReason;
|
|
209
|
+
if (typeof result === 'string') return result || null;
|
|
210
|
+
if (typeof result === 'object') {
|
|
211
|
+
if (result.ok === false) return result.reason || fallbackReason;
|
|
212
|
+
if (result.allowed === false) return result.reason || fallbackReason;
|
|
213
|
+
}
|
|
214
|
+
return null;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function normalizeRecentEntries(entries = []) {
|
|
218
|
+
return (Array.isArray(entries) ? entries : []).map(entry => {
|
|
219
|
+
const rawTimestamp = Number(entry.timestamp ?? entry.timestamp_epoch ?? Date.now());
|
|
220
|
+
const timestamp = rawTimestamp > 1000000000000 ? rawTimestamp / 1000 : rawTimestamp;
|
|
221
|
+
return {
|
|
222
|
+
path_lower: String(entry.path_lower || entry.path || '').toLowerCase(),
|
|
223
|
+
timestamp: Number.isFinite(timestamp) ? timestamp : Date.now() / 1000,
|
|
224
|
+
status: Number(entry.status || entry.status_code || 0),
|
|
225
|
+
kw_check: entry.kw_check !== false
|
|
226
|
+
};
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function normalizeHeaderValue(value) {
|
|
231
|
+
if (value === undefined || value === null) return '';
|
|
232
|
+
return String(value);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function toPlainHeaderObject(headers) {
|
|
236
|
+
const out = {};
|
|
237
|
+
if (!headers) return out;
|
|
238
|
+
if (typeof headers.forEach === 'function' && typeof headers.get === 'function') {
|
|
239
|
+
headers.forEach((value, key) => {
|
|
240
|
+
if (!key) return;
|
|
241
|
+
out[String(key).toLowerCase()] = normalizeHeaderValue(value);
|
|
242
|
+
});
|
|
243
|
+
return out;
|
|
244
|
+
}
|
|
245
|
+
for (const [key, value] of Object.entries(headers || {})) {
|
|
246
|
+
if (!key) continue;
|
|
247
|
+
const normalizedValue = Array.isArray(value)
|
|
248
|
+
? value.map(v => normalizeHeaderValue(v)).join(', ')
|
|
249
|
+
: normalizeHeaderValue(value);
|
|
250
|
+
out[String(key).toLowerCase()] = normalizedValue;
|
|
251
|
+
}
|
|
252
|
+
return out;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
async function validateHeaders(headers, config) {
|
|
256
|
+
const mod = await loadWasm();
|
|
257
|
+
if (!mod || typeof mod.validate_headers !== 'function') return null;
|
|
258
|
+
try {
|
|
259
|
+
const headerObject = toPlainHeaderObject(headers);
|
|
260
|
+
if (process.env.AIWAF_DEBUG_WASM_HEADERS) {
|
|
261
|
+
// eslint-disable-next-line no-console
|
|
262
|
+
console.error(`[WASM-HEADER-VALIDATION] headers keys: ${Object.keys(headerObject || {}).join(', ')}`);
|
|
263
|
+
// eslint-disable-next-line no-console
|
|
264
|
+
console.error(`[WASM-HEADER-VALIDATION] user-agent: ${headerObject?.['user-agent'] || ''}`);
|
|
265
|
+
// eslint-disable-next-line no-console
|
|
266
|
+
console.error(`[WASM-HEADER-VALIDATION] accept: ${headerObject?.['accept'] || ''}`);
|
|
267
|
+
}
|
|
268
|
+
let result;
|
|
269
|
+
const forcePlain = process.env.AIWAF_FORCE_PLAIN_HEADERS === '1';
|
|
270
|
+
const allowHeaders = process.env.AIWAF_USE_HEADERS === '1';
|
|
271
|
+
const canUseHeaders = allowHeaders
|
|
272
|
+
&& !forcePlain
|
|
273
|
+
&& (typeof window !== 'undefined' && typeof Headers === 'function');
|
|
274
|
+
|
|
275
|
+
const src = headerObject || {};
|
|
276
|
+
const headerInputObj = { ...src };
|
|
277
|
+
if (src['user-agent'] && !headerInputObj.HTTP_USER_AGENT) {
|
|
278
|
+
headerInputObj.HTTP_USER_AGENT = src['user-agent'];
|
|
279
|
+
}
|
|
280
|
+
if (src.accept && !headerInputObj.HTTP_ACCEPT) {
|
|
281
|
+
headerInputObj.HTTP_ACCEPT = src.accept;
|
|
282
|
+
}
|
|
283
|
+
if (src['accept-language'] && !headerInputObj.HTTP_ACCEPT_LANGUAGE) {
|
|
284
|
+
headerInputObj.HTTP_ACCEPT_LANGUAGE = src['accept-language'];
|
|
285
|
+
}
|
|
286
|
+
if (src['accept-encoding'] && !headerInputObj.HTTP_ACCEPT_ENCODING) {
|
|
287
|
+
headerInputObj.HTTP_ACCEPT_ENCODING = src['accept-encoding'];
|
|
288
|
+
}
|
|
289
|
+
if (src.connection && !headerInputObj.HTTP_CONNECTION) {
|
|
290
|
+
headerInputObj.HTTP_CONNECTION = src.connection;
|
|
291
|
+
}
|
|
292
|
+
if (src['cache-control'] && !headerInputObj.HTTP_CACHE_CONTROL) {
|
|
293
|
+
headerInputObj.HTTP_CACHE_CONTROL = src['cache-control'];
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
const headerInput = canUseHeaders ? new Headers(src) : headerInputObj;
|
|
297
|
+
if (config && typeof mod.validate_headers_with_config === 'function') {
|
|
298
|
+
const required = (config.requiredHeaders && config.requiredHeaders.length) ? config.requiredHeaders : null;
|
|
299
|
+
const minScore = Number.isFinite(Number(config.minScore)) ? Number(config.minScore) : null;
|
|
300
|
+
result = mod.validate_headers_with_config(headerInput, required, minScore);
|
|
301
|
+
} else {
|
|
302
|
+
result = mod.validate_headers(headerInput);
|
|
303
|
+
}
|
|
304
|
+
if (process.env.AIWAF_DEBUG_WASM_HEADERS) {
|
|
305
|
+
// eslint-disable-next-line no-console
|
|
306
|
+
console.error(`[WASM-HEADER-VALIDATION] raw=${JSON.stringify(result)}`);
|
|
307
|
+
}
|
|
308
|
+
return normalizeValidationResult(result, 'wasm_header_invalid');
|
|
309
|
+
} catch (err) {
|
|
310
|
+
if (process.env.AIWAF_DEBUG_WASM_HEADERS) {
|
|
311
|
+
// eslint-disable-next-line no-console
|
|
312
|
+
console.error(`[WASM-HEADER-VALIDATION] error=${err?.message || err}`);
|
|
313
|
+
}
|
|
314
|
+
return 'wasm_header_error';
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
async function validateUrl(url) {
|
|
319
|
+
const mod = await loadWasm();
|
|
320
|
+
if (!mod || typeof mod.validate_url !== 'function') return null;
|
|
321
|
+
try {
|
|
322
|
+
const result = mod.validate_url(url);
|
|
323
|
+
return normalizeValidationResult(result, 'wasm_url_invalid');
|
|
324
|
+
} catch (err) {
|
|
325
|
+
return 'wasm_url_error';
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
async function validateContent(content) {
|
|
330
|
+
const mod = await loadWasm();
|
|
331
|
+
if (!mod || typeof mod.validate_content !== 'function') return null;
|
|
332
|
+
try {
|
|
333
|
+
const result = mod.validate_content(content);
|
|
334
|
+
return normalizeValidationResult(result, 'wasm_content_invalid');
|
|
335
|
+
} catch (err) {
|
|
336
|
+
return 'wasm_content_error';
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
async function validateRecent(recent) {
|
|
341
|
+
const mod = await loadWasm();
|
|
342
|
+
if (mod && typeof mod.validate_recent === 'function') {
|
|
343
|
+
try {
|
|
344
|
+
const result = mod.validate_recent(recent);
|
|
345
|
+
return normalizeValidationResult(result, 'wasm_recent_invalid');
|
|
346
|
+
} catch (err) {
|
|
347
|
+
return 'wasm_recent_error';
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
if (!mod || typeof mod.analyze_recent_behavior !== 'function') return null;
|
|
351
|
+
try {
|
|
352
|
+
const result = mod.analyze_recent_behavior(normalizeRecentEntries(recent), []);
|
|
353
|
+
if (result && typeof result === 'object' && result.should_block === true) {
|
|
354
|
+
return 'wasm_recent_invalid';
|
|
355
|
+
}
|
|
356
|
+
return null;
|
|
357
|
+
} catch (err) {
|
|
358
|
+
return 'wasm_recent_error';
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
async function analyzeRecentBehavior(entries, staticKeywords = []) {
|
|
363
|
+
const mod = await loadWasm();
|
|
364
|
+
if (!mod || typeof mod.analyze_recent_behavior !== 'function') return null;
|
|
365
|
+
try {
|
|
366
|
+
return mod.analyze_recent_behavior(normalizeRecentEntries(entries), staticKeywords || []);
|
|
367
|
+
} catch (err) {
|
|
368
|
+
return null;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
async function extractWasmFeatures(records, staticKeywords = []) {
|
|
373
|
+
const mod = await loadWasm();
|
|
374
|
+
if (!mod || typeof mod.extract_features !== 'function') return null;
|
|
375
|
+
try {
|
|
376
|
+
return mod.extract_features(records || [], staticKeywords || []);
|
|
377
|
+
} catch (err) {
|
|
378
|
+
return null;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
async function extractWasmFeaturesBatchWithState(records, staticKeywords = [], state = null) {
|
|
383
|
+
const mod = await loadWasm();
|
|
384
|
+
if (!mod || typeof mod.extract_features_batch_with_state !== 'function') return null;
|
|
385
|
+
try {
|
|
386
|
+
return mod.extract_features_batch_with_state(records || [], staticKeywords || [], state);
|
|
387
|
+
} catch (err) {
|
|
388
|
+
return null;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
async function finalizeWasmFeatureState() {
|
|
393
|
+
const mod = await loadWasm();
|
|
394
|
+
if (!mod || typeof mod.finalize_feature_state !== 'function') return null;
|
|
395
|
+
try {
|
|
396
|
+
return mod.finalize_feature_state();
|
|
397
|
+
} catch (err) {
|
|
398
|
+
return null;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
async function buildWasmRecords(parsed, ip404, pathExistsFn, pathExemptFn, statusIdxList) {
|
|
403
|
+
const mod = await loadWasm();
|
|
404
|
+
if (!mod || typeof mod.build_records !== 'function') return null;
|
|
405
|
+
try {
|
|
406
|
+
return mod.build_records(
|
|
407
|
+
parsed || [],
|
|
408
|
+
ip404 || {},
|
|
409
|
+
typeof pathExistsFn === 'function' ? pathExistsFn : (() => false),
|
|
410
|
+
typeof pathExemptFn === 'function' ? pathExemptFn : (() => false),
|
|
411
|
+
statusIdxList || []
|
|
412
|
+
);
|
|
413
|
+
} catch (err) {
|
|
414
|
+
return null;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
async function rustPayloadFromRecords(records) {
|
|
419
|
+
const mod = await loadWasm();
|
|
420
|
+
if (!mod || typeof mod.rust_payload_from_records !== 'function') return null;
|
|
421
|
+
try {
|
|
422
|
+
return mod.rust_payload_from_records(records || []);
|
|
423
|
+
} catch (err) {
|
|
424
|
+
return null;
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
async function pythonFeatureFromRecord(record, ipTimes = {}, staticKeywords = []) {
|
|
429
|
+
const mod = await loadWasm();
|
|
430
|
+
if (!mod || typeof mod.python_feature_from_record !== 'function') return null;
|
|
431
|
+
try {
|
|
432
|
+
return mod.python_feature_from_record(record, ipTimes, staticKeywords);
|
|
433
|
+
} catch (err) {
|
|
434
|
+
return null;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
async function pythonFeaturesBatched(records, ipTimes = {}, staticKeywords = [], options = {}) {
|
|
439
|
+
const mod = await loadWasm();
|
|
440
|
+
if (!mod || typeof mod.python_features_batched !== 'function') return null;
|
|
441
|
+
try {
|
|
442
|
+
return mod.python_features_batched(
|
|
443
|
+
records || [],
|
|
444
|
+
ipTimes || {},
|
|
445
|
+
staticKeywords || [],
|
|
446
|
+
null,
|
|
447
|
+
Number.isFinite(Number(options.batchSize)) ? Number(options.batchSize) : 1000,
|
|
448
|
+
options.parallelEnabled !== false,
|
|
449
|
+
Number.isFinite(Number(options.parallelChunkSize)) ? Number(options.parallelChunkSize) : 1000,
|
|
450
|
+
Number.isFinite(Number(options.maxWorkers)) ? Number(options.maxWorkers) : 0
|
|
451
|
+
);
|
|
452
|
+
} catch (err) {
|
|
453
|
+
return null;
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
function getWasmStatus() {
|
|
458
|
+
return {
|
|
459
|
+
loaded: !!(wasmModule && (wasmModule.AiwafIsolationForest || wasmModule.IsolationForest)),
|
|
460
|
+
error: wasmLoadError ? String(wasmLoadError.message || wasmLoadError) : null
|
|
461
|
+
};
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
module.exports = {
|
|
465
|
+
createIsolationForest,
|
|
466
|
+
createIsolationForestFromJSON,
|
|
467
|
+
validateHeaders,
|
|
468
|
+
validateUrl,
|
|
469
|
+
validateContent,
|
|
470
|
+
validateRecent,
|
|
471
|
+
analyzeRecentBehavior,
|
|
472
|
+
extractWasmFeatures,
|
|
473
|
+
extractWasmFeaturesBatchWithState,
|
|
474
|
+
finalizeWasmFeatureState,
|
|
475
|
+
buildWasmRecords,
|
|
476
|
+
rustPayloadFromRecords,
|
|
477
|
+
pythonFeatureFromRecord,
|
|
478
|
+
pythonFeaturesBatched,
|
|
479
|
+
getWasmStatus
|
|
480
|
+
};
|
package/lib/whois.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
const dns = require('dns').promises;
|
|
2
|
+
const { execFile } = require('child_process');
|
|
3
|
+
const net = require('net');
|
|
4
|
+
|
|
5
|
+
async function resolveDomain(target) {
|
|
6
|
+
const candidate = String(target || '').trim();
|
|
7
|
+
if (!candidate) throw new Error('Target is required');
|
|
8
|
+
if (!net.isIP(candidate)) return candidate;
|
|
9
|
+
|
|
10
|
+
try {
|
|
11
|
+
const [host] = await dns.reverse(candidate);
|
|
12
|
+
if (host) return host;
|
|
13
|
+
} catch (err) {
|
|
14
|
+
// Convert DNS-specific failures to the Python-compatible contract below.
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
throw new Error(`Cannot resolve reverse DNS for IP ${candidate}`);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async function runWhoisLookup(target, options = {}) {
|
|
21
|
+
const domain = await resolveDomain(target);
|
|
22
|
+
const binary = options.binary || 'whois';
|
|
23
|
+
return new Promise((resolve, reject) => {
|
|
24
|
+
execFile(binary, [domain], { timeout: Number(options.timeoutMs || 10000) }, (err, stdout, stderr) => {
|
|
25
|
+
if (err) {
|
|
26
|
+
err.stderr = stderr;
|
|
27
|
+
reject(err);
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
resolve(stdout);
|
|
31
|
+
});
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
module.exports = {
|
|
36
|
+
resolveDomain,
|
|
37
|
+
runWhoisLookup
|
|
38
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "aiwaf",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Adaptive Web Application Firewall middleware for Node.js (Express, Fastify, Hapi, Next.js)",
|
|
5
|
+
"main": "index.js",
|
|
6
|
+
"files": [
|
|
7
|
+
"index.js",
|
|
8
|
+
"bin/",
|
|
9
|
+
"lib/",
|
|
10
|
+
"resources/",
|
|
11
|
+
"utils/",
|
|
12
|
+
"train.js",
|
|
13
|
+
"README.md",
|
|
14
|
+
"INSTALLATION.md",
|
|
15
|
+
"LICENSE"
|
|
16
|
+
],
|
|
17
|
+
"bin": {
|
|
18
|
+
"aiwaf": "bin/aiwaf.js"
|
|
19
|
+
},
|
|
20
|
+
"scripts": {
|
|
21
|
+
"retrain": "AIWAF_LOG_PATH=/var/log/nginx/access.log npm run train",
|
|
22
|
+
"train": "node train.js",
|
|
23
|
+
"test": "jest --runInBand",
|
|
24
|
+
"aiwaf": "node bin/aiwaf.js",
|
|
25
|
+
"perf:wasm": "node test/perf-wasm.js",
|
|
26
|
+
"test:wasm-real": "node test/wasm-real.js"
|
|
27
|
+
},
|
|
28
|
+
"dependencies": {
|
|
29
|
+
"@babel/parser": "^7.29.2",
|
|
30
|
+
"aiwaf-wasm": "^0.2.0",
|
|
31
|
+
"express": "^4.21.2",
|
|
32
|
+
"glob": "^8.1.0",
|
|
33
|
+
"jest": "^29.7.0",
|
|
34
|
+
"knex": "^2.4.2",
|
|
35
|
+
"node-cache": "^5.1.2",
|
|
36
|
+
"redis": "^4.6.5",
|
|
37
|
+
"sqlite3": "^6.0.1",
|
|
38
|
+
"supertest": "^7.1.0"
|
|
39
|
+
},
|
|
40
|
+
"devDependencies": {
|
|
41
|
+
"fastify": "^4.29.1",
|
|
42
|
+
"@hapi/hapi": "^21.3.12",
|
|
43
|
+
"koa": "^2.15.4",
|
|
44
|
+
"koa-bodyparser": "^4.4.1",
|
|
45
|
+
"@nestjs/common": "^10.4.2",
|
|
46
|
+
"@nestjs/core": "^10.4.2",
|
|
47
|
+
"@nestjs/platform-express": "^10.4.2",
|
|
48
|
+
"reflect-metadata": "^0.1.14",
|
|
49
|
+
"rxjs": "^7.8.1"
|
|
50
|
+
},
|
|
51
|
+
"jest": {
|
|
52
|
+
"globalTeardown": "<rootDir>/test/jest.teardown.js",
|
|
53
|
+
"forceExit": true
|
|
54
|
+
},
|
|
55
|
+
"optionalDependencies": {
|
|
56
|
+
"maxmind": "^4.3.0"
|
|
57
|
+
},
|
|
58
|
+
"overrides": {
|
|
59
|
+
"body-parser": "^1.20.3",
|
|
60
|
+
"qs": "^6.14.1",
|
|
61
|
+
"path-to-regexp": "^0.1.13",
|
|
62
|
+
"brace-expansion": "^1.1.13",
|
|
63
|
+
"minimatch": "^5.1.8",
|
|
64
|
+
"picomatch": "^2.3.2",
|
|
65
|
+
"form-data": "^4.0.4",
|
|
66
|
+
"js-yaml": "^3.14.2",
|
|
67
|
+
"lodash": "^4.17.24",
|
|
68
|
+
"tar-fs": "^2.1.4"
|
|
69
|
+
},
|
|
70
|
+
"keywords": [
|
|
71
|
+
"waf",
|
|
72
|
+
"firewall",
|
|
73
|
+
"security",
|
|
74
|
+
"express",
|
|
75
|
+
"nodejs",
|
|
76
|
+
"middleware",
|
|
77
|
+
"ml"
|
|
78
|
+
],
|
|
79
|
+
"repository": {
|
|
80
|
+
"type": "git",
|
|
81
|
+
"url": "git+https://github.com/aiwaf-project/aiwaf-js.git"
|
|
82
|
+
},
|
|
83
|
+
"author": "Aayush Gauba",
|
|
84
|
+
"license": "MIT"
|
|
85
|
+
}
|