aiwaf 1.1.5 → 1.2.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/README.md +366 -44
- package/bin/aiwaf.js +23 -4
- package/index.js +3 -0
- package/lib/geoBlocker.js +1 -7
- package/lib/hapiPlugin.js +5 -2
- package/lib/injectionAnalysis.js +600 -0
- package/lib/nativePipeline.js +370 -23
- package/lib/nativeRateCounter.js +45 -0
- package/lib/nativeSettings.js +242 -0
- package/lib/pathManifest.js +17 -1
- package/lib/routeRisks.js +181 -0
- package/lib/runtimeUtils.js +201 -6
- package/lib/settingsCompat.js +2 -0
- package/lib/sqlInjection.js +55 -49
- package/lib/wafMiddleware.js +71 -6
- package/lib/wasmAdapter.js +8 -1
- package/lib/wasmChecks.js +40 -0
- package/package.json +6 -41
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Builds native pipeline options from the options the regular aiwaf(options) middleware takes.
|
|
4
|
+
// Options are read through the same normalizeSettings(), with the same defaults and environment
|
|
5
|
+
// variables, and every option that doesn't carry over exactly is reported with the reason.
|
|
6
|
+
const { normalizeSettings } = require('./settingsCompat');
|
|
7
|
+
const { planEnabledMiddlewares, isAutoSelection } = require('./middlewarePlan');
|
|
8
|
+
const { normalizeMiddlewareName } = require('./pathRules');
|
|
9
|
+
// Loaded when first used, since nativePipeline loads this module's callers.
|
|
10
|
+
const regularStores = settings => require('./nativePipeline').regularStores(settings);
|
|
11
|
+
|
|
12
|
+
const fs = require('fs');
|
|
13
|
+
const path = require('path');
|
|
14
|
+
const crypto = require('crypto');
|
|
15
|
+
|
|
16
|
+
// The sample model shipped in resources/model.json. Its old format can't be loaded natively,
|
|
17
|
+
// and it's only a sample, so the native pipeline runs without it, as a new install does.
|
|
18
|
+
const SHIPPED_MODEL_SHA256 = '56254f9bdeba0f96bed3c72ce88ed9f1e5ad552d7510c84742fd6a349e72c091';
|
|
19
|
+
const SHIPPED_MODEL = path.join(__dirname, '..', 'resources', 'model.json');
|
|
20
|
+
|
|
21
|
+
/** What the regular middleware would load as its anomaly model, read without loading it. */
|
|
22
|
+
function settingsModel(opts) {
|
|
23
|
+
if ((opts.AIWAF_MODEL_STORAGE || 'file') !== 'file') return { kind: 'storage' };
|
|
24
|
+
const file = opts.AIWAF_MODEL_PATH || SHIPPED_MODEL;
|
|
25
|
+
let text;
|
|
26
|
+
try { text = fs.readFileSync(file); } catch (_) { return { kind: 'none', file }; }
|
|
27
|
+
if (crypto.createHash('sha256').update(text).digest('hex') === SHIPPED_MODEL_SHA256) return { kind: 'shipped', file };
|
|
28
|
+
try {
|
|
29
|
+
const data = JSON.parse(text);
|
|
30
|
+
return { kind: data?.model_type === 'aiwaf_wasm.IsolationForest' && data.model_state ? 'wasm' : 'js', file };
|
|
31
|
+
} catch (_) { return { kind: 'unreadable', file }; }
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const STAGES = ['geo_block', 'ip_keyword_block', 'rate_limit', 'ai_anomaly', 'honeypot', 'uuid_tamper', 'header_validation', 'logging'];
|
|
35
|
+
const PATTERN = /[*?[]/;
|
|
36
|
+
// Options with no native equivalent, reported when they differ from the regular defaults.
|
|
37
|
+
const NOT_CARRIED = {
|
|
38
|
+
AIWAF_ALLOWED_PATH_KEYWORDS: 'The native pipeline has its own legitimate_keywords list.',
|
|
39
|
+
AIWAF_EXEMPT_KEYWORDS: 'The native pipeline has no exempt keywords.',
|
|
40
|
+
AIWAF_LOGIN_PATH_PREFIXES: 'The native pipeline treats paths under /login and /admin/login as login forms.',
|
|
41
|
+
AIWAF_POST_ONLY_SUFFIXES: 'The native method policy is allowed_methods only.',
|
|
42
|
+
AIWAF_MAX_HEADER_BYTES: 'The native header limits are fixed.',
|
|
43
|
+
AIWAF_MAX_HEADER_COUNT: 'The native header limits are fixed.',
|
|
44
|
+
AIWAF_MAX_USER_AGENT_LENGTH: 'The native header limits are fixed.',
|
|
45
|
+
AIWAF_MAX_ACCEPT_LENGTH: 'The native header limits are fixed.',
|
|
46
|
+
AIWAF_BLOCKED_USER_AGENTS: 'The native header check has its own list of scanner user agents.',
|
|
47
|
+
AIWAF_GEO_MMDB_PATH: 'Pass a countryLookup(req) option to the native pipeline instead.',
|
|
48
|
+
AIWAF_GEO_CACHE_SECONDS: 'Country lookups come from countryLookup(req).',
|
|
49
|
+
AIWAF_GEO_CACHE_PREFIX: 'Country lookups come from countryLookup(req).',
|
|
50
|
+
AIWAF_MODEL_STORAGE: 'The native pipeline loads a model from a file only; pass a model option instead.',
|
|
51
|
+
AIWAF_MODEL_STORAGE_FALLBACK: 'The native pipeline loads a model from a file only; pass a model option instead.',
|
|
52
|
+
AIWAF_MODEL_CACHE_KEY: 'Pass a model option to the native pipeline instead.',
|
|
53
|
+
AIWAF_MODEL_CACHE_TTL: 'Pass a model option to the native pipeline instead.',
|
|
54
|
+
AIWAF_MIDDLEWARE_LOG_PATH: 'Native logs go to logPath, by default native_requests.csv in dataDir.',
|
|
55
|
+
AIWAF_MIDDLEWARE_LOG_DB: 'The native pipeline logs to a CSV file only.',
|
|
56
|
+
AIWAF_MIDDLEWARE_LOG_CSV: 'The native pipeline logs to a CSV file only.',
|
|
57
|
+
AIWAF_MIDDLEWARE_LOG_CSV_PATH: 'Native logs go to logPath, by default native_requests.csv in dataDir.',
|
|
58
|
+
AIWAF_CAPTURE_EXTENDED_REQUEST_INFO: 'The native log has fixed columns.',
|
|
59
|
+
AIWAF_EXTENDED_INFO_MAX_HEADERS: 'The native log has fixed columns.',
|
|
60
|
+
AIWAF_EXTENDED_INFO_MAX_VALUE_LENGTH: 'The native log has fixed columns.',
|
|
61
|
+
AIWAF_DYNAMIC_KEYWORDS_DB: 'The native pipeline reads learned keywords from the keyword store.',
|
|
62
|
+
AIWAF_MIN_AI_LOGS: 'Training settings don\'t apply to request handling.',
|
|
63
|
+
AIWAF_ROUTE_PLAN_VERSION: 'The native pipeline compiles path rules once at startup.',
|
|
64
|
+
AIWAF_FORCE_JSON_ERRORS: 'Native responses are always JSON.'
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
// Options that carry over exactly, reported as carried when they differ from the regular defaults.
|
|
68
|
+
const CARRIED = ['WINDOW_SEC', 'MAX_REQ', 'FLOOD_REQ', 'AIWAF_MIN_FORM_TIME', 'AIWAF_MAX_PAGE_TIME', 'HONEYPOT_FIELD',
|
|
69
|
+
'AIWAF_METHOD_POLICY_ENABLED', 'AIWAF_ALLOWED_METHODS', 'staticKeywords', 'AIWAF_ENABLE_KEYWORD_LEARNING',
|
|
70
|
+
'AIWAF_GEO_BLOCK_ENABLED', 'AIWAF_GEO_ALLOW_COUNTRIES', 'AIWAF_GEO_BLOCK_COUNTRIES', 'AIWAF_HEADER_VALIDATION',
|
|
71
|
+
'AIWAF_REQUIRED_HEADERS', 'AIWAF_HEADER_QUALITY_MIN_SCORE', 'AIWAF_EXEMPT_PATHS', 'AIWAF_EXEMPT_IPS',
|
|
72
|
+
'AIWAF_MIDDLEWARES', 'AIWAF_DISABLE_MIDDLEWARES', 'AIWAF_MIDDLEWARE_LOGGING', 'AIWAF_PATH_RULES',
|
|
73
|
+
'AIWAF_PATH_MANIFEST', 'AIWAF_INJECTION_RISK_MODE', 'dynamicTopN', 'AIWAF_EXEMPTIONS_DB', 'AIWAF_TRUSTED_PROXIES'];
|
|
74
|
+
// Where settingsCompat reads each number from, in the same order, so unreadable values can be reported.
|
|
75
|
+
const NUMBER_SOURCES = {
|
|
76
|
+
WINDOW_SEC: ['WINDOW_SEC', 'windowSec', 'AIWAF_WINDOW_SECONDS', 'env:AIWAF_RATE_WINDOW'],
|
|
77
|
+
MAX_REQ: ['MAX_REQ', 'maxReq', 'env:AIWAF_RATE_MAX'],
|
|
78
|
+
FLOOD_REQ: ['FLOOD_REQ', 'floodReq', 'env:AIWAF_RATE_FLOOD'],
|
|
79
|
+
AIWAF_MIN_FORM_TIME: ['AIWAF_MIN_FORM_TIME', 'minFormTime', 'env:AIWAF_MIN_FORM_TIME'],
|
|
80
|
+
AIWAF_MAX_PAGE_TIME: ['AIWAF_MAX_PAGE_TIME', 'maxPageTime', 'env:AIWAF_MAX_PAGE_TIME'],
|
|
81
|
+
AIWAF_HEADER_QUALITY_MIN_SCORE: ['AIWAF_HEADER_QUALITY_MIN_SCORE', 'headerQualityMinScore', 'env:AIWAF_HEADER_QUALITY_MIN_SCORE']
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
85
|
+
const headerName = name => (String(name).toUpperCase().startsWith('HTTP_')
|
|
86
|
+
? String(name).toUpperCase() : `HTTP_${String(name).toUpperCase().replace(/-/g, '_')}`);
|
|
87
|
+
|
|
88
|
+
function nativeOptionsFromSettings(rawOpts = {}) {
|
|
89
|
+
const opts = normalizeSettings(rawOpts);
|
|
90
|
+
const defaults = normalizeSettings({});
|
|
91
|
+
const notes = [];
|
|
92
|
+
const note = (setting, outcome, detail = '') => notes.push({ setting, outcome, detail });
|
|
93
|
+
const profile = {};
|
|
94
|
+
|
|
95
|
+
// Regular defaults differ from the native ones, so effective values are always written.
|
|
96
|
+
profile.rate_window = opts.WINDOW_SEC;
|
|
97
|
+
profile.rate_max = opts.MAX_REQ;
|
|
98
|
+
profile.rate_flood = opts.FLOOD_REQ;
|
|
99
|
+
if (profile.rate_flood < profile.rate_max) {
|
|
100
|
+
profile.rate_max = profile.rate_flood;
|
|
101
|
+
note('MAX_REQ', 'changed', `It's above FLOOD_REQ (${profile.rate_flood}), so requests were flood-blocked first. The native limit is ${profile.rate_flood}.`);
|
|
102
|
+
}
|
|
103
|
+
if (profile.rate_flood > 100000) {
|
|
104
|
+
profile.rate_flood = 100000;
|
|
105
|
+
note('FLOOD_REQ', 'changed', 'The native flood threshold is at most 100000.');
|
|
106
|
+
}
|
|
107
|
+
profile.min_form_time = opts.AIWAF_MIN_FORM_TIME;
|
|
108
|
+
if (opts.AIWAF_MAX_PAGE_TIME > 0) profile.max_page_time = opts.AIWAF_MAX_PAGE_TIME;
|
|
109
|
+
else note('AIWAF_MAX_PAGE_TIME', 'not carried', 'The native page expiry must be positive, so its default applies.');
|
|
110
|
+
profile.honeypot_field = opts.HONEYPOT_FIELD ? String(opts.HONEYPOT_FIELD) : '';
|
|
111
|
+
profile.allowed_methods = opts.AIWAF_METHOD_POLICY_ENABLED === true
|
|
112
|
+
? (opts.AIWAF_ALLOWED_METHODS || []).map(method => String(method).toUpperCase()) : [];
|
|
113
|
+
profile.static_keywords = [...(opts.staticKeywords || [])].map(String);
|
|
114
|
+
profile.learning = opts.AIWAF_ENABLE_KEYWORD_LEARNING !== false;
|
|
115
|
+
profile.geo_allow = [...(opts.AIWAF_GEO_ALLOW_COUNTRIES || [])];
|
|
116
|
+
profile.geo_block = [...(opts.AIWAF_GEO_BLOCK_COUNTRIES || [])];
|
|
117
|
+
const required = opts.AIWAF_REQUIRED_HEADERS || [];
|
|
118
|
+
if (required && typeof required === 'object' && !Array.isArray(required)) {
|
|
119
|
+
profile.required_headers = (required.DEFAULT || []).map(headerName);
|
|
120
|
+
note('AIWAF_REQUIRED_HEADERS', 'changed', 'Per-method lists aren\'t supported natively, so its DEFAULT list applies to every method.');
|
|
121
|
+
} else {
|
|
122
|
+
profile.required_headers = [].concat(required).map(headerName);
|
|
123
|
+
}
|
|
124
|
+
// With no required headers, the regular check also skips the quality score.
|
|
125
|
+
profile.header_min_score = profile.required_headers.length ? opts.AIWAF_HEADER_QUALITY_MIN_SCORE : 0;
|
|
126
|
+
profile.sql_mode = String(rawOpts.AIWAF_SQL_INJECTION_MODE ?? process.env.AIWAF_SQL_INJECTION_MODE ?? 'block').toLowerCase();
|
|
127
|
+
profile.max_bytes = Number(rawOpts.AIWAF_PAYLOAD_MAX_BYTES ?? process.env.AIWAF_PAYLOAD_MAX_BYTES ?? 65536);
|
|
128
|
+
|
|
129
|
+
const paths = (opts.AIWAF_EXEMPT_PATHS || []).map(String);
|
|
130
|
+
profile.exempt_paths = paths.filter(path => !PATTERN.test(path));
|
|
131
|
+
const pathPatterns = paths.filter(path => PATTERN.test(path));
|
|
132
|
+
if (pathPatterns.length) {
|
|
133
|
+
note('AIWAF_EXEMPT_PATHS', 'changed', `The native pipeline matches literal prefixes only, so these patterns aren't exempt: ${pathPatterns.join(', ')}.`);
|
|
134
|
+
}
|
|
135
|
+
const ips = (opts.AIWAF_EXEMPT_IPS || []).map(String);
|
|
136
|
+
profile.exempt_ips = ips.filter(ip => !ip.includes('/') && !ip.includes('*'));
|
|
137
|
+
const ranges = ips.filter(ip => ip.includes('/') || ip.includes('*'));
|
|
138
|
+
if (ranges.length) {
|
|
139
|
+
note('AIWAF_EXEMPT_IPS', 'changed', `The native pipeline exempts exact addresses only, so these ranges aren't exempt: ${ranges.join(', ')}.`);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// The same stage plan as the regular middleware, then its per-stage switches.
|
|
143
|
+
const requested = Array.isArray(opts.AIWAF_MIDDLEWARES) ? opts.AIWAF_MIDDLEWARES.map(normalizeMiddlewareName) : opts.AIWAF_MIDDLEWARES;
|
|
144
|
+
const enabled = planEnabledMiddlewares({
|
|
145
|
+
orderedAvailable: STAGES, requested, disabled: (opts.AIWAF_DISABLE_MIDDLEWARES || []).map(normalizeMiddlewareName),
|
|
146
|
+
accessLog: opts.AIWAF_ACCESS_LOG, geoEnabledFlag: !!opts.AIWAF_GEO_BLOCK_ENABLED,
|
|
147
|
+
staticBlockCountries: opts.AIWAF_GEO_BLOCK_COUNTRIES, dynamicBlockCountries: []
|
|
148
|
+
});
|
|
149
|
+
const auto = isAutoSelection(requested);
|
|
150
|
+
const explicit = key => Object.hasOwn(rawOpts, key) || process.env[key] !== undefined;
|
|
151
|
+
const logging = opts.AIWAF_MIDDLEWARE_LOGGING || (auto && enabled.has('logging') && !explicit('AIWAF_MIDDLEWARE_LOGGING'));
|
|
152
|
+
if (!opts.AIWAF_HEADER_VALIDATION) enabled.delete('header_validation');
|
|
153
|
+
if (!logging) enabled.delete('logging');
|
|
154
|
+
profile.enabled = STAGES.filter(stage => enabled.has(stage));
|
|
155
|
+
if (enabled.has('logging')) {
|
|
156
|
+
note('AIWAF_MIDDLEWARE_LOGGING', 'changed', 'Requests are logged to native_requests.csv in dataDir, with the native log\'s columns.');
|
|
157
|
+
}
|
|
158
|
+
// The regular middleware's stores: the same blocks, exemptions, learned keywords and blocked
|
|
159
|
+
// countries. An older aiwaf-wasm can't use them, and then the adapter keeps its own in dataDir.
|
|
160
|
+
note('stores', 'carried');
|
|
161
|
+
|
|
162
|
+
const options = {
|
|
163
|
+
stores: regularStores({ dynamicTopN: opts.dynamicTopN, exemptionsDb: opts.AIWAF_EXEMPTIONS_DB }),
|
|
164
|
+
storesFallback: 'csv',
|
|
165
|
+
rateFailureMode: opts.AIWAF_RATE_CACHE_FAILURE_MODE,
|
|
166
|
+
// Resolved as the regular middleware resolves it, with its default trusted proxies.
|
|
167
|
+
trustedProxies: opts.AIWAF_TRUSTED_PROXIES ?? 'default',
|
|
168
|
+
pathRules: opts.AIWAF_PATH_RULES || [],
|
|
169
|
+
manifestPath: opts.AIWAF_PATH_MANIFEST,
|
|
170
|
+
injectionRiskMode: opts.AIWAF_INJECTION_RISK_MODE
|
|
171
|
+
};
|
|
172
|
+
// The regular UUID check matches one segment under uuidRoutePrefix, and asks uuidResolver.
|
|
173
|
+
const uuidPrefix = rawOpts.uuidRoutePrefix || '/user';
|
|
174
|
+
profile.uuid_prefix = `${String(uuidPrefix).replace(/\/+$/, '')}/`;
|
|
175
|
+
if (rawOpts.uuidRoutePrefix) note('uuidRoutePrefix', 'carried');
|
|
176
|
+
if (typeof rawOpts.uuidResolver === 'function') {
|
|
177
|
+
options.uuidResolver = rawOpts.uuidResolver;
|
|
178
|
+
note('uuidResolver', 'carried');
|
|
179
|
+
}
|
|
180
|
+
// The regular rate limiter counts in its cache option. A Redis client there is shared the
|
|
181
|
+
// same way natively; an older aiwaf-wasm counts in each worker instead, and warns.
|
|
182
|
+
const cache = rawOpts.cache;
|
|
183
|
+
if (cache && (typeof cache.call === 'function' || typeof cache.sendCommand === 'function')) {
|
|
184
|
+
options.rateCounter = require('./nativeRateCounter').redisRateCounter(cache);
|
|
185
|
+
options.rateCounterFallback = 'memory';
|
|
186
|
+
note('cache', 'carried');
|
|
187
|
+
} else if (cache) {
|
|
188
|
+
note('cache', 'not carried', 'Shared native rate limits need a node-redis or ioredis client, so rate limits are counted in each worker.');
|
|
189
|
+
}
|
|
190
|
+
if (opts.AIWAF_RATE_CACHE_FAILURE_MODE !== 'closed') note('AIWAF_RATE_CACHE_FAILURE_MODE', 'carried');
|
|
191
|
+
const model = settingsModel(opts);
|
|
192
|
+
if (model.kind === 'wasm') {
|
|
193
|
+
options.modelFile = model.file;
|
|
194
|
+
note('AIWAF_MODEL_PATH', 'carried');
|
|
195
|
+
} else if (model.kind === 'js' || model.kind === 'unreadable') {
|
|
196
|
+
note('AIWAF_MODEL_PATH', 'not carried', `${model.file} is in an older model format the native pipeline can't load. Retrain with: aiwaf train`);
|
|
197
|
+
} else if (model.kind === 'none' && opts.AIWAF_MODEL_PATH) {
|
|
198
|
+
note('AIWAF_MODEL_PATH', 'carried', 'No model file exists there yet, so anomaly detection runs without a model, as in the regular middleware.');
|
|
199
|
+
}
|
|
200
|
+
for (const [key, reason] of Object.entries(NOT_CARRIED)) {
|
|
201
|
+
if (!same(opts[key], defaults[key])) note(key, 'not carried', reason);
|
|
202
|
+
}
|
|
203
|
+
// A number that couldn't be read falls back to the regular default, which is what's converted.
|
|
204
|
+
for (const [key, sources] of Object.entries(NUMBER_SOURCES)) {
|
|
205
|
+
const source = sources.find(name => (name.startsWith('env:') ? process.env[name.slice(4)] : rawOpts[name]) != null
|
|
206
|
+
&& (name.startsWith('env:') ? process.env[name.slice(4)] : rawOpts[name]) !== '');
|
|
207
|
+
if (!source) continue;
|
|
208
|
+
const raw = source.startsWith('env:') ? process.env[source.slice(4)] : rawOpts[source];
|
|
209
|
+
if (!Number.isFinite(Number(raw))) {
|
|
210
|
+
note(key, 'not carried', `Its value couldn't be read (expected a number), so the regular default of ${defaults[key]} applies, as in the regular middleware.`);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
const noted = new Set(notes.map(n => n.setting));
|
|
214
|
+
for (const key of CARRIED) {
|
|
215
|
+
if (!noted.has(key) && !same(opts[key], defaults[key])) note(key, 'carried');
|
|
216
|
+
}
|
|
217
|
+
for (const key of ['AIWAF_SQL_INJECTION_MODE', 'AIWAF_PAYLOAD_MAX_BYTES']) {
|
|
218
|
+
if (rawOpts[key] !== undefined || process.env[key] !== undefined) note(key, 'carried');
|
|
219
|
+
}
|
|
220
|
+
const differences = () => notes.filter(n => n.outcome !== 'carried');
|
|
221
|
+
const report = () => {
|
|
222
|
+
const carried = notes.filter(n => n.outcome === 'carried').length;
|
|
223
|
+
return [`Native pipeline settings: ${carried} carried over unchanged.`,
|
|
224
|
+
...differences().map(n => `- ${n.setting}: ${n.outcome}. ${n.detail}`.trimEnd())].join('\n');
|
|
225
|
+
};
|
|
226
|
+
return {
|
|
227
|
+
// Ready for aiwaf.native(); profile and options are also available separately.
|
|
228
|
+
config: { ...options, profile },
|
|
229
|
+
profile,
|
|
230
|
+
options,
|
|
231
|
+
notes,
|
|
232
|
+
differences,
|
|
233
|
+
report,
|
|
234
|
+
/** Logs the report: a warning when anything differs, otherwise one info line, as in Python. */
|
|
235
|
+
log(logger = console) {
|
|
236
|
+
const write = differences().length ? logger.warn : (logger.info || logger.log);
|
|
237
|
+
write?.call(logger, report());
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
module.exports = { nativeOptionsFromSettings, settingsModel, SHIPPED_MODEL_SHA256 };
|
package/lib/pathManifest.js
CHANGED
|
@@ -477,8 +477,22 @@ function extractNestRoutes(app, routesInput = null) {
|
|
|
477
477
|
}
|
|
478
478
|
}
|
|
479
479
|
|
|
480
|
-
|
|
480
|
+
// Saves the source's injection findings into a manifest that's about to be written. A failed scan
|
|
481
|
+
// leaves the manifest without saved risks, so routes keep their normal checks.
|
|
482
|
+
function auditIntoManifest(manifest, source) {
|
|
483
|
+
if (!source) return null;
|
|
484
|
+
try {
|
|
485
|
+
const { analyzePath } = require('./injectionAnalysis');
|
|
486
|
+
return require('./routeRisks').applyReport(analyzePath(source), manifest);
|
|
487
|
+
} catch (error) {
|
|
488
|
+
console.warn(`Injection audit skipped: ${error.message || error}`);
|
|
489
|
+
return null;
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
function generateExpressManifest(app, outputPath = DEFAULT_MANIFEST_PATH, options = {}) {
|
|
481
494
|
const manifest = buildManifest({ framework: 'express', routes: extractExpressRoutes(app) });
|
|
495
|
+
auditIntoManifest(manifest, options.auditSource);
|
|
482
496
|
writeManifest(manifest, outputPath);
|
|
483
497
|
return manifest;
|
|
484
498
|
}
|
|
@@ -504,12 +518,14 @@ function generateFrameworkManifest(framework, app, outputPath = DEFAULT_MANIFEST
|
|
|
504
518
|
routes: extractor(),
|
|
505
519
|
appContext: options.appContext || {}
|
|
506
520
|
});
|
|
521
|
+
auditIntoManifest(manifest, options.auditSource);
|
|
507
522
|
writeManifest(manifest, outputPath);
|
|
508
523
|
return manifest;
|
|
509
524
|
}
|
|
510
525
|
|
|
511
526
|
module.exports = {
|
|
512
527
|
DEFAULT_MANIFEST_PATH,
|
|
528
|
+
auditIntoManifest,
|
|
513
529
|
SCHEMA_VERSION,
|
|
514
530
|
computeContextHash,
|
|
515
531
|
classifyRoute,
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Uses audit findings to check risky routes' inputs on live requests. The checks run in
|
|
4
|
+
// aiwaf-wasm. Matches are logged and, in block mode (the default), blocked. Log events never
|
|
5
|
+
// include request values.
|
|
6
|
+
const { loadManifest, writeManifest } = require('./pathManifest');
|
|
7
|
+
const { bodyBytes } = require('./sqlInjection');
|
|
8
|
+
const wasmChecks = require('./wasmChecks');
|
|
9
|
+
|
|
10
|
+
// The operations a saved finding can name. The rules for each run in aiwaf-wasm.
|
|
11
|
+
const SINKS = ['sql', 'nosql', 'command', 'path', 'ssrf', 'code', 'template', 'deserialization'];
|
|
12
|
+
|
|
13
|
+
/** Returns the first rule for this operation that matches the value. Needs aiwaf-wasm loaded. */
|
|
14
|
+
function ruleFor(sink, value) {
|
|
15
|
+
return wasmChecks.get().route_rule(String(sink), String(value)) ?? null;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Compiles a manifest's saved risks in aiwaf-wasm. Needs aiwaf-wasm loaded. */
|
|
19
|
+
function compileRisks(manifest) {
|
|
20
|
+
return new (wasmChecks.get().RouteRiskChecker)(JSON.stringify(manifest ?? null));
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// Turns a parsed query object back into name=value pairs, as in user[$ne]=1.
|
|
24
|
+
function queryString(query, prefix = '', out = []) {
|
|
25
|
+
if (query === null || query === undefined) return out;
|
|
26
|
+
if (typeof query !== 'object') {
|
|
27
|
+
out.push(`${encodeURIComponent(prefix)}=${encodeURIComponent(String(query))}`);
|
|
28
|
+
return out;
|
|
29
|
+
}
|
|
30
|
+
for (const [key, value] of Object.entries(query)) queryString(value, prefix ? `${prefix}[${key}]` : key, out);
|
|
31
|
+
return out;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Checks one request against a compiled checker and returns its matches. */
|
|
35
|
+
function inspectRisks(checker, path, query, body) {
|
|
36
|
+
const text = typeof query === 'string' ? query : queryString(query).join('&');
|
|
37
|
+
return JSON.parse(checker.inspect(String(path || '/'), text, bodyBytes(body) || Buffer.alloc(0)));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const hasRisks = manifest => Object.values((manifest && manifest.routes) || {})
|
|
41
|
+
.some(entry => entry && Array.isArray(entry.injection_risks) && entry.injection_risks.length);
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Returns a function that checks a request, or null when there's nothing to check. The function
|
|
45
|
+
* returns a blocking finding in block mode, and null otherwise.
|
|
46
|
+
*/
|
|
47
|
+
function createObserver(options = {}) {
|
|
48
|
+
const mode = String(options.AIWAF_INJECTION_RISK_MODE ?? process.env.AIWAF_INJECTION_RISK_MODE ?? 'block').trim().toLowerCase();
|
|
49
|
+
if (!['block', 'log', 'off'].includes(mode)) throw new Error('AIWAF_INJECTION_RISK_MODE must be block, log, or off');
|
|
50
|
+
if (mode === 'off') return null;
|
|
51
|
+
const manifest = loadManifest(options.AIWAF_PATH_MANIFEST || undefined);
|
|
52
|
+
if (!hasRisks(manifest)) return null;
|
|
53
|
+
let checker = null;
|
|
54
|
+
const logger = options.logger || console;
|
|
55
|
+
// Adapters can inspect twice: before and after the body is parsed.
|
|
56
|
+
const logged = new WeakMap();
|
|
57
|
+
return req => {
|
|
58
|
+
let events;
|
|
59
|
+
try {
|
|
60
|
+
const url = String(req.path || req.url || '/');
|
|
61
|
+
const raw = String(req.originalUrl || req.url || '').split('?').slice(1).join('?');
|
|
62
|
+
// Compiled on first use, after the middleware has loaded aiwaf-wasm.
|
|
63
|
+
checker = checker || compileRisks(manifest);
|
|
64
|
+
events = inspectRisks(checker, url.split('?')[0], raw || req.query, req.body);
|
|
65
|
+
} catch (_) {
|
|
66
|
+
// A failing check must not break the request. Other protections still apply.
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
if (!events.length) return null;
|
|
70
|
+
const seen = logged.get(req) || new Set();
|
|
71
|
+
logged.set(req, seen);
|
|
72
|
+
for (const event of events) {
|
|
73
|
+
const key = JSON.stringify(event);
|
|
74
|
+
if (seen.has(key)) continue;
|
|
75
|
+
seen.add(key);
|
|
76
|
+
try {
|
|
77
|
+
logger.warn?.({ event: 'aiwaf.injection_risk', mode, method: String(req.method || ''), ...event });
|
|
78
|
+
} catch (_) { /* Logging must not decide the outcome. */ }
|
|
79
|
+
}
|
|
80
|
+
return mode === 'block' ? { rule: events[0].rule, status: 403, mode: 'block' } : null;
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function inputFromSource(source) {
|
|
85
|
+
const text = String(source || '');
|
|
86
|
+
let match = /^@\w+ (.+)$/.exec(text);
|
|
87
|
+
if (match) return match[1];
|
|
88
|
+
match = /\('(.+?)'\)$/.exec(text);
|
|
89
|
+
if (match) return match[1];
|
|
90
|
+
match = /(?:\.|^request )(?:body|params|payload|query)\.([^.]+)$/.exec(text);
|
|
91
|
+
return match ? match[1] : '';
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const trimRoute = path => (path.length > 1 ? path.replace(/\/+$/, '') : path);
|
|
95
|
+
|
|
96
|
+
function fileRoute(filename) {
|
|
97
|
+
const file = String(filename).replace(/\\/g, '/');
|
|
98
|
+
let match = /(?:^|\/)pages(\/api\/.*?)(?:\/index)?\.[cm]?[jt]sx?$/.exec(file);
|
|
99
|
+
if (match) return match[1].replace(/\[\.{3}([^\]]+)\]/g, ':$1*').replace(/\[([^\]]+)\]/g, ':$1');
|
|
100
|
+
match = /(?:^|\/)app(\/.*?)\/route\.[cm]?[jt]sx?$/.exec(file);
|
|
101
|
+
return match ? match[1].replace(/\[\.{3}([^\]]+)\]/g, ':$1*').replace(/\[([^\]]+)\]/g, ':$1') : '';
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function routesFor(finding, routes) {
|
|
105
|
+
const entry = String(finding.function || '').split(' -> ')[0];
|
|
106
|
+
const paths = Object.keys(routes);
|
|
107
|
+
const fromSource = (/^\S+ (\/\S*)$/.exec(entry) || [])[1] || fileRoute(finding.file);
|
|
108
|
+
if (fromSource) {
|
|
109
|
+
const wanted = trimRoute(fromSource);
|
|
110
|
+
const exact = paths.filter(path => trimRoute(path) === wanted);
|
|
111
|
+
if (exact.length) return exact;
|
|
112
|
+
// A router mounted under a prefix. Only trust this when one route fits.
|
|
113
|
+
const mounted = paths.filter(path => trimRoute(path).endsWith(wanted));
|
|
114
|
+
if (mounted.length === 1) return mounted;
|
|
115
|
+
if (entry.includes(' ')) return [];
|
|
116
|
+
}
|
|
117
|
+
// JavaScript views are bare function names, so a name used twice can't be trusted.
|
|
118
|
+
const name = entry.split('.').pop();
|
|
119
|
+
const named = paths.filter(path => {
|
|
120
|
+
const view = String(routes[path]?.view || '').replace(/^bound /, '');
|
|
121
|
+
return view && view.split('.').pop() === name;
|
|
122
|
+
});
|
|
123
|
+
return named.length === 1 ? named : [];
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Replaces saved risks in a manifest with this report's findings, and counts the results. */
|
|
127
|
+
function applyReport(report, manifest) {
|
|
128
|
+
const routes = manifest && manifest.routes;
|
|
129
|
+
if (!routes || typeof routes !== 'object' || Array.isArray(routes)) throw new Error('The manifest has no routes');
|
|
130
|
+
for (const entry of Object.values(routes)) if (entry && typeof entry === 'object') delete entry.injection_risks;
|
|
131
|
+
let linked = 0;
|
|
132
|
+
let unlinked = 0;
|
|
133
|
+
const collected = new Map();
|
|
134
|
+
for (const finding of report.findings || []) {
|
|
135
|
+
const matches = routesFor(finding, routes);
|
|
136
|
+
if (matches.length) linked += 1;
|
|
137
|
+
else unlinked += 1;
|
|
138
|
+
for (const path of matches) {
|
|
139
|
+
const risk = { sink: String(finding.sink), input: inputFromSource(finding.source), confidence: String(finding.confidence) };
|
|
140
|
+
if (!collected.has(path)) collected.set(path, new Map());
|
|
141
|
+
collected.get(path).set(`${risk.sink}\0${risk.input}`, risk);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
for (const [path, risks] of collected) {
|
|
145
|
+
routes[path].injection_risks = [...risks.keys()].sort().map(key => risks.get(key));
|
|
146
|
+
}
|
|
147
|
+
manifest.injection_audit = {
|
|
148
|
+
generated_at: new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'),
|
|
149
|
+
files_scanned: Number(report.files_scanned || 0),
|
|
150
|
+
linked_findings: linked,
|
|
151
|
+
unlinked_findings: unlinked
|
|
152
|
+
};
|
|
153
|
+
return { routes: collected.size, linked, unlinked };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function updateManifest(report, manifestPath) {
|
|
157
|
+
const manifest = loadManifest(manifestPath);
|
|
158
|
+
if (!manifest) throw new Error(`Manifest not found or unreadable: ${manifestPath}. Generate it first with init.`);
|
|
159
|
+
const counts = applyReport(report, manifest);
|
|
160
|
+
writeManifest(manifest, manifestPath);
|
|
161
|
+
return counts;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function formatCounts(counts, manifestPath) {
|
|
165
|
+
const saved = `Saved ${counts.linked} possible injection paths to ${counts.routes} routes in ${manifestPath}.`;
|
|
166
|
+
return counts.unlinked
|
|
167
|
+
? `${saved} ${counts.unlinked} couldn't be tied to a route, so they get no route-specific checks.`
|
|
168
|
+
: saved;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
module.exports = {
|
|
172
|
+
SINKS,
|
|
173
|
+
applyReport,
|
|
174
|
+
compileRisks,
|
|
175
|
+
createObserver,
|
|
176
|
+
formatCounts,
|
|
177
|
+
inputFromSource,
|
|
178
|
+
inspectRisks,
|
|
179
|
+
ruleFor,
|
|
180
|
+
updateManifest
|
|
181
|
+
};
|