aiwaf 1.0.2 → 1.1.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.
@@ -54,6 +54,7 @@ module.exports = function createAdonisMiddleware(opts = {}) {
54
54
  if (!req.path) req.path = ctx.request?.url?.() || ctx.request?.url || req.url;
55
55
  if (!req.url) req.url = req.path;
56
56
  if (!req.ip) req.ip = ctx.request?.ip?.() || ctx.request?.ip;
57
+ if (req.body === undefined && typeof ctx.request?.body === 'function') req.body = ctx.request.body();
57
58
 
58
59
  // Don't override headers - the raw request already has them from the HTTP server
59
60
 
@@ -32,16 +32,22 @@ function fastifyPlugin(fastify, opts = {}, done) {
32
32
  const middleware = createExpressMiddleware(opts);
33
33
 
34
34
  fastify.addHook('onRequest', async (request, reply) => {
35
- await new Promise(resolve => {
36
- const res = createExpressLikeResponse(reply);
37
- middleware(request.raw, res, resolve);
38
- });
35
+ const res = createExpressLikeResponse(reply);
36
+ await middleware(request.raw, res, () => {});
39
37
 
40
38
  if (reply.sent) {
41
39
  return reply;
42
40
  }
43
41
  });
44
42
 
43
+ fastify.addHook('preValidation', async (request, reply) => {
44
+ const finding = await middleware.inspectPayload({
45
+ headers: request.headers, ip: request.ip, url: request.raw.url,
46
+ body: request.body, query: request.query, aiwafRoute: request.raw.aiwafRoute
47
+ });
48
+ if (finding) return reply.code(finding.status).send({ error: finding.rule });
49
+ });
50
+
45
51
  done();
46
52
  }
47
53
 
package/lib/hapiPlugin.js CHANGED
@@ -1,4 +1,5 @@
1
1
  const createExpressMiddleware = require('./wafMiddleware');
2
+ const { version } = require('../package.json');
2
3
 
3
4
  function createExpressLikeResponse(h, rawRes) {
4
5
  const res = {
@@ -45,10 +46,19 @@ function createExpressLikeResponse(h, rawRes) {
45
46
 
46
47
  module.exports = {
47
48
  name: 'aiwaf',
48
- version: '1.0.0',
49
+ version,
49
50
  register: async (server, opts = {}) => {
50
51
  const middleware = createExpressMiddleware(opts);
51
52
 
53
+ server.ext('onPreHandler', async (request, h) => {
54
+ const finding = await middleware.inspectPayload({
55
+ headers: request.headers, ip: request.info?.remoteAddress,
56
+ path: request.path, url: request.url?.href,
57
+ body: request.payload, query: request.query, aiwafRoute: request.raw.req.aiwafRoute
58
+ });
59
+ return finding ? h.response({ error: finding.rule }).code(finding.status).takeover() : h.continue;
60
+ });
61
+
52
62
  server.ext('onRequest', async (request, h) => {
53
63
  const res = createExpressLikeResponse(h, request.raw.res);
54
64
  const req = request.raw.req;
@@ -41,6 +41,8 @@ module.exports = function createKoaMiddleware(opts = {}) {
41
41
  if (!req.path) req.path = ctx.path;
42
42
  if (!req.url) req.url = ctx.url;
43
43
  if (!req.ip) req.ip = ctx.ip;
44
+ if (req.body === undefined) req.body = ctx.request?.body;
45
+ if (req.query === undefined) req.query = ctx.query;
44
46
 
45
47
  // Don't override headers - use what's already on the raw request
46
48
  // ctx.headers is Koa's parsed version, but req.headers from Node.js has the originals
@@ -0,0 +1,61 @@
1
+ // Deterministic, bounded signatures. Findings never include request values.
2
+ const RULES = [
3
+ ['sql_union_select', /\bunion\s+(?:all\s+)?select\b/i],
4
+ ['sql_boolean_tautology', /['"`]\s*(?:or|and)\s+(?:true\b|\d+\s*=\s*\d+|['"][^'"\r\n]{0,80}['"]\s*=\s*['"])/i],
5
+ ['sql_quote_comment', /['"`]\s*(?:--|#)/],
6
+ ['sql_stacked_statement', /;\s*(?:drop\s+table|delete\s+from|insert\s+into|update\s+\w+\s+set)\b/i]
7
+ ];
8
+
9
+ function createInspector(options = {}) {
10
+ const mode = String(options.AIWAF_SQL_INJECTION_MODE ?? process.env.AIWAF_SQL_INJECTION_MODE ?? 'block').toLowerCase();
11
+ if (!['block', 'monitor', 'off'].includes(mode)) throw new Error('Invalid AIWAF_SQL_INJECTION_MODE');
12
+ const maxBytes = Number(options.AIWAF_PAYLOAD_MAX_BYTES ?? process.env.AIWAF_PAYLOAD_MAX_BYTES ?? 65536);
13
+ if (!Number.isInteger(maxBytes) || maxBytes < 1 || maxBytes > 1048576) throw new Error('AIWAF_PAYLOAD_MAX_BYTES must be 1..1048576');
14
+ return function inspect(req) {
15
+ if (mode === 'off') return null;
16
+ const stack = [[req.body, 0], [req.query, 0]];
17
+ // Also handles raw Node requests whose framework has not populated query.
18
+ const query = String(req.originalUrl || req.url || '').split('?').slice(1).join('?');
19
+ if (query) stack.push([query, 0]);
20
+ let bytes = 0, nodes = 0;
21
+ const seen = new Set();
22
+ const finding = (rule, status = 403) => ({ rule, status, mode });
23
+ while (stack.length) {
24
+ const [value, depth] = stack.pop();
25
+ if (++nodes > 4096 || depth > 16) return finding('payload_inspection_limit', 413);
26
+ if (value === undefined || value === null) continue;
27
+ // Frameworks may expose an unparsed upload stream; never traverse or consume it.
28
+ if (typeof value.pipe === 'function') continue;
29
+ if (Buffer.isBuffer(value)) {
30
+ if (value.length + bytes > maxBytes) return finding('payload_inspection_limit', 413);
31
+ stack.push([value.toString('utf8'), depth + 1]);
32
+ } else if (typeof value === 'object') {
33
+ if (seen.has(value)) return finding('payload_inspection_limit', 413);
34
+ seen.add(value);
35
+ for (const [key, item] of Object.entries(value)) {
36
+ stack.push([key, depth + 1], [item, depth + 1]);
37
+ if (stack.length > 4096) return finding('payload_inspection_limit', 413);
38
+ }
39
+ } else if (typeof value === 'string') {
40
+ bytes += Buffer.byteLength(value);
41
+ if (bytes > maxBytes) return finding('payload_inspection_limit', 413);
42
+ let normalized = value;
43
+ for (let round = 0; round < 2; round++) {
44
+ try { normalized = decodeURIComponent(normalized.replace(/\+/g, ' ')); } catch (_) { break; }
45
+ }
46
+ // Decode serialized JSON escapes before signature matching.
47
+ if (/^\s*[\[{]/.test(normalized)) {
48
+ try {
49
+ const parsed = JSON.parse(normalized);
50
+ stack.push([parsed, depth + 1]);
51
+ } catch (_) { /* Non-JSON strings still receive signature checks. */ }
52
+ }
53
+ normalized = normalized.replace(/\/\*[\s\S]*?\*\//g, ' ');
54
+ for (const [rule, pattern] of RULES) if (pattern.test(normalized)) return finding(rule);
55
+ }
56
+ }
57
+ return null;
58
+ };
59
+ }
60
+
61
+ module.exports = { createInspector };
@@ -1,4 +1,12 @@
1
- const { extractWasmTrainingFeatures } = require('./wasmAdapter');
1
+ const { extractWasmTrainingFeatures, extractWasmRawTrainingFeatures } = require('./wasmAdapter');
2
+
3
+ function modelFeaturesFromRust(features, expectedLength) {
4
+ if (!Array.isArray(features) || features.length !== expectedLength
5
+ || !features.every(rec => rec && Number.isFinite(Number(rec.burst_count)))) return null;
6
+ return features.map(rec => [
7
+ rec.path_len, rec.kw_hits, rec.status_idx, rec.resp_time, rec.burst_count, rec.total_404
8
+ ]);
9
+ }
2
10
 
3
11
  function lowerBound(values, target) {
4
12
  let left = 0;
@@ -25,6 +33,15 @@ function upperBound(values, target) {
25
33
  async function calculateTrainingFeatures(parsedRequests, staticKeywords, statusIndices) {
26
34
  const keywords = staticKeywords || [];
27
35
  const statuses = statusIndices || [];
36
+ // Direct JS-object parsing currently costs more than the prepared-record path
37
+ // on typical Node workloads; keep it opt-in until workload benchmarks improve.
38
+ if (process.env.AIWAF_EXPERIMENTAL_WASM_RAW_TRAINING === '1'
39
+ && parsedRequests.length && keywords.every(kw => kw === String(kw).toLowerCase())
40
+ && typeof extractWasmRawTrainingFeatures === 'function') {
41
+ const rawFeatures = await extractWasmRawTrainingFeatures(parsedRequests, keywords, statuses);
42
+ const mapped = modelFeaturesFromRust(rawFeatures, parsedRequests.length);
43
+ if (mapped) return mapped;
44
+ }
28
45
  const ip404Counts = new Map();
29
46
  const timestampsByIp = new Map();
30
47
 
@@ -62,12 +79,8 @@ async function calculateTrainingFeatures(parsedRequests, staticKeywords, statusI
62
79
  && keywords.every(kw => kw === String(kw).toLowerCase());
63
80
  if (canUseRust && records.length > 0) {
64
81
  const rustFeatures = await extractWasmTrainingFeatures(records, keywords);
65
- if (Array.isArray(rustFeatures) && rustFeatures.length === records.length
66
- && rustFeatures.every(rec => rec && Number.isFinite(Number(rec.burst_count)))) {
67
- return rustFeatures.map(rec => [
68
- rec.path_len, rec.kw_hits, rec.status_idx, rec.resp_time, rec.burst_count, rec.total_404
69
- ]);
70
- }
82
+ const mapped = modelFeaturesFromRust(rustFeatures, records.length);
83
+ if (mapped) return mapped;
71
84
  }
72
85
 
73
86
  return parsedRequests.map((req, index) => {
@@ -1,4 +1,5 @@
1
1
  const rateLimiter = require('./rateLimiter');
2
+ const { createInspector } = require('./sqlInjection');
2
3
  const blacklistManager = require('./blacklistManager');
3
4
  const keywordDetector = require('./keywordDetector');
4
5
  const dynamicKeyword = require('./dynamicKeyword');
@@ -129,6 +130,7 @@ function applyAutoMiddlewareDefaults(opts, enabled, rawOpts = {}) {
129
130
 
130
131
  module.exports = function aiwaf(rawOpts = {}) {
131
132
  let opts = normalizeSettings(rawOpts);
133
+ const inspectSql = createInspector(opts);
132
134
  opts.AIWAF_MIDDLEWARES = normalizedMiddlewareList(opts.AIWAF_MIDDLEWARES);
133
135
  opts.AIWAF_DISABLE_MIDDLEWARES = normalizedMiddlewareList(opts.AIWAF_DISABLE_MIDDLEWARES) || [];
134
136
  const pathRules = getEffectivePathRules(opts.AIWAF_PATH_RULES, { manifestPath: opts.AIWAF_PATH_MANIFEST });
@@ -174,7 +176,20 @@ module.exports = function aiwaf(rawOpts = {}) {
174
176
  ]).catch(() => {});
175
177
  }
176
178
 
177
- return async (req, res, next) => {
179
+ const inspectPayload = async req => {
180
+ const path = String(req.path || req.url || '/').split('?')[0].toLowerCase();
181
+ const ip = req.headers?.['x-forwarded-for']?.split(',')[0].trim() || req.ip;
182
+ const plan = createRoutePlan(path, pathRules, req.aiwafRoute || {});
183
+ if (!enabledMiddlewares.has('ip_keyword_block') || !plan.shouldApply('ip_keyword_block')
184
+ || await exemptions.isExemptRequest(ip, path)) return null;
185
+ const finding = inspectSql(req);
186
+ if (finding?.mode === 'monitor') {
187
+ (opts.logger || console).warn?.({ event: 'aiwaf.payload', rule: finding.rule, mode: finding.mode });
188
+ return null;
189
+ }
190
+ return finding;
191
+ };
192
+ const middleware = async (req, res, next) => {
178
193
  const ipHdr = req.headers['x-forwarded-for'];
179
194
  const ip = ipHdr ? ipHdr.split(',')[0].trim() : req.ip;
180
195
  const path = String(req.path || req.url || '/').toLowerCase();
@@ -258,6 +273,9 @@ module.exports = function aiwaf(rawOpts = {}) {
258
273
  return deny(403, 'blocked', 'blacklist');
259
274
  }
260
275
 
276
+ const payloadFinding = await inspectPayload(req);
277
+ if (payloadFinding) return deny(payloadFinding.status, payloadFinding.rule, payloadFinding.rule);
278
+
261
279
  if (shouldApply('header_validation')) {
262
280
  const headerReason = headerValidation.validate(req);
263
281
  if (headerReason) {
@@ -464,4 +482,6 @@ module.exports = function aiwaf(rawOpts = {}) {
464
482
 
465
483
  next();
466
484
  };
485
+ middleware.inspectPayload = inspectPayload;
486
+ return middleware;
467
487
  };
@@ -31,11 +31,15 @@ async function loadWasmFromDisk() {
31
31
  AiwafIsolationForest: bg.IsolationForest,
32
32
  IsolationForest: bg.IsolationForest,
33
33
  KeywordMatcher: bg.KeywordMatcher,
34
+ RouteMatcher: bg.RouteMatcher,
34
35
  validate_headers: bg.validate_headers,
35
36
  validate_headers_with_config: bg.validate_headers_with_config,
37
+ validate_url: bg.validate_url,
38
+ validate_content: bg.validate_content,
36
39
  analyze_recent_behavior: bg.analyze_recent_behavior,
37
40
  extract_features: bg.extract_features,
38
41
  extract_training_features: bg.extract_training_features,
42
+ extract_raw_training_features: bg.extract_raw_training_features,
39
43
  extract_features_batch_with_state: bg.extract_features_batch_with_state,
40
44
  finalize_feature_state: bg.finalize_feature_state,
41
45
  build_records: bg.build_records,
@@ -395,6 +399,16 @@ async function extractWasmTrainingFeatures(records, staticKeywords = []) {
395
399
  }
396
400
  }
397
401
 
402
+ async function extractWasmRawTrainingFeatures(records, staticKeywords = [], statusIndices = []) {
403
+ const mod = await loadWasm();
404
+ if (!mod || typeof mod.extract_raw_training_features !== 'function') return null;
405
+ try {
406
+ return mod.extract_raw_training_features(records || [], staticKeywords || [], statusIndices || []);
407
+ } catch (err) {
408
+ return null;
409
+ }
410
+ }
411
+
398
412
  async function createKeywordMatcher(keywords = []) {
399
413
  const mod = await loadWasm();
400
414
  if (!mod || typeof mod.KeywordMatcher !== 'function') return null;
@@ -410,6 +424,22 @@ async function createKeywordMatcher(keywords = []) {
410
424
  }
411
425
  }
412
426
 
427
+ async function createRouteMatcher(prefixes = []) {
428
+ const mod = await loadWasm();
429
+ if (!mod || typeof mod.RouteMatcher !== 'function') return null;
430
+ try {
431
+ const matcher = new mod.RouteMatcher(prefixes);
432
+ return {
433
+ matchIndex(path) {
434
+ const index = matcher.match_index(path);
435
+ return Number.isInteger(index) ? index : null;
436
+ }
437
+ };
438
+ } catch (err) {
439
+ return null;
440
+ }
441
+ }
442
+
413
443
  async function extractWasmFeaturesBatchWithState(records, staticKeywords = [], state = null) {
414
444
  const mod = await loadWasm();
415
445
  if (!mod || typeof mod.extract_features_batch_with_state !== 'function') return null;
@@ -502,7 +532,9 @@ module.exports = {
502
532
  analyzeRecentBehavior,
503
533
  extractWasmFeatures,
504
534
  extractWasmTrainingFeatures,
535
+ extractWasmRawTrainingFeatures,
505
536
  createKeywordMatcher,
537
+ createRouteMatcher,
506
538
  extractWasmFeaturesBatchWithState,
507
539
  finalizeWasmFeatureState,
508
540
  buildWasmRecords,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiwaf",
3
- "version": "1.0.2",
3
+ "version": "1.1.0",
4
4
  "description": "AIWAF Web Application Firewall for JavaScript applications and major Node.js frameworks",
5
5
  "main": "index.js",
6
6
  "files": [
@@ -12,7 +12,6 @@
12
12
  "utils/",
13
13
  "train.js",
14
14
  "README.md",
15
- "INSTALLATION.md",
16
15
  "LICENSE"
17
16
  ],
18
17
  "bin": {
@@ -36,14 +35,14 @@
36
35
  "aiwaf-wasm": "^0.2.0",
37
36
  "express": "^4.21.2",
38
37
  "glob": "^8.1.0",
39
- "jest": "^29.7.0",
40
38
  "knex": "^2.4.2",
41
39
  "node-cache": "^5.1.2",
42
40
  "redis": "^4.6.5",
43
- "sqlite3": "^6.0.1",
44
- "supertest": "^7.1.0"
41
+ "sqlite3": "^6.0.1"
45
42
  },
46
43
  "devDependencies": {
44
+ "jest": "^29.7.0",
45
+ "supertest": "^7.1.0",
47
46
  "fastify": "^4.29.1",
48
47
  "@hapi/hapi": "^21.3.12",
49
48
  "koa": "^2.15.4",
package/INSTALLATION.md DELETED
@@ -1,144 +0,0 @@
1
- # AIWAF-JS Installation Guide
2
-
3
- This guide covers local setup, Redis setup, training setup, and common failure modes.
4
-
5
- ## Prerequisites
6
-
7
- - Node.js 18+ recommended
8
- - npm 9+ recommended
9
- - Build tooling required by `sqlite3` (platform dependent)
10
-
11
- ## 1. Install Package
12
-
13
- For application use:
14
-
15
- ```bash
16
- npm install aiwaf
17
- ```
18
-
19
- For local development in this repository:
20
-
21
- ```bash
22
- npm install
23
- ```
24
-
25
- ## 2. Basic Integration (Express)
26
-
27
- ```js
28
- const express = require('express');
29
- const aiwaf = require('aiwaf');
30
-
31
- const app = express();
32
- app.use(express.json());
33
-
34
- app.use(aiwaf({
35
- staticKeywords: ['.php', '.env', '.git'],
36
- dynamicTopN: 10,
37
- WINDOW_SEC: 10,
38
- MAX_REQ: 20,
39
- FLOOD_REQ: 40,
40
- HONEYPOT_FIELD: 'hp_field',
41
- uuidRoutePrefix: '/user'
42
- }));
43
- ```
44
-
45
- ## 3. Optional Redis Setup
46
-
47
- Set `REDIS_URL` (or `AIWAF_REDIS_URL`) before app startup:
48
-
49
- ```bash
50
- export REDIS_URL=redis://localhost:6379
51
- ```
52
-
53
- PowerShell:
54
-
55
- ```powershell
56
- $env:REDIS_URL = 'redis://localhost:6379'
57
- ```
58
-
59
- If Redis is not configured or not reachable, AIWAF-JS falls back to in-memory behavior.
60
-
61
- ## 3.1 Optional GeoIP MMDB Setup
62
-
63
- Install MMDB reader:
64
-
65
- ```bash
66
- npm install maxmind
67
- ```
68
-
69
- Place your database at `geolock/ipinfo_lite.mmdb` or set:
70
-
71
- ```bash
72
- export AIWAF_GEO_MMDB_PATH=/absolute/path/to/ipinfo_lite.mmdb
73
- ```
74
-
75
- ## 4. Train a Model from Logs
76
-
77
- By default, trainer reads `/var/log/nginx/access.log`. Override as needed:
78
-
79
- ```bash
80
- NODE_LOG_PATH=/path/to/access.log npm run train
81
- ```
82
-
83
- Include rotated logs:
84
-
85
- ```bash
86
- NODE_LOG_GLOB='/path/to/access.log.*' npm run train
87
- ```
88
-
89
- Output model artifact:
90
-
91
- - `resources/model.json`
92
-
93
- ## 5. Verify Installation
94
-
95
- Run tests:
96
-
97
- ```bash
98
- npm test
99
- ```
100
-
101
- Check CLI wiring:
102
-
103
- ```bash
104
- npm run aiwaf -- help
105
- ```
106
-
107
- Run a minimal app and hit a known benign route (`/`) and a suspicious route (for example path with `.php`) to validate block behavior.
108
-
109
- ## 6. Troubleshooting
110
-
111
- ### `Failed to load pretrained model`
112
-
113
- - Run `npm run train` to generate `resources/model.json`.
114
- - Ensure process has read access to the `resources/` directory.
115
-
116
- ### Redis warnings or connection failures
117
-
118
- - Verify `REDIS_URL` value and Redis server health.
119
- - Runtime is designed to continue with fallback behavior.
120
-
121
- ### SQLite errors (`blocked_ips` table not found)
122
-
123
- - Ensure process can create/write `./aiwaf.sqlite`.
124
- - `blacklistManager` auto-initializes the table, but write permissions are required.
125
- - If DB logging is unavailable, enable CSV middleware logs:
126
- - `AIWAF_MIDDLEWARE_LOG_CSV=true`
127
- - `AIWAF_MIDDLEWARE_LOG_CSV_PATH=logs/aiwaf-requests.csv`
128
- - Core tables also fall back automatically to CSV files in `logs/storage/` when DB operations fail.
129
-
130
- ### `sqlite3` install/build issues
131
-
132
- - Install platform-native build dependencies and reinstall packages.
133
- - On CI/container images, ensure compiler toolchain is present.
134
-
135
- ### Training finds no logs
136
-
137
- - Confirm `NODE_LOG_PATH` exists and is readable.
138
- - If using rotation, set `NODE_LOG_GLOB` to a valid glob.
139
-
140
- ## 7. Production Notes
141
-
142
- - Prefer Redis or a custom shared cache backend for multi-instance deployments.
143
- - Place middleware after body parsing middleware if honeypot detection is required.
144
- - Review rate limits and thresholds against real traffic profiles before broad rollout.