Use Custom Chain in iptables Aug 28th 2021 Words: 366

Instead of writing every rule directly to the default chain, as the following example shows:

1
2
3
4
5
6
7
8
9
10
# this messy blob is ugly
iptables -t mangle -A PREROUTING -j CONNMARK --restore-mark
iptables -t mangle -A PREROUTING -m mark ! --mark 0 -j ACCEPT
iptables -t mangle -A PREROUTING -m conntrack --ctstate NEW -m statistic --mode nth --every 6 --packet 0 -j MARK --set-mark 100
iptables -t mangle -A PREROUTING -m conntrack --ctstate NEW -m statistic --mode nth --every 6 --packet 1 -j MARK --set-mark 110
iptables -t mangle -A PREROUTING -m conntrack --ctstate NEW -m statistic --mode nth --every 6 --packet 2 -j MARK --set-mark 120
iptables -t mangle -A PREROUTING -m conntrack --ctstate NEW -m statistic --mode nth --every 6 --packet 3 -j MARK --set-mark 130
iptables -t mangle -A PREROUTING -m conntrack --ctstate NEW -m statistic --mode nth --every 6 --packet 4 -j MARK --set-mark 140
iptables -t mangle -A PREROUTING -m conntrack --ctstate NEW -m statistic --mode nth --every 6 --packet 5 -j MARK --set-mark 150
iptables -t mangle -A PREROUTING -j CONNMARK --save-mark

Wrap the rules with a custom chain:

1
2
3
4
5
6
7
8
9
10
11
12
iptables -t mangle -N wan_load_balancing # group everything and give the chian a human friendly name
# Append rules to the custom chain
iptables -t mangle -A wan_load_balancing -j CONNMARK --restore-mark
iptables -t mangle -A wan_load_balancing -m mark ! --mark 0 -j ACCEPT
iptables -t mangle -A wan_load_balancing -m conntrack --ctstate NEW -m statistic --mode nth --every 6 --packet 0 -j MARK --set-mark 100
iptables -t mangle -A wan_load_balancing -m conntrack --ctstate NEW -m statistic --mode nth --every 6 --packet 1 -j MARK --set-mark 110
iptables -t mangle -A wan_load_balancing -m conntrack --ctstate NEW -m statistic --mode nth --every 6 --packet 2 -j MARK --set-mark 120
iptables -t mangle -A wan_load_balancing -m conntrack --ctstate NEW -m statistic --mode nth --every 6 --packet 3 -j MARK --set-mark 130
iptables -t mangle -A wan_load_balancing -m conntrack --ctstate NEW -m statistic --mode nth --every 6 --packet 4 -j MARK --set-mark 140
iptables -t mangle -A wan_load_balancing -m conntrack --ctstate NEW -m statistic --mode nth --every 6 --packet 5 -j MARK --set-mark 150
iptables -t mangle -A wan_load_balancing -j CONNMARK --save-mark
iptables -t mangle -A PREROUTING -j wan_load_balancing # Insert the chain in the PREROUTING chain