Easy add IP to be blocked by iptables

A question was asked over at www.lowendtalk.com on how to add ip addresses to iptables from a textfile.

AnthonySmith found a simple but still effective way to solve this.

The entry that were discussed was

Let’s break it all down in parts (click on the tabs to see the explanation)

Parameter Views
-A Append this to existing rules
-s XXX.XXX.XXX.XXX -s Sets the source for a particular packet, in this case the ip of XXX.XXX.XXX.XXX
-p udp -p = Sets the IP protocol for the rule, which can be either icmp, tcp, udp, or all, to match every possible protocol. If this option is omitted when creating a rule, the all option is the default.
-m udp -m = match option
Different network protocols provide specialized matching options which may be set in specific ways to match a particular packet using that protocol. Of course, the protocol must first be specified in the iptables command, such as using -p tcp , to make the options for that protocol available.
–dport 28960:28965 –dport Specifies the destination port of the UDP packet, using the service name, port number, or range of port numbers. The –destination-port match option may be used instead of –dport.
To specify a specific range of port numbers, separate the two numbers with a colon (:), such as our example.
You may also use an exclamation point character (!) as a flag after the –dport option to tell iptables to match all packets which do not use that network service or port.
-j DROP -j Tells iptables to jump to a particular target when a packet matches a particular rule. Valid targets to be used include the standard options, ACCEPT, DROP, QUEUE, and RETURN, as well as extended options that are available through modules loaded, such as LOG, MARK, and REJECT, among others.

If no target is specified, the packet moves past the rule with no action taken. However, the counter for this rule is still increased by 1, as the packet matched the specified rule.
in our example we use DROP — The system that sent the packet is not notified of the failure. The packet is simply removed from the rule checking the chain and discarded.

So, first of all, create a script that will be run by a cron job to add the rule from a text file

To add IP to the text file read by the cron job you could use a simple shell script like this

Leave a Reply

Your email address will not be published. Required fields are marked *