using System.Net;
using System.Net.Sockets;
using OpenWaf.Domain.Engine;
using OpenWaf.Domain.Policy;
namespace OpenWaf.Domain.Security;
///
/// A netblock the edge's own bans point at (OPEN-67). This is not a decision
/// and nothing here enforces anything: it says "these N live engine bans all
/// sit inside this one block", which is a fact about the edge's list, not a
/// claim that the block is one farm. Twenty honest visitors of one provider and
/// one scanner rotating through one rented /24 produce the same number, and
/// only the operator can tell them apart — which is why the candidate ends as a
/// suggestion on a surface and never as a row in the block list.
///
/// The block in the one CIDR spelling OPEN-66 stores and
/// enforces, so the string on the surface is the string the block form takes.
/// How many live engine bans sit inside it.
/// A few of those keys, so the operator can check the
/// claim against the rows rather than trust the count.
/// Whether a live operator range already covers this
/// block — the offer has been taken, and the row in the block list is the answer.
public sealed record NetblockCandidate(
string Match,
int Prefix,
int Bans,
DateTimeOffset FirstBanAt,
DateTimeOffset LastBanAt,
IReadOnlyList Sample,
bool AlreadyBanned);
/// The grouping rules, as pure functions: the arithmetic a reader has
/// to check sits in one place and is testable without a database.
public static class Netblocks
{
/// How many of a candidate's addresses the surface shows.
public const int SampleSize = 3;
/// The prefix a ban key itself names: 32 for a bare v4 address, 64
/// for a v6 key written "a:b:c:d::/64", -1 when the key names no address at
/// all (the "*" a /0 source key becomes).
public static int KeyPrefix(string? banKey)
{
if (!TryKeyAddress(banKey, out var ip)) return -1;
var full = ip.AddressFamily == AddressFamily.InterNetwork ? 32 : 128;
var slash = banKey!.Trim().IndexOf('/');
if (slash < 0) return full;
return int.TryParse(banKey.Trim()[(slash + 1)..], out var prefix) ? prefix : -1;
}
/// The address a ban key names, whether the key was written as one
/// address or as a block. The v6 key the engine stores is a block —
/// "2001:db8:1:2::/64" — so a parser that only accepts bare addresses cannot
/// see the bans it is supposed to group.
private static bool TryKeyAddress(string? banKey, out IPAddress address)
{
address = IPAddress.None;
if (string.IsNullOrWhiteSpace(banKey)) return false;
var text = banKey.Trim();
var slash = text.IndexOf('/');
if (slash >= 0) text = text[..slash];
return SourceKey.TryParse(text, out _, out address);
}
/// The block this ban key sits under, or null when the key is not
/// evidence about one block.
public static string? Covering(string? banKey, EdgePolicy policy)
{
if (!TryKeyAddress(banKey, out var ip)) return null;
var prefix = NetblockPrefix(ip.AddressFamily, policy);
return $"{SourceKey.Mask(ip, prefix)}/{prefix}";
}
public static int NetblockPrefix(AddressFamily family, EdgePolicy policy)
=> family == AddressFamily.InterNetwork ? policy.NetblockPrefixV4 : policy.NetblockPrefixV6;
/// Group live engine bans into the blocks they point at and keep
/// the blocks with enough of them to be worth showing.
public static IReadOnlyList Candidates(
IEnumerable<(string Key, DateTimeOffset CreatedAt)> liveEngineBans,
EdgePolicy policy,
NetworkBanIndex operatorRanges,
DateTimeOffset now)
{
if (policy.NetblockCandidateBans <= 0) return [];
var groups = new Dictionary(StringComparer.Ordinal);
foreach (var (key, createdAt) in liveEngineBans)
{
if (!TryKeyAddress(key, out var ip)) continue;
var ownPrefix = KeyPrefix(key);
// A key that names no address at all (the "*" a /0 source key
// becomes) is inside no block, and a ban whose own key is a block
// wider than the netblock prefix is not evidence about one netblock:
// counting the /8 the operator keyed on as "one ban inside
// 198.51.100.0/24" would invent a candidate out of a row that
// already claims more than that.
if (ownPrefix < 0 || ownPrefix < NetblockPrefix(ip.AddressFamily, policy)) continue;
var prefix = NetblockPrefix(ip.AddressFamily, policy);
var match = $"{SourceKey.Mask(ip, prefix)}/{prefix}";
if (!groups.TryGetValue(match, out var group)) groups[match] = group = new Group();
group.Add(key, createdAt);
}
var candidates = new List();
foreach (var (match, group) in groups)
{
if (group.Count < policy.NetblockCandidateBans) continue;
var slash = match.IndexOf('/');
// The block's own address answers the question "is this block
// already inside a range the operator wrote?" — a range equal to it
// or broader covers that address, and a narrower one does not.
var covered = operatorRanges.Covers(match[..slash], now);
candidates.Add(new NetblockCandidate(
match, NetworkBans.PrefixOf(match), group.Count, group.First, group.Last,
group.Sample(), covered));
}
candidates.Sort((a, b) =>
{
var byBans = b.Bans.CompareTo(a.Bans);
return byBans != 0 ? byBans : string.CompareOrdinal(a.Match, b.Match);
});
return candidates;
}
private sealed class Group
{
private readonly List _sample = [];
public int Count { get; private set; }
public DateTimeOffset First { get; private set; }
public DateTimeOffset Last { get; private set; }
public void Add(string key, DateTimeOffset createdAt)
{
Count++;
if (Count == 1 || createdAt < First) First = createdAt;
if (Count == 1 || createdAt > Last) Last = createdAt;
if (_sample.Count < SampleSize && !_sample.Contains(key, StringComparer.Ordinal)) _sample.Add(key);
}
public IReadOnlyList Sample() => _sample;
}
}