Merge pull request #2 from Stone-Red-Code/develop

Develop
This commit is contained in:
Stone_Red
2022-01-21 17:20:44 +01:00
committed by GitHub
10 changed files with 306 additions and 137 deletions
@@ -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;
}
}
@@ -0,0 +1,19 @@
namespace FraudCapturer.Configuration;
internal class BlockConfigSet
{
public BlockConfigSet(bool blockIfNotProxy, bool blockIfProxy, bool blockIfVpn)
{
BlockIfNotProxy = blockIfNotProxy;
BlockIfProxy = blockIfProxy;
BlockIfVpn = blockIfVpn;
}
public BlockConfigSet()
{
}
public bool BlockIfNotProxy { get; set; }
public bool BlockIfProxy { get; set; }
public bool BlockIfVpn { get; set; }
}
@@ -0,0 +1,63 @@
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]";
}
}
-67
View File
@@ -1,67 +0,0 @@
using System.Net;
namespace FraudCapturer;
internal class FirewallHelper
{
public static void BlockIp(IPAddress? ipAddress)
{
if (ipAddress is null)
{
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
{
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)
{
if (ipAddress is null)
{
throw new ArgumentNullException(nameof(ipAddress));
}
List<string> 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
{
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();
}
}
+1
View File
@@ -9,6 +9,7 @@
<ItemGroup>
<PackageReference Include="SharpPcap" Version="6.1.0" />
<PackageReference Include="Stone_Red-C-Sharp-Utilities" Version="1.0.3.1" />
</ItemGroup>
</Project>
@@ -1,5 +1,7 @@
using PacketDotNet;
using Stone_Red_Utilities.ConsoleExtentions;
using System.Net;
using System.Net.Sockets;
using System.Text;
@@ -7,7 +9,7 @@ using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
namespace FraudCapturer;
namespace FraudCapturer.Helpers;
internal class DomainHelper
{
@@ -22,7 +24,7 @@ internal class DomainHelper
return domains.Distinct().ToArray();
}
public static DomainInfo? GetDomainReputation(string domain)
public static async Task<DomainInfo?> GetDomainReputation(string domain)
{
try
{
@@ -41,10 +43,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)
{
ConsoleExt.WriteLine($"error: {ex.Message}", ConsoleColor.Gray);
return null;
}
string resultString = responseMessage.Content.ReadAsStringAsync().GetAwaiter().GetResult(); ;
string resultString = await responseMessage.Content.ReadAsStringAsync();
AntiFishResultBody? resultBody = JsonSerializer.Deserialize<AntiFishResultBody>(resultString);
AntiFishResult? result = resultBody?.Matches?.FirstOrDefault(m => m.Domain == domain);
@@ -63,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;
}
}
+76
View File
@@ -0,0 +1,76 @@
using System.Net;
namespace FraudCapturer.Helpers;
internal class FirewallHelper
{
public static void BlockIp(IPAddress? ipAddress)
{
if (ipAddress is null)
{
throw new ArgumentNullException(nameof(ipAddress));
}
lock (Program.IpStorePath)
{
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)
{
if (ipAddress is null)
{
throw new ArgumentNullException(nameof(ipAddress));
}
lock (Program.IpStorePath)
{
List<string> 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)
{
lock (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 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();
}
}
}
@@ -1,17 +1,28 @@
using System.Net;
using Stone_Red_Utilities.ConsoleExtentions;
using System.Net;
using System.Text.Json;
namespace FraudCapturer;
namespace FraudCapturer.Helpers;
internal class IpHelper
{
public static string? ProxycheckApiKey { get; set; }
public static IpInfo? GetIpReputation(IPAddress ipAddress)
public static async Task<IpInfo?> 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)
{
ConsoleExt.WriteLine($"error: {ex.Message}", ConsoleColor.Gray);
return null;
}
JsonDocument responseData = JsonDocument.Parse(rawResponseData);
@@ -22,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
{
@@ -87,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)
@@ -2,7 +2,7 @@
using System.Text;
namespace FraudCapturer;
namespace FraudCapturer.Helpers;
internal static class PackageHelper
{
+65 -44
View File
@@ -1,26 +1,32 @@
using FraudCapturer.Configuration;
using FraudCapturer.Helpers;
using PacketDotNet;
using SharpPcap;
using Stone_Red_Utilities.ConsoleExtentions;
using System.Collections.Concurrent;
using System.Net;
using System.Text.Json;
namespace FraudCapturer;
/// <summary>
/// Example showing packet manipulation
/// </summary>
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;
private static readonly List<string> capturedIpsCache = new();
private static readonly Dictionary<string, DomainInfo> capturedDomainsCache = new();
private static readonly ConcurrentBag<string> capturedIpsCache = new();
private static readonly ConcurrentDictionary<string, DomainInfo?> capturedDomainsCache = new();
private static BlockConfig blockConfig = new BlockConfig();
/// <summary>
/// The main entry point for the application.
@@ -35,18 +41,30 @@ public class Program
// Retrieve the device list
CaptureDeviceList devices = CaptureDeviceList.Instance;
if (string.IsNullOrWhiteSpace(args.FirstOrDefault()))
if (args.FirstOrDefault() == "config")
{
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.");
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();
Console.ResetColor();
}
else
{
IpHelper.ProxycheckApiKey = args.FirstOrDefault();
}
if (File.Exists(ConfigStorePath))
{
blockConfig = JsonSerializer.Deserialize<BlockConfig>(File.ReadAllText(ConfigStorePath)) ?? new BlockConfig();
}
// If no devices were found print an error
if (devices.Count < 1)
{
@@ -92,7 +110,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();
@@ -101,6 +119,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)
{
@@ -133,74 +156,73 @@ 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.
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);
ConsoleExt.WriteLine($"Next cache reset in {timeRemainingUntilCacheReset.Minutes} minute(s) and {timeRemainingUntilCacheReset.Seconds} second(s)", ConsoleColor.Gray);
}
}
}
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()))
{
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;
if (ipInfo.Risk >= 67)
ConsoleColor consoleColor;
if (ipInfo.Risk >= 67 && blockConfig.CheckIfBlockSet(ipInfo, blockConfig.HighRiskSet))
{
FirewallHelper.BlockIp(remoteIpAddress);
Console.ForegroundColor = ConsoleColor.Red;
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);
Console.ForegroundColor = ConsoleColor.DarkYellow;
consoleColor = ConsoleColor.Yellow;
block = true;
}
else if (ipInfo.IsProxy && ipInfo.Type != "VPN")
else if (blockConfig.CheckIfBlockSet(ipInfo, blockConfig.MeduimRiskSet))
{
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 void CheckDns(Packet packet, IPAddress remoteIpAddress, string direction)
private static async Task CheckDns(Packet packet, IPAddress remoteIpAddress, string direction)
{
TransportPacket transportPacket = packet.Extract<TcpPacket>();
transportPacket ??= packet.Extract<UdpPacket>();
@@ -219,54 +241,53 @@ public class Program
}
else
{
domainInfo = DomainHelper.GetDomainReputation(domain);
domainInfo = await DomainHelper.GetDomainReputation(domain);
_ = capturedDomainsCache.TryAdd(domain, domainInfo);
}
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();