Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating existing firewall rule using API

I am able to pro grammatically add individual rules to the Windows Firewall (Server 2008 R2), however I am trying to avoid multiple rules per IP address, and would just like to update the existing rule RemoteAddresses. Below is the code I am using to add rules, I am doing my best to research how to update the existing rules Remote Addresses, but with no luck.

Any help is appreciated!

string ip = "x.x.x.x";

INetFwRule2 firewallRule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));

firewallRule.Name = "Block Bad IP Addresses";
firewallRule.Description = "Block Nasty Incoming Connections from IP Address.";
firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
firewallRule.Enabled = true;
firewallRule.InterfaceTypes = "All";
firewallRule.RemoteAddresses = ip;

INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
firewallPolicy.Rules.Add(firewallRule);
like image 673
user1270483 Avatar asked Mar 15 '12 01:03

user1270483


2 Answers

I have found this package it is available via nuget WindowsFirewallHelper

PM> install-package WindowsFirewallHelper

Example

var rule = FirewallManager.Instance.Rules.Where(o => 
    o.Direction == FirewallDirection.Inbound &&
    o.Name.Equals("Allow Remote Desktop")
).FirstOrDefault();

if (rule != null)
{
    //Update an existing Rule
    rule.RemoteAddresses = new IAddress[]
    {
        SingleIP.Parse("192.168.184.1"),
        SingleIP.Parse("192.168.184.2")
    };

    return;
}

//Create a new rule
rule = FirewallManager.Instance.CreateApplicationRule(
     FirewallManager.Instance.GetProfile().Type,
     @"Allow Remote Desktop",
     FirewallAction.Allow,
     null
);

rule.Direction = FirewallDirection.Inbound;
rule.LocalPorts = new ushort[] { 3389 };
rule.Action = FirewallAction.Allow;
rule.Protocol = FirewallProtocol.TCP;
rule.Scope = FirewallScope.All;
rule.Profiles = FirewallProfiles.Public | FirewallProfiles.Private;
rule.RemoteAddresses = new IAddress[] { SingleIP.Parse("192.168.184.1") };

FirewallManager.Instance.Rules.Add(rule);
like image 104
live2 Avatar answered Oct 12 '22 19:10

live2


The code below works for me:

INetFwPolicy2 firewallPolicy = (INetFwPolicy2) Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));

var rule = firewallPolicy.Rules.Item("Block Bad IP Addresses"); // Name of your rule here
rule.Name = "Block Block Block"; // Update the rule here. Nothing else needed to persist the changes
like image 41
amdmax Avatar answered Oct 12 '22 19:10

amdmax