public IPNetwork(uint value, byte prefixLength) { if (!IPNetworkHelper.IsValidNetworkPrefixLength(prefixLength)) { throw new ArgumentOutOfRangeException("prefixLength"); } m_prefixLength = prefixLength; // TODO: Consider moving GetNetworkMaskValue into constructor IPNetworkMask since we now have a separate class for it... m_networkMask = new IPNetworkMask(IPNetworkHelper.GetNetworkMaskValue(m_prefixLength)); m_networkAddressValue = value & m_networkMask.Value; m_networkAddress = new IPAddress(m_networkAddressValue); if (m_prefixLength < 32) { m_firstUsableAddress = new IPAddress(m_networkAddressValue + 1); var wildcardMask = 0xffffffff - m_networkMask.Value; var broadcastAddressValue = m_networkAddressValue | wildcardMask; m_lastUsableAddress = new IPAddress(broadcastAddressValue - 1); m_broadcastAddress = new IPAddress(broadcastAddressValue); m_usableAddresses = new IPAddressRange(m_firstUsableAddress, m_lastUsableAddress); } else { m_usableAddresses = IPAddressRange.Empty; } }
public static string GetIPClassFamily2(string ipAddress) { if (string.IsNullOrEmpty(ipAddress)) return "unknown"; IPAddressRange range = new IPAddressRange(IPAddress.Parse("0.0.0.0"), IPAddress.Parse("127.255.255.255")); if (range.IsInRange(IPAddress.Parse(ipAddress))) { return "A"; } else { range = new IPAddressRange(IPAddress.Parse("128.0.0.0"), IPAddress.Parse("191.255.255.255")); if (range.IsInRange(IPAddress.Parse(ipAddress))) { return "B"; } else { range = new IPAddressRange(IPAddress.Parse("192.0.0.0"), IPAddress.Parse("223.255.255.255")); if (range.IsInRange(IPAddress.Parse(ipAddress))) { return "C"; } else { return "unknown"; } } } }
public static bool ContainsIp(List<string> ipRules, string clientIp) { var ip = ParseIp(clientIp); if (ipRules != null && ipRules.Any()) { foreach (var rule in ipRules) { var range = new IPAddressRange(rule); if (range.Contains(ip)) { return true; } } } return false; }
public static void ScanNetwork(CancellationToken userToken, DnsResolverBase resolver, IPAddressRange addresses, INetworkServiceCore[] networkServices, IProgress<ScanNetworkBatch> progress) { if (resolver == null) { throw new ArgumentNullException("resolver"); } if (addresses == null) { throw new ArgumentNullException("addresses"); } if (networkServices == null) { throw new ArgumentNullException("networkServices"); } if (progress == null) { throw new ArgumentNullException("progress"); } var nestedTasks = new List<Task>(); var chunkSize = GetChunkSize(addresses); foreach (var addressChunk in addresses.Chunk(chunkSize)) { userToken.ThrowIfCancellationRequested(); var nestedTask = Task.Factory.StartNew(() => { foreach (var address in addressChunk) { var results = new List<ScanNetworkResult>(); foreach (var networkService in networkServices) { userToken.ThrowIfCancellationRequested(); var endpoint = new IPEndpoint(address, networkService.Port); var result = ScanEndpoint(userToken, resolver, networkService.Protocol, endpoint); results.Add(result); } progress.Report(new ScanNetworkBatch(results.ToArray())); } }); nestedTasks.Add(nestedTask); } Task.WaitAll(nestedTasks.ToArray(), userToken); }
public IpAddressRangeWithWildcard(IPAddressRange addressRange) { _base = addressRange; _wildCard = false; }
public bool IsWhitelisted(IPAddressRange range) { isWhitelistedCount++; return(whiteList.Contains(range)); }
public void SubnetMaskLengthTest_Invalid() { AssertEx.Throws <ArgumentException>(() => new IPAddressRange(IPAddress.Parse("192.168.75.23"), IPAddressRange.SubnetMaskLength(IPAddress.Parse("255.255.54.0")))); }
public void ContainsTest_TestIPv6_to_IPv4Range() { var range = IPAddressRange.Parse("192.168.60.26-192.168.60.37"); range.Contains(IPAddress.Parse("c0a8:3c1a::")).Is(false); }
protected override void BecauseOf() { m_result = IPAddressRange.Empty; }
// deleteRule will drop the rule and matching set before creating the rule and set, use this is you don't care to update the rule and set in place private List <uint> UpdateRule(string ruleName, string action, IEnumerable <string> ipAddresses, List <uint> existingIPAddresses, string hashType, int maxCount, bool deleteRule, IEnumerable <PortRange> allowPorts, CancellationToken cancelToken, out bool result) { string ipFile = GetSetFileName(ruleName); string ipFileTemp = ipFile + ".tmp"; List <uint> newIPAddressesUint = new List <uint>(); uint value = 0; // add and remove the appropriate ip addresses from the set using (StreamWriter writer = File.CreateText(ipFileTemp)) { if (cancelToken.IsCancellationRequested) { throw new OperationCanceledException(cancelToken); } writer.WriteLine($"create {ruleName} hash:{hashType} family {inetFamily} hashsize {hashSize} maxelem {maxCount} -exist"); foreach (string ipAddress in ipAddresses) { if (cancelToken.IsCancellationRequested) { throw new OperationCanceledException(cancelToken); } // only allow ipv4 for now if (IPAddressRange.TryParse(ipAddress, out IPAddressRange range) && range.Begin.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork && range.End.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork && // if deleting the rule, don't track the uint value (!deleteRule || (value = IPBanFirewallUtility.ParseIPV4(ipAddress)) != 0)) { try { if (range.Begin.Equals(range.End)) { writer.WriteLine($"add {ruleName} {range.Begin} -exist"); } else { writer.WriteLine($"add {ruleName} {range.ToCidrString()} -exist"); } if (!deleteRule) { newIPAddressesUint.Add(value); } } catch { // ignore invalid cidr ranges } } } newIPAddressesUint.Sort(); // if the rule was deleted, no need to add del entries if (!deleteRule) { // for ip that dropped out, remove from firewall foreach (uint droppedIP in existingIPAddresses.Where(e => newIPAddressesUint.BinarySearch(e) < 0)) { writer.WriteLine($"del {ruleName} {IPBanFirewallUtility.IPV4ToString(droppedIP)} -exist"); } } } if (cancelToken.IsCancellationRequested) { throw new OperationCanceledException(cancelToken); } else { // TODO: Is there an easier way to move to a file that exists? if (File.Exists(ipFile)) { DeleteFile(ipFile); } File.Move(ipFileTemp, ipFile); if (deleteRule) { DeleteRule(ruleName); } // restore the file to get the set updated result = (RunProcess("ipset", true, $"restore < \"{ipFile}\"") == 0); // ensure rule exists for the set CreateOrUpdateRule(ruleName, action, hashType, maxCount, allowPorts, cancelToken); } return(newIPAddressesUint); }
private static int GetChunkSize(IPAddressRange addresses) { var chunkSize = addresses.Count / TaskCount; var result = chunkSize == 0 ? addresses.Count : chunkSize; return result; }
public ClientIPAddressFilterAttribute(IIPWhitelistConfiguration configuration) { this.authorizedRanges = configuration.AuthorizedIPAddresses .Select(item => IPAddressRange.Parse(item)); }
public override IPRangeCountry ParseRecord(string record) { if (record == null) { throw new ArgumentNullException(nameof(record)); } var data = ReadQuotedValues(record).ToArray(); // Minimum of 3 columns (ASN file) if (data.Length >= 3) { var ipnetwork = IPAddressRange.Parse(data[0]); MaxMindGeoLiteGeonameEntry country = null, regcountry = null, repcountry = null; // Only city/country files contain these columns; ASN file doesn't if (data.Length > 3) { country = int.TryParse(data[1], out var cntid) ? _geolookup.TryGetValue(cntid, out var cnt) ? cnt : null : null; regcountry = int.TryParse(data[2], out var regid) ? _geolookup.TryGetValue(regid, out var reg) ? reg : null : null; repcountry = int.TryParse(data[3], out var repid) ? _geolookup.TryGetValue(repid, out var rep) ? rep : null : null; } #pragma warning disable CS0618 // Type or member is obsolete switch (data.Length) { case 3: return(new MaxMindGeoLiteASN { Start = ipnetwork.Begin, End = ipnetwork.End, Country = null, ASN = int.Parse(data[1], CultureInfo.InvariantCulture), Organisation = data[2] }); case 6: return(new MaxMindGeoLiteIPRangeCountry { Start = ipnetwork.Begin, End = ipnetwork.End, Country = country?.ISOCode, Location = country, RegisteredLocation = regcountry, RepresentedLocation = repcountry, IsAnonymousProxy = ParseBool(data[4]), IsSatelliteProvider = ParseBool(data[5]) }); case 10: return(new MaxMindGeoLiteIPRangeCity { Start = ipnetwork.Begin, End = ipnetwork.End, Country = country?.ISOCode, Location = country, RegisteredLocation = regcountry, RepresentedLocation = repcountry, IsAnonymousProxy = ParseBool(data[4]), IsSatelliteProvider = ParseBool(data[5]), PostalCode = data[6], Latitude = ParseLatLon(data[7]), Longitude = ParseLatLon(data[8]), AccuracyRadius = int.TryParse(data[9], out var ac) ? (int?)ac : null });
/// <summary> /// Determines whether two IP addresses are in the same subnet /// </summary> /// <param name="ipAddress1">IP address 1</param> /// <param name="ipAddress2">IP address 2</param> /// <param name="subnetMask">The subnet</param> /// <returns>True if the IP addresses are within the same subnet. False otherwise</returns> public static bool IsInSameSubnet(IPAddress ipAddress1, string ipAddress2, string subnetMask) { var range = IPAddressRange.Parse(ipAddress2 + "/" + subnetMask); return(range.Contains(ipAddress1)); }
public void TestMethod1() { var rangeB1 = IPAddressRange.Parse("192.168.0.10 - 192.168.10.20"); // rangeB1.ToCidrString(); // is 192.168.0.0/24 bool result = rangeB1.Contains(IPAddress.Parse("192.168.3.45")); }
public static void ScanNetwork(CancellationToken userToken, DnsResolverBase resolver, IPAddressRange addresses, INetworkServiceCore[] networkServices, IProgress <ScanNetworkBatch> progress) { if (resolver == null) { throw new ArgumentNullException("resolver"); } if (addresses == null) { throw new ArgumentNullException("addresses"); } if (networkServices == null) { throw new ArgumentNullException("networkServices"); } if (progress == null) { throw new ArgumentNullException("progress"); } var nestedTasks = new List <Task>(); var chunkSize = GetChunkSize(addresses); foreach (var addressChunk in addresses.Chunk(chunkSize)) { userToken.ThrowIfCancellationRequested(); var nestedTask = Task.Factory.StartNew(() => { foreach (var address in addressChunk) { var results = new List <ScanNetworkResult>(); foreach (var networkService in networkServices) { userToken.ThrowIfCancellationRequested(); var endpoint = new IPEndpoint(address, networkService.Port); var result = ScanEndpoint(userToken, resolver, networkService.Protocol, endpoint); results.Add(result); } progress.Report(new ScanNetworkBatch(results.ToArray())); } }); nestedTasks.Add(nestedTask); } Task.WaitAll(nestedTasks.ToArray(), userToken); }
/// <summary> /// Filter ip address ranges from ranges using filter /// </summary> /// <param name="ranges">Ip address ranges to filter</param> /// <param name="filter">Ip address ranges to filter out of ranges, null for no filtering</param> /// <returns>Filtered ip address ranges in sorted order</returns> public static IEnumerable <IPAddressRange> FilterRanges(this IEnumerable <IPAddressRange> ranges, IEnumerable <IPAddressRange> filter) { // if null ranges we are done if (ranges is null) { yield break; } // if null filter, return ranges as is else if (filter is null) { foreach (IPAddressRange range in ranges.OrderBy(r => r)) { yield return(range); } yield break; } using (IEnumerator <IPAddressRange> rangeEnum = ranges.OrderBy(r => r).GetEnumerator()) using (IEnumerator <IPAddressRange> filterEnum = filter.OrderBy(r => r).GetEnumerator()) { // if no ranges left, we are done if (!rangeEnum.MoveNext()) { yield break; } IPAddressRange currentFilter = (filterEnum.MoveNext() ? filterEnum.Current : null); IPAddressRange currentRange = rangeEnum.Current; while (true) { // if no more filter, just continue returning ranges as is if (currentFilter is null) { yield return(currentRange); if (!rangeEnum.MoveNext()) { break; } continue; } int compare = currentFilter.Begin.CompareTo(currentRange.End); if (compare > 0) { // current filter begin is after the range end, just return the range as is yield return(currentRange); if (!rangeEnum.MoveNext()) { break; } currentRange = rangeEnum.Current; } else { compare = currentFilter.End.CompareTo(currentRange.Begin); // check if the current filter end is before the range begin if (compare < 0) { // current filter end is before the range begin, move to next filter currentFilter = (filterEnum.MoveNext() ? filterEnum.Current : null); } else { // the current filter is inside the current range, filter int compareBegin = currentFilter.Begin.CompareTo(currentRange.Begin); int compareEnd = currentFilter.End.CompareTo(currentRange.End); if (compareBegin <= 0) { // filter begin is less than or equal to the range begin if (compareEnd < 0 && currentFilter.End.TryIncrement(out IPAddress begin)) { // set the range to have the filtered portion removed currentRange = new IPAddressRange(begin, currentRange.End); // move to next filter currentFilter = (filterEnum.MoveNext() ? filterEnum.Current : currentFilter); } else { // else the filter has blocked out this entire range, ignore it if (!rangeEnum.MoveNext()) { break; } currentRange = rangeEnum.Current; } } else { // if compareBegin was >= the ip address range begin, we won't get here // this means the current filter begin must be greater than 0 if (!currentFilter.Begin.TryDecrement(out IPAddress end)) { throw new InvalidOperationException("Current filter should have been able to decrement the begin ip address"); } // filter begin is after the range begin, return the range begin and one before the filter begin yield return(new IPAddressRange(currentRange.Begin, end)); if (!currentFilter.End.TryIncrement(out IPAddress newBegin)) { newBegin = currentFilter.End; } if (newBegin.CompareTo(currentRange.End) > 0) { // end of range, get a new range if (!rangeEnum.MoveNext()) { break; } currentRange = rangeEnum.Current; } else { currentRange = new IPAddressRange(newBegin, currentRange.End); } } } } } } }
public void TestDB() { IPBanService.UtcNow = new DateTime(2020, 1, 1); DateTime now = IPBanService.UtcNow; using IPBanDB db = new(); db.Truncate(true); const string ip = "10.10.10.10"; int year = now.Year; DateTime dt1 = new(year - 1, 1, 1, 1, 1, 1, 1, DateTimeKind.Utc); DateTime dt2 = new(year, 1, 1, 1, 1, 1, 1, DateTimeKind.Utc); DateTime dt3 = new(year + 1, 1, 1, 1, 1, 1, 1, DateTimeKind.Utc); DateTime dt4 = new(year + 2, 1, 1, 1, 1, 1, 1, DateTimeKind.Utc); int count = db.IncrementFailedLoginCount(ip, "testuser", "testsource", dt1, 1); Assert.IsTrue(db.TryGetIPAddress(ip, out IPBanDB.IPAddressEntry entry)); Assert.AreEqual(entry.UserName, "testuser"); Assert.AreEqual(entry.Source, "testsource"); Assert.AreEqual(1, count); Assert.AreEqual(1, db.EnumerateIPAddresses(dt1.AddMinutes(1.0)).Count()); count = db.IncrementFailedLoginCount(ip, null, null, dt2, 2); Assert.AreEqual(3, count); Assert.AreEqual(0, db.EnumerateIPAddresses(dt1.AddMinutes(1.0)).Count()); Assert.IsTrue(db.SetBanDates(ip, dt2, dt3, now)); // increment fail login for a ban or ban pending should do nothing Assert.AreEqual(3, db.IncrementFailedLoginCount(ip, null, null, dt2.AddSeconds(15.0f), 10)); Assert.IsFalse(db.SetBanDates(ip, dt2 + TimeSpan.FromDays(1.0), dt4, now)); // no effect Assert.IsTrue(db.TryGetIPAddress(ip, out IPBanDB.IPAddressEntry e)); Assert.AreEqual(ip, e.IPAddress); Assert.AreEqual(dt2, e.LastFailedLogin); Assert.AreEqual(3, e.FailedLoginCount); Assert.AreEqual(dt2, e.BanStartDate); count = db.IncrementFailedLoginCount("5.5.5.5", null, null, dt1, 2); Assert.AreEqual(2, count); count = db.GetIPAddressCount(); Assert.AreEqual(2, count); count = db.GetBannedIPAddressCount(); Assert.AreEqual(1, count); Assert.IsTrue(db.TryGetBanDates(ip, out KeyValuePair <DateTime?, DateTime?> banDate)); Assert.AreEqual(dt2, banDate.Key); Assert.AreEqual(dt3, banDate.Value); Assert.IsTrue(db.TryGetBanDates("5.5.5.5", out banDate)); count = db.SetBannedIPAddresses(new Tuple <string, DateTime, DateTime>[] { new Tuple <string, DateTime, DateTime>(ip, dt2, dt3), new Tuple <string, DateTime, DateTime>("5.5.5.5", dt2, dt3), new Tuple <string, DateTime, DateTime>("5.5.5.6", dt2, dt3), new Tuple <string, DateTime, DateTime>("::5.5.5.5", dt2, dt3), new Tuple <string, DateTime, DateTime>("6.6.6.6", dt2, dt3), new Tuple <string, DateTime, DateTime>("11.11.11.11", dt2, dt3), new Tuple <string, DateTime, DateTime>("12.12.12.12", dt2, dt3), new Tuple <string, DateTime, DateTime>("11.11.11.11", dt2, dt3) }, now); Assert.AreEqual(6, count); IPAddressRange range = IPAddressRange.Parse("5.5.5.0/24"); count = 0; foreach (string ipAddress in db.DeleteIPAddresses(range)) { Assert.IsTrue(ipAddress == "5.5.5.5" || ipAddress == "5.5.5.6"); count++; } db.SetBannedIPAddresses(new Tuple <string, DateTime, DateTime>[] { new Tuple <string, DateTime, DateTime>("5.5.5.5", dt2, dt3), new Tuple <string, DateTime, DateTime>("5.5.5.6", dt2, dt3) }, now); count = db.IncrementFailedLoginCount("9.9.9.9", null, null, dt2, 1); Assert.AreEqual(1, count); count = 0; range = new IPAddressRange { Begin = System.Net.IPAddress.Parse("::5.5.5.0"), End = System.Net.IPAddress.Parse("::5.5.5.255") }; foreach (string ipAddress in db.DeleteIPAddresses(range)) { Assert.AreEqual(ipAddress, "::5.5.5.5"); count++; } Assert.AreEqual(1, count); IPBanDB.IPAddressEntry[] ipAll = db.EnumerateIPAddresses().ToArray(); Assert.AreEqual(7, ipAll.Length); // ensure deltas work properly Assert.AreEqual(1, db.SetIPAddressesState(new string[] { "5.5.5.5" }, IPBanDB.IPAddressState.RemovePending)); IPBanFirewallIPAddressDelta[] deltas = db.EnumerateIPAddressesDeltaAndUpdateState(false, now).ToArray(); Assert.AreEqual(6, deltas.Length); Assert.AreEqual("10.10.10.10", deltas[0].IPAddress); Assert.AreEqual("11.11.11.11", deltas[1].IPAddress); Assert.AreEqual("12.12.12.12", deltas[2].IPAddress); Assert.AreEqual("5.5.5.5", deltas[3].IPAddress); Assert.AreEqual("5.5.5.6", deltas[4].IPAddress); Assert.AreEqual("6.6.6.6", deltas[5].IPAddress); Assert.IsTrue(deltas[0].Added); Assert.IsTrue(deltas[1].Added); Assert.IsTrue(deltas[2].Added); Assert.IsFalse(deltas[3].Added); Assert.IsTrue(deltas[4].Added); Assert.IsTrue(deltas[5].Added); deltas = db.EnumerateIPAddressesDeltaAndUpdateState(true, now).ToArray(); Assert.AreEqual(6, deltas.Length); Assert.AreEqual("10.10.10.10", deltas[0].IPAddress); Assert.AreEqual("11.11.11.11", deltas[1].IPAddress); Assert.AreEqual("12.12.12.12", deltas[2].IPAddress); Assert.AreEqual("5.5.5.5", deltas[3].IPAddress); Assert.AreEqual("5.5.5.6", deltas[4].IPAddress); Assert.AreEqual("6.6.6.6", deltas[5].IPAddress); Assert.IsTrue(deltas[0].Added); Assert.IsTrue(deltas[1].Added); Assert.IsTrue(deltas[2].Added); Assert.IsFalse(deltas[3].Added); Assert.IsTrue(deltas[4].Added); Assert.IsTrue(deltas[5].Added); string[] bannedIpAll = db.EnumerateBannedIPAddresses().ToArray(); Assert.AreEqual(5, bannedIpAll.Length); deltas = db.EnumerateIPAddressesDeltaAndUpdateState(true, now).ToArray(); Assert.AreEqual(0, deltas.Length); db.Truncate(true); DateTime banStart = now; Tuple <string, DateTime, DateTime>[] ips = new Tuple <string, DateTime, DateTime> [65536]; int index = 0; for (int i = 0; i < 256; i++) { for (int j = 0; j < 256; j++) { ips[index++] = new Tuple <string, DateTime, DateTime>("255." + i + ".255." + j, banStart, (now = now.AddMilliseconds(1))); } } count = db.SetBannedIPAddresses(ips, now); Assert.AreEqual(65536, count); DateTime cutOff = now - TimeSpan.FromMilliseconds(1634.0); IPBanDB.IPAddressEntry[] entries = db.EnumerateIPAddresses(null, cutOff).ToArray(); Assert.AreEqual(65536 - 1634, entries.Length); TimeSpan span = (IPBanService.UtcNow - now); // make sure performance is good Assert.Less(span, TimeSpan.FromSeconds(10.0)); }
protected override void BecauseOf() { m_result = new IPAddressRange(FirstValue, LastValue); }
public bool IsInRange(IPAddress ipAddress, string cidrNetwork) { var range = IPAddressRange.Parse(cidrNetwork); return(range.Contains(ipAddress)); }
// deleteRule will drop the rule and matching set before creating the rule and set, use this is you don't care to update the rule and set in place protected bool UpdateRuleDelta(string ruleName, string action, IEnumerable <IPBanFirewallIPAddressDelta> deltas, string hashType, int maxCount, bool deleteRule, IEnumerable <PortRange> allowPorts, CancellationToken cancelToken) { string ipFileTemp = IPBanOS.GetTempFileName(); try { // add and remove the appropriate ip addresses from the set using (StreamWriter writer = File.CreateText(ipFileTemp)) { if (cancelToken.IsCancellationRequested) { throw new OperationCanceledException(cancelToken); } writer.WriteLine($"create {ruleName} hash:{hashType} family {INetFamily} hashsize {hashSize} maxelem {maxCount} -exist"); foreach (IPBanFirewallIPAddressDelta delta in deltas) { if (cancelToken.IsCancellationRequested) { throw new OperationCanceledException(cancelToken); } if (IPAddressRange.TryParse(delta.IPAddress, out IPAddressRange range) && range.Begin.AddressFamily == addressFamily && range.End.AddressFamily == addressFamily) { try { if (delta.Added) { if (range.Begin.Equals(range.End)) { writer.WriteLine($"add {ruleName} {range.Begin} -exist"); } else { writer.WriteLine($"add {ruleName} {range.ToCidrString()} -exist"); } } else { if (range.Begin.Equals(range.End)) { writer.WriteLine($"del {ruleName} {range.Begin} -exist"); } else { writer.WriteLine($"del {ruleName} {range.ToCidrString()} -exist"); } } } catch { // ignore invalid cidr ranges } } } } if (cancelToken.IsCancellationRequested) { throw new OperationCanceledException(cancelToken); } else { // restore the deltas into the existing set bool result = (RunProcess("ipset", true, $"restore < \"{ipFileTemp}\"") == 0); CreateOrUpdateRule(ruleName, action, hashType, maxCount, allowPorts, cancelToken); return(result); } } finally { File.Delete(ipFileTemp); } }
public string ParseRange(string cidrNetwork) { var range = IPAddressRange.Parse(cidrNetwork); return(range.ToCidrString()); }
public Task <bool> AllowIPAddresses(string ruleNamePrefix, IEnumerable <IPAddressRange> ipAddresses, IEnumerable <PortRange> allowedPorts = null, CancellationToken cancelToken = default) { lock (this) { allowRuleRanges[ruleNamePrefix] = new MemoryFirewallRuleRanges(ipAddresses.Select(i => IPAddressRange.Parse(i)).ToList(), allowedPorts?.ToList(), false); } return(Task.FromResult <bool>(true)); }
public async Task <IEnumerable <int> > UpdateDnsAttacks(IEnumerable <DnsAttackModel> attacks) { var newAttacks = new List <Attacks>(); var ignoreAttacks = new List <Attacks>(); var storedAttacks = await _dbContext.DnsAttacks.Include(x => x.AttackGroup).ToListAsync(); var blockedIps = await _redis.GetStringSetMembers(RedisKeys.BLACK_IPS); var blockedSubnets = await _redis.GetStringSetMembers(RedisKeys.BLACK_SUBNETS); foreach (var recentAttack in attacks) { bool needNotify = false; Attacks attack = null; var groups = storedAttacks .Where(x => x.WhiteDomain == recentAttack.WhiteDomain && x.BlackDomain == recentAttack.BlackDomain) .Select(x => x.AttackGroup); if (groups.Any()) { var lastGroup = groups.OrderBy(x => x.Id).LastOrDefault(); if (lastGroup.StatusEnum == AttackGroupStatusEnum.Complete) { var group = CreateNewAttackGroup(recentAttack, blockedIps, blockedSubnets); _dbContext.AttackGroups.Add(group); lastGroup = group; attack = lastGroup.Attacks.LastOrDefault(); needNotify = true; } else { attack = lastGroup.Attacks.FirstOrDefault(x => x.Ip == recentAttack.Ip); if (attack != null) { if (attack.StatusEnum == AttackStatusEnum.Closing || attack.StatusEnum == AttackStatusEnum.Completed) { var prevStatus = (AttackStatusEnum)attack.Status; attack.Status = (int)AttackStatusEnum.Intersection; var history = AddNewAttackHistory(attack, prevStatus); needNotify = true; } else { ignoreAttacks.Add(attack); } } else { attack = AddNewAttack(recentAttack, lastGroup); var history = AddNewAttackHistory(attack, AttackStatusEnum.None); needNotify = true; } } } else { var group = CreateNewAttackGroup(recentAttack, blockedIps, blockedSubnets); _dbContext.AttackGroups.Add(group); attack = group.Attacks.LastOrDefault(); needNotify = true; } attack.IpBlocked = blockedIps.Any(x => x == recentAttack.Ip); try { attack.SubnetBlocked = blockedSubnets .Select(x => IPAddressRange.Parse(x)) .FirstOrDefault(x => x.Contains(IPAddress.Parse(recentAttack.Ip))) ?.ToCidrString(); } catch (Exception ex) { _logger.LogWarning(ex, ex.Message); } await _dbContext.SaveChangesAsync(); if (needNotify) { newAttacks.Add(attack); } } var treshholdCompleted = DateTimeOffset.UtcNow.AddDays(-1); var newIds = newAttacks.Select(x => x.Id).ToList(); var ignoreIds = ignoreAttacks.Select(x => x.Id).ToList(); var allIds = storedAttacks.Select(x => x.Id).ToList(); var notUpdatedIds = allIds.Except(newIds).Except(ignoreIds).ToList(); var notUpdatedAttacks = storedAttacks.Where(x => notUpdatedIds.Contains(x.Id)).ToList(); foreach (var attack in notUpdatedAttacks) { if (attack.AttackGroup.StatusEnum != AttackGroupStatusEnum.Complete) { var status = attack.StatusEnum; var history = _dbContext.AttackHistories.Where(x => x.AttackId == attack.Id).OrderBy(x => x.Id).LastOrDefault(); if (status == AttackStatusEnum.Intersection) { attack.Status = (int)AttackStatusEnum.Closing; AddNewAttackHistory(attack, AttackStatusEnum.Intersection); newAttacks.Add(attack); } else if (status == AttackStatusEnum.Closing) { if (history.Date < treshholdCompleted) { attack.Status = (int)AttackStatusEnum.Completed; AddNewAttackHistory(attack, AttackStatusEnum.Closing); newAttacks.Add(attack); } } } } await _dbContext.SaveChangesAsync(); _logger.LogInformation("Update DNS Attacks complete"); return(newAttacks.Select(x => x.Id).AsEnumerable()); }
public static List <IpV4Address> GetIpRange(string rangeString) => IPAddressRange.Parse(rangeString).AsEnumerable().Select(x => new IpV4Address(x.ToString())).ToList();
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 is 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); }
public void MyMethod() { IEnumerable <IPAddress> x = IPAddressRange.Parse("127.0.0.1/24"); var y = x.GetEnumerator(); }
public void Is_ScannerAddQueue_Run_Correctly(IPAddressRange ipAddressRange) { Assert.DoesNotThrowAsync(async() => { await _scanner.AddQueueAsync(ipAddressRange); }); Assert.IsNotNull(_scanner.ScannerQueues); CollectionAssert.IsNotEmpty(_scanner.ScannerQueues); }
public IPv4RangeOperator(IPAddressRange range) { Begin = range.Begin.ToUInt32(); End = range.End.ToUInt32(); }
public static IEnumerable <IPAddressRange> Is_ScannerAddQueue_Run_Correctly_TestCaseSource() { yield return(IPAddressRange.Parse("127.0.0.1-127.0.0.1")); }
private static void TestDB() { IPBanDB db = new IPBanDB(); db.Truncate(true); const string ip = "10.10.10.10"; DateTime dt1 = new DateTime(2018, 1, 1, 1, 1, 1, 1, DateTimeKind.Utc); DateTime dt2 = new DateTime(2019, 1, 1, 1, 1, 1, 1, DateTimeKind.Utc); int count = db.IncrementFailedLoginCount(ip, dt1, 1); if (count != 1) { throw new InvalidDataException("Failed login count is wrong"); } count = db.IncrementFailedLoginCount(ip, dt2, 2); if (count != 3) { throw new InvalidDataException("Failed login count is wrong"); } if (!db.SetBanDate(ip, dt2)) { throw new InvalidDataException("Ban date should have been set"); } if (db.SetBanDate(ip, dt2 + TimeSpan.FromDays(1.0))) // no effect { throw new InvalidDataException("Ban date should not have been set"); } IPBanDB.IPAddressEntry e = db.GetIPAddress(ip); if (e.IPAddress != ip) { throw new InvalidDataException("Wrong ip address from db"); } if (e.LastFailedLogin != dt2) { throw new InvalidDataException("Last failed login datetime is not correct"); } if (e.FailedLoginCount != 3) { throw new InvalidDataException("Last failed login count is not correct"); } if (e.BanDate != dt2) { throw new InvalidDataException("Ban date is not correct"); } count = db.IncrementFailedLoginCount("5.5.5.5", dt1, 2); if (count != 2) { throw new InvalidDataException("Count of failed login is wrong"); } count = db.GetIPAddressCount(); if (count != 2) { throw new InvalidDataException("Count of all ip is wrong"); } count = db.GetBannedIPAddressCount(); if (count != 1) { throw new InvalidDataException("Count of banned ip is wrong"); } DateTime?banDate = db.GetBanDate(ip); if (banDate != dt2) { throw new InvalidDataException("Ban date is wrong"); } banDate = db.GetBanDate("5.5.5.5"); if (banDate != null) { throw new InvalidDataException("Ban date is wrong"); } db.SetBannedIPAddresses(new string[] { ip, "5.5.5.5", "5.5.5.6", "::5.5.5.5", "6.6.6.6", "11.11.11.11", "12.12.12.12", "11.11.11.11" }, dt2); count = db.GetBannedIPAddressCount(); if (count != 7) { throw new InvalidDataException("Count of banned ip is wrong"); } IPAddressRange range = IPAddressRange.Parse("5.5.5.0/24"); count = 0; foreach (string ipAddress in db.DeleteIPAddresses(range)) { if (ipAddress != "5.5.5.5" && ipAddress != "5.5.5.6") { throw new InvalidDataException("Wrong ip address deleted from range"); } count++; } db.SetBannedIPAddresses(new string[] { "5.5.5.5", "5.5.5.6" }, dt2); if (db.IncrementFailedLoginCount("9.9.9.9", dt2, 1) != 1) { throw new InvalidDataException("Failed login count is wrong"); } count = 0; range = new IPAddressRange { Begin = System.Net.IPAddress.Parse("::5.5.5.0"), End = System.Net.IPAddress.Parse("::5.5.5.255") }; foreach (string ipAddress in db.DeleteIPAddresses(range)) { if (ipAddress != "::5.5.5.5") { throw new InvalidDataException("Wrong ip address deleted from range"); } count++; } if (count != 1) { throw new InvalidDataException("Wrong number of ip addresses deleted from range"); } IPBanDB.IPAddressEntry[] ipAll = db.EnumerateIPAddresses().ToArray(); if (ipAll.Length != 7) { throw new InvalidDataException("IP address count is wrong"); } IPBanDB.IPAddressEntry[] bannedIpAll = db.EnumerateBannedIPAddresses().ToArray(); if (bannedIpAll.Length != 6) { throw new InvalidDataException("Banned ip address count is wrong"); } string[] ips = new string[65536]; int index = 0; for (int i = 0; i < 256; i++) { for (int j = 0; j < 256; j++) { ips[index++] = "255." + i + ".255." + j; } } DateTime now = IPBanService.UtcNow; if (db.SetBannedIPAddresses(ips, dt2) != 65536) { throw new InvalidDataException("Invalid count for set banned ip addresses"); } if ((IPBanService.UtcNow - now).TotalSeconds > 5.0) { throw new InvalidDataException("SetBannedIPAddresses took too long"); } Console.WriteLine("IPBanDB test complete, no errors"); }
public void TestDB() { DateTime now = DateTime.UtcNow; using (IPBanDB db = new IPBanDB()) { db.Truncate(true); const string ip = "10.10.10.10"; DateTime dt1 = new DateTime(2018, 1, 1, 1, 1, 1, 1, DateTimeKind.Utc); DateTime dt2 = new DateTime(2019, 1, 1, 1, 1, 1, 1, DateTimeKind.Utc); int count = db.IncrementFailedLoginCount(ip, dt1, 1); Assert.AreEqual(1, count); Assert.AreEqual(1, db.EnumerateIPAddresses(dt1.AddMinutes(1.0)).Count()); count = db.IncrementFailedLoginCount(ip, dt2, 2); Assert.AreEqual(3, count); Assert.AreEqual(0, db.EnumerateIPAddresses(dt1.AddMinutes(1.0)).Count()); Assert.IsTrue(db.SetBanDate(ip, dt2)); // increment fail login for a ban or ban pending should do nothing Assert.AreEqual(3, db.IncrementFailedLoginCount(ip, dt2.AddSeconds(15.0f), 10)); Assert.IsFalse(db.SetBanDate(ip, dt2 + TimeSpan.FromDays(1.0))); // no effect IPBanDB.IPAddressEntry e = db.GetIPAddress(ip); Assert.AreEqual(ip, e.IPAddress); Assert.AreEqual(dt2, e.LastFailedLogin); Assert.AreEqual(3, e.FailedLoginCount); Assert.AreEqual(dt2, e.BanDate); count = db.IncrementFailedLoginCount("5.5.5.5", dt1, 2); Assert.AreEqual(2, count); count = db.GetIPAddressCount(); Assert.AreEqual(2, count); count = db.GetBannedIPAddressCount(); Assert.AreEqual(1, count); DateTime?banDate = db.GetBanDate(ip); Assert.IsNotNull(banDate); Assert.AreEqual(dt2, banDate); banDate = db.GetBanDate("5.5.5.5"); Assert.IsNull(banDate); count = db.SetBannedIPAddresses(new KeyValuePair <string, DateTime>[] { new KeyValuePair <string, DateTime>(ip, dt2), new KeyValuePair <string, DateTime>("5.5.5.5", dt2), new KeyValuePair <string, DateTime>("5.5.5.6", dt2), new KeyValuePair <string, DateTime>("::5.5.5.5", dt2), new KeyValuePair <string, DateTime>("6.6.6.6", dt2), new KeyValuePair <string, DateTime>("11.11.11.11", dt2), new KeyValuePair <string, DateTime>("12.12.12.12", dt2), new KeyValuePair <string, DateTime>("11.11.11.11", dt2) }); Assert.AreEqual(6, count); IPAddressRange range = IPAddressRange.Parse("5.5.5.0/24"); count = 0; foreach (string ipAddress in db.DeleteIPAddresses(range)) { Assert.IsTrue(ipAddress == "5.5.5.5" || ipAddress == "5.5.5.6"); count++; } db.SetBannedIPAddresses(new KeyValuePair <string, DateTime>[] { new KeyValuePair <string, DateTime>("5.5.5.5", dt2), new KeyValuePair <string, DateTime>("5.5.5.6", dt2) }); count = db.IncrementFailedLoginCount("9.9.9.9", dt2, 1); Assert.AreEqual(1, count); count = 0; range = new IPAddressRange { Begin = System.Net.IPAddress.Parse("::5.5.5.0"), End = System.Net.IPAddress.Parse("::5.5.5.255") }; foreach (string ipAddress in db.DeleteIPAddresses(range)) { Assert.AreEqual(ipAddress, "::5.5.5.5"); count++; } Assert.AreEqual(1, count); IPBanDB.IPAddressEntry[] ipAll = db.EnumerateIPAddresses().ToArray(); Assert.AreEqual(7, ipAll.Length); // ensure deltas work properly Assert.AreEqual(1, db.SetIPAddressesState(new string[] { "5.5.5.5" }, IPBanDB.IPAddressState.RemovePending)); IPBanFirewallIPAddressDelta[] deltas = db.EnumerateIPAddressesDelta(false).ToArray(); Assert.AreEqual(6, deltas.Length); Assert.AreEqual("10.10.10.10", deltas[0].IPAddress); Assert.AreEqual("11.11.11.11", deltas[1].IPAddress); Assert.AreEqual("12.12.12.12", deltas[2].IPAddress); Assert.AreEqual("5.5.5.5", deltas[3].IPAddress); Assert.AreEqual("5.5.5.6", deltas[4].IPAddress); Assert.AreEqual("6.6.6.6", deltas[5].IPAddress); Assert.IsTrue(deltas[0].Added); Assert.IsTrue(deltas[1].Added); Assert.IsTrue(deltas[2].Added); Assert.IsFalse(deltas[3].Added); Assert.IsTrue(deltas[4].Added); Assert.IsTrue(deltas[5].Added); deltas = db.EnumerateIPAddressesDelta(true).ToArray(); Assert.AreEqual(6, deltas.Length); Assert.AreEqual("10.10.10.10", deltas[0].IPAddress); Assert.AreEqual("11.11.11.11", deltas[1].IPAddress); Assert.AreEqual("12.12.12.12", deltas[2].IPAddress); Assert.AreEqual("5.5.5.5", deltas[3].IPAddress); Assert.AreEqual("5.5.5.6", deltas[4].IPAddress); Assert.AreEqual("6.6.6.6", deltas[5].IPAddress); Assert.IsTrue(deltas[0].Added); Assert.IsTrue(deltas[1].Added); Assert.IsTrue(deltas[2].Added); Assert.IsFalse(deltas[3].Added); Assert.IsTrue(deltas[4].Added); Assert.IsTrue(deltas[5].Added); string[] bannedIpAll = db.EnumerateBannedIPAddresses().ToArray(); Assert.AreEqual(5, bannedIpAll.Length); deltas = db.EnumerateIPAddressesDelta(true).ToArray(); Assert.AreEqual(0, deltas.Length); db.Truncate(true); KeyValuePair <string, DateTime>[] ips = new KeyValuePair <string, DateTime> [65536]; int index = 0; for (int i = 0; i < 256; i++) { for (int j = 0; j < 256; j++) { ips[index++] = new KeyValuePair <string, DateTime>("255." + i + ".255." + j, (now = now.AddMilliseconds(1))); } } count = db.SetBannedIPAddresses(ips); Assert.AreEqual(65536, count); Assert.AreEqual(65536 - 1634, db.EnumerateIPAddresses(null, now.Subtract(TimeSpan.FromMilliseconds(1634.0))).Count()); TimeSpan span = (DateTime.UtcNow - now); // make sure performance is good Assert.Less(span, TimeSpan.FromSeconds(10.0)); } }
public static IpAddressRangeWithWildcard Parse(string ipAddress) { return(new IpAddressRangeWithWildcard(IPAddressRange.Parse(ipAddress))); }
public void Count_IPv4_Test() { var ipAddressRange = IPAddressRange.Parse("10.0.0.0/8"); ipAddressRange.AsEnumerable().Count().Is(16777216); }
public void Count_IPv6_Test() { var ipAddressRange = IPAddressRange.Parse("fe80::0000:0000-fe80::0100:0001"); ipAddressRange.AsEnumerable().Count().Is(16777218); }
bool FncInLan(string serverIP) { try { List<IPAddressRange> lstLanIPAddrRange = new List<IPAddressRange>(); IPAddressRange ipRange = new IPAddressRange(); ipRange.lo = IPAddress.Parse("10.0.0.0"); ipRange.hi = IPAddress.Parse("10.255.255.255"); lstLanIPAddrRange.Add(ipRange); ipRange = new IPAddressRange(); ipRange.lo = IPAddress.Parse("172.16.0.0"); ipRange.hi = IPAddress.Parse("172.31.255.255"); lstLanIPAddrRange.Add(ipRange); ipRange = new IPAddressRange(); ipRange.lo = IPAddress.Parse("192.168.0.0"); ipRange.hi = IPAddress.Parse("192.168.255.255"); lstLanIPAddrRange.Add(ipRange); if (IsAddressInRange(IPAddress.Parse(serverIP), lstLanIPAddrRange)) { foreach (IPAddress ipaddress in (System.Net.Dns.GetHostEntry(System.Environment.MachineName)).AddressList) { if (ipaddress.AddressFamily.ToString() == "InterNetwork" && ipaddress.ToString() != "127.0.0.1") { string myIP = ipaddress.ToString().Substring(0, ipaddress.ToString().LastIndexOf(".")); string serIP = serverIP.Substring(0, serverIP.LastIndexOf(".")); if (myIP == serIP) { VMuktiAPI.VMuktiInfo.CurrentPeer.CurrentMachineIP = ipaddress.ToString(); IsAbleToBecomeSuperNode = true; break; } else { VMuktiAPI.VMuktiInfo.CurrentPeer.CurrentMachineIP = ipaddress.ToString(); IsAbleToBecomeSuperNode = false; } } } return true; } else { return false; } } catch (Exception ex) { VMuktiHelper.ExceptionHandler(ex, "FncInLan()", "App.xaml.cs"); return false; } }