@stacksjs/waf 0.0.0-stage → 0.75.636
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/LICENSE.md +21 -0
- package/README.md +73 -2
- package/dist/ffi.d.ts +97 -0
- package/dist/ffi.js +1 -0
- package/dist/index.d.ts +43 -0
- package/dist/index.js +1 -0
- package/dist/library.d.ts +2 -0
- package/dist/library.js +1 -0
- package/dist/rules.d.ts +23 -0
- package/dist/rules.js +3 -0
- package/dist/tsconfig.json +5 -0
- package/package.json +44 -4
package/LICENSE.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 Open Web Foundation
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,74 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @stacksjs/waf
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[zig-waf](https://github.com/zig-utils/zig-waf) in process, through `bun:ffi`.
|
|
4
|
+
|
|
5
|
+
On a box deploy, rpx's dataplane runs zig-waf in front of the app. This package
|
|
6
|
+
is for the places it does not: `buddy dev`, serverless, any app not behind rpx.
|
|
7
|
+
The framework's `waf` middleware uses it; add that to a route or a group.
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { Waf } from '@stacksjs/waf'
|
|
11
|
+
|
|
12
|
+
const waf = new Waf({
|
|
13
|
+
mode: 'detection', // or 'blocking'
|
|
14
|
+
library: '/opt/zig-waf/lib/libzig-waf.so', // or set ZIG_WAF_LIBRARY
|
|
15
|
+
rules: ['/opt/crs/crs-setup.conf', ...crsRuleFiles], // zig-waf ships no rules
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
const decision = waf.inspect({
|
|
19
|
+
method: 'GET',
|
|
20
|
+
uri: '/search?q=1',
|
|
21
|
+
headers: [['host', 'example.com']],
|
|
22
|
+
clientAddress: '203.0.113.7',
|
|
23
|
+
clientPort: 51234,
|
|
24
|
+
serverAddress: '127.0.0.1',
|
|
25
|
+
serverPort: 3008,
|
|
26
|
+
})
|
|
27
|
+
// { matched: true, enforced: false, status: 403, ruleId: 949110 } in detection mode
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
- **Rules are required.** zig-waf bundles none, so `rules` names SecLang files in
|
|
31
|
+
load order, usually an OWASP CRS checkout. With none it refuses to start: a
|
|
32
|
+
firewall that matches nothing looks the same as one that found nothing wrong.
|
|
33
|
+
- **The library is named, never searched for**: `library`, then
|
|
34
|
+
`ZIG_WAF_LIBRARY`. It is `lib/libzig-waf.{dylib,so}` in a zig-waf release, or
|
|
35
|
+
`zig-out/lib/` after `zig build`.
|
|
36
|
+
- **Data files** (`@pmFromFile`) resolve from `dataDir`, by default the last
|
|
37
|
+
rule file's directory: a CRS checkout's `rules/`, where its `.data` files are.
|
|
38
|
+
- **Methods.** CRS allows only GET, HEAD, POST and OPTIONS by default, which
|
|
39
|
+
would refuse a Stacks API's PUT, PATCH and DELETE routes. The generated setup
|
|
40
|
+
adds them; `allowedMethods` narrows or widens the list.
|
|
41
|
+
- **Bodies.** At most `maxBodyBytes` (default 128 KB) is read. Blocking refuses a
|
|
42
|
+
larger body with 413, since past that point the rules see nothing. Detection
|
|
43
|
+
inspects its start and logs the rest as unseen.
|
|
44
|
+
- **Detection by default.** Nothing switches to `blocking` by itself; read the
|
|
45
|
+
detection log first.
|
|
46
|
+
|
|
47
|
+
`bun test ./tests` runs the engine tests when `ZIG_WAF_LIBRARY` is set and skips
|
|
48
|
+
them, with a warning, when it is not.
|
|
49
|
+
|
|
50
|
+
## Added latency
|
|
51
|
+
|
|
52
|
+
`bun bench/latency.ts [rule files]` times `Waf.inspect` per request through
|
|
53
|
+
`bun:ffi`. Measured on an Apple M-series Mac (Bun 1.4.3, zig-waf `ReleaseFast`),
|
|
54
|
+
p50 per request, before and after zig-utils/zig-waf#84, which makes the C ABI
|
|
55
|
+
allocate through malloc instead of a page per allocation (#82):
|
|
56
|
+
|
|
57
|
+
| Rules | Request | zig-waf 6c61dc6 | with #84 |
|
|
58
|
+
| --- | --- | --- | --- |
|
|
59
|
+
| test fixture (CRS 942100 + 949110), 20,000 runs | GET, clean | 252 us | 13 us |
|
|
60
|
+
| | GET, SQL injection | 438 us | 17 us |
|
|
61
|
+
| | POST, 1 KB form | 245 us | 16 us |
|
|
62
|
+
| full CRS 4 (55b09f5), paranoia level 1, 300 runs | GET, clean | 26.5 ms | 9.6 ms |
|
|
63
|
+
| | GET, SQL injection | 18.8 ms | 11.1 ms |
|
|
64
|
+
| | POST, 1 KB form | 42.3 ms | 37.5 ms |
|
|
65
|
+
|
|
66
|
+
The full-CRS cost that remains is mostly zig-waf compiling every `@rx` and `@pm`
|
|
67
|
+
operator again on every request (zig-utils/zig-waf#83), which is why the body
|
|
68
|
+
rules barely moved. Measure with your own rules (a full CRS needs a smaller run):
|
|
69
|
+
|
|
70
|
+
```sh
|
|
71
|
+
BENCH_ITERATIONS=300 bun bench/latency.ts crs-setup.conf rules/*.conf
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
The CI job `waf` prints the fixture table for Linux.
|
package/dist/ffi.d.ts
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { dlopen, FFIType, ptr } from 'bun:ffi';
|
|
2
|
+
export declare function statusName(code: number): string;
|
|
3
|
+
/**
|
|
4
|
+
* Open the library at `path` and check its ABI: same major, and a minor at
|
|
5
|
+
* least the one this binding needs. A library that predates the binding is
|
|
6
|
+
* refused rather than called with structs it does not know.
|
|
7
|
+
*/
|
|
8
|
+
export declare function openLibrary(path: string): ZigWafLibrary;
|
|
9
|
+
/** A buffer the library reads, kept alive by the caller for the call. */
|
|
10
|
+
export declare function bytes(value: string | Uint8Array): Uint8Array;
|
|
11
|
+
/** The ABI this binding was written against: major 1, minor 1. */
|
|
12
|
+
export declare const ABI_VERSION: 0x00010001;
|
|
13
|
+
export declare const Status: {
|
|
14
|
+
readonly OK: 0;
|
|
15
|
+
readonly INVALID_ARGUMENT: 1;
|
|
16
|
+
readonly UNSUPPORTED_ABI: 2;
|
|
17
|
+
readonly OUT_OF_MEMORY: 3;
|
|
18
|
+
readonly INVALID_CONFIG: 4;
|
|
19
|
+
readonly INVALID_LIFECYCLE: 5;
|
|
20
|
+
readonly LIMIT_EXCEEDED: 6;
|
|
21
|
+
readonly BUSY: 7;
|
|
22
|
+
readonly NOT_FOUND: 8;
|
|
23
|
+
readonly INTERNAL: 255
|
|
24
|
+
};
|
|
25
|
+
export declare const Mode: {
|
|
26
|
+
readonly ENABLED: 0;
|
|
27
|
+
readonly DETECTION_ONLY: 1
|
|
28
|
+
};
|
|
29
|
+
export declare const Phase: {
|
|
30
|
+
readonly REQUEST_HEADERS: 1;
|
|
31
|
+
readonly REQUEST_BODY: 2;
|
|
32
|
+
readonly LOGGING: 5
|
|
33
|
+
};
|
|
34
|
+
export declare const AuditFormat: {
|
|
35
|
+
readonly JSON: 1
|
|
36
|
+
};
|
|
37
|
+
/** `zig_waf_config_t`: 4 x u32, 5 x size_t, a pointer, 7 x u64. */
|
|
38
|
+
export declare const CONFIG_SIZE: 120;
|
|
39
|
+
/** `zig_waf_intervention_t`: header, action, status, enforced, has_rule_id, rule_id, then 4 x u64. */
|
|
40
|
+
export declare const INTERVENTION_SIZE: 56;
|
|
41
|
+
declare const u64: unknown;
|
|
42
|
+
declare const symbols: {
|
|
43
|
+
readonly zig_waf_abi_version: {
|
|
44
|
+
readonly args: readonly [];
|
|
45
|
+
readonly returns: typeof FFIType.u32
|
|
46
|
+
};
|
|
47
|
+
readonly zig_waf_create_with_rules_at: {
|
|
48
|
+
readonly args: readonly [unknown, unknown, unknown, unknown, unknown, unknown];
|
|
49
|
+
readonly returns: typeof FFIType.i32
|
|
50
|
+
};
|
|
51
|
+
readonly zig_waf_destroy: {
|
|
52
|
+
readonly args: readonly [unknown];
|
|
53
|
+
readonly returns: typeof FFIType.i32
|
|
54
|
+
};
|
|
55
|
+
readonly zig_waf_transaction_create: {
|
|
56
|
+
readonly args: readonly [unknown, unknown];
|
|
57
|
+
readonly returns: typeof FFIType.i32
|
|
58
|
+
};
|
|
59
|
+
readonly zig_waf_transaction_destroy: {
|
|
60
|
+
readonly args: readonly [unknown];
|
|
61
|
+
readonly returns: typeof FFIType.void
|
|
62
|
+
};
|
|
63
|
+
readonly zig_waf_transaction_process_connection: {
|
|
64
|
+
readonly args: readonly [unknown, unknown, unknown, unknown, unknown, unknown, unknown];
|
|
65
|
+
readonly returns: typeof FFIType.i32
|
|
66
|
+
};
|
|
67
|
+
readonly zig_waf_transaction_process_uri: {
|
|
68
|
+
readonly args: readonly [unknown, unknown, unknown, unknown, unknown, unknown, unknown];
|
|
69
|
+
readonly returns: typeof FFIType.i32
|
|
70
|
+
};
|
|
71
|
+
readonly zig_waf_transaction_add_request_header: {
|
|
72
|
+
readonly args: readonly [unknown, unknown, unknown, unknown, unknown];
|
|
73
|
+
readonly returns: typeof FFIType.i32
|
|
74
|
+
};
|
|
75
|
+
readonly zig_waf_transaction_process_request_headers: {
|
|
76
|
+
readonly args: readonly [unknown];
|
|
77
|
+
readonly returns: typeof FFIType.i32
|
|
78
|
+
};
|
|
79
|
+
readonly zig_waf_transaction_write_request_body: {
|
|
80
|
+
readonly args: readonly [unknown, unknown, unknown];
|
|
81
|
+
readonly returns: typeof FFIType.i32
|
|
82
|
+
};
|
|
83
|
+
readonly zig_waf_transaction_process_request_body: {
|
|
84
|
+
readonly args: readonly [unknown];
|
|
85
|
+
readonly returns: typeof FFIType.i32
|
|
86
|
+
};
|
|
87
|
+
readonly zig_waf_transaction_evaluate_phase: {
|
|
88
|
+
readonly args: readonly [unknown, unknown];
|
|
89
|
+
readonly returns: typeof FFIType.i32
|
|
90
|
+
};
|
|
91
|
+
readonly zig_waf_transaction_intervention: {
|
|
92
|
+
readonly args: readonly [unknown, unknown];
|
|
93
|
+
readonly returns: typeof FFIType.i32
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
export type ZigWafLibrary = ReturnType<typeof dlopen<typeof symbols>>['symbols'];
|
|
97
|
+
export { ptr };
|
package/dist/ffi.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{dlopen,FFIType,ptr}from"bun:ffi";export const ABI_VERSION=65537;export const Status={OK:0,INVALID_ARGUMENT:1,UNSUPPORTED_ABI:2,OUT_OF_MEMORY:3,INVALID_CONFIG:4,INVALID_LIFECYCLE:5,LIMIT_EXCEEDED:6,BUSY:7,NOT_FOUND:8,INTERNAL:255};const STATUS_NAMES=Object.fromEntries(Object.entries(Status).map(([name,code])=>[code,name]));export function statusName(code){return STATUS_NAMES[code]??`status ${code}`}export const Mode={ENABLED:0,DETECTION_ONLY:1};export const Phase={REQUEST_HEADERS:1,REQUEST_BODY:2,LOGGING:5};export const AuditFormat={JSON:1};export const CONFIG_SIZE=120;export const INTERVENTION_SIZE=56;const u64=FFIType.u64;const symbols={zig_waf_abi_version:{args:[],returns:FFIType.u32},zig_waf_create_with_rules_at:{args:[FFIType.ptr,FFIType.ptr,u64,FFIType.ptr,u64,FFIType.ptr],returns:FFIType.i32},zig_waf_destroy:{args:[u64],returns:FFIType.i32},zig_waf_transaction_create:{args:[u64,FFIType.ptr],returns:FFIType.i32},zig_waf_transaction_destroy:{args:[u64],returns:FFIType.void},zig_waf_transaction_process_connection:{args:[u64,FFIType.ptr,u64,FFIType.u16,FFIType.ptr,u64,FFIType.u16],returns:FFIType.i32},zig_waf_transaction_process_uri:{args:[u64,FFIType.ptr,u64,FFIType.ptr,u64,FFIType.ptr,u64],returns:FFIType.i32},zig_waf_transaction_add_request_header:{args:[u64,FFIType.ptr,u64,FFIType.ptr,u64],returns:FFIType.i32},zig_waf_transaction_process_request_headers:{args:[u64],returns:FFIType.i32},zig_waf_transaction_write_request_body:{args:[u64,FFIType.ptr,u64],returns:FFIType.i32},zig_waf_transaction_process_request_body:{args:[u64],returns:FFIType.i32},zig_waf_transaction_evaluate_phase:{args:[u64,FFIType.u32],returns:FFIType.i32},zig_waf_transaction_intervention:{args:[u64,FFIType.ptr],returns:FFIType.i32}};const opened=new Map;export function openLibrary(path){const cached=opened.get(path);if(cached)return cached;const library=dlopen(path,symbols).symbols;const abi=library.zig_waf_abi_version();if(abi>>>16!==ABI_VERSION>>>16||(abi&65535)<(ABI_VERSION&65535))throw new Error(`${path} speaks zig-waf ABI ${formatAbi(abi)}; @stacksjs/waf needs ${formatAbi(ABI_VERSION)} or a later minor of the same major.`);opened.set(path,library);return library}function formatAbi(abi){return`${abi>>>16}.${abi&65535}`}export function bytes(value){return typeof value==="string"?Buffer.from(value):value}export{ptr};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { findWafLibrary } from './library';
|
|
2
|
+
import { renderWafRules } from './rules';
|
|
3
|
+
import type { WafRuleSettings } from './rules';
|
|
4
|
+
export type { RenderedRules, WafRuleSettings } from './rules';
|
|
5
|
+
export declare interface WafOptions extends WafRuleSettings {
|
|
6
|
+
mode?: Exclude<WafMode, 'off'>
|
|
7
|
+
library?: string
|
|
8
|
+
maxHeaderCount?: number
|
|
9
|
+
maxHeaderBytes?: number
|
|
10
|
+
maxRequestTargetBytes?: number
|
|
11
|
+
}
|
|
12
|
+
export declare interface WafRequest {
|
|
13
|
+
method: string
|
|
14
|
+
uri: string
|
|
15
|
+
protocol?: string
|
|
16
|
+
headers: Iterable<[string, string]>
|
|
17
|
+
body?: string | Uint8Array
|
|
18
|
+
clientAddress: string
|
|
19
|
+
clientPort: number
|
|
20
|
+
serverAddress: string
|
|
21
|
+
serverPort: number
|
|
22
|
+
}
|
|
23
|
+
export declare interface WafDecision {
|
|
24
|
+
matched: boolean
|
|
25
|
+
enforced: boolean
|
|
26
|
+
status?: number
|
|
27
|
+
ruleId?: number
|
|
28
|
+
}
|
|
29
|
+
export type WafMode = 'off' | 'detection' | 'blocking';
|
|
30
|
+
export declare class Waf {
|
|
31
|
+
readonly mode: Exclude<WafMode, 'off'>;
|
|
32
|
+
readonly warnings: string[];
|
|
33
|
+
readonly maxBodyBytes: number;
|
|
34
|
+
private handle;
|
|
35
|
+
private lib;
|
|
36
|
+
constructor(options: WafOptions);
|
|
37
|
+
inspect(request: WafRequest): WafDecision;
|
|
38
|
+
close(): void;
|
|
39
|
+
private decision;
|
|
40
|
+
private check;
|
|
41
|
+
}
|
|
42
|
+
export { findWafLibrary, libraryFileName } from './library';
|
|
43
|
+
export { renderWafRules } from './rules';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{bytes,CONFIG_SIZE,INTERVENTION_SIZE,Mode,openLibrary,Phase,ptr,Status,statusName}from"./ffi";import{findWafLibrary}from"./library";import{renderWafRules}from"./rules";export{findWafLibrary,libraryFileName}from"./library";export{renderWafRules}from"./rules";export class Waf{mode;warnings;maxBodyBytes;handle;lib;constructor(options){this.mode=options.mode??"detection";this.maxBodyBytes=options.maxBodyBytes??131072;this.lib=openLibrary(findWafLibrary(options.library));const rules=renderWafRules(options);this.warnings=rules.warnings;const config=new DataView(new ArrayBuffer(CONFIG_SIZE));config.setUint32(0,CONFIG_SIZE,true);config.setUint32(4,65537,true);config.setUint32(8,this.mode==="blocking"?Mode.ENABLED:Mode.DETECTION_ONLY,true);const limits=[options.maxRequestTargetBytes??8192,options.maxHeaderCount??128,options.maxHeaderBytes??65536,this.maxBodyBytes,this.maxBodyBytes];limits.forEach((limit,index)=>config.setBigUint64(16+index*8,BigInt(limit),true));const text=bytes(rules.text);const dataDir=bytes(rules.dataDir);const out=new BigUint64Array(1);const status=this.lib.zig_waf_create_with_rules_at(ptr(config.buffer),ptr(text),text.length,ptr(dataDir),dataDir.length,ptr(out));if(status!==Status.OK)throw new Error(`zig-waf refused the rules (${statusName(status)}). Run \`zig-waf validate\` on them for the line at fault.`);this.handle=out[0]}inspect(request){if(!this.handle)throw new Error("This Waf has been closed.");const out=new BigUint64Array(1);this.check(this.lib.zig_waf_transaction_create(this.handle,ptr(out)),"start a transaction");const tx=out[0];try{const client=bytes(request.clientAddress);const server=bytes(request.serverAddress);this.check(this.lib.zig_waf_transaction_process_connection(tx,ptr(client),client.length,request.clientPort,ptr(server),server.length,request.serverPort),"read the connection");const uri=bytes(request.uri);const method=bytes(request.method.toUpperCase());const protocol=bytes(request.protocol??"HTTP/1.1");this.check(this.lib.zig_waf_transaction_process_uri(tx,ptr(uri),uri.length,ptr(method),method.length,ptr(protocol),protocol.length),"read the request line");for(const[name,value]of request.headers){const n=bytes(name);const v=bytes(value);this.check(this.lib.zig_waf_transaction_add_request_header(tx,ptr(n),n.length,v.length?ptr(v):null,v.length),"read a header")}this.check(this.lib.zig_waf_transaction_process_request_headers(tx),"process the headers");this.check(this.lib.zig_waf_transaction_evaluate_phase(tx,Phase.REQUEST_HEADERS),"evaluate the headers");const decided=this.decision(tx);if(decided.matched)return decided;const body=request.body===undefined?undefined:bytes(request.body);if(body&&body.length>0)this.check(this.lib.zig_waf_transaction_write_request_body(tx,ptr(body),Math.min(body.length,this.maxBodyBytes)),"read the body");this.check(this.lib.zig_waf_transaction_process_request_body(tx),"process the body");this.check(this.lib.zig_waf_transaction_evaluate_phase(tx,Phase.REQUEST_BODY),"evaluate the body");return this.decision(tx)}finally{this.lib.zig_waf_transaction_destroy(tx)}}close(){if(!this.handle)return;this.check(this.lib.zig_waf_destroy(this.handle),"close");this.handle=0n}decision(tx){const out=new DataView(new ArrayBuffer(INTERVENTION_SIZE));out.setUint32(0,INTERVENTION_SIZE,true);out.setUint32(4,65537,true);const status=this.lib.zig_waf_transaction_intervention(tx,ptr(out.buffer));if(status===Status.NOT_FOUND)return{matched:false,enforced:false};this.check(status,"read the decision");const code=out.getUint16(12,true);return{matched:true,enforced:out.getUint8(14)===1,status:code||undefined,ruleId:out.getUint8(15)===1?out.getUint32(16,true):undefined}}check(status,step){if(status!==Status.OK)throw new Error(`zig-waf could not ${step} (${statusName(status)}).`)}}
|
package/dist/library.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync}from"node:fs";import process from"node:process";export function libraryFileName(platform=process.platform){return platform==="darwin"?"libzig-waf.dylib":platform==="win32"?"zig-waf.dll":"libzig-waf.so"}export function findWafLibrary(configured,env=process.env){const candidate=configured||env.ZIG_WAF_LIBRARY;if(!candidate)throw new Error(`The in-process WAF needs zig-waf's shared library (${libraryFileName()}). Set security.waf.library or ZIG_WAF_LIBRARY to its path: it is in lib/ of a zig-waf release, or zig-out/lib/ after \`zig build\` in a zig-waf checkout.`);if(!existsSync(candidate))throw new Error(`zig-waf's shared library is not at ${candidate} (from ${configured?"security.waf.library":"ZIG_WAF_LIBRARY"}).`);return candidate}
|
package/dist/rules.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { WafRuleExclusion } from '@stacksjs/types';
|
|
2
|
+
export declare function renderWafRules(settings: WafRuleSettings, read?: (path: string) => string): RenderedRules;
|
|
3
|
+
/**
|
|
4
|
+
* The methods a Stacks API uses, on top of CRS's default.
|
|
5
|
+
* @defaultValue `['GET', 'HEAD', 'POST', 'OPTIONS', 'PUT', 'PATCH', 'DELETE']`
|
|
6
|
+
*/
|
|
7
|
+
export declare const DEFAULT_ALLOWED_METHODS: string[];
|
|
8
|
+
export declare interface WafRuleSettings {
|
|
9
|
+
paranoiaLevel?: number
|
|
10
|
+
inboundThreshold?: number
|
|
11
|
+
outboundThreshold?: number
|
|
12
|
+
maxBodyBytes?: number
|
|
13
|
+
bypassPaths?: string[]
|
|
14
|
+
exclusions?: WafRuleExclusion[]
|
|
15
|
+
rules?: string[]
|
|
16
|
+
dataDir?: string
|
|
17
|
+
allowedMethods?: string[]
|
|
18
|
+
}
|
|
19
|
+
export declare interface RenderedRules {
|
|
20
|
+
text: string
|
|
21
|
+
dataDir: string
|
|
22
|
+
warnings: string[]
|
|
23
|
+
}
|
package/dist/rules.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{readFileSync}from"node:fs";import{dirname}from"node:path";export const DEFAULT_ALLOWED_METHODS=["GET","HEAD","POST","OPTIONS","PUT","PATCH","DELETE"];const IDS={setup:99000,bypass:1e5,exclusion:101000};export function renderWafRules(settings,read=(path)=>readFileSync(path,"utf8")){const files=settings.rules??[];if(files.length===0)throw new Error("security.waf.rules names no rule files. zig-waf ships no rules, so the in-process WAF would match nothing. Point it at an OWASP CRS checkout (crs-setup.conf, then rules/*.conf) or your own SecLang files.");const warnings=[];const lines=["SecRuleEngine On","SecRequestBodyAccess On",`SecAction "id:${IDS.setup},phase:1,pass,nolog,t:none,setvar:tx.blocking_paranoia_level=${settings.paranoiaLevel??1},setvar:tx.paranoia_level=${settings.paranoiaLevel??1}"`,`SecAction "id:${IDS.setup+1},phase:1,pass,nolog,t:none,setvar:tx.inbound_anomaly_score_threshold=${settings.inboundThreshold??5},setvar:tx.outbound_anomaly_score_threshold=${settings.outboundThreshold??4}"`,`SecAction "id:${IDS.setup+2},phase:1,pass,nolog,t:none,setvar:'tx.allowed_methods=${methods(settings.allowedMethods,warnings)}'"`];let bypassId=IDS.bypass;for(const path of settings.bypassPaths??[]){lines.push(`SecRule REQUEST_FILENAME "@beginsWith ${escape(path)}" "id:${bypassId++},phase:1,pass,nolog,ctl:ruleEngine=Off"`)}const removeAfter=[];let exclusionId=IDS.exclusion;for(const exclusion of settings.exclusions??[]){if(!Number.isInteger(exclusion.ruleId)||exclusion.ruleId<=0){warnings.push(`Exclusion for rule "${exclusion.ruleId}" was dropped: the id is not a positive integer.`);continue}if(exclusion.pathPattern)lines.push(`SecRule REQUEST_FILENAME "@rx ${escape(exclusion.pathPattern)}" "id:${exclusionId++},phase:1,pass,nolog,ctl:ruleRemoveById=${exclusion.ruleId}"`);else removeAfter.push(exclusion.ruleId)}for(const file of files)lines.push(`# ${file}`,read(file));for(const id of removeAfter)lines.push(`SecRuleRemoveById ${id}`);return{text:`${lines.join(`
|
|
2
|
+
`)}
|
|
3
|
+
`,dataDir:settings.dataDir??dirname(files.at(-1)),warnings}}function methods(configured,warnings){const valid=(configured??DEFAULT_ALLOWED_METHODS).filter((method)=>{if(/^[A-Z]+$/.test(method))return true;warnings.push(`Allowed method "${method}" was dropped: a method is upper-case letters only.`);return false});return valid.join(" ")}function escape(value){return value.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/[\r\n]/g," ")}
|
package/package.json
CHANGED
|
@@ -1,6 +1,46 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stacksjs/waf",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"type": "module",
|
|
4
|
+
"sideEffects": false,
|
|
5
|
+
"version": "0.75.636",
|
|
6
|
+
"description": "zig-waf in process through bun:ffi: OWASP CRS inspection for Stacks apps that are not behind rpx.",
|
|
7
|
+
"author": "Chris Breuer <chris@stacksjs.com>",
|
|
8
|
+
"license": "MIT",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/stacksjs/stacks.git",
|
|
12
|
+
"directory": "storage/framework/core/waf"
|
|
13
|
+
},
|
|
14
|
+
"keywords": [
|
|
15
|
+
"waf",
|
|
16
|
+
"firewall",
|
|
17
|
+
"owasp",
|
|
18
|
+
"crs",
|
|
19
|
+
"stacks"
|
|
20
|
+
],
|
|
21
|
+
"exports": {
|
|
22
|
+
".": {
|
|
23
|
+
"types": "./dist/index.d.ts",
|
|
24
|
+
"import": "./dist/index.js",
|
|
25
|
+
"default": "./dist/index.js"
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
"module": "dist/index.js",
|
|
29
|
+
"types": "dist/index.d.ts",
|
|
30
|
+
"files": [
|
|
31
|
+
"README.md",
|
|
32
|
+
"dist"
|
|
33
|
+
],
|
|
34
|
+
"scripts": {
|
|
35
|
+
"build": "bun build.ts",
|
|
36
|
+
"test": "bun test ./tests",
|
|
37
|
+
"typecheck": "bun tsc --noEmit",
|
|
38
|
+
"prepublishOnly": "bun run build"
|
|
39
|
+
},
|
|
40
|
+
"dependencies": {
|
|
41
|
+
"@stacksjs/types": "0.75.636"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"better-dx": "^0.2.39"
|
|
45
|
+
}
|
|
46
|
+
}
|