Files
FraudCapturer/FraudCapturer/Helpers/FirewallHelper.cs
T
2022-01-11 23:30:54 +01:00

76 lines
2.9 KiB
C#

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();
}
}
}