TsgcWebSocketFirewall implements a comprehensive firewall component that protects WebSocket servers against a wide range of security threats.
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.
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.
| Property | Description |
| Enabled | Enables or disables the firewall. Default: True. |
| Blacklist | IP blacklist configuration. Contains Enabled (Boolean) and IPs (TStringList) properties. Supports exact IPs and CIDR notation (e.g., "192.168.0.0/16"). |
| Whitelist | IP whitelist configuration. Whitelisted IPs bypass all security checks. Same structure as Blacklist. |
| BruteForce | Brute force protection. Properties: Enabled, MaxAttempts (default 5), TimeWindowSec (default 60), BanDurationSec (default 300). Automatically bans IPs that exceed the attempt limit. |
| SQLInjection | SQL injection detection. Properties: Enabled, Action (faDeny/faAllow/faLog), CustomPatterns (TStringList for additional patterns). |
| XSS | Cross-site scripting detection. Properties: Enabled, Action (faDeny/faAllow/faLog). |
| RateLimit | Connection rate limiting. Properties: Enabled, MaxConnectionsPerIP (default 10), TimeWindowSec (default 60). |
| FloodProtection | Message flood protection. Properties: Enabled, MaxMessagesPerSec (default 100), Action (faDeny/faAllow/faLog). |
| PayloadLimit | Message size limiting. Properties: Enabled, MaxSizeBytes (default 1048576), Action (faDeny/faAllow/faLog). |
| PathTraversal | Path traversal detection. Properties: Enabled, Action (faDeny/faAllow/faLog). |
| CommandInjection | Command injection detection. Properties: Enabled, Action (faDeny/faAllow/faLog), CustomPatterns (TStringList for additional patterns). |
| ThreatScore | Dynamic threat scoring. Properties: Enabled, AutoBanThreshold (default 80), DecayPerHour (default 5), plus per-violation-type weights for fine-tuning score calculations. |
| BanEscalation | Progressive 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. |
| GeoIP | Geographic IP filtering. Properties: Enabled, Mode (gmBlockList/gmAllowList), Countries (TStringList of ISO 3166-1 alpha-2 country codes), DatabaseFile (path to a GeoIP CSV database). |
| WebSocketProtection | WebSocket-specific protections. Properties: Enabled, AllowedOrigins (TStringList), MaxFrameSize (Integer), AllowedSubprotocols (TStringList). |
| CustomRules | Custom rules engine. Properties: Enabled, Rules (TCollection of TsgcFirewallRuleItem). Each rule defines conditions and actions for complex filtering logic. |
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.
| Method | Description |
| 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. |
| ClearBans | Removes all active bans. |
| ClearTracking | Resets 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. |
| Stats | Public read-only TsgcFirewallStats object with real-time counters for connections blocked, messages filtered, bans issued, threat scores, and per-module hit counts. |
When assigned to a server's Firewall property, the component automatically:
The blacklist and whitelist support CIDR notation for IP ranges:
// 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;
The built-in SQL injection detector checks for these patterns (case-insensitive):
Additional custom patterns can be added via the SQLInjection.CustomPatterns property.
The built-in path traversal detector checks for these patterns:
The built-in command injection detector checks for these patterns:
Additional custom patterns can be added via the CommandInjection.CustomPatterns property.
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.