fix(portproxy): Fix handling of connections in PortProxy to improve stability and performance.

This commit is contained in:
Philipp Kunz 2025-02-21 20:17:35 +00:00
parent 477b930a37
commit e841bda003
3 changed files with 221 additions and 122 deletions

View File

@ -1,5 +1,12 @@
# Changelog
## 2025-02-21 - 3.7.3 - fix(portproxy)
Fix handling of connections in PortProxy to improve stability and performance.
- Improved IP normalization and matching
- Better SNI extraction and handling for TLS
- Streamlined connection handling with robust error management
## 2025-02-21 - 3.7.2 - fix(PortProxy)
Improve SNICallback and connection handling in PortProxy

View File

@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@push.rocks/smartproxy',
version: '3.7.2',
version: '3.7.3',
description: 'a proxy for handling high workloads of proxying'
}

View File

@ -1,30 +1,122 @@
import * as plugins from './smartproxy.plugins.js';
export interface DomainConfig {
domain: string; // glob pattern for domain
allowedIPs: string[]; // glob patterns for IPs allowed to access this domain
targetIP?: string; // Optional target IP for this domain
export interface IDomainConfig {
domain: string; // glob pattern for domain
allowedIPs: string[]; // glob patterns for IPs allowed to access this domain
targetIP?: string; // Optional target IP for this domain
}
export interface ProxySettings extends plugins.tls.TlsOptions {
export interface IProxySettings extends plugins.tls.TlsOptions {
// Port configuration
fromPort: number;
toPort: number;
toHost?: string; // Target host to proxy to, defaults to 'localhost'
toHost?: string; // Target host to proxy to, defaults to 'localhost'
// Domain and security settings
domains: DomainConfig[];
domains: IDomainConfig[];
sniEnabled?: boolean;
defaultAllowedIPs?: string[]; // Optional default IP patterns if no matching domain found
preserveSourceIP?: boolean; // Whether to preserve the client's source IP when proxying
defaultAllowedIPs?: string[]; // Optional default IP patterns if no matching domain found
preserveSourceIP?: boolean; // Whether to preserve the client's source IP when proxying
}
/**
* Extract SNI (Server Name Indication) from a TLS ClientHello packet.
* Returns the server name if found, or undefined.
*/
function extractSNI(buffer: Buffer): string | undefined {
let offset = 0;
// We need at least 5 bytes for the record header.
if (buffer.length < 5) {
return undefined;
}
// TLS record header
const recordType = buffer.readUInt8(0);
if (recordType !== 22) { // 22 = handshake
return undefined;
}
// Read record length
const recordLength = buffer.readUInt16BE(3);
if (buffer.length < 5 + recordLength) {
// Not all data arrived yet; in production you might need to accumulate more data.
return undefined;
}
offset = 5;
// Handshake message type should be 1 for ClientHello.
const handshakeType = buffer.readUInt8(offset);
if (handshakeType !== 1) {
return undefined;
}
// Skip handshake header (1 byte type + 3 bytes length)
offset += 4;
// Skip client version (2 bytes) and random (32 bytes)
offset += 2 + 32;
// Session ID
const sessionIDLength = buffer.readUInt8(offset);
offset += 1 + sessionIDLength;
// Cipher suites
const cipherSuitesLength = buffer.readUInt16BE(offset);
offset += 2 + cipherSuitesLength;
// Compression methods
const compressionMethodsLength = buffer.readUInt8(offset);
offset += 1 + compressionMethodsLength;
// Extensions length
if (offset + 2 > buffer.length) {
return undefined;
}
const extensionsLength = buffer.readUInt16BE(offset);
offset += 2;
const extensionsEnd = offset + extensionsLength;
// Iterate over extensions
while (offset + 4 <= extensionsEnd) {
const extensionType = buffer.readUInt16BE(offset);
const extensionLength = buffer.readUInt16BE(offset + 2);
offset += 4;
// Check for SNI extension (type 0)
if (extensionType === 0x0000) {
// SNI extension: first 2 bytes are the SNI list length.
if (offset + 2 > buffer.length) {
return undefined;
}
const sniListLength = buffer.readUInt16BE(offset);
offset += 2;
const sniListEnd = offset + sniListLength;
// Loop through the list; typically there is one entry.
while (offset + 3 < sniListEnd) {
const nameType = buffer.readUInt8(offset);
offset++;
const nameLen = buffer.readUInt16BE(offset);
offset += 2;
if (nameType === 0) { // host_name
if (offset + nameLen > buffer.length) {
return undefined;
}
const serverName = buffer.toString('utf8', offset, offset + nameLen);
return serverName;
}
offset += nameLen;
}
break;
} else {
offset += extensionLength;
}
}
return undefined;
}
export class PortProxy {
netServer: plugins.net.Server | plugins.tls.Server;
settings: ProxySettings;
netServer: plugins.net.Server;
settings: IProxySettings;
constructor(settings: ProxySettings) {
constructor(settings: IProxySettings) {
this.settings = {
...settings,
toHost: settings.toHost || 'localhost'
@ -42,6 +134,7 @@ export class PortProxy {
from.destroy();
to.destroy();
};
const normalizeIP = (ip: string): string[] => {
// Handle IPv4-mapped IPv6 addresses
if (ip.startsWith('::ffff:')) {
@ -49,7 +142,7 @@ export class PortProxy {
return [ip, ipv4];
}
// Handle IPv4 addresses by adding IPv4-mapped IPv6 variant
if (ip.match(/^\d{1,3}(\.\d{1,3}){3}$/)) {
if (/^\d{1,3}(\.\d{1,3}){3}$/.test(ip)) {
return [ip, `::ffff:${ip}`];
}
return [ip];
@ -59,122 +152,121 @@ export class PortProxy {
// Expand patterns to include both IPv4 and IPv6 variants
const expandedPatterns = patterns.flatMap(normalizeIP);
// Check if any variant of the IP matches any expanded pattern
return normalizeIP(value).some(ip =>
return normalizeIP(value).some(ip =>
expandedPatterns.some(pattern => plugins.minimatch(ip, pattern))
);
};
const findMatchingDomain = (serverName: string): DomainConfig | undefined => {
const findMatchingDomain = (serverName: string): IDomainConfig | undefined => {
return this.settings.domains.find(config => plugins.minimatch(serverName, config.domain));
};
const server = this.settings.sniEnabled
? plugins.tls.createServer({
SNICallback: (serverName: string, cb: (err: Error | null, ctx?: plugins.tls.SecureContext) => void) => {
console.log(`SNI request for domain: ${serverName}`);
// Create a minimal context just to read SNI, we'll pass through the actual TLS
const ctx = plugins.tls.createSecureContext({
minVersion: 'TLSv1.2',
maxVersion: 'TLSv1.3'
});
cb(null, ctx);
}
})
: plugins.net.createServer();
const handleConnection = (from: plugins.net.Socket | plugins.tls.TLSSocket) => {
const remoteIP = from.remoteAddress || '';
let serverName = '';
// First check if this IP is in the default allowed list
const isDefaultAllowed = this.settings.defaultAllowedIPs && isAllowed(remoteIP, this.settings.defaultAllowedIPs);
if (this.settings.sniEnabled && from instanceof plugins.tls.TLSSocket) {
serverName = (from as any).servername || '';
console.log(`TLS Connection from ${remoteIP} for domain: ${serverName}`);
}
// If IP is in defaultAllowedIPs, allow the connection regardless of SNI
if (isDefaultAllowed) {
console.log(`Connection allowed: IP ${remoteIP} is in default allowed list`);
} else if (this.settings.sniEnabled && serverName) {
// For SNI connections that aren't in default list, check domain-specific rules
const domainConfig = findMatchingDomain(serverName);
if (!domainConfig) {
console.log(`Connection rejected: No matching domain config for ${serverName} from IP ${remoteIP}`);
from.end();
return;
}
if (!isAllowed(remoteIP, domainConfig.allowedIPs)) {
console.log(`Connection rejected: IP ${remoteIP} not allowed for domain ${serverName}`);
from.end();
return;
}
} else {
// Non-SNI connection and not in default list
console.log(`Connection rejected: IP ${remoteIP} not allowed for non-SNI connection`);
from.end();
return;
}
// Determine target host - use domain-specific targetIP if available
const domainConfig = serverName ? findMatchingDomain(serverName) : undefined;
const targetHost = domainConfig?.targetIP || this.settings.toHost!;
// Always create a plain net server for TLS passthrough.
this.netServer = plugins.net.createServer((socket: plugins.net.Socket) => {
const remoteIP = socket.remoteAddress || '';
// Create connection, optionally preserving the client's source IP
const connectionOptions: plugins.net.NetConnectOpts = {
host: targetHost,
port: this.settings.toPort,
};
// 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}`);
// Only set localAddress if preserveSourceIP is enabled
if (this.settings.preserveSourceIP) {
connectionOptions.localAddress = remoteIP.replace('::ffff:', ''); // Remove IPv6 mapping if present
// 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`);
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:', '');
}
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`);
socket.end();
return;
}
const targetHost = this.settings.toHost!;
const connectionOptions: plugins.net.NetConnectOpts = {
host: targetHost,
port: this.settings.toPort,
};
if (this.settings.preserveSourceIP) {
connectionOptions.localAddress = remoteIP.replace('::ffff:', '');
}
const to = plugins.net.connect(connectionOptions);
console.log(`Connection established: ${remoteIP} -> ${targetHost}:${this.settings.toPort}`);
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);
}
// If this is a TLS connection, use net.connect to ensure raw passthrough
const to = plugins.net.connect(connectionOptions);
console.log(`Connection established: ${remoteIP} -> ${targetHost}:${this.settings.toPort}${serverName ? ` (SNI: ${serverName})` : ''}`);
from.setTimeout(120000);
from.pipe(to);
to.pipe(from);
from.on('error', () => {
cleanUpSockets(from, to);
});
to.on('error', () => {
cleanUpSockets(from, to);
});
from.on('close', () => {
cleanUpSockets(from, to);
});
to.on('close', () => {
cleanUpSockets(from, to);
});
from.on('timeout', () => {
cleanUpSockets(from, to);
});
to.on('timeout', () => {
cleanUpSockets(from, to);
});
from.on('end', () => {
cleanUpSockets(from, to);
});
to.on('end', () => {
cleanUpSockets(from, to);
});
};
this.netServer = server
.on('connection', handleConnection)
.on('secureConnection', handleConnection)
.on('tlsClientError', (err, tlsSocket) => {
console.log(`TLS Client Error: ${err.message}`);
})
.on('error', (err) => {
console.log(`Server Error: ${err.message}`);
})
.listen(this.settings.fromPort);
console.log(`PortProxy -> OK: Now listening on port ${this.settings.fromPort}${this.settings.sniEnabled ? ' (SNI enabled)' : ''}`);
})
.on('error', (err: Error) => {
console.log(`Server Error: ${err.message}`);
})
.listen(this.settings.fromPort, () => {
console.log(`PortProxy -> OK: Now listening on port ${this.settings.fromPort}${this.settings.sniEnabled ? ' (SNI passthrough enabled)' : ''}`);
});
}
public async stop() {
@ -184,4 +276,4 @@ export class PortProxy {
});
await done.promise;
}
}
}