Repository navigation
Expand file tree
/
Copy pathproxy.js
More file actions
335 lines (288 loc) · 13.1 KB
/
Copy pathproxy.js
File metadata and controls
335 lines (288 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
/**
* BBSFirewall - TCP proxy connection handler
*
* Shared by the telnet proxy and the SSH passthrough proxy. The passthrough
* path forwards an already-encrypted SSH stream, so it opts out of encoding
* detection and (by default) PROXY Protocol via the options argument.
*
* https://github.com/SysopNetwork/BBSFirewall
*/
const net = require('net');
const logger = require('./logger');
const { config } = require('./config');
const { getGeoIP } = require('./geoip');
const { getIPFilter } = require('./ipfilter');
const metrics = require('./metrics');
const { detectFromTelnetNegotiation, getBackendPortForEncoding } = require('./encoding-detector');
const { buildHeader: buildProxyHeader } = require('./proxy-protocol');
class ProxyConnection {
constructor(clientSocket, backendHost, backendPort, options = {}) {
this.clientSocket = clientSocket;
this.backendHost = backendHost;
this.backendPort = backendPort;
this.backendSocket = null;
this.clientAddress = `${clientSocket.remoteAddress || 'unknown'}:${clientSocket.remotePort || 'unknown'}`;
this.connectionId = this.generateConnectionId();
this.bytesFromClient = 0;
this.bytesFromBackend = 0;
this.isCleanedUp = false;
this.detectedEncoding = 'cp437';
this.terminalType = null;
this.clientIp = null; // set in connect() once validated
this.connectionTracked = false; // true when trackConnectionOpen has been called
this.connectTimer = null; // backend connect deadline (cleared on connect/cleanup)
// Auto-block trigger scanning — telnet only (an encrypted SSH passthrough
// stream has nothing plaintext to match). Disabled for whitelisted IPs in
// connect(). this.triggerScanner (ipfilter.createTriggerScanner) covers the
// first TRIGGER_SCAN_BYTES the client sends; once it fills, scanning stops
// for the rest of the session.
this.triggerScan = config.triggerBlock.enabled && (options.proxyName || 'telnet') === 'telnet';
this.triggerScanner = null;
// Per-proxy behavior. The SSH passthrough forwards encrypted bytes, so it
// disables encoding detection and defaults PROXY Protocol off.
this.proxyName = options.proxyName || 'telnet';
this.encodingDetection = options.encodingDetection !== undefined
? options.encodingDetection
: config.encodingDetection;
this.proxyProtocol = options.proxyProtocol !== undefined
? options.proxyProtocol
: config.proxyProtocolEnabled;
this.log = logger.getLogger(this.proxyName);
}
generateConnectionId() {
return `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
}
// Drop a refused caller now. end() only half-closed the socket and then
// waited for the caller to close its side, and server.js releases the
// connection slot on 'close' - so a blocked caller that simply never hung
// up held a MAX_CONNECTIONS slot until CONNECTION_TIMEOUT (forever at 0).
// Nothing is ever sent to a refused caller, so there is nothing to flush.
rejectClient() {
this.clientSocket.on('error', (err) => {
this.log.debug(`[${this.connectionId}] Client socket error during rejection: ${err.message}`);
});
this.clientSocket.destroy();
}
connect() {
const clientIp = this.clientSocket.remoteAddress;
if (!clientIp) {
this.log.blocked(`[${this.connectionId}] Connection rejected: unable to determine client IP`);
this.rejectClient();
return;
}
this.clientIp = clientIp;
this.log.connection(`[${this.connectionId}] New connection from ${this.clientAddress}`);
const ipFilter = getIPFilter();
let isWhitelisted = false;
if (ipFilter) {
const filterResult = ipFilter.shouldAllowConnection(clientIp);
if (!filterResult.allowed) {
this.log.blocked(`[${this.connectionId}] Connection blocked by IP filter: ${filterResult.reason}`);
this.rejectClient();
return;
}
isWhitelisted = filterResult.whitelisted || false;
}
if (isWhitelisted) this.triggerScan = false;
// Check per-IP concurrent connection limit (whitelisted IPs are exempt)
if (!isWhitelisted && ipFilter && ipFilter.isConnectionLimitExceeded(clientIp)) {
this.log.blocked(`[${this.connectionId}] Connection rejected: per-IP limit reached for ${clientIp}`);
this.rejectClient();
return;
}
// Check country blocking (whitelisted IPs are exempt)
if (!isWhitelisted && this.shouldBlockConnection(clientIp)) {
this.log.blocked(`[${this.connectionId}] Connection blocked by country filter`);
this.rejectClient();
return;
}
// All checks passed — register this connection in the per-IP tracker
if (ipFilter) {
ipFilter.trackConnectionOpen(clientIp);
this.connectionTracked = true;
}
this.clientSocket.setNoDelay(true);
this.clientSocket.setKeepAlive(true);
// Pause client data until the backend is connected and the PROXY header
// (if enabled) has been written. Fast-connecting clients (fTelnet,
// MuffTerm, MegaMUD) send telnet negotiation bytes immediately on TCP
// connect. Without this pause those bytes can reach the BBS before the
// PROXY header, causing PROXCLIP to miss the header and GALTNTD to echo
// it as raw text.
this.clientSocket.pause();
const actualBackendPort = this.encodingDetection
? getBackendPortForEncoding(this.detectedEncoding, config)
: this.backendPort;
if (this.encodingDetection) {
this.log.info(`[${this.connectionId}] Using backend port ${actualBackendPort} for encoding: ${this.detectedEncoding}`);
}
// Give up if the backend TCP connection does not establish in time. Without
// this, a backend that silently drops SYN leaves the client paused and
// holding a global + per-IP connection slot until the OS TCP timeout.
if (config.backendConnectTimeout > 0) {
this.connectTimer = setTimeout(() => {
this.log.blocked(`[${this.connectionId}] Backend connect timed out after ` +
`${config.backendConnectTimeout}ms (${this.backendHost}:${actualBackendPort})`);
this.cleanup('backend-connect-timeout');
}, config.backendConnectTimeout);
}
this.backendSocket = net.createConnection({
host: this.backendHost,
port: actualBackendPort,
}, () => {
if (this.connectTimer) { clearTimeout(this.connectTimer); this.connectTimer = null; }
const backendAddr = `${this.backendSocket.remoteAddress}:${this.backendSocket.remotePort}`;
const localAddr = `${this.backendSocket.localAddress}:${this.backendSocket.localPort}`;
this.log.connection(`[${this.connectionId}] Connected to backend ${backendAddr} (from ${localAddr})`);
this.backendSocket.setNoDelay(true);
this.backendSocket.setKeepAlive(true);
// Send PROXY Protocol v1 header before any BBS data flows.
// The backend must support it — see PROXY_PROTOCOL_ENABLED in .env.
if (this.proxyProtocol) {
// The PROXY header describes the ORIGINAL connection from the client's
// perspective: src = client, dst = the address on this proxy the client
// connected to. Use the client-facing socket's local address (not the
// backend-side one) so the two addresses share a family — an IPv6 client
// yields a valid TCP6 line instead of a mixed-family one PROXCLIP drops.
const header = buildProxyHeader(
this.clientSocket.remoteAddress,
this.clientSocket.localAddress,
this.clientSocket.remotePort,
this.clientSocket.localPort
);
this.backendSocket.write(header);
this.log.info(`[${this.connectionId}] PROXY Protocol header sent: ${header.trim()}`);
}
// PROXY header is now in the send buffer (or skipped); safe to let
// client data flow.
this.clientSocket.resume();
});
// Error handlers must be set before data pipes to catch early failures
this.setupErrorHandlers();
this.setupPipes();
this.setupCloseHandlers();
}
shouldBlockConnection(ipAddress) {
const geoip = getGeoIP();
if (!geoip || !geoip.isEnabled) {
return false;
}
const geoInfo = geoip.getCountryInfo(ipAddress);
if (!geoInfo || !geoInfo.countryCode) {
if (config.blockUnknownCountries) {
this.log.info(`[${this.connectionId}] Blocked unknown country for IP: ${ipAddress}`);
return true;
}
return false;
}
this.log.debug(`[${this.connectionId}] Connection from ${geoInfo.countryName} (${geoInfo.countryCode})`);
if (config.blockedCountries.length > 0) {
const isBlocked = config.blockedCountries.includes(geoInfo.countryCode.toUpperCase());
if (isBlocked) {
this.log.info(`[${this.connectionId}] Blocked ${geoInfo.countryName} (${geoInfo.countryCode})`);
}
return isBlocked;
}
return false;
}
setupPipes() {
this.clientSocket.on('data', (data) => {
if (this.triggerScan) {
const ipFilter = getIPFilter();
if (!this.triggerScanner && ipFilter) this.triggerScanner = ipFilter.createTriggerScanner(config.triggerBlock.scanBytes);
const hit = this.triggerScanner && this.triggerScanner.feed(data);
if (hit) {
this.log.blocked(`[${this.connectionId}] Auto-block ${this.clientIp}: matched trigger ${JSON.stringify(hit)}`);
ipFilter.autoBlockIP(this.clientIp, hit);
metrics.incTriggerBlock();
this.cleanup('trigger-block');
return; // do not forward the offending bytes
}
if (!this.triggerScanner || this.triggerScanner.full) {
this.triggerScan = false;
this.triggerScanner = null;
}
}
this.bytesFromClient += data.length;
metrics.incBytes('fromClient', data.length);
const preview = data.toString('hex').substring(0, 60);
this.log.debug(`[${this.connectionId}] Client → Backend: ${data.length} bytes [${preview}${data.length > 30 ? '...' : ''}]`);
if (this.backendSocket && !this.backendSocket.destroyed) {
if (!this.backendSocket.write(data)) {
this.log.debug(`[${this.connectionId}] Backend buffer full, pausing client`);
this.clientSocket.pause();
this.backendSocket.once('drain', () => {
this.log.debug(`[${this.connectionId}] Backend drained, resuming client`);
this.clientSocket.resume();
});
}
}
});
this.backendSocket.on('data', (data) => {
this.bytesFromBackend += data.length;
metrics.incBytes('fromBackend', data.length);
const preview = data.toString('hex').substring(0, 60);
this.log.debug(`[${this.connectionId}] Backend → Client: ${data.length} bytes [${preview}${data.length > 30 ? '...' : ''}]`);
if (this.clientSocket && !this.clientSocket.destroyed) {
if (!this.clientSocket.write(data)) {
this.log.debug(`[${this.connectionId}] Client buffer full, pausing backend`);
this.backendSocket.pause();
this.clientSocket.once('drain', () => {
this.log.debug(`[${this.connectionId}] Client drained, resuming backend`);
this.backendSocket.resume();
});
}
}
});
}
setupErrorHandlers() {
this.clientSocket.on('error', (err) => {
this.log.error(`[${this.connectionId}] Client socket error: ${err.message}`);
this.cleanup('client-error');
});
this.backendSocket.on('error', (err) => {
this.log.error(`[${this.connectionId}] Backend socket error: ${err.message}`);
this.cleanup('backend-error');
});
}
setupCloseHandlers() {
this.clientSocket.on('close', (hadError) => {
this.log.debug(`[${this.connectionId}] Client socket closed (hadError: ${hadError})`);
this.cleanup('client-close');
});
this.backendSocket.on('close', (hadError) => {
this.log.debug(`[${this.connectionId}] Backend socket closed (hadError: ${hadError})`);
this.cleanup('backend-close');
});
}
cleanup(reason) {
if (this.isCleanedUp) return;
this.isCleanedUp = true;
if (this.connectTimer) { clearTimeout(this.connectTimer); this.connectTimer = null; }
// Release the per-IP connection slot regardless of how the connection ended
if (this.connectionTracked && this.clientIp) {
const ipFilter = getIPFilter();
if (ipFilter) {
ipFilter.trackConnectionClose(this.clientIp);
}
}
this.log.connection(`[${this.connectionId}] Connection closed (reason: ${reason}). Bytes: client→backend=${this.bytesFromClient}, backend→client=${this.bytesFromBackend}`);
if (this.clientSocket && !this.clientSocket.destroyed) {
this.clientSocket.destroy();
}
if (this.backendSocket && !this.backendSocket.destroyed) {
this.backendSocket.destroy();
}
}
}
/**
* @param {net.Socket} clientSocket
* @param {string} backendHost
* @param {number} backendPort
* @param {{proxyName?: string, encodingDetection?: boolean, proxyProtocol?: boolean}} [options]
*/
function handleConnection(clientSocket, backendHost, backendPort, options = {}) {
const proxy = new ProxyConnection(clientSocket, backendHost, backendPort, options);
proxy.connect();
}
module.exports = { handleConnection };