Updating existing firewall rule using API

前端 未结 3 1354
花落未央
花落未央 2021-02-06 02:02

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

相关标签:
3条回答
  • 2021-02-06 02:06

    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
    
    0 讨论(0)
  • 2021-02-06 02:11

    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);
    
    0 讨论(0)
  • 2021-02-06 02:26

    In addition to amdmax's answer (sorry I can't add a comment) I found that there is no simple method call to check to see if a rule exists so I came up with this to ensure that a rule is created whether it exists or not:

      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);
      }
    
    0 讨论(0)
提交回复
热议问题