Skip to content

Instantly share code, notes, and snippets.

@SwarajKetan
Last active April 24, 2022 06:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SwarajKetan/626d546fe52192e6b8f80db66a07b6b0 to your computer and use it in GitHub Desktop.
Save SwarajKetan/626d546fe52192e6b8f80db66a07b6b0 to your computer and use it in GitHub Desktop.
You need to have a reference to %system32%/FirewallAPI.dll
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NetFwTypeLib;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
AddOrUpdateRule();
Console.ReadLine();
}
public static void AddOrUpdateRule()
{
const string ruleName = "TESTING_RESTRICTED_ACCESS";
INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(
Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
INetFwRule rule = null;
try
{
rule = firewallPolicy.Rules.Item(ruleName);
if (rule != null)
{
ConfigureRule(rule, ruleName);
return;
}
}
catch(Exception ex)
{
}
rule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
ConfigureRule(rule, ruleName);
firewallPolicy.Rules.Add(rule);
}
private static void ConfigureRule(INetFwRule rule, string ruleName)
{
const string programPath = @"E:\dev\CRun\ConsoleApp1\bin\Debug\ConsoleApp1.exe";
rule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
rule.Description = $"Allow Only specific IPs. Last updated on: {DateTime.Now}";
rule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
rule.Enabled = true;
rule.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
rule.RemotePorts = "443";
rule.RemoteAddresses = "10.30.50.60/32,45.67.89.45/32";
rule.InterfaceTypes = "All";
rule.Name = ruleName;
rule.ApplicationName = programPath;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment