Welcome to MSDN Blogs Sign in | Join | Help

Managed classes to view/manipulate the Windows Firewall

I have been needing a set of classes to give me access to the settings for the Windows Firewall.  I did a quick search and didn't find much that would help me in my quest to view or manipulate these settings, so I ended up writing my own managed wrapper classes for the underlying COM objects.  I thought I would post my code here so that others can take advantage of the work I did.  Note that at this point I have only done cursory testing, so I don't promise that it is bug free.  Please let me know if you see any errors/improvements that need to be addressed.  Note that towards the bottom I have included a simple Main function that shows some sample usage.

using System;
using System.Collections;
using System.Text;
using System.Globalization;
using System.Security.Permissions;
using System.Security.Principal;
using System.ComponentModel;
using System.Runtime.InteropServices;

namespace WindowsFirewallTools
{


 [ComImport, ComVisible(false), Guid("304CE942-6E39-40D8-943A-B913C40C9CD4")]
    public class NetFwMgr {

    }

    [ComImport, ComVisible(false), Guid("F7898AF5-CAC4-4632-A2EC-DA06E5111AF2"), System.Runtime.InteropServices.InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
    public interface INetFwMgr {
       
   INetFwPolicy LocalPolicy {get;}

   FirewallProfileType CurrentProfileType {get;}

   void RestoreDefaults();

         void IsPortAllowed(string imageFileName,
          IPVersion ipVersion,
          long portNumber,
          string localAddress,
          IPProtocol ipProtocol,
          [Out] out bool allowed,
          [Out] out bool restricted);

        void IsIcmpTypeAllowed(IPVersion ipVersion,
          string localAddress,
          byte type,
          [Out] out bool allowed,
          [Out] out bool restricted);
    }

 [ComImport, ComVisible(false), Guid("D46D2478-9AC9-4008-9DC7-5563CE5536CC"), System.Runtime.InteropServices.InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
 public interface INetFwPolicy
 {

   INetFwProfile CurrentProfile{get;}
         INetFwProfile GetProfileByType(FirewallProfileType profileType);
 }

 [ComImport, ComVisible(false), Guid("174A0DDA-E9F9-449D-993B-21AB667CA456"), System.Runtime.InteropServices.InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
 public interface INetFwProfile
 {

  
   FirewallProfileType Type {get;}
         bool FirewallEnabled {get;set;}
   bool ExceptionsNotAllowed {get;set;}
   bool NotificationsDisabled {get;set;}
   bool UnicastResponsesToMulticastBroadcastDisabled {get;set;}
   INetFwRemoteAdminSettings RemoteAdminSettings {get;}
         INetFwIcmpSettings IcmpSettings {get;}
   INetFwOpenPorts GloballyOpenPorts {get;}
   INetFwServices Services {get;}
   INetFwAuthorizedApplications AuthorizedApplications {get;}
       
      
 }

 [ComImport, ComVisible(false), Guid("D4BECDDF-6F73-4A83-B832-9C66874CD20E"), System.Runtime.InteropServices.InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
 public interface INetFwRemoteAdminSettings
 {
         IPVersion IpVersion {get;set;}
        
   Scope Scope{get;set;}
       
   string RemoteAddresses{get;set;}
       
   bool Enabled {get;set;}
 }

 [ComImport, ComVisible(false), Guid("A6207B2E-7CDD-426A-951E-5E1CBC5AFEAD"), System.Runtime.InteropServices.InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
 public interface INetFwIcmpSettings
 {
         bool AllowOutboundDestinationUnreachable{get;set;}
       
   bool AllowRedirect{get;set;}
       
   bool AllowInboundEchoRequest{get;set;}

   bool AllowOutboundTimeExceeded{get;set;}

   bool AllowOutboundParameterProblem{get;set;}
       
   bool AllowOutboundSourceQuench{get;set;}

   bool AllowInboundRouterRequest{get;set;}
  
   bool AllowInboundTimestampRequest{get;set;}
       
         bool AllowInboundMaskRequest{get;set;}

   bool AllowOutboundPacketTooBig{get;set;}
       
 }

 [ComImport, ComVisible(false), Guid("C0E9D7FA-E07E-430A-B19A-090CE82D92E2"), System.Runtime.InteropServices.InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
 public interface INetFwOpenPorts
 {
         long Count {get;}
       
   void Add(INetFwOpenPort port);

   void Remove(long portNumber, IPProtocol ipProtocol);
       
   INetFwOpenPort Item(long portNumber, IPProtocol ipProtocol);
       
   System.Collections.IEnumerator _NewEnum{get;}
 }

 [ComImport, ComVisible(false), Guid("E0483BA0-47FF-4D9C-A6D6-7741D0B195F7"), System.Runtime.InteropServices.InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
 public interface INetFwOpenPort
 {


  string Name{get;set;}
       
  IPVersion IpVersion{get;set;}
  
  IPProtocol Protocol{get;set;}

  long Port {get;set;}

  Scope Scope{get;set;}
  
  string RemoteAddresses{get;set;}
  
  bool Enabled{get;set;}
    
  bool BuiltIn {get;}
       
 }

 [ComImport, ComVisible(false), Guid("79649BB4-903E-421B-94C9-79848E79F6EE"), System.Runtime.InteropServices.InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
 public interface INetFwServices
 {
         long Count {get;}
       
   INetFwService Item(ServiceType svcType);
       
         System.Collections.IEnumerator _NewEnum{get;}

 }

 [ComImport, ComVisible(false), Guid("79FD57C8-908E-4A36-9888-D5B3F0A444CF"), System.Runtime.InteropServices.InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
 public interface INetFwService
 {
         string Name{get;}
       
   ServiceType Type{get;}

   bool Customized{get;}

   IPVersion IpVersion{get;set;}
  
   Scope Scope{get;set;}
  
   string RemoteAddresses{get;set;}

         bool Enabled{get;set;}
       
         INetFwOpenPorts GloballyOpenPorts {get;}

 }

 [ComImport, ComVisible(false), Guid("644EFD52-CCF9-486C-97A2-39F352570B30"), System.Runtime.InteropServices.InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
 public interface INetFwAuthorizedApplications
 {
         long Count {get;}
       
   void Add(INetFwAuthorizedApplication port);

   void Remove(string imageFileName);
       
   INetFwAuthorizedApplication Item(string imageFileName);
       
   System.Collections.IEnumerator _NewEnum{get;}
 }

 [ComImport, ComVisible(false), Guid("EC9846B3-2762-4A6B-A214-6ACB603462D2")]
    public class NetFwAuthorizedApplication {

    }

 [ComImport, ComVisible(false), Guid("B5E64FFA-C2C5-444E-A301-FB5E00018050"), System.Runtime.InteropServices.InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
 public interface INetFwAuthorizedApplication
 {
         string Name{get;set;}
       
   string ProcessImageFileName{get;set;}

   
   IPVersion IpVersion{get;set;}
  
   Scope Scope{get;set;}
  
   string RemoteAddresses{get;set;}

         bool Enabled{get;set;}
 }

    public enum FirewallProfileType
 {
  Domain = 0,
  Standard = 1,
  Current = 2,
  Max = 3
 }

    public enum IPVersion
 {
  IPv4 = 0,
  IPv6 = 1,
  IPAny = 2,
  IPMax = 3
 }
    public enum IPProtocol
 {
  Tcp= 6,
  Udp= 17
 }

 public enum Scope
 {
  All = 0,
  Subnet = 1,
  Custom = 2,
  Max = 3
 }

 public enum ServiceType
 {
  FileAndPrint = 0,
  UPnP = 1,
  RemoteDesktop = 2,
  None = 3,
  Max = 4
 
 }


#if COMPILE_MAIN 
 public class App {
  //a sample main application that shows the usage of these objects.
  public static void Main()
  {
   try {

    INetFwMgr mgr = (INetFwMgr)new NetFwMgr();

    Console.WriteLine("CurrentProfileType: " +mgr.CurrentProfileType);

    INetFwProfile profile = mgr.LocalPolicy.CurrentProfile;
    Console.WriteLine("FirewallEnabled: " + profile.FirewallEnabled);


    System.Collections.IEnumerator e = null;

    e = profile.AuthorizedApplications._NewEnum;


     

    Console.WriteLine("\r\n-----  Applications  -----  ");
    while (e.MoveNext()) {
     INetFwAuthorizedApplication app = e.Current as INetFwAuthorizedApplication;
     Console.WriteLine("\t{0}\r\n\t\tImageFilename={1}\r\n\t\tEnabled={2}\r\n\t\tIpVersion={3}\r\n\t\tScope={4}\r\n\t\tRemoteAddresses={5}",
           app.Name,
           app.ProcessImageFileName,
           app.Enabled,
           app.IpVersion,
           app.Scope,
           app.RemoteAddresses
          );
    }


    e = profile.Services._NewEnum;
    Console.WriteLine("\r\n-----  Services  -----  ");
    while (e.MoveNext()) {
     INetFwService service = e.Current as INetFwService;
     Console.WriteLine("\t{0}\r\n\t\tType={1}\r\n\t\tEnabled={2}\r\n\t\tIpVersion={3}"+
           "\r\n\t\tScope={4}\r\n\t\tcustomized={5}\r\n\t\tRemoteAddresses={6}",
           service.Name,
           service.Type,
           service.Enabled,
           service.IpVersion,
           service.Scope,
           service.Customized,
           service.RemoteAddresses
          );
    }

    e = profile.GloballyOpenPorts._NewEnum;
    Console.WriteLine("\r\n-----  Globally Open Ports  -----  ");
    while (e.MoveNext()) {
     INetFwOpenPort port = e.Current as INetFwOpenPort;
     Console.WriteLine("\t{0}\r\n\t\tIsBuiltIn={1}\r\n\t\tEnabled={2}\r\n\t\tIpVersion={3}"+
           "\r\n\t\tScope={4}\r\n\t\tProtocol={5}\r\n\t\tRemoteAddresses={6}",
           port.Name,
           port.BuiltIn,
           port.Enabled,
           port.IpVersion,
           port.Scope,
           port.Protocol,
           port.RemoteAddresses
          );
    }


   } catch (Exception ex) {
    Console.WriteLine(ex);
   }
  }
 }

#endif //COMPILE_MAIN
}

Published Tuesday, December 06, 2005 7:13 PM by joncole
Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

Friday, January 06, 2006 9:17 AM by bobk

# re: Managed classes to view/manipulate the Windows Firewall

Thanks! This is just what i need. But I think I may be missing something. I want to open the Firewall for a web server that will optionally be installed on a customer's computer. To do it manually, I would go into the Security Center, go to Firewall, Advanced, Settings, and check the Web Server (HTTP)box. I can't seem to find the equivalent in your code. Is there any material difference between checking this box and just opening port 80?
Monday, January 09, 2006 3:14 PM by bobk

# re: Managed classes to view/manipulate the Windows Firewall

Thanks for an excellent sample. I do have a question: I would like to enable web server on a customer computer, and I would do this manually by going into Security Center/Advanced/settings, and then clicking the "Web Server(HTTP)" box. Is there any material difference between this method and simply opening port 80 using your sample code?
Monday, January 09, 2006 5:38 PM by joncole

# re: Managed classes to view/manipulate the Windows Firewall

There is no guarantee that the web server is running on port 80. By checking the check box manually I would hope that the security center is smart enough to find out what port the WebServer is running on. If you do it manually, then you could be opening the wrong port…
Tuesday, January 10, 2006 8:38 AM by Karsten Burger

# re: Managed classes to view/manipulate the Windows Firewall

Thanks for this great article. The return from FirewallEnabled ist allways true. Where is the mistake?

Regards

Karsten
Tuesday, January 10, 2006 9:21 AM by bobk

# re: Managed classes to view/manipulate the Windows Firewall

Thanks. I don't see how to "check that box" in your code sample. Am I missing something? What about adding the service W3SVC?

I do appreciate your help.
Bob
Tuesday, January 10, 2006 6:46 PM by joncole

# re: Managed classes to view/manipulate the Windows Firewall

What I meant by checking the checkbox was in the Firewall management tool that Windows provides (the Graphical User Interace) and has nothing to do with the code I have provided.
Tuesday, January 10, 2006 7:11 PM by joncole

# re: Managed classes to view/manipulate the Windows Firewall

Karsten,

I looked into the FirewallEnabled always being true and my experimenting showed it to be correctly true/false as appropriate, so I don't think it is an issue with the code I have given above - the code is really just a simple wrapper around the underlying COM object so there isn't a lot that can go wrong on this side. It could be there is a bug in the underlying COM object that doesn't always manifest itself.
Tuesday, May 09, 2006 3:20 PM by jimbo

# re: Managed classes to view/manipulate the Windows Firewall

The FirewallEnabled only reflects local policy and not group policy settings.
Monday, June 05, 2006 2:24 AM by gloong

# re: Managed classes to view/manipulate the Windows Firewall

Hi Jon,

I am having some simiar problems on the firewall with my application.

The firewall port 80 is open and I can even ping. I am working on a handheld application with .NET compact framework.
I can even see the web service pages.
What troubling me is that, bu just sending a simple user ID and password to the remote server thru the firewall, it keeps telling me that unable to connect to the remote server.

If I were to do it without the firewall, it works fine. Just to note that I am not using the window firewall but external firewall.

Are there any special coding for this ?

Please help
Tuesday, June 13, 2006 5:12 PM by joncole

# re: Managed classes to view/manipulate the Windows Firewall

If you are using a 3rd party firewall, then I can only guess as to what would be the problem.  These are the things I would check on the firewall configuration:
1) Verify that the firewall is not blocking the port/protocol you are trying to connect to.
2) Verify that the firewall is allowing you to connect from the subnet you are on.  Some firewalls allow you control what IPAddresses or subnets clients can connect from.  I think that in the Windows Firewall, the options are "Any" or "Local Subnet".
3) See if your firewall application has any type of logging capabilities that you can take advantage of in helping you figure out what is going wrong.

Good luck.
Tuesday, August 07, 2007 5:26 AM by MMartin

# re: Managed classes to view/manipulate the Windows Firewall

Hi,

the IsPortAllowed function never changes one of its out parameters 'allowed' and 'restricted'.

Could it be that the prototype of IsPortAllowed without a return value isn't possible?

When I change the prototype of IsPortAllowed to return an integer value, this call always fails:

int ret = mgr.IsPortAllowed( "C:\\MyApp.exe", IPVersion.IPAny, 0, "", IPProtocol.Tcp, out  allowed, out  restricted );

It complains that the 'local address' is empty. When I try to give 'local address' a value it complains that the value is invalid...

Have you ever tried the IsPortAllowed function?

Kind regards,

MMartin

Leave a Comment

(required) 
required 
(required) 

  
Enter Code Here: Required
 
Page view tracker