aiwaf 1.1.3 → 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/train.js CHANGED
@@ -6,8 +6,11 @@ const readline = require('readline');
6
6
  const { createIsolationForest } = require('./lib/wasmAdapter');
7
7
  const requestLogStore = require('./lib/requestLogStore');
8
8
  const modelStore = require('./lib/modelStore');
9
- const blacklistManager = require('./lib/blacklistManager');
9
+ const blocklistManager = require('./lib/blocklistManager');
10
10
  const { calculateTrainingFeatures } = require('./lib/trainingFeatures');
11
+ const { withTrainingEvidence } = require('./lib/trainingEvidence');
12
+ const TRAINING_STATE_DIR = process.env.AIWAF_TRAINING_STATE_DIR
13
+ || path.dirname(process.env.AIWAF_BLOCKED_IPS_CSV_PATH || path.join('logs', 'storage', 'blocked_ips.csv'));
11
14
 
12
15
  const STATIC_KW = [
13
16
  '.php', '.xmlrpc', 'wp-', '.env', '.git', '.bak',
@@ -233,9 +236,9 @@ async function unblockExemptIps() {
233
236
  const ips = rows.map(row => row.ip_address).filter(Boolean);
234
237
  if (ips.length === 0) return;
235
238
  for (const ip of ips) {
236
- await blacklistManager.unblock(ip);
239
+ await blocklistManager.unblock(ip);
237
240
  }
238
- console.log(`Cleared ${ips.length} exempt IPs from blacklist`);
241
+ console.log(`Cleared ${ips.length} exempt IPs from blocklist`);
239
242
  } catch (err) {
240
243
  // ignore
241
244
  }
@@ -337,7 +340,7 @@ function parseLogLine(line) {
337
340
  const status = match[4];
338
341
  const rt = match[5] ? parseFloat(match[5]) : 0.0;
339
342
 
340
- let timestamp = new Date();
343
+ let timestamp = new Date(NaN);
341
344
  try {
342
345
  const cleanTimestamp = timestampStr.split(' ')[0];
343
346
  const monthMap = {
@@ -349,12 +352,16 @@ function parseLogLine(line) {
349
352
  const parts = cleanTimestamp.split(/[/:\s]/);
350
353
  if (parts.length >= 6) {
351
354
  const [day, monthText, year, hour, minute, second] = parts;
352
- const month = monthMap[monthText] || '01';
353
- timestamp = new Date(`${year}-${month}-${day}T${hour}:${minute}:${second}`);
355
+ const month = monthMap[monthText];
356
+ if (!month) return null;
357
+ const offset = timestampStr.trim().split(/\s+/)[1] || '+0000';
358
+ if (!/^[+-]\d{4}$/.test(offset)) return null;
359
+ timestamp = new Date(`${year}-${month}-${day}T${hour}:${minute}:${second}${offset.slice(0, 3)}:${offset.slice(3)}`);
354
360
  }
355
361
  } catch (err) {
356
- timestamp = new Date();
362
+ return null;
357
363
  }
364
+ if (!Number.isFinite(timestamp.getTime())) return null;
358
365
 
359
366
  return {
360
367
  ip,
@@ -367,29 +374,33 @@ function parseLogLine(line) {
367
374
 
368
375
  function parseMiddlewareEvent(event) {
369
376
  if (!event || !event.path || !event.ip) return null;
377
+ const timestamp = new Date(event.timestamp);
378
+ if (!event.timestamp || !Number.isFinite(timestamp.getTime())) return null;
370
379
 
371
380
  return {
372
381
  ip: String(event.ip),
373
382
  path: String(event.path).split('?')[0],
374
383
  status: String(event.status || 200),
375
384
  responseTime: Number(event.responseTime || 0),
376
- timestamp: event.timestamp ? new Date(event.timestamp) : new Date()
385
+ timestamp
377
386
  };
378
387
  }
379
388
 
380
389
  function parseDbEvent(event) {
381
390
  if (!event || !event.path || !event.ip) return null;
391
+ const timestamp = new Date(event.timestamp);
392
+ if (!event.timestamp || !Number.isFinite(timestamp.getTime())) return null;
382
393
  return {
383
394
  ip: String(event.ip),
384
395
  path: String(event.path).split('?')[0],
385
396
  status: String(event.status || 200),
386
397
  responseTime: Number(event.responseTime || 0),
387
- timestamp: event.timestamp ? new Date(event.timestamp) : new Date()
398
+ timestamp
388
399
  };
389
400
  }
390
401
 
391
- (async () => {
392
- try {
402
+ async function train() {
403
+ return withTrainingEvidence(TRAINING_STATE_DIR, async evidence => {
393
404
  const rawAccessLines = await readAccessLogLines();
394
405
  let parsedRequests = rawAccessLines.map(parseLogLine).filter(Boolean);
395
406
 
@@ -423,12 +434,15 @@ function parseDbEvent(event) {
423
434
  return;
424
435
  }
425
436
 
437
+ // Unstable/missing timestamps cannot establish fresh evidence on a replay.
438
+ parsedRequests = parsedRequests.filter(record => Number.isFinite(record.timestamp.getTime()));
439
+ const freshRequests = evidence.fresh(parsedRequests);
426
440
  await unblockExemptIps();
427
441
 
428
442
  const ip404Counts = new Map();
429
443
  const ip404LoginCounts = new Map();
430
444
  const ipTimes = new Map();
431
- for (const record of parsedRequests) {
445
+ for (const record of freshRequests) {
432
446
  const ts = record.timestamp instanceof Date ? record.timestamp.getTime() : new Date(record.timestamp).getTime();
433
447
  if (!ipTimes.has(record.ip)) ipTimes.set(record.ip, []);
434
448
  ipTimes.get(record.ip).push(ts);
@@ -444,7 +458,7 @@ function parseDbEvent(event) {
444
458
  if (count >= 6) {
445
459
  const loginCount = ip404LoginCounts.get(ip) || 0;
446
460
  if (count > loginCount) {
447
- await blacklistManager.block(ip, `Excessive 404s (non-login ${count}/${count + loginCount})`);
461
+ await evidence.block(ip, () => blocklistManager.block(ip, `Excessive 404s (non-login ${count}/${count + loginCount})`));
448
462
  }
449
463
  }
450
464
  }
@@ -487,8 +501,9 @@ function parseDbEvent(event) {
487
501
 
488
502
  // Identify anomalous IPs and optionally block if suspicious.
489
503
  const anomaliesByIp = new Map();
490
- parsedRequests.forEach((record, idx) => {
491
- const feature = features[idx];
504
+ const enforcementFeatures = freshRequests.length ? await calculateTrainingFeatures(freshRequests, STATIC_KW, STATUS_IDX) : [];
505
+ freshRequests.forEach((record, idx) => {
506
+ const feature = enforcementFeatures[idx];
492
507
  if (!feature) return;
493
508
  const isAnomaly = model.isAnomaly(feature, 0.5);
494
509
  if (!isAnomaly) return;
@@ -519,7 +534,7 @@ function parseDbEvent(event) {
519
534
  if (avgKwHits < 2 && max404s < 10 && avgBurst < 15 && totalRequests < 100) {
520
535
  continue;
521
536
  }
522
- await blacklistManager.block(ip, `AI anomaly + suspicious patterns (kw:${avgKwHits.toFixed(1)}, 404s:${max404s}, burst:${avgBurst.toFixed(1)})`);
537
+ await evidence.block(ip, () => blocklistManager.block(ip, `AI anomaly + suspicious patterns (kw:${avgKwHits.toFixed(1)}, 404s:${max404s}, burst:${avgBurst.toFixed(1)})`));
523
538
  }
524
539
  } else {
525
540
  console.log(`AI training skipped: ${parsedRequests.length} logs < ${MIN_AI_LOGS}`);
@@ -553,12 +568,23 @@ function parseDbEvent(event) {
553
568
  }
554
569
 
555
570
  try {
556
- const blocked = await blacklistManager.getBlockedIPs();
571
+ const blocked = await blocklistManager.getBlockedIPs();
557
572
  summarizeGeo(blocked.map(row => row.ip_address).filter(Boolean), 'Geo summary for blocked IPs (top 10):');
558
573
  } catch (err) {
559
574
  // ignore
560
575
  }
561
- } catch (err) {
562
- console.error('Training failed:', err);
576
+ });
577
+ }
578
+
579
+ module.exports = train;
580
+ async function runCLI() {
581
+ try {
582
+ await train();
583
+ process.exitCode = 0;
584
+ } catch (error) {
585
+ console.error('Training failed:', error);
586
+ process.exitCode = 1;
563
587
  }
564
- })();
588
+ }
589
+ module.exports.runCLI = runCLI;
590
+ if (require.main === module) runCLI();