コード例 #1
0
        /// <inheritdoc />
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (context.Filters.Any(m => m.ToString().Contains(nameof(AllowAccessFirewallAttribute))))
            {
                return;
            }

            var request    = context.HttpContext.Request;
            var httpMethod = request.Method;

            if (httpMethod.Equals("OPTIONS", StringComparison.InvariantCultureIgnoreCase) || httpMethod.Equals("HEAD", StringComparison.InvariantCultureIgnoreCase))
            {
                return;
            }

            if (request.Cookies["Email"].MDString3(AppConfig.BaiduAK).Equals(request.Cookies["FullAccessToken"]))
            {
                return;
            }

            var ip = context.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();

            if (ip.IsDenyIpAddress() && string.IsNullOrEmpty(context.HttpContext.Session.Get <string>("FullAccessViewToken")))
            {
                AccessDeny(context, ip, request);
                return;
            }

            if (request.IsRobot())
            {
                return;
            }

            var times = CacheManager.AddOrUpdate("Frequency:" + ip, 1, i => i + 1, 5);

            CacheManager.Expire("Frequency:" + ip, ExpirationMode.Sliding, TimeSpan.FromSeconds(CommonHelper.SystemSettings.GetOrAdd("LimitIPFrequency", "60").ToInt32()));
            var limit = CommonHelper.SystemSettings.GetOrAdd("LimitIPRequestTimes", "90").ToInt32();

            if (times <= limit)
            {
                return;
            }

            if (times > limit * 1.2)
            {
                CacheManager.Expire("Frequency:" + ip, ExpirationMode.Sliding, TimeSpan.FromMinutes(CommonHelper.SystemSettings.GetOrAdd("BanIPTimespan", "10").ToInt32()));
                var path = HttpUtility.UrlDecode(request.Path + request.QueryString, Encoding.UTF8);
                BackgroundJob.Enqueue(() => HangfireBackJob.InterceptLog(new IpIntercepter()
                {
                    IP         = ip,
                    RequestUrl = HttpUtility.UrlDecode(request.Scheme + "://" + request.Host + path),
                    Time       = DateTime.Now,
                    UserAgent  = request.Headers[HeaderNames.UserAgent]
                }));
            }

            context.Result = new RedirectResult("/tempdeny");
        }
コード例 #2
0
        /// <summary>
        /// 执行调用
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            string httpMethod = context.Request.Method;

            if (httpMethod.Equals("OPTIONS", StringComparison.InvariantCultureIgnoreCase) || httpMethod.Equals("HEAD", StringComparison.InvariantCultureIgnoreCase))
            {
                return;
            }

            if (context.Request.IsRobot())
            {
                await _next.Invoke(context);

                return;
            }

            if (context.Request.Path.ToString().Contains(new[] { "error", "serviceunavailable" }))
            {
                await _next.Invoke(context);

                return;
            }

            string ip = context.Connection.RemoteIpAddress.MapToIPv4().ToString();

            if (ip.IsDenyIpAddress())
            {
                context.Response.StatusCode = 403;
                await context.Response.WriteAsync($"检测到您的IP({ip})异常,已被本站禁止访问,如有疑问,请联系站长!");

                BackgroundJob.Enqueue(() => HangfireBackJob.InterceptLog(new IpIntercepter()
                {
                    IP         = ip,
                    RequestUrl = HttpUtility.UrlDecode(context.Request.Scheme + "://" + context.Request.Host + context.Request.Path),
                    Time       = DateTime.Now
                }));
                return;
            }

            var times = RedisHelper.IncrBy("Frequency:" + context.Session.Id);

            RedisHelper.Expire("Frequency:" + context.Session.Id, TimeSpan.FromMinutes(1));
            if (times > 300)
            {
                await context.Response.WriteAsync($"检测到您的IP({context.Connection.RemoteIpAddress})访问过于频繁,已被本站暂时禁止访问,如有疑问,请联系站长!");

                return;
            }

            if (bool.Parse(CommonHelper.SystemSettings["EnableDenyArea"]) && !context.Session.TryGetValue("firewall", out _))
            {
                context.Session.Set("firewall", 0);
                BackgroundJob.Enqueue(() => CheckFirewallIP(ip));
            }

            await _next.Invoke(context);
        }
コード例 #3
0
        public async Task Invoke(HttpContext context)
        {
            var request = context.Request;

            if (!AppConfig.EnableIPDirect && request.Host.Host.MatchInetAddress() && !request.Host.Host.IsPrivateIP())
            {
                return;
            }

            var path       = HttpUtility.UrlDecode(request.Path + request.QueryString, Encoding.UTF8);
            var requestUrl = HttpUtility.UrlDecode(request.Scheme + "://" + request.Host + path);
            var match      = Regex.Match(path ?? "", CommonHelper.BanRegex);

            if (match.Length > 0)
            {
                BackgroundJob.Enqueue(() => HangfireBackJob.InterceptLog(new IpIntercepter()
                {
                    IP         = context.Connection.RemoteIpAddress.ToString(),
                    RequestUrl = requestUrl,
                    Time       = DateTime.Now,
                    UserAgent  = request.Headers[HeaderNames.UserAgent],
                    Remark     = $"检测到敏感词拦截:{match.Value}"
                }));
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("参数不合法!", Encoding.UTF8);

                return;
            }

            if (!context.Session.TryGetValue("session", out _) && !context.Request.IsRobot())
            {
                context.Session.Set("session", 0);
                var referer = context.Request.Headers[HeaderNames.Referer].ToString();
                if (!string.IsNullOrEmpty(referer))
                {
                    try
                    {
                        new Uri(referer);//判断是不是一个合法的referer
                        if (!referer.Contains(context.Request.Host.Value) && !referer.Contains(new[] { "baidu.com", "google", "sogou", "so.com", "bing.com", "sm.cn" }))
                        {
                            HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(IHangfireBackJob.UpdateLinkWeight), args: referer);
                        }
                    }
                    catch
                    {
                        context.Response.StatusCode = 504;
                        await context.Response.WriteAsync("您的浏览器不支持访问本站!", Encoding.UTF8);

                        return;
                    }
                }
            }

            TrackData.RequestLogs.AddOrUpdate(requestUrl, 1, (s, i) => i + 1);
            await _next.Invoke(context);
        }
コード例 #4
0
        /// <summary>
        /// 执行调用
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            string httpMethod = context.Request.Method;

            if (httpMethod.Equals("OPTIONS", StringComparison.InvariantCultureIgnoreCase) || httpMethod.Equals("HEAD", StringComparison.InvariantCultureIgnoreCase))
            {
                return;
            }

            if (context.Request.IsRobot())
            {
                await _next.Invoke(context);

                return;
            }

            if (context.Request.Path.ToString().Contains(new[] { "error", "serviceunavailable", "accessdeny", "tempdeny" }))
            {
                await _next.Invoke(context);

                return;
            }

            string ip = context.Connection.RemoteIpAddress.MapToIPv4().ToString();

            if (ip.IsDenyIpAddress())
            {
                BackgroundJob.Enqueue(() => HangfireBackJob.InterceptLog(new IpIntercepter()
                {
                    IP         = ip,
                    RequestUrl = HttpUtility.UrlDecode(context.Request.Scheme + "://" + context.Request.Host + context.Request.Path),
                    Time       = DateTime.Now
                }));
                context.Response.Redirect("/accessdeny", true);
                return;
            }

            try
            {
                var times = RedisHelper.IncrBy("Frequency:" + context.Session.Id);
                RedisHelper.Expire("Frequency:" + context.Session.Id, TimeSpan.FromMinutes(1));
                if (times > 300)
                {
                    context.Response.Redirect("/tempdeny", true);
                    return;
                }
            }
            catch
            {
                // ignore
            }

            await _next.Invoke(context);
        }
コード例 #5
0
 private void Disallow(Post post)
 {
     BackgroundJob.Enqueue(() => HangfireBackJob.InterceptLog(new IpIntercepter()
     {
         IP         = ClientIP,
         RequestUrl = $"//{Request.Host}/{post.Id}",
         Time       = DateTime.Now,
         UserAgent  = Request.Headers[HeaderNames.UserAgent],
         Remark     = "无权限查看该文章"
     }));
     throw new NotFoundException("文章未找到");
 }
コード例 #6
0
        private void AccessDeny(ActionExecutingContext context, string ip, HttpRequest request)
        {
            var path = HttpUtility.UrlDecode(request.Path + request.QueryString, Encoding.UTF8);

            BackgroundJob.Enqueue(() => HangfireBackJob.InterceptLog(new IpIntercepter()
            {
                IP         = ip,
                RequestUrl = HttpUtility.UrlDecode(request.Scheme + "://" + request.Host + path),
                Time       = DateTime.Now,
                UserAgent  = request.Headers[HeaderNames.UserAgent]
            }));
        }
コード例 #7
0
        public async Task Invoke(HttpContext context)
        {
            var request = context.Request;
            var path    = HttpUtility.UrlDecode(request.Path + request.QueryString, Encoding.UTF8);

            if (Regex.Match(path ?? "", CommonHelper.BanRegex).Length > 0)
            {
                BackgroundJob.Enqueue(() => HangfireBackJob.InterceptLog(new IpIntercepter()
                {
                    IP         = context.Connection.RemoteIpAddress.MapToIPv4().ToString(),
                    RequestUrl = HttpUtility.UrlDecode(request.Scheme + "://" + request.Host + path),
                    Time       = DateTime.Now,
                    UserAgent  = request.Headers[HeaderNames.UserAgent]
                }));
                context.Response.StatusCode = 504;
                await context.Response.WriteAsync("参数不合法!", Encoding.UTF8);

                return;
            }

            if (!context.Session.TryGetValue("session", out _) && !context.Request.IsRobot())
            {
                context.Session.Set("session", 0);
                CommonHelper.InterviewCount++;
                var referer = context.Request.Headers[HeaderNames.Referer].ToString();
                if (!string.IsNullOrEmpty(referer))
                {
                    try
                    {
                        new Uri(referer);//判断是不是一个合法的referer
                        if (!referer.Contains(context.Request.Host.Value) && !referer.Contains(new[] { "baidu.com", "google", "sogou", "so.com", "bing.com", "sm.cn" }))
                        {
                            HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(IHangfireBackJob.UpdateLinkWeight), args: referer);
                        }
                    }
                    catch
                    {
                        context.Response.StatusCode = 504;
                        await context.Response.WriteAsync("您的浏览器不支持访问本站!", Encoding.UTF8);

                        return;
                    }
                }
            }

            await _next.Invoke(context);
        }
コード例 #8
0
        /// <inheritdoc />
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (context.Filters.Any(m => m.ToString().Contains(nameof(AllowAccessFirewallAttribute))))
            {
                return;
            }

            string httpMethod = context.HttpContext.Request.Method;

            if (httpMethod.Equals("OPTIONS", StringComparison.InvariantCultureIgnoreCase) || httpMethod.Equals("HEAD", StringComparison.InvariantCultureIgnoreCase))
            {
                return;
            }

            string ip = context.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();

            if (ip.IsDenyIpAddress() && string.IsNullOrEmpty(context.HttpContext.Session.Get <string>("AccessViewToken")))
            {
                BackgroundJob.Enqueue(() => HangfireBackJob.InterceptLog(new IpIntercepter()
                {
                    IP         = ip,
                    RequestUrl = HttpUtility.UrlDecode(context.HttpContext.Request.Scheme + "://" + context.HttpContext.Request.Host + context.HttpContext.Request.Path),
                    Time       = DateTime.Now
                }));
                context.Result = new RedirectToActionResult("AccessDeny", "Error", null);
                return;
            }

            if (context.HttpContext.Request.IsRobot())
            {
                return;
            }

            try
            {
                var times = RedisHelper.IncrBy("Frequency:" + context.HttpContext.Session.Id);
                RedisHelper.Expire("Frequency:" + context.HttpContext.Session.Id, TimeSpan.FromMinutes(1));
                if (times > 300)
                {
                    context.Result = new RedirectToActionResult("TempDeny", "Error", null);
                }
            }
            catch
            {
                // ignore
            }
        }
コード例 #9
0
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
#if !DEBUG
            if (Request.UserHostAddress != null && Request.UserHostAddress.IsDenyIpAddress())
            {
                Response.Write($"检测到您的IP({Request.UserHostAddress})异常,已被本站禁止访问,如有疑问,请联系站长!");
                BackgroundJob.Enqueue(() => HangfireBackJob.InterceptLog(new IpIntercepter()
                {
                    IP         = Request.UserHostAddress,
                    RequestUrl = Request.Url.ToString(),
                    Time       = DateTime.Now
                }));
                Response.End();
                return;
            }
#endif
            string httpMethod = Request.HttpMethod;
            if (httpMethod.Equals("OPTIONS", StringComparison.InvariantCultureIgnoreCase) || httpMethod.Equals("HEAD", StringComparison.InvariantCultureIgnoreCase))
            {
                Response.End();
                return;
            }

            bool isSpider = Request.UserAgent != null && Request.UserAgent.Contains(new[] { "DNSPod", "Baidu", "spider", "Python", "bot" });
            if (isSpider)
            {
                return;
            }
            try
            {
                var times = RedisHelper.StringIncrement("Frequency:" + Request.UserHostAddress + ":" + Request.UserAgent);
                RedisHelper.Expire("Frequency:" + Request.UserHostAddress + ":" + Request.UserAgent, TimeSpan.FromMinutes(1));
                if (times > 200)
                {
                    Response.Write($"检测到您的IP({Request.UserHostAddress})访问过于频繁,已被本站暂时禁止访问,如有疑问,请联系站长!");
                    Response.End();
                    return;
                }
            }
            catch
            {
                // ignored
            }
        }
コード例 #10
0
        private async void AccessDeny(string ip, HttpRequest request, string remark)
        {
            var path = HttpUtility.UrlDecode(request.Path + request.QueryString, Encoding.UTF8);

            BackgroundJob.Enqueue(() => HangfireBackJob.InterceptLog(new IpIntercepter()
            {
                IP         = ip,
                RequestUrl = HttpUtility.UrlDecode(request.Scheme + "://" + request.Host + path),
                Time       = DateTime.Now,
                UserAgent  = request.Headers[HeaderNames.UserAgent],
                Remark     = remark
            }));
            var limit = CommonHelper.SystemSettings.GetOrAdd("LimitIPInterceptTimes", "30").ToInt32();
            await RedisHelper.LRangeAsync <IpIntercepter>("intercept", 0, -1).ContinueWith(async t =>
            {
                if (t.Result.Count(x => x.IP == ip) >= limit)
                {
                    LogManager.Info($"准备上报IP{ip}到{FirewallRepoter.ReporterName}");
                    await FirewallRepoter.ReportAsync(IPAddress.Parse(ip)).ContinueWith(_ => LogManager.Info($"访问频次限制,已上报IP{ip}至:" + FirewallRepoter.ReporterName));
                }
            });
        }
コード例 #11
0
        private void CheckPermission(Post post)
        {
            var location = Request.Location() + "|" + Request.Headers[HeaderNames.UserAgent];

            switch (post.LimitMode)
            {
            case PostLimitMode.AllowRegion:
                if (!location.Contains(post.Regions.Split(',', StringSplitOptions.RemoveEmptyEntries)) && !CurrentUser.IsAdmin && !VisitorTokenValid && !Request.IsRobot())
                {
                    BackgroundJob.Enqueue(() => HangfireBackJob.InterceptLog(new IpIntercepter()
                    {
                        IP         = ClientIP,
                        RequestUrl = $"{Request.Host}/{post.Id}",
                        Time       = DateTime.Now,
                        UserAgent  = Request.Headers[HeaderNames.UserAgent],
                        Remark     = "无权限查看该文章"
                    }));
                    throw new NotFoundException("文章未找到");
                }

                break;

            case PostLimitMode.ForbidRegion:
                if (location.Contains(post.Regions.Split(',', StringSplitOptions.RemoveEmptyEntries)) && !CurrentUser.IsAdmin && !VisitorTokenValid && !Request.IsRobot())
                {
                    BackgroundJob.Enqueue(() => HangfireBackJob.InterceptLog(new IpIntercepter()
                    {
                        IP         = ClientIP,
                        RequestUrl = $"{Request.Host}/{post.Id}",
                        Time       = DateTime.Now,
                        UserAgent  = Request.Headers[HeaderNames.UserAgent],
                        Remark     = "无权限查看该文章"
                    }));
                    throw new NotFoundException("文章未找到");
                }

                break;
            }
        }
コード例 #12
0
        public async Task Invoke(HttpContext context)
        {
            var request = context.Request;

            if (!AppConfig.EnableIPDirect && request.Host.Host.MatchInetAddress() && !request.Host.Host.IsPrivateIP())
            {
                context.Response.StatusCode = 404;
                return;
            }
            var ip = context.GetTrueIP();

            context.Items.AddOrUpdate("ip.asn", ip.GetIPAsn());
            context.Items.AddOrUpdate("ip.location", ip.GetIPLocation());
            var path       = HttpUtility.UrlDecode(request.Path + request.QueryString, Encoding.UTF8);
            var requestUrl = HttpUtility.UrlDecode(request.Scheme + "://" + request.Host + path);
            var match      = Regex.Match(path ?? "", CommonHelper.BanRegex);

            if (match.Length > 0)
            {
                BackgroundJob.Enqueue(() => HangfireBackJob.InterceptLog(new IpIntercepter()
                {
                    IP         = ip,
                    RequestUrl = requestUrl,
                    Time       = DateTime.Now,
                    UserAgent  = request.Headers[HeaderNames.UserAgent],
                    Remark     = $"检测到敏感词拦截:{match.Value}"
                }));
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("参数不合法!", Encoding.UTF8);

                return;
            }

            if (!context.Session.TryGetValue("session", out _) && !context.Request.IsRobot())
            {
                context.Session.Set("session", 0);
                var referer = context.Request.Headers[HeaderNames.Referer].ToString();
                if (!string.IsNullOrEmpty(referer))
                {
                    try
                    {
                        new Uri(referer);//判断是不是一个合法的referer
                        if (!referer.Contains(context.Request.Host.Value) && !referer.Contains(new[] { "baidu.com", "google", "sogou", "so.com", "bing.com", "sm.cn" }))
                        {
                            HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(IHangfireBackJob.UpdateLinkWeight), args: referer);
                        }
                    }
                    catch
                    {
                        context.Response.StatusCode = 504;
                        await context.Response.WriteAsync("您的浏览器不支持访问本站!", Encoding.UTF8);

                        return;
                    }
                }
            }

            if (!context.Request.IsRobot())
            {
                if (request.QueryString.HasValue)
                {
                    var q = request.QueryString.Value.Trim('?');
                    requestUrl = requestUrl.Replace(q, q.Split('&').Where(s => !s.StartsWith("cid") && !s.StartsWith("uid")).Join("&"));
                }
                TrackData.RequestLogs.AddOrUpdate(ip, new RequestLog()
                {
                    Count       = 1,
                    RequestUrls = { requestUrl },
                    UserAgents  = { request.Headers[HeaderNames.UserAgent] }
                }, (s, i) =>
                {
                    i.UserAgents.Add(request.Headers[HeaderNames.UserAgent]);
                    i.RequestUrls.Add(requestUrl);
                    i.Count++;
                    return(i);
                });
            }

            if (string.IsNullOrEmpty(context.Session.Get <string>(SessionKey.TimeZone)))
            {
                context.Session.Set(SessionKey.TimeZone, context.Connection.RemoteIpAddress.GetClientTimeZone());
            }

            await _next(context);
        }