Reputation: 297
I'm trying to set a firewall exception for Windows 10. After doing numerous searches, I put together this code:
private const string PROGID_OPEN_PORT = "HNetCfg.FWOpenPort";
private const string CLSID_FIREWALL_MANAGER = "{304CE942-6E39-40D8-943A-B913C40C9CD4}";
private NetFwTypeLib.INetFwMgr GetFirewallManager()
{
Type objectType = Type.GetTypeFromCLSID(
new Guid(CLSID_FIREWALL_MANAGER));
return Activator.CreateInstance(objectType)
as NetFwTypeLib.INetFwMgr;
}
INetFwMgr manager = GetFirewallManager();
Type type = Type.GetTypeFromProgID(PROGID_OPEN_PORT);
INetFwOpenPort port = Activator.CreateInstance(type) as INetFwOpenPort;
port.Name = "MyPortRule";
port.Port = 9600;
port.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL;
port.Protocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
port.IpVersion = NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY;
manager.LocalPolicy.CurrentProfile.GloballyOpenPorts.Add(port);
This does get a firewall rule put into the Windows Firewall with Advanced Security, but the Profile for the rule is set to public. With the Profile set to public the firewall does not let the data through the port.
Using the Windows UI to modify the rule, I determined that the Profile must be set to 'private' or 'any' in order for the data to pass through. Why doesn't the port.Scope set to NET_FW_SCOPE_.NET_FW_SCOPE_ALL get the profile set to Any? How do you set the profile in the firewall rule to private or any?
I also tried setting port.Scope to NET_FW_SCOPE_.NET_FW_SCOPE_LOCAL_SUBNET. The profile is still set to 'public'.
Upvotes: 3
Views: 4172
Reputation: 297
Adding to the GloballyOpenPorts did not work. The following code did work, based on the answer suggested by Stack Overflow.
INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(
Type.GetTypeFromProgID("HNetCfg.FWRule"));
firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
firewallRule.Description = "Enables eATM REST Web Service adapter
traffic.";
firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
firewallRule.Enabled = true;
firewallRule.InterfaceTypes = "All";
firewallRule.Name = "MyPort";
firewallRule.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
firewallRule.LocalPorts = "9600";
INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(
Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
firewallPolicy.Rules.Add(firewallRule);
So... the firewallRule with firewallPolicy worked where the INetFwMgr GloballyOpenPorts did not work because you could not set the Profile value for the port rule.
If anyone from Microsoft reads this it would be helpful to have some documentation on how these functions can be used. The online documentation is very very poor.
Upvotes: 5