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

后端 未结 4 2097
灰色年华
灰色年华 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:41

    I think your best bet is to talk to the Windows Firewall with Advanced Security API.

    A quick google for "C# INetFwRule2" will show you numerous examples of how to register or update a Firewall rule.

    In order to add to both public and private policies i've used something along the lines of

    Type tNetFwPolicy2 = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
    INetFwPolicy2 fwPolicy2 = (INetFwPolicy2)Activator.CreateInstance(tNetFwPolicy2);
    var currentProfiles = fwPolicy2.CurrentProfileTypes;
    
    // Let's create a new rule
    
    INetFwRule2 inboundRule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
    inboundRule.Enabled = true;
    inboundRule.LocalPorts = "1234";
    inboundRule.Protocol = 6; // TCP
    // ...
    inboundRule.Profiles = currentProfiles;
    
    // Now add the rule
    
    INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
    firewallPolicy.Rules.Add(inboundRule);
    

提交回复
热议问题