The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BlacklistMiddleware.cs 3.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. using Microsoft.AspNetCore.Builder;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.AspNetCore.Routing;
  4. using Microsoft.Extensions.Caching.Memory;
  5. using Newtonsoft.Json;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Collections.Specialized;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Threading.Tasks;
  12. using Teknik.Configuration;
  13. namespace Teknik.IdentityServer.Middleware
  14. {
  15. public class BlacklistMiddleware
  16. {
  17. private readonly RequestDelegate _next;
  18. private readonly IMemoryCache _cache;
  19. public BlacklistMiddleware(RequestDelegate next, IMemoryCache cache)
  20. {
  21. _next = next;
  22. _cache = cache;
  23. }
  24. public async Task Invoke(HttpContext context, Config config)
  25. {
  26. // Beggining of Request
  27. bool blocked = false;
  28. string blockReason = string.Empty;
  29. #region Detect Blacklisted IPs
  30. if (!blocked)
  31. {
  32. string IPAddr = context.Request.HttpContext.Connection.RemoteIpAddress.ToString();
  33. if (!string.IsNullOrEmpty(IPAddr))
  34. {
  35. StringDictionary badIPs = GetFileData(context, "BlockedIPs", config.IPBlacklistFile);
  36. blocked |= (badIPs != null && badIPs.ContainsKey(IPAddr));
  37. blockReason = $"This IP address ({IPAddr}) has been blacklisted. If you feel this is in error, please contact support@teknik.io for assistance.";
  38. }
  39. }
  40. #endregion
  41. #region Detect Blacklisted Referrers
  42. if (!blocked)
  43. {
  44. string referrer = context.Request.Headers["Referer"].ToString();
  45. if (!string.IsNullOrEmpty(referrer))
  46. {
  47. StringDictionary badReferrers = GetFileData(context, "BlockedReferrers", config.ReferrerBlacklistFile);
  48. blocked |= (badReferrers != null && badReferrers.ContainsKey(referrer));
  49. blockReason = $"This referrer ({referrer}) has been blacklisted. If you feel this is in error, please contact support@teknik.io for assistance.";
  50. }
  51. }
  52. #endregion
  53. if (blocked)
  54. {
  55. // Clear the response
  56. context.Response.Clear();
  57. string jsonResult = JsonConvert.SerializeObject(new { error = new { type = "Blacklist", message = blockReason } });
  58. await context.Response.WriteAsync(jsonResult);
  59. return;
  60. }
  61. await _next.Invoke(context);
  62. // End of request
  63. }
  64. public StringDictionary GetFileData(HttpContext context, string key, string filePath)
  65. {
  66. StringDictionary data;
  67. if (!_cache.TryGetValue(key, out data))
  68. {
  69. data = GetFileLines(filePath);
  70. _cache.Set(key, data);
  71. }
  72. return data;
  73. }
  74. public StringDictionary GetFileLines(string configPath)
  75. {
  76. StringDictionary retval = new StringDictionary();
  77. if (File.Exists(configPath))
  78. {
  79. using (StreamReader sr = new StreamReader(configPath))
  80. {
  81. String line;
  82. while ((line = sr.ReadLine()) != null)
  83. {
  84. line = line.Trim();
  85. if (line.Length != 0)
  86. {
  87. retval.Add(line, null);
  88. }
  89. }
  90. }
  91. }
  92. return retval;
  93. }
  94. }
  95. public static class BlacklistMiddlewareExtensions
  96. {
  97. public static IApplicationBuilder UseBlacklist(this IApplicationBuilder builder)
  98. {
  99. return builder.UseMiddleware<BlacklistMiddleware>();
  100. }
  101. }
  102. }