Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Allow/Block a Program

0.00/5 (No votes)
29 Nov 2012 1  
This is a quick way to allow or disallow a program through the firewall.

Introduction

This is a single method that allows/blocks an executable through the firewall. I wrote this method for one of my applications and decided to post here for everyone's good.

Background

The idea here is to use the NetFwTypeLib located in (C:\windows\system32\FirewallAPI.dll) to add a rule that allows/blocks the executable with the specified path from establishing a connection of any type.

Using the Code

First, the FirewallAPI.dll must be added to references and NetFwTypeLib to usings.

Then, you can use the following method:

/// <summary>
/// Adds or removes a firewall rule.
/// </summary>
/// <param name="path">The path to the executable.</param>
/// <param name="d">The affected connection type.</param>
/// <param name="fwaction">Rule action.</param>
/// <param name="action">"Add (1) or 
/// remove (0) the specified rule."</param>
private void FWRule(string path, NET_FW_RULE_DIRECTION_ d, 
		NET_FW_ACTION_ fwaction, string action)
{
    try
    {
        INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(
        Type.GetTypeFromProgID("HNetCfg.FWRule"));
        firewallRule.Action = fwaction;
        firewallRule.Enabled = true;
        firewallRule.InterfaceTypes = "All";
        firewallRule.ApplicationName = path;
        firewallRule.Name = "CSwitch: " + Path.GetFileName(path);
        INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance
        (Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
            firewallRule.Direction = d;
            if (action == "1") firewallPolicy.Rules.Add(firewallRule);
            else firewallPolicy.Rules.Remove(firewallRule.Name);
    }
    catch (Exception ex) { MessageBox.Show(ex.Message, "ERROR"); }}} }   

Example

FWRule(@"C:\test.exe", NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT, 
NET_FW_ACTION_.NET_FW_ACTION_BLOCK, "1"); 

This will block test.exe from making any outgoing connections.

Points of Interest

While writing this, I noticed that trying to use the same INetFwRule variable multiple times could throw a CATASTROPHIC FAILURE (Access Denied) exception.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here