Click here to Skip to main content
Click here to Skip to main content

Windows XP SP2 Firewall Controller

By , 10 Jul 2006
 

Sample Image - WinXPSP2Firewall.jpg

Introduction

Windows XP SP2 basically has a small firewall. It's very easy to control, but sometimes it bothers you. When your application tries to connect to the internet, Windows shows a warning message-box, and this makes users feel your application is an Ad-Ware.

To prevent such things, I suggest you add your program to a Firewall Collection List. (This list contains the allowed programs.)

This wrapper class is very easy, simple, and useful. You don't need to see this 'Security Alert' message box any more:

Sample Image - Windows Firewall Security Alert Message Box

Implementation - C++

It's very easy. Just connect to the Windows XP Firewall as a COM, and do what you want.

FW_ERROR_CODE WinXPSP2FireWall::Initialize()
{
 HRESULT hr = S_FALSE;
 INetFwMgr* fwMgr = NULL;
 INetFwPolicy* fwPolicy = NULL;

 FW_ERROR_CODE ret = FW_NOERROR;
 try
 {
  if( m_pFireWallProfile )
   throw FW_ERR_INITIALIZED;
  /* Create an instance of the firewall settings manager. */
  hr = CoCreateInstance( __uuidof(NetFwMgr), NULL, 
         CLSCTX_INPROC_SERVER, __uuidof( INetFwMgr), (void**)&fwMgr );
  if( FAILED( hr ))
   throw FW_ERR_CREATE_SETTING_MANAGER;
  /* Retrieve the local firewall policy. */
  hr = fwMgr->get_LocalPolicy( &fwPolicy );
  if( FAILED( hr ))
   throw FW_ERR_LOCAL_POLICY;
  /* Retrieve the firewall profile currently in effect */

  hr = fwPolicy->get_CurrentProfile( &m_pFireWallProfile );
  if( FAILED( hr ))
   throw FW_ERR_PROFILE;
 }
 catch( FW_ERROR_CODE nError)
 {
  ret = nError;
 }
 if( fwPolicy )
  fwPolicy->Release();
 if( fwMgr )
  fwMgr->Release();
 return ret;
}

How to Use in C++

It's very easy to use. Just make an instance, and call Initialize(). Ensure that you call the Initialize() function after calling CoInitialize(). You can call Uninitialize() by yourself, but the destructor calls the function too. Also, you should know that you must let Uninitialize() be called before CoUninitialize() is called.

{
 WinXPSP2FireWall fw;
 fw.Initialize();
 wchar_t szApplication[MAX_PATH];
 GetCurrentDirectoryW( MAX_PATH, szApplication );

#ifdef _DEBUG

  wcscat(szApplication, L"file://Debug//WindowsFirewall.exe");
#else
 wcscat( szApplication, L"file://Release//WindowsFirewall.exe");
#endif

 fw.AddApplication( szApplication, L"FireWallTest");
 fw.RemoveApplication( szApplication );
 fw.AddPort( 4321, NET_FW_IP_PROTOCOL_TCP, L"FireWallPortTest" );
 fw.RemovePort( 4321, NET_FW_IP_PROTOCOL_TCP );
 fw.Uninitialize();
}

How to Use in C#

Usage in C# is very similar to that in C++. But it doesn't require APIs for COM interfaces, this makes it easier to implement this in C# than C++. Allocate an instance of the WinXPSP2FireWall, and call Initialize() first. And then use the methods you want. That's all! :)

Moah.WinXPSP2FireWall fw = new Moah.WinXPSP2FireWall();
fw.Initialize();

string strApplication = System.Environment.CurrentDirectory + 
                        "\\WindowsFirewall.exe";
fw.AddApplication(strApplication, "FireWallTest");
fw.RemoveApplication(strApplication);

fw.AddPort(4321, NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP, 
           "FireWallPortTest");
fw.RemovePort(4321, NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP);

Acknowledgment for C++

You need four files to compile this project: netfw.h, netfw.idl, icftypes.h, and icftypes.idl. You can get those files from the Windows XP SP2 PSDK. Or I have included the files in the downloads. You can just use them, instead of downloading and installing the SDK.

Acknowledgment for C#

If you have errors with NetFwTypeLib, add a reference to hnetcfg.dll. You can do that through "Project -> Add Reference... -> Browse" in Visual Studio, and the DLL file is usually located in "C:\Windows\System32\hnetcfg.dll".

History

  • 6, Jul. 2005
    • First release.
  • 10, Jul. 2006
    • Added a C# version of the Windows XP SP2 Firewall Controller.

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

About the Author

moah
Web Developer
Korea (Republic Of) Korea (Republic Of)
Member
Youngjin Kim lives in South Korea. I'm interested in every part of Computer Science, cause it has not been long time since graduate a University.
But now I'm working and researching on Pattern Recognition. Using that trying to recognize a Handwriting Prints. Korean and Chinese are my interesting Research Part.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionLicensememberMember 896106528 May '12 - 23:27 
The article does not include any specified license, so, can you tell what license should apply?
Is it The Code Project Open License (CPOL)?
 
Thanks
Cornelia
Questionhow to run this source codememberMember 39583126 Sep '08 - 23:24 
i am sorry may be this question would be so stupid for you people but i am running this source code for the first time ever and i dont know where to copy WinXPSP2FireWall.cpp ,WinXPSP2FireWall.cs and WinXPSP2FireWall.h and how to run this project is there any tutorial for running this source code
thanx looking for your favor
QuestionHow to add Windws Service Exception???membererickbp212 Sep '08 - 9:20 
Hi
 
Good article.
 
I have a question.
 
How can I get an instance of a class that implement the interface INetFwService ?
 
I use XP SP2
 
You wrote this for an application exception. I could do the same for a service but I need the GUID
 

Type typeFwService = Type.GetTypeFromCLSID(new Guid("{}"));
 
INetFwService FWService = (INetFwService)Activator.CreateInstance(typeFwService);
 
Thanks in advanced,
 
Erick
Generalbug under Vistamembernoelhx27 Mar '07 - 18:55 
If the Windows Firewall service in Vista is not running, an exception will occur at
 
WinXPSP2Firewall.cs:
 
public FW_ERROR_CODE Initialize()
...
...
fwMgr = (INetFwMgr)Activator.CreateInstance(typFwMgr);
...
...
 
Should you just wrap in a try/catch block?
 
Thanks!
 
Noël Henderson

QuestionXP firewall gets automatically DISABLED when using this??memberOrion Richardson228 Dec '06 - 4:28 
Great code example!
 
I've been trying to use this code in a program to register two ports with the firewall. I've been getting some weird behavior, though, where the firewall gets automatically DISABLED when I use these classes. It happens on install and the user then has to go back and manually re-enable the firewall. Is that expected behavior? Has anybody else seen it?
 
I definitely don't want our product to be labeled spyware, so I'm concerned about this.
 
Thanks for any help people can provide!

AnswerRe: XP firewall gets automatically DISABLED when using this??membermoah28 Dec '06 - 6:02 
Hi Orion.
 
Unfortunately, I have not experienced such unexpected behavior.
Now I have tested several cases and it works well.
 
Can you share your test case with us?
AnswerRe: XP firewall gets automatically DISABLED when using this??memberOrion Richardson27 Feb '07 - 8:49 
Hi moah,
 
You are correct - this was not the source of my problems and apologies for my guessing that it was. Your code has worked wonderfully.
 
For future reference, the issue arose when we created a listening socket during our main form's Shown() function. We also have our application start at Windows startup (configurable by the user) and it seems like if you do this the socket starts listening before the Windows firewall starts running (or the exceptions list gets loaded?), so you get a complaint from Windows. We solved this problem by queuing a worker thread that in turn started the socket listening.
 
Thanks again for the great code examples! I love code project. Smile | :) Can't wait to share some of my snippets on here in the near future.
 

GeneralRe: XP firewall gets automatically DISABLED when using this??memberchinnu_113 Feb '07 - 23:19 
I am facing some issues in using the XP Firewall API's..in my machine the firewall page is disabled,so the API's are working.But it is not able to change the status of FW..Is there any known issue or resolution for the same?
GeneralRe: XP firewall gets automatically DISABLED when using this??memberel delo15 May '07 - 12:52 
Just a thought, but I believe the MS Firewall can also be controlled (or at least it's state interrogatged) by/according-to Group Policy.
 
Assuming that's the case, then even a Local Admin might not be able to muck with the Firewall if the Group Policies preclude it.
 
As I said, I don't know this as fact and am not asserting it to be true, just proposing the thought as one scenario/hypothesis.
 
I know that at a certain very large SW company the net nannies would detect the FW being off or having certain ports/exceptions opened (and a laundry list of other settings etc), then generated nag-ware and nag-mail based on that. At some point they'd also simply boot ones' machine off the network.
 
BTW, very nice work!!!
 
- Lance
QuestionDoes this work on Vista?memberthomastom19 Sep '06 - 11:00 
THX

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 10 Jul 2006
Article Copyright 2005 by moah
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid