I have a working nftables rule-set. However it is very long, and has a lot of repeated code:
- Exact (just a few characters different) duplicate for ip4 and ip6.
- Chains of rules, that branch into near identical branches. I feel that some boolean logic would help here.
How can I reduce the repeated code, to make this rule-set more concise?
I was trying various things then realised I can do it like below, but it makes the programmer in me feel dirty. It has too much repeated code.
#!/usr/sbin/nft -f
table ip vnc_table {};
table ip6 vnc_table {};
flush table ip vnc_table;
flush table ip6 vnc_table;
table ip vnc_table {
# 3 near identical sets
set richardports {
type inet_service;
flags interval;
elements = { 5910-5919 };
}
set henryports {
type inet_service;
flags interval;
elements = { 5920-5929 };
}
set sholaports {
type inet_service;
flags interval;
elements = { 5930-5939 };
}
chain output {
type filter hook output priority 0; policy accept;
ip daddr 127.0.0.1 jump localhost;
}
chain localhost {
tcp dport @richardports jump richard_chain;
tcp dport @henryports jump henry_chain;
tcp dport @sholaports jump shola_chain;
}
# 3 near identical chains
chain richard_chain {
skuid "richard" accept;
reject;
}
chain henry_chain {
skuid "henry" accept;
reject;
}
chain shola_chain {
skuid "shola" accept;
reject;
}
}
#then we do it all again for ip6
table ip6 vnc_table {
set richardports {
type inet_service;
flags interval;
elements = { 5910-5919 };
}
set henryports {
type inet_service;
flags interval;
elements = { 5920-5929 };
}
set sholaports {
type inet_service;
flags interval;
elements = { 5930-5939 };
}
chain output {
type filter hook output priority 0; policy accept;
ip6 daddr ::1 jump localhost;
}
chain localhost {
tcp dport @richardports jump richard_chain;
tcp dport @henryports jump henry_chain;
tcp dport @sholaports jump shola_chain;
}
chain richard_chain {
skuid "richard" accept;
reject;
}
chain henry_chain {
skuid "henry" accept;
reject;
}
chain shola_chain {
skuid "shola" accept;
reject;
}
}