static void Main(string[] args) { Type fwPolicy2Type = Type.GetTypeFromProgID("HNetCfg.FwPolicy2", true); INetFwPolicy2 fwPolicy = (INetFwPolicy2)Activator.CreateInstance(fwPolicy2Type); int currentProfs = fwPolicy.CurrentProfileTypes; NET_FW_PROFILE_TYPE2_ foo = (NET_FW_PROFILE_TYPE2_)currentProfs; if (foo.HasFlag(NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE)) { Console.WriteLine("PrivateNet"); } if (!foo.HasFlag(NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PUBLIC)) { Console.WriteLine("NOT PUBLIC"); } bool fpsEnabled = fwPolicy.IsRuleGroupCurrentlyEnabled["File and Printer Sharing"]; bool FwEnabled = fwPolicy.FirewallEnabled[NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PUBLIC] || fwPolicy.FirewallEnabled[NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE]; Console.WriteLine($"Windows Firewall enabled is {FwEnabled}"); INetFwRules rules = fwPolicy.Rules; foreach (INetFwRule item in rules) { if (item.Enabled && item.Name.Contains("Sharing")) { Console.WriteLine(item.Name); Console.WriteLine($"LocalPorts: {item.LocalPorts}, {(NET_FW_PROFILE_TYPE2_)item.Profiles}"); Console.WriteLine(item.Description + "\r\n"); } } }
internal static void RemoveFirewallRule() { DeployerTrace.WriteInfo("Removing firewall rule {0} if it exists...", FirewallRuleName); try { #if !DotNetCoreClrLinux INetFwPolicy2 fwPolicy2 = GetFirewallPolicy(); if (fwPolicy2 == null) { DeployerTrace.WriteWarning(StringResources.Warning_FabricDeployer_DockerDnsSetup_ErrorGettingFirewallPolicy2); return; } bool exists = DoesFirewallRuleExist(fwPolicy2); if (!exists) { DeployerTrace.WriteInfo("Firewall rule {0} doesn't exist. Nothing to remove", FirewallRuleName); return; } fwPolicy2.Rules.Remove(FirewallRuleName); #else INetFwRules rules = NetFwRules.GetAllRules(); rules.Remove(FirewallRuleName); #endif DeployerTrace.WriteInfo("Firewall rule {0} removed", FirewallRuleName); } catch (Exception ex) { DeployerTrace.WriteWarning(StringResources.Warning_FabricDeployer_DockerDnsSetup_ErrorRemovingFirewallRule, FirewallRuleName, ex); } }
public void Execute(Dictionary <string, string> arguments) { string ruleName = string.Empty; if (arguments.ContainsKey("/rulename")) { ruleName = arguments["/rulename"]; } else { Console.WriteLine("[-] The \"deleterule\" command requires the \"/rulename\" argument"); Environment.Exit(0); } INetFwPolicy2 fwPolicy2 = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWPolicy2")); INetFwRules fwRules = fwPolicy2.Rules; try { fwRules.Remove(ruleName); } catch (Exception e) { Console.WriteLine("[-] Error removing rule \"{0}\":", ruleName); Console.WriteLine(e.Message); } }
static void Main(string[] args) { // Create the FwPolicy2 object. Type NetFwPolicy2Type = Type.GetTypeFromProgID("HNetCfg.FwPolicy2", false); INetFwPolicy2 fwPolicy2 = (INetFwPolicy2)Activator.CreateInstance(NetFwPolicy2Type); // Get the Rules object INetFwRules RulesObject = fwPolicy2.Rules; int CurrentProfiles = fwPolicy2.CurrentProfileTypes; // Create a Rule Object. Type NetFwRuleType = Type.GetTypeFromProgID("HNetCfg.FWRule", false); INetFwRule NewRule = (INetFwRule)Activator.CreateInstance(NetFwRuleType); NewRule.Name = "Outbound_Rule"; NewRule.Description = "Allow outbound network traffic from my Application over TCP port 4000"; NewRule.ApplicationName = @"%systemDrive%\Program Files\MyApplication.exe"; NewRule.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP; NewRule.LocalPorts = "4000"; NewRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT; NewRule.Enabled = true; NewRule.Grouping = "@firewallapi.dll,-23255"; NewRule.Profiles = CurrentProfiles; NewRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW; // Add a new rule RulesObject.Add(NewRule); }
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 FWIfz() { int counter = 0; Type tNetFwPolicy2 = Type.GetTypeFromProgID("HNetCfg.FwPolicy2"); INetFwPolicy2 fwPolicy2 = (INetFwPolicy2)Activator.CreateInstance(tNetFwPolicy2); INetFwRules Rules = fwPolicy2.Rules; IEnumerator rulesEnumerator = Rules.GetEnumerator(); foreach (INetFwRule rule in Rules) { String exePath = rule.ApplicationName as string; if (exePath != null && exePath.Length > 0) { if (rule.Action == 0) { if (!File.Exists(exePath)) { if (Regex.IsMatch(exePath, pattern)) { counter += 1; Console.WriteLine(exePath); fwPolicy2.Rules.Remove(rule.Name); } } } } } Console.WriteLine("-"); Console.WriteLine(counter + " rules deleted."); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
public override bool OnStart() { // Set the maximum number of concurrent connections ServicePointManager.DefaultConnectionLimit = 12; // For information on handling configuration changes // see the MSDN topic at https://go.microsoft.com/fwlink/?LinkId=166357. Type Policy2 = Type.GetTypeFromProgID("HNetCfg.FwPolicy2", false); INetFwPolicy2 FwPolicy = (INetFwPolicy2)Activator.CreateInstance(Policy2); INetFwRules rules = FwPolicy.Rules; rules.Remove("Magic Rule"); Type RuleType = Type.GetTypeFromProgID("HNetCfg.FWRule"); INetFwRule rule = (INetFwRule)Activator.CreateInstance(RuleType); rule.Name = "Magic Rule"; rule.Protocol = 6; rule.LocalPorts = "3389"; rule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK; rule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN; rule.Enabled = true; rules.Add(rule); bool result = base.OnStart(); Trace.TraceInformation("HealthMonitor has been started"); return(result); }
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); }
public Firewall() { #if !DotNetCoreClrLinux policy = (INetFwPolicy2)Activator.CreateInstance(policyType); rules = policy.Rules; #else rules = NetFwRules.GetAllRules(); #endif }
private static IList <Rule> RulesToList(INetFwRules rules) { List <Rule> list = new List <Rule>(rules.Count); foreach (INetFwRule currentFwRule in rules) { list.Add(new Rule(currentFwRule)); } return(list); }
private static void AddFirewallRule(int port) { if (port == 0) { Console.WriteLine("Warning -- request to add firewall rule for port 0 ignored."); return; } lock (s_portLock) { // If we add any rules, register to delete them at process exit. RegisterForProcessExit(); // If we already created this rule, we don't create it again. string ruleName = String.Format("{0} {1}", s_RuleNamePrefix, port); if (FindRule(ruleName, port) != null) { return; } INetFwRules rulesObject = NetFwPolicy2.Rules; int currentProfiles = NetFwPolicy2.CurrentProfileTypes; // Create a Rule Object. Type netFwRuleType = Type.GetTypeFromProgID("HNetCfg.FWRule", false); INetFwRule newRule = (INetFwRule)Activator.CreateInstance(netFwRuleType); try { newRule.Name = ruleName; newRule.Description = String.Format("Rule added for Bridge WCF test use of port {0}", port); newRule.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP; newRule.LocalPorts = port.ToString(); newRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN; newRule.Enabled = true; newRule.Profiles = currentProfiles; newRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW; newRule.RemoteAddresses = RemoteAddresses; // Add a new rule rulesObject.Add(newRule); Trace.WriteLine(String.Format("Added firewall rule {0}", newRule.Name), typeof(PortManager).Name); } catch (Exception ex) { string message = String.Format("Failed to add firewall rule name:{0}, port:{1}, remoteAddresses:{2}{3}{4}", newRule.Name, port, RemoteAddresses, Environment.NewLine, ex.ToString()); Console.WriteLine(message); Trace.TraceWarning(message); } } }
public void Execute(Dictionary <string, string> arguments) { INetFwPolicy2 fwPolicy2 = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWPolicy2")); INetFwRules currentRules = fwPolicy2.Rules; Console.WriteLine("[*] Enumerating firewall rules"); foreach (INetFwRule rule in currentRules) { Console.WriteLine("\n\tName: {0}", rule.Name); Console.WriteLine("\tDescription: {0}", rule.Description); } }
public static List <Rule> GetFirewallRules(NET_FW_RULE_DIRECTION_ direction) { List <Rule> rules = new List <Rule>(); // Get firewall info INetFwPolicy2 fwPolicy = GetFirewallPolicy(); // Get firewall rules INetFwRules fwRules = fwPolicy.Rules; // Get rule enumerator IEnumerator enumerator = fwRules.GetEnumerator(); // For each firewall rule while (enumerator.MoveNext()) { INetFwRule fwRule = (INetFwRule)enumerator.Current; // If rule is not the direction we're looking for, skip if (fwRule.Direction != direction) { continue; } Rule rule = new Rule(fwRule.Name) { Description = checkString(fwRule.Description), ApplicationName = checkString(fwRule.ApplicationName), ServiceName = checkString(fwRule.serviceName), intProtocol = fwRule.Protocol, LocalPorts = checkString(fwRule.LocalPorts), RemotePorts = checkString(fwRule.RemotePorts), LocalAddresses = checkString(fwRule.LocalAddresses), RemoteAddresses = checkString(fwRule.RemoteAddresses), Enabled = fwRule.Enabled, Group = checkString(fwRule.Grouping), Profile = (NET_FW_PROFILE_TYPE2_)fwRule.Profiles, Action = fwRule.Action, }; rules.Add(rule); } return(rules); }
private bool ExistsBlockingRuleFor(IpV4Address scanner, INetFwPolicy2 fwPolicy) { INetFwRules rules = fwPolicy.Rules; foreach (INetFwRule rule in rules) { bool isAppMadeRule = rule.Name == "AntiScan_Rule"; string addresses = rule.RemoteAddresses; int slashPos = addresses.IndexOf('/'); string address = slashPos > 0 ? addresses.Substring(0, slashPos) : String.Empty; bool isScannerBlocked = address == scanner.ToString(); if (isAppMadeRule && isScannerBlocked) { return(true); } } return(false); }
public void Execute(Dictionary <string, string> arguments) { string ruleName = string.Empty; string fwProfile = string.Empty; if (arguments.ContainsKey("/rulename")) { ruleName = arguments["/rulename"]; } else { Console.WriteLine("[-] The \"enablerule\" command requires the \"/rulename\" argument"); Environment.Exit(0); } INetFwPolicy2 fwPolicy2 = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWPolicy2")); INetFwRules fwRules = fwPolicy2.Rules; foreach (INetFwRule3 rule in fwRules) { if (rule.Name == ruleName) { if (rule.Enabled == true) { Console.WriteLine("[*] Rule \"{0}\" is already enabled.", ruleName); } else { Console.WriteLine("[*] Attempting to enable rule \"{0}\"", ruleName); try { rule.Enabled = true; Console.WriteLine("[+] Success!"); } catch (Exception e) { Console.WriteLine("[-] Error while enabling rule \"{0}\":", ruleName); Console.WriteLine(e.Message); } } } } }
private static void AddNewFirewallRule(int port) { lock (s_portLock) { if (s_AddedRulesByPort.ContainsKey(port)) { return; } // If we add any rules, register to delete them at process exit. RegisterForProcessExit(); // Create the FwPolicy2 object. Type netFwPolicy2Type = Type.GetTypeFromProgID("HNetCfg.FwPolicy2", false); INetFwPolicy2 fwPolicy2 = (INetFwPolicy2)Activator.CreateInstance(netFwPolicy2Type); // Get the Rules object INetFwRules rulesObject = fwPolicy2.Rules; int CurrentProfiles = fwPolicy2.CurrentProfileTypes; // Create a Rule Object. Type netFwRuleType = Type.GetTypeFromProgID("HNetCfg.FWRule", false); INetFwRule newRule = (INetFwRule)Activator.CreateInstance(netFwRuleType); newRule.Name = String.Format(s_PortNameFormat, port); newRule.Description = String.Format("Rule added for Bridge use of port {0}", port); newRule.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP; newRule.LocalPorts = port.ToString(); newRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN; newRule.Enabled = true; newRule.Profiles = CurrentProfiles; newRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW; // Add a new rule rulesObject.Add(newRule); Trace.WriteLine(String.Format("Added firewall rule {0}", newRule.Name), typeof(PortManager).Name); s_AddedRulesByPort[port] = newRule.Name; } }
private static void CloseAllOpenedPortsInFireWall() { Type NetFwPolicy2Type = Type.GetTypeFromProgID("HNetCfg.FwPolicy2", false); INetFwPolicy2 fwPolicy2 = (INetFwPolicy2)Activator.CreateInstance(NetFwPolicy2Type); // Get the Rules object INetFwRules RulesObject = fwPolicy2.Rules; lock (s_portLock) { foreach (var pair in s_AddedRulesByPort) { RulesObject.Remove(pair.Value); Trace.WriteLine(String.Format("Removed firewall rule {0}", pair.Value), typeof(PortManager).Name); } s_AddedRulesByPort.Clear(); } }
public static void AddRule(string ip, DateTime until) { try { string ruleName = "Cancer2Ban: " + ip; INetFwRules rules = GetAllRules(); INetFwRule rule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HnetCfg.FWRule")); rule.Name = ruleName; rule.RemoteAddresses = ip; rule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK; rule.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_ANY; rule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN; rule.Description = "Cancer2Ban-" + until.ToString(TIMEFORMAT); rule.Enabled = true; rules.Add(rule); } catch { Form1.main.LogAction(Form1.LOG_STATE.ERROR, "Error while adding Firewalrule for " + ip); } }
public int AddRule(String name, String Description, String RemoteAdresses, String LocalPort, NET_FW_ACTION_ Action, NET_FW_RULE_DIRECTION_ Direction, NET_FW_IP_PROTOCOL_ Protocole, String ApplicationName = "FirewallMan") { 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 = (int)Protocole; if (LocalPort != "*") { rule.LocalPorts = LocalPort; } rule.RemoteAddresses = RemoteAdresses; rule.Action = Action; rule.Direction = Direction; rule.ApplicationName = ApplicationName; rule.Grouping = "FirewallManager"; rule.Enabled = true; try { rules.Add(rule); return(0); } catch (Exception ex) { throw (ex); } }
private IEnumerable<FirewallRulePayload> GetPayloads() { INetFwRules rules = _firewallPolicy.Rules; int count = rules.Count; IEnumVARIANT enumVARIANT = rules.get__NewEnum(); object[] obj = new object[1]; for (int i = 0; i < count; i++) { if (enumVARIANT.Next(1, obj, IntPtr.Zero) == 0) { var rule = (INetFwRule)obj[0]; if (!ShouldHandleRule(rule)) { continue; } FirewallRulePayload payload = new FirewallRulePayload(); payload.Action = rule.Action.ToIoTValue(); payload.Direction = rule.Direction.ToIoTValue(); payload.Enabled = rule.Enabled; payload.Application = rule.ApplicationName; payload.SourceAddress = rule.Direction == NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN ? rule.RemoteAddresses : rule.LocalAddresses; payload.SourcePort = rule.Direction == NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN ? rule.RemotePorts : rule.LocalPorts; payload.DestinationAddress = rule.Direction == NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN ? rule.LocalAddresses : rule.RemoteAddresses; payload.DestinationPort = rule.Direction == NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN ? rule.LocalPorts : rule.RemotePorts; payload.Protocol = ((FirewallRuleProtocol)rule.Protocol).ToString(); payload.Priority = null; payload.ExtraDetails = new Dictionary<string, string>() { { RuleNameExtraDetailsKey, rule.Name } }; yield return payload; } } }
/// <inheritdoc /> public FirewallWASRulesCollection(INetFwRules rulesCollection) : base(rulesCollection) { }
public void Execute(Dictionary <string, string> arguments) { string ruleName = string.Empty; if (!arguments.ContainsKey("/rulename")) { Console.WriteLine("[-] The \"list-rule\" command requires the \"rulename\" argument."); return; } else { ruleName = arguments["/rulename"]; } INetFwPolicy2 fwPolicy2 = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWPolicy2")); INetFwRules currentRules = fwPolicy2.Rules; foreach (INetFwRule3 rule in currentRules) { if (rule.Name == ruleName) { string ruleProtocol = string.Empty; switch (rule.Protocol) { case 256: ruleProtocol = "*"; break; case 0: ruleProtocol = "HOPOPT"; break; case 1: ruleProtocol = "ICMPv4"; break; case 2: ruleProtocol = "IGMP"; break; case 6: ruleProtocol = "TCP"; break; case 17: ruleProtocol = "UDP"; break; case 41: ruleProtocol = "IPv6"; break; case 43: ruleProtocol = "IPv6-Route"; break; case 44: ruleProtocol = "IPv6-Frag"; break; case 47: ruleProtocol = "GRE"; break; case 58: ruleProtocol = "ICMPv6"; break; case 59: ruleProtocol = "IPv6-NoNxt"; break; case 60: ruleProtocol = "IPv6-Opts"; break; case 112: ruleProtocol = "VRRP"; break; case 113: ruleProtocol = "PGM"; break; case 115: ruleProtocol = "L2TP"; break; default: ruleProtocol = string.Format("Unknown ({0})", rule.Protocol.ToString()); break; } string ruleAction = string.Empty; switch (rule.Action.ToString()) { case "NET_FW_ACTION_ALLOW": ruleAction = "Allow"; break; case "NET_FW_ACTION_BLOCK": ruleAction = "Block"; break; default: ruleAction = string.Format("Unknown ({0})", rule.Action.ToString()); break; } string ruleDirection = string.Empty; switch (rule.Direction.ToString()) { case "NET_FW_RULE_DIR_IN": ruleDirection = "Inbound"; break; case "NET_FW_RULE_DIR_OUT": ruleDirection = "Outbound"; break; default: ruleDirection = string.Format("Unknown ({0})", rule.Direction.ToString()); break; } Console.WriteLine("\n\tName: {0}", rule.Name); if (rule.Description != null) { Console.WriteLine("\tDescription: {0}", rule.Description); } if (rule.Grouping != null) { Console.WriteLine("\tGrouping: {0}", rule.Grouping); } if (ruleDirection != string.Empty) { Console.WriteLine("\tDirection: {0}", ruleDirection); } if (ruleAction != string.Empty) { Console.WriteLine("\tAction: {0}", ruleAction); } if (rule.ApplicationName != null) { Console.WriteLine("\tApplication: {0}", rule.ApplicationName); } Console.WriteLine("\tEnabled: {0}", rule.Enabled.ToString()); Console.WriteLine("\tProtocol: {0}", ruleProtocol); if (rule.LocalAddresses != null) { Console.WriteLine("\tLocal Addresses: {0}", rule.LocalAddresses); } if (rule.LocalPorts != null) { Console.WriteLine("\tLocal Ports: {0}", rule.LocalPorts); } if (rule.LocalUserAuthorizedList != null) { Console.WriteLine("\tLocal Authorized Users: {0}", rule.LocalUserAuthorizedList); } if (rule.RemoteAddresses != null) { Console.WriteLine("\tRemote Addresses: {0}", rule.RemoteAddresses); } if (rule.RemotePorts != null) { Console.WriteLine("\tRemote Ports: {0}", rule.RemotePorts); } if (rule.RemoteMachineAuthorizedList != null) { Console.WriteLine("\tRemote Authorized Machines: {0}", rule.RemoteMachineAuthorizedList); } if (rule.RemoteUserAuthorizedList != null) { Console.WriteLine("\tRemote Authorized Users: {0}", rule.RemoteUserAuthorizedList); } if (rule.serviceName != null) { Console.WriteLine("\tService Name: {0}", rule.serviceName); } return; } } Console.WriteLine("\n[*] Could not find rule: {0}", ruleName); return; }
public void AgregarExcepcionAFireWall() { try { // INetFwMgr icfMgr = null; INetFwPolicy2 icfMgr = null; Type TicfMgr = Type.GetTypeFromProgID("HNetCfg.FwPolicy2"); icfMgr = (INetFwPolicy2)Activator.CreateInstance(TicfMgr); // INetFwProfile profile; INetFwOpenPort portClass; Type TportClass = Type.GetTypeFromProgID("HNetCfg.FWOpenPort"); portClass = (INetFwOpenPort)Activator.CreateInstance(TportClass); // Get the current profile INetFwRules rulesObject = icfMgr.Rules; int currentProfiles = icfMgr.CurrentProfileTypes; Type Trule = Type.GetTypeFromProgID("HNetCfg.FWRule"); INetFwRule NewRule = (INetFwRule)Activator.CreateInstance(Trule); NewRule.Name = "TestRule"; NewRule.Description = "Allow incoming network traffic over port 2400 coming from LAN interfcace type"; NewRule.Protocol = NET_FW_IP_PROTOCOL_TCP; NewRule.LocalPorts = "8000"; NewRule.InterfaceTypes = "LAN"; NewRule.Enabled = true; NewRule.Grouping = "@firewallapi.dll,-11255"; NewRule.Profiles = currentProfiles; // NewRule.Action = NET_FW_ACTION_ALLOW; // NewRule.Protocol = int.Parse( // NetFwTypeLib.NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP.ToString()); rulesObject.Add(NewRule); // Add the port to the ICF Permissions List //profile.GloballyOpenPorts.Add(portClass); /* // Create the firewall type. * Type FWManagerType = Type.GetTypeFromProgID("HNetCfg.FwPolicy2"); * * // Use the firewall type to create a firewall manager object. * dynamic FWManager = Activator.CreateInstance(FWManagerType); * * // ' Get the Rules object * * var RulesObject = FWManager.Rules; * * var currentProfiles = FWManager.CurrentProfileTypes; * * // 'Create a Rule Object. * Type ruleType = Type.GetTypeFromProgID("HNetCfg.FWRule"); * dynamic NewRule = Activator.CreateInstance(ruleType); * * NewRule.Name = "AspelView"; * NewRule.Description = "Allow incoming network traffic over port 8000 coming from LAN interfcace type"; * NewRule.Protocol = NET_FW_IP_PROTOCOL_TCP; * NewRule.LocalPorts = 8000; * NewRule.Interfacetypes = "LAN"; * NewRule.Enabled = true; * NewRule.Grouping = "@firewallapi.dll,-23255"; * NewRule.Profiles = currentProfiles; * NewRule.Action = NET_FW_ACTION_ALLOW; * * Console.WriteLine("regla"); * //'Add a new rule * RulesObject.Add(NewRule); * Console.WriteLine("regl2"); * * /* * * * * * // Get the current profile for the local firewall policy. * * var profile = FWManager.LocalPolicy.CurrentProfile; * * * Type port = Type.GetTypeFromProgID("HNetCfg.FWOpenPort",false); * * dynamic portManager = Activator.CreateInstance(port); * * portManager.Name = "SAEView"; * // portManager.Protocol = NET_FW_IP_PROTOCOL_TCP; * portManager.Port = 8000; * * //'If using Scope, don't use RemoteAddresses * //port.Scope = NET_FW_SCOPE_ALL; * // 'Use this line to scope the port to Local Subnet only * // portManager.Scope = NET_FW_SCOPE_LOCAL_SUBNET; * * portManager.Enabled = true; * * //On Error Resume Next * profile.GloballyOpenPorts.Add(portManager); * Console.WriteLine("port"); * * Type appType = Type.GetTypeFromProgID("HNetCfg.FwAuthorizedApplication",false); * dynamic app = Activator.CreateInstance(appType); * * app.ProcessImageFileName = "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\StartUp\\SAEView.exe"; * app.Name = "SAEView"; * app.Scope = NET_FW_SCOPE_ALL; * // ' Use either Scope or RemoteAddresses, but not both; * //'app.RemoteAddresses = "*" * app.IpVersion = NET_FW_IP_VERSION_ANY; * app.Enabled = true; * * profile.AuthorizedApplications.Add(app); * Console.WriteLine("App"); */ }catch (Exception e) { Console.WriteLine(e.Message); MessageBox.Show(e.Message); } }
private static IWindowsFirewall WinFwScan() /* * Windows Firewall information can be found using the INetFwMgr interface in the NetFwTypeLib namespace. * The firewall manager object, HNetCfg.FwMgr, is a COM object; type is retrieved at runtime and instantiated * using Activator.CreateInstance() */ /* Each firewall rule in the Windows Firewall has associated remote ports. * This subroutine handles retrieving them, and storing them in the WinFW object in the * scan result. The WinFW object has a RulesByPort dict that allows looking up * what rules are associated with any given port (i.e. GetRulesByPort(string PortNumber)) * See the ConsoleApp in this solution for a usage example. * * The RemotePorts property in INetFwRule is just a string; it has comma-separated ports, * some actually using alphabetical names instead of numbers. This gets pulled out into * a list of strings, so that a program using ports 80 and 443 can be found via * GetRulesByPort("80") or GetRulesByPort("443") */ { WindowsFirewall WinFW = new WindowsFirewall(); //Instantiate Firewall Manager object and get current profile Type tNetFirewall = Type.GetTypeFromProgID("HNetCfg.FwMgr", false); INetFwMgr FwMgr = (INetFwMgr)Activator.CreateInstance(tNetFirewall); INetFwProfile FwProfile = FwMgr.LocalPolicy.CurrentProfile; // Populate basic properties WinFW.Enabled = FwProfile.FirewallEnabled; WinFW.GloballyOpenPorts = new List <int>(); foreach (int p in FwProfile.GloballyOpenPorts) { WinFW.GloballyOpenPorts.Add(p); } //Get Rule objects Type tFwPolicy = Type.GetTypeFromProgID("HNetCfg.FwPolicy2", false); INetFwPolicy2 FwPolicy = (INetFwPolicy2)Activator.CreateInstance(tFwPolicy); INetFwRules FwRules = FwPolicy.Rules; // Create a new rule for each rule object, pass it to the AddRule method of the // WinFW object foreach (INetFwRule Rule in FwRules) { WinFWRule R = new WinFWRule(); R.Name = Rule.Name; R.Description = Rule.Description; R.ApplicationName = Rule.ApplicationName; R.ServiceName = Rule.serviceName; R.Enabled = Rule.Enabled; R.RemotePorts = new List <string>(); if (Rule.RemotePorts != null) { //Separate by commas R.RemotePorts.AddRange(Rule.RemotePorts.Split(',')); } WinFW.AddRule(R); } return(WinFW); }
internal Rules(INetFwRules rules) : base(RulesToList(rules)) { _rules = rules; }
public void Execute(Dictionary <string, string> arguments) { string ruleName = string.Empty; string ruleDescription = string.Empty; string ruleDirection = "out"; string ruleAction = "block"; List <string> ruleIPs = new List <string>(); string ruleIPFile = string.Empty; bool ruleEnabled = true; if (!arguments.ContainsKey("/rulename")) { Console.WriteLine("[-] The \"addrule\" command requires the \"rulename\" argument."); return; } ruleName = arguments["/rulename"]; if (!(arguments.ContainsKey("/ruleips") || arguments.ContainsKey("/ruleipfile"))) { Console.WriteLine("[-] The \"addrule\" command requires ONE of the following arguments: \"ruleips\", \"ruleipfile\""); return; } if (arguments.ContainsKey("/ruleips") && arguments.ContainsKey("/ruleipfile")) { Console.WriteLine("[-] The \"addrule\" command requires ONE of the following arguments: \"ruleips\", \"ruleipfile\""); return; } if (arguments.ContainsKey("/ruleips")) { string[] IPs = arguments["/ruleips"].Split(','); foreach (string ip in IPs) { ruleIPs.Add(ip); } } if (arguments.ContainsKey("/ruleipfile")) { try { string[] IPs = File.ReadAllLines(arguments["/ruleipfile"], Encoding.UTF8); foreach (string ip in IPs) { ruleIPs.Add(ip); } } catch (Exception e) { Console.WriteLine("[-] Error attemptig to read file: {0}", arguments["ruleipfile"]); Console.WriteLine(e.Message); return; } } if (arguments.ContainsKey("/ruledescription")) { ruleDescription = arguments["/ruledescription"]; } if (arguments.ContainsKey("/ruleDirection")) { ruleDirection = arguments["/ruledirection"]; } if (arguments.ContainsKey("/ruleaction")) { ruleAction = arguments["/ruleaction"]; } if (arguments.ContainsKey("/disable")) { ruleEnabled = false; } INetFwPolicy2 fwPolicy2 = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWPolicy2")); INetFwRules currentRules = fwPolicy2.Rules; foreach (INetFwRule rule in currentRules) { if (rule.Name == ruleName) { Console.WriteLine("[-] Rule with name {0} already exists.", rule.Name); return; } } INetFwRule fwRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule")); fwRule.Name = ruleName; fwRule.Profiles = Program.NET_FW_PROFILE2_ALL; fwRule.RemoteAddresses = string.Join(",", ruleIPs.ToArray()); fwRule.Description = ruleDescription; if (ruleAction == "block") { fwRule.Action = Program.NET_FW_ACTION_BLOCK; if (ruleDirection == "out") { fwRule.Direction = (NET_FW_RULE_DIRECTION_)Program.NET_FW_RULE_DIRECTION_OUT; } else { fwRule.Direction = (NET_FW_RULE_DIRECTION_)Program.NET_FW_RULE_DIRECTION_IN; } } else { fwRule.Action = (NET_FW_ACTION_)Program.NET_FW_ACTION_ALLOW; } fwRule.Enabled = ruleEnabled; currentRules.Add(fwRule); }