@push.rocks/smartnftables 1.0.1
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/changelog.md +10 -0
- package/dist_ts/00_commitinfo_data.d.ts +8 -0
- package/dist_ts/00_commitinfo_data.js +9 -0
- package/dist_ts/index.d.ts +10 -0
- package/dist_ts/index.js +14 -0
- package/dist_ts/nft.executor.d.ts +32 -0
- package/dist_ts/nft.executor.js +59 -0
- package/dist_ts/nft.manager.d.ts +59 -0
- package/dist_ts/nft.manager.firewall.d.ts +49 -0
- package/dist_ts/nft.manager.firewall.js +121 -0
- package/dist_ts/nft.manager.js +132 -0
- package/dist_ts/nft.manager.nat.d.ts +34 -0
- package/dist_ts/nft.manager.nat.js +61 -0
- package/dist_ts/nft.manager.ratelimit.d.ts +26 -0
- package/dist_ts/nft.manager.ratelimit.js +39 -0
- package/dist_ts/nft.rulebuilder.firewall.d.ts +30 -0
- package/dist_ts/nft.rulebuilder.firewall.js +119 -0
- package/dist_ts/nft.rulebuilder.nat.d.ts +15 -0
- package/dist_ts/nft.rulebuilder.nat.js +51 -0
- package/dist_ts/nft.rulebuilder.ratelimit.d.ts +16 -0
- package/dist_ts/nft.rulebuilder.ratelimit.js +61 -0
- package/dist_ts/nft.rulebuilder.table.d.ts +13 -0
- package/dist_ts/nft.rulebuilder.table.js +27 -0
- package/dist_ts/nft.types.d.ts +88 -0
- package/dist_ts/nft.types.js +2 -0
- package/dist_ts/plugins.d.ts +6 -0
- package/dist_ts/plugins.js +9 -0
- package/license +21 -0
- package/package.json +57 -0
- package/readme.md +357 -0
- package/ts/00_commitinfo_data.ts +8 -0
- package/ts/index.ts +59 -0
- package/ts/nft.executor.ts +74 -0
- package/ts/nft.manager.firewall.ts +148 -0
- package/ts/nft.manager.nat.ts +76 -0
- package/ts/nft.manager.ratelimit.ts +43 -0
- package/ts/nft.manager.ts +157 -0
- package/ts/nft.rulebuilder.firewall.ts +173 -0
- package/ts/nft.rulebuilder.nat.ts +82 -0
- package/ts/nft.rulebuilder.ratelimit.ts +89 -0
- package/ts/nft.rulebuilder.table.ts +30 -0
- package/ts/nft.types.ts +102 -0
- package/ts/plugins.ts +16 -0
package/readme.md
ADDED
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
# @push.rocks/smartnftables
|
|
2
|
+
|
|
3
|
+
A TypeScript module for managing Linux nftables rules with a high-level, type-safe API. Handles NAT (DNAT/SNAT/masquerade), firewall rules, IP sets, and rate limiting — all from clean, declarative TypeScript.
|
|
4
|
+
|
|
5
|
+
## Issue Reporting and Security
|
|
6
|
+
|
|
7
|
+
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pnpm install @push.rocks/smartnftables
|
|
13
|
+
# or
|
|
14
|
+
npm install @push.rocks/smartnftables
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
> ⚠️ **Requires root privileges** to actually apply nftables rules to the kernel. Without root, rules are tracked in memory but not applied (a warning is logged). Great for development/testing!
|
|
18
|
+
|
|
19
|
+
## Quick Start
|
|
20
|
+
|
|
21
|
+
```typescript
|
|
22
|
+
import { SmartNftables } from '@push.rocks/smartnftables';
|
|
23
|
+
|
|
24
|
+
const nft = new SmartNftables();
|
|
25
|
+
await nft.initialize();
|
|
26
|
+
|
|
27
|
+
// Port forward 8080 → 192.168.1.100:80
|
|
28
|
+
await nft.nat.addPortForwarding('web', {
|
|
29
|
+
sourcePort: 8080,
|
|
30
|
+
targetHost: '192.168.1.100',
|
|
31
|
+
targetPort: 80,
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
// Block a suspicious IP
|
|
35
|
+
await nft.firewall.blockIP('10.0.0.99');
|
|
36
|
+
|
|
37
|
+
// Rate limit HTTP to 100 req/s per IP
|
|
38
|
+
await nft.rateLimit.addRateLimit('http-limit', {
|
|
39
|
+
port: 80,
|
|
40
|
+
protocol: 'tcp',
|
|
41
|
+
rate: '100/second',
|
|
42
|
+
perSourceIP: true,
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
// Clean up everything when done
|
|
46
|
+
await nft.cleanup();
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Architecture 🏗️
|
|
50
|
+
|
|
51
|
+
The library is organized around a **facade pattern** with specialized sub-managers:
|
|
52
|
+
|
|
53
|
+
```
|
|
54
|
+
SmartNftables (main facade)
|
|
55
|
+
├── nat → NatManager (DNAT, SNAT, masquerade)
|
|
56
|
+
├── firewall → FirewallManager (filter rules, IP sets, stateful tracking)
|
|
57
|
+
└── rateLimit → RateLimitManager (packet/connection rate limiting)
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
All rules are tracked in **rule groups** identified by string IDs, so you can add, inspect, and remove them programmatically.
|
|
61
|
+
|
|
62
|
+
## API Reference
|
|
63
|
+
|
|
64
|
+
### `SmartNftables` — Main Facade
|
|
65
|
+
|
|
66
|
+
```typescript
|
|
67
|
+
const nft = new SmartNftables({
|
|
68
|
+
tableName: 'smartnftables', // nftables table name (default: 'smartnftables')
|
|
69
|
+
family: 'ip', // 'ip' | 'ip6' | 'inet' (default: 'ip')
|
|
70
|
+
dryRun: false, // generate commands without executing (default: false)
|
|
71
|
+
});
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
| Method | Description |
|
|
75
|
+
|---|---|
|
|
76
|
+
| `initialize()` | Create the nftables table and NAT chains. Idempotent. |
|
|
77
|
+
| `cleanup()` | Delete the entire table and clear all tracking. |
|
|
78
|
+
| `status()` | Get an `INftStatus` report of the current managed state. |
|
|
79
|
+
| `applyRuleGroup(id, commands)` | Apply and track a group of raw nft commands. |
|
|
80
|
+
| `removeRuleGroup(id)` | Remove a tracked rule group. |
|
|
81
|
+
| `getRuleGroup(id)` | Retrieve a tracked rule group by ID. |
|
|
82
|
+
|
|
83
|
+
---
|
|
84
|
+
|
|
85
|
+
### 🌐 NAT — `nft.nat`
|
|
86
|
+
|
|
87
|
+
#### Port Forwarding (DNAT)
|
|
88
|
+
|
|
89
|
+
```typescript
|
|
90
|
+
await nft.nat.addPortForwarding('my-service', {
|
|
91
|
+
sourcePort: 443,
|
|
92
|
+
targetHost: '10.0.0.5',
|
|
93
|
+
targetPort: 8443,
|
|
94
|
+
protocol: 'tcp', // 'tcp' | 'udp' | 'both' (default: 'tcp')
|
|
95
|
+
preserveSourceIP: false, // skip masquerade if true (default: false)
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
await nft.nat.removePortForwarding('my-service');
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
#### Port Range Forwarding
|
|
102
|
+
|
|
103
|
+
Map a range of ports to another host:
|
|
104
|
+
|
|
105
|
+
```typescript
|
|
106
|
+
// Forward ports 3000-3010 → 10.0.0.5:3000-3010
|
|
107
|
+
await nft.nat.addPortRange('dev-ports', 3000, 3010, '10.0.0.5', 3000, 'tcp');
|
|
108
|
+
await nft.nat.removePortRange('dev-ports');
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
#### SNAT (Source NAT)
|
|
112
|
+
|
|
113
|
+
```typescript
|
|
114
|
+
await nft.nat.addSnat('egress', {
|
|
115
|
+
sourceAddress: '203.0.113.1',
|
|
116
|
+
targetPort: 80,
|
|
117
|
+
protocol: 'tcp',
|
|
118
|
+
});
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
#### Masquerade
|
|
122
|
+
|
|
123
|
+
```typescript
|
|
124
|
+
await nft.nat.addMasquerade('outbound', {
|
|
125
|
+
targetPort: 443,
|
|
126
|
+
protocol: 'tcp',
|
|
127
|
+
});
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
---
|
|
131
|
+
|
|
132
|
+
### 🛡️ Firewall — `nft.firewall`
|
|
133
|
+
|
|
134
|
+
#### Basic Rules
|
|
135
|
+
|
|
136
|
+
```typescript
|
|
137
|
+
await nft.firewall.addRule('allow-ssh', {
|
|
138
|
+
direction: 'input', // 'input' | 'output' | 'forward'
|
|
139
|
+
action: 'accept', // 'accept' | 'drop' | 'reject'
|
|
140
|
+
sourceIP: '10.0.0.0/24',
|
|
141
|
+
destPort: 22,
|
|
142
|
+
protocol: 'tcp',
|
|
143
|
+
comment: 'Allow SSH from trusted network',
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
await nft.firewall.removeRule('allow-ssh');
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
#### Block an IP
|
|
150
|
+
|
|
151
|
+
```typescript
|
|
152
|
+
await nft.firewall.blockIP('10.0.0.99');
|
|
153
|
+
await nft.firewall.blockIP('192.168.0.0/16', { direction: 'forward' });
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
#### Allow Only Specific IPs on a Port
|
|
157
|
+
|
|
158
|
+
```typescript
|
|
159
|
+
// Only these IPs can reach port 3306 — everything else is dropped
|
|
160
|
+
await nft.firewall.allowOnlyIPs('db-access', ['10.0.0.1', '10.0.0.2'], 3306, 'tcp');
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
#### Stateful Connection Tracking
|
|
164
|
+
|
|
165
|
+
```typescript
|
|
166
|
+
// Allow established/related, drop invalid — on the input chain
|
|
167
|
+
await nft.firewall.enableStatefulTracking('input');
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
#### IP Sets
|
|
171
|
+
|
|
172
|
+
Create named sets and match against them:
|
|
173
|
+
|
|
174
|
+
```typescript
|
|
175
|
+
// Create a set of blocked IPs
|
|
176
|
+
await nft.firewall.createIPSet({
|
|
177
|
+
name: 'blocklist',
|
|
178
|
+
type: 'ipv4_addr',
|
|
179
|
+
elements: ['10.0.0.50', '10.0.0.51'],
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
// Dynamically add/remove elements
|
|
183
|
+
await nft.firewall.addToIPSet('blocklist', ['10.0.0.52']);
|
|
184
|
+
await nft.firewall.removeFromIPSet('blocklist', ['10.0.0.50']);
|
|
185
|
+
|
|
186
|
+
// Clean up
|
|
187
|
+
await nft.firewall.deleteIPSet('blocklist');
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
You can also build set-matching rules directly with the low-level builder:
|
|
191
|
+
|
|
192
|
+
```typescript
|
|
193
|
+
import { buildIPSetMatchRule } from '@push.rocks/smartnftables';
|
|
194
|
+
|
|
195
|
+
const rule = buildIPSetMatchRule('smartnftables', 'ip', {
|
|
196
|
+
setName: 'blocklist',
|
|
197
|
+
direction: 'input',
|
|
198
|
+
matchField: 'saddr',
|
|
199
|
+
action: 'drop',
|
|
200
|
+
});
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
---
|
|
204
|
+
|
|
205
|
+
### ⏱️ Rate Limiting — `nft.rateLimit`
|
|
206
|
+
|
|
207
|
+
#### Packet Rate Limiting
|
|
208
|
+
|
|
209
|
+
```typescript
|
|
210
|
+
// Global: drop packets over 1000/second on port 80
|
|
211
|
+
await nft.rateLimit.addRateLimit('http-global', {
|
|
212
|
+
port: 80,
|
|
213
|
+
protocol: 'tcp',
|
|
214
|
+
rate: '1000/second',
|
|
215
|
+
burst: 50,
|
|
216
|
+
action: 'drop',
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
// Per-IP: each source IP gets its own 100/second limit
|
|
220
|
+
await nft.rateLimit.addRateLimit('http-per-ip', {
|
|
221
|
+
port: 80,
|
|
222
|
+
protocol: 'tcp',
|
|
223
|
+
rate: '100/second',
|
|
224
|
+
perSourceIP: true,
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
await nft.rateLimit.removeRateLimit('http-per-ip');
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
#### Connection Rate Limiting
|
|
231
|
+
|
|
232
|
+
Limit the rate of **new connections** (uses `ct state new`):
|
|
233
|
+
|
|
234
|
+
```typescript
|
|
235
|
+
await nft.rateLimit.addConnectionRateLimit('ssh-connrate', {
|
|
236
|
+
port: 22,
|
|
237
|
+
protocol: 'tcp',
|
|
238
|
+
rate: '5/second',
|
|
239
|
+
perSourceIP: true,
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
await nft.rateLimit.removeConnectionRateLimit('ssh-connrate');
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
---
|
|
246
|
+
|
|
247
|
+
### 🔧 Low-Level Rule Builders
|
|
248
|
+
|
|
249
|
+
For advanced use cases, you can generate raw nft command strings without applying them:
|
|
250
|
+
|
|
251
|
+
```typescript
|
|
252
|
+
import {
|
|
253
|
+
buildDnatRules,
|
|
254
|
+
buildSnatRule,
|
|
255
|
+
buildMasqueradeRule,
|
|
256
|
+
buildFirewallRule,
|
|
257
|
+
buildRateLimitRule,
|
|
258
|
+
buildPerIpRateLimitRule,
|
|
259
|
+
buildConnectionRateRule,
|
|
260
|
+
buildIPSetCreate,
|
|
261
|
+
buildIPSetAddElements,
|
|
262
|
+
buildIPSetRemoveElements,
|
|
263
|
+
buildIPSetDelete,
|
|
264
|
+
buildIPSetMatchRule,
|
|
265
|
+
buildTableSetup,
|
|
266
|
+
buildFilterChains,
|
|
267
|
+
buildTableCleanup,
|
|
268
|
+
} from '@push.rocks/smartnftables';
|
|
269
|
+
|
|
270
|
+
const commands = buildDnatRules('mytable', 'ip', {
|
|
271
|
+
sourcePort: 8080,
|
|
272
|
+
targetHost: '10.0.0.5',
|
|
273
|
+
targetPort: 80,
|
|
274
|
+
});
|
|
275
|
+
// → ['nft add rule ip mytable prerouting tcp dport 8080 dnat to 10.0.0.5:80',
|
|
276
|
+
// 'nft add rule ip mytable postrouting tcp dport 80 masquerade']
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
---
|
|
280
|
+
|
|
281
|
+
### Dry Run Mode 🧪
|
|
282
|
+
|
|
283
|
+
Generate commands without touching the kernel — perfect for testing, debugging, or CI:
|
|
284
|
+
|
|
285
|
+
```typescript
|
|
286
|
+
const nft = new SmartNftables({ dryRun: true });
|
|
287
|
+
await nft.initialize();
|
|
288
|
+
await nft.nat.addPortForwarding('test', {
|
|
289
|
+
sourcePort: 80,
|
|
290
|
+
targetHost: '10.0.0.1',
|
|
291
|
+
targetPort: 8080,
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
console.log(nft.status());
|
|
295
|
+
// Rules tracked in memory, nothing executed
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
---
|
|
299
|
+
|
|
300
|
+
### Status Reporting 📊
|
|
301
|
+
|
|
302
|
+
```typescript
|
|
303
|
+
const status = nft.status();
|
|
304
|
+
// {
|
|
305
|
+
// initialized: true,
|
|
306
|
+
// tableName: 'smartnftables',
|
|
307
|
+
// family: 'ip',
|
|
308
|
+
// isRoot: true,
|
|
309
|
+
// activeGroups: 3,
|
|
310
|
+
// groups: {
|
|
311
|
+
// 'nat:web': { ruleCount: 2, createdAt: 1711411200000 },
|
|
312
|
+
// 'fw:block-10_0_0_99': { ruleCount: 1, createdAt: 1711411200100 },
|
|
313
|
+
// 'ratelimit:http-limit': { ruleCount: 1, createdAt: 1711411200200 },
|
|
314
|
+
// }
|
|
315
|
+
// }
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
## Types
|
|
319
|
+
|
|
320
|
+
All interfaces and types are fully exported for use in your own code:
|
|
321
|
+
|
|
322
|
+
| Type | Description |
|
|
323
|
+
|---|---|
|
|
324
|
+
| `INftDnatRule` | DNAT port forwarding rule config |
|
|
325
|
+
| `INftSnatRule` | Source NAT rule config |
|
|
326
|
+
| `INftMasqueradeRule` | Masquerade rule config |
|
|
327
|
+
| `INftFirewallRule` | Firewall filter rule config |
|
|
328
|
+
| `INftIPSetConfig` | IP set creation config |
|
|
329
|
+
| `INftRateLimitRule` | Rate limiting rule config |
|
|
330
|
+
| `INftConnectionRateRule` | New-connection rate limit config |
|
|
331
|
+
| `ISmartNftablesOptions` | Constructor options |
|
|
332
|
+
| `INftStatus` | Status report shape |
|
|
333
|
+
| `TNftProtocol` | `'tcp' \| 'udp' \| 'both'` |
|
|
334
|
+
| `TNftFamily` | `'ip' \| 'ip6' \| 'inet'` |
|
|
335
|
+
| `TFirewallAction` | `'accept' \| 'drop' \| 'reject'` |
|
|
336
|
+
| `TCtState` | `'new' \| 'established' \| 'related' \| 'invalid'` |
|
|
337
|
+
|
|
338
|
+
## License and Legal Information
|
|
339
|
+
|
|
340
|
+
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file.
|
|
341
|
+
|
|
342
|
+
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
|
|
343
|
+
|
|
344
|
+
### Trademarks
|
|
345
|
+
|
|
346
|
+
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.
|
|
347
|
+
|
|
348
|
+
Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
|
|
349
|
+
|
|
350
|
+
### Company Information
|
|
351
|
+
|
|
352
|
+
Task Venture Capital GmbH
|
|
353
|
+
Registered at District Court Bremen HRB 35230 HB, Germany
|
|
354
|
+
|
|
355
|
+
For any legal inquiries or further information, please contact us via email at hello@task.vc.
|
|
356
|
+
|
|
357
|
+
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* autocreated commitinfo by @push.rocks/commitinfo
|
|
3
|
+
*/
|
|
4
|
+
export const commitinfo = {
|
|
5
|
+
name: '@push.rocks/smartnftables',
|
|
6
|
+
version: '1.0.1',
|
|
7
|
+
description: 'A TypeScript module for managing nftables rules including NAT, firewall, and rate limiting with a high-level API.'
|
|
8
|
+
}
|
package/ts/index.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// Main facade
|
|
2
|
+
export { SmartNftables } from './nft.manager.js';
|
|
3
|
+
|
|
4
|
+
// Sub-managers
|
|
5
|
+
export { NatManager } from './nft.manager.nat.js';
|
|
6
|
+
export { FirewallManager } from './nft.manager.firewall.js';
|
|
7
|
+
export { RateLimitManager } from './nft.manager.ratelimit.js';
|
|
8
|
+
|
|
9
|
+
// Executor
|
|
10
|
+
export { NftExecutor, NftNotRootError, NftCommandError } from './nft.executor.js';
|
|
11
|
+
|
|
12
|
+
// Rule builders (for advanced usage)
|
|
13
|
+
export {
|
|
14
|
+
buildTableSetup,
|
|
15
|
+
buildFilterChains,
|
|
16
|
+
buildTableCleanup,
|
|
17
|
+
} from './nft.rulebuilder.table.js';
|
|
18
|
+
|
|
19
|
+
export {
|
|
20
|
+
buildDnatRules,
|
|
21
|
+
buildSnatRule,
|
|
22
|
+
buildMasqueradeRule,
|
|
23
|
+
} from './nft.rulebuilder.nat.js';
|
|
24
|
+
|
|
25
|
+
export {
|
|
26
|
+
buildRateLimitRule,
|
|
27
|
+
buildPerIpRateLimitRule,
|
|
28
|
+
buildConnectionRateRule,
|
|
29
|
+
} from './nft.rulebuilder.ratelimit.js';
|
|
30
|
+
|
|
31
|
+
export {
|
|
32
|
+
buildFirewallRule,
|
|
33
|
+
buildIPSetCreate,
|
|
34
|
+
buildIPSetAddElements,
|
|
35
|
+
buildIPSetRemoveElements,
|
|
36
|
+
buildIPSetDelete,
|
|
37
|
+
buildIPSetMatchRule,
|
|
38
|
+
} from './nft.rulebuilder.firewall.js';
|
|
39
|
+
|
|
40
|
+
// Types
|
|
41
|
+
export type {
|
|
42
|
+
TNftProtocol,
|
|
43
|
+
TNftFamily,
|
|
44
|
+
TNftChainHook,
|
|
45
|
+
TNftChainType,
|
|
46
|
+
TNftPolicy,
|
|
47
|
+
TFirewallAction,
|
|
48
|
+
TCtState,
|
|
49
|
+
INftDnatRule,
|
|
50
|
+
INftSnatRule,
|
|
51
|
+
INftMasqueradeRule,
|
|
52
|
+
INftRateLimitRule,
|
|
53
|
+
INftConnectionRateRule,
|
|
54
|
+
INftFirewallRule,
|
|
55
|
+
INftIPSetConfig,
|
|
56
|
+
INftRuleGroup,
|
|
57
|
+
ISmartNftablesOptions,
|
|
58
|
+
INftStatus,
|
|
59
|
+
} from './nft.types.js';
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import * as plugins from './plugins.js';
|
|
2
|
+
|
|
3
|
+
const execFile = plugins.util.promisify(plugins.childProcess.execFile);
|
|
4
|
+
|
|
5
|
+
export class NftNotRootError extends Error {
|
|
6
|
+
constructor() {
|
|
7
|
+
super('Not running as root — nftables commands require root privileges');
|
|
8
|
+
this.name = 'NftNotRootError';
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export class NftCommandError extends Error {
|
|
13
|
+
public readonly command: string;
|
|
14
|
+
public readonly stderr: string;
|
|
15
|
+
|
|
16
|
+
constructor(command: string, stderr: string) {
|
|
17
|
+
super(`nft command failed: ${command} — ${stderr}`);
|
|
18
|
+
this.name = 'NftCommandError';
|
|
19
|
+
this.command = command;
|
|
20
|
+
this.stderr = stderr;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Low-level executor for nft CLI commands.
|
|
26
|
+
*/
|
|
27
|
+
export class NftExecutor {
|
|
28
|
+
private dryRun: boolean;
|
|
29
|
+
|
|
30
|
+
constructor(options?: { dryRun?: boolean }) {
|
|
31
|
+
this.dryRun = options?.dryRun ?? false;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Check if running as root (euid 0). */
|
|
35
|
+
public isRoot(): boolean {
|
|
36
|
+
return process.getuid?.() === 0;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Execute a single nft command.
|
|
41
|
+
* The command may or may not start with "nft " — the prefix is stripped if present.
|
|
42
|
+
* Returns stdout on success.
|
|
43
|
+
*/
|
|
44
|
+
public async exec(command: string): Promise<string> {
|
|
45
|
+
if (this.dryRun) {
|
|
46
|
+
return '';
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Strip "nft " prefix if present
|
|
50
|
+
const args = command.startsWith('nft ') ? command.slice(4) : command;
|
|
51
|
+
|
|
52
|
+
const { stdout } = await execFile('nft', args.split(/\s+/));
|
|
53
|
+
return stdout;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Execute multiple nft commands sequentially.
|
|
58
|
+
* By default stops on first failure. Set continueOnError to keep going.
|
|
59
|
+
*/
|
|
60
|
+
public async execBatch(
|
|
61
|
+
commands: string[],
|
|
62
|
+
options?: { continueOnError?: boolean }
|
|
63
|
+
): Promise<void> {
|
|
64
|
+
for (const cmd of commands) {
|
|
65
|
+
try {
|
|
66
|
+
await this.exec(cmd);
|
|
67
|
+
} catch (err) {
|
|
68
|
+
if (!options?.continueOnError) {
|
|
69
|
+
throw err;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import type { SmartNftables } from './nft.manager.js';
|
|
2
|
+
import type { INftFirewallRule, INftIPSetConfig } from './nft.types.js';
|
|
3
|
+
import {
|
|
4
|
+
buildFirewallRule,
|
|
5
|
+
buildIPSetCreate,
|
|
6
|
+
buildIPSetAddElements,
|
|
7
|
+
buildIPSetRemoveElements,
|
|
8
|
+
buildIPSetDelete,
|
|
9
|
+
buildIPSetMatchRule,
|
|
10
|
+
} from './nft.rulebuilder.firewall.js';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Manages firewall (filter) rules, IP sets, and convenience methods.
|
|
14
|
+
*/
|
|
15
|
+
export class FirewallManager {
|
|
16
|
+
constructor(private parent: SmartNftables) {}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Add a firewall rule (input/output/forward).
|
|
20
|
+
*/
|
|
21
|
+
public async addRule(groupId: string, rule: INftFirewallRule): Promise<void> {
|
|
22
|
+
await this.parent.ensureFilterChains();
|
|
23
|
+
const commands = buildFirewallRule(this.parent.tableName, this.parent.family, rule);
|
|
24
|
+
await this.parent.applyRuleGroup(`fw:${groupId}`, commands);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Remove a firewall rule group.
|
|
29
|
+
*/
|
|
30
|
+
public async removeRule(groupId: string): Promise<void> {
|
|
31
|
+
await this.parent.removeRuleGroup(`fw:${groupId}`);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Create a named IP set.
|
|
36
|
+
*/
|
|
37
|
+
public async createIPSet(config: INftIPSetConfig): Promise<void> {
|
|
38
|
+
await this.parent.ensureInitialized();
|
|
39
|
+
const commands = buildIPSetCreate(this.parent.tableName, this.parent.family, config);
|
|
40
|
+
await this.parent.applyRuleGroup(`ipset:${config.name}`, commands);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Add elements to an existing IP set.
|
|
45
|
+
*/
|
|
46
|
+
public async addToIPSet(setName: string, elements: string[]): Promise<void> {
|
|
47
|
+
const commands = buildIPSetAddElements(this.parent.tableName, this.parent.family, setName, elements);
|
|
48
|
+
if (commands.length > 0) {
|
|
49
|
+
await this.parent.executor.execBatch(commands);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Remove elements from an IP set.
|
|
55
|
+
*/
|
|
56
|
+
public async removeFromIPSet(setName: string, elements: string[]): Promise<void> {
|
|
57
|
+
const commands = buildIPSetRemoveElements(this.parent.tableName, this.parent.family, setName, elements);
|
|
58
|
+
if (commands.length > 0) {
|
|
59
|
+
await this.parent.executor.execBatch(commands);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Delete an IP set entirely.
|
|
65
|
+
*/
|
|
66
|
+
public async deleteIPSet(setName: string): Promise<void> {
|
|
67
|
+
const commands = buildIPSetDelete(this.parent.tableName, this.parent.family, setName);
|
|
68
|
+
await this.parent.executor.execBatch(commands);
|
|
69
|
+
await this.parent.removeRuleGroup(`ipset:${setName}`);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Convenience: block an IP or CIDR subnet.
|
|
74
|
+
*/
|
|
75
|
+
public async blockIP(ip: string, options?: { direction?: 'input' | 'forward' }): Promise<void> {
|
|
76
|
+
const direction = options?.direction ?? 'input';
|
|
77
|
+
const safeId = ip.replace(/[/.]/g, '_');
|
|
78
|
+
await this.addRule(`block-${safeId}`, {
|
|
79
|
+
direction,
|
|
80
|
+
action: 'drop',
|
|
81
|
+
sourceIP: ip,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Convenience: allow only specific IPs on a port.
|
|
87
|
+
* Adds accept rules for each IP, then a drop rule for everything else on that port.
|
|
88
|
+
*/
|
|
89
|
+
public async allowOnlyIPs(
|
|
90
|
+
groupId: string,
|
|
91
|
+
ips: string[],
|
|
92
|
+
port?: number,
|
|
93
|
+
protocol?: 'tcp' | 'udp' | 'both',
|
|
94
|
+
): Promise<void> {
|
|
95
|
+
await this.parent.ensureFilterChains();
|
|
96
|
+
const commands: string[] = [];
|
|
97
|
+
|
|
98
|
+
for (const ip of ips) {
|
|
99
|
+
const acceptCmds = buildFirewallRule(this.parent.tableName, this.parent.family, {
|
|
100
|
+
direction: 'input',
|
|
101
|
+
action: 'accept',
|
|
102
|
+
sourceIP: ip,
|
|
103
|
+
destPort: port,
|
|
104
|
+
protocol,
|
|
105
|
+
});
|
|
106
|
+
commands.push(...acceptCmds);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// Drop everything else on that port
|
|
110
|
+
const dropCmds = buildFirewallRule(this.parent.tableName, this.parent.family, {
|
|
111
|
+
direction: 'input',
|
|
112
|
+
action: 'drop',
|
|
113
|
+
destPort: port,
|
|
114
|
+
protocol,
|
|
115
|
+
});
|
|
116
|
+
commands.push(...dropCmds);
|
|
117
|
+
|
|
118
|
+
await this.parent.applyRuleGroup(`fw:allowonly:${groupId}`, commands);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Convenience: enable stateful connection tracking.
|
|
123
|
+
* Allows established+related, drops invalid.
|
|
124
|
+
*/
|
|
125
|
+
public async enableStatefulTracking(chain?: 'input' | 'forward' | 'output'): Promise<void> {
|
|
126
|
+
await this.parent.ensureFilterChains();
|
|
127
|
+
const direction = chain ?? 'input';
|
|
128
|
+
const commands: string[] = [];
|
|
129
|
+
|
|
130
|
+
// Allow established and related connections
|
|
131
|
+
const allowCmds = buildFirewallRule(this.parent.tableName, this.parent.family, {
|
|
132
|
+
direction,
|
|
133
|
+
action: 'accept',
|
|
134
|
+
ctStates: ['established', 'related'],
|
|
135
|
+
});
|
|
136
|
+
commands.push(...allowCmds);
|
|
137
|
+
|
|
138
|
+
// Drop invalid connections
|
|
139
|
+
const dropCmds = buildFirewallRule(this.parent.tableName, this.parent.family, {
|
|
140
|
+
direction,
|
|
141
|
+
action: 'drop',
|
|
142
|
+
ctStates: ['invalid'],
|
|
143
|
+
});
|
|
144
|
+
commands.push(...dropCmds);
|
|
145
|
+
|
|
146
|
+
await this.parent.applyRuleGroup(`fw:stateful:${direction}`, commands);
|
|
147
|
+
}
|
|
148
|
+
}
|