💾 Archived View for gmi.noulin.net › 2023-11-22-using-iptables.gmi captured on 2024-02-05 at 09:20:24. Gemini links have been rewritten to link to archived content

View Raw

More Information

⬅️ Previous capture (2023-12-28)

➡️ Next capture (2024-03-21)

🚧 View Differences

-=-=-=-=-=-=-

Using iptables

Feed

date: 2023-11-22 20:37:47

categories: linux

firstPublishDate: 2023-11-22 20:37:47

On this page, I list basic iptables and ipset commands. I have been using `iptables` for many years and recently netfilter has replaced iptables in the linux kernel. I use the iptables command for netfilter, I only use ipv4 so for me, it is the same as before.

iptables -V
iptables v1.8.9 (nf_tables)

Iptables

List the current rules:

iptables -L --line-numbers

Clear/flush out all the existing rules

iptables -F

Append a rule at the end of the chain:

iptables -A

Append a rule at the start of the chain:

iptables -I

Delete a rule:

iptables -D chain_name rule_number
iptables -D INPUT 1

Ipset

List sets:

ipset -L

Delete a set named “myset”:

ipset destroy myset
or
ipset -X myset

Delete all sets:

ipset destroy

Delete a member in an ipset

ipset del myset 64.225.75.109

Rate limiter: Ban ip after N connections per minute

Rate limit connections on port 22 (`-dport 22`) after 3 attempts (`--hitcount 3`) during a period of 1 minute (`--seconds 60`). The ips are blocked for 10 minutes (`timeout 600`).

iptables -N LOG_DROP_TOO_MANY
iptables -A LOG_DROP_TOO_MANY -m limit --limit 5/m --limit-burst 7 -j LOG --log-prefix "INPUT:DROP TOO MANY: " --log-level 6
iptables -A LOG_DROP_TOO_MANY -j DROP
ipset create too_many hash:ip family inet hashsize 32768 maxelem 65536 timeout 600
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 3 -j SET --add-set too_many src
iptables -A INPUT -p tcp --dport 22 -m set --match-set too_many src -j LOG_DROP_TOO_MANY

How to block or only allow a list of networks

Create a file `nets.txt` with the list of networks:

vi nets.txt
1.0.0.0/8
2.0.0.0/8
128.0.0.0/16

Create a script to the networks to a set:

vi add.sh
ipset create nets hash:net
while read network ; do
    ipset add nets $network;
done < nets.txt

Run the script:

chmod 755 add.sh
./add.sh

Block or allow the ip in the set:

# Allow ips in the set:
iptables -A INPUT -m set ! --match-set nets src -j DROP
# or
# block ips in the set:
iptables -A INPUT -m set --match-set nets src -j DROP

Related article from Cheapskate's Guide:

Building My Own Firewall/Router, Part 2

Hashtags: #networking

Feed