/// <summary> /// Configures the Firewall to allow requests from IP addresses as long as they are accessing a specific hostname. E.g. internal access to staging url /// </summary> /// <param name="rule">Base rule which gets validated when the client ip or hostname are not valid.</param> /// <param name="allowedClientIPAddresses">The list of valid client ip addresses</param> /// <param name="hostNamePartial">part of the hostname to check e.g. -staging.azurewebsites.net</param> public static IFirewallRule ExceptForHostnameFromClientIPs( this IFirewallRule rule, List <IPAddress> allowedClientIPAddresses, string hostNamePartial) { return(new HostnameSpecificIPAddressRule(rule, allowedClientIPAddresses, hostNamePartial)); }
/// <inheritdoc /> // ReSharper disable once MethodNameNotMeaningful // ReSharper disable once ExcessiveIndentation // ReSharper disable once MethodTooLong public void Add(IFirewallRule rule) { if (rule is FirewallLegacyApplicationRule applicationRule) { foreach (var firewallProfile in _firewallApplicationCollections.Keys) { if (applicationRule.Profiles.HasFlag(firewallProfile)) { foreach (var comObject in applicationRule.GetCOMObjects(firewallProfile)) { _firewallApplicationCollections[firewallProfile].Add(comObject); } } } } else if (rule is FirewallLegacyPortRule portRule) { foreach (var firewallProfile in _firewallPortCollections.Keys) { if (portRule.Profiles.HasFlag(firewallProfile)) { foreach (var comObject in portRule.GetCOMObjects(firewallProfile)) { _firewallPortCollections[firewallProfile].Add(comObject); } } } } else { throw new ArgumentException("Invalid argument type passed.", nameof(rule)); } }
public static Firewall TryCreate(string exePath) { if (!FirewallManager.IsServiceRunning) { MessageBox.Show(String.Format("Windows firewall service is not running")); return(null); } IFirewall inst; if (!FirewallManager.TryGetInstance(out inst)) { MessageBox.Show(String.Format("Cannot get windows firewall service instance")); return(null); } var rule = inst.Rules.FirstOrDefault(r => r.Name == RuleName); if (rule == null) { rule = CreateRule(inst, exePath); Console.WriteLine("Firewall rule has been created: {0}", rule); } else { Console.WriteLine("Firewall rule already exists: {0}", rule); } return(new Firewall(inst, rule)); }
/// <summary> /// Initialises a new instance of <see cref="CountryRule"/>. /// </summary> public CountryRule( IFirewallRule nextRule, IList <CountryCode> allowedCountries, string geoIP2FileName = null) { _nextRule = nextRule ?? throw new ArgumentNullException(nameof(nextRule)); if (allowedCountries == null) { throw new ArgumentNullException(nameof(allowedCountries)); } _allowedCountries = allowedCountries .Select(isoCode => isoCode.ToString()) .ToList(); var stream = geoIP2FileName != null ? new FileStream(geoIP2FileName, FileMode.Open) : Assembly .GetExecutingAssembly() .GetManifestResourceStream( "Firewall.GeoIP2.GeoLite2-Country.mmdb"); _databaseReader = new DatabaseReader(stream); }
private void InitFirewallRules() { _firewallRule = FirewallRulesEngine.DenyAllAccess(); if (_allow_cidrs != null && _allow_cidrs.Any()) { _firewallRule = _firewallRule.ExceptFromIPAddressRanges(_allow_cidrs.ToList()); } }
/// <summary> /// Initialises a new instance of <see cref="IPAddressRule"/>. /// </summary> public ReverseProxyClientIPAddressRangeRule(IFirewallRule nextRule, IList <CIDRNotation> cidrNotations, IList <IPAddress> ips, List <CIDRNotation> allowedClientIPAddressRanges, string reverseProxyHeader) { _nextRule = nextRule ?? throw new ArgumentNullException(nameof(nextRule)); _validReverseProxyCIDRs = cidrNotations ?? throw new ArgumentNullException(nameof(cidrNotations)); this.validReverseProxyIps = ips; this.allowedClientIPAddressRanges = allowedClientIPAddressRanges; _reverseProxyHeader = reverseProxyHeader; }
/// <summary> /// Initialises a new instance of <see cref="IPAddressRule"/>. /// </summary> public ReverseProxyClientIPAddressRule(IFirewallRule nextRule, IList <CIDRNotation> cidrs, IList <IPAddress> ipAddresses, List <IPAddress> allowedClientIPAddresses, string reverseProxyHeader) { _nextRule = nextRule ?? throw new ArgumentNullException(nameof(nextRule)); _reverseProxyIPAddresses = ipAddresses ?? throw new ArgumentNullException(nameof(ipAddresses)); this._allowedClientIPAddresses = allowedClientIPAddresses; _reverseProxyHeader = reverseProxyHeader; _reverseProxyCIDRs = cidrs; }
/// <summary> /// Instantiates a new object of type <see cref="FirewallMiddleware"/>. /// </summary> public FirewallMiddleware( RequestDelegate next, IFirewallRule ruleEngine, ILogger <FirewallMiddleware> logger) { _next = next ?? throw new ArgumentNullException(nameof(next)); _ruleEngine = ruleEngine ?? throw new ArgumentNullException(nameof(ruleEngine)); _logger = logger; }
private static void SetHttpRule(FirewallProfiles firewallProfile, ushort portNumber) { IFirewallRule rule = FirewallManager.Instance.CreateApplicationRule( FirewallManager.Instance.GetProfile(firewallProfile).Type, HTTP_DOT_SYS_INBOUND_RULE_NAME, FirewallAction.Allow, "SYSTEM"); rule.Direction = FirewallDirection.Inbound; rule.Protocol = FirewallProtocol.TCP; rule.LocalPorts = new ushort[1] { portNumber }; // Create an array containing the port number TL.LogMessage("SetHttpSysFireWallRule", "Successfully created inbound rule"); // Add edge traversal permission to the inbound rule so that the rule will apply to packets delivered in encapsulated transmission formats such as VPNs if (rule is FirewallWASRule) { TL.LogMessage("SetHttpSysFireWallRule", "Firewall rule is a standard rule"); ((FirewallWASRule)rule).EdgeTraversal = true; ((FirewallWASRule)rule).Grouping = GROUP_NAME; TL.LogMessage("SetHttpSysFireWallRule", $"Edge traversal set {true}, Group name set to: {GROUP_NAME}"); } else { TL.LogMessage("SetHttpSysFireWallRule", "Firewall rule is not a standard rule"); } if (rule is FirewallWASRuleWin7) { TL.LogMessage("SetHttpSysFireWallRule", "Firewall rule is a WIN7 rule"); ((FirewallWASRuleWin7)rule).EdgeTraversalOptions = EdgeTraversalAction.Allow; ((FirewallWASRuleWin7)rule).Grouping = GROUP_NAME; TL.LogMessage("SetHttpSysFireWallRule", $"Edge traversal set {true}, Group name set to: {GROUP_NAME}"); } else { TL.LogMessage("SetHttpSysFireWallRule", "Firewall rule is not a WIN7 rule"); } if (rule is FirewallWASRuleWin8) { TL.LogMessage("SetHttpSysFireWallRule", "Firewall rule is a WIN8 rule"); ((FirewallWASRuleWin8)rule).EdgeTraversalOptions = EdgeTraversalAction.Allow; ((FirewallWASRuleWin8)rule).Grouping = GROUP_NAME; TL.LogMessage("SetHttpSysFireWallRule", $"Edge traversal set {true}, Group name set to: {GROUP_NAME}"); } else { TL.LogMessage("SetHttpSysFireWallRule", "Firewall rule is not a WIN8 rule"); } TL.LogMessage("SetHttpSysFireWallRule", "Successfully created inbound firewall rule"); FirewallManager.Instance.Rules.Add(rule); TL.LogMessage("SetHttpSysFireWallRule", $"Successfully added inbound rule for HTTP.SYS permitting listening on port {portNumber} for {firewallProfile}"); TL.BlankLine(); }
/// <summary> /// Configures the Firewall to allow requests from IP addresses which belong to Cloudflare. /// </summary> /// <param name="rule">Base rule which gets validated when the request did not come from Cloudflare.</param> /// <param name="ipv4ListUrl">URL which returns a list of all Cloudflare IPv4 address ranges.</param> /// <param name="ipv6ListUrl">URL which returns a list of all Cloudflare IPv6 address ranges.</param> public static IFirewallRule ExceptFromCloudflare( this IFirewallRule rule, string ipv4ListUrl = null, string ipv6ListUrl = null) { var helper = new CloudflareHelper(new HttpClient()); var(ips, cidrs) = helper.GetIPAddressRangesAsync(ipv4ListUrl, ipv6ListUrl).Result; return(new IPAddressRule(new IPAddressRangeRule(rule, cidrs), ips)); }
/// <summary> /// Configures the Firewall to allow requests from IP addresses proxied through Cloudflare. /// </summary> /// <param name="rule">Base rule which gets validated when the request did not come from Cloudflare or the client ip is not valid.</param> /// <param name="allowedClientIPAddressRanges">Address ranges of client ips proxied through cloudflare</param> /// <param name="ipv4ListUrl">URL which returns a list of all Cloudflare IPv4 address ranges.</param> /// <param name="ipv6ListUrl">URL which returns a list of all Cloudflare IPv6 address ranges.</param> public static IFirewallRule ExceptFromCloudflareAndClientIPRanges( this IFirewallRule rule, List <CIDRNotation> allowedClientIPAddressRanges, string ipv4ListUrl = null, string ipv6ListUrl = null) { var helper = new CloudflareHelper(new HttpClient()); var(ips, cidrs) = helper.GetIPAddressRangesAsync(ipv4ListUrl, ipv6ListUrl).Result; return(new ReverseProxyClientIPAddressRangeRule(rule, cidrs, ips, allowedClientIPAddressRanges, "CF-Connecting-IP")); }
/// <summary> /// Initialises a new instance of <see cref="HostnameSpecificIPAddressRule"/>. /// </summary> public HostnameSpecificIPAddressRule(IFirewallRule nextRule, IList <IPAddress> ipAddresses, string hostnamePartial) { _nextRule = nextRule ?? throw new ArgumentNullException(nameof(nextRule)); _ipAddresses = ipAddresses ?? throw new ArgumentNullException(nameof(ipAddresses)); _hostNamePartial = hostnamePartial; }
/// <summary> /// Initialises a new instance of <see cref="LocalhostRule"/>. /// </summary> public LocalhostRule(IFirewallRule nextRule) =>
/// <summary> /// Adds the <see cref="FirewallMiddleware"/> to the ASP.NET Core pipeline. /// <para>The Firewall should be registered after global error handling and before any other middleware.</para> /// </summary> /// <param name="builder">The application builder which is used to register all ASP.NET Core middleware.</param> /// <param name="rulesEngine">The Firewall rules which should be used for request filtering.</param> public static IApplicationBuilder UseFirewall( this IApplicationBuilder builder, IFirewallRule rulesEngine) => builder.UseMiddleware <FirewallMiddleware>(rulesEngine);
private static void SetLocalServerFireWallOutboundRule(string applicationPath) { try // Make sure that we still try and set the firewall rules even if we bomb out trying to get information on the firewall configuration { TL.LogMessage("QueryFireWall", string.Format("Firewall version: {0}", FirewallManager.Version.ToString())); // Log the firewall version in use foreach (IFirewallProfile profile in FirewallManager.Instance.Profiles) { TL.LogMessage("QueryFireWall", string.Format("Found current firewall profile {0}, enabled: {1}", profile.Type.ToString(), profile.IsActive)); } COMTypeResolver cOMTypeResolver = new COMTypeResolver(); IFirewallProductsCollection thirdPartyFirewalls = FirewallManager.GetRegisteredProducts(cOMTypeResolver); TL.LogMessage("QueryFireWall", string.Format("number of third party firewalls: {0}", thirdPartyFirewalls.Count)); foreach (FirewallProduct firewall in thirdPartyFirewalls) { TL.LogMessage("QueryFireWall", $"Found third party firewall: {firewall.Name} - {firewall.FriendlyName}"); //foreach (IFirewallProfile profile in firewall.) //{ // TL.LogMessage("QueryFireWall", string.Format("Found third party firewall profile {0}, enabled: {1}", profile.Type.ToString(), profile.IsActive)); //} } } catch (Exception ex) { TL.LogMessageCrLf("QueryFireWall", "Exception: " + ex.ToString()); } TL.BlankLine(); try { if ((new WindowsPrincipal(WindowsIdentity.GetCurrent())).IsInRole(WindowsBuiltInRole.Administrator)) // Application is being run with Administrator privilege so go ahead and set the firewall rules { // Check whether the specified file exists if (File.Exists(applicationPath)) // The file does exist so process it { string applicationPathFull = Path.GetFullPath(applicationPath); TL.LogMessage("SetFireWallOutboundRule", string.Format("Supplied path: {0}, full path: {1}", applicationPath, applicationPathFull)); // Now clear up previous instances of this rule IEnumerable <IFirewallRule> query = FirewallManager.Instance.Rules.Where(ruleName => ruleName.Name.ToUpperInvariant().StartsWith(LOCAL_SERVER_OUTBOUND_RULE_NAME.ToUpperInvariant())); List <IFirewallRule> queryCopy = query.ToList(); foreach (IFirewallRule existingRule in queryCopy) { TL.LogMessage("SetFireWallOutboundRule", string.Format("Found rule: {0}", existingRule.Name)); FirewallManager.Instance.Rules.Remove(existingRule); // Delete the rule TL.LogMessage("SetFireWallOutboundRule", string.Format("Deleted rule: {0}", existingRule.Name)); } IFirewallRule rule = FirewallManager.Instance.CreateApplicationRule(FirewallManager.Instance.GetProfile(FirewallProfiles.Domain | FirewallProfiles.Private | FirewallProfiles.Public).Type, LOCAL_SERVER_OUTBOUND_RULE_NAME, FirewallAction.Allow, applicationPathFull); rule.Direction = FirewallDirection.Outbound; // Add the group name to the outbound rule if (rule is FirewallWASRule) //Rules.StandardRule) { TL.LogMessage("SetHttpSysFireWallRule", "Firewall rule is a standard rule"); ((FirewallWASRule)rule).Grouping = GROUP_NAME; TL.LogMessage("SetHttpSysFireWallRule", $"Group name set to: {GROUP_NAME}"); } else { TL.LogMessage("SetHttpSysFireWallRule", "Firewall rule is not a standard rule"); } if (rule is FirewallWASRuleWin7) { TL.LogMessage("SetHttpSysFireWallRule", "Firewall rule is a WIN7 rule"); ((FirewallWASRuleWin7)rule).Grouping = GROUP_NAME; TL.LogMessage("SetHttpSysFireWallRule", $"Group name set to: {GROUP_NAME}"); } else { TL.LogMessage("SetHttpSysFireWallRule", "Firewall rule is not a WIN7 rule"); } if (rule is FirewallWASRuleWin8) { TL.LogMessage("SetHttpSysFireWallRule", "Firewall rule is a WIN8 rule"); ((FirewallWASRuleWin8)rule).Grouping = GROUP_NAME; TL.LogMessage("SetHttpSysFireWallRule", $"Group name set to: {GROUP_NAME}"); } else { TL.LogMessage("SetHttpSysFireWallRule", "Firewall rule is not a WIN8 rule"); } TL.LogMessage("SetFireWallOutboundRule", "Successfully created outbound rule"); FirewallManager.Instance.Rules.Add(rule); TL.LogMessage("SetFireWallOutboundRule", string.Format("Successfully added outbound rule for {0}", applicationPathFull)); } else { TL.LogMessage("SetFireWallOutboundRule", string.Format("The specified file does not exist: {0}", applicationPath)); Console.WriteLine("The specified file does not exist: {0}", applicationPath); } } else { TL.LogMessage("SetFireWallOutboundRule", "Not running as Administrator so unable to set firewall rules."); Console.WriteLine("Not running as Administrator so unable to set firewall rules."); } TL.BlankLine(); } catch (Exception ex) { TL.LogMessageCrLf("SetFireWallOutboundRule", "Exception: " + ex.ToString()); Console.WriteLine("SetFireWallOutboundRule threw an exception: " + ex.Message); } }
/// <summary> /// Configures the Firewall to allow requests from localhost. /// </summary> public static IFirewallRule ExceptFromLocalhost(this IFirewallRule rule) => new LocalhostRule(rule);
/// <summary> /// Adds the <see cref="FirewallMiddleware"/> to the ASP.NET Core pipeline. /// <para>The Firewall should be registered after global error handling and before any other middleware.</para> /// </summary> /// <param name="builder">The application builder which is used to register all ASP.NET Core middleware.</param> /// <param name="rulesEngine">The Firewall rules which should be used for request filtering.</param> /// <param name="accessDeniedDelegate">An optional <see cref="RequestDelegate"/> for blocked requests..</param> public static IApplicationBuilder UseFirewall( this IApplicationBuilder builder, IFirewallRule rulesEngine, RequestDelegate accessDeniedDelegate) => builder.UseMiddleware <FirewallMiddleware>(rulesEngine, accessDeniedDelegate);
/// <inheritdoc /> public bool Contains(IFirewallRule item) { return(this.Any(rule => rule.Equals(item))); }
/// <summary> /// Initialises a new instance of <see cref="CustomRule"/>. /// </summary> public CustomRule(IFirewallRule nextRule, Func <HttpContext, bool> filter) { _nextRule = nextRule ?? throw new ArgumentNullException(nameof(nextRule)); _filter = filter ?? throw new ArgumentNullException(nameof(filter)); }
private Firewall(IFirewall _inst, IFirewallRule _rule) { inst = _inst; rule = _rule; Console.WriteLine("Firewall instance has been created"); }
public EditRuleForm(IFirewallRule rule) { InitializeComponent(); propertyGrid1.SelectedObject = rule; }
/// <summary> /// Configures the Firewall to allow requests which satisfy a custom <paramref name="filter"/>. /// </summary> public static IFirewallRule ExceptWhen( this IFirewallRule rule, Func <HttpContext, bool> filter) { return(new CustomRule(rule, filter)); }
/// <summary> /// Initialises a new instance of <see cref="IPAddressRangeRule"/>. /// </summary> public IPAddressRangeRule(IFirewallRule nextRule, IList <CIDRNotation> cidrNotations) { _nextRule = nextRule ?? throw new ArgumentNullException(nameof(nextRule)); _cidrNotations = cidrNotations ?? throw new ArgumentNullException(nameof(cidrNotations)); }
/// <summary> /// Configures the Firewall to allow requests from localhost. /// </summary> public static IFirewallRule ExceptFromLocalhost(this IFirewallRule rule) { return(new LocalhostRule(rule)); }
/// <summary> /// Configures the Firewall to allow requests from IP addresses which belong to a list of specific IP address ranges. /// </summary> public static IFirewallRule ExceptFromIPAddressRanges( this IFirewallRule rule, IList <CIDRNotation> cidrNotations) { return(new IPAddressRangeRule(rule, cidrNotations)); }
/// <summary> /// Configures the Firewall to allow requests from specific IP addresses. /// </summary> public static IFirewallRule ExceptFromIPAddresses( this IFirewallRule rule, IList <IPAddress> ipAddresses) { return(new IPAddressRule(rule, ipAddresses)); }
/// <summary> /// Initialises a new instance of <see cref="IPAddressRule"/>. /// </summary> public IPAddressRule(IFirewallRule nextRule, IList <IPAddress> ipAddresses) { _nextRule = nextRule ?? throw new ArgumentNullException(nameof(nextRule)); _ipAddresses = ipAddresses ?? throw new ArgumentNullException(nameof(ipAddresses)); }
/// <summary> /// Configures the Firewall to allow requests from specific countries. /// </summary> public static IFirewallRule ExceptFromCountries( this IFirewallRule rule, IList <CountryCode> countries) { return(new CountryRule(rule, countries)); }