aiwaf 1.1.4 → 1.1.5
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/README.md +141 -190
- package/bin/aiwaf.js +61 -57
- package/lib/blacklistManager.js +2 -358
- package/lib/blocklistManager.js +364 -0
- package/lib/csvStore.js +1 -1
- package/lib/nativePipeline.js +5 -3
- package/lib/rateLimiter.js +4 -4
- package/lib/wafMiddleware.js +8 -8
- package/lib/wasmAdapter.js +7 -1
- package/package.json +3 -5
- package/train.js +6 -6
package/bin/aiwaf.js
CHANGED
|
@@ -9,9 +9,9 @@ function print(obj) {
|
|
|
9
9
|
process.stdout.write(`${JSON.stringify(obj, null, 2)}\n`);
|
|
10
10
|
}
|
|
11
11
|
|
|
12
|
-
async function
|
|
13
|
-
const
|
|
14
|
-
const deleted = await
|
|
12
|
+
async function clearBlocklist() {
|
|
13
|
+
const blocklistManager = require('../lib/blocklistManager');
|
|
14
|
+
const deleted = await blocklistManager.clear();
|
|
15
15
|
print({ ok: true, cleared: deleted });
|
|
16
16
|
}
|
|
17
17
|
|
|
@@ -51,13 +51,13 @@ function parseDuration(value) {
|
|
|
51
51
|
}
|
|
52
52
|
|
|
53
53
|
async function collectOperationalState() {
|
|
54
|
-
const
|
|
54
|
+
const blocklistManager = require('../lib/blocklistManager');
|
|
55
55
|
const exemptionStore = require('../lib/exemptionStore');
|
|
56
56
|
const geoStore = require('../lib/geoStore');
|
|
57
57
|
const dynamicKeywordStore = require('../lib/dynamicKeywordStore');
|
|
58
58
|
const modelStore = require('../lib/modelStore');
|
|
59
|
-
const [
|
|
60
|
-
|
|
59
|
+
const [blocklist, ipExemptions, pathExemptions, geo, dynamicKeywords, model] = await Promise.all([
|
|
60
|
+
blocklistManager.exportRecords(),
|
|
61
61
|
exemptionStore.listIps(),
|
|
62
62
|
exemptionStore.listPaths(),
|
|
63
63
|
geoStore.listBlockedCountries(),
|
|
@@ -67,7 +67,7 @@ async function collectOperationalState() {
|
|
|
67
67
|
return {
|
|
68
68
|
schema_version: '1.0',
|
|
69
69
|
exported_at: new Date().toISOString(),
|
|
70
|
-
|
|
70
|
+
blocklist,
|
|
71
71
|
ip_exemptions: ipExemptions,
|
|
72
72
|
path_exemptions: pathExemptions,
|
|
73
73
|
geo_blocked_countries: geo,
|
|
@@ -79,7 +79,7 @@ async function collectOperationalState() {
|
|
|
79
79
|
async function exportOperationalState(filePath = 'aiwaf-export.json') {
|
|
80
80
|
const state = await collectOperationalState();
|
|
81
81
|
return print({ ok: true, output: writeJsonFile(filePath, state), counts: {
|
|
82
|
-
|
|
82
|
+
blocklist: state.blocklist.length,
|
|
83
83
|
ip_exemptions: state.ip_exemptions.length,
|
|
84
84
|
path_exemptions: state.path_exemptions.length,
|
|
85
85
|
geo: state.geo_blocked_countries.length,
|
|
@@ -90,12 +90,12 @@ async function exportOperationalState(filePath = 'aiwaf-export.json') {
|
|
|
90
90
|
async function importOperationalState(filePath) {
|
|
91
91
|
if (!filePath) throw new Error('Import file is required');
|
|
92
92
|
const state = readJsonFile(filePath);
|
|
93
|
-
const
|
|
93
|
+
const blocklistManager = require('../lib/blocklistManager');
|
|
94
94
|
const exemptionStore = require('../lib/exemptionStore');
|
|
95
95
|
const geoStore = require('../lib/geoStore');
|
|
96
96
|
const dynamicKeywordStore = require('../lib/dynamicKeywordStore');
|
|
97
97
|
const modelStore = require('../lib/modelStore');
|
|
98
|
-
const imported = {
|
|
98
|
+
const imported = { blocklist: await blocklistManager.importRecords(state.blocklist ?? state.blacklist ?? []) };
|
|
99
99
|
for (const row of state.ip_exemptions || []) await exemptionStore.addIp(row.ip_address || row.ip, row.reason);
|
|
100
100
|
for (const row of state.path_exemptions || []) await exemptionStore.addPath(row.path_prefix || row.path, row.reason);
|
|
101
101
|
for (const row of state.geo_blocked_countries || []) await geoStore.addBlockedCountry(row.country_code || row.country, row.reason);
|
|
@@ -109,20 +109,20 @@ async function importOperationalState(filePath) {
|
|
|
109
109
|
}
|
|
110
110
|
|
|
111
111
|
async function operationalStatus() {
|
|
112
|
-
const
|
|
112
|
+
const blocklistManager = require('../lib/blocklistManager');
|
|
113
113
|
const exemptionStore = require('../lib/exemptionStore');
|
|
114
114
|
const geoStore = require('../lib/geoStore');
|
|
115
115
|
const dynamicKeywordStore = require('../lib/dynamicKeywordStore');
|
|
116
116
|
const requestLogStore = require('../lib/requestLogStore');
|
|
117
117
|
const modelStore = require('../lib/modelStore');
|
|
118
|
-
const [
|
|
119
|
-
|
|
118
|
+
const [blocklist, ips, paths, geo, keywords, logs, model] = await Promise.all([
|
|
119
|
+
blocklistManager.getStatistics(), exemptionStore.listIps(), exemptionStore.listPaths(),
|
|
120
120
|
geoStore.listBlockedCountries(), dynamicKeywordStore.list(100000), requestLogStore.recent(1),
|
|
121
121
|
modelStore.load(process.env)
|
|
122
122
|
]);
|
|
123
123
|
return print({
|
|
124
124
|
status: 'enabled',
|
|
125
|
-
|
|
125
|
+
blocklist,
|
|
126
126
|
exemptions: { ips: ips.length, paths: paths.length },
|
|
127
127
|
geo_blocked_countries: geo.length,
|
|
128
128
|
dynamic_keywords: keywords.length,
|
|
@@ -133,9 +133,9 @@ async function operationalStatus() {
|
|
|
133
133
|
}
|
|
134
134
|
|
|
135
135
|
async function operationalStats(limit = 5000) {
|
|
136
|
-
const
|
|
136
|
+
const blocklistManager = require('../lib/blocklistManager');
|
|
137
137
|
const requestLogStore = require('../lib/requestLogStore');
|
|
138
|
-
const [
|
|
138
|
+
const [blocklist, logs] = await Promise.all([blocklistManager.getStatistics(), requestLogStore.recent(limit)]);
|
|
139
139
|
const statuses = {};
|
|
140
140
|
const paths = {};
|
|
141
141
|
let blocked = 0;
|
|
@@ -145,7 +145,7 @@ async function operationalStats(limit = 5000) {
|
|
|
145
145
|
if (row.blocked === true || row.blocked === 1 || String(row.blocked).toLowerCase() === 'true') blocked += 1;
|
|
146
146
|
});
|
|
147
147
|
return print({
|
|
148
|
-
|
|
148
|
+
blocklist,
|
|
149
149
|
requests: { total: logs.length, blocked, statuses },
|
|
150
150
|
top_paths: Object.entries(paths).sort((a, b) => b[1] - a[1]).slice(0, 10).map(([requestPath, count]) => ({ path: requestPath, count }))
|
|
151
151
|
});
|
|
@@ -172,10 +172,10 @@ function parseManifestArgs(args = []) {
|
|
|
172
172
|
}
|
|
173
173
|
|
|
174
174
|
async function diagnoseIp(ip) {
|
|
175
|
-
const
|
|
175
|
+
const blocklistManager = require('../lib/blocklistManager');
|
|
176
176
|
const exemptionStore = require('../lib/exemptionStore');
|
|
177
|
-
const blocked = await
|
|
178
|
-
const blockInfo = await
|
|
177
|
+
const blocked = await blocklistManager.isBlocked(ip);
|
|
178
|
+
const blockInfo = await blocklistManager.getBlockInfo(ip);
|
|
179
179
|
const exempt = await exemptionStore.isIpExempt(ip);
|
|
180
180
|
print({ ip, blocked, exempt, block_info: blockInfo });
|
|
181
181
|
}
|
|
@@ -231,25 +231,25 @@ function runPathShell() {
|
|
|
231
231
|
}
|
|
232
232
|
|
|
233
233
|
async function runReset(args) {
|
|
234
|
-
const flags = {
|
|
234
|
+
const flags = { blocklist: false, keywords: false, exemptions: false, confirm: false };
|
|
235
235
|
for (const arg of args) {
|
|
236
|
-
if (arg === '--
|
|
236
|
+
if (arg === '--blocklist') flags.blocklist = true;
|
|
237
237
|
if (arg === '--keywords') flags.keywords = true;
|
|
238
238
|
if (arg === '--exemptions') flags.exemptions = true;
|
|
239
|
-
if (arg === '--all') { flags.
|
|
239
|
+
if (arg === '--all') { flags.blocklist = true; flags.keywords = true; flags.exemptions = true; }
|
|
240
240
|
if (arg === '--confirm') flags.confirm = true;
|
|
241
241
|
}
|
|
242
|
-
if (!flags.
|
|
243
|
-
return print({ error: 'Specify what to reset: --
|
|
242
|
+
if (!flags.blocklist && !flags.keywords && !flags.exemptions) {
|
|
243
|
+
return print({ error: 'Specify what to reset: --blocklist, --keywords, --exemptions, or --all' });
|
|
244
244
|
}
|
|
245
245
|
if (!flags.confirm) {
|
|
246
246
|
return print({ error: 'Must pass --confirm to execute reset' });
|
|
247
247
|
}
|
|
248
248
|
|
|
249
249
|
const results = {};
|
|
250
|
-
if (flags.
|
|
251
|
-
const
|
|
252
|
-
results.
|
|
250
|
+
if (flags.blocklist) {
|
|
251
|
+
const blocklistManager = require('../lib/blocklistManager');
|
|
252
|
+
results.blocklist = await blocklistManager.clear();
|
|
253
253
|
}
|
|
254
254
|
if (flags.keywords) {
|
|
255
255
|
const dynamicKeywordStore = require('../lib/dynamicKeywordStore');
|
|
@@ -263,35 +263,39 @@ async function runReset(args) {
|
|
|
263
263
|
}
|
|
264
264
|
|
|
265
265
|
async function main() {
|
|
266
|
-
const
|
|
266
|
+
const argv = [...process.argv];
|
|
267
|
+
for (const index of [2, 3]) {
|
|
268
|
+
argv[index] = { blacklist: 'blocklist', whitelist: 'allowlist' }[argv[index]] || argv[index];
|
|
269
|
+
}
|
|
270
|
+
const [, , cmd, subcmd, ...args] = argv;
|
|
267
271
|
|
|
268
272
|
if (!cmd || ['help', '--help', '-h'].includes(cmd)) {
|
|
269
273
|
print({
|
|
270
274
|
usage: 'aiwaf <command> [subcommand] [args]',
|
|
271
275
|
commands: [
|
|
272
|
-
'list
|
|
276
|
+
'list blocklist|exemptions|geo|request-logs',
|
|
273
277
|
'list dynamic-keywords',
|
|
274
278
|
'list model-info',
|
|
275
279
|
'list recent-blocks [hours]',
|
|
276
280
|
'list top-reasons [limit]',
|
|
277
|
-
'add
|
|
281
|
+
'add blocklist <ip> [reason] [--duration 24h|--permanent]',
|
|
278
282
|
'add ip-exemption <ip> [reason]',
|
|
279
283
|
'add path-exemption <pathPrefix> [reason]',
|
|
280
284
|
'add dynamic-keyword <keyword> [count]',
|
|
281
|
-
'remove
|
|
285
|
+
'remove blocklist <ip>',
|
|
282
286
|
'remove ip-exemption <ip>',
|
|
283
287
|
'remove path-exemption <pathPrefix>',
|
|
284
288
|
'remove dynamic-keyword <keyword>',
|
|
285
289
|
'geo block <CC> [reason]',
|
|
286
290
|
'geo unblock <CC>',
|
|
287
291
|
'geo summary',
|
|
288
|
-
'clear
|
|
292
|
+
'clear blocklist|request-logs',
|
|
289
293
|
'clear dynamic-keywords',
|
|
290
294
|
'status',
|
|
291
295
|
'stats [request-limit]',
|
|
292
296
|
'logs analyze [limit]',
|
|
293
|
-
'
|
|
294
|
-
'
|
|
297
|
+
'blocklist migrate [--duration 24h]',
|
|
298
|
+
'blocklist cleanup',
|
|
295
299
|
'export [output.json]',
|
|
296
300
|
'import <input.json>',
|
|
297
301
|
'model info|export|import|clear [file]',
|
|
@@ -299,7 +303,7 @@ async function main() {
|
|
|
299
303
|
'manifest --framework <name> --routes <routes.json> [--output .aiwaf/paths.json]',
|
|
300
304
|
'whois <domain|ip>',
|
|
301
305
|
'diagnose <ip>',
|
|
302
|
-
'reset [--
|
|
306
|
+
'reset [--blocklist] [--keywords] [--exemptions] [--all] --confirm',
|
|
303
307
|
'pathshell'
|
|
304
308
|
]
|
|
305
309
|
});
|
|
@@ -318,16 +322,16 @@ async function main() {
|
|
|
318
322
|
return operationalStats(Number(args[0] || 5000));
|
|
319
323
|
}
|
|
320
324
|
|
|
321
|
-
if (cmd === '
|
|
322
|
-
const
|
|
323
|
-
return print({ ok: true, cleaned: await
|
|
325
|
+
if (cmd === 'blocklist' && subcmd === 'cleanup') {
|
|
326
|
+
const blocklistManager = require('../lib/blocklistManager');
|
|
327
|
+
return print({ ok: true, cleaned: await blocklistManager.cleanupExpired() });
|
|
324
328
|
}
|
|
325
329
|
|
|
326
|
-
if (cmd === '
|
|
330
|
+
if (cmd === 'blocklist' && subcmd === 'migrate') {
|
|
327
331
|
const durationIndex = args.indexOf('--duration');
|
|
328
332
|
const duration = durationIndex >= 0 ? parseDuration(args[durationIndex + 1]) : null;
|
|
329
|
-
const
|
|
330
|
-
return print({ ok: true, ...(await
|
|
333
|
+
const blocklistManager = require('../lib/blocklistManager');
|
|
334
|
+
return print({ ok: true, ...(await blocklistManager.migrateLegacy({ duration })) });
|
|
331
335
|
}
|
|
332
336
|
|
|
333
337
|
if (cmd === 'model') {
|
|
@@ -362,9 +366,9 @@ async function main() {
|
|
|
362
366
|
return print({ ok: true, output: options.output, framework: options.framework, routes: Object.keys(manifest.routes || {}).length });
|
|
363
367
|
}
|
|
364
368
|
|
|
365
|
-
if (cmd === 'list' && subcmd === '
|
|
366
|
-
const
|
|
367
|
-
const rows = await
|
|
369
|
+
if (cmd === 'list' && subcmd === 'blocklist') {
|
|
370
|
+
const blocklistManager = require('../lib/blocklistManager');
|
|
371
|
+
const rows = await blocklistManager.getBlockedIPs();
|
|
368
372
|
return print(rows);
|
|
369
373
|
}
|
|
370
374
|
|
|
@@ -403,13 +407,13 @@ async function main() {
|
|
|
403
407
|
}
|
|
404
408
|
|
|
405
409
|
if (cmd === 'list' && subcmd === 'recent-blocks') {
|
|
406
|
-
const
|
|
407
|
-
return print(await
|
|
410
|
+
const blocklistManager = require('../lib/blocklistManager');
|
|
411
|
+
return print(await blocklistManager.getRecentBlocks(Number(args[0] || 24)));
|
|
408
412
|
}
|
|
409
413
|
|
|
410
414
|
if (cmd === 'list' && subcmd === 'top-reasons') {
|
|
411
|
-
const
|
|
412
|
-
return print(await
|
|
415
|
+
const blocklistManager = require('../lib/blocklistManager');
|
|
416
|
+
return print(await blocklistManager.getTopBlockedReasons(Number(args[0] || 10)));
|
|
413
417
|
}
|
|
414
418
|
|
|
415
419
|
if (cmd === 'add' && subcmd === 'ip-exemption') {
|
|
@@ -419,15 +423,15 @@ async function main() {
|
|
|
419
423
|
return print({ ok: true, ip });
|
|
420
424
|
}
|
|
421
425
|
|
|
422
|
-
if (cmd === 'add' && subcmd === '
|
|
423
|
-
const
|
|
426
|
+
if (cmd === 'add' && subcmd === 'blocklist') {
|
|
427
|
+
const blocklistManager = require('../lib/blocklistManager');
|
|
424
428
|
const [ip, ...values] = args;
|
|
425
429
|
const durationIndex = values.indexOf('--duration');
|
|
426
430
|
const permanent = values.includes('--permanent');
|
|
427
431
|
const duration = durationIndex >= 0 ? parseDuration(values[durationIndex + 1]) : undefined;
|
|
428
432
|
const reasonParts = values.filter((value, index) => value !== '--permanent'
|
|
429
433
|
&& value !== '--duration' && index !== durationIndex + 1);
|
|
430
|
-
await
|
|
434
|
+
await blocklistManager.block(ip, reasonParts.join(' ') || 'manual', { duration, permanent });
|
|
431
435
|
return print({ ok: true, ip });
|
|
432
436
|
}
|
|
433
437
|
|
|
@@ -445,10 +449,10 @@ async function main() {
|
|
|
445
449
|
return print({ ok: true, keyword });
|
|
446
450
|
}
|
|
447
451
|
|
|
448
|
-
if (cmd === 'remove' && subcmd === '
|
|
449
|
-
const
|
|
452
|
+
if (cmd === 'remove' && subcmd === 'blocklist') {
|
|
453
|
+
const blocklistManager = require('../lib/blocklistManager');
|
|
450
454
|
const [ip] = args;
|
|
451
|
-
const deleted = await
|
|
455
|
+
const deleted = await blocklistManager.unblock(ip);
|
|
452
456
|
return print({ ok: true, deleted });
|
|
453
457
|
}
|
|
454
458
|
|
|
@@ -493,8 +497,8 @@ async function main() {
|
|
|
493
497
|
return print(rows);
|
|
494
498
|
}
|
|
495
499
|
|
|
496
|
-
if (cmd === 'clear' && subcmd === '
|
|
497
|
-
return
|
|
500
|
+
if (cmd === 'clear' && subcmd === 'blocklist') {
|
|
501
|
+
return clearBlocklist();
|
|
498
502
|
}
|
|
499
503
|
|
|
500
504
|
if (cmd === 'clear' && subcmd === 'request-logs') {
|
package/lib/blacklistManager.js
CHANGED
|
@@ -1,358 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
const csvStore = require('./csvStore');
|
|
4
|
-
const {
|
|
5
|
-
FIRST_BLOCK_SECONDS,
|
|
6
|
-
evaluateReputation,
|
|
7
|
-
formatBlockReason,
|
|
8
|
-
normalizeReason
|
|
9
|
-
} = require('./reputation');
|
|
10
|
-
|
|
11
|
-
const headers = [
|
|
12
|
-
'id', 'ip_address', 'reason', 'reputation_reason', 'reasons', 'score', 'offenses',
|
|
13
|
-
'blocked_at', 'expires_at', 'duration', 'permanent', 'extended_request_info'
|
|
14
|
-
];
|
|
15
|
-
const csvPath = process.env.AIWAF_BLOCKED_IPS_CSV_PATH || path.join('logs', 'storage', 'blocked_ips.csv');
|
|
16
|
-
|
|
17
|
-
let initialized = false;
|
|
18
|
-
let dbAvailable = true;
|
|
19
|
-
|
|
20
|
-
const schemaColumns = {
|
|
21
|
-
reputation_reason: table => table.string('reputation_reason').defaultTo(''),
|
|
22
|
-
reasons: table => table.text('reasons').defaultTo('[]'),
|
|
23
|
-
score: table => table.integer('score').defaultTo(0),
|
|
24
|
-
offenses: table => table.integer('offenses').defaultTo(0),
|
|
25
|
-
expires_at: table => table.float('expires_at').nullable(),
|
|
26
|
-
duration: table => table.integer('duration').nullable(),
|
|
27
|
-
permanent: table => table.boolean('permanent').defaultTo(false),
|
|
28
|
-
extended_request_info: table => table.text('extended_request_info').defaultTo('{}')
|
|
29
|
-
};
|
|
30
|
-
|
|
31
|
-
function parseJson(value, fallback) {
|
|
32
|
-
if (value && typeof value === 'object') return value;
|
|
33
|
-
try { return value ? JSON.parse(value) : fallback; } catch (err) { return fallback; }
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
function toTimestamp(value) {
|
|
37
|
-
if (value === null || value === undefined || value === '') return null;
|
|
38
|
-
const numeric = Number(value);
|
|
39
|
-
if (Number.isFinite(numeric)) return numeric;
|
|
40
|
-
const parsed = new Date(value).getTime();
|
|
41
|
-
return Number.isFinite(parsed) ? parsed / 1000 : null;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
function normalizeRow(row = {}) {
|
|
45
|
-
const reason = normalizeReason(row.reason || 'legacy block');
|
|
46
|
-
const legacy = !row.reputation_reason;
|
|
47
|
-
return {
|
|
48
|
-
...row,
|
|
49
|
-
ip_address: String(row.ip_address || row.ip || '').trim(),
|
|
50
|
-
reason,
|
|
51
|
-
reputation_reason: row.reputation_reason || (legacy ? 'legacy_blacklist' : ''),
|
|
52
|
-
reasons: parseJson(row.reasons, legacy ? ['legacy_blacklist', reason] : [reason]),
|
|
53
|
-
score: Number(row.score || (legacy ? 100 : 0)),
|
|
54
|
-
offenses: Number(row.offenses || (legacy ? 1 : 0)),
|
|
55
|
-
blocked_at: toTimestamp(row.blocked_at) || Date.now() / 1000,
|
|
56
|
-
expires_at: toTimestamp(row.expires_at),
|
|
57
|
-
duration: row.duration === '' || row.duration === null || row.duration === undefined ? null : Number(row.duration),
|
|
58
|
-
permanent: row.permanent === true || row.permanent === 1 || String(row.permanent) === '1' || String(row.permanent).toLowerCase() === 'true' || legacy,
|
|
59
|
-
extended_request_info: parseJson(row.extended_request_info, {})
|
|
60
|
-
};
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
function serializeRow(row) {
|
|
64
|
-
return {
|
|
65
|
-
...row,
|
|
66
|
-
reasons: JSON.stringify(row.reasons || []),
|
|
67
|
-
extended_request_info: JSON.stringify(row.extended_request_info || {}),
|
|
68
|
-
permanent: row.permanent ? 1 : 0
|
|
69
|
-
};
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
function isActive(row, now = Date.now() / 1000) {
|
|
73
|
-
return !!row && (row.permanent || !row.expires_at || Number(row.expires_at) > now);
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
async function ensureDbColumns() {
|
|
77
|
-
if (typeof db.schema.hasColumn !== 'function' || typeof db.schema.table !== 'function') return;
|
|
78
|
-
for (const [name, addColumn] of Object.entries(schemaColumns)) {
|
|
79
|
-
if (!await db.schema.hasColumn('blocked_ips', name)) {
|
|
80
|
-
await db.schema.table('blocked_ips', addColumn);
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
async function initialize() {
|
|
86
|
-
if (initialized) return dbAvailable;
|
|
87
|
-
|
|
88
|
-
try {
|
|
89
|
-
const exists = await db.schema.hasTable('blocked_ips');
|
|
90
|
-
if (!exists) {
|
|
91
|
-
await db.schema.createTable('blocked_ips', table => {
|
|
92
|
-
table.increments('id').primary();
|
|
93
|
-
table.string('ip_address').unique().notNullable();
|
|
94
|
-
table.string('reason').defaultTo('WAF blocked');
|
|
95
|
-
table.timestamp('blocked_at').defaultTo(db.fn.now());
|
|
96
|
-
Object.values(schemaColumns).forEach(addColumn => addColumn(table));
|
|
97
|
-
});
|
|
98
|
-
} else {
|
|
99
|
-
await ensureDbColumns();
|
|
100
|
-
}
|
|
101
|
-
dbAvailable = true;
|
|
102
|
-
} catch (err) {
|
|
103
|
-
dbAvailable = false;
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
initialized = true;
|
|
107
|
-
return dbAvailable;
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
function csvRows() {
|
|
111
|
-
return csvStore.readRows(csvPath, headers).map(normalizeRow);
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
async function rawRow(ip) {
|
|
115
|
-
const normalizedIp = String(ip || '').trim();
|
|
116
|
-
if (await initialize()) {
|
|
117
|
-
try {
|
|
118
|
-
const row = await db('blocked_ips').where('ip_address', normalizedIp).first();
|
|
119
|
-
return row ? normalizeRow(row) : null;
|
|
120
|
-
} catch (err) {
|
|
121
|
-
dbAvailable = false;
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
return csvRows().find(row => row.ip_address === normalizedIp) || null;
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
async function saveRow(row) {
|
|
128
|
-
if (dbAvailable) {
|
|
129
|
-
try {
|
|
130
|
-
const payload = serializeRow(row);
|
|
131
|
-
delete payload.id;
|
|
132
|
-
await db('blocked_ips').insert(payload).onConflict('ip_address').merge();
|
|
133
|
-
return;
|
|
134
|
-
} catch (err) {
|
|
135
|
-
dbAvailable = false;
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
await csvStore.updateRows(csvPath, headers, current => {
|
|
139
|
-
const rows = current.map(normalizeRow);
|
|
140
|
-
const index = rows.findIndex(item => item.ip_address === row.ip_address);
|
|
141
|
-
const stored = { ...row, id: index >= 0 ? rows[index].id : csvStore.nextId(rows) };
|
|
142
|
-
if (index >= 0) rows[index] = stored;
|
|
143
|
-
else rows.push(stored);
|
|
144
|
-
return { rows: rows.map(serializeRow) };
|
|
145
|
-
});
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
module.exports = {
|
|
149
|
-
async isBlocked(ip) {
|
|
150
|
-
const row = await rawRow(ip);
|
|
151
|
-
// An expired snapshot is not authority to delete a concurrent refresh.
|
|
152
|
-
return isActive(row);
|
|
153
|
-
},
|
|
154
|
-
|
|
155
|
-
async block(ip, reason = 'WAF blocked', options = {}) {
|
|
156
|
-
const normalizedIp = String(ip || '').trim();
|
|
157
|
-
if (!normalizedIp) return false;
|
|
158
|
-
if (options.checkExemptions !== false) {
|
|
159
|
-
try {
|
|
160
|
-
const exemptionStore = require('./exemptionStore');
|
|
161
|
-
if (await exemptionStore.isIpExempt(normalizedIp)) return false;
|
|
162
|
-
} catch (err) {
|
|
163
|
-
// Storage failures must not disable blocking.
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
const now = Number(options.now ?? Date.now() / 1000);
|
|
167
|
-
const existing = await rawRow(normalizedIp);
|
|
168
|
-
const decision = evaluateReputation({ existing: existing || {}, reason, now });
|
|
169
|
-
const explicitDuration = options.duration === undefined ? null : Number(options.duration);
|
|
170
|
-
const permanent = options.permanent === true || explicitDuration === 0;
|
|
171
|
-
const duration = permanent ? null : (explicitDuration || decision.duration || FIRST_BLOCK_SECONDS);
|
|
172
|
-
await saveRow({
|
|
173
|
-
...(existing || {}),
|
|
174
|
-
ip_address: normalizedIp,
|
|
175
|
-
reason: normalizeReason(reason),
|
|
176
|
-
reputation_reason: formatBlockReason(decision),
|
|
177
|
-
reasons: decision.reasons,
|
|
178
|
-
score: decision.score,
|
|
179
|
-
offenses: decision.offenses,
|
|
180
|
-
blocked_at: now,
|
|
181
|
-
expires_at: permanent ? null : now + duration,
|
|
182
|
-
duration,
|
|
183
|
-
permanent,
|
|
184
|
-
extended_request_info: options.extendedRequestInfo || existing?.extended_request_info || {}
|
|
185
|
-
});
|
|
186
|
-
return true;
|
|
187
|
-
},
|
|
188
|
-
|
|
189
|
-
blockTemporary(ip, reason, minutes = 60, extendedRequestInfo = {}) {
|
|
190
|
-
return this.block(ip, reason, { duration: Number(minutes) * 60, extendedRequestInfo });
|
|
191
|
-
},
|
|
192
|
-
|
|
193
|
-
blockPermanent(ip, reason, extendedRequestInfo = {}) {
|
|
194
|
-
return this.block(ip, reason, { permanent: true, extendedRequestInfo });
|
|
195
|
-
},
|
|
196
|
-
|
|
197
|
-
async unblock(ip) {
|
|
198
|
-
const normalizedIp = String(ip || '').trim();
|
|
199
|
-
const useDb = await initialize();
|
|
200
|
-
if (useDb) {
|
|
201
|
-
try {
|
|
202
|
-
const deleted = await db('blocked_ips').where('ip_address', normalizedIp).del();
|
|
203
|
-
return deleted > 0;
|
|
204
|
-
} catch (err) {
|
|
205
|
-
dbAvailable = false;
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
return csvStore.updateRows(csvPath, headers, current => {
|
|
210
|
-
const rows = current.map(normalizeRow);
|
|
211
|
-
const filtered = rows.filter(row => row.ip_address !== normalizedIp);
|
|
212
|
-
return { rows: filtered.map(serializeRow), result: filtered.length !== rows.length };
|
|
213
|
-
});
|
|
214
|
-
},
|
|
215
|
-
|
|
216
|
-
async getBlockedIPs({ activeOnly = true } = {}) {
|
|
217
|
-
let rows;
|
|
218
|
-
const useDb = await initialize();
|
|
219
|
-
if (useDb) {
|
|
220
|
-
try {
|
|
221
|
-
rows = (await db('blocked_ips').select('*').orderBy('blocked_at', 'desc')).map(normalizeRow);
|
|
222
|
-
} catch (err) {
|
|
223
|
-
dbAvailable = false;
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
rows = rows || csvRows().sort((a, b) => b.blocked_at - a.blocked_at);
|
|
227
|
-
return activeOnly ? rows.filter(row => isActive(row)) : rows;
|
|
228
|
-
},
|
|
229
|
-
|
|
230
|
-
async getBlockInfo(ip) {
|
|
231
|
-
return rawRow(ip);
|
|
232
|
-
},
|
|
233
|
-
|
|
234
|
-
async cleanupExpired(now = Date.now() / 1000) {
|
|
235
|
-
if (await initialize()) {
|
|
236
|
-
try {
|
|
237
|
-
// Evaluate expiry in the DELETE itself, against the current row.
|
|
238
|
-
return await db('blocked_ips').where('permanent', false)
|
|
239
|
-
.whereNotNull('reputation_reason').whereNot('reputation_reason', '')
|
|
240
|
-
.where('expires_at', '>', 0).where('expires_at', '<=', now).del();
|
|
241
|
-
} catch (err) {
|
|
242
|
-
dbAvailable = false;
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
return csvStore.updateRows(csvPath, headers, current => {
|
|
246
|
-
const rows = current.map(normalizeRow);
|
|
247
|
-
const active = rows.filter(row => isActive(row, now));
|
|
248
|
-
return { rows: active.map(serializeRow), result: rows.length - active.length };
|
|
249
|
-
});
|
|
250
|
-
},
|
|
251
|
-
|
|
252
|
-
async getStatistics() {
|
|
253
|
-
const all = await this.getBlockedIPs({ activeOnly: false });
|
|
254
|
-
const active = all.filter(row => isActive(row));
|
|
255
|
-
const reasonCounts = {};
|
|
256
|
-
active.forEach(row => { reasonCounts[row.reason] = (reasonCounts[row.reason] || 0) + 1; });
|
|
257
|
-
return {
|
|
258
|
-
total: all.length,
|
|
259
|
-
active: active.length,
|
|
260
|
-
expired: all.length - active.length,
|
|
261
|
-
permanent: active.filter(row => row.permanent).length,
|
|
262
|
-
temporary: active.filter(row => !row.permanent).length,
|
|
263
|
-
average_score: active.length ? active.reduce((sum, row) => sum + row.score, 0) / active.length : 0,
|
|
264
|
-
reason_counts: reasonCounts
|
|
265
|
-
};
|
|
266
|
-
},
|
|
267
|
-
|
|
268
|
-
async getRecentBlocks(hours = 24) {
|
|
269
|
-
const cutoff = Date.now() / 1000 - Number(hours) * 3600;
|
|
270
|
-
return (await this.getBlockedIPs()).filter(row => row.blocked_at >= cutoff);
|
|
271
|
-
},
|
|
272
|
-
|
|
273
|
-
async getTopBlockedReasons(limit = 10) {
|
|
274
|
-
const stats = await this.getStatistics();
|
|
275
|
-
return Object.entries(stats.reason_counts)
|
|
276
|
-
.sort((a, b) => b[1] - a[1])
|
|
277
|
-
.slice(0, Number(limit))
|
|
278
|
-
.map(([reason, count]) => ({ reason, count }));
|
|
279
|
-
},
|
|
280
|
-
|
|
281
|
-
async bulkBlock(ips, reason, options = {}) {
|
|
282
|
-
const pairs = await Promise.all((ips || []).map(async ip => [ip, await this.block(ip, reason, options)]));
|
|
283
|
-
return Object.fromEntries(pairs);
|
|
284
|
-
},
|
|
285
|
-
|
|
286
|
-
async bulkUnblock(ips) {
|
|
287
|
-
const pairs = await Promise.all((ips || []).map(async ip => [ip, await this.unblock(ip)]));
|
|
288
|
-
return Object.fromEntries(pairs);
|
|
289
|
-
},
|
|
290
|
-
|
|
291
|
-
async addToWhitelist(ip, reason = 'Manual whitelist') {
|
|
292
|
-
const exemptionStore = require('./exemptionStore');
|
|
293
|
-
await exemptionStore.addIp(ip, reason);
|
|
294
|
-
await this.unblock(ip);
|
|
295
|
-
return true;
|
|
296
|
-
},
|
|
297
|
-
|
|
298
|
-
async removeFromWhitelist(ip) {
|
|
299
|
-
return require('./exemptionStore').removeIp(ip);
|
|
300
|
-
},
|
|
301
|
-
|
|
302
|
-
async isWhitelisted(ip) {
|
|
303
|
-
return require('./exemptionStore').isIpExempt(ip);
|
|
304
|
-
},
|
|
305
|
-
|
|
306
|
-
async getWhitelist() {
|
|
307
|
-
const exemptionStore = require('./exemptionStore');
|
|
308
|
-
return { ips: await exemptionStore.listIps(), paths: await exemptionStore.listPaths() };
|
|
309
|
-
},
|
|
310
|
-
|
|
311
|
-
async migrateLegacy({ duration = null, now = Date.now() / 1000 } = {}) {
|
|
312
|
-
const rows = await this.getBlockedIPs({ activeOnly: false });
|
|
313
|
-
let changed = 0;
|
|
314
|
-
for (const original of rows) {
|
|
315
|
-
if (original.reputation_reason && original.reputation_reason !== 'legacy_blacklist') continue;
|
|
316
|
-
const row = normalizeRow(original);
|
|
317
|
-
row.reputation_reason = duration ? 'legacy_blacklist_converted' : 'legacy_blacklist';
|
|
318
|
-
row.permanent = !duration;
|
|
319
|
-
row.duration = duration || null;
|
|
320
|
-
row.expires_at = duration ? Number(now) + Number(duration) : null;
|
|
321
|
-
await saveRow(row);
|
|
322
|
-
changed += 1;
|
|
323
|
-
}
|
|
324
|
-
return { total: rows.length, changed };
|
|
325
|
-
},
|
|
326
|
-
|
|
327
|
-
async exportRecords() {
|
|
328
|
-
return this.getBlockedIPs({ activeOnly: false });
|
|
329
|
-
},
|
|
330
|
-
|
|
331
|
-
async importRecords(rows = []) {
|
|
332
|
-
let imported = 0;
|
|
333
|
-
for (const raw of rows) {
|
|
334
|
-
const row = normalizeRow(raw);
|
|
335
|
-
if (!row.ip_address) continue;
|
|
336
|
-
await saveRow(row);
|
|
337
|
-
imported += 1;
|
|
338
|
-
}
|
|
339
|
-
return imported;
|
|
340
|
-
},
|
|
341
|
-
|
|
342
|
-
async clear() {
|
|
343
|
-
const useDb = await initialize();
|
|
344
|
-
if (useDb) {
|
|
345
|
-
try {
|
|
346
|
-
return await db('blocked_ips').del();
|
|
347
|
-
} catch (err) {
|
|
348
|
-
dbAvailable = false;
|
|
349
|
-
}
|
|
350
|
-
}
|
|
351
|
-
|
|
352
|
-
return csvStore.updateRows(csvPath, headers, rows => ({ rows: [], result: rows.length }));
|
|
353
|
-
},
|
|
354
|
-
|
|
355
|
-
async initialize() {
|
|
356
|
-
return initialize();
|
|
357
|
-
}
|
|
358
|
-
};
|
|
1
|
+
// Compatibility import; prefer blocklistManager.
|
|
2
|
+
module.exports = require('./blocklistManager');
|