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.

BlacklistModule.cs 5.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.Specialized;
  4. using System.IO;
  5. using System.Linq;
  6. using System.ServiceModel.Channels;
  7. using System.Web;
  8. using System.Web.Caching;
  9. using System.Web.Helpers;
  10. using System.Web.Mvc;
  11. using System.Web.Routing;
  12. using Teknik.Areas.Error.Controllers;
  13. using Teknik.Configuration;
  14. namespace Teknik.Modules
  15. {
  16. public class BlacklistModule : IHttpModule
  17. {
  18. private EventHandler onBeginRequest;
  19. public BlacklistModule()
  20. {
  21. onBeginRequest = new EventHandler(this.HandleBeginRequest);
  22. }
  23. void IHttpModule.Dispose()
  24. {
  25. }
  26. void IHttpModule.Init(HttpApplication context)
  27. {
  28. context.BeginRequest += onBeginRequest;
  29. }
  30. #region Referrer Info
  31. private const string BLOCKEDREFERRERKEY = "BlockedReferrer";
  32. private static string referrerFileName = null;
  33. private static object referrerFileNameObj = new object();
  34. public static string GetReferrerFilePath()
  35. {
  36. if (referrerFileName != null)
  37. return referrerFileName;
  38. lock (referrerFileNameObj)
  39. {
  40. if (referrerFileName == null)
  41. {
  42. Config config = Config.Load();
  43. referrerFileName = config.ReferrerBlacklistFile;
  44. }
  45. }
  46. return referrerFileName;
  47. }
  48. #endregion
  49. #region IP Info
  50. private const string BLOCKEDIPKEY = "BlockedIP";
  51. private static string ipFileName = null;
  52. private static object ipFileNameObj = new object();
  53. public static string GetIPFilePath()
  54. {
  55. if (ipFileName != null)
  56. return ipFileName;
  57. lock (ipFileNameObj)
  58. {
  59. if (ipFileName == null)
  60. {
  61. Config config = Config.Load();
  62. ipFileName = config.IPBlacklistFile;
  63. }
  64. }
  65. return ipFileName;
  66. }
  67. #endregion
  68. public static StringDictionary GetFileData(HttpContext context, string key, Func<string> fn)
  69. {
  70. StringDictionary data = (StringDictionary)context.Cache[key];
  71. if (data == null)
  72. {
  73. string filePath = fn();
  74. data = GetFileLines(filePath);
  75. context.Cache.Insert(key, data, new CacheDependency(filePath));
  76. }
  77. return data;
  78. }
  79. public static StringDictionary GetFileLines(string configPath)
  80. {
  81. StringDictionary retval = new StringDictionary();
  82. if (File.Exists(configPath))
  83. {
  84. using (StreamReader sr = new StreamReader(configPath))
  85. {
  86. String line;
  87. while ((line = sr.ReadLine()) != null)
  88. {
  89. line = line.Trim();
  90. if (line.Length != 0)
  91. {
  92. retval.Add(line, null);
  93. }
  94. }
  95. }
  96. }
  97. return retval;
  98. }
  99. private void HandleBeginRequest(object sender, EventArgs evargs)
  100. {
  101. HttpApplication app = sender as HttpApplication;
  102. if (app != null)
  103. {
  104. bool blocked = false;
  105. string blockReason = string.Empty;
  106. #region Detect Blacklisted IPs
  107. if (!blocked)
  108. {
  109. string IPAddr = app.Context.Request.ServerVariables["REMOTE_ADDR"];
  110. if (!string.IsNullOrEmpty(IPAddr))
  111. {
  112. StringDictionary badIPs = GetFileData(app.Context, BLOCKEDIPKEY, GetIPFilePath);
  113. blocked |= (badIPs != null && badIPs.ContainsKey(IPAddr));
  114. blockReason = $"This IP address ({IPAddr}) has been blacklisted. If you feel this is in error, please contact support@teknik.io for assistance.";
  115. }
  116. }
  117. #endregion
  118. #region Detect Blacklisted Referrers
  119. if (!blocked)
  120. {
  121. string referrer = app.Context.Request.UrlReferrer?.Host;
  122. if (!string.IsNullOrEmpty(referrer))
  123. {
  124. StringDictionary badReferrers = GetFileData(app.Context, BLOCKEDREFERRERKEY, GetReferrerFilePath);
  125. blocked |= (badReferrers != null && badReferrers.ContainsKey(referrer));
  126. blockReason = $"This referrer ({referrer}) has been blacklisted. If you feel this is in error, please contact support@teknik.io for assistance.";
  127. }
  128. }
  129. #endregion
  130. if (blocked)
  131. {
  132. // Clear the response
  133. app.Context.Response.Clear();
  134. RouteData routeData = new RouteData();
  135. routeData.DataTokens.Add("namespaces", new[] { typeof(ErrorController).Namespace });
  136. routeData.DataTokens.Add("area", "Error");
  137. routeData.Values.Add("controller", "Error");
  138. routeData.Values.Add("scheme", "https");
  139. routeData.Values.Add("action", "Http403");
  140. // Clear the error on server.
  141. app.Context.Server.ClearError();
  142. // Avoid IIS7 getting in the middle
  143. app.Context.Response.TrySkipIisCustomErrors = true;
  144. string jsonResult = Json.Encode(new { error = new { type = "Blacklist", message = blockReason } });
  145. app.Context.Response.Write(jsonResult);
  146. app.Context.Response.End();
  147. return;
  148. }
  149. }
  150. }
  151. }
  152. }