Troubleshoot Mod_Security Rules

How To Troubleshoot Mod_Security Rules

Posted on January 8, 2011 by

So you’ve read all my posts about how wonderful and necessary Mod_Security is and decided to configure it on your server. You activate a bunch of new rules from GotRoot or OWASP and now suddenly nobody can access your website, you can’t create new posts, or things are otherwise FUBAR – NOW what do you do?

First – don’t panic. Premade Modsecurity rulesets have hundreds of rules that must work across a variety of websites and CMS’s. They are usually 99% perfect, but there is always that 1% that may cause problems on your particular site or configuration. If you are coming to this post via Google, and you are already panicking, just go into your HTTP.CONF or MODSEC2.CONF file (you will need to figure out where your ModSecurity directives are being stored) and add the following line:
SecFilterEngine Off
Then restart Apache. This should stop Mod_Security from blocking anything, but still let you see what it’s doing in the logs. Now you can relax and start troubleshooting.

Troubleshooting Mod_Security 2.5:
The first step is to identify which rule is blocking your users or breaking your site. To see what is happening, check your Apache Error log or your Mod_Security log. In your logs, you will see something like this:

Pattern match "(?:cd |\;|php |echo |perl |killall |python |rpm |yum |apt-get |emerge |lynx |links |mkdir |elinks |wget |lwp-(?:download|request|mirror|rget) |id|uname |cvs |svn |(?:s|r)(?:cp|sh) |net(?:stat|cat) |rexec |smbclient |t?ftp |ncftp |curl |telnet |g?cc |cp ..." at REQUEST_URI. [file "/etc/modsecurity/10_asl_rules.conf"]
[line "587"] [id "340037"] [rev "3"] [msg " - FREE UNSUPPORTED DELAYED FEED - WAF Rules: Generic command injection"] [severity "CRITICAL"] 340037 [07/Jan/2011:22:43:29 --0800]
Pattern match "(?:cd |\;|php |echo |perl |killall |python |rpm |yum |apt-get |emerge |lynx |links |mkdir |elinks |wget |lwp-(?:download|request|mirror|rget) |id|uname |cvs |svn |(?:s|r)(?:cp|sh) |net(?:stat|cat) |rexec |smbclient |t?ftp |ncftp |curl |telnet |g?cc |cp ..." at REQUEST_URI. [file "/etc/modsecurity/10_asl_rules.conf"] [line "587"] [id "340037"] [rev "3"] [msg " - FREE UNSUPPORTED DELAYED FEED - WAF Rules: Generic command injection"] [severity "CRITICAL"]
[07/Jan/2011:22:43:29 --0800] THcUgdXS8AADiSIm4AX 42556 80
GET /modules/forum/hide-comments.png HTTP/1.1
User-Agent: Mozilla/5.0 (iPad; U; CPU OS 4_2_1 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5
Accept: */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate

Look through the log for the “id” and file – in the example above, it’s [file/etc/modsecurity/10_asl_rules.conf] and the ID is rule #340037. Now you know what mod_security file to focus on (10_asl_rules.conf) and where in that file to start looking (rule/id 340037).

Open up file 10_asl_rules.conf and search until you find 340037 –

Rule 340037 looks like this:

# Rule 340037: generic attack signature
SecRule REQUEST_URI "(?:cd |\;|php |echo |perl |killall |python |rpm |yum |apt-get |emerge |lynx |links |mkdir |elinks |wget |lwp-(?:download|request|mirror|rget) |id|uname |cvs |svn |(?:s|r)(?:cp|sh) |net(?:stat|cat) |rexec |smbclient |t?ftp |ncftp |curl |telnet |g?cc |cpp |g\+\+ |/bin/(xterm|id|bash|sh|echo|kill|chmod|ch?sh|python|perl|nasm|ping|mail|ssh))" \
"id:340037,rev:3,severity:2,msg:' - FREE UNSUPPORTED DELAYED FEED - WAF Rules: Generic command injection'"

Now you need to figure out what it is about this rule that is going wrong, so back to the error log:
The error (above) says “Pattern match” (then all the match-rules) at REQUEST_URI. “REQUEST_URI” is the Mod_Security directive to inspect the URL being requested. (For a list of all the directives, check the MODSECURITY online-manual). To see what the URL was, find the GET command a little further down – in the example above, it’s GET /modules/forum/hide-comments.png

So we now know that rule #340037 located in file 10_asl_rules.conf does not like “modules/forum/hide-comments.png” – So let’s figure out why.

Rule 340037 (above) is made up of just a few lines (like most rules). The first line, starting with the ‘#’ is a comment describing the rule: # Rule 340037: generic attack signature

The next line:
"SecRule REQUEST_URI "(?:cd |\;|php |echo |perl |killall |python |rpm |yum |apt-get |emerge |lynx |links |mkdir |elinks |wget |lwp-(?:download|request|mirror|rget) |id|uname |cvs |svn |(?:s|r)(?:cp|sh) |net(?:stat|cat) |rexec |smbclient |t?ftp |ncftp |curl |telnet |g?cc |cpp |g\+\+ |/bin/(xterm|id|bash|sh|echo|kill|chmod|ch?sh|python|perl|nasm|ping|mail|ssh))"

Basically says if the URL matches this very complex regular expression, then do what’s in the next line, which reads:
"id:340037,rev:3,severity:2,msg:' - FREE UNSUPPORTED DELAYED FEED - WAF Rules: Generic command injection'"

This ID’s the rule as ’340037′ with revision#3, sets the severity level for logging, and assigns the message to show in the logs – because elsewhere in the mod_security configuration the default action as been set to “deny” – this page/url will been blocked – but WHY?

To figure out what it is about about the path “modules/forum/hide-comments.png” that the expression above does not like you can try to read-through it and figure it out (good luck!) or use a RegEx (Regular Expression) tool such as to see what the match is. In our example, it is the “id” in the path ‘hide-comments.png’ that matches (?:download|request|mirror|rget) |id|uname |cvs |svn |(?:s|r) in the rule.

Now we know where and why Mod_Security has blocked this particular page.. Now what?

Now you have to decide what to do about it – here are some choices:
1) Disable the entire rule
2) Disable the rule only for this particular URL (“ByLocation”)
3) Create a slightly modified custom rule that overrides this rule and works with this particular page/URL

Which route you take depends on many things and I can’t tell you which to choose – that part you will have to figure out on your own.

Option 1 – Disable the entire rule:
You could simply delete all the lines associated with rule 340037, or comment them out by putting a ‘#’ on each line, then restart Apache. The problem with this method is that if you ever update your rules, your changes will be overwritten with the new file, and the rule would be active again. A better way to disable the rule is to add the following line in your HTTP.CONF or MODSEC2.CONF file:

SecRuleRemoveById 340037

Restart Apache and now rule 340037 will be disabled

Option 2 – Disable the rule just for this particular URL:
You can tell Mod_security to ignore rule 340037 only for the URL /modules/forum/hide-comments.png by adding the following line to your HTTP.CONF or MODSEC2.CONF file:

<LocationMatch modules/forum/hide-comments.png>

SecRuleRemoveById 340037


Restart Apache and now rule 340037 will be ignored/disabled only for the URL /modules/forum/hide-comments.png

Option 3 – Replace rule 340037 with your own, slightly customized rule:
You can create your own custom rule that does not include the “id” match, then disable the ‘real’ rule 340037.

First, create a new file named something like “99_my_rules.conf” and place in the same directory as your other Mod_Security rules (probably at /etc/modsecurity). Copy and paste rule 340037 from 10_asl_rules.conf and put into your new custom-rules file and make the following changes:

Change “340037″ to 990037 – This will keep you from confusing it with the real rule “340037″

Change the message from : ‘ – FREE UNSUPPORTED DELAYED FEED – WAF Rules: Generic command injection’
to something like: ‘My custom rule that replaces 340037′

Find the part of the expression that we want to get rid of – in this case it is the “id” at this part:

|request|mirror|rget) |id|uname |cvs |svn

Remove the “id|”, which should leave just:

|request|mirror|rget) |uname |cvs |svn

and save the file.

In your HTTP.CONF or MODSEC2.CONF file, disable the original rule 340037 by following Option #1 above

Add the following line in your HTTP.CONF or MODSEC2.CONF file to tell Mod_security to load your new custom rules:
Include /etc/modsecurity/99_my_rules.conf — place this line right after the other rules listed. Be sure to use the correct path for your system.

Restart Apache and now the original rule 340037 will be disabled and your new rule 990037 will be active. If you ever need to create any other custom rules, just add them into your new 99_my_rules.conf file (and restart Apache).

Some things to keep in mind when changing Mod_Security rules:
Before you change any files, make a copy of it first. It’s very easy to make a syntax error, or screw something up.

Each time you restart Apache, make sure it actually starts and check your site! If Apache will not start, just put back the backup file that you made, and start Apache again – then figure out what went wrong.

If you disabled blocking in Mod_Security with the SecFilterEngine Off directive, be sure to change it back to SecFilterEngine ON

Most important – watch your logs very closely and verify that ModSecurity is only blocking things you really want blocked.

Published in: on April 1, 2012 at 12:39 pm  Comments Off on Troubleshoot Mod_Security Rules  

Prevent and Stop DoS or DDoS Attacks on Web Server (D)DOS-Deflate

All web servers been connected to the Internet subjected to DoS (Denial of Service) or DDoS (Distrubuted Denial of Service) attacks in some kind or another, where hackers or attackers launch large amount connections consistently and persistently to the server, and in advanced stage, distributed from multiple IP addresses or sources, in the hope to bring down the server or use up all network bandwidth and system resources to deny web pages serving or website not responding to legitimate visitors.

There are plenty of ways to prevent, stop, fight and kill off DDoS attack, such as using firewall. A low cost, and probably free method is by using software based firewall or filtering service. (D)DoS-Deflate is a free open source

Unix/Linux script by MediaLayer that automatically mitigate (D)DoS attacks. It claims to be the best, free, open source solution

to protect servers against some of the most excruciating DDoS attacks.

(D)DoS-Deflate script basically monitors and tracks the IP addresses are sending and establishing large amount of TCP network connections such as mass emailing, DoS pings, HTTP requests) by using “netstat” command, which is the symptom of a denial of service attack. When it detects number of connections from a single node that exceeds certain preset limit, the script will automatically uses APF or IPTABLES to ban and block the IPs. Depending on the configuration, the banned IP addresses would be unbanned using APF or IPTABLES (only works on APF v 0.96 or better).

Installation and setup of (D)DOS-Deflate on the server is extremely easy. Simply login as root by open SSH secure shell access to the server, and run the the following commands one by one:

chmod 0700

To uninstall the (D)DOS-Deflate, run the following commands one by one instead:

chmod 0700 uninstall.ddos

The configuration file for (D)DOS-Deflate is ddos.conf, and by default it will have the following values:


Users can change any of these settings to suit the different need or usage pattern of different servers. It’s also possible to whitelist and permanently unblock (never ban) IP addresses by listing them in /usr/local/ddos/ignore.ip.list file. If you plan to execute and run the script interactively, users can set KILL=0 so that any bad IPs detected are not banned.

Published in: on January 5, 2011 at 2:07 pm  Comments Off on Prevent and Stop DoS or DDoS Attacks on Web Server (D)DOS-Deflate  

Prevent HTTP DoS or DDoS (Denial of Service) attack or brute force attack at the web server

mod_evasive, formerly known as mod_dosevasive is a Apache module that provides evasive maneuvers action in the event of an HTTP DoS or DDoS (Denial of Service) attack or brute force attack at the web server. When possible attacks are detected, mod_evasive will block the traffic from the source for a specific duration of time, while reports abuses via email and syslog facilities. Or administrators can configure mod_evasive to talk to iptables, ipchains, firewalls, routers, and etc. to build a comprehensive DDOS prevention system for the high traffic busy web server.

Although mod_evasive is not a foolproof and complete DOS prevention system, but installing mod_evasive module for Apache will likely to reduce and stop certain DDOS attacks, minimizing the risks of web hosts and web sites been completely brought down inaccessible by malicious denial of service attack attempts.

How to Install mod_evasive

  1. Login to web server via SSH.
  2. For Apache 2.0.x, execute the following command:up2date -i httpd-devel
  3. Continue with the following commands one by one for all version of Apache HTTPD server. wget command will download the current stable version 1.10.1 source /usr/local/src
    tar -zxvf mod_evasive_1.10.1.tar.gz
    cd mod_evasive
  4. For Apache 2.0.x , execute the following command:/usr/sbin/apxs -cia mod_evasive20.c

    Else, for Apache 1.3.x,

    /usr/local/apache/bin/apxs -cia mod_evasive.c

    Above commands will compile mod_evasive to .so and subsequently add corrensponding AddModule and LoadModule lines into httpd.conf.

  5. mod_evasive comes with default configuration value preset, however, if webmasters want to configure and set the value themselves, the following parameters have to be added into httpd.conf Apache configuration file below the AddModule section.For Apache 2.0.x, add the following text to httpd.conf below AddModule section:

    <IfModule mod_evasive20.c>
    DOSHashTableSize 3097
    DOSPageCount 5
    DOSSiteCount 100
    DOSPageInterval 1
    DOSSiteInterval 1
    DOSBlockingPeriod 600

    For apache 1.3.x, add the following text to httpd.conf below AddModule section:

    <IfModule mod_evasive.c>
    DOSHashTableSize 3097
    DOSPageCount 5
    DOSSiteCount 100
    DOSPageInterval 1
    DOSSiteInterval 1
    DOSBlockingPeriod 600

    Save and exit the httpd.conf Apache configuration file.

  6. Restart the Apache server with the following command:/etc/init.d/httpd restart

Note: If apxs is not found, it can be installed via “yum install httpd-devel” command.

Installation is completed. Note that mod_evasive has known issues with FrontPage Server Extensions. Administrator can configure the variables such as enlarging the DOSHashTableSize especially for busy server. But note that whenever when a sournce of attack is blocked, the blocking duration is automatically extended whenever the source attempts to connect again, thus the DOSBlockingPeriod needs not to be too long. Beside, the blocking is based on each sessions of Apache child process, thus the blocking has the lifespan of that particular session only. If webmaster set the maximum clients per process to a very low value, the blocking may not be very effective. All definitions of mod_evasive directives can be found on README file comes with the source codes.

Other than above common configuration parameters, mod_evasive also supports the following three advanced directives:

DOSSystemCommand “su – someuser -c ‘/sbin/… %s …’”
DOSLogDir “/var/lock/mod_evasive”

The DOSEmailNotify is particular useful, where you can set mod_evasive to send a notification email whenever a possible DOS attack is detected and blocked. For example, “DOSEmailNotify root” will send the email to root user. But note that mailer configuration (by default is “/bin/mail -t %s”) in mod_evasive.c or mod_evasive20.c is correct. You can create a symbolic link if needed to or modify the source code file.

Published in: on January 5, 2011 at 2:03 pm  Comments Off on Prevent HTTP DoS or DDoS (Denial of Service) attack or brute force attack at the web server  

Linux Internet Web Server and Domain Configuration Tutorial

Linux Internet Web Server and Domain Configuration Tutorial

Check this link

Published in: on May 6, 2010 at 9:40 pm  Comments Off on Linux Internet Web Server and Domain Configuration Tutorial  

Apache Server Securing-Tips


This article shows in a step-by-step fashion, how to install and configure the Apache 1.3.x Web server in order to mitigate or avoid successful break-in when new vulnerabilities in this software are found.


Before we start securing Apache, we must specify what functionality we expect from the server. Variety of Apache’s use makes it difficult to write a universal procedure to secure the server in every case. That’s why in this article we’ll base on the following functionality:

  • The Web server will be accessible from the Internet; and,
  • Only static HTML pages will be served
  • the server will support name-based virtual hosting mechanism
  • specified Web pages can be accessible only from selected IP addresses or users (basic authentication)
  • the server will log all the Web requests (including information about Web browsers)

It is worth emphasizing that the above model doesn’t support PHP, JSP, CGI or any other technologies that make it possible to interact with Web services. The use of such technologies may pose a large security threat, so that even a small, inconspicuous script can radically decrease the server’s security level. Why? Primarily, ASP/CGI applications may contain security vulnerabilities (e.g. SQL injection, cross-site-scripting). Secondarily, the technology itself can be dangerous (vulnerabilities in PHP, Perl modules etc.). That’s why I strongly recommend using such technologies only when an interaction with a Web site is absolutely necessary.

Security Assumptions

One of the most important elements of every computer project is the specification of security assumptions. This must be fulfilled before the project is implemented. The security assumptions for our Web server are as follows:

  • The operating system must be hardened as much as possible, both against local and remote attacks;
  • The server must not offer any network services except HTTP: (80/TCP);
  • Remote access to the server must be controlled by a firewall, which should block all outbound connections, and allow inbound connections only to the 80/TCP port of the Web server;
  • The Apache Web server must be the only service available on the system;
  • Only absolutely necessary Apache modules should be enabled;
  • Any diagnostic Web pages and automatic directory indexing service must be turned off;
  • The server should disclose the least amount of information about itself (security by obscurity);
  • The Apache server must run under a unique UID/GID, not used by any other system process;
  • Apache’s processes must have limited access to the file systems (chrooting); and,
  • No shell programs can be present in the Apache’s chrooted environment (/bin/sh, /bin/csh etc.).

Installing the Operating System

Before installing Apache we must choose an operating system, upon which the server will run. We’ve got a broad choice here, because Apache can be compiled and installed on almost every operating system. The rest of the article instructs how to secure the Apache Web server on FreeBSD (4.7), however the described methods are possible to apply in case of most UNIX/Linux systems. The only operating system I do not recommend using is MS Windows – mainly because of the limited capabilities of securing the Apache.

The first step in securing the Web server is hardening the operating system. A discussion of hardening the operating system is beyond the scope of this article. However, there are a lot of documents on the Net describing how to perform that. Readers are encouraged to conduct their own issue on this topic.

After the system is installed and hardened, we have to add a new group and regular user called “apache” like this (an example from FreeBSD):

 pw groupadd apache pw useradd apache -c "Apache Server" -d /dev/null -g apache -s /sbin/nologin

By default, Apache processes run with privileges of user nobody (except the main process, which runs with root privileges) and GID of group nogroup. This might pose a significant security threat. In case of successful break-in, the intruder can obtain access to all other processes that run under the same UID/GID. Hence, the optimum solution is to run Apache under the UID/GID of a unique regular user/group, dedicated to that software.

Preparing the Software

The next step is to download the latest version of the Apache Web server. Some of Apache’s options can be enabled only during compilation time, thus it is important to download the source code instead of the binary version.

After downloading the software, we must unpack it. Then we must decide which modules should remain enabled. A short description of all modules available in the latest version of Apache 1.3.x (1.3.27) can be found at

Apache’s Modules

The choice of modules is one of the most important steps of securing Apache. We should go by the rule: the less the better. To fulfill the functionality and security assumptions, the following modules must remain enabled:

Module’s name Description
httpd_core The core Apache features, required in every Apache installation.
mod_access Provides access control based on client hostname, IP address, or other characteristics of the client request. Because this module is needed to use “order”, “allow” and “deny” directives, it should remain enabled.
mod_auth Required in order to implement user authentication using text files (HTTP Basic Authentication), which was specified in functionality assumptions.
mod_dir Required to search and serve directory index files: “index.html”, “default.htm”, etc.
mod_log_config Required to implement logging of the requests made to the server.
mod_mime Required to set the character set, content- encoding, handler, content-language, and MIME types of documents.

All other Apache’s modules must be disabled. We can safely turn them off, mainly because we do not need them. By disabling unneeded modules, we can avoid potential break-ins when new security vulnerabilities are found in one of them.

It is also worth to note that two of Apache’s modules can be more dangerous than others: mod_autoindex and mod_info. The first module provides for automatic directory indexing, and is enabled by default. It is very easy to use this module in order to check if Apache runs on a server (e.g. http://server_name/icons/) and to get the content of the Web server’s directories, when no index files are found in them. The second module, mod_info, should never be accessible from the Internet, mainly because it reveals the Apache server’s configuration.

The next question is how to compile modules. The static method seems to be a better choice. If new vulnerabilities in Apache are found, we will probably recompile not just the vulnerable modules, but the whole software. By choosing the static method, we eliminate the need of one more module – mod_so.

Compiling the software

First of all – if exist – any security patches must be applied. Then, the server should be compiled and installed as follows:

 ./configure --prefix=/usr/local/apache --disable-module=all --server-      uid=apache --server-gid=apache --enable-module=access --enable-      module=log_config --enable-module=dir --enable-module=mime --enable-module=auth make su umask 022 make install chown -R root:sys /usr/local/apache

Chrooting the server

The next step is to limit Apache processes’ access to the filesystems. We can achieve that by chrooting it’s main daemon (httpd). Generally, the chrooting technique means creating a new root directory structure, moving all daemon files to it, and running the proper daemon in that new environment. Thanks to that, the daemon (and all child processes) will have access only to the new directory structure.

We’ll start this process by creating a new root directory structure under the /chroot/httpd directory:

 mkdir -p /chroot/httpd/dev mkdir -p /chroot/httpd/etc mkdir -p /chroot/httpd/var/run mkdir -p /chroot/httpd/usr/lib mkdir -p /chroot/httpd/usr/libexec mkdir -p /chroot/httpd/usr/local/apache/bin mkdir -p /chroot/httpd/usr/local/apache/logs mkdir -p /chroot/httpd/usr/local/apache/conf mkdir -p /chroot/httpd/www

The owner of all above directories must be root, and the access rights should be set to the 0755. Next, we’ll create the special device file: /dev/null:

 ls -al /dev/null   crw-rw-rw-   1  root wheel   2,  2 Mar 14 12:53 /dev/null mknod /chroot/httpd/dev/null c 2 2 chown root:sys /chroot/httpd/dev/null  chmod 666 /chroot/httpd/dev/null

A different method must be used to create a /chroot/httpd/dev/log device, which is also needed for the server to work properly. In case of the FreeBSD system, the following line should be added to the /etc/rc.conf:

 syslogd_flags="-l /chroot/httpd/dev/log"

We must restart the system or the syslogd daemon itself for the changes to take effect. In order to create a /chroot/httpd/dev/log device on other operating systems, we must take a look at the proper manuals (man syslogd).

The next step is to copy the main httpd program into the new directory tree with all necessary binaries and libraries. In order to do that, we must prepare the list of all required files. We can make such list by using the following commands (their presence depends on particular operating system):

Command Availability Descript ion
ldd All Lists dynamiic dependencies of executable files or shared libraries
ktrace/ktruss/kdump *BSD Enables kernal process tracing, Displays kernal trace data
sotruss Solaris Traces shared library procedure calls
strace/ltrace Linux Traces system calls and signals
strings All Finds the printable strings in binary files
trace AIX Records selected system events
trace (freeware) HP-UX <10.20 Print system call and kernal traces of processes
truss FreeBSD, Solaris, AIX 5L, SCO Unixware Traces system calls and signals
tusc (freeware) HP-UX>11 Traces the system calls a process invokes in HP-UX 11

Examples of using ldd, strings and truss commands are shown below:

 localhost# ldd /usr/local/apache/bin/httpd /usr/local/apache/bin/httpd: => /usr/lib/ (0x280bd000) => /usr/lib/ (0x280d6000) localhost# strings /usr/local/apache/bin/httpd | grep lib /usr/libexec/ localhost# truss /usr/local/apache/bin/httpd | grep open (...) open("/var/run/",0,00)            = 3 (0x3) open("/usr/lib/",0,027757775370)    = 3 (0x3) open("/usr/lib/",0,027757775370)        = 3 (0x3) open("/etc/spwd.db",0,00)                        = 3 (0x3) open("/etc/group",0,0666)                        = 3 (0x3) open("/usr/local/apache/conf/httpd.conf",0,0666) = 3 (0x3) (...)

The above commands should be applied not only to the httpd program, but also to all of the libraries and binaries required (libraries often require other libraries). In case of FreeBSD system, the following files have to be copied to the new root directory structure:

 cp /usr/local/apache/bin/httpd /chroot/httpd/usr/local/apache/bin/ cp /var/run/ /chroot/httpd/var/run/ cp /usr/lib/ /chroot/httpd/usr/lib/ cp /usr/lib/ /chroot/httpd/usr/lib/ cp /usr/libexec/ /chroot/httpd/usr/libexec/

By using the truss command we can also discover that the following configuration files must be present in the chrooted environment as well:

 cp /etc/hosts /chroot/httpd/etc/ cp /etc/host.conf /chroot/httpd/etc/ cp /etc/resolv.conf /chroot/httpd/etc/ cp /etc/group /chroot/httpd/etc/ cp /etc/master.passwd /chroot/httpd/etc/passwords cp /usr/local/apache/conf/mime.types /chroot/httpd/usr/local/apache/conf/

Note, that from /chroot/httpd/etc/passwords we have to remove all the lines except “nobody” and “apache”. In a similar way, we must remove all the lines except “apache” and “nogroup” from /chroot/httpd/etc/group. Next, we have to build the password database as follows:

 cd /chroot/httpd/etc pwd_mkdb -d /chroot/httpd/etc passwords rm -rf /chroot/httpd/etc/master.passwd

The next step is to test if the httpd server runs correctly in the new chrooted environment. In order to perform that, we have to copy the default Apache configuration file and sample index.html:

 cp /usr/local/apache/conf/httpd.conf /chroot/httpd/usr/local/apache/co nf/ cp /usr/local/apache/htdocs/index.html.en /chroot/httpd/www/index.html

After copying the aforementioned files, we must change the DocumentRoot directive as presented below (in /chroot/httpd/usr/local/apache/conf/httpd.conf):

 DocumentRoot "/www"

Next, we can try to run the server:

 chroot /chroot/httpd /usr/local/apache/bin/httpd

If any problems occur, I recommend analyzing Apache’s log files precisely (/chroot/httpd/usr/local/apache/logs). Alternatively, the following command can be used:

 truss chroot /chroot/httpd /usr/local/apache/bin/httpd

The truss program should show the cause of the problems. After eliminating any eventual faults, we can configure the Apache server.

Configuring Apache

The first step is to remove the /chroot/httpd/usr/local/apache/conf/httpd.conf file and create a new one in its place, with content similar to the following:

 # ================================================= # Basic settings # ================================================= ServerType standalone ServerRoot "/usr/local/apache" PidFile /usr/local/apache/logs/ ScoreBoardFile /usr/local/apache/logs/httpd.scoreboard ResourceConfig /dev/null AccessConfig /dev/null # ================================================= # Performance settings # ================================================= Timeout 300 KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 15 MinSpareServers 5 MaxSpareServers 10 StartServers 5 MaxClients 150 MaxRequestsPerChild 0 # ================================================= # Apache's modules # ================================================= ClearModuleList AddModule mod_log_config.c AddModule mod_mime.c AddModule mod_dir.c AddModule mod_access.c AddModule mod_auth.c # ================================================= # General settings # ================================================= Port 80 User apache Group apache ServerAdmin Webmaster@www.ebank.lab UseCanonicalName Off ServerSignature Off HostnameLookups Off ServerTokens Prod <IfModule mod_dir.c>     DirectoryIndex index.html </IfModule> DocumentRoot "/www/vhosts" # ================================================= # Access control # ================================================= <Directory />     Options None     AllowOverride None     Order deny,allow     Deny from all </Directory> <Directory "/www/vhosts/www.ebank.lab">     Order allow,deny     Allow from all </Directory> <Directory "/www/vhosts/www.test.lab">     Order allow,deny     Allow from all </Directory> # ================================================= # MIME encoding # ================================================= <IfModule mod_mime.c>     TypesConfig /usr/local/apache/conf/mime.types </IfModule> DefaultType text/plain <IfModule mod_mime.c>     AddEncoding x-compress Z     AddEncoding x-gzip gz tgz     AddType application/x-tar .tgz </IfModule> # ================================================= # Logs # ================================================= LogLevel warn LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %b" common LogFormat "%{Referer}i -> %U" referer LogFormat "%{User-agent}i" agent ErrorLog /usr/local/apache/logs/error_log CustomLog /usr/local/apache/logs/access_log combined # ================================================= # Virtual hosts # ================================================= NameVirtualHost * <VirtualHost *> 	DocumentRoot "/www/vhosts/www.ebank.lab" 	ServerName "www.ebank.lab" 	ServerAlias "www.e-bank.lab" 	ErrorLog logs/www.ebank.lab/error_log 	CustomLog logs/www.ebank.lab/access_log combined </VirtualHost> <VirtualHost *> 	DocumentRoot "/www/vhosts/www.test.lab" 	ServerName "www.test.lab" 	ErrorLog logs/www.test.lab/error_log 	CustomLog logs/www.test.lab/access_log combined </VirtualHost>

The above configuration includes only the commands that are necessary to fulfill the functionality and security assumptions. In the configuration presented, there are two virtual hosts supported by the Web server:

www.ebank.lab (www.e-bank.lab)

The content of the above Web sites is physically present in the following directories:

 - /chroot/httpd/www/vhosts/www.ebank.lab - /chroot/httpd/www/vhosts/www.test.lab

Each Web site has its own log files, which are present in the following directories:

 - /chroot/httpd/usr/local/apache/logs/www.ebank.lab - /chroot/httpd/usr/local/apache/logs/www.test.lab

The above directories must be created before running the Apache for the first time – otherwise the Apache will not run correctly. The owner of the above directories should be root:sys, and the rights should be set to 0755.

Compared with the default Apache configuration file, the following changes have been made:

  • the number of enabled modules has been significantly reduced
  • Apache doesn’t disclose information about its version number (directives: ServerTokens, ServerSignature)
  • Apache’s processes (except the root process) are set to be executed with unique regular user’s/group’s privileges (directives: User, Group)
  • Apache will allow access only to the directories, subdirectories and files, which are explicitly specified in the configuration file (directives: Directory, Allow); all other requests will be denied by default
  • Apache will log more information about HTTP requests

Final steps

At the end we should create a start-up script “”, the content of which will be similar to the following:

 #!/bin/sh CHROOT=/chroot/httpd/ HTTPD=/usr/local/apache/bin/httpd PIDFILE=/usr/local/apache/logs/ echo -n " apache" case "$1" in start) 	/usr/sbin/chroot $CHROOT $HTTPD 	;; stop) 	kill `cat ${CHROOT}/${PIDFILE}` 	;; *) 	echo "" 	echo "Usage: `basename $0` {start|stop}" >&2 	exit 64 	;; esac exit 0

The above script should be copied to the proper directory (depends on particular UNIX system), where by default startup scripts are held. In case of FreeBSD it is the /usr/local/etc/rc.d directory.


The above method allows achieving a higher security level of the Apache server than the one, offered in the default installation.

Thanks to enabling only the absolutely necessary Apache modules, finding a new vulnerability in one of them doesn’t have to indicate that our server is vulnerable. Hiding the Apache’s version number, turning off the directory indexing service, chrooting and restricted configuration make a successful break-in very difficult. A chrooted environment has also one more important advantage – immunity to the large number of exploits, mainly because of lack of the shell (/bin/sh, /bin/csh etc.). Even if an intruder will success in executing system commands, escaping the chrooted environment could turn out to be quite a problem.

Published in: on April 21, 2010 at 9:42 am  Comments Off on Apache Server Securing-Tips  

MySQL 5, PHP4 as CGI, with PHP5 as module on CentOS

Experts Only….(Since Apache and Mysql configuring steps not included)

Download PHp4source :

cd /usr/local/src/
wget http://some.mirror.get/php-4.4.5.tar.gz

tar -zxf php-4.4.5.tar.gz


cd php-4.4.5

./configure –prefix=/usr/local/php4 –enable-force-cgi-redirect –enable-fastcgi –with-config-file-path=/usr/local/etc/php4/cgi –with-curl –with-curl-dir=/usr/local/lib –with-gd –with-gd-dir=/usr/local/lib –with-gettext –with-jpeg-dir=/usr/local/lib –with-kerberos –with-mcrypt –with-mhash –with-mysql=/usr –with-pear –with-png-dir=/usr/local/lib –with-xml –with-zlib –with-zlib-dir=/usr/include –with-zip –enable-bcmath –enable-calendar –enable-ftp –enable-magic-quotes –enable-sockets –enable-track-vars –enable-mbstring –enable-memory-limit

You will most likely get failures that tell you which libraries you need to install, eventually, it will work. I needed to install flex and zzlib. You can always choose to remove an option above from the compile command if you can’t or don’t want to install a dependency.

Once the complie command succeeds, run:



make install

Make the php4 cgi folder and copy the compiled PHP module to the proper location:

mkdir -p /usr/local/etc/php4/cgi
cp /usr/local/src/php-4.4.2/php.ini-dist /usr/local/etc/php4/cgi/php.ini

Make a php4.conf file:

The previous PHP5 installation created a the file /etc/httpd/conf.d/php.conf- duplicate this file and rename it php4.conf, then edit the “DirectoryIndex” “Action” and “AddHandler” lines with the following information:

DirectoryIndex index.php4 index.php3
Action php4-script /cgi-bin/php
AddHandler php4-script .php3 .php4

and comment out the “LoadModule php5…” line

Create link to PHP4 in Client’s cgi-bin Directory
# Due to Security Issues the PHP4 CGI is installed at /usr/local/etc/php4/cgi/php.ini. In the Interworx virtual host setup using suexec, each user has their own cgi-bin. Do the following to link the PHP4 CGI into your hosting client’s cgi-bin directory.

cd /chroot/home/client/public_html/cgi-bin (ie:virtual host document root or the alias path of your site)
ln /usr/local/php4/bin/php php
chown client php
chgrp client php
chmod 755 php

Test your PHP installation
try creating a doc for both versions of PHP:

This  can be your virtualhost document root or the alias path of your site.

using the same code:


The phpinfo() function reports the version number, as well as the features that are compiled into PHP. You’ll see that info.php4 uses php4 and info.php5 uses php5.

.htaccess Instructions:
Instruct your customers to create .htaccess files when they want to force php4 to be used on their site, or in just certain folders:

Customers just need to place that .htaccess file in the ../public_html folder or whatever folder they want php4 to be used instead of the default handler for the server, PHP5, which is stipulated in /etc/httpd/conf.d/php.conf.

Wherever you customer puts this .htaccess file, PHP4 will be used on that folder and any of that folder’s sub-folders.

The .htaccess file should read:

Options + FollowSymlinks
Action php-script /cgi-bin/php
AddHandler php-script .php

Sub-Domain Issues with PHP as a CGI:

Placing an .htaccess file like the one above in a sub-domain folder doesn’t work! Your choice’s are:

1. Place the .htaccess file above in the client’s root site folder (/html/.htaccess) do that PHP4 is used on the entire site
2. Don’t use sub-domains (use as long as the folder isn’t a subdomain placing the .htaccess file above will apply php4 to that folder and it’s sub-folders only.

Option 1 isn’t as bad as it sounds- because php5 is an apache module, you can enable it on any folder (subdoamin or regular subfolder) using the .htaccess code below.You just have to realize that any individual files in the site’s root level (like index.php ) are going to be stuck with PHP4.

Quick summary:
1. Place the .htaccess file above in the client’s /html folder- now their site uses php4 by default
2. Any folders you wish to override with PHP5 must have the following .htaccess file at the sub-domain/sub-folder’s root (/html/subdomain_folder/.htaccess) using this syntax:

Options +FollowSymlinks
AddHandler php5-script .php
AddType text/html .php

Published in: on January 30, 2010 at 2:58 pm  Comments Off on MySQL 5, PHP4 as CGI, with PHP5 as module on CentOS  

Password protect a web directory with .htaccess

Apache references the .htaccess file in web document directories for access control information and other uses. A simple configuration allows password protection with multiple username/password combinations.

In the directory to be protected, create a .htaccess file with contents like this:

AuthType Basic

AuthUserFile /safe/dir/htpasswd

AuthName “Text displayed in popup”

require valid-user

There are many other options for .htaccess, but these are basic password related options to get started. The AuthUserFile refers to a fully qualified file that should not be in the web server document directories. The htpasswd file can be named anything, there can be multiple files storing passwords for .htaccess, and each can be shared for use in multiple directories.

To create the first and second user/password pairs, use:

htpasswd -cb /safe/dir/htpasswd user1 password1

htpasswd -b /safe/dir/htpasswd user2 PaSsWoRd2

Additional user/password pairs can be added using the second form. Be certain to protect the htpasswd file.

Published in: on January 23, 2010 at 2:15 pm  Comments Off on Password protect a web directory with .htaccess  

To find the hacked website (Gumblar/Martuz)..

To find the website is hacked by someone or badware scripts running on the server. You can find here…

This site should be healthy report…. If the report shows badware running..

You need to clean the site on the server & restore the old backup..

Then send review to google web tools &b google will unblock from google blacklist.

Email me for further doubts..


Published in: on January 23, 2010 at 2:09 pm  Comments Off on To find the hacked website (Gumblar/Martuz)..  

Installing Redmine & Redmine Migration Guide


Operating system

Redmine should run on most Unix, Linux, Mac and Windows systems as long as ruby is available on this platform.

Ruby & Ruby on Rails

The required Ruby and Ruby on Rails versions for a given Redmine version is:

Redmine version Supported Ruby versions Required Rails version
current trunk ruby 1.8.6, 1.8.7 Rails 2.2.2
trunk before r2493 ruby 1.8.6, 1.8.7 Rails 2.1.2
0.8.x ruby 1.8.6, 1.8.7 Rails 2.1.2
0.7.x ruby 1.8.6 Rails 2.0.2

Official releases include the appropriate Rails version in their vendor directory. So no particular action is needed.

If you checkout the source from the Redmine repository, you can install a specific Rails version on your machine by running:

gem install rails -v=2.2.2


  • RubyGems 1.3.1 is required
  • Rake 0.8.3 is required


  • MySQL 4.1 or higher (recommended) [One exception- the ruby mysql gem does not currently support mysql 5.1]
    • make sure to install the C bindings for ruby that dramatically improve performance. You can get them by running gem install mysql.
  • PostgreSQL 8
    • make sure your database datestyle is set to ISO (Postgresql default setting). You can set it using: ALTER DATABASE "redmine_db" SET datestyle="ISO,MDY";
  • SQLite 3

Optional components

  • SCM binaries (eg. svn), for repository browsing (must be available in your PATH). See RedmineRepositories for SCM compatibility and requirements.
  • RMagick (to enable Gantt export to png image)


1. Download and extract the archive or checkout Redmine.

2. Create an empty database and accompanying user named redmine for example.

For MySQL:

create database redmine character set utf8;
create user 'redmine'@'localhost' identified by 'my_password';
grant all privileges on redmine.* to 'redmine'@'localhost';

3. Copy config/database.yml.example to config/database.yml and edit this file in order to configure your database settings for “production” environment.

Example for a MySQL database:

  adapter: mysql
  database: redmine
  host: localhost
  username: redmine
  password: my_password

Example for a PostgreSQL database:

  adapter: postgresql
  database: <your_database_name>
  host: <postgres_host>
  username: <postgres_user>
  password: <postgres_user_password>
  encoding: utf8
  schema_search_path: <database_schema> (default - public)

4. Generate a session store secret (r2493 and higher only. 0.8.x users can skip this step) ***

Redmine stores session data in cookies by default, which requires a secret to be generated. This can be done by running:

rake config/initializers/session_store.rb

5. Create the database structure, by running the following command under the application root directory:

rake db:migrate RAILS_ENV="production"

It will create tables and an administrator account.

6. Insert default configuration data in database, by running the following command:

rake redmine:load_default_data RAILS_ENV="production"

This step is optional but highly recommended, as you can define your own configuration from scratch. It will load default roles, trackers, statuses, workflows and enumerations.

7. Setting up permissions

NB: Windows users have to skip this section.

The user who runs Redmine must have write permission on the following subdirectories: fileslogtmp (create the last one if not present).

Assuming you run Redmine with a redmine user:

mkdir tmp public/plugin_assets
sudo chown -R redmine:redmine files log tmp public/plugin_assets
sudo chmod -R 755 files log tmp public/plugin_assets

8. Test the installation by running WEBrick web server:

ruby script/server webrick -e production

Once WEBrick has started, point your browser to http://localhost:3000/. You should now see the application welcome page.

9. Use default administrator account to log in:

  • login: admin
  • password: admin

You can go to Admin & Settings to modify application settings.


Published in: on January 23, 2010 at 1:55 pm  Comments Off on Installing Redmine & Redmine Migration Guide