- Add async packet processing

This commit is contained in:
Stone_Red
2022-01-08 19:33:35 +01:00
parent 4b80b801fb
commit 0b09e749bc
4 changed files with 86 additions and 52 deletions
+12 -3
View File
@@ -22,7 +22,7 @@ internal class DomainHelper
return domains.Distinct().ToArray(); return domains.Distinct().ToArray();
} }
public static DomainInfo? GetDomainReputation(string domain) public static async Task<DomainInfo?> GetDomainReputation(string domain)
{ {
try try
{ {
@@ -41,10 +41,19 @@ internal class DomainHelper
}; };
HttpContent httpContent = new StringContent(JsonSerializer.Serialize(reqestBody), Encoding.UTF8, "application/json"); 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<AntiFishResultBody>(resultString); AntiFishResultBody? resultBody = JsonSerializer.Deserialize<AntiFishResultBody>(resultString);
AntiFishResult? result = resultBody?.Matches?.FirstOrDefault(m => m.Domain == domain); AntiFishResult? result = resultBody?.Matches?.FirstOrDefault(m => m.Domain == domain);
+45 -36
View File
@@ -11,21 +11,24 @@ internal class FirewallHelper
throw new ArgumentNullException(nameof(ipAddress)); throw new ArgumentNullException(nameof(ipAddress));
} }
AddRuleIfDoesnotExist(ipAddress); lock (Program.IpStorePath)
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, AddRuleIfDoesnotExist(ipAddress);
FileName = "cmd.exe",
Arguments = $"/C netsh advfirewall firewall set rule name=\"{Program.AppName} IP Block\" new remoteIp={string.Join(',', iPs)}" File.AppendAllText(Program.IpStorePath, $"{Environment.NewLine}{ipAddress}");
};
process.StartInfo = startInfo; string[] iPs = File.ReadAllLines(Program.IpStorePath);
_ = process.Start();
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) public static void UnblockIp(IPAddress? ipAddress)
@@ -35,33 +38,39 @@ internal class FirewallHelper
throw new ArgumentNullException(nameof(ipAddress)); throw new ArgumentNullException(nameof(ipAddress));
} }
List<string> iPs = File.ReadAllLines(Program.IpStorePath).ToList(); lock (Program.IpStorePath)
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, List<string> iPs = File.ReadAllLines(Program.IpStorePath).ToList();
FileName = "cmd.exe", iPs.Remove(ipAddress.ToString());
Arguments = $"/C netsh advfirewall firewall set rule name=\"{Program.AppName} IP Block\" new remoteIp={string.Join(',', iPs.ToArray())}"
}; File.WriteAllLines(Program.IpStorePath, iPs);
process.StartInfo = startInfo;
_ = process.Start(); 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) public static void AddRuleIfDoesnotExist(IPAddress ipAddress)
{ {
System.Diagnostics.Process process = new System.Diagnostics.Process(); lock (Program.IpStorePath)
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo
{ {
WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden, System.Diagnostics.Process process = new System.Diagnostics.Process();
FileName = "cmd.exe", System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo
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}" {
}; WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
process.StartInfo = startInfo; FileName = "cmd.exe",
_ = process.Start(); 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.WaitForExit(); };
process.StartInfo = startInfo;
_ = process.Start();
process.WaitForExit();
}
} }
} }
+11 -2
View File
@@ -7,11 +7,20 @@ internal class IpHelper
{ {
public static string? ProxycheckApiKey { get; set; } public static string? ProxycheckApiKey { get; set; }
public static IpInfo? GetIpReputation(IPAddress ipAddress) public static async Task<IpInfo?> GetIpReputation(IPAddress ipAddress)
{ {
HttpClient httpClient = new HttpClient(); 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); JsonDocument responseData = JsonDocument.Parse(rawResponseData);
+18 -11
View File
@@ -3,6 +3,7 @@ using PacketDotNet;
using SharpPcap; using SharpPcap;
using System.Collections.Concurrent;
using System.Net; using System.Net;
namespace FraudCapturer; namespace FraudCapturer;
@@ -19,8 +20,8 @@ public class Program
private static DateTime lastCacheClear; private static DateTime lastCacheClear;
private static string lastDomain = string.Empty; private static string lastDomain = string.Empty;
private static readonly List<string> capturedIpsCache = new(); private static readonly ConcurrentBag<string> capturedIpsCache = new();
private static readonly Dictionary<string, DomainInfo> capturedDomainsCache = new(); private static readonly ConcurrentDictionary<string, DomainInfo?> capturedDomainsCache = new();
/// <summary> /// <summary>
/// The main entry point for the application. /// The main entry point for the application.
@@ -101,6 +102,11 @@ public class Program
private static void Device_OnPacketArrival(object sender, PacketCapture e) private static void Device_OnPacketArrival(object sender, PacketCapture e)
{ {
RawCapture rawPacket = e.GetPacket(); RawCapture rawPacket = e.GetPacket();
ProcessRawPacket(rawPacket);
}
private static async void ProcessRawPacket(RawCapture rawPacket)
{
Packet packet = Packet.ParsePacket(rawPacket.LinkLayerType, rawPacket.Data); Packet packet = Packet.ParsePacket(rawPacket.LinkLayerType, rawPacket.Data);
if (packet is EthernetPacket) if (packet is EthernetPacket)
{ {
@@ -137,27 +143,27 @@ public class Program
} }
//Check if a DNS packet contains a "dangerous" domain. //Check if a DNS packet contains a "dangerous" domain.
CheckDns(packet, remoteIpAddress, direction); await CheckDns(packet, remoteIpAddress, direction);
if (capturedIpsCache.Contains(remoteIpAddress.ToString())) if (capturedIpsCache.Contains(remoteIpAddress.ToString()))
{ {
return; 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()); capturedIpsCache.Add(remoteIpAddress.ToString());
//Check if ip address is "dangerous" or blocked //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())) if (IpHelper.IsInternalIpAddress(remoteIpAddress.ToString()))
{ {
@@ -200,7 +206,7 @@ public class Program
Console.ResetColor(); 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 transportPacket = packet.Extract<TcpPacket>();
transportPacket ??= packet.Extract<UdpPacket>(); transportPacket ??= packet.Extract<UdpPacket>();
@@ -219,7 +225,8 @@ public class Program
} }
else else
{ {
domainInfo = DomainHelper.GetDomainReputation(domain); domainInfo = await DomainHelper.GetDomainReputation(domain);
_ = capturedDomainsCache.TryAdd(domain, domainInfo);
} }
if (domainInfo is null) if (domainInfo is null)