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
package/train.js
ADDED
|
@@ -0,0 +1,595 @@
|
|
|
1
|
+
const fs = require('fs');
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const glob = require('glob');
|
|
4
|
+
const zlib = require('zlib');
|
|
5
|
+
const readline = require('readline');
|
|
6
|
+
const { IsolationForest } = require('./lib/isolationForest');
|
|
7
|
+
const requestLogStore = require('./lib/requestLogStore');
|
|
8
|
+
const modelStore = require('./lib/modelStore');
|
|
9
|
+
const blacklistManager = require('./lib/blacklistManager');
|
|
10
|
+
|
|
11
|
+
const STATIC_KW = [
|
|
12
|
+
'.php', '.xmlrpc', 'wp-', '.env', '.git', '.bak',
|
|
13
|
+
'conflg', 'shell', 'filemanager'
|
|
14
|
+
];
|
|
15
|
+
|
|
16
|
+
const STATUS_IDX = ['200', '403', '404', '500'];
|
|
17
|
+
|
|
18
|
+
const LOG_PATH = process.env.AIWAF_ACCESS_LOG || process.env.NODE_LOG_PATH || '/var/log/nginx/access.log';
|
|
19
|
+
const LOG_GLOB = process.env.NODE_LOG_GLOB || `${LOG_PATH}.*`;
|
|
20
|
+
const MIDDLEWARE_LOG_PATH = process.env.AIWAF_MIDDLEWARE_LOG_PATH || path.join(__dirname, 'logs', 'aiwaf-requests.jsonl');
|
|
21
|
+
const MIDDLEWARE_LOG_CSV_PATH = process.env.AIWAF_MIDDLEWARE_LOG_CSV_PATH || path.join(__dirname, 'logs', 'aiwaf-requests.csv');
|
|
22
|
+
const MIN_TRAIN_LOGS = Number(process.env.AIWAF_MIN_TRAIN_LOGS || 50);
|
|
23
|
+
const MIN_AI_LOGS = Number(process.env.AIWAF_MIN_AI_LOGS || 10000);
|
|
24
|
+
const FORCE_TRAINING = ['1', 'true', 'yes', 'on'].includes(String(process.env.AIWAF_FORCE_AI_TRAINING || '').toLowerCase());
|
|
25
|
+
const ENABLE_KEYWORD_LEARNING = ['1', 'true', 'yes', 'on'].includes(String(process.env.AIWAF_ENABLE_KEYWORD_LEARNING ?? 'true').toLowerCase());
|
|
26
|
+
const DYNAMIC_TOP_N = Number(process.env.AIWAF_DYNAMIC_TOP_N || 10);
|
|
27
|
+
|
|
28
|
+
const LINE_RX = /(\d+\.\d+\.\d+\.\d+).*?\[(.*?)\].*?"(?:GET|POST|PUT|DELETE|HEAD|OPTIONS) (.*?) HTTP\/.*?" (\d{3}).*?(?:response-time=(\d+\.\d+)|$)/;
|
|
29
|
+
|
|
30
|
+
async function* readLines(file) {
|
|
31
|
+
const stream = file.endsWith('.gz')
|
|
32
|
+
? fs.createReadStream(file).pipe(zlib.createGunzip())
|
|
33
|
+
: fs.createReadStream(file);
|
|
34
|
+
const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
|
|
35
|
+
for await (const line of rl) {
|
|
36
|
+
yield line;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function readAccessLogLines() {
|
|
41
|
+
const lines = [];
|
|
42
|
+
|
|
43
|
+
if (fs.existsSync(LOG_PATH)) {
|
|
44
|
+
for await (const line of readLines(LOG_PATH)) {
|
|
45
|
+
lines.push(line);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
for (const rotatedPath of glob.sync(LOG_GLOB)) {
|
|
50
|
+
for await (const line of readLines(rotatedPath)) {
|
|
51
|
+
lines.push(line);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
return lines;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async function readMiddlewareEvents() {
|
|
59
|
+
if (!fs.existsSync(MIDDLEWARE_LOG_PATH)) return [];
|
|
60
|
+
|
|
61
|
+
const events = [];
|
|
62
|
+
for await (const line of readLines(MIDDLEWARE_LOG_PATH)) {
|
|
63
|
+
const raw = String(line || '').trim();
|
|
64
|
+
if (!raw) continue;
|
|
65
|
+
|
|
66
|
+
try {
|
|
67
|
+
const event = JSON.parse(raw);
|
|
68
|
+
events.push(event);
|
|
69
|
+
} catch (err) {
|
|
70
|
+
// Ignore malformed lines.
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return events;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async function readMiddlewareCsvEvents() {
|
|
78
|
+
if (!fs.existsSync(MIDDLEWARE_LOG_CSV_PATH)) return [];
|
|
79
|
+
|
|
80
|
+
const events = [];
|
|
81
|
+
let isFirstLine = true;
|
|
82
|
+
for await (const line of readLines(MIDDLEWARE_LOG_CSV_PATH)) {
|
|
83
|
+
const raw = String(line || '').trim();
|
|
84
|
+
if (!raw) continue;
|
|
85
|
+
if (isFirstLine) {
|
|
86
|
+
isFirstLine = false;
|
|
87
|
+
if (raw.toLowerCase().startsWith('timestamp,')) {
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const parts = raw.match(/("([^"]|"")*"|[^,]+)/g) || [];
|
|
93
|
+
const unquote = val => {
|
|
94
|
+
const trimmed = String(val || '').trim();
|
|
95
|
+
if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
|
|
96
|
+
return trimmed.slice(1, -1).replace(/""/g, '"');
|
|
97
|
+
}
|
|
98
|
+
return trimmed;
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
events.push({
|
|
102
|
+
timestamp: unquote(parts[0] || ''),
|
|
103
|
+
ip: unquote(parts[1] || ''),
|
|
104
|
+
method: unquote(parts[2] || ''),
|
|
105
|
+
path: unquote(parts[3] || ''),
|
|
106
|
+
status: unquote(parts[4] || ''),
|
|
107
|
+
responseTime: unquote(parts[5] || '')
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
return events;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async function readDbRequestLogs() {
|
|
115
|
+
try {
|
|
116
|
+
const rows = await requestLogStore.recent(20000);
|
|
117
|
+
return rows.map(row => ({
|
|
118
|
+
ip: row.ip_address,
|
|
119
|
+
path: row.path,
|
|
120
|
+
status: row.status,
|
|
121
|
+
responseTime: row.response_time_ms,
|
|
122
|
+
timestamp: row.created_at
|
|
123
|
+
}));
|
|
124
|
+
} catch (err) {
|
|
125
|
+
return [];
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function getDynamicKeywordStore() {
|
|
130
|
+
// Lazy require for easier test mocking.
|
|
131
|
+
// eslint-disable-next-line global-require
|
|
132
|
+
return require('./lib/dynamicKeywordStore');
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function getExemptionStore() {
|
|
136
|
+
// Lazy require for easier test mocking.
|
|
137
|
+
// eslint-disable-next-line global-require
|
|
138
|
+
return require('./lib/exemptionStore');
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function normalizeTokens(value) {
|
|
142
|
+
if (!value) return [];
|
|
143
|
+
if (Array.isArray(value)) return value.map(v => String(v).toLowerCase());
|
|
144
|
+
return String(value)
|
|
145
|
+
.split(',')
|
|
146
|
+
.map(v => v.trim().toLowerCase())
|
|
147
|
+
.filter(Boolean);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const LOGIN_PATH_PREFIXES = normalizeTokens(process.env.AIWAF_LOGIN_PATH_PREFIXES || '/admin/login/,/login/,/accounts/login/,/auth/login/,/signin/');
|
|
151
|
+
const GEO_MMDB_PATH = process.env.AIWAF_GEO_MMDB_PATH
|
|
152
|
+
? path.resolve(process.env.AIWAF_GEO_MMDB_PATH)
|
|
153
|
+
: path.resolve(__dirname, 'geolock', 'ipinfo_lite.mmdb');
|
|
154
|
+
|
|
155
|
+
let geoReader = null;
|
|
156
|
+
function loadGeoReader() {
|
|
157
|
+
if (geoReader || !fs.existsSync(GEO_MMDB_PATH)) return geoReader;
|
|
158
|
+
try {
|
|
159
|
+
// Optional dependency
|
|
160
|
+
// eslint-disable-next-line global-require, import/no-extraneous-dependencies
|
|
161
|
+
const maxmind = require('maxmind');
|
|
162
|
+
geoReader = maxmind.openSync(GEO_MMDB_PATH);
|
|
163
|
+
} catch (err) {
|
|
164
|
+
geoReader = null;
|
|
165
|
+
}
|
|
166
|
+
return geoReader;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function lookupCountry(ip) {
|
|
170
|
+
const reader = loadGeoReader();
|
|
171
|
+
if (!reader) return null;
|
|
172
|
+
try {
|
|
173
|
+
const result = reader.get(ip);
|
|
174
|
+
return result?.country?.iso_code || result?.registered_country?.iso_code || null;
|
|
175
|
+
} catch (err) {
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async function getExemptPaths() {
|
|
181
|
+
const fromEnv = normalizeTokens(process.env.AIWAF_EXEMPT_PATHS);
|
|
182
|
+
const fromDb = [];
|
|
183
|
+
try {
|
|
184
|
+
const exemptionStore = getExemptionStore();
|
|
185
|
+
await exemptionStore.initialize();
|
|
186
|
+
const rows = await exemptionStore.listPaths(1000);
|
|
187
|
+
rows.forEach(row => fromDb.push(String(row.path_prefix || '').toLowerCase()));
|
|
188
|
+
} catch (err) {
|
|
189
|
+
// ignore
|
|
190
|
+
}
|
|
191
|
+
return Array.from(new Set([...fromEnv, ...fromDb]));
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
async function removeExemptKeywords() {
|
|
195
|
+
const exemptTokens = new Set();
|
|
196
|
+
const exemptPaths = await getExemptPaths();
|
|
197
|
+
exemptPaths.forEach(pathVal => {
|
|
198
|
+
String(pathVal || '')
|
|
199
|
+
.split(/\W+/)
|
|
200
|
+
.filter(seg => seg.length > 3)
|
|
201
|
+
.forEach(seg => exemptTokens.add(seg.toLowerCase()));
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
normalizeTokens(process.env.AIWAF_EXEMPT_KEYWORDS).forEach(token => exemptTokens.add(token));
|
|
205
|
+
normalizeTokens(process.env.AIWAF_ALLOWED_PATH_KEYWORDS).forEach(token => exemptTokens.add(token));
|
|
206
|
+
|
|
207
|
+
for (const token of exemptTokens) {
|
|
208
|
+
const dynamicKeywordStore = getDynamicKeywordStore();
|
|
209
|
+
await dynamicKeywordStore.remove(token);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
if (exemptTokens.size > 0) {
|
|
213
|
+
console.log(`Removed ${exemptTokens.size} exempt keywords from learning`);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
async function unblockExemptIps() {
|
|
218
|
+
try {
|
|
219
|
+
const exemptionStore = getExemptionStore();
|
|
220
|
+
await exemptionStore.initialize();
|
|
221
|
+
const rows = await exemptionStore.listIps();
|
|
222
|
+
const ips = rows.map(row => row.ip_address).filter(Boolean);
|
|
223
|
+
if (ips.length === 0) return;
|
|
224
|
+
for (const ip of ips) {
|
|
225
|
+
await blacklistManager.unblock(ip);
|
|
226
|
+
}
|
|
227
|
+
console.log(`Cleared ${ips.length} exempt IPs from blacklist`);
|
|
228
|
+
} catch (err) {
|
|
229
|
+
// ignore
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function getLegitimateKeywords() {
|
|
234
|
+
const defaults = new Set([
|
|
235
|
+
'profile', 'user', 'users', 'account', 'accounts', 'settings', 'dashboard',
|
|
236
|
+
'home', 'about', 'contact', 'help', 'search', 'list', 'lists',
|
|
237
|
+
'view', 'views', 'edit', 'create', 'update', 'delete', 'detail', 'details',
|
|
238
|
+
'api', 'auth', 'login', 'logout', 'register', 'signup', 'signin',
|
|
239
|
+
'reset', 'confirm', 'activate', 'verify', 'page', 'pages',
|
|
240
|
+
'category', 'categories', 'tag', 'tags', 'post', 'posts',
|
|
241
|
+
'article', 'articles', 'blog', 'blogs', 'news', 'item', 'items',
|
|
242
|
+
'admin', 'administration', 'manage', 'manager', 'control', 'panel',
|
|
243
|
+
'config', 'configuration', 'option', 'options', 'preference', 'preferences',
|
|
244
|
+
'token', 'tokens', 'oauth', 'social', 'rest', 'framework', 'cors',
|
|
245
|
+
'debug', 'toolbar', 'extensions', 'allauth', 'crispy', 'forms',
|
|
246
|
+
'channels', 'celery', 'redis', 'cache', 'email', 'mail',
|
|
247
|
+
'endpoint', 'endpoints', 'resource', 'resources', 'data', 'export',
|
|
248
|
+
'import', 'upload', 'download', 'file', 'files', 'media', 'images',
|
|
249
|
+
'documents', 'reports', 'analytics', 'stats', 'statistics',
|
|
250
|
+
'customer', 'customers', 'client', 'clients', 'company', 'companies',
|
|
251
|
+
'department', 'departments', 'employee', 'employees', 'team', 'teams',
|
|
252
|
+
'project', 'projects', 'task', 'tasks', 'event', 'events',
|
|
253
|
+
'notification', 'notifications', 'alert', 'alerts',
|
|
254
|
+
'language', 'languages', 'locale', 'locales', 'translation', 'translations',
|
|
255
|
+
'en', 'fr', 'de', 'es', 'it', 'pt', 'ru', 'ja', 'zh', 'ko'
|
|
256
|
+
]);
|
|
257
|
+
|
|
258
|
+
normalizeTokens(process.env.AIWAF_ALLOWED_PATH_KEYWORDS).forEach(token => defaults.add(token));
|
|
259
|
+
normalizeTokens(process.env.AIWAF_EXEMPT_KEYWORDS).forEach(token => defaults.add(token));
|
|
260
|
+
return defaults;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function isMaliciousContext(path, keyword, status = '404') {
|
|
264
|
+
if (!path || !keyword) return false;
|
|
265
|
+
const pathLower = String(path).toLowerCase();
|
|
266
|
+
|
|
267
|
+
const indicators = [
|
|
268
|
+
pathLower.includes('../') || pathLower.includes('..\\'),
|
|
269
|
+
pathLower.includes('.env') || pathLower.includes('wp-admin') || pathLower.includes('phpmyadmin'),
|
|
270
|
+
pathLower.includes('backup') || pathLower.includes('database') || pathLower.includes('mysql'),
|
|
271
|
+
pathLower.includes('passwd') || pathLower.includes('shadow') || pathLower.includes('xmlrpc'),
|
|
272
|
+
pathLower.includes('shell') || pathLower.includes('cmd') || pathLower.includes('exec') || pathLower.includes('eval'),
|
|
273
|
+
pathLower.includes('union+select') || pathLower.includes('<script') || pathLower.includes('javascript:'),
|
|
274
|
+
pathLower.includes('%2e%2e') || pathLower.includes('%252e') || pathLower.includes('%c0%ae') || pathLower.includes('%3c%73%63%72%69%70%74'),
|
|
275
|
+
status === '404' && (pathLower.length > 50 || (pathLower.match(/\//g) || []).length > 10),
|
|
276
|
+
status === '404' && /[<>{}$`]/.test(pathLower)
|
|
277
|
+
];
|
|
278
|
+
|
|
279
|
+
return indicators.some(Boolean);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function extractLegitimateFromLogs(parsedRequests) {
|
|
283
|
+
const legitimate = new Set();
|
|
284
|
+
for (const record of parsedRequests) {
|
|
285
|
+
const status = String(record.status || '');
|
|
286
|
+
if (!status.startsWith('2') && !status.startsWith('3')) continue;
|
|
287
|
+
const pathLower = String(record.path || '').toLowerCase();
|
|
288
|
+
for (const seg of pathLower.split(/\W+/)) {
|
|
289
|
+
if (seg.length > 2) legitimate.add(seg);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
return legitimate;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function summarizeGeo(ips, title) {
|
|
296
|
+
if (!ips || ips.length === 0) return;
|
|
297
|
+
const counts = new Map();
|
|
298
|
+
let unknown = 0;
|
|
299
|
+
for (const ip of ips) {
|
|
300
|
+
const code = lookupCountry(ip);
|
|
301
|
+
if (!code) {
|
|
302
|
+
unknown += 1;
|
|
303
|
+
continue;
|
|
304
|
+
}
|
|
305
|
+
counts.set(code, (counts.get(code) || 0) + 1);
|
|
306
|
+
}
|
|
307
|
+
if (counts.size === 0 && unknown === 0) return;
|
|
308
|
+
|
|
309
|
+
const top = Array.from(counts.entries()).sort((a, b) => b[1] - a[1]).slice(0, 10);
|
|
310
|
+
console.log(title);
|
|
311
|
+
top.forEach(([code, count]) => {
|
|
312
|
+
console.log(` - ${code}: ${count}`);
|
|
313
|
+
});
|
|
314
|
+
if (unknown) {
|
|
315
|
+
console.log(` - UNKNOWN: ${unknown}`);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function parseLogLine(line) {
|
|
320
|
+
const match = LINE_RX.exec(line);
|
|
321
|
+
if (!match) return null;
|
|
322
|
+
|
|
323
|
+
const ip = match[1];
|
|
324
|
+
const timestampStr = match[2];
|
|
325
|
+
const uri = match[3].split('?')[0];
|
|
326
|
+
const status = match[4];
|
|
327
|
+
const rt = match[5] ? parseFloat(match[5]) : 0.0;
|
|
328
|
+
|
|
329
|
+
let timestamp = new Date();
|
|
330
|
+
try {
|
|
331
|
+
const cleanTimestamp = timestampStr.split(' ')[0];
|
|
332
|
+
const monthMap = {
|
|
333
|
+
Jan: '01', Feb: '02', Mar: '03', Apr: '04',
|
|
334
|
+
May: '05', Jun: '06', Jul: '07', Aug: '08',
|
|
335
|
+
Sep: '09', Oct: '10', Nov: '11', Dec: '12'
|
|
336
|
+
};
|
|
337
|
+
|
|
338
|
+
const parts = cleanTimestamp.split(/[/:\s]/);
|
|
339
|
+
if (parts.length >= 6) {
|
|
340
|
+
const [day, monthText, year, hour, minute, second] = parts;
|
|
341
|
+
const month = monthMap[monthText] || '01';
|
|
342
|
+
timestamp = new Date(`${year}-${month}-${day}T${hour}:${minute}:${second}`);
|
|
343
|
+
}
|
|
344
|
+
} catch (err) {
|
|
345
|
+
timestamp = new Date();
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
return {
|
|
349
|
+
ip,
|
|
350
|
+
path: uri,
|
|
351
|
+
status,
|
|
352
|
+
responseTime: rt,
|
|
353
|
+
timestamp
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function parseMiddlewareEvent(event) {
|
|
358
|
+
if (!event || !event.path || !event.ip) return null;
|
|
359
|
+
|
|
360
|
+
return {
|
|
361
|
+
ip: String(event.ip),
|
|
362
|
+
path: String(event.path).split('?')[0],
|
|
363
|
+
status: String(event.status || 200),
|
|
364
|
+
responseTime: Number(event.responseTime || 0),
|
|
365
|
+
timestamp: event.timestamp ? new Date(event.timestamp) : new Date()
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function parseDbEvent(event) {
|
|
370
|
+
if (!event || !event.path || !event.ip) return null;
|
|
371
|
+
return {
|
|
372
|
+
ip: String(event.ip),
|
|
373
|
+
path: String(event.path).split('?')[0],
|
|
374
|
+
status: String(event.status || 200),
|
|
375
|
+
responseTime: Number(event.responseTime || 0),
|
|
376
|
+
timestamp: event.timestamp ? new Date(event.timestamp) : new Date()
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
function calculateFeatures(parsedRequests) {
|
|
381
|
+
const ipRequests = new Map();
|
|
382
|
+
const ip404Counts = new Map();
|
|
383
|
+
|
|
384
|
+
for (const req of parsedRequests) {
|
|
385
|
+
if (!ipRequests.has(req.ip)) {
|
|
386
|
+
ipRequests.set(req.ip, []);
|
|
387
|
+
}
|
|
388
|
+
ipRequests.get(req.ip).push(req);
|
|
389
|
+
|
|
390
|
+
if (req.status === '404') {
|
|
391
|
+
ip404Counts.set(req.ip, (ip404Counts.get(req.ip) || 0) + 1);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
const features = [];
|
|
396
|
+
|
|
397
|
+
for (const req of parsedRequests) {
|
|
398
|
+
const pathLen = req.path.length;
|
|
399
|
+
|
|
400
|
+
const kwHits = STATIC_KW.reduce(
|
|
401
|
+
(sum, kw) => sum + (req.path.toLowerCase().includes(kw) ? 1 : 0),
|
|
402
|
+
0
|
|
403
|
+
);
|
|
404
|
+
|
|
405
|
+
const statusIdx = STATUS_IDX.indexOf(req.status) >= 0
|
|
406
|
+
? STATUS_IDX.indexOf(req.status)
|
|
407
|
+
: -1;
|
|
408
|
+
|
|
409
|
+
const respTime = req.responseTime;
|
|
410
|
+
|
|
411
|
+
const ipReqs = ipRequests.get(req.ip);
|
|
412
|
+
const burst = ipReqs.filter(item => Math.abs(item.timestamp.getTime() - req.timestamp.getTime()) <= 10000).length;
|
|
413
|
+
|
|
414
|
+
const total404 = ip404Counts.get(req.ip) || 0;
|
|
415
|
+
|
|
416
|
+
features.push([pathLen, kwHits, statusIdx, respTime, burst, total404]);
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
return features;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
(async () => {
|
|
423
|
+
try {
|
|
424
|
+
const rawAccessLines = await readAccessLogLines();
|
|
425
|
+
let parsedRequests = rawAccessLines.map(parseLogLine).filter(Boolean);
|
|
426
|
+
|
|
427
|
+
if (parsedRequests.length === 0) {
|
|
428
|
+
const middlewareEvents = await readMiddlewareEvents();
|
|
429
|
+
parsedRequests = middlewareEvents.map(parseMiddlewareEvent).filter(Boolean);
|
|
430
|
+
|
|
431
|
+
if (parsedRequests.length > 0) {
|
|
432
|
+
console.log(`Using middleware logs from ${MIDDLEWARE_LOG_PATH} (${parsedRequests.length} records)`);
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
if (parsedRequests.length === 0) {
|
|
437
|
+
const csvEvents = await readMiddlewareCsvEvents();
|
|
438
|
+
parsedRequests = csvEvents.map(parseMiddlewareEvent).filter(Boolean);
|
|
439
|
+
if (parsedRequests.length > 0) {
|
|
440
|
+
console.log(`Using middleware CSV logs from ${MIDDLEWARE_LOG_CSV_PATH} (${parsedRequests.length} records)`);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
if (parsedRequests.length === 0) {
|
|
445
|
+
const dbEvents = await readDbRequestLogs();
|
|
446
|
+
parsedRequests = dbEvents.map(parseDbEvent).filter(Boolean);
|
|
447
|
+
if (parsedRequests.length > 0) {
|
|
448
|
+
console.log(`Using request_logs table (${parsedRequests.length} records)`);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
if (parsedRequests.length === 0) {
|
|
453
|
+
console.warn('No logs found. Set NODE_LOG_PATH or enable AIWAF middleware logging.');
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
await unblockExemptIps();
|
|
458
|
+
|
|
459
|
+
const ip404Counts = new Map();
|
|
460
|
+
const ip404LoginCounts = new Map();
|
|
461
|
+
const ipTimes = new Map();
|
|
462
|
+
for (const record of parsedRequests) {
|
|
463
|
+
const ts = record.timestamp instanceof Date ? record.timestamp.getTime() : new Date(record.timestamp).getTime();
|
|
464
|
+
if (!ipTimes.has(record.ip)) ipTimes.set(record.ip, []);
|
|
465
|
+
ipTimes.get(record.ip).push(ts);
|
|
466
|
+
|
|
467
|
+
if (String(record.status) !== '404') continue;
|
|
468
|
+
const pathLower = String(record.path || '').toLowerCase();
|
|
469
|
+
const isLogin = LOGIN_PATH_PREFIXES.some(prefix => pathLower.startsWith(prefix));
|
|
470
|
+
const map = isLogin ? ip404LoginCounts : ip404Counts;
|
|
471
|
+
map.set(record.ip, (map.get(record.ip) || 0) + 1);
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
for (const [ip, count] of ip404Counts.entries()) {
|
|
475
|
+
if (count >= 6) {
|
|
476
|
+
const loginCount = ip404LoginCounts.get(ip) || 0;
|
|
477
|
+
if (count > loginCount) {
|
|
478
|
+
await blacklistManager.block(ip, `Excessive 404s (non-login ${count}/${count + loginCount})`);
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
if (parsedRequests.length < MIN_TRAIN_LOGS && !FORCE_TRAINING) {
|
|
484
|
+
console.warn(`Insufficient logs (${parsedRequests.length}) < AIWAF_MIN_TRAIN_LOGS (${MIN_TRAIN_LOGS}). Set AIWAF_FORCE_AI_TRAINING=true to override.`);
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
console.log(`Parsed ${parsedRequests.length} valid requests`);
|
|
489
|
+
|
|
490
|
+
const features = calculateFeatures(parsedRequests);
|
|
491
|
+
if (features.length === 0) {
|
|
492
|
+
console.warn('No features generated.');
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
console.log(`Generated ${features.length} feature vectors`);
|
|
497
|
+
|
|
498
|
+
await removeExemptKeywords();
|
|
499
|
+
const legitimateFromLogs = extractLegitimateFromLogs(parsedRequests);
|
|
500
|
+
|
|
501
|
+
let anomalyIps = new Set();
|
|
502
|
+
if (parsedRequests.length >= MIN_AI_LOGS || FORCE_TRAINING) {
|
|
503
|
+
const model = new IsolationForest({ nTrees: 100, sampleSize: 256 });
|
|
504
|
+
model.fit(features);
|
|
505
|
+
|
|
506
|
+
const modelData = {
|
|
507
|
+
...model.toJSON(),
|
|
508
|
+
metadata: {
|
|
509
|
+
createdAt: new Date().toISOString(),
|
|
510
|
+
samplesCount: features.length,
|
|
511
|
+
featureCount: 6,
|
|
512
|
+
version: '1.1'
|
|
513
|
+
}
|
|
514
|
+
};
|
|
515
|
+
|
|
516
|
+
await modelStore.save(process.env, modelData, modelData.metadata);
|
|
517
|
+
console.log(`Trained on ${features.length} samples`);
|
|
518
|
+
|
|
519
|
+
// Identify anomalous IPs and optionally block if suspicious.
|
|
520
|
+
const anomaliesByIp = new Map();
|
|
521
|
+
parsedRequests.forEach((record, idx) => {
|
|
522
|
+
const feature = features[idx];
|
|
523
|
+
if (!feature) return;
|
|
524
|
+
const isAnomaly = model.isAnomaly(feature, 0.5);
|
|
525
|
+
if (!isAnomaly) return;
|
|
526
|
+
const ip = record.ip;
|
|
527
|
+
if (!anomaliesByIp.has(ip)) anomaliesByIp.set(ip, []);
|
|
528
|
+
anomaliesByIp.get(ip).push(record);
|
|
529
|
+
});
|
|
530
|
+
|
|
531
|
+
anomalyIps = new Set(anomaliesByIp.keys());
|
|
532
|
+
if (anomalyIps.size > 0) {
|
|
533
|
+
console.log(`Detected ${anomalyIps.size} potentially anomalous IPs`);
|
|
534
|
+
summarizeGeo(Array.from(anomalyIps), 'Geo summary for anomalous IPs (top 10):');
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
for (const [ip, records] of anomaliesByIp.entries()) {
|
|
538
|
+
const totalRequests = records.length;
|
|
539
|
+
const max404s = records.reduce((sum, r) => sum + (String(r.status) === '404' ? 1 : 0), 0);
|
|
540
|
+
const avgKwHits = records.reduce((sum, r) => {
|
|
541
|
+
const pathLower = String(r.path || '').toLowerCase();
|
|
542
|
+
return sum + STATIC_KW.reduce((acc, kw) => acc + (pathLower.includes(kw) ? 1 : 0), 0);
|
|
543
|
+
}, 0) / totalRequests;
|
|
544
|
+
const bursts = (ipTimes.get(ip) || []).filter(ts => Date.now() - ts <= 10000).length;
|
|
545
|
+
const avgBurst = totalRequests ? bursts / totalRequests : 0;
|
|
546
|
+
|
|
547
|
+
if (max404s === 0 && avgKwHits === 0) {
|
|
548
|
+
continue;
|
|
549
|
+
}
|
|
550
|
+
if (avgKwHits < 2 && max404s < 10 && avgBurst < 15 && totalRequests < 100) {
|
|
551
|
+
continue;
|
|
552
|
+
}
|
|
553
|
+
await blacklistManager.block(ip, `AI anomaly + suspicious patterns (kw:${avgKwHits.toFixed(1)}, 404s:${max404s}, burst:${avgBurst.toFixed(1)})`);
|
|
554
|
+
}
|
|
555
|
+
} else {
|
|
556
|
+
console.log(`AI training skipped: ${parsedRequests.length} logs < ${MIN_AI_LOGS}`);
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
if (ENABLE_KEYWORD_LEARNING) {
|
|
560
|
+
const legitimate = new Set([...getLegitimateKeywords(), ...legitimateFromLogs]);
|
|
561
|
+
const tokens = new Map();
|
|
562
|
+
for (const record of parsedRequests) {
|
|
563
|
+
const status = String(record.status || '');
|
|
564
|
+
if (!status.startsWith('4') && !status.startsWith('5')) continue;
|
|
565
|
+
const pathLower = String(record.path || '').toLowerCase();
|
|
566
|
+
for (const seg of pathLower.split(/\W+/)) {
|
|
567
|
+
if (seg.length <= 3) continue;
|
|
568
|
+
if (STATIC_KW.includes(seg)) continue;
|
|
569
|
+
if (legitimate.has(seg)) continue;
|
|
570
|
+
if (!isMaliciousContext(pathLower, seg, status)) continue;
|
|
571
|
+
tokens.set(seg, (tokens.get(seg) || 0) + 1);
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
const ranked = Array.from(tokens.entries()).sort((a, b) => b[1] - a[1]).slice(0, DYNAMIC_TOP_N);
|
|
576
|
+
for (const [kw, count] of ranked) {
|
|
577
|
+
const dynamicKeywordStore = getDynamicKeywordStore();
|
|
578
|
+
await dynamicKeywordStore.add(kw, count);
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
console.log(`Learned ${ranked.length} dynamic keywords`);
|
|
582
|
+
} else {
|
|
583
|
+
console.log('Keyword learning disabled via AIWAF_ENABLE_KEYWORD_LEARNING');
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
try {
|
|
587
|
+
const blocked = await blacklistManager.getBlockedIPs();
|
|
588
|
+
summarizeGeo(blocked.map(row => row.ip_address).filter(Boolean), 'Geo summary for blocked IPs (top 10):');
|
|
589
|
+
} catch (err) {
|
|
590
|
+
// ignore
|
|
591
|
+
}
|
|
592
|
+
} catch (err) {
|
|
593
|
+
console.error('Training failed:', err);
|
|
594
|
+
}
|
|
595
|
+
})();
|
package/utils/cache.js
ADDED
package/utils/db.js
ADDED