使用API更新现有防火墙规则

本文关键字:防火墙 规则 API 更新 使用 | 更新日期: 2023-09-27 18:27:46

我能够按语法向Windows防火墙(Server 2008 R2)添加单个规则,但我正在尝试避免每个IP地址有多个规则,并且只想更新现有的规则RemoteAddresses。下面是我用来添加规则的代码,我正在尽我所能研究如何更新现有的规则远程地址,但没有成功。

感谢您的帮助!

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);

使用API更新现有防火墙规则

下面的代码适用于我:

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

除了amdmax的答案(很抱歉我不能添加注释),我发现没有简单的方法调用来检查规则是否存在,所以我想出了这个方法来确保创建规则,无论它是否存在:

  INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(
      Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
  INetFwRule firewallRule = firewallPolicy.Rules.OfType<INetFwRule>().Where(x => x.Name == RULE_NAME).FirstOrDefault();
  if (firewallRule == null)
  {
    firewallRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
    firewallRule.Name = RULE_NAME;
    firewallPolicy.Rules.Add(firewallRule);
  }

我找到了这个包,它可以通过nuget-WindowsFirewallHelper 获得

PM> install-package WindowsFirewallHelper

示例

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);