By Admin on Wednesday, 25 March 2026
Category: All

Firewall for sgcWebSockets Servers

Security is no longer optional. Every WebSocket server exposed to the internet is a target for brute force attacks, injection attempts, connection flooding, and automated abuse. Defending against these threats typically requires bolting on external middleware, writing custom filtering logic, or deploying a separate reverse proxy — all of which add complexity and slow down development.

sgcWebSockets 2026.3.0 introduces TsgcWSFirewall — a dedicated firewall component that plugs directly into your WebSocket server. Drop the component, configure the protection modules you need, assign it to the server, and your application is protected. No external dependencies. No middleware. No custom code for the common cases.

This article covers the full feature set and shows how to configure each protection module in Delphi.

Seven Protection Modules, One Component

The firewall provides seven independent protection modules. Enable only what you need — each module works on its own or in combination with the others.

IP Blacklist
Block specific IP addresses or entire ranges using CIDR notation. Connections from blacklisted IPs are rejected before reaching your application code.
IP Whitelist
Define a trusted list of IPs. When enabled, whitelisted addresses bypass all other security checks — ideal for internal services and monitoring tools.
Brute Force Protection
Track failed authentication attempts per IP. Automatically ban offenders after a configurable threshold within a sliding time window.
SQL Injection Detection
Scan incoming messages for common SQL injection patterns. Built-in detection for boolean injection, UNION SELECT, statement injection, and more.
XSS Detection
Detect cross-site scripting payloads in messages. Catches script tags, event handlers, JavaScript protocol URIs, iframe injection, and CSS expressions.
Connection Rate Limiting
Limit the number of concurrent connections per IP address. Prevent a single client from exhausting server resources.
Message Flood Protection
Throttle the number of messages a single IP can send per second. Protects against message flooding and denial-of-service patterns without affecting normal traffic.

Quick Start

Getting the firewall up and running requires just three steps: create, configure, and assign.

var
  oFirewall: TsgcWSFirewall;
  oServer: TsgcWebSocketHTTPServer;
begin
  oFirewall := TsgcWSFirewall.Create(nil);
  oFirewall.Enabled := True;

  // Enable the modules you need
  oFirewall.Blacklist.Enabled := True;
  oFirewall.Blacklist.IPs.Add('10.0.0.0/8');

  oFirewall.RateLimit.Enabled := True;
  oFirewall.RateLimit.MaxConnectionsPerIP := 5;

  oFirewall.SQLInjection.Enabled := True;
  oFirewall.XSS.Enabled := True;

  // Assign to any server component
  oServer.Firewall := oFirewall;
  oServer.Active := True;
end;

Once assigned, the firewall integrates automatically: connections are checked before they reach your event handlers, messages are scanned in real-time, and disconnected clients are unregistered from tracking — all without writing a single line of event handling code.

IP Blacklist & Whitelist

The blacklist rejects connections from specific IPs or ranges. The whitelist does the opposite — it defines a trusted set of addresses that bypass all other checks, including message filtering.

Both support exact IP addresses and CIDR notation for range-based filtering:

// Blacklist: block entire subnets and specific IPs
oFirewall.Blacklist.Enabled := True;
oFirewall.Blacklist.IPs.Add('10.0.0.0/8');        // All 10.x.x.x
oFirewall.Blacklist.IPs.Add('172.16.0.0/16');     // All 172.16.x.x
oFirewall.Blacklist.IPs.Add('192.168.1.100');     // Single IP

// Whitelist: trusted IPs bypass everything
oFirewall.Whitelist.Enabled := True;
oFirewall.Whitelist.IPs.Add('192.168.1.1');       // Admin machine
oFirewall.Whitelist.IPs.Add('192.168.1.0/24');    // Internal network

Priority. When the whitelist is enabled, it is checked first. If the IP matches, the connection is allowed immediately — blacklist, bans, rate limits, and message filters are all skipped.

Brute Force Protection

The brute force module tracks failed authentication attempts per IP using a sliding time window. When an IP exceeds the maximum number of attempts within the window, it is automatically banned for a configurable duration.

Property Default Description
MaxAttempts 5 Failed attempts before ban
TimeWindowSec 60 Sliding window in seconds for counting attempts
BanDurationSec 300 Ban duration in seconds (0 = permanent)
// Ban after 3 failed logins within 60 seconds, for 10 minutes
oFirewall.BruteForce.Enabled := True;
oFirewall.BruteForce.MaxAttempts := 3;
oFirewall.BruteForce.TimeWindowSec := 60;
oFirewall.BruteForce.BanDurationSec := 600;

// Register failed attempts from your authentication handler
procedure TForm1.ServerAuthentication(Connection: TsgcWSConnection;
  aUser, aPassword: String; var Authenticated: Boolean);
begin
  Authenticated := ValidateCredentials(aUser, aPassword);
  if not Authenticated then
    oFirewall.RegisterFailedAttempt(Connection.IP);
end;

The firewall automatically handles the rest: it counts attempts, checks the time window, and bans the IP when the threshold is reached. Banned IPs are rejected at the connection level before any further processing.

Manual Ban Management

Beyond automatic bans, you can manage bans programmatically at any time:

// Ban an IP for 1 hour
oFirewall.BanIP('203.0.113.50', 3600);

// Permanent ban (duration = 0)
oFirewall.BanIP('198.51.100.10');

// Check ban status
if oFirewall.IsBanned('203.0.113.50') then
  WriteLn('IP is banned');

// Remove a specific ban
oFirewall.UnbanIP('203.0.113.50');

// Clear all bans
oFirewall.ClearBans;

SQL Injection Detection

The SQL injection module scans every incoming text message for common attack patterns. When a match is detected, the configurable action determines the response: block the client, log the event, or allow it through.

oFirewall.SQLInjection.Enabled := True;
oFirewall.SQLInjection.Action := faDeny;  // faDeny, faLog, or faAllow

// Add custom patterns beyond the built-in set
oFirewall.SQLInjection.CustomPatterns.Add('WAITFOR DELAY');
oFirewall.SQLInjection.CustomPatterns.Add('BENCHMARK(');

Built-in Patterns

The detector includes case-insensitive checks for the most common SQL injection techniques:

XSS Detection

The XSS module detects cross-site scripting payloads in WebSocket messages before they can reach your application logic or be relayed to other clients.

oFirewall.XSS.Enabled := True;
oFirewall.XSS.Action := faDeny;

Built-in detection covers:

Connection Rate Limiting

Limit the number of concurrent connections a single IP address can hold. This prevents resource exhaustion from clients that open excessive connections — whether malicious or misconfigured.

// Allow up to 5 concurrent connections per IP
oFirewall.RateLimit.Enabled := True;
oFirewall.RateLimit.MaxConnectionsPerIP := 5;
oFirewall.RateLimit.TimeWindowSec := 60;

Connection tracking is fully automatic: the firewall increments the counter on connect and decrements it on disconnect. When a new connection would exceed the limit, it is rejected before the server's OnConnect event fires.

Message Flood Protection

Throttle the number of messages a single IP can send per second. This protects against denial-of-service patterns where a client rapidly sends messages to overwhelm the server or other connected clients.

// Limit to 50 messages per second per IP
oFirewall.FloodProtection.Enabled := True;
oFirewall.FloodProtection.MaxMessagesPerSec := 50;
oFirewall.FloodProtection.Action := faDeny;  // Disconnect offender

Action Modes

The SQL injection, XSS, and flood protection modules support three configurable actions when a violation is detected:

Action Behavior Use Case
faDeny Block and disconnect the client Production servers
faLog Fire the OnViolation event but allow the connection Monitoring, testing, gradual rollout
faAllow No action Temporarily disable a module without removing config

Tip. Start with faLog in production to observe how the firewall reacts to your real traffic before switching to faDeny. This avoids blocking legitimate users during the initial deployment.

Events — Logging & Overrides

Two events give you full visibility into firewall decisions and the ability to override them when needed.

OnViolation — Security Logging

Fired on every detected violation. Use it to write security logs, send alerts, or feed a monitoring dashboard.

procedure TForm1.FirewallViolation(Sender: TObject;
  const aIP: string;
  const aViolationType: TsgcFirewallViolationType;
  const aDetails: string);
begin
  LogToFile(Format('[%s] Firewall: %s - %s',
    [aIP, ViolationTypeToStr(aViolationType), aDetails]));
end;

Violation types include:

Type Triggered When
fvBlacklist IP is in the blacklist
fvBruteForce Failed attempt threshold exceeded
fvRateLimit Connection rate limit exceeded
fvFlood Message flood detected
fvSQLInjection SQL injection pattern detected
fvXSS XSS pattern detected

OnFiltered — Override Decisions

Fired when a connection or message is about to be blocked. The Allow parameter lets you override the firewall's decision at runtime.

procedure TForm1.FirewallFiltered(Sender: TObject;
  const aIP: string; const aReason: string;
  var Allow: Boolean);
begin
  // Override: always allow the office IP even if rate-limited
  if aIP = '203.0.113.10' then
    Allow := True;
end;

Server Integration

The firewall works with all three server components. A single firewall instance can even be shared across multiple servers.

Component Description
TsgcWebSocketHTTPServer WebSocket + HTTP server (Indy-based)
TsgcWebSocketServer Pure WebSocket server (Indy TCP)
TsgcWebSocketServer_HTTPAPI WebSocket server using HTTP.SYS kernel driver

Integration is automatic once assigned. The firewall intercepts at three points:

Complete Example

A fully configured WebSocket server with all protection modules enabled.

uses
  sgcWebSocket_Server, sgcWebSocket_Server_Firewall;

var
  oFirewall: TsgcWSFirewall;
  oServer: TsgcWebSocketHTTPServer;
begin
  oFirewall := TsgcWSFirewall.Create(nil);
  oServer := TsgcWebSocketHTTPServer.Create(nil);
  Try
    // IP filtering
    oFirewall.Blacklist.Enabled := True;
    oFirewall.Blacklist.IPs.Add('10.0.0.0/8');
    oFirewall.Whitelist.Enabled := True;
    oFirewall.Whitelist.IPs.Add('192.168.1.0/24');

    // Brute force: ban after 3 failures in 60s, for 10 minutes
    oFirewall.BruteForce.Enabled := True;
    oFirewall.BruteForce.MaxAttempts := 3;
    oFirewall.BruteForce.BanDurationSec := 600;

    // Message security
    oFirewall.SQLInjection.Enabled := True;
    oFirewall.XSS.Enabled := True;

    // Rate limiting and flood protection
    oFirewall.RateLimit.Enabled := True;
    oFirewall.RateLimit.MaxConnectionsPerIP := 5;
    oFirewall.FloodProtection.Enabled := True;
    oFirewall.FloodProtection.MaxMessagesPerSec := 50;

    // Events
    oFirewall.OnViolation := FirewallViolation;
    oFirewall.OnFiltered := FirewallFiltered;

    // Assign to server and start
    oServer.Port := 443;
    oServer.Firewall := oFirewall;
    oServer.Active := True;

    WriteLn('Server running with firewall protection.');
    ReadLn;
  Finally
    oServer.Active := False;
    oServer.Free;
    oFirewall.Free;
  End;
end;

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, background workers — without external synchronization.

Important Notes

Related Posts