|
|
|
@ -10,18 +10,9 @@ export interface IDomainConfig {
|
|
|
|
|
portRanges?: Array<{ from: number; to: number }>; // Optional port ranges
|
|
|
|
|
// Allow domain-specific timeout override
|
|
|
|
|
connectionTimeout?: number; // Connection timeout override (ms)
|
|
|
|
|
|
|
|
|
|
// New properties for NetworkProxy integration
|
|
|
|
|
useNetworkProxy?: boolean; // When true, forwards TLS connections to NetworkProxy
|
|
|
|
|
networkProxyIndex?: number; // Optional index to specify which NetworkProxy to use (defaults to 0)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Port proxy settings including global allowed port ranges
|
|
|
|
|
*
|
|
|
|
|
* NOTE: In version 3.31.0+, timeout settings have been simplified and hardcoded with sensible defaults
|
|
|
|
|
* to ensure TLS certificate safety in all deployment scenarios, especially chained proxies.
|
|
|
|
|
*/
|
|
|
|
|
/** Port proxy settings including global allowed port ranges */
|
|
|
|
|
export interface IPortProxySettings extends plugins.tls.TlsOptions {
|
|
|
|
|
fromPort: number;
|
|
|
|
|
toPort: number;
|
|
|
|
@ -32,10 +23,14 @@ export interface IPortProxySettings extends plugins.tls.TlsOptions {
|
|
|
|
|
defaultBlockedIPs?: string[];
|
|
|
|
|
preserveSourceIP?: boolean;
|
|
|
|
|
|
|
|
|
|
// Simplified timeout settings
|
|
|
|
|
gracefulShutdownTimeout?: number; // (ms) maximum time to wait for connections to close during shutdown
|
|
|
|
|
// Timeout settings
|
|
|
|
|
initialDataTimeout?: number; // Timeout for initial data/SNI (ms), default: 60000 (60s)
|
|
|
|
|
socketTimeout?: number; // Socket inactivity timeout (ms), default: 3600000 (1h)
|
|
|
|
|
inactivityCheckInterval?: number; // How often to check for inactive connections (ms), default: 60000 (60s)
|
|
|
|
|
maxConnectionLifetime?: number; // Default max connection lifetime (ms), default: 86400000 (24h)
|
|
|
|
|
inactivityTimeout?: number; // Inactivity timeout (ms), default: 14400000 (4h)
|
|
|
|
|
|
|
|
|
|
// Ranged port settings
|
|
|
|
|
gracefulShutdownTimeout?: number; // (ms) maximum time to wait for connections to close during shutdown
|
|
|
|
|
globalPortRanges: Array<{ from: number; to: number }>; // Global allowed port ranges
|
|
|
|
|
forwardAllGlobalRanges?: boolean; // When true, forwards all connections on global port ranges to the global targetIP
|
|
|
|
|
|
|
|
|
@ -45,7 +40,9 @@ export interface IPortProxySettings extends plugins.tls.TlsOptions {
|
|
|
|
|
keepAliveInitialDelay?: number; // Initial delay before sending keepalive probes (ms)
|
|
|
|
|
maxPendingDataSize?: number; // Maximum bytes to buffer during connection setup
|
|
|
|
|
|
|
|
|
|
// Logging settings
|
|
|
|
|
// Enhanced features
|
|
|
|
|
disableInactivityCheck?: boolean; // Disable inactivity checking entirely
|
|
|
|
|
enableKeepAliveProbes?: boolean; // Enable TCP keep-alive probes
|
|
|
|
|
enableDetailedLogging?: boolean; // Enable detailed connection logging
|
|
|
|
|
enableTlsDebugLogging?: boolean; // Enable TLS handshake debug logging
|
|
|
|
|
enableRandomizedTimeouts?: boolean; // Randomize timeouts slightly to prevent thundering herd
|
|
|
|
@ -54,8 +51,14 @@ export interface IPortProxySettings extends plugins.tls.TlsOptions {
|
|
|
|
|
maxConnectionsPerIP?: number; // Maximum simultaneous connections from a single IP
|
|
|
|
|
connectionRateLimitPerMinute?: number; // Max new connections per minute from a single IP
|
|
|
|
|
|
|
|
|
|
// NetworkProxy integration
|
|
|
|
|
networkProxies?: NetworkProxy[]; // Array of NetworkProxy instances to use for TLS termination
|
|
|
|
|
// Enhanced keep-alive settings
|
|
|
|
|
keepAliveTreatment?: 'standard' | 'extended' | 'immortal'; // How to treat keep-alive connections
|
|
|
|
|
keepAliveInactivityMultiplier?: number; // Multiplier for inactivity timeout for keep-alive connections
|
|
|
|
|
extendedKeepAliveLifetime?: number; // Extended lifetime for keep-alive connections (ms)
|
|
|
|
|
|
|
|
|
|
// New property for NetworkProxy integration
|
|
|
|
|
useNetworkProxy?: number[]; // Array of ports to forward to NetworkProxy
|
|
|
|
|
networkProxyPort?: number; // Port where NetworkProxy is listening (default: 8443)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
@ -91,13 +94,15 @@ interface IConnectionRecord {
|
|
|
|
|
incomingTerminationReason?: string | null; // Reason for incoming termination
|
|
|
|
|
outgoingTerminationReason?: string | null; // Reason for outgoing termination
|
|
|
|
|
|
|
|
|
|
// New field for NetworkProxy tracking
|
|
|
|
|
// NetworkProxy tracking
|
|
|
|
|
usingNetworkProxy?: boolean; // Whether this connection is using a NetworkProxy
|
|
|
|
|
networkProxyIndex?: number; // Which NetworkProxy instance is being used
|
|
|
|
|
|
|
|
|
|
// Sleep detection fields
|
|
|
|
|
possibleSystemSleep?: boolean; // Flag to indicate a possible system sleep was detected
|
|
|
|
|
lastSleepDetection?: number; // Timestamp of the last sleep detection
|
|
|
|
|
// Renegotiation handler
|
|
|
|
|
renegotiationHandler?: (chunk: Buffer) => void; // Handler for renegotiation detection
|
|
|
|
|
|
|
|
|
|
// Browser connection tracking
|
|
|
|
|
isBrowserConnection?: boolean; // Whether this connection appears to be from a browser
|
|
|
|
|
domainSwitches?: number; // Number of times the domain has been switched on this connection
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
@ -264,6 +269,29 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Checks if a TLS record is a proper ClientHello message (more accurate than just checking record type)
|
|
|
|
|
* @param buffer - Buffer containing the TLS record
|
|
|
|
|
* @returns true if the buffer contains a proper ClientHello message
|
|
|
|
|
*/
|
|
|
|
|
function isClientHello(buffer: Buffer): boolean {
|
|
|
|
|
try {
|
|
|
|
|
if (buffer.length < 9) return false; // Too small for a proper ClientHello
|
|
|
|
|
|
|
|
|
|
// Check record type (has to be handshake - 22)
|
|
|
|
|
if (buffer.readUInt8(0) !== 22) return false;
|
|
|
|
|
|
|
|
|
|
// After the TLS record header (5 bytes), check the handshake type (1 for ClientHello)
|
|
|
|
|
if (buffer.readUInt8(5) !== 1) return false;
|
|
|
|
|
|
|
|
|
|
// Basic checks passed, this appears to be a ClientHello
|
|
|
|
|
return true;
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.log(`Error checking for ClientHello: ${err}`);
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Helper: Check if a port falls within any of the given port ranges
|
|
|
|
|
const isPortInRanges = (port: number, ranges: Array<{ from: number; to: number }>): boolean => {
|
|
|
|
|
return ranges.some((range) => port >= range.from && port <= range.to);
|
|
|
|
@ -326,22 +354,7 @@ const randomizeTimeout = (baseTimeout: number, variationPercent: number = 5): nu
|
|
|
|
|
|
|
|
|
|
export class PortProxy {
|
|
|
|
|
private netServers: plugins.net.Server[] = [];
|
|
|
|
|
|
|
|
|
|
// Define the internal settings interface to include all fields, including those removed from the public interface
|
|
|
|
|
settings: IPortProxySettings & {
|
|
|
|
|
// Internal fields removed from public interface in 3.31.0+
|
|
|
|
|
initialDataTimeout: number;
|
|
|
|
|
socketTimeout: number;
|
|
|
|
|
inactivityCheckInterval: number;
|
|
|
|
|
maxConnectionLifetime: number;
|
|
|
|
|
inactivityTimeout: number;
|
|
|
|
|
disableInactivityCheck: boolean;
|
|
|
|
|
enableKeepAliveProbes: boolean;
|
|
|
|
|
keepAliveTreatment: 'standard' | 'extended' | 'immortal';
|
|
|
|
|
keepAliveInactivityMultiplier: number;
|
|
|
|
|
extendedKeepAliveLifetime: number;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
settings: IPortProxySettings;
|
|
|
|
|
private connectionRecords: Map<string, IConnectionRecord> = new Map();
|
|
|
|
|
private connectionLogger: NodeJS.Timeout | null = null;
|
|
|
|
|
private isShuttingDown: boolean = false;
|
|
|
|
@ -362,21 +375,21 @@ export class PortProxy {
|
|
|
|
|
private connectionsByIP: Map<string, Set<string>> = new Map();
|
|
|
|
|
private connectionRateByIP: Map<string, number[]> = new Map();
|
|
|
|
|
|
|
|
|
|
// New property to store NetworkProxy instances
|
|
|
|
|
private networkProxies: NetworkProxy[] = [];
|
|
|
|
|
// NetworkProxy instance for TLS termination
|
|
|
|
|
private networkProxy: NetworkProxy | null = null;
|
|
|
|
|
|
|
|
|
|
constructor(settingsArg: IPortProxySettings) {
|
|
|
|
|
// Set hardcoded sensible defaults for all settings
|
|
|
|
|
// Set reasonable defaults for all settings
|
|
|
|
|
this.settings = {
|
|
|
|
|
...settingsArg,
|
|
|
|
|
targetIP: settingsArg.targetIP || 'localhost',
|
|
|
|
|
|
|
|
|
|
// Hardcoded timeout settings optimized for TLS safety in all deployment scenarios
|
|
|
|
|
initialDataTimeout: 60000, // 60 seconds for initial handshake
|
|
|
|
|
socketTimeout: 1800000, // 30 minutes - short enough for regular certificate refresh
|
|
|
|
|
inactivityCheckInterval: 60000, // 60 seconds interval for regular cleanup
|
|
|
|
|
maxConnectionLifetime: 3600000, // 1 hour maximum lifetime for all connections
|
|
|
|
|
inactivityTimeout: 1800000, // 30 minutes inactivity timeout
|
|
|
|
|
// Timeout settings with reasonable defaults
|
|
|
|
|
initialDataTimeout: settingsArg.initialDataTimeout || 60000, // 60 seconds for initial handshake
|
|
|
|
|
socketTimeout: ensureSafeTimeout(settingsArg.socketTimeout || 3600000), // 1 hour socket timeout
|
|
|
|
|
inactivityCheckInterval: settingsArg.inactivityCheckInterval || 60000, // 60 seconds interval
|
|
|
|
|
maxConnectionLifetime: ensureSafeTimeout(settingsArg.maxConnectionLifetime || 86400000), // 24 hours default
|
|
|
|
|
inactivityTimeout: ensureSafeTimeout(settingsArg.inactivityTimeout || 14400000), // 4 hours inactivity timeout
|
|
|
|
|
|
|
|
|
|
gracefulShutdownTimeout: settingsArg.gracefulShutdownTimeout || 30000, // 30 seconds
|
|
|
|
|
|
|
|
|
@ -384,27 +397,48 @@ export class PortProxy {
|
|
|
|
|
noDelay: settingsArg.noDelay !== undefined ? settingsArg.noDelay : true,
|
|
|
|
|
keepAlive: settingsArg.keepAlive !== undefined ? settingsArg.keepAlive : true,
|
|
|
|
|
keepAliveInitialDelay: settingsArg.keepAliveInitialDelay || 10000, // 10 seconds
|
|
|
|
|
maxPendingDataSize: settingsArg.maxPendingDataSize || 10 * 1024 * 1024, // 10MB to handle large TLS handshakes
|
|
|
|
|
maxPendingDataSize: settingsArg.maxPendingDataSize || 10 * 1024 * 1024, // 10MB
|
|
|
|
|
|
|
|
|
|
// Feature flags - simplified with sensible defaults
|
|
|
|
|
disableInactivityCheck: false, // Always enable inactivity checks for TLS safety
|
|
|
|
|
enableKeepAliveProbes: true, // Always enable keep-alive probes for connection health
|
|
|
|
|
// Feature flags
|
|
|
|
|
disableInactivityCheck: settingsArg.disableInactivityCheck || false,
|
|
|
|
|
enableKeepAliveProbes: settingsArg.enableKeepAliveProbes !== undefined
|
|
|
|
|
? settingsArg.enableKeepAliveProbes : true,
|
|
|
|
|
enableDetailedLogging: settingsArg.enableDetailedLogging || false,
|
|
|
|
|
enableTlsDebugLogging: settingsArg.enableTlsDebugLogging || false,
|
|
|
|
|
enableRandomizedTimeouts: settingsArg.enableRandomizedTimeouts || false,
|
|
|
|
|
|
|
|
|
|
// Rate limiting defaults
|
|
|
|
|
maxConnectionsPerIP: settingsArg.maxConnectionsPerIP || 100, // 100 connections per IP
|
|
|
|
|
connectionRateLimitPerMinute: settingsArg.connectionRateLimitPerMinute || 300, // 300 per minute
|
|
|
|
|
maxConnectionsPerIP: settingsArg.maxConnectionsPerIP || 100,
|
|
|
|
|
connectionRateLimitPerMinute: settingsArg.connectionRateLimitPerMinute || 300,
|
|
|
|
|
|
|
|
|
|
// Keep-alive settings with sensible defaults that ensure certificate safety
|
|
|
|
|
keepAliveTreatment: 'standard', // Always use standard treatment for certificate safety
|
|
|
|
|
keepAliveInactivityMultiplier: 2, // 2x normal inactivity timeout for minimal extension
|
|
|
|
|
extendedKeepAliveLifetime: 3 * 60 * 60 * 1000, // 3 hours maximum (previously was 7 days!)
|
|
|
|
|
// Enhanced keep-alive settings
|
|
|
|
|
keepAliveTreatment: settingsArg.keepAliveTreatment || 'extended',
|
|
|
|
|
keepAliveInactivityMultiplier: settingsArg.keepAliveInactivityMultiplier || 6,
|
|
|
|
|
extendedKeepAliveLifetime: settingsArg.extendedKeepAliveLifetime || 7 * 24 * 60 * 60 * 1000, // 7 days
|
|
|
|
|
|
|
|
|
|
// NetworkProxy settings
|
|
|
|
|
networkProxyPort: settingsArg.networkProxyPort || 8443, // Default NetworkProxy port
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Store NetworkProxy instances if provided
|
|
|
|
|
this.networkProxies = settingsArg.networkProxies || [];
|
|
|
|
|
// Initialize NetworkProxy if enabled
|
|
|
|
|
if (this.settings.useNetworkProxy && this.settings.useNetworkProxy.length > 0) {
|
|
|
|
|
this.initializeNetworkProxy();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Initialize NetworkProxy instance
|
|
|
|
|
*/
|
|
|
|
|
private initializeNetworkProxy(): void {
|
|
|
|
|
if (!this.networkProxy) {
|
|
|
|
|
this.networkProxy = new NetworkProxy({
|
|
|
|
|
port: this.settings.networkProxyPort!,
|
|
|
|
|
portProxyIntegration: true,
|
|
|
|
|
logLevel: this.settings.enableDetailedLogging ? 'debug' : 'info'
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
console.log(`Initialized NetworkProxy on port ${this.settings.networkProxyPort}`);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
@ -412,45 +446,36 @@ export class PortProxy {
|
|
|
|
|
* @param connectionId - Unique connection identifier
|
|
|
|
|
* @param socket - The incoming client socket
|
|
|
|
|
* @param record - The connection record
|
|
|
|
|
* @param domainConfig - The domain configuration
|
|
|
|
|
* @param initialData - Initial data chunk (TLS ClientHello)
|
|
|
|
|
* @param serverName - SNI hostname (if available)
|
|
|
|
|
*/
|
|
|
|
|
private forwardToNetworkProxy(
|
|
|
|
|
connectionId: string,
|
|
|
|
|
socket: plugins.net.Socket,
|
|
|
|
|
record: IConnectionRecord,
|
|
|
|
|
domainConfig: IDomainConfig,
|
|
|
|
|
initialData: Buffer,
|
|
|
|
|
serverName?: string
|
|
|
|
|
initialData: Buffer
|
|
|
|
|
): void {
|
|
|
|
|
// Determine which NetworkProxy to use
|
|
|
|
|
const proxyIndex =
|
|
|
|
|
domainConfig.networkProxyIndex !== undefined ? domainConfig.networkProxyIndex : 0;
|
|
|
|
|
|
|
|
|
|
// Validate the NetworkProxy index
|
|
|
|
|
if (proxyIndex < 0 || proxyIndex >= this.networkProxies.length) {
|
|
|
|
|
// Ensure NetworkProxy is initialized
|
|
|
|
|
if (!this.networkProxy) {
|
|
|
|
|
console.log(
|
|
|
|
|
`[${connectionId}] Invalid NetworkProxy index: ${proxyIndex}. Using fallback direct connection.`
|
|
|
|
|
`[${connectionId}] NetworkProxy not initialized. Using fallback direct connection.`
|
|
|
|
|
);
|
|
|
|
|
// Fall back to direct connection
|
|
|
|
|
return this.setupDirectConnection(
|
|
|
|
|
connectionId,
|
|
|
|
|
socket,
|
|
|
|
|
record,
|
|
|
|
|
domainConfig,
|
|
|
|
|
serverName,
|
|
|
|
|
undefined,
|
|
|
|
|
undefined,
|
|
|
|
|
initialData
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const networkProxy = this.networkProxies[proxyIndex];
|
|
|
|
|
const proxyPort = networkProxy.getListeningPort();
|
|
|
|
|
const proxyPort = this.networkProxy.getListeningPort();
|
|
|
|
|
const proxyHost = 'localhost'; // Assuming NetworkProxy runs locally
|
|
|
|
|
|
|
|
|
|
if (this.settings.enableDetailedLogging) {
|
|
|
|
|
console.log(
|
|
|
|
|
`[${connectionId}] Forwarding TLS connection to NetworkProxy[${proxyIndex}] at ${proxyHost}:${proxyPort}`
|
|
|
|
|
`[${connectionId}] Forwarding TLS connection to NetworkProxy at ${proxyHost}:${proxyPort}`
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
@ -464,7 +489,6 @@ export class PortProxy {
|
|
|
|
|
record.outgoing = proxySocket;
|
|
|
|
|
record.outgoingStartTime = Date.now();
|
|
|
|
|
record.usingNetworkProxy = true;
|
|
|
|
|
record.networkProxyIndex = proxyIndex;
|
|
|
|
|
|
|
|
|
|
// Set up error handlers
|
|
|
|
|
proxySocket.on('error', (err) => {
|
|
|
|
@ -503,31 +527,12 @@ export class PortProxy {
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Update activity on data transfer
|
|
|
|
|
socket.on('data', (chunk: Buffer) => {
|
|
|
|
|
this.updateActivity(record);
|
|
|
|
|
|
|
|
|
|
// Check for potential TLS renegotiation or reconnection packets
|
|
|
|
|
if (chunk.length > 0 && chunk[0] === 22) {
|
|
|
|
|
// ContentType.handshake
|
|
|
|
|
if (this.settings.enableDetailedLogging) {
|
|
|
|
|
console.log(
|
|
|
|
|
`[${connectionId}] Detected potential TLS handshake data while connected to NetworkProxy`
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// NOTE: We don't need to explicitly forward the renegotiation packets
|
|
|
|
|
// because socket.pipe(proxySocket) is already handling that.
|
|
|
|
|
// The pipe ensures all data (including renegotiation) flows through properly.
|
|
|
|
|
// Just update the activity timestamp to prevent timeouts
|
|
|
|
|
record.lastActivity = Date.now();
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
socket.on('data', () => this.updateActivity(record));
|
|
|
|
|
proxySocket.on('data', () => this.updateActivity(record));
|
|
|
|
|
|
|
|
|
|
if (this.settings.enableDetailedLogging) {
|
|
|
|
|
console.log(
|
|
|
|
|
`[${connectionId}] TLS connection successfully forwarded to NetworkProxy[${proxyIndex}]`
|
|
|
|
|
`[${connectionId}] TLS connection successfully forwarded to NetworkProxy`
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
@ -848,112 +853,45 @@ export class PortProxy {
|
|
|
|
|
record.pendingData = [];
|
|
|
|
|
record.pendingDataSize = 0;
|
|
|
|
|
|
|
|
|
|
// Add the renegotiation listener for SNI validation
|
|
|
|
|
// Add the renegotiation handler for SNI validation with strict domain enforcement
|
|
|
|
|
if (serverName) {
|
|
|
|
|
// This listener will check for TLS renegotiation attempts
|
|
|
|
|
// Note: We don't need to explicitly forward the renegotiation packets
|
|
|
|
|
// since socket.pipe(targetSocket) is already set up earlier and handles that
|
|
|
|
|
socket.on('data', (renegChunk: Buffer) => {
|
|
|
|
|
if (renegChunk.length > 0 && renegChunk.readUInt8(0) === 22) {
|
|
|
|
|
// Define a handler for checking renegotiation with improved detection
|
|
|
|
|
const renegotiationHandler = (renegChunk: Buffer) => {
|
|
|
|
|
// Only process if this looks like a TLS ClientHello
|
|
|
|
|
if (isClientHello(renegChunk)) {
|
|
|
|
|
try {
|
|
|
|
|
// Try to extract SNI from potential renegotiation
|
|
|
|
|
// Extract SNI from ClientHello
|
|
|
|
|
const newSNI = extractSNI(renegChunk, this.settings.enableTlsDebugLogging);
|
|
|
|
|
|
|
|
|
|
// IMPORTANT: If we can't extract an SNI from renegotiation, we MUST allow it through
|
|
|
|
|
// Otherwise valid renegotiations that don't explicitly repeat the SNI will break
|
|
|
|
|
if (newSNI === undefined) {
|
|
|
|
|
if (this.settings.enableDetailedLogging) {
|
|
|
|
|
// Skip if no SNI was found
|
|
|
|
|
if (!newSNI) return;
|
|
|
|
|
|
|
|
|
|
// Handle SNI change during renegotiation - always terminate for domain switches
|
|
|
|
|
if (newSNI !== record.lockedDomain) {
|
|
|
|
|
// Log and terminate the connection for any SNI change
|
|
|
|
|
console.log(
|
|
|
|
|
`[${connectionId}] Rehandshake detected without SNI, allowing it through.`
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
// Let it pass through - this is critical for Chrome's TLS handling
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Check if the SNI has changed
|
|
|
|
|
if (newSNI && newSNI !== record.lockedDomain) {
|
|
|
|
|
// Always check whether the new SNI would be allowed by the EXISTING domain config first
|
|
|
|
|
// This ensures we're using the same ruleset that allowed the initial connection
|
|
|
|
|
let allowed = false;
|
|
|
|
|
|
|
|
|
|
// First check if the exact original domain config would allow this new SNI
|
|
|
|
|
if (record.domainConfig) {
|
|
|
|
|
// Check if the new SNI matches any domain pattern in the original domain config
|
|
|
|
|
allowed = record.domainConfig.domains.some(d => plugins.minimatch(newSNI, d));
|
|
|
|
|
|
|
|
|
|
if (allowed && this.settings.enableDetailedLogging) {
|
|
|
|
|
console.log(
|
|
|
|
|
`[${connectionId}] Rehandshake with new SNI: ${newSNI} matched existing domain config ` +
|
|
|
|
|
`patterns ${record.domainConfig.domains.join(', ')}. Allowing connection reuse.`
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// If not allowed by the existing domain config, try to find another domain config
|
|
|
|
|
if (!allowed) {
|
|
|
|
|
const newDomainConfig = this.settings.domainConfigs.find((config) =>
|
|
|
|
|
config.domains.some((d) => plugins.minimatch(newSNI, d))
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
// If we found a matching domain config, check IP rules
|
|
|
|
|
if (newDomainConfig) {
|
|
|
|
|
const effectiveAllowedIPs = [
|
|
|
|
|
...newDomainConfig.allowedIPs,
|
|
|
|
|
...(this.settings.defaultAllowedIPs || []),
|
|
|
|
|
];
|
|
|
|
|
const effectiveBlockedIPs = [
|
|
|
|
|
...(newDomainConfig.blockedIPs || []),
|
|
|
|
|
...(this.settings.defaultBlockedIPs || []),
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
// Check if the IP is allowed for the new domain
|
|
|
|
|
allowed = isGlobIPAllowed(record.remoteIP, effectiveAllowedIPs, effectiveBlockedIPs);
|
|
|
|
|
|
|
|
|
|
if (allowed && this.settings.enableDetailedLogging) {
|
|
|
|
|
console.log(
|
|
|
|
|
`[${connectionId}] Rehandshake with new SNI: ${newSNI} (previously ${record.lockedDomain}). ` +
|
|
|
|
|
`New domain is allowed by different domain config rules, permitting connection reuse.`
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Update the domain config reference to the new one
|
|
|
|
|
if (allowed) {
|
|
|
|
|
record.domainConfig = newDomainConfig;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (allowed) {
|
|
|
|
|
// Update the locked domain to the new domain
|
|
|
|
|
record.lockedDomain = newSNI;
|
|
|
|
|
if (this.settings.enableDetailedLogging) {
|
|
|
|
|
console.log(
|
|
|
|
|
`[${connectionId}] Updated locked domain for connection from ${record.remoteIP} to: ${newSNI}`
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
// If we get here, either no matching domain config was found or the IP is not allowed
|
|
|
|
|
console.log(
|
|
|
|
|
`[${connectionId}] Rehandshake detected with different SNI: ${newSNI} vs locked ${record.lockedDomain}. ` +
|
|
|
|
|
`New domain not allowed by any rules. Terminating connection.`
|
|
|
|
|
`[${connectionId}] Renegotiation with different SNI: ${record.lockedDomain} -> ${newSNI}. ` +
|
|
|
|
|
`Terminating connection - SNI domain switching is not allowed.`
|
|
|
|
|
);
|
|
|
|
|
this.initiateCleanupOnce(record, 'sni_mismatch');
|
|
|
|
|
}
|
|
|
|
|
} else if (newSNI && this.settings.enableDetailedLogging) {
|
|
|
|
|
} else if (this.settings.enableDetailedLogging) {
|
|
|
|
|
console.log(
|
|
|
|
|
`[${connectionId}] Rehandshake detected with same SNI: ${newSNI}. Allowing.`
|
|
|
|
|
`[${connectionId}] Renegotiation detected with same SNI: ${newSNI}. Allowing.`
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
} catch (err) {
|
|
|
|
|
// Always allow the renegotiation to continue if we encounter an error
|
|
|
|
|
// This ensures Chrome can complete its TLS renegotiation
|
|
|
|
|
console.log(
|
|
|
|
|
`[${connectionId}] Error processing potential renegotiation: ${err}. Allowing connection to continue.`
|
|
|
|
|
`[${connectionId}] Error processing ClientHello: ${err}. Allowing connection to continue.`
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Store the handler in the connection record so we can remove it during cleanup
|
|
|
|
|
record.renegotiationHandler = renegotiationHandler;
|
|
|
|
|
|
|
|
|
|
// Add the listener
|
|
|
|
|
socket.on('data', renegotiationHandler);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Set connection timeout with simpler logic
|
|
|
|
@ -970,38 +908,6 @@ export class PortProxy {
|
|
|
|
|
}
|
|
|
|
|
// No cleanup timer for immortal connections
|
|
|
|
|
}
|
|
|
|
|
// For TLS keep-alive connections, use a more generous timeout now that
|
|
|
|
|
// we've fixed the renegotiation handling issue that was causing certificate problems
|
|
|
|
|
else if (record.hasKeepAlive && record.isTLS) {
|
|
|
|
|
// Use a longer timeout for TLS connections now that renegotiation handling is fixed
|
|
|
|
|
// This reduces unnecessary reconnections while still ensuring certificate freshness
|
|
|
|
|
const tlsKeepAliveTimeout = 4 * 60 * 60 * 1000; // 4 hours for TLS keep-alive - increased from 30 minutes
|
|
|
|
|
const safeTimeout = ensureSafeTimeout(tlsKeepAliveTimeout);
|
|
|
|
|
|
|
|
|
|
record.cleanupTimer = setTimeout(() => {
|
|
|
|
|
console.log(
|
|
|
|
|
`[${connectionId}] TLS keep-alive connection from ${
|
|
|
|
|
record.remoteIP
|
|
|
|
|
} exceeded max lifetime (${plugins.prettyMs(
|
|
|
|
|
tlsKeepAliveTimeout
|
|
|
|
|
)}), forcing cleanup to refresh certificate context.`
|
|
|
|
|
);
|
|
|
|
|
this.initiateCleanupOnce(record, 'tls_certificate_refresh');
|
|
|
|
|
}, safeTimeout);
|
|
|
|
|
|
|
|
|
|
// Make sure timeout doesn't keep the process alive
|
|
|
|
|
if (record.cleanupTimer.unref) {
|
|
|
|
|
record.cleanupTimer.unref();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (this.settings.enableDetailedLogging) {
|
|
|
|
|
console.log(
|
|
|
|
|
`[${connectionId}] TLS keep-alive connection with aggressive certificate refresh protection, lifetime: ${plugins.prettyMs(
|
|
|
|
|
tlsKeepAliveTimeout
|
|
|
|
|
)}`
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
// For extended keep-alive connections, use extended timeout
|
|
|
|
|
else if (record.hasKeepAlive && this.settings.keepAliveTreatment === 'extended') {
|
|
|
|
|
const extendedTimeout = this.settings.extendedKeepAliveLifetime || 7 * 24 * 60 * 60 * 1000; // 7 days
|
|
|
|
@ -1122,126 +1028,6 @@ export class PortProxy {
|
|
|
|
|
this.terminationStats[side][reason] = (this.terminationStats[side][reason] || 0) + 1;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Update connection activity timestamp with sleep detection
|
|
|
|
|
*/
|
|
|
|
|
private updateActivity(record: IConnectionRecord): void {
|
|
|
|
|
// Get the current time
|
|
|
|
|
const now = Date.now();
|
|
|
|
|
|
|
|
|
|
// Check if there was a large time gap that suggests system sleep
|
|
|
|
|
if (record.lastActivity > 0) {
|
|
|
|
|
const timeDiff = now - record.lastActivity;
|
|
|
|
|
|
|
|
|
|
// If time difference is very large (> 30 minutes) and this is a keep-alive connection,
|
|
|
|
|
// this might indicate system sleep rather than just inactivity
|
|
|
|
|
if (timeDiff > 30 * 60 * 1000 && record.hasKeepAlive) {
|
|
|
|
|
if (this.settings.enableDetailedLogging) {
|
|
|
|
|
console.log(
|
|
|
|
|
`[${record.id}] Detected possible system sleep for ${plugins.prettyMs(timeDiff)}. ` +
|
|
|
|
|
`Handling keep-alive connection after long inactivity.`
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// For TLS keep-alive connections after sleep/long inactivity, force close
|
|
|
|
|
// to make browser establish a new connection with fresh certificate context
|
|
|
|
|
if (record.isTLS && record.tlsHandshakeComplete) {
|
|
|
|
|
// More generous timeout now that we've fixed the renegotiation handling
|
|
|
|
|
if (timeDiff > 2 * 60 * 60 * 1000) {
|
|
|
|
|
// If inactive for more than 2 hours (increased from 20 minutes)
|
|
|
|
|
console.log(
|
|
|
|
|
`[${record.id}] TLS connection inactive for ${plugins.prettyMs(timeDiff)}. ` +
|
|
|
|
|
`Closing to force new connection with fresh certificate.`
|
|
|
|
|
);
|
|
|
|
|
return this.initiateCleanupOnce(record, 'certificate_refresh_needed');
|
|
|
|
|
} else if (timeDiff > 30 * 60 * 1000) {
|
|
|
|
|
// For shorter but still significant inactivity (30+ minutes), refresh TLS state
|
|
|
|
|
console.log(
|
|
|
|
|
`[${record.id}] TLS connection inactive for ${plugins.prettyMs(timeDiff)}. ` +
|
|
|
|
|
`Refreshing TLS state.`
|
|
|
|
|
);
|
|
|
|
|
this.refreshTlsStateAfterSleep(record);
|
|
|
|
|
|
|
|
|
|
// Add an additional check in 15 minutes if no activity
|
|
|
|
|
const refreshCheckId = record.id;
|
|
|
|
|
const refreshCheck = setTimeout(() => {
|
|
|
|
|
const currentRecord = this.connectionRecords.get(refreshCheckId);
|
|
|
|
|
if (currentRecord && Date.now() - currentRecord.lastActivity > 15 * 60 * 1000) {
|
|
|
|
|
console.log(
|
|
|
|
|
`[${refreshCheckId}] No activity detected after TLS refresh. ` +
|
|
|
|
|
`Closing connection to ensure certificate freshness.`
|
|
|
|
|
);
|
|
|
|
|
this.initiateCleanupOnce(currentRecord, 'tls_refresh_verification_failed');
|
|
|
|
|
}
|
|
|
|
|
}, 15 * 60 * 1000);
|
|
|
|
|
|
|
|
|
|
// Make sure timeout doesn't keep the process alive
|
|
|
|
|
if (refreshCheck.unref) {
|
|
|
|
|
refreshCheck.unref();
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
// For shorter inactivity periods, try to refresh the TLS state normally
|
|
|
|
|
this.refreshTlsStateAfterSleep(record);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Mark that we detected sleep
|
|
|
|
|
record.possibleSystemSleep = true;
|
|
|
|
|
record.lastSleepDetection = now;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Update the activity timestamp
|
|
|
|
|
record.lastActivity = now;
|
|
|
|
|
|
|
|
|
|
// Clear any inactivity warning
|
|
|
|
|
if (record.inactivityWarningIssued) {
|
|
|
|
|
record.inactivityWarningIssued = false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Refresh TLS state after sleep detection
|
|
|
|
|
*/
|
|
|
|
|
private refreshTlsStateAfterSleep(record: IConnectionRecord): void {
|
|
|
|
|
// Skip if we're using a NetworkProxy as it handles its own TLS state
|
|
|
|
|
if (record.usingNetworkProxy) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
// For outgoing connections that might need to be refreshed
|
|
|
|
|
if (record.outgoing && !record.outgoing.destroyed) {
|
|
|
|
|
// Check how long this connection has been established
|
|
|
|
|
const connectionAge = Date.now() - record.incomingStartTime;
|
|
|
|
|
const hourInMs = 60 * 60 * 1000;
|
|
|
|
|
|
|
|
|
|
// For TLS browser connections, use a more generous timeout now that
|
|
|
|
|
// we've fixed the renegotiation handling issues
|
|
|
|
|
if (record.isTLS && record.hasKeepAlive && connectionAge > 8 * hourInMs) { // 8 hours instead of 45 minutes
|
|
|
|
|
console.log(
|
|
|
|
|
`[${record.id}] Long-lived TLS connection (${plugins.prettyMs(connectionAge)}). ` +
|
|
|
|
|
`Closing to ensure proper certificate handling on browser reconnect in proxy chain.`
|
|
|
|
|
);
|
|
|
|
|
return this.initiateCleanupOnce(record, 'certificate_context_refresh');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// For newer connections, try to send a refresh packet
|
|
|
|
|
record.outgoing.write(Buffer.alloc(0));
|
|
|
|
|
|
|
|
|
|
if (this.settings.enableDetailedLogging) {
|
|
|
|
|
console.log(`[${record.id}] Sent refresh packet after sleep detection`);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.log(`[${record.id}] Error refreshing TLS state: ${err}`);
|
|
|
|
|
|
|
|
|
|
// If we hit an error, it's likely the connection is already broken
|
|
|
|
|
// Force cleanup to ensure browser reconnects cleanly
|
|
|
|
|
return this.initiateCleanupOnce(record, 'tls_refresh_error');
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Cleans up a connection record.
|
|
|
|
|
* Destroys both incoming and outgoing sockets, clears timers, and removes the record.
|
|
|
|
@ -1265,6 +1051,16 @@ export class PortProxy {
|
|
|
|
|
const bytesReceived = record.bytesReceived;
|
|
|
|
|
const bytesSent = record.bytesSent;
|
|
|
|
|
|
|
|
|
|
// Remove the renegotiation handler if present
|
|
|
|
|
if (record.renegotiationHandler && record.incoming) {
|
|
|
|
|
try {
|
|
|
|
|
record.incoming.removeListener('data', record.renegotiationHandler);
|
|
|
|
|
record.renegotiationHandler = undefined;
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.log(`[${record.id}] Error removing renegotiation handler: ${err}`);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
if (!record.incoming.destroyed) {
|
|
|
|
|
// Try graceful shutdown first, then force destroy after a short timeout
|
|
|
|
@ -1342,7 +1138,8 @@ export class PortProxy {
|
|
|
|
|
`TLS: ${record.isTLS ? 'Yes' : 'No'}, Keep-Alive: ${
|
|
|
|
|
record.hasKeepAlive ? 'Yes' : 'No'
|
|
|
|
|
}` +
|
|
|
|
|
`${record.usingNetworkProxy ? `, NetworkProxy: ${record.networkProxyIndex}` : ''}`
|
|
|
|
|
`${record.usingNetworkProxy ? ', Using NetworkProxy' : ''}` +
|
|
|
|
|
`${record.domainSwitches ? `, Domain switches: ${record.domainSwitches}` : ''}`
|
|
|
|
|
);
|
|
|
|
|
} else {
|
|
|
|
|
console.log(
|
|
|
|
@ -1352,6 +1149,18 @@ export class PortProxy {
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Update connection activity timestamp
|
|
|
|
|
*/
|
|
|
|
|
private updateActivity(record: IConnectionRecord): void {
|
|
|
|
|
record.lastActivity = Date.now();
|
|
|
|
|
|
|
|
|
|
// Clear any inactivity warning
|
|
|
|
|
if (record.inactivityWarningIssued) {
|
|
|
|
|
record.inactivityWarningIssued = false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Get target IP with round-robin support
|
|
|
|
|
*/
|
|
|
|
@ -1469,6 +1278,12 @@ export class PortProxy {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Start NetworkProxy if configured
|
|
|
|
|
if (this.networkProxy) {
|
|
|
|
|
await this.networkProxy.start();
|
|
|
|
|
console.log(`NetworkProxy started on port ${this.settings.networkProxyPort}`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Define a unified connection handler for all listening ports.
|
|
|
|
|
const connectionHandler = (socket: plugins.net.Socket) => {
|
|
|
|
|
if (this.isShuttingDown) {
|
|
|
|
@ -1529,11 +1344,12 @@ export class PortProxy {
|
|
|
|
|
incomingTerminationReason: null,
|
|
|
|
|
outgoingTerminationReason: null,
|
|
|
|
|
|
|
|
|
|
// Initialize NetworkProxy tracking fields
|
|
|
|
|
// Initialize NetworkProxy tracking
|
|
|
|
|
usingNetworkProxy: false,
|
|
|
|
|
|
|
|
|
|
// Initialize sleep detection fields
|
|
|
|
|
possibleSystemSleep: false,
|
|
|
|
|
// Initialize browser connection tracking
|
|
|
|
|
isBrowserConnection: false,
|
|
|
|
|
domainSwitches: 0,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Apply keep-alive settings if enabled
|
|
|
|
@ -1578,8 +1394,63 @@ export class PortProxy {
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Check if this connection should be forwarded directly to NetworkProxy based on port
|
|
|
|
|
const shouldUseNetworkProxy = this.settings.useNetworkProxy &&
|
|
|
|
|
this.settings.useNetworkProxy.includes(localPort);
|
|
|
|
|
|
|
|
|
|
if (shouldUseNetworkProxy) {
|
|
|
|
|
// For NetworkProxy ports, we want to capture the TLS handshake and forward directly
|
|
|
|
|
let initialDataReceived = false;
|
|
|
|
|
|
|
|
|
|
// Set an initial timeout for handshake data
|
|
|
|
|
let initialTimeout: NodeJS.Timeout | null = setTimeout(() => {
|
|
|
|
|
if (!initialDataReceived) {
|
|
|
|
|
console.log(
|
|
|
|
|
`[${connectionId}] Initial data timeout (${this.settings.initialDataTimeout}ms) for connection from ${remoteIP} on port ${localPort}`
|
|
|
|
|
);
|
|
|
|
|
if (connectionRecord.incomingTerminationReason === null) {
|
|
|
|
|
connectionRecord.incomingTerminationReason = 'initial_timeout';
|
|
|
|
|
this.incrementTerminationStat('incoming', 'initial_timeout');
|
|
|
|
|
}
|
|
|
|
|
socket.end();
|
|
|
|
|
this.cleanupConnection(connectionRecord, 'initial_timeout');
|
|
|
|
|
}
|
|
|
|
|
}, this.settings.initialDataTimeout!);
|
|
|
|
|
|
|
|
|
|
// Make sure timeout doesn't keep the process alive
|
|
|
|
|
if (initialTimeout.unref) {
|
|
|
|
|
initialTimeout.unref();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
socket.on('error', this.handleError('incoming', connectionRecord));
|
|
|
|
|
|
|
|
|
|
// First data handler to capture initial TLS handshake for NetworkProxy
|
|
|
|
|
socket.once('data', (chunk: Buffer) => {
|
|
|
|
|
// Clear the initial timeout since we've received data
|
|
|
|
|
if (initialTimeout) {
|
|
|
|
|
clearTimeout(initialTimeout);
|
|
|
|
|
initialTimeout = null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
initialDataReceived = true;
|
|
|
|
|
connectionRecord.hasReceivedInitialData = true;
|
|
|
|
|
|
|
|
|
|
// Check if this looks like a TLS handshake
|
|
|
|
|
if (isTlsHandshake(chunk)) {
|
|
|
|
|
connectionRecord.isTLS = true;
|
|
|
|
|
|
|
|
|
|
// Forward directly to NetworkProxy without SNI processing
|
|
|
|
|
this.forwardToNetworkProxy(connectionId, socket, connectionRecord, chunk);
|
|
|
|
|
} else {
|
|
|
|
|
// If not TLS, use normal direct connection
|
|
|
|
|
console.log(`[${connectionId}] Non-TLS connection on NetworkProxy port ${localPort}`);
|
|
|
|
|
this.setupDirectConnection(connectionId, socket, connectionRecord, undefined, undefined, chunk);
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
} else {
|
|
|
|
|
// For non-NetworkProxy ports, proceed with normal processing
|
|
|
|
|
|
|
|
|
|
// Define helpers for rejecting connections
|
|
|
|
|
const rejectIncomingConnection = (reason: string, logMessage: string) => {
|
|
|
|
|
console.log(`[${connectionId}] ${logMessage}`);
|
|
|
|
@ -1591,6 +1462,8 @@ export class PortProxy {
|
|
|
|
|
this.cleanupConnection(connectionRecord, reason);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
let initialDataReceived = false;
|
|
|
|
|
|
|
|
|
|
// Set an initial timeout for SNI data if needed
|
|
|
|
|
let initialTimeout: NodeJS.Timeout | null = null;
|
|
|
|
|
if (this.settings.sniEnabled) {
|
|
|
|
@ -1639,7 +1512,7 @@ export class PortProxy {
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Sets up the connection to the target host or NetworkProxy.
|
|
|
|
|
* Sets up the connection to the target host.
|
|
|
|
|
* @param serverName - The SNI hostname (unused when forcedDomain is provided).
|
|
|
|
|
* @param initialChunk - Optional initial data chunk.
|
|
|
|
|
* @param forcedDomain - If provided, overrides SNI/domain lookup (used for port-based routing).
|
|
|
|
@ -1708,23 +1581,6 @@ export class PortProxy {
|
|
|
|
|
)}`
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Check if we should forward this to a NetworkProxy
|
|
|
|
|
if (
|
|
|
|
|
isTlsHandshakeDetected &&
|
|
|
|
|
domainConfig.useNetworkProxy === true &&
|
|
|
|
|
initialChunk &&
|
|
|
|
|
this.networkProxies.length > 0
|
|
|
|
|
) {
|
|
|
|
|
return this.forwardToNetworkProxy(
|
|
|
|
|
connectionId,
|
|
|
|
|
socket,
|
|
|
|
|
connectionRecord,
|
|
|
|
|
domainConfig,
|
|
|
|
|
initialChunk,
|
|
|
|
|
serverName
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
} else if (this.settings.defaultAllowedIPs && this.settings.defaultAllowedIPs.length > 0) {
|
|
|
|
|
if (
|
|
|
|
|
!isGlobIPAllowed(
|
|
|
|
@ -1740,7 +1596,12 @@ export class PortProxy {
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// If we didn't forward to NetworkProxy, proceed with direct connection
|
|
|
|
|
// Save the initial SNI
|
|
|
|
|
if (serverName) {
|
|
|
|
|
connectionRecord.lockedDomain = serverName;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Set up the direct connection
|
|
|
|
|
return this.setupDirectConnection(
|
|
|
|
|
connectionId,
|
|
|
|
|
socket,
|
|
|
|
@ -1885,6 +1746,7 @@ export class PortProxy {
|
|
|
|
|
|
|
|
|
|
setupConnection('');
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// --- SETUP LISTENERS ---
|
|
|
|
@ -1909,10 +1771,11 @@ export class PortProxy {
|
|
|
|
|
console.log(`Server Error on port ${port}: ${err.message}`);
|
|
|
|
|
});
|
|
|
|
|
server.listen(port, () => {
|
|
|
|
|
const isNetworkProxyPort = this.settings.useNetworkProxy?.includes(port);
|
|
|
|
|
console.log(
|
|
|
|
|
`PortProxy -> OK: Now listening on port ${port}${
|
|
|
|
|
this.settings.sniEnabled ? ' (SNI passthrough enabled)' : ''
|
|
|
|
|
}${this.networkProxies.length > 0 ? ' (NetworkProxy integration enabled)' : ''}`
|
|
|
|
|
this.settings.sniEnabled && !isNetworkProxyPort ? ' (SNI passthrough enabled)' : ''
|
|
|
|
|
}${isNetworkProxyPort ? ' (NetworkProxy forwarding enabled)' : ''}`
|
|
|
|
|
);
|
|
|
|
|
});
|
|
|
|
|
this.netServers.push(server);
|
|
|
|
@ -1932,6 +1795,7 @@ export class PortProxy {
|
|
|
|
|
let pendingTlsHandshakes = 0;
|
|
|
|
|
let keepAliveConnections = 0;
|
|
|
|
|
let networkProxyConnections = 0;
|
|
|
|
|
let domainSwitchedConnections = 0;
|
|
|
|
|
|
|
|
|
|
// Create a copy of the keys to avoid modification during iteration
|
|
|
|
|
const connectionIds = [...this.connectionRecords.keys()];
|
|
|
|
@ -1960,11 +1824,14 @@ export class PortProxy {
|
|
|
|
|
networkProxyConnections++;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (record.domainSwitches && record.domainSwitches > 0) {
|
|
|
|
|
domainSwitchedConnections++;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
maxIncoming = Math.max(maxIncoming, now - record.incomingStartTime);
|
|
|
|
|
if (record.outgoingStartTime) {
|
|
|
|
|
maxOutgoing = Math.max(maxOutgoing, now - record.outgoingStartTime);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Parity check: if outgoing socket closed and incoming remains active
|
|
|
|
|
if (
|
|
|
|
|
record.outgoingClosedTime &&
|
|
|
|
@ -2002,48 +1869,6 @@ export class PortProxy {
|
|
|
|
|
) {
|
|
|
|
|
const inactivityTime = now - record.lastActivity;
|
|
|
|
|
|
|
|
|
|
// Special handling for TLS keep-alive connections
|
|
|
|
|
if (
|
|
|
|
|
record.hasKeepAlive &&
|
|
|
|
|
record.isTLS &&
|
|
|
|
|
inactivityTime > this.settings.inactivityTimeout! / 2
|
|
|
|
|
) {
|
|
|
|
|
// For TLS keep-alive connections that are getting stale, try to refresh before closing
|
|
|
|
|
if (!record.inactivityWarningIssued) {
|
|
|
|
|
console.log(
|
|
|
|
|
`[${id}] TLS keep-alive connection from ${
|
|
|
|
|
record.remoteIP
|
|
|
|
|
} inactive for ${plugins.prettyMs(inactivityTime)}. ` +
|
|
|
|
|
`Attempting to preserve connection.`
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
// Set warning flag but give a much longer grace period for TLS connections
|
|
|
|
|
record.inactivityWarningIssued = true;
|
|
|
|
|
|
|
|
|
|
// For TLS connections, extend the last activity time considerably
|
|
|
|
|
// This gives browsers more time to re-establish the connection properly
|
|
|
|
|
record.lastActivity = now - this.settings.inactivityTimeout! / 3;
|
|
|
|
|
|
|
|
|
|
// Try to stimulate the connection with a probe packet
|
|
|
|
|
if (record.outgoing && !record.outgoing.destroyed) {
|
|
|
|
|
try {
|
|
|
|
|
// For TLS connections, send a proper TLS heartbeat-like packet
|
|
|
|
|
// This is just a small empty buffer that won't affect the TLS session
|
|
|
|
|
record.outgoing.write(Buffer.alloc(0));
|
|
|
|
|
|
|
|
|
|
if (this.settings.enableDetailedLogging) {
|
|
|
|
|
console.log(`[${id}] Sent TLS keep-alive probe packet`);
|
|
|
|
|
}
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.log(`[${id}] Error sending TLS probe packet: ${err}`);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Don't proceed to the normal inactivity check logic
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Use extended timeout for extended-treatment keep-alive connections
|
|
|
|
|
let effectiveTimeout = this.settings.inactivityTimeout!;
|
|
|
|
|
if (record.hasKeepAlive && this.settings.keepAliveTreatment === 'extended') {
|
|
|
|
@ -2077,33 +1902,6 @@ export class PortProxy {
|
|
|
|
|
console.log(`[${id}] Error sending probe packet: ${err}`);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
// MODIFIED: For TLS connections, be more lenient before closing
|
|
|
|
|
// For TLS browser connections, we need to handle certificate context properly
|
|
|
|
|
if (record.isTLS && record.hasKeepAlive) {
|
|
|
|
|
// For very long inactivity, it's better to close the connection
|
|
|
|
|
// so the browser establishes a new one with a fresh certificate context
|
|
|
|
|
if (inactivityTime > 6 * 60 * 60 * 1000) {
|
|
|
|
|
// 6 hours
|
|
|
|
|
console.log(
|
|
|
|
|
`[${id}] TLS keep-alive connection from ${
|
|
|
|
|
record.remoteIP
|
|
|
|
|
} inactive for ${plugins.prettyMs(inactivityTime)}. ` +
|
|
|
|
|
`Closing to ensure proper certificate handling on browser reconnect.`
|
|
|
|
|
);
|
|
|
|
|
this.cleanupConnection(record, 'tls_certificate_refresh');
|
|
|
|
|
} else {
|
|
|
|
|
// For shorter inactivity periods, add grace period
|
|
|
|
|
console.log(
|
|
|
|
|
`[${id}] TLS keep-alive connection from ${
|
|
|
|
|
record.remoteIP
|
|
|
|
|
} inactive for ${plugins.prettyMs(inactivityTime)}. ` +
|
|
|
|
|
`Adding extra grace period.`
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
// Give additional time for browsers to reconnect properly
|
|
|
|
|
record.lastActivity = now - effectiveTimeout / 2;
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
// For non-keep-alive or after warning, close the connection
|
|
|
|
|
console.log(
|
|
|
|
@ -2113,7 +1911,6 @@ export class PortProxy {
|
|
|
|
|
);
|
|
|
|
|
this.cleanupConnection(record, 'inactivity');
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
} else if (inactivityTime <= effectiveTimeout && record.inactivityWarningIssued) {
|
|
|
|
|
// If activity detected after warning, clear the warning
|
|
|
|
|
if (this.settings.enableDetailedLogging) {
|
|
|
|
@ -2130,7 +1927,8 @@ export class PortProxy {
|
|
|
|
|
console.log(
|
|
|
|
|
`Active connections: ${this.connectionRecords.size}. ` +
|
|
|
|
|
`Types: TLS=${tlsConnections} (Completed=${completedTlsHandshakes}, Pending=${pendingTlsHandshakes}), ` +
|
|
|
|
|
`Non-TLS=${nonTlsConnections}, KeepAlive=${keepAliveConnections}, NetworkProxy=${networkProxyConnections}. ` +
|
|
|
|
|
`Non-TLS=${nonTlsConnections}, KeepAlive=${keepAliveConnections}, NetworkProxy=${networkProxyConnections}, ` +
|
|
|
|
|
`DomainSwitched=${domainSwitchedConnections}. ` +
|
|
|
|
|
`Longest running: IN=${plugins.prettyMs(maxIncoming)}, OUT=${plugins.prettyMs(
|
|
|
|
|
maxOutgoing
|
|
|
|
|
)}. ` +
|
|
|
|
@ -2147,21 +1945,6 @@ export class PortProxy {
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Add or replace NetworkProxy instances
|
|
|
|
|
*/
|
|
|
|
|
public setNetworkProxies(networkProxies: NetworkProxy[]): void {
|
|
|
|
|
this.networkProxies = networkProxies;
|
|
|
|
|
console.log(`Updated NetworkProxy instances: ${this.networkProxies.length} proxies configured`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Get a list of configured NetworkProxy instances
|
|
|
|
|
*/
|
|
|
|
|
public getNetworkProxies(): NetworkProxy[] {
|
|
|
|
|
return this.networkProxies;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Gracefully shut down the proxy
|
|
|
|
|
*/
|
|
|
|
@ -2253,6 +2036,16 @@ export class PortProxy {
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Stop NetworkProxy if it was started
|
|
|
|
|
if (this.networkProxy) {
|
|
|
|
|
try {
|
|
|
|
|
await this.networkProxy.stop();
|
|
|
|
|
console.log('NetworkProxy stopped successfully');
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.log(`Error stopping NetworkProxy: ${err}`);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Clear all tracking maps
|
|
|
|
|
this.connectionRecords.clear();
|
|
|
|
|
this.domainTargetIndices.clear();
|
|
|
|
|