Web 2.0 Bubble
WeakReference: GC knows the Best

Controlling Windows Firewall using C# via COM Interop

Firewall Windows firewall is the built in firewall that ships with Windows XP and Windows Vista. This firewall can be controlled from any .NET language via COM interop. The windows firewall UI is a little clumsy to work with so anyone can make his own frontend using any .NET based language.

Setting up

Start by adding a reference to the COM dll that provides the functionality to control the windows firewall. The filename is hnetcfg.dll which can be found at the system32 folder inside windows. So add the file to your C# project.

File location: \Windows\System32\hnetcfg.dll
Then add these using statements to import the COM Objects

using NATUPNPLib;
using NETCONLib;
using NetFwTypeLib;

Obtaining a reference to the firewall manager

The first step toward controlling the windows firewall is to obtain a reference to the firewall manager class. For this we will use the CLSID of the class which is

   {304CE942-6E39-40D8-943A-B913C40C9CD4}

So our code looks like this

private const string CLSID_FIREWALL_MANAGER = 
      "{304CE942-6E39-40D8-943A-B913C40C9CD4}";
private static NetFwTypeLib.INetFwMgr GetFirewallManager()
{
    Type objectType = Type.GetTypeFromCLSID(
          new Guid(CLSID_FIREWALL_MANAGER));
    return Activator.CreateInstance(objectType)
          as NetFwTypeLib.INetFwMgr;
}

The above code shows how to get a reference to the firewall manager

Check if the firewall is turned on

If the firewall is not turned we should look into the current profile and find out then turn it on.

INetFwMgr manager = GetFirewallManager();
bool isFirewallEnabled =
    manager.LocalPolicy.CurrentProfile.FirewallEnabled;
if (isFirewallEnabled==false)
    manager.LocalPolicy.CurrentProfile.FirewallEnabled=true;

Give full trust to your executable

If we want to authorize some application with full trust then we need to create a FirewallAuthorizedApplication (INetFwAuthorizedApplication) object and add it to the authorized application list.

// ProgID for the AuthorizedApplication object
private const string PROGID_AUTHORIZED_APPLICATION =
    "HNetCfg.FwAuthorizedApplication";

public bool AuthorizeApplication(string title, string applicationPath,
    NET_FW_SCOPE_ scope, NET_FW_IP_VERSION_ ipVersion )
{   
  // Create the type from prog id
  Type type = Type.GetTypeFromProgID(PROGID_AUTHORIZED_APPLICATION);
  INetFwAuthorizedApplication auth = Activator.CreateInstance(type)
      as INetFwAuthorizedApplication;
  auth.Name  = title;
  auth.ProcessImageFileName = applicationPath;
  auth.Scope = scope;
  auth.IpVersion = ipVersion;
  auth.Enabled = true;

  INetFwMgr manager = GetFirewallManager();
  try
  {
    manager.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(auth);
  }
  catch (Exception ex)
  {
    return false;
  }
  return true;
}

The above code is for a function that adds an authorized application. Let see the use by authorizing notepad full internet access!

AuthorizeApplication ("Notepad", @"C:\Windows\Notepad.exe", 
                NET_FW_SCOPE_.NET_FW_SCOPE_ALL,
                NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY)

Walla! Now notepad has internet access.

Opening a Port Globally

Sometimes we may want to open a port for any application no matter what. Windows Firewall can be instructed to open a port globally for all applications by adding a port to the globally open ports list. Let try to write a function that opens up a port globally ...

private const string PROGID_OPEN_PORT = "HNetCfg.FWOpenPort";
public bool GloballyOpenPort(string title, int portNo,
    NET_FW_SCOPE_ scope, NET_FW_IP_PROTOCOL_ protocol,
    NET_FW_IP_VERSION_ ipVersion)
{
  Type type = Type.GetTypeFromProgID(PROGID_OPEN_PORT);
  INetFwOpenPort port = Activator.CreateInstance(type)
      as INetFwOpenPort;
  port.Name = title;
  port.Port = portNo;
  port.Scope = scope;
  port.Protocol = protocol;
  port.IpVersion = ipVersion;

  INetFwMgr manager = GetFirewallManagerCached();
  try
  {
    manager.LocalPolicy.CurrentProfile.GloballyOpenPorts.Add(port);
  }
  catch (Exception ex)
  {
    return false;
  }
  return true }

Going further

Since we have demonstrated how to access the windows firewall manager and control its various aspects, now anyone can explore the Windows Fireall API and do a lot more that presented in this post. I would like to point to several MSDN references for further read.

MSDN Windows Firewall Reference
Loads of VBScript samples to do various things, you can translate the code to C#

Since windows firewall can be controlled via COM, any application running in your system can enable/disable or modify the firewall settings. I would suggest to use a third party firewall. For real security geek I would recommend Outpost Firewall ( I use the Outpost Security Suite) as the paid firewall and Comodo Personal Firewall as the best free firewall. Both these firewalls are way superior to other available firewalls.

kick it on DotNetKicks.com

Comments

jasintha dasanayaka

i am student of uva wellassa univrsity i am following software eng degree i am doing project to make firewall your note is important to me thank you

Khushboo Chirmade

This code doesn't not work for windows vista

Shafqat Ahmed

I am sorry to hear that. I have tested this code on WindowsXP to run smoothly. I do not have Vista and do not plan to upgrade because I despise that OS. However I might have some clues for you.

In Vista the your program do not run as the admin by default, you might want to check if that is the reason. Also Vista comes with the advanced version of the Windows Firewall ( See MSDN), so the COM CLSID for the classes may be different in Vista. Check out the dll in Windows\System32\hnetcfg.dll and find the appropriate CLSID reference.

Junaid

Dear Shafqat.i really enjoyed reading your this code. i really need help regarding firewall. i just want to give interface to the firewall. so far i just can ON and OFF fire wall by your this code. could you help me that how i can enabled the traffic in HTTP, Telnet etc and how i can off and on these protocols

kindly help me regarding this..

e.hafez

I want to built Port Knocking with c#
Please tell me how can I do>
hafez

Phillip

Just to let you (and others) know that the NetFwTypeLib object doesn't reside in hnetcfg.dll library on Vista (I'm using Vista Business). Rather, it resides in FirewallAPI.dll at %system32%\FirewallAPI.dll (eg c:\windows\system32\FirewallAPI.dll). Once this (and hnetcfg.dll have wbeen added, the project runs fine on Vista. The COM CLSID is the same.

Thanks for the script by the way, excellent reference

Jon

Hi.

First off, thanks for the script. It seems like it should work. However, for me it is not. I am not sure if you can help me or not.

When I call the

manager.LocalPolicy.CurrentProfile.FirewallEnabled;

method, I get an exception:

"There are no more endpoints available from the endpoint mapper. (Exception from HRESULT: 0x800706D9)"

Any ideas? Thanks.

Nick

I'm getting the same error as Jon when this method is run and the Firewall service is current not running. I too am at a loss as to how to resolve this.

Marc

Hi,

Great Post. I found it very useful but i don't think it is what i need. I have another question and it regarding when developing a server / client application.

I am wondering what would be the best solution to provide the user with the easiest method to add the port to their allowed ports for the client / server application to allow traffic / messages between each other.

I know the code above would help if they were simply running Windows Firewall. However if they were running a third party firewall solution. Is there a way to detect which firewall application is being used and either prompt the user to add the port required to the allowed traffic.

I hope the above makes sense to what i want to achieve.

I would simply like to make configuring the client / server application easier if a firewall application is running

Kind Regards
Marc

Kamran

Hi,
Can we all this information from windows registry?
can you let me know what will be missing if we use registry.

Regards
Kamran

Michael

My understanding of COM interop is limited. I thought an app will fail to run if an external DLL you reference does not exist. Will adding references to these DLL's

%system32%\hnetcfg.dll
%system32%\FirewallAPI.dll

cause my program to fail on older OS's that lack these DLL's, such as Windows XP SP1 or Windows 2000 (or even XP SP2 in the case of FirewallAPI.dll)?

Thanks,

Roma

Rid of those pesky bugs you pick when surfing the net.
One of the first things that I learned when I got my new computer was that if you own a PC then you better have a good antispyware scanner to help get rid of those pesky bugs you pick when surfing the net. Otherwise, your computer won’t keep running like new for very long. It will begin to slow down and eventually get so sluggish you won’t even be able to use it. I tried a variety of different scans before I ran across Search-and-destroy Antispyware at http://www.Search-and-destroy.com. So far I have been very happy with the antispyware solution from Search-and-destroy and very glad that I gave it a try.

Adrian

This is great, thanks for the article. I'd be really interested to find out if there is a way to programatically intercept firewall logging events - e.g. listen for successful connections and report the IP address of the remote site.

Thanks for any help.

JC

Hello Shafqat!
I've tried this and it's working perfectly! Tks!

Is there a way to Enable/Disable a Firewall on a remote computer?

I'm developing an app that finds all computers in a network, then discovers all devices in each computer. And the same error cames to me "The RPC Server is unavailable", it's the firewall that's blocking my app.

Can you help me?

JC

Simon Tasker

Hello Shafqat,

Ive been going through all of your above code and have found it very helpful for my current project, which is for the college I work for.
Thhe current Project in question is Called
Class room manager V6

I am actually taking over the project from a previous programmer who has now left the college, I'm writing the entire program in c# where as before it was spread over many languages and strung together using various 3rd party applications to cover area's missed.
The aim of the System is to give tutors here extra control over classes with disruptive students or students with the knowledge to break the current Classroom Manager which prohibits students from accessing websites or other web related content if the tutor deems it fit.

It may be a bit of a stretch to ask this but I have a couple of questions I would like to ask you. Is there any way you could email me back it would be much appreciated.

Ken

Jon and Nick,

Don't know if you are still having the same error:

"There are no more endpoints available from the endpoint mapper. (Exception from HRESULT: 0x800706D9)"

I found that if I turn off the Windows Firewall, but leave the service running, this error goes away. This is on an Win2008 R2 server.

Good luck.

Tim

Hi! Great post!
Question - is there a way to do this without using the COM object (i.e., a completely COM-free solution)?
Thanks!

DJ Williams

INetFwMgr manager = GetFirewallManagerCached();

Is there a function a missing in your code or is there another Library I need referenced for the "GetFirewallManagerCached()"

Thanks

Sach

Thanks a lot.

It works fine. However, I am encountering a problem that needs to be solved. That is, the "NetFwTypeLib" object resides in hnetcfg.dll in XP while it is inside the FirewallAPI.dll in Vista.

Since I need my application be authorized irrespective of the OS, how am I to tackle that problem? I cannot use both the .dlls can I? And it is a must that one code should be able to do this.

Alex

Hi Shafqat,
I just tried this under VS 2010 under Windows 7 64 bit, but am getting reference resolution errors in NATUPNPLib. Works great under VS 2008. Any trick you know to make it work under VS 2010?

shafqat Ahmed

I don't have 2010 installed. Will update the post if I install it.

Dave Evans

Shafqat,

Thank you VERY much!

FYI Alex; thats a bug in VS 2010. The COM UPnP only works correctly with 2008 or lower. So, compile your UPnP assembly in 2008 and call it from 2010.

pri

is this method missing in code.
INetFwMgr manager = GetFirewallManagerCached();

dileep


Hi Shafqat,
Thanks for the nice article, The above code works fine for me, but I am facing one issue, while testing the code. If I pass the port number as the one which is already in use, since there is no checks available before adding to GloballyOpenPorts.Add(port), how Add method will behave, since it is meaningless to have two ports with the same number, will it throw some exception or as a developer we need to take care of this while adding the port, why because the user who is entering the port number to create new port, he might not have the knowledge on the existing ports which are already open.
For Example:
There is an Existing port with the properities as
port.Name = "Test";
port.Port = 3010
port.Protocol = "TCP";
And as a user If I enter the same as follows
port.Name = "Test1";
port.Port = 3010
port.Protocol = "TCP";

Then finally if I see the open ports through "firewall.cpl", it is showing as follows
port.Name = "Test1";
port.Port = 3010
port.Protocol = "TCP";

Can you suggest me how this Add is implemented in this situation, is it like taking the port number as primary key and replacing the existing data with new attributes instead of adding the new port with the same number. Can you please suggest me on this?

mad_dog

This works fine for checking the status of my firewall, but if I try to enable/disabled the firewall, the "manager.LocalPolicy.CurrentProfile.FirewallEnabled = false;" (or = true) throws a methodNotImplemented exception
"The Method or Operation is not implemented"

StackTrace:
"at NetFwTypeLib.INetFwProfile.set_FirewallEnabled(Boolean Enabled) at sysTray_Click(Object sender, EventArgs e)"

At the same time, a Windows Security Alert pops up and says "A program or firewall is not compatible with this version of Windows" and references my executable.

I am running Windows 7 Home Pro 32-bit and using the Windows Firewall.
Any ideas?

The comments to this entry are closed.