Category Archives: CPanel

Issue with exim — require_files: Permission denied in logs ?

Facing issue in sending/receiving mails in a cPanel server ?

As always, first place is to check for /var/log/exim_mainlog.
If you spot something like this :

2014-04-30 17:07:34 H=(xxxx-122-106-xx-xx-co.in) [xx.xx.xx.xx]:55278 F= temporarily rejected RCPT : require_files: error for /home/account/etc/domain.com: Permission denied

It looks like the permission/ownership has been altered for the path
given in the logs ( the mailbox location )

Fix this issue by running the following :

/scripts/mailperm 'account-name'

— mailperm script is provided by cPanel to automatically fix the permission
and ownership of mailboxes with the user account provided.

cPanel – Chkservd showing Exim/IMAP getting failed numerous times ?

— Check chkservd logs (/var/log/chkservd.log ) and see if we can find something
like this in-relation to exim

==========================

>> AUTH PLAIN AF9fsdsdxcxcxcX19pspdivxc1k1MGJYek44eXpOMVliWkdOdF
dfTVRWbjNPU29uADlBVEFlMG 1MR0hsMVRESlI2WnFIZ3FRSDWWEXQ0dMYUlqZzVEbTFMY
k1FQUpHJokUtTAn:DWQ=

<< 421 host.xxxx.com Service not available - closing connection exim: ** [421 host.xxxx.com: Service not available - closing connection != 2]

==========================

-- This shows that the check daemon failed to authenticate
with the temporal auth key (exim ) and therefore check is getting
failed.

-- As a result of this, we can find lots of SMTP authentication failures
in exim_mainlog ( both from valid and invalid IP's )

-- To fix this issue with exim-auth key, we need to generate them.

-- # cd /var/cpanel/serviceauth/
# rm -rf exim
# service cpanel restart
# service exim restart

Monitor chkservd logs ( /var/log/chkservd.log ) and make sure things are fine !

Error when trying to FTP !

When trying to FTP-in, facing this error ? :

=================

Status: Resolving address of xxxxxxxxxxxxxxx.com
Status: Connecting to xx.xx.xx.xx:21…
Status: Connection established, waiting for welcome message…
Response: 421 Too many connections (x) from this IP
ons (x) from this IP

=================

As the logs indicate, the limit for connections from the IP you are trying
to login has reached its maximum value.

Increase this from the configuration file, the value 'MaxClientsPerIP'
( if its pure-ftp ) or 'MaxClientsPerHost' ( pro-ftpd)
and restart the service.

Alternatively, you can also terminate the existing connections, if they are not in use.
# netstat -plan | grep :21 and kill the corresponding process
( # kill -9 PID )

Error when enabling SMTP Restrictions – cPanel/WHM

SMTP restrictions prevent users from bypassing your mail server to send mail.
This feature allows you to configure your server so that the mail
transport agent (MTA), Mailman mailing list software, and root user
are the only accounts able to connect to remote SMTP servers.

Enable from WHM as :

Home >> Security Center >> SMTP Restrictions

When doing so, do you face this error ?

An error occurred attempting to update this setting.
The SMTP restriction is disabled.

When trying to do it from backend,

# /scripts/smtpmailgidonly on

SMTP Mail protection has been disabled. All users may make smtp connections.
There was a problem setting up iptables. You either have an older kernel or a
broken iptables install, or ipt_owner could not be loaded.

In Most cases, the required iptables module, ‘ipt_owner’ would be disabled.
You can confirm it by running # /etc/csf/csftest.pl

If your’s is a VPS, ask the provider to enable it for you, or if
you manage your server, enable it using the command :

# modprobe ipt_owner

Apache error_log – piling up with PHP errors ?

Is error_log associated with a domain piling up in huge size ?

Check the contents of it and see if its something like this :

=============

[07-Feb-2014 00:19:15 America/New_York] PHP Strict Standards: Non-static method JDispatcher::getInstance() should not be called statically in
[07-Feb-2014 00:19:15 America/New_York] PHP Strict Standards: Non-static method JLoader::load() should not be called statically in
[07-Feb-2014 00:19:15 America/New_York] PHP Strict Standards: Non-static method JLoader::register() should not be called statically in
[07-Feb-2014 00:19:15 America/New_York] PHP Strict Standards: Non-static method JPluginHelper::_import() should not be called statically in
[07-Feb-2014 00:19:15 America/New_York] PHP Strict Standards: Non-static method JLoader::import() should not be called statically in

……….
……….

=============

We can see that it is reporting PHP Strict-Standards errors.
As each and every strict standard errors is being reported,
error_log is consuming huge amount of space.

This is a change which has been seen in the newer version of PHP, ( PHP 5.4 )
which now reports E_STRICT errors on default.

To get around this issue, disable error reporting for strict standards,
by adding the below line to PHP configuration file.

error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT

An issue with exim — mails not getting delivered to certain mail-servers

Facing an issue with exim, that it doesn’t send any mails to certain SMTP server’s like gmail etc?

First place to check is the /var/log/exim_mainlog and see if you can spot something like this

=============

-bash-3.2# grep 1W6OuM-0005cl-J8 /var/log/exim_mainlog
2014-01-23 19:21:42 1W6OuM-0005cl-J8 <= root@host.xxxx. U=root P=local S=350 T=”test mail” for test@gmail.com
2014-01-23 19:21:42 cwd=/var/spool/exim 4 args: /usr/sbin/exim -v -Mc 1W6OuM-0005cl-J8
2014-01-23 19:21:42 1W6OuM-0005cl-J8 gmail-smtp-in.l.google.com [xxxx:abcd:xxxx:xab::xa] Network is unreachable
2014-01-23 19:21:43 1W6OuM-0005cl-J8 Completed

============

You can see that exim is trying to send outgoing emails via IPv6 . It happens if the recipient server supports it, ( gmail supports it ) as a result mail delivery gets affected or the mails reach junk/spam folder.

If IPv6 delivery is not intended and DNS records for the same are not configured, then the recipient SMTP server would not be able to obtain a reverse DNS entry of the sending IP ( IP in IPv6 ) and as a result it affects the mail delivery.

To get around this, either configure your IPv6 DNS entries or just force exim to send mails only via IPv4 by adding the below line to the exim config file ( /etc/exim.conf

disable_ipv6 = true

Finally restart exim.

Useful MySQL commands

To find MySQL root/admin pass :

cPanel server           : cat /root/.my.cnf ( username : root )
Plesk server             : cat /etc/psa/.psa.shadow ( username : admin )
DirectAdmin server  : cat /usr/local/directadmin/conf/mysql.conf

To login to MySQL :

mysql -u 'username' -p ( will prompt for password )
Password:

To create MySQL dump of a database :

mysqldump -u 'username' -p dbname > database_name.sql ( will prompt for password )

To create MySQL dump of all databases :

mysqldump -u 'username' -p --all-databases > all_databases.sql ( will prompt for password )

To restore all databases from the MySQL dump :

mysql -u username -p < all_databases.sql ( will prompt for password )

To restore a MySQL dump for a database :

mysql -u 'username' -p dbname < database_name.sql ( will prompt for password )

To restore a single database from dump of all databases :

mysql -u 'username' -p --one-database dbname < all_databases.sql ( will prompt for password )

To create MySQL dump of a single table in a database :

mysqldump -u 'username' -p dbname table_name > table_name.sql ( will prompt for password )

To restore the above table from MySQL dump :

mysql -u 'username' -p dbname < /path/to/table_name.sql ( will prompt for password )

One liner to truncate all tables in a db from MySQL :

mysql -Nse 'show tables' DBNAME | while read table;
do mysql -e "truncate table $table" DBNAME; done

One liner to drop all tables in a db from MySQL :

mysql -Nse 'show tables' DBNAME | while read table;
do mysql -e "drop table $table" DBNAME; done

MySQL server not starting ?

There are ton’s of causes for which MySQL might not start,
ranging from disk space full to databases getting corrupt.

First place where you have to check for a clue is the .err log
( /var/lib/mysql/hostname.err )

If the err corresponds to something like this :

InnoDB: End of page dump
140104 12:33:19 InnoDB: Page checksum 2288969011, prior-to-4.0.14-form checksum 2949853821
InnoDB: stored checksum 492713095, prior-to-4.0.14-form stored checksum 2949853821
InnoDB: Page lsn 0 40542, low 4 bytes of lsn at page end 40542
InnoDB: Page number (if stored to page already) 47,
InnoDB: space id (if created with >= MySQL-4.1.1 and stored already) 0
InnoDB: Page may be an update undo log page
InnoDB: Page may be an index page where index id is 12
InnoDB: Also the page in the doublewrite buffer is corrupt.
InnoDB: Cannot continue operation.
InnoDB: You can try to recover the database with the my.cnf
InnoDB: option:
InnoDB: innodb_force_recovery=6

One of the reason for this error is the use of multiple
storage engines, MyISAM or InnoDB

Check your /etc/my.cnf for any lines which highlight the use
of multiple storage engines.

Following can be an example :

innodb_force_recovery=4
default-storage-engine=MyISAM

The above configuration implies MyISAM is the default
storage engine, but another setting related to innoDB is
already given, which conflicts.

If your default storage engine is MyISAM, then
giving the following option in /etc/my.cnf would
help : skip-innodb

A cPanel bug ( for version — 11.40 ) with clamAV

Getting the following error message ?

===========

Original Message --------
Subject: Cron /usr/local/cpanel/3rdparty/bin/freshclam --quiet --no-warnings
From: (Cron Daemon)
To: root@hostname
Date: 12/12/2013 04:38
> ERROR: Can't create temporary directory

/usr/local/cpanel/3rdparty/share/clamav/clamav-xxxxx.tmp

===========

This is a known issue/bug with cPanel in 11.40

Although the directory ‘/usr/local/cpanel/3rdparty/share/clamav’
has enough permission and ownership configured, it is not able to
create the required files/folders.

A temporary workaround to this issue is to change the ownership of
the directory as shown below :

==========

chown clamav:clamav /usr/local/cpanel/3rdparty/share/clamav

==========

csf & iptables cheatsheet !!

CSF

csf -a   : allow an ip and add it to /etc/csf.allow
csf -ar  : remove an ip from /etc/csf.allow and delete rule
csf -d   : deny an ip and add to /etc/csf.deny
csf -dr  : unblock an ip and remove from /etc/csf.deny
csf -g   : search the list and give the rule that matches the ip
csf -tr : Remove the IP from temporary ban
csf -x   : disable csf and lfd
csf -e   : enable csf and lfd if disabled
csf -r   : restart csf

CSF config files

  • /etc/csf/csf.conf     :csf config file
  • /etc/csf/csf.allow    :csf allow file
  • /etc/csf/csf.deny     :csf deny file
  • /etc/csf/csf.ignore   :ignore list file ( the ip’s lfd should ignore and not block )
  • /etc/csf/csf.tempban  :to see the ips in temporary ban

To block an entire range of IP’s from a country

Open CSF config file and check for the line  “CC_DENY”  and add the corresponding country code.

For eg, if you want to block the IPs from china, add the country code as ‘CN’

IPTABLES

service iptables status : display the status of firewall
iptables -F :flush out rules
iptables -L -INPUT -n : check the lines of the chain input
iptables -I INPUT -s x.x.x.x -j DROP   : block a single ip address
iptables -D INPUT -s x.x.x.x -j DROP   : delete the ip from the rule
iptables -A INPUT -s x.x.x.x -j ACCEPT : allow all traffic from the ip address
iptables -A INPUT -p tcp --dport 3306 -j DROP : block a port from all ip
iptables -A INPUT -p tcp -s x.x.x.x --dport 3306 -j ACCEPT : allow a port from a single ip
iptables -A INPUT -m mac --mac-source 00:0F:EA:91:04:08 -j DROP :
block traffic from mac address

Diff b/w DROP and REJECT : REJECT works like DROP, but will return an error
message to the host sending the packet that the packet was blocked

iptables-save > /root/rule.file: To save iptables rules to an external file
iptables-restore < /root/rule.file
: To restore the rules back

iptables -L INPUT --line-numbers : To list the rules along with the rule
number in the chain 'INPUT'
iptables -D INPUT 1 : To delete the rule 1 in the chain INPUT

Passive mode FTP !

Enable the passive port range for Pure-FTPd !!

Before that, an overview of different modes for an FTP connection.

File Transfer Protocol (FTP) has 2 modes that you can use for an FTP connection: active and passive. During active mode, the FTP server responds to the connection attempt and returns a connection request from a different port to the FTP client. FTP’s passive mode allows the FTP client to initiate both connection attempts.

Now, to enable passive mode and its range,

* Open the /etc/pure-ftpd.conf configuration file in your preferred text editor.
* Remove the comment (#) from the beginning of the line which contains the PassivePortRange option.
* Change that line to the following:

PassivePortRange 49152 65534 ( indicate the range here )

* Save the changes to the configuration file.
* Run the /usr/local/cpanel/scripts/restartsrv_ftpserver command to restart the server.

Remember to open these ports in firewall.

Issue with Apache and SymLinks

The vulnerability with Symlinks and Apache is a known issue
in a shared hosting environment.

1st step employed by the attacker in order to carry out this attack it to find a compromised ‘single’ website or domain which has got any vulnerable scripts or 3rd party applications or any themes used in it. Once he get access to a single domain, he moves forward by creating the symlinks to other websites or even he can symlink to / (root).

For eg, if you have the following symlink set in any domain,

link -> /root , using the directory ‘link’ anyone can actually access
/root and can access any sensitive file.

Rather than manually creating this sort of symlinks, the hacker can even use any
perl/cgi script to create a symlink to other users of the server.

As a basic soultion for this, you can ensure that Apache is configured in a
way so as not to following symlinks (Options -FollowSymLinks)

================

To disable the ability for Apache to allow users to follow symbolic links in their requests, remove the FollowSymLinks directive on your Directory commands.

For example, if the below was the configuration then,

<Directory "/usr/local/apache/htdocs">
Options Indexes FollowSymLinks
AllowOverrride None
Order allow,deny
Allow from all

Remove the FollowSymLinks reference so that this reads:

<Directory "/usr/local/apache/htdocs">
Options Indexes
AllowOverrride None
Order allow,deny
Allow from all

================

If you really need symlinks, you can use the “SymLinksIfOwnerMatch” option to only
allow links from within the same user.

To prevent PHP from accessing any file outside of their directory, you need to specify the ‘open_basedir’ setting ( in PHP configuration file ) to only have access to their directory.

This option can be enabled from WHM, but :

==========

This security tweak uses Apache DSO style directives. If PHP is
configured to run as a CGI, SuPHP or
FastCGI process, the open_basedir setting must be manually specified
in the relevant php.ini file.
See the EasyApache documentation for more information.

==========

If the PHP handler is set as CGI or SuPHP, then tweak settings seen in WHM
cannot be used to set the openbase_dir option.

You need to manually specify the openbase_dir option in the global
PHP configuration file ( use php -i |grep php.ini to find the php.ini location )

In addition to prevent this SymLinks attack, there are various patches too :

https://forums.cpanel.net/f185/solutions-handling-symlink-attacks-202242-p4.html#post996441

To be kept in mind is :: the root cause for this attack or vulernablity is due any
unsecured scripts/plugins/applications which might be employed in any of the domains.

Dovecot issue – dovecot.index file broken ?

Dovecot issue – dovecot.index file corrupted?

Any email user not able to access via his webmail? Does it show
logins failed, even if you are cent percent sure logins are correct?

Check /var/log/maillog.

# tailf /var/log/maillog

If you find anything like dis,

=============

Nov 12 20:59:02 host dovecot: imap(zzzz@yyyy.com): Error: Transaction log file /home/xxxx/mail/yyyy.com/zzzz/dovecot.index.log seq 302:

Nov 12 20:59:02 host dovecot: imap(zzzz@yyyy.com): Error: broken sync positions in index file /home/xxxx/mail/yyyy.com/zzzz/dovecot.index

Nov 12 20:59:02 host dovecot: imap(zzzz@yyyy.com): Warning: fscking index file /home/xxxx/mail/yyyy.com/zzzz/dovecot.index

Nov 12 20:59:02 host dovecot: imap(zzzz@yyyy.com) Error: Fixed index file /home/xxxx/mail/yyyy.com/zzzz/dovecot.index log_file_tail_offset 1184 -> 988

Nov 12 20:59:02 host dovecot: imap(zzzz@yyyy.com): Panic: file mail-transaction-log.c: line 350 (mail_transaction_log_set_mailbox_sync_pos): assertion failed: (file_offset >= log->head->saved_tail_offset)

=============

As indicated in the logs, there seems to be an issue with the dovecot index file for the user ‘zzzz’. The basic idea behind Dovecot’s index files is that it makes reading the mailboxes a lot faster.

This happens to be a long term issue with dovecot.

The solution to fix this issue is to delete dovecot.index file.

 

Out of memory error in PHP scripts?

Facing the following error when running any PHP scripts ?

=========
PHP Fatal error: Out of memory (allocated xxxxx (tried to allocate xxxx bytes)
=========

Tried increasing the memory limit from php.ini file and still getting the above error ?

Initially, we might think this issue is with the memory limit factor seen in php.ini file.
But if we analyze the error we get we can see that the issue was not with
the PHP.ini configuration settings.

Usually, when a PHP script does not have enough memory to execute itself,
the error message seen is as below :

=========
Fatal error: Allowed memory size of xxxx bytes exhausted (tried to allocate xxxxxx bytes)
=========

In this case, the error seen is not the usual one, which suggests its not directly related to the PHP configuration.

When we analyse things further, we could see that the real issue lies within
the Apache configuration. Apache have memory limits of its own set in the configuration
files. This value is referred to as ‘RLimitMEM’

Explanation of RLimitMEM from the official documentation of Apache :

===============

RLimitMEM Directive

It sets the soft resource limit for all processes and the second parameter sets the maximum resource limit. It indicate to the server that the limit should be set to the maximum allowed by the operating system configuration. Raising the maximum resource limit requires that the server is running as root, or in the initial startup phase.

This applies to processes forked off from Apache children servicing requests, not the Apache children themselves. This includes CGI scripts and SSI exec commands, but not any processes forked off from the Apache parent such as piped logs.

Memory resource limits are expressed in bytes per process.

===========

So, increase this value/limit from your httpd configuration file, to get around this issue.

Want PHP4 and PHP5 in same cPanel server ?

Want PHP4 and PHP5 running in the same cPanel server ?

Kindly keep in mind, PHP4 is no longer supported (1st released in 2000) Not preferred to do this unless you absolutely need it. Since it’s not supported anymore, it could leave your server more vulnerable than it would be without it.

To install, do the following steps:

* Download the PHP4 custom module for EasyApache from,

http://docs.cpanel.net/twiki/pub/EasyApache/EasyApacheCustomModules/custom_opt_mod-PHP449.tar.gz

* Extract the tarball to the folder, /var/cpanel/easy/apache/cusom_opt_mods

# tar -C /var/cpanel/easy/apache/custom_opt_mods -zxvf custom_opt_mod-PHP449.tar.gz

* Run EasyApache ( from WHM or # /scripts/easyapache )

* Enable the PHP4.4.9 support module in the short options list.

* Complete the steps of EasyApache

* Verify both PHP versions are present

# php4 -v & # php -v

* Configure apache to run both versions of php***

# /usr/local/cpanel/bin/rebuild_phpconf 5 cgi dso 1
(The syntax is rebuild_phpconf <Default PHP Major Version> <PHP4 Handler> <PHP5 Handler> <Suexec>)

–> So in the above case, php5 is default PHP Major version
CGI is PHP4 handler and DSO is PHP5 handler and suexec is enabled.

* If the PHP4 script requires the extension to be .php instead of .php4, you can set the handler for the one site using a .htaccess with the following contents:

AddType application/x-httpd-php4 .php

Exim cheatsheet !!

# cat /var/log/exim_paniclog :info abt the exim program itself
# cat /var/log/exim_mainlog :logs every single transaction that the server handles
# cat /var/log/exim_rejectlog :this logs delivery rejections
# exim -bp :show mails on the queue
# exim -bpc :This option counts the number of messages on the queue
# exim -bpr :This option operates like -bp, but the output is not sorted into
chronological order of message arrival.
# exim -bp | exiqsumm : generate a summary table for all the messages in the queue
# eximstats /var/log/exim_mainlog :  Display Exim stats using the default log file

==================

# eximstats -ne -nr -nt /path/to/exim_mainlog : More concise info from the log

ne : display error info

nr : display relaying info

nt : display transport info that matches

–bydomain:show results by sending domain

–byemail:show results by sender email id

–byhost:show results by sending host

==================

# fgrep YYYY-MM-DD /path/to/exim_mainlog | eximstats : Narrow down Exim stats
generation to a particular day

# exiwhat : show what is exim doing at the moment

# exim -bt [user]@domain : Test how Exim's configuration will handle mail
sent to the specified address

# exiqgrep -f [user]@domain: Find messages from a particular sender in the queue

# exiqgrep -r [user]@domain: Find messages to a particular addressee on your server

# exim -Mrm <message-id> [ <message-id> ... ]: Remove a specific
message(s) from the queue

# exiqgrep -o 36000 -i | xargs exim -Mrm: Remove all messages older than
ten hours (36000 seconds)

# exiqgrep -y 3600 [...] : Use -y to print messages that are younger than the
specified number of seconds. For example, messages less than an hour old

# exim -Mvh <message-id>: View a specific messages full headers

# exim -Mvb <message-id>: View a specific messages body

# exim -Mvl <message-id>: View a specific messages Exim log

# exim -qf : Force another queue run

# exim -qff : Force another queue run and attempt to flush frozen messages

# exim -Mar <message ID> "rcpt address" : Add recipient

# exim -Mes <message ID> "to address" : Edit sender

# exim -bv <address> :Verify an address

# exim -bp | grep frozen | wc -l : To check frozen emails in the queue

# exiqgrep -z -i | xargs exim -Mrm : Delete frozen mails

How to customize SpamAssassin!!

SpamAssassin can be configured from cPanel of each domain. It can be customized further by
adding rules or filters.

In order to specify custom rules for a domain, you need to create the file
~/.spamassassin/user_prefs’ for each domain.

For eg, for the domain letushare.com under the account letushare, you need to create a file /home/letushare/.spamassassin/user_prefs and add the custom rules.

A simple rule,

body LOCAL_DEMONSTRATION_RULE /test/
score LOCAL_DEMONSTRATION_RULE 0.1
describe LOCAL_DEMONSTRATION_RULE

This rule does a simple case-sensitive search of the body of the email for the string 
“test” and adds a 0.1 to the score of the email if it finds it. It will match “test”
but also “testing” and “attest”. The describe statement contains the text which will
be placed into the verbose report, if verbose reports are used.

 

Changing Exim interface IP !!

In order to change the exim interface IP, do the following :

Editing /etc/mailips : This file controls the IP address from which each domains
should send mail. You will need to create and open the /etc/mailips file for editing using
your preferred text editor. You will need to configure this file in the following way:

*: 192.168.0.1 (<- desired IP )

Disable this option,

From WHM »Service Configuration »Exim Configuration Manager>>
Domain and IPs>> Send mail from account’s dedicated IP address "on"

And enable this option,

Reference /etc/mailips for outgoing SMTP connections.

And now, restart the exim service.

Protect your server from DDoS attacks – Part 1 !!

What is a DDoS attack ?

DDoS, short for Distributed Denial of Service, is a type of DOS attack where multiple compromised systems — which are usually infected with a Trojan (70% of the time)– are used to target a single system causing a Denial of Service (DoS) attack. Victims of a DDoS attack consist of both the end targeted system and all systems maliciously used and controlled by the hacker in the distributed attack.

In a DDoS attack, the incoming traffic flooding the victim originates from many different sources – potentially hundreds of thousands or more. This effectively makes it impossible to stop the attack simply by blocking a single IP address.

Honestly, it would be so difficult to protect against a DDoS attack. But we can follow some steps to make our servers more watchful against them.

=====================================

CSF ( WHM default firewall ) can be fine tuned as follows :

ConfigServer Security & Firewall from WHM >> Firewall Configuration

Connection Tracking : This option enables tracking of all connections from IP
addresses to the server. If the total number of connections is greater than
this value then the offending IP address is blocked. This can be used to help
prevent some types of DOS attack.

Care should be taken with this option. It’s entirely possible that you will
see false-positives. Some protocols can be connection hungry, e.g. FTP, IMAPD
and HTTP so it could be quite easy to trigger, especially with a lot of
closed connections in TIME_WAIT. However, for a server that is prone to DOS
attacks this may be very useful. A reasonable setting for this option might
be around 300.

=====================================
If you see your server is a bit on the slower side, check the number of connections to it using the following command.

# netstat -anp |grep 'tcp|udp' | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n

As a preliminary step, block the IPs which doesn look valid and are offending ones using csf commands.

Another option is to go for the the MOD_EVASIVE module in the httpd configuration.

Mod_evasive is an evasive maneuvers module for Apache to provide evasive
action in the event of an HTTP DoS or DDoS attack or brute force attack.
It is also designed to be a detection tool and can be easily configured to talk
to ipchains, firewalls.

Mod_evasive have got many many options to gun down our requirements to handle the
IPs connecting to our server.

Steps to install mod_evasive is given below :

# cd /usr/local/src/

# wget http://www.zdziarski.com/blog/ wpcontent/uploads/2010/02/mod_evasive_1.10.1.tar.gz

# tar -xvzf mod_evasive_1.10.1.tar.gz

# cd mod_evasive/

# /usr/local/apache/bin/apxs -cia mod_evasive20.c

Now create a file named /usr/local/apache/conf/mod_evasive.conf and add your custom settings.

For eg :

# cat /usr/local/apache/conf/mod_evasive.conf

LoadModule evasive20_module modules/mod_evasive20.so
<IfModule mod_evasive20.c>

DOSHashTableSize 3097

((The hash table size defines the number of top-level nodes for each child’s hash table. Increasing this number will provide faster performance by decreasing the number of iterations required to get to the record, but consume more memory for table space. You should increase this if you have a busy web server. The value you specify will automatically be tiered up to the next prime number in the primes list))

DOSPageCount 2

((This is the threshhold for the number of requests for the same page (or URI) per page interval. Once the threshhold for that interval has been exceeded, the IP address of the client will be added to the blocking list))

DOSSiteCount 50

((This is the threshhold for the total number of requests for any object by the same client on the same listener per site interval. Once the threshhold for that interval has been exceeded, the IP address of the client will be added to the blocking list))

DOSPageInterval 1

((The interval for the page count threshhold; defaults to 1 second intervals))

DOSSiteInterval 1

((The interval for the site count threshhold; defaults to 1 second intervals))

DOSBlockingPeriod 10

((The blocking period is the amount of time (in seconds) that a client will be blocked for if they are added to the blocking list. During this time, all subsequent requests from the client will result in a 403 (Forbidden) and the timer being reset (e.g. another 10 seconds). Since the timer is reset for every subsequent request, it is not necessary to have a long blocking period; in the event of a DoS attack, this timer will keep getting reset))

</IfModule>

Now include the above file inside /usr/local/apache/conf/includes/pre_main_global.conf

Include “/usr/local/apache/conf/mod_evasive.conf

Now rebuild httpd.conf
# /scripts/rebuildhttpdconf

Now restart apache
# /scripts/restartsrv httpd