Archive for the ‘iptables’ Category


iptables string match to drop malicious urls

August 5, 2008

iptables string match to drop malicious urls


Usually modsecurity rules can help filter many malicious url attack patterns combined with apache on apache port (http|https).  But what if a malicious attack using a vulnerable url pattern, that exposes or tries to break into your system is coming onto another port?

This is where iptables string match comes in handy.

/usr/local/sbin/iptables -I INPUT -p tcp -s -m stringstring “download?file=%2e%2e” –algo bm -j DROP

[root@server ~]# iptables -L -v | grep STR
73 49908 DROP       tcp  —  any    any     anywhere             anywhere            STRING match “download?file=%2e%2e” ALGO name bm TO 65535

[root@server ~]#

The above iptable rule will block any url  that has the string “download?file=%2e%2e” on any port on your server.

Note: your iptables binary path may be /sbin/iptables

Say http://yourserverIP:9132/blah/download?file=%2e%2e


How do I Drop or block attackers IP with null routes?

July 4, 2006

Someone might attack on your system. You can drop attacker IP using IPtables. However one of our sr. sys admin highlighted something new for me. You can nullroute (like some time ISP do prevent your network device from sending any data to a remote system.) stopping various attacks coming from a single IP (read as spammers or hackers):

Suppose that bad IP is, type following command at shell:

# route add

You can verify it with following command:

# netstat -nr

This is cool, as you do not have to play with iptables rules.


Server Security with Advanced Policy Firewall and Antidos

July 2, 2006

LinuxAPF is a policy based iptables firewall system designed for ease of use and configuration.  APF is ideal for deployment in many server environments based on Linux.

Below are notes on installing, configuring and running APF.

  1. Download the latest tarball via
  2. Extract and install it:
    # tar -xvzf apf-current.tar.gz
    # cd apf*
    # ./
  3. Check the port that you need to protect with `ifconfig`. Usually it is “eth0” but if it’s something else, change it in the “conf.apf” file or you’ll risk locking yourself from the server.
  4. Edit “/etc/apf/conf.apf” and enable D-Shield block list of top networks exhibiting suspicious activity, and activate Antidos also.
  5. Open the common inbound and outboud ports.
  6. Edit “/etc/apf/ad/conf.antidos”:
  7. Add antidos to “/etc/crontab”:
    # Antidos
    */2 * * * * root /etc/apf/ad/antidos -a >> /dev/null 2>&1
  8. Star the firewall via `apf –s`.
  9. If you are not locked out of SSH, disable development mode in “conf.apf” file.
  10. Restart with `apf -r` and verify that firewall is up and protecting the server using `iptables -L -n`.


  • APF uses init files and is automatically set to startup at boot time. Check with `chkconfig –list apf`.
  • The apf and antidos logs are rotated via the conf files present in “/etc/logrotate.d”.
  • Remember to add your IP address in “/etc/apf/allow_hosts.rules” and “/etc/apf/ad/ignore.hosts” files to avoid being locked out of the server.


Writing Linux firewall rules w/ IPTables

July 2, 2006

The Linux kernel, since version 2.0, has included the capabilities to act as a firewall. In those days, the kernel module was called ipfwadm and was very simple. With the 2.2 kernel, the firewall module became called ipchains and had greater capabilities than its predecessor. Today, we have IPTables, the firewall module in the kernel since the 2.4 days. IPTables was built to take over ipchains, and includes improvements that now allow it to compete against some of the best commercial products available in the market. This guide will give you some background on IPTables and how to use it to secure your network.

Getting to know some important terminology
IPTables can be used in three main jobs: NAT, Packet Filtering, and Routing.

  • NAT stands Network Address Translation, and it is used to allow the use of one public IP address for many computers.
  • Packet Filteringstateless firewall and the other is stateful firewall. Stateless firewalls do not have the ability to inspect incoming packets to see if the packet is coming from a known connection originating at your computer. Stateful firewalls have the ability to inspect each packet to see if it’s part of a known connection, and if the packet is not part of a known, established connection then the packet is “dropped” or not allowed to pass through the firewall.
  • Routing is used to route various network packets to different ports, which are similar to Airport gates, or different IP addresses depending on what is requested. For example, if you have a web server somewhere in your network that uses port 8080, you can use Linux’s packet routing to route port 80 packets to your server’s port 8080. More on all this this later on.

A word on tables
There are three table types: filter, NAT, and mangle.

  • Filter – this is the default table type and contains most of the chains including input, output, and forward.
  • NAT – this table is used when new connections are created. It contains only three chains: prerouting, output, and postrouting.
  • Mangle – is used to alter packets.

The importance of chains…
There are three built-in chains that are part of IPTables.

  • The INPUT chain is used for packets comming into the Linux box. This chain can be used to stop certain packets from coming into the network or system, so for example, if would prevent another computer from pinging your network.. I will talk more about stopping ping attacks later.
  • The OUTPUT chain is used for packets coming out of your Linux box. This chain can be used to stop certain packets that you do not want to leave your network or system.
  • The FORWARD chain is used for packets passing through the network’s firewall. This chain will be used to set our NAT rules. I will go into the syntax of a basic NAT filter later in this article.
  • The PREROUTING chain is for changing packets as they come in
  • The POSTROUTING chain is for changing packets as they leave

Every chain in IPTables is either user-defined or built-in and will have a default policy, which can be either ACCEPT or DROP. ACCEPT and DROP will be discussed in the next section.

Packet targets
IPTables has targets which denotes what happens to all packets. There are four built-in targets:

  • ACCEPT – denotes if the packet should be allowed to move on.
  • DROP – denotes if the packet should be dropped and ignored.
  • QUEUE – denotes if the packet should be passed to userspace.
  • RETURN – denotes if the packet should be passed to the previous chain. Should this happen, then the packet is governed by the default policy of the previous chain.

For the most part I will be using ACCEPT and DROP targets for the sake of simplicity. These two targets are also more than enough to create your firewall rules. Please note that while there are predefined chains, they can also be a user-defined.

NAT, one IP for them all
NAT is one of the best tricks for networking; it allows one IP address to be used by many computers so they can all access the internet. NAT on your network would work through the rewriting the packet by changing the source IP address to read your internet IP address as it passes out of your network. When a packet needs to return to the source, the packet’s destination IP address is changed back to the computer’s IP address inside your network. For example, if your computer with an IP address of needed to get to Google, whose IP address is, the NAT firewall would change to something like and would then be passed throught the internet to Google. When Google sends a response, the IP address is changed from to and is received at your computer inside the network.

To write IPTables rules you will need to open a command prompt, but there are some graphical apps to help you out. One application that makes writing IPTables rules simple is Firestarter for GNOME. KDE users can benefit from an application like knetfilter.

Firestarter Firestarter Policy Manager

Some notes on IPTables syntax
IPTables chain syntax can be confusing, particularly for beginners, but once you have the basics down, anyone can learn to write their own firewall rules; be patient, it just takes time. It took me about 3 months to figure out how to write a rule to block ICMP packets which are used to ping computers. IPTables syntax looks like this: iptables -t filter -A INPUT -p icmp -i eth0 -j DROP.

  • The -t filter specifies that this rule will go into the filter table. If you wanted to write a NAT rule you would type -t nat.
  • The -A INPUT specifies that the rule is going to be appended to the INPUT chain. Other possible syntax would be -A OUTPUT, -A FORWARD, -A PRETROUTING, and-A POSTROUTING.
  • The -p icmp specifies that the packet has be from the ICMP protocol. The other two options are -p tcp used for TCP packets, and -p udp used for UDP packets.
  • The -i eth0 specifies that the packet has to be coming in via the eth0 interface or your first network device.
  • The -j DROP that if the packet matches it should be dropped. This rule is to stop people from using finger (used to see who else is on the system) , ping (used to check if a server is responding), or other methods to discover your network.

The next two rules are going to do the work of blocking connections not originating from inside your network.

iptables -A FORWARD -o eth0 -j ACCEPT
iptables -A FORWARD -i eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT

The -m state --state ESTABLISHED,RELATED was used to match the state of the packet coming in via eth0 (your ethernet device) and if the packet matches, then the packet is accepted. The -m is used to match on a specific option. Some possible options are -m limit --limit which looks for a limited rate, -m tos --tos used to match the TOS IP header field on a packet, -m unclean which is used to match packets that look “suspicious”.

The next rule is going to do source NAT, which will allow your network to connect using one IP address.

iptables -t nat -A POSTROUTING -o eth0

Depending on if you have a Static IP or Dynamic IP you would type: -j SNAT --to-source for Static IP, and -j MASQUERADE for Dynamic IP at the end of the above code. As a bonus, i’ll tell you how to do destination NAT, which will allow you to put a server behind the firewall at the expense of security.

iptables -t nat -A PREROUTING -i eth0 -p tcp --dport www -j DNAT --to-dest

The --dport www denotes that the destination port is port 80. You can use text like www (port 80) or ftp (port 21) or simply use port numbers. The -j DNAT part of the rule is the target, similar to -j DROP or -j ACCEPT in previous examples. --to-dest tells IPTables where you want the packet to go. --sport 8080 is just like --dport www.

For three years i have writen my own firewall rules. IPTables saved my computer from MyDoom and Sasser worms/viruses. Hopefully, now you too can write your own firewall rules. IPTables is a usefull tool in the Linux user’s tool belt, for protecting Linux and Windows computers.


netfilter’s geoip match

June 19, 2006

netfilter and iptables are building blocks of a framework inside the Linux 2.4.x and 2.6.x kernel. This framework enables packet filtering, network addresss [and port] translation (NA[P]T) and other packet mangling. It is the re-designed and heavily improved successor of the previous Linux 2.2.x ipchains and Linux 2.0.x ipfwadm systems. To learn more about iptables/netfilter you should visit

what is iptables/netfilter’s geoip match?
This framework is modular and easily let you extend the features. This is exactly what geoip is : an extension to iptables/netfilter that allows you to filter, nat or mangle packets based on the country’s destination or provenance.
There’s some minor steps to go through before using this match.
The geoip’s database
In order to efficiently filter on a country basis, we obviously need a subnet-to-country database. Fortunately, there’s a free one available at
However, this database is big and unsorted. Loading this database into memory would eat up too much ressources than what we really need. Also, seeking through unsorted database takes ages. This is why you need a tool called ‘csv2bin’ to strip, sort and compile your database.
csv2bin is available at
An alternative to creating your own up-to-date database is downloading a prebuilt but possibly outdated database from
You’ll now have to copy `geoipdb.bin’ and its index file `geoipdb.idx’ into /var/geoip/. The reason on why we do this is that iptables’s geoip shared library is statically reading both files from that path. If you ever need to change that path, take a look at extensions/libipt_geoip.c and suit it for your needs.
Applying patch-o-matic
Just like other “official” patches, geoip is part of patch-o-matic-ng. As a new match, we’ve put it into Testing state and Extra repository, so start ‘runme’ accordingly.
#> tar xfz patch-o-matic-ng-XXXXXX.tar.gz
#> cd patch-o-matic-ng
#> IPTABLES_DIR=/usr/src/iptables KERNEL_DIR=/usr/src/linux ./runme geoip

Do not forget to :
o recompile iptables;
o enable geoip into your kernel config;
o recompile your kernel or compile geoip as a module;
o boot the new kernel or modprobe ipt_geoip.
NOTE: If you had to change the database path into libipt_geoip.c, you MUST do it before compiling.

If you want to block all Anonymous Proxies and Satellite Providers, you can enter something like that: (I assume that your linux box acts as a router, else you can provide `-A INPUT’ instead.)
#> iptables -A FORWARD -m geoip –src-cc A1,A2 -j DROP

If you only plan to accept connections from your country.
#> iptables -P INPUT DROP
#> iptables -A INPUT -m geoip ! –src-cc CA -j DROP

Some people likes to know which countries are hitting obscure or well-known security risk ports.
Create a dedicated accounting custom chain
#> iptables -N SSH_GEOIP

Feed that chain with your targeted countries (below are for exemple means only)
#> iptables -A SSH_GEOIP -m geoip –src-cc CA
#> iptables -A SSH_GEOIP -m geoip –src-cc DE
#> iptables -A SSH_GEOIP -m geoip –src-cc US
#> iptables -A SSH_GEOIP -m geoip –src-cc JP
#> iptables -A SSH_GEOIP -m geoip –src-cc FR

The sixth rule will match all other countries
#> iptables -A SSH_GEOIP -m geoip ! –src-cc CA,DE,US,JP,FR

Then call the chain for a specific situation
#> iptables -A INPUT -p tcp –dport 22 -j SSH_GEOIP

This patch has been provided for fun and as a challenge only. Please do not consider this patch as an anti-spam approach. There is much better uses of this patch than such a racist-routing.

Thanks to

Charles Michaud, for giving us the project’s idea.
Arthur Ouellet, for giving us ideas and bugs report.
Martin Josefsson, for answering our technicals questions.

Tarek W. Said for jiggling his butt when we succeed.
Sean Donner for testing and writing the

and all the netfilter core team, you’re working like a big mama.


Autoblock IPs with failed SSH logins

June 1, 2006

automatic blocking of systems after a number of failed login-try’s

some general things first…

first of all i would like to announce, i know there are tools like ‘denyhosts’ or ‘pam_abl’ (which i use too) but the problem is: i just wan’t a system to be ignored and not justed blocked…otherwise the system can still continue attacking my system via http, ftp or other services i’m running or just waste my system performance.

for this purpose i setup a script which automaticly adds the hosts identified by ‘pam_abl’ ( by Andy Armstrong) to iptables, which drops every traffic of this system.

this howto is just an english translation out of this documentation: http://nimue/doc/?doc=032-abl_iptab…_abl%20iptables

now, heres the howto….


install, configure and activate ‘pam_abl’
under fedora its soo easy…just


yum install pam_abl

next configure pam_abl in ‘/etc/security/pam_abl.conf’.
with a configuration like this:


# /etc/security/pam_abl.conf

pam_abl will deny every system (host_rule=*:…), which gives 5 times per hour or 20 times per day an invalid user/password token.
for further information about configuring ‘pam_abl’ consider the official docs at

after this, enable ‘pam_abl’ like its described in ‘/usr/share/doc/pam_abl-*/README.fedora’. i would advice you to add the ‘pam_abl’-rule before a sufficient pam-rule, otherwise it is possible for a system to go around this rule…
and be aware of changing pam-configuration, make a backup-copy first!

using ‘pam_abl’
now you have the ‘pam_abl’ module (called and the command-line tool ‘pam_abl’. this enables you to manually edit the database of so called ‘crackers’.


pam_abl -p

this purges old hosts in your database (means, hosts which are longer in database than defined in your config). we do this, cause we’ll be blocking ip-adresses via iptables and in most cases these ip-adresses were dynamically distributed by an isp.

changes to iptables
that we can automatically update our iptables rules with ‘crackers’ we must create a chain and then insert a rule into our current iptables rules (or firewall script):


iptables -t filter --new crackers
iptables -A INPUT -j crackers

it’s important to insert the rule at the top of iptables, otherwise a rule can allow a system before we can check if its a cracker identified by pam_abl (if you use iptables -I INPUT -j crackers, its inserted at top).

blocking the systems identified by ‘pam_abl’
now, we just need to update the ‘crackers’ chain with the systems attacking our system:


# script: - updates crackers reported by pam_abl ( in the firwall

# initalitaion
# define variables

# check access to iptables
if [ ! -x $iptables ]; then
echo "cannot execute iptables!"
echo "please correct iptables-variable in $0"

# check access to read-db-script
if [ ! -x $read_dbscript ]; then
echo "cannot execute read-db-script!"
echo "please correct read_dbscript-variable in $0"

# check if defined chain exist in current iptable-rules
if [ -z "`$iptables -n -L | grep -i "chain $chain_name"`" ]; then
echo "chain $chain_name is not defined in your iptable rules!"
echo "cannot add a rule into a non-existing chain. please update your iptables-config."

# checks ok, go on...
# purge old hosts from pam_abl
/usr/sbin/pam_abl -p

# flush crackers chain
$iptables -t filter -F $chain_name

# reload chain with actual crackers
for i in `/usr/sbin/pam_abl | grep -v hosts: | grep -v ocking | awk '{print $1}'`; do
$iptables -t filter -A $chain_name -s $i -j DROP

this script does all for you, it cleans the ‘pam_abl’-databse and the chain and finally adds every system identified by ‘pam_abl’ to iptables.

if you then add this script to your crontab (for example every 10minutes) a cracker system has max. 10minutes of time after blocked by pam_abl to attack another service or wasting your system performance…