FirewallAttribute.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. using CacheManager.Core;
  2. using Masuit.MyBlogs.Core.Common;
  3. using Masuit.MyBlogs.Core.Configs;
  4. using Masuit.MyBlogs.Core.Models.ViewModel;
  5. using Masuit.Tools;
  6. using Masuit.Tools.AspNetCore.Mime;
  7. using Masuit.Tools.Logging;
  8. using Masuit.Tools.Security;
  9. using Masuit.Tools.Strings;
  10. using Microsoft.AspNetCore.Http;
  11. using Microsoft.AspNetCore.Mvc;
  12. using Microsoft.AspNetCore.Mvc.Filters;
  13. using System;
  14. using System.Linq;
  15. using System.Net;
  16. using System.Text;
  17. using System.Text.RegularExpressions;
  18. using System.Web;
  19. using HeaderNames = Microsoft.Net.Http.Headers.HeaderNames;
  20. namespace Masuit.MyBlogs.Core.Extensions.Firewall
  21. {
  22. public class FirewallAttribute : ActionFilterAttribute
  23. {
  24. public ICacheManager<int> CacheManager { get; set; }
  25. public IFirewallRepoter FirewallRepoter { get; set; }
  26. /// <inheritdoc />
  27. public override void OnActionExecuting(ActionExecutingContext context)
  28. {
  29. var request = context.HttpContext.Request;
  30. var ip = context.HttpContext.Connection.RemoteIpAddress.ToString();
  31. var tokenValid = request.Cookies["Email"].MDString3(AppConfig.BaiduAK).Equals(request.Cookies["FullAccessToken"]);
  32. //黑名单
  33. if (ip.IsDenyIpAddress() && !tokenValid)
  34. {
  35. AccessDeny(ip, request, "黑名单IP地址");
  36. context.Result = new BadRequestObjectResult("您当前所在的网络环境不支持访问本站!");
  37. return;
  38. }
  39. //bypass
  40. if (CommonHelper.SystemSettings.GetOrAdd("FirewallEnabled", "true") == "false" || context.Filters.Any(m => m.ToString().Contains(new[] { nameof(AllowAccessFirewallAttribute), nameof(MyAuthorizeAttribute) })) || tokenValid)
  41. {
  42. return;
  43. }
  44. //UserAgent
  45. var ua = request.Headers[HeaderNames.UserAgent] + "";
  46. var blocked = CommonHelper.SystemSettings.GetOrAdd("UserAgentBlocked", "").Split(new[] { ',', '|' }, StringSplitOptions.RemoveEmptyEntries);
  47. if (ua.Contains(blocked))
  48. {
  49. var agent = UserAgent.Parse(ua);
  50. AccessDeny(ip, request, $"UA黑名单({agent.Browser} {agent.BrowserVersion}/{agent.Platform})");
  51. var msg = CommonHelper.SystemSettings.GetOrAdd("UserAgentBlockedMsg", "当前浏览器不支持访问本站");
  52. context.Result = new ContentResult()
  53. {
  54. Content = Template.Create(msg).Set("browser", agent.Browser + " " + agent.BrowserVersion).Set("os", agent.Platform).Render(),
  55. ContentType = ContentType.Html,
  56. StatusCode = 403
  57. };
  58. return;
  59. }
  60. //搜索引擎
  61. if (Regex.IsMatch(request.Method, "OPTIONS|HEAD", RegexOptions.IgnoreCase) || request.IsRobot())
  62. {
  63. return;
  64. }
  65. DenyArea(ip, request);//禁区
  66. Challenge(context, request);//挑战模式
  67. ThrottleLimit(ip, request);//限流
  68. }
  69. private void DenyArea(string ip, HttpRequest request)
  70. {
  71. if (ip.IsInDenyArea())
  72. {
  73. AccessDeny(ip, request, "访问地区限制");
  74. throw new AccessDenyException("访问地区限制");
  75. }
  76. }
  77. private void ThrottleLimit(string ip, HttpRequest request)
  78. {
  79. var times = CacheManager.AddOrUpdate("Frequency:" + ip, 1, i => i + 1, 5);
  80. CacheManager.Expire("Frequency:" + ip, ExpirationMode.Absolute, TimeSpan.FromSeconds(CommonHelper.SystemSettings.GetOrAdd("LimitIPFrequency", "60").ToInt32()));
  81. var limit = CommonHelper.SystemSettings.GetOrAdd("LimitIPRequestTimes", "90").ToInt32();
  82. if (times <= limit)
  83. {
  84. return;
  85. }
  86. if (times > limit * 1.2)
  87. {
  88. CacheManager.Expire("Frequency:" + ip, TimeSpan.FromMinutes(CommonHelper.SystemSettings.GetOrAdd("BanIPTimespan", "10").ToInt32()));
  89. AccessDeny(ip, request, "访问频次限制");
  90. }
  91. throw new TempDenyException("访问频次限制");
  92. }
  93. private static void Challenge(ActionExecutingContext context, HttpRequest request)
  94. {
  95. if (!context.HttpContext.Session.TryGetValue("js-challenge", out _))
  96. {
  97. try
  98. {
  99. if (request.Cookies.TryGetValue(SessionKey.ChallengeBypass, out var time) && time.AESDecrypt(AppConfig.BaiduAK).ToDateTime() > DateTime.Now)
  100. {
  101. return;
  102. }
  103. }
  104. catch
  105. {
  106. // ignored
  107. }
  108. var mode = CommonHelper.SystemSettings.GetOrAdd(SessionKey.ChallengeMode, "");
  109. if (mode == SessionKey.JSChallenge)
  110. {
  111. context.Result = new ViewResult()
  112. {
  113. ViewName = "/Views/Shared/JSChallenge.cshtml"
  114. };
  115. }
  116. if (mode == SessionKey.CaptchaChallenge)
  117. {
  118. context.Result = new ViewResult()
  119. {
  120. ViewName = "/Views/Shared/CaptchaChallenge.cshtml"
  121. };
  122. }
  123. }
  124. }
  125. private async void AccessDeny(string ip, HttpRequest request, string remark)
  126. {
  127. var path = HttpUtility.UrlDecode(request.Path + request.QueryString, Encoding.UTF8);
  128. await RedisHelper.IncrByAsync("interceptCount");
  129. await RedisHelper.LPushAsync("intercept", new IpIntercepter()
  130. {
  131. IP = ip,
  132. RequestUrl = HttpUtility.UrlDecode(request.Scheme + "://" + request.Host + path),
  133. Time = DateTime.Now,
  134. Referer = request.Headers[HeaderNames.Referer],
  135. UserAgent = request.Headers[HeaderNames.UserAgent],
  136. Remark = remark,
  137. Address = request.Location(),
  138. HttpVersion = request.Protocol,
  139. Headers = request.Headers.ToJsonString()
  140. });
  141. var limit = CommonHelper.SystemSettings.GetOrAdd("LimitIPInterceptTimes", "30").ToInt32();
  142. await RedisHelper.LRangeAsync<IpIntercepter>("intercept", 0, -1).ContinueWith(async t =>
  143. {
  144. if (t.Result.Count(x => x.IP == ip) >= limit)
  145. {
  146. LogManager.Info($"准备上报IP{ip}到{FirewallRepoter.ReporterName}");
  147. await FirewallRepoter.ReportAsync(IPAddress.Parse(ip)).ContinueWith(_ => LogManager.Info($"访问频次限制,已上报IP{ip}至:" + FirewallRepoter.ReporterName));
  148. }
  149. });
  150. }
  151. }
  152. }