简体   繁体   中英

How to check if Firewall rule existed

I have a button that's once clicked, it will add a new rule to firewall. BUT the problem is it can be clicked many times and will add many rules.

How do I check if the rule exists in Firewall? (or is it possible to check rules?)

Here's my code for adding a rule:

ProcessStartInfo run = new ProcessStartInfo();
run.FileName = "cmd.exe";
run.Verb = "runas";
run.Arguments = "/C netsh advfirewall firewall add rule name=\"Block IP Rule\" dir=in interface=any action=block remoteip=x.x.x.x";
run.WindowStyle = ProcessWindowStyle.Hidden;
Process.Start(run);
    public static void RemoveFirewallRules(string RuleName = "BreakermindCom")
{
    try
    {
        Type tNetFwPolicy2 = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
        INetFwPolicy2 fwPolicy2 = (INetFwPolicy2)Activator.CreateInstance(tNetFwPolicy2);
        var currentProfiles = fwPolicy2.CurrentProfileTypes;               

        // Lista rules
        List<INetFwRule> RuleList = new List<INetFwRule>();

        foreach (INetFwRule rule in fwPolicy2.Rules)
        {
            // Add rule to list
            //RuleList.Add(rule);
            // Console.WriteLine(rule.Name);
            if (rule.Name.IndexOf(RuleName) != -1)
            {
                // Now add the rule
                INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));                     
                firewallPolicy.Rules.Remove(rule.Name);
                Console.WriteLine(rule.Name + " has been deleted from Firewall Policy");
            }
        }
    }
    catch (Exception r)
    {
        Console.WriteLine("Error delete rule from firewall");
    }}

Works ... :}

You can use linq when initializing your firewall rules to be selective/specific.

For multiple firewall rules with the same name:

    INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2")); 
    List<INetFwRule> firewallRules = firewallPolicy.Rules.OfType<INetFwRule>().Where(x => x.Name.Contains(fwRuleName)).ToList();

    foreach (INetFwRule rule in firewallRules)
    {
        firewallPolicy.Rules.Remove(rule.Name);
    }

For a single firewall rule:

    INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
    INetFwRule firewallRule = firewallPolicy.Rules.OfType<INetFwRule>().Where(x => x.Name == fwRuleName).FirstOrDefault();
    firewallPolicy.Rules.Remove(firewallRule.Name);

However, if you know the firewall rule name already, you might also just be able to do this (untested, but without the Where clause):

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

The point though was to show the linq syntax and the flexibility of being able to search specific names, patterns, etc. with it.

WindowsFirewallHelper class. Available as a NuGet package for VS. I looked for days for a solution and found this. Changed my life for a very important project.

Here's the code to do what you want:

 private void initFWrule(object sender, EventArgs e) { Console.WriteLine("CHECKING FIREWALL RULE EXISTENCE"); var myRule = FirewallManager.Instance.Rules.SingleOrDefault(r => r.Name == "BlockUTG_Port-26881"); //substitute your rule name in place of BlockUTG_Port-26881 above try { if (myRule != null) { Console.WriteLine("Rules DOES Exist"); } else { Console.WriteLine("Rules DOES NOT Exist"); //run your code here to create rule } } catch (Exception ex) { MessageBox.Show(ex.Message); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM