Beispiel #1
0
        static CityResponse GeoLocate_GetCity(System.Net.IPAddress ipaddress)
        {
            using (var mm = new MaxMind.GeoIP2.DatabaseReader(GEOLOCATION_CITY_DB_FILE))
            {
                var responce = mm.City(ipaddress);

                return(responce);
            }
        }
Beispiel #2
0
        public async Task <string> FormatCountry(string endPoint)
        {
            var cacheKey     = $".CountryInfo:{endPoint}";
            var cachedString = await m_cache.GetStringAsync(cacheKey);

            if (cachedString != null)
            {
                return(cachedString);
            }

            string cc          = "us";
            var    geoLitePath = Path.Combine(Startup.RootPath, "GeoLite2-Country.mmdb");

            if (File.Exists(geoLitePath))
            {
                try
                {
                    if (ms_mmdbReader == null)
                    {
                        ms_mmdbReader = new MaxMind.GeoIP2.DatabaseReader(geoLitePath);
                    }

                    var country = ms_mmdbReader.Country(endPoint.Replace("[", "").Replace("]", "").Replace("::ffff:", ""));
                    cc = country.Country.IsoCode.ToLowerInvariant();
                }
                catch {}
            }
            else
            {
                try
                {
                    var response = await ms_httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Get, $"https://freegeoip.app/json/{endPoint.Replace("[", "").Replace("]", "")}"));

                    if (response.IsSuccessStatusCode)
                    {
                        var obj = JObject.Parse(await response.Content.ReadAsStringAsync());
                        cc = obj.Value <string>("country_code").ToLowerInvariant();

                        if (cc == "")
                        {
                            cc = "us";
                        }
                    }
                }
                catch {}
            }

            await m_cache.SetStringAsync(cacheKey, cc, new DistributedCacheEntryOptions()
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(6)
            });

            return(cc);
        }
Beispiel #3
0
        public NodeScraper()
        {
            ThreadPool.SetMinThreads(MaxPoll, 20);
            GeoIp = new MaxMind.GeoIP2.DatabaseReader("GeoLite2-City.mmdb");
            Redis = ConnectionMultiplexer.Connect("localhost");

            Ver = new bitcoin_lib.P2P.Version($"https://nodes.hashstream.net/");
            var nd = new byte[9];

            new Random().NextBytes(nd);
            Ver.Nonce         = BitConverter.ToUInt64(nd, 0);
            Ver.RecvServices  = 0;
            Ver.StartHeight   = 0;
            Ver.TransIp       = Ver.RecvIp = IPAddress.None;
            Ver.TransPort     = Ver.RecvPort = 0;
            Ver.TransServices = Ver.RecvServices = (UInt64)Services.Unknown;
        }
Beispiel #4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="IP">IP пользователя</param>
        /// <returns>Страна/Город/Регион</returns>
        public static (string Country, string City, string Region) City(string IP)
        {
            string Country = "Unknown", City = "Unknown", Region = "Unknown";

            try
            {
                using (var reader = new MaxMind.GeoIP2.DatabaseReader(Folders.Databases + "/GeoLite2-City.mmdb"))
                {
                    var response = reader.City(IP);
                    City    = string.IsNullOrEmpty(response.City.Name) ? "Unknown" : response.City.Name;
                    Country = string.IsNullOrEmpty(response.Country.Name) ? "Unknown" : response.Country.Name;
                    Region  = string.IsNullOrEmpty(response.MostSpecificSubdivision.Name) ? "Unknown" : response.MostSpecificSubdivision.Name;
                }
            }
            catch { }

            return(Country, City, Region);
        }
Beispiel #5
0
        /// <summary>
        /// Checks the country to which the ip's belong to and determines whether or not access is denied or allowed
        /// </summary>
        /// <param name="ipAddressesToCheck">The ip addresses to check</param>
        /// <param name="resultMessage">An explanation of the result</param>
        /// <returns>True if access is allowed. False otherwise</returns>
        /// <remarks>All IP addresses must be allowed for the request to be allowed</remarks>
        public bool Allowed(List <System.Net.IPAddress> ipAddressesToCheck, out string resultMessage)
        {
            if (ipAddressesToCheck == null || ipAddressesToCheck.Count == 0)
            {
                resultMessage = "No valid IP found in request";
                return(false);
            }

            using (var reader = new MaxMind.GeoIP2.DatabaseReader(geoIpFilepath, MaxMind.Db.FileAccessMode.MemoryMapped))
            {
                //sanity check
                if (reader == null)
                {
                    resultMessage = "IP check failed";
                    return(true);
                }

                foreach (System.Net.IPAddress ipAddress in ipAddressesToCheck)
                {
                    //first check if the IP is a private ip. It turns out that proxy servers put private ip addresses in the X_FORWARDED_FOR header.
                    //we won't base our geoblocking on private ip addresses
                    if (IPUtilities.IsPrivateIpAddress(ipAddress))
                    {
                        continue;
                    }

                    //next check the exception rules
                    bool matchedOnExceptionRule = false;
                    bool allowedByExceptionRule = false;
                    foreach (ExceptionRule exceptionRule in exceptionRules)
                    {
                        if (IpAddressMatchesExceptionRule(ipAddress, exceptionRule))
                        {
                            matchedOnExceptionRule = true;
                            if (exceptionRule.AllowedMode)
                            {
                                allowedByExceptionRule = true;
                            }
                            else
                            {
                                allowedByExceptionRule = false;
                                //one IP denied = deny access alltogether
                                break;
                            }
                        }
                    }
                    if (matchedOnExceptionRule)
                    {
                        if (allowedByExceptionRule)
                        {
                            //IP found that matches an allow exception rule, don't check the country
                            //We continue if verifyAll is specified, because another IP could be denied
                            if (verifyAll)
                            {
                                continue;
                            }
                            else
                            {
                                break;
                            }
                        }
                        else
                        {
                            //IP found that matches a deny exception rule, deny access immediately
                            resultMessage = "Blocked IP: [" + ipAddress.ToString() + "]";
                            return(false);
                        }
                    }

                    if (reader.Metadata.DatabaseType.ToLower().IndexOf("country") == -1)
                    {
                        throw new System.InvalidOperationException("This is not a GeoLite2-Country or GeoIP2-Country database");
                    }

                    string countryCode = string.Empty;
                    //not found in exception rule, so base access rights on the country
                    try
                    {
                        MaxMind.GeoIP2.Responses.CountryResponse countryResponse = reader.Country(ipAddress);
                        countryCode = !string.IsNullOrEmpty(countryResponse.Country.IsoCode) ? countryResponse.Country.IsoCode : !string.IsNullOrEmpty(countryResponse.RegisteredCountry.IsoCode) ? countryResponse.RegisteredCountry.IsoCode : string.Empty;
                    }
                    catch (MaxMind.GeoIP2.Exceptions.AddressNotFoundException) { }
                    catch (MaxMind.GeoIP2.Exceptions.PermissionRequiredException) { }
                    catch (MaxMind.GeoIP2.Exceptions.GeoIP2Exception) { }
                    finally
                    {
                        if (string.IsNullOrEmpty(countryCode))
                        {
                            countryCode = "--";
                        }
                    }

                    bool selected = CountryCodeSelected(countryCode);
                    bool allowed  = (selected == allowedMode);

                    /*
                     * allowedmode     selected     allowed
                     *  1               1            1
                     *  1               0            0
                     *  0               1            0
                     *  0               0            1
                     */

                    if (!allowed)
                    {
                        resultMessage = "Blocked IP: [" + ipAddress.ToString() + "] from [" + countryCode + "]";
                        return(false);
                    }
                    else
                    {
                        // If a proxy in HTTP_X_FORWARDED_FOR should be ignored if previous checked ip matches previous found country or exceptionRule
                        if (!verifyAll)
                        {
                            break;
                        }
                    }
                }
            }
            resultMessage = "None";
            return(true);
        }
        private string City(string ip)
        {
            if (string.IsNullOrWhiteSpace(ip) || ip.Equals("127.0.0.1")) return string.Empty;

            var db = new MaxMind.GeoIP2.DatabaseReader(Server.MapPath("/App_Data/GeoLite2-City.mmdb"));
            
            try{
                var city = db.City(ip);
                return city.City.Name;
            }
            catch{
                return string.Empty;
            }
        }