fix(portproxy): Fix handling of connections in PortProxy to improve stability and performance.
This commit is contained in:
parent
477b930a37
commit
e841bda003
@ -1,5 +1,12 @@
|
|||||||
# Changelog
|
# 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)
|
## 2025-02-21 - 3.7.2 - fix(PortProxy)
|
||||||
Improve SNICallback and connection handling in PortProxy
|
Improve SNICallback and connection handling in PortProxy
|
||||||
|
|
||||||
|
@ -3,6 +3,6 @@
|
|||||||
*/
|
*/
|
||||||
export const commitinfo = {
|
export const commitinfo = {
|
||||||
name: '@push.rocks/smartproxy',
|
name: '@push.rocks/smartproxy',
|
||||||
version: '3.7.2',
|
version: '3.7.3',
|
||||||
description: 'a proxy for handling high workloads of proxying'
|
description: 'a proxy for handling high workloads of proxying'
|
||||||
}
|
}
|
||||||
|
@ -1,30 +1,122 @@
|
|||||||
import * as plugins from './smartproxy.plugins.js';
|
import * as plugins from './smartproxy.plugins.js';
|
||||||
|
|
||||||
|
export interface IDomainConfig {
|
||||||
export interface DomainConfig {
|
|
||||||
domain: string; // glob pattern for domain
|
domain: string; // glob pattern for domain
|
||||||
allowedIPs: string[]; // glob patterns for IPs allowed to access this domain
|
allowedIPs: string[]; // glob patterns for IPs allowed to access this domain
|
||||||
targetIP?: string; // Optional target IP for 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
|
// Port configuration
|
||||||
fromPort: number;
|
fromPort: number;
|
||||||
toPort: 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
|
// Domain and security settings
|
||||||
domains: DomainConfig[];
|
domains: IDomainConfig[];
|
||||||
sniEnabled?: boolean;
|
sniEnabled?: boolean;
|
||||||
defaultAllowedIPs?: string[]; // Optional default IP patterns if no matching domain found
|
defaultAllowedIPs?: string[]; // Optional default IP patterns if no matching domain found
|
||||||
preserveSourceIP?: boolean; // Whether to preserve the client's source IP when proxying
|
preserveSourceIP?: boolean; // Whether to preserve the client's source IP when proxying
|
||||||
}
|
}
|
||||||
|
|
||||||
export class PortProxy {
|
/**
|
||||||
netServer: plugins.net.Server | plugins.tls.Server;
|
* Extract SNI (Server Name Indication) from a TLS ClientHello packet.
|
||||||
settings: ProxySettings;
|
* 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;
|
||||||
|
}
|
||||||
|
|
||||||
constructor(settings: ProxySettings) {
|
// 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;
|
||||||
|
settings: IProxySettings;
|
||||||
|
|
||||||
|
constructor(settings: IProxySettings) {
|
||||||
this.settings = {
|
this.settings = {
|
||||||
...settings,
|
...settings,
|
||||||
toHost: settings.toHost || 'localhost'
|
toHost: settings.toHost || 'localhost'
|
||||||
@ -42,6 +134,7 @@ export class PortProxy {
|
|||||||
from.destroy();
|
from.destroy();
|
||||||
to.destroy();
|
to.destroy();
|
||||||
};
|
};
|
||||||
|
|
||||||
const normalizeIP = (ip: string): string[] => {
|
const normalizeIP = (ip: string): string[] => {
|
||||||
// Handle IPv4-mapped IPv6 addresses
|
// Handle IPv4-mapped IPv6 addresses
|
||||||
if (ip.startsWith('::ffff:')) {
|
if (ip.startsWith('::ffff:')) {
|
||||||
@ -49,7 +142,7 @@ export class PortProxy {
|
|||||||
return [ip, ipv4];
|
return [ip, ipv4];
|
||||||
}
|
}
|
||||||
// Handle IPv4 addresses by adding IPv4-mapped IPv6 variant
|
// 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, `::ffff:${ip}`];
|
||||||
}
|
}
|
||||||
return [ip];
|
return [ip];
|
||||||
@ -64,117 +157,116 @@ export class PortProxy {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const findMatchingDomain = (serverName: string): DomainConfig | undefined => {
|
const findMatchingDomain = (serverName: string): IDomainConfig | undefined => {
|
||||||
return this.settings.domains.find(config => plugins.minimatch(serverName, config.domain));
|
return this.settings.domains.find(config => plugins.minimatch(serverName, config.domain));
|
||||||
};
|
};
|
||||||
|
|
||||||
const server = this.settings.sniEnabled
|
// Always create a plain net server for TLS passthrough.
|
||||||
? plugins.tls.createServer({
|
this.netServer = plugins.net.createServer((socket: plugins.net.Socket) => {
|
||||||
SNICallback: (serverName: string, cb: (err: Error | null, ctx?: plugins.tls.SecureContext) => void) => {
|
const remoteIP = socket.remoteAddress || '';
|
||||||
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) => {
|
// If SNI is enabled, we peek at the first chunk to extract the SNI.
|
||||||
const remoteIP = from.remoteAddress || '';
|
if (this.settings.sniEnabled) {
|
||||||
let serverName = '';
|
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}`);
|
||||||
|
|
||||||
// First check if this IP is in the default allowed list
|
// Check if the IP is allowed by default.
|
||||||
const isDefaultAllowed = this.settings.defaultAllowedIPs && isAllowed(remoteIP, this.settings.defaultAllowedIPs);
|
const isDefaultAllowed = this.settings.defaultAllowedIPs && isAllowed(remoteIP, this.settings.defaultAllowedIPs);
|
||||||
|
if (!isDefaultAllowed && serverName) {
|
||||||
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);
|
const domainConfig = findMatchingDomain(serverName);
|
||||||
if (!domainConfig) {
|
if (!domainConfig) {
|
||||||
console.log(`Connection rejected: No matching domain config for ${serverName} from IP ${remoteIP}`);
|
console.log(`Connection rejected: No matching domain config for ${serverName} from IP ${remoteIP}`);
|
||||||
from.end();
|
socket.end();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!isAllowed(remoteIP, domainConfig.allowedIPs)) {
|
if (!isAllowed(remoteIP, domainConfig.allowedIPs)) {
|
||||||
console.log(`Connection rejected: IP ${remoteIP} not allowed for domain ${serverName}`);
|
console.log(`Connection rejected: IP ${remoteIP} not allowed for domain ${serverName}`);
|
||||||
from.end();
|
socket.end();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
} else {
|
} else if (!isDefaultAllowed && !serverName) {
|
||||||
// Non-SNI connection and not in default list
|
console.log(`Connection rejected: No SNI and IP ${remoteIP} not in default allowed list`);
|
||||||
console.log(`Connection rejected: IP ${remoteIP} not allowed for non-SNI connection`);
|
socket.end();
|
||||||
from.end();
|
|
||||||
return;
|
return;
|
||||||
|
} else {
|
||||||
|
console.log(`Connection allowed: IP ${remoteIP} is in default allowed list`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Determine target host - use domain-specific targetIP if available
|
// Determine target host.
|
||||||
const domainConfig = serverName ? findMatchingDomain(serverName) : undefined;
|
const domainConfig = serverName ? findMatchingDomain(serverName) : undefined;
|
||||||
const targetHost = domainConfig?.targetIP || this.settings.toHost!;
|
const targetHost = domainConfig?.targetIP || this.settings.toHost!;
|
||||||
|
|
||||||
// Create connection, optionally preserving the client's source IP
|
// Create connection options.
|
||||||
const connectionOptions: plugins.net.NetConnectOpts = {
|
const connectionOptions: plugins.net.NetConnectOpts = {
|
||||||
host: targetHost,
|
host: targetHost,
|
||||||
port: this.settings.toPort,
|
port: this.settings.toPort,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Only set localAddress if preserveSourceIP is enabled
|
|
||||||
if (this.settings.preserveSourceIP) {
|
if (this.settings.preserveSourceIP) {
|
||||||
connectionOptions.localAddress = remoteIP.replace('::ffff:', ''); // Remove IPv6 mapping if present
|
connectionOptions.localAddress = remoteIP.replace('::ffff:', '');
|
||||||
}
|
}
|
||||||
|
|
||||||
// If this is a TLS connection, use net.connect to ensure raw passthrough
|
|
||||||
const to = plugins.net.connect(connectionOptions);
|
const to = plugins.net.connect(connectionOptions);
|
||||||
console.log(`Connection established: ${remoteIP} -> ${targetHost}:${this.settings.toPort}${serverName ? ` (SNI: ${serverName})` : ''}`);
|
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
|
// Unshift the data chunk back so that the TLS handshake can complete at the backend.
|
||||||
.on('connection', handleConnection)
|
socket.unshift(chunk);
|
||||||
.on('secureConnection', handleConnection)
|
socket.setTimeout(120000);
|
||||||
.on('tlsClientError', (err, tlsSocket) => {
|
socket.pipe(to);
|
||||||
console.log(`TLS Client Error: ${err.message}`);
|
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);
|
||||||
|
}
|
||||||
})
|
})
|
||||||
.on('error', (err) => {
|
.on('error', (err: Error) => {
|
||||||
console.log(`Server Error: ${err.message}`);
|
console.log(`Server Error: ${err.message}`);
|
||||||
})
|
})
|
||||||
.listen(this.settings.fromPort);
|
.listen(this.settings.fromPort, () => {
|
||||||
console.log(`PortProxy -> OK: Now listening on port ${this.settings.fromPort}${this.settings.sniEnabled ? ' (SNI enabled)' : ''}`);
|
console.log(`PortProxy -> OK: Now listening on port ${this.settings.fromPort}${this.settings.sniEnabled ? ' (SNI passthrough enabled)' : ''}`);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public async stop() {
|
public async stop() {
|
||||||
|
Loading…
x
Reference in New Issue
Block a user