Skip to content

Commit

Permalink
- Load ban list on start
Browse files Browse the repository at this point in the history
- Added configuration file
- Optimize the log system.
- Added Debug level for devloppement
- Cleaned log output
- Prevent banning multiple time the same IP
- Check if error when check an IP on IPDB Abuse
  • Loading branch information
Gaël committed May 7, 2021
1 parent 1672371 commit 0057d7c
Show file tree
Hide file tree
Showing 4 changed files with 129 additions and 54 deletions.
10 changes: 6 additions & 4 deletions IPABan/Configuration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@

namespace IPABan
{
public static class Config
public class Configuration
{
static public int banDuration = 3600;
static public string apiKey = "";
static public int attemptPermaBan = 3;
public int banDuration = 3600;
public string IPDBapiKey = "";
public int attemptPermaBan = 3;
public int attempBeforeBan = 5;
public int debugLevel = 0;
}
}
10 changes: 5 additions & 5 deletions IPABan/IPDBApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ public class ipStat
public long timeStamp;
public string ip;
public int banAmount = 0;
public bool trusted = false;
public bool check = false;
}

Expand Down Expand Up @@ -88,7 +89,7 @@ string GetBlackList()
{
var client = new RestClient("https://api.abuseipdb.com/api/v2/blacklist");
var request = new RestRequest(Method.GET);
request.AddHeader("Key", Config.apiKey);
request.AddHeader("Key", Service1.Config.IPDBapiKey);
request.AddHeader("Accept", "application/json");
request.AddParameter("confidenceMinimum", "90");

Expand All @@ -107,10 +108,9 @@ public static bool CheckIP(string _ip)
{
try
{

var client = new RestClient("https://api.abuseipdb.com/api/v2/check");
var request = new RestRequest(Method.GET);
request.AddHeader("Key", Config.apiKey);
request.AddHeader("Key", Service1.Config.IPDBapiKey);
request.AddHeader("Accept", "application/json");
request.AddParameter("ipAddress", _ip);
request.AddParameter("maxAgeInDays", "90");
Expand All @@ -121,7 +121,7 @@ public static bool CheckIP(string _ip)

// Service1.WriteToFile(response.Content);

if (json.errors.Count > 0)
if (json.errors != null)
{
Service1.WriteError("Error from IPDB");
foreach (Error err in json.errors)
Expand Down Expand Up @@ -162,7 +162,7 @@ public static void ReportIP(string _reportip, string _reason)
Service1.WriteLog("Reporting user");
var client = new RestClient("https://api.abuseipdb.com/api/v2/report");
var request = new RestRequest(Method.POST);
request.AddHeader("Key", Config.apiKey);
request.AddHeader("Key", Service1.Config.IPDBapiKey);
request.AddHeader("Accept", "application/json");
request.AddParameter("ip", _reportip);
request.AddParameter("categories", "18");
Expand Down
4 changes: 2 additions & 2 deletions IPABan/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,5 @@
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut
// en utilisant '*', comme indiqué ci-dessous :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.3.0.0")]
[assembly: AssemblyFileVersion("0.3.0.0")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
159 changes: 116 additions & 43 deletions IPABan/Service1.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,26 +8,22 @@
using WindowsFirewallHelper;
using WindowsFirewallHelper.Addresses;
using System.Threading;
using RestSharp;
using Newtonsoft.Json;
using Formatting = Newtonsoft.Json.Formatting;
using System.Net;

namespace IPABan
{
public partial class Service1 : ServiceBase
{

public static Configuration Config = new Configuration();
public static List<String> LogProcess = new List<string>();
public static List<String> ErrorProcess = new List<string>();

class BannedIP
{
public IAddress ipAddress;
public string ipAddress;
public long expire;
}





Expand All @@ -39,28 +35,66 @@ public Service1()
InitializeComponent();
}


void BanIP(IAddress _ip, int _expire)
{
bool Found = false;
foreach(BannedIP b in bannedIPList)
{
if(b.ipAddress == _ip)
{
return;
//Dont work without the .ToString() I dont know why ...
if (b.ipAddress.ToString() == _ip.ToString())
{
Found = true;
}
}

BannedIP ban = new BannedIP();
ban.ipAddress = _ip;
ban.expire = _expire;
bannedIPList.Add(ban);
WriteLog("Banning");
if(!Found)
{
BannedIP ban = new BannedIP();
ban.ipAddress = _ip.ToString();
ban.expire = _expire;
bannedIPList.Add(ban);
WriteLog("Banning : " + _ip + " Expire : " + _expire);
}
FirewallUpdate();

}

void LoadBanList()
{
string BanListFile = AppDomain.CurrentDomain.BaseDirectory + "\\banlist.json";
if (File.Exists(BanListFile))
{
string fileText = File.ReadAllText(BanListFile);
List<BannedIP> loadedBanList = JsonConvert.DeserializeObject<List<BannedIP>>(fileText);
bannedIPList = loadedBanList;
FirewallUpdate();
}
}

void LoadConfiguration()
{
string ConfigPath = AppDomain.CurrentDomain.BaseDirectory + "\\config.conf";
if(!File.Exists(ConfigPath))
{
string jsonString = JsonConvert.SerializeObject(Config, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText(ConfigPath,jsonString);

WriteToFile(jsonString);
}
else
{
string fileText = File.ReadAllText(ConfigPath);
Configuration loadedConf = JsonConvert.DeserializeObject<Configuration>(fileText);
Config = loadedConf;
}
}

protected override void OnStart(string[] args)
{
WriteToFile("Service is started. " + DateTime.Now);
WriteToFile("Service is started. " + DateTime.Now);
LoadConfiguration();
LoadBanList();

FindRule();
RegisterListener();
Thread trd = new Thread(new ThreadStart(this.FirewallUpdater));
Expand All @@ -80,6 +114,21 @@ protected override void OnStop()
}


void UpdateBanFile()
{
string json = JsonConvert.SerializeObject(bannedIPList, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "\\banlist.json", json);
}
void UpdateAttemptFile()
{
if (Config.debugLevel >= 2)
{
File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "\\attemptsize.txt", ipAttempt.Count.ToString());
string json = JsonConvert.SerializeObject(ipAttempt, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "\\attempt.txt", json);
}
}

#region Threads
void FirewallUpdater()
{
Expand All @@ -88,10 +137,6 @@ void FirewallUpdater()
try
{
Thread.Sleep(1000);

//string json = JsonConvert.SerializeObject(bannedIPList, Formatting.Indented);

//WriteLog(json.ToString());
List<BannedIP> ban = bannedIPList;

foreach (BannedIP ip in ban)
Expand All @@ -103,7 +148,6 @@ void FirewallUpdater()
WriteLog("unban ip : " + ip.ipAddress);
bannedIPList.Remove(ip);
FirewallUpdate();

}
}
}
Expand All @@ -120,19 +164,28 @@ void CheckThread(string ipAddress)
{
try
{
if(Config.IPDBapiKey == null)
{
return;
}
if (!IPDBApi.CheckIP(ipAddress))
{
ipAttempt[FindIP(ipAddress.ToString())].banAmount++;
BanIP(SingleIP.Parse(ipAddress), (Int32)(DateTime.Now.Subtract(new DateTime(1970, 1, 1))).TotalSeconds + Config.banDuration);


int idx = FindIP(ipAddress.ToString());
ipAttempt[idx].banAmount++;
BanIP(SingleIP.Parse(ipAddress), -1);
ipAttempt[idx].trusted = false;
ipAttempt[idx].check = true;
WriteLog("Banning from DB IP : " + ipAddress);
FirewallUpdate();
}
else
{
int idx = FindIP(ipAddress.ToString());
//WriteLog("IP Trusted");
ipAttempt[idx].trusted = true;
ipAttempt[idx].check = true;
}

}
catch (Exception e)
{
Expand All @@ -145,6 +198,18 @@ void ThreadLog()
WriteToFile("Stating threadlog");
while (true)
{
//Debug================
if (Config.debugLevel >= 2)
{
UpdateAttemptFile();
string json = JsonConvert.SerializeObject(LogProcess, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "\\LogList.txt", json);
string json1 = JsonConvert.SerializeObject(ErrorProcess, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "\\ErrorList.txt", json1);
//=======================
}


Thread.Sleep(100);

try
Expand Down Expand Up @@ -184,7 +249,7 @@ void ThreadLog()

#region Writers
public static void WriteLog(string _string)
{
{
LogProcess.Add(_string);
}

Expand All @@ -209,15 +274,20 @@ public static void WriteToFile(string text)
using (StreamWriter sw = File.CreateText(filePath))
{
sw.WriteLine(text);
//sw.Close();
sw.Flush();
}
}
else
{
using (StreamWriter sw = File.AppendText(filePath))
{
sw.WriteLine(text);
//sw.Close();
sw.Flush();
}
}


}

Expand Down Expand Up @@ -287,26 +357,29 @@ private void OnEntryWritten(object source, EntryWrittenEventArgs e)
if (reader.GetAttribute(0) == "IpAddress")
{
string ipAddress = reader.ReadElementContentAsString();
WriteLog("Connection attempts with IP : " + ipAddress);
var t = new Thread(() => CheckThread(ipAddress));
t.Start();



int idxIP = FindIP(ipAddress);


int idxIP = FindIP(ipAddress);
if (idxIP == -1)
{
var t = new Thread(() => CheckThread(ipAddress));
t.Start();
IPDBApi.ipStat newStat = new IPDBApi.ipStat();
newStat.timeStamp = (Int32)(DateTime.Now.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
newStat.ip = ipAddress;
newStat.attemptCount = 1;
newStat.banAmount++;
ipAttempt.Add(newStat);
newStat.banAmount = 1;
ipAttempt.Add(newStat);
}
else
{
if (!ipAttempt[idxIP].check)
{
var t = new Thread(() => CheckThread(ipAddress));
t.Start();
}
ipAttempt[idxIP].attemptCount++;
if (ipAttempt[idxIP].attemptCount >= 5)
if (ipAttempt[idxIP].attemptCount >= Config.attempBeforeBan)
{
if(ipAttempt[idxIP].banAmount >= Config.attemptPermaBan)
{
Expand All @@ -325,10 +398,10 @@ private void OnEntryWritten(object source, EntryWrittenEventArgs e)
Reporter.Start();
}
}
}
WriteLog("Attemps : " + ipAttempt[idxIP].attemptCount.ToString());
FirewallUpdate();
}

WriteLog("IP :" + ipAttempt[idxIP].ip + " Attemps : " + ipAttempt[idxIP].attemptCount.ToString());

}
break;
}
Expand Down Expand Up @@ -388,13 +461,13 @@ void FirewallUpdate()

foreach (BannedIP banned in bannedIPList)
{
banList[i] = banned.ipAddress;
banList[i] = SingleIP.Parse(banned.ipAddress);
i++;
}
}
rule.RemoteAddresses = banList;
FirewallManager.Instance.Rules.Add(rule);

UpdateBanFile();

}
catch (Exception e)
Expand Down Expand Up @@ -436,7 +509,7 @@ List<IRule> FindRule()
WriteError(e.Message);
return null;
}
}
}

int FindIP(string _ip)
{
Expand Down

0 comments on commit 0057d7c

Please sign in to comment.