aiwaf 1.2.4 → 1.3.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 CHANGED
@@ -39,15 +39,15 @@ the supported Redis backends when sharing limits across workers.
39
39
 
40
40
  Each package is versioned and released independently.
41
41
 
42
- Python 1.2.5, Rust/Python 0.2.12, Node.js 1.2.4, WASM 0.2.9, and Java 1.3.8 are local source targets. See the package table below and [CHANGELOG](CHANGELOG.md) for release changes.
42
+ Python 1.3.0, Rust/Python 0.2.15, Node.js 1.3.0, WASM 0.2.11, and Java 1.4.0 are local source targets. See the package table below and [CHANGELOG](CHANGELOG.md) for release changes.
43
43
 
44
44
  | Runtime | Package | Repository version | Primary use |
45
45
  | --- | --- | ---: | --- |
46
- | Python | [`aiwaf`](https://pypi.org/project/aiwaf/) | `1.2.5` | Django, Flask, and FastAPI protection |
47
- | Node.js | [`aiwaf`](https://www.npmjs.com/package/aiwaf) | `1.2.4` | Express and Node framework middleware |
48
- | Rust/Python | [`aiwaf-rust`](https://pypi.org/project/aiwaf-rust/) | `0.2.12` | Native Python acceleration and JSON model inference |
49
- | WebAssembly | [`aiwaf-wasm`](https://www.npmjs.com/package/aiwaf-wasm) | `0.2.9` | Rust detection and model primitives for JavaScript |
50
- | Java | `io.github.aiwaf-project:aiwaf-java` | `1.3.8` | Spring MVC and Jakarta Servlet protection |
46
+ | Python | [`aiwaf`](https://pypi.org/project/aiwaf/) | `1.3.0` | Django, Flask, and FastAPI protection |
47
+ | Node.js | [`aiwaf`](https://www.npmjs.com/package/aiwaf) | `1.3.0` | Express and Node framework middleware |
48
+ | Rust/Python | [`aiwaf-rust`](https://pypi.org/project/aiwaf-rust/) | `0.2.15` | Native Python acceleration and JSON model inference |
49
+ | WebAssembly | [`aiwaf-wasm`](https://www.npmjs.com/package/aiwaf-wasm) | `0.2.11` | Rust detection and model primitives for JavaScript |
50
+ | Java | `io.github.aiwaf-project:aiwaf-java` | `1.4.0` | Spring MVC and Jakarta Servlet protection |
51
51
 
52
52
  Supported framework integrations include Django, Flask, FastAPI, Express, Fastify, Hapi, Koa, NestJS, Next.js API routes, AdonisJS, Sails.js, Spring MVC, and Jakarta Servlet.
53
53
 
@@ -68,6 +68,24 @@ Supported framework integrations include Django, Flask, FastAPI, Express, Fastif
68
68
 
69
69
  The runtimes share policy intent and training feature names, but their framework adapters and model implementations remain language-native. Model artifacts are not generally interchangeable across languages.
70
70
 
71
+ ## Profiles
72
+
73
+ `AIWAF_PROFILE` sets sensible defaults with one setting, in Django and Flask settings,
74
+ FastAPI's `AIWAFConfig` (or `AIWAF(app, profile=...)`), the Node.js options, the Java config
75
+ (`profile`) or the environment. A setting you give explicitly always wins over the profile.
76
+
77
+ | Profile | What it does |
78
+ | --- | --- |
79
+ | `balanced` (default) | Every default as it is. |
80
+ | `strict` | Halves the rate and flood limits (Django, Flask, FastAPI and Java: 10 and 20 a window; Node.js: 50 and 100), turns on UUID scoring, header validation and the method policy where the runtime has them as settings, and keeps the SQL and route checks blocking. |
81
+ | `monitor` | A dry run. Every check runs, and what it would block is logged instead, as `AIWAF monitor: would block GET /.env from 203.0.113.9 with 403 (...)`. Nothing is blocked and no IP is added to the blocklist. |
82
+
83
+ Use `monitor` to try AIWAF on real traffic before turning it on. Its log lines go to the
84
+ `aiwaf.monitor` logger in Python, `console.warn` in Node.js and `com.aiwaf.monitor` in Java.
85
+ Monitor runs the regular middleware, where every block decision can be logged instead: the
86
+ automatic native pipeline stays off, and a native pipeline chosen explicitly refuses to start.
87
+ Java's request body size limit still applies.
88
+
71
89
  ## Client IP addresses and proxies
72
90
 
73
91
  Blocks, exemptions, rate limits, and geo policies all depend on the client address. Python, Node.js, and Java read `X-Forwarded-For` and `X-Real-IP` only when the connecting peer is a trusted proxy. They walk `X-Forwarded-For` from the right and stop at the first untrusted address, because anything further left is client-supplied. `CF-Connecting-IP` and other vendor headers are not read for this purpose. In Python and Node.js the walk runs in `aiwaf-rust` and `aiwaf-wasm`, which also write IPv6 addresses in canonical form.
@@ -166,17 +184,17 @@ java -cp <classpath> com.aiwaf.cli.AiwafConsole init --source src --output .aiwa
166
184
 
167
185
  AIWAF checks request values for SQL injection with a tokenizer. It tries each value as a
168
186
  bare number, inside single quotes, and inside double quotes, and flags it only when the
169
- value closes that SQL value and what follows reads as SQL. It catches `1 OR 1=1` and
170
- `1 AND SLEEP(5)`, which have no quote, and MySQL's executed comments such as
171
- `/*!50000UNION*/`. It passes text like `"Item" #3`, `o'reilly`, `union select committee`
187
+ value closes that SQL value and what follows reads as SQL. It catches a number followed by an
188
+ always-true condition or a time delay, which needs no quote, and MySQL's version comments,
189
+ whose contents MySQL executes. It passes text like `"Item" #3`, `o'reilly`, `union select committee`
172
190
  and `Drop table tennis; update your set list`.
173
191
 
174
- Text such as `union select password` on its own isn't flagged, because without a value to
175
- close it can't change a query.
192
+ SQL keywords on their own, with no value to close, aren't flagged, because they can't change a
193
+ query.
176
194
 
177
195
  Besides the query string and body, the check reads the URL path and the headers, where SQL
178
- injection also reaches applications. The path is checked one segment at a time, as in
179
- `/post/1 OR 1=1`. Cookies are checked by their names and values, and the `Referer`,
196
+ injection also reaches applications. The path is checked one segment at a time, so a SQL
197
+ condition after a post ID in the path is found. Cookies are checked by their names and values, and the `Referer`,
180
198
  `X-Original-URL` and `X-Rewrite-URL` by their path and query string. Every other header is
181
199
  checked as one value, such as `User-Agent`, `X-Forwarded-For`, `Accept-Language` or an app's own
182
200
  `X-` headers. Headers that hold credentials, framing or browser-set values aren't checked:
@@ -212,10 +230,10 @@ fails if the results get worse:
212
230
 
213
231
  CRS also matches SQL keywords and function names on their own, such as `concat(` or
214
232
  `cast(`, especially at higher paranoia levels. AIWAF flags values that break out of a
215
- SQL value, plus names that only appear in SQL such as `pg_sleep(` and `information_schema`, so
233
+ SQL value, plus names that only appear in SQL, such as delay functions and the schema catalog, so
216
234
  it misses many of those CRS fragments by design: matching them would block code snippets and
217
235
  ordinary text. Each CRS test's whole request is checked, including its path and headers. Three
218
- CRS tests marked benign carry SQL injection, such as `/post/foo/24 union all select 1,2,3 from aa`,
236
+ CRS tests marked benign carry SQL injection, such as a post path ending in a UNION query,
219
237
  because CRS only means that one rule shouldn't match them. AIWAF flags them, and the benchmark
220
238
  lists them apart from false positives.
221
239
 
@@ -223,6 +241,86 @@ The SQL tokenizer, request walker and route checks are fuzzed: for two minutes p
223
241
  each pull request, and for 30 minutes each week (`rust/fuzz`). Short random-input tests also
224
242
  run with every `cargo test`.
225
243
 
244
+ ### Remote code execution
245
+
246
+ The same payload check looks in every request value for text that runs code on the server:
247
+
248
+ | Rule | What it matches |
249
+ | --- | --- |
250
+ | `rce_jndi_lookup` | Log4Shell JNDI lookups, including nested lookups that spell out the keyword |
251
+ | `rce_shellshock` | Shellshock function definitions in headers and values |
252
+ | `rce_serialized_object` | Serialized Java, Python pickle, PHP, .NET and node-serialize objects, and unsafe YAML tags |
253
+ | `rce_gadget` | Deserialization gadgets: Fastjson and Jackson type keys that name known gadget classes, XStream dynamic proxies and `XMLDecoder` documents that start a process |
254
+ | `rce_expression` | OGNL, SpEL, EL, Thymeleaf preprocessing and Java reflection that reach a process, and Spring4Shell's class-loader property path |
255
+ | `rce_template_escape` | Jinja, Twig, Smarty, Velocity, Mako, Ruby ERB and Node.js sandbox escapes that reach Python internals, shell filters or Node's process module |
256
+ | `rce_webshell` | JSP, ASP and ASP.NET webshell code, and PHP that runs code or function names taken from the request, including base64-encoded code |
257
+ | `rce_script_upload` | Uploads named as server scripts: PHP, JSP, ASPX, `.htaccess` and similar |
258
+ | `rce_command_injection` | A probe or timing command chained onto the end of a value, as scanners send it: an identity, system-information or delay command after a semicolon, pipe or `&&`, or inside backticks or command substitution. A short probe must touch its separator, so ordinary text with a semicolon passes |
259
+ | `rce_shell_payload` | Reverse shells, download-and-run commands, reads of system account files, shell field-separator tricks, and Windows download commands and PowerShell download cradles |
260
+ | `rce_php` | PHP opening tags, PHP calls that run request input, and the PHP stream wrappers that run or unpack code |
261
+ | `rce_prototype_pollution` | Prototype-pollution keys in JSON bodies, forms and query strings |
262
+
263
+ Each value is checked as sent, then again with the disguises attackers use undone: `\u0024`,
264
+ `\x24` and `%u0024` escapes, HTML entities such as `&#36;` and `&dollar;`, fullwidth
265
+ characters such as `%`, invisible characters inside a word, Log4j lookups nested inside other
266
+ lookups, and a whole value sent as base64.
267
+
268
+ Each field of a query string or form body is also checked on its own, so a serialized Java
269
+ object in one field is found whether it's base64 or percent-encoded, and base64 is unwrapped up to three layers deep,
270
+ including base64 of gzip or deflate. A raw binary serialized body (Java, pickle, .NET
271
+ `BinaryFormatter`, Ruby `Marshal`) is checked before it's read as text. A prototype key in a
272
+ JSON body, form or query string is blocked as `rce_prototype_pollution`, since in Node.js it turns into code execution through
273
+ options that libraries pass to `child_process` and template compilers.
274
+
275
+ A multipart form is checked by its first `AIWAF_PAYLOAD_MAX_BYTES`, part by part: each
276
+ part's headers (such as a file name ending in `.php`) and field name, each text field as any
277
+ other value, and each file for a binary serialized object or PHP, JSP or ASP code, such as PHP
278
+ hidden in an image.
279
+ A file isn't checked for SQL or the other rules, since an ordinary document can quote them,
280
+ and a large upload isn't refused: the rest of it reaches your app unread. Node.js reads the
281
+ start of an unparsed multipart body and puts it back for your upload parser; Java reads the
282
+ parts the container parsed, when the servlet has a multipart config.
283
+
284
+ A gzip or deflate body (`Content-Encoding`) is read inflated, within
285
+ `AIWAF_PAYLOAD_MAX_BYTES`, so one that inflates past it is refused with `413`. Node.js also
286
+ reads `br`. A body in an encoding that can't be read is refused with `413`, since it can't be
287
+ checked (Java refuses compressed bodies unless `allowCompressedRequestBodies` is on). Every
288
+ header is checked; a request with more than 256 headers or 256 cookies is refused with `413`
289
+ rather than checked in part.
290
+
291
+ It reads the query, the body (JSON, XML and forms), path segments and headers, including
292
+ `User-Agent`, `Accept` and `Content-Disposition`, which the SQL check skips. Every rule is checked against the shared
293
+ list of ordinary text and must match none of it, and shell syntax on its own (`;`, `|`, a
294
+ backtick) isn't matched: only the probes `rce_command_injection` lists are, and routes whose input
295
+ reaches a command get the full command checks from `init`.
296
+ The rules are in `aiwaf-rust` and `aiwaf-wasm`. Java's copy is generated from them by
297
+ `scripts/sync_rce_rules.py`, and a test fails when it's out of date. The cases in
298
+ `tests/fixtures/rce_cases.json` (73 attacks and 57 ordinary look-alikes, plus whole form and JSON bodies, such as JSON-LD
299
+ `"@type": "Person"` and `filename="report.pdf"`) run against both. It follows `AIWAF_SQL_INJECTION_MODE`:
300
+ `block` (the default) answers `403`, `monitor` logs the rule, and `off` turns both checks off.
301
+
302
+ ### WebSocket messages
303
+
304
+ HTTP checks don't see what a WebSocket carries after its handshake, so each message a client
305
+ sends can be checked like a request body, with the same rules and `AIWAF_SQL_INJECTION_MODE`.
306
+ A message with a finding closes the socket with `1008` (`1009` when it's too large to check)
307
+ and never reaches your handlers; log events carry the rule and path, never the message.
308
+
309
+ - Python (FastAPI, Starlette, Django Channels): `app.add_middleware(WebSocketGuard)`, from
310
+ `aiwaf.core.websocket` (also `aiwaf.fast.WebSocketGuard`), or wrap your ASGI application.
311
+ Flask-SocketIO: `guard_socketio(socketio)` for every event, or `@aiwaf_message()` under
312
+ `@socketio.on(...)` for one handler, from `aiwaf.flask.websocket`. `inspect_message(data)`
313
+ checks one message anywhere else.
314
+ - Node.js: `await aiwaf.guardWebSocketServer(wss)` for `ws`, `await aiwaf.guardSocketIo(io)` for
315
+ socket.io, or `aiwaf.inspectMessage(data)`.
316
+ - Java: `new AiwafWebSocketHandler(handler, config)` for Spring WebSocket, and
317
+ `new AiwafEndpoint(endpoint, config)` for a Jakarta WebSocket endpoint (return it from your
318
+ `ServerEndpointConfig.Configurator`). In an annotated `@ServerEndpoint`, call
319
+ `AiwafMessageCore.check(message, config, path)` and close with `AiwafMessageCore.closeCode(rule)`.
320
+
321
+ These are tested against real servers: Starlette, Flask-SocketIO's test server, `ws` and
322
+ socket.io with their clients, and Tomcat's WebSocket container with the JDK client.
323
+
226
324
  ### Route-specific checks from init
227
325
 
228
326
  `init` audits your source as it builds the route manifest, and saves which operation each
@@ -235,6 +333,25 @@ values too. A match blocks the request with `403` and logs an event like this:
235
333
  {"event": "aiwaf.injection_risk", "mode": "block", "method": "GET", "route": "/files", "sink": "path", "input": "name", "rule": "path_traversal", "confidence": "medium"}
236
334
  ```
237
335
 
336
+ | Operation | Rules: what a value must contain to match |
337
+ | --- | --- |
338
+ | `sql` | The SQL tokenizer: a value that closes its SQL literal and continues as SQL |
339
+ | `command` | `command_chain`, `command_substitution`: `;`, `&` or `\|` and a command, `$(...)`, backticks |
340
+ | `path` | `path_traversal`, `path_sensitive_location`, `path_null_byte` |
341
+ | `ssrf` | `ssrf_scheme`, `ssrf_internal_host`: `file://` and similar, private and metadata hosts |
342
+ | `nosql`, `code`, `template`, `deserialization` | query operators, code evaluation calls, template expressions, serialized object markers |
343
+ | `xss` | `xss_markup`, `xss_event_handler`, `xss_script_url`: script tags, event-handler attributes, script URLs |
344
+ | `redirect` | `redirect_external`: protocol-relative, backslash, script-URL, user-info and scheme-only targets |
345
+ | `ldap` | `ldap_filter`: filter breakouts, OR filters and leading wildcards |
346
+ | `xpath` | `xpath_quote_break`, `xpath_tautology`: quote breakouts and always-true conditions |
347
+ | `xxe` | `xxe_entity`: document type and entity declarations |
348
+ | `redos` | `redos_nested_quantifier`: nested quantifiers |
349
+ | `prototype` | `prototype_key`: prototype-pollution keys |
350
+
351
+ Every rule is checked against a shared list of ordinary values (names, addresses, prose with
352
+ quotes and parentheses) that must never match. A plain absolute URL passes the redirect rule,
353
+ because the site's own host isn't known there.
354
+
238
355
  ```bash
239
356
  aiwaf init --framework flask --app app:app # audits the current folder
240
357
  aiwaf init --framework flask --app app:app --source src # audits another folder
@@ -267,6 +384,53 @@ and `AIWAF_PATH_MANIFEST` from the environment.
267
384
  - **Accuracy isn't measured on real traffic yet:** if a rule blocks real users on a route,
268
385
  set `AIWAF_INJECTION_RISK_MODE=log` while you report it.
269
386
 
387
+ ### Route schemas from init
388
+
389
+ `init` also saves what each route reads from the query and body, and a type for each input,
390
+ from your code: `int`, `float`, `bool`, `uuid` or `text`.
391
+
392
+ ```json
393
+ "/comments": {"inputs": {"body": "text", "post_id": "int"}, "inputs_complete": true}
394
+ ```
395
+
396
+ Types come from what the code says:
397
+ - Python: `int(request.GET["page"])`, `type=int`, FastAPI type hints and Pydantic models, Django
398
+ forms and DRF serializers in the same module.
399
+ - Node.js: `parseInt(req.query.page)`, `Number(...)`, destructuring, and zod object schemas.
400
+ - Java: `@RequestParam int page`, `@RequestBody` and `@ModelAttribute` classes and records in the
401
+ project, `Pageable`, and `Integer.parseInt(request.getParameter("n"))`.
402
+
403
+ The request is followed into functions in the same file (Python and Node.js) or methods of the
404
+ same class (Java), as in `return render(request)`, and a key held in a constant, as in
405
+ `request.GET[PAGE_PARAM]` or `getParameter(PAGE)`, is known. `inputs_complete` is true only when every read was
406
+ understood. Passing the request to a helper,
407
+ using `request.POST` or `req.body` whole, a key that isn't a constant, an unknown body class or
408
+ route middleware that isn't a body parser all make it false.
409
+
410
+ Requests to those routes are then reviewed after the general check:
411
+
412
+ - A typed input sent with a value of another type, as in a SQL condition sent as a numeric
413
+ ID, is `schema_type_mismatch`.
414
+ - A finding from `sql_function`, `sql_comment` or `sql_breakout_numeric` is checked again
415
+ without the inputs the schema clears: typed inputs of their type, text that reaches no
416
+ operation, and, when the list is complete, inputs the route never reads. When nothing else is
417
+ found, the finding is cleared. This is where prose and pasted code, such as a question about
418
+ a SQL function, stops being blocked.
419
+ - A finding from the URL path, such as a blog slug that names a SQL function, is reviewed by the
420
+ route's parameters: static segments are code, typed parameters (`<int:id>`, `{id:uuid}`, or a
421
+ saved type) must fit, and text parameters that reach no operation are cleared the same way.
422
+ - Quote breakouts and every remote code execution rule still block on every
423
+ input. An incomplete list, a sink reached by an input the audit couldn't name, a body that
424
+ isn't a form or JSON object, or a finding from headers or the path keeps the finding.
425
+
426
+ `AIWAF_ROUTE_SCHEMA_MODE` is `monitor` by default: it logs what it would do
427
+ (`{"event": "aiwaf.route_schema", "action": "relax", "rule": "sql_function", ...}`, never
428
+ request values) and changes nothing. Set it to `enforce` to act on it, or `off`. Java reads
429
+ `security.route_schema_mode` and `aiwaf.route-schema-mode`. The native pipelines review in the
430
+ engine too: Python's reads `route_schema_mode` (or `AIWAF_ROUTE_SCHEMA_MODE`), and Node.js's
431
+ takes `routeSchemaMode`, including its `inspectPayload()`. The cases in `tests/fixtures/route_schema_cases.json` run against aiwaf-rust, aiwaf-wasm
432
+ and Java.
433
+
270
434
  ## Repository layout
271
435
 
272
436
  ```text
@@ -294,7 +458,7 @@ pip install "aiwaf[django]"
294
458
  pip install "aiwaf[flask]"
295
459
  pip install "aiwaf[fastapi]"
296
460
 
297
- # Backward-compatible alias; Python 1.2.5 already installs aiwaf-rust
461
+ # Backward-compatible alias; Python 1.3.0 already installs aiwaf-rust
298
462
  pip install "aiwaf[rust]"
299
463
 
300
464
  # Node.js middleware
@@ -304,13 +468,23 @@ npm install aiwaf
304
468
  npm install aiwaf-wasm
305
469
  ```
306
470
 
307
- Java 1.3.8, after it is published to Maven Central:
471
+ npm 12 runs a dependency's install script only after you approve it, and `sqlite3`, where
472
+ Node.js AIWAF keeps its blocklist, exemptions and logs, gets its native binary from its install
473
+ script. Without approval AIWAF still runs, keeps that data in CSV files under `logs/storage`, and
474
+ prints one warning. To use SQLite, approve and build it once in your app:
475
+
476
+ ```bash
477
+ npm approve-scripts sqlite3
478
+ npm rebuild sqlite3
479
+ ```
480
+
481
+ Java 1.4.0, after it is published to Maven Central:
308
482
 
309
483
  ```xml
310
484
  <dependency>
311
485
  <groupId>io.github.aiwaf-project</groupId>
312
486
  <artifactId>aiwaf-java</artifactId>
313
- <version>1.3.8</version>
487
+ <version>1.4.0</version>
314
488
  </dependency>
315
489
  ```
316
490
 
@@ -318,7 +492,7 @@ Java 1.3.8, after it is published to Maven Central:
318
492
 
319
493
  The Python package requires Python 3.10 or newer. Framework dependencies are optional, so install only the extra needed by the application.
320
494
 
321
- Python 1.2.5 requires `aiwaf-rust>=0.2.12`; the `rust` extra remains an installation
495
+ Python 1.3.0 requires `aiwaf-rust>=0.2.15`; the `rust` extra remains an installation
322
496
  alias. Publish the matching Rust wheel with `NativeCSVPipeline` support before
323
497
  the Python release. The Rust release workflow builds Linux x86_64/aarch64,
324
498
  musl x86_64, macOS x86_64/arm64 and Windows x86_64 wheels and checks the native
@@ -1388,7 +1562,7 @@ cp -R ../licenses crates/aiwaf_wasm/pkg/
1388
1562
 
1389
1563
  ## Java package
1390
1564
 
1391
- AIWAF Java 1.3.8 targets Java 17, Spring Framework 7.0, and Jakarta Servlet 6.1. It is a native Java implementation and does not load the Rust library.
1565
+ AIWAF Java 1.4.0 targets Java 17, Spring Framework 7.0, and Jakarta Servlet 6.1. It is a native Java implementation and does not load the Rust library.
1392
1566
 
1393
1567
  ### Core engine
1394
1568
 
@@ -1477,7 +1651,7 @@ UUID protection uses Python-compatible weighted signals: malformed input, valid
1477
1651
  Generate a route manifest from the live Spring application rather than supplying controller methods manually:
1478
1652
 
1479
1653
  ```bash
1480
- java -cp "your-app.jar:aiwaf-java-1.3.8.jar" \
1654
+ java -cp "your-app.jar:aiwaf-java-1.4.0.jar" \
1481
1655
  com.aiwaf.cli.AiwafConsole init \
1482
1656
  --app com.example.Application \
1483
1657
  --output .aiwaf/paths.json
@@ -1705,11 +1879,11 @@ Release versions and tags must match the relevant manifest.
1705
1879
 
1706
1880
  | Package | Manifest | Tag | Workflow |
1707
1881
  | --- | --- | --- | --- |
1708
- | Python `aiwaf` | `pyproject.toml` | `python-v1.2.5` | `python-publish.yml` |
1709
- | npm `aiwaf` | `js/package.json` | `js-v1.2.4` | `npm-publish.yml` |
1710
- | PyPI `aiwaf-rust` | `rust/pyproject.toml` + `rust/Cargo.toml` | `rust-v0.2.12` | `rust-publish.yml` |
1711
- | npm `aiwaf-wasm` | `rust/crates/aiwaf_wasm/Cargo.toml` | `wasm-v0.2.9` | `wasm-publish.yml` |
1712
- | Maven `aiwaf-java` | `java/pom.xml` | `java-v1.3.8` | `java-publish.yml` |
1882
+ | Python `aiwaf` | `pyproject.toml` | `python-v1.3.0` | `python-publish.yml` |
1883
+ | npm `aiwaf` | `js/package.json` | `js-v1.3.0` | `npm-publish.yml` |
1884
+ | PyPI `aiwaf-rust` | `rust/pyproject.toml` + `rust/Cargo.toml` | `rust-v0.2.15` | `rust-publish.yml` |
1885
+ | npm `aiwaf-wasm` | `rust/crates/aiwaf_wasm/Cargo.toml` | `wasm-v0.2.11` | `wasm-publish.yml` |
1886
+ | Maven `aiwaf-java` | `java/pom.xml` | `java-v1.4.0` | `java-publish.yml` |
1713
1887
 
1714
1888
  Python and Rust publish to PyPI with trusted publishing. The npm workflows use npm trusted publishing and stage packages for approval. Configure the trusted publisher with organization `aiwaf-project`, repository `aiwaf`, the exact workflow filename, and the environment used by that workflow.
1715
1889
 
@@ -1717,12 +1891,13 @@ Java publishing uses the protected `maven-publish` environment plus `GPG_PRIVATE
1717
1891
 
1718
1892
  Registry releases are immutable. Increment the relevant manifest version before publishing another release.
1719
1893
 
1720
- This release is Python `aiwaf 1.2.5`, npm `aiwaf 1.2.4` and Java `aiwaf-java 1.3.8`, with
1721
- the injection audit changes. Python 1.2.4, Java 1.3.7, `aiwaf-rust 0.2.12` and
1722
- `aiwaf-wasm 0.2.9` are already published, and the engines are unchanged. Python now requires
1723
- `aiwaf-rust>=0.2.12` and npm `aiwaf` `aiwaf-wasm ^0.2.9`, so every native feature is available
1724
- after an install. npm `aiwaf` 1.2.3 was staged but never released, and npm doesn't reuse a
1725
- version, so npm `aiwaf 1.2.4` also ships the Node.js changes listed under Python 1.2.4.
1894
+ This release is Python `aiwaf 1.3.0`, npm `aiwaf 1.3.0`, Java `aiwaf-java 1.4.0`,
1895
+ `aiwaf-rust 0.2.15` and `aiwaf-wasm 0.2.11`: remote code execution checks, route schemas from
1896
+ `init`, multipart and compressed bodies, and WebSocket messages; Java 1.4.0 also brings
1897
+ `AIWAF_PROFILE` and the route checks for the new operations. Python 1.2.6, npm 1.2.5, Java 1.3.8,
1898
+ `aiwaf-rust 0.2.14` and `aiwaf-wasm 0.2.11` are already published; the engines carry the new
1899
+ checks. `aiwaf-rust 0.2.15` moves to PyO3 0.29: publish it before Python 1.3.0, which requires
1900
+ `aiwaf-rust>=0.2.15`. npm `aiwaf` requires `aiwaf-wasm ^0.2.11`.
1726
1901
 
1727
1902
  ## Security and limitations
1728
1903
 
package/index.js CHANGED
@@ -68,3 +68,7 @@ module.exports.extractNextRoutes = pathManifest.extractNextRoutes;
68
68
  module.exports.extractNestRoutes = pathManifest.extractNestRoutes;
69
69
  module.exports.generateExpressManifest = pathManifest.generateExpressManifest;
70
70
  module.exports.generateFrameworkManifest = pathManifest.generateFrameworkManifest;
71
+ const webSocketGuard = require('./lib/webSocketGuard');
72
+ module.exports.guardWebSocketServer = webSocketGuard.guardWebSocketServer;
73
+ module.exports.guardSocketIo = webSocketGuard.guardSocketIo;
74
+ module.exports.inspectMessage = webSocketGuard.inspectMessage;
@@ -155,6 +155,7 @@ module.exports = {
155
155
  async block(ip, reason = 'WAF blocked', options = {}) {
156
156
  const normalizedIp = String(ip || '').trim();
157
157
  if (!normalizedIp) return false;
158
+ if (require('./profiles').skipBlocklist(normalizedIp, reason)) return false;
158
159
  if (options.checkExemptions !== false) {
159
160
  try {
160
161
  const exemptionStore = require('./exemptionStore');
@@ -0,0 +1,40 @@
1
+ 'use strict';
2
+
3
+ // Reading the start of a request body without consuming it, for checks that run before the
4
+ // application's body parser.
5
+
6
+ function isMultipart(req) {
7
+ return String(req.headers?.['content-type'] || '').split(';', 1)[0].trim().toLowerCase() === 'multipart/form-data';
8
+ }
9
+
10
+ // Reads at most limit + 1 bytes of the body, then puts them back on the stream, so body
11
+ // parsers after this adapter still read the whole body. Python's adapters do the same.
12
+ function peekBody(req, limit) {
13
+ return new Promise((resolve, reject) => {
14
+ const chunks = [];
15
+ let size = 0;
16
+ const expected = Number(req.headers?.['content-length']) || null;
17
+ const finish = () => {
18
+ req.removeListener('readable', onReadable);
19
+ req.removeListener('error', onError);
20
+ const prefix = Buffer.concat(chunks);
21
+ if (prefix.length) req.unshift(prefix);
22
+ resolve(prefix);
23
+ };
24
+ const onError = error => { req.removeListener('readable', onReadable); reject(error); };
25
+ function onReadable() {
26
+ let chunk;
27
+ while ((chunk = req.read()) !== null) {
28
+ chunks.push(chunk);
29
+ size += chunk.length;
30
+ if (size > limit || size === expected) return finish();
31
+ }
32
+ // The whole body is buffered: put it back before the stream emits 'end'.
33
+ if (req._readableState?.ended) finish();
34
+ }
35
+ req.on('error', onError);
36
+ req.on('readable', onReadable);
37
+ });
38
+ }
39
+
40
+ module.exports = { peekBody, isMultipart };
@@ -10,6 +10,7 @@ const crypto = require('crypto');
10
10
  const fs = require('fs');
11
11
  const path = require('path');
12
12
  const parser = require('@babel/parser');
13
+ const { fileInputs } = require('./inputSchema');
13
14
 
14
15
  const SCHEMA_VERSION = '1.0';
15
16
  const SKIPPED_DIRECTORIES = new Set(['.git', '.next', '.nuxt', 'build', 'coverage', 'dist', 'node_modules', 'out', 'vendor']);
@@ -121,7 +122,10 @@ const SQLITE_METHODS = new Set(['all', 'each', 'exec', 'get', 'prepare', 'run'])
121
122
  const SQLITE_RECEIVER = /(^|\.)(db|sqlite|database)$/i;
122
123
  const NOSQL_METHODS = new Set(['aggregate', 'count', 'countDocuments', 'deleteMany', 'deleteOne', 'find', 'findOne', 'findOneAndDelete', 'findOneAndUpdate', 'updateMany', 'updateOne']);
123
124
  const NOSQL_RECEIVER = /(coll|db|mongo|model|users?$|^[A-Z])/;
124
- const COMMAND_FUNCTIONS = new Set(['child_process.exec', 'child_process.execSync', 'cp.exec', 'cp.execSync', 'exec', 'execSync']);
125
+ const COMMAND_FUNCTIONS = new Set([
126
+ 'child_process.exec', 'child_process.execFile', 'child_process.execFileSync', 'child_process.execSync', 'child_process.fork',
127
+ 'cp.exec', 'cp.execFile', 'cp.execFileSync', 'cp.execSync', 'cp.fork', 'exec', 'execFile', 'execFileSync', 'execSync', 'fork'
128
+ ]);
125
129
  const SHELL_FUNCTIONS = new Set(['child_process.spawn', 'child_process.spawnSync', 'cp.spawn', 'cp.spawnSync', 'spawn', 'spawnSync']);
126
130
  const PATH_METHODS = new Set([
127
131
  'appendFile', 'appendFileSync', 'createReadStream', 'createWriteStream', 'readFile', 'readFileSync', 'readdir',
@@ -134,9 +138,14 @@ const SSRF_FUNCTIONS = new Set([
134
138
  'got.get', 'got.post', 'http.get', 'http.request', 'https.get', 'https.request', 'needle', 'superagent.get', 'superagent.post',
135
139
  'undici.fetch', 'undici.request'
136
140
  ]);
137
- const CODE_FUNCTIONS = new Set(['eval', 'setImmediate.call', 'vm.compileFunction', 'vm.runInContext', 'vm.runInNewContext', 'vm.runInThisContext']);
141
+ // A string given to setTimeout or setInterval runs as code; require() and import() of a module
142
+ // named by input run that module.
143
+ const CODE_FUNCTIONS = new Set([
144
+ 'Function', 'eval', 'import', 'require', 'setImmediate.call', 'setInterval', 'setTimeout', 'vm.compileFunction',
145
+ 'vm.runInContext', 'vm.runInNewContext', 'vm.runInThisContext', 'window.eval'
146
+ ]);
138
147
  const TEMPLATE_FUNCTIONS = new Set(['Handlebars.compile', 'dot.template', 'ejs.compile', 'ejs.render', 'handlebars.compile', 'lodash.template', 'nunjucks.renderString', 'pug.compile', 'pug.render', '_.template']);
139
- const DESERIALIZE_FUNCTIONS = new Set(['serialize.unserialize', 'nodeSerialize.unserialize', 'funcster.deepDeserialize']);
148
+ const DESERIALIZE_FUNCTIONS = new Set(['serialize.unserialize', 'nodeSerialize.unserialize', 'funcster.deepDeserialize', 'v8.deserialize']);
140
149
 
141
150
  function dottedName(node) {
142
151
  if (!node) return '';
@@ -1267,9 +1276,18 @@ class FunctionWalker {
1267
1276
  if (name === 'Function') {
1268
1277
  const code = this.first(node.arguments);
1269
1278
  if (code) this.report(node, 'code', 'new Function', code, 'high');
1279
+ } else if ((name === 'vm.Script' || name === 'Script') && source) {
1280
+ this.report(node, 'code', `new ${name}`, source, 'high');
1281
+ } else if (name === 'Worker' && source && node.arguments.some(argument => argument.type === 'ObjectExpression'
1282
+ && argument.properties.some(item => item.key && item.key.name === 'eval' && item.value.value === true))) {
1283
+ this.report(node, 'code', 'new Worker', source, 'high');
1270
1284
  }
1271
1285
  return;
1272
1286
  }
1287
+ if (node.callee.type === 'Import' && source) {
1288
+ this.report(node, 'code', 'import()', source, 'high');
1289
+ return;
1290
+ }
1273
1291
  const head = receiver.split('.')[0];
1274
1292
  if (method && XSS_METHODS.has(method) && RESPONSE_NAMES.has(head) && source && this.isText(first, source)) {
1275
1293
  this.report(node, 'xss', name || `res.${method}`, source, 'medium');
@@ -1629,7 +1647,14 @@ function analyzePath(target = '.', options = {}) {
1629
1647
  }
1630
1648
  findings.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.sink.localeCompare(b.sink)
1631
1649
  || a.function.localeCompare(b.function));
1632
- const report = { schema_version: SCHEMA_VERSION, language: 'javascript', files_scanned: filesScanned, findings, errors };
1650
+ // What each handler reads, with types, labelled as its findings are so both link to the same routes.
1651
+ const inputs = [];
1652
+ for (const item of parsed) {
1653
+ const analyzer = project.get(item.full);
1654
+ const label = (node, parent) => analyzer.routeLabels.get(node) || functionName(node, parent);
1655
+ for (const entry of fileInputs(item.ast, item.display, item.text, label)) inputs.push(entry);
1656
+ }
1657
+ const report = { schema_version: SCHEMA_VERSION, language: 'javascript', files_scanned: filesScanned, findings, errors, inputs };
1633
1658
  if (suppressed) report.suppressed = suppressed;
1634
1659
  return report;
1635
1660
  }