3

So I have the following script that blocks IPs:

#!/bin/bash
# here's your list of IPS
CURRENT_BL=/path/to/my/ip_black_list.txt
# create/flush recreate the tables
iptables -F BLACKHOLE
iptables -N BLACKHOLE 
for BAD_IP in $(cat $CURRENT_BL)
do
        ipset add ipset-blacklist $BAD_IP 2>/dev/null || \
                echo "Failed to add ${BAD_IP}"
done
# REJECT the matching target
iptables -A BLACKHOLE -p all -m set --match-set ipset-blacklist src -j REJECT 
iptables -A BLACKHOLE -j RETURN
# assume your nginx is on 80 and 443
iptables -A INPUT -p tcp -m multiport --destination-ports 80,443 -j BLACKHOLE
iptables -A INPUT -p tcp -m multiport --destination-ports 80,443 -j ACCEPT

The ipset was created with the following command:

ipset create ipset-blacklist hash:ip

It is all working fine with IPv4 now but the problem is wiht IPv6, I am getting the following error - Syntax error: cannot parse 2003:e6:6f03:7b80:21dc:54c8:ac26:552b: resolving to IPv4 address failed

How can I make this script to read both types of IPs?

Emmanuel-Ab
  • 195
  • 1
  • 8

1 Answers1

5

You need to create the ipset using the following command:

$ sudo ipset create ipset-blacklist hash:ip family inet6

The option family { inet | inet6 } defines the protocol family of the IP addresses to be stored in the set. By default it is inet (IPv4). For more info, you can see man ipset.

Also, you need to use ip6tables instead of iptables. Otherwise, you will get an error similar to this (I created a test6 ipset with family inet6)

iptables v1.6.0: The protocol family of set test6 is IPv6, which is not applicable.

Khaled
  • 36,533
  • 8
  • 72
  • 99
  • Thank you, now I am able to add the IPv6, but the IPv4 is a problem. Is there a way to do this in one signe ipset list, or I should split it in two and do some kind of if statement in the loop? – Emmanuel-Ab Feb 21 '19 at 08:18
  • 1
    @Emmanuel-Ab: You need to have two different sets: one for IPv4 and another for IPv6. – Khaled Feb 21 '19 at 08:20