Search code examples
c#windowswindows-firewall

read firewall settings to see which profiles are allowed on applications with c# on windows


I am trying to programmatically read which profiles are allowed for applications are allowed through the firewall. I have been using the following c# code:

string inputname  = "TestFirewallUpdateSettings";
    private void button1_Click(object sender, EventArgs e)
    {
        INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(
        Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));

        INetFwRule firewallRule = firewallPolicy.Rules.OfType<INetFwRule>().Where(x => x.Name == inputname).FirstOrDefault();

        richTextBox1.Text +=  firewallRule.Profiles.ToString();

    }

The value returned is an integer value returned as seen here:

https://msdn.microsoft.com/en-us/library/microsoft.teamfoundation.build.common.inetfwrule.profiles(v=vs.120).aspx

Now I want to know if Domain, public or private profiles have been allowed. my return values have been all over the place from 4 to 2147483647 and I assume it is coded somehow, but there is no explanation I can find that says what the output actually means. Can someone let me know where to find this information.


Solution

  • I think I found the answer through several trial and error.

    The output of firewallRule.Profiles() is a int value.

    This image is the GUI version of the firewall for allowed programs

    So the output value is:

    Domain + Private + public = output value

    If the values are enabled the math looks like:

    1 + 2 + 4 = 7

    So it is just the first 3 bits of the integer value. The picture above would be:

    1 + 4 = 5

    since the Private network is not enabled, the 2 would not be added in.

    If the firewall you are trying to find cannot be found, then that is when the 2147483647 value is found (max positive int32 value)