Skip to content

Commit

Permalink
Added persistent IP banning
Browse files Browse the repository at this point in the history
Enhanced performance during startup
  • Loading branch information
mingl0280 committed Apr 2, 2018
1 parent 06daa1c commit 2f30ea5
Show file tree
Hide file tree
Showing 9 changed files with 569 additions and 50 deletions.
62 changes: 61 additions & 1 deletion Fail2Ban-wsl-setup/Fail2Ban-wsl-setup.vdproj
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@
"Entry"
{
"MsmKey" = "8:_158AD5A193A12E7090082CC7924BAA3F"
"OwnerKey" = "8:_B286BA74448549F781DE843E4C5C321C"
"MsmSig" = "8:_UNDEFINED"
}
"Entry"
{
"MsmKey" = "8:_158AD5A193A12E7090082CC7924BAA3F"
"OwnerKey" = "8:_E3B49AABA8F249179FB83306C670D853"
"MsmSig" = "8:_UNDEFINED"
}
Expand All @@ -45,6 +51,12 @@
}
"Entry"
{
"MsmKey" = "8:_B286BA74448549F781DE843E4C5C321C"
"OwnerKey" = "8:_UNDEFINED"
"MsmSig" = "8:_UNDEFINED"
}
"Entry"
{
"MsmKey" = "8:_B62D47DCE21640B39A38D8E0C4EEDFF9"
"OwnerKey" = "8:_UNDEFINED"
"MsmSig" = "8:_UNDEFINED"
Expand All @@ -64,6 +76,12 @@
"Entry"
{
"MsmKey" = "8:_E262D8553770AE22FA34547A046ED24C"
"OwnerKey" = "8:_B286BA74448549F781DE843E4C5C321C"
"MsmSig" = "8:_UNDEFINED"
}
"Entry"
{
"MsmKey" = "8:_E262D8553770AE22FA34547A046ED24C"
"OwnerKey" = "8:_E3B49AABA8F249179FB83306C670D853"
"MsmSig" = "8:_UNDEFINED"
}
Expand All @@ -82,7 +100,7 @@
"Entry"
{
"MsmKey" = "8:_UNDEFINED"
"OwnerKey" = "8:_E262D8553770AE22FA34547A046ED24C"
"OwnerKey" = "8:_B286BA74448549F781DE843E4C5C321C"
"MsmSig" = "8:_UNDEFINED"
}
"Entry"
Expand All @@ -94,6 +112,12 @@
"Entry"
{
"MsmKey" = "8:_UNDEFINED"
"OwnerKey" = "8:_E262D8553770AE22FA34547A046ED24C"
"MsmSig" = "8:_UNDEFINED"
}
"Entry"
{
"MsmKey" = "8:_UNDEFINED"
"OwnerKey" = "8:_158AD5A193A12E7090082CC7924BAA3F"
"MsmSig" = "8:_UNDEFINED"
}
Expand Down Expand Up @@ -122,6 +146,14 @@
"PrerequisitesLocation" = "2:1"
"Url" = "8:"
"ComponentsUrl" = "8:"
"Items"
{
"{EDC2488A-8267-493A-A98E-7D9C3B36CDF3}:.NETFramework,Version=v4.6.1"
{
"Name" = "8:Microsoft .NET Framework 4.6.1 (x86 and x64)"
"ProductCode" = "8:.NETFramework,Version=v4.6.1"
}
}
}
}
"Release"
Expand Down Expand Up @@ -1091,6 +1123,34 @@
{
}
}
"{5259A561-127C-4D43-A0A1-72F10C7B3BF8}:_B286BA74448549F781DE843E4C5C321C"
{
"SourcePath" = "8:..\\PersistantFwRules\\obj\\Release\\PersistantFwRules.dll"
"TargetName" = "8:"
"Tag" = "8:"
"Folder" = "8:_E78A5D143865420397CF4C903EC875AA"
"Condition" = "8:"
"Transitive" = "11:FALSE"
"Vital" = "11:TRUE"
"ReadOnly" = "11:FALSE"
"Hidden" = "11:FALSE"
"System" = "11:FALSE"
"Permanent" = "11:FALSE"
"SharedLegacy" = "11:FALSE"
"PackageAs" = "3:1"
"Register" = "3:1"
"Exclude" = "11:FALSE"
"IsDependency" = "11:FALSE"
"IsolateTo" = "8:"
"ProjectOutputGroupRegister" = "3:1"
"OutputConfiguration" = "8:"
"OutputGroupCanonicalName" = "8:Built"
"OutputProjectGuid" = "8:{F58DC036-C7B8-442D-BA96-7B7747BD2691}"
"ShowKeyOutput" = "11:TRUE"
"ExcludeFilters"
{
}
}
"{5259A561-127C-4D43-A0A1-72F10C7B3BF8}:_E3B49AABA8F249179FB83306C670D853"
{
"SourcePath" = "8:..\\f2b-wsl\\obj\\Release\\f2b-wsl.exe"
Expand Down
160 changes: 116 additions & 44 deletions FirewallPolicyPlugin/FirewallPolicyModifier.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ You should have received a copy of the GNU General Public License
using System.ServiceProcess;
using static PluginAPIs.EventLogEnums;
using System.Collections.Generic;
using System.Linq;

namespace FirewallPolicyPlugin
{
Expand All @@ -40,7 +41,9 @@ public class FirewallPolicyModifier : IPlugin
private static INetFwRule FwRule;
private static object FwAccessLocker = new object();
private static object FwStackLocker = new object();

private static object FwRedirectLock = new object();
private static bool RedirectWrite = false;
private static Dictionary<string, int> CachedFwItems = new Dictionary<string, int>();

public override void OnDestroy()
{
Expand Down Expand Up @@ -87,24 +90,81 @@ public override void OnLoad()

public override bool RegisterPlugin(EventLog logger)
{
EnvStartInitialize += FirewallPolicyModifier_EnvStartInitialize;
EnvEndInitialize += FirewallPolicyModifier_EnvEndInitialize;
OnBadIPDetected += FirewallPolicyModifier_OnBadIPDetected;
_logger = logger;
if (!CheckWinFwStatus())
return false;
return true;
}

private void FirewallPolicyModifier_OnBadIPDetected(object sender, PluginEventArgs args)
private void FirewallPolicyModifier_EnvEndInitialize(object sender, EventArgs args)
{
#if DIRECT
if (args.EventTextContent.StartsWith("+"))
lock (FwRedirectLock)
{
AddFwBadIP(args.EventTextContent.Substring(1));
return;
RedirectWrite = false;
WriteAllCached();
}
if (args.EventTextContent.StartsWith("-"))
}

private void FirewallPolicyModifier_EnvStartInitialize(object sender, EventArgs args)
{
lock (FwRedirectLock)
{
RemoveFwBadIP(args.EventTextContent.Substring(1));
RedirectWrite = true;
}

}

private void WriteAllCached()
{
lock (FwAccessLocker)
{
if (CachedFwItems.Count > 0)
{
SetFwBadIPs(CachedFwItems);
CachedFwItems.Clear();
}
}
}

private void FirewallPolicyModifier_OnBadIPDetected(object sender, PluginEventArgs args)
{
#if DIRECT
lock (FwStackLocker)
{
if (args.EventTextContent.StartsWith("+"))
{
if (RedirectWrite == true)
{
try
{
CachedFwItems.Add(args.EventTextContent.Substring(1), 1);
}
catch (Exception) { }
}
else
{
AddFwBadIP(args.EventTextContent.Substring(1));
return;
}
}
if (args.EventTextContent.StartsWith("-"))
{
if (RedirectWrite == true)
{
try
{
CachedFwItems.Remove(args.EventTextContent.Substring(1));
}
catch (Exception) { }
}
else
{
RemoveFwBadIP(args.EventTextContent.Substring(1));
}
}
}
#else
lock (FwStackLocker)
Expand Down Expand Up @@ -176,22 +236,26 @@ private bool CheckWinFwStatus()
/// <param name="IPAddr">ip address string</param>
private void AddFwBadIP(string IPAddr)
{
if (!FwRule.RemoteAddresses.Contains(IPAddr))
System.Threading.Thread.MemoryBarrier();
lock (FwAccessLocker)
{
if (string.IsNullOrEmpty(FwRule.RemoteAddresses) || FwRule.RemoteAddresses == "*")
if (!FwRule.RemoteAddresses.Contains(IPAddr))
{
FwRule.RemoteAddresses = IPAddr;
FwRule.Enabled = true;
if (string.IsNullOrEmpty(FwRule.RemoteAddresses) || FwRule.RemoteAddresses == "*")
{
FwRule.RemoteAddresses = IPAddr;
FwRule.Enabled = true;
}
else
{
FwRule.RemoteAddresses += "," + IPAddr;
}
_logger.WriteEntry("Firewall rule added for IP: " + IPAddr, EventLogEntryType.Warning, (int)FwEventIDs.IPAdded, (short)LogCategories.Log_Info);
}
else
{
FwRule.RemoteAddresses += "," + IPAddr;
//_logger.WriteEntry("Firewall rule duplicate for IP: " + IPAddr, EventLogEntryType.Warning, (int)FwEventIDs.IPDuplicate, (short)LogCategories.Log_Info); // Don't want too much duplicated info
}
_logger.WriteEntry("Firewall rule added for IP: " + IPAddr, EventLogEntryType.Warning, (int)FwEventIDs.IPAdded, (short)LogCategories.Log_Info);
}
else
{
//_logger.WriteEntry("Firewall rule duplicate for IP: " + IPAddr, EventLogEntryType.Warning, (int)FwEventIDs.IPDuplicate, (short)LogCategories.Log_Info); // Don't want too much duplicated info
}
}

Expand All @@ -201,50 +265,58 @@ private void AddFwBadIP(string IPAddr)
/// <param name="IPAddr">ip address string</param>
private void RemoveFwBadIP(string IPAddr)
{
if (FwRule.RemoteAddresses.Contains(IPAddr))
lock (FwAccessLocker)
{
List<string> IPAddrList = new List<string>();
IPAddrList.AddRange(FwRule.RemoteAddresses.Split(','));
IPAddrList.RemoveAll(x => x.Contains(IPAddr));
string AfterRmAddrs = "";
if (IPAddrList.Count < 1)
if (FwRule.RemoteAddresses.Contains(IPAddr))
{
FwRule.Enabled = false;
FwRule.RemoteAddresses = "*";
List<string> IPAddrList = new List<string>();
IPAddrList.AddRange(FwRule.RemoteAddresses.Split(','));
IPAddrList.RemoveAll(x => x.Contains(IPAddr));
string AfterRmAddrs = "";
if (IPAddrList.Count < 1)
{
FwRule.Enabled = false;
FwRule.RemoteAddresses = "*";
}
else
{
foreach (string item in IPAddrList)
{
AfterRmAddrs += "," + item;
}
AfterRmAddrs = AfterRmAddrs.Trim(',');
FwRule.RemoteAddresses = AfterRmAddrs;
}
_logger.WriteEntry("Firewall rule removed for IP: " + IPAddr, EventLogEntryType.Warning, (int)FwEventIDs.IPRemoved, (short)LogCategories.Log_Info);
}
else
{
foreach (string item in IPAddrList)
{
AfterRmAddrs += "," + item;
}
AfterRmAddrs = AfterRmAddrs.Trim(',');
FwRule.RemoteAddresses = AfterRmAddrs;
_logger.WriteEntry("Firewall rule not exist for removal: " + IPAddr, EventLogEntryType.Warning, (int)FwEventIDs.IPNotExist, (short)LogCategories.Log_Info);
}
_logger.WriteEntry("Firewall rule removed for IP: " + IPAddr, EventLogEntryType.Warning, (int)FwEventIDs.IPRemoved, (short)LogCategories.Log_Info);
}
else
{
_logger.WriteEntry("Firewall rule not exist for removal: " + IPAddr, EventLogEntryType.Warning, (int)FwEventIDs.IPNotExist, (short)LogCategories.Log_Info);
}
}
#region "StackFwIPProcess"
#if !DIRECT
private static Dictionary<string, Stack<int>> FwRuleStack;

protected void SetFwBadIPs()
#endif
protected void SetFwBadIPs(Dictionary<string, int> FwRuleStack)
{
string FwBadIPStr = "";
lock (FwAccessLocker)
{
lock (FwStackLocker)
{
foreach (KeyValuePair<string, Stack<int>> BadIPPair in FwRuleStack)
List<string> IPAddrList = new List<string>();
IPAddrList.AddRange(FwRule.RemoteAddresses.Replace("/255.255.255.255","").Split(','));
IPAddrList.AddRange(FwRuleStack.Keys);
List<string> DeDupedList = IPAddrList.Distinct().ToList();
foreach (var BadIPStr in DeDupedList)
{
if (BadIPPair.Value.Count > 0)
FwBadIPStr += "," + BadIPPair.Key + @"/255.255.255.255";
if (BadIPStr != "*")
FwBadIPStr += BadIPStr + @"/255.255.255.255,";
}
FwBadIPStr = FwBadIPStr.Trim(',');

if (string.IsNullOrEmpty(FwBadIPStr) || string.IsNullOrWhiteSpace(FwBadIPStr))
{
FwRule.RemoteAddresses = "*";
Expand All @@ -260,12 +332,12 @@ protected void SetFwBadIPs()
}
}
}
#endif

#endregion
#if DEBUG
public void RaiseBIPDeteacted(string IPAddr)
{
FirewallPolicyModifier_OnBadIPDetected(null, new PluginEventArgs() { EventSource = "", EventTextContent = IPAddr, EventType ="Det" });
FirewallPolicyModifier_OnBadIPDetected(null, new PluginEventArgs() { EventSource = "", EventTextContent = IPAddr, EventType = "Det" });
}
#endif
}
Expand Down
Loading

0 comments on commit 2f30ea5

Please sign in to comment.