|
| 1 | +using EmbedIO.Utilities; |
| 2 | +using Swan; |
| 3 | +using Swan.Logging; |
| 4 | +using Swan.Threading; |
| 5 | +using System; |
| 6 | +using System.Collections.Concurrent; |
| 7 | +using System.Collections.Generic; |
| 8 | +using System.Linq; |
| 9 | +using System.Net; |
| 10 | +using System.Text.RegularExpressions; |
| 11 | +using System.Threading; |
| 12 | +using System.Threading.Tasks; |
| 13 | + |
| 14 | +namespace EmbedIO.Security |
| 15 | +{ |
| 16 | + /// <summary> |
| 17 | + /// A module for ban IPs that show the malicious signs, based on scanning log messages. |
| 18 | + /// </summary> |
| 19 | + /// <seealso cref="WebModuleBase" /> |
| 20 | + public class IPBanningModule : WebModuleBase, ILogger |
| 21 | + { |
| 22 | + /// <summary> |
| 23 | + /// The default ban time, in minutes. |
| 24 | + /// </summary> |
| 25 | + public const int DefaultBanTime = 30; |
| 26 | + |
| 27 | + /// <summary> |
| 28 | + /// The default maximum retries per minute. |
| 29 | + /// </summary> |
| 30 | + public const int DefaultMaxRetry = 10; |
| 31 | + |
| 32 | + private static readonly ConcurrentDictionary<IPAddress, ConcurrentBag<long>> AccessAttempts = new ConcurrentDictionary<IPAddress, ConcurrentBag<long>>(); |
| 33 | + private static readonly ConcurrentDictionary<IPAddress, BannedInfo> Blacklist = new ConcurrentDictionary<IPAddress, BannedInfo>(); |
| 34 | + private static readonly ConcurrentDictionary<string, Regex> FailRegex = new ConcurrentDictionary<string, Regex>(); |
| 35 | + private static readonly PeriodicTask? Purger; |
| 36 | + |
| 37 | + private readonly List<IPAddress> _whitelist = new List<IPAddress>(); |
| 38 | + private readonly int _banTime; |
| 39 | + private readonly int _maxRetry; |
| 40 | + private bool _disposedValue; |
| 41 | + |
| 42 | + static IPBanningModule() |
| 43 | + { |
| 44 | + Purger = new PeriodicTask(TimeSpan.FromMinutes(1), ct => |
| 45 | + { |
| 46 | + PurgeBlackList(); |
| 47 | + PurgeAccessAttempts(); |
| 48 | + |
| 49 | + return Task.CompletedTask; |
| 50 | + }); |
| 51 | + } |
| 52 | + |
| 53 | + /// <summary> |
| 54 | + /// Initializes a new instance of the <see cref="IPBanningModule"/> class. |
| 55 | + /// </summary> |
| 56 | + /// <param name="baseRoute">The base route.</param> |
| 57 | + /// <param name="failRegex">A collection of regex to match the log messages against.</param> |
| 58 | + /// <param name="banTime">The time that an IP will remain ban, in minutes.</param> |
| 59 | + /// <param name="maxRetry">The maximum number of failed attempts before banning an IP.</param> |
| 60 | + public IPBanningModule(string baseRoute, |
| 61 | + IEnumerable<string> failRegex, |
| 62 | + int banTime = DefaultBanTime, |
| 63 | + int maxRetry = DefaultMaxRetry) |
| 64 | + : this(baseRoute, failRegex, null, banTime, maxRetry) |
| 65 | + { |
| 66 | + } |
| 67 | + |
| 68 | + /// <summary> |
| 69 | + /// Initializes a new instance of the <see cref="IPBanningModule"/> class. |
| 70 | + /// </summary> |
| 71 | + /// <param name="baseRoute">The base route.</param> |
| 72 | + /// <param name="failRegex">A collection of regex to match the log messages against.</param> |
| 73 | + /// <param name="whitelist">A collection of valid IPs that never will be banned.</param> |
| 74 | + /// <param name="banTime">The time that an IP will remain ban, in minutes.</param> |
| 75 | + /// <param name="maxRetry">The maximum number of failed attempts before banning an IP.</param> |
| 76 | + public IPBanningModule(string baseRoute, |
| 77 | + IEnumerable<string>? failRegex = null, |
| 78 | + IEnumerable<string>? whitelist = null, |
| 79 | + int banTime = DefaultBanTime, |
| 80 | + int maxRetry = DefaultMaxRetry) |
| 81 | + : base(baseRoute) |
| 82 | + { |
| 83 | + if (failRegex != null) |
| 84 | + AddRules(failRegex); |
| 85 | + |
| 86 | + _banTime = banTime; |
| 87 | + _maxRetry = maxRetry; |
| 88 | + AddToWhitelist(whitelist); |
| 89 | + Logger.RegisterLogger(this); |
| 90 | + } |
| 91 | + |
| 92 | + /// <inheritdoc /> |
| 93 | + public override bool IsFinalHandler => false; |
| 94 | + |
| 95 | + /// <inheritdoc /> |
| 96 | + public LogLevel LogLevel => LogLevel.Trace; |
| 97 | + |
| 98 | + private IPAddress? ClientAddress { get; set; } |
| 99 | + |
| 100 | + /// <summary> |
| 101 | + /// Gets the list of current banned IPs. |
| 102 | + /// </summary> |
| 103 | + /// <returns>A collection of <see cref="BannedInfo"/> in the blacklist.</returns> |
| 104 | + public static IEnumerable<BannedInfo> GetBannedIPs() => |
| 105 | + Blacklist.Values.ToList(); |
| 106 | + |
| 107 | + /// <summary> |
| 108 | + /// Tries to ban an IP explicitly. |
| 109 | + /// </summary> |
| 110 | + /// <param name="address">The IP address to ban.</param> |
| 111 | + /// <param name="minutes">The time in minutes that the IP will remain ban.</param> |
| 112 | + /// <param name="isExplicit">if set to <c>true</c> [is explicit].</param> |
| 113 | + /// <returns> |
| 114 | + /// <c>true</c> if the IP was added to the blacklist; otherwise, <c>false</c>. |
| 115 | + /// </returns> |
| 116 | + public static bool TryBanIP(IPAddress address, int minutes, bool isExplicit = true) => |
| 117 | + TryBanIP(address, DateTime.Now.AddMinutes(minutes), isExplicit); |
| 118 | + |
| 119 | + /// <summary> |
| 120 | + /// Tries to ban an IP explicitly. |
| 121 | + /// </summary> |
| 122 | + /// <param name="address">The IP address to ban.</param> |
| 123 | + /// <param name="banTime">An <see cref="TimeSpan"/> that sets the time the IP will remain ban.</param> |
| 124 | + /// <param name="isExplicit">if set to <c>true</c> [is explicit].</param> |
| 125 | + /// <returns> |
| 126 | + /// <c>true</c> if the IP was added to the blacklist; otherwise, <c>false</c>. |
| 127 | + /// </returns> |
| 128 | + public static bool TryBanIP(IPAddress address, TimeSpan banTime, bool isExplicit = true) => |
| 129 | + TryBanIP(address, DateTime.Now.Add(banTime), isExplicit); |
| 130 | + |
| 131 | + /// <summary> |
| 132 | + /// Tries to ban an IP explicitly. |
| 133 | + /// </summary> |
| 134 | + /// <param name="address">The IP address to ban.</param> |
| 135 | + /// <param name="banUntil">A <see cref="DateTime"/> that sets until when the IP will remain ban.</param> |
| 136 | + /// <param name="isExplicit">if set to <c>true</c> [is explicit].</param> |
| 137 | + /// <returns> |
| 138 | + /// <c>true</c> if the IP was added to the blacklist; otherwise, <c>false</c>. |
| 139 | + /// </returns> |
| 140 | + public static bool TryBanIP(IPAddress address, DateTime banUntil, bool isExplicit = true) |
| 141 | + { |
| 142 | + if (Blacklist.ContainsKey(address)) |
| 143 | + { |
| 144 | + var bannedInfo = Blacklist[address]; |
| 145 | + bannedInfo.BanUntil = banUntil.Ticks; |
| 146 | + bannedInfo.IsExplicit = isExplicit; |
| 147 | + |
| 148 | + return true; |
| 149 | + } |
| 150 | + |
| 151 | + return Blacklist.TryAdd(address, new BannedInfo() |
| 152 | + { |
| 153 | + IPAddress = address, |
| 154 | + BanUntil = banUntil.Ticks, |
| 155 | + IsExplicit = isExplicit, |
| 156 | + }); |
| 157 | + } |
| 158 | + |
| 159 | + /// <summary> |
| 160 | + /// Tries to unban an IP explicitly. |
| 161 | + /// </summary> |
| 162 | + /// <param name="address">The IP address.</param> |
| 163 | + /// <returns> |
| 164 | + /// <c>true</c> if the IP was removed from the blacklist; otherwise, <c>false</c>. |
| 165 | + /// </returns> |
| 166 | + public static bool TryUnbanIP(IPAddress address) => |
| 167 | + Blacklist.TryRemove(address, out _); |
| 168 | + |
| 169 | + /// <inheritdoc /> |
| 170 | + public void Log(LogMessageReceivedEventArgs logEvent) |
| 171 | + { |
| 172 | + // Process Log |
| 173 | + if (string.IsNullOrWhiteSpace(logEvent.Message) || |
| 174 | + ClientAddress == null || |
| 175 | + !FailRegex.Any() || |
| 176 | + _whitelist.Contains(ClientAddress) || |
| 177 | + Blacklist.ContainsKey(ClientAddress)) |
| 178 | + return; |
| 179 | + |
| 180 | + foreach (var regex in FailRegex.Values) |
| 181 | + { |
| 182 | + try |
| 183 | + { |
| 184 | + if (!regex.IsMatch(logEvent.Message)) continue; |
| 185 | + |
| 186 | + // Add to list |
| 187 | + AddAccessAttempt(ClientAddress); |
| 188 | + UpdateBlackList(); |
| 189 | + break; |
| 190 | + } |
| 191 | + catch (RegexMatchTimeoutException ex) |
| 192 | + { |
| 193 | + $"Timeout trying to match '{ex.Input}' with pattern '{ex.Pattern}'.".Error(nameof(IPBanningModule)); |
| 194 | + } |
| 195 | + } |
| 196 | + } |
| 197 | + |
| 198 | + /// <inheritdoc /> |
| 199 | + public void Dispose() => |
| 200 | + Dispose(true); |
| 201 | + |
| 202 | + internal void AddRules(IEnumerable<string> patterns) |
| 203 | + { |
| 204 | + foreach (var pattern in patterns) |
| 205 | + AddRule(pattern); |
| 206 | + } |
| 207 | + |
| 208 | + internal void AddRule(string pattern) |
| 209 | + { |
| 210 | + try |
| 211 | + { |
| 212 | + FailRegex.TryAdd(pattern, new Regex(pattern, RegexOptions.Compiled | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(500))); |
| 213 | + } |
| 214 | + catch (Exception ex) |
| 215 | + { |
| 216 | + ex.Log(nameof(IPBanningModule), $"Invalid regex - '{pattern}'."); |
| 217 | + } |
| 218 | + } |
| 219 | + |
| 220 | + internal void AddToWhitelist(IEnumerable<string> whitelist) => |
| 221 | + AddToWhitelistAsync(whitelist).GetAwaiter().GetResult(); |
| 222 | + |
| 223 | + internal async Task AddToWhitelistAsync(IEnumerable<string> whitelist) |
| 224 | + { |
| 225 | + if (whitelist?.Any() != true) |
| 226 | + return; |
| 227 | + |
| 228 | + foreach (var address in whitelist) |
| 229 | + { |
| 230 | + var addressees = await IPParser.Parse(address).ConfigureAwait(false); |
| 231 | + _whitelist.AddRange(addressees.Where(x => !_whitelist.Contains(x))); |
| 232 | + } |
| 233 | + } |
| 234 | + |
| 235 | + /// <inheritdoc /> |
| 236 | + protected override Task OnRequestAsync(IHttpContext context) |
| 237 | + { |
| 238 | + ClientAddress = context.Request.RemoteEndPoint.Address; |
| 239 | + if (!Blacklist.ContainsKey(ClientAddress)) |
| 240 | + return Task.CompletedTask; |
| 241 | + |
| 242 | + context.SetHandled(); |
| 243 | + throw HttpException.Forbidden(); |
| 244 | + } |
| 245 | + |
| 246 | + /// <summary> |
| 247 | + /// Releases unmanaged and - optionally - managed resources. |
| 248 | + /// </summary> |
| 249 | + /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> |
| 250 | + protected virtual void Dispose(bool disposing) |
| 251 | + { |
| 252 | + if (_disposedValue) return; |
| 253 | + if (disposing) |
| 254 | + { |
| 255 | + _whitelist.Clear(); |
| 256 | + } |
| 257 | + |
| 258 | + _disposedValue = true; |
| 259 | + } |
| 260 | + |
| 261 | + private static void AddAccessAttempt(IPAddress address) |
| 262 | + { |
| 263 | + if (AccessAttempts.ContainsKey(address)) |
| 264 | + AccessAttempts[address].Add(DateTime.Now.Ticks); |
| 265 | + else |
| 266 | + AccessAttempts.TryAdd(address, new ConcurrentBag<long>() { DateTime.Now.Ticks }); |
| 267 | + } |
| 268 | + |
| 269 | + private static void PurgeBlackList() |
| 270 | + { |
| 271 | + foreach (var k in Blacklist.Keys) |
| 272 | + { |
| 273 | + if (DateTime.Now.Ticks > Blacklist[k].BanUntil) |
| 274 | + Blacklist.TryRemove(k, out _); |
| 275 | + } |
| 276 | + } |
| 277 | + |
| 278 | + private static void PurgeAccessAttempts() |
| 279 | + { |
| 280 | + var banDate = DateTime.Now.AddMinutes(-1).Ticks; |
| 281 | + |
| 282 | + foreach (var k in AccessAttempts.Keys) |
| 283 | + { |
| 284 | + var recentAttempts = new ConcurrentBag<long>(AccessAttempts[k].Where(x => x >= banDate)); |
| 285 | + if (!recentAttempts.Any()) |
| 286 | + AccessAttempts.TryRemove(k, out _); |
| 287 | + else |
| 288 | + Interlocked.Exchange(ref recentAttempts, AccessAttempts[k]); |
| 289 | + } |
| 290 | + } |
| 291 | + |
| 292 | + private void UpdateBlackList() |
| 293 | + { |
| 294 | + var time = DateTime.Now.AddMinutes(-1).Ticks; |
| 295 | + if ((AccessAttempts[ClientAddress]?.Where(x => x >= time).Count() >= _maxRetry)) |
| 296 | + { |
| 297 | + TryBanIP(ClientAddress, _banTime, false); |
| 298 | + } |
| 299 | + } |
| 300 | + } |
| 301 | +} |
0 commit comments