feat(network): pluggable connection filters; file blocklist + contribute-first CrowdSec (#2542)
Reshapes IP banning around one idea: **core owns the question, content owns every answer.**
Core gains a single accept-path seam — `IConnectionFilter` — and loses everything that used to implement one. The firewall moves to UOContent, a new file-backed blocklist joins it there, and CrowdSec is repositioned from an in-app enforcer to a contribute-first reporter.
## The seam
```csharp
public interface IConnectionFilter
{
string Name { get; }
void Configure();
void Start(CancellationToken token);
void Stop();
bool ShouldDeny(IPAddress address);
}
```
The accept path went from hardcoded branches to one question:
```csharp
else if (ConnectionFilters.ShouldDeny(remoteIP, out var deniedBy))
{
logger.Debug("{Address} denied by connection filter '{Filter}'", remoteIP, deniedBy);
}
```
Filters register during the Configure sweep. The registry is a plain array walked by an indexed loop — no enumerator, no closure, no allocation — and the first denial short-circuits. An interface dispatch is noise next to the `accept()` syscall, so pluggability costs nothing measurable on the path that has to survive a DDoS.
Whatever a hit implies — persisting, promoting to an OS bouncer, contributing to the ban channel — is the filter's business, not the accept path's.
A filter that throws is **unregistered and the connection fails open**. A filter that faults once faults for every subsequent connection, so leaving it registered means an exception and a log line per accept — exactly the amplification an attacker wants — and a broken filter must not be able to deny everyone either.
This deliberately does **not** reuse `EventSink.InvokeSocketConnect`: that fires later and allocates a `SocketConnectEventArgs` per connection, which is what the accept path avoids for rejected traffic.
## What ships behind it
**`firewall`** (UOContent) — the existing admin-curated set. Collapsed from `Firewall` + `AdminFirewall` + a threaded enforcer into one single-threaded store with **zero concurrency primitives**: the accept path, admin gump, TTL expiry and boot load all run on the game loop. Persists to `Configuration/firewall.json` with automatic migration from the legacy `firewall.cfg`. No behavior change for operators — same namespace, same gump, same commands.
**`blocklist`** (UOContent) — new. Holds a millions-strong list in-app and **demand-pages** hits up to CrowdSec, which promotes them to the OS firewall.
The motivation is concrete: CrowdSec's Windows bouncer cannot load the ~3.9M IPs that 91 community feeds produce, but it handles ~100k fine. So the millions live in-process behind a binary search, and only addresses that *actually connect* get promoted. A `PromotedGuard` suppresses re-reporting an address until the bouncer picks it up.
The list is parsed straight from UTF-8 file bytes with no per-line string allocation, off the game loop, and published as an immutable snapshot swapped through a single `volatile` reference. Reloads yield to world saves.
**`tools/Export-IpBlocklist.ps1`** — the producer. Requires PowerShell 7 and runs on Windows, Linux and macOS; Windows PowerShell 5.1 is refused up front via `#requires`. Merges a thin, non-overlapping feed set into one de-duplicated, bogon-filtered file. Parsing runs in a compiled `Add-Type` hot loop (~1s for ~4M lines instead of minutes). Written to a `.tmp` sibling and swapped with `File.Replace`, so the shard never reads a half-written list, and a total feed outage refuses to overwrite a good list with an empty one. Re-running is idempotent — it exits without downloading anything while the list on disk is younger than `-MinInterval` (default 2h, the anchor feed's own refresh period), so a misconfigured scheduler can't hammer upstream.
## CrowdSec: contribute-first
`IBanReporter` + `BanChannel` fan locally-decided bans out to external systems. `CrowdSecReporter` (UOContent) posts to LAPI `POST /v1/alerts` and retracts via `DELETE /v1/decisions`.
Reporting is **enqueue-only** on the accept path: a bounded, coalescing channel drained off-loop with bounded retry, counted drops on overflow, and a flush on shutdown. Under a DDoS the accept path never does synchronous or lock-contending per-IP work.
### Why not pull decisions from CrowdSec?
The original design streamed decisions into an in-app snapshot and enforced them at the accept gate. That's the wrong layer: by the time the shard sees the connection, the TCP handshake and socket setup are already paid for. `cs-firewall-bouncer` drops the same traffic **at the kernel**, and it's what CrowdSec is built to do. So the shard now contributes what it uniquely knows (rate-limit trips, blocklist hits from real connection attempts) and lets the OS enforce.
The one thing the OS can't do — hold millions of entries on Windows — is exactly what the in-app blocklist covers, and it feeds the same pipeline.
## Threading policy
`CLAUDE.md` rule #3 is rewritten as an explicit three-part policy, with rule #10 restated in tandem:
- Anything touching game state runs **only** on the main loop.
- Heavy work that *needs* game state must be **chunked** across ticks, never threaded.
- Heavy work that does *not* need game state (large-file parse, external I/O) **must** run off-loop **and must yield to world saves**.
Results come back via an immutable snapshot swapped through a single `volatile` reference, or `Core.LoopContext.Post` — never by letting the scheduler decide where heavy work runs. Both new subsystems follow it.
## Shared primitives
`SortedRangeIndex<T> where T : IBinaryInteger<T>` — coalesced disjoint interval arrays plus a binary search. The firewall, the blocklist, and (as of this PR) core's reserved-network tables all use it.
Coalescing is a correctness requirement, not an optimization: multi-feed lists nest CIDRs (`/24` containing a `/32`), and a search that inspects only the rightmost run whose minimum is ≤ the value is sound **only** over disjoint runs. That bug was caught in review and is covered by regression tests.
`IPAddressUtility` collects the allocation-free `IPAddress` ↔ `UInt128` conversions and CIDR parsing that were previously scattered or duplicated.
## Config
| File | Owner | Keys |
|---|---|---|
| `Configuration/bans.json` | core | `reportRateLimitTrips`, `autoBanDuration` |
| `Configuration/blocklist.json` | content | `file`, `reloadInterval`, `reportHits`, `banDuration`, `promoteSuppression` |
| `Configuration/crowdsec.json` | content | `lapiUrl`, `machineId`, `password`, `origin`, `manualBanDuration`, `flushInterval`, `maxQueue` |
| `Configuration/firewall.json` | content | persisted firewall entries (migrated from `firewall.cfg`) |
Everything is inert by default. CrowdSec self-disables without credentials; the blocklist self-disables until its file exists. A shard that changes nothing sees no behavior change.
## Notes for review
- **Core no longer references `Firewall` or `IFirewallEntry` anywhere.** `NetworkUtilities` used to build its reserved-network tables out of `CidrFirewallEntry`, which coupled core to the firewall for something unrelated to banning; those are now a `SortedRangeIndex<UInt128>`, same semantics and public API.
- **`BanChannel.Stop()` no longer persists the firewall** — a contribution coordinator has no business saving an enforcement store. That's the firewall filter's `Stop()`.
- **A dead `whitelisted` parameter was dropped** from the blocklist gate: it was hardcoded `false` at its only call site, and no whitelist concept exists in core.
- **The blocklist filter is an instance, not a static.** The static version forced its tests onto the sequential collection with a reset hook; they now run in parallel.
- `dev-docs/networking-packets.md` documents the seam for content authors, plus a known wart in the `IPAddress` ↔ `UInt128` normalization flagged for a follow-up PR.
- The generator was verified on Linux, macOS and Windows under a temporary CI matrix (since removed). It caught two portability bugs — a Windows-only path separator, and a culture-sensitive duration parse that read `2.5` as `25` on comma-decimal locales and *silently* turned a 2.5h cooldown into 25h — plus a third that made the script unparseable on Windows PowerShell 5.1. The source is ASCII-only for that last reason: `#requires` is only honored once a file parses, so non-ASCII in a BOM-less script produces parse errors instead of the version message.
## Tests
**1344 pass** (782 `Server.Tests`, 562 `UOContent.Tests`). New coverage: filter registry (registration, short-circuit, fault-disable), blocklist parsing/CIDR/coalescing, snapshot reload markers, promote-guard TTL, ban-channel fan-out, CrowdSec alert building/dedup/flush-on-stop, and the generator's output-format contract pinned against the reader.
This commit is contained in:
parent
bec4cfa910
commit
c39454137e
52 changed files with 4655 additions and 547 deletions
65
Projects/UOContent/Misc/CrowdSec/CrowdSecAlert.cs
Normal file
65
Projects/UOContent/Misc/CrowdSec/CrowdSecAlert.cs
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
/*************************************************************************
|
||||
* ModernUO *
|
||||
* Copyright 2019-2026 - ModernUO Development Team *
|
||||
* Email: hi@modernuo.com *
|
||||
* File: CrowdSecAlert.cs *
|
||||
* *
|
||||
* This program is free software: you can redistribute it and/or modify *
|
||||
* it under the terms of the GNU General Public License as published by *
|
||||
* the Free Software Foundation, either version 3 of the License, or *
|
||||
* (at your option) any later version. *
|
||||
* *
|
||||
* You should have received a copy of the GNU General Public License *
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
|
||||
*************************************************************************/
|
||||
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Server.Network.Bans.CrowdSec;
|
||||
|
||||
/// <summary>One CrowdSec alert (<c>POST /v1/alerts</c> takes an array of these).</summary>
|
||||
public sealed class CrowdSecAlert
|
||||
{
|
||||
[JsonPropertyName("scenario")] public string Scenario { get; set; }
|
||||
[JsonPropertyName("message")] public string Message { get; set; }
|
||||
[JsonPropertyName("events_count")] public int EventsCount { get; set; } = 1;
|
||||
[JsonPropertyName("start_at")] public string StartAt { get; set; }
|
||||
[JsonPropertyName("stop_at")] public string StopAt { get; set; }
|
||||
[JsonPropertyName("capacity")] public int Capacity { get; set; }
|
||||
[JsonPropertyName("leakspeed")] public string LeakSpeed { get; set; } = "0s";
|
||||
[JsonPropertyName("simulated")] public bool Simulated { get; set; }
|
||||
[JsonPropertyName("events")] public object[] Events { get; set; } = [];
|
||||
[JsonPropertyName("remediation")] public bool Remediation { get; set; } = true;
|
||||
[JsonPropertyName("source")] public CrowdSecSource Source { get; set; }
|
||||
[JsonPropertyName("decisions")] public CrowdSecDecisionDto[] Decisions { get; set; }
|
||||
}
|
||||
|
||||
public sealed class CrowdSecSource
|
||||
{
|
||||
[JsonPropertyName("scope")] public string Scope { get; set; } = "Ip";
|
||||
[JsonPropertyName("value")] public string Value { get; set; }
|
||||
}
|
||||
|
||||
public sealed class CrowdSecDecisionDto
|
||||
{
|
||||
[JsonPropertyName("origin")] public string Origin { get; set; }
|
||||
[JsonPropertyName("type")] public string Type { get; set; } = "ban";
|
||||
[JsonPropertyName("scope")] public string Scope { get; set; } = "Ip";
|
||||
[JsonPropertyName("value")] public string Value { get; set; }
|
||||
[JsonPropertyName("duration")] public string Duration { get; set; }
|
||||
[JsonPropertyName("scenario")] public string Scenario { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Watcher login request/response for <c>POST /v1/watchers/login</c>.</summary>
|
||||
public sealed class CrowdSecLoginRequest
|
||||
{
|
||||
[JsonPropertyName("machine_id")] public string MachineId { get; set; }
|
||||
[JsonPropertyName("password")] public string Password { get; set; }
|
||||
}
|
||||
|
||||
public sealed class CrowdSecLoginResponse
|
||||
{
|
||||
[JsonPropertyName("code")] public int Code { get; set; }
|
||||
[JsonPropertyName("token")] public string Token { get; set; }
|
||||
[JsonPropertyName("expire")] public string Expire { get; set; }
|
||||
}
|
||||
137
Projects/UOContent/Misc/CrowdSec/CrowdSecAlertClient.cs
Normal file
137
Projects/UOContent/Misc/CrowdSec/CrowdSecAlertClient.cs
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
/*************************************************************************
|
||||
* ModernUO *
|
||||
* Copyright 2019-2026 - ModernUO Development Team *
|
||||
* Email: hi@modernuo.com *
|
||||
* File: CrowdSecAlertClient.cs *
|
||||
* *
|
||||
* This program is free software: you can redistribute it and/or modify *
|
||||
* it under the terms of the GNU General Public License as published by *
|
||||
* the Free Software Foundation, either version 3 of the License, or *
|
||||
* (at your option) any later version. *
|
||||
* *
|
||||
* You should have received a copy of the GNU General Public License *
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
|
||||
*************************************************************************/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Server.Network.Bans.CrowdSec;
|
||||
|
||||
/// <summary>Reporter-side LAPI operations, mockable for tests.</summary>
|
||||
public interface ICrowdSecAlertClient : IDisposable
|
||||
{
|
||||
ValueTask PostAlertsAsync(IReadOnlyList<CrowdSecAlert> alerts, CancellationToken token);
|
||||
ValueTask DeleteDecisionsAsync(string origin, IPAddress ip, CancellationToken token);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// CrowdSec LAPI watcher client: authenticates with machine credentials and posts/deletes decisions.
|
||||
/// Holds a JWT refreshed on expiry or a 401.
|
||||
/// </summary>
|
||||
public sealed class CrowdSecAlertClient : ICrowdSecAlertClient
|
||||
{
|
||||
private static readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
private readonly HttpClient _http;
|
||||
private readonly string _machineId;
|
||||
private readonly string _password;
|
||||
|
||||
private string _token;
|
||||
private DateTime _tokenExpiresUtc = DateTime.MinValue;
|
||||
|
||||
public CrowdSecAlertClient(CrowdSecSettings settings)
|
||||
{
|
||||
var baseUri = new Uri(settings.LapiUrl, UriKind.Absolute); // fails loud on malformed url
|
||||
_http = new HttpClient { BaseAddress = baseUri, Timeout = TimeSpan.FromSeconds(30) };
|
||||
_http.DefaultRequestHeaders.Add("User-Agent", "ModernUO-watcher/1.0");
|
||||
_machineId = settings.MachineId;
|
||||
_password = settings.Password;
|
||||
}
|
||||
|
||||
private async Task EnsureAuthAsync(CancellationToken token)
|
||||
{
|
||||
if (_token != null && DateTime.UtcNow < _tokenExpiresUtc - TimeSpan.FromMinutes(1))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var request = new CrowdSecLoginRequest { MachineId = _machineId, Password = _password };
|
||||
using var response = await _http.PostAsJsonAsync("/v1/watchers/login", request, _jsonOptions, token)
|
||||
.ConfigureAwait(false);
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
var login = await response.Content.ReadFromJsonAsync<CrowdSecLoginResponse>(_jsonOptions, token)
|
||||
.ConfigureAwait(false);
|
||||
_token = login?.Token ?? throw new InvalidOperationException("CrowdSec login returned no token.");
|
||||
_tokenExpiresUtc = DateTime.TryParse(login.Expire, out var exp) ? exp.ToUniversalTime() : DateTime.UtcNow.AddHours(1);
|
||||
}
|
||||
|
||||
private void Authorize(HttpRequestMessage message) =>
|
||||
message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _token);
|
||||
|
||||
public async ValueTask PostAlertsAsync(IReadOnlyList<CrowdSecAlert> alerts, CancellationToken token)
|
||||
{
|
||||
if (alerts.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await SendWithRetryAsync(() =>
|
||||
{
|
||||
var message = new HttpRequestMessage(HttpMethod.Post, "/v1/alerts")
|
||||
{
|
||||
Content = JsonContent.Create(alerts, options: _jsonOptions)
|
||||
};
|
||||
Authorize(message);
|
||||
return message;
|
||||
}, token).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async ValueTask DeleteDecisionsAsync(string origin, IPAddress ip, CancellationToken token)
|
||||
{
|
||||
var query = BuildDeleteQuery(origin, ip);
|
||||
await SendWithRetryAsync(() =>
|
||||
{
|
||||
var message = new HttpRequestMessage(HttpMethod.Delete, query);
|
||||
Authorize(message);
|
||||
return message;
|
||||
}, token).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the decisions-delete query string. <paramref name="origin"/> is operator-controlled config
|
||||
/// (crowdsec.json), so it must be escaped like any other untrusted value going into a URL.
|
||||
/// </summary>
|
||||
internal static string BuildDeleteQuery(string origin, IPAddress ip) =>
|
||||
$"/v1/decisions?origin={Uri.EscapeDataString(origin)}&ip={Uri.EscapeDataString(ip.ToString())}";
|
||||
|
||||
private async ValueTask SendWithRetryAsync(Func<HttpRequestMessage> build, CancellationToken token)
|
||||
{
|
||||
await EnsureAuthAsync(token).ConfigureAwait(false);
|
||||
|
||||
using var first = build();
|
||||
using var response = await _http.SendAsync(first, token).ConfigureAwait(false);
|
||||
if (response.StatusCode != HttpStatusCode.Unauthorized)
|
||||
{
|
||||
response.EnsureSuccessStatusCode();
|
||||
return;
|
||||
}
|
||||
|
||||
// Token rejected mid-flight: force a re-login and retry once.
|
||||
_token = null;
|
||||
await EnsureAuthAsync(token).ConfigureAwait(false);
|
||||
using var retry = build();
|
||||
using var retryResponse = await _http.SendAsync(retry, token).ConfigureAwait(false);
|
||||
retryResponse.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
public void Dispose() => _http.Dispose();
|
||||
}
|
||||
101
Projects/UOContent/Misc/CrowdSec/CrowdSecConfiguration.cs
Normal file
101
Projects/UOContent/Misc/CrowdSec/CrowdSecConfiguration.cs
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
/*************************************************************************
|
||||
* ModernUO *
|
||||
* Copyright 2019-2026 - ModernUO Development Team *
|
||||
* Email: hi@modernuo.com *
|
||||
* File: CrowdSecConfiguration.cs *
|
||||
* *
|
||||
* This program is free software: you can redistribute it and/or modify *
|
||||
* it under the terms of the GNU General Public License as published by *
|
||||
* the Free Software Foundation, either version 3 of the License, or *
|
||||
* (at your option) any later version. *
|
||||
* *
|
||||
* You should have received a copy of the GNU General Public License *
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
|
||||
*************************************************************************/
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text.Json.Serialization;
|
||||
using Server.Json;
|
||||
|
||||
namespace Server.Network.Bans.CrowdSec;
|
||||
|
||||
/// <summary>
|
||||
/// Loads the <see cref="CrowdSecSettings"/> from <c>Configuration/crowdsec.json</c> (matching the
|
||||
/// per-feature JSON config pattern used by <c>AssistantConfiguration</c>). Loaded once; a missing file
|
||||
/// writes a disabled-by-default template so operators have something to edit.
|
||||
/// </summary>
|
||||
public static class CrowdSecConfiguration
|
||||
{
|
||||
private const string _path = "Configuration/crowdsec.json";
|
||||
|
||||
public static CrowdSecSettings Settings { get; private set; }
|
||||
|
||||
public static void Load()
|
||||
{
|
||||
var path = Path.Join(Core.BaseDirectory, _path);
|
||||
|
||||
if (File.Exists(path))
|
||||
{
|
||||
Settings = JsonConfig.Deserialize<CrowdSecSettings>(path);
|
||||
}
|
||||
else
|
||||
{
|
||||
Settings = new CrowdSecSettings
|
||||
{
|
||||
LapiUrl = "http://127.0.0.1:8080",
|
||||
MachineId = "",
|
||||
Password = "",
|
||||
Origin = "modernuo",
|
||||
ManualBanDuration = TimeSpan.FromHours(168),
|
||||
FlushInterval = TimeSpan.FromSeconds(1),
|
||||
MaxQueue = 10000
|
||||
};
|
||||
|
||||
Save();
|
||||
}
|
||||
}
|
||||
|
||||
private static void Save()
|
||||
{
|
||||
JsonConfig.Serialize(Path.Join(Core.BaseDirectory, _path), Settings);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Bound configuration for <see cref="CrowdSecReporter"/>. Read once at <c>Configure()</c>.
|
||||
/// The reporter is inert unless <see cref="ReportingEnabled"/> is true.
|
||||
/// </summary>
|
||||
public record CrowdSecSettings
|
||||
{
|
||||
/// <summary>LAPI endpoint. Default <c>http://127.0.0.1:8080</c>.</summary>
|
||||
[JsonPropertyName("lapiUrl")]
|
||||
public string LapiUrl { get; set; } = "http://127.0.0.1:8080";
|
||||
|
||||
/// <summary>Watcher machine id from <c>cscli machines add</c>. Empty disables reporting.</summary>
|
||||
[JsonPropertyName("machineId")]
|
||||
public string MachineId { get; set; } = "";
|
||||
|
||||
/// <summary>Watcher password paired with <see cref="MachineId"/>.</summary>
|
||||
[JsonPropertyName("password")]
|
||||
public string Password { get; set; } = "";
|
||||
|
||||
/// <summary>Decision <c>origin</c> stamped on our contributions. Default <c>modernuo</c>.</summary>
|
||||
[JsonPropertyName("origin")]
|
||||
public string Origin { get; set; } = "modernuo";
|
||||
|
||||
/// <summary>Duration for manual admin bans pushed to CrowdSec. Default 168h (renewable). Finite so a missed retract self-heals.</summary>
|
||||
[JsonPropertyName("manualBanDuration")]
|
||||
public TimeSpan ManualBanDuration { get; set; } = TimeSpan.FromHours(168);
|
||||
|
||||
/// <summary>Max time the drain coalesces before flushing a batch. Default 1s.</summary>
|
||||
[JsonPropertyName("flushInterval")]
|
||||
public TimeSpan FlushInterval { get; set; } = TimeSpan.FromSeconds(1);
|
||||
|
||||
/// <summary>Bounded contribution queue capacity; overflow is dropped (counted). Default 10000.</summary>
|
||||
[JsonPropertyName("maxQueue")]
|
||||
public int MaxQueue { get; set; } = 10000;
|
||||
|
||||
[JsonIgnore]
|
||||
public bool ReportingEnabled => !string.IsNullOrWhiteSpace(MachineId) && !string.IsNullOrWhiteSpace(Password);
|
||||
}
|
||||
399
Projects/UOContent/Misc/CrowdSec/CrowdSecReporter.cs
Normal file
399
Projects/UOContent/Misc/CrowdSec/CrowdSecReporter.cs
Normal file
|
|
@ -0,0 +1,399 @@
|
|||
/*************************************************************************
|
||||
* ModernUO *
|
||||
* Copyright 2019-2026 - ModernUO Development Team *
|
||||
* Email: hi@modernuo.com *
|
||||
* File: CrowdSecReporter.cs *
|
||||
* *
|
||||
* This program is free software: you can redistribute it and/or modify *
|
||||
* it under the terms of the GNU General Public License as published by *
|
||||
* the Free Software Foundation, either version 3 of the License, or *
|
||||
* (at your option) any later version. *
|
||||
* *
|
||||
* You should have received a copy of the GNU General Public License *
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
|
||||
*************************************************************************/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net;
|
||||
using System.Threading;
|
||||
using System.Threading.Channels;
|
||||
using System.Threading.Tasks;
|
||||
using Server.Logging;
|
||||
|
||||
namespace Server.Network.Bans.CrowdSec;
|
||||
|
||||
/// <summary>
|
||||
/// Contributes locally-decided bans to CrowdSec via the LAPI alerts API. Non-blocking on the accept
|
||||
/// path: <see cref="Report"/> enqueues onto a bounded, drop-on-overflow channel drained by a single
|
||||
/// background task that coalesces by IP and POSTs batched alerts.
|
||||
/// </summary>
|
||||
public sealed class CrowdSecReporter : IBanReporter
|
||||
{
|
||||
private static readonly ILogger logger = LogFactory.GetLogger(typeof(CrowdSecReporter));
|
||||
|
||||
internal readonly record struct ReportItem(IPAddress Ip, TimeSpan Ttl, string Reason, bool Retract);
|
||||
|
||||
// Bounded retry for transient LAPI failures during a drain send (network blips, 5xx). Distinct from
|
||||
// CrowdSecAlertClient.SendWithRetryAsync's single 401-relogin retry, which is an auth concern.
|
||||
private static readonly TimeSpan[] _retryDelays = [TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2)];
|
||||
|
||||
private ICrowdSecAlertClient _client;
|
||||
private CrowdSecSettings _settings;
|
||||
private Channel<ReportItem> _queue;
|
||||
private CancellationTokenSource _cts;
|
||||
private Task _drainTask;
|
||||
private int _dropped;
|
||||
private int _sendFailures;
|
||||
|
||||
public CrowdSecReporter()
|
||||
{
|
||||
}
|
||||
|
||||
// Test/embedding ctor with an injected client + settings.
|
||||
internal CrowdSecReporter(ICrowdSecAlertClient client, CrowdSecSettings settings)
|
||||
{
|
||||
_client = client;
|
||||
_settings = settings;
|
||||
_queue = CreateQueue(settings.MaxQueue);
|
||||
}
|
||||
|
||||
public string Name => "crowdsec";
|
||||
public bool CanRetract => true;
|
||||
public int DroppedCount => _dropped;
|
||||
|
||||
/// <summary>
|
||||
/// Batches ultimately dropped after the bounded transient-retry in <see cref="DrainLoop"/> gave up.
|
||||
/// Distinct from <see cref="DroppedCount"/> (queue-overflow drops on the accept path): this counts
|
||||
/// sustained LAPI outages so operators can see contribution loss instead of it being silent.
|
||||
/// </summary>
|
||||
public int SendFailureCount => _sendFailures;
|
||||
|
||||
/// <summary>The drain loop's task, so tests can assert it stays alive until the loop exits.</summary>
|
||||
internal Task DrainTaskForTesting => _drainTask;
|
||||
|
||||
public static void Configure()
|
||||
{
|
||||
BanChannel.Register(new CrowdSecReporter());
|
||||
}
|
||||
|
||||
public void Register()
|
||||
{
|
||||
CrowdSecConfiguration.Load();
|
||||
_settings ??= CrowdSecConfiguration.Settings;
|
||||
}
|
||||
|
||||
public void Start(CancellationToken token)
|
||||
{
|
||||
if (!_settings.ReportingEnabled)
|
||||
{
|
||||
logger.Information("CrowdSec reporter disabled (machineId/password empty in crowdsec.json)");
|
||||
return;
|
||||
}
|
||||
|
||||
_client ??= new CrowdSecAlertClient(_settings);
|
||||
_queue ??= CreateQueue(_settings.MaxQueue);
|
||||
_cts = CancellationTokenSource.CreateLinkedTokenSource(token);
|
||||
_drainTask = Task.Run(() => DrainLoop(_cts.Token), _cts.Token);
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
_cts?.Cancel();
|
||||
|
||||
// The flush below reads a SingleReader channel, so wait for the drain to actually exit first.
|
||||
var drainExited = true;
|
||||
try
|
||||
{
|
||||
// Wait(timeout) is false only on timeout; a throw means faulted/cancelled, which is still exited.
|
||||
drainExited = _drainTask == null || _drainTask.Wait(TimeSpan.FromSeconds(2));
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Ignored: a faulted wait means the drain has completed and released the channel.
|
||||
}
|
||||
|
||||
_cts?.Dispose();
|
||||
_cts = null;
|
||||
|
||||
if (drainExited)
|
||||
{
|
||||
FlushRemainingOnStop();
|
||||
}
|
||||
|
||||
_client?.Dispose();
|
||||
_drainTask = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Best-effort bounded flush of whatever is still queued at shutdown. Blocking is correct here — the
|
||||
/// loop has stopped ticking — but must not happen on the loop thread: <see cref="Stop"/> runs where
|
||||
/// <c>SynchronizationContext.Current</c> is the <c>EventLoopContext</c>, and a captured continuation
|
||||
/// would be posted to a queue nothing pumps any more. <see cref="Task.Run(Func{Task})"/> keeps the
|
||||
/// chain on the pool; the bounded wait caps a wedged send at a few seconds of shutdown.
|
||||
/// </summary>
|
||||
private void FlushRemainingOnStop()
|
||||
{
|
||||
if (_queue == null || _client == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_queue.Writer.TryComplete();
|
||||
|
||||
List<ReportItem> reports = [];
|
||||
List<ReportItem> retracts = [];
|
||||
while (_queue.Reader.TryRead(out var item))
|
||||
{
|
||||
(item.Retract ? retracts : reports).Add(item);
|
||||
}
|
||||
|
||||
if (reports.Count == 0 && retracts.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (!Task.Run(() => FlushRemainingOnStopAsync(reports, retracts)).Wait(TimeSpan.FromSeconds(4)))
|
||||
{
|
||||
logger.Warning(
|
||||
"CrowdSec flush-on-stop timed out; {Count} item(s) not contributed",
|
||||
reports.Count + retracts.Count
|
||||
);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.Warning(e, "CrowdSec flush-on-stop failed");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Uses a fresh token, not the drain loop's already-cancelled one, which would fail every send
|
||||
/// immediately. Reports go as one deduped batch; retracts go as individual DELETEs so an admin's
|
||||
/// unban propagates on a clean shutdown. Leftovers self-heal via
|
||||
/// <see cref="CrowdSecSettings.ManualBanDuration"/>.
|
||||
/// </summary>
|
||||
private async Task FlushRemainingOnStopAsync(List<ReportItem> reports, List<ReportItem> retracts)
|
||||
{
|
||||
using var flushCts = new CancellationTokenSource(TimeSpan.FromSeconds(3));
|
||||
|
||||
if (reports.Count > 0)
|
||||
{
|
||||
var alerts = BuildAlerts(reports, _settings, DateTime.UtcNow);
|
||||
try
|
||||
{
|
||||
await _client.PostAlertsAsync(alerts, flushCts.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.Warning(e, "CrowdSec flush-on-stop reports failed");
|
||||
RecordSendFailure(alerts.Count);
|
||||
}
|
||||
}
|
||||
|
||||
HashSet<string> seen = [];
|
||||
for (var i = 0; i < retracts.Count; i++)
|
||||
{
|
||||
if (flushCts.IsCancellationRequested)
|
||||
{
|
||||
break; // out of budget; the rest self-heal via ManualBanDuration
|
||||
}
|
||||
|
||||
var ip = retracts[i].Ip;
|
||||
if (!seen.Add(ip.ToString()))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await _client.DeleteDecisionsAsync(_settings.Origin, ip, flushCts.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.Warning(e, "CrowdSec flush-on-stop retract failed for {Address}", ip);
|
||||
RecordSendFailure(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Report(IPAddress address, TimeSpan ttl, string reason) =>
|
||||
Enqueue(new ReportItem(address, ttl, reason, false));
|
||||
|
||||
public void Retract(IPAddress address) =>
|
||||
Enqueue(new ReportItem(address, TimeSpan.Zero, "retract", true));
|
||||
|
||||
private void Enqueue(ReportItem item)
|
||||
{
|
||||
if (_queue == null || !_queue.Writer.TryWrite(item))
|
||||
{
|
||||
Interlocked.Increment(ref _dropped);
|
||||
}
|
||||
}
|
||||
|
||||
// FullMode.Wait (the default) makes TryWrite return false immediately when the channel is full
|
||||
// instead of blocking the caller — exactly the non-blocking drop-on-overflow behavior the accept
|
||||
// path requires. DropWrite would silently discard the new item and always report success, which
|
||||
// would make overflow undetectable.
|
||||
private static Channel<ReportItem> CreateQueue(int capacity) =>
|
||||
Channel.CreateBounded<ReportItem>(new BoundedChannelOptions(Math.Max(1, capacity))
|
||||
{
|
||||
FullMode = BoundedChannelFullMode.Wait,
|
||||
SingleReader = true
|
||||
});
|
||||
|
||||
// Must return Task: Start() passes this to Task.Run, which has no Func<ValueTask> overload, so a
|
||||
// ValueTask would bind to Task.Run<TResult> and yield a Task<ValueTask> that completes at the first
|
||||
// await rather than when the loop exits.
|
||||
private async Task DrainLoop(CancellationToken token)
|
||||
{
|
||||
var reader = _queue.Reader;
|
||||
|
||||
while (!token.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!await reader.WaitToReadAsync(token).ConfigureAwait(false))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Coalesce a burst before flushing.
|
||||
await Task.Delay(_settings.FlushInterval, token).ConfigureAwait(false);
|
||||
|
||||
List<ReportItem> reports = [];
|
||||
List<ReportItem> retracts = [];
|
||||
while (reader.TryRead(out var item))
|
||||
{
|
||||
(item.Retract ? retracts : reports).Add(item);
|
||||
}
|
||||
|
||||
if (reports.Count > 0)
|
||||
{
|
||||
var alerts = BuildAlerts(reports, _settings, DateTime.UtcNow);
|
||||
if (!await SendWithBoundedRetryAsync(() => _client.PostAlertsAsync(alerts, token), token)
|
||||
.ConfigureAwait(false))
|
||||
{
|
||||
RecordSendFailure(alerts.Count);
|
||||
}
|
||||
}
|
||||
|
||||
for (var i = 0; i < retracts.Count; i++)
|
||||
{
|
||||
var ip = retracts[i].Ip;
|
||||
if (!await SendWithBoundedRetryAsync(() => _client.DeleteDecisionsAsync(_settings.Origin, ip, token), token)
|
||||
.ConfigureAwait(false))
|
||||
{
|
||||
RecordSendFailure(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// Contribution is auxiliary: log and keep draining. Never crash the shard.
|
||||
logger.Warning(e, "CrowdSec contribution flush failed; dropped this batch");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends with up to 3 attempts total (1 initial + 2 retries), backing off 1s then 2s between
|
||||
/// attempts, for transient LAPI failures (network blips, 5xx). Backoff uses <see cref="Task.Delay"/>
|
||||
/// so it never blocks the thread; a cancellation during backoff propagates as
|
||||
/// <see cref="OperationCanceledException"/> so the drain loop exits cleanly. Returns false (never
|
||||
/// throws for a send failure) once attempts are exhausted, so the caller can count the drop and keep
|
||||
/// draining instead of losing the rest of the batch/queue.
|
||||
/// </summary>
|
||||
private static async ValueTask<bool> SendWithBoundedRetryAsync(Func<ValueTask> send, CancellationToken token)
|
||||
{
|
||||
for (var attempt = 0; ; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
await send().ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
if (attempt >= _retryDelays.Length)
|
||||
{
|
||||
logger.Warning(e, "CrowdSec send failed after {Attempts} attempt(s); giving up", attempt + 1);
|
||||
return false;
|
||||
}
|
||||
|
||||
var delay = _retryDelays[attempt];
|
||||
logger.Warning(e, "CrowdSec send failed (attempt {Attempt}); retrying in {Delay}", attempt + 1, delay);
|
||||
await Task.Delay(delay, token).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void RecordSendFailure(int itemCount)
|
||||
{
|
||||
var total = Interlocked.Increment(ref _sendFailures);
|
||||
logger.Warning(
|
||||
"CrowdSec contribution batch dropped after retries ({Items} item(s)); total dropped batches: {Total}",
|
||||
itemCount,
|
||||
total
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>Coalesces items by IP (last write wins) and builds one alert per unique address.</summary>
|
||||
internal static List<CrowdSecAlert> BuildAlerts(IEnumerable<ReportItem> items, CrowdSecSettings settings, DateTime nowUtc)
|
||||
{
|
||||
Dictionary<string, ReportItem> byIp = [];
|
||||
foreach (var item in items)
|
||||
{
|
||||
byIp[item.Ip.ToString()] = item;
|
||||
}
|
||||
|
||||
var timestamp = nowUtc.ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
|
||||
var alerts = new List<CrowdSecAlert>(byIp.Count);
|
||||
|
||||
foreach (var (value, item) in byIp)
|
||||
{
|
||||
var ttl = item.Reason == "manual" || item.Ttl <= TimeSpan.Zero ? settings.ManualBanDuration : item.Ttl;
|
||||
var scenario = $"{settings.Origin}/{item.Reason}";
|
||||
|
||||
alerts.Add(new CrowdSecAlert
|
||||
{
|
||||
Scenario = scenario,
|
||||
Message = $"ModernUO {item.Reason} ban for {value}",
|
||||
StartAt = timestamp,
|
||||
StopAt = timestamp,
|
||||
Source = new CrowdSecSource { Scope = "Ip", Value = value },
|
||||
Decisions =
|
||||
[
|
||||
new CrowdSecDecisionDto
|
||||
{
|
||||
Origin = settings.Origin,
|
||||
Type = "ban",
|
||||
Scope = "Ip",
|
||||
Value = value,
|
||||
Duration = FormatDuration(ttl),
|
||||
Scenario = scenario
|
||||
}
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
return alerts;
|
||||
}
|
||||
|
||||
/// <summary>CrowdSec accepts Go durations; whole seconds are unambiguous and sufficient.</summary>
|
||||
internal static string FormatDuration(TimeSpan ttl)
|
||||
{
|
||||
var seconds = (long)ttl.TotalSeconds;
|
||||
return $"{Math.Max(1, seconds)}s";
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue