I'm adapting a manual auditing PowerShell script to a C# .NET 4.5 Windows Service application that will run on multiple workstations, and I need to check if the firewall is enabled on the domain, private and public Windows network profiles. If the firewall is enabled on each profile the audit passes otherwise it fails. The PowerShell version is as follows.
$pass = $false
$firewallProfiles = netsh advfirewall show all state | Out-String -Stream
$domain = $false
$private = $false
$public = $false
# Check Domain profile
if ($firewallProfiles[3] -eq "State ON") {
$domain = $true
}
# Check Private profile
if ($firewallProfiles[7] -eq "State ON") {
$private = $true
}
# Check Public profile
if ($firewallProfiles[11] -eq "State ON") {
$public = $true
}
My C# implementation is partially working until I try and check the public profile. I then get a compile-time error of An unhandled exception of type 'System.ArgumentException' occurred in ConsoleApp3.dll Value does not fall within the expected range. I am using the FirewallAPI.dll for the following code. I'm not even really sure if I'm actually checking the profiles I'm intending to, so any input would be beneficial.
using NetFwTypeLib;
Type NetFwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false);
INetFwMgr mgr = (INetFwMgr)Activator.CreateInstance(NetFwMgrType);
bool domainProfile =mgr.LocalPolicy.GetProfileByType((NET_FW_PROFILE_TYPE_)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE 2_DOMAIN).FirewallEnabled;
bool privateProfile = mgr.LocalPolicy.GetProfileByType((NET_FW_PROFILE_TYPE_)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE).FirewallEnabled;
bool publicProfile = mgr.LocalPolicy.GetProfileByType((NET_FW_PROFILE_TYPE_)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PUBLIC).FirewallEnabled;
if (domainProfile)
{
Console.WriteLine("domain profile firewall enabled");
}
if (privateProfile)
{
Console.WriteLine("private profile firewall enabled");
}
if (publicProfile)
{
Console.WriteLine("public profile firewall enabled");
}