public void TestStart() { firewall = IPBanFirewallUtility.CreateFirewall(firewallAndOsType, "IPBanTest_"); // clear all blocks firewall.BlockIPAddresses(new string[0]).Sync(); }
public void TestStart() { firewall = IPBanFirewallUtility.CreateFirewall(); Assert.AreNotEqual(typeof(IPBanMemoryFirewall), firewall.GetType()); // clear all blocks firewall.Truncate(); }
/// <summary> /// Create a firewall /// </summary> /// <param name="rulePrefix">Rule prefix or null for default</param> /// <returns>Firewall</returns> public static IIPBanFirewall CreateFirewall(string rulePrefix = null, IIPBanFirewall existing = null) { try { int priority = int.MinValue; Type firewallType = typeof(IIPBanFirewall); IReadOnlyCollection <Type> allTypes = ExtensionMethods.GetAllTypes(); var q = from fwType in allTypes where fwType.IsPublic && fwType != firewallType && firewallType.IsAssignableFrom(fwType) && fwType.GetCustomAttribute <RequiredOperatingSystemAttribute>() != null && fwType.GetCustomAttribute <RequiredOperatingSystemAttribute>().IsMatch select new { FirewallType = fwType, OS = fwType.GetCustomAttribute <RequiredOperatingSystemAttribute>(), Name = fwType.GetCustomAttribute <CustomNameAttribute>() }; var array = q.OrderBy(f => f.OS.Priority).ToArray(); foreach (var result in array) { // look up the requested firewall by os name bool matchPriority = priority < result.OS.Priority; if (matchPriority) { // if IsAvailable method is provided, attempt to call MethodInfo available = result.FirewallType.GetMethod("IsAvailable", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy); if (available != null) { try { if (!Convert.ToBoolean(available.Invoke(null, null))) { continue; } } catch { continue; } } firewallType = result.FirewallType; priority = result.OS.Priority; } } if (firewallType is null || firewallType == typeof(IIPBanFirewall)) { throw new ArgumentException("Firewall is null, at least one type should implement IIPBanFirewall"); } if (existing != null && existing.GetType().Equals(firewallType)) { return(existing); } return(Activator.CreateInstance(firewallType, new object[] { rulePrefix }) as IIPBanFirewall); } catch (Exception ex) { throw new ArgumentException("Unable to create firewall, please double check your Firewall configuration property", ex); } }
/// <summary> /// Create a firewall /// </summary> /// <param name="osAndFirewall">Dictionary of string operating system name (Windows, Linux, OSX) and firewall class</param> /// <param name="rulePrefix">Rule prefix or null for default</param> /// <returns>Firewall</returns> public static IIPBanFirewall CreateFirewall(IReadOnlyDictionary <string, string> osAndFirewall, string rulePrefix) { bool foundFirewallType = false; int priority = int.MinValue; Type firewallType = typeof(IIPBanFirewall); var q = from a in AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()) where a != firewallType && firewallType.IsAssignableFrom(a) && a.GetCustomAttribute <RequiredOperatingSystemAttribute>() != null && a.GetCustomAttribute <RequiredOperatingSystemAttribute>().IsValid select new { Type = a, OS = a.GetCustomAttribute <RequiredOperatingSystemAttribute>(), Name = a.GetCustomAttribute <CustomNameAttribute>() }; foreach (var result in q) { firewallType = result.Type; // look up the requested firewall by os name if (osAndFirewall.TryGetValue(IPBanOS.Name, out string firewallToUse) && priority < result.OS.Priority && // check type name or custom name attribute name, at least one must match (firewallType.Name == firewallToUse || (result.Name != null && (result.Name.Name ?? string.Empty).Equals(firewallToUse, StringComparison.OrdinalIgnoreCase)))) { priority = result.OS.Priority; foundFirewallType = true; } } if (firewallType == null) { throw new ArgumentException("Firewall is null, at least one type should implement IIPBanFirewall"); } else if (osAndFirewall.Count != 0 && !foundFirewallType) { string typeString = string.Join(',', osAndFirewall.Select(kv => kv.Key + ":" + kv.Value)); throw new ArgumentException("Unable to find firewalls of types: " + typeString + ", osname: " + IPBanOS.Name); } IIPBanFirewall firewall = Activator.CreateInstance(firewallType) as IIPBanFirewall; firewall.Initialize(string.IsNullOrWhiteSpace(rulePrefix) ? "IPBan_" : rulePrefix); return(firewall); }
/// <summary> /// Constructor /// </summary> /// <param name="firewall">The firewall to block with</param> /// <param name="whitelistChecker">Whitelist checker</param> /// <param name="httpRequestMaker">Http request maker for http uris, can leave null if uri is file</param> /// <param name="rulePrefix">Firewall rule prefix</param> /// <param name="interval">Interval to check uri for changes</param> /// <param name="uri">Uri, can be either file or http(s).</param> public IPBanUriFirewallRule(IIPBanFirewall firewall, IIsWhitelisted whitelistChecker, IHttpRequestMaker httpRequestMaker, string rulePrefix, TimeSpan interval, Uri uri) { this.firewall = firewall.ThrowIfNull(); this.whitelistChecker = whitelistChecker.ThrowIfNull(); this.httpRequestMaker = httpRequestMaker; RulePrefix = rulePrefix.ThrowIfNull(); Uri = uri.ThrowIfNull(); Interval = (interval.TotalSeconds < 5.0 ? fiveSeconds : interval); if (!uri.IsFile) { // ensure uri ends with slash if (!uri.ToString().EndsWith("/")) { uri = new Uri(uri.ToString() + "/"); } httpClient = new HttpClient { BaseAddress = uri, Timeout = thirtySeconds }; } }
/// <summary> /// Create a firewall /// </summary> /// <param name="osAndFirewall">Dictionary of string operating system name (Windows, Linux, OSX) and firewall class</param> /// <param name="rulePrefix">Rule prefix or null for default</param> /// <returns>Firewall</returns> public static IIPBanFirewall CreateFirewall(IReadOnlyDictionary <string, string> osAndFirewall, string rulePrefix = null, IIPBanFirewall existing = null) { try { bool foundFirewallType = false; int priority = int.MinValue; Type firewallType = typeof(IIPBanFirewall); List <Type> allTypes = ExtensionMethods.GetAllTypes(); var q = from fwType in allTypes where fwType.IsPublic && fwType != firewallType && firewallType.IsAssignableFrom(fwType) && fwType.GetCustomAttribute <RequiredOperatingSystemAttribute>() != null && fwType.GetCustomAttribute <RequiredOperatingSystemAttribute>().IsValid select new { FirewallType = fwType, OS = fwType.GetCustomAttribute <RequiredOperatingSystemAttribute>(), Name = fwType.GetCustomAttribute <CustomNameAttribute>() }; var array = q.ToArray(); foreach (var result in array) { // look up the requested firewall by os name bool matchPriority = priority < result.OS.Priority; if (matchPriority) { bool matchName = true; if (osAndFirewall != null && osAndFirewall.Count != 0 && (osAndFirewall.TryGetValue(OSUtility.Instance.Name, out string firewallToUse) || osAndFirewall.TryGetValue("*", out firewallToUse))) { matchName = result.Name.Name.Equals(firewallToUse, StringComparison.OrdinalIgnoreCase); } if (matchName) { // if IsAvailable method is provided, attempt to call MethodInfo available = result.FirewallType.GetMethod("IsAvailable", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy); if (available != null) { try { if (!Convert.ToBoolean(available.Invoke(null, null))) { continue; } } catch { continue; } } firewallType = result.FirewallType; priority = result.OS.Priority; foundFirewallType = true; } } } if (firewallType is null) { throw new ArgumentException("Firewall is null, at least one type should implement IIPBanFirewall"); } else if (osAndFirewall.Count != 0 && !foundFirewallType) { string typeString = string.Join(',', osAndFirewall.Select(kv => kv.Key + ":" + kv.Value)); throw new ArgumentException("Unable to find firewalls of types: " + typeString + ", osname: " + OSUtility.Instance.Name); } if (existing != null && existing.GetType().Equals(firewallType)) { return(existing); } return(Activator.CreateInstance(firewallType, new object[] { rulePrefix }) as IIPBanFirewall); } catch (Exception ex) { throw new ArgumentException("Unable to create firewall, please double check your Firewall configuration property", ex); } }
/// <summary> /// Create a firewall /// </summary> /// <param name="rulePrefix">Rule prefix or null for default</param> /// <returns>Firewall</returns> public static IIPBanFirewall CreateFirewall(string rulePrefix = null, IIPBanFirewall existing = null) { try { int priority = int.MinValue; Type firewallType = typeof(IIPBanFirewall); Type fallbackType = null; IReadOnlyCollection <Type> allTypes = ExtensionMethods.GetAllTypes(); var q = from fwType in allTypes where fwType.IsPublic && fwType != firewallType && firewallType.IsAssignableFrom(fwType) && fwType.GetCustomAttribute <RequiredOperatingSystemAttribute>() != null && fwType.GetCustomAttribute <RequiredOperatingSystemAttribute>().IsMatch select new { FirewallType = fwType, OS = fwType.GetCustomAttribute <RequiredOperatingSystemAttribute>(), Name = fwType.GetCustomAttribute <CustomNameAttribute>() }; var array = q.OrderBy(f => f.OS.Priority).ToArray(); foreach (var result in array) { // look up the requested firewall by os name bool matchPriority = priority < result.OS.Priority; if (matchPriority) { // if IsAvailable method is provided, attempt to call MethodInfo available = result.FirewallType.GetMethod("IsAvailable", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy); if (available != null) { try { if (!Convert.ToBoolean(available.Invoke(null, null))) { continue; } } catch { continue; } } firewallType = result.FirewallType; priority = result.OS.Priority; fallbackType = result.OS.FallbackFirewallType; } } if (firewallType is null || firewallType == typeof(IIPBanFirewall)) { throw new ArgumentException("Firewall is null, at least one type should implement IIPBanFirewall"); } RequiredOperatingSystemAttribute fallbackAttr = fallbackType?.GetCustomAttribute <RequiredOperatingSystemAttribute>(); Type existingType = existing?.GetType(); if (existingType != null && // if we have an existing firewall and ( firewallType.Equals(existingType)) || // if the existing firewall is the desired type or ( fallbackType != null && // we have a fallback type and ( fallbackType.Equals(existingType) || // the existing firewall is the fallback type or ( // the fallback firewall has another fallback firewall and it matches the existing type fallbackAttr?.FallbackFirewallType != null && fallbackAttr.FallbackFirewallType.Equals(existingType) ) ) ) ) { return(existing); } try { return(Activator.CreateInstance(firewallType, new object[] { rulePrefix }) as IIPBanFirewall); } catch (Exception ex) { // see if there's a fallback if (fallbackType is null) { throw; } Logger.Error(ex, "Failed to create firewall of type {0}, falling back to firewall type {1}", firewallType, fallbackType); try { return(Activator.CreateInstance(fallbackType, new object[] { rulePrefix }) as IIPBanFirewall); } catch (Exception ex2) { // last fallback attempt if (fallbackAttr?.FallbackFirewallType is null) { throw; } Logger.Error(ex2, "Failed to create firewall of type {0}, falling back to final attempt with firewall type {1}", fallbackType, fallbackAttr.FallbackFirewallType); return(Activator.CreateInstance(fallbackAttr.FallbackFirewallType, new object[] { rulePrefix }) as IIPBanFirewall); } } } catch (Exception ex) { throw new ArgumentException("Unable to create firewall, please double check your Firewall configuration property", ex); } }
/// <inheritdoc /> public IIPBanFirewall CreateFirewall(IPBanConfig config, IIPBanFirewall previousFirewall) { return(IPBanFirewallUtility.CreateFirewall(config.FirewallRulePrefix, previousFirewall)); }
private void LoadFirewall(IPBanConfig oldConfig) { IIPBanFirewall existing = Firewall; Firewall = FirewallCreator.CreateFirewall(Config, Firewall); if (existing != Firewall) { AddUpdater(Firewall); Logger.Warn("Loaded firewall type {0}", Firewall.GetType()); if (existing != null) { RemoveUpdater(existing); // transfer banned ip to new firewall Firewall.BlockIPAddresses(null, ipDB.EnumerateBannedIPAddresses()).Sync(); } } if (oldConfig is null) { // clear out all previous custom rules foreach (string rule in Firewall.GetRuleNames(Firewall.RulePrefix + "EXTRA_").ToArray()) { Firewall.DeleteRule(rule); } } else { // check for updated / new / removed block rules List <string> deleteList = new List <string>(oldConfig.ExtraRules.Select(r => r.Name)); // cleanup rules that are no longer in the config foreach (string newRule in Config.ExtraRules.Select(r => r.Name)) { deleteList.Remove(newRule); } foreach (string rule in deleteList) { foreach (string ruleName in Firewall.GetRuleNames(rule).ToArray()) { Firewall.DeleteRule(ruleName); } } } // ensure firewall is cleared out if needed - will only execute once UpdateBannedIPAddressesOnStart(); // ensure windows event viewer is setup if needed - will only execute once SetupWindowsEventViewer(); // add/update global rules Firewall.AllowIPAddresses("GlobalWhitelist", Config.Whitelist); Firewall.BlockIPAddresses("GlobalBlacklist", Config.BlackList); // add/update user specified rules foreach (IPBanFirewallRule rule in Config.ExtraRules) { if (rule.Block) { Firewall.BlockIPAddresses(rule.Name, rule.IPAddressRanges, rule.AllowPortRanges); } else { Firewall.AllowIPAddresses(rule.Name, rule.IPAddressRanges, rule.AllowPortRanges); } } }
/// <inheritdoc /> public IIPBanFirewall CreateFirewall(System.Collections.Generic.IReadOnlyCollection <Type> allTypes, IPBanConfig config, IIPBanFirewall previousFirewall) { return(IPBanFirewallUtility.CreateFirewall(allTypes, config.FirewallRulePrefix, previousFirewall)); }