Windows Firewall and C#

June 19, 2008

This is great for any type of application that requires access to a network. I wrote this WindowsFirewall class that dumps out configuration settings for the Windows Firewall of a local machine. Currently, in this example it just spits it to the console, however, you can dump it to a text file easily. I found a similar example here using VB.NET. Also, Shafqat Ahmed’s .NET Blog had some other examples!

To begin, you will need to add a reference in your project to the COM assembly hnetcfg.dll which can be found at C:\Windows\System32\hnetcfg.dll

using System;
using NATUPNPLib;
using NETCONLib;
using NetFwTypeLib;

namespace ListOfProcesses
{
	/// <summary>
	/// A class that contains methods to display the current information
	/// about the local computers Windows Firewall.
	/// </summary>
	public class WindowsFirewall
	{
		#region Constants

		private const string CLSID_FIREWALL_MANAGER = "{304CE942-6E39-40D8-943A-B913C40C9CD4}";
		private const NET_FW_PROFILE_TYPE_ NET_FW_PROFILE_DOMAIN = NET_FW_PROFILE_TYPE_.NET_FW_PROFILE_DOMAIN;
		private const string LINE_HEADER = "--------------------------------------------------------------------------------";
		private const string SHORT_LINE_HEADER = "-----------------";

		#endregion
		
		#region Constructor

		public WindowsFirewall()
		{

		}

		#endregion

		#region Public Methods

		/// <summary>
		/// Displays a comprehensive list of information regarding the Windows Firewall
		/// </summary>
		public void DisplayFirewallInformation()
		{
			INetFwMgr manager = GetFirewallManager();
			
			this.DisplayFirewallProfile(manager);
		}

		#endregion

		#region Private Methods

		/// <summary>
		/// Returns a firewall manager object
		/// </summary>
		/// <returns>INetFwMgr interface</returns>
		private static INetFwMgr GetFirewallManager()
		{
			Type objectType = Type.GetTypeFromCLSID(new Guid(CLSID_FIREWALL_MANAGER));
			
			return Activator.CreateInstance(objectType) as NetFwTypeLib.INetFwMgr;
		}
	
		/// <summary>
		/// Writes out various firewall configurations for the local firewall policy.
		/// </summary>
		/// <param name="manager">INetFwMgr object</param>
		private void DisplayFirewallProfile(INetFwMgr manager)
		{
			         
			INetFwProfile profile = manager.LocalPolicy.CurrentProfile;

			/*
			 * 
			 * Profile Information
			 *    
			 */

			Console.Write(WindowsFirewall.LINE_HEADER);
			Console.WriteLine("Windows Firewall Report\n");
			Console.WriteLine("\n\n{0}\n{1}", "Profile", WindowsFirewall.SHORT_LINE_HEADER);
			Console.WriteLine("Firewall Policy Type: {0}", this.GetPolicyType(profile));
			Console.WriteLine("Exceptions Not Allowed: {0}", profile.ExceptionsNotAllowed);
			Console.WriteLine("Notifications Disabled: {0}", profile.NotificationsDisabled);
			Console.WriteLine("Remote Administration Enabled: {0}", profile.RemoteAdminSettings.Enabled);

			/*
			 *    
			 * ICMP Settings
			 * 
			 */

			Console.WriteLine("\n\n{0}\n{1}", "ICMP Settings", WindowsFirewall.SHORT_LINE_HEADER);
			Console.WriteLine("Allow Inbound Echo Request: {0}", profile.IcmpSettings.AllowInboundEchoRequest);
			Console.WriteLine("Allow Inbound Mask Request: {0}", profile.IcmpSettings.AllowInboundMaskRequest);
			Console.WriteLine("Allow Inbound Router Request: {0}", profile.IcmpSettings.AllowInboundRouterRequest);
			Console.WriteLine("Allow Inbound TimeStamp Request: {0}", profile.IcmpSettings.AllowInboundTimestampRequest);
			Console.WriteLine("Allow Outbound Destination Unreachable: {0}", profile.IcmpSettings.AllowOutboundDestinationUnreachable);
			Console.WriteLine("Allow Outbound Packet Too Big: {0}", profile.IcmpSettings.AllowOutboundPacketTooBig);
			Console.WriteLine("Allow Outbout Parameter Problem: {0}", profile.IcmpSettings.AllowOutboundParameterProblem);
			Console.WriteLine("Allow Outbound Source Quench: {0}", profile.IcmpSettings.AllowOutboundSourceQuench);
			Console.WriteLine("Allow Outbound Time Exceeded: {0}", profile.IcmpSettings.AllowOutboundTimeExceeded);
			Console.WriteLine("Allow Redirect: {0}", profile.IcmpSettings.AllowRedirect);

			/*
			 *    
			 * Port Information
			 * 
			 */

			Console.WriteLine("\n\n{0}\n{1}", "Port Information", WindowsFirewall.SHORT_LINE_HEADER);
			Console.WriteLine("Globally Opened Ports: {0}", profile.GloballyOpenPorts.Count);

			// Display detailed port information.
			foreach (INetFwOpenPort port in profile.GloballyOpenPorts)
			{
				Console.WriteLine("\n\nPort Name: {0}", port.Name);
				Console.WriteLine("{0, 20}{1}", "Port Number: ", port.Port);
				Console.WriteLine("{0, 20}{1}", "Port Protocol: ", this.GetPortType(port));
				Console.WriteLine("{0, 20}{1}", "Port IP Version: ", this.GetIPVersion(port));
				Console.WriteLine("{0, 20}{1}", "Port Enabled: ", port.Enabled);
				Console.WriteLine("{0, 20}{1}", "Remote Addresses: ", port.RemoteAddresses);
			}

			/*
			 *    
			 * Service Information
			 * 
			 */
			
			Console.WriteLine("\n\n{0}\n{1}", "Services Information", WindowsFirewall.SHORT_LINE_HEADER);
			Console.WriteLine("# of Services: {0}", profile.Services.Count);

			// Display detailed service information.
			foreach (INetFwService service in profile.Services)
			{
				Console.WriteLine("\n\nService Name: {0}", service.Name);
				Console.WriteLine("{0, 20}{1}", "Enabled: ", service.Enabled);
				Console.WriteLine("{0, 20}{1}", "Scope: ", this.GetServiceScope(service));
				
				// Obtain all the port information the service is utilizing.
				foreach (INetFwOpenPort port in service.GloballyOpenPorts)
				{
					Console.WriteLine("{0, 20}{1}", "Port Number: ", port.Port);
					Console.WriteLine("{0, 20}{1}", "Port Protocol: ", this.GetPortType(port));
					Console.WriteLine("{0, 20}{1}", "Port IP Version: ", this.GetIPVersion(port));
					Console.WriteLine("{0, 20}{1}", "Port Enabled: ", port.Enabled);
					Console.WriteLine("{0, 20}{1}", "Remote Addresses: ", port.RemoteAddresses);
				}
			}

			/*
			 *    
			 * Authorized Applications
			 * 
			 */

			Console.WriteLine("\n\n{0}\n{1}", "Authorized Applications", WindowsFirewall.SHORT_LINE_HEADER);
			Console.WriteLine("# of Authorized Applications: {0}", profile.AuthorizedApplications.Count);

			// Display detailed authorized application information.
			foreach (INetFwAuthorizedApplication application in profile.AuthorizedApplications)
			{
				Console.WriteLine("\n\nApplication Name: {0}", application.Name);
				Console.WriteLine("{0, 20}{1}", "Enabled: ", application.Enabled);
				Console.WriteLine("{0, 20}{1}", "Remote Addresses: ", application.RemoteAddresses);
				Console.WriteLine("{0, 20}{1}", "File Path: ", application.ProcessImageFileName);
			}

		}

		/// <summary>
		/// Returns a friendly string format of the policy type.
		/// </summary>
		/// <param name="profile">INetFwProfile object</param>
		/// <returns>string</returns>
		private string GetPolicyType(INetFwProfile profile)
		{
			string policyType = string.Empty;
			
			// Displays what type of policy the Windows Firewall is controlled by.
			switch (profile.Type)
			{				
				case NET_FW_PROFILE_TYPE_.NET_FW_PROFILE_DOMAIN:
					policyType = "Domain";
					break;
			
				case NET_FW_PROFILE_TYPE_.NET_FW_PROFILE_STANDARD:
					policyType = "Standard";
					break;

				case NET_FW_PROFILE_TYPE_.NET_FW_PROFILE_CURRENT:
					policyType = "Current";
					break;

				case NET_FW_PROFILE_TYPE_.NET_FW_PROFILE_TYPE_MAX:
					policyType = "Max";
					break;

			}

			return policyType;
		}
		
		/// <summary>
		/// Returns a friendly string format of the type of protocol.
		/// </summary>
		/// <param name="port">INetFwOpenPort port object</param>
		/// <returns>string</returns>
		private string GetPortType(INetFwOpenPort port)
		{
			string protocolType =  string.Empty;
			
			switch (port.Protocol)
			{
				case NetFwTypeLib.NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP:
					protocolType = "TCP";
					break;

				case NetFwTypeLib.NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP:
					protocolType = "UDP";

					break;
			}

			return protocolType;
		}

		/// <summary>
		/// Returns a friendly string format of the IP version.
		/// </summary>
		/// <param name="port">INetFwOpenPort port object</param>
		/// <returns>string</returns>
		private string GetIPVersion(INetFwOpenPort port)
		{
			string ipVersion = string.Empty;

			switch (port.IpVersion)
			{
				case NetFwTypeLib.NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY:
					ipVersion = "Any";
					break;

				case NetFwTypeLib.NET_FW_IP_VERSION_.NET_FW_IP_VERSION_MAX:
					ipVersion = "Max";
					break;

				case NetFwTypeLib.NET_FW_IP_VERSION_.NET_FW_IP_VERSION_V4:
					ipVersion = "IPV4";
					break;

				case NetFwTypeLib.NET_FW_IP_VERSION_.NET_FW_IP_VERSION_V6:
					ipVersion = "IPV6";
					break;
			}

			return ipVersion;
		}

		/// <summary>
		/// Returns a friendly string format of the service scope.
		/// </summary>
		/// <param name="service">INetFwService object</param>
		/// <returns>string</returns>
		private string GetServiceScope(INetFwService service)
		{
			string serviceScope = string.Empty;

			switch (service.Scope)
			{
				case NetFwTypeLib.NET_FW_SCOPE_.NET_FW_SCOPE_ALL:
					serviceScope = "All";
					break;

				case NetFwTypeLib.NET_FW_SCOPE_.NET_FW_SCOPE_CUSTOM:
					serviceScope = "Custom";
					break;

				case NetFwTypeLib.NET_FW_SCOPE_.NET_FW_SCOPE_LOCAL_SUBNET:
					serviceScope = "Local Subnet";
					break;

				case NetFwTypeLib.NET_FW_SCOPE_.NET_FW_SCOPE_MAX:
					serviceScope = "Max";
					break;
			}

			return serviceScope;
		}

		#endregion
	}
}
Advertisements