@push.rocks/smartproxy 22.4.2 → 23.0.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/changelog.md +36 -0
- package/dist_rust/rustproxy +0 -0
- package/dist_ts/00_commitinfo_data.js +1 -1
- package/dist_ts/index.d.ts +1 -6
- package/dist_ts/index.js +3 -11
- package/dist_ts/protocols/common/fragment-handler.js +5 -1
- package/dist_ts/proxies/index.d.ts +1 -6
- package/dist_ts/proxies/index.js +2 -8
- package/dist_ts/proxies/smart-proxy/index.d.ts +5 -10
- package/dist_ts/proxies/smart-proxy/index.js +7 -13
- package/dist_ts/proxies/smart-proxy/models/interfaces.d.ts +5 -2
- package/dist_ts/proxies/smart-proxy/models/route-types.js +1 -1
- package/dist_ts/proxies/smart-proxy/route-preprocessor.d.ts +37 -0
- package/dist_ts/proxies/smart-proxy/route-preprocessor.js +103 -0
- package/dist_ts/proxies/smart-proxy/rust-binary-locator.d.ts +23 -0
- package/dist_ts/proxies/smart-proxy/rust-binary-locator.js +104 -0
- package/dist_ts/proxies/smart-proxy/rust-metrics-adapter.d.ts +74 -0
- package/dist_ts/proxies/smart-proxy/rust-metrics-adapter.js +146 -0
- package/dist_ts/proxies/smart-proxy/rust-proxy-bridge.d.ts +49 -0
- package/dist_ts/proxies/smart-proxy/rust-proxy-bridge.js +259 -0
- package/dist_ts/proxies/smart-proxy/smart-proxy.d.ts +39 -157
- package/dist_ts/proxies/smart-proxy/smart-proxy.js +224 -621
- package/dist_ts/proxies/smart-proxy/socket-handler-server.d.ts +45 -0
- package/dist_ts/proxies/smart-proxy/socket-handler-server.js +253 -0
- package/dist_ts/routing/index.d.ts +1 -1
- package/dist_ts/routing/index.js +3 -3
- package/dist_ts/routing/models/http-types.d.ts +119 -4
- package/dist_ts/routing/models/http-types.js +93 -5
- package/package.json +1 -1
- package/readme.md +444 -219
- package/ts/00_commitinfo_data.ts +1 -1
- package/ts/index.ts +4 -15
- package/ts/protocols/common/fragment-handler.ts +4 -0
- package/ts/proxies/index.ts +1 -12
- package/ts/proxies/smart-proxy/index.ts +6 -13
- package/ts/proxies/smart-proxy/models/interfaces.ts +6 -4
- package/ts/proxies/smart-proxy/models/route-types.ts +0 -2
- package/ts/proxies/smart-proxy/route-preprocessor.ts +122 -0
- package/ts/proxies/smart-proxy/rust-binary-locator.ts +112 -0
- package/ts/proxies/smart-proxy/rust-metrics-adapter.ts +161 -0
- package/ts/proxies/smart-proxy/rust-proxy-bridge.ts +310 -0
- package/ts/proxies/smart-proxy/smart-proxy.ts +282 -798
- package/ts/proxies/smart-proxy/socket-handler-server.ts +279 -0
- package/ts/routing/index.ts +2 -2
- package/ts/routing/models/http-types.ts +147 -4
- package/dist_ts/proxies/nftables-proxy/index.d.ts +0 -6
- package/dist_ts/proxies/nftables-proxy/index.js +0 -7
- package/dist_ts/proxies/nftables-proxy/models/errors.d.ts +0 -15
- package/dist_ts/proxies/nftables-proxy/models/errors.js +0 -28
- package/dist_ts/proxies/nftables-proxy/models/index.d.ts +0 -5
- package/dist_ts/proxies/nftables-proxy/models/index.js +0 -6
- package/dist_ts/proxies/nftables-proxy/models/interfaces.d.ts +0 -75
- package/dist_ts/proxies/nftables-proxy/models/interfaces.js +0 -5
- package/dist_ts/proxies/nftables-proxy/nftables-proxy.d.ts +0 -124
- package/dist_ts/proxies/nftables-proxy/nftables-proxy.js +0 -1374
- package/dist_ts/proxies/nftables-proxy/utils/index.d.ts +0 -9
- package/dist_ts/proxies/nftables-proxy/utils/index.js +0 -12
- package/dist_ts/proxies/nftables-proxy/utils/nft-command-executor.d.ts +0 -66
- package/dist_ts/proxies/nftables-proxy/utils/nft-command-executor.js +0 -131
- package/dist_ts/proxies/nftables-proxy/utils/nft-port-spec-normalizer.d.ts +0 -39
- package/dist_ts/proxies/nftables-proxy/utils/nft-port-spec-normalizer.js +0 -112
- package/dist_ts/proxies/nftables-proxy/utils/nft-rule-validator.d.ts +0 -59
- package/dist_ts/proxies/nftables-proxy/utils/nft-rule-validator.js +0 -130
- package/ts/proxies/http-proxy/connection-pool.ts +0 -228
- package/ts/proxies/http-proxy/context-creator.ts +0 -145
- package/ts/proxies/http-proxy/default-certificates.ts +0 -150
- package/ts/proxies/http-proxy/function-cache.ts +0 -279
- package/ts/proxies/http-proxy/handlers/index.ts +0 -5
- package/ts/proxies/http-proxy/http-proxy.ts +0 -669
- package/ts/proxies/http-proxy/http-request-handler.ts +0 -331
- package/ts/proxies/http-proxy/http2-request-handler.ts +0 -255
- package/ts/proxies/http-proxy/index.ts +0 -18
- package/ts/proxies/http-proxy/models/http-types.ts +0 -148
- package/ts/proxies/http-proxy/models/index.ts +0 -5
- package/ts/proxies/http-proxy/models/types.ts +0 -125
- package/ts/proxies/http-proxy/request-handler.ts +0 -878
- package/ts/proxies/http-proxy/security-manager.ts +0 -413
- package/ts/proxies/http-proxy/websocket-handler.ts +0 -581
- package/ts/proxies/nftables-proxy/index.ts +0 -6
- package/ts/proxies/nftables-proxy/models/errors.ts +0 -30
- package/ts/proxies/nftables-proxy/models/index.ts +0 -5
- package/ts/proxies/nftables-proxy/models/interfaces.ts +0 -94
- package/ts/proxies/nftables-proxy/nftables-proxy.ts +0 -1754
- package/ts/proxies/nftables-proxy/utils/index.ts +0 -38
- package/ts/proxies/nftables-proxy/utils/nft-command-executor.ts +0 -162
- package/ts/proxies/nftables-proxy/utils/nft-port-spec-normalizer.ts +0 -125
- package/ts/proxies/nftables-proxy/utils/nft-rule-validator.ts +0 -156
- package/ts/proxies/smart-proxy/acme-state-manager.ts +0 -112
- package/ts/proxies/smart-proxy/cert-store.ts +0 -92
- package/ts/proxies/smart-proxy/certificate-manager.ts +0 -895
- package/ts/proxies/smart-proxy/connection-manager.ts +0 -809
- package/ts/proxies/smart-proxy/http-proxy-bridge.ts +0 -213
- package/ts/proxies/smart-proxy/metrics-collector.ts +0 -453
- package/ts/proxies/smart-proxy/nftables-manager.ts +0 -271
- package/ts/proxies/smart-proxy/port-manager.ts +0 -358
- package/ts/proxies/smart-proxy/route-connection-handler.ts +0 -1712
- package/ts/proxies/smart-proxy/route-orchestrator.ts +0 -297
- package/ts/proxies/smart-proxy/security-manager.ts +0 -269
- package/ts/proxies/smart-proxy/throughput-tracker.ts +0 -138
- package/ts/proxies/smart-proxy/timeout-manager.ts +0 -196
- package/ts/proxies/smart-proxy/tls-manager.ts +0 -171
|
@@ -1,1754 +0,0 @@
|
|
|
1
|
-
import { exec, execSync } from 'child_process';
|
|
2
|
-
import { promisify } from 'util';
|
|
3
|
-
import * as fs from 'fs';
|
|
4
|
-
import * as path from 'path';
|
|
5
|
-
import * as os from 'os';
|
|
6
|
-
import { AsyncFileSystem } from '../../core/utils/fs-utils.js';
|
|
7
|
-
import {
|
|
8
|
-
NftValidationError,
|
|
9
|
-
NftExecutionError,
|
|
10
|
-
NftResourceError
|
|
11
|
-
} from './models/index.js';
|
|
12
|
-
import type {
|
|
13
|
-
PortRange,
|
|
14
|
-
NfTableProxyOptions,
|
|
15
|
-
NfTablesStatus
|
|
16
|
-
} from './models/index.js';
|
|
17
|
-
import {
|
|
18
|
-
NftCommandExecutor,
|
|
19
|
-
normalizePortSpec,
|
|
20
|
-
validateSettings,
|
|
21
|
-
filterIPsByFamily
|
|
22
|
-
} from './utils/index.js';
|
|
23
|
-
|
|
24
|
-
const execAsync = promisify(exec);
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
* Represents a rule added to nftables
|
|
28
|
-
*/
|
|
29
|
-
interface NfTablesRule {
|
|
30
|
-
handle?: number; // Rule handle for deletion
|
|
31
|
-
tableFamily: string; // 'ip' or 'ip6'
|
|
32
|
-
tableName: string; // Table name
|
|
33
|
-
chainName: string; // Chain name
|
|
34
|
-
ruleContents: string; // Rule definition
|
|
35
|
-
added: boolean; // Whether the rule was successfully added
|
|
36
|
-
verified?: boolean; // Whether the rule has been verified as applied
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* NfTablesProxy sets up nftables NAT rules to forward TCP traffic.
|
|
41
|
-
* Enhanced with multi-port support, IPv6, connection tracking, metrics,
|
|
42
|
-
* and more advanced features.
|
|
43
|
-
*/
|
|
44
|
-
export class NfTablesProxy {
|
|
45
|
-
public settings: NfTableProxyOptions;
|
|
46
|
-
private rules: NfTablesRule[] = [];
|
|
47
|
-
private ipSets: Map<string, string[]> = new Map(); // Store IP sets for tracking
|
|
48
|
-
private ruleTag: string;
|
|
49
|
-
private tableName: string;
|
|
50
|
-
private tempFilePath: string;
|
|
51
|
-
private executor: NftCommandExecutor;
|
|
52
|
-
private static NFT_CMD = 'nft';
|
|
53
|
-
|
|
54
|
-
constructor(settings: NfTableProxyOptions) {
|
|
55
|
-
// Validate inputs to prevent command injection
|
|
56
|
-
validateSettings(settings);
|
|
57
|
-
|
|
58
|
-
// Set default settings
|
|
59
|
-
this.settings = {
|
|
60
|
-
...settings,
|
|
61
|
-
toHost: settings.toHost || 'localhost',
|
|
62
|
-
protocol: settings.protocol || 'tcp',
|
|
63
|
-
enableLogging: settings.enableLogging !== undefined ? settings.enableLogging : false,
|
|
64
|
-
ipv6Support: settings.ipv6Support !== undefined ? settings.ipv6Support : false,
|
|
65
|
-
tableName: settings.tableName || 'portproxy',
|
|
66
|
-
logFormat: settings.logFormat || 'plain',
|
|
67
|
-
useIPSets: settings.useIPSets !== undefined ? settings.useIPSets : true,
|
|
68
|
-
maxRetries: settings.maxRetries || 3,
|
|
69
|
-
retryDelayMs: settings.retryDelayMs || 1000,
|
|
70
|
-
useAdvancedNAT: settings.useAdvancedNAT !== undefined ? settings.useAdvancedNAT : false,
|
|
71
|
-
};
|
|
72
|
-
|
|
73
|
-
// Generate a unique identifier for the rules added by this instance
|
|
74
|
-
this.ruleTag = `NfTablesProxy:${Date.now()}:${Math.random().toString(36).substr(2, 5)}`;
|
|
75
|
-
|
|
76
|
-
// Set table name
|
|
77
|
-
this.tableName = this.settings.tableName || 'portproxy';
|
|
78
|
-
|
|
79
|
-
// Create a temp file path for batch operations
|
|
80
|
-
this.tempFilePath = path.join(os.tmpdir(), `nft-rules-${Date.now()}.nft`);
|
|
81
|
-
|
|
82
|
-
// Create the command executor
|
|
83
|
-
this.executor = new NftCommandExecutor(
|
|
84
|
-
(level, message, data) => this.log(level, message, data),
|
|
85
|
-
{
|
|
86
|
-
maxRetries: this.settings.maxRetries,
|
|
87
|
-
retryDelayMs: this.settings.retryDelayMs,
|
|
88
|
-
tempFilePath: this.tempFilePath
|
|
89
|
-
}
|
|
90
|
-
);
|
|
91
|
-
|
|
92
|
-
// Register cleanup handlers if deleteOnExit is true
|
|
93
|
-
if (this.settings.deleteOnExit) {
|
|
94
|
-
// Synchronous cleanup for 'exit' event (only sync code runs here)
|
|
95
|
-
const syncCleanup = () => {
|
|
96
|
-
try {
|
|
97
|
-
this.stopSync();
|
|
98
|
-
} catch (err) {
|
|
99
|
-
this.log('error', 'Error cleaning nftables rules on exit:', { error: err.message });
|
|
100
|
-
}
|
|
101
|
-
};
|
|
102
|
-
|
|
103
|
-
// Async cleanup for signal handlers (preferred, non-blocking)
|
|
104
|
-
const asyncCleanup = async () => {
|
|
105
|
-
try {
|
|
106
|
-
await this.stop();
|
|
107
|
-
} catch (err) {
|
|
108
|
-
this.log('error', 'Error cleaning nftables rules on signal:', { error: err.message });
|
|
109
|
-
}
|
|
110
|
-
};
|
|
111
|
-
|
|
112
|
-
process.on('exit', syncCleanup);
|
|
113
|
-
process.on('SIGINT', () => {
|
|
114
|
-
asyncCleanup().finally(() => process.exit());
|
|
115
|
-
});
|
|
116
|
-
process.on('SIGTERM', () => {
|
|
117
|
-
asyncCleanup().finally(() => process.exit());
|
|
118
|
-
});
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
/**
|
|
123
|
-
* Checks if nftables is available and the required modules are loaded
|
|
124
|
-
*/
|
|
125
|
-
private async checkNftablesAvailability(): Promise<boolean> {
|
|
126
|
-
const available = await this.executor.checkAvailability();
|
|
127
|
-
|
|
128
|
-
if (available && this.settings.useAdvancedNAT) {
|
|
129
|
-
await this.executor.checkConntrackModules();
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
return available;
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
/**
|
|
136
|
-
* Creates the necessary tables and chains
|
|
137
|
-
*/
|
|
138
|
-
private async setupTablesAndChains(isIpv6: boolean = false): Promise<boolean> {
|
|
139
|
-
const family = isIpv6 ? 'ip6' : 'ip';
|
|
140
|
-
|
|
141
|
-
try {
|
|
142
|
-
// Check if the table already exists
|
|
143
|
-
const stdout = await this.executor.executeWithRetry(
|
|
144
|
-
`${NfTablesProxy.NFT_CMD} list tables ${family}`,
|
|
145
|
-
this.settings.maxRetries,
|
|
146
|
-
this.settings.retryDelayMs
|
|
147
|
-
);
|
|
148
|
-
|
|
149
|
-
const tableExists = stdout.includes(`table ${family} ${this.tableName}`);
|
|
150
|
-
|
|
151
|
-
if (!tableExists) {
|
|
152
|
-
// Create the table
|
|
153
|
-
await this.executor.executeWithRetry(
|
|
154
|
-
`${NfTablesProxy.NFT_CMD} add table ${family} ${this.tableName}`,
|
|
155
|
-
this.settings.maxRetries,
|
|
156
|
-
this.settings.retryDelayMs
|
|
157
|
-
);
|
|
158
|
-
|
|
159
|
-
this.log('info', `Created table ${family} ${this.tableName}`);
|
|
160
|
-
|
|
161
|
-
// Create the nat chain for the prerouting hook
|
|
162
|
-
await this.executor.executeWithRetry(
|
|
163
|
-
`${NfTablesProxy.NFT_CMD} add chain ${family} ${this.tableName} nat_prerouting { type nat hook prerouting priority -100 ; }`,
|
|
164
|
-
this.settings.maxRetries,
|
|
165
|
-
this.settings.retryDelayMs
|
|
166
|
-
);
|
|
167
|
-
|
|
168
|
-
this.log('info', `Created nat_prerouting chain in ${family} ${this.tableName}`);
|
|
169
|
-
|
|
170
|
-
// Create the nat chain for the postrouting hook if not preserving source IP
|
|
171
|
-
if (!this.settings.preserveSourceIP) {
|
|
172
|
-
await this.executor.executeWithRetry(
|
|
173
|
-
`${NfTablesProxy.NFT_CMD} add chain ${family} ${this.tableName} nat_postrouting { type nat hook postrouting priority 100 ; }`,
|
|
174
|
-
this.settings.maxRetries,
|
|
175
|
-
this.settings.retryDelayMs
|
|
176
|
-
);
|
|
177
|
-
|
|
178
|
-
this.log('info', `Created nat_postrouting chain in ${family} ${this.tableName}`);
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
// Create the chain for NetworkProxy integration if needed
|
|
182
|
-
if (this.settings.netProxyIntegration?.enabled && this.settings.netProxyIntegration.redirectLocalhost) {
|
|
183
|
-
await this.executor.executeWithRetry(
|
|
184
|
-
`${NfTablesProxy.NFT_CMD} add chain ${family} ${this.tableName} nat_output { type nat hook output priority 0 ; }`,
|
|
185
|
-
this.settings.maxRetries,
|
|
186
|
-
this.settings.retryDelayMs
|
|
187
|
-
);
|
|
188
|
-
|
|
189
|
-
this.log('info', `Created nat_output chain in ${family} ${this.tableName}`);
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
// Create the QoS chain if needed
|
|
193
|
-
if (this.settings.qos?.enabled) {
|
|
194
|
-
await this.executor.executeWithRetry(
|
|
195
|
-
`${NfTablesProxy.NFT_CMD} add chain ${family} ${this.tableName} qos_forward { type filter hook forward priority 0 ; }`,
|
|
196
|
-
this.settings.maxRetries,
|
|
197
|
-
this.settings.retryDelayMs
|
|
198
|
-
);
|
|
199
|
-
|
|
200
|
-
this.log('info', `Created QoS forward chain in ${family} ${this.tableName}`);
|
|
201
|
-
}
|
|
202
|
-
} else {
|
|
203
|
-
this.log('info', `Table ${family} ${this.tableName} already exists, using existing table`);
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
return true;
|
|
207
|
-
} catch (err) {
|
|
208
|
-
this.log('error', `Failed to set up tables and chains: ${err.message}`);
|
|
209
|
-
return false;
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
/**
|
|
214
|
-
* Creates IP sets for efficient filtering of large IP lists
|
|
215
|
-
*/
|
|
216
|
-
private async createIPSet(
|
|
217
|
-
family: string,
|
|
218
|
-
setName: string,
|
|
219
|
-
ips: string[],
|
|
220
|
-
setType: 'ipv4_addr' | 'ipv6_addr' = 'ipv4_addr'
|
|
221
|
-
): Promise<boolean> {
|
|
222
|
-
try {
|
|
223
|
-
// Filter IPs based on family
|
|
224
|
-
const filteredIPs = filterIPsByFamily(ips, family as 'ip' | 'ip6');
|
|
225
|
-
|
|
226
|
-
if (filteredIPs.length === 0) {
|
|
227
|
-
this.log('info', `No IP addresses of type ${setType} to add to set ${setName}`);
|
|
228
|
-
return true;
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
// Check if set already exists
|
|
232
|
-
try {
|
|
233
|
-
const sets = await this.executor.executeWithRetry(
|
|
234
|
-
`${NfTablesProxy.NFT_CMD} list sets ${family} ${this.tableName}`,
|
|
235
|
-
this.settings.maxRetries,
|
|
236
|
-
this.settings.retryDelayMs
|
|
237
|
-
);
|
|
238
|
-
|
|
239
|
-
if (sets.includes(`set ${setName} {`)) {
|
|
240
|
-
this.log('info', `IP set ${setName} already exists, will add elements`);
|
|
241
|
-
} else {
|
|
242
|
-
// Create the set
|
|
243
|
-
await this.executor.executeWithRetry(
|
|
244
|
-
`${NfTablesProxy.NFT_CMD} add set ${family} ${this.tableName} ${setName} { type ${setType}; }`,
|
|
245
|
-
this.settings.maxRetries,
|
|
246
|
-
this.settings.retryDelayMs
|
|
247
|
-
);
|
|
248
|
-
|
|
249
|
-
this.log('info', `Created IP set ${setName} for ${family} with type ${setType}`);
|
|
250
|
-
}
|
|
251
|
-
} catch (err) {
|
|
252
|
-
// Set might not exist yet, create it
|
|
253
|
-
await this.executor.executeWithRetry(
|
|
254
|
-
`${NfTablesProxy.NFT_CMD} add set ${family} ${this.tableName} ${setName} { type ${setType}; }`,
|
|
255
|
-
this.settings.maxRetries,
|
|
256
|
-
this.settings.retryDelayMs
|
|
257
|
-
);
|
|
258
|
-
|
|
259
|
-
this.log('info', `Created IP set ${setName} for ${family} with type ${setType}`);
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
// Add IPs to the set in batches to avoid command line length limitations
|
|
263
|
-
const batchSize = 100;
|
|
264
|
-
for (let i = 0; i < filteredIPs.length; i += batchSize) {
|
|
265
|
-
const batch = filteredIPs.slice(i, i + batchSize);
|
|
266
|
-
const elements = batch.join(', ');
|
|
267
|
-
|
|
268
|
-
await this.executor.executeWithRetry(
|
|
269
|
-
`${NfTablesProxy.NFT_CMD} add element ${family} ${this.tableName} ${setName} { ${elements} }`,
|
|
270
|
-
this.settings.maxRetries,
|
|
271
|
-
this.settings.retryDelayMs
|
|
272
|
-
);
|
|
273
|
-
|
|
274
|
-
this.log('info', `Added batch of ${batch.length} IPs to set ${setName}`);
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
// Track the IP set
|
|
278
|
-
this.ipSets.set(`${family}:${setName}`, filteredIPs);
|
|
279
|
-
|
|
280
|
-
return true;
|
|
281
|
-
} catch (err) {
|
|
282
|
-
this.log('error', `Failed to create IP set ${setName}: ${err.message}`);
|
|
283
|
-
return false;
|
|
284
|
-
}
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
/**
|
|
288
|
-
* Adds source IP filtering rules, potentially using IP sets for efficiency
|
|
289
|
-
*/
|
|
290
|
-
private async addSourceIPFilters(isIpv6: boolean = false): Promise<boolean> {
|
|
291
|
-
if (!this.settings.ipAllowList && !this.settings.ipBlockList) {
|
|
292
|
-
return true; // Nothing to do
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
const family = isIpv6 ? 'ip6' : 'ip';
|
|
296
|
-
const chain = 'nat_prerouting';
|
|
297
|
-
const setType = isIpv6 ? 'ipv6_addr' : 'ipv4_addr';
|
|
298
|
-
|
|
299
|
-
try {
|
|
300
|
-
// Start building the ruleset file content
|
|
301
|
-
let rulesetContent = '';
|
|
302
|
-
|
|
303
|
-
// Using IP sets for more efficient rule processing with large IP lists
|
|
304
|
-
if (this.settings.useIPSets) {
|
|
305
|
-
// Create sets for banned and allowed IPs if needed
|
|
306
|
-
if (this.settings.ipBlockList && this.settings.ipBlockList.length > 0) {
|
|
307
|
-
const setName = 'banned_ips';
|
|
308
|
-
await this.createIPSet(family, setName, this.settings.ipBlockList, setType as any);
|
|
309
|
-
|
|
310
|
-
// Add rule to drop traffic from banned IPs
|
|
311
|
-
const rule = `add rule ${family} ${this.tableName} ${chain} ip${isIpv6 ? '6' : ''} saddr @${setName} drop comment "${this.ruleTag}:BANNED_SET"`;
|
|
312
|
-
rulesetContent += `${rule}\n`;
|
|
313
|
-
|
|
314
|
-
this.rules.push({
|
|
315
|
-
tableFamily: family,
|
|
316
|
-
tableName: this.tableName,
|
|
317
|
-
chainName: chain,
|
|
318
|
-
ruleContents: rule,
|
|
319
|
-
added: false
|
|
320
|
-
});
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
if (this.settings.ipAllowList && this.settings.ipAllowList.length > 0) {
|
|
324
|
-
const setName = 'allowed_ips';
|
|
325
|
-
await this.createIPSet(family, setName, this.settings.ipAllowList, setType as any);
|
|
326
|
-
|
|
327
|
-
// Add rule to allow traffic from allowed IPs
|
|
328
|
-
const rule = `add rule ${family} ${this.tableName} ${chain} ip${isIpv6 ? '6' : ''} saddr @${setName} ${this.settings.protocol} dport {${this.getAllPorts(this.settings.fromPort)}} accept comment "${this.ruleTag}:ALLOWED_SET"`;
|
|
329
|
-
rulesetContent += `${rule}\n`;
|
|
330
|
-
|
|
331
|
-
this.rules.push({
|
|
332
|
-
tableFamily: family,
|
|
333
|
-
tableName: this.tableName,
|
|
334
|
-
chainName: chain,
|
|
335
|
-
ruleContents: rule,
|
|
336
|
-
added: false
|
|
337
|
-
});
|
|
338
|
-
|
|
339
|
-
// Add default deny rule for unlisted IPs
|
|
340
|
-
const denyRule = `add rule ${family} ${this.tableName} ${chain} ${this.settings.protocol} dport {${this.getAllPorts(this.settings.fromPort)}} drop comment "${this.ruleTag}:DENY_ALL"`;
|
|
341
|
-
rulesetContent += `${denyRule}\n`;
|
|
342
|
-
|
|
343
|
-
this.rules.push({
|
|
344
|
-
tableFamily: family,
|
|
345
|
-
tableName: this.tableName,
|
|
346
|
-
chainName: chain,
|
|
347
|
-
ruleContents: denyRule,
|
|
348
|
-
added: false
|
|
349
|
-
});
|
|
350
|
-
}
|
|
351
|
-
} else {
|
|
352
|
-
// Traditional approach without IP sets - less efficient for large IP lists
|
|
353
|
-
|
|
354
|
-
// Ban specific IPs first
|
|
355
|
-
if (this.settings.ipBlockList && this.settings.ipBlockList.length > 0) {
|
|
356
|
-
for (const ip of this.settings.ipBlockList) {
|
|
357
|
-
// Skip IPv4 addresses for IPv6 rules and vice versa
|
|
358
|
-
if (isIpv6 && ip.includes('.')) continue;
|
|
359
|
-
if (!isIpv6 && ip.includes(':')) continue;
|
|
360
|
-
|
|
361
|
-
const rule = `add rule ${family} ${this.tableName} ${chain} ip${isIpv6 ? '6' : ''} saddr ${ip} drop comment "${this.ruleTag}:BANNED"`;
|
|
362
|
-
rulesetContent += `${rule}\n`;
|
|
363
|
-
|
|
364
|
-
this.rules.push({
|
|
365
|
-
tableFamily: family,
|
|
366
|
-
tableName: this.tableName,
|
|
367
|
-
chainName: chain,
|
|
368
|
-
ruleContents: rule,
|
|
369
|
-
added: false
|
|
370
|
-
});
|
|
371
|
-
}
|
|
372
|
-
}
|
|
373
|
-
|
|
374
|
-
// Allow specific IPs
|
|
375
|
-
if (this.settings.ipAllowList && this.settings.ipAllowList.length > 0) {
|
|
376
|
-
// Add rules to allow specific IPs
|
|
377
|
-
for (const ip of this.settings.ipAllowList) {
|
|
378
|
-
// Skip IPv4 addresses for IPv6 rules and vice versa
|
|
379
|
-
if (isIpv6 && ip.includes('.')) continue;
|
|
380
|
-
if (!isIpv6 && ip.includes(':')) continue;
|
|
381
|
-
|
|
382
|
-
const rule = `add rule ${family} ${this.tableName} ${chain} ip${isIpv6 ? '6' : ''} saddr ${ip} ${this.settings.protocol} dport {${this.getAllPorts(this.settings.fromPort)}} accept comment "${this.ruleTag}:ALLOWED"`;
|
|
383
|
-
rulesetContent += `${rule}\n`;
|
|
384
|
-
|
|
385
|
-
this.rules.push({
|
|
386
|
-
tableFamily: family,
|
|
387
|
-
tableName: this.tableName,
|
|
388
|
-
chainName: chain,
|
|
389
|
-
ruleContents: rule,
|
|
390
|
-
added: false
|
|
391
|
-
});
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
// Add default deny rule for unlisted IPs
|
|
395
|
-
const denyRule = `add rule ${family} ${this.tableName} ${chain} ${this.settings.protocol} dport {${this.getAllPorts(this.settings.fromPort)}} drop comment "${this.ruleTag}:DENY_ALL"`;
|
|
396
|
-
rulesetContent += `${denyRule}\n`;
|
|
397
|
-
|
|
398
|
-
this.rules.push({
|
|
399
|
-
tableFamily: family,
|
|
400
|
-
tableName: this.tableName,
|
|
401
|
-
chainName: chain,
|
|
402
|
-
ruleContents: denyRule,
|
|
403
|
-
added: false
|
|
404
|
-
});
|
|
405
|
-
}
|
|
406
|
-
}
|
|
407
|
-
|
|
408
|
-
// Only write and apply if we have rules to add
|
|
409
|
-
if (rulesetContent) {
|
|
410
|
-
// Apply the ruleset using the helper
|
|
411
|
-
await this.executor.executeWithTempFile(rulesetContent);
|
|
412
|
-
|
|
413
|
-
this.log('info', `Added source IP filter rules for ${family}`);
|
|
414
|
-
|
|
415
|
-
// Mark rules as added
|
|
416
|
-
for (const rule of this.rules) {
|
|
417
|
-
if (rule.tableFamily === family && !rule.added) {
|
|
418
|
-
rule.added = true;
|
|
419
|
-
|
|
420
|
-
// Verify the rule was applied
|
|
421
|
-
await this.verifyRuleApplication(rule);
|
|
422
|
-
}
|
|
423
|
-
}
|
|
424
|
-
}
|
|
425
|
-
|
|
426
|
-
return true;
|
|
427
|
-
} catch (err) {
|
|
428
|
-
this.log('error', `Failed to add source IP filter rules: ${err.message}`);
|
|
429
|
-
|
|
430
|
-
// Try to clean up any rules that might have been added
|
|
431
|
-
this.rollbackRules();
|
|
432
|
-
|
|
433
|
-
return false;
|
|
434
|
-
}
|
|
435
|
-
}
|
|
436
|
-
|
|
437
|
-
/**
|
|
438
|
-
* Gets a comma-separated list of all ports from a port specification
|
|
439
|
-
*/
|
|
440
|
-
private getAllPorts(portSpec: number | PortRange | Array<number | PortRange>): string {
|
|
441
|
-
const portRanges = normalizePortSpec(portSpec);
|
|
442
|
-
const ports: string[] = [];
|
|
443
|
-
|
|
444
|
-
for (const range of portRanges) {
|
|
445
|
-
if (range.from === range.to) {
|
|
446
|
-
ports.push(range.from.toString());
|
|
447
|
-
} else {
|
|
448
|
-
ports.push(`${range.from}-${range.to}`);
|
|
449
|
-
}
|
|
450
|
-
}
|
|
451
|
-
|
|
452
|
-
return ports.join(', ');
|
|
453
|
-
}
|
|
454
|
-
|
|
455
|
-
/**
|
|
456
|
-
* Configures advanced NAT with connection tracking
|
|
457
|
-
*/
|
|
458
|
-
private async setupAdvancedNAT(isIpv6: boolean = false): Promise<boolean> {
|
|
459
|
-
if (!this.settings.useAdvancedNAT) {
|
|
460
|
-
return true; // Skip if not using advanced NAT
|
|
461
|
-
}
|
|
462
|
-
|
|
463
|
-
const family = isIpv6 ? 'ip6' : 'ip';
|
|
464
|
-
const preroutingChain = 'nat_prerouting';
|
|
465
|
-
|
|
466
|
-
try {
|
|
467
|
-
// Get the port ranges
|
|
468
|
-
const fromPortRanges = normalizePortSpec(this.settings.fromPort);
|
|
469
|
-
const toPortRanges = normalizePortSpec(this.settings.toPort);
|
|
470
|
-
|
|
471
|
-
let rulesetContent = '';
|
|
472
|
-
|
|
473
|
-
// Simple case - one-to-one mapping with connection tracking
|
|
474
|
-
if (fromPortRanges.length === 1 && toPortRanges.length === 1) {
|
|
475
|
-
const fromRange = fromPortRanges[0];
|
|
476
|
-
const toRange = toPortRanges[0];
|
|
477
|
-
|
|
478
|
-
// Single port to single port with connection tracking
|
|
479
|
-
if (fromRange.from === fromRange.to && toRange.from === toRange.to) {
|
|
480
|
-
const rule = `add rule ${family} ${this.tableName} ${preroutingChain} ${this.settings.protocol} dport ${fromRange.from} ct state new dnat to ${this.settings.toHost}:${toRange.from} comment "${this.ruleTag}:DNAT_CT"`;
|
|
481
|
-
rulesetContent += `${rule}\n`;
|
|
482
|
-
|
|
483
|
-
this.rules.push({
|
|
484
|
-
tableFamily: family,
|
|
485
|
-
tableName: this.tableName,
|
|
486
|
-
chainName: preroutingChain,
|
|
487
|
-
ruleContents: rule,
|
|
488
|
-
added: false
|
|
489
|
-
});
|
|
490
|
-
}
|
|
491
|
-
// Port range with same size
|
|
492
|
-
else if ((fromRange.to - fromRange.from) === (toRange.to - toRange.from)) {
|
|
493
|
-
const rule = `add rule ${family} ${this.tableName} ${preroutingChain} ${this.settings.protocol} dport ${fromRange.from}-${fromRange.to} ct state new dnat to ${this.settings.toHost}:${toRange.from}-${toRange.to} comment "${this.ruleTag}:DNAT_RANGE_CT"`;
|
|
494
|
-
rulesetContent += `${rule}\n`;
|
|
495
|
-
|
|
496
|
-
this.rules.push({
|
|
497
|
-
tableFamily: family,
|
|
498
|
-
tableName: this.tableName,
|
|
499
|
-
chainName: preroutingChain,
|
|
500
|
-
ruleContents: rule,
|
|
501
|
-
added: false
|
|
502
|
-
});
|
|
503
|
-
}
|
|
504
|
-
// Add related and established connection rule for efficient connection handling
|
|
505
|
-
const ctRule = `add rule ${family} ${this.tableName} ${preroutingChain} ct state established,related accept comment "${this.ruleTag}:CT_ESTABLISHED"`;
|
|
506
|
-
rulesetContent += `${ctRule}\n`;
|
|
507
|
-
|
|
508
|
-
this.rules.push({
|
|
509
|
-
tableFamily: family,
|
|
510
|
-
tableName: this.tableName,
|
|
511
|
-
chainName: preroutingChain,
|
|
512
|
-
ruleContents: ctRule,
|
|
513
|
-
added: false
|
|
514
|
-
});
|
|
515
|
-
|
|
516
|
-
// Apply the rules if we have any
|
|
517
|
-
if (rulesetContent) {
|
|
518
|
-
await this.executor.executeWithTempFile(rulesetContent);
|
|
519
|
-
|
|
520
|
-
this.log('info', `Added advanced NAT rules for ${family}`);
|
|
521
|
-
|
|
522
|
-
// Mark rules as added
|
|
523
|
-
for (const rule of this.rules) {
|
|
524
|
-
if (rule.tableFamily === family && !rule.added) {
|
|
525
|
-
rule.added = true;
|
|
526
|
-
|
|
527
|
-
// Verify the rule was applied
|
|
528
|
-
await this.verifyRuleApplication(rule);
|
|
529
|
-
}
|
|
530
|
-
}
|
|
531
|
-
}
|
|
532
|
-
}
|
|
533
|
-
|
|
534
|
-
return true;
|
|
535
|
-
} catch (err) {
|
|
536
|
-
this.log('error', `Failed to set up advanced NAT: ${err.message}`);
|
|
537
|
-
return false;
|
|
538
|
-
}
|
|
539
|
-
}
|
|
540
|
-
|
|
541
|
-
/**
|
|
542
|
-
* Adds port forwarding rules
|
|
543
|
-
*/
|
|
544
|
-
private async addPortForwardingRules(isIpv6: boolean = false): Promise<boolean> {
|
|
545
|
-
// Skip if using advanced NAT as that already handles the port forwarding
|
|
546
|
-
if (this.settings.useAdvancedNAT) {
|
|
547
|
-
return true;
|
|
548
|
-
}
|
|
549
|
-
|
|
550
|
-
const family = isIpv6 ? 'ip6' : 'ip';
|
|
551
|
-
const preroutingChain = 'nat_prerouting';
|
|
552
|
-
const postroutingChain = 'nat_postrouting';
|
|
553
|
-
|
|
554
|
-
try {
|
|
555
|
-
// Normalize port specifications
|
|
556
|
-
const fromPortRanges = normalizePortSpec(this.settings.fromPort);
|
|
557
|
-
const toPortRanges = normalizePortSpec(this.settings.toPort);
|
|
558
|
-
|
|
559
|
-
// Handle the case where fromPort and toPort counts don't match
|
|
560
|
-
if (fromPortRanges.length !== toPortRanges.length) {
|
|
561
|
-
if (toPortRanges.length === 1) {
|
|
562
|
-
// If there's only one toPort, use it for all fromPorts
|
|
563
|
-
const singleToRange = toPortRanges[0];
|
|
564
|
-
|
|
565
|
-
return await this.addPortMappings(family, preroutingChain, postroutingChain, fromPortRanges, singleToRange);
|
|
566
|
-
} else {
|
|
567
|
-
throw new NftValidationError('Mismatched port counts: fromPort and toPort arrays must have equal length or toPort must be a single value');
|
|
568
|
-
}
|
|
569
|
-
} else {
|
|
570
|
-
// Add port mapping rules for each port pair
|
|
571
|
-
return await this.addPortPairMappings(family, preroutingChain, postroutingChain, fromPortRanges, toPortRanges);
|
|
572
|
-
}
|
|
573
|
-
} catch (err) {
|
|
574
|
-
this.log('error', `Failed to add port forwarding rules: ${err.message}`);
|
|
575
|
-
return false;
|
|
576
|
-
}
|
|
577
|
-
}
|
|
578
|
-
|
|
579
|
-
/**
|
|
580
|
-
* Adds port forwarding rules for the case where one toPortRange maps to multiple fromPortRanges
|
|
581
|
-
*/
|
|
582
|
-
private async addPortMappings(
|
|
583
|
-
family: string,
|
|
584
|
-
preroutingChain: string,
|
|
585
|
-
postroutingChain: string,
|
|
586
|
-
fromPortRanges: PortRange[],
|
|
587
|
-
toPortRange: PortRange
|
|
588
|
-
): Promise<boolean> {
|
|
589
|
-
try {
|
|
590
|
-
let rulesetContent = '';
|
|
591
|
-
|
|
592
|
-
// For each from port range, create a mapping to the single to port range
|
|
593
|
-
for (const fromRange of fromPortRanges) {
|
|
594
|
-
// Simple case: single port to single port
|
|
595
|
-
if (fromRange.from === fromRange.to && toPortRange.from === toPortRange.to) {
|
|
596
|
-
const rule = `add rule ${family} ${this.tableName} ${preroutingChain} ${this.settings.protocol} dport ${fromRange.from} dnat to ${this.settings.toHost}:${toPortRange.from} comment "${this.ruleTag}:DNAT"`;
|
|
597
|
-
rulesetContent += `${rule}\n`;
|
|
598
|
-
|
|
599
|
-
this.rules.push({
|
|
600
|
-
tableFamily: family,
|
|
601
|
-
tableName: this.tableName,
|
|
602
|
-
chainName: preroutingChain,
|
|
603
|
-
ruleContents: rule,
|
|
604
|
-
added: false
|
|
605
|
-
});
|
|
606
|
-
}
|
|
607
|
-
// Multiple ports in from range, but only one port in to range
|
|
608
|
-
else if (toPortRange.from === toPortRange.to) {
|
|
609
|
-
// Map each port in from range to the single to port
|
|
610
|
-
for (let p = fromRange.from; p <= fromRange.to; p++) {
|
|
611
|
-
const rule = `add rule ${family} ${this.tableName} ${preroutingChain} ${this.settings.protocol} dport ${p} dnat to ${this.settings.toHost}:${toPortRange.from} comment "${this.ruleTag}:DNAT"`;
|
|
612
|
-
rulesetContent += `${rule}\n`;
|
|
613
|
-
|
|
614
|
-
this.rules.push({
|
|
615
|
-
tableFamily: family,
|
|
616
|
-
tableName: this.tableName,
|
|
617
|
-
chainName: preroutingChain,
|
|
618
|
-
ruleContents: rule,
|
|
619
|
-
added: false
|
|
620
|
-
});
|
|
621
|
-
}
|
|
622
|
-
}
|
|
623
|
-
// Port range to port range mapping with modulo distribution
|
|
624
|
-
else {
|
|
625
|
-
const toRangeSize = toPortRange.to - toPortRange.from + 1;
|
|
626
|
-
|
|
627
|
-
for (let p = fromRange.from; p <= fromRange.to; p++) {
|
|
628
|
-
const offset = (p - fromRange.from) % toRangeSize;
|
|
629
|
-
const targetPort = toPortRange.from + offset;
|
|
630
|
-
|
|
631
|
-
const rule = `add rule ${family} ${this.tableName} ${preroutingChain} ${this.settings.protocol} dport ${p} dnat to ${this.settings.toHost}:${targetPort} comment "${this.ruleTag}:DNAT"`;
|
|
632
|
-
rulesetContent += `${rule}\n`;
|
|
633
|
-
|
|
634
|
-
this.rules.push({
|
|
635
|
-
tableFamily: family,
|
|
636
|
-
tableName: this.tableName,
|
|
637
|
-
chainName: preroutingChain,
|
|
638
|
-
ruleContents: rule,
|
|
639
|
-
added: false
|
|
640
|
-
});
|
|
641
|
-
}
|
|
642
|
-
}
|
|
643
|
-
}
|
|
644
|
-
|
|
645
|
-
// Add masquerade rule for source NAT if not preserving source IP
|
|
646
|
-
if (!this.settings.preserveSourceIP) {
|
|
647
|
-
const ports = this.getAllPorts(this.settings.toPort);
|
|
648
|
-
const masqRule = `add rule ${family} ${this.tableName} ${postroutingChain} ${this.settings.protocol} daddr ${this.settings.toHost} dport {${ports}} masquerade comment "${this.ruleTag}:MASQ"`;
|
|
649
|
-
rulesetContent += `${masqRule}\n`;
|
|
650
|
-
|
|
651
|
-
this.rules.push({
|
|
652
|
-
tableFamily: family,
|
|
653
|
-
tableName: this.tableName,
|
|
654
|
-
chainName: postroutingChain,
|
|
655
|
-
ruleContents: masqRule,
|
|
656
|
-
added: false
|
|
657
|
-
});
|
|
658
|
-
}
|
|
659
|
-
|
|
660
|
-
// Apply the ruleset if we have any rules
|
|
661
|
-
if (rulesetContent) {
|
|
662
|
-
// Apply the ruleset using the helper
|
|
663
|
-
await this.executor.executeWithTempFile(rulesetContent);
|
|
664
|
-
|
|
665
|
-
this.log('info', `Added port forwarding rules for ${family}`);
|
|
666
|
-
|
|
667
|
-
// Mark rules as added
|
|
668
|
-
for (const rule of this.rules) {
|
|
669
|
-
if (rule.tableFamily === family && !rule.added) {
|
|
670
|
-
rule.added = true;
|
|
671
|
-
|
|
672
|
-
// Verify the rule was applied
|
|
673
|
-
await this.verifyRuleApplication(rule);
|
|
674
|
-
}
|
|
675
|
-
}
|
|
676
|
-
}
|
|
677
|
-
|
|
678
|
-
return true;
|
|
679
|
-
} catch (err) {
|
|
680
|
-
this.log('error', `Failed to add port mappings: ${err.message}`);
|
|
681
|
-
return false;
|
|
682
|
-
}
|
|
683
|
-
}
|
|
684
|
-
|
|
685
|
-
/**
|
|
686
|
-
* Adds port forwarding rules for pairs of fromPortRanges and toPortRanges
|
|
687
|
-
*/
|
|
688
|
-
private async addPortPairMappings(
|
|
689
|
-
family: string,
|
|
690
|
-
preroutingChain: string,
|
|
691
|
-
postroutingChain: string,
|
|
692
|
-
fromPortRanges: PortRange[],
|
|
693
|
-
toPortRanges: PortRange[]
|
|
694
|
-
): Promise<boolean> {
|
|
695
|
-
try {
|
|
696
|
-
let rulesetContent = '';
|
|
697
|
-
|
|
698
|
-
// Process each fromPort and toPort pair
|
|
699
|
-
for (let i = 0; i < fromPortRanges.length; i++) {
|
|
700
|
-
const fromRange = fromPortRanges[i];
|
|
701
|
-
const toRange = toPortRanges[i];
|
|
702
|
-
|
|
703
|
-
// Simple case: single port to single port
|
|
704
|
-
if (fromRange.from === fromRange.to && toRange.from === toRange.to) {
|
|
705
|
-
const rule = `add rule ${family} ${this.tableName} ${preroutingChain} ${this.settings.protocol} dport ${fromRange.from} dnat to ${this.settings.toHost}:${toRange.from} comment "${this.ruleTag}:DNAT"`;
|
|
706
|
-
rulesetContent += `${rule}\n`;
|
|
707
|
-
|
|
708
|
-
this.rules.push({
|
|
709
|
-
tableFamily: family,
|
|
710
|
-
tableName: this.tableName,
|
|
711
|
-
chainName: preroutingChain,
|
|
712
|
-
ruleContents: rule,
|
|
713
|
-
added: false
|
|
714
|
-
});
|
|
715
|
-
}
|
|
716
|
-
// Port range with equal size - can use direct mapping
|
|
717
|
-
else if ((fromRange.to - fromRange.from) === (toRange.to - toRange.from)) {
|
|
718
|
-
const rule = `add rule ${family} ${this.tableName} ${preroutingChain} ${this.settings.protocol} dport ${fromRange.from}-${fromRange.to} dnat to ${this.settings.toHost}:${toRange.from}-${toRange.to} comment "${this.ruleTag}:DNAT_RANGE"`;
|
|
719
|
-
rulesetContent += `${rule}\n`;
|
|
720
|
-
|
|
721
|
-
this.rules.push({
|
|
722
|
-
tableFamily: family,
|
|
723
|
-
tableName: this.tableName,
|
|
724
|
-
chainName: preroutingChain,
|
|
725
|
-
ruleContents: rule,
|
|
726
|
-
added: false
|
|
727
|
-
});
|
|
728
|
-
}
|
|
729
|
-
// Unequal port ranges - need to map individually
|
|
730
|
-
else {
|
|
731
|
-
const toRangeSize = toRange.to - toRange.from + 1;
|
|
732
|
-
|
|
733
|
-
for (let p = fromRange.from; p <= fromRange.to; p++) {
|
|
734
|
-
const offset = (p - fromRange.from) % toRangeSize;
|
|
735
|
-
const targetPort = toRange.from + offset;
|
|
736
|
-
|
|
737
|
-
const rule = `add rule ${family} ${this.tableName} ${preroutingChain} ${this.settings.protocol} dport ${p} dnat to ${this.settings.toHost}:${targetPort} comment "${this.ruleTag}:DNAT_INDIVIDUAL"`;
|
|
738
|
-
rulesetContent += `${rule}\n`;
|
|
739
|
-
|
|
740
|
-
this.rules.push({
|
|
741
|
-
tableFamily: family,
|
|
742
|
-
tableName: this.tableName,
|
|
743
|
-
chainName: preroutingChain,
|
|
744
|
-
ruleContents: rule,
|
|
745
|
-
added: false
|
|
746
|
-
});
|
|
747
|
-
}
|
|
748
|
-
}
|
|
749
|
-
|
|
750
|
-
// Add masquerade rule for this port range if not preserving source IP
|
|
751
|
-
if (!this.settings.preserveSourceIP) {
|
|
752
|
-
const masqRule = `add rule ${family} ${this.tableName} ${postroutingChain} ${this.settings.protocol} daddr ${this.settings.toHost} dport ${toRange.from}-${toRange.to} masquerade comment "${this.ruleTag}:MASQ"`;
|
|
753
|
-
rulesetContent += `${masqRule}\n`;
|
|
754
|
-
|
|
755
|
-
this.rules.push({
|
|
756
|
-
tableFamily: family,
|
|
757
|
-
tableName: this.tableName,
|
|
758
|
-
chainName: postroutingChain,
|
|
759
|
-
ruleContents: masqRule,
|
|
760
|
-
added: false
|
|
761
|
-
});
|
|
762
|
-
}
|
|
763
|
-
}
|
|
764
|
-
|
|
765
|
-
// Apply the ruleset if we have any rules
|
|
766
|
-
if (rulesetContent) {
|
|
767
|
-
await this.executor.executeWithTempFile(rulesetContent);
|
|
768
|
-
|
|
769
|
-
this.log('info', `Added port forwarding rules for ${family}`);
|
|
770
|
-
|
|
771
|
-
// Mark rules as added
|
|
772
|
-
for (const rule of this.rules) {
|
|
773
|
-
if (rule.tableFamily === family && !rule.added) {
|
|
774
|
-
rule.added = true;
|
|
775
|
-
|
|
776
|
-
// Verify the rule was applied
|
|
777
|
-
await this.verifyRuleApplication(rule);
|
|
778
|
-
}
|
|
779
|
-
}
|
|
780
|
-
}
|
|
781
|
-
|
|
782
|
-
return true;
|
|
783
|
-
} catch (err) {
|
|
784
|
-
this.log('error', `Failed to add port pair mappings: ${err.message}`);
|
|
785
|
-
return false;
|
|
786
|
-
}
|
|
787
|
-
}
|
|
788
|
-
|
|
789
|
-
/**
|
|
790
|
-
* Setup quality of service rules
|
|
791
|
-
*/
|
|
792
|
-
private async addTrafficShaping(isIpv6: boolean = false): Promise<boolean> {
|
|
793
|
-
if (!this.settings.qos?.enabled) {
|
|
794
|
-
return true;
|
|
795
|
-
}
|
|
796
|
-
|
|
797
|
-
const family = isIpv6 ? 'ip6' : 'ip';
|
|
798
|
-
const qosChain = 'qos_forward';
|
|
799
|
-
|
|
800
|
-
try {
|
|
801
|
-
let rulesetContent = '';
|
|
802
|
-
|
|
803
|
-
// Add rate limiting rule if specified
|
|
804
|
-
if (this.settings.qos.maxRate) {
|
|
805
|
-
const ruleContent = `add rule ${family} ${this.tableName} ${qosChain} ip daddr ${this.settings.toHost} ${this.settings.protocol} dport {${this.getAllPorts(this.settings.toPort)}} limit rate over ${this.settings.qos.maxRate} drop comment "${this.ruleTag}:QOS_RATE"`;
|
|
806
|
-
rulesetContent += `${ruleContent}\n`;
|
|
807
|
-
|
|
808
|
-
this.rules.push({
|
|
809
|
-
tableFamily: family,
|
|
810
|
-
tableName: this.tableName,
|
|
811
|
-
chainName: qosChain,
|
|
812
|
-
ruleContents: ruleContent,
|
|
813
|
-
added: false
|
|
814
|
-
});
|
|
815
|
-
}
|
|
816
|
-
|
|
817
|
-
// Add priority marking if specified
|
|
818
|
-
if (this.settings.qos.priority !== undefined) {
|
|
819
|
-
// Check if the chain exists
|
|
820
|
-
const chainsOutput = await this.executor.executeWithRetry(
|
|
821
|
-
`${NfTablesProxy.NFT_CMD} list chains ${family} ${this.tableName}`,
|
|
822
|
-
this.settings.maxRetries,
|
|
823
|
-
this.settings.retryDelayMs
|
|
824
|
-
);
|
|
825
|
-
|
|
826
|
-
// Check if we need to create priority queues
|
|
827
|
-
const hasPrioChain = chainsOutput.includes(`chain prio${this.settings.qos.priority}`);
|
|
828
|
-
|
|
829
|
-
if (!hasPrioChain) {
|
|
830
|
-
// Create priority chain
|
|
831
|
-
const prioChainRule = `add chain ${family} ${this.tableName} prio${this.settings.qos.priority} { type filter hook forward priority ${this.settings.qos.priority * 10}; }`;
|
|
832
|
-
rulesetContent += `${prioChainRule}\n`;
|
|
833
|
-
}
|
|
834
|
-
|
|
835
|
-
// Add the rules to mark packets with this priority
|
|
836
|
-
for (const range of normalizePortSpec(this.settings.toPort)) {
|
|
837
|
-
const markRule = `add rule ${family} ${this.tableName} ${qosChain} ${this.settings.protocol} dport ${range.from}-${range.to} counter goto prio${this.settings.qos.priority} comment "${this.ruleTag}:QOS_PRIORITY"`;
|
|
838
|
-
rulesetContent += `${markRule}\n`;
|
|
839
|
-
|
|
840
|
-
this.rules.push({
|
|
841
|
-
tableFamily: family,
|
|
842
|
-
tableName: this.tableName,
|
|
843
|
-
chainName: qosChain,
|
|
844
|
-
ruleContents: markRule,
|
|
845
|
-
added: false
|
|
846
|
-
});
|
|
847
|
-
}
|
|
848
|
-
}
|
|
849
|
-
|
|
850
|
-
// Apply the ruleset if we have any rules
|
|
851
|
-
if (rulesetContent) {
|
|
852
|
-
// Apply the ruleset using the helper
|
|
853
|
-
await this.executor.executeWithTempFile(rulesetContent);
|
|
854
|
-
|
|
855
|
-
this.log('info', `Added QoS rules for ${family}`);
|
|
856
|
-
|
|
857
|
-
// Mark rules as added
|
|
858
|
-
for (const rule of this.rules) {
|
|
859
|
-
if (rule.tableFamily === family && !rule.added) {
|
|
860
|
-
rule.added = true;
|
|
861
|
-
|
|
862
|
-
// Verify the rule was applied
|
|
863
|
-
await this.verifyRuleApplication(rule);
|
|
864
|
-
}
|
|
865
|
-
}
|
|
866
|
-
}
|
|
867
|
-
|
|
868
|
-
return true;
|
|
869
|
-
} catch (err) {
|
|
870
|
-
this.log('error', `Failed to add traffic shaping: ${err.message}`);
|
|
871
|
-
return false;
|
|
872
|
-
}
|
|
873
|
-
}
|
|
874
|
-
|
|
875
|
-
/**
|
|
876
|
-
* Setup NetworkProxy integration rules
|
|
877
|
-
*/
|
|
878
|
-
private async setupNetworkProxyIntegration(isIpv6: boolean = false): Promise<boolean> {
|
|
879
|
-
if (!this.settings.netProxyIntegration?.enabled) {
|
|
880
|
-
return true;
|
|
881
|
-
}
|
|
882
|
-
|
|
883
|
-
const netProxyConfig = this.settings.netProxyIntegration;
|
|
884
|
-
const family = isIpv6 ? 'ip6' : 'ip';
|
|
885
|
-
const outputChain = 'nat_output';
|
|
886
|
-
|
|
887
|
-
try {
|
|
888
|
-
// Only proceed if we're redirecting localhost and have a port
|
|
889
|
-
if (netProxyConfig.redirectLocalhost && netProxyConfig.sslTerminationPort) {
|
|
890
|
-
const localhost = isIpv6 ? '::1' : '127.0.0.1';
|
|
891
|
-
|
|
892
|
-
// Create the redirect rule
|
|
893
|
-
const rule = `add rule ${family} ${this.tableName} ${outputChain} ${this.settings.protocol} daddr ${localhost} redirect to :${netProxyConfig.sslTerminationPort} comment "${this.ruleTag}:NETPROXY_REDIRECT"`;
|
|
894
|
-
|
|
895
|
-
// Apply the rule
|
|
896
|
-
await this.executor.executeWithRetry(
|
|
897
|
-
`${NfTablesProxy.NFT_CMD} ${rule}`,
|
|
898
|
-
this.settings.maxRetries,
|
|
899
|
-
this.settings.retryDelayMs
|
|
900
|
-
);
|
|
901
|
-
|
|
902
|
-
this.log('info', `Added NetworkProxy redirection rule for ${family}`);
|
|
903
|
-
|
|
904
|
-
const newRule = {
|
|
905
|
-
tableFamily: family,
|
|
906
|
-
tableName: this.tableName,
|
|
907
|
-
chainName: outputChain,
|
|
908
|
-
ruleContents: rule,
|
|
909
|
-
added: true
|
|
910
|
-
};
|
|
911
|
-
|
|
912
|
-
this.rules.push(newRule);
|
|
913
|
-
|
|
914
|
-
// Verify the rule was actually applied
|
|
915
|
-
await this.verifyRuleApplication(newRule);
|
|
916
|
-
}
|
|
917
|
-
|
|
918
|
-
return true;
|
|
919
|
-
} catch (err) {
|
|
920
|
-
this.log('error', `Failed to set up NetworkProxy integration: ${err.message}`);
|
|
921
|
-
return false;
|
|
922
|
-
}
|
|
923
|
-
}
|
|
924
|
-
|
|
925
|
-
/**
|
|
926
|
-
* Verify that a rule was successfully applied
|
|
927
|
-
*/
|
|
928
|
-
private async verifyRuleApplication(rule: NfTablesRule): Promise<boolean> {
|
|
929
|
-
try {
|
|
930
|
-
const { tableFamily, tableName, chainName, ruleContents } = rule;
|
|
931
|
-
|
|
932
|
-
// Extract the distinctive parts of the rule to create a search pattern
|
|
933
|
-
const commentMatch = ruleContents.match(/comment "([^"]+)"/);
|
|
934
|
-
if (!commentMatch) return false;
|
|
935
|
-
|
|
936
|
-
const commentTag = commentMatch[1];
|
|
937
|
-
|
|
938
|
-
// List the chain to check if our rule is there
|
|
939
|
-
const stdout = await this.executor.executeWithRetry(
|
|
940
|
-
`${NfTablesProxy.NFT_CMD} list chain ${tableFamily} ${tableName} ${chainName}`,
|
|
941
|
-
this.settings.maxRetries,
|
|
942
|
-
this.settings.retryDelayMs
|
|
943
|
-
);
|
|
944
|
-
|
|
945
|
-
// Check if the comment appears in the output
|
|
946
|
-
const isApplied = stdout.includes(commentTag);
|
|
947
|
-
|
|
948
|
-
rule.verified = isApplied;
|
|
949
|
-
|
|
950
|
-
if (!isApplied) {
|
|
951
|
-
this.log('warn', `Rule verification failed: ${commentTag} not found in chain ${chainName}`);
|
|
952
|
-
} else {
|
|
953
|
-
this.log('debug', `Rule verified: ${commentTag} found in chain ${chainName}`);
|
|
954
|
-
}
|
|
955
|
-
|
|
956
|
-
return isApplied;
|
|
957
|
-
} catch (err) {
|
|
958
|
-
this.log('error', `Failed to verify rule application: ${err.message}`);
|
|
959
|
-
return false;
|
|
960
|
-
}
|
|
961
|
-
}
|
|
962
|
-
|
|
963
|
-
/**
|
|
964
|
-
* Rolls back rules in case of error during setup
|
|
965
|
-
*/
|
|
966
|
-
private async rollbackRules(): Promise<void> {
|
|
967
|
-
// Process rules in reverse order (LIFO)
|
|
968
|
-
for (let i = this.rules.length - 1; i >= 0; i--) {
|
|
969
|
-
const rule = this.rules[i];
|
|
970
|
-
|
|
971
|
-
if (rule.added) {
|
|
972
|
-
try {
|
|
973
|
-
// For nftables, create a delete rule by replacing 'add' with 'delete'
|
|
974
|
-
const deleteRule = rule.ruleContents.replace('add rule', 'delete rule');
|
|
975
|
-
await this.executor.executeWithRetry(
|
|
976
|
-
`${NfTablesProxy.NFT_CMD} ${deleteRule}`,
|
|
977
|
-
this.settings.maxRetries,
|
|
978
|
-
this.settings.retryDelayMs
|
|
979
|
-
);
|
|
980
|
-
|
|
981
|
-
this.log('info', `Rolled back rule: ${deleteRule}`);
|
|
982
|
-
|
|
983
|
-
rule.added = false;
|
|
984
|
-
rule.verified = false;
|
|
985
|
-
} catch (err) {
|
|
986
|
-
this.log('error', `Failed to roll back rule: ${err.message}`);
|
|
987
|
-
}
|
|
988
|
-
}
|
|
989
|
-
}
|
|
990
|
-
}
|
|
991
|
-
|
|
992
|
-
/**
|
|
993
|
-
* Checks if nftables table exists
|
|
994
|
-
*/
|
|
995
|
-
private async tableExists(family: string, tableName: string): Promise<boolean> {
|
|
996
|
-
try {
|
|
997
|
-
const stdout = await this.executor.executeWithRetry(
|
|
998
|
-
`${NfTablesProxy.NFT_CMD} list tables ${family}`,
|
|
999
|
-
this.settings.maxRetries,
|
|
1000
|
-
this.settings.retryDelayMs
|
|
1001
|
-
);
|
|
1002
|
-
|
|
1003
|
-
return stdout.includes(`table ${family} ${tableName}`);
|
|
1004
|
-
} catch (err) {
|
|
1005
|
-
return false;
|
|
1006
|
-
}
|
|
1007
|
-
}
|
|
1008
|
-
|
|
1009
|
-
/**
|
|
1010
|
-
* Get system metrics like connection counts
|
|
1011
|
-
*/
|
|
1012
|
-
private async getSystemMetrics(): Promise<{
|
|
1013
|
-
activeConnections?: number;
|
|
1014
|
-
forwardedConnections?: number;
|
|
1015
|
-
bytesForwarded?: { sent: number; received: number };
|
|
1016
|
-
}> {
|
|
1017
|
-
const metrics: {
|
|
1018
|
-
activeConnections?: number;
|
|
1019
|
-
forwardedConnections?: number;
|
|
1020
|
-
bytesForwarded?: { sent: number; received: number };
|
|
1021
|
-
} = {};
|
|
1022
|
-
|
|
1023
|
-
try {
|
|
1024
|
-
// Try to get connection metrics if conntrack is available
|
|
1025
|
-
try {
|
|
1026
|
-
const stdout = await this.executor.executeWithRetry('conntrack -C', this.settings.maxRetries, this.settings.retryDelayMs);
|
|
1027
|
-
metrics.activeConnections = parseInt(stdout.trim(), 10);
|
|
1028
|
-
} catch (err) {
|
|
1029
|
-
// conntrack not available, skip this metric
|
|
1030
|
-
}
|
|
1031
|
-
|
|
1032
|
-
// Try to get forwarded connections count from nftables counters
|
|
1033
|
-
try {
|
|
1034
|
-
// Look for counters in our rules
|
|
1035
|
-
const stdout = await this.executor.executeWithRetry(
|
|
1036
|
-
`${NfTablesProxy.NFT_CMD} list table ip ${this.tableName}`,
|
|
1037
|
-
this.settings.maxRetries,
|
|
1038
|
-
this.settings.retryDelayMs
|
|
1039
|
-
);
|
|
1040
|
-
|
|
1041
|
-
// Parse counter information from the output
|
|
1042
|
-
const counterMatches = stdout.matchAll(/counter packets (\d+) bytes (\d+)/g);
|
|
1043
|
-
let totalPackets = 0;
|
|
1044
|
-
let totalBytes = 0;
|
|
1045
|
-
|
|
1046
|
-
for (const match of counterMatches) {
|
|
1047
|
-
totalPackets += parseInt(match[1], 10);
|
|
1048
|
-
totalBytes += parseInt(match[2], 10);
|
|
1049
|
-
}
|
|
1050
|
-
|
|
1051
|
-
if (totalPackets > 0) {
|
|
1052
|
-
metrics.forwardedConnections = totalPackets;
|
|
1053
|
-
metrics.bytesForwarded = {
|
|
1054
|
-
sent: totalBytes,
|
|
1055
|
-
received: 0 // We can't easily determine this without additional rules
|
|
1056
|
-
};
|
|
1057
|
-
}
|
|
1058
|
-
} catch (err) {
|
|
1059
|
-
// Failed to get counter info, skip this metric
|
|
1060
|
-
}
|
|
1061
|
-
|
|
1062
|
-
return metrics;
|
|
1063
|
-
} catch (err) {
|
|
1064
|
-
this.log('error', `Failed to get system metrics: ${err.message}`);
|
|
1065
|
-
return metrics;
|
|
1066
|
-
}
|
|
1067
|
-
}
|
|
1068
|
-
|
|
1069
|
-
/**
|
|
1070
|
-
* Get status of IP sets
|
|
1071
|
-
*/
|
|
1072
|
-
private async getIPSetStatus(): Promise<{
|
|
1073
|
-
name: string;
|
|
1074
|
-
elementCount: number;
|
|
1075
|
-
type: string;
|
|
1076
|
-
}[]> {
|
|
1077
|
-
const result: {
|
|
1078
|
-
name: string;
|
|
1079
|
-
elementCount: number;
|
|
1080
|
-
type: string;
|
|
1081
|
-
}[] = [];
|
|
1082
|
-
|
|
1083
|
-
try {
|
|
1084
|
-
for (const family of ['ip', 'ip6']) {
|
|
1085
|
-
try {
|
|
1086
|
-
const stdout = await this.executor.executeWithRetry(
|
|
1087
|
-
`${NfTablesProxy.NFT_CMD} list sets ${family} ${this.tableName}`,
|
|
1088
|
-
this.settings.maxRetries,
|
|
1089
|
-
this.settings.retryDelayMs
|
|
1090
|
-
);
|
|
1091
|
-
|
|
1092
|
-
const setMatches = stdout.matchAll(/set (\w+) {\s*type (\w+)/g);
|
|
1093
|
-
|
|
1094
|
-
for (const match of setMatches) {
|
|
1095
|
-
const setName = match[1];
|
|
1096
|
-
const setType = match[2];
|
|
1097
|
-
|
|
1098
|
-
// Get element count from tracking map
|
|
1099
|
-
const setKey = `${family}:${setName}`;
|
|
1100
|
-
const elements = this.ipSets.get(setKey) || [];
|
|
1101
|
-
|
|
1102
|
-
result.push({
|
|
1103
|
-
name: setName,
|
|
1104
|
-
elementCount: elements.length,
|
|
1105
|
-
type: setType
|
|
1106
|
-
});
|
|
1107
|
-
}
|
|
1108
|
-
} catch (err) {
|
|
1109
|
-
// No sets for this family, or table doesn't exist
|
|
1110
|
-
}
|
|
1111
|
-
}
|
|
1112
|
-
|
|
1113
|
-
return result;
|
|
1114
|
-
} catch (err) {
|
|
1115
|
-
this.log('error', `Failed to get IP set status: ${err.message}`);
|
|
1116
|
-
return result;
|
|
1117
|
-
}
|
|
1118
|
-
}
|
|
1119
|
-
|
|
1120
|
-
/**
|
|
1121
|
-
* Get detailed status about the current state of the proxy
|
|
1122
|
-
*/
|
|
1123
|
-
public async getStatus(): Promise<NfTablesStatus> {
|
|
1124
|
-
const result: NfTablesStatus = {
|
|
1125
|
-
active: this.rules.some(r => r.added),
|
|
1126
|
-
ruleCount: {
|
|
1127
|
-
total: this.rules.length,
|
|
1128
|
-
added: this.rules.filter(r => r.added).length,
|
|
1129
|
-
verified: this.rules.filter(r => r.verified).length
|
|
1130
|
-
},
|
|
1131
|
-
tablesConfigured: [],
|
|
1132
|
-
metrics: {},
|
|
1133
|
-
qosEnabled: this.settings.qos?.enabled || false
|
|
1134
|
-
};
|
|
1135
|
-
|
|
1136
|
-
try {
|
|
1137
|
-
// Get list of configured tables
|
|
1138
|
-
const stdout = await this.executor.executeWithRetry(
|
|
1139
|
-
`${NfTablesProxy.NFT_CMD} list tables`,
|
|
1140
|
-
this.settings.maxRetries,
|
|
1141
|
-
this.settings.retryDelayMs
|
|
1142
|
-
);
|
|
1143
|
-
|
|
1144
|
-
const tableRegex = /table (ip|ip6) (\w+)/g;
|
|
1145
|
-
let match;
|
|
1146
|
-
|
|
1147
|
-
while ((match = tableRegex.exec(stdout)) !== null) {
|
|
1148
|
-
const [, family, name] = match;
|
|
1149
|
-
if (name === this.tableName) {
|
|
1150
|
-
result.tablesConfigured.push({ family, tableName: name });
|
|
1151
|
-
}
|
|
1152
|
-
}
|
|
1153
|
-
|
|
1154
|
-
// Get system metrics
|
|
1155
|
-
result.metrics = await this.getSystemMetrics();
|
|
1156
|
-
|
|
1157
|
-
// Get IP set status if using IP sets
|
|
1158
|
-
if (this.settings.useIPSets) {
|
|
1159
|
-
result.ipSetsConfigured = await this.getIPSetStatus();
|
|
1160
|
-
}
|
|
1161
|
-
|
|
1162
|
-
return result;
|
|
1163
|
-
} catch (err) {
|
|
1164
|
-
this.log('error', `Failed to get status: ${err.message}`);
|
|
1165
|
-
return result;
|
|
1166
|
-
}
|
|
1167
|
-
}
|
|
1168
|
-
|
|
1169
|
-
/**
|
|
1170
|
-
* Performs a dry run to see what commands would be executed without actually applying them
|
|
1171
|
-
*/
|
|
1172
|
-
public async dryRun(): Promise<string[]> {
|
|
1173
|
-
const commands: string[] = [];
|
|
1174
|
-
|
|
1175
|
-
// Simulate all the necessary setup steps and collect commands
|
|
1176
|
-
|
|
1177
|
-
// Tables and chains
|
|
1178
|
-
commands.push(`add table ip ${this.tableName}`);
|
|
1179
|
-
commands.push(`add chain ip ${this.tableName} nat_prerouting { type nat hook prerouting priority -100; }`);
|
|
1180
|
-
|
|
1181
|
-
if (!this.settings.preserveSourceIP) {
|
|
1182
|
-
commands.push(`add chain ip ${this.tableName} nat_postrouting { type nat hook postrouting priority 100; }`);
|
|
1183
|
-
}
|
|
1184
|
-
|
|
1185
|
-
if (this.settings.netProxyIntegration?.enabled && this.settings.netProxyIntegration.redirectLocalhost) {
|
|
1186
|
-
commands.push(`add chain ip ${this.tableName} nat_output { type nat hook output priority 0; }`);
|
|
1187
|
-
}
|
|
1188
|
-
|
|
1189
|
-
if (this.settings.qos?.enabled) {
|
|
1190
|
-
commands.push(`add chain ip ${this.tableName} qos_forward { type filter hook forward priority 0; }`);
|
|
1191
|
-
}
|
|
1192
|
-
|
|
1193
|
-
// Add IPv6 tables if enabled
|
|
1194
|
-
if (this.settings.ipv6Support) {
|
|
1195
|
-
commands.push(`add table ip6 ${this.tableName}`);
|
|
1196
|
-
commands.push(`add chain ip6 ${this.tableName} nat_prerouting { type nat hook prerouting priority -100; }`);
|
|
1197
|
-
|
|
1198
|
-
if (!this.settings.preserveSourceIP) {
|
|
1199
|
-
commands.push(`add chain ip6 ${this.tableName} nat_postrouting { type nat hook postrouting priority 100; }`);
|
|
1200
|
-
}
|
|
1201
|
-
|
|
1202
|
-
if (this.settings.netProxyIntegration?.enabled && this.settings.netProxyIntegration.redirectLocalhost) {
|
|
1203
|
-
commands.push(`add chain ip6 ${this.tableName} nat_output { type nat hook output priority 0; }`);
|
|
1204
|
-
}
|
|
1205
|
-
|
|
1206
|
-
if (this.settings.qos?.enabled) {
|
|
1207
|
-
commands.push(`add chain ip6 ${this.tableName} qos_forward { type filter hook forward priority 0; }`);
|
|
1208
|
-
}
|
|
1209
|
-
}
|
|
1210
|
-
|
|
1211
|
-
// Source IP filters
|
|
1212
|
-
if (this.settings.useIPSets) {
|
|
1213
|
-
if (this.settings.ipBlockList?.length) {
|
|
1214
|
-
commands.push(`add set ip ${this.tableName} banned_ips { type ipv4_addr; }`);
|
|
1215
|
-
commands.push(`add element ip ${this.tableName} banned_ips { ${this.settings.ipBlockList.join(', ')} }`);
|
|
1216
|
-
commands.push(`add rule ip ${this.tableName} nat_prerouting ip saddr @banned_ips drop comment "${this.ruleTag}:BANNED_SET"`);
|
|
1217
|
-
}
|
|
1218
|
-
|
|
1219
|
-
if (this.settings.ipAllowList?.length) {
|
|
1220
|
-
commands.push(`add set ip ${this.tableName} allowed_ips { type ipv4_addr; }`);
|
|
1221
|
-
commands.push(`add element ip ${this.tableName} allowed_ips { ${this.settings.ipAllowList.join(', ')} }`);
|
|
1222
|
-
commands.push(`add rule ip ${this.tableName} nat_prerouting ip saddr @allowed_ips ${this.settings.protocol} dport {${this.getAllPorts(this.settings.fromPort)}} accept comment "${this.ruleTag}:ALLOWED_SET"`);
|
|
1223
|
-
commands.push(`add rule ip ${this.tableName} nat_prerouting ${this.settings.protocol} dport {${this.getAllPorts(this.settings.fromPort)}} drop comment "${this.ruleTag}:DENY_ALL"`);
|
|
1224
|
-
}
|
|
1225
|
-
} else if (this.settings.ipBlockList?.length || this.settings.ipAllowList?.length) {
|
|
1226
|
-
// Traditional approach without IP sets
|
|
1227
|
-
if (this.settings.ipBlockList?.length) {
|
|
1228
|
-
for (const ip of this.settings.ipBlockList) {
|
|
1229
|
-
commands.push(`add rule ip ${this.tableName} nat_prerouting ip saddr ${ip} drop comment "${this.ruleTag}:BANNED"`);
|
|
1230
|
-
}
|
|
1231
|
-
}
|
|
1232
|
-
|
|
1233
|
-
if (this.settings.ipAllowList?.length) {
|
|
1234
|
-
for (const ip of this.settings.ipAllowList) {
|
|
1235
|
-
commands.push(`add rule ip ${this.tableName} nat_prerouting ip saddr ${ip} ${this.settings.protocol} dport {${this.getAllPorts(this.settings.fromPort)}} accept comment "${this.ruleTag}:ALLOWED"`);
|
|
1236
|
-
}
|
|
1237
|
-
commands.push(`add rule ip ${this.tableName} nat_prerouting ${this.settings.protocol} dport {${this.getAllPorts(this.settings.fromPort)}} drop comment "${this.ruleTag}:DENY_ALL"`);
|
|
1238
|
-
}
|
|
1239
|
-
}
|
|
1240
|
-
|
|
1241
|
-
// Port forwarding rules
|
|
1242
|
-
if (this.settings.useAdvancedNAT) {
|
|
1243
|
-
// Advanced NAT with connection tracking
|
|
1244
|
-
const fromPortRanges = normalizePortSpec(this.settings.fromPort);
|
|
1245
|
-
const toPortRanges = normalizePortSpec(this.settings.toPort);
|
|
1246
|
-
|
|
1247
|
-
if (fromPortRanges.length === 1 && toPortRanges.length === 1) {
|
|
1248
|
-
const fromRange = fromPortRanges[0];
|
|
1249
|
-
const toRange = toPortRanges[0];
|
|
1250
|
-
|
|
1251
|
-
if (fromRange.from === fromRange.to && toRange.from === toRange.to) {
|
|
1252
|
-
commands.push(`add rule ip ${this.tableName} nat_prerouting ${this.settings.protocol} dport ${fromRange.from} ct state new dnat to ${this.settings.toHost}:${toRange.from} comment "${this.ruleTag}:DNAT_CT"`);
|
|
1253
|
-
} else if ((fromRange.to - fromRange.from) === (toRange.to - toRange.from)) {
|
|
1254
|
-
commands.push(`add rule ip ${this.tableName} nat_prerouting ${this.settings.protocol} dport ${fromRange.from}-${fromRange.to} ct state new dnat to ${this.settings.toHost}:${toRange.from}-${toRange.to} comment "${this.ruleTag}:DNAT_RANGE_CT"`);
|
|
1255
|
-
}
|
|
1256
|
-
|
|
1257
|
-
commands.push(`add rule ip ${this.tableName} nat_prerouting ct state established,related accept comment "${this.ruleTag}:CT_ESTABLISHED"`);
|
|
1258
|
-
}
|
|
1259
|
-
} else {
|
|
1260
|
-
// Standard NAT rules
|
|
1261
|
-
const fromRanges = normalizePortSpec(this.settings.fromPort);
|
|
1262
|
-
const toRanges = normalizePortSpec(this.settings.toPort);
|
|
1263
|
-
|
|
1264
|
-
if (fromRanges.length === 1 && toRanges.length === 1) {
|
|
1265
|
-
const fromRange = fromRanges[0];
|
|
1266
|
-
const toRange = toRanges[0];
|
|
1267
|
-
|
|
1268
|
-
if (fromRange.from === fromRange.to && toRange.from === toRange.to) {
|
|
1269
|
-
commands.push(`add rule ip ${this.tableName} nat_prerouting ${this.settings.protocol} dport ${fromRange.from} dnat to ${this.settings.toHost}:${toRange.from} comment "${this.ruleTag}:DNAT"`);
|
|
1270
|
-
} else {
|
|
1271
|
-
commands.push(`add rule ip ${this.tableName} nat_prerouting ${this.settings.protocol} dport ${fromRange.from}-${fromRange.to} dnat to ${this.settings.toHost}:${toRange.from}-${toRange.to} comment "${this.ruleTag}:DNAT_RANGE"`);
|
|
1272
|
-
}
|
|
1273
|
-
} else if (toRanges.length === 1) {
|
|
1274
|
-
// One-to-many mapping
|
|
1275
|
-
for (const fromRange of fromRanges) {
|
|
1276
|
-
commands.push(`add rule ip ${this.tableName} nat_prerouting ${this.settings.protocol} dport ${fromRange.from}-${fromRange.to} dnat to ${this.settings.toHost}:${toRanges[0].from}-${toRanges[0].to} comment "${this.ruleTag}:DNAT_RANGE"`);
|
|
1277
|
-
}
|
|
1278
|
-
} else {
|
|
1279
|
-
// One-to-one mapping of multiple ranges
|
|
1280
|
-
for (let i = 0; i < fromRanges.length; i++) {
|
|
1281
|
-
commands.push(`add rule ip ${this.tableName} nat_prerouting ${this.settings.protocol} dport ${fromRanges[i].from}-${fromRanges[i].to} dnat to ${this.settings.toHost}:${toRanges[i].from}-${toRanges[i].to} comment "${this.ruleTag}:DNAT_RANGE"`);
|
|
1282
|
-
}
|
|
1283
|
-
}
|
|
1284
|
-
}
|
|
1285
|
-
|
|
1286
|
-
// Masquerade rules if not preserving source IP
|
|
1287
|
-
if (!this.settings.preserveSourceIP) {
|
|
1288
|
-
commands.push(`add rule ip ${this.tableName} nat_postrouting ${this.settings.protocol} daddr ${this.settings.toHost} dport {${this.getAllPorts(this.settings.toPort)}} masquerade comment "${this.ruleTag}:MASQ"`);
|
|
1289
|
-
}
|
|
1290
|
-
|
|
1291
|
-
// NetworkProxy integration
|
|
1292
|
-
if (this.settings.netProxyIntegration?.enabled &&
|
|
1293
|
-
this.settings.netProxyIntegration.redirectLocalhost &&
|
|
1294
|
-
this.settings.netProxyIntegration.sslTerminationPort) {
|
|
1295
|
-
|
|
1296
|
-
commands.push(`add rule ip ${this.tableName} nat_output ${this.settings.protocol} daddr 127.0.0.1 redirect to :${this.settings.netProxyIntegration.sslTerminationPort} comment "${this.ruleTag}:NETPROXY_REDIRECT"`);
|
|
1297
|
-
}
|
|
1298
|
-
|
|
1299
|
-
// QoS rules
|
|
1300
|
-
if (this.settings.qos?.enabled) {
|
|
1301
|
-
if (this.settings.qos.maxRate) {
|
|
1302
|
-
commands.push(`add rule ip ${this.tableName} qos_forward ip daddr ${this.settings.toHost} ${this.settings.protocol} dport {${this.getAllPorts(this.settings.toPort)}} limit rate over ${this.settings.qos.maxRate} drop comment "${this.ruleTag}:QOS_RATE"`);
|
|
1303
|
-
}
|
|
1304
|
-
|
|
1305
|
-
if (this.settings.qos.priority !== undefined) {
|
|
1306
|
-
commands.push(`add chain ip ${this.tableName} prio${this.settings.qos.priority} { type filter hook forward priority ${this.settings.qos.priority * 10}; }`);
|
|
1307
|
-
|
|
1308
|
-
for (const range of normalizePortSpec(this.settings.toPort)) {
|
|
1309
|
-
commands.push(`add rule ip ${this.tableName} qos_forward ${this.settings.protocol} dport ${range.from}-${range.to} counter goto prio${this.settings.qos.priority} comment "${this.ruleTag}:QOS_PRIORITY"`);
|
|
1310
|
-
}
|
|
1311
|
-
}
|
|
1312
|
-
}
|
|
1313
|
-
|
|
1314
|
-
return commands;
|
|
1315
|
-
}
|
|
1316
|
-
|
|
1317
|
-
/**
|
|
1318
|
-
* Starts the proxy by setting up all nftables rules
|
|
1319
|
-
*/
|
|
1320
|
-
public async start(): Promise<void> {
|
|
1321
|
-
// Check if nftables is available
|
|
1322
|
-
const nftablesAvailable = await this.checkNftablesAvailability();
|
|
1323
|
-
if (!nftablesAvailable) {
|
|
1324
|
-
throw new NftResourceError('nftables is not available or not properly configured');
|
|
1325
|
-
}
|
|
1326
|
-
|
|
1327
|
-
// Optionally clean slate first
|
|
1328
|
-
if (this.settings.forceCleanSlate) {
|
|
1329
|
-
await NfTablesProxy.cleanSlate();
|
|
1330
|
-
}
|
|
1331
|
-
|
|
1332
|
-
// Set up tables and chains for IPv4
|
|
1333
|
-
const setupSuccess = await this.setupTablesAndChains();
|
|
1334
|
-
if (!setupSuccess) {
|
|
1335
|
-
throw new NftExecutionError('Failed to set up nftables tables and chains');
|
|
1336
|
-
}
|
|
1337
|
-
|
|
1338
|
-
// Set up IPv6 tables and chains if enabled
|
|
1339
|
-
if (this.settings.ipv6Support) {
|
|
1340
|
-
const setupIPv6Success = await this.setupTablesAndChains(true);
|
|
1341
|
-
if (!setupIPv6Success) {
|
|
1342
|
-
this.log('warn', 'Failed to set up IPv6 tables and chains, continuing with IPv4 only');
|
|
1343
|
-
}
|
|
1344
|
-
}
|
|
1345
|
-
|
|
1346
|
-
// Add source IP filters
|
|
1347
|
-
await this.addSourceIPFilters();
|
|
1348
|
-
if (this.settings.ipv6Support) {
|
|
1349
|
-
await this.addSourceIPFilters(true);
|
|
1350
|
-
}
|
|
1351
|
-
|
|
1352
|
-
// Set up advanced NAT with connection tracking if enabled
|
|
1353
|
-
if (this.settings.useAdvancedNAT) {
|
|
1354
|
-
const advancedNatSuccess = await this.setupAdvancedNAT();
|
|
1355
|
-
if (!advancedNatSuccess) {
|
|
1356
|
-
this.log('warn', 'Failed to set up advanced NAT, falling back to standard NAT');
|
|
1357
|
-
this.settings.useAdvancedNAT = false;
|
|
1358
|
-
} else if (this.settings.ipv6Support) {
|
|
1359
|
-
await this.setupAdvancedNAT(true);
|
|
1360
|
-
}
|
|
1361
|
-
}
|
|
1362
|
-
|
|
1363
|
-
// Add port forwarding rules (skip if using advanced NAT)
|
|
1364
|
-
if (!this.settings.useAdvancedNAT) {
|
|
1365
|
-
const forwardingSuccess = await this.addPortForwardingRules();
|
|
1366
|
-
if (!forwardingSuccess) {
|
|
1367
|
-
throw new NftExecutionError('Failed to add port forwarding rules');
|
|
1368
|
-
}
|
|
1369
|
-
|
|
1370
|
-
// Add IPv6 port forwarding rules if enabled
|
|
1371
|
-
if (this.settings.ipv6Support) {
|
|
1372
|
-
const forwardingIPv6Success = await this.addPortForwardingRules(true);
|
|
1373
|
-
if (!forwardingIPv6Success) {
|
|
1374
|
-
this.log('warn', 'Failed to add IPv6 port forwarding rules');
|
|
1375
|
-
}
|
|
1376
|
-
}
|
|
1377
|
-
}
|
|
1378
|
-
|
|
1379
|
-
// Set up QoS if enabled
|
|
1380
|
-
if (this.settings.qos?.enabled) {
|
|
1381
|
-
const qosSuccess = await this.addTrafficShaping();
|
|
1382
|
-
if (!qosSuccess) {
|
|
1383
|
-
this.log('warn', 'Failed to set up QoS rules, continuing without traffic shaping');
|
|
1384
|
-
} else if (this.settings.ipv6Support) {
|
|
1385
|
-
await this.addTrafficShaping(true);
|
|
1386
|
-
}
|
|
1387
|
-
}
|
|
1388
|
-
|
|
1389
|
-
// Set up NetworkProxy integration if enabled
|
|
1390
|
-
if (this.settings.netProxyIntegration?.enabled) {
|
|
1391
|
-
const netProxySetupSuccess = await this.setupNetworkProxyIntegration();
|
|
1392
|
-
if (!netProxySetupSuccess) {
|
|
1393
|
-
this.log('warn', 'Failed to set up NetworkProxy integration');
|
|
1394
|
-
}
|
|
1395
|
-
|
|
1396
|
-
if (this.settings.ipv6Support) {
|
|
1397
|
-
await this.setupNetworkProxyIntegration(true);
|
|
1398
|
-
}
|
|
1399
|
-
}
|
|
1400
|
-
|
|
1401
|
-
// Final check - ensure we have at least one rule added
|
|
1402
|
-
if (this.rules.filter(r => r.added).length === 0) {
|
|
1403
|
-
throw new NftExecutionError('No rules were added');
|
|
1404
|
-
}
|
|
1405
|
-
|
|
1406
|
-
this.log('info', 'NfTablesProxy started successfully');
|
|
1407
|
-
}
|
|
1408
|
-
|
|
1409
|
-
/**
|
|
1410
|
-
* Stops the proxy by removing all added rules
|
|
1411
|
-
*/
|
|
1412
|
-
public async stop(): Promise<void> {
|
|
1413
|
-
try {
|
|
1414
|
-
let rulesetContent = '';
|
|
1415
|
-
|
|
1416
|
-
// Process rules in reverse order (LIFO)
|
|
1417
|
-
for (let i = this.rules.length - 1; i >= 0; i--) {
|
|
1418
|
-
const rule = this.rules[i];
|
|
1419
|
-
|
|
1420
|
-
if (rule.added) {
|
|
1421
|
-
// Create delete rules by replacing 'add' with 'delete'
|
|
1422
|
-
const deleteRule = rule.ruleContents.replace('add rule', 'delete rule');
|
|
1423
|
-
rulesetContent += `${deleteRule}\n`;
|
|
1424
|
-
}
|
|
1425
|
-
}
|
|
1426
|
-
|
|
1427
|
-
// Apply the ruleset if we have any rules to delete
|
|
1428
|
-
if (rulesetContent) {
|
|
1429
|
-
// Write to temporary file
|
|
1430
|
-
await AsyncFileSystem.writeFile(this.tempFilePath, rulesetContent);
|
|
1431
|
-
|
|
1432
|
-
try {
|
|
1433
|
-
// Apply the ruleset
|
|
1434
|
-
await this.executor.executeWithRetry(
|
|
1435
|
-
`${NfTablesProxy.NFT_CMD} -f ${this.tempFilePath}`,
|
|
1436
|
-
this.settings.maxRetries,
|
|
1437
|
-
this.settings.retryDelayMs
|
|
1438
|
-
);
|
|
1439
|
-
|
|
1440
|
-
this.log('info', 'Removed all added rules');
|
|
1441
|
-
|
|
1442
|
-
// Mark all rules as removed
|
|
1443
|
-
this.rules.forEach(rule => {
|
|
1444
|
-
rule.added = false;
|
|
1445
|
-
rule.verified = false;
|
|
1446
|
-
});
|
|
1447
|
-
} finally {
|
|
1448
|
-
// Remove temporary file
|
|
1449
|
-
await AsyncFileSystem.remove(this.tempFilePath);
|
|
1450
|
-
}
|
|
1451
|
-
}
|
|
1452
|
-
|
|
1453
|
-
// Clean up IP sets if we created any
|
|
1454
|
-
if (this.settings.useIPSets && this.ipSets.size > 0) {
|
|
1455
|
-
for (const [key, _] of this.ipSets) {
|
|
1456
|
-
const [family, setName] = key.split(':');
|
|
1457
|
-
|
|
1458
|
-
try {
|
|
1459
|
-
await this.executor.executeWithRetry(
|
|
1460
|
-
`${NfTablesProxy.NFT_CMD} delete set ${family} ${this.tableName} ${setName}`,
|
|
1461
|
-
this.settings.maxRetries,
|
|
1462
|
-
this.settings.retryDelayMs
|
|
1463
|
-
);
|
|
1464
|
-
|
|
1465
|
-
this.log('info', `Removed IP set ${setName} from ${family} ${this.tableName}`);
|
|
1466
|
-
} catch (err) {
|
|
1467
|
-
this.log('warn', `Failed to remove IP set ${setName}: ${err.message}`);
|
|
1468
|
-
}
|
|
1469
|
-
}
|
|
1470
|
-
|
|
1471
|
-
this.ipSets.clear();
|
|
1472
|
-
}
|
|
1473
|
-
|
|
1474
|
-
// Optionally clean up tables if they're empty
|
|
1475
|
-
await this.cleanupEmptyTables();
|
|
1476
|
-
|
|
1477
|
-
this.log('info', 'NfTablesProxy stopped successfully');
|
|
1478
|
-
} catch (err) {
|
|
1479
|
-
this.log('error', `Error stopping NfTablesProxy: ${err.message}`);
|
|
1480
|
-
throw err;
|
|
1481
|
-
}
|
|
1482
|
-
}
|
|
1483
|
-
|
|
1484
|
-
/**
|
|
1485
|
-
* Synchronous version of stop, for use in exit handlers only.
|
|
1486
|
-
* Uses single-attempt commands without retry (process is exiting anyway).
|
|
1487
|
-
*/
|
|
1488
|
-
public stopSync(): void {
|
|
1489
|
-
try {
|
|
1490
|
-
let rulesetContent = '';
|
|
1491
|
-
|
|
1492
|
-
// Process rules in reverse order (LIFO)
|
|
1493
|
-
for (let i = this.rules.length - 1; i >= 0; i--) {
|
|
1494
|
-
const rule = this.rules[i];
|
|
1495
|
-
|
|
1496
|
-
if (rule.added) {
|
|
1497
|
-
// Create delete rules by replacing 'add' with 'delete'
|
|
1498
|
-
const deleteRule = rule.ruleContents.replace('add rule', 'delete rule');
|
|
1499
|
-
rulesetContent += `${deleteRule}\n`;
|
|
1500
|
-
}
|
|
1501
|
-
}
|
|
1502
|
-
|
|
1503
|
-
// Apply the ruleset if we have any rules to delete
|
|
1504
|
-
if (rulesetContent) {
|
|
1505
|
-
// Write to temporary file
|
|
1506
|
-
fs.writeFileSync(this.tempFilePath, rulesetContent);
|
|
1507
|
-
|
|
1508
|
-
// Apply the ruleset (single attempt, no retry - process is exiting)
|
|
1509
|
-
this.executor.executeSync(`${NfTablesProxy.NFT_CMD} -f ${this.tempFilePath}`);
|
|
1510
|
-
|
|
1511
|
-
this.log('info', 'Removed all added rules');
|
|
1512
|
-
|
|
1513
|
-
// Mark all rules as removed
|
|
1514
|
-
this.rules.forEach(rule => {
|
|
1515
|
-
rule.added = false;
|
|
1516
|
-
rule.verified = false;
|
|
1517
|
-
});
|
|
1518
|
-
|
|
1519
|
-
// Remove temporary file
|
|
1520
|
-
try {
|
|
1521
|
-
fs.unlinkSync(this.tempFilePath);
|
|
1522
|
-
} catch {
|
|
1523
|
-
// Ignore - process is exiting
|
|
1524
|
-
}
|
|
1525
|
-
}
|
|
1526
|
-
|
|
1527
|
-
// Clean up IP sets if we created any
|
|
1528
|
-
if (this.settings.useIPSets && this.ipSets.size > 0) {
|
|
1529
|
-
for (const [key, _] of this.ipSets) {
|
|
1530
|
-
const [family, setName] = key.split(':');
|
|
1531
|
-
|
|
1532
|
-
try {
|
|
1533
|
-
this.executor.executeSync(
|
|
1534
|
-
`${NfTablesProxy.NFT_CMD} delete set ${family} ${this.tableName} ${setName}`
|
|
1535
|
-
);
|
|
1536
|
-
} catch {
|
|
1537
|
-
// Non-critical error, continue
|
|
1538
|
-
}
|
|
1539
|
-
}
|
|
1540
|
-
}
|
|
1541
|
-
|
|
1542
|
-
// Optionally clean up tables if they're empty (sync version)
|
|
1543
|
-
this.cleanupEmptyTablesSync();
|
|
1544
|
-
|
|
1545
|
-
this.log('info', 'NfTablesProxy stopped successfully');
|
|
1546
|
-
} catch (err) {
|
|
1547
|
-
this.log('error', `Error stopping NfTablesProxy: ${err.message}`);
|
|
1548
|
-
}
|
|
1549
|
-
}
|
|
1550
|
-
|
|
1551
|
-
/**
|
|
1552
|
-
* Cleans up empty tables
|
|
1553
|
-
*/
|
|
1554
|
-
private async cleanupEmptyTables(): Promise<void> {
|
|
1555
|
-
// Check if tables are empty, and if so, delete them
|
|
1556
|
-
for (const family of ['ip', 'ip6']) {
|
|
1557
|
-
// Skip IPv6 if not enabled
|
|
1558
|
-
if (family === 'ip6' && !this.settings.ipv6Support) {
|
|
1559
|
-
continue;
|
|
1560
|
-
}
|
|
1561
|
-
|
|
1562
|
-
try {
|
|
1563
|
-
// Check if table exists
|
|
1564
|
-
const tableExists = await this.tableExists(family, this.tableName);
|
|
1565
|
-
if (!tableExists) {
|
|
1566
|
-
continue;
|
|
1567
|
-
}
|
|
1568
|
-
|
|
1569
|
-
// Check if the table has any rules
|
|
1570
|
-
const stdout = await this.executor.executeWithRetry(
|
|
1571
|
-
`${NfTablesProxy.NFT_CMD} list table ${family} ${this.tableName}`,
|
|
1572
|
-
this.settings.maxRetries,
|
|
1573
|
-
this.settings.retryDelayMs
|
|
1574
|
-
);
|
|
1575
|
-
|
|
1576
|
-
const hasRules = stdout.includes('rule');
|
|
1577
|
-
|
|
1578
|
-
if (!hasRules) {
|
|
1579
|
-
// Table is empty, delete it
|
|
1580
|
-
await this.executor.executeWithRetry(
|
|
1581
|
-
`${NfTablesProxy.NFT_CMD} delete table ${family} ${this.tableName}`,
|
|
1582
|
-
this.settings.maxRetries,
|
|
1583
|
-
this.settings.retryDelayMs
|
|
1584
|
-
);
|
|
1585
|
-
|
|
1586
|
-
this.log('info', `Deleted empty table ${family} ${this.tableName}`);
|
|
1587
|
-
}
|
|
1588
|
-
} catch (err) {
|
|
1589
|
-
this.log('error', `Error cleaning up tables: ${err.message}`);
|
|
1590
|
-
}
|
|
1591
|
-
}
|
|
1592
|
-
}
|
|
1593
|
-
|
|
1594
|
-
/**
|
|
1595
|
-
* Synchronous version of cleanupEmptyTables (for exit handlers only)
|
|
1596
|
-
*/
|
|
1597
|
-
private cleanupEmptyTablesSync(): void {
|
|
1598
|
-
// Check if tables are empty, and if so, delete them
|
|
1599
|
-
for (const family of ['ip', 'ip6']) {
|
|
1600
|
-
// Skip IPv6 if not enabled
|
|
1601
|
-
if (family === 'ip6' && !this.settings.ipv6Support) {
|
|
1602
|
-
continue;
|
|
1603
|
-
}
|
|
1604
|
-
|
|
1605
|
-
try {
|
|
1606
|
-
// Check if table exists
|
|
1607
|
-
const tableExistsOutput = this.executor.executeSync(
|
|
1608
|
-
`${NfTablesProxy.NFT_CMD} list tables ${family}`
|
|
1609
|
-
);
|
|
1610
|
-
|
|
1611
|
-
const tableExists = tableExistsOutput.includes(`table ${family} ${this.tableName}`);
|
|
1612
|
-
|
|
1613
|
-
if (!tableExists) {
|
|
1614
|
-
continue;
|
|
1615
|
-
}
|
|
1616
|
-
|
|
1617
|
-
// Check if the table has any rules
|
|
1618
|
-
const stdout = this.executor.executeSync(
|
|
1619
|
-
`${NfTablesProxy.NFT_CMD} list table ${family} ${this.tableName}`
|
|
1620
|
-
);
|
|
1621
|
-
|
|
1622
|
-
const hasRules = stdout.includes('rule');
|
|
1623
|
-
|
|
1624
|
-
if (!hasRules) {
|
|
1625
|
-
// Table is empty, delete it
|
|
1626
|
-
this.executor.executeSync(
|
|
1627
|
-
`${NfTablesProxy.NFT_CMD} delete table ${family} ${this.tableName}`
|
|
1628
|
-
);
|
|
1629
|
-
|
|
1630
|
-
this.log('info', `Deleted empty table ${family} ${this.tableName}`);
|
|
1631
|
-
}
|
|
1632
|
-
} catch (err) {
|
|
1633
|
-
this.log('error', `Error cleaning up tables: ${err.message}`);
|
|
1634
|
-
}
|
|
1635
|
-
}
|
|
1636
|
-
}
|
|
1637
|
-
|
|
1638
|
-
/**
|
|
1639
|
-
* Removes all nftables rules created by this module
|
|
1640
|
-
*/
|
|
1641
|
-
public static async cleanSlate(): Promise<void> {
|
|
1642
|
-
try {
|
|
1643
|
-
// Check for rules with our comment pattern
|
|
1644
|
-
const stdout = await execAsync(`${NfTablesProxy.NFT_CMD} list ruleset`);
|
|
1645
|
-
|
|
1646
|
-
// Extract our tables
|
|
1647
|
-
const tableMatches = stdout.stdout.match(/table (ip|ip6) (\w+) {[^}]*NfTablesProxy:[^}]*}/g);
|
|
1648
|
-
|
|
1649
|
-
if (tableMatches) {
|
|
1650
|
-
for (const tableMatch of tableMatches) {
|
|
1651
|
-
// Extract table family and name
|
|
1652
|
-
const familyMatch = tableMatch.match(/table (ip|ip6) (\w+)/);
|
|
1653
|
-
if (familyMatch) {
|
|
1654
|
-
const family = familyMatch[1];
|
|
1655
|
-
const tableName = familyMatch[2];
|
|
1656
|
-
|
|
1657
|
-
// Delete the table
|
|
1658
|
-
await execAsync(`${NfTablesProxy.NFT_CMD} delete table ${family} ${tableName}`);
|
|
1659
|
-
console.log(`Deleted table ${family} ${tableName} containing NfTablesProxy rules`);
|
|
1660
|
-
}
|
|
1661
|
-
}
|
|
1662
|
-
} else {
|
|
1663
|
-
console.log('No NfTablesProxy rules found to clean up');
|
|
1664
|
-
}
|
|
1665
|
-
} catch (err) {
|
|
1666
|
-
console.error(`Error in cleanSlate: ${err}`);
|
|
1667
|
-
}
|
|
1668
|
-
}
|
|
1669
|
-
|
|
1670
|
-
/**
|
|
1671
|
-
* Synchronous version of cleanSlate
|
|
1672
|
-
* @deprecated This method blocks the event loop and should be avoided. Use cleanSlate() instead.
|
|
1673
|
-
* WARNING: This method uses execSync which blocks the entire Node.js event loop!
|
|
1674
|
-
*/
|
|
1675
|
-
public static cleanSlateSync(): void {
|
|
1676
|
-
console.warn('[DEPRECATION WARNING] cleanSlateSync blocks the event loop and should not be used. Consider using the async cleanSlate() method instead.');
|
|
1677
|
-
|
|
1678
|
-
try {
|
|
1679
|
-
// Check for rules with our comment pattern
|
|
1680
|
-
const stdout = execSync(`${NfTablesProxy.NFT_CMD} list ruleset`).toString();
|
|
1681
|
-
|
|
1682
|
-
// Extract our tables
|
|
1683
|
-
const tableMatches = stdout.match(/table (ip|ip6) (\w+) {[^}]*NfTablesProxy:[^}]*}/g);
|
|
1684
|
-
|
|
1685
|
-
if (tableMatches) {
|
|
1686
|
-
for (const tableMatch of tableMatches) {
|
|
1687
|
-
// Extract table family and name
|
|
1688
|
-
const familyMatch = tableMatch.match(/table (ip|ip6) (\w+)/);
|
|
1689
|
-
if (familyMatch) {
|
|
1690
|
-
const family = familyMatch[1];
|
|
1691
|
-
const tableName = familyMatch[2];
|
|
1692
|
-
|
|
1693
|
-
// Delete the table
|
|
1694
|
-
execSync(`${NfTablesProxy.NFT_CMD} delete table ${family} ${tableName}`);
|
|
1695
|
-
console.log(`Deleted table ${family} ${tableName} containing NfTablesProxy rules`);
|
|
1696
|
-
}
|
|
1697
|
-
}
|
|
1698
|
-
} else {
|
|
1699
|
-
console.log('No NfTablesProxy rules found to clean up');
|
|
1700
|
-
}
|
|
1701
|
-
} catch (err) {
|
|
1702
|
-
console.error(`Error in cleanSlateSync: ${err}`);
|
|
1703
|
-
}
|
|
1704
|
-
}
|
|
1705
|
-
|
|
1706
|
-
/**
|
|
1707
|
-
* Improved logging with structured output
|
|
1708
|
-
*/
|
|
1709
|
-
private log(level: 'info' | 'warn' | 'error' | 'debug', message: string, meta?: Record<string, any>): void {
|
|
1710
|
-
if (!this.settings.enableLogging && (level === 'info' || level === 'debug')) {
|
|
1711
|
-
return;
|
|
1712
|
-
}
|
|
1713
|
-
|
|
1714
|
-
const timestamp = new Date().toISOString();
|
|
1715
|
-
|
|
1716
|
-
const logData = {
|
|
1717
|
-
timestamp,
|
|
1718
|
-
level: level.toUpperCase(),
|
|
1719
|
-
message,
|
|
1720
|
-
...meta,
|
|
1721
|
-
context: {
|
|
1722
|
-
instance: this.ruleTag,
|
|
1723
|
-
table: this.tableName
|
|
1724
|
-
}
|
|
1725
|
-
};
|
|
1726
|
-
|
|
1727
|
-
// Determine if output should be JSON or plain text based on settings
|
|
1728
|
-
const useJson = this.settings.logFormat === 'json';
|
|
1729
|
-
|
|
1730
|
-
if (useJson) {
|
|
1731
|
-
const logOutput = JSON.stringify(logData);
|
|
1732
|
-
console.log(logOutput);
|
|
1733
|
-
return;
|
|
1734
|
-
}
|
|
1735
|
-
|
|
1736
|
-
// Plain text format
|
|
1737
|
-
const metaStr = meta ? ` ${JSON.stringify(meta)}` : '';
|
|
1738
|
-
|
|
1739
|
-
switch (level) {
|
|
1740
|
-
case 'info':
|
|
1741
|
-
console.log(`[${timestamp}] [INFO] ${message}${metaStr}`);
|
|
1742
|
-
break;
|
|
1743
|
-
case 'warn':
|
|
1744
|
-
console.warn(`[${timestamp}] [WARN] ${message}${metaStr}`);
|
|
1745
|
-
break;
|
|
1746
|
-
case 'error':
|
|
1747
|
-
console.error(`[${timestamp}] [ERROR] ${message}${metaStr}`);
|
|
1748
|
-
break;
|
|
1749
|
-
case 'debug':
|
|
1750
|
-
console.log(`[${timestamp}] [DEBUG] ${message}${metaStr}`);
|
|
1751
|
-
break;
|
|
1752
|
-
}
|
|
1753
|
-
}
|
|
1754
|
-
}
|