Windows Firewall API Reference

The Windows Firewall API provides programmatic access to configure and manage the built‑in Windows Defender Firewall. It is part of the NetFw COM library and can be used from C++, C#, PowerShell, or any language that can interoperate with COM.

Overview

This API enables you to:

  • Add, remove, or modify inbound and outbound firewall rules.
  • Query the current firewall profile state (Domain, Private, Public).
  • Enable or disable the firewall globally or per‑profile.
  • Configure advanced settings such as logging, notifications, and default action.

The primary COM interface is INetFwPolicy2, which provides access to the firewall policy across all profiles.

Getting Started

To use the API, reference the FirewallAPI.dll (COM library {E2B3C97F-6AE1-41ac-817A-F6F92166D7DD}) and obtain an instance of INetFwPolicy2:

// C# example
using NetFwTypeLib;

public class FirewallHelper
{
    private INetFwPolicy2 _policy;

    public FirewallHelper()
    {
        Type policyType = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
        _policy = (INetFwPolicy2)Activator.CreateInstance(policyType);
    }
}

For native C++:

// C++ example
#import "netfw.h" raw_interfaces_only
using namespace NetFwTypeLib;

int main()
{
    CoInitializeEx(0, COINIT_APARTMENTTHREADED);
    INetFwPolicy2* pPolicy = nullptr;
    HRESULT hr = CoCreateInstance(__uuidof(NetFwPolicy2), nullptr, CLSCTX_INPROC_SERVER,
                                  __uuidof(INetFwPolicy2), (void**)&pPolicy);
    // ...
}

Code Sample: Adding an Inbound Rule

The following C# snippet adds an inbound rule that allows TCP traffic on port 443:

public void AddHttpsRule()
{
    var rule = (INetFwRule)Activator.CreateInstance(
        Type.GetTypeFromProgID("HNetCfg.FWRule"));
    rule.Name = "Allow HTTPS";
    rule.Description = "Open inbound HTTPS traffic";
    rule.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
    rule.LocalPorts = "443";
    rule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
    rule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
    rule.Enabled = true;

    _policy.Rules.Add(rule);
}

References