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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  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. public static StringDictionary GetFileData(HttpContext context, string key, string filePath)
  31. {
  32. StringDictionary data = (StringDictionary)context.Cache[key];
  33. if (data == null)
  34. {
  35. data = GetFileLines(filePath);
  36. context.Cache.Insert(key, data, new CacheDependency(filePath));
  37. }
  38. return data;
  39. }
  40. public static StringDictionary GetFileLines(string configPath)
  41. {
  42. StringDictionary retval = new StringDictionary();
  43. if (File.Exists(configPath))
  44. {
  45. using (StreamReader sr = new StreamReader(configPath))
  46. {
  47. String line;
  48. while ((line = sr.ReadLine()) != null)
  49. {
  50. line = line.Trim();
  51. if (line.Length != 0)
  52. {
  53. retval.Add(line, null);
  54. }
  55. }
  56. }
  57. }
  58. return retval;
  59. }
  60. private void HandleBeginRequest(object sender, EventArgs evargs)
  61. {
  62. HttpApplication app = sender as HttpApplication;
  63. if (app != null)
  64. {
  65. Config config = Config.Load();
  66. bool blocked = false;
  67. string blockReason = string.Empty;
  68. #region Detect Blacklisted IPs
  69. if (!blocked)
  70. {
  71. string IPAddr = app.Context.Request.ServerVariables["REMOTE_ADDR"];
  72. if (!string.IsNullOrEmpty(IPAddr))
  73. {
  74. StringDictionary badIPs = GetFileData(app.Context, "BlockedIPs", config.IPBlacklistFile);
  75. blocked |= (badIPs != null && badIPs.ContainsKey(IPAddr));
  76. blockReason = $"This IP address ({IPAddr}) has been blacklisted. If you feel this is in error, please contact support@teknik.io for assistance.";
  77. }
  78. }
  79. #endregion
  80. #region Detect Blacklisted Referrers
  81. if (!blocked)
  82. {
  83. string referrer = app.Context.Request.UrlReferrer?.Host;
  84. if (!string.IsNullOrEmpty(referrer))
  85. {
  86. StringDictionary badReferrers = GetFileData(app.Context, "BlockedReferrers", config.ReferrerBlacklistFile);
  87. blocked |= (badReferrers != null && badReferrers.ContainsKey(referrer));
  88. blockReason = $"This referrer ({referrer}) has been blacklisted. If you feel this is in error, please contact support@teknik.io for assistance.";
  89. }
  90. }
  91. #endregion
  92. if (blocked)
  93. {
  94. // Clear the response
  95. app.Context.Response.Clear();
  96. RouteData routeData = new RouteData();
  97. routeData.DataTokens.Add("namespaces", new[] { typeof(ErrorController).Namespace });
  98. routeData.DataTokens.Add("area", "Error");
  99. routeData.Values.Add("controller", "Error");
  100. routeData.Values.Add("scheme", "https");
  101. routeData.Values.Add("action", "Http403");
  102. // Clear the error on server.
  103. app.Context.Server.ClearError();
  104. // Avoid IIS7 getting in the middle
  105. app.Context.Response.TrySkipIisCustomErrors = true;
  106. string jsonResult = Json.Encode(new { error = new { type = "Blacklist", message = blockReason } });
  107. app.Context.Response.Write(jsonResult);
  108. app.Context.Response.End();
  109. return;
  110. }
  111. }
  112. }
  113. }
  114. }