0
votes

I am trying to add application in firewall. It is working fine but it only checks "Public" option. I want to add firewall rule for "Domain".

Here is my code.

private const string ClsidFirewallManager = "{304CE942-6E39-40D8-943A-B913C40C9CD4}";

private INetFwMgr _firewallManager;
private INetFwMgr FirewallMgr
{
    get { return _firewallManager ?? (_firewallManager = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid(ClsidFirewallManager)))); }
}

private INetFwPolicy FirewallPolicy
{
    get { return FirewallMgr.LocalPolicy; }
}

private INetFwProfile _firewallProfile;
private INetFwProfile FirewallProfile
{
    get { return _firewallProfile ?? (_firewallProfile = FirewallPolicy.CurrentProfile); }
}


public void AddApplication(string imageFileName, string registerName)
{
    if (!IsAppEnabled(imageFileName))
    {
        var firewallApplicatoins = FirewallProfile.AuthorizedApplications;
        var type = Type.GetTypeFromProgID("HNetCfg.FwAuthorizedApplication");
        var firewallApplication = Activator.CreateInstance(type) as INetFwAuthorizedApplication;

            firewallApplication.ProcessImageFileName = imageFileName;
            firewallApplication.Name = registerName;
            firewallApplication.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_LOCAL_SUBNET; ---> Here it adds to public, whatever the value for enum is.
            firewallApplication.Enabled = true;

            firewallApplicatoins.Add(firewallApplication);
    }
}

I have followed this link.

http://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/10c6ff4b-701b-4351-a3d8-a716d8831a66/add-c-application-to-firewall-exception-list-of-windows-7?forum=windowssecurity&prof=required

Now here in whatever I assign value to Scope, firewall rule is added for public network only. I want to add it for Domain network.

firewallApplication.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_LOCAL_SUBNET;

What I am doing wrong here. I am using Windows 8.

1

1 Answers

0
votes

I got the problem. My existing code works only on Windows XP. For Vista or higher it was not working fine. For Vista I need to work with next version of firewall.

Here is the code.

var firewallRule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));

firewallRule.Name = registerName;
firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
firewallRule.Enabled = true;
firewallRule.InterfaceTypes = "All";

var rules = VistaFirewallPolicy.Rules;
rules.Add(firewallRule);

This code will add firewall rule to domain, private and public.