using System.Net; using System.Net.Sockets; using OpenWaf.Domain.Policy; namespace OpenWaf.Domain.Engine; /// /// The identity a streak and a ban are keyed on (Q4). /// /// IPv4 is used as-is by default: one address is one source. IPv6 is grouped /// to its /64 — a subscriber is handed a whole /64 and a bot rotating /// addresses inside one allocation is still one source, which is the only way /// a v6 streak rule means anything. /// /// The known cost is stated rather than hidden: a shared-egress office behind /// one IPv4 is one source, so ten honest people browsing a broken page can /// add up to one ban. That is why the streak threshold counts *consecutive* /// refusals (an honest click resets it) and why the allowlist outranks every /// pillar. /// public static class SourceKey { public static string For(IPAddress? address, EdgePolicy policy) => address is null ? string.Empty : For(address.ToString(), policy); public static string For(string address, EdgePolicy policy) { if (!TryParse(address, out var ip, out var mapped)) return Invalid(address); return KeyFor(mapped, policy); } /// Normalise an address string, resolving IPv4-mapped IPv6 /// (::ffff:203.0.113.7) to the v4 form so the same host never appears as /// two sources. public static bool TryParse(string? address, out IPAddress raw, out IPAddress normalized) { raw = IPAddress.None; normalized = IPAddress.None; if (string.IsNullOrWhiteSpace(address)) return false; if (!IPAddress.TryParse(address.Trim(), out var parsed)) return false; raw = parsed; normalized = parsed.AddressFamily == AddressFamily.InterNetworkV6 && parsed.IsIPv4MappedToIPv6 ? parsed.MapToIPv4() : parsed; return true; } private static string KeyFor(IPAddress ip, EdgePolicy policy) { var prefix = ip.AddressFamily == AddressFamily.InterNetwork ? Clamp(policy.Ipv4KeyPrefixLength, 0, 32) : Clamp(policy.Ipv6KeyPrefixLength, 0, 128); if (prefix == (ip.AddressFamily == AddressFamily.InterNetwork ? 32 : 128)) { return ip.ToString(); } var masked = Mask(ip, prefix); return prefix == 0 ? "*" : $"{masked}/{prefix}"; } public static IPAddress Mask(IPAddress ip, int prefixLength) { var bytes = ip.GetAddressBytes(); var bits = bytes.Length * 8; var p = Clamp(prefixLength, 0, bits); // The partial octet has to be masked before the octets after it are // zeroed, or the mask lands on a byte that is already zero and the // prefix silently widens (198.51.100.24/19 would become 198.51.0.0). var firstZeroed = p / 8; if (p % 8 != 0) { bytes[firstZeroed] &= (byte)(0xFF << (8 - (p % 8))); firstZeroed++; } for (var i = firstZeroed; i < bytes.Length; i++) bytes[i] = 0; return new IPAddress(bytes); } private static int Clamp(int v, int lo, int hi) => v < lo ? lo : (v > hi ? hi : v); private static string Invalid(string address) => $"invalid:{address}"; }