12

I am trying to programmatically create an Outbound Windows firewall rule. In addition, I'd like to programmatically enable and disable this rule. How can I go about doing this in C#? Manually, I can do this by going into control panel, clicking on Windows Firewall, then clicking advanced settings.

live2
  • 3,771
  • 2
  • 37
  • 46
Icemanind
  • 47,519
  • 50
  • 171
  • 296
  • 2
    +1 Can't believe you didn't try Google first – Kieren Johnstone Feb 27 '12 at 20:29
  • @EdS.: Not sure if you read the comments on that or not but there are issues with it involving the enhanced security model of Vista/Win7. – NotMe Feb 27 '12 at 21:02
  • @ChrisLively: No wonder; in general it should be difficult to muck with my firewall without my express permission. As the question doesn't state that anything has yet been tried I think a link to a general method is appropriate. – Ed S. Feb 27 '12 at 21:07
  • 2
    @KierenJohnstone - Google brought me here, dammit `Stack Overflow Exception Occurred` – Piotr Kula May 14 '14 at 13:51

4 Answers4

8

It's nicer to use the Windows library C:\windows\system32\FirewallAPI.dll. This DLL is available since Windows 7. Visual Studio will automatically add a wrapper for this COM library if you add it to your project references or you can create the wrapper manually with tlbimp.exe.

using NetFwTypeLib;

INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
firewallRule.Description = "Your rule description";
firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN; // inbound
firewallRule.Enabled = true;
firewallRule.InterfaceTypes = "All";
firewallRule.RemoteAddresses = "1.2.3.0/24"; // add more blocks comma separated
firewallRule.Name = "You rule name";
firewallPolicy.Rules.Add(firewallRule);

VS IntelliSense should give you sufficient details on the lib.

needfulthing
  • 1,056
  • 11
  • 21
5

You can use this nuget package WindowsFirewallHelper

PM> Install-Package WindowsFirewallHelper

Example code add a new outbound rule for an application

var rule = FirewallManager.Instance.CreateApplicationRule(
    @"MyApp Rule",
    FirewallAction.Allow,
    @"C:\MyApp.exe"
);
rule.Direction = FirewallDirection.Outbound;
FirewallManager.Instance.Rules.Add(rule);
live2
  • 3,771
  • 2
  • 37
  • 46
  • 1
    do you also know by any chance how to activate or deactivate that rule with a click of a button? i dont find any method that does something like "enable rule, desable rule" – Hakunama Tatarov Jan 10 '21 at 12:48
  • Take a look at the code https://github.com/nager/Nager.FirewallManagement/blob/master/src/Nager.FirewallManagement/WebApi/FirewallController.cs – live2 Jan 10 '21 at 18:13
  • just fyi you need to add a FirewallManager.Instance.GetProfile().Type, between ( and @"MyApp Rule", otherwise it doesnt work – Hakunama Tatarov Jan 22 '21 at 11:04
4

You could wrap the netsh advfirewall command syntax into a small library to allow you to enable/disable settings on demand. Failing that, see http://msdn.microsoft.com/en-us/library/windows/desktop/ff956124(v=vs.85).aspx for the Windows Firewall with Advanced Security API.

Jamie Howarth
  • 3,273
  • 3
  • 20
  • 26
2

You could use "netsh" command. Make a method to call it.
Use this if you don't want to reference FirewallAPI.dll or install the nuget WindowsFirewallHelper.

Example:


        /// <summary>
        /// Creates a Firewall Rule on current computer. Uses 'netsh'
        /// </summary>
        /// <param name="rulename"></param>
        /// <param name="protocol"></param>
        /// <param name="port"></param>
        /// <param name="direction">"in" or "out"</param>
        /// <param name="action"></param>
        /// <returns>netsh command response</returns>
        public static string CreateFirewalPort(string rulename, string protocol, int port, string direction = "in", string action = "allow")
        {
            // https://support.microsoft.com/en-us/help/947709/how-to-use-the-netsh-advfirewall-firewall-context-instead-of-the-netsh

            //Remove any rule with the same name. Otherwise every time you run this code a new rule is added.  
            Process removeproc = new Process
            {
                StartInfo = {
                    FileName = "netsh",
                    Arguments = $@"advfirewall firewall delete rule name=""{rulename}""",
                    UseShellExecute = false,
                    WindowStyle = ProcessWindowStyle.Hidden,
                    RedirectStandardOutput = true
                }
            };
            try
            {
                removeproc.Start();
                var output = removeproc.StandardOutput.ReadToEnd();
                removeproc.WaitForExit();
            }
            catch (Exception ex)
            {
                Log.Info(ex.Message);
            }

            Process process = new Process
            {
                StartInfo = {
                    FileName = "netsh",
                    Arguments = $@"advfirewall firewall add rule name=""{rulename}"" protocol={protocol} localport={port} dir={direction} action={action}",
                    UseShellExecute = false,
                    WindowStyle = ProcessWindowStyle.Hidden,
                    RedirectStandardOutput = true
                }
            };

            try
            {
                process.Start();
                var output = process.StandardOutput.ReadToEnd();
                process.WaitForExit();
                return output;
            }
            catch (Exception ex)
            {
                return ex.ExceptionToString();
            }
        }
Rui Caramalho
  • 455
  • 8
  • 16