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/lib/geoStore.js
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
const path = require('path');
|
|
2
|
+
const db = require('../utils/db');
|
|
3
|
+
const csvStore = require('./csvStore');
|
|
4
|
+
|
|
5
|
+
const headers = ['id', 'country_code', 'reason', 'created_at'];
|
|
6
|
+
const csvPath = process.env.AIWAF_GEO_BLOCKED_COUNTRIES_CSV_PATH || path.join('logs', 'storage', 'geo_blocked_countries.csv');
|
|
7
|
+
|
|
8
|
+
let initialized = false;
|
|
9
|
+
let dbAvailable = true;
|
|
10
|
+
|
|
11
|
+
function normalizeCountry(value) {
|
|
12
|
+
return String(value || '').trim().toUpperCase();
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
async function initialize() {
|
|
16
|
+
if (initialized) return dbAvailable;
|
|
17
|
+
|
|
18
|
+
try {
|
|
19
|
+
const hasGeo = await db.schema.hasTable('geo_blocked_countries');
|
|
20
|
+
if (!hasGeo) {
|
|
21
|
+
await db.schema.createTable('geo_blocked_countries', table => {
|
|
22
|
+
table.increments('id').primary();
|
|
23
|
+
table.string('country_code', 2).notNullable().unique();
|
|
24
|
+
table.string('reason').defaultTo('manual');
|
|
25
|
+
table.timestamp('created_at').defaultTo(db.fn.now());
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
dbAvailable = true;
|
|
29
|
+
} catch (err) {
|
|
30
|
+
dbAvailable = false;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
if (!dbAvailable) {
|
|
34
|
+
csvStore.writeRows(csvPath, headers, csvStore.readRows(csvPath, headers));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
initialized = true;
|
|
38
|
+
return dbAvailable;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function rows() {
|
|
42
|
+
return csvStore.readRows(csvPath, headers);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
module.exports = {
|
|
46
|
+
async initialize() {
|
|
47
|
+
await initialize();
|
|
48
|
+
},
|
|
49
|
+
|
|
50
|
+
async addBlockedCountry(countryCode, reason = 'manual') {
|
|
51
|
+
const normalized = normalizeCountry(countryCode);
|
|
52
|
+
if (!normalized) return;
|
|
53
|
+
|
|
54
|
+
if (await initialize()) {
|
|
55
|
+
try {
|
|
56
|
+
await db('geo_blocked_countries').insert({ country_code: normalized, reason }).onConflict('country_code').ignore();
|
|
57
|
+
return;
|
|
58
|
+
} catch (err) {
|
|
59
|
+
dbAvailable = false;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const current = rows();
|
|
64
|
+
if (current.some(row => String(row.country_code) === normalized)) return;
|
|
65
|
+
current.push({ id: csvStore.nextId(current), country_code: normalized, reason, created_at: new Date().toISOString() });
|
|
66
|
+
csvStore.writeRows(csvPath, headers, current);
|
|
67
|
+
},
|
|
68
|
+
|
|
69
|
+
async removeBlockedCountry(countryCode) {
|
|
70
|
+
const normalized = normalizeCountry(countryCode);
|
|
71
|
+
|
|
72
|
+
if (await initialize()) {
|
|
73
|
+
try {
|
|
74
|
+
return db('geo_blocked_countries').where('country_code', normalized).del();
|
|
75
|
+
} catch (err) {
|
|
76
|
+
dbAvailable = false;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const current = rows();
|
|
81
|
+
const filtered = current.filter(row => String(row.country_code) !== normalized);
|
|
82
|
+
csvStore.writeRows(csvPath, headers, filtered);
|
|
83
|
+
return current.length - filtered.length;
|
|
84
|
+
},
|
|
85
|
+
|
|
86
|
+
async listBlockedCountries() {
|
|
87
|
+
if (await initialize()) {
|
|
88
|
+
try {
|
|
89
|
+
return db('geo_blocked_countries').select('*').orderBy('country_code', 'asc');
|
|
90
|
+
} catch (err) {
|
|
91
|
+
dbAvailable = false;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
return rows().sort((a, b) => String(a.country_code).localeCompare(String(b.country_code)));
|
|
96
|
+
},
|
|
97
|
+
|
|
98
|
+
async isBlockedCountry(countryCode) {
|
|
99
|
+
const normalized = normalizeCountry(countryCode);
|
|
100
|
+
if (await initialize()) {
|
|
101
|
+
try {
|
|
102
|
+
const row = await db('geo_blocked_countries').where('country_code', normalized).first();
|
|
103
|
+
return !!row;
|
|
104
|
+
} catch (err) {
|
|
105
|
+
dbAvailable = false;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
return rows().some(row => String(row.country_code) === normalized);
|
|
110
|
+
}
|
|
111
|
+
};
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
const createExpressMiddleware = require('./wafMiddleware');
|
|
2
|
+
|
|
3
|
+
function createExpressLikeResponse(h, rawRes) {
|
|
4
|
+
const res = {
|
|
5
|
+
locals: {},
|
|
6
|
+
on: (...args) => rawRes.on(...args),
|
|
7
|
+
get statusCode() {
|
|
8
|
+
return rawRes.statusCode;
|
|
9
|
+
},
|
|
10
|
+
set statusCode(code) {
|
|
11
|
+
rawRes.statusCode = code;
|
|
12
|
+
},
|
|
13
|
+
status(code) {
|
|
14
|
+
res._statusCode = code;
|
|
15
|
+
res._handled = true;
|
|
16
|
+
return res;
|
|
17
|
+
},
|
|
18
|
+
json(payload) {
|
|
19
|
+
res._payload = payload;
|
|
20
|
+
res._contentType = 'application/json';
|
|
21
|
+
res._handled = true;
|
|
22
|
+
return res;
|
|
23
|
+
},
|
|
24
|
+
send(payload) {
|
|
25
|
+
res._payload = payload;
|
|
26
|
+
res._handled = true;
|
|
27
|
+
return res;
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
res.toResponse = () => {
|
|
32
|
+
const response = h.response(res._payload);
|
|
33
|
+
if (res._contentType) {
|
|
34
|
+
response.type(res._contentType);
|
|
35
|
+
}
|
|
36
|
+
if (res._statusCode) {
|
|
37
|
+
response.code(res._statusCode);
|
|
38
|
+
}
|
|
39
|
+
return response;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
return res;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
module.exports = {
|
|
46
|
+
name: 'aiwaf',
|
|
47
|
+
version: '1.0.0',
|
|
48
|
+
register: async (server, opts = {}) => {
|
|
49
|
+
const middleware = createExpressMiddleware(opts);
|
|
50
|
+
|
|
51
|
+
server.ext('onRequest', async (request, h) => {
|
|
52
|
+
const res = createExpressLikeResponse(h, request.raw.res);
|
|
53
|
+
const req = request.raw.req;
|
|
54
|
+
|
|
55
|
+
// Set path and URL from Hapi's request object
|
|
56
|
+
req.path = request.path || req.path;
|
|
57
|
+
req.url = request.url?.pathname || req.url;
|
|
58
|
+
|
|
59
|
+
// For headers: prefer the framework's parsed headers, but merge them
|
|
60
|
+
// Don't try to replace req.headers entirely as it's read-only on raw requests
|
|
61
|
+
if (request.headers) {
|
|
62
|
+
// Copy headers to the req.headers object (which is read-only but properties can be added)
|
|
63
|
+
try {
|
|
64
|
+
Object.keys(request.headers).forEach(key => {
|
|
65
|
+
if (!req.headers[key]) {
|
|
66
|
+
req.headers[key] = request.headers[key];
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
} catch (err) {
|
|
70
|
+
// If we can't modify headers, continue anyway
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
req.ip = request.info?.remoteAddress || req.ip;
|
|
75
|
+
|
|
76
|
+
return new Promise(resolve => {
|
|
77
|
+
let resolved = false;
|
|
78
|
+
const finish = () => {
|
|
79
|
+
if (resolved) return;
|
|
80
|
+
resolved = true;
|
|
81
|
+
if (res._payload !== undefined || res._statusCode) {
|
|
82
|
+
resolve(res.toResponse().takeover());
|
|
83
|
+
} else {
|
|
84
|
+
resolve(h.continue);
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
const maybePromise = middleware(req, res, finish);
|
|
88
|
+
Promise.resolve(maybePromise).then(finish).catch(finish);
|
|
89
|
+
});
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
};
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
let config = {
|
|
2
|
+
enabled: false,
|
|
3
|
+
requiredHeaders: [],
|
|
4
|
+
blockedUserAgents: [],
|
|
5
|
+
minScore: 3,
|
|
6
|
+
maxHeaderBytes: 32 * 1024,
|
|
7
|
+
maxHeaderCount: 100,
|
|
8
|
+
maxUserAgentLength: 500,
|
|
9
|
+
maxAcceptLength: 4096,
|
|
10
|
+
suspiciousUserAgents: [],
|
|
11
|
+
legitimateBots: [],
|
|
12
|
+
staticExtensions: ['.css', '.js', '.png', '.jpg', '.jpeg', '.gif', '.ico', '.svg', '.woff', '.woff2', '.ttf'],
|
|
13
|
+
staticPaths: ['/static/', '/media/', '/assets/', '/favicon.ico']
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
const BROWSER_HEADERS = [
|
|
17
|
+
'accept-language',
|
|
18
|
+
'accept-encoding',
|
|
19
|
+
'connection',
|
|
20
|
+
'cache-control'
|
|
21
|
+
];
|
|
22
|
+
|
|
23
|
+
const DEFAULT_SUSPICIOUS_UA = [
|
|
24
|
+
/bot/i,
|
|
25
|
+
/crawler/i,
|
|
26
|
+
/spider/i,
|
|
27
|
+
/scraper/i,
|
|
28
|
+
/curl/i,
|
|
29
|
+
/wget/i,
|
|
30
|
+
/python/i,
|
|
31
|
+
/java/i,
|
|
32
|
+
/node/i,
|
|
33
|
+
/go-http/i,
|
|
34
|
+
/axios/i,
|
|
35
|
+
/okhttp/i,
|
|
36
|
+
/libwww/i,
|
|
37
|
+
/lwp-trivial/i,
|
|
38
|
+
/mechanize/i,
|
|
39
|
+
/requests/i,
|
|
40
|
+
/urllib/i,
|
|
41
|
+
/httpie/i,
|
|
42
|
+
/postman/i,
|
|
43
|
+
/insomnia/i,
|
|
44
|
+
/^$/,
|
|
45
|
+
/^mozilla\/4\.0$/i
|
|
46
|
+
];
|
|
47
|
+
|
|
48
|
+
const DEFAULT_LEGIT_BOTS = [
|
|
49
|
+
/googlebot/i,
|
|
50
|
+
/bingbot/i,
|
|
51
|
+
/slurp/i,
|
|
52
|
+
/duckduckbot/i,
|
|
53
|
+
/baiduspider/i,
|
|
54
|
+
/yandexbot/i,
|
|
55
|
+
/facebookexternalhit/i,
|
|
56
|
+
/twitterbot/i,
|
|
57
|
+
/linkedinbot/i,
|
|
58
|
+
/whatsapp/i,
|
|
59
|
+
/telegrambot/i,
|
|
60
|
+
/applebot/i,
|
|
61
|
+
/pingdom/i,
|
|
62
|
+
/uptimerobot/i,
|
|
63
|
+
/statuscake/i,
|
|
64
|
+
/site24x7/i
|
|
65
|
+
];
|
|
66
|
+
|
|
67
|
+
function isStaticRequest(pathname) {
|
|
68
|
+
const pathLower = String(pathname || '').toLowerCase();
|
|
69
|
+
if (config.staticExtensions.some(ext => pathLower.endsWith(ext))) return true;
|
|
70
|
+
if (config.staticPaths.some(prefix => pathLower.startsWith(prefix))) return true;
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function enforceHeaderCaps(headers) {
|
|
75
|
+
let totalBytes = 0;
|
|
76
|
+
let headerCount = 0;
|
|
77
|
+
|
|
78
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
79
|
+
headerCount += 1;
|
|
80
|
+
const valueStr = value === undefined || value === null ? '' : String(value);
|
|
81
|
+
totalBytes += String(key).length + valueStr.length;
|
|
82
|
+
|
|
83
|
+
if (totalBytes > config.maxHeaderBytes) {
|
|
84
|
+
return `header_bytes_exceeded:${config.maxHeaderBytes}`;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
if (headerCount > config.maxHeaderCount) {
|
|
89
|
+
return `header_count_exceeded:${config.maxHeaderCount}`;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const ua = headers['user-agent'];
|
|
93
|
+
if (ua && String(ua).length > config.maxUserAgentLength) {
|
|
94
|
+
return `user_agent_too_long:${config.maxUserAgentLength}`;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const accept = headers['accept'];
|
|
98
|
+
if (accept && String(accept).length > config.maxAcceptLength) {
|
|
99
|
+
return `accept_too_long:${config.maxAcceptLength}`;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function matchesPattern(list, value) {
|
|
106
|
+
return list.some(pattern => pattern.test(value));
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function checkSuspiciousCombinations(headers) {
|
|
110
|
+
const protocol = String(headers['server-protocol'] || '').toUpperCase();
|
|
111
|
+
const ua = String(headers['user-agent'] || '').toLowerCase();
|
|
112
|
+
const accept = headers['accept'];
|
|
113
|
+
|
|
114
|
+
if (protocol.startsWith('HTTP/2') && ua.includes('mozilla/4.0')) {
|
|
115
|
+
return 'http2_with_old_ua';
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
if (headers['user-agent'] && !accept) {
|
|
119
|
+
return 'ua_without_accept';
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
if (accept === '*/*' && !headers['accept-language'] && !headers['accept-encoding']) {
|
|
123
|
+
return 'generic_accept_no_locale';
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
if (headers['user-agent'] && !headers['accept-language'] && !headers['accept-encoding'] && !headers['connection']) {
|
|
127
|
+
return 'missing_browser_headers';
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
if (protocol === 'HTTP/1.0' && ua.includes('chrome')) {
|
|
131
|
+
return 'modern_browser_http10';
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function calculateHeaderQuality(headers) {
|
|
138
|
+
let score = 0;
|
|
139
|
+
const ua = headers['user-agent'];
|
|
140
|
+
const accept = headers['accept'];
|
|
141
|
+
|
|
142
|
+
if (ua) score += 2;
|
|
143
|
+
if (accept) score += 2;
|
|
144
|
+
|
|
145
|
+
for (const header of BROWSER_HEADERS) {
|
|
146
|
+
if (headers[header]) score += 1;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (headers['accept-language'] && headers['accept-encoding']) score += 1;
|
|
150
|
+
|
|
151
|
+
if (String(headers['connection'] || '').toLowerCase() === 'keep-alive') score += 1;
|
|
152
|
+
|
|
153
|
+
const acceptValue = String(accept || '').toLowerCase();
|
|
154
|
+
if (acceptValue.includes('text/html') && acceptValue.includes('application/xml')) score += 1;
|
|
155
|
+
|
|
156
|
+
return score;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
module.exports = {
|
|
160
|
+
init(opts = {}) {
|
|
161
|
+
const requiredHeaders = opts.AIWAF_REQUIRED_HEADERS || [];
|
|
162
|
+
const toRegexList = (items, fallback) => {
|
|
163
|
+
if (!items) return fallback;
|
|
164
|
+
if (!Array.isArray(items)) return fallback;
|
|
165
|
+
return items.map(item => {
|
|
166
|
+
if (item instanceof RegExp) return item;
|
|
167
|
+
return new RegExp(String(item), 'i');
|
|
168
|
+
});
|
|
169
|
+
};
|
|
170
|
+
config = {
|
|
171
|
+
enabled: !!opts.AIWAF_HEADER_VALIDATION,
|
|
172
|
+
requiredHeaders: Array.isArray(requiredHeaders)
|
|
173
|
+
? requiredHeaders.map(h => String(h).toLowerCase())
|
|
174
|
+
: (requiredHeaders && typeof requiredHeaders === 'object' ? requiredHeaders : []),
|
|
175
|
+
blockedUserAgents: (opts.AIWAF_BLOCKED_USER_AGENTS || []).map(u => String(u).toLowerCase()),
|
|
176
|
+
minScore: Number.isFinite(Number(opts.AIWAF_HEADER_QUALITY_MIN_SCORE))
|
|
177
|
+
? Number(opts.AIWAF_HEADER_QUALITY_MIN_SCORE)
|
|
178
|
+
: 3,
|
|
179
|
+
maxHeaderBytes: Number.isFinite(Number(opts.AIWAF_MAX_HEADER_BYTES))
|
|
180
|
+
? Number(opts.AIWAF_MAX_HEADER_BYTES)
|
|
181
|
+
: 32 * 1024,
|
|
182
|
+
maxHeaderCount: Number.isFinite(Number(opts.AIWAF_MAX_HEADER_COUNT))
|
|
183
|
+
? Number(opts.AIWAF_MAX_HEADER_COUNT)
|
|
184
|
+
: 100,
|
|
185
|
+
maxUserAgentLength: Number.isFinite(Number(opts.AIWAF_MAX_USER_AGENT_LENGTH))
|
|
186
|
+
? Number(opts.AIWAF_MAX_USER_AGENT_LENGTH)
|
|
187
|
+
: 500,
|
|
188
|
+
maxAcceptLength: Number.isFinite(Number(opts.AIWAF_MAX_ACCEPT_LENGTH))
|
|
189
|
+
? Number(opts.AIWAF_MAX_ACCEPT_LENGTH)
|
|
190
|
+
: 4096,
|
|
191
|
+
suspiciousUserAgents: toRegexList(opts.AIWAF_SUSPICIOUS_USER_AGENTS, DEFAULT_SUSPICIOUS_UA),
|
|
192
|
+
legitimateBots: toRegexList(opts.AIWAF_LEGITIMATE_BOTS, DEFAULT_LEGIT_BOTS),
|
|
193
|
+
staticExtensions: opts.AIWAF_STATIC_EXTENSIONS || config.staticExtensions,
|
|
194
|
+
staticPaths: opts.AIWAF_STATIC_PATHS || config.staticPaths
|
|
195
|
+
};
|
|
196
|
+
},
|
|
197
|
+
|
|
198
|
+
validate(req) {
|
|
199
|
+
if (!config.enabled) return null;
|
|
200
|
+
|
|
201
|
+
const headers = Object.fromEntries(
|
|
202
|
+
Object.entries(req.headers || {}).map(([key, value]) => [String(key).toLowerCase(), value])
|
|
203
|
+
);
|
|
204
|
+
headers['server-protocol'] = req.httpVersion ? `HTTP/${req.httpVersion}` : headers['server-protocol'];
|
|
205
|
+
|
|
206
|
+
if (process.env.AIWAF_DEBUG_HEADERS) {
|
|
207
|
+
console.error(`[HEADER-VALIDATION] headers keys: ${Object.keys(headers).join(', ')}`);
|
|
208
|
+
console.error(`[HEADER-VALIDATION] user-agent: ${headers['user-agent']}`);
|
|
209
|
+
console.error(`[HEADER-VALIDATION] accept: ${headers['accept']}`);
|
|
210
|
+
console.error(`[HEADER-VALIDATION] accept-language: ${headers['accept-language']}`);
|
|
211
|
+
console.error(`[HEADER-VALIDATION] accept-encoding: ${headers['accept-encoding']}`);
|
|
212
|
+
console.error(`[HEADER-VALIDATION] connection: ${headers['connection']}`);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
if (isStaticRequest(req.path || req.url || '')) return null;
|
|
216
|
+
|
|
217
|
+
const capReason = enforceHeaderCaps(headers);
|
|
218
|
+
if (capReason) {
|
|
219
|
+
return capReason;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
let requiredHeaders = config.requiredHeaders;
|
|
223
|
+
if (requiredHeaders && typeof requiredHeaders === 'object' && !Array.isArray(requiredHeaders)) {
|
|
224
|
+
const method = String(req.method || '').toUpperCase();
|
|
225
|
+
requiredHeaders = requiredHeaders[method] || requiredHeaders.DEFAULT || [];
|
|
226
|
+
}
|
|
227
|
+
for (const header of requiredHeaders || []) {
|
|
228
|
+
if (!headers[header]) {
|
|
229
|
+
return `missing_header:${header}`;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const ua = String(headers['user-agent'] || '').toLowerCase();
|
|
234
|
+
if (config.legitimateBots.length && matchesPattern(config.legitimateBots, ua)) {
|
|
235
|
+
return null;
|
|
236
|
+
}
|
|
237
|
+
if (config.suspiciousUserAgents.length && matchesPattern(config.suspiciousUserAgents, ua)) {
|
|
238
|
+
return 'suspicious_user_agent';
|
|
239
|
+
}
|
|
240
|
+
if (config.blockedUserAgents.some(pattern => ua.includes(pattern))) {
|
|
241
|
+
return 'blocked_user_agent';
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const comboReason = checkSuspiciousCombinations(headers);
|
|
245
|
+
if (comboReason) {
|
|
246
|
+
return `suspicious_headers:${comboReason}`;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
const minScore = (Array.isArray(requiredHeaders) && requiredHeaders.length === 0) ? 0 : config.minScore;
|
|
250
|
+
if (minScore > 0) {
|
|
251
|
+
const qualityScore = calculateHeaderQuality(headers);
|
|
252
|
+
if (qualityScore < minScore) {
|
|
253
|
+
return 'header_quality_low';
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
return null;
|
|
258
|
+
}
|
|
259
|
+
,
|
|
260
|
+
getWasmConfig(method) {
|
|
261
|
+
if (!config.enabled) return null;
|
|
262
|
+
let requiredHeaders = config.requiredHeaders;
|
|
263
|
+
if (requiredHeaders && typeof requiredHeaders === 'object' && !Array.isArray(requiredHeaders)) {
|
|
264
|
+
const normalizedMethod = String(method || '').toUpperCase();
|
|
265
|
+
requiredHeaders = requiredHeaders[normalizedMethod] || requiredHeaders.DEFAULT || [];
|
|
266
|
+
}
|
|
267
|
+
return {
|
|
268
|
+
requiredHeaders: Array.isArray(requiredHeaders) ? requiredHeaders : [],
|
|
269
|
+
minScore: (Array.isArray(requiredHeaders) && requiredHeaders.length === 0) ? 0 : config.minScore
|
|
270
|
+
};
|
|
271
|
+
},
|
|
272
|
+
isStaticRequest(pathname) {
|
|
273
|
+
return isStaticRequest(pathname);
|
|
274
|
+
}
|
|
275
|
+
};
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
let config = {
|
|
2
|
+
field: undefined,
|
|
3
|
+
minFormTimeMs: 0,
|
|
4
|
+
maxPageTimeMs: 3600 * 1000,
|
|
5
|
+
loginPathPrefixes: [
|
|
6
|
+
'/admin/login/',
|
|
7
|
+
'/login/',
|
|
8
|
+
'/accounts/login/',
|
|
9
|
+
'/auth/login/',
|
|
10
|
+
'/signin/'
|
|
11
|
+
],
|
|
12
|
+
postOnlySuffixes: [
|
|
13
|
+
'/create/',
|
|
14
|
+
'/submit/',
|
|
15
|
+
'/upload/',
|
|
16
|
+
'/delete/',
|
|
17
|
+
'/process/'
|
|
18
|
+
],
|
|
19
|
+
allowedMethods: ['GET', 'POST', 'HEAD', 'OPTIONS'],
|
|
20
|
+
methodPolicyEnabled: false
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
const lastGetByKey = new Map();
|
|
24
|
+
|
|
25
|
+
function getKey(ip, path) {
|
|
26
|
+
return `${ip || 'unknown'}`;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function isLoginPath(path) {
|
|
30
|
+
const pathLower = String(path || '').toLowerCase();
|
|
31
|
+
return config.loginPathPrefixes.some(prefix => pathLower.startsWith(prefix));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function isObviousPostOnly(path) {
|
|
35
|
+
const pathLower = String(path || '').toLowerCase();
|
|
36
|
+
return config.postOnlySuffixes.some(suffix => pathLower.endsWith(suffix));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
module.exports = {
|
|
40
|
+
init(opts = {}) {
|
|
41
|
+
config = {
|
|
42
|
+
field: opts.HONEYPOT_FIELD,
|
|
43
|
+
minFormTimeMs: Math.max(0, Number(opts.AIWAF_MIN_FORM_TIME || 0) * 1000),
|
|
44
|
+
maxPageTimeMs: Math.max(0, Number(opts.AIWAF_MAX_PAGE_TIME || 3600) * 1000),
|
|
45
|
+
loginPathPrefixes: (opts.AIWAF_LOGIN_PATH_PREFIXES || config.loginPathPrefixes).map(p => String(p)),
|
|
46
|
+
postOnlySuffixes: (opts.AIWAF_POST_ONLY_SUFFIXES || config.postOnlySuffixes).map(p => String(p)),
|
|
47
|
+
allowedMethods: (opts.AIWAF_ALLOWED_METHODS || config.allowedMethods).map(m => String(m).toUpperCase()),
|
|
48
|
+
methodPolicyEnabled: opts.AIWAF_METHOD_POLICY_ENABLED === true
|
|
49
|
+
};
|
|
50
|
+
},
|
|
51
|
+
|
|
52
|
+
evaluate(req, ip, path) {
|
|
53
|
+
const method = String(req.method || 'GET').toUpperCase();
|
|
54
|
+
const key = getKey(ip, path);
|
|
55
|
+
|
|
56
|
+
if (config.methodPolicyEnabled && !config.allowedMethods.includes(method)) {
|
|
57
|
+
return { triggered: true, reason: `method_not_allowed:${method}`, statusCode: 405, errorCode: 'blocked' };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
if (method === 'GET') {
|
|
61
|
+
if (config.methodPolicyEnabled && isObviousPostOnly(path)) {
|
|
62
|
+
return { triggered: true, reason: `get_post_only:${path}`, statusCode: 405, errorCode: 'blocked' };
|
|
63
|
+
}
|
|
64
|
+
lastGetByKey.set(key, Date.now());
|
|
65
|
+
return { triggered: false };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (config.field && req.body && req.body[config.field]) {
|
|
69
|
+
return { triggered: true, reason: 'honeypot_field' };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
if (method === 'POST' && (config.minFormTimeMs > 0 || config.maxPageTimeMs > 0)) {
|
|
73
|
+
const lastGet = lastGetByKey.get(key);
|
|
74
|
+
if (lastGet) {
|
|
75
|
+
const elapsed = Date.now() - lastGet;
|
|
76
|
+
const minTime = isLoginPath(path) ? Math.min(config.minFormTimeMs, 100) : config.minFormTimeMs;
|
|
77
|
+
|
|
78
|
+
if (minTime > 0 && elapsed < minTime) {
|
|
79
|
+
return { triggered: true, reason: 'honeypot_too_fast' };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (config.maxPageTimeMs > 0 && elapsed > config.maxPageTimeMs) {
|
|
83
|
+
lastGetByKey.delete(key);
|
|
84
|
+
return { triggered: true, reason: 'honeypot_too_slow', statusCode: 409, errorCode: 'page_expired' };
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return { triggered: false };
|
|
90
|
+
}
|
|
91
|
+
};
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
class IsolationTree {
|
|
2
|
+
constructor(depth = 0, maxDepth = 0) {
|
|
3
|
+
this.depth = depth;
|
|
4
|
+
this.maxDepth = maxDepth;
|
|
5
|
+
this.left = null;
|
|
6
|
+
this.right = null;
|
|
7
|
+
this.splitAttr = null;
|
|
8
|
+
this.splitValue = null;
|
|
9
|
+
this.size = 0;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
fit(data) {
|
|
13
|
+
this.size = data.length;
|
|
14
|
+
if (this.depth >= this.maxDepth || data.length <= 1) return;
|
|
15
|
+
const numFeatures = data[0].length;
|
|
16
|
+
this.splitAttr = Math.floor(Math.random() * numFeatures);
|
|
17
|
+
let vals = data.map(row => row[this.splitAttr]);
|
|
18
|
+
const min = Math.min(...vals), max = Math.max(...vals);
|
|
19
|
+
if (min === max) return;
|
|
20
|
+
this.splitValue = min + Math.random() * (max - min);
|
|
21
|
+
const leftData = [], rightData = [];
|
|
22
|
+
for (let row of data) {
|
|
23
|
+
(row[this.splitAttr] < this.splitValue ? leftData : rightData).push(row);
|
|
24
|
+
}
|
|
25
|
+
this.left = new IsolationTree(this.depth + 1, this.maxDepth);
|
|
26
|
+
this.right = new IsolationTree(this.depth + 1, this.maxDepth);
|
|
27
|
+
this.left.fit(leftData);
|
|
28
|
+
this.right.fit(rightData);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
pathLength(point) {
|
|
32
|
+
if (!this.left || !this.right) {
|
|
33
|
+
return this.depth + c(this.size);
|
|
34
|
+
}
|
|
35
|
+
return point[this.splitAttr] < this.splitValue
|
|
36
|
+
? this.left.pathLength(point)
|
|
37
|
+
: this.right.pathLength(point);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
serialize() {
|
|
41
|
+
return {
|
|
42
|
+
depth: this.depth,
|
|
43
|
+
maxDepth: this.maxDepth,
|
|
44
|
+
splitAttr: this.splitAttr,
|
|
45
|
+
splitValue: this.splitValue,
|
|
46
|
+
size: this.size,
|
|
47
|
+
left: this.left ? this.left.serialize() : null,
|
|
48
|
+
right: this.right ? this.right.serialize() : null
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
static deserialize(obj) {
|
|
53
|
+
const tree = new IsolationTree(obj.depth, obj.maxDepth);
|
|
54
|
+
tree.splitAttr = obj.splitAttr;
|
|
55
|
+
tree.splitValue = obj.splitValue;
|
|
56
|
+
tree.size = obj.size;
|
|
57
|
+
tree.left = obj.left ? IsolationTree.deserialize(obj.left) : null;
|
|
58
|
+
tree.right = obj.right ? IsolationTree.deserialize(obj.right) : null;
|
|
59
|
+
return tree;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Average path length
|
|
64
|
+
function c(n) {
|
|
65
|
+
if (n <= 1) return 1;
|
|
66
|
+
return 2 * (Math.log(n - 1) + 0.5772156649) - (2 * (n - 1) / n);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
class IsolationForest {
|
|
70
|
+
constructor({ nTrees = 100, sampleSize = 256 } = {}) {
|
|
71
|
+
this.nTrees = nTrees;
|
|
72
|
+
this.sampleSize = sampleSize;
|
|
73
|
+
this.trees = [];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
fit(data) {
|
|
77
|
+
const heightLimit = Math.ceil(Math.log2(this.sampleSize));
|
|
78
|
+
for (let i = 0; i < this.nTrees; i++) {
|
|
79
|
+
const sample = [];
|
|
80
|
+
for (let j = 0; j < this.sampleSize; j++) {
|
|
81
|
+
sample.push(data[Math.floor(Math.random() * data.length)]);
|
|
82
|
+
}
|
|
83
|
+
const tree = new IsolationTree(0, heightLimit);
|
|
84
|
+
tree.fit(sample);
|
|
85
|
+
this.trees.push(tree);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
anomalyScore(point) {
|
|
90
|
+
const pathLens = this.trees.map(t => t.pathLength(point));
|
|
91
|
+
const avgPath = pathLens.reduce((a, b) => a + b, 0) / this.nTrees;
|
|
92
|
+
return Math.pow(2, -avgPath / c(this.sampleSize));
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
isAnomaly(point, thresh = 0.5) {
|
|
96
|
+
return this.anomalyScore(point) > thresh;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
toJSON() {
|
|
100
|
+
return {
|
|
101
|
+
nTrees: this.nTrees,
|
|
102
|
+
sampleSize: this.sampleSize,
|
|
103
|
+
trees: this.trees.map(t => t.serialize())
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
static fromJSON(obj) {
|
|
108
|
+
const forest = new IsolationForest({
|
|
109
|
+
nTrees: obj.nTrees,
|
|
110
|
+
sampleSize: obj.sampleSize
|
|
111
|
+
});
|
|
112
|
+
forest.trees = obj.trees.map(IsolationTree.deserialize);
|
|
113
|
+
return forest;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
module.exports = { IsolationForest };
|