From 0b09e749bcf0bfe333e577d4ad65f37706f19767 Mon Sep 17 00:00:00 2001 From: Stone_Red <56473591+Stone-Red-Code@users.noreply.github.com> Date: Sat, 8 Jan 2022 19:33:35 +0100 Subject: [PATCH 1/4] - Add async packet processing --- FraudCapturer/DomainHelper.cs | 15 ++++-- FraudCapturer/FirewallHelper.cs | 81 ++++++++++++++++++--------------- FraudCapturer/IpHelper.cs | 13 +++++- FraudCapturer/Program.cs | 29 +++++++----- 4 files changed, 86 insertions(+), 52 deletions(-) diff --git a/FraudCapturer/DomainHelper.cs b/FraudCapturer/DomainHelper.cs index 26e8ec7..53ed20d 100644 --- a/FraudCapturer/DomainHelper.cs +++ b/FraudCapturer/DomainHelper.cs @@ -22,7 +22,7 @@ internal class DomainHelper return domains.Distinct().ToArray(); } - public static DomainInfo? GetDomainReputation(string domain) + public static async Task GetDomainReputation(string domain) { try { @@ -41,10 +41,19 @@ internal class DomainHelper }; HttpContent httpContent = new StringContent(JsonSerializer.Serialize(reqestBody), Encoding.UTF8, "application/json"); + HttpResponseMessage responseMessage; - HttpResponseMessage responseMessage = httpClient.PostAsync("https://anti-fish.bitflow.dev/check", httpContent).GetAwaiter().GetResult(); ; + try + { + responseMessage = await httpClient.PostAsync("https://anti-fish.bitflow.dev/check", httpContent); + } + catch (HttpRequestException ex) + { + Console.WriteLine($"error: {ex.Message}"); + return null; + } - string resultString = responseMessage.Content.ReadAsStringAsync().GetAwaiter().GetResult(); ; + string resultString = await responseMessage.Content.ReadAsStringAsync(); AntiFishResultBody? resultBody = JsonSerializer.Deserialize(resultString); AntiFishResult? result = resultBody?.Matches?.FirstOrDefault(m => m.Domain == domain); diff --git a/FraudCapturer/FirewallHelper.cs b/FraudCapturer/FirewallHelper.cs index b4e678e..e1bb141 100644 --- a/FraudCapturer/FirewallHelper.cs +++ b/FraudCapturer/FirewallHelper.cs @@ -11,21 +11,24 @@ internal class FirewallHelper throw new ArgumentNullException(nameof(ipAddress)); } - AddRuleIfDoesnotExist(ipAddress); - - File.AppendAllText(Program.IpStorePath, $"{Environment.NewLine}{ipAddress}"); - - string[] iPs = File.ReadAllLines(Program.IpStorePath); - - System.Diagnostics.Process process = new System.Diagnostics.Process(); - System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo + lock (Program.IpStorePath) { - WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden, - FileName = "cmd.exe", - Arguments = $"/C netsh advfirewall firewall set rule name=\"{Program.AppName} IP Block\" new remoteIp={string.Join(',', iPs)}" - }; - process.StartInfo = startInfo; - _ = process.Start(); + AddRuleIfDoesnotExist(ipAddress); + + File.AppendAllText(Program.IpStorePath, $"{Environment.NewLine}{ipAddress}"); + + string[] iPs = File.ReadAllLines(Program.IpStorePath); + + System.Diagnostics.Process process = new System.Diagnostics.Process(); + System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo + { + WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden, + FileName = "cmd.exe", + Arguments = $"/C netsh advfirewall firewall set rule name=\"{Program.AppName} IP Block\" new remoteIp={string.Join(',', iPs)}" + }; + process.StartInfo = startInfo; + _ = process.Start(); + } } public static void UnblockIp(IPAddress? ipAddress) @@ -35,33 +38,39 @@ internal class FirewallHelper throw new ArgumentNullException(nameof(ipAddress)); } - List iPs = File.ReadAllLines(Program.IpStorePath).ToList(); - iPs.Remove(ipAddress.ToString()); - - File.WriteAllLines(Program.IpStorePath, iPs); - - System.Diagnostics.Process process = new System.Diagnostics.Process(); - System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo + lock (Program.IpStorePath) { - WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden, - FileName = "cmd.exe", - Arguments = $"/C netsh advfirewall firewall set rule name=\"{Program.AppName} IP Block\" new remoteIp={string.Join(',', iPs.ToArray())}" - }; - process.StartInfo = startInfo; - _ = process.Start(); + List iPs = File.ReadAllLines(Program.IpStorePath).ToList(); + iPs.Remove(ipAddress.ToString()); + + File.WriteAllLines(Program.IpStorePath, iPs); + + System.Diagnostics.Process process = new System.Diagnostics.Process(); + System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo + { + WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden, + FileName = "cmd.exe", + Arguments = $"/C netsh advfirewall firewall set rule name=\"{Program.AppName} IP Block\" new remoteIp={string.Join(',', iPs.ToArray())}" + }; + process.StartInfo = startInfo; + _ = process.Start(); + } } public static void AddRuleIfDoesnotExist(IPAddress ipAddress) { - System.Diagnostics.Process process = new System.Diagnostics.Process(); - System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo + lock (Program.IpStorePath) { - WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden, - FileName = "cmd.exe", - Arguments = $"/C netsh advfirewall firewall show rule name=\"{Program.AppName} IP Block\" >nul || netsh advfirewall firewall add rule name=\"{Program.AppName} IP Block\" dir=in interface=any action=block remoteIp={ipAddress} && netsh advfirewall firewall add rule name=\"{Program.AppName} IP Block\" dir=out interface=any action=block remoteIp={ipAddress}" - }; - process.StartInfo = startInfo; - _ = process.Start(); - process.WaitForExit(); + System.Diagnostics.Process process = new System.Diagnostics.Process(); + System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo + { + WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden, + FileName = "cmd.exe", + Arguments = $"/C netsh advfirewall firewall show rule name=\"{Program.AppName} IP Block\" >nul || netsh advfirewall firewall add rule name=\"{Program.AppName} IP Block\" dir=in interface=any action=block remoteIp={ipAddress} && netsh advfirewall firewall add rule name=\"{Program.AppName} IP Block\" dir=out interface=any action=block remoteIp={ipAddress}" + }; + process.StartInfo = startInfo; + _ = process.Start(); + process.WaitForExit(); + } } } \ No newline at end of file diff --git a/FraudCapturer/IpHelper.cs b/FraudCapturer/IpHelper.cs index 5a9b04c..2fb7915 100644 --- a/FraudCapturer/IpHelper.cs +++ b/FraudCapturer/IpHelper.cs @@ -7,11 +7,20 @@ internal class IpHelper { public static string? ProxycheckApiKey { get; set; } - public static IpInfo? GetIpReputation(IPAddress ipAddress) + public static async Task GetIpReputation(IPAddress ipAddress) { HttpClient httpClient = new HttpClient(); + string rawResponseData; - string rawResponseData = httpClient.GetStringAsync($"http://proxycheck.io/v2/{ipAddress}?key={ProxycheckApiKey}&risk=2&vpn=1&asn=1&tag={Program.AppName}({Environment.MachineName})").GetAwaiter().GetResult(); + try + { + rawResponseData = await httpClient.GetStringAsync($"http://proxycheck.io/v2/{ipAddress}?key={ProxycheckApiKey}&risk=2&vpn=1&asn=1&tag={Program.AppName}({Environment.MachineName})"); + } + catch (HttpRequestException ex) + { + Console.WriteLine($"error: {ex.Message}"); + return null; + } JsonDocument responseData = JsonDocument.Parse(rawResponseData); diff --git a/FraudCapturer/Program.cs b/FraudCapturer/Program.cs index 4f471cb..a266179 100644 --- a/FraudCapturer/Program.cs +++ b/FraudCapturer/Program.cs @@ -3,6 +3,7 @@ using PacketDotNet; using SharpPcap; +using System.Collections.Concurrent; using System.Net; namespace FraudCapturer; @@ -19,8 +20,8 @@ public class Program private static DateTime lastCacheClear; private static string lastDomain = string.Empty; - private static readonly List capturedIpsCache = new(); - private static readonly Dictionary capturedDomainsCache = new(); + private static readonly ConcurrentBag capturedIpsCache = new(); + private static readonly ConcurrentDictionary capturedDomainsCache = new(); /// /// The main entry point for the application. @@ -101,6 +102,11 @@ public class Program private static void Device_OnPacketArrival(object sender, PacketCapture e) { RawCapture rawPacket = e.GetPacket(); + ProcessRawPacket(rawPacket); + } + + private static async void ProcessRawPacket(RawCapture rawPacket) + { Packet packet = Packet.ParsePacket(rawPacket.LinkLayerType, rawPacket.Data); if (packet is EthernetPacket) { @@ -137,27 +143,27 @@ public class Program } //Check if a DNS packet contains a "dangerous" domain. - CheckDns(packet, remoteIpAddress, direction); + await CheckDns(packet, remoteIpAddress, direction); if (capturedIpsCache.Contains(remoteIpAddress.ToString())) { return; } - TimeSpan timeRemainingUntilCacheReset = new TimeSpan(0, 10, 0) - (DateTime.Now - lastCacheClear); - Console.WriteLine($"Next cache reset in {timeRemainingUntilCacheReset.Minutes} minute(s) and {timeRemainingUntilCacheReset.Seconds} second(s)"); - capturedIpsCache.Add(remoteIpAddress.ToString()); //Check if ip address is "dangerous" or blocked - CheckIpAddress(remoteIpAddress, direction); + await CheckIpAddress(remoteIpAddress, direction); + + TimeSpan timeRemainingUntilCacheReset = new TimeSpan(0, 10, 0) - (DateTime.Now - lastCacheClear); + Console.WriteLine($"Next cache reset in {timeRemainingUntilCacheReset.Minutes} minute(s) and {timeRemainingUntilCacheReset.Seconds} second(s)"); } } } - private static void CheckIpAddress(IPAddress remoteIpAddress, string direction) + private static async Task CheckIpAddress(IPAddress remoteIpAddress, string direction) { - IpInfo? ipInfo = IpHelper.GetIpReputation(remoteIpAddress); + IpInfo? ipInfo = await IpHelper.GetIpReputation(remoteIpAddress); if (IpHelper.IsInternalIpAddress(remoteIpAddress.ToString())) { @@ -200,7 +206,7 @@ public class Program Console.ResetColor(); } - private static void CheckDns(Packet packet, IPAddress remoteIpAddress, string direction) + private static async Task CheckDns(Packet packet, IPAddress remoteIpAddress, string direction) { TransportPacket transportPacket = packet.Extract(); transportPacket ??= packet.Extract(); @@ -219,7 +225,8 @@ public class Program } else { - domainInfo = DomainHelper.GetDomainReputation(domain); + domainInfo = await DomainHelper.GetDomainReputation(domain); + _ = capturedDomainsCache.TryAdd(domain, domainInfo); } if (domainInfo is null) From 48304bb030ed7aad0791c33690bbb5c369fc9d74 Mon Sep 17 00:00:00 2001 From: Stone_Red <56473591+Stone-Red-Code@users.noreply.github.com> Date: Sun, 9 Jan 2022 14:56:54 +0100 Subject: [PATCH 2/4] - Fix messed up output colors --- FraudCapturer/DomainHelper.cs | 6 ++-- FraudCapturer/FraudCapturer.csproj | 1 + FraudCapturer/IpHelper.cs | 30 ++++++++---------- FraudCapturer/Program.cs | 49 ++++++++++++++---------------- 4 files changed, 40 insertions(+), 46 deletions(-) diff --git a/FraudCapturer/DomainHelper.cs b/FraudCapturer/DomainHelper.cs index 53ed20d..18feb7e 100644 --- a/FraudCapturer/DomainHelper.cs +++ b/FraudCapturer/DomainHelper.cs @@ -1,5 +1,7 @@ using PacketDotNet; +using Stone_Red_Utilities.ConsoleExtentions; + using System.Net; using System.Net.Sockets; using System.Text; @@ -49,7 +51,7 @@ internal class DomainHelper } catch (HttpRequestException ex) { - Console.WriteLine($"error: {ex.Message}"); + ConsoleExt.WriteLine($"error: {ex.Message}", ConsoleColor.Gray); return null; } @@ -72,7 +74,7 @@ internal class DomainHelper } catch (SocketException ex) { - Console.WriteLine($"error: {ex.Message} ({domain})"); + ConsoleExt.WriteLine($"error: {ex.Message} ({domain})", ConsoleColor.Gray); return null; } } diff --git a/FraudCapturer/FraudCapturer.csproj b/FraudCapturer/FraudCapturer.csproj index 6f4a3ce..ecd6d27 100644 --- a/FraudCapturer/FraudCapturer.csproj +++ b/FraudCapturer/FraudCapturer.csproj @@ -9,6 +9,7 @@ + diff --git a/FraudCapturer/IpHelper.cs b/FraudCapturer/IpHelper.cs index 2fb7915..f507b68 100644 --- a/FraudCapturer/IpHelper.cs +++ b/FraudCapturer/IpHelper.cs @@ -1,4 +1,6 @@ -using System.Net; +using Stone_Red_Utilities.ConsoleExtentions; + +using System.Net; using System.Text.Json; namespace FraudCapturer; @@ -18,7 +20,7 @@ internal class IpHelper } catch (HttpRequestException ex) { - Console.WriteLine($"error: {ex.Message}"); + ConsoleExt.WriteLine($"error: {ex.Message}", ConsoleColor.Gray); return null; } @@ -31,10 +33,10 @@ internal class IpHelper if (statusValue.GetString() != "ok") { - Console.Write(statusValue.GetString()); + ConsoleExt.Write(statusValue.GetString(), ConsoleColor.Gray); if (responseData.RootElement.TryGetProperty("message", out JsonElement messageValue)) { - Console.WriteLine($": {messageValue.GetString()}"); + ConsoleExt.WriteLine($": {messageValue.GetString()}", ConsoleColor.Gray); } else { @@ -96,21 +98,13 @@ internal class IpHelper } byte[] ip = IPAddress.Parse(ipAdress).GetAddressBytes(); - switch (ip[0]) + return ip[0] switch { - case 10: - case 127: - return true; - - case 172: - return ip[1] >= 16 && ip[1] < 32; - - case 192: - return ip[1] == 168; - - default: - return false; - } + 10 or 127 => true, + 172 => ip[1] >= 16 && ip[1] < 32, + 192 => ip[1] == 168, + _ => false, + }; } public static bool IsLocalIpAddress(string host) diff --git a/FraudCapturer/Program.cs b/FraudCapturer/Program.cs index a266179..9f7fa90 100644 --- a/FraudCapturer/Program.cs +++ b/FraudCapturer/Program.cs @@ -3,6 +3,8 @@ using PacketDotNet; using SharpPcap; +using Stone_Red_Utilities.ConsoleExtentions; + using System.Collections.Concurrent; using System.Net; @@ -38,10 +40,8 @@ public class Program if (string.IsNullOrWhiteSpace(args.FirstOrDefault())) { - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine("No proxycheck api key provided! You are limited to 100 IP checks per day. Get one for free at proxycheck.io."); + ConsoleExt.WriteLine("No proxycheck api key provided! You are limited to 100 IP checks per day. Get one for free at proxycheck.io.", ConsoleColor.Red); Console.WriteLine(); - Console.ResetColor(); } else { @@ -93,7 +93,7 @@ public class Program device.Open(); Console.WriteLine(); - Console.WriteLine("-- Listening on {0}, hit 'Ctrl-C' to exit...", device.Description); + Console.WriteLine($"-- Listening on {device.Description}, hit 'Ctrl-C' to exit..."); // Start capture of packets device.Capture(); @@ -139,7 +139,7 @@ public class Program capturedIpsCache.Clear(); capturedDomainsCache.Clear(); File.WriteAllText(IpStorePath, string.Empty); - Console.WriteLine("Cleared cache"); + ConsoleExt.WriteLine("Cleared cache", ConsoleColor.Gray); } //Check if a DNS packet contains a "dangerous" domain. @@ -156,7 +156,7 @@ public class Program await CheckIpAddress(remoteIpAddress, direction); TimeSpan timeRemainingUntilCacheReset = new TimeSpan(0, 10, 0) - (DateTime.Now - lastCacheClear); - Console.WriteLine($"Next cache reset in {timeRemainingUntilCacheReset.Minutes} minute(s) and {timeRemainingUntilCacheReset.Seconds} second(s)"); + ConsoleExt.WriteLine($"Next cache reset in {timeRemainingUntilCacheReset.Minutes} minute(s) and {timeRemainingUntilCacheReset.Seconds} second(s)", ConsoleColor.Gray); } } } @@ -167,43 +167,42 @@ public class Program if (IpHelper.IsInternalIpAddress(remoteIpAddress.ToString())) { - Console.ForegroundColor = ConsoleColor.Cyan; - Console.WriteLine($"[{direction}] [Internal] {remoteIpAddress}"); + ConsoleExt.WriteLine($"[{direction}] [Internal] {remoteIpAddress}", ConsoleColor.Cyan); } else if (ipInfo is not null) { bool block = false; + ConsoleColor consoleColor; + if (ipInfo.Risk >= 67) { FirewallHelper.BlockIp(remoteIpAddress); - Console.ForegroundColor = ConsoleColor.Red; + consoleColor = ConsoleColor.Red; block = true; } else if (ipInfo.Risk >= 34 && ipInfo.IsProxy) { FirewallHelper.BlockIp(remoteIpAddress); - Console.ForegroundColor = ConsoleColor.DarkYellow; + consoleColor = ConsoleColor.DarkYellow; block = true; } else if (ipInfo.IsProxy && ipInfo.Type != "VPN") { FirewallHelper.BlockIp(remoteIpAddress); - Console.ForegroundColor = ConsoleColor.DarkYellow; + consoleColor = ConsoleColor.DarkYellow; block = true; } else { - Console.ForegroundColor = ConsoleColor.Green; + consoleColor = ConsoleColor.Green; } - Console.WriteLine($"[{direction}] [Provider: {ipInfo.Provider}] [Risk: {ipInfo.Risk}] [Proxy: {ipInfo.IsProxy}] [Type: {ipInfo.Type}] [Block: {block}] {remoteIpAddress}"); + ConsoleExt.WriteLine($"[{direction}] [Provider: {ipInfo.Provider}] [Risk: {ipInfo.Risk}] [Proxy: {ipInfo.IsProxy}] [Type: {ipInfo.Type}] [Block: {block}] {remoteIpAddress}", consoleColor); } else { - Console.ForegroundColor = ConsoleColor.Magenta; - Console.WriteLine($"[{direction}] [Invalid] {remoteIpAddress}"); + ConsoleExt.WriteLine($"[{direction}] [Invalid] {remoteIpAddress}", ConsoleColor.Magenta); } - Console.ResetColor(); } private static async Task CheckDns(Packet packet, IPAddress remoteIpAddress, string direction) @@ -231,49 +230,47 @@ public class Program if (domainInfo is null) { - Console.ForegroundColor = ConsoleColor.Magenta; if (lastDomain != domain) { lastDomain = domain; - Console.WriteLine($"[{direction}] [Dns] [Invalid] [Domain: {domain}] {remoteIpAddress}"); + ConsoleExt.WriteLine($"[{direction}] [Dns] [Invalid] [Domain: {domain}] {remoteIpAddress}", ConsoleColor.Magenta); } - Console.ResetColor(); continue; } if (domainInfo.IsMatch == false) { - Console.ForegroundColor = ConsoleColor.Green; if (lastDomain != domain) { lastDomain = domain; - Console.WriteLine($"[{direction}] [Dns] [Domain: {domain}] [Type: Undetected] [Block: {block}] {remoteIpAddress}"); + ConsoleExt.WriteLine($"[{direction}] [Dns] [Domain: {domain}] [Type: Undetected] [Block: {block}] {remoteIpAddress}", ConsoleColor.Green); } - Console.ResetColor(); continue; } + ConsoleColor consoleColor; + if (domainInfo.TrustRating >= 0.9) { FirewallHelper.BlockIp(domainInfo.IpAddress); - Console.ForegroundColor = ConsoleColor.Red; + consoleColor = ConsoleColor.Red; block = true; } else if (domainInfo.TrustRating >= 0.5) { FirewallHelper.BlockIp(domainInfo.IpAddress); - Console.ForegroundColor = ConsoleColor.DarkYellow; + consoleColor = ConsoleColor.DarkYellow; block = true; } else { - Console.ForegroundColor = ConsoleColor.Green; + consoleColor = ConsoleColor.Green; } if (lastDomain != domain) { lastDomain = domain; - Console.WriteLine($"[{direction}] [Dns] [Domain: {domain}] [Type: {domainInfo.Type}] [Source: {domainInfo.Source}] [Source Trust: {domainInfo.TrustRating * 100d}] [Block: {block}] {remoteIpAddress}"); + ConsoleExt.WriteLine($"[{direction}] [Dns] [Domain: {domain}] [Type: {domainInfo.Type}] [Source: {domainInfo.Source}] [Source Trust: {domainInfo.TrustRating * 100d}] [Block: {block}] {remoteIpAddress}", consoleColor); } Console.ResetColor(); From e9147ff2b7d66ce216ac951a352e14bffeb5ed37 Mon Sep 17 00:00:00 2001 From: Stone_Red <56473591+Stone-Red-Code@users.noreply.github.com> Date: Tue, 11 Jan 2022 23:30:54 +0100 Subject: [PATCH 3/4] - Add Block config class --- FraudCapturer/Configuration/BlockConfig.cs | 42 +++++++++++++++++++ FraudCapturer/Configuration/BlockConfigSet.cs | 15 +++++++ FraudCapturer/Configuration/Configurator.cs | 11 +++++ FraudCapturer/{ => Helpers}/DomainHelper.cs | 2 +- FraudCapturer/{ => Helpers}/FirewallHelper.cs | 2 +- FraudCapturer/{ => Helpers}/IpHelper.cs | 2 +- FraudCapturer/{ => Helpers}/PackageHelper.cs | 2 +- FraudCapturer/Program.cs | 17 ++++---- 8 files changed, 81 insertions(+), 12 deletions(-) create mode 100644 FraudCapturer/Configuration/BlockConfig.cs create mode 100644 FraudCapturer/Configuration/BlockConfigSet.cs create mode 100644 FraudCapturer/Configuration/Configurator.cs rename FraudCapturer/{ => Helpers}/DomainHelper.cs (99%) rename FraudCapturer/{ => Helpers}/FirewallHelper.cs (98%) rename FraudCapturer/{ => Helpers}/IpHelper.cs (99%) rename FraudCapturer/{ => Helpers}/PackageHelper.cs (96%) diff --git a/FraudCapturer/Configuration/BlockConfig.cs b/FraudCapturer/Configuration/BlockConfig.cs new file mode 100644 index 0000000..1255ee9 --- /dev/null +++ b/FraudCapturer/Configuration/BlockConfig.cs @@ -0,0 +1,42 @@ +namespace FraudCapturer.Configuration; + +internal class BlockConfig +{ + public BlockConfigSet LowRiskSet { get; set; } = new BlockConfigSet(false, true, false); + public BlockConfigSet MeduimRiskSet { get; set; } = new BlockConfigSet(false, true, true); + public BlockConfigSet HighRiskSet { get; set; } = new BlockConfigSet(true, true, true); + + public bool CheckIfBlock(IpInfo ipInfo) + { + if (ipInfo.Risk <= 33) + { + return CheckIfBlockSet(ipInfo, LowRiskSet); + } + else if (ipInfo.Risk >= 67) + { + return CheckIfBlockSet(ipInfo, HighRiskSet); + } + else + { + return CheckIfBlockSet(ipInfo, MeduimRiskSet); + } + } + + public bool CheckIfBlockSet(IpInfo ipInfo, BlockConfigSet blockConfigSet) + { + if (ipInfo.Type == "VPN" && blockConfigSet.BlockIfVpn) + { + return true; + } + else if (ipInfo.IsProxy && blockConfigSet.BlockIfProxy) + { + return true; + } + else if (!ipInfo.IsProxy && blockConfigSet.BlockIfNotProxy) + { + return true; + } + + return false; + } +} \ No newline at end of file diff --git a/FraudCapturer/Configuration/BlockConfigSet.cs b/FraudCapturer/Configuration/BlockConfigSet.cs new file mode 100644 index 0000000..4e2b952 --- /dev/null +++ b/FraudCapturer/Configuration/BlockConfigSet.cs @@ -0,0 +1,15 @@ +namespace FraudCapturer.Configuration; + +internal class BlockConfigSet +{ + public BlockConfigSet(bool blockIfNotProxy, bool blockIfProxy, bool blockIfVpn) + { + BlockIfNotProxy = blockIfNotProxy; + BlockIfProxy = blockIfProxy; + BlockIfVpn = blockIfVpn; + } + + public bool BlockIfNotProxy { get; } + public bool BlockIfProxy { get; } + public bool BlockIfVpn { get; } +} \ No newline at end of file diff --git a/FraudCapturer/Configuration/Configurator.cs b/FraudCapturer/Configuration/Configurator.cs new file mode 100644 index 0000000..19ab305 --- /dev/null +++ b/FraudCapturer/Configuration/Configurator.cs @@ -0,0 +1,11 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FraudCapturer.Configuration; + +internal class Configurator +{ +} diff --git a/FraudCapturer/DomainHelper.cs b/FraudCapturer/Helpers/DomainHelper.cs similarity index 99% rename from FraudCapturer/DomainHelper.cs rename to FraudCapturer/Helpers/DomainHelper.cs index 18feb7e..1bb8bc7 100644 --- a/FraudCapturer/DomainHelper.cs +++ b/FraudCapturer/Helpers/DomainHelper.cs @@ -9,7 +9,7 @@ using System.Text.Json; using System.Text.Json.Serialization; using System.Text.RegularExpressions; -namespace FraudCapturer; +namespace FraudCapturer.Helpers; internal class DomainHelper { diff --git a/FraudCapturer/FirewallHelper.cs b/FraudCapturer/Helpers/FirewallHelper.cs similarity index 98% rename from FraudCapturer/FirewallHelper.cs rename to FraudCapturer/Helpers/FirewallHelper.cs index e1bb141..7113eb6 100644 --- a/FraudCapturer/FirewallHelper.cs +++ b/FraudCapturer/Helpers/FirewallHelper.cs @@ -1,6 +1,6 @@ using System.Net; -namespace FraudCapturer; +namespace FraudCapturer.Helpers; internal class FirewallHelper { diff --git a/FraudCapturer/IpHelper.cs b/FraudCapturer/Helpers/IpHelper.cs similarity index 99% rename from FraudCapturer/IpHelper.cs rename to FraudCapturer/Helpers/IpHelper.cs index f507b68..3ee1465 100644 --- a/FraudCapturer/IpHelper.cs +++ b/FraudCapturer/Helpers/IpHelper.cs @@ -3,7 +3,7 @@ using System.Net; using System.Text.Json; -namespace FraudCapturer; +namespace FraudCapturer.Helpers; internal class IpHelper { diff --git a/FraudCapturer/PackageHelper.cs b/FraudCapturer/Helpers/PackageHelper.cs similarity index 96% rename from FraudCapturer/PackageHelper.cs rename to FraudCapturer/Helpers/PackageHelper.cs index b4e824b..a87572d 100644 --- a/FraudCapturer/PackageHelper.cs +++ b/FraudCapturer/Helpers/PackageHelper.cs @@ -2,7 +2,7 @@ using System.Text; -namespace FraudCapturer; +namespace FraudCapturer.Helpers; internal static class PackageHelper { diff --git a/FraudCapturer/Program.cs b/FraudCapturer/Program.cs index 9f7fa90..8c6e509 100644 --- a/FraudCapturer/Program.cs +++ b/FraudCapturer/Program.cs @@ -1,4 +1,6 @@ - +using FraudCapturer.Configuration; +using FraudCapturer.Helpers; + using PacketDotNet; using SharpPcap; @@ -10,9 +12,6 @@ using System.Net; namespace FraudCapturer; -/// -/// Example showing packet manipulation -/// public class Program { public const string AppName = "FraudCapturer"; @@ -25,6 +24,8 @@ public class Program private static readonly ConcurrentBag capturedIpsCache = new(); private static readonly ConcurrentDictionary capturedDomainsCache = new(); + private static BlockConfig blockConfig = new BlockConfig(); + /// /// The main entry point for the application. /// @@ -174,19 +175,19 @@ public class Program bool block = false; ConsoleColor consoleColor; - if (ipInfo.Risk >= 67) + if (ipInfo.Risk >= 67 && blockConfig.CheckIfBlockSet(ipInfo, blockConfig.HighRiskSet)) { FirewallHelper.BlockIp(remoteIpAddress); consoleColor = ConsoleColor.Red; block = true; } - else if (ipInfo.Risk >= 34 && ipInfo.IsProxy) + else if (ipInfo.Risk <= 33 && blockConfig.CheckIfBlockSet(ipInfo, blockConfig.LowRiskSet)) { FirewallHelper.BlockIp(remoteIpAddress); - consoleColor = ConsoleColor.DarkYellow; + consoleColor = ConsoleColor.Yellow; block = true; } - else if (ipInfo.IsProxy && ipInfo.Type != "VPN") + else if (blockConfig.CheckIfBlockSet(ipInfo, blockConfig.MeduimRiskSet)) { FirewallHelper.BlockIp(remoteIpAddress); consoleColor = ConsoleColor.DarkYellow; From 591c7055e942fbd0728ef75424220210b12af5cf Mon Sep 17 00:00:00 2001 From: Stone_Red <56473591+Stone-Red-Code@users.noreply.github.com> Date: Thu, 20 Jan 2022 09:29:16 +0100 Subject: [PATCH 4/4] - Add configuration opption --- FraudCapturer/Configuration/BlockConfigSet.cs | 10 ++- FraudCapturer/Configuration/Configurator.cs | 68 ++++++++++++++++--- FraudCapturer/Program.cs | 18 ++++- 3 files changed, 84 insertions(+), 12 deletions(-) diff --git a/FraudCapturer/Configuration/BlockConfigSet.cs b/FraudCapturer/Configuration/BlockConfigSet.cs index 4e2b952..719fe53 100644 --- a/FraudCapturer/Configuration/BlockConfigSet.cs +++ b/FraudCapturer/Configuration/BlockConfigSet.cs @@ -9,7 +9,11 @@ internal class BlockConfigSet BlockIfVpn = blockIfVpn; } - public bool BlockIfNotProxy { get; } - public bool BlockIfProxy { get; } - public bool BlockIfVpn { get; } + public BlockConfigSet() + { + } + + public bool BlockIfNotProxy { get; set; } + public bool BlockIfProxy { get; set; } + public bool BlockIfVpn { get; set; } } \ No newline at end of file diff --git a/FraudCapturer/Configuration/Configurator.cs b/FraudCapturer/Configuration/Configurator.cs index 19ab305..dd81117 100644 --- a/FraudCapturer/Configuration/Configurator.cs +++ b/FraudCapturer/Configuration/Configurator.cs @@ -1,11 +1,63 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace FraudCapturer.Configuration; +namespace FraudCapturer.Configuration; internal class Configurator { -} + public BlockConfig GetConfig() + { + BlockConfig blockConfig = new BlockConfig(); + + Console.WriteLine("Configuration:"); + Console.WriteLine(); + + Console.WriteLine("High risk rules (>=66%):"); + Console.WriteLine("----------------------------------------------------"); + blockConfig.HighRiskSet = GetBlockConfigSetFromConsole(true, true, true); + + Console.WriteLine("High medium rules (>33% & <66%):"); + Console.WriteLine("----------------------------------------------------"); + blockConfig.MeduimRiskSet = GetBlockConfigSetFromConsole(false, true, true); + + Console.WriteLine("High low rules (<=33%):"); + Console.WriteLine("----------------------------------------------------"); + blockConfig.LowRiskSet = GetBlockConfigSetFromConsole(false, true, false); + + return blockConfig; + } + + private BlockConfigSet GetBlockConfigSetFromConsole(bool ifNotProxyDefault, bool ifproxyDefault, bool ifVpnDeault) + { + BlockConfigSet blockConfigSet = new BlockConfigSet(); + Console.WriteLine($"Block if no Proxy detected {GetDefaultHintString(ifNotProxyDefault)}:"); + blockConfigSet.BlockIfNotProxy = GetBoolValueFromConsole(ifNotProxyDefault); + + Console.WriteLine($"Block if Proxy detected {GetDefaultHintString(ifproxyDefault)}:"); + blockConfigSet.BlockIfProxy = GetBoolValueFromConsole(ifproxyDefault); + + Console.WriteLine($"Block if VPN detected {GetDefaultHintString(ifVpnDeault)}:"); + blockConfigSet.BlockIfVpn = GetBoolValueFromConsole(ifVpnDeault); + + return blockConfigSet; + } + + private bool GetBoolValueFromConsole(bool defaultValue) + { + string input = Console.ReadLine() ?? string.Empty; + + if (string.IsNullOrWhiteSpace(input)) + { + return defaultValue; + } + + while (input.ToLower() != "y" && input.ToLower() != "n") + { + input = Console.ReadLine() ?? string.Empty; + } + + return input.ToLower() == "y"; + } + + private string GetDefaultHintString(bool defaultValue) + { + return defaultValue ? "[Y/n]" : "[y/N]"; + } +} \ No newline at end of file diff --git a/FraudCapturer/Program.cs b/FraudCapturer/Program.cs index 8c6e509..3389f2b 100644 --- a/FraudCapturer/Program.cs +++ b/FraudCapturer/Program.cs @@ -9,6 +9,7 @@ using Stone_Red_Utilities.ConsoleExtentions; using System.Collections.Concurrent; using System.Net; +using System.Text.Json; namespace FraudCapturer; @@ -17,6 +18,7 @@ public class Program public const string AppName = "FraudCapturer"; public const string AppUrl = "https://github.com/Stone-Red-Code/FraudCapturer"; public const string IpStorePath = "ipAdresses.txt"; + public const string ConfigStorePath = "config.txt"; private static DateTime lastCacheClear; private static string lastDomain = string.Empty; @@ -39,7 +41,16 @@ public class Program // Retrieve the device list CaptureDeviceList devices = CaptureDeviceList.Instance; - if (string.IsNullOrWhiteSpace(args.FirstOrDefault())) + if (args.FirstOrDefault() == "config") + { + blockConfig = new Configurator().GetConfig(); + string jsonConfig = JsonSerializer.Serialize(blockConfig); + File.WriteAllText(ConfigStorePath, jsonConfig); + + Console.WriteLine("-- Configuration saved!"); + return; + } + else if (string.IsNullOrWhiteSpace(args.FirstOrDefault())) { ConsoleExt.WriteLine("No proxycheck api key provided! You are limited to 100 IP checks per day. Get one for free at proxycheck.io.", ConsoleColor.Red); Console.WriteLine(); @@ -49,6 +60,11 @@ public class Program IpHelper.ProxycheckApiKey = args.FirstOrDefault(); } + if (File.Exists(ConfigStorePath)) + { + blockConfig = JsonSerializer.Deserialize(File.ReadAllText(ConfigStorePath)) ?? new BlockConfig(); + } + // If no devices were found print an error if (devices.Count < 1) {