From 0c3d0f1a724852fdcc9ad543be8fd5f0add6448e Mon Sep 17 00:00:00 2001 From: zouhair-isk Date: Sat, 22 Feb 2014 23:13:01 +0000 Subject: [PATCH] *=> Add rules to firewall grammatically(using Firewall API): Must Reference NetFwTypeLib from COM The old version didn't work for me in Windows FR because it reply on the buffer returned from the console and that buffer change from OS[en-fr-es] to other --- ScreenTask/FirewallConf.cs | 44 ++++++++++++++++++++++++++++++++ ScreenTask/ScreenTask.csproj | 12 +++++++++ ScreenTask/ScreenTask.sln | 20 +++++++++++++++ ScreenTask/frmMain.Designer.cs | 16 ++++++------ ScreenTask/frmMain.cs | 46 +++++++++------------------------- 5 files changed, 96 insertions(+), 42 deletions(-) create mode 100644 ScreenTask/FirewallConf.cs create mode 100644 ScreenTask/ScreenTask.sln diff --git a/ScreenTask/FirewallConf.cs b/ScreenTask/FirewallConf.cs new file mode 100644 index 0000000..ff5c6e9 --- /dev/null +++ b/ScreenTask/FirewallConf.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using NetFwTypeLib; + +namespace ScreenTask +{ + class FirewallConf + { + public void AddRule(String name, String Description, + NET_FW_ACTION_ Action, NET_FW_RULE_DIRECTION_ Direction, String LocalPort, + bool Enabled = true, int Protocole = 6, String RemoteAdresses = "localsubnet", String ApplicationName = "ScreenTask") + { + Type Policy2 = Type.GetTypeFromProgID("HNetCfg.FwPolicy2", false); + INetFwPolicy2 FwPolicy = (INetFwPolicy2)Activator.CreateInstance(Policy2); + INetFwRules rules = FwPolicy.Rules; + //Delete if exist to avoid deplicated rules + DeleteRule(name); + Type RuleType = Type.GetTypeFromProgID("HNetCfg.FWRule"); + INetFwRule rule = (INetFwRule)Activator.CreateInstance(RuleType); + + rule.Name = name; + rule.Description = Description; + rule.Protocol = Protocole;// TCP/IP + rule.LocalPorts = LocalPort; + rule.RemoteAddresses = RemoteAdresses; + rule.Action = Action; + rule.Direction = Direction; + rule.ApplicationName = ApplicationName; + rule.Enabled = true; + //Add Rule + rules.Add(rule); + } + public void DeleteRule(String RuleName) + { + Type Policy2 = Type.GetTypeFromProgID("HNetCfg.FwPolicy2", false); + INetFwPolicy2 FwPolicy = (INetFwPolicy2)Activator.CreateInstance(Policy2); + INetFwRules rules = FwPolicy.Rules; + + rules.Remove(RuleName); + } + } +} diff --git a/ScreenTask/ScreenTask.csproj b/ScreenTask/ScreenTask.csproj index 51386b7..c7fadca 100644 --- a/ScreenTask/ScreenTask.csproj +++ b/ScreenTask/ScreenTask.csproj @@ -53,6 +53,7 @@ + Form @@ -102,6 +103,17 @@ PreserveNewest + + + {58FBCF7C-E7A9-467C-80B3-FC65E8FCCA08} + 1 + 0 + 0 + tlbimp + False + True + +