|
|
|
@ -16,7 +16,12 @@ export interface IDomainConfig {
|
|
|
|
|
networkProxyIndex?: number; // Optional index to specify which NetworkProxy to use (defaults to 0)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Port proxy settings including global allowed port ranges */
|
|
|
|
|
/**
|
|
|
|
|
* 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.
|
|
|
|
|
*/
|
|
|
|
|
export interface IPortProxySettings extends plugins.tls.TlsOptions {
|
|
|
|
|
fromPort: number;
|
|
|
|
|
toPort: number;
|
|
|
|
@ -27,14 +32,10 @@ export interface IPortProxySettings extends plugins.tls.TlsOptions {
|
|
|
|
|
defaultBlockedIPs?: string[];
|
|
|
|
|
preserveSourceIP?: boolean;
|
|
|
|
|
|
|
|
|
|
// 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)
|
|
|
|
|
|
|
|
|
|
// Simplified timeout settings
|
|
|
|
|
gracefulShutdownTimeout?: number; // (ms) maximum time to wait for connections to close during shutdown
|
|
|
|
|
|
|
|
|
|
// Ranged port settings
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
@ -44,9 +45,7 @@ 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
|
|
|
|
|
|
|
|
|
|
// Enhanced features
|
|
|
|
|
disableInactivityCheck?: boolean; // Disable inactivity checking entirely
|
|
|
|
|
enableKeepAliveProbes?: boolean; // Enable TCP keep-alive probes
|
|
|
|
|
// Logging settings
|
|
|
|
|
enableDetailedLogging?: boolean; // Enable detailed connection logging
|
|
|
|
|
enableTlsDebugLogging?: boolean; // Enable TLS handshake debug logging
|
|
|
|
|
enableRandomizedTimeouts?: boolean; // Randomize timeouts slightly to prevent thundering herd
|
|
|
|
@ -55,12 +54,7 @@ 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
|
|
|
|
|
|
|
|
|
|
// 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
|
|
|
|
|
// NetworkProxy integration
|
|
|
|
|
networkProxies?: NetworkProxy[]; // Array of NetworkProxy instances to use for TLS termination
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
@ -106,14 +100,82 @@ interface IConnectionRecord {
|
|
|
|
|
lastSleepDetection?: number; // Timestamp of the last sleep detection
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Structure to track TLS session information for proper resumption handling
|
|
|
|
|
*/
|
|
|
|
|
interface ITlsSessionInfo {
|
|
|
|
|
domain: string; // The SNI domain associated with this session
|
|
|
|
|
sessionId?: Buffer; // The TLS session ID (if available)
|
|
|
|
|
ticketId?: string; // Session ticket identifier for newer TLS versions
|
|
|
|
|
ticketTimestamp: number; // When this session was recorded
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Global cache of TLS session IDs to SNI domains
|
|
|
|
|
// This ensures resumed sessions maintain their SNI binding
|
|
|
|
|
const tlsSessionCache = new Map<string, ITlsSessionInfo>();
|
|
|
|
|
|
|
|
|
|
// Reference to session cleanup timer so we can clear it
|
|
|
|
|
let tlsSessionCleanupTimer: NodeJS.Timeout | null = null;
|
|
|
|
|
|
|
|
|
|
// Start the cleanup timer for session cache
|
|
|
|
|
function startSessionCleanupTimer() {
|
|
|
|
|
// Avoid creating multiple timers
|
|
|
|
|
if (tlsSessionCleanupTimer) {
|
|
|
|
|
clearInterval(tlsSessionCleanupTimer);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Create new cleanup timer
|
|
|
|
|
tlsSessionCleanupTimer = setInterval(() => {
|
|
|
|
|
const now = Date.now();
|
|
|
|
|
const expiryTime = 24 * 60 * 60 * 1000; // 24 hours
|
|
|
|
|
|
|
|
|
|
for (const [sessionId, info] of tlsSessionCache.entries()) {
|
|
|
|
|
if (now - info.ticketTimestamp > expiryTime) {
|
|
|
|
|
tlsSessionCache.delete(sessionId);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}, 60 * 60 * 1000); // Clean up once per hour
|
|
|
|
|
|
|
|
|
|
// Make sure the interval doesn't keep the process alive
|
|
|
|
|
if (tlsSessionCleanupTimer.unref) {
|
|
|
|
|
tlsSessionCleanupTimer.unref();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Start the timer initially
|
|
|
|
|
startSessionCleanupTimer();
|
|
|
|
|
|
|
|
|
|
// Function to stop the cleanup timer (used during shutdown)
|
|
|
|
|
function stopSessionCleanupTimer() {
|
|
|
|
|
if (tlsSessionCleanupTimer) {
|
|
|
|
|
clearInterval(tlsSessionCleanupTimer);
|
|
|
|
|
tlsSessionCleanupTimer = null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Return type for the extractSNIInfo function
|
|
|
|
|
*/
|
|
|
|
|
interface ISNIExtractResult {
|
|
|
|
|
serverName?: string; // The extracted SNI hostname
|
|
|
|
|
sessionId?: Buffer; // The TLS session ID if present
|
|
|
|
|
sessionIdKey?: string; // The hex string representation of session ID
|
|
|
|
|
sessionTicketId?: string; // Session ticket identifier for TLS 1.3+ resumption
|
|
|
|
|
hasSessionTicket?: boolean; // Whether a session ticket extension was found
|
|
|
|
|
isResumption: boolean; // Whether this appears to be a session resumption
|
|
|
|
|
resumedDomain?: string; // The domain associated with the session if resuming
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Extracts the SNI (Server Name Indication) from a TLS ClientHello packet.
|
|
|
|
|
* Enhanced for robustness and detailed logging.
|
|
|
|
|
* Also extracts and tracks TLS Session IDs for session resumption handling.
|
|
|
|
|
*
|
|
|
|
|
* @param buffer - Buffer containing the TLS ClientHello.
|
|
|
|
|
* @param enableLogging - Whether to enable detailed logging.
|
|
|
|
|
* @returns The server name if found, otherwise undefined.
|
|
|
|
|
* @returns An object containing SNI and session information, or undefined if parsing fails.
|
|
|
|
|
*/
|
|
|
|
|
function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | undefined {
|
|
|
|
|
function extractSNIInfo(buffer: Buffer, enableLogging: boolean = false): ISNIExtractResult | undefined {
|
|
|
|
|
try {
|
|
|
|
|
// Check if buffer is too small for TLS
|
|
|
|
|
if (buffer.length < 5) {
|
|
|
|
@ -159,9 +221,38 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
|
|
|
|
|
|
|
|
|
offset += 2 + 32; // Skip client version and random
|
|
|
|
|
|
|
|
|
|
// Session ID
|
|
|
|
|
// Extract Session ID for session resumption tracking
|
|
|
|
|
const sessionIDLength = buffer.readUInt8(offset);
|
|
|
|
|
if (enableLogging) console.log(`Session ID Length: ${sessionIDLength}`);
|
|
|
|
|
|
|
|
|
|
// If there's a session ID, extract it
|
|
|
|
|
let sessionId: Buffer | undefined;
|
|
|
|
|
let sessionIdKey: string | undefined;
|
|
|
|
|
let isResumption = false;
|
|
|
|
|
let resumedDomain: string | undefined;
|
|
|
|
|
|
|
|
|
|
if (sessionIDLength > 0) {
|
|
|
|
|
sessionId = Buffer.from(buffer.slice(offset + 1, offset + 1 + sessionIDLength));
|
|
|
|
|
|
|
|
|
|
// Convert sessionId to a string key for our cache
|
|
|
|
|
sessionIdKey = sessionId.toString('hex');
|
|
|
|
|
|
|
|
|
|
if (enableLogging) {
|
|
|
|
|
console.log(`Session ID: ${sessionIdKey}`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Check if this is a session resumption attempt
|
|
|
|
|
if (tlsSessionCache.has(sessionIdKey)) {
|
|
|
|
|
const cachedInfo = tlsSessionCache.get(sessionIdKey)!;
|
|
|
|
|
resumedDomain = cachedInfo.domain;
|
|
|
|
|
isResumption = true;
|
|
|
|
|
|
|
|
|
|
if (enableLogging) {
|
|
|
|
|
console.log(`TLS Session Resumption detected for domain: ${resumedDomain}`);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
offset += 1 + sessionIDLength; // Skip session ID
|
|
|
|
|
|
|
|
|
|
// Cipher suites
|
|
|
|
@ -200,6 +291,10 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
|
|
|
|
return undefined;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Variables to track session tickets
|
|
|
|
|
let hasSessionTicket = false;
|
|
|
|
|
let sessionTicketId: string | undefined;
|
|
|
|
|
|
|
|
|
|
// Parse extensions
|
|
|
|
|
while (offset + 4 <= extensionsEnd) {
|
|
|
|
|
const extensionType = buffer.readUInt16BE(offset);
|
|
|
|
@ -209,6 +304,33 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
|
|
|
|
console.log(`Extension Type: 0x${extensionType.toString(16)}, Length: ${extensionLength}`);
|
|
|
|
|
|
|
|
|
|
offset += 4;
|
|
|
|
|
|
|
|
|
|
// Check for Session Ticket extension (type 0x0023)
|
|
|
|
|
if (extensionType === 0x0023 && extensionLength > 0) {
|
|
|
|
|
hasSessionTicket = true;
|
|
|
|
|
|
|
|
|
|
// Extract a hash of the ticket for tracking
|
|
|
|
|
if (extensionLength > 16) { // Ensure we have enough bytes to create a meaningful ID
|
|
|
|
|
const ticketBytes = buffer.slice(offset, offset + Math.min(16, extensionLength));
|
|
|
|
|
sessionTicketId = ticketBytes.toString('hex');
|
|
|
|
|
|
|
|
|
|
if (enableLogging) {
|
|
|
|
|
console.log(`Session Ticket found, ID: ${sessionTicketId}`);
|
|
|
|
|
|
|
|
|
|
// Check if this is a known session ticket
|
|
|
|
|
if (tlsSessionCache.has(`ticket:${sessionTicketId}`)) {
|
|
|
|
|
const cachedInfo = tlsSessionCache.get(`ticket:${sessionTicketId}`);
|
|
|
|
|
console.log(`TLS Session Ticket Resumption detected for domain: ${cachedInfo?.domain}`);
|
|
|
|
|
|
|
|
|
|
// Set isResumption and resumedDomain if not already set
|
|
|
|
|
if (!isResumption && !resumedDomain) {
|
|
|
|
|
isResumption = true;
|
|
|
|
|
resumedDomain = cachedInfo?.domain;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (extensionType === 0x0000) {
|
|
|
|
|
// SNI extension
|
|
|
|
@ -251,7 +373,43 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
|
|
|
|
|
|
|
|
|
const serverName = buffer.toString('utf8', offset, offset + nameLen);
|
|
|
|
|
if (enableLogging) console.log(`Extracted SNI: ${serverName}`);
|
|
|
|
|
return serverName;
|
|
|
|
|
|
|
|
|
|
// Store the session ID to domain mapping for future resumptions
|
|
|
|
|
if (sessionIdKey && sessionId && serverName) {
|
|
|
|
|
tlsSessionCache.set(sessionIdKey, {
|
|
|
|
|
domain: serverName,
|
|
|
|
|
sessionId: sessionId,
|
|
|
|
|
ticketTimestamp: Date.now()
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (enableLogging) {
|
|
|
|
|
console.log(`Stored session ${sessionIdKey} for domain ${serverName}`);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Also store session ticket information if present
|
|
|
|
|
if (sessionTicketId && serverName) {
|
|
|
|
|
tlsSessionCache.set(`ticket:${sessionTicketId}`, {
|
|
|
|
|
domain: serverName,
|
|
|
|
|
ticketId: sessionTicketId,
|
|
|
|
|
ticketTimestamp: Date.now()
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (enableLogging) {
|
|
|
|
|
console.log(`Stored session ticket ${sessionTicketId} for domain ${serverName}`);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Return the complete extraction result
|
|
|
|
|
return {
|
|
|
|
|
serverName,
|
|
|
|
|
sessionId,
|
|
|
|
|
sessionIdKey,
|
|
|
|
|
sessionTicketId,
|
|
|
|
|
isResumption,
|
|
|
|
|
resumedDomain,
|
|
|
|
|
hasSessionTicket
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
offset += nameLen;
|
|
|
|
@ -263,13 +421,46 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (enableLogging) console.log('No SNI extension found');
|
|
|
|
|
return undefined;
|
|
|
|
|
|
|
|
|
|
// Even without SNI, we might be dealing with a session resumption
|
|
|
|
|
if (isResumption && resumedDomain) {
|
|
|
|
|
return {
|
|
|
|
|
serverName: resumedDomain, // Use the domain from previous session
|
|
|
|
|
sessionId,
|
|
|
|
|
sessionIdKey,
|
|
|
|
|
sessionTicketId,
|
|
|
|
|
hasSessionTicket,
|
|
|
|
|
isResumption: true,
|
|
|
|
|
resumedDomain
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Return a basic result with just the session info
|
|
|
|
|
return {
|
|
|
|
|
isResumption,
|
|
|
|
|
sessionId,
|
|
|
|
|
sessionIdKey,
|
|
|
|
|
sessionTicketId,
|
|
|
|
|
hasSessionTicket,
|
|
|
|
|
resumedDomain
|
|
|
|
|
};
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.log(`Error extracting SNI: ${err}`);
|
|
|
|
|
return undefined;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Legacy wrapper for extractSNIInfo to maintain backward compatibility
|
|
|
|
|
* @param buffer - Buffer containing the TLS ClientHello
|
|
|
|
|
* @param enableLogging - Whether to enable detailed logging
|
|
|
|
|
* @returns The server name if found, otherwise undefined
|
|
|
|
|
*/
|
|
|
|
|
function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | undefined {
|
|
|
|
|
const result = extractSNIInfo(buffer, enableLogging);
|
|
|
|
|
return result?.serverName;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 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);
|
|
|
|
@ -332,7 +523,22 @@ const randomizeTimeout = (baseTimeout: number, variationPercent: number = 5): nu
|
|
|
|
|
|
|
|
|
|
export class PortProxy {
|
|
|
|
|
private netServers: plugins.net.Server[] = [];
|
|
|
|
|
settings: IPortProxySettings;
|
|
|
|
|
|
|
|
|
|
// 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;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
private connectionRecords: Map<string, IConnectionRecord> = new Map();
|
|
|
|
|
private connectionLogger: NodeJS.Timeout | null = null;
|
|
|
|
|
private isShuttingDown: boolean = false;
|
|
|
|
@ -357,42 +563,41 @@ export class PortProxy {
|
|
|
|
|
private networkProxies: NetworkProxy[] = [];
|
|
|
|
|
|
|
|
|
|
constructor(settingsArg: IPortProxySettings) {
|
|
|
|
|
// Set reasonable defaults for all settings
|
|
|
|
|
// Set hardcoded sensible defaults for all settings
|
|
|
|
|
this.settings = {
|
|
|
|
|
...settingsArg,
|
|
|
|
|
targetIP: settingsArg.targetIP || 'localhost',
|
|
|
|
|
|
|
|
|
|
// 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
|
|
|
|
|
|
|
|
|
|
// 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
|
|
|
|
|
|
|
|
|
|
gracefulShutdownTimeout: settingsArg.gracefulShutdownTimeout || 30000, // 30 seconds
|
|
|
|
|
|
|
|
|
|
// Socket optimization settings
|
|
|
|
|
noDelay: settingsArg.noDelay !== undefined ? settingsArg.noDelay : true,
|
|
|
|
|
keepAlive: settingsArg.keepAlive !== undefined ? settingsArg.keepAlive : true,
|
|
|
|
|
keepAliveInitialDelay: settingsArg.keepAliveInitialDelay || 10000, // 10 seconds (reduced for responsiveness)
|
|
|
|
|
keepAliveInitialDelay: settingsArg.keepAliveInitialDelay || 10000, // 10 seconds
|
|
|
|
|
maxPendingDataSize: settingsArg.maxPendingDataSize || 10 * 1024 * 1024, // 10MB to handle large TLS handshakes
|
|
|
|
|
|
|
|
|
|
// Feature flags
|
|
|
|
|
disableInactivityCheck: settingsArg.disableInactivityCheck || false,
|
|
|
|
|
enableKeepAliveProbes:
|
|
|
|
|
settingsArg.enableKeepAliveProbes !== undefined ? settingsArg.enableKeepAliveProbes : true, // Enable by default
|
|
|
|
|
// 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
|
|
|
|
|
enableDetailedLogging: settingsArg.enableDetailedLogging || false,
|
|
|
|
|
enableTlsDebugLogging: settingsArg.enableTlsDebugLogging || false,
|
|
|
|
|
enableRandomizedTimeouts: settingsArg.enableRandomizedTimeouts || false, // Disable randomization by default
|
|
|
|
|
enableRandomizedTimeouts: settingsArg.enableRandomizedTimeouts || false,
|
|
|
|
|
|
|
|
|
|
// Rate limiting defaults
|
|
|
|
|
maxConnectionsPerIP: settingsArg.maxConnectionsPerIP || 100, // 100 connections per IP
|
|
|
|
|
connectionRateLimitPerMinute: settingsArg.connectionRateLimitPerMinute || 300, // 300 per minute
|
|
|
|
|
|
|
|
|
|
// Enhanced keep-alive settings
|
|
|
|
|
keepAliveTreatment: settingsArg.keepAliveTreatment || 'extended', // Extended by default
|
|
|
|
|
keepAliveInactivityMultiplier: settingsArg.keepAliveInactivityMultiplier || 6, // 6x normal inactivity timeout
|
|
|
|
|
extendedKeepAliveLifetime: settingsArg.extendedKeepAliveLifetime || 7 * 24 * 60 * 60 * 1000, // 7 days
|
|
|
|
|
// 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!)
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Store NetworkProxy instances if provided
|
|
|
|
@ -493,26 +698,17 @@ export class PortProxy {
|
|
|
|
|
}
|
|
|
|
|
this.cleanupConnection(record, 'client_closed');
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Update activity on data transfer
|
|
|
|
|
|
|
|
|
|
// Special handler for TLS handshake detection with NetworkProxy
|
|
|
|
|
socket.on('data', (chunk: Buffer) => {
|
|
|
|
|
this.updateActivity(record);
|
|
|
|
|
|
|
|
|
|
// Check for potential TLS renegotiation or reconnection packets
|
|
|
|
|
// Check for TLS handshake packets (ContentType.handshake)
|
|
|
|
|
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`
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Let the NetworkProxy handle the TLS renegotiation
|
|
|
|
|
// Just update the activity timestamp to prevent timeouts
|
|
|
|
|
record.lastActivity = Date.now();
|
|
|
|
|
console.log(`[${connectionId}] Detected potential TLS handshake with NetworkProxy, updating activity`);
|
|
|
|
|
this.updateActivity(record);
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Update activity on data transfer from the proxy socket
|
|
|
|
|
proxySocket.on('data', () => this.updateActivity(record));
|
|
|
|
|
|
|
|
|
|
if (this.settings.enableDetailedLogging) {
|
|
|
|
@ -768,6 +964,82 @@ export class PortProxy {
|
|
|
|
|
return this.initiateCleanupOnce(record, 'write_error');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Set up the renegotiation listener *before* piping if this is a TLS connection with SNI
|
|
|
|
|
if (serverName && record.isTLS) {
|
|
|
|
|
// This listener handles TLS renegotiation detection
|
|
|
|
|
socket.on('data', (renegChunk) => {
|
|
|
|
|
if (renegChunk.length > 0 && renegChunk.readUInt8(0) === 22) {
|
|
|
|
|
// Always update activity timestamp for any handshake packet
|
|
|
|
|
this.updateActivity(record);
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
// Extract all TLS information including session resumption data
|
|
|
|
|
const sniInfo = extractSNIInfo(renegChunk, this.settings.enableTlsDebugLogging);
|
|
|
|
|
let newSNI = sniInfo?.serverName;
|
|
|
|
|
|
|
|
|
|
// Handle session resumption - if we recognize the session ID, we know what domain it belongs to
|
|
|
|
|
if (sniInfo?.isResumption && sniInfo.resumedDomain) {
|
|
|
|
|
console.log(`[${connectionId}] Rehandshake with session resumption for domain: ${sniInfo.resumedDomain}`);
|
|
|
|
|
newSNI = sniInfo.resumedDomain;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// IMPORTANT: If we can't extract an SNI from renegotiation, we MUST allow it through
|
|
|
|
|
if (newSNI === undefined) {
|
|
|
|
|
console.log(`[${connectionId}] Rehandshake detected without SNI, allowing it through.`);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Check if the SNI has changed
|
|
|
|
|
if (newSNI !== serverName) {
|
|
|
|
|
console.log(`[${connectionId}] Rehandshake with different SNI: ${newSNI} vs original ${serverName}`);
|
|
|
|
|
|
|
|
|
|
// Allow if the new SNI matches existing domain config or find a new matching config
|
|
|
|
|
let allowed = false;
|
|
|
|
|
|
|
|
|
|
if (record.domainConfig) {
|
|
|
|
|
allowed = record.domainConfig.domains.some(d => plugins.minimatch(newSNI, d));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!allowed) {
|
|
|
|
|
const newDomainConfig = this.settings.domainConfigs.find((config) =>
|
|
|
|
|
config.domains.some((d) => plugins.minimatch(newSNI, d))
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
if (newDomainConfig) {
|
|
|
|
|
const effectiveAllowedIPs = [
|
|
|
|
|
...newDomainConfig.allowedIPs,
|
|
|
|
|
...(this.settings.defaultAllowedIPs || []),
|
|
|
|
|
];
|
|
|
|
|
const effectiveBlockedIPs = [
|
|
|
|
|
...(newDomainConfig.blockedIPs || []),
|
|
|
|
|
...(this.settings.defaultBlockedIPs || []),
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
allowed = isGlobIPAllowed(record.remoteIP, effectiveAllowedIPs, effectiveBlockedIPs);
|
|
|
|
|
|
|
|
|
|
if (allowed) {
|
|
|
|
|
record.domainConfig = newDomainConfig;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (allowed) {
|
|
|
|
|
console.log(`[${connectionId}] Updated domain for connection from ${record.remoteIP} to: ${newSNI}`);
|
|
|
|
|
record.lockedDomain = newSNI;
|
|
|
|
|
} else {
|
|
|
|
|
console.log(`[${connectionId}] Rehandshake SNI ${newSNI} not allowed. Terminating connection.`);
|
|
|
|
|
this.initiateCleanupOnce(record, 'sni_mismatch');
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
console.log(`[${connectionId}] Rehandshake with same SNI: ${newSNI}`);
|
|
|
|
|
}
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.log(`[${connectionId}] Error processing renegotiation: ${err}. Allowing to continue.`);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Now set up piping for future data and resume the socket
|
|
|
|
|
socket.pipe(targetSocket);
|
|
|
|
|
targetSocket.pipe(socket);
|
|
|
|
@ -801,7 +1073,83 @@ export class PortProxy {
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
} else {
|
|
|
|
|
// No pending data, so just set up piping
|
|
|
|
|
// Set up the renegotiation listener *before* piping if this is a TLS connection with SNI
|
|
|
|
|
if (serverName && record.isTLS) {
|
|
|
|
|
// This listener handles TLS renegotiation detection
|
|
|
|
|
socket.on('data', (renegChunk) => {
|
|
|
|
|
if (renegChunk.length > 0 && renegChunk.readUInt8(0) === 22) {
|
|
|
|
|
// Always update activity timestamp for any handshake packet
|
|
|
|
|
this.updateActivity(record);
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
// Extract all TLS information including session resumption data
|
|
|
|
|
const sniInfo = extractSNIInfo(renegChunk, this.settings.enableTlsDebugLogging);
|
|
|
|
|
let newSNI = sniInfo?.serverName;
|
|
|
|
|
|
|
|
|
|
// Handle session resumption - if we recognize the session ID, we know what domain it belongs to
|
|
|
|
|
if (sniInfo?.isResumption && sniInfo.resumedDomain) {
|
|
|
|
|
console.log(`[${connectionId}] Rehandshake with session resumption for domain: ${sniInfo.resumedDomain}`);
|
|
|
|
|
newSNI = sniInfo.resumedDomain;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// IMPORTANT: If we can't extract an SNI from renegotiation, we MUST allow it through
|
|
|
|
|
if (newSNI === undefined) {
|
|
|
|
|
console.log(`[${connectionId}] Rehandshake detected without SNI, allowing it through.`);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Check if the SNI has changed
|
|
|
|
|
if (newSNI !== serverName) {
|
|
|
|
|
console.log(`[${connectionId}] Rehandshake with different SNI: ${newSNI} vs original ${serverName}`);
|
|
|
|
|
|
|
|
|
|
// Allow if the new SNI matches existing domain config or find a new matching config
|
|
|
|
|
let allowed = false;
|
|
|
|
|
|
|
|
|
|
if (record.domainConfig) {
|
|
|
|
|
allowed = record.domainConfig.domains.some(d => plugins.minimatch(newSNI, d));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!allowed) {
|
|
|
|
|
const newDomainConfig = this.settings.domainConfigs.find((config) =>
|
|
|
|
|
config.domains.some((d) => plugins.minimatch(newSNI, d))
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
if (newDomainConfig) {
|
|
|
|
|
const effectiveAllowedIPs = [
|
|
|
|
|
...newDomainConfig.allowedIPs,
|
|
|
|
|
...(this.settings.defaultAllowedIPs || []),
|
|
|
|
|
];
|
|
|
|
|
const effectiveBlockedIPs = [
|
|
|
|
|
...(newDomainConfig.blockedIPs || []),
|
|
|
|
|
...(this.settings.defaultBlockedIPs || []),
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
allowed = isGlobIPAllowed(record.remoteIP, effectiveAllowedIPs, effectiveBlockedIPs);
|
|
|
|
|
|
|
|
|
|
if (allowed) {
|
|
|
|
|
record.domainConfig = newDomainConfig;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (allowed) {
|
|
|
|
|
console.log(`[${connectionId}] Updated domain for connection from ${record.remoteIP} to: ${newSNI}`);
|
|
|
|
|
record.lockedDomain = newSNI;
|
|
|
|
|
} else {
|
|
|
|
|
console.log(`[${connectionId}] Rehandshake SNI ${newSNI} not allowed. Terminating connection.`);
|
|
|
|
|
this.initiateCleanupOnce(record, 'sni_mismatch');
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
console.log(`[${connectionId}] Rehandshake with same SNI: ${newSNI}`);
|
|
|
|
|
}
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.log(`[${connectionId}] Error processing renegotiation: ${err}. Allowing to continue.`);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Now set up piping
|
|
|
|
|
socket.pipe(targetSocket);
|
|
|
|
|
targetSocket.pipe(socket);
|
|
|
|
|
socket.resume(); // Resume the socket after piping is established
|
|
|
|
@ -838,31 +1186,8 @@ export class PortProxy {
|
|
|
|
|
record.pendingData = [];
|
|
|
|
|
record.pendingDataSize = 0;
|
|
|
|
|
|
|
|
|
|
// Add the renegotiation listener for SNI validation
|
|
|
|
|
if (serverName) {
|
|
|
|
|
socket.on('data', (renegChunk: Buffer) => {
|
|
|
|
|
if (renegChunk.length > 0 && renegChunk.readUInt8(0) === 22) {
|
|
|
|
|
try {
|
|
|
|
|
// Try to extract SNI from potential renegotiation
|
|
|
|
|
const newSNI = extractSNI(renegChunk, this.settings.enableTlsDebugLogging);
|
|
|
|
|
if (newSNI && newSNI !== record.lockedDomain) {
|
|
|
|
|
console.log(
|
|
|
|
|
`[${connectionId}] Rehandshake detected with different SNI: ${newSNI} vs locked ${record.lockedDomain}. Terminating connection.`
|
|
|
|
|
);
|
|
|
|
|
this.initiateCleanupOnce(record, 'sni_mismatch');
|
|
|
|
|
} else if (newSNI && this.settings.enableDetailedLogging) {
|
|
|
|
|
console.log(
|
|
|
|
|
`[${connectionId}] Rehandshake detected with same SNI: ${newSNI}. Allowing.`
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.log(
|
|
|
|
|
`[${connectionId}] Error processing potential renegotiation: ${err}. Allowing connection to continue.`
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
// Renegotiation detection is now handled before piping is established
|
|
|
|
|
// This ensures the data listener receives all packets properly
|
|
|
|
|
|
|
|
|
|
// Set connection timeout with simpler logic
|
|
|
|
|
if (record.cleanupTimer) {
|
|
|
|
@ -878,12 +1203,12 @@ export class PortProxy {
|
|
|
|
|
}
|
|
|
|
|
// No cleanup timer for immortal connections
|
|
|
|
|
}
|
|
|
|
|
// For TLS keep-alive connections, use a moderately extended timeout
|
|
|
|
|
// but not too long to prevent certificate issues
|
|
|
|
|
// 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 shorter timeout for TLS connections to ensure certificate contexts are refreshed periodically
|
|
|
|
|
// This prevents issues with stale certificates in browser tabs that have been idle for a long time
|
|
|
|
|
const tlsKeepAliveTimeout = 8 * 60 * 60 * 1000; // 8 hours for TLS keep-alive - reduced from 14 days
|
|
|
|
|
// 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(() => {
|
|
|
|
@ -904,7 +1229,7 @@ export class PortProxy {
|
|
|
|
|
|
|
|
|
|
if (this.settings.enableDetailedLogging) {
|
|
|
|
|
console.log(
|
|
|
|
|
`[${connectionId}] TLS keep-alive connection with certificate refresh protection, lifetime: ${plugins.prettyMs(
|
|
|
|
|
`[${connectionId}] TLS keep-alive connection with aggressive certificate refresh protection, lifetime: ${plugins.prettyMs(
|
|
|
|
|
tlsKeepAliveTimeout
|
|
|
|
|
)}`
|
|
|
|
|
);
|
|
|
|
@ -1054,15 +1379,41 @@ export class PortProxy {
|
|
|
|
|
// 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) {
|
|
|
|
|
if (timeDiff > 4 * 60 * 60 * 1000) {
|
|
|
|
|
// If inactive for more than 4 hours
|
|
|
|
|
// 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
|
|
|
|
|
// For shorter inactivity periods, try to refresh the TLS state normally
|
|
|
|
|
this.refreshTlsStateAfterSleep(record);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
@ -1098,12 +1449,12 @@ export class PortProxy {
|
|
|
|
|
const connectionAge = Date.now() - record.incomingStartTime;
|
|
|
|
|
const hourInMs = 60 * 60 * 1000;
|
|
|
|
|
|
|
|
|
|
// For TLS browser connections that are very old, it's better to force a new connection
|
|
|
|
|
// rather than trying to refresh the state, to avoid certificate issues
|
|
|
|
|
if (record.isTLS && record.hasKeepAlive && connectionAge > 12 * hourInMs) {
|
|
|
|
|
// 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.`
|
|
|
|
|
`Closing to ensure proper certificate handling on browser reconnect in proxy chain.`
|
|
|
|
|
);
|
|
|
|
|
return this.initiateCleanupOnce(record, 'certificate_context_refresh');
|
|
|
|
|
}
|
|
|
|
@ -1566,6 +1917,12 @@ export class PortProxy {
|
|
|
|
|
|
|
|
|
|
// Save domain config in connection record
|
|
|
|
|
connectionRecord.domainConfig = domainConfig;
|
|
|
|
|
|
|
|
|
|
// Always set the lockedDomain, even for non-SNI connections
|
|
|
|
|
if (serverName) {
|
|
|
|
|
connectionRecord.lockedDomain = serverName;
|
|
|
|
|
console.log(`[${connectionId}] Locked connection to domain: ${serverName}`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// IP validation is skipped if allowedIPs is empty
|
|
|
|
|
if (domainConfig) {
|
|
|
|
@ -1734,7 +2091,17 @@ export class PortProxy {
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
serverName = extractSNI(chunk, this.settings.enableTlsDebugLogging) || '';
|
|
|
|
|
// Extract all TLS information including session resumption
|
|
|
|
|
const sniInfo = extractSNIInfo(chunk, this.settings.enableTlsDebugLogging);
|
|
|
|
|
|
|
|
|
|
if (sniInfo?.isResumption && sniInfo.resumedDomain) {
|
|
|
|
|
// This is a session resumption with a known domain
|
|
|
|
|
serverName = sniInfo.resumedDomain;
|
|
|
|
|
console.log(`[${connectionId}] TLS Session resumption detected for domain: ${serverName}`);
|
|
|
|
|
} else {
|
|
|
|
|
// Normal SNI extraction
|
|
|
|
|
serverName = sniInfo?.serverName || '';
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Lock the connection to the negotiated SNI.
|
|
|
|
@ -2050,6 +2417,9 @@ export class PortProxy {
|
|
|
|
|
public async stop() {
|
|
|
|
|
console.log('PortProxy shutting down...');
|
|
|
|
|
this.isShuttingDown = true;
|
|
|
|
|
|
|
|
|
|
// Stop the session cleanup timer
|
|
|
|
|
stopSessionCleanupTimer();
|
|
|
|
|
|
|
|
|
|
// Stop accepting new connections
|
|
|
|
|
const closeServerPromises: Promise<void>[] = this.netServers.map(
|
|
|
|
|