如何配置iptables:仅放行源端首个UDP包,10秒内拦截后续包
Hey there, let's fix this UDP packet handling issue with iptables. Your goal is to accept only the first UDP packet from a source IP, then block all follow-ups from that same source for 10 seconds—way better than the "drop first 4, accept 5th" approach you tried earlier, which wouldn't stop the flood of repeated packets in that 10-second window.
We'll use iptables' recent module, which is perfect for tracking and limiting traffic from specific sources. Here's how to set it up:
Step 1: Clear Existing Rules (Optional but Recommended)
First, clean up any old iptables rules to avoid conflicts:
iptables -F iptables -X iptables -Z
Step 2: Configure the Core Rules
These rules need to be added in this exact order (iptables matches rules top-to-bottom):
Accept the first UDP packet and track the source IP
This rule lets the first UDP packet through, and adds the source IP to a named tracking list (UDP_SOURCE):iptables -A INPUT -p udp -m recent --set --name UDP_SOURCE -j ACCEPTBlock all subsequent UDP packets from the same source for 10 seconds
This rule checks if the source IP is already in ourUDP_SOURCElist (added in the last 10 seconds) and drops the packet if so:iptables -A INPUT -p udp -m recent --rcheck --seconds 10 --name UDP_SOURCE -j DROP
Step 3: Target Specific UDP Ports (Optional)
If you only want this restriction for a specific port (e.g., UDP port 53 for DNS), add the --dport flag to both rules:
# Accept first DNS packet and track source iptables -A INPUT -p udp --dport 53 -m recent --set --name UDP_DNS_SOURCE -j ACCEPT # Block subsequent DNS packets from the same source for 10s iptables -A INPUT -p udp --dport 53 -m recent --rcheck --seconds 10 --name UDP_DNS_SOURCE -j DROP
How This Works
- The
--setflag registers the source IP in the tracking list the first time a packet hits the rule. - The
--rcheckflag checks if the source IP exists in the list and was added within the last--secondswindow. If yes, the packet gets dropped. - After 10 seconds, the source IP is removed from the list automatically, so the next UDP packet from that IP will be accepted again.
This setup directly addresses your problem: it stops the client from spamming repeated UDP packets while ensuring the first one gets through, eliminating the need to wait for multiple retries.
内容的提问来源于stack exchange,提问作者Prakash H R

