|
|
|
@ -1,4 +1,4 @@
|
|
|
|
|
import * as plugins from './smartproxy.plugins.js';
|
|
|
|
|
import * as plugins from './plugins.js';
|
|
|
|
|
|
|
|
|
|
export interface IDomainConfig {
|
|
|
|
|
domain: string; // glob pattern for domain
|
|
|
|
@ -115,6 +115,13 @@ function extractSNI(buffer: Buffer): string | undefined {
|
|
|
|
|
export class PortProxy {
|
|
|
|
|
netServer: plugins.net.Server;
|
|
|
|
|
settings: IProxySettings;
|
|
|
|
|
// Track active incoming connections
|
|
|
|
|
private activeConnections: Set<plugins.net.Socket> = new Set();
|
|
|
|
|
// Record start times for incoming connections
|
|
|
|
|
private incomingConnectionTimes: Map<plugins.net.Socket, number> = new Map();
|
|
|
|
|
// Record start times for outgoing connections
|
|
|
|
|
private outgoingConnectionTimes: Map<plugins.net.Socket, number> = new Map();
|
|
|
|
|
private connectionLogger: NodeJS.Timeout | null = null;
|
|
|
|
|
|
|
|
|
|
constructor(settings: IProxySettings) {
|
|
|
|
|
this.settings = {
|
|
|
|
@ -161,81 +168,90 @@ export class PortProxy {
|
|
|
|
|
return this.settings.domains.find(config => plugins.minimatch(serverName, config.domain));
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Always create a plain net server for TLS passthrough.
|
|
|
|
|
// Create a plain net server for TLS passthrough.
|
|
|
|
|
this.netServer = plugins.net.createServer((socket: plugins.net.Socket) => {
|
|
|
|
|
const remoteIP = socket.remoteAddress || '';
|
|
|
|
|
|
|
|
|
|
// If SNI is enabled, we peek at the first chunk to extract the SNI.
|
|
|
|
|
if (this.settings.sniEnabled) {
|
|
|
|
|
socket.once('data', (chunk: Buffer) => {
|
|
|
|
|
// Try to extract the server name from the ClientHello.
|
|
|
|
|
const serverName = extractSNI(chunk) || '';
|
|
|
|
|
console.log(`Received connection from ${remoteIP} with SNI: ${serverName}`);
|
|
|
|
|
|
|
|
|
|
// Check if the IP is allowed by default.
|
|
|
|
|
const isDefaultAllowed = this.settings.defaultAllowedIPs && isAllowed(remoteIP, this.settings.defaultAllowedIPs);
|
|
|
|
|
if (!isDefaultAllowed && serverName) {
|
|
|
|
|
const domainConfig = findMatchingDomain(serverName);
|
|
|
|
|
if (!domainConfig) {
|
|
|
|
|
console.log(`Connection rejected: No matching domain config for ${serverName} from IP ${remoteIP}`);
|
|
|
|
|
socket.end();
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
if (!isAllowed(remoteIP, domainConfig.allowedIPs)) {
|
|
|
|
|
console.log(`Connection rejected: IP ${remoteIP} not allowed for domain ${serverName}`);
|
|
|
|
|
socket.end();
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
} else if (!isDefaultAllowed && !serverName) {
|
|
|
|
|
console.log(`Connection rejected: No SNI and IP ${remoteIP} not in default allowed list`);
|
|
|
|
|
// Record start time for the incoming connection.
|
|
|
|
|
this.activeConnections.add(socket);
|
|
|
|
|
this.incomingConnectionTimes.set(socket, Date.now());
|
|
|
|
|
console.log(`New connection from ${remoteIP}. Active connections: ${this.activeConnections.size}`);
|
|
|
|
|
|
|
|
|
|
// Flag to detect if we've received the first data chunk.
|
|
|
|
|
let initialDataReceived = false;
|
|
|
|
|
|
|
|
|
|
// Immediately attach an error handler to catch early errors.
|
|
|
|
|
socket.on('error', (err: Error) => {
|
|
|
|
|
if (!initialDataReceived) {
|
|
|
|
|
console.log(`(Premature) Incoming socket error from ${remoteIP} before data received: ${err.message}`);
|
|
|
|
|
} else {
|
|
|
|
|
console.log(`(Immediate) Incoming socket error from ${remoteIP}: ${err.message}`);
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Flag to ensure cleanup happens only once.
|
|
|
|
|
let connectionClosed = false;
|
|
|
|
|
const cleanupOnce = () => {
|
|
|
|
|
if (!connectionClosed) {
|
|
|
|
|
connectionClosed = true;
|
|
|
|
|
cleanUpSockets(socket, to);
|
|
|
|
|
this.incomingConnectionTimes.delete(socket);
|
|
|
|
|
if (to) {
|
|
|
|
|
this.outgoingConnectionTimes.delete(to);
|
|
|
|
|
}
|
|
|
|
|
if (this.activeConnections.has(socket)) {
|
|
|
|
|
this.activeConnections.delete(socket);
|
|
|
|
|
console.log(`Connection from ${remoteIP} terminated. Active connections: ${this.activeConnections.size}`);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
let to: plugins.net.Socket;
|
|
|
|
|
|
|
|
|
|
const handleError = (side: 'incoming' | 'outgoing') => (err: Error) => {
|
|
|
|
|
const code = (err as any).code;
|
|
|
|
|
if (code === 'ECONNRESET') {
|
|
|
|
|
console.log(`ECONNRESET on ${side} side from ${remoteIP}: ${err.message}`);
|
|
|
|
|
} else {
|
|
|
|
|
console.log(`Error on ${side} side from ${remoteIP}: ${err.message}`);
|
|
|
|
|
}
|
|
|
|
|
cleanupOnce();
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const handleClose = (side: 'incoming' | 'outgoing') => () => {
|
|
|
|
|
console.log(`Connection closed on ${side} side from ${remoteIP}`);
|
|
|
|
|
cleanupOnce();
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Setup connection, optionally accepting the initial data chunk.
|
|
|
|
|
const setupConnection = (serverName: string, initialChunk?: Buffer) => {
|
|
|
|
|
// Check if the IP is allowed by default.
|
|
|
|
|
const isDefaultAllowed = this.settings.defaultAllowedIPs && isAllowed(remoteIP, this.settings.defaultAllowedIPs);
|
|
|
|
|
if (!isDefaultAllowed && serverName) {
|
|
|
|
|
const domainConfig = findMatchingDomain(serverName);
|
|
|
|
|
if (!domainConfig) {
|
|
|
|
|
console.log(`Connection rejected: No matching domain config for ${serverName} from ${remoteIP}`);
|
|
|
|
|
socket.end();
|
|
|
|
|
return;
|
|
|
|
|
} else {
|
|
|
|
|
console.log(`Connection allowed: IP ${remoteIP} is in default allowed list`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Determine target host.
|
|
|
|
|
const domainConfig = serverName ? findMatchingDomain(serverName) : undefined;
|
|
|
|
|
const targetHost = domainConfig?.targetIP || this.settings.toHost!;
|
|
|
|
|
|
|
|
|
|
// Create connection options.
|
|
|
|
|
const connectionOptions: plugins.net.NetConnectOpts = {
|
|
|
|
|
host: targetHost,
|
|
|
|
|
port: this.settings.toPort,
|
|
|
|
|
};
|
|
|
|
|
if (this.settings.preserveSourceIP) {
|
|
|
|
|
connectionOptions.localAddress = remoteIP.replace('::ffff:', '');
|
|
|
|
|
if (!isAllowed(remoteIP, domainConfig.allowedIPs)) {
|
|
|
|
|
console.log(`Connection rejected: IP ${remoteIP} not allowed for domain ${serverName}`);
|
|
|
|
|
socket.end();
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const to = plugins.net.connect(connectionOptions);
|
|
|
|
|
console.log(`Connection established: ${remoteIP} -> ${targetHost}:${this.settings.toPort}${serverName ? ` (SNI: ${serverName})` : ''}`);
|
|
|
|
|
|
|
|
|
|
// Unshift the data chunk back so that the TLS handshake can complete at the backend.
|
|
|
|
|
socket.unshift(chunk);
|
|
|
|
|
socket.setTimeout(120000);
|
|
|
|
|
socket.pipe(to);
|
|
|
|
|
to.pipe(socket);
|
|
|
|
|
|
|
|
|
|
const errorHandler = () => {
|
|
|
|
|
cleanUpSockets(socket, to);
|
|
|
|
|
};
|
|
|
|
|
socket.on('error', errorHandler);
|
|
|
|
|
to.on('error', errorHandler);
|
|
|
|
|
socket.on('close', errorHandler);
|
|
|
|
|
to.on('close', errorHandler);
|
|
|
|
|
socket.on('timeout', errorHandler);
|
|
|
|
|
to.on('timeout', errorHandler);
|
|
|
|
|
socket.on('end', errorHandler);
|
|
|
|
|
to.on('end', errorHandler);
|
|
|
|
|
});
|
|
|
|
|
} else {
|
|
|
|
|
// If SNI is not enabled, use defaultAllowedIPs check.
|
|
|
|
|
if (!this.settings.defaultAllowedIPs || !isAllowed(remoteIP, this.settings.defaultAllowedIPs)) {
|
|
|
|
|
console.log(`Connection rejected: IP ${remoteIP} not allowed for non-SNI connection`);
|
|
|
|
|
} else if (!isDefaultAllowed && !serverName) {
|
|
|
|
|
console.log(`Connection rejected: No SNI and IP ${remoteIP} not in default allowed list`);
|
|
|
|
|
socket.end();
|
|
|
|
|
return;
|
|
|
|
|
} else {
|
|
|
|
|
console.log(`Connection allowed: IP ${remoteIP} is in default allowed list`);
|
|
|
|
|
}
|
|
|
|
|
const targetHost = this.settings.toHost!;
|
|
|
|
|
|
|
|
|
|
// Determine target host.
|
|
|
|
|
const domainConfig = serverName ? findMatchingDomain(serverName) : undefined;
|
|
|
|
|
const targetHost = domainConfig?.targetIP || this.settings.toHost!;
|
|
|
|
|
|
|
|
|
|
// Create connection options.
|
|
|
|
|
const connectionOptions: plugins.net.NetConnectOpts = {
|
|
|
|
|
host: targetHost,
|
|
|
|
|
port: this.settings.toPort,
|
|
|
|
@ -243,22 +259,50 @@ export class PortProxy {
|
|
|
|
|
if (this.settings.preserveSourceIP) {
|
|
|
|
|
connectionOptions.localAddress = remoteIP.replace('::ffff:', '');
|
|
|
|
|
}
|
|
|
|
|
const to = plugins.net.connect(connectionOptions);
|
|
|
|
|
console.log(`Connection established: ${remoteIP} -> ${targetHost}:${this.settings.toPort}`);
|
|
|
|
|
|
|
|
|
|
// Establish outgoing connection.
|
|
|
|
|
to = plugins.net.connect(connectionOptions);
|
|
|
|
|
// Record start time for the outgoing connection.
|
|
|
|
|
this.outgoingConnectionTimes.set(to, Date.now());
|
|
|
|
|
console.log(`Connection established: ${remoteIP} -> ${targetHost}:${this.settings.toPort}${serverName ? ` (SNI: ${serverName})` : ''}`);
|
|
|
|
|
|
|
|
|
|
// Push back the initial chunk if provided.
|
|
|
|
|
if (initialChunk) {
|
|
|
|
|
socket.unshift(initialChunk);
|
|
|
|
|
}
|
|
|
|
|
socket.setTimeout(120000);
|
|
|
|
|
socket.pipe(to);
|
|
|
|
|
to.pipe(socket);
|
|
|
|
|
const errorHandler = () => {
|
|
|
|
|
cleanUpSockets(socket, to);
|
|
|
|
|
};
|
|
|
|
|
socket.on('error', errorHandler);
|
|
|
|
|
to.on('error', errorHandler);
|
|
|
|
|
socket.on('close', errorHandler);
|
|
|
|
|
to.on('close', errorHandler);
|
|
|
|
|
socket.on('timeout', errorHandler);
|
|
|
|
|
to.on('timeout', errorHandler);
|
|
|
|
|
socket.on('end', errorHandler);
|
|
|
|
|
to.on('end', errorHandler);
|
|
|
|
|
|
|
|
|
|
// Attach error and close handlers for both sockets.
|
|
|
|
|
socket.on('error', handleError('incoming'));
|
|
|
|
|
to.on('error', handleError('outgoing'));
|
|
|
|
|
socket.on('close', handleClose('incoming'));
|
|
|
|
|
to.on('close', handleClose('outgoing'));
|
|
|
|
|
socket.on('timeout', handleError('incoming'));
|
|
|
|
|
to.on('timeout', handleError('outgoing'));
|
|
|
|
|
socket.on('end', handleClose('incoming'));
|
|
|
|
|
to.on('end', handleClose('outgoing'));
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// For SNI-enabled connections, peek at the first chunk.
|
|
|
|
|
if (this.settings.sniEnabled) {
|
|
|
|
|
socket.once('data', (chunk: Buffer) => {
|
|
|
|
|
initialDataReceived = true;
|
|
|
|
|
// Try to extract the server name from the ClientHello.
|
|
|
|
|
const serverName = extractSNI(chunk) || '';
|
|
|
|
|
console.log(`Received connection from ${remoteIP} with SNI: ${serverName}`);
|
|
|
|
|
setupConnection(serverName, chunk);
|
|
|
|
|
});
|
|
|
|
|
} else {
|
|
|
|
|
// For non-SNI connections, simply check defaultAllowedIPs.
|
|
|
|
|
initialDataReceived = true;
|
|
|
|
|
if (!this.settings.defaultAllowedIPs || !isAllowed(remoteIP, this.settings.defaultAllowedIPs)) {
|
|
|
|
|
console.log(`Connection rejected: IP ${remoteIP} not allowed for non-SNI connection`);
|
|
|
|
|
socket.end();
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
setupConnection('');
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
.on('error', (err: Error) => {
|
|
|
|
@ -267,6 +311,26 @@ export class PortProxy {
|
|
|
|
|
.listen(this.settings.fromPort, () => {
|
|
|
|
|
console.log(`PortProxy -> OK: Now listening on port ${this.settings.fromPort}${this.settings.sniEnabled ? ' (SNI passthrough enabled)' : ''}`);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Log active connection count and longest running connections every 10 seconds.
|
|
|
|
|
this.connectionLogger = setInterval(() => {
|
|
|
|
|
const now = Date.now();
|
|
|
|
|
let maxIncoming = 0;
|
|
|
|
|
for (const startTime of this.incomingConnectionTimes.values()) {
|
|
|
|
|
const duration = now - startTime;
|
|
|
|
|
if (duration > maxIncoming) {
|
|
|
|
|
maxIncoming = duration;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
let maxOutgoing = 0;
|
|
|
|
|
for (const startTime of this.outgoingConnectionTimes.values()) {
|
|
|
|
|
const duration = now - startTime;
|
|
|
|
|
if (duration > maxOutgoing) {
|
|
|
|
|
maxOutgoing = duration;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
console.log(`(Interval Log) Active connections: ${this.activeConnections.size}. Longest running incoming: ${maxIncoming}ms, outgoing: ${maxOutgoing}ms`);
|
|
|
|
|
}, 10000);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async stop() {
|
|
|
|
@ -274,6 +338,10 @@ export class PortProxy {
|
|
|
|
|
this.netServer.close(() => {
|
|
|
|
|
done.resolve();
|
|
|
|
|
});
|
|
|
|
|
if (this.connectionLogger) {
|
|
|
|
|
clearInterval(this.connectionLogger);
|
|
|
|
|
this.connectionLogger = null;
|
|
|
|
|
}
|
|
|
|
|
await done.promise;
|
|
|
|
|
}
|
|
|
|
|
}
|