/// <inheritdoc /> /// <summary> /// Creates a rule about an executable file (application) to be registered to a firewall profile /// </summary> /// <param name="profile">The profile that the rule belongs to</param> /// <param name="name">Name of the rule</param> /// <param name="action">Action of the rule</param> /// <param name="filename">Address of the executable file that the rule applies to</param> /// <param name="protocol">Protocol that the rule applies to</param> /// <returns>Returns the newly created rule object implementing <see cref="T:WindowsFirewallHelper.IRule" /> interface</returns> /// <exception cref="T:System.NotSupportedException">This class is not supported on this machine</exception> /// <exception cref="T:WindowsFirewallHelper.FirewallAPIv1.FirewallAPIv1NotSupportedException"> /// The asked setting is not /// supported with this class /// </exception> // ReSharper disable once TooManyArguments public IRule CreateApplicationRule( FirewallProfiles profile, string name, // ReSharper disable once FlagArgument FirewallAction action, string filename, FirewallProtocol protocol) { if (!IsSupported) { throw new NotSupportedException(); } if (!protocol.Equals(FirewallProtocol.Any)) { throw new FirewallAPIv1NotSupportedException(); } if (action != FirewallAction.Allow) { throw new FirewallAPIv1NotSupportedException(); } return(new ApplicationRule(name, filename, profile)); }
public static void AddApplicationRule(string ruleName, string fileName, FirewallDirection direction, FirewallProtocol protocol) { if (Firewall.Instance.IsSupported) { if (StandardRuleWin8.IsSupported) { var rule = new StandardRuleWin8(ruleName, fileName, FirewallAction.Allow, direction, FirewallProfiles.Domain | FirewallProfiles.Private | FirewallProfiles.Public) { Grouping = "Celeste Fan Project", Description = "Auto-generated rules by \"Celeste Fan Project Launcher\"", InterfaceTypes = FirewallInterfaceTypes.Lan | FirewallInterfaceTypes.RemoteAccess | FirewallInterfaceTypes.Wireless, Protocol = protocol }; //if (direction == FirewallDirection.Inbound && (protocol.Equals(FirewallProtocol.TCP) || protocol.Equals(FirewallProtocol.UDP))) // rule.EdgeTraversalOptions = EdgeTraversalAction.DefferToUser; Firewall.Instance.Rules.Add(rule); } else if (StandardRuleWin7.IsSupported) { var rule = new StandardRuleWin7(ruleName, fileName, FirewallAction.Allow, direction, FirewallProfiles.Domain | FirewallProfiles.Private | FirewallProfiles.Public) { Grouping = "Celeste Fan Project", Description = "Auto-generated rules by \"Celeste Fan Project Launcher\"", InterfaceTypes = FirewallInterfaceTypes.Lan | FirewallInterfaceTypes.RemoteAccess | FirewallInterfaceTypes.Wireless, Protocol = protocol }; //if (direction == FirewallDirection.Inbound && (protocol.Equals(FirewallProtocol.TCP) || protocol.Equals(FirewallProtocol.UDP))) // rule.EdgeTraversalOptions = EdgeTraversalAction.DefferToUser; Firewall.Instance.Rules.Add(rule); } else { goto default_rule; } return; } default_rule: var defaultRule = FirewallManager.Instance.CreateApplicationRule( FirewallProfiles.Domain | FirewallProfiles.Private | FirewallProfiles.Public, ruleName, FirewallAction.Allow, fileName, protocol); defaultRule.Direction = direction; FirewallManager.Instance.Rules.Add(defaultRule); }
private static void AddDefaultPortRule(string ruleName, ushort portNumber, FirewallDirection direction, FirewallProtocol protocol) { var defaultRule = FirewallManager.Instance.CreatePortRule( FirewallProfiles.Domain | FirewallProfiles.Private | FirewallProfiles.Public, ruleName, FirewallAction.Allow, portNumber, protocol); defaultRule.Direction = direction; FirewallManager.Instance.Rules.Add(defaultRule); }
/// <summary> /// Creates a rule about an executable file (application) to be registered to a firewall profile /// </summary> /// <param name="profiles">The profile or profiles that the rule belongs to</param> /// <param name="name">Name of the rule</param> /// <param name="action">Action of the rule</param> /// <param name="filename">Address of the executable file that the rule applies to</param> /// <param name="protocol">Protocol that the rule applies to</param> /// <returns>Returns the newly created rule object implementing <see cref="IRule" /> interface</returns> /// <exception cref="NotSupportedException">This class is not supported on this machine</exception> public IRule CreateApplicationRule(FirewallProfiles profiles, string name, FirewallAction action, string filename, FirewallProtocol protocol) { if (!IsSupported) { throw new NotSupportedException(); } return(new StandardRule(name, filename, action, FirewallDirection.Inbound, profiles) { Protocol = protocol }); }
/// <summary> /// Creates a rule about a port to be registered to a firewall profile /// </summary> /// <param name="profiles">The profile or profiles that the rule belongs to</param> /// <param name="name">Name of the rule</param> /// <param name="action">Action of the rule</param> /// <param name="portNumber">Port number that the rule applies to</param> /// <param name="protocol">Protocol that the rule applies to</param> /// <returns>Returns the newly created rule object implementing <see cref="IRule" /> interface</returns> /// <exception cref="NotSupportedException">This class is not supported on this machine</exception> public IRule CreatePortRule(FirewallProfiles profiles, string name, FirewallAction action, ushort portNumber, FirewallProtocol protocol) { if (!IsSupported) { throw new NotSupportedException(); } return(new StandardRule(name, portNumber, action, FirewallDirection.Inbound, profiles) { Protocol = protocol }); }
public static void AddPortRule(string ruleName, ushort portNumber, FirewallDirection direction, FirewallProtocol protocol) { if (Firewall.Instance.IsSupported) { if (StandardRuleWin8.IsSupported) { var rule = new StandardRuleWin8(ruleName, portNumber, FirewallAction.Allow, direction, FirewallProfiles.Domain | FirewallProfiles.Private | FirewallProfiles.Public) { Grouping = "Celeste Fan Project", Description = "Auto-generated rules by \"Celeste Fan Project Launcher\"", InterfaceTypes = FirewallInterfaceTypes.Lan | FirewallInterfaceTypes.RemoteAccess | FirewallInterfaceTypes.Wireless, Protocol = protocol }; Firewall.Instance.Rules.Add(rule); } else if (StandardRuleWin7.IsSupported) { var rule = new StandardRuleWin7(ruleName, portNumber, FirewallAction.Allow, direction, FirewallProfiles.Domain | FirewallProfiles.Private | FirewallProfiles.Public) { Grouping = "Celeste Fan Project", Description = "Auto-generated rules by \"Celeste Fan Project Launcher\"", InterfaceTypes = FirewallInterfaceTypes.Lan | FirewallInterfaceTypes.RemoteAccess | FirewallInterfaceTypes.Wireless, Protocol = protocol }; Firewall.Instance.Rules.Add(rule); } else { goto default_rule; } return; } default_rule: var defaultRule = FirewallManager.Instance.CreatePortRule( FirewallProfiles.Domain | FirewallProfiles.Private | FirewallProfiles.Public, ruleName, FirewallAction.Allow, portNumber, protocol); defaultRule.Direction = direction; FirewallManager.Instance.Rules.Add(defaultRule); }
/// <summary> /// Creates a rule about a port to be registered to a firewall profile /// </summary> /// <param name="profile">The profile that the rule belongs to</param> /// <param name="name">Name of the rule</param> /// <param name="action">Action of the rule</param> /// <param name="portNumber">Port number that the rule applies to</param> /// <param name="protocol">Protocol that the rule applies to</param> /// <returns>Returns the newly created rule object implementing <see cref="IRule" /> interface</returns> /// <exception cref="NotSupportedException">This class is not supported on this machine</exception> /// <exception cref="FirewallAPIv1NotSupportedException">The asked setting is not supported with this class</exception> public IRule CreatePortRule(FirewallProfiles profile, string name, FirewallAction action, ushort portNumber, FirewallProtocol protocol) { if (!IsSupported) { throw new NotSupportedException(); } if (action != FirewallAction.Allow) { throw new FirewallAPIv1NotSupportedException(); } return(new PortRule(name, portNumber, profile) { Protocol = protocol }); }
/// <summary> /// Creates a rule about a port to be registered to a firewall profile /// </summary> /// <param name="profiles">The profile or profiles that the rule belongs to</param> /// <param name="name">Name of the rule</param> /// <param name="action">Action of the rule</param> /// <param name="portNumber">Port number that the rule applies to</param> /// <param name="protocol">Protocol that the rule applies to</param> /// <returns>Returns the newly created rule object implementing <see cref="IRule" /> interface</returns> /// <exception cref="NotSupportedException">This class is not supported on this machine</exception> public IRule CreatePortRule(FirewallProfiles profiles, string name, FirewallAction action, ushort portNumber, FirewallProtocol protocol) { if (!IsSupported) { throw new NotSupportedException(); } if (!protocol.Equals(FirewallProtocol.TCP) && protocol.Equals(FirewallProtocol.UDP)) { throw new FirewallAPIv2InvalidProtocolException( "Invalid protocol selected; rule's protocol should be TCP or UDP."); } return(new StandardRule(name, portNumber, action, FirewallDirection.Inbound, profiles) { Protocol = protocol }); }
public static void AddRule(String name, FirewallAction action, FirewallProtocol protocol, FirewallDirection direction , Int32[] localPorts, Int32[] remotePorts, String serviceName = null) { //Don't add if it already exists var policy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2")); if (policy.Rules.Cast <INetFwRule3>().Any(rule => rule.Name == name)) { return; } //Add new rule var newRule = (INetFwRule3)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule")); newRule.Enabled = true; newRule.Action = (NET_FW_ACTION_)action; newRule.Protocol = (Int32)protocol; if (localPorts != null) { newRule.LocalPorts = String.Join(",", localPorts); } if (remotePorts != null) { newRule.RemotePorts = String.Join(",", remotePorts); } newRule.Direction = (NET_FW_RULE_DIRECTION_)direction; if (serviceName != null) { newRule.serviceName = serviceName; } newRule.Name = name; //newRule.Grouping = group; newRule.Profiles = (Int32)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_ALL; policy.Rules.Add(newRule); }
public static void AddApplicationRule(string nameOfApp, string localOfApp, string groupKey, string description, FirewallDirection direction, FirewallProtocol protocol, string firewallLogNote) { try { Log.Info("WINDOWS FIREWALL: Supported Firewall Found"); var rule = new FirewallWASRuleWin8(localOfApp, FirewallAction.Allow, direction, FirewallProfiles.Domain | FirewallProfiles.Private | FirewallProfiles.Public) { ApplicationName = localOfApp, Name = nameOfApp, Grouping = groupKey, Description = description, NetworkInterfaceTypes = NetworkInterfaceTypes.Lan | NetworkInterfaceTypes.RemoteAccess | NetworkInterfaceTypes.Wireless, Protocol = protocol }; if (direction == FirewallDirection.Inbound) { rule.EdgeTraversalOptions = EdgeTraversalAction.Allow; } FirewallManager.Instance.Rules.Add(rule); Log.Info("WINDOWS FIREWALL: Finished Adding " + nameOfApp + " to Firewall! {" + firewallLogNote + "}"); } catch (FirewallWASNotSupportedException Error) { Log.Error("WINDOWS FIREWALL: " + Error.Message); AddDefaultApplicationRule(nameOfApp, localOfApp, direction, protocol, firewallLogNote); } }
private static void Main() { ConsoleWriter.Default.PrintMessage("Firewall Control"); // Информация о версии брандмауэра ConsoleWriter.Default.PrintMessage($"Firewall Version: {FirewallManager.Version}"); // Экземпляр ('пульт') управления брандмауэром var firewallInstance = FirewallManager.Instance; ConsoleWriter.Default.PrintMessage($"Type of control: {firewallInstance.Name}"); // Если версия брандмауэра неизвестная или недействительна if (FirewallManager.Version == FirewallAPIVersion.None) { ConsoleWriter.Default.PrintMessage("Press any key to exit."); Console.ReadKey(); // То выход return; } // Панель навигации // Генеральная консоль ConsoleNavigation.Default.PrintNavigation(new[] { // Консоль для профилей new ConsoleNavigationItem("Profiles", (i, item) => { // Консоль подпунктов профилей ConsoleNavigation.Default.PrintNavigation( // Объект кладем в массив firewallInstance.Profiles.ToArray(), (i1, profile) => { // Выводим данные о конкретном профиле ConsoleWriter.Default.WriteObject(profile); ConsoleWriter.Default.PrintMessage("Press any key to get one step back."); // Возврат Console.ReadKey(); }, "Select a profile to view its settings." ); }), // Консоль для правил new ConsoleNavigationItem("Rules", (i, item) => { // Консоль всех правил ConsoleNavigation.Default.PrintNavigation( // Сортируем правила в алфавитном порядке // Каждое правило (объект) кладем в массив firewallInstance.Rules.OrderBy((rule) => rule.FriendlyName).ToArray(), (i1, rule) => { // Вывод правила ConsoleWriter.Default.WriteObject(rule); ConsoleWriter.Default.PrintMessage("Press any key to get one step back."); // Возврат Console.ReadKey(); }, "Select a rule to view its settings." ); }), new ConsoleNavigationItem("Create rule", (i, item) => { // Задание правилу профиля string profile = ConsoleWriter.Default.PrintQuestion("Enter type of profile"); if (profile.ToUpper() == "PUBLIC" || profile.ToUpper() == "DOMAIN" || profile.ToUpper() == "PRIVATE") { FirewallProfiles firewallProfile = FirewallProfiles.Public; if (profile.ToUpper() == "PUBLIC") { firewallProfile = FirewallProfiles.Public; } if (profile.ToUpper() == "DOMAIN") { firewallProfile = FirewallProfiles.Domain; } if (profile.ToUpper() == "PRIVATE") { firewallProfile = FirewallProfiles.Private; } // Имя правила string name = ConsoleWriter.Default.PrintQuestion("Enter name of rule"); if (name != "") { // Тип доступа FirewallAction firewallaction = FirewallAction.Block; string action = ConsoleWriter.Default.PrintQuestion("Enter type of acces"); if (action.ToUpper() == "ALLOW" || action.ToUpper() == "BLOCK") { if (action.ToUpper() == "ALLOW") { firewallaction = FirewallAction.Allow; } if (action.ToUpper() == "BLOCK") { firewallaction = FirewallAction.Block; } string fullPath = ConsoleWriter.Default.PrintQuestion("Enter full path of exe file"); var rule = firewallInstance.CreateApplicationRule( firewallProfile, @$ "{name}", firewallaction, @$ "{fullPath}" ); rule.Direction = FirewallDirection.Outbound; firewallInstance.Rules.Add(rule); ConsoleWriter.Default.PrintSuccess("Rule successfully aded"); } else { ConsoleWriter.Default.PrintError("This type of acces is invalid"); } } else { ConsoleWriter.Default.PrintError("This name of rule is invalid"); } } else { ConsoleWriter.Default.PrintError("This profile name is invalid"); } ConsoleWriter.Default.PrintMessage("Press any key to get one step back."); // Вsозврат Console.ReadKey(); }), new ConsoleNavigationItem("Create port rule", (i, item) => { string name = ConsoleWriter.Default.PrintQuestion("Enter name of port rule"); if (name != "") { string action = ConsoleWriter.Default.PrintQuestion("Enter type of access"); FirewallAction firewallAction = FirewallAction.Block; if (action.ToUpper() == "ALLOW" || action.ToUpper() == "BLOCK") { if (action.ToUpper() == "ALLOW") { firewallAction = FirewallAction.Allow; } if (action.ToUpper() == "BLOCK") { firewallAction = FirewallAction.Block; } string port = ConsoleWriter.Default.PrintQuestion("Enter port"); ushort finallyPort = Convert.ToUInt16(port); string protocol = ConsoleWriter.Default.PrintQuestion("Enter protocol"); FirewallProtocol firewallProtocol = FirewallProtocol.TCP; if (protocol.ToUpper() == "UDP" || protocol.ToUpper() == "TCP") { if (protocol.ToUpper() == "UDP") { firewallProtocol = FirewallProtocol.UDP; } if (protocol.ToUpper() == "TCP") { firewallProtocol = FirewallProtocol.TCP; } var rule = firewallInstance.CreatePortRule( @$ "{name}", firewallAction, finallyPort, firewallProtocol ); firewallInstance.Rules.Add(rule); ConsoleWriter.Default.PrintSuccess("Protocol rule successfully aded"); } else { ConsoleWriter.Default.PrintError("This protocol is invalid"); } } else { ConsoleWriter.Default.PrintError("This type of acces is invalid"); } } else { ConsoleWriter.Default.PrintError("This name of port rule is invalid"); } // Возврат Console.ReadKey(); }), new ConsoleNavigationItem("Delete rule", (i, item) => { string deleted = ConsoleWriter.Default.PrintQuestion("Enter name of rule"); var rule = firewallInstance.Rules.SingleOrDefault(r => r.Name == deleted); if (rule != null) { firewallInstance.Rules.Remove(rule); ConsoleWriter.Default.PrintSuccess("Rule was successfully deleted"); } else { ConsoleWriter.Default.PrintError("This name rule is invalid"); } }) }, "Select an execution path."); }
public static void DoesRulesExist(bool removeFirewallRule, bool firstTimeRun, string nameOfApp, string localOfApp, string groupKey, string description, FirewallProtocol protocol) { if (FirewallManager.IsServiceRunning == true && !DetectLinux.LinuxDetected()) { if (FirewallStatus() == true) { CheckIfRuleExists(removeFirewallRule, firstTimeRun, nameOfApp, localOfApp, groupKey, description, FirewallDirection.Inbound, protocol, FirewallDirection.Inbound.ToString()); CheckIfRuleExists(removeFirewallRule, firstTimeRun, nameOfApp, localOfApp, groupKey, description, FirewallDirection.Outbound, protocol, FirewallDirection.Outbound.ToString()); } else { Log.Warning("WINDOWS FIREWALL: Turned Off [Not by Launcher]"); } } else if (FirewallManager.IsServiceRunning == false && !DetectLinux.LinuxDetected()) { Log.Warning("WINDOWS FIREWALL: Service is Stopped [Not by Launcher]"); } else if (DetectLinux.LinuxDetected()) { Log.Warning("WINDOWS FIREWALL: Not Supported On Linux"); } else { Log.Error("WINDOWS FIREWALL: Unknown Error Had Occured -> Check System Software"); } }
public static void CheckIfRuleExists(bool removeFirewallRule, bool firstTimeRun, string nameOfApp, string localOfApp, string groupKey, string description, FirewallDirection direction, FirewallProtocol protocol, string firewallLogNote) { //Remove Firewall Rules if (removeFirewallRule == true && firstTimeRun == false) { RemoveRules(nameOfApp, firewallLogNote); } //Add Firewall Rules else if (removeFirewallRule == false && firstTimeRun == true) { AddApplicationRule(nameOfApp, localOfApp, groupKey, description, direction, protocol, firewallLogNote); } //Removes a Specific Rule from Firewall (When switching locations) else if (removeFirewallRule == true && firstTimeRun == true) { if (RuleExist(nameOfApp) == true) { RemoveRules(nameOfApp, firewallLogNote); Log.Info("WINDOWS FIREWALL: Found " + nameOfApp + " {" + firewallLogNote + "} In Firewall"); } else if (RuleExist(nameOfApp) == false) { AddApplicationRule(nameOfApp, localOfApp, groupKey, description, direction, protocol, firewallLogNote); } } else if (removeFirewallRule == false && firstTimeRun == false) { Log.Info("WINDOWS FIREWALL: Already Exlcuded " + nameOfApp + " {" + firewallLogNote + "}"); } else { Log.Error("WINDOWS FIREWALL: Firewall Error - Check With Visual Studio for Error Debuging"); } }
private static void AddDefaultApplicationRule(string nameOfApp, string localOfApp, FirewallDirection direction, FirewallProtocol protocol, string firewallLogNote) { try { Log.Warning("WINDOWS FIREWALL: Falling back to 'LegacyStandard'"); var defaultRule = FirewallManager.Instance.CreateApplicationRule( FirewallProfiles.Domain | FirewallProfiles.Private | FirewallProfiles.Public, nameOfApp, FirewallAction.Allow, localOfApp, protocol); defaultRule.Direction = direction; FirewallManager.Instance.Rules.Add(defaultRule); Log.Warning("WINDOWS FIREWALL: Finished Adding " + nameOfApp + " to Firewall! {" + firewallLogNote + "}"); } catch (FirewallWASNotSupportedException Error) { Log.Error("WINDOWS FIREWALL: " + Error.Message); } }
public static void DoesRulesExist(bool removeFirewallRule, bool firstTimeRun, string nameOfApp, string localOfApp, string groupKey, string description, FirewallProtocol protocol) { CheckIfRuleExists(removeFirewallRule, firstTimeRun, nameOfApp, localOfApp, groupKey, description, FirewallDirection.Inbound, protocol, FirewallDirection.Inbound.ToString()); CheckIfRuleExists(removeFirewallRule, firstTimeRun, nameOfApp, localOfApp, groupKey, description, FirewallDirection.Outbound, protocol, FirewallDirection.Outbound.ToString()); }
public static void AddApplicationRule(string nameOfApp, string localOfApp, string groupKey, string description, FirewallDirection direction, FirewallProtocol protocol, string firewallLogNote) { if (Firewall.Instance.IsSupported) { Log.Info("WINDOWS FIREWALL: Supported Firewall Found"); var rule = new StandardRuleWin7(localOfApp, FirewallAction.Allow, direction, FirewallProfiles.Domain | FirewallProfiles.Private | FirewallProfiles.Public) { ApplicationName = localOfApp, Name = nameOfApp, Grouping = groupKey, Description = description, InterfaceTypes = FirewallInterfaceTypes.Lan | FirewallInterfaceTypes.RemoteAccess | FirewallInterfaceTypes.Wireless, Protocol = protocol }; if (direction == FirewallDirection.Inbound) { rule.EdgeTraversalOptions = EdgeTraversalAction.Allow; } Firewall.Instance.Rules.Add(rule); Log.Info("WINDOWS FIREWALL: Finished Adding " + nameOfApp + " to Firewall! {" + firewallLogNote + "}"); } else { AddDefaultApplicationRule(nameOfApp, localOfApp, direction, protocol, firewallLogNote); } }
private static void AddDefaultApplicationRule(string ruleName, string fileName, FirewallDirection direction, FirewallProtocol protocol) { var defaultRule = FirewallManager.Instance.CreateApplicationRule( FirewallProfiles.Domain | FirewallProfiles.Private | FirewallProfiles.Public, ruleName, FirewallAction.Allow, fileName, protocol); defaultRule.Direction = direction; FirewallManager.Instance.Rules.Add(defaultRule); }
/* * Firewall Methods */ // Did a little abstraction private IEnumerable <IFirewallRule> FindMatchingFirewallRules(ushort PortNumber, FirewallProtocol RuleProtocol) => FirewallManager.Instance.Rules.Where( Rule => Rule.LocalPorts.Contains(PortNumber) && Rule.Protocol.Equals(RuleProtocol) );