Compare commits
30 Commits
Author | SHA1 | Date | |
---|---|---|---|
3593e411cf | |||
ca6f6de798 | |||
80d2f30804 | |||
22f46700f1 | |||
1611f65455 | |||
c6350e271a | |||
0fb5e5ea50 | |||
35f6739b3c | |||
4634c68ea6 | |||
e126032b61 | |||
7797c799dd | |||
e8639e1b01 | |||
60a0ad106d | |||
a70c123007 | |||
46aa7620b0 | |||
f72db86e37 | |||
d612df107e | |||
1c34578c36 | |||
1f9943b5a7 | |||
67ddf97547 | |||
8a96b45ece | |||
2b6464acd5 | |||
efbb4335d7 | |||
9dd402054d | |||
6c1efc1dc0 | |||
cad0e6a2b2 | |||
794e1292e5 | |||
ee79f9ab7c | |||
107bc3b50b | |||
97982976c8 |
101
changelog.md
101
changelog.md
@ -1,5 +1,106 @@
|
||||
# Changelog
|
||||
|
||||
## 2025-03-17 - 4.1.16 - fix(tls)
|
||||
Improve TLS alert handling in connection handler: use the new TlsAlert class to send proper unrecognized_name alerts when a ClientHello is missing SNI and wait for a retry on the same connection before closing. Also, add alertFallbackTimeout tracking to connection records for better timeout management.
|
||||
|
||||
- Replaced hardcoded alert buffers in ConnectionHandler with calls to the TlsAlert class.
|
||||
- Removed old warnings and implemented a mechanism to remove existing 'data' listeners and await a new ClientHello.
|
||||
- Introduced alertFallbackTimeout property in connection records to track fallback timeout and ensure proper cleanup.
|
||||
- Extended the delay before closing the connection after sending an alert, providing the client more time to retry.
|
||||
|
||||
## 2025-03-17 - 4.1.15 - fix(connectionhandler)
|
||||
Delay socket termination in TLS session resumption handling to allow proper alert processing
|
||||
|
||||
- Removed the immediate socket.end() call in finishConnection and moved it inside the setTimeout, ensuring that clients (especially Chrome) have additional time to process the TLS alert before connection termination
|
||||
- This prevents premature socket closure on ClientHello without SNI when session tickets are disallowed
|
||||
|
||||
## 2025-03-17 - 4.1.14 - fix(ConnectionHandler)
|
||||
Use the correct TLS alert data and increase the delay before socket termination when session resumption without SNI is detected.
|
||||
|
||||
- Replaced certificateExpiredAlert with serverNameUnknownAlertData for sending the appropriate alert.
|
||||
- Increased the cleanup delay from 1000ms to 5000ms to allow a more graceful termination.
|
||||
|
||||
## 2025-03-17 - 4.1.13 - fix(tls-handshake)
|
||||
Set certificate_expired TLS alert level to warning instead of fatal to allow graceful termination.
|
||||
|
||||
- In the TLS handshake alert for certificate_expired (0x2F), changed the alert level from 0x02 (fatal) to 0x01 (warning).
|
||||
- This change avoids abrupt connection termination, enabling a smoother handling of certificate expiration alerts.
|
||||
|
||||
## 2025-03-17 - 4.1.12 - fix(classes.pp.connectionhandler)
|
||||
Replace unrecognized_name alert data with certificate_expired alert in TLS handshake handling for session resumption without SNI
|
||||
|
||||
- Switched the alert payload from serverNameUnknownAlertData to a new certificateExpiredAlert buffer
|
||||
- Now sends a fatal certificate_expired alert (code 47) instead of a warning unrecognized_name alert
|
||||
- Improves TLS error reporting and encourages immediate disconnection when a ClientHello lacks SNI and session tickets are disallowed
|
||||
|
||||
## 2025-03-17 - 4.1.11 - fix(connectionhandler)
|
||||
Increase delay before cleaning up connections when session resumption is blocked due to missing SNI, allowing more natural socket termination.
|
||||
|
||||
- Changed cleanup delay in ts/classes.pp.connectionhandler.ts from 300ms to 1000ms.
|
||||
- This fix ensures that sockets get sufficient time to terminate gracefully.
|
||||
|
||||
## 2025-03-16 - 4.1.10 - fix(connectionhandler)
|
||||
Increase delay timings for TLS alert transmission in session ticket blocking to allow graceful socket termination
|
||||
|
||||
- Updated finishConnection: replaced immediate socket.destroy with a graceful end call
|
||||
- Increased delay after successful write from 50ms to 200ms to allow alert processing
|
||||
- Raised safety timeout from 250ms to 400ms when waiting for 'drain' event
|
||||
|
||||
## 2025-03-16 - 4.1.9 - fix(ConnectionHandler)
|
||||
Replace closeNotify alert with handshake failure alert in TLS ClientHello handling to properly signal missing SNI and enforce session ticket restrictions.
|
||||
|
||||
- Switched alert data sent on missing SNI from closeNotifyAlert to sslHandshakeFailureAlertData.
|
||||
- Ensures consistent TLS alert behavior during handshake failure.
|
||||
|
||||
## 2025-03-16 - 4.1.8 - fix(ConnectionHandler/tls)
|
||||
Change the TLS alert sent when a ClientHello lacks SNI: use the close_notify alert instead of handshake_failure to prompt immediate retry with SNI.
|
||||
|
||||
- Replaced the previously sent handshake_failure alert (code 0x28) with a close_notify alert (code 0x00) in the TLS session resumption handling in ConnectionHandler.
|
||||
- This change encourages clients to immediately retry and include SNI when allowSessionTicket is false.
|
||||
|
||||
## 2025-03-16 - 4.1.7 - fix(classes.pp.connectionhandler)
|
||||
Improve TLS alert handling in ClientHello when SNI is missing and session tickets are disallowed
|
||||
|
||||
- Replace the unrecognized_name alert with a handshake_failure alert to ensure better client behavior.
|
||||
- Refactor the alert sending mechanism using cork/uncork and add a safety timeout for the drain event.
|
||||
- Enhance logging for debugging TLS handshake failures when SNI is absent.
|
||||
|
||||
## 2025-03-16 - 4.1.6 - fix(tls)
|
||||
Refine TLS ClientHello handling when allowSessionTicket is false by replacing extensive alert timeout logic with a concise warning alert and short delay, encouraging immediate client retry with proper SNI
|
||||
|
||||
- Update the TLS alert sending mechanism to use cork/uncork and a short, fixed delay instead of long timeouts
|
||||
- Remove redundant event listeners and excessive cleanup logic after sending the alert
|
||||
- Improve code clarity and encourage clients (e.g., Chrome) to retry handshake with SNI more responsively
|
||||
|
||||
## 2025-03-16 - 4.1.5 - fix(TLS/ConnectionHandler)
|
||||
Improve handling of TLS session resumption without SNI by sending an 'unrecognized_name' alert instead of immediately terminating the connection. This change adds a grace period for the client to retry the handshake with proper SNI and cleans up the connection if no valid response is received.
|
||||
|
||||
- Send a TLS warning (unrecognized_name alert, code 112) when a ClientHello is received without SNI and session tickets are disallowed.
|
||||
- Utilize socket cork/uncork to ensure the alert is sent as a single packet.
|
||||
- Add a 5-second alert timeout and a subsequent 30-second grace period to allow clients to initiate a new handshake with SNI.
|
||||
- Clean up and terminate the connection if no valid SNI is provided after the grace period, logging appropriate termination reasons.
|
||||
|
||||
## 2025-03-15 - 4.1.4 - fix(ConnectionHandler)
|
||||
Refactor ConnectionHandler code formatting for improved readability and consistency in log messages and whitespace handling
|
||||
|
||||
- Standardized indentation and spacing in method signatures and log statements
|
||||
- Aligned inline comments and string concatenations for clarity
|
||||
- Minor refactoring of parameter formatting without changing functionality
|
||||
|
||||
## 2025-03-15 - 4.1.3 - fix(connectionhandler)
|
||||
Improve handling of TLS ClientHello messages when allowSessionTicket is disabled and no SNI is provided by sending a warning alert (unrecognized_name, code 0x70) with a proper callback and delay to ensure the alert is transmitted before closing the connection.
|
||||
|
||||
- Replace the fatal alert (0x02/0x40) with a warning alert (0x01/0x70) to notify clients to send SNI.
|
||||
- Use socket.write callback to wait 100ms after sending the alert before terminating the connection.
|
||||
- Remove the previous short (50ms) delay in favor of a more reliable delay mechanism before cleanup.
|
||||
|
||||
## 2025-03-15 - 4.1.2 - fix(connectionhandler)
|
||||
Send proper TLS alert before terminating connections when SNI is missing and session tickets are disallowed.
|
||||
|
||||
- Added logic to transmit a fatal TLS alert (Handshake Failure) before closing the connection when no SNI is present with allowSessionTicket=false.
|
||||
- Introduced a slight 50ms delay after sending the alert to ensure the client receives the alert properly.
|
||||
- Applied these changes both for the initial ClientHello and when handling subsequent TLS data.
|
||||
|
||||
## 2025-03-15 - 4.1.1 - fix(tls)
|
||||
Enforce strict SNI handling in TLS connections by terminating ClientHello messages lacking SNI when session tickets are disallowed and removing legacy session cache code.
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@push.rocks/smartproxy",
|
||||
"version": "4.1.1",
|
||||
"version": "4.1.16",
|
||||
"private": false,
|
||||
"description": "A powerful proxy package that effectively handles high traffic, with features such as SSL/TLS support, port proxying, WebSocket handling, dynamic routing with authentication options, and automatic ACME certificate management.",
|
||||
"main": "dist_ts/index.js",
|
||||
|
@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartproxy',
|
||||
version: '4.1.1',
|
||||
version: '4.1.16',
|
||||
description: 'A powerful proxy package that effectively handles high traffic, with features such as SSL/TLS support, port proxying, WebSocket handling, dynamic routing with authentication options, and automatic ACME certificate management.'
|
||||
}
|
||||
|
@ -1,5 +1,9 @@
|
||||
import * as plugins from './plugins.js';
|
||||
import type { IConnectionRecord, IDomainConfig, IPortProxySettings } from './classes.pp.interfaces.js';
|
||||
import type {
|
||||
IConnectionRecord,
|
||||
IDomainConfig,
|
||||
IPortProxySettings,
|
||||
} from './classes.pp.interfaces.js';
|
||||
import { ConnectionManager } from './classes.pp.connectionmanager.js';
|
||||
import { SecurityManager } from './classes.pp.securitymanager.js';
|
||||
import { DomainConfigManager } from './classes.pp.domainconfigmanager.js';
|
||||
@ -7,6 +11,7 @@ import { TlsManager } from './classes.pp.tlsmanager.js';
|
||||
import { NetworkProxyBridge } from './classes.pp.networkproxybridge.js';
|
||||
import { TimeoutManager } from './classes.pp.timeoutmanager.js';
|
||||
import { PortRangeManager } from './classes.pp.portrangemanager.js';
|
||||
import { TlsAlert } from './classes.pp.tlsalert.js';
|
||||
|
||||
/**
|
||||
* Handles new connection processing and setup logic
|
||||
@ -73,8 +78,8 @@ export class ConnectionHandler {
|
||||
if (this.settings.enableDetailedLogging) {
|
||||
console.log(
|
||||
`[${connectionId}] New connection from ${remoteIP} on port ${localPort}. ` +
|
||||
`Keep-Alive: ${record.hasKeepAlive ? 'Enabled' : 'Disabled'}. ` +
|
||||
`Active connections: ${this.connectionManager.getConnectionCount()}`
|
||||
`Keep-Alive: ${record.hasKeepAlive ? 'Enabled' : 'Disabled'}. ` +
|
||||
`Active connections: ${this.connectionManager.getConnectionCount()}`
|
||||
);
|
||||
} else {
|
||||
console.log(
|
||||
@ -94,7 +99,10 @@ export class ConnectionHandler {
|
||||
/**
|
||||
* Handle a connection that should be forwarded to NetworkProxy
|
||||
*/
|
||||
private handleNetworkProxyConnection(socket: plugins.net.Socket, record: IConnectionRecord): void {
|
||||
private handleNetworkProxyConnection(
|
||||
socket: plugins.net.Socket,
|
||||
record: IConnectionRecord
|
||||
): void {
|
||||
const connectionId = record.id;
|
||||
let initialDataReceived = false;
|
||||
|
||||
@ -104,7 +112,7 @@ export class ConnectionHandler {
|
||||
console.log(
|
||||
`[${connectionId}] Initial data warning (${this.settings.initialDataTimeout}ms) for connection from ${record.remoteIP}`
|
||||
);
|
||||
|
||||
|
||||
// Add a grace period instead of immediate termination
|
||||
setTimeout(() => {
|
||||
if (!initialDataReceived) {
|
||||
@ -144,7 +152,7 @@ export class ConnectionHandler {
|
||||
if (!this.tlsManager.isTlsHandshake(chunk) && localPort === 443) {
|
||||
console.log(
|
||||
`[${connectionId}] Non-TLS connection detected on port 443. ` +
|
||||
`Terminating connection - only TLS traffic is allowed on standard HTTPS port.`
|
||||
`Terminating connection - only TLS traffic is allowed on standard HTTPS port.`
|
||||
);
|
||||
if (record.incomingTerminationReason === null) {
|
||||
record.incomingTerminationReason = 'non_tls_blocked';
|
||||
@ -159,8 +167,8 @@ export class ConnectionHandler {
|
||||
if (this.tlsManager.isTlsHandshake(chunk)) {
|
||||
record.isTLS = true;
|
||||
|
||||
// Check session tickets if they're disabled
|
||||
if (this.settings.allowSessionTicket === false && this.tlsManager.isClientHello(chunk)) {
|
||||
// Check for ClientHello to extract SNI - but don't enforce it for NetworkProxy
|
||||
if (this.tlsManager.isClientHello(chunk)) {
|
||||
// Create connection info for SNI extraction
|
||||
const connInfo = {
|
||||
sourceIp: record.remoteIP,
|
||||
@ -169,49 +177,46 @@ export class ConnectionHandler {
|
||||
destPort: socket.localPort || 0,
|
||||
};
|
||||
|
||||
// Extract SNI for domain-specific NetworkProxy handling
|
||||
// Extract SNI for domain-specific NetworkProxy handling if available
|
||||
const serverName = this.tlsManager.extractSNI(chunk, connInfo);
|
||||
|
||||
// If allowSessionTicket is false and we can't determine SNI, terminate the connection
|
||||
if (!serverName) {
|
||||
console.log(
|
||||
`[${connectionId}] No SNI detected in ClientHello and allowSessionTicket=false. ` +
|
||||
`Terminating connection to force new TLS handshake with SNI.`
|
||||
);
|
||||
if (record.incomingTerminationReason === null) {
|
||||
record.incomingTerminationReason = 'session_ticket_blocked_no_sni';
|
||||
this.connectionManager.incrementTerminationStat('incoming', 'session_ticket_blocked_no_sni');
|
||||
}
|
||||
socket.end();
|
||||
this.connectionManager.cleanupConnection(record, 'session_ticket_blocked_no_sni');
|
||||
return;
|
||||
}
|
||||
// For NetworkProxy connections, we'll allow session tickets even without SNI
|
||||
// We'll only use the serverName if available to determine the specific NetworkProxy port
|
||||
if (serverName) {
|
||||
// Save domain config and SNI in connection record
|
||||
const domainConfig = this.domainConfigManager.findDomainConfig(serverName);
|
||||
record.domainConfig = domainConfig;
|
||||
record.lockedDomain = serverName;
|
||||
|
||||
// Save domain config and SNI in connection record
|
||||
const domainConfig = this.domainConfigManager.findDomainConfig(serverName);
|
||||
record.domainConfig = domainConfig;
|
||||
record.lockedDomain = serverName;
|
||||
// Use domain-specific NetworkProxy port if configured
|
||||
if (domainConfig && this.domainConfigManager.shouldUseNetworkProxy(domainConfig)) {
|
||||
const networkProxyPort = this.domainConfigManager.getNetworkProxyPort(domainConfig);
|
||||
|
||||
// Use domain-specific NetworkProxy port if configured
|
||||
if (domainConfig && this.domainConfigManager.shouldUseNetworkProxy(domainConfig)) {
|
||||
const networkProxyPort = this.domainConfigManager.getNetworkProxyPort(domainConfig);
|
||||
if (this.settings.enableDetailedLogging) {
|
||||
console.log(
|
||||
`[${connectionId}] Using domain-specific NetworkProxy for ${serverName} on port ${networkProxyPort}`
|
||||
);
|
||||
}
|
||||
|
||||
if (this.settings.enableDetailedLogging) {
|
||||
console.log(
|
||||
`[${connectionId}] Using domain-specific NetworkProxy for ${serverName} on port ${networkProxyPort}`
|
||||
// Forward to NetworkProxy with domain-specific port
|
||||
this.networkProxyBridge.forwardToNetworkProxy(
|
||||
connectionId,
|
||||
socket,
|
||||
record,
|
||||
chunk,
|
||||
networkProxyPort,
|
||||
(reason) => this.connectionManager.initiateCleanupOnce(record, reason)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Forward to NetworkProxy with domain-specific port
|
||||
this.networkProxyBridge.forwardToNetworkProxy(
|
||||
connectionId,
|
||||
socket,
|
||||
record,
|
||||
chunk,
|
||||
networkProxyPort,
|
||||
(reason) => this.connectionManager.initiateCleanupOnce(record, reason)
|
||||
} else if (
|
||||
this.settings.allowSessionTicket === false &&
|
||||
this.settings.enableDetailedLogging
|
||||
) {
|
||||
// Log that we're allowing a session resumption without SNI for NetworkProxy
|
||||
console.log(
|
||||
`[${connectionId}] Allowing session resumption without SNI for NetworkProxy forwarding`
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@ -226,14 +231,10 @@ export class ConnectionHandler {
|
||||
);
|
||||
} else {
|
||||
// If not TLS, use normal direct connection
|
||||
console.log(`[${connectionId}] Non-TLS connection on NetworkProxy port ${record.localPort}`);
|
||||
this.setupDirectConnection(
|
||||
socket,
|
||||
record,
|
||||
undefined,
|
||||
undefined,
|
||||
chunk
|
||||
console.log(
|
||||
`[${connectionId}] Non-TLS connection on NetworkProxy port ${record.localPort}`
|
||||
);
|
||||
this.setupDirectConnection(socket, record, undefined, undefined, chunk);
|
||||
}
|
||||
});
|
||||
}
|
||||
@ -266,7 +267,7 @@ export class ConnectionHandler {
|
||||
console.log(
|
||||
`[${connectionId}] Initial data warning (${this.settings.initialDataTimeout}ms) for connection from ${record.remoteIP}`
|
||||
);
|
||||
|
||||
|
||||
// Add a grace period instead of immediate termination
|
||||
setTimeout(() => {
|
||||
if (!initialDataReceived) {
|
||||
@ -351,14 +352,13 @@ export class ConnectionHandler {
|
||||
record.domainConfig = domainConfig;
|
||||
|
||||
// Check if this domain should use NetworkProxy (domain-specific setting)
|
||||
if (domainConfig &&
|
||||
this.domainConfigManager.shouldUseNetworkProxy(domainConfig) &&
|
||||
this.networkProxyBridge.getNetworkProxy()) {
|
||||
|
||||
if (
|
||||
domainConfig &&
|
||||
this.domainConfigManager.shouldUseNetworkProxy(domainConfig) &&
|
||||
this.networkProxyBridge.getNetworkProxy()
|
||||
) {
|
||||
if (this.settings.enableDetailedLogging) {
|
||||
console.log(
|
||||
`[${connectionId}] Domain ${serverName} is configured to use NetworkProxy`
|
||||
);
|
||||
console.log(`[${connectionId}] Domain ${serverName} is configured to use NetworkProxy`);
|
||||
}
|
||||
|
||||
const networkProxyPort = this.domainConfigManager.getNetworkProxyPort(domainConfig);
|
||||
@ -380,23 +380,24 @@ export class ConnectionHandler {
|
||||
// IP validation
|
||||
if (domainConfig) {
|
||||
const ipRules = this.domainConfigManager.getEffectiveIPRules(domainConfig);
|
||||
|
||||
|
||||
// Skip IP validation if allowedIPs is empty
|
||||
if (
|
||||
domainConfig.allowedIPs.length > 0 &&
|
||||
!this.securityManager.isIPAuthorized(record.remoteIP, ipRules.allowedIPs, ipRules.blockedIPs)
|
||||
!this.securityManager.isIPAuthorized(
|
||||
record.remoteIP,
|
||||
ipRules.allowedIPs,
|
||||
ipRules.blockedIPs
|
||||
)
|
||||
) {
|
||||
return rejectIncomingConnection(
|
||||
'rejected',
|
||||
`Connection rejected: IP ${record.remoteIP} not allowed for domain ${domainConfig.domains.join(
|
||||
', '
|
||||
)}`
|
||||
`Connection rejected: IP ${
|
||||
record.remoteIP
|
||||
} not allowed for domain ${domainConfig.domains.join(', ')}`
|
||||
);
|
||||
}
|
||||
} else if (
|
||||
this.settings.defaultAllowedIPs &&
|
||||
this.settings.defaultAllowedIPs.length > 0
|
||||
) {
|
||||
} else if (this.settings.defaultAllowedIPs && this.settings.defaultAllowedIPs.length > 0) {
|
||||
if (
|
||||
!this.securityManager.isIPAuthorized(
|
||||
record.remoteIP,
|
||||
@ -463,28 +464,36 @@ export class ConnectionHandler {
|
||||
} else {
|
||||
// Attempt to find a matching forced domain config based on the local port.
|
||||
const forcedDomain = this.domainConfigManager.findDomainConfigForPort(localPort);
|
||||
|
||||
|
||||
if (forcedDomain) {
|
||||
const ipRules = this.domainConfigManager.getEffectiveIPRules(forcedDomain);
|
||||
|
||||
if (!this.securityManager.isIPAuthorized(record.remoteIP, ipRules.allowedIPs, ipRules.blockedIPs)) {
|
||||
|
||||
if (
|
||||
!this.securityManager.isIPAuthorized(
|
||||
record.remoteIP,
|
||||
ipRules.allowedIPs,
|
||||
ipRules.blockedIPs
|
||||
)
|
||||
) {
|
||||
console.log(
|
||||
`[${connectionId}] Connection from ${record.remoteIP} rejected: IP not allowed for domain ${forcedDomain.domains.join(
|
||||
`[${connectionId}] Connection from ${
|
||||
record.remoteIP
|
||||
} rejected: IP not allowed for domain ${forcedDomain.domains.join(
|
||||
', '
|
||||
)} on port ${localPort}.`
|
||||
);
|
||||
socket.end();
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (this.settings.enableDetailedLogging) {
|
||||
console.log(
|
||||
`[${connectionId}] Port-based connection from ${record.remoteIP} on port ${localPort} matched domain ${forcedDomain.domains.join(
|
||||
', '
|
||||
)}.`
|
||||
`[${connectionId}] Port-based connection from ${
|
||||
record.remoteIP
|
||||
} on port ${localPort} matched domain ${forcedDomain.domains.join(', ')}.`
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
setupConnection('', undefined, forcedDomain, localPort);
|
||||
return;
|
||||
}
|
||||
@ -502,14 +511,14 @@ export class ConnectionHandler {
|
||||
clearTimeout(initialTimeout);
|
||||
initialTimeout = null;
|
||||
}
|
||||
|
||||
|
||||
initialDataReceived = true;
|
||||
|
||||
|
||||
// Block non-TLS connections on port 443
|
||||
if (!this.tlsManager.isTlsHandshake(chunk) && localPort === 443) {
|
||||
console.log(
|
||||
`[${connectionId}] Non-TLS connection detected on port 443 in SNI handler. ` +
|
||||
`Terminating connection - only TLS traffic is allowed on standard HTTPS port.`
|
||||
`Terminating connection - only TLS traffic is allowed on standard HTTPS port.`
|
||||
);
|
||||
if (record.incomingTerminationReason === null) {
|
||||
record.incomingTerminationReason = 'non_tls_blocked';
|
||||
@ -542,38 +551,144 @@ export class ConnectionHandler {
|
||||
|
||||
// Extract SNI
|
||||
serverName = this.tlsManager.extractSNI(chunk, connInfo) || '';
|
||||
|
||||
|
||||
// If allowSessionTicket is false and this is a ClientHello with no SNI, terminate the connection
|
||||
if (this.settings.allowSessionTicket === false &&
|
||||
this.tlsManager.isClientHello(chunk) &&
|
||||
!serverName) {
|
||||
|
||||
// Check if this is a session resumption
|
||||
const resumptionInfo = this.tlsManager.handleSessionResumption(
|
||||
chunk,
|
||||
connectionId,
|
||||
false // No SNI
|
||||
if (
|
||||
this.settings.allowSessionTicket === false &&
|
||||
this.tlsManager.isClientHello(chunk) &&
|
||||
!serverName
|
||||
) {
|
||||
// Block ClientHello without SNI when allowSessionTicket is false
|
||||
console.log(
|
||||
`[${connectionId}] No SNI detected in ClientHello and allowSessionTicket=false. ` +
|
||||
`Sending unrecognized_name alert to encourage immediate retry with SNI on same connection.`
|
||||
);
|
||||
|
||||
if (resumptionInfo.shouldBlock) {
|
||||
|
||||
try {
|
||||
// Send the alert but do NOT end the connection
|
||||
// Using our new TlsAlert class for better alert management
|
||||
socket.cork();
|
||||
socket.write(TlsAlert.alerts.unrecognizedName);
|
||||
socket.uncork();
|
||||
|
||||
console.log(
|
||||
`[${connectionId}] Session resumption without SNI detected and allowSessionTicket=false. ` +
|
||||
`Terminating connection to force new TLS handshake with SNI.`
|
||||
`[${connectionId}] Alert sent, waiting for new ClientHello on same connection...`
|
||||
);
|
||||
if (record.incomingTerminationReason === null) {
|
||||
record.incomingTerminationReason = resumptionInfo.reason || 'session_ticket_blocked_no_sni';
|
||||
this.connectionManager.incrementTerminationStat(
|
||||
'incoming',
|
||||
resumptionInfo.reason || 'session_ticket_blocked_no_sni'
|
||||
);
|
||||
|
||||
// Remove existing data listener and wait for a new ClientHello
|
||||
socket.removeAllListeners('data');
|
||||
|
||||
// Set up a new data handler to capture the next message
|
||||
socket.once('data', (retryChunk) => {
|
||||
// Cancel the fallback timeout as we received data
|
||||
if (record.alertFallbackTimeout) {
|
||||
clearTimeout(record.alertFallbackTimeout);
|
||||
record.alertFallbackTimeout = null;
|
||||
}
|
||||
|
||||
// Check if this is a new ClientHello
|
||||
if (this.tlsManager.isClientHello(retryChunk)) {
|
||||
console.log(`[${connectionId}] Received new ClientHello after alert`);
|
||||
|
||||
// Extract SNI from the new ClientHello
|
||||
const newServerName = this.tlsManager.extractSNI(retryChunk, connInfo) || '';
|
||||
|
||||
if (newServerName) {
|
||||
console.log(`[${connectionId}] New ClientHello contains SNI: ${newServerName}`);
|
||||
|
||||
// Update the record with the new SNI
|
||||
record.lockedDomain = newServerName;
|
||||
|
||||
// Continue with normal connection setup using the new chunk with SNI
|
||||
setupConnection(newServerName, retryChunk);
|
||||
} else {
|
||||
console.log(
|
||||
`[${connectionId}] New ClientHello still missing SNI, closing connection`
|
||||
);
|
||||
|
||||
// If still no SNI after retry, now we can close the connection
|
||||
if (record.incomingTerminationReason === null) {
|
||||
record.incomingTerminationReason = 'session_ticket_blocked_no_sni';
|
||||
this.connectionManager.incrementTerminationStat(
|
||||
'incoming',
|
||||
'session_ticket_blocked_no_sni'
|
||||
);
|
||||
}
|
||||
|
||||
// Send a close_notify alert before ending the connection
|
||||
TlsAlert.sendCloseNotify(socket)
|
||||
.catch((err) => {
|
||||
console.log(`[${connectionId}] Error sending close_notify: ${err.message}`);
|
||||
})
|
||||
.finally(() => {
|
||||
// Clean up even if sending the alert fails
|
||||
this.connectionManager.cleanupConnection(
|
||||
record,
|
||||
'session_ticket_blocked_no_sni'
|
||||
);
|
||||
});
|
||||
}
|
||||
} else {
|
||||
console.log(
|
||||
`[${connectionId}] Received non-ClientHello data after alert, closing connection`
|
||||
);
|
||||
|
||||
// If we got something other than a ClientHello, close the connection
|
||||
if (record.incomingTerminationReason === null) {
|
||||
record.incomingTerminationReason = 'invalid_protocol';
|
||||
this.connectionManager.incrementTerminationStat('incoming', 'invalid_protocol');
|
||||
}
|
||||
|
||||
// Send a protocol_version alert before ending the connection
|
||||
TlsAlert.send(socket, TlsAlert.LEVEL_FATAL, TlsAlert.PROTOCOL_VERSION, true)
|
||||
.catch((err) => {
|
||||
console.log(
|
||||
`[${connectionId}] Error sending protocol_version alert: ${err.message}`
|
||||
);
|
||||
})
|
||||
.finally(() => {
|
||||
// Clean up even if sending the alert fails
|
||||
this.connectionManager.cleanupConnection(record, 'invalid_protocol');
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Set a fallback timeout in case the client doesn't respond
|
||||
const fallbackTimeout = setTimeout(() => {
|
||||
console.log(`[${connectionId}] No response after alert, closing connection`);
|
||||
|
||||
if (record.incomingTerminationReason === null) {
|
||||
record.incomingTerminationReason = 'alert_timeout';
|
||||
this.connectionManager.incrementTerminationStat('incoming', 'alert_timeout');
|
||||
}
|
||||
|
||||
// Send a close_notify alert before ending the connection
|
||||
TlsAlert.sendCloseNotify(socket)
|
||||
.catch((err) => {
|
||||
console.log(`[${connectionId}] Error sending close_notify: ${err.message}`);
|
||||
})
|
||||
.finally(() => {
|
||||
// Clean up even if sending the alert fails
|
||||
this.connectionManager.cleanupConnection(record, 'alert_timeout');
|
||||
});
|
||||
}, 10000); // 10 second timeout
|
||||
|
||||
// Make sure the timeout doesn't keep the process alive
|
||||
if (fallbackTimeout.unref) {
|
||||
fallbackTimeout.unref();
|
||||
}
|
||||
|
||||
// Store the timeout in the record so it can be cleared during cleanup
|
||||
record.alertFallbackTimeout = fallbackTimeout;
|
||||
} catch (err) {
|
||||
// If we can't send the alert, fall back to immediate termination
|
||||
console.log(`[${connectionId}] Error sending TLS alert: ${err.message}`);
|
||||
socket.end();
|
||||
this.connectionManager.cleanupConnection(
|
||||
record,
|
||||
resumptionInfo.reason || 'session_ticket_blocked_no_sni'
|
||||
);
|
||||
return;
|
||||
this.connectionManager.cleanupConnection(record, 'session_ticket_blocked_no_sni');
|
||||
}
|
||||
|
||||
// Return early to prevent the normal flow
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@ -621,23 +736,21 @@ export class ConnectionHandler {
|
||||
overridePort?: number
|
||||
): void {
|
||||
const connectionId = record.id;
|
||||
|
||||
|
||||
// Determine target host
|
||||
const targetHost = domainConfig
|
||||
? this.domainConfigManager.getTargetIP(domainConfig)
|
||||
const targetHost = domainConfig
|
||||
? this.domainConfigManager.getTargetIP(domainConfig)
|
||||
: this.settings.targetIP!;
|
||||
|
||||
|
||||
// Determine target port
|
||||
const targetPort = overridePort !== undefined
|
||||
? overridePort
|
||||
: this.settings.toPort;
|
||||
|
||||
const targetPort = overridePort !== undefined ? overridePort : this.settings.toPort;
|
||||
|
||||
// Setup connection options
|
||||
const connectionOptions: plugins.net.NetConnectOpts = {
|
||||
host: targetHost,
|
||||
port: targetPort,
|
||||
};
|
||||
|
||||
|
||||
// Preserve source IP if configured
|
||||
if (this.settings.preserveSourceIP) {
|
||||
connectionOptions.localAddress = record.remoteIP.replace('::ffff:', '');
|
||||
@ -894,18 +1007,20 @@ export class ConnectionHandler {
|
||||
|
||||
// Process any remaining data in the queue before switching to piping
|
||||
processDataQueue();
|
||||
|
||||
|
||||
// Set up piping immediately
|
||||
pipingEstablished = true;
|
||||
|
||||
|
||||
// Flush all pending data to target
|
||||
if (record.pendingData.length > 0) {
|
||||
const combinedData = Buffer.concat(record.pendingData);
|
||||
|
||||
|
||||
if (this.settings.enableDetailedLogging) {
|
||||
console.log(`[${connectionId}] Forwarding ${combinedData.length} bytes of initial data to target`);
|
||||
console.log(
|
||||
`[${connectionId}] Forwarding ${combinedData.length} bytes of initial data to target`
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
// Write pending data immediately
|
||||
targetSocket.write(combinedData, (err) => {
|
||||
if (err) {
|
||||
@ -913,19 +1028,19 @@ export class ConnectionHandler {
|
||||
return this.connectionManager.initiateCleanupOnce(record, 'write_error');
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
// Clear the buffer now that we've processed it
|
||||
record.pendingData = [];
|
||||
record.pendingDataSize = 0;
|
||||
}
|
||||
|
||||
|
||||
// Setup piping in both directions without any delays
|
||||
socket.pipe(targetSocket);
|
||||
targetSocket.pipe(socket);
|
||||
|
||||
|
||||
// Resume the socket to ensure data flows
|
||||
socket.resume();
|
||||
|
||||
|
||||
// Process any data that might be queued in the interim
|
||||
if (dataQueue.length > 0) {
|
||||
// Write any remaining queued data directly to the target socket
|
||||
@ -936,7 +1051,7 @@ export class ConnectionHandler {
|
||||
dataQueue.length = 0;
|
||||
queueSize = 0;
|
||||
}
|
||||
|
||||
|
||||
if (this.settings.enableDetailedLogging) {
|
||||
console.log(
|
||||
`[${connectionId}] Connection established: ${record.remoteIP} -> ${targetHost}:${connectionOptions.port}` +
|
||||
@ -1001,15 +1116,12 @@ export class ConnectionHandler {
|
||||
}
|
||||
|
||||
// Set connection timeout
|
||||
record.cleanupTimer = this.timeoutManager.setupConnectionTimeout(
|
||||
record,
|
||||
(record, reason) => {
|
||||
console.log(
|
||||
`[${connectionId}] Connection from ${record.remoteIP} exceeded max lifetime, forcing cleanup.`
|
||||
);
|
||||
this.connectionManager.initiateCleanupOnce(record, reason);
|
||||
}
|
||||
);
|
||||
record.cleanupTimer = this.timeoutManager.setupConnectionTimeout(record, (record, reason) => {
|
||||
console.log(
|
||||
`[${connectionId}] Connection from ${record.remoteIP} exceeded max lifetime, forcing cleanup.`
|
||||
);
|
||||
this.connectionManager.initiateCleanupOnce(record, reason);
|
||||
});
|
||||
|
||||
// Mark TLS handshake as complete for TLS connections
|
||||
if (record.isTLS) {
|
||||
@ -1023,4 +1135,4 @@ export class ConnectionHandler {
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -104,6 +104,7 @@ export interface IConnectionRecord {
|
||||
lockedDomain?: string; // Used to lock this connection to the initial SNI
|
||||
connectionClosed: boolean; // Flag to prevent multiple cleanup attempts
|
||||
cleanupTimer?: NodeJS.Timeout; // Timer for max lifetime/inactivity
|
||||
alertFallbackTimeout?: NodeJS.Timeout; // Timer for fallback after alert
|
||||
lastActivity: number; // Last activity timestamp for inactivity detection
|
||||
pendingData: Buffer[]; // Buffer to hold data during connection setup
|
||||
pendingDataSize: number; // Track total size of pending data
|
||||
|
218
ts/classes.pp.tlsalert.ts
Normal file
218
ts/classes.pp.tlsalert.ts
Normal file
@ -0,0 +1,218 @@
|
||||
import * as net from 'net';
|
||||
|
||||
/**
|
||||
* TlsAlert class for managing TLS alert messages
|
||||
*/
|
||||
export class TlsAlert {
|
||||
// TLS Alert Levels
|
||||
static readonly LEVEL_WARNING = 0x01;
|
||||
static readonly LEVEL_FATAL = 0x02;
|
||||
|
||||
// TLS Alert Description Codes - RFC 8446 (TLS 1.3) / RFC 5246 (TLS 1.2)
|
||||
static readonly CLOSE_NOTIFY = 0x00;
|
||||
static readonly UNEXPECTED_MESSAGE = 0x0A;
|
||||
static readonly BAD_RECORD_MAC = 0x14;
|
||||
static readonly DECRYPTION_FAILED = 0x15; // TLS 1.0 only
|
||||
static readonly RECORD_OVERFLOW = 0x16;
|
||||
static readonly DECOMPRESSION_FAILURE = 0x1E; // TLS 1.2 and below
|
||||
static readonly HANDSHAKE_FAILURE = 0x28;
|
||||
static readonly NO_CERTIFICATE = 0x29; // SSLv3 only
|
||||
static readonly BAD_CERTIFICATE = 0x2A;
|
||||
static readonly UNSUPPORTED_CERTIFICATE = 0x2B;
|
||||
static readonly CERTIFICATE_REVOKED = 0x2C;
|
||||
static readonly CERTIFICATE_EXPIRED = 0x2F;
|
||||
static readonly CERTIFICATE_UNKNOWN = 0x30;
|
||||
static readonly ILLEGAL_PARAMETER = 0x2F;
|
||||
static readonly UNKNOWN_CA = 0x30;
|
||||
static readonly ACCESS_DENIED = 0x31;
|
||||
static readonly DECODE_ERROR = 0x32;
|
||||
static readonly DECRYPT_ERROR = 0x33;
|
||||
static readonly EXPORT_RESTRICTION = 0x3C; // TLS 1.0 only
|
||||
static readonly PROTOCOL_VERSION = 0x46;
|
||||
static readonly INSUFFICIENT_SECURITY = 0x47;
|
||||
static readonly INTERNAL_ERROR = 0x50;
|
||||
static readonly INAPPROPRIATE_FALLBACK = 0x56;
|
||||
static readonly USER_CANCELED = 0x5A;
|
||||
static readonly NO_RENEGOTIATION = 0x64; // TLS 1.2 and below
|
||||
static readonly MISSING_EXTENSION = 0x6D; // TLS 1.3
|
||||
static readonly UNSUPPORTED_EXTENSION = 0x6E; // TLS 1.3
|
||||
static readonly CERTIFICATE_REQUIRED = 0x6F; // TLS 1.3
|
||||
static readonly UNRECOGNIZED_NAME = 0x70;
|
||||
static readonly BAD_CERTIFICATE_STATUS_RESPONSE = 0x71;
|
||||
static readonly BAD_CERTIFICATE_HASH_VALUE = 0x72; // TLS 1.2 and below
|
||||
static readonly UNKNOWN_PSK_IDENTITY = 0x73;
|
||||
static readonly CERTIFICATE_REQUIRED_1_3 = 0x74; // TLS 1.3
|
||||
static readonly NO_APPLICATION_PROTOCOL = 0x78;
|
||||
|
||||
/**
|
||||
* Create a TLS alert buffer with the specified level and description code
|
||||
*
|
||||
* @param level Alert level (warning or fatal)
|
||||
* @param description Alert description code
|
||||
* @param tlsVersion TLS version bytes (default is TLS 1.2: 0x0303)
|
||||
* @returns Buffer containing the TLS alert message
|
||||
*/
|
||||
static create(
|
||||
level: number,
|
||||
description: number,
|
||||
tlsVersion: [number, number] = [0x03, 0x03]
|
||||
): Buffer {
|
||||
return Buffer.from([
|
||||
0x15, // Alert record type
|
||||
tlsVersion[0],
|
||||
tlsVersion[1], // TLS version (default to TLS 1.2: 0x0303)
|
||||
0x00,
|
||||
0x02, // Length
|
||||
level, // Alert level
|
||||
description, // Alert description
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a warning-level TLS alert
|
||||
*
|
||||
* @param description Alert description code
|
||||
* @returns Buffer containing the warning-level TLS alert message
|
||||
*/
|
||||
static createWarning(description: number): Buffer {
|
||||
return this.create(this.LEVEL_WARNING, description);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a fatal-level TLS alert
|
||||
*
|
||||
* @param description Alert description code
|
||||
* @returns Buffer containing the fatal-level TLS alert message
|
||||
*/
|
||||
static createFatal(description: number): Buffer {
|
||||
return this.create(this.LEVEL_FATAL, description);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a TLS alert to a socket and optionally close the connection
|
||||
*
|
||||
* @param socket The socket to send the alert to
|
||||
* @param level Alert level (warning or fatal)
|
||||
* @param description Alert description code
|
||||
* @param closeAfterSend Whether to close the connection after sending the alert
|
||||
* @param closeDelay Milliseconds to wait before closing the connection (default: 200ms)
|
||||
* @returns Promise that resolves when the alert has been sent
|
||||
*/
|
||||
static async send(
|
||||
socket: net.Socket,
|
||||
level: number,
|
||||
description: number,
|
||||
closeAfterSend: boolean = false,
|
||||
closeDelay: number = 200
|
||||
): Promise<void> {
|
||||
const alert = this.create(level, description);
|
||||
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
try {
|
||||
// Ensure the alert is written as a single packet
|
||||
socket.cork();
|
||||
const writeSuccessful = socket.write(alert, (err) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
|
||||
if (closeAfterSend) {
|
||||
setTimeout(() => {
|
||||
socket.end();
|
||||
resolve();
|
||||
}, closeDelay);
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
socket.uncork();
|
||||
|
||||
// If write wasn't successful immediately, wait for drain
|
||||
if (!writeSuccessful && !closeAfterSend) {
|
||||
socket.once('drain', () => {
|
||||
resolve();
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Pre-defined TLS alert messages
|
||||
*/
|
||||
static readonly alerts = {
|
||||
// Warning level alerts
|
||||
closeNotify: TlsAlert.createWarning(TlsAlert.CLOSE_NOTIFY),
|
||||
unsupportedExtension: TlsAlert.createWarning(TlsAlert.UNSUPPORTED_EXTENSION),
|
||||
certificateRequired: TlsAlert.createWarning(TlsAlert.CERTIFICATE_REQUIRED),
|
||||
unrecognizedName: TlsAlert.createWarning(TlsAlert.UNRECOGNIZED_NAME),
|
||||
noRenegotiation: TlsAlert.createWarning(TlsAlert.NO_RENEGOTIATION),
|
||||
userCanceled: TlsAlert.createWarning(TlsAlert.USER_CANCELED),
|
||||
|
||||
// Warning level alerts for session resumption
|
||||
certificateExpiredWarning: TlsAlert.createWarning(TlsAlert.CERTIFICATE_EXPIRED),
|
||||
handshakeFailureWarning: TlsAlert.createWarning(TlsAlert.HANDSHAKE_FAILURE),
|
||||
insufficientSecurityWarning: TlsAlert.createWarning(TlsAlert.INSUFFICIENT_SECURITY),
|
||||
|
||||
// Fatal level alerts
|
||||
unexpectedMessage: TlsAlert.createFatal(TlsAlert.UNEXPECTED_MESSAGE),
|
||||
badRecordMac: TlsAlert.createFatal(TlsAlert.BAD_RECORD_MAC),
|
||||
recordOverflow: TlsAlert.createFatal(TlsAlert.RECORD_OVERFLOW),
|
||||
handshakeFailure: TlsAlert.createFatal(TlsAlert.HANDSHAKE_FAILURE),
|
||||
badCertificate: TlsAlert.createFatal(TlsAlert.BAD_CERTIFICATE),
|
||||
certificateExpired: TlsAlert.createFatal(TlsAlert.CERTIFICATE_EXPIRED),
|
||||
certificateUnknown: TlsAlert.createFatal(TlsAlert.CERTIFICATE_UNKNOWN),
|
||||
illegalParameter: TlsAlert.createFatal(TlsAlert.ILLEGAL_PARAMETER),
|
||||
unknownCA: TlsAlert.createFatal(TlsAlert.UNKNOWN_CA),
|
||||
accessDenied: TlsAlert.createFatal(TlsAlert.ACCESS_DENIED),
|
||||
decodeError: TlsAlert.createFatal(TlsAlert.DECODE_ERROR),
|
||||
decryptError: TlsAlert.createFatal(TlsAlert.DECRYPT_ERROR),
|
||||
protocolVersion: TlsAlert.createFatal(TlsAlert.PROTOCOL_VERSION),
|
||||
insufficientSecurity: TlsAlert.createFatal(TlsAlert.INSUFFICIENT_SECURITY),
|
||||
internalError: TlsAlert.createFatal(TlsAlert.INTERNAL_ERROR),
|
||||
};
|
||||
|
||||
/**
|
||||
* Utility method to send a warning-level unrecognized_name alert
|
||||
* Specifically designed for SNI issues to encourage the client to retry with SNI
|
||||
*
|
||||
* @param socket The socket to send the alert to
|
||||
* @returns Promise that resolves when the alert has been sent
|
||||
*/
|
||||
static async sendSniRequired(socket: net.Socket): Promise<void> {
|
||||
return this.send(socket, this.LEVEL_WARNING, this.UNRECOGNIZED_NAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility method to send a close_notify alert and close the connection
|
||||
*
|
||||
* @param socket The socket to send the alert to
|
||||
* @param closeDelay Milliseconds to wait before closing the connection (default: 200ms)
|
||||
* @returns Promise that resolves when the alert has been sent and the connection closed
|
||||
*/
|
||||
static async sendCloseNotify(socket: net.Socket, closeDelay: number = 200): Promise<void> {
|
||||
return this.send(socket, this.LEVEL_WARNING, this.CLOSE_NOTIFY, true, closeDelay);
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility method to send a certificate_expired alert to force new TLS session
|
||||
*
|
||||
* @param socket The socket to send the alert to
|
||||
* @param fatal Whether to send as a fatal alert (default: false)
|
||||
* @param closeAfterSend Whether to close the connection after sending the alert (default: true)
|
||||
* @param closeDelay Milliseconds to wait before closing the connection (default: 200ms)
|
||||
* @returns Promise that resolves when the alert has been sent
|
||||
*/
|
||||
static async sendCertificateExpired(
|
||||
socket: net.Socket,
|
||||
fatal: boolean = false,
|
||||
closeAfterSend: boolean = true,
|
||||
closeDelay: number = 200
|
||||
): Promise<void> {
|
||||
const level = fatal ? this.LEVEL_FATAL : this.LEVEL_WARNING;
|
||||
return this.send(socket, level, this.CERTIFICATE_EXPIRED, closeAfterSend, closeDelay);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user