TsgcWebSocketFirewall

TsgcWebSocketFirewall implements a comprehensive firewall component that protects WebSocket servers against a wide range of security threats.

Introduction

TsgcWebSocketFirewall implements a comprehensive firewall component that protects WebSocket servers against a wide range of security threats. It provides fifteen protection modules including IP blacklist/whitelist filtering, brute force protection with automatic IP banning, SQL injection detection, XSS (Cross-Site Scripting) detection, connection rate limiting, message flood protection, GeoIP country-based filtering, dynamic threat scoring, path traversal detection, command injection detection, payload size limiting, WebSocket-specific protections (origin validation, frame size limits, subprotocol filtering), progressive ban escalation, a custom rules engine, and real-time statistics.

 

The firewall integrates automatically with server components through the Firewall property available on TsgcWebSocketServer, TsgcWebSocketHTTPServer, and TsgcWebSocketServer_HTTPAPI. Once assigned and configured, it intercepts connections and messages without requiring any manual event wiring.

 

Quick Start

 

1. Drop a TsgcWebSocketFirewall component on the form.

 

2. Configure the desired protection modules:

 

Blacklist: Set Enabled to True and add IPs or CIDR ranges to the IPs list (e.g., "10.0.0.0/8", "192.168.1.100").

 

Whitelist: Set Enabled to True and add trusted IPs. Whitelisted IPs bypass all other checks.

 

BruteForce: Set Enabled to True. Configure MaxAttempts (default 5), TimeWindowSec (default 60), and BanDurationSec (default 300).

 

SQLInjection: Set Enabled to True. Detects common SQL injection patterns in messages.

 

XSS: Set Enabled to True. Detects cross-site scripting patterns in messages.

 

RateLimit: Set Enabled to True. Limits concurrent connections per IP (default 10 per 60 seconds).

 

FloodProtection: Set Enabled to True. Limits messages per second per IP (default 100).

 

PayloadLimit: Set Enabled to True. Blocks messages exceeding MaxSizeBytes (default 1MB).

 

PathTraversal: Set Enabled to True. Detects directory traversal patterns.

 

CommandInjection: Set Enabled to True. Detects shell command injection patterns.

 

ThreatScore: Set Enabled to True. Assigns dynamic scores to IPs based on violations.

 

BanEscalation: Set Enabled to True. Escalates ban durations for repeat offenders.

 

GeoIP: Set Enabled to True. Blocks or allows connections by country code.

 

WebSocketProtection: Set Enabled to True. Validates origins, frame sizes, and subprotocols.

 

CustomRules: Set Enabled to True. Configurable rule engine for complex filtering.

 

3. Assign the firewall to a server component:

 

sgcWebSocketHTTPServer1.Firewall := sgcWebSocketFirewall1;

 

4. Start the server. The firewall automatically protects all connections and messages.

 

Properties

 

PropertyDescription
EnabledEnables or disables the firewall. Default: True.
BlacklistIP blacklist configuration. Contains Enabled (Boolean) and IPs (TStringList) properties. Supports exact IPs and CIDR notation (e.g., "192.168.0.0/16").
WhitelistIP whitelist configuration. Whitelisted IPs bypass all security checks. Same structure as Blacklist.
BruteForceBrute force protection. Properties: Enabled, MaxAttempts (default 5), TimeWindowSec (default 60), BanDurationSec (default 300). Automatically bans IPs that exceed the attempt limit.
SQLInjectionSQL injection detection. Properties: Enabled, Action (faDeny/faAllow/faLog), CustomPatterns (TStringList for additional patterns).
XSSCross-site scripting detection. Properties: Enabled, Action (faDeny/faAllow/faLog).
RateLimitConnection rate limiting. Properties: Enabled, MaxConnectionsPerIP (default 10), TimeWindowSec (default 60).
FloodProtectionMessage flood protection. Properties: Enabled, MaxMessagesPerSec (default 100), Action (faDeny/faAllow/faLog).
PayloadLimitMessage size limiting. Properties: Enabled, MaxSizeBytes (default 1048576), Action (faDeny/faAllow/faLog).
PathTraversalPath traversal detection. Properties: Enabled, Action (faDeny/faAllow/faLog).
CommandInjectionCommand injection detection. Properties: Enabled, Action (faDeny/faAllow/faLog), CustomPatterns (TStringList for additional patterns).
ThreatScoreDynamic threat scoring. Properties: Enabled, AutoBanThreshold (default 80), DecayPerHour (default 5), plus per-violation-type weights for fine-tuning score calculations.
BanEscalationProgressive ban escalation. Properties: Enabled, Levels (TStringList of durations in seconds), ResetAfterSec (default 86400). Each subsequent ban uses the next level duration. A level value of 0 means permanent ban.
GeoIPGeographic IP filtering. Properties: Enabled, Mode (gmBlockList/gmAllowList), Countries (TStringList of ISO 3166-1 alpha-2 country codes), DatabaseFile (path to a GeoIP CSV database).
WebSocketProtectionWebSocket-specific protections. Properties: Enabled, AllowedOrigins (TStringList), MaxFrameSize (Integer), AllowedSubprotocols (TStringList).
CustomRulesCustom rules engine. Properties: Enabled, Rules (TCollection of TsgcFirewallRuleItem). Each rule defines conditions and actions for complex filtering logic.

 

Events

 

OnFiltered: Fired when a connection or message is blocked. The Allow parameter (var Boolean) lets you override the firewall decision.

 

OnViolation: Fired when a security violation is detected. Provides the IP address, violation type, and details for logging purposes.

 

OnResolveCountry: Fired when GeoIP needs to resolve an IP to a country code. Assign a handler to provide custom country resolution, or load a GeoIP database file for automatic lookups.

 

OnThreatScoreChanged: Fired when an IP's threat score changes. Provides the IP address together with the old and new score values.

 

Public Methods

 

MethodDescription
IsConnectionAllowed(IP)Checks if a connection from the given IP is allowed. Called automatically when integrated with a server.
IsMessageAllowed(IP, Message)Checks if a message from the given IP passes all message filters. Called automatically when integrated with a server.
RegisterConnection(IP)Registers a new connection for rate limiting tracking. Called automatically.
UnregisterConnection(IP)Removes a connection from tracking. Called automatically on disconnect.
RegisterFailedAttempt(IP)Records a failed authentication attempt for brute force detection. Call this from your OnAuthentication event handler when authentication fails.
BanIP(IP, DurationSec)Manually bans an IP address. DurationSec = 0 means permanent ban.
UnbanIP(IP)Removes a ban from the specified IP address.
IsBanned(IP)Returns True if the specified IP is currently banned.
ClearBansRemoves all active bans.
ClearTrackingResets all internal tracking data (connection counts, attempt logs, message counts).
SaveBansToFile(FileName)Saves all active bans to a file for persistence across restarts.
LoadBansFromFile(FileName)Restores bans from a previously saved file.
LoadGeoIPDatabase(FileName)Loads a GeoIP CSV database. Expected format: start_ip,end_ip,country_code.
LookupCountry(IP)Returns the 2-letter ISO country code for an IP address.
GetThreatScore(IP)Returns the current threat score (0-100) for an IP address.
ResetThreatScore(IP)Resets an IP's threat score to 0.
GetTopThreats(Count)Returns a list of IPs with the highest threat scores.
IsOriginAllowed(Origin)Checks if a WebSocket Origin header is allowed by the WebSocketProtection configuration.
IsFrameSizeAllowed(Size)Checks if a message size is within the limits defined by WebSocketProtection.MaxFrameSize.
IsSubprotocolAllowed(Subprotocol)Checks if a WebSocket subprotocol is allowed by the WebSocketProtection configuration.
StatsPublic read-only TsgcFirewallStats object with real-time counters for connections blocked, messages filtered, bans issued, threat scores, and per-module hit counts.

 

Automatic Integration

 

When assigned to a server's Firewall property, the component automatically:

 

CIDR Support

 

The blacklist and whitelist support CIDR notation for IP ranges:

 

Example

 


    // Configure firewall
    sgcWebSocketFirewall1.Blacklist.Enabled := True;
    sgcWebSocketFirewall1.Blacklist.IPs.Add('10.0.0.0/8');
    sgcWebSocketFirewall1.Whitelist.Enabled := True;
    sgcWebSocketFirewall1.Whitelist.IPs.Add('192.168.1.1');
    sgcWebSocketFirewall1.BruteForce.Enabled := True;
    sgcWebSocketFirewall1.BruteForce.MaxAttempts := 3;
    sgcWebSocketFirewall1.BruteForce.BanDurationSec := 600;
    sgcWebSocketFirewall1.SQLInjection.Enabled := True;
    sgcWebSocketFirewall1.XSS.Enabled := True;
    sgcWebSocketFirewall1.RateLimit.Enabled := True;
    sgcWebSocketFirewall1.RateLimit.MaxConnectionsPerIP := 5;
    sgcWebSocketFirewall1.FloodProtection.Enabled := True;

    // GeoIP: block connections from specific countries
    sgcWebSocketFirewall1.GeoIP.Enabled := True;
    sgcWebSocketFirewall1.GeoIP.Mode := gmBlockList;
    sgcWebSocketFirewall1.GeoIP.Countries.Add('CN');
    sgcWebSocketFirewall1.GeoIP.Countries.Add('RU');
    sgcWebSocketFirewall1.LoadGeoIPDatabase('geoip.csv');

    // Threat scoring with auto-ban
    sgcWebSocketFirewall1.ThreatScore.Enabled := True;
    sgcWebSocketFirewall1.ThreatScore.AutoBanThreshold := 80;

    // Progressive ban escalation (5min, 30min, 2hr, 24hr, permanent)
    sgcWebSocketFirewall1.BanEscalation.Enabled := True;
    sgcWebSocketFirewall1.BanEscalation.Levels.Add('300');
    sgcWebSocketFirewall1.BanEscalation.Levels.Add('1800');
    sgcWebSocketFirewall1.BanEscalation.Levels.Add('7200');
    sgcWebSocketFirewall1.BanEscalation.Levels.Add('86400');
    sgcWebSocketFirewall1.BanEscalation.Levels.Add('0');

    // Additional content protection
    sgcWebSocketFirewall1.PayloadLimit.Enabled := True;
    sgcWebSocketFirewall1.PayloadLimit.MaxSizeBytes := 65536;
    sgcWebSocketFirewall1.PathTraversal.Enabled := True;
    sgcWebSocketFirewall1.CommandInjection.Enabled := True;

    // Persistent bans
    sgcWebSocketFirewall1.SaveBansToFile('bans.dat');
    sgcWebSocketFirewall1.LoadBansFromFile('bans.dat');

    // Assign to server
    sgcWebSocketHTTPServer1.Firewall := sgcWebSocketFirewall1;

    // Optional: Track failed login attempts
    procedure TForm1.ServerAuthentication(Connection: TsgcWSConnection;
      aUser, aPassword: String; var Authenticated: Boolean);
    begin
      Authenticated := (aUser = 'admin') and (aPassword = 'secret');
      if not Authenticated then
        sgcWebSocketFirewall1.RegisterFailedAttempt(Connection.IP);
    end;

    // Optional: Handle firewall events for logging
    procedure TForm1.FirewallViolation(Sender: TObject; const aIP: string;
      const aViolationType: TsgcFirewallViolationType; const aDetails: string);
    begin
      Log('Firewall violation from ' + aIP + ': ' + aDetails);
    end;
    

SQL Injection Patterns Detected

 

The built-in SQL injection detector checks for these patterns (case-insensitive):

 

Additional custom patterns can be added via the SQLInjection.CustomPatterns property.

 

XSS Patterns Detected

 

 

Path Traversal Patterns Detected

 

The built-in path traversal detector checks for these patterns:

 

Command Injection Patterns Detected

 

The built-in command injection detector checks for these patterns:

 

Additional custom patterns can be added via the CommandInjection.CustomPatterns property.

 

Thread Safety

 

The firewall component is fully thread-safe. All public methods use internal critical sections to protect concurrent access to tracking data. It has been stress-tested with 20 concurrent threads performing 100,000 operations with zero errors and zero memory leaks.

 

The component can safely be shared across multiple server instances and accessed from any thread (server event handlers, timer threads, etc.) without external synchronization.

 

Reference