feat: Moves TcpServer to another thread. Rewrites Firewall (#1660)

## Breaking Changes
* The Firewall and IP Limiter have been rewritten. Please read the notes carefully!
* `TcpServer.Instances` moved back to `NetState.Instances` - sorry - it was stupid to move it to begin with.

> [!Note]
> Sockets that fail the IP Limiter or Firewall will be immediately and forcibly disconnected.
> This means they will be stuck at "Verifying account..." if it was a real client.

### Summary
- Removes firewall wildcard support.
- Removes `AccessRestrictions`.
- Moves Firewall/IPLimiter to the core.
- Moves `TcpServer` to its own thread.
- Removes the `SocketConnect` and `SocketDisconnect` event sinks.
- Moves `Instances` back to `NetState.Instances`.
- Fixes a long standing bug with bad handling of duplicate listener addresses.

#### Firewall
The firewall has been completely rewritten. There is now an "Admin Firewall" which saves to the config file. Secondarily, there is an internal firewall used exclusively by the TcpServer while processing sockets. The Admin firewall mirrors it's additions/deletions to the internal firewall by adding requests to a queue.

> [!IMPORTANT]  
> **Wildcard firewall entries, such as `X`, `*`, `?` are not allowed.**
> **Ranges in between IP classes or sextets are not allowed.**
> **Please make sure to use one of the following:**
> * IP Address - `192.168.1.1`
> * CIDR - `192.168.1.0/24`
> * Range - `192.168.1.1-192.168.1.100`

#### IP Limiter
The IP Limiter has been completely rewritten. The available configurations are:
```json
"ipLimiter.enable": "True",
"ipLimiter.maxConnectionsPerIP": 10,
"ipLimiter.clearConnectionAttemptsDuration": "00:00:00:10",
"ipLimiter.clearThrottledDuration": "00:00:02:00",
```

The IP Limiter is set up to prevent spamming connections from the same IP. Every time an IP connects, it is added to a connection list. After 10 attempts, the IP is added to the throttle list. To keep the system fast, the connection list is entirely wiped every 10 seconds, and the throttle list is entirely wiped every 2 minutes.
This commit is contained in:
Kamron Batman 2024-01-20 14:25:12 -08:00 • committed by GitHub
parent 5f3de6537b
commit 4cd668ef61
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
38 changed files with 1117 additions and 1030 deletions

View file

@ -1,48 +0,0 @@
using System.IO;
using System.Net;
using Server.Logging;
using Server.Misc;
namespace Server
{
public static class AccessRestrictions
{
private static readonly ILogger logger = LogFactory.GetLogger(typeof(AccessRestrictions));
public static void Initialize()
{
EventSink.SocketConnect += EventSink_SocketConnect;
}
private static void EventSink_SocketConnect(SocketConnectEventArgs e)
{
try
{
var ip = (e.Connection.RemoteEndPoint as IPEndPoint)?.Address;
if (Firewall.IsBlocked(ip))
{
logger.Information("Client: {IP}: Firewall blocked connection attempt.", ip);
e.AllowConnection = false;
return;
}
if (IPLimiter.SocketBlock && !IPLimiter.Verify(ip))
{
logger.Warning("Client: {IP}: Past IP limit threshold", ip);
using (var op = new StreamWriter("ipLimits.log", true))
{
op.WriteLine("{0}\tPast IP limit threshold\t{1}", ip, Core.Now);
}
e.AllowConnection = false;
}
}
catch
{
e.AllowConnection = false;
}
}
}
}

View file

@ -136,7 +136,7 @@ public static class AccountHandler
{
var ipAddress = ns.Address;
if (Utility.IPMatchClassC(accessList[0], ipAddress))
if (accessList[0].MatchClassC(ipAddress))
{
acct.SetPassword(pass);
from.SendMessage("The password to your account has changed.");
@ -302,19 +302,6 @@ public static class AccountHandler
public static void EventSink_AccountLogin(AccountLoginEventArgs e)
{
if (!IPLimiter.SocketBlock && !IPLimiter.Verify(e.State.Address))
{
e.Accepted = false;
e.RejectReason = ALRReason.InUse;
logger.Information("Login: {NetState}: Past IP limit threshold", e.State);
using var op = new StreamWriter("ipLimits.log", true);
op.WriteLine($"{e.State}\tPast IP limit threshold\t{Core.Now}");
return;
}
var un = e.Username;
var pw = e.Password;
@ -371,18 +358,6 @@ public static class AccountHandler
public static void EventSink_GameLogin(GameLoginEventArgs e)
{
if (!IPLimiter.SocketBlock && !IPLimiter.Verify(e.State.Address))
{
e.Accepted = false;
logger.Warning("Login: {NetState} Past IP limit threshold", e.State);
using var op = new StreamWriter("ipLimits.log", true);
op.WriteLine($"{e.State}\tPast IP limit threshold\t{Core.Now}");
return;
}
var un = e.Username;
var pw = e.Password;

View file

@ -1,233 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Runtime.CompilerServices;
using CommunityToolkit.HighPerformance;
namespace Server
{
public static class Firewall
{
private const string firewallConfigPath = "firewall.cfg";
static Firewall()
{
Set = new HashSet<IFirewallEntry>();
if (File.Exists(firewallConfigPath))
{
using var ip = new StreamReader(firewallConfigPath);
string line;
while ((line = ip.ReadLine()) != null)
{
line = line.Trim();
if (line.Length == 0)
{
continue;
}
Set.Add(ToFirewallEntry(line));
}
}
}
public static HashSet<IFirewallEntry> Set { get; }
public static IFirewallEntry ToFirewallEntry(object entry)
{
return entry switch
{
IFirewallEntry firewallEntry => firewallEntry,
IPAddress address => new IPFirewallEntry(address),
string s => ToFirewallEntry(s),
_ => null
};
}
public static IFirewallEntry ToFirewallEntry(string entry)
{
if (entry == null)
{
return null;
}
if (IPAddress.TryParse(entry, out var addr))
{
return new IPFirewallEntry(addr);
}
// Try CIDR parse
var tokenizer = entry.Tokenize('/');
var ip = tokenizer.MoveNext() ? tokenizer.Current : null;
var length = tokenizer.MoveNext() ? tokenizer.Current : null;
if (
length != null &&
IPAddress.TryParse(ip, out var cidrPrefix) &&
int.TryParse(length, out var cidrLength)
)
{
return new CIDRFirewallEntry(cidrPrefix, cidrLength);
}
return new WildcardIPFirewallEntry(entry);
}
public static void Remove(object obj)
{
var entry = ToFirewallEntry(obj);
if (entry != null)
{
Set.Remove(entry);
Save();
}
}
public static void Add(object obj)
{
Add(ToFirewallEntry(obj));
}
public static void Add(IFirewallEntry entry)
{
Set.Add(entry);
Save();
}
public static void Add(string pattern)
{
Add(ToFirewallEntry(pattern));
}
public static void Add(IPAddress ip)
{
Add(ToFirewallEntry(ip));
}
public static void Save()
{
using var op = new StreamWriter(firewallConfigPath);
foreach (var entry in Set)
{
op.WriteLine(entry);
}
}
public static bool IsBlocked(IPAddress ip)
{
foreach (var entry in Set)
{
if (entry.IsBlocked(ip))
{
return true;
}
}
return false;
}
public interface IFirewallEntry
{
bool IsBlocked(IPAddress address);
}
public class IPFirewallEntry : IFirewallEntry
{
private readonly IPAddress m_Address;
public IPFirewallEntry(IPAddress address) => m_Address = address;
public bool IsBlocked(IPAddress address) => m_Address.Equals(address);
public override string ToString() => m_Address.ToString();
public override bool Equals(object obj)
{
return obj switch
{
IPAddress => obj.Equals(m_Address),
string s when IPAddress.TryParse(s, out var otherAddress) => otherAddress.Equals(m_Address),
IPFirewallEntry entry => m_Address.Equals(entry.m_Address),
_ => false
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override int GetHashCode() => m_Address.GetHashCode();
}
public class CIDRFirewallEntry : IFirewallEntry
{
private readonly int m_CIDRLength;
private readonly IPAddress m_CIDRPrefix;
public CIDRFirewallEntry(IPAddress cidrPrefix, int cidrLength)
{
m_CIDRPrefix = cidrPrefix;
m_CIDRLength = cidrLength;
}
public bool IsBlocked(IPAddress address) => Utility.IPMatchCIDR(m_CIDRPrefix, address, m_CIDRLength);
public override string ToString() => $"{m_CIDRPrefix}/{m_CIDRLength}";
public override bool Equals(object obj)
{
if (obj is string entry)
{
var str = entry.Split('/');
if (str.Length == 2)
{
if (IPAddress.TryParse(str[0], out var cidrPrefix))
{
if (int.TryParse(str[1], out var cidrLength))
{
return m_CIDRPrefix.Equals(cidrPrefix) && m_CIDRLength.Equals(cidrLength);
}
}
}
}
else if (obj is CIDRFirewallEntry cidrEntry)
{
return m_CIDRPrefix.Equals(cidrEntry.m_CIDRPrefix) && m_CIDRLength.Equals(cidrEntry.m_CIDRLength);
}
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override int GetHashCode() => HashCode.Combine(m_CIDRPrefix, m_CIDRLength);
}
public class WildcardIPFirewallEntry : IFirewallEntry
{
private readonly string m_Entry;
private bool m_Valid = true;
public WildcardIPFirewallEntry(string entry) => m_Entry = entry;
public bool IsBlocked(IPAddress address) => m_Valid && Utility.IPMatch(m_Entry, address, out m_Valid);
public override string ToString() => m_Entry;
public override bool Equals(object obj)
{
if (obj is string)
{
return obj.Equals(m_Entry);
}
return obj is WildcardIPFirewallEntry entry && m_Entry == entry.m_Entry;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override int GetHashCode() => m_Entry.GetHashCode(StringComparison.Ordinal);
}
}
}

View file

@ -1,62 +0,0 @@
using System.Net;
using Server.Network;
namespace Server.Misc
{
public static class IPLimiter
{
public static readonly IPAddress[] Exemptions =
{
IPAddress.Parse( "127.0.0.1" )
};
public static bool Enabled { get; private set; }
public static bool SocketBlock { get; private set; }
public static int MaxAddresses { get; private set; }
public static void Configure()
{
Enabled = ServerConfiguration.GetOrUpdateSetting("ipLimiter.enable", true);
SocketBlock = ServerConfiguration.GetOrUpdateSetting("ipLimiter.blockAtConnection", true);
MaxAddresses = ServerConfiguration.GetOrUpdateSetting("ipLimiter.maxConnectionsPerIP", 10);
}
public static bool IsExempt(IPAddress ip)
{
for (int i = 0; i < Exemptions.Length; i++)
{
if (ip.Equals(Exemptions[i]))
{
return true;
}
}
return false;
}
public static bool Verify(IPAddress ourAddress)
{
if (!Enabled || IsExempt(ourAddress))
{
return true;
}
var count = 0;
foreach (var ns in TcpServer.Instances)
{
if (ourAddress.Equals(ns.Address))
{
++count;
if (count >= MaxAddresses)
{
return false;
}
}
}
return true;
}
}
}