IPtables Blacklist Script

Publicado por Narcochaos em 16/06/2014

[ Hits: 12.166 ]

 


IPtables Blacklist Script



IPtables Blacklist é um pequeno script feito em Shell Script que usa IPset e IPtables para proibir um grande número de endereços IP publicados em listas negras de IP.

IPset usa uma tabela hash para armazenar/buscar endereços IP e, portanto, a pesquisa de IP é muito mais rápida do que analisar milhares de regras de proibição no IPtables. No entanto, o limite de uma lista IPset é de 2^16 entradas.

#!/bin/bash
IP_TMP=/tmp/ip.tmp
IP_BLACKLIST=/etc/ip-blacklist.conf
IP_BLACKLIST_TMP=/tmp/ip-blacklist.tmp
IP_BLACKLIST_CUSTOM=/etc/ip-blacklist-custom.conf # optional
list="chinese nigerian russian lacnic exploited-servers"
BLACKLISTS=(
"http://www.projecthoneypot.org/list_of_ips.php?t=d&rss=1"  # Project Honey Pot Directory of Dictionary Attacker IPs
"http://check.torproject.org/cgi-bin/TorBulkExitList.py?ip=1.1.1.1"  # TOR Exit Nodes
"http://www.maxmind.com/en/anonymous_proxies"  # MaxMind GeoIP Anonymous Proxies
"http://danger.rulez.sk/projects/bruteforceblocker/blist.php"  # BruteForceBlocker IP List
"http://rules.emergingthreats.net/blockrules/rbn-ips.txt"  # Emerging Threats - Russian Business Networks List
"http://www.spamhaus.org/drop/drop.lasso"  # Spamhaus Don't Route Or Peer List (DROP)
"http://cinsscore.com/list/ci-badguys.txt"  # C.I. Army Malicious IP List
"http://www.openbl.org/lists/base.txt"  # OpenBL.org 30 day List
"http://www.autoshun.org/files/shunlist.csv"  # Autoshun Shun List
"http://lists.blocklist.de/lists/all.txt"  # blocklist.de attackers
)
for i in "${BLACKLISTS[@]}"
do
    curl "$i" > $IP_TMP
    grep -Po '(?:d{1,3}.){3}d{1,3}(?:/d{1,2})?' $IP_TMP >> $IP_BLACKLIST_TMP
done
for i in `echo $list`; do
        # Download
        wget --quiet http://www.wizcrafts.net/$i-iptables-blocklist.html
        # Grep out all but ip blocks
        cat $i-iptables-blocklist.html | grep -v < | grep -v : | grep -v ; | grep -v # | grep [0-9] > $i.txt
        # Consolidate blocks into master list
        cat $i.txt >> $IP_BLACKLIST_TMP
done

sort $IP_BLACKLIST_TMP -n | uniq > $IP_BLACKLIST
rm $IP_BLACKLIST_TMP
wc -l $IP_BLACKLIST

ipset flush blacklist
egrep -v "^#|^$" $IP_BLACKLIST | while IFS= read -r ip
do
        ipset add blacklist $ip
done

Instalação

Copie update-blacklist.sh para /usr/local/bin, em seguida, dê permissão ao script no diretório do local/bin.

Ficaria assim:

# chmod +x /usr/local/bin/update-blacklist.sh

Modifique o script update-blacklist.sh de acordo com suas necessidades. Por padrão, os endereços IP na lista negra serão salvos em /etc/ip-blacklist.conf.

Agora, instale o IPset para fazermos a criação da lista negra:

# apt-get install ipset

Vamos criar uma lista negra no IPset e inserir o filtro nas entradas do IPtables:

# ipset create blacklist hash:net

Regra de filtragem IPtables:

# iptables -I INPUT -m set --match-set blacklist src -j DROP

Certifique-se de executar esse trecho no seu script de Firewall. Se você não fizer isso, o IPtables não vai proibir os endereços IP na lista negra!

Trabalhando com o cron

Agora, fazemos o auto update da lista negra usando uma tarefa do cron.

Para a atualização automática da lista negra, copie o seguinte código no arquivo /etc/cron.d/update-blacklist:

Obs.: não atualize a lista com muita frequência ou alguns provedores da lista negra irão proibir o seu endereço IP. Uma vez por dia deve estar OK.

MAILTO=root
33 23 * * *      root /usr/local/bin/update-blacklist.sh

Outras dicas deste autor

Fail2ban - Aprendendo a instalar e configurar

Verificador Ortográfico e Gramatical no LibreOffice/OpenOffice

Instalando tcpdump no DD-WRT

Leitura recomendada

Utilizando a classe phpmailer como alternativa a função mail() do PHP

Administração de usuários no Linux

Recuperar grub após instalação do Windows

Instalando o Automatix no Ubuntu

Rodando o jSMS no Linux Kubuntu 8.10

  

Comentários
[1] Comentário enviado por campoTiago em 16/06/2014 - 09:22h

Olá, está ocorrendo o seguinte erro:

/usr/local/bin/update-blacklist.sh: line 28: syntax error near unexpected token `|'
/usr/local/bin/update-blacklist.sh: line 28: ` cat $i-iptables-blocklist.html | grep -v < | grep -v : | grep -v ; | grep -v # | grep [0-9] > $i.txt'

[2] Comentário enviado por rpugsley em 28/07/2014 - 15:01h

#!/bin/bash
IP_TMP=/tmp/ip.tmp
IP_BLACKLIST=/etc/ip-blacklist.conf
IP_BLACKLIST_TMP=/tmp/ip-blacklist.tmp
IP_BLACKLIST_CUSTOM=/etc/ip-blacklist-custom.conf # optional
BLACKLISTS=(
"http://www.projecthoneypot.org/list_of_ips.php?t=d&rss=1" # Project Honey Pot Directory of Dictionary Attacker IPs
"http://check.torproject.org/cgi-bin/TorBulkExitList.py?ip=1.1.1.1" # TOR Exit Nodes
"http://www.maxmind.com/en/anonymous_proxies" # MaxMind GeoIP Anonymous Proxies
"http://rules.emergingthreats.net/blockrules/emerging-compromised-BLOCK.rules" # BruteForceBlocker IP List
"http://www.spamhaus.org/drop/drop.lasso" # Spamhaus Don't Route Or Peer List (DROP)
"http://cinsscore.com/list/ci-badguys.txt" # C.I. Army Malicious IP List
"http://www.openbl.org/lists/base.txt" # OpenBL.org 30 day List
"http://www.autoshun.org/files/shunlist.csv" # Autoshun Shun List
"http://lists.blocklist.de/lists/all.txt" # blocklist.de attackers
)
for i in "${BLACKLISTS[@]}"
do
curl "$i" > $IP_TMP
grep -Po '(?:\d{1,3}\.){3}\d{1,3}(?:/\d{1,2})?' $IP_TMP >> $IP_BLACKLIST_TMP
done
sort $IP_BLACKLIST_TMP -n | uniq > $IP_BLACKLIST
rm $IP_BLACKLIST_TMP
wc -l $IP_BLACKLIST

ipset flush blacklist
egrep -v "^#|^$" $IP_BLACKLIST | while IFS= read -r ip
do
ipset add blacklist $ip
done

if [ -f $IP_BLACKLIST_CUSTOM ]; then
egrep -v "^#|^$" $IP_BLACKLIST_CUSTOM | while IFS= read -r ip
do
ipset add blacklist $ip
done
fi



Contribuir com comentário




Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts