October 2025
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031  

Categories

October 2025
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031  

Qmail : How does it work ?

Qmail : How does it work ?

Qmail programs & configuration files
Qmail works using about 15 small programs. It also uses a pretty large number of configuration files. At the beginning, this may appear as quite confusing. Once you are familiarised with these configuration files & programs, qmail administration will be easier.

Qmail programs

Qmail continuously runs 5 daemons. Remaining 10 programs are launched by these 5 daemons as and when required.

Let us see which are the 5 daemons.

1. qmail-send
2. qmail-lspawn
3. qmail-rspawn
4. qmail-clean
5. tcpserver

How Qmail works

1. Email arrival in Qmail

Mail arrives in Qmail in two different ways.

(i) Locally injected emails.

There is a program called sendmail that comes with qmail. It is a program that mimics functionality of legacy sendmail, its arguments are also similar. sendmail accepts the local email and passes it to qmail-inject.

(ii) Remote emails arrived via SMTP

* tcpserver listens incoming connections on the SMTP port.
* upon a new SMTP connection, qmail-smtpd is launched.
* qmail-smtpd receives emails via SMTP.

2. Queuing emails

* qmail-inject & qmail-smpd pass received emails to qmail-queue.
* qmail-queue places emails in the folder /var/qmail/todo
* qmail-queue adds necessary headers to emails
* Then, it notifies qmail-send about newly queued emails.

3. Processing queued emails

* qmail-send takes the message out of /var/qmail/queue/todo folder
* qmail-send checks the recipient address of the email
* If the recipient addres is local, email is passed to qmail-lspwan
* If the recipient address is remote, email is passed to qmail-rspawn

4. Email delivery to local and remote recipients

* qmail-lspawn passes email to qmail-local
* qmail-local delivers email to local email address
* qmail-rspawn passes email to qmail-remote
* qmail-remote connects to remote mail server and delivers email to remote email address

5. Cleaning queue after delivering emails

* Once all messages are delivered, qmail-send notifies qmail-clean
* qmail-clean removes the delivered emails from the queue

Qmail configuration files

Qmail configuration files are located in the folder /var/qmail/control.

1. badmailfrom
All “from addresses” which are blacklisted.

2. bouncefrom
It is the bounce email from address. Usually it is “mailer-daemon”.

3. bouncehost
It is host name of server

4. concurrencyincoming
Maximum number of simultaneous incoming SMTP connections allowed.

5. concurrencylocal
Maximum number of simultaneous local deliveries

6. concurrencyremote
Maximum number of simultaneous remote deliveries

7. defaultdomain
Default domain name of server

8. defaulthost
Host name of server

9. databytes
Maximum number of bytes in message (0=no limit)

10. doublebouncehost
It is the bounce email from address. Usually it is “mailer-daemon”.

11. doublebounceto
It is the bounce email to address. Usually it is “postmaster”.

12. helohost
It is the host name used in SMTP HELO command

13. idhost
It is host name of server. It is used when creating Message-ID.

13. localiphost
It is local IP address

14. locals
List of all local domains.

15. me
It is the hostname of server

16. morercpthosts
Only 50 domains can be added in rcpthosts, remaining domains should be in morercpthosts.

17. queuelifetime
It is the number of seconds an email can remain in queue

18. rcpthosts
Domains of all locally hosted email addresses.

19 smtpgreeting
It is the SMTP greeting message used by mail server.

20. timeoutconnect
Time in seconds, the server has to wait for SMTP connection

21. timeoutremote
Time in seconds, server has to wait for remote server

22. timeoutsmtpd
Time in seconds, server has to wait for SMTP client

23. virtualdomains
List of all virtual domains

qmail: queue wrong owner # 4.3.5 error

qmail: queue wrong owner # 4.3.5 error

 

1. download and run queue-repair to fix the queue
http://pyropus.ca/software/queue-repair/
2. make sure qmail-queue is owned by qmailq
# chown -Rf qmailq qmail-queue
3. set qmail-queue’s user id bit (to run qmail-queue as qmailq user)
# chmod u+s qmail-queue

don’t go playing with your qmail files if you don’t know what you’re doing. i think that’s how i got in trouble. lol

How to check mail queue in qmail?

/var/qmail/bin/qmail-qstat

# nice find /var/qmail/queue/mess/ -type f | xargs grep ‘^From: ‘ | awk ‘{print $2}’ | sort | uniq -c | sort -n | tail

# nice -20 find /var/qmail/queue/mess/ -type f |xargs egrep ‘^From|^To’ |sort -k1 |uniq |sort -k2 |uniq -c -f 1 |sort -n |tail

Postfix-SMTP-AUTH-TLS-Howto

Postfix-SMTP-AUTH-TLS-Howto

Version 1.0
Author: Falko Timme <falko [dot] timme [at] projektfarm [dot] de>
Last edited 12/31/2003

You can find the latest version of this document at http://www.howtoforge.com

This document describes how to install a mail server based on postfix that is capable of SMTP-AUTH and TLS. It should work (maybe with slight changes concerning paths etc.) on all *nix operating systems. I tested it on Debian Woody and Fedora Core 1 so far.

This howto is meant as a practical guide; it does not cover the theoretical backgrounds. They are treated in a lot of other documents in the web.

This document comes without warranty of any kind!

 

1 Get the Sources

We need the following software: openssl, cyrus-sasl2, postfix and the TLS patch for postfix. We will install the software from the /tmp directory.

cd /tmp
wget http://www.openssl.org/source/openssl-0.9.7c.tar.gz
wget –passive-ftp ftp://ftp.andrew.cmu.edu/pub/cyrus-mail/cyrus-sasl-2.1.17.tar.gz
wget –passive-ftp ftp://ftp.aet.tu-cottbus.de/pub/postfix_tls/related/postfix/postfix-2.0.16.tar.gz
wget –passive-ftp ftp://ftp.aet.tu-cottbus.de/pub/postfix_tls/pfixtls-0.8.16-2.0.16-0.9.7b.tar.gz

 

2 Install Openssl

tar xvfz openssl-0.9.7c.tar.gz
cd openssl-0.9.7c
./config
make
make install

 

3 Install Cyrus-sasl

cd /tmp
tar xvfz cyrus-sasl-2.1.17.tar.gz
cd cyrus-sasl-2.1.17
./configure –enable-anon –enable-plain –enable-login –disable-krb4 –with-saslauthd=/var/run/saslauthd –with-pam –with-openssl=/usr/local/ssl –with-plugindir=/usr/local/lib/sasl2 –enable-cram –enable-digest –enable-otp
(1 line!)
make
make install

If /usr/lib/sasl2 exists:
mv /usr/lib/sasl2 /usr/lib/sasl2_orig

ln -s /usr/local/lib/sasl2 /usr/lib/sasl2

Create the file /usr/local/lib/sasl2/smtpd.conf:

# This sets smtpd to authenticate using the saslauthd daemon.
pwcheck_method:saslauthd
# This allows only plain, login, cram-md5 and digest-md5 as the authentication mechanisms.
mech_list: plain login cram-md5 digest-md5

 

4 Install Postfix

cd /tmp
tar xvfz pfixtls-0.8.16-2.0.16-0.9.7b.tar.gz
tar xvfz postfix-2.0.16.tar.gz
cd postfix-2.0.16
useradd postfix
groupadd postdrop
patch -p1 < ../pfixtls-0.8.16-2.0.16-0.9.7b/pfixtls.diff
make makefiles CCARGS=”-DHAS_SSL -DUSE_SASL_AUTH -I/usr/local/include/sasl -I/usr/local/ssl/include” AUXLIBS=”-L/usr/local/ssl/lib -L/usr/local/lib -R/usr/local/lib -lsasl2 -lssl -lcrypto”
(1 line!)
make
make install
(accept the default values)

cp /etc/postfix/aliases /etc/
newaliases

Create /etc/init.d/postfix:

#!/bin/bash
#
# postfix        This script controls the postfix daemon.
#

# description: Postfix MTA
# processname: postfix

case "$1" in
    start)
        /usr/sbin/postfix start
    ;;
    stop)
        /usr/sbin/postfix stop
    ;;
    reload)
        /usr/sbin/postfix reload
    ;;
    restart)
        $0 stop
        $0 start
    ;;
    *)
    echo "Usage: $0 {start|stop|reload|restart}"
    exit 1
esac
exit 0

chmod 755 /etc/init.d/postfix

In order to start postfix at boot time do the following:

ln -s /etc/init.d/postfix /etc/rc2.d/S20postfix
ln -s /etc/init.d/postfix /etc/rc3.d/S20postfix
ln -s /etc/init.d/postfix /etc/rc4.d/S20postfix
ln -s /etc/init.d/postfix /etc/rc5.d/S20postfix
ln -s /etc/init.d/postfix /etc/rc0.d/K20postfix
ln -s /etc/init.d/postfix /etc/rc1.d/K20postfix
ln -s /etc/init.d/postfix /etc/rc6.d/K20postfix

Our postfix will run chrooted in /var/spool/postfix so we have to copy a few files:

mkdir -p /var/spool/postfix/etc
cd /etc
cp localtime services hosts resolv.conf /var/spool/postfix/etc/
mkdir -p /var/spool/postfix/var/run
mv -f /var/run/saslauthd/ /var/spool/postfix/var/run/
chmod 755 /var/spool/postfix/var/run/saslauthd/
ln -s /var/spool/postfix/var/run/saslauthd/ /var/run/saslauthd

Now we have to generate the certificate files needed for TLS:

mkdir /etc/postfix/ssl
cd /etc/postfix/ssl/

If /usr/bin/openssl exists:

mv /usr/bin/openssl /usr/bin/openssl_orig

ln -s /usr/local/ssl/bin/openssl /usr/bin/openssl
openssl genrsa -des3 -rand /etc/hosts -out smtpd.key 1024

<- Enter a password for smtpd.key.

chmod 600 smtpd.key
openssl req -new -key smtpd.key -out smtpd.csr

<- Again, enter your password for smtpd.key.
<- Enter your Country Name (e.g., “DE”).
<- Enter your State or Province Name.
<- Enter your City.
<- Enter your Organization Name (e.g., the name of your company).
<- Enter your Organizational Unit Name (e.g. “IT Department”).
<- Enter the Fully Qualified Domain Name of the system (e.g. “server1.example.com”).
<- Enter your Email Address.

The following information is optional:

<- Enter a challenge password.
<- Enter an optional company name.

openssl x509 -req -days 3650 -in smtpd.csr -signkey smtpd.key -out smtpd.crt

<- Again, enter your password for smtpd.key.

openssl rsa -in smtpd.key -out smtpd.key.unencrypted

<- Again, enter your password for smtpd.key.

mv -f smtpd.key.unencrypted smtpd.key
openssl req -new -x509 -extensions v3_ca -keyout cakey.pem -out cacert.pem -days 3650

<- Again, enter your password for smtpd.key.
<- Enter your Country Name (e.g., “DE”).
<- Enter your State or Province Name.
<- Enter your City.
<- Enter your Organization Name (e.g., the name of your company).
<- Enter your Organizational Unit Name (e.g. “IT Department”).
<- Enter the Fully Qualified Domain Name of the system (e.g. “server1.example.com”).
<- Enter your Email Address.

Edit /etc/postfix/main.cf in order to enable SMTP-AUTH and TLS:

postconf -e ‘mydomain = example.com’
postconf -e ‘myhostname = server1.$mydomain’
postconf -e ‘smtpd_sasl_local_domain =’
postconf -e ‘smtpd_sasl_auth_enable = yes’
postconf -e ‘smtpd_sasl_security_options = noanonymous’
postconf -e ‘broken_sasl_auth_clients = yes’
postconf -e ‘smtpd_recipient_restrictions=permit_sasl_authenticated,permit_mynetworks,check_relay_domains’
postconf -e ‘inet_interfaces = all’
postconf -e ‘alias_maps = hash:/etc/aliases’
postconf -e ‘smtpd_tls_auth_only = no’
postconf -e ‘smtp_use_tls = yes’
postconf -e ‘smtpd_use_tls = yes’
postconf -e ‘smtp_tls_note_starttls_offer = yes’
postconf -e ‘smtpd_tls_key_file = /etc/postfix/ssl/smtpd.key’
postconf -e ‘smtpd_tls_cert_file = /etc/postfix/ssl/smtpd.crt’
postconf -e ‘smtpd_tls_CAfile = /etc/postfix/ssl/cacert.pem’
postconf -e ‘smtpd_tls_loglevel = 1’
postconf -e ‘smtpd_tls_received_header = yes’
postconf -e ‘smtpd_tls_session_cache_timeout = 3600s’
postconf -e ‘tls_random_source = dev:/dev/urandom’

 

5 Configure Saslauthd

Create /etc/init.d/saslauthd:

#!/bin/sh -e

NAME=saslauthd
DAEMON="/usr/sbin/${NAME}"
DESC="SASL Authentication Daemon"
DEFAULTS=/etc/default/saslauthd

test -f "${DAEMON}" || exit 0

# Source defaults file; edit that file to configure this script.
if [ -e "${DEFAULTS}" ]; then
    . "${DEFAULTS}"
fi

# If we're not to start the daemon, simply exit
if [ "${START}" != "yes" ]; then
    exit 0
fi

# If we have no mechanisms defined
if [ "x${MECHANISMS}" = "x" ]; then
    echo "You need to configure ${DEFAULTS} with mechanisms to be used"
    exit 0
fi

# Add our mechanimsms with the necessary flag
for i in ${MECHANISMS}; do
    PARAMS="${PARAMS} -a ${i}"
done

# Consider our options
case "${1}" in
  start)
        echo -n "Starting ${DESC}: "
        ln -fs /var/spool/postfix/var/run/${NAME} /var/run/${NAME}
        ${DAEMON} ${PARAMS}
        echo "${NAME}."
        ;;
  stop)
        echo -n "Stopping ${DESC}: "
        PROCS=`ps aux | grep -iw '/usr/sbin/saslauthd' | grep -v 'grep' |awk '{print $2}' | tr '\n' ' '`
        if [ "x${PROCS}" != "x" ]; then
          kill -15 ${PROCS} &> /dev/null
        fi
        echo "${NAME}."
        ;;
  restart|force-reload)
        $0 stop
        sleep 1
        $0 start
        echo "${NAME}."
        ;;
  *)
        echo "Usage: /etc/init.d/${NAME} {start|stop|restart|force-reload}" >&2
        exit 1
        ;;
esac

exit 0

chmod 755 /etc/init.d/saslauthd

In order to start saslauthd at boot time do the following:

ln -s /etc/init.d/saslauthd /etc/rc2.d/S20saslauthd
ln -s /etc/init.d/saslauthd /etc/rc3.d/S20saslauthd
ln -s /etc/init.d/saslauthd /etc/rc4.d/S20saslauthd
ln -s /etc/init.d/saslauthd /etc/rc5.d/S20saslauthd
ln -s /etc/init.d/saslauthd /etc/rc0.d/K20saslauthd
ln -s /etc/init.d/saslauthd /etc/rc1.d/K20saslauthd
ln -s /etc/init.d/saslauthd /etc/rc6.d/K20saslauthd

Then create /etc/default/saslauthd:

# This needs to be uncommented before saslauthd will be run automatically
START=yes

# You must specify the authentication mechanisms you wish to use.
# This defaults to "pam" for PAM support, but may also include
# "shadow" or "sasldb"
MECHANISMS=shadow

If you find out that saslauthd is located in /usr/local/sbin instead of /usr/sbin create a symbolic link:

ln -s /usr/local/sbin/saslauthd /usr/sbin/saslauthd

Then start saslauthd and postfix:

/etc/init.d/saslauthd start

/etc/init.d/postfix start

 

6 Test your Configuration

To see if SMTP-AUTH and TLS work properly now run the following command:

telnet localhost 25

After you have established the connection to your postfix mail server type

ehlo localhost

If you see the lines

250-STARTTLS

and

250-AUTH

everything is fine.

Type

quit

to return to the system’s shell.
Further (Debian-specific) information about this topic can be found here: http://www.projektfarm.com/en/support/debian_setup/index.html.

 

Links

Configure NOD32 and Postfix as Antivirus Gateway

Configure NOD32 and Postfix as Antivirus Gateway

 

 

Requirements:
1. Postifx (2.0.18) http://www.postfix.org/download.html
2. Cyrus-sasl (2.1.17) http://asg.web.cmu.edu/sasl/
3. NOD32 for Linux Mail Server (2.09-1) http://www.nod32.si/download/download.htm
Introduction
In this article, we are going to use Postfix as an antivirus gateway. The reason why to do so is that, other MTAs (Qmail, Sendmail, Courier etc) do not support, or do not have simple configurations to make a content filtering, which scans incoming and outgoing emails. In traditional approach, dual mail servers are set up to enable scanning, Postfix has built-in content filter function. Once setup, it scans all emails, without considering the setup in MDAs. Also multiple filtering can be set up easily, with or without the help of amavisd. So Postfix is the best MTA to use as a gateway. At the same time, Postfix takes place some of the jobs of the original MTA, such as SASL Authentication, rate control etc.
Postfix listens to port 25 as gateway. It will not handle any local delivery nor outgoing transfer.
Compilation and Installation
Recommended reference site for compiling Postfix + SASL:
http://www.projektfarm.com/en/support/howto/postfix_smtp_auth_tls.html

You can use the default postfix and cyrus-sasl package also or use the rpm delivered with your distribution, install postfix and cyrus-sasl package. (RPM Packages that comes with your distribution may be older, it is still OK)

Configuration
Basic configuration concepts in Postfix
The main configurations files of Postfix are in /etc/postfix. You can change main.cf to config 300+ parameters for Postfix. Either you can edit the file directly, e.g. add a line ‘content_filter=smtp:[127.0.0.1]:2526, or use the command postconf: postconf -e ‘content_filter=smtp:[127.0.0.1]:2526’.

There are alias, access, transport, virtual files in /etc/postfix, these files are for different kinds of mapping.

After changing these files, you must rebuild the db file by postmap, e.g.
postmap hash:/etc/postfix/transport

remember to change alias_maps and alias_database parameters in /etc/main.cf, pointing to the correct aliases file. By default, the aliases file is located in /etc/. The postfix style command for build alias database is

postalias hash:/etc/postfix/aliases

(your aliases file path)

Change the original mail server

In this gateway, Postfix will NOT handle any kinds of local delivery. The original mail server is changed to listen port 26. Here are few examples how to change the listen port.

Sendmail:

Edit /etc/mail/sendmail.mc, find the line contains Port=smtp,Name=MTA,Addr=…… , change to Port=26

Qmail:

Edit /var/qmail/supervise/qmail-smtpd (or equivalent file):

exec /usr/local/bin/softlimit -m 2000000 \
/usr/local/bin/tcpserver -H -R -v -p -x /etc/tcp.smtp.cdb \
-u $QMAILDUID -g $NOFILESGID 0 smtp /var/qmail/bin/qmail-smtpd 2>&1

change smtp to 26

Courier

Locate your courier configuration file esmtpd, look in /etc/courier, or /usr/local/etc/courier

change PORT=26

The emails goes into Postfix through port 25, after scanning, they will be forwarded to the original mail server on port 26. In order to prevent open relaying, sasl authentication must be setup. The alternative solution is setting restrictions on senders.

Configure NOD32

The configuration files of NOD32 is located in /etc/nod32. Key in your username and password in /etc/nod32/nod32.auth for update. For security reason, you are recommended to chmod 400 on the file.

Notification can be enabled by adding the line

exec_script = yes

in /etc/nod32/nod32.cfg, edit nod32d_script with your favourite format.

Add the following line in main.cf:

content_filter=smtp:[127.0.0.1]:2526

And the following in master.cf

localhost:2525 inet n – n – 10 smtpd
-o local_recipient_maps=
-o content_filter=
-o myhostname=nod32.dummydomain.com
-o disable_dns_lookups=yes

After installing NOD32, you are recommended to put a shortcut of /usr/sbin/nod32_update in /etc/cron.hourly, so NOD32 check updates every hour.

Configure a gateway

First we have to give a hostname for Postfx, why? As Postfix delivers emails to the original email server after scanning, the 2 email servers cannot have the same hostname.

Edit main.cf:

myhostname=nod32gateway.domain.com

customize the smtp banner (for fun) as you like

smtpd_banner = $myhostname Virus Gateway

The next is relayhost parameter, Postfix uses this as the default next hop

relayhost=127.0.0.1:26

Then we have to disable local delivery, and make emails for local domain deliver to the original mail server. Here we use the transport map. Setup the transport_maps parameter in main.cf,

transport_maps = hash:/etc/postfix/transport
default_transport = smtp

Add the follow line in /etc/postfix/transport, rebuild transport map afterwards

domain.com     smtp:[127.0.0.1]:26
.domain.com    smtp:[127.0.0.1]:26

(If you have other sub domains)

Everythng is OK now. Restart the original mail server, and run the gateway.

postfix start
service nod32smtp start
service nod32d start

Other issues

Installing Postix over the original mail server will overwrite the original sendmail program, if you want to keep the old one, backup the sendmail program in /usr/bin (or in somewhere). If you have a webmail, you may have to correct your sendmail path in your webmail configuration file.

It is advisable for you to disable the incoming access of port 26, 2525 and 2526, otherwise your mail server may become an open relay host.

 

mod_cband (Apache 2 module of the traffic control like mod_throttle & mod_bandwidth) usage

As in the past to apache 1 mod_throttle gasanghoseuteubyeol the measure and limit traffic was possible.
Limiting the traffic to the hosting is required. Used in any domain that
Knowing very important job. But,
apache2 could only give this guy writes. Is search. cband found.
mod_throttle and function and the structure and almost identical, mod_bandwidth including the functions of, and
Continued performance improvements have been developed recently was becoming.
Than flattering,? Xml glue that, if data are available in the form of xml,
For hosting a really good module.
[Note] cband the apache 2 module. is not easy apache 1.3.XX 1.3.XX mod_throttle use!

[Feature]
* Apache2 module for traffic restrictions Lightweight
* Per-user bandwidth limit
* Gasanghoseuteubyeol bandwidth limit
* The purpose-specific bandwidth limit
* Limit:
All user bandwidth limit o
o limit download sokje
o Fresh water limit requests per second
o IP vs. Small Areas limit
* Support for virtualhosts
* Support for defined users
* Limit the results confirm a Web-based (/ cband-status)
* Check the results for each user limit (/ cband-status-me)

A. How to Install
cd / usr / local
wget http://cband.linux.pl/download/mod-cband-0.9.7.4.tgz
tar xvfpz mod-cband-0.9.7.4.tgz
cd mod-cband-0.9.7.4
. / Configure – with-apxs = / usr / local / apache / bin / apxs
# # Option Description
# # – With-apxs = / usr / local / apache / bin / apxs: apache apxs to specify the path.
make
make install

Two. Verifying the Installation
– Httpd.conf file
LoadModule cband_module modules / mod_cband.so
You can see that the added lines.
– Apache / modules directory
mod_cband.so
You can see what files are added.

Three. The default setting

====================================
<Location /cband-status>
SetHandler cband-status
Order deny, allow
Deny from all
Allow from IP to open up
</ Location>

<Location /cband-status-me>
SetHandler cband-status-me
</ Location>

<VirtualHost *>
ServerName gnux.co.kr
Document / home / gnux / www
CBandLimit 300Mi
CBandPeriod 1D
CBandExceededURL http://manager.gnux.co.kr/traffic_exceeded.html
</ VirtualHost>
======================================
The configuration file in the domain of gnux.co.kr
Day, 300M (300 * 1024 * 1024byte) is set to provide the traffic.
In terms of as a bit, 2.4Gbit / is to provide a traffic.
If you exceed 300M in one day, “http://manager.gnux.co.kr/traffic_exceeded.html”
Pop up page, if you did not give 503 error page will appear.
You! If you want to without restriction in infants, CBandPeriod like portion is deleted.

Four. Contextual Setting
1) Media Speed Limit
==============================
<VirtualHost *>
ServerName rmohan.com
Document / home / gnux / file
CBandSpeed 1024 10 30
CBandRemoteSpeed 20kb / s 3 30
</ VirtualHost>
==============================
File rmohan.com above settings for the domain
Speed is limited to 1024kbps, and 10 times per second connection,
An example of concurrent users is limited to 30.

2) provide users and ilteuraepik yeongyeolsu limit is exceeded.
==============================
<VirtualHost *>
ServerName  rmohan.com
Document / home / gnux / doly
CBandLimit 100Mi
CBandExceededSpeed 128 5 15
CBandPeriod 1D
</ VirtualHost>
==============================
rmohan.com  above settings for a domain
Day of 100Mbyte provide traffic and
If the second 100M,
Limited to 128bps rate, five times per second connection,
An example of concurrent users is limited to 15.

3) If a user has multiple domains?
==============================
<CBandUser Host_user1>
CBandUserLimit 100Mi
CBandUserPeriod 1D
</ CBandUser>
<VirtualHost *>
ServerName rmohan.com
Document / home/host_user1/aaa
CBandUser host_user1
</ VirtualHost>
<VirtualHost *>
ServerName rmohan.com
Document / home/host_user1/bbb
CBandUser host_user1
</ VirtualHost>
==============================
Set of virtual users to specify that the host_user1 a following.
The user is enables the use of a day 100Mbyte.
Then, aaa.co.kr, bbb.co.kr all of host_user1
Traffic has been set to use.

4) IP range, depending on if you want to limit the speed?
==============================================
<CBandClass Class_1>
CBandClassDst 192.168.0.0/24
</ CBandClass>
<CBandClass Class_2>
CBandClassDst 222.97.189.0/24
</ CBandClass>

<VirtualHost *>
ServerName rmohan.com
Document / home / gnux / intranet
CBandClassRemoteSpeed class_1 50Mbps 10 30
CBandClassRemoteSpeed class_2 300kbps 10 30
</ VirtualHost>
==============================================
For the above configuration, the internal IP 192.168.0.XXX, in
The bandwidth of 50Mbps, and 10 times per second the request, a setting of 30 concurrent users, and
In a different ip range 222.97.189.XXX
300kpbs, one request per second, 30 sets of concurrent users.

5 Check usage.
http:// domain / cband-status
http:// domain / cband-status-me

6. Indicators and unit description (if applicable huge!)

  1) unit.
* Transfer speed unit
o kbps, Mbps, Gbps – bits per second: 1024, 1024 * 1024, 1024 * 1024 * 1024 bps
o kb / s, Mb / s, Gb / s – bytes per second: 1024, 1024 * 1024, 1024 * 1024 * 1024 b / s
o Default: kbps

* Traffic quota units
o K, M, G – bytes: 1000, 1000 * 1000, 1000 * 1000 * 1000 bytes
o Ki, Mi, Gi – bytes: 1024, 1024 * 1024, 1024 * 1024 * 1024 bytes
o base: K

* Time (period), the unit
o S, M, H, D, W – seconds, minutes, hours, days, weeks
o Default: S

2) Directives
(1) Name: CBandDefaultExceededURL
Description: When limit is exceeded, show URL (If you do not specify the error page 503)
Context: Server config
Grammar: CBandDefaultExceededURL URL

(2) Name: CBandDefaultExceededCode
Description: show an error code when the limit has been exceeded
Context: Server config
Grammar: CBandDefaultExceededCode HTTP_CODE
Example: CBandDefaultExceededCode 509

(3) Name: CBandScoreFlushPeriod
Description: scoreboard file record number of requests, mod_cband affects performance.
Default: 1
Context: Server config
Grammar: CBandScoreFlushPeriod number of requests
Example: CBandScoreFlushPeriod 100 (one request every scoreboard every 100 records on file)

(4) Name: CBandSpeed
Description: The maximum speed of the virtual host domain, the number of requests, number of connections set
Context: <Virtualhost>
Grammar: CBandSpeed kbps rps max_conn
kbps – maximum transfer rate per second
rps – the maximum number of requests per second
max_conn – the maximum number of simultaneous connections
Example: CBandSpeed 1024 10 30
The maximum transfer rate is limited to 1024kbps, handle 10 requests per second, a limit of 30 simultaneous connections.

(5) Name: CBandRemoteSpeed
Description: The visitor (IP) of the maximum speed, number of requests, number of connections limit (CBandSpeed and similar, but per-connection settings)
Context: <Virtualhost>
Grammar: CBandRemoteSpeed kbps rps max_conn
kbps – maximum transfer rate per second
rps – the maximum number of requests per second
max_conn – the maximum number of simultaneous connections
Example: CBandRemoteSpeed 20kb / s 3 3
Splice (ip) advised on the maximum 20kb / s, 3 requests per second, limited to 3 simultaneous connections.

(6) Name: CBandClassRemoteSpeed
Explanation: The defined class (ip ranges) for the maximum speed, number of requests, number of connections limit
Context: <Virtualhost>
Grammar: CBandClassRemoteSpeed class_name kbps rps
class_name – class name is already defined (IP range)
kbps – maximum transfer rate per second
rps – the maximum number of requests per second
max_conn – the maximum number of simultaneous connections
Example: <CBandClass googlebot_class>
CBandClassDst 66.249.64/24
CBandClassDst 66.249.65/24
CBandClassDst 66.249.79/24
</ CBandClass>
CBandClassRemoteSpeed googlebot_class 20kb / s 2 3
Class defined above (googlebot_class) The request of 20kb / s transfer rate,
Three requests per second, limited to three simultaneous connections.

(7) Name: CBandRandomPulse
Description: The speed limit in order to generate arbitrary waveforms, the following is how to handle the processing of mod_cband.
When there are too many men is the Auto Off.
Context: Global
Grammar: CBandRandomPulse On / Off

(8) Name: CBandLimit
Description: Sets the limit throughput. (The period set in the CBandPeriod)
Context: <Virtualhost>
Grammar: CBandLimit limit
limit – throughput, use the units: K (kilo), M (mega), G (giga), Ki (kibi), Mi (mebi), Gi (gibi)
Example: CBandLimit 10M
Transfer the amount of 10M (10 * 1000 * 1000bytes) is limited to.
CBandLimit 10Mi
Transfer the amount of 10M (10 * 1024 * 1024bytes) is limited to.

(9) Name: CBandClassLimit
Explanation: The defined class (ip ranges) throughput for a set limit.
Context: <Virtualhost>
Grammar: CBandClassLimit class_name limit
class_name – class name is already defined (ip ranges)
limit – throughput, use the units: K (kilo), M (mega), G (giga), Ki (kibi), Mi (mebi), Gi (gibi)

(10) Name: CBandExceededURL
Description: The limit has been exceeded during show URL, if you do not specify a 503 error (virtual host).
Context: <Virtualhost>
Grammar: CBandExceededURL URL

(11) Name: CBandExceededSpeed
Description: The transfer would exceed the amount of time, transfer rate limiting.
Context: <Virtualhost>
Grammar: CBandExceededSpeed kbps rps max_conn
kbps – maximum transfer rate per second
rps – the maximum number of requests per second
max_conn – the maximum number of simultaneous connections

(12) Name: CBandScoreboard
Description: Specifies the virtual host of the scoreboard file. (Required for better performance)
Context: <Virtualhost>
Grammar: CBandScoreboard path
(Path of the Apache (nobody or apache) authority must be writable)

(13) Name: CBandPeriod
Description: The capacity limitations period (After this period, which was measured capacity is cleared.)
Context: <Virtualhost>
Grammar: CBandPeriod period
period – use the units: S (seconds), M (minute), H (hour), D (a), W (weeks)
Example: CBandPeriod 1W (1 Sunday)
CBandPeriod 14D (14 days)
CBandPeriod 60M (60 minutes)

(14) Name: CBandPeriodSlice
Description: The period gilttae shall specify the period of the share.
Defaults: slice_len = limit
Context: <Virtualhost>
Grammar: CBandPeriodSlice slice_length
Example: CBandLimit 100G
CBandPeriod 4W
CBandPeriodSlice 1W
Which is divided into four units per week (4W/1W = 4). Capacity of 100G / 4 = 25G
1 week, 25G, 2 weeks, this split is processed 50G.

(15) Name: <CBandUser>
Description: A new set of virtual users cband
Context: Server config
Grammar: <CBandUser user_name>

(16) Name: CBandUserSpeed
Description: cband virtual user’s speed, the number of requests, limiting the number of simultaneous connections
Context: <CBandUser>
Grammar: CBandUserSpeed kbps rps max_conn
kbps – maximum transfer rate per second
rps – the maximum number of requests per second
max_conn – the maximum number of simultaneous connections
Example: CBandUserSpeed 100kb / s 10 5

(17) Name: CBandUserLimit
Description: cband jeosong capacity limitations of virtual users.
Context: <CBandUser>
Grammar: CBandUserLimit limit
limit – use the capacity, use the units: K (kilo), M (mega), G (giga), Ki (kibi), Mi (mebi), Gi (gibi)
Example: CBandUserLimit 10M
CBandUserLimit 10Mi

(18) Name: CBandUserClassLimit
Description: cband virtual user-defined class (ip ranges) throughput limit set for
Context: <CBandUser>
Grammar: CBandUserClassLimit class_name limit
class_name – the specified class (IP range) Name
limit – use the capacity, use the units: K (kilo), M (mega), G (giga), Ki (kibi), Mi (mebi), Gi (gibi)

(19) Name: CBandUserExceededURL
Description: cband virtual users, to show the limit has been exceeded at URL,
If you do not specify a 503 error (virtual host).
Context: <CBandUser>
Grammar: CBandUserExceededURL URL

(20) Name: CBandUserExceededSpeed
Description: cband virtual users, would exceed the amount of transmission time, transmission rate limiting.
Context: <CBandUser>
Grammar: CBandUserExceededSpeed kbps rps max_conn
kbps – maximum transfer rate per second
rps – the maximum number of requests per second
max_conn – the maximum number of simultaneous connections

(21) Name: CBandUserScoreboard
Description: cband virtual users, scoreboard file specification.
Context: <CBandUser>
Grammar: CBandUserScoreboard path
(Path of the Apache (nobody or apache) authority must be writable)

(22) Name: CBandUserPeriod
Description: cband virtual users, capacity limitations period (After this period, which was measured capacity is cleared.)
Context: <CBandUser>
Grammar: CBandUserPeriod period
period – use the units: S (seconds), M (minute), H (hour), D (a), W (weeks)
Example: CBandUserPeriod 1W
CBandUserPeriod 14D
CBandUserPeriod 60M

(23) Name: CBandUserPeriodSlice
Description: cband virtual users, the period stated period divided
Defaults: slice_len = limit
Context: <CBandUser>
Grammar: CBandUserPeriodSlice slice_length
Example: CBandUserLimit 100G
CBandUserPeriod 4W
CBandUserPeriodSlice 1W
Which is divided into four units per week (4W/1W = 4). Capacity of 100G / 4 = 25G
1 week, 25G, 2 weeks, this split is processed 50G.

7 Enough.
This is the latest version of the current mod_cband installation and operation, detailed description of the directive is the end of the course.
When first discovered, this module gippeotgo so too, has been tested by applying it.
In particular, it can extract the data to xml processing as it was very, very convenient.
Yet excesses in the domestic mod_cband course many people do not have

# # See the document
http://cband.linux.pl
http://www.howtoforge.com/mod_cband_apache2_bandwidth_quota_throttling

New! Click the words above to edit and view alternate translations.

kernel tuning Apache performance

Source:

Here all of the website is an example kernel tuning for improved performance. Try one of those boring study. (Actually, I do not know) I’m just the only data is transferred.

References
http://www.apache.org/docs/misc/perf-tuning.html
web performance tunning – O’Reilly

Keep in mind, however, have some points. In order to improve website performance, rather than the kernel only sondaejuneun OS, networking, programming, etc. that will be considered as a variety of conditions. In addition, blindly without consideration of the performance of the hardware change is to have problems. Services are also generally not an issue in static html, but where performance bottlenecks occur unless the network is often cgi one. Contained in the Apache ab, unix time, ping, netstat, and always use a variety of commands to try to monitor the status of the system will need to take your speed. In addition, the tuning at best, no matter how incredibly to put an image on a web page dundamyeon haneungeot yijiyo vain. As I do not know that eoseolkeuge haetdeoni Oracle tuning cpu 4 dogs, 2G of memory in the system rather than a traditional PC slower deogunyo Oracle. If you are not familiar even better to use the default itjiyo. For example, large sites such as keepalive option below if you have to lay off a lot better if you can. Quick as soon as the connection process and nothing is lost without bothering to put up just making fun of the process rather than anger.

? Apache Web Server Tuning

The tuning of the Apache web server can be briefly divided into two parts. The first is hard-coded into the source code to adjust the limit value, and second, the configuration file is to modify the limit values of each.

1) source-level
HARD_SERVER_LIMIT httpd.h, in the case of Linux, the default value is set to 256 and the server can accept this value implies a connection. This value is set to 1280.

2) the configuration file
A. KeepAliveTimeout
If the client contacts the server to connect to a Web server processes the transmission of multiple objects of the Web page without creating a new process while maintaining continuous connectivity is responsible for the client’s request for a timeout value . Base increased to 30 seconds from 15 seconds.
Or. MaxKeepAliveRequests
Web server process, while maintaining continuous connectivity is the number of requests that can be processed.
Set to 100 and increased to 10000.
All. StartServer, Min / MaxSpareServer
The default setting is 5, 5, 10 or so, and if the new connection to the Web server receives a request Standalone bangsikil existing Spare Child Process Child Process to create a new fork, so basically I Spare Process, the more quickly you can deal with congestion . StartServer 20, MinSpareServer 20, MaxSpareServer 40 increases.
(D) MaxRequestsPerChild
Web server processes to handle client requests a certain number of figures is terminated, and increased to 1000.
E. MaxClients
That can be run concurrently and to limit the maximum number of processes, the default is set to 256. This increased to 512.
Bar. The creation of log files
Users that are logged every time you connect once jeopsokdang access_log files, increasing approximately 85 bytes, and if there are a large number of hits, the size of this file is actually enormous. In this case, whenever access to the log file and load it takes considerable time to access the log files at regular intervals initialized by the need to always have a lighter. Provided by Apache using rotatelog.

Soft-level tuning ?keoneol

The kernel parameter values that provides the / proc file system using the boot is completed, the time change after. This mainly related to the file system and network resources are tuned for the content.

1) The file system-related
– Linux kernel maximum number of files that can be assigned: 4096 -> 32768
– Linux kernel can allocate the maximum number of inode number: 16384 -> 65536
– Root for the user to allocate the maximum number of files: 1024 -> 32768
– A process that can be open at the number of files: 256 -> 512

2) related to network resources
– TCP Keep Alive message to the sending time intervals: 7200 -> 1200
– Final FIN before the socket is always time to wait for a CLOSE: 180 -> 30
– TCP connection requests for a response to the retransmission count: 7 -> 2

This setup your system boots, the values should be set through a script, because the / etc / rc.d / rc.local file is defined at the end of.

? hard kernel-level tuning

By directly modifying the kernel source to adjust the limit. To do this, it is essential to compile the kernel, cautious approach is needed.

– The number of files open
– The number of processes that can handle

Note **

A. Apache Web Server Tuning
– Apache / src / include / httpd.h:
HARD_SERVER_LIMIT 256 -> 1280
– Apache / conf / httpd.conf:
MaxKeepAliveRequests 100 -> 10000
KeepAliveTimeout 15 -> 30
MinSpareServers 5 -> 20
MaxSpareServers 10 -> 40
StartServers 5 -> 20
MaxClients 256 -> 1024

Two. Tuning the kernel level software
– Ulimit-n 32768
– / Proc / sys / fs / file-max: 4096 -> 32768
– / Proc / sys / fs / inode-max: 16384 -> 65536
– / Proc/sys/net/ipv4/tcp_keepalive_time: 7200 -> 1200
– / Proc/sys/net/ipv4/tcp_fin_timeout: 180 -> 30
– / Proc/sys/net/ipv4/tcp_sack: 1 -> 0
– / Proc/sys/net/ipv4/tcp_timestamps: 1 -> 0
– / Proc/sys/net/ipv4/tcp_syncookies: 0 -> 1
– / Proc/sys/net/ipv4/tcp_retries1: 7 -> 2
– / Proc/sys/net/ipv4/tcp_max_syn_backlog: 128 -> 8192
– / Proc/sys/net/ipv4/tcp_window_scaling: 1 -> 0

Three. Hard kernel-level tuning
– / Usr / src / linux / include / linux / fs.h:
NR_FILE 4096 -> 32768
INR_OPEN 1024 -> 32767
– / Usr / src / linux / include / linux / tasks.h:
NR_TASKS 2560 -> 3192
MAX_TASKS_PER_USER 2048 -> 3192
– / Usr / src / linux / include / linux / limits.h:
NR_OPEN 1024 -> 32767
– / Usr / src / linux / include / net / tcp.h:
TCP_TIMEWAIT_LEN (60 * HZ) -> (15 * HZ)

qmail multiple domains support

 

Some time ago I wrote an article about qmail e-mail accounts setting.
Since that time I needed to specify multiple domains with same e-mail names, like:
– info@examle.com to deliver mails to info_example user
– info@example1.com to deliver mails to info_example1 user
– test@example.com to deliver mails to test_example user

This article describes how to set up such environment greatly.

Here is short explanation how to do it.
Add following lines to /var/qmail/control/virtualdomains

1 examle.com:alias-example
2 examle1.com:alias-example1

Add the following files to /var/qmail/alias/
.qmail-example-info with entry line info_example
.qmail-example1-info with entry line info_example1
.qmail-example-test with entry line test_example

restart qmail and it should work.

mod_evasive on Apache

mod_evasive is an evasive maneuvers module for Apache that provides evasive action in the event of an HTTP DoS attack or brute force attack. It is also designed to be a detection and network management tool, and can be easily configured to talk to ipchains, firewalls, routers, and more. mod_evasive presently reports abuse via email and syslog facilities. This guide assumes you already have your LAMP server configured. Guides for setting up a LMAP stack can be found under our LAMP guidessection.

Contents

  • Prerequesites
  • Installing mod_evasive
  • mod_evasive Configuration Options
    • DOSHashTableSize
    • DOSPageCount
    • DOSSiteCount
    • DOSPageInterval
    • DOSSiteInterval
    • DOSBlockingPeriod
    • DOSEmailNotify
    • DOSSystemCommand
    • DOSLogDir
    • Whitelisting IP Address
    • mod_evasive has just one prerequesite beyond the standard LAMP install. To install this module, just run the following command as root in SSH:
    • Debian / Ubuntu:
      apt-get install apache2-utils

      CentOS / Fedora:

      yum install httpd-devel

      Installing mod_evasive

      You’ll first want to get the mod_evasive package, uncompress it, and install it using apxs:

      cd /usr/src
      wget wget http://www.zdziarski.com/blog/wp-content/uploads/2010/02/mod_evasive_1.10.1.tar.gz
      tar xzf mod_evasive_1.10.1.tar.gz
      cd mod_evasive
      apxs -cia mod_evasive20.c

      You’ll then need to add the mod_evasive configuration to your Apache configuration file. First, find this section:

      File:/etc/apache2/apache2.conf (Debian / Ubuntu)

      # Include module configuration:
      Include mods-enabled/*.load
      Include mods-enabled/*.conf

      File:/etc/httpd/conf/httpd.conf (CentOS / Fedora)

      LoadModule evasive20_module   /usr/lib/httpd/modules/mod_evasive20.so
      #

      Below those sections, add the mod_evasive configuration:

      File excerpt:mod_evasive configuration

      <IfModule mod_evasive20.c>
      DOSHashTableSize    3097
      DOSPageCount        2
      DOSSiteCount        50
      DOSPageInterval     1
      DOSSiteInterval     1
      DOSBlockingPeriod   60
      DOSEmailNotify test@rmohan.com
      </IfModule>

      You’ll then need to restart Apache for your changes to take effect:

      Debian / Ubuntu:

      /etc/init.d/apache2 restart

      CentOS / Fedora:

      /etc/init.d/httpd restart

      mod_evasive Configuration Options

      These configuration option descriptions were taken directly from the README file packaged with the mod_evasive tarball you downloaded during installation.

      DOSHashTableSize

      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 (see mod_evasive.c for a list of primes used).

      DOSPageCount

      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

      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

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

      DOSSiteInterval

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

      DOSBlockingPeriod

      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.

      DOSEmailNotify

      If this value is set, an email will be sent to the address specified whenever an IP address becomes blacklisted. A locking mechanism using /tmp prevents continuous emails from being sent.

      NOTE: Be sure MAILER is set correctly in mod_evasive.c
      (or mod_evasive20.c). The default is “/bin/mail -t %s” where %s is used to denote the destination email address set in the configuration. If you are running on linux or some other operating system with a different type of mailer, you’ll need to change this.

      DOSSystemCommand

      If this value is set, the system command specified will be executed whenever an IP address becomes blacklisted. This is designed to enable system calls to ip filter or other tools. A locking mechanism using /tmp prevents continuous system calls. Use %s to denote the IP address of the blacklisted IP.

      DOSLogDir

      Choose an alternative temp directory

      By default “/tmp” will be used for locking mechanism, which opens some security issues if your system is open to shell users. In the event you have nonprivileged shell users, you’ll want to create a directory writable only to the user Apache is running as (usually root), then set this in your httpd.conf.

      Whitelisting IP Addresses

      IP addresses of trusted clients can be whitelisted to insure they are never denied. The purpose of whitelisting is to protect software, scripts, local searchbots, or other automated tools from being denied for requesting large amounts of data from the server. Whitelisting should not be used to add customer lists or anything of the sort, as this will open the server to abuse. This module is very difficult to trigger without performing some type of malicious attack, and for that reason it is more appropriate to allow the module to decide on its own whether or not an individual customer should be blocked.

      To whitelist an address (or range) add an entry to the Apache configuration in the following fashion:

      DOSWhitelist 127.0.0.1 DOSWhitelist 127.0.0.*

      Wildcards can be used on up to the last 3 octets if necessary. Multiple DOSWhitelist commands may be used in the configuration.


      Protecting Apache against DOS attack with mod_evasive

       

      Novell Cool Solutions: Feature

      Problem:

       

      Having users constantly making HTTP requests to slow your server down and possibly causing a DOS (Denial Of Service) attack.

       

      Solution:

       

      Deploy the mod_evasive module.

       

      Environment Factors:

       

      This article was tested on SUSE Linux Enterprise Server SP1.

       

      Protecting Apache against DOS attack with mod_evasive

       

      The Apache web server is the most popular web server on the Internet today holding a “52.65% market share for top servers across all domains August 1995 – July 2007” (Netcraft, 2007). The Apache module “mod_evasive” is an excellent module which helps defend against malicious users trying to perform HTTP DoS (Denial of Service) attacks and also helps protect against brute force attacks.

       

      The “mod_evasive” module detects attacks using three different methods; 1) requesting the same page more than a few times per second, 2) making more than 50 concurrent requests on the same child per second and 3) making any requests while temporarily blacklisted.

       

      Mod_evasive

       

      The first step to installing mod_evasive is to download the source code from [2] website. Once you have downloaded the source file you will need to unpack the compressed archive using the “tar” utility as shown in Figure 1.

       

      Linux-w2mu:~# tar zvxf mod_evasive_1.10.1.tar.gz

       

      Figure 1: Unpacking mod_evasive.

       

      Once mod_evasive has been unpacked change into the directory that contains the source code as we will need to compile the “mod_evasive20.c” file, but before you compile the source code you will need to install some dependencies that mod_evasive relies on.

       

      mod_evasive dependencies

       

      The dependencies that mod_evasive requires are listed in Table 1, you can install these dependencies off the SUSE Linux Enterprise Server CD/DVD.

       

      Dependency Summary
      apache2-devel Header and Include Files
      apache2-prefork “prefork” MPM (Multi-Processing Module)

       

      Table 1: Mod_evasive dependencies.

       

      Once you have installed all the dependencies listed in Table 1 and unpackaged the source code, you can begin to compile the “mod_evasive20.c” file with the “apxs2” command as shown in Figure 1.1.

       

      Linux-w2mu:~# apxs2 -ci mod_evasive20.c
      /usr/lib/apr-1/build/libtool --silent --mode=compile gcc -prefer-pic -O2 -march=i586 -mtune=i686 -fmessage-length=0 -Wall -D_FORTIFY_SOURCE=2 -g -fPIC -Wall -fno-strict-aliasing -DLDAP_DEPRECATED -DLINUX=2 -D_REENTRANT -D_GNU_SOURCE -D_LARGEFILE64_SOURCE -DAP_DEBUG -pthread -I/usr/include/apache2  -I/usr/include   -I/usr/include/apr-1   -c -o mod_evasive20.lo mod_evasive20.c && touch mod_evasive20.slo 
      ...
      ...

       

      Figure 1.1: Compiling mod_evasive for Apache 2.

       

      Enabling mod_evasive

       

      Once you have compiled the mod_evasive module you will need the module to load when Apache is started or restarted. The file that needs to be modified is “/etc/sysconfig/apache2” and the directive that needs to be altered is “APACHE_MODULES=” as it needs to include the mod_evasive20 module, as shown in Figure 2.

       

      ...
      APACHE_MODULES="mod_evasive20 actions alias auth_basic authn_file authz_host authz_groupfile authz_default authz_user authn_dbm autoindex cgi dir env expires include log_config mime negotiation setenvif ssl suexec userdir php5"
      ...

       

      Figure 2: Altered /etc/sysconfig/apache2 configuration file.

       

      Once you have modified the “/etc/sysconfig/apache2” configuration file you will need to check the Apache syntax using the “service” command as shown in Figure 2.1.

       

      Linux-w2mu:~# service apache2 configtest
      Syntax OK

       

      Figure 2.1: Verifying the syntax is OK.

       

      Mod_evasive configuration

       

      Once you have modified the “/etc/sysconfig/apache2” configuration file you will need to create a configuration file for the mod_evasive module. In the “/etc/apache2” directory you will need to create a file called: “mod_evasive.conf” with the following or similar content shown in Figure 3.

       

      <IfModule mod_evasive20.c> 
          DOSHashTableSize    3097 
          DOSPageCount        2 
          DOSSiteCount        50 
          DOSPageInterval     1 
          DOSSiteInterval     1 
          DOSBlockingPeriod   10 
      </IfModule>

       

      Figure 3: mod_evasive.conf

       

      The key pairs that are used in the “mod_evasive.conf” configuration file are listen in Table 2 along with a description.

       

      Key Description
      DOSHashTableSize 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
      DOSPageCount This is the threshold for the number of requests for the same page (or URI) per page interval. Once the threshold for that interval has been exceeded, the IP address of the client will be added to the blocking list.
      DOSSiteCount This is the threshold for the total number of requests for any object by the same client on the same listener per site interval.
      DOSPageInterval The interval for the page count threshold; defaults to 1 second intervals.
      DOSSiteInterval The interval for the site count threshold; defaults to 1 second intervals.
      DOSBlockingPeriod 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).
      DOSEmailNotify If this value is set, an email will be sent to the address specified whenever an IP address becomes blacklisted. A locking mechanism using /tmp prevents continuous emails from being sent.
      DOSSystemCommand If this value is set, the system command specified will be executed whenever an IP address becomes blacklisted. This is designed to enable system calls to ip filter or other tools.
      DOSLogDir Choose an alternative temp directory, default is /tmp.

       

      Table 2: Mod_evasive key pairs.

       

      Once you are happy with your “mod_evasive.conf” configuration file you can restart the Apache web server and test your new configuration. There are two methods of checking mod_evasive is function correctly. The first method is to run the “test.pl” file in the mod_evasive directory as shown in Figure 3.1.

       

      Linux-w2mu:~# perl test.pl
      HTTP/1.1 200 OK 
      HTTP/1.1 200 OK 
      HTTP/1.1 200 OK 
      HTTP/1.1 200 OK 
      HTTP/1.1 403 Forbidden 
      HTTP/1.1 403 Forbidden 
      ...
      ...

       

      Figure 3.1: Checking mod_evasive.

       

      The second method to check mod_evasive is functioning correctly is to connect to your web server and hit the refresh button really fast and you should be presented with a “403 Forbidden” message.

       

      Final Thoughts

       

      Now that you have installed and configured mod_evasive, your Apache web server should be able to defend against HTTP DOS attacks and brute force attacks. I would also recommend placing offending IP addresses into your IP tables using the “DOSSystemCommand” key. The reason you should add the offending IP address into your IP tables is so they don’t even get to see the “403 Forbidden” message thus making your website look down.

    • Securing Apache against HTTP DoS and/or Brute Force attacks

      There are some native Apache directives that can be configured to help mitigate the effects of a Denial of Service (DoS) attack. The directives included Timeout, KeepAlive, and KeepAliveTimeout.

      TimeOut

      One way of attacking web servers is to try and exhaust the target systems resources by opening multiple connections and then never closing them. The more connections the server has open at once, the more resources are tied up holding details of those connections, which can lead to increased load and eventually to the server running out of resources.

      The TimeOut directive tells the server how long to wait to receive a GET request, the amount of time between receipt of TCP packets on a POST or PUT request, or the amount of time between ACKs on transmissions of TCP packets in responses. Basically, this is the total time it takes to receive and respond to an http request.

      In order to prevent a DoS attack from shutting down our web server, we need to change the default setting of 300 (which is 5 minutes) to something more reasonable such as 60 (which is 1 minute). You may even adjust this setting to be lower than 60. Think about this for a minute.

      KeepAlive
      How many individual graphics files do you think there are in the average web page? Last check on the Amazon.com home page showed approximately 58 graphics files (gif and jpg) being referenced. Now imagine if your web browser had to create a brand-new connection for every one of those files. The overhead associated with initializing the HTTP connection would increase the time to fully load a web page significantly. This is where the concept of KeepAlives and “pipelining” web requests came from. The idea is simple: to allow multiple requests from the same client to utilize the same established HTTP connection. This efficient use of this capability dramatically decreases the amount of time it takes to fully download and display a web page. It is for this reason that the KeepAlive directive should be turned on.

      KeepAliveTimeout
      Much in the same way that the Timeout directive limited the amount of time that the established HTTP connection would be valid, the KeepAliveTimeout directive will expire a socket after the designated amount of time. The difference between the Timeout and the KeepAliveTimeout directives is that the timeout setting designates the amount of time that the entire connection will be open and the KeepAliveTimeout directive states how long the server will wait for a subsequent request from the client. This means that the KeepAliveTimeout setting should always be less then the timeout setting. The default setting for KeepAliveTimeout is 15 seconds, which is reasonable; however, you could lower this just a bit if desired.

      While these directives help with the performance of Apache and will lessen the impact of a DoS attack, there is another third-party module that is extremely effective.

      mod_evasive is an evasive maneuvers module for Apache whose purpose is to react to HTTP DoS and/or Brute Force attacks. It was developed by Jonathan Zdziarski.

      An additional capability of the module is that it is also able to execute system commands when DoS attacks are identified. This provides an interface to send attacking IP addresses to other security applications such as local host-based firewalls to block the offending IP address.

      Installing mod_evasive on Centos 5.3:

      ( you can find lots of documents that explains how to install mod_evasive on other distributions )
      # rpm -Uvh http://download.fedora.redhat.com/pub/epel/5/i386/epel-release-5-3.noarch.rpm
      # yum install mod_evasive

      Configuring  mod_evasive :

      /etc/httpd/conf.d/mod_evasive.conf is main configuration file for mod_evasive :

      LoadModule evasive20_module modules/mod_evasive20.so <IfModule mod_evasive20.c> DOSHashTableSize    3097 DOSPageCount        5 DOSSiteCount        100 DOSPageInterval     1 DOSSiteInterval     1 DOSBlockingPeriod   10 DOSEmailNotify      nasser@mydomain.com #DOSSystemCommand    "su - someuser -c '/sbin/... %s ...'" DOSLogDir           "/var/lock/mod_evasive" #DOSWhitelist   127.0.0.1 </IfModule> 

      We will now discuss each of the mod_evasive directives. Most of this information is taken directly from the README file of mod_evasive, so proper credit should be given to the developer of this module.

      DosHashTableSize

      This directive specifies the number of top-level nodes for each apache child process’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.

      DOSPageCount

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

      DOSSiteCount

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

      DOSPageInterval

      The interval for the page count threshold; defaults to 1 second intervals.

      DOSSiteInterval

      The interval for the site count threshold; defaults to 1 second intervals.

      DOSBlockingPeriod

      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). Because 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.

      DOSEmailNotify

      If this value is set, an email will be sent to the address specified whenever an IP address becomes blacklisted. A locking mechanism using /var/lock/mod_evasive prevents continuous emails from being sent.
      Note: Requires /bin/mail (provided by mailx)

      DOSSystemCommand

      If this value is set, the system command specified will be executed whenever an IP address becomes blacklisted. This is designed to enable system calls to ip filter or other tools. Use %s to denote the IP address of the blacklisted IP.

      DOSLogDir

      Choose an alternative temp directory. By default, “/tmp” will be used for the locking mechanism, which opens some security issues if your system is open to shell users. refer to => http://security.lss.hr/index.php?page=details&ID=LSS-2005-01-01

      WhiteListing

      IP addresses of trusted clients can be whitelisted to ensure they are never denied. The purpose of whitelisting is to protect software, scripts, local searchbots, or other automated tools from being denied for requesting large amounts of data from the server. Whitelisting should not be used to add customer lists or anything of the sort, as this will open the server to abuse. This module is very difficult to trigger without performing some type of malicious attack, and for that reason, it is more appropriate to allow the module to decide on its own whether or not an individual customer should be blocked.
      To whitelist an address (or range), add an entry to the Apache configuration in the following fashion:
      DOSWhitelist    127.0.0.1

      DOSWhitelist    127.0.0.*
      Wildcards can be used on up to the last three octets if necessary. Multiple DOSWhitelist commands may be used in the configuration.

      Testing

      mod_evasive comes with a PERL script called test.pl. Without editing the file, if you execute it, it will send a total of 100 requests for incrementing URLs (based on 0-100) to the localhost address on port 80.

      #!/usr/bin/perl
      # test.pl: small script to test mod_evasive's effectiveness
      use IO::Socket;
      use strict;
      
      for(0..100) {
       my($response);
       my($SOCKET) = new IO::Socket::INET( Proto   => "tcp",
       PeerAddr=> "127.0.0.1:80");
      
       if (! defined $SOCKET) { die $!; }
       print $SOCKET "GET /?$_ HTTP/1.0\n\n";
       $response = <$SOCKET>;
       print $response;
       close($SOCKET);
      }

      If you run the script, you should see output similar to the following:

      # ./test.pl

      HTTP/1.1 200 OK

      HTTP/1.1 200 OK

      HTTP/1.1 200 OK

      HTTP/1.1 200 OK

      HTTP/1.1 200 OK

      HTTP/1.1 200 OK

      HTTP/1.1 200 OK

      HTTP/1.1 200 OK

      HTTP/1.1 200 OK

      HTTP/1.1 200 OK

      HTTP/1.1 200 OK

      HTTP/1.1 200 OK

      HTTP/1.1 200 OK

      HTTP/1.1 200 OK

      HTTP/1.1 200 OK

      HTTP/1.1 200 OK

      HTTP/1.1 200 OK

      HTTP/1.1 200 OK

      HTTP/1.1 403 Forbidden

      HTTP/1.1 403 Forbidden

      HTTP/1.1 403 Forbidden

      HTTP/1.1 403 Forbidden

      HTTP/1.1 403 Forbidden

      –CUT–

his address no longer accepts mail quick fix

To fix this edit these files:
vi /var/qmail/control/rcpthosts
vi /var/qmail/control/virtualdomains

Remove the line with this domain from both files then restart Qmail:
/etc/init.d/qmail restart