IPSet

From Gentoo Wiki
Jump to: navigation, search
Resources

IPSet is used to set up, maintain and inspect so called IP sets in the Linux kernel. Depending on the type of the set, an IP set may store IP(v4/v6) addresses, (TCP/UDP) port numbers, IP and MAC address pairs, IP address and port number pairs, etc. - Wikipedia

IPSet is a tool for Iptables, successor of IPpool. It is an administration tool for IP sets which can be added to IPTables rules to filter out networks.

Installation

Prerequisites

You will need to configure your kernel to support ipset.

Kernel

For example, if ipset support is compiled as a module:

KERNEL Kernel settings for ipset
[*] Networking support  --->
    Networking options  --->
    [*] Network packet filtering framework (Netfilter) --->
        <M>  IP set support --->

as well as
             Core Netfilter Configuration --->       
                <M>  set target and match support

then select the desired ipset types.

USE flags

USE flags for net-firewall/ipset IPset tool for iptables, successor to ippool

modules Build the kernel modules global

Emerge

Install IPSet:

root #emerge --ask net-firewall/ipset

Filtering

The simple following script can be used to filter IP addresses based on a file that have to be retrieved on the internet, and then create or update iptables firewall rules:

FILE ~/scripts/ips.shExample IPSet script
#!/bin/sh
opt="hash:net --hashsize 64"
datadir=/var/lib/ipset
target=http://feeds.dshield.org/block.txt
wget -qNP $datadir $target || exit
set=IPBlock
tmp=${set}-tmp
ipset create $tmp $opt
networks="$(grep -E '^[0-9]' $datadir/$set | sed -rne 's/(^([0-9]{1,3}\.){3}[0-9]{1,3}).*$/\1/p')"
for i in $networks; do
    ipset add $tmp ${i}/24
done
ipset create -exist $set $opt &&
ipset swap $tmp $set &&
ipset destroy $tmp &&
echo "IPSet: $set updated"
unset -v i networks opt set tmp

The above script is just a simple way to retrieve different or various IPSet table and make use of an up to date filtering.

The script creates a new table and swap and destroys a previous set if one exists. For a more refined script see the following examples:

Save the rules to a file and start IPSet init service:

root #/etc/init.d/ipset save
root #/etc/init.d/ipset start
root #rc-update add ipset boot

The previous network filtering can be added to iptables with the following command:

root #iptables -I INPUT -m set --match-set IPBlock src,dst -j Drop

See also

External resources