Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

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

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 allowedprogram program= "Path.." name=AppName ENABLE scope=ALL profile=CURRENT"

But now I'd like to automate the proccess a little using a COM object. Found this shiny piece of code - http://web.archive.org/web/20070707110141/http://www.dot.net.nz/Default.aspx?tabid=42&mid=404&ctl=Details&ItemID=8

And after implementing the class I've been trying to use- FirewallHelper.Instance.GrantAuthorization(@"Path... ","AppName ",NET_FW_SCOPE_.NET_FW_SCOPE_ALL,NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY);

The problem I'm facing is that the GrantAuthorization method will only add a rule for the public OR private network whereas my old netsh command would 2 rules for- 1 for each network.

The commands actually seems very similar so it is kinda buffling to me.

So... how to add both network rules?

Shaun

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

My answer is from David's answer but more detail. And fix problem about setting Localports. You need to setting Protocol before setting Localports. More detail is bellow:

the first, you need to import reference FirewallAPI.dll. It's in "C:WindowsSystem32FirewallAPI.dll" then:

using NetFwTypeLib;

and insert code into your:

        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;
        //Allow through firewall
        inboundRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
        //Using protocol TCP
        inboundRule.Protocol = 6; // TCP
        //Port 81
        inboundRule.LocalPorts = "81";
        //Name of rule
        inboundRule.Name = "MyRule";
        // ...//
        inboundRule.Profiles = currentProfiles;

        // Now add the rule
        INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
        firewallPolicy.Rules.Add(inboundRule);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...