Skip to content

maravento/blackip

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

180 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

status-maintained last commit Twitter Follow

BlackIP is a project that collects and unifies public blocklists of IP addresses, to make them compatible with Squid and IPSET (Iptables Netfilter). BlackIP es un proyecto que recopila y unifica listas públicas de bloqueo de direcciones IP, para hacerlas compatibles con Squid e IPSET (Iptables Netfilter).

DATA SHEET


ACL Blocked IP File Size
blackip.txt 448906 6,3 Mb

GIT CLONE


git clone --depth=1 https://github.com/maravento/blackip.git

HOW TO USE


blackip.txt is already optimized. Download it and unzip it in the path of your preference. blackip.txt ya viene optimizada. Descárguela y descomprímala en la ruta de su preferencia.

Download

wget -q -N https://raw.githubusercontent.com/maravento/blackip/master/blackip.tar.gz && cat blackip.tar.gz* | tar xzf -

Checksum

wget -q -N https://raw.githubusercontent.com/maravento/blackip/master/blackip.tar.gz && cat blackip.tar.gz* | tar xzf -
wget -q -N https://raw.githubusercontent.com/maravento/blackip/master/blackip.txt.sha256
LOCAL=$(sha256sum blackip.txt | awk '{print $1}'); REMOTE=$(awk '{print $1}' blackip.txt.sha256); echo "$LOCAL" && echo "$REMOTE" && [ "$LOCAL" = "$REMOTE" ] && echo OK || echo FAIL

Important about BlackIP

  • Should not be used blackip.txt in IPSET and in Squid at the same time (double filtrate).
  • blackip.txt is a list IPv4. Does not include CIDR.
  • No debe utilizar blackip.txt en IPSET y en Squid al mismo tiempo (doble filtrado).
  • blackip.txt es una lista IPv4. No incluye CIDR.
Edit your Iptables bash script and add the following lines (run with root privileges): Edite su bash script de Iptables y agregue las siguientes líneas (ejecutar con privilegios root):
#!/bin/bash
# https://linux.die.net/man/8/ipset
# dependencie: sudo apt install ipset

# Replace with your path to blackip.txt
ips=/path_to_lst/blackip.txt

# ipset rules
ipset -L blackip >/dev/null 2>&1
if [ $? -ne 0 ]; then
        echo "set blackip does not exist. create set..."
        ipset -! create blackip hash:net family inet hashsize 1024 maxelem 10000000
    else
        echo "set blackip exist. flush set..."
        ipset -! flush blackip
fi
ipset -! save > /tmp/ipset_blackip.txt
# read file and sort (v8.32 or later)
cat $ips | sort -V -u | while read line; do
    # optional: if there are commented lines
    if [ "${line:0:1}" = "#" ]; then
        continue
    fi
    # adding IPv4 addresses to the tmp list
    echo "add blackip $line" >> /tmp/ipset_blackip.txt
done
# adding the tmp list of IPv4 addresses to the blackip set of ipset
ipset -! restore < /tmp/ipset_blackip.txt

# iptables rules
iptables -t raw -I PREROUTING -m set --match-set blackip src -j DROP
iptables -t raw -I PREROUTING -m set --match-set blackip dst -j DROP
iptables -t raw -I OUTPUT     -m set --match-set blackip dst -j DROP
echo "done"

Ipset/Iptables Rules with IPDeny (Optional)

You can add the following lines to the bash above to include full country IP ranges with IPDeny adding the countries of your choice. Puede agregar las siguientes líneas al bash anterior para incluir rangos de IPs completos de países con IPDeny agregando los países de su elección.
# Put these lines at the end of the "variables" section
# Replace with your path to zones folder
zones=/path_to_folder/zones
# download zones
if [ ! -d $zones ]; then mkdir -p $zones; fi
wget -q -N http://www.ipdeny.com/ipblocks/data/countries/all-zones.tar.gz
tar -C $zones -zxvf all-zones.tar.gz >/dev/null 2>&1
rm -f all-zones.tar.gz >/dev/null 2>&1

# replace the line:
cat $ips | sort -V -u | while read line; do
# with (e.g: Russia and China):
cat $zones/{cn,ru}.zone $ips | sort -V -u | while read line; do

About Ipset/Iptables Rules

  • Ipset allows mass filtering, at a much higher processing speed than other solutions (check benchmark).
  • Blackip is a list containing millions of IPv4 lines and to be supported by Ipset, we had to arbitrarily increase the parameter maxelem (for more information, check ipset's hashsize and maxelem parameters).
  • Ipset/iptables limitation: "When entries added by the SET target of iptables/ip6tables, then the hash size is fixed and the set won't be duplicated, even if the new entry cannot be added to the set" (for more information, check Man Ipset).
  • Heavy use of these rules can slow down your PC to the point of crashing. Use them at your own risk.
  • Tested on iptables v1.8.7, ipset v7.15, protocol version: 7.
  • Ipset permite realizar filtrado masivo, a una velocidad de procesamiento muy superior a otras soluciones (consulte benchmark).
  • Blackip es una lista que contiene millones de líneas IPv4 y para ser soportada por Ipset, hemos tenido que aumentar arbitrariamente el parámetro maxelem (para más información, consulte ipset's hashsize and maxelem parameters).
  • Limitación de Ipset/iptables: "Cuando las entradas agregadas por el objetivo SET de iptables/ip6tables, el tamaño del hash es fijo y el conjunto no se duplicará, incluso si la nueva entrada no se puede agregar al conjunto" (para más información, consulte Man Ipset).
  • El uso intensivo de estas reglas puede ralentizar su PC al punto de hacerlo colapsar. Úselas bajo su propio riesgo.
  • Probado en: iptables v1.8.7, ipset v7.15, protocol version: 7.

Squid Rule

Edit: Edite:
/etc/squid/squid.conf
And add the following lines: Y agregue las siguientes líneas:
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS

# Block Rule for BlackIP
acl blackip dst "/path_to/blackip.txt"
http_access deny blackip

About Squid Rule

blackip.txt has been tested in Squid v3.5.x and later. blackip.txt ha sido testeada en Squid v3.5.x y posteriores.

Advanced Rules

BlackIP contains millions of IP addresses, therefore it is recommended:
  • Use blackcidr.txt to add IP/CIDR that are not included in blackip.txt (By default it contains some Block CIDR).
  • Use allowip.txt (a whitelist of IPv4 IP addresses such as Hotmail, Gmail, Yahoo. etc.).
  • Use aipextra.txt to add whitelists of IP/CIDRs that are not included in allowip.txt.
  • By default, blackip.txt excludes some private or reserved ranges RFC1918. Use IANA (iana.txt) to exclude them all.
  • By default, blackip.txt excludes some DNS servers included in dns.txt. You can use this list and expand it to deny or allow DNS servers.
  • To increase security, close Squid to any other request to IP addresses with ZTR.
BlackIP contiene millones de direcciones IP, por tanto se recomienda:
  • Use blackcidr.txt para agregar IP/CIDR que no están incluidas en blackip.txt (Por defecto contiene algunos Block CIDR).
  • Use allowip.txt (una lista blanca de direcciones IPv4 tales como Hotmail, Gmail, Yahoo, etc).
  • Use aipextra.txt para agregar listas blancas de IP/CIDR que no están incluidas en allowip.txt.
  • Por defecto, blackip.txt excluye algunos rangos privados o reservados RFC1918. Use IANA (iana.txt) para excluirlos todos.
  • Por defecto, blackip.txt excluye algunos servidores DNS incluidos en dns.txt. Puede usar esta lista y ampliarla, para denegar o permitir servidores DNS.
  • Para incrementar la seguridad, cierre Squid a cualquier otra petición a direcciones IP con ZTR.
### INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS ###

# Allow Rule for IP
acl allowip dst "/path_to/allowip.txt"
http_access allow allowip

# Allow Rule for IP/CIDR ACL (not included in allowip.txt)
acl aipextra dst "/path_to/aipextra.txt"
http_access allow aipextra

# Allow Rule for IANA ACL (not included in allowip.txt)
acl iana dst "/path_to/iana.txt"
http_access allow iana

# Allow Rule for DNS ACL (excluded from blackip.txt)
acl dnslst dst "/path_to/dns.txt"
http_access allow dnslst # or deny dnlst

# Block Rule for IP/CIDR ACL (not included in blackip.txt)
acl blackcidr dst "/path_to/blackcidr.txt"
http_access deny blackcidr

## Block Rule for BlackIP
acl blackip dst "/path_to/blackip.txt"
http_access deny blackip

# Block: Direct IPv4
acl direct_ipv4 dstdom_regex -n -i ^([0-9]{1,3}\.){3}[0-9]{1,3}$
http_access deny direct_ipv4
# Block: Direct IPv6
acl direct_ipv6 dstdom_regex -n -i ^\[([0-9a-f:]+)\]$
http_access deny direct_ipv6

BLACKIP UPDATE


⚠️ WARNING: BEFORE YOU CONTINUE

This section is only to explain how the update and optimization process works. It is not necessary for the user to run it. This process can take time and consume a lot of hardware and bandwidth resources, therefore it is recommended to use test equipment. Esta sección es únicamente para explicar cómo funciona el proceso de actualización y optimización. No es necesario que el usuario la ejecute. Este proceso puede tardar y consumir muchos recursos de hardware y ancho de banda, por tanto se recomienda usar equipos de pruebas.

Bash Update

The update process of blackip.txt is executed in sequence by the script bipupdate.sh. The script will request privileges when required. El proceso de actualización de blackip.txt es ejecutado en secuencia por el script bipupdate.sh. El script solicitará privilegios cuando lo requiera.
wget -q -N https://raw.githubusercontent.com/maravento/blackip/master/bipupdate/bipupdate.sh && chmod +x bipupdate.sh && ./bipupdate.sh

Dependencies

Update requires python 3x and bash 5x. La actualización requiere python 3x y bash 5x.
pkgs='wget git curl tar unzip zip gzip idn2 grepcidr squid python3 bind9-host'

Capture Public Blocklists

Capture IPv4 from downloaded public blocklists (see SOURCES) and unify them in a single file. Captura las IPv4 de las listas de bloqueo públicas descargadas (ver FUENTES) y las unifica en un solo archivo.

DNS Lookup

Most of the SOURCES contain millions of invalid and nonexistent IP. Then, a double check of each IP is done (in 2 steps) via DNS and invalid and nonexistent are excluded from Blackip. This process may take time. By default it processes in parallel ≈ 6k to 12k x min, depending on the hardware and bandwidth. La mayoría de las FUENTES contienen millones de IP inválidas e inexistentes. Entonces se hace una verificación doble de cada IP (en 2 pasos) vía DNS y los inválidos e inexistentes se excluyen de Blackip. Este proceso puede tardar. Por defecto procesa en paralelo ≈ 6k a 12k x min, en dependencia del hardware y ancho de banda.
HIT 8.8.8.8
Host 8.8.8.8.in-addr.arpa domain name pointer dns.google
FAULT 0.0.9.1
Host 1.9.0.0.in-addr.arpa. not found: 3(NXDOMAIN)

Run Squid-Cache with BlackIP

Run Squid-Cache with BlackIP and any error sends it to SquidError.txt on your desktop. Corre Squid-Cache con BlackIP y cualquier error lo envía a SquidError.txt en su escritorio.

Log

Both bipupdate.sh and aipupdate.sh generate a log file (bipupdate.log / aipupdate.log) in the same directory where they are executed. bipupdate.sh y aipupdate.sh generan un archivo de log (bipupdate.log / aipupdate.log) en el mismo directorio donde se ejecutan.

Important about BlackIP Update

  • tw.txt containing IPs of teamviewer servers. By default they are commented. To block or authorize them, activate them in bipupdate.sh. To update it use tw.sh.
  • You must activate the rules in Squid before using bipupdate.sh.
  • Some lists have download restrictions, so do not run bipupdate.sh more than once a day.
  • During the execution of bipupdate.sh it will request privileges when needed.
  • If you use aufs, temporarily change it to ufs during the upgrade, to avoid: ERROR: Can't change type of existing cache_dir aufs /var/spool/squid to ufs. Restart required.
  • tw.txt contiene IPs de servidores teamviewer. Por defecto están comentadas. Para bloquearlas o autorizarlas actívelas en bipupdate.sh. Para actualizarla use tw.sh.
  • Antes de utilizar bipupdate.sh debe activar las reglas en Squid.
  • Algunas listas tienen restricciones de descarga, entonces no ejecute bipupdate.sh más de una vez al día.
  • Durante la ejecución de bipupdate.sh solicitará privilegios cuando los necesite.
  • Si usa aufs, cámbielo temporalmente a ufs durante la actualización, para evitar: ERROR: Can't change type of existing cache_dir aufs /var/spool/squid to ufs. Restart required.

AllowIP Update

allowip.txt is already updated and optimized. The update process of allowip.txt is executed in sequence by the script aipupdate.sh. allowip.txt ya está actualizada y optimizada. El proceso de actualización de allowip.txt es ejecutado en secuencia por el script aipupdate.sh.
wget -q -N https://raw.githubusercontent.com/maravento/blackip/master/bipupdate/wlst/aipupdate.sh && chmod +x aipupdate.sh && ./aipupdate.sh

SOURCES


BLOCKLISTS

DEBUG LISTS

WORKTOOLS

NOTICE


  • This project includes third-party components.
  • Changes must be submitted via Issues. Pull requests are not accepted.
  • Blackip is not a blacklist service itself. It does not independently verify IP addresses. Its purpose is to consolidate and reformat public blacklist sources to make them compatible with Squid/Iptables/Ipset.
  • If your IP address is listed on Blackip and you believe this is an error, you should check the public sources in SOURCES, identify which one(s) it appears in, and contact the person responsible for that list to request its removal. Once the IP address is removed from the original source, it will automatically disappear from Blackip with the next update.
  • Este proyecto incluye componentes de terceros.
  • Los cambios deben proponerse mediante Issues. No se aceptan Pull Requests.
  • Blackip no es un servicio de listas negras como tal. No verifica de forma independiente las direcciones IP. Su función es consolidar y formatear listas negras públicas para hacerlas compatibles con Squid/Iptables/Ipset.
  • Si su dirección IP aparece en Blackip y considera que esto es un error, debe revisar las fuentes públicas en SOURCES, identificar en cuál(es) aparece, y contactar al responsable de dicha lista para solicitar su eliminación. Una vez que la dirección IP sea eliminada en la fuente original, desaparecerá automáticamente de Blackip en la siguiente actualización.

STARGAZERS


Stargazers

CONTRIBUTIONS


We thank all those who contributed to this project. Those interested may contribute sending us new "Blocklist" links to be included in this project. Agradecemos a todos aquellos que han contribuido a este proyecto. Los interesados pueden contribuir, enviándonos enlaces de nuevas "Blocklist", para ser incluidas en este proyecto.

Special thanks to: Jhonatan Sneider

SPONSOR THIS PROJECT


Image

PROJECT LICENSES


This project uses a dual-licensing model to balance software freedom with content protection: Este proyecto utiliza un modelo de licencia dual para equilibrar la libertad del software con la protección del contenido:
Content Licensed Under
Scripts, Binaries, Infrastructure GPL-3.0
RAG, Workers, Specialized Modules, Docs CC

DISCLAIMER


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.

OBJECTION


Due to recent arbitrary changes in computer terminology, it is necessary to clarify the meaning and connotation of the term blacklist, associated with this project:

In computing, a blacklist, denylist or blocklist is a basic access control mechanism that allows through all elements (email addresses, users, passwords, URLs, IP addresses, domain names, file hashes, etc.), except those explicitly mentioned. Those items on the list are denied access. The opposite is a whitelist, which means only items on the list are let through whatever gate is being used. Source Wikipedia

Therefore, blacklist, blocklist, blackweb, blackip, whitelist and similar, are terms that have nothing to do with racial discrimination.
Debido a los recientes cambios arbitrarios en la terminología informática, es necesario aclarar el significado y connotación del término blacklist, asociado a este proyecto:

En informática, una lista negra, lista de denegación o lista de bloqueo es un mecanismo básico de control de acceso que permite a través de todos los elementos (direcciones de correo electrónico, usuarios, contraseñas, URL, direcciones IP, nombres de dominio, hashes de archivos, etc.), excepto los mencionados explícitamente. Esos elementos en la lista tienen acceso denegado. Lo opuesto es una lista blanca, lo que significa que solo los elementos de la lista pueden pasar por cualquier puerta que se esté utilizando. Fuente Wikipedia

Por tanto, blacklist, blocklist, blackweb, blackip, whitelist y similares, son términos que no tienen ninguna relación con la discriminación racial.

Releases

No releases published

Packages

 
 
 

Contributors