private int RunProcess(string program, bool requireExitCode, out IReadOnlyList <string> lines, string commandLine, params object[] args) { commandLine = program + " " + string.Format(commandLine, args); commandLine = "-c \"" + commandLine.Replace("\"", "\\\"") + "\""; IPBanLog.Debug("Running firewall process: /bin/bash {0}", commandLine); Process p = new Process { StartInfo = new ProcessStartInfo { FileName = "/bin/bash", Arguments = commandLine, UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true } }; p.Start(); List <string> lineList = new List <string>(); string line; while ((line = p.StandardOutput.ReadLine()) != null) { lineList.Add(line); } lines = lineList; p.WaitForExit(); if (requireExitCode && p.ExitCode != 0) { IPBanLog.Error("Process {0} had exit code {1}", commandLine, p.ExitCode); } return(p.ExitCode); }
/// <summary> /// Update - if the text file path exists, all ip addresses from each line will be banned /// </summary> public async Task Update() { try { if (File.Exists(textFilePath)) { string[] lines = (await File.ReadAllLinesAsync(textFilePath)).Where(l => IPAddress.TryParse(l, out _)).ToArray(); IPBanLog.Warn("Queueing {0} ip addresses to ban from {1} file", lines.Length, textFilePath); List <IPAddressLogEvent> bans = new List <IPAddressLogEvent>(); foreach (string[] pieces in lines.Select(l => l.Split(','))) { if (pieces.Length < 1) { continue; } string ipAddress = pieces[0]; string source = (pieces.Length < 2 ? "Block" : pieces[1]); bans.Add(new IPAddressLogEvent(ipAddress, string.Empty, source, 1, IPAddressEventType.Blocked)); } service.AddIPAddressLogEvents(bans); File.Delete(textFilePath); } } catch (Exception ex) { IPBanLog.Error(ex); } }
private bool DeleteRules(string ruleNamePrefix, int startIndex = 0) { try { lock (policy) { foreach (INetFwRule rule in EnumerateRulesMatchingPrefix(ruleNamePrefix).ToArray()) { try { Match match = Regex.Match(rule.Name, $"^{ruleNamePrefix}(?<num>[0-9]+)$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); if (match.Success && int.TryParse(match.Groups["num"].Value, NumberStyles.None, CultureInfo.InvariantCulture, out int num) && num >= startIndex) { policy.Rules.Remove(rule.Name); } } catch { } } } return(true); } catch (Exception ex) { IPBanLog.Error(ex); return(false); } }
private List <uint> LoadIPAddresses(string ruleName, string action, string hashType, int maxCount) { List <uint> ipAddresses = new List <uint>(); try { if (hashType != "ip") { throw new ArgumentException("Can only load hash of type 'ip'"); } CreateOrUpdateRule(ruleName, action, hashType, maxCount, null, default); // copy ip addresses from the rule to the set string fileName = GetSetFileName(ruleName); if (File.Exists(fileName)) { uint value; foreach (string line in File.ReadLines(fileName).Skip(1)) { string[] pieces = line.Split(' '); if (pieces.Length > 2 && pieces[0] == "add" && (value = IPBanFirewallUtility.ParseIPV4(pieces[2])) != 0) { ipAddresses.Add(value); } } } } catch (Exception ex) { IPBanLog.Error(ex); } return(ipAddresses); }
public bool IsIPAddressAllowed(string ipAddress) { try { lock (policy) { for (int i = 0; ; i += MaxIpAddressesPerRule) { string ruleName = AllowRulePrefix + i.ToString(CultureInfo.InvariantCulture); try { INetFwRule rule = policy.Rules.Item(ruleName); if (rule == null) { break; } else if (rule.RemoteAddresses.Contains(ipAddress)) { return(true); } } catch { // OK, rule does not exist } } } } catch (Exception ex) { IPBanLog.Error(ex); } return(false); }
private bool DeleteRules(string rulePrefix, int startIndex = 0) { try { lock (policy) { for (int i = startIndex; ; i += MaxIpAddressesPerRule) { string ruleName = rulePrefix + i.ToString(CultureInfo.InvariantCulture); try { INetFwRule rule = policy.Rules.Item(ruleName); if (rule == null) { break; } policy.Rules.Remove(ruleName); } catch { break; } } } return(true); } catch (Exception ex) { IPBanLog.Error(ex); return(false); } }
/// <summary> /// Set a field / variable from configuration manager app settings. If null or not found, nothing is changed. /// </summary> /// <typeparam name="T">Type of value to set</typeparam> /// <param name="key">Key</param> /// <param name="value">Value</param> /// <param name="defaultValue">Default value if array was empty</param> public void GetConfigArray <T>(string key, ref T[] value, T[] defaultValue) { try { var converter = TypeDescriptor.GetConverter(typeof(T)); string[] items = (appSettings[key] ?? string.Empty).Split('|', ';', ','); List <T> list = new List <T>(); foreach (string item in items) { string normalizedItem = item.Trim(); if (normalizedItem.Length != 0) { list.Add((T)converter.ConvertFromInvariantString(normalizedItem)); } } if (list.Count == 0) { value = (defaultValue ?? list.ToArray()); } else { value = list.ToArray(); } } catch (Exception ex) { IPBanLog.Error(ex, "Error deserializing appSettings key {0}", key); } }
private void SetupEventLogWatcher() { try { List <string> ignored = new List <string>(); string queryString = GetEventLogQueryString(ignored); if (queryString != previousQueryString) { IPBanLog.Warn("Event viewer query string: {0}", queryString); foreach (string path in ignored) { IPBanLog.Warn("Ignoring event viewer path {0}", path); } watcher?.Dispose(); query = new EventLogQuery(null, PathType.LogName, queryString); watcher = new EventLogWatcher(query); watcher.EventRecordWritten += EventRecordWritten; watcher.Enabled = true; previousQueryString = queryString; } } catch (Exception ex) { IPBanLog.Error("Failed to create event viewer watcher", ex); } }
private void EventRecordWritten(object sender, EventRecordWrittenEventArgs e) { try { if (e != null && e.EventRecord != null) { EventRecord rec = e.EventRecord; string xml = null; try { xml = rec.ToXml(); } catch { } if (xml != null) { ProcessEventViewerXml(xml); } } } catch (Exception ex) { IPBanLog.Error(ex); } }
public async Task <bool> BlockIPAddresses(string ruleNamePrefix, IEnumerable <IPAddressRange> ranges, IEnumerable <PortRange> allowedPorts, CancellationToken cancelToken = default) { bool result = await firewall6.BlockIPAddresses(ruleNamePrefix, ranges, allowedPorts, cancelToken); if (!result) { return(false); } if (string.IsNullOrWhiteSpace(ruleNamePrefix)) { return(false); } try { string ruleName = RulePrefix + "_" + ruleNamePrefix + "_0"; UpdateRule(ruleName, "DROP", ranges.Select(r => r.ToCidrString()), null, "net", blockRuleRangesMaxCount, true, allowedPorts, cancelToken, out result); return(result); } catch (Exception ex) { IPBanLog.Error(ex); return(false); } }
public Task <bool> BlockIPAddresses(string ruleNamePrefix, IEnumerable <IPAddressRange> ranges, IEnumerable <PortRange> allowedPorts, CancellationToken cancelToken = default) { if (string.IsNullOrWhiteSpace(ruleNamePrefix)) { return(Task.FromResult(false)); } try { string prefix = (RulePrefix + ruleNamePrefix).TrimEnd('_') + "_"; // recreate rules int counter = 0; int index = 0; StringBuilder ipList = new StringBuilder(); foreach (IPAddressRange range in ranges) { if (cancelToken.IsCancellationRequested) { throw new OperationCanceledException(cancelToken); } ipList.Append(range.ToCidrString()); ipList.Append(','); if (++counter == MaxIpAddressesPerRule) { ipList.Length--; // remove ending comma GetOrCreateRule(prefix + index.ToString(CultureInfo.InvariantCulture), ipList.ToString(), NET_FW_ACTION_.NET_FW_ACTION_BLOCK, allowedPorts); counter = 0; index += MaxIpAddressesPerRule; ipList.Clear(); } } if (cancelToken.IsCancellationRequested) { throw new OperationCanceledException(cancelToken); } // create rule for any leftover ip addresses if (ipList.Length > 1) { ipList.Length--; // remove ending comma GetOrCreateRule(prefix + index.ToString(CultureInfo.InvariantCulture), ipList.ToString(), NET_FW_ACTION_.NET_FW_ACTION_BLOCK, allowedPorts); index += MaxIpAddressesPerRule; } // delete any leftover rules DeleteRules(prefix, index); return(Task.FromResult(true)); } catch (Exception ex) { IPBanLog.Error(ex); return(Task.FromResult(false)); } }
private async Task RunConsoleService(string[] args) { try { await start.Invoke(args); } catch (Exception ex) { IPBanLog.Error(ex); } }
private Task <bool> BlockOrAllowIPAddresses(string ruleNamePrefix, bool block, IEnumerable <string> ipAddresses, IEnumerable <PortRange> allowedPorts = null, CancellationToken cancelToken = default) { try { string prefix = ruleNamePrefix.TrimEnd('_') + "_"; int i = 0; List <string> ipAddressesList = new List <string>(); foreach (string ipAddress in ipAddresses) { if (cancelToken.IsCancellationRequested) { throw new OperationCanceledException(cancelToken); } ipAddressesList.Add(ipAddress); if (ipAddressesList.Count == MaxIpAddressesPerRule) { if (block) { CreateBlockRule(ipAddressesList, 0, MaxIpAddressesPerRule, prefix + i.ToStringInvariant(), allowedPorts); } else { CreateAllowRule(ipAddressesList, 0, MaxIpAddressesPerRule, prefix + i.ToStringInvariant(), allowedPorts); } i += MaxIpAddressesPerRule; ipAddressesList.Clear(); } } if (cancelToken.IsCancellationRequested) { throw new OperationCanceledException(cancelToken); } if (ipAddressesList.Count != 0) { if (block) { CreateBlockRule(ipAddressesList, 0, MaxIpAddressesPerRule, prefix + i.ToStringInvariant(), allowedPorts); } else { CreateAllowRule(ipAddressesList, 0, MaxIpAddressesPerRule, prefix + i.ToStringInvariant(), allowedPorts); } i += MaxIpAddressesPerRule; } DeleteRules(prefix, i); return(Task.FromResult(true)); } catch (Exception ex) { IPBanLog.Error(ex); return(Task.FromResult(false)); } }
public virtual Task <bool> AllowIPAddresses(IEnumerable <string> ipAddresses, CancellationToken cancelToken = default) { try { return(Task.FromResult(UpdateRule(AllowRuleName, "ACCEPT", ipAddresses, hashTypeSingleIP, allowRuleMaxCount, null, cancelToken))); } catch (Exception ex) { IPBanLog.Error(ex); return(Task.FromResult(false)); } }
public Task <bool> AllowIPAddresses(IEnumerable <string> ipAddresses, CancellationToken cancelToken = default) { try { allowedIPAddresses = UpdateRule(allowRuleName, "ACCEPT", ipAddresses, allowedIPAddresses, "ip", allowRuleMaxCount, false, null, cancelToken, out bool result); return(Task.FromResult <bool>(result)); } catch (Exception ex) { IPBanLog.Error(ex); return(Task.FromResult <bool>(false)); } }
public virtual Task <bool> AllowIPAddresses(string ruleNamePrefix, IEnumerable <IPAddressRange> ipAddresses, IEnumerable <PortRange> allowedPorts = null, CancellationToken cancelToken = default) { try { ruleNamePrefix.ThrowIfNullOrEmpty(); return(Task.FromResult(UpdateRule(RulePrefix + ruleNamePrefix, "ACCEPT", ipAddresses.Select(r => r.ToCidrString()), hashTypeCidrMask, blockRuleMaxCount, allowedPorts, cancelToken))); } catch (Exception ex) { IPBanLog.Error(ex); return(Task.FromResult(false)); } }
public virtual Task <bool> BlockIPAddressesDelta(string ruleNamePrefix, IEnumerable <IPBanFirewallIPAddressDelta> deltas, IEnumerable <PortRange> allowedPorts = null, CancellationToken cancelToken = default) { try { string ruleName = (string.IsNullOrWhiteSpace(ruleNamePrefix) ? BlockRuleName : RulePrefix + ruleNamePrefix); return(Task.FromResult(UpdateRuleDelta(ruleName, "DROP", deltas, hashTypeSingleIP, blockRuleMaxCount, false, allowedPorts, cancelToken))); } catch (Exception ex) { IPBanLog.Error(ex); return(Task.FromResult(false)); } }
public virtual Task <bool> BlockIPAddresses(string ruleNamePrefix, IEnumerable <string> ipAddresses, IEnumerable <PortRange> allowedPorts = null, CancellationToken cancelToken = default) { try { string ruleName = (string.IsNullOrWhiteSpace(ruleNamePrefix) ? BlockRuleName : RulePrefix + ruleNamePrefix); return(Task.FromResult(UpdateRule(ruleName, "DROP", ipAddresses, "ip", blockRuleMaxCount, allowedPorts, cancelToken))); } catch (Exception ex) { IPBanLog.Error(ex); return(Task.FromResult(false)); } }
public Task <bool> BlockIPAddresses(IEnumerable <string> ipAddresses, CancellationToken cancelToken = default) { try { bannedIPAddresses = UpdateRule(blockRuleName, "DROP", ipAddresses, bannedIPAddresses, "ip", blockRuleMaxCount, false, null, cancelToken, out bool result); return(Task.FromResult(result)); } catch (Exception ex) { IPBanLog.Error(ex); return(Task.FromResult(false)); } }
/// <summary> /// Get a value from configuration manager app settings /// </summary> /// <typeparam name="T">Type of value to get</typeparam> /// <param name="key">Key</param> /// <param name="defaultValue">Default value if null or not found</param> /// <returns>Value</returns> public T GetConfig <T>(string key, T defaultValue = default) { try { var converter = TypeDescriptor.GetConverter(typeof(T)); return((T)converter.ConvertFromInvariantString(appSettings[key])); } catch (Exception ex) { IPBanLog.Error(ex, "Error deserializing appSettings key {0}", key); return(defaultValue); } }
protected override void OnStart(string[] args) { base.OnStart(args); Task.Run(async() => { try { await runner.start.Invoke(args); } catch (Exception ex) { IPBanLog.Error(ex); } }); }
/// <summary> /// Set a field / variable from configuration manager app settings. If null or not found, nothing is changed. /// </summary> /// <typeparam name="T">Type of value to set</typeparam> /// <param name="key">Key</param> /// <param name="value">Value</param> public void GetConfig <T>(string key, ref T value) { try { var converter = TypeDescriptor.GetConverter(typeof(T)); if (appSettings.ContainsKey(key)) { value = (T)converter.ConvertFromInvariantString(appSettings[key]); } } catch (Exception ex) { IPBanLog.Error(ex, "Error deserializing appSettings key {0}", key); } }
/// <summary> /// Update - if the text file path exists, all ip addresses from each line will be unbanned /// </summary> public void Update() { try { if (File.Exists(textFilePath)) { UnbanIPAddresses(File.ReadLines(textFilePath)); File.Delete(textFilePath); } } catch (Exception ex) { IPBanLog.Error(ex); } }
public void UnblockIPAddresses(IEnumerable <string> ipAddresses) { try { lock (policy) { for (int i = 0; ; i += MaxIpAddressesPerRule) { string ruleName = RulePrefix + i.ToString(CultureInfo.InvariantCulture); try { INetFwRule rule = policy.Rules.Item(ruleName); if (rule == null) { // no more rules to check break; } string remoteIPs = rule.RemoteAddresses; foreach (string ipAddress in ipAddresses) { remoteIPs = Regex.Replace(remoteIPs, ipAddress.Replace(".", "\\.") + "\\/[^,]+,?", ",", RegexOptions.IgnoreCase); remoteIPs = remoteIPs.Replace(",,", ","); remoteIPs = remoteIPs.Trim().Trim(',', '/', ':', '.', ';', '*').Trim(); } // ensure we don't have a block rule with no ip addresses, this will block the entire world (WTF Microsoft)... if (string.IsNullOrWhiteSpace(remoteIPs)) { policy.Rules.Remove(rule.Name); } else { rule.RemoteAddresses = remoteIPs; } } catch { // no more rules to check break; } } } } catch (Exception ex) { IPBanLog.Error(ex); } }
/// <summary> /// Update - if the text file path exists, all ip addresses from each line will be unbanned /// </summary> public async Task Update() { try { if (File.Exists(textFilePath)) { string[] lines = (await File.ReadAllLinesAsync(textFilePath)).Where(l => IPAddress.TryParse(l, out _)).ToArray(); IPBanLog.Warn("Queueing {0} ip addresses to unban from {1} file", lines.Length, textFilePath); UnblockIPAddresses(lines); File.Delete(textFilePath); } } catch (Exception ex) { IPBanLog.Error(ex); } }
public Task <bool> BlockIPAddresses(string ruleNamePrefix, IEnumerable <string> ipAddresses, CancellationToken cancelToken = default) { try { if (string.IsNullOrWhiteSpace(ruleNamePrefix)) { ruleNamePrefix = RulePrefix; } else { ruleNamePrefix = RulePrefix + ruleNamePrefix; } int i = 0; List <string> ipAddressesList = new List <string>(); foreach (string ipAddress in ipAddresses) { if (cancelToken.IsCancellationRequested) { throw new OperationCanceledException(cancelToken); } ipAddressesList.Add(ipAddress); if (ipAddressesList.Count == MaxIpAddressesPerRule) { CreateBlockRule(ipAddressesList, 0, MaxIpAddressesPerRule, ruleNamePrefix + i.ToStringInvariant()); i += MaxIpAddressesPerRule; ipAddressesList.Clear(); } } if (cancelToken.IsCancellationRequested) { throw new OperationCanceledException(cancelToken); } if (ipAddressesList.Count != 0) { CreateBlockRule(ipAddressesList, 0, MaxIpAddressesPerRule, ruleNamePrefix + i.ToStringInvariant()); i += MaxIpAddressesPerRule; } DeleteRules(ruleNamePrefix, i); return(Task.FromResult(true)); } catch (Exception ex) { IPBanLog.Error(ex); return(Task.FromResult(false)); } }
/// <summary> /// Get a value from configuration manager app settings /// </summary> /// <typeparam name="T">Type of value to get</typeparam> /// <param name="key">Key</param> /// <param name="value">Value to set</param> /// <param name="minValue">Min value</param> /// <param name="maxValue">Max value</param> /// <param name="clampSmallTimeSpan">Whether to clamp small timespan to max value</param> /// <returns>Value</returns> public void GetConfig <T>(string key, ref T value, T?minValue = null, T?maxValue = null, bool clampSmallTimeSpan = true) where T : struct, IComparable <T> { try { var converter = TypeDescriptor.GetConverter(typeof(T)); value = (T)converter.ConvertFromInvariantString(appSettings[key]); } catch (Exception ex) { IPBanLog.Error(ex, "Error deserializing appSettings key {0}", key); } if (minValue != null && maxValue != null) { value = value.Clamp(minValue.Value, maxValue.Value, clampSmallTimeSpan); } }
public virtual Task <bool> BlockIPAddresses(string ruleNamePrefix, IEnumerable <IPAddressRange> ranges, IEnumerable <PortRange> allowedPorts, CancellationToken cancelToken = default) { if (string.IsNullOrWhiteSpace(ruleNamePrefix)) { return(Task.FromResult(false)); } try { string ruleName = RulePrefix + RuleSuffix + ruleNamePrefix; return(Task.FromResult(UpdateRule(ruleName, "DROP", ranges.Select(r => r.ToCidrString()), "net", blockRuleRangesMaxCount, allowedPorts, cancelToken))); } catch (Exception ex) { IPBanLog.Error(ex); return(Task.FromResult(false)); } }
public Task <bool> AllowIPAddresses(IEnumerable <string> ipAddresses, CancellationToken cancelToken = default) { try { List <string> ipAddressesList = new List <string>(); int i = 0; foreach (string ipAddress in ipAddresses) { if (cancelToken.IsCancellationRequested) { throw new OperationCanceledException(); } ipAddressesList.Add(ipAddress); if (ipAddressesList.Count == MaxIpAddressesPerRule) { string remoteIP = CreateRuleStringForIPAddresses(ipAddressesList, i, MaxIpAddressesPerRule); GetOrCreateRule(AllowRulePrefix + i.ToString(CultureInfo.InvariantCulture), remoteIP, NET_FW_ACTION_.NET_FW_ACTION_ALLOW); i += MaxIpAddressesPerRule; ipAddressesList.Clear(); } } if (cancelToken.IsCancellationRequested) { throw new OperationCanceledException(); } if (ipAddressesList.Count != 0) { string remoteIP = CreateRuleStringForIPAddresses(ipAddressesList, i, MaxIpAddressesPerRule); GetOrCreateRule(AllowRulePrefix + i.ToString(CultureInfo.InvariantCulture), remoteIP, NET_FW_ACTION_.NET_FW_ACTION_ALLOW); i += MaxIpAddressesPerRule; } if (cancelToken.IsCancellationRequested) { throw new OperationCanceledException(); } DeleteRules(AllowRulePrefix, i); return(Task.FromResult <bool>(true)); } catch (Exception ex) { IPBanLog.Error(ex); return(Task.FromResult <bool>(false)); } }
public bool IsIPAddressBlocked(string ipAddress, out string ruleName, int port = -1) { ruleName = null; try { lock (policy) { for (int i = 0; ; i += MaxIpAddressesPerRule) { string firewallRuleName = BlockRulePrefix + i.ToString(CultureInfo.InvariantCulture); try { INetFwRule rule = policy.Rules.Item(firewallRuleName); if (rule == null) { // no more rules to check break; } else { HashSet <string> set = new HashSet <string>(rule.RemoteAddresses.Split(',').Select(i2 => IPAddressRange.Parse(i2).Begin.ToString())); if (set.Contains(ipAddress)) { ruleName = firewallRuleName; return(true); } } } catch { // no more rules to check break; } } } } catch (Exception ex) { IPBanLog.Error(ex); } return(false); }