Stop DDoS Attacks with these free firewalls! IPTABLES

edited March 2015 in Tutorials
Setup a firewall which works with cpanel and any Linux Servers Protect your server today!

Make sure you add all ports you are using for various types of software / scripts to work correctly.
Add you ip's or even ip blocks if you are not using a static ip. 
Also you could use a vps to connect to your server and whitelist the ip of the vps server you are using to connect to your other server.

Install CSF FIREWALL widely used and supported with 3rd party applications.

cd /usr/local/src


tar -zxvf csf.tgz

cd csf


Step 3:

Edit the configuration with your favorite editor, in this case I used vi:

vi /etc/csf/csf.conf

Edit the value from:


to => TESTING = "0"

Step 4: Restart the service:

/etc/init.d/csf restart

vi /etc/csf/csf.conf

Enable connection tracking.

CT_LIMIT is max number of connection allowed from one IP, you can set this value as per your server requirement.


Set connection tracking interval.


If you want to get possible ddos attack email then enable it.


If you want to make IP blocks permanent then set this to 1, otherwise blocks

will be temporary and will be cleared after CT_BLOCK_TIME seconds


If you opt for temporary IP blocks for CT, then the following is the interval

in seconds that the IP will remained blocked for (e.g. 1800 = 30 mins)


If you only want to count specific ports (e.g. 80,443) then add the ports

to the following as a comma separated list. E.g. “80,443”

CT_PORTS = 80,23,443

These settings will be enough for DDOS attacks but if you are getting
more attacks even you have above option configured then we can set few
more options.

Step 2: Enable distributed attacks


Set the following to the minimum number of unique IP addresses that trigger



Step 3: Enable distributed FTP attacks


Set the following to the minimum number of unique IP addresses that trigger

LF_DISTFTP. LF_DISTFTP_UNIQ must be <= LF_DISTFTP for this to work


If this option is set to 1 the blocks will be permanent

If this option is > 1, the blocks will be temporary for the specified number

of seconds


Step 4: Enable distributed SMTP attacks.


Set the following to the minimum number of unique IP addresses that trigger

LF_DISTSMTP. LF_DISTSMTP_UNIQ must be <= LF_DISTSMTP for this to work


If this option is set to 1 the blocks will be permanent

If this option is > 1, the blocks will be temporary for the specified number

of seconds


This is the interval during which a distributed FTP or SMTP attack is



Install IDS on your gateway/hosts to alert you when someone tries to sniff In.


(b) Untar it

tar -zxvf aide-0.7.tar.gz

(c) cd aide-0.7

(d) Then execute

./configure -with-gnu-regexp

(e) Final steps to install make;make install

Here is a sample short aide.conf:

Rule = p+i+u+g+n+s+md5

/etc p+i+u+g

/sbin Rule

/usr/local/apache/conf Rule

/var Rule



After configuring AIDE should be initiated with all these rules.

For that execute aide -init


Implement Sysctl protection against DDOS

bash# vi /etc/sysctl.conf

add the below code:

# Enable IP spoofing protection, turn on Source Address Verification

net.ipv4.conf.all.rp_filter = 1

# Enable TCP SYN Cookie Protection

net.ipv4.tcp_syncookies = 1

Add the below code in /etc/rc.local and restart network

for f in /proc/sys/net/ipv4/conf/*/rp_filter;

do echo 1 > done

echo 1 > /proc/sys/net/ipv4/tcp_syncookies

Install Mod_dosevasive to your apache.  >> A few users have reported Mod_dosevaiasive does not work but give it a try see how it goes.

bash# wget

bash# tar -zxvf mod_evasive_1.10.1.tar.gz

bash# cd mod_evasive_1.10.1

bash# $APACHE_ROOT/bin/apxs -iac mod_evasive.c

Dont get scared by the variable ``$APACHE_ROOT'' . Its nothing, but a
simple variable which stores the location of the apache installation (eg
$APACHE_ROOT =/usr/local/apache)

bash# vi /usr/loca/apache/conf/httpd.conf

After this add the below code in httpd.conf

<IfModule mod_dosevasive.c>

DOSHashTableSize 3097

DOSPageCount 2

DOSSiteCount 50

DOSPageInterval 1

DOSSiteInterval 1

DOSBlockingPeriod 10


bash# /usr/loca/apache/bin/apachectl restart

Install Mod_security


bash# tar -zxvf modsecurity-apache-1.9.2.tar.gz

bash# cd modsecurity-apache-1.9.2

bash# /usr/local/apache/bin/apxs -cia mod_security.c

Create a file named mod_security.conf under the folder /usr/local/apache/conf

bash# vi /usr/local/apache/conf/mod_security.conf

Create the rule with reference to the link

and add it in the mod_security.conf file.

Add the location of mod_security.conf to httpd.conf

bash# vi /usr/local/apache/conf/httpd.conf

Add the string below Include /usr/local/apache/conf/mod_security.conf

bash# /usr/local/apache/bin/apachectl stop

bash# /usr/local/apache/bin/apachectl start


chmod 0700


Script to check No of connected ip’s.

sh /usr/local/ddos/

How To Edit Configuration File:-

vi /usr/local/ddos/ddos.conf

Edit the paths according to your system:







Customize the options and its values as you want:


# Frequency in minutes in which the script will be executed


# Number of connections received to block an IP address of an alleged attacker


# 1 means that DDoS Deflate will use APF to block, 0 use directly Iptables


# Time (in seconds) to block an attacker.


# Address to send an email when someone is banned


# With a 0 value, the attackers won't be banned, 1 is selected by default

Restart DDos Deflate

sh /usr/local/ddos/ -c

Fail2Ban install


Install Fail2Ban on Ubuntu

The installation process for this tool is simple because the Ubuntu
packaging team maintains a package in the default repositories.

First, we need to update our local package index and then we can use apt to download and install the package:

sudo apt-get update
sudo apt-get install fail2ban

As you can see, the installation is trivial. We can now begin configuring the utility for our own use.

Configure Fail2Ban with your Service Settings

The fail2ban service keeps its configuration files in the /etc/fail2ban directory. There is a file with defaults called jail.conf.

Since this file can be modified by package upgrades, we should not
edit this file in-place, but rather copy it so that we can make our
changes safely.

We need to copy this to a file called jail.local for fail2ban to find it:

sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

Once the file is copied, we can open it for editing to see how everything works:

sudo nano /etc/fail2ban/jail.local

In this file, there are a few settings you may wish to adjust. The settings located under the [DEFAULT] section will be applied to all services enabled for fail2ban that are not overridden in the service's own section.

ignoreip =

You can adjust the source addresses that fail2ban ignores by adding a value to the ignoreip
parameter. Currently, it is configured not ban any traffic coming from
the local machine. You can add additional addresses to ignore by
appending them to the end of the parameter, separated by a space.

bantime = 600

The bantime parameter sets length of time that a client
will be banned when they have failed to authenticate correctly. This is
measured in seconds. By default, this is set to 600 seconds, or 10

findtime = 600
maxretry = 3

The next two parameters that you want to pay attention to are findtime and maxretry.
These work together to establish the conditions under which a client
is found to be an illegitimate user that should be banned.

The maxretry variable sets the number of tries a client has to authenticate within a window of time defined by findtime,
before being banned. With the default settings, the fail2ban service
will ban a client that unsuccessfully attempts to log in 3 times within a
10 minute window.

destemail = root@localhost
sendername = Fail2Ban
mta = sendmail

Some other settings you may wish to are the destemail, sendername, and mta settings if you wish to configure email alerts. The destemail parameter sets the email address that should receive ban messages. The sendername sets the value of the "From" field in the email. The mta parameter configures what mail service will be used to send mail.

action = $(action_)s

This parameter configures the action that fail2ban takes when it wants to institute a ban. The value action_
is defined in the file shortly before this parameter. The default
action is to simply configure the firewall to reject traffic from the
offending host until the ban time elapses.

If you would like to configure email alerts, you can change the value from action_ to action_mw. If you want the email to include the relevant log lines, you can change it to action_mwl. Make sure you have the appropriate mail settings configured if you choose to use mail alerts.

Individual Jail Settings

Finally, we get to the portion of the configuration file that deals
with individual services. These are specified by the section headers,
like [SSH].

Each of these sections can be enabled by modifying or adding the enabled line to be "true":

enabled = true

By default, the SSH service is enabled and all others are disabled.

These sections work by using the default values we defined above. If
you want to override any values, you can do so under the service's
section. If you want to use the defaults, you aren't required to add

Some other settings that are set here are the filter that will be used to decide whether a line in a log indicates a failed authentication and the logpath which tells fail2ban where the logs for that particular service are located.

The filter value is actually a reference to a file located in the /etc/fail2ban/filter.d directory, with its .conf
extension removed. This file contains the regular expressions that
determine whether a line in the log is bad. We won't be covering this
file in-depth in this guide, because it is fairly complex and the
predefined settings match appropriate lines well.

However, you can see what kind of filters are available by looking into that directory:

ls /etc/fail2ban/filter.d

If you see a file that looks to be related to a service you are
using, you should open it with a text editor. Most of the files are
fairly well commented and you should be able to at least tell what type
of condition the script was designed to guard against. Most of these
filters have appropriate (disabled) sections in the jail.local file that we can enable if desired.

For instance, pretend that we are serving a website using nginx and
realize that a password-protected portion of our site is getting slammed
with login attempts. We can tell fail2ban to use the nginx-http-auth.conf file to check for this condition within the /var/log/nginx/error.log file.

This is actually already set up in a section called [nginx-http-auth] in our /etc/fail2ban/jail.local file. We just need to flip the enabled parameter to protect our service:


enabled = true
filter = nginx-http-auth
port = http,https
logpath = /var/log/nginx/error.log

If you enable this, you'll want to restart your fail2ban service to make sure your rules are constructed correctly.

Putting It All Together

Now that you understand the basic idea behind fail2ban, let's run through a basic setup.

We're going to configure a auto-banning policy for SSH and Nginx,
just as we described above. We want fail2ban to email us when an IP is

First, let's install all of the relevant software.

If you don't already have it, you'll need nginx, since we're going to
be monitoring its logs, and you'll need sendmail to mail us
notifications. We'll also grab iptables-persistent to
allow the server to automatically set up our firewall rules at boot.
These can be acquired from Ubuntu's default repositories:

sudo apt-get update
sudo apt-get install nginx sendmail iptables-persistent

Establish a Base Firewall

When that is finished, we should implement a default firewall. You can learn how to configure an iptables firewall on Ubuntu 14.04 here. We are going to just create a basic firewall for this guide.

We're going to tell it to allow established connections, traffic
generated by the server itself, traffic destined for our SSH and web
server ports. We will drop all other traffic. We can set this basic
firewall up by typing:

sudo iptables -A INPUT -i lo -j ACCEPT
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -j DROP

These commands will implement the above policy. We can see our current firewall rules by typing:

sudo iptables -S
-N fail2ban-ssh
-A INPUT -p tcp -m multiport --dports 22 -j fail2ban-ssh
-A INPUT -i lo -j ACCEPT
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A fail2ban-ssh -j RETURN

We have our default policy for each of our chains, and then the five
rules that we just established. In red, we also have the default
structure set up by fail2ban since it already implements SSH banning
policies by default.

Adjusting the Fail2ban Configuration

Now, we need to configure fail2ban using the settings we'd like. Open the jail.local file:

sudo nano /etc/fail2ban/jail.local

We can set a more severe ban time here. Under the default heading, change the bantime setting so that our service bans clients for half an hour:

bantime = 1800

We also need to configure our alert email information. First, find the destemail parameter and put in the email address that you want to use to collect these messages:

destemail =

You can set the sendername to something else if you'd
like. It's useful to have a value that can be easily filtered using
your mail service though, or else your regular inbox may get flooded
with alerts if there are a lot of break in attempts from various places.

Moving down, we need to adjust the action parameter to one of the actions that sends us email. The choices are between action_mw which institutes the ban and then emails us a "whois" report on the offending host, or action_mwl which does the above, but also emails the relevant log lines.

We're going to chose action_mwl because the log lines will help us troubleshoot and gather more information if there are issues:

action = %(action_mwl)s

Moving on to our SSH section, if we want to adjust the amount of
unsuccessful attempts that should be allowed before a ban is
established, you can edit the maxretry entry. If you are using a port other than "22", you'll want to adjust the port parameter appropriately. As we said before, this service is already enabled, so we don't need to modify that.

Next, search for the nginx-http-auth section. Change the enabled parameter to read "true":


enabled = true
. . .

This should be all you have to do this section unless your web server
is operating on non-standard ports or if you moved the default error
log path.

Restarting the Fail2ban Service

When you are finished, save and close the file.

Now, start or restart your fail2ban service. Sometimes, it's better
to completely shut down the service and then start it again:

sudo service fail2ban stop

Now we can restart it by typing:

sudo service fail2ban start

It may take a few moments for all of your firewall rules to be
populated. However, after a time, you can check the new rules by

sudo iptables -S
-N fail2ban-nginx-http-auth
-N fail2ban-ssh
-A INPUT -p tcp -m multiport --dports 80,443 -j fail2ban-nginx-http-auth
-A INPUT -p tcp -m multiport --dports 22 -j fail2ban-ssh
-A INPUT -i lo -j ACCEPT
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A fail2ban-nginx-http-auth -j RETURN
-A fail2ban-ssh -j RETURN

The lines in red are the ones that our fail2ban policies have
created. Right now, they are just directing traffic to new, almost
empty chains and then letting the traffic flow right back into the INPUT

However, these new chains are where the banning rules will be added.

Testing the Banning Policies

From another server, one that won't need to log into your fail2ban
server with, we can test the rules by getting our second server banned.

After logging into your second server, try to SSH into the fail2ban
server. You can try to connect using a non-existent name for instance:

ssh blah@fail2ban_server_IP

Enter random characters into the password prompt. Repeat this a few
times. At some point, the fail2ban server will stop responding with the
Permission denied message. This signals that your second server has been banned from the fail2ban server.

On your fail2ban server, you can see the new rule by checking our iptables again:

sudo iptables -S
-N fail2ban-nginx-http-auth
-N fail2ban-ssh
-A INPUT -p tcp -m multiport --dports 80,443 -j fail2ban-nginx-http-auth
-A INPUT -p tcp -m multiport --dports 22 -j fail2ban-ssh
-A INPUT -i lo -j ACCEPT
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A fail2ban-nginx-http-auth -j RETURN
-A fail2ban-ssh -s -j REJECT --reject-with icmp-port-unreachable
-A fail2ban-ssh -j RETURN

As you can see in the highlighted line, we have a new rule in our
configuration which rejects traffic to the SSH port coming from our
second server's IP address. You should have also gotten an email about
the ban in the account you configured.

Fail2Ban Install


Step One—Install Fail2Ban

Because fail2ban is not available from CentOS, we should start by downloading the EPEL repository:

rpm -Uvh

Follow up by installing fail2ban:

yum install fail2ban

Step Two—Copy the Configuration File

The default fail2ban configuration file is location at
/etc/fail2ban/jail.conf. The configuration work should not be done in
that file, however, and we should instead make a local copy of it.

cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

After the file is copied, you can make all of your changes within the
new jail.local file. Many of possible services that may need protection
are in the file already. Each is located in its own section, configured
and turned off.

Step Three—Configure defaults in Jail.Local

Open up the the new fail2ban configuration file:

vi /etc/fail2ban/jail.local

The first section of defaults covers the basic rules that fail2ban
will follow. If you want to set up more nuanced protection for your
virtual private server, you can customize the details in each section.

You can see the default section below.


# "ignoreip" can be an IP address, a CIDR mask or a DNS host. Fail2ban will not
# ban a host which matches an address in this list. Several addresses can be
# defined using space separator.
ignoreip =

# "bantime" is the number of seconds that a host is banned.
bantime = 3600

# A host is banned if it has generated "maxretry" during the last "findtime"
# seconds.
findtime = 600

# "maxretry" is the number of failures before a host get banned.
maxretry = 3

Write your personal IP address into the ignoreip line. You can
separate each address with a space. IgnoreIP allows you white list
certain IP addresses and make sure that they are not locked out from
your VPS. Including your address will guarantee that you do not
accidentally ban yourself from your own virtual private server.

The next step is to decide on a bantime, the number of seconds
that a host would be blocked from the server if they are found to be in
violation of any of the rules. This is especially useful in the case of
bots, that once banned, will simply move on to the next target. The
default is set for 10 minutes—you may raise this to an hour (or higher)
if you like.

Maxretry is the amount of incorrect login attempts that a host may have before they get banned for the length of the ban time.

Findtime refers to the amount of time that a host has to log
in. The default setting is 10 minutes; this means that if a host
attempts, and fails, to log in more than the maxretry number of times in
the designated 10 minutes, they will be banned.

Step Four (Optional)—Configure the ssh-iptables Section in Jail.Local

The SSH details section is just a little further down in the config,
and it is already set up and turned on. Although you should not be
required to make to make any changes within this section, you can find
the details about each line below.


enabled = true
filter = sshd
action = iptables[name=SSH, port=ssh, protocol=tcp]
sendmail-whois[name=SSH, dest=root,]
logpath = /var/log/secure
maxretry = 5

Enabled simply refers to the fact that SSH protection is on. You can turn it off with the word "false".

The filter, set by default to sshd, refers to the config file
containing the rules that fail2banuses to find matches. The name is a
shortened version of the file extension. For example, sshd refers to the

Action describes the steps that fail2ban will take to ban a
matching IP address. Just like the filter entry, each action refers to a
file within the action.d directory. The default ban action, "iptables"
can be found at /etc/fail2ban/action.d/iptables.conf .

In the "iptables" details, you can customize fail2ban further. For
example, if you are using a non-standard port, you can change the port
number within the brackets to match, making the line look more like

 eg. iptables[name=SSH, port=30000, protocol=tcp]

You can change the protocol from TCP to UDP in this line as well, depending on which one you want fail2ban to monitor.

If you have a mail server set up on your virtual private server,
Fail2Ban can email you when it bans an IP address. In the default case,
the sendmail-whois refers to the actions located at

log path refers to the log location that fail2ban will track.

The max retry line within the SSH section has the same
definition as the default option. However, if you have enabled multiple
services and want to have specific values for each one, you can set the
new max retry amount for SSH here.

Step Five—Restart Fail2Ban

After making any changes to the fail2ban config, always be sure to restart Fail2Ban:

sudo service fail2ban restart

You can see the rules that fail2ban puts in effect within the IP table:

iptables -L

Fail2Ban Website

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion