Adding an application firewall rule to both private and public networks via win7 FirewallAPI

后端 未结 4 2081
灰色年华
灰色年华 2020-12-09 23:13

A little background: Basicaly I\'d like to add a program firewall access rule to both private and public networks.

I used to use this- \"netsh firewall add allowedpr

4条回答
  •  暖寄归人
    2020-12-09 23:33

    This page doesn't say this has been answered and is old, so just in case, for future use, I'll answer this.

    First, import reference FirewallAPI.dll, located at "C:\Windows\System32\FirewallAPI.dll", then add the using directive

    using NetFwTypeLib;
    

    The inboundRule.Profiles property seems to be classified as a set of flags with the following values (the property's type is an int, so i made an enum):

    public enum FirewallProfiles
    {
        Domain = 1,
        Private = 2,
        Public = 4
    }
    

    So, with that code, we can change the Profiles to the following:

    // Create a new rule
    INetFwRule2 inboundRule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwRule"));
    // Enable the rule
    inboundRule.Enabled = true;
    // Allow through firewall
    inboundRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
    // Using protocol TCP
    inboundRule.Protocol = 6; // TCP
    // Set port number
    inboundRule.LocalPorts = "1234";
    // Name of rule
    inboundRule.Name = "Name Of Firewall Rule";
    // Set profiles
    inboundRule.Profiles = (int)(FirewallProfiles.Private | FirewallProfiles.Public);
    
    // Add the rule
    INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
    firewallPolicy.Rules.Add(inboundRule);
    

    Or you could change inboundRule.Profiles to an int value.

    Two notes:

    1: If you don't run this code under administrative privilege's,

    firewallPolicty.Rules.Add(inboundRule);
    

    will throw an exception.

    2: inboundRule.Profiles must be between values 1 and 7. Otherwise, it will throw an exception

提交回复
热议问题