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 4.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  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.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. string referrerHost = referrer;
  46. try
  47. {
  48. var referrerUri = new Uri(referrer);
  49. referrerHost = referrerUri.Host;
  50. } catch
  51. { }
  52. if (!string.IsNullOrEmpty(referrer))
  53. {
  54. StringDictionary badReferrers = GetFileData(context, "BlockedReferrers", config.ReferrerBlacklistFile);
  55. if (badReferrers != null)
  56. {
  57. blocked |= badReferrers.ContainsKey(referrer) || badReferrers.ContainsKey(referrerHost);
  58. blockReason = $"This referrer ({referrer}) has been blacklisted. If you feel this is in error, please contact support@teknik.io for assistance.";
  59. }
  60. }
  61. }
  62. #endregion
  63. if (blocked)
  64. {
  65. // Clear the response
  66. context.Response.Clear();
  67. string jsonResult = JsonConvert.SerializeObject(new { error = new { type = "Blacklist", message = blockReason } });
  68. await context.Response.WriteAsync(jsonResult);
  69. return;
  70. }
  71. await _next.Invoke(context);
  72. // End of request
  73. }
  74. public StringDictionary GetFileData(HttpContext context, string key, string filePath)
  75. {
  76. StringDictionary data;
  77. if (!_cache.TryGetValue(key, out data))
  78. {
  79. data = GetFileLines(filePath);
  80. _cache.Set(key, data);
  81. }
  82. return data;
  83. }
  84. public StringDictionary GetFileLines(string configPath)
  85. {
  86. StringDictionary retval = new StringDictionary();
  87. if (File.Exists(configPath))
  88. {
  89. using (StreamReader sr = new StreamReader(configPath))
  90. {
  91. String line;
  92. while ((line = sr.ReadLine()) != null)
  93. {
  94. line = line.Trim();
  95. if (line.Length != 0)
  96. {
  97. retval.Add(line, null);
  98. }
  99. }
  100. }
  101. }
  102. return retval;
  103. }
  104. }
  105. public static class BlacklistMiddlewareExtensions
  106. {
  107. public static IApplicationBuilder UseBlacklist(this IApplicationBuilder builder)
  108. {
  109. return builder.UseMiddleware<BlacklistMiddleware>();
  110. }
  111. }
  112. }