Herramientas de usuario

Herramientas del sitio


rusia:ips_del_kremlin

Obtener de dónde es una dirección ip es fácil, también qué ips pertenecen a un país a través de https://www.ipdeny.com/ipblocks/, pero si lo que se quiere son las de una zona concreta es bastante más difícil, a pesar de estar en la base de datos GeoLite2-City la obtención es más compleja y mucho más lenta. Existen otras opciones, como shodan maps, RIPEstat o IP2Location Geolocator, pero no lo he conseguido así porque hay que registrarse, son servicios de pago o demo

wget https://git.io/GeoLite2-City.mmdb
instalar mmdblookup
mmdblookup –file GeoLite2-City.mmdb –ip 8.8.8.8
Esto devuelve una salida en formato .json con detalles como ciudad, región, país, latitud y longitud

{
    "continent":
      {
        "code":
          "NA" <utf8_string>
        "geoname_id":
          6255149 <uint32>
        "names":
          {
            "de":
              "Nordamerika" <utf8_string>
            "en":
              "North America" <utf8_string>
            "es":
              "Norteamérica" <utf8_string>
            "fr":
              "Amérique du Nord" <utf8_string>
            "ja":
              "北アメリカ" <utf8_string>
            "pt-BR":
              "América do Norte" <utf8_string>
            "ru":
              "Северная Америка" <utf8_string>
            "zh-CN":
              "北美洲" <utf8_string>
          }
      }
    "country":
      {
        "geoname_id":
          6252001 <uint32>
        "iso_code":
          "US" <utf8_string>
        "names":
          {
            "de":
              "USA" <utf8_string>
            "en":
              "United States" <utf8_string>
            "es":
              "Estados Unidos" <utf8_string>
            "fr":
              "États Unis" <utf8_string>
            "ja":
              "アメリカ" <utf8_string>
            "pt-BR":
              "EUA" <utf8_string>
            "ru":
              "США" <utf8_string>
            "zh-CN":
              "美国" <utf8_string>
          }
      }
    "location":
      {
        "accuracy_radius":
          1000 <uint16>
        "latitude":
          37.751000 <double>
        "longitude":
          -97.822000 <double>
        "time_zone":
          "America/Chicago" <utf8_string>
      }
    "registered_country":
      {
        "geoname_id":
          6252001 <uint32>
        "iso_code":
          "US" <utf8_string>
        "names":
          {
            "de":
              "USA" <utf8_string>
            "en":
              "United States" <utf8_string>
            "es":
              "Estados Unidos" <utf8_string>
            "fr":
              "États Unis" <utf8_string>
            "ja":
              "アメリカ" <utf8_string>
            "pt-BR":
              "EUA" <utf8_string>
            "ru":
              "США" <utf8_string>
            "zh-CN":
              "美国" <utf8_string>
          }
      }
  }

Para poder hacer uso de ésta herramienta lo más fácil es crear un script en python y así poder extraer qué ips pertenecen a una zona:

Instalamos el módulo geoip2 para python
pip3 install geoip2.

Para poder obtener latitudes y longitudes, seleccionar bien y de manera fácil una zona geográfica, recomiendo utilizar josm, crear una capa en archivo/nueva capa, añadir un nodo en herramientas/añadir nodo, poner latitud y longitud y dar a descargar mapas (en el icono de la flecha verde hacia abajo) desde un servidor y ahí seleccionar la zona. Al mover el puntero por el cuadro seleccionado aparece latitud y longitud en la parte inferior

"""
MIT License
 
Copyright (c) 2024 foro.acosadores.net
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
 
 
 
import geoip2.database
import ipaddress
 
# Archivo de la base de datos GeoLite2
MMDB_FILE = "GeoLite2-City.mmdb"
 
# Áreas de interés: define los límites de latitud y longitud para cada área
AREAS = [
    {"lat_min": 55.7180, "lat_max": 55.7415, "lon_min": 37.1821, "lon_max": 37.2261, "output_file": "ips_obo_oropeso.txt"},
    {"lat_min": 55.7477, "lat_max": 55.7560, "lon_min": 37.6106, "lon_max": 37.6255, "output_file": "ips_kremlin.txt"},
    {"lat_min": 44.4158, "lat_max": 44.4306, "lon_min": 38.1968, "lon_max": 38.2066, "output_file": "ips_palacio.txt"}
]
 
# Archivo de entrada: bloques de IP en formato CIDR
IP_BLOCKS_FILE = "ru-aggregated.zone"
 
# Limpiar archivos de salida
for area in AREAS:
    with open(area["output_file"], "w") as f:
        pass
 
# Cargar la base de datos
reader = geoip2.database.Reader(MMDB_FILE)
 
def is_within_area(lat, lon, area):
    """Verifica si una coordenada está dentro del área definida."""
    return area["lat_min"] <= lat <= area["lat_max"] and area["lon_min"] <= lon <= area["lon_max"]
 
def process_ip_block(block, areas):
    """Procesa un rango de IP y encuentra las IPs dentro de las áreas."""
    results = {area["output_file"]: [] for area in areas}
 
    for ip in ipaddress.IPv4Network(block, strict=False):
        try:
            # Consultar la base de datos para la IP
            response = reader.city(str(ip))
            lat = response.location.latitude
            lon = response.location.longitude
 
            # Verificar si lat o lon es None
            if lat is None or lon is None:
                print(f"IP {ip}: Latitud o longitud no disponibles.")
                continue
 
            # Verificar si la IP está dentro de alguna área
            for area in areas:
                if is_within_area(lat, lon, area):
                    print(f"IP {ip} está dentro del área: {area['output_file']}")
                    results[area["output_file"]].append(str(ip))
                else:
                    print(f"IP {ip} está fuera del área: {area['output_file']}")
        except geoip2.errors.AddressNotFoundError:
            # Debug: IP no encontrada en la base de datos
            print(f"IP {ip} no encontrada en la base de datos.")
            continue
 
    return results
 
# Leer los bloques de IP y procesar cada uno
with open(IP_BLOCKS_FILE, "r") as blocks:
    for block in blocks:
        block = block.strip()
        if not block:
            continue
        print(f"Procesando bloque: {block}")
        area_results = process_ip_block(block, AREAS)
 
        # Escribir resultados en los archivos correspondientes
        for output_file, ips in area_results.items():
            with open(output_file, "a") as output:
                for ip in ips:
                    output.write(ip + "\n")
 
print("IPs dentro de las áreas guardadas en los archivos correspondientes.")

Cosas curiosas:

No existen ips para las 2 zonas de las mansiones de Putin. Sólo para la zona del Kremlin hay 3 millones y medio de ips, y para todo Moscú (contando el Kremlin) hay unas 25 millones de ip

ips_kremlin.tar.gz

rusia/ips_del_kremlin.txt · Última modificación: 2025/01/13 18:45 por anonimo