Automating Windows Firewall settings with C# (part 2)
Hi Vamsy here. I am an Operations Engineer in the Information Security Team. In my previous post, I have described automating Windows Firewall Settings with C#. As promised in the previous post, I will describe the tool I call Windows Firewall Checker in this blog.
The tools is written in C# and uses .NET Framework 3.5. It uses the COM object HnetCfg.FwMgr. A recent version of the api is also available as commented in my previous post. But we will be using the older api so that this application runs even on systems with older versions of Windows.
The purpose of this application is to check the status of Windows Firewall and enable it, in case it is disabled. This tool runs in the background and provides status messages as balloon tips in the notification area, the tool of course could be run by network administrators in a corporate network to make sure that all the users have their firewall enabled.
Let me first walk you through the functionality of the tool with the help of some screen shots and later will give you a dump of the code.
Note: The application needs to run under administrative privileges in order turn the firewall on.
When the application is launched ( either manually or using a scheduler) the tool first checks for the status of firewall and depending on the status displays the following message.
In case the firewall is turned on
In case the firewall is off, the following message is displayed
Then the tool tries to turn the firewall on and displays either of the following. In case the firewall is turned on then it says so
else due to some reason it is unable to turn on the firewall the following is displayed. This often happens due to not running this tool under administrative privileges.
After this application exits automatically. Let us now take a look at the code behind this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Text;
using System.Windows;
using System.Threading;
using System.Windows.Forms;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Interop;
using NetFwTypeLib;
namespace WpfApplication2
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>4
public partial class Window1 : Window
{
private System.Windows.Forms.NotifyIcon notifyIcon;
private System.Windows.Forms.ContextMenu contextMenu;
private System.Windows.Forms.MenuItem menuItem_Exit;
private System.ComponentModel.IContainer components;
private bool Firewallenabled = false;
public Window1()
{
InitializeComponent();
this.Visibility = Visibility.Hidden;
try
{
this.IntializeNotifyIcon();
if (this.CheckFirewall())
{
this.ShowNotifyIcon("Windows Firewall is enabled on your system ", true, 3000);
}
else
{
this.ShowNotifyIcon("Windows Firewall has been disabled on your system. The application will now try to enable it", false, 3000);
if (this.EnableFirewall())
{
this.ShowNotifyIcon("Windows Firewall has been successfully enabled on your system", true, 3000);
}
else
{
this.ShowNotifyIcon("The application failed to enable the Firewall on your system. Please contact the helpdesk", false, 3000);
}
}
Thread.Sleep(3000);
this.Close();
}
catch (FirewallCheckerException e)
{
this.ShowNotifyIcon(e.Message, false, 3000);
Thread.Sleep(3000);
this.Close();
}
}
// this function is used to intialize the notification icon in the taskbar
public void IntializeNotifyIcon()
{
try
{
this.components = new System.ComponentModel.Container();
this.contextMenu = new System.Windows.Forms.ContextMenu();
this.menuItem_Exit = new System.Windows.Forms.MenuItem();
// Initialize contextMenu for the notification icon
this.contextMenu.MenuItems.AddRange(
new System.Windows.Forms.MenuItem[] { this.menuItem_Exit });
// Initialize menuItem_Exit
this.menuItem_Exit.Index = 0;
this.menuItem_Exit.Text = "Exit";
this.menuItem_Exit.Click += new System.EventHandler(this.menuItem_Exit_Click);
this.notifyIcon = new System.Windows.Forms.NotifyIcon(this.components);
// The Icon property sets the icon that will appear
// in the systray for this application.
notifyIcon.Icon = SystemIcons.Shield;
// The ContextMenu property sets the menu that will
// appear when the systray icon is right clicked.
notifyIcon.ContextMenu = this.contextMenu;
// The Text property sets the text that will be displayed,
// in a tooltip, when the mouse hovers over the systray icon.
notifyIcon.Text = "Windows Firewall Checker";
notifyIcon.Visible = true;
this.ShowNotifyIcon("Checking the status of Windows Firewall on your System ", true, 3000);
Thread.Sleep(3000);
}
catch (Exception e)
{
throw new FirewallCheckerException("Unable to initialize the notification icon" + e.InnerException);
}
}
// checks the status of firewall and returns the status
private bool CheckFirewall()
{
try
{
Type NetFwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false);
INetFwMgr mgr = (INetFwMgr)Activator.CreateInstance(NetFwMgrType);
this.Firewallenabled = mgr.LocalPolicy.CurrentProfile.FirewallEnabled;
mgr = null;
NetFwMgrType = null;
return this.Firewallenabled;
}
catch (Exception e)
{
throw new FirewallCheckerException("Unable to check the firewall" + e.InnerException);
}
}
// enables the firewall and returns the status after enabling
private bool EnableFirewall()
{
try
{
Type NetFwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false);
INetFwMgr mgr = (INetFwMgr)Activator.CreateInstance(NetFwMgrType);
mgr.LocalPolicy.CurrentProfile.FirewallEnabled = true;
this.Firewallenabled = mgr.LocalPolicy.CurrentProfile.FirewallEnabled;
mgr = null;
NetFwMgrType = null;
return this.Firewallenabled;
}
catch (Exception e)
{
throw new FirewallCheckerException("Failed to enable the Firewall" + e.InnerException);
}
}
//this function is used to show the balloon tip message
//flag is a bool value, when 0 it indicates the use of INFO icon for tooltip else Error icon, message is the message to be displayed
private void ShowNotifyIcon(string message, bool flag, int time)
{
try
{
notifyIcon.BalloonTipTitle = "Windows Firewall Checker";
notifyIcon.BalloonTipText = message;
if (flag)
{
notifyIcon.BalloonTipIcon = ToolTipIcon.Info;
}
else
{
notifyIcon.BalloonTipIcon = ToolTipIcon.Error;
}
notifyIcon.ShowBalloonTip(time);
}
catch (Exception e)
{
throw new FirewallCheckerException("Unable to display the balloon tip" + e.InnerException);
}
}
//event handler to handle the click event on exit item in the context menu of the notify icon
private void menuItem_Exit_Click(object Sender, EventArgs e)
{
// Close the form, which closes the application.
this.Close();
}
}
}
I have created this tool as a WPF application so that going ahead this would also support a basic report that can be presented to the user.
The following is the code for the exception class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WpfApplication2
{
class FirewallCheckerException : Exception
{
public FirewallCheckerException()
: base()
{
}
public FirewallCheckerException(string message) :base(message)
{
}
}
}
This is a very very simple tool, but can be very helpful to make the systems more secure. This tool can be run at the startup of the machine or at scheduled intervals to check the status of firewall and enable it.