Skip to content

Commit 0057d7c

Browse files
author
Gaël
committed
- Load ban list on start
- 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
1 parent 1672371 commit 0057d7c

4 files changed

Lines changed: 129 additions & 54 deletions

File tree

IPABan/Configuration.cs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,12 @@
66

77
namespace IPABan
88
{
9-
public static class Config
9+
public class Configuration
1010
{
11-
static public int banDuration = 3600;
12-
static public string apiKey = "";
13-
static public int attemptPermaBan = 3;
11+
public int banDuration = 3600;
12+
public string IPDBapiKey = "";
13+
public int attemptPermaBan = 3;
14+
public int attempBeforeBan = 5;
15+
public int debugLevel = 0;
1416
}
1517
}

IPABan/IPDBApi.cs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ public class ipStat
5959
public long timeStamp;
6060
public string ip;
6161
public int banAmount = 0;
62+
public bool trusted = false;
6263
public bool check = false;
6364
}
6465

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

@@ -107,10 +108,9 @@ public static bool CheckIP(string _ip)
107108
{
108109
try
109110
{
110-
111111
var client = new RestClient("https://api.abuseipdb.com/api/v2/check");
112112
var request = new RestRequest(Method.GET);
113-
request.AddHeader("Key", Config.apiKey);
113+
request.AddHeader("Key", Service1.Config.IPDBapiKey);
114114
request.AddHeader("Accept", "application/json");
115115
request.AddParameter("ipAddress", _ip);
116116
request.AddParameter("maxAgeInDays", "90");
@@ -121,7 +121,7 @@ public static bool CheckIP(string _ip)
121121

122122
// Service1.WriteToFile(response.Content);
123123

124-
if (json.errors.Count > 0)
124+
if (json.errors != null)
125125
{
126126
Service1.WriteError("Error from IPDB");
127127
foreach (Error err in json.errors)
@@ -162,7 +162,7 @@ public static void ReportIP(string _reportip, string _reason)
162162
Service1.WriteLog("Reporting user");
163163
var client = new RestClient("https://api.abuseipdb.com/api/v2/report");
164164
var request = new RestRequest(Method.POST);
165-
request.AddHeader("Key", Config.apiKey);
165+
request.AddHeader("Key", Service1.Config.IPDBapiKey);
166166
request.AddHeader("Accept", "application/json");
167167
request.AddParameter("ip", _reportip);
168168
request.AddParameter("categories", "18");

IPABan/Properties/AssemblyInfo.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,5 +33,5 @@
3333
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut
3434
// en utilisant '*', comme indiqué ci-dessous :
3535
// [assembly: AssemblyVersion("1.0.*")]
36-
[assembly: AssemblyVersion("0.3.0.0")]
37-
[assembly: AssemblyFileVersion("0.3.0.0")]
36+
[assembly: AssemblyVersion("1.0.0.0")]
37+
[assembly: AssemblyFileVersion("1.0.0.0")]

IPABan/Service1.cs

Lines changed: 116 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -8,26 +8,22 @@
88
using WindowsFirewallHelper;
99
using WindowsFirewallHelper.Addresses;
1010
using System.Threading;
11-
using RestSharp;
1211
using Newtonsoft.Json;
13-
using Formatting = Newtonsoft.Json.Formatting;
14-
using System.Net;
1512

1613
namespace IPABan
1714
{
1815
public partial class Service1 : ServiceBase
1916
{
20-
17+
public static Configuration Config = new Configuration();
2118
public static List<String> LogProcess = new List<string>();
2219
public static List<String> ErrorProcess = new List<string>();
2320

2421
class BannedIP
2522
{
26-
public IAddress ipAddress;
23+
public string ipAddress;
2724
public long expire;
2825
}
2926

30-
3127

3228

3329

@@ -39,28 +35,66 @@ public Service1()
3935
InitializeComponent();
4036
}
4137

42-
38+
4339
void BanIP(IAddress _ip, int _expire)
4440
{
41+
bool Found = false;
4542
foreach(BannedIP b in bannedIPList)
4643
{
47-
if(b.ipAddress == _ip)
48-
{
49-
return;
44+
//Dont work without the .ToString() I dont know why ...
45+
if (b.ipAddress.ToString() == _ip.ToString())
46+
{
47+
Found = true;
5048
}
5149
}
52-
53-
BannedIP ban = new BannedIP();
54-
ban.ipAddress = _ip;
55-
ban.expire = _expire;
56-
bannedIPList.Add(ban);
57-
WriteLog("Banning");
50+
if(!Found)
51+
{
52+
BannedIP ban = new BannedIP();
53+
ban.ipAddress = _ip.ToString();
54+
ban.expire = _expire;
55+
bannedIPList.Add(ban);
56+
WriteLog("Banning : " + _ip + " Expire : " + _expire);
57+
}
58+
FirewallUpdate();
59+
60+
}
61+
62+
void LoadBanList()
63+
{
64+
string BanListFile = AppDomain.CurrentDomain.BaseDirectory + "\\banlist.json";
65+
if (File.Exists(BanListFile))
66+
{
67+
string fileText = File.ReadAllText(BanListFile);
68+
List<BannedIP> loadedBanList = JsonConvert.DeserializeObject<List<BannedIP>>(fileText);
69+
bannedIPList = loadedBanList;
70+
FirewallUpdate();
71+
}
5872
}
5973

74+
void LoadConfiguration()
75+
{
76+
string ConfigPath = AppDomain.CurrentDomain.BaseDirectory + "\\config.conf";
77+
if(!File.Exists(ConfigPath))
78+
{
79+
string jsonString = JsonConvert.SerializeObject(Config, Newtonsoft.Json.Formatting.Indented);
80+
File.WriteAllText(ConfigPath,jsonString);
81+
82+
WriteToFile(jsonString);
83+
}
84+
else
85+
{
86+
string fileText = File.ReadAllText(ConfigPath);
87+
Configuration loadedConf = JsonConvert.DeserializeObject<Configuration>(fileText);
88+
Config = loadedConf;
89+
}
90+
}
6091

6192
protected override void OnStart(string[] args)
6293
{
63-
WriteToFile("Service is started. " + DateTime.Now);
94+
WriteToFile("Service is started. " + DateTime.Now);
95+
LoadConfiguration();
96+
LoadBanList();
97+
6498
FindRule();
6599
RegisterListener();
66100
Thread trd = new Thread(new ThreadStart(this.FirewallUpdater));
@@ -80,6 +114,21 @@ protected override void OnStop()
80114
}
81115

82116

117+
void UpdateBanFile()
118+
{
119+
string json = JsonConvert.SerializeObject(bannedIPList, Newtonsoft.Json.Formatting.Indented);
120+
File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "\\banlist.json", json);
121+
}
122+
void UpdateAttemptFile()
123+
{
124+
if (Config.debugLevel >= 2)
125+
{
126+
File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "\\attemptsize.txt", ipAttempt.Count.ToString());
127+
string json = JsonConvert.SerializeObject(ipAttempt, Newtonsoft.Json.Formatting.Indented);
128+
File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "\\attempt.txt", json);
129+
}
130+
}
131+
83132
#region Threads
84133
void FirewallUpdater()
85134
{
@@ -88,10 +137,6 @@ void FirewallUpdater()
88137
try
89138
{
90139
Thread.Sleep(1000);
91-
92-
//string json = JsonConvert.SerializeObject(bannedIPList, Formatting.Indented);
93-
94-
//WriteLog(json.ToString());
95140
List<BannedIP> ban = bannedIPList;
96141

97142
foreach (BannedIP ip in ban)
@@ -103,7 +148,6 @@ void FirewallUpdater()
103148
WriteLog("unban ip : " + ip.ipAddress);
104149
bannedIPList.Remove(ip);
105150
FirewallUpdate();
106-
107151
}
108152
}
109153
}
@@ -120,19 +164,28 @@ void CheckThread(string ipAddress)
120164
{
121165
try
122166
{
167+
if(Config.IPDBapiKey == null)
168+
{
169+
return;
170+
}
123171
if (!IPDBApi.CheckIP(ipAddress))
124172
{
125-
ipAttempt[FindIP(ipAddress.ToString())].banAmount++;
126-
BanIP(SingleIP.Parse(ipAddress), (Int32)(DateTime.Now.Subtract(new DateTime(1970, 1, 1))).TotalSeconds + Config.banDuration);
127-
128-
173+
int idx = FindIP(ipAddress.ToString());
174+
ipAttempt[idx].banAmount++;
175+
BanIP(SingleIP.Parse(ipAddress), -1);
176+
ipAttempt[idx].trusted = false;
177+
ipAttempt[idx].check = true;
129178
WriteLog("Banning from DB IP : " + ipAddress);
130179
FirewallUpdate();
131180
}
132181
else
133182
{
183+
int idx = FindIP(ipAddress.ToString());
134184
//WriteLog("IP Trusted");
185+
ipAttempt[idx].trusted = true;
186+
ipAttempt[idx].check = true;
135187
}
188+
136189
}
137190
catch (Exception e)
138191
{
@@ -145,6 +198,18 @@ void ThreadLog()
145198
WriteToFile("Stating threadlog");
146199
while (true)
147200
{
201+
//Debug================
202+
if (Config.debugLevel >= 2)
203+
{
204+
UpdateAttemptFile();
205+
string json = JsonConvert.SerializeObject(LogProcess, Newtonsoft.Json.Formatting.Indented);
206+
File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "\\LogList.txt", json);
207+
string json1 = JsonConvert.SerializeObject(ErrorProcess, Newtonsoft.Json.Formatting.Indented);
208+
File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "\\ErrorList.txt", json1);
209+
//=======================
210+
}
211+
212+
148213
Thread.Sleep(100);
149214

150215
try
@@ -184,7 +249,7 @@ void ThreadLog()
184249

185250
#region Writers
186251
public static void WriteLog(string _string)
187-
{
252+
{
188253
LogProcess.Add(_string);
189254
}
190255

@@ -209,15 +274,20 @@ public static void WriteToFile(string text)
209274
using (StreamWriter sw = File.CreateText(filePath))
210275
{
211276
sw.WriteLine(text);
277+
//sw.Close();
278+
sw.Flush();
212279
}
213280
}
214281
else
215282
{
216283
using (StreamWriter sw = File.AppendText(filePath))
217284
{
218285
sw.WriteLine(text);
286+
//sw.Close();
287+
sw.Flush();
219288
}
220289
}
290+
221291

222292
}
223293

@@ -287,26 +357,29 @@ private void OnEntryWritten(object source, EntryWrittenEventArgs e)
287357
if (reader.GetAttribute(0) == "IpAddress")
288358
{
289359
string ipAddress = reader.ReadElementContentAsString();
290-
WriteLog("Connection attempts with IP : " + ipAddress);
291-
var t = new Thread(() => CheckThread(ipAddress));
292-
t.Start();
293-
294-
295-
296-
int idxIP = FindIP(ipAddress);
360+
361+
362+
int idxIP = FindIP(ipAddress);
297363
if (idxIP == -1)
298364
{
365+
var t = new Thread(() => CheckThread(ipAddress));
366+
t.Start();
299367
IPDBApi.ipStat newStat = new IPDBApi.ipStat();
300368
newStat.timeStamp = (Int32)(DateTime.Now.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
301369
newStat.ip = ipAddress;
302370
newStat.attemptCount = 1;
303-
newStat.banAmount++;
304-
ipAttempt.Add(newStat);
371+
newStat.banAmount = 1;
372+
ipAttempt.Add(newStat);
305373
}
306374
else
307375
{
376+
if (!ipAttempt[idxIP].check)
377+
{
378+
var t = new Thread(() => CheckThread(ipAddress));
379+
t.Start();
380+
}
308381
ipAttempt[idxIP].attemptCount++;
309-
if (ipAttempt[idxIP].attemptCount >= 5)
382+
if (ipAttempt[idxIP].attemptCount >= Config.attempBeforeBan)
310383
{
311384
if(ipAttempt[idxIP].banAmount >= Config.attemptPermaBan)
312385
{
@@ -325,10 +398,10 @@ private void OnEntryWritten(object source, EntryWrittenEventArgs e)
325398
Reporter.Start();
326399
}
327400
}
328-
}
329-
WriteLog("Attemps : " + ipAttempt[idxIP].attemptCount.ToString());
330-
FirewallUpdate();
401+
}
331402

403+
WriteLog("IP :" + ipAttempt[idxIP].ip + " Attemps : " + ipAttempt[idxIP].attemptCount.ToString());
404+
332405
}
333406
break;
334407
}
@@ -388,13 +461,13 @@ void FirewallUpdate()
388461

389462
foreach (BannedIP banned in bannedIPList)
390463
{
391-
banList[i] = banned.ipAddress;
464+
banList[i] = SingleIP.Parse(banned.ipAddress);
392465
i++;
393466
}
394467
}
395468
rule.RemoteAddresses = banList;
396469
FirewallManager.Instance.Rules.Add(rule);
397-
470+
UpdateBanFile();
398471

399472
}
400473
catch (Exception e)
@@ -436,7 +509,7 @@ List<IRule> FindRule()
436509
WriteError(e.Message);
437510
return null;
438511
}
439-
}
512+
}
440513

441514
int FindIP(string _ip)
442515
{

0 commit comments

Comments
 (0)