Пример #1
0
        public static void RunBlocked(JsonDB jsonDB, IMemoryCache memoryCache)
        {
            if (IsRunBlocked || BlockedIP.IsEmpty)
            {
                return;
            }
            IsRunBlocked = true;

            //
            bool BlockToIPtables = jsonDB.AntiDdos.BlockToIPtables;

            #region Получаем текущий список заблокированных IP
            string IPv4 = string.Empty;
            string IPv6 = string.Empty;

            if (BlockToIPtables)
            {
                IPv4 = new Bash().Run("iptables -L -n -v | grep \"ISPCore_\" | awk '{print $8}'");
                IPv6 = new Bash().Run("ip6tables -L -n -v | grep \"ISPCore_\" | awk '{print $8}'");
            }
            #endregion

            // Блокируем IP
            Parallel.For(0, BlockedIP.Count, new ParallelOptions {
                MaxDegreeOfParallelism = jsonDB.Base.CountParallel
            }, (index, state) =>
            {
                try
                {
                    if (BlockedIP.TryDequeue(out string IP))
                    {
                        // IP уже заблокирован
                        if (IPv4.Contains(IP) || IPv6.Contains(IP))
                        {
                            return;
                        }

                        #region DNSLookup
                        string HostName = null;
                        try
                        {
                            if (jsonDB.AntiDdos.DNSLookupEnabled)
                            {
                                // Получаем имя хоста по IP
                                var host = Dns.GetHostEntryAsync(IP).Result;

                                // Получаем IP хоста по имени
                                host = Dns.GetHostEntryAsync(host.HostName).Result;

                                // Проверяем имя хоста и IP на совпадение
                                if (host.AddressList.Where(i => i.ToString() == IP).FirstOrDefault() != null)
                                {
                                    HostName = host.HostName;

                                    // Проверяем имя хоста на белый список DNSLookup
                                    if (Regex.IsMatch(host.HostName, WhiteUserList.PtrRegex, RegexOptions.IgnoreCase))
                                    {
                                        // Добовляем IP в белый список на неделю
                                        WhitePtr.Add(IP, host.HostName, DateTime.Now.AddDays(7));
                                        Trigger.OnAddToWhitePtr((IP, HostName, 7));

                                        // Удаляем временное значение с кеша
                                        memoryCache.Remove($"AntiDdosCheckBlockedIP-{IP}");
                                        return;
                                    }
                                }
                            }
                        }
                        catch { }
                        #endregion

                        // Добовляем IP в IPtables
                        if (BlockToIPtables)
                        {
                            string comandTables = IP.Contains(":") ? "ip6tables" : "iptables";
                            new Bash().Run($"{comandTables} -A INPUT -s {IP} -m comment --comment \"ISPCore_{DateTime.Now.AddMinutes(jsonDB.AntiDdos.BlockingTime).ToString("yyy-MM-ddTHH:mm:00")}\" -j REJECT");
                        }

                        //
                        Trigger.OnBlockedIP((IP, HostName, jsonDB.AntiDdos.BlockingTime));

                        // Пишем IP в базу
                        if (jsonDB.AntiDdos.Jurnal)
                        {
                            (string Country, string City, string Region)geo = ("Disabled", "Disabled", "Disabled");
                            if (jsonDB.AntiDdos.GeoIP)
                            {
                                geo = GeoIP2.City(IP);
                            }

                            WriteLogTo.SQL(new Jurnal()
                            {
                                City     = geo.City,
                                Country  = geo.Country,
                                Region   = geo.Region,
                                HostName = HostName,
                                IP       = IP,
                                Time     = DateTime.Now
                            });
                        }

                        // Обновляем кеш
                        int BlockingTime = jsonDB.AntiDdos.BlockingTime > 10 ? 10 : jsonDB.AntiDdos.BlockingTime;
                        memoryCache.Set($"AntiDdosCheckBlockedIP-{IP}", (byte)0, TimeSpan.FromMinutes(BlockingTime));
                    }
                }