jump to navigation

PHPIDS — An Intrusion Detection System Ready To Use March 25, 2012

Posted by Tournas Dimitrios in PHP.

Web applications are regularly threatened by attacks that try to exploit programming weaknesses . The PHP-based , open source PHPIDS solution detects attempted intrusions and raises the alarm when a threat is identified . PHPIDS neither strips , sanitizes nor filters any malicious input , it simply recognizes when an attacker tries to break your site and reacts in exactly the way you want it to . Based on a set of approved and heavily tested filter rules any attack is given a numerical impact rating  ( indicates the severity of the attack)  which makes it easy to decide what kind of action should follow the hacking attempt  . This could range from simple logging to sending out an emergency mail to the development team , logging into a Database-Table ( implements the singleton pattern and is based on PDO extension) , displaying a warning message for the attacker or even ending the user’s session .

Q: Will the PHPIDS protect my application by default?
Nope – the PHPIDS doesn’t touch any input variable by default – it just detects attack patterns and reports them. How your application reacts on those reports depends on your application. There are a lot of possible reactions so the PHPIDS doesn’t limit you in your creativity 🙂

The simplest scenario involves logging attacks to establish whether a site is being targeted and requires further protective measures . Furthermore modules  like the HTML parser htmlpurifier  are only included and used in case there is input coming in with a key matching the ones given in the Config.ini / via $monitor->setHtml() for content with HTML allowed. So the performance hungry components normally won’t be loaded during about 95% of all requests .

Let’s demonstrate a  basic example :

  • First , download and unpack the phpids zip/tarbal archive , it will include a  licence-file  , a docs – tests  and – lib folder . Locate the IDS folder (into lib)  and move it into the directory that contains the web application . You can use the example.php file in the /docs/examples subdirectory for your first trials , as it is easily adapted . Simply remove any unnecessary items and change the paths in the file so that you’re only left with the following
    //Define the path of PHPIDS lib
       . '.'
    if (!session_id()) {
    require_once 'IDS/Init.php';
    try {
    //Define what to scan
       $request = array(
           'REQUEST' => $_REQUEST,
           'GET' => $_GET,
           'POST' => $_POST,
           'COOKIE' => $_COOKIE
    //Initiate the framework and define the path of it's central configuration file
       $init = IDS_Init::init(dirname(__FILE__) .
    The following three configurations are optional as they are defined into the centroal configuration file (see previous step) 
       $init->config['General']['base_path'] = dirname(__FILE__) .
       $init->config['General']['use_base_path'] = true;
       $init->config['Caching']['caching'] = 'none';
    //Initiate "Monitor" , this is the actual work-horse 
       $ids = new IDS_Monitor($request, $init);
       $result = $ids->run();
    //If the returned object isn't empty (attack was detected) , act upon
       if (!$result->isEmpty()) {
    Initiate a Logging Class , alternatively , an Mail or DataBase Class could be initiated 
           require_once 'IDS/Log/File.php';
           require_once 'IDS/Log/Composite.php';
           $compositeLog = new IDS_Log_Composite();
       } else {
    } catch (Exception $e) {
           'An error occured: %s',

    System admins tend to dislike having all lib- files accessible via the web server’s publicly accessible directories, as it potentially gives attackers room to play. PHPIDS can , therefore , also be installed and run outside of a publicly accessible web directory(in your lib-directory ) . For simplicity this article has uploaded PHPIDS’s folder into a publicly available  folder  which is protected by an “.htaccess” file with the following directive : deny from all

  • IDS\Config\config.ini.php contains all the basic configurations separated into three sections (General , Logging and Caching ) . Each configuration is well commented to help us understand it’s functionality . Actually this is the place  where we shall configure PHPIDS behavior , though many of these configurations can be over-ridden  from your script  :
    //$init represents an initiated PHPID  object
    $init->config[‘General’][‘base_path’] = dirname(__FILE__) . ‘/../../lib/IDS/’ ;
    $init->config[‘General’][‘use_base_path’] = true;
    $init->config[‘Caching’][‘caching’] = ‘none’ ; 
A quick review of a script that implements the PHPIDS framework :
  • Defining the include path and importing all Classes that are needed from the framework (require_once )
  • Initiating the framework and passing the path of the central configuration file into it’s constructor function :
    $init = IDS_Init::init(dirname(__FILE__) . ‘/../../lib/IDS/Config/Config.ini.php’);
  • Define new configuration values if we need to over-write configuration options that where defined in the central configuration file (IDS\Config\config.ini.php) .
  • Initiating a PHPIDS object and fetching the results
     $ids = new IDS_Monitor($request, $init);
     $result = $ids->run();
  • That’s it – In normal operation , the $result object will be empty . If an attack was detected , the $result object will embed all information which we can  analyze  and act upon (redirecting the user , logging to file / database or sending an email to the admin team ) .
  • Logging the results into a file can be achieved by initiating a Composite() Class and passing the $result object into its constructor .
    $compositeLog = new IDS_Log_Composite();

Links :



1. Lokal - March 25, 2012

You made some really good points there. I checked on the net to learn more about the issue and found
most people will go along with your views on this web site.

2. drupal - March 31, 2012

Thank you for every other wonderful post. The place else may anybody get that kind of information in such a perfect approach of writing? I’ve a presentation subsequent week, and I am at the search for such information.

3. khaled - July 3, 2012

Thank you

can you tell us how to save log file on database ?


tournasdimitrios1 - July 3, 2012

PHPIDS implements the composite design pattern . Just in case this pattern doesn’t “ring any bells over your head ” , let me help you out by using an over-simplified example . When the “composite pattern” is applied in the context of a given application , an common interface is used (“API” in programming parlance) to talk to one ore more objects . The API exposes a nearly identical behavior , no matter how the final result is implemented .

To log some data in case intrusion is detected :
1) Instantiate the API($compositeLog = new IDS_Log_Composite();
2)Define what logger-mechanism will be used ($compositeLog->addLogger(IDS_Log_Database::getInstance($init));)
3) Execute logging ($compositeLog->execute($result);)
As you see , no matter what logger-mechanism is defined in “step-2”, the implementation is hidden to us . Regardless our final expectations (log to file , log to database-table , send mail to administrator ) , the API exposes an identical behavior .
PHPIDS’s “log” folder has the Database.php , File.php and Email.php files . One of these files can be used as “target objects” into step-2 . We could even create a custom “target-object” , for example , logging into a remote LDAP server by creating a “Ldap.php” file .
The “Database.php” has extensive comments to get you started (you should manually create a database table and define your DB-credentials into Config.ini.php).
Hope this has shed some light , if you need further help , let me know .

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s