Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically add an application to all profile Windows Firewall (Vista+)

I have searched around and there are similar questions on SO, however, no one talks about how to add exception to "All Profile" (windows 7, AKA "Any Profile" on Vista/Windows Server 2008). Examples on internet talk about add to current profile only.

The reason for this is I have a problem with one of my virtual machine: windows 2008 x86, current firewall profile is Domain, and my application is added to Exception list of Domain. (Firewall setting is as default: block any inbound calls that are not in exception list.) However, inbound calls are still blocked unless : 1. turn off firewall on that this virtual machine. 2. manually change rule profile of my application to "any"

It is very confusing as I thought only active profile should be "active" and should be functional, no matter other profiles are blocking my application inbound calls.

I am using XPSP2 INetFwMgr interface to add exceptions which is lacking of "any" profile support.

I am using c# but any language with example will be appreciated.

like image 842
Yuan Avatar asked Apr 12 '11 21:04

Yuan


1 Answers

You may try something like this:

using System;
using NetFwTypeLib;

namespace FirewallManager

{
  class Program
  {
    static void Main(string[] args)
    {
        INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
        firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
        firewallRule.Description = "Allow notepad";
        firewallRule.ApplicationName = @"C:\Windows\notepad.exe";
        firewallRule.Enabled = true;
        firewallRule.InterfaceTypes = "All";
        firewallRule.Name = "Notepad";

        INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(
            Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
        firewallPolicy.Rules.Add(firewallRule);

    }
  }
}

For sake of completeness, add reference to c:\Windows\System32\FirewallAPI.dll

like image 178
manojlds Avatar answered Oct 15 '22 02:10

manojlds