OP wishes to implement a very crude (because there's a single knock) port knocker.
My advice would be to use a tool like fwknop
for Single Packet Authentication instead: doesn't send the secret in the clear, prevents replay attacks and is easy to integrate with firewall rules.
Anyway to answer the question. OP didn't state the system is a router, so I'll consider the system is a simple host. For a router, rules appearing in filter's INPUT
should be adapted for use in filter's FORWARD
instead or in addition.
The method is to:
prepare a store to act as memory for IPs currently allowed: ipset, and define its default timeout so entries will expire without additional script
If you want to
- store multiple IP addresses or port numbers and match against the collection by iptables at one swoop;
[...]
There's at least one other choice such as the recent
iptables module, but it's not so flexible in case changes are needed later.
ipset create allowedset hash:ip timeout 120
Note for integration at boot: this set must be created before the iptables rules referencing it are added or loaded or iptables will fail loading these rules (or iptables-restore
the whole ruleset that includes these rules).
add the IP of the succeeding client to the memory store using -j SET
(reusing and fixing OP's rule which was in the raw table for... reasons?):
iptables -t raw -I PREROUTING 1 -p udp --dport 4578 -m string --algo bm --hex-string '|fefffffffffffffffff77f12|' -j SET --add-set allowedset src
Add usual boilerplate for a stateful firewall (this could have more details handled):
iptables -I INPUT 1 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
iptables -I INPUT 2 -m conntrack --ctstate INVALID -j DROP
iptables -I INPUT 3 -i lo -j ACCEPT
When the first packet of a new flow appears, using -m set
check if this flow is from an IP stored before, if so allow the packet
iptables -I INPUT 4 -m set --match-set allowedset src -j ACCEPT
drop anything else (or else set the default policy to drop)
iptables -I INPUT 5 -j DROP
The timeout was defined to 120: 2mn. This is the window during which new flows can be established. Once established (eg: an SSH remote connection or an UDP-based tunnel), it can stay established forever as long as activity makes it stay established (for UDP, from the point of view of Netfilter's conntrack, that's activity in less than 120s for flows having seen multiple exchanges, or less than 30s else).
Other options could have been used to not allow flows to continue past the timeout (which would then need to be greater, like OP's 2 hours), but this would have made it more difficult to integrate with a system that should still be able to initiate its own communications to outside.
nfqueue
, which is probably the most robust way to do it.