ipset Command Examples in Linux

IP sets are stored collections of IP addresses, network ranges, MAC addresses, port numbers, and network interface names. The iptables tool can leverage IP sets for more efficient rule matching. For example, let’s say you want to drop traffic that originates from one of several IP address ranges that you know to be malicious. Instead of configuring rules for each range in iptables directly, you can create an IP set and then reference that set in an iptables rule. This makes your rule sets dynamic and therefore easier to configure; whenever you need to add or swap out network identifiers that are handled by the firewall, you simply change the IP set.

The ipset command enables you to create and modify IP sets. First, you need to set a name, storage method, and data type for your set, such as:

# ipset create range_set hash:net

In this case, range_set is the name, hash is the storage method, and net is the data type. Then, you can add the ranges to the set:

# ipset add range_set 178.137.87.0/24
# ipset add range_set 46.148.22.0/24

Then, you use iptables to configure a rule to drop traffic whose source matches the ranges in this set:

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

Alternatively, to drop traffic whose destination matches the set:

# iptables -I OUTPUT -m set --match-set range_set dst -j DROP

Syntax

The syntax of the ipset command is:

# ipset [options] {command}

ipset Command Examples

1. Create an empty IP set which will contain IP addresses:

# ipset create set_name hash:ip

2. Destroy a specific IP set:

# ipset destroy set_name

3. Add an IP address to a specific set:

# ipset add set_name 192.168.1.25

4. Delete a specific IP address from a set:

# ipset del set_name 192.168.1.25

5. Save an IP set:

# ipset save set_name > path/to/ip_set

6. The ipset tool can also be used when troubleshooting the iptables firewall. For example, you can use the test subcommand to test whether or not an entry exists:

# ipset test range_set 178.137.87.5
Related Post