Wednesday, March 24, 2010

PHPIDS in CodeIgniter by using Hook

I have been busy for a while, especially with programming stuffs and some personal things. Recently I look into the XSS filtering in CodeIgniter. There is a quick configuration to protect your application from all XSS attack. It is powerful but you will certainly need to put in some extra logic to suit your own needs, for example if you have rich text input or textarea in your web application that only allows certain characters.

I found out there is a PHP script which can be used to block malicious inputs (both XSS and SQL Injection typical strings) effectively - PHPIDS. I was thinking to integrate it into my CI web application later on. Download the file from the site and extract all the files into a directory in the root directory of your CI web application'directory.

NOTE: Make sure you add the redirect rule to phpids in your .htaccess file which can be found in CI's directory.

The question is -> do I still need to add codes to validate the inputs on each and every of my web forms? In this case, using the Hooks in CI will save up your development time. So I set up a post_controller_constructor hook in my CI web application.

First I create a file called PHPIDSHook.php in System->Application->Hooks directory.


PHPIDSHook.php - Source Code


require_once (dirname(__FILE__) . '/../../../phpids/lib/IDS/Init.php');

class PHPIDSHook
{
function run()
{
$request = array($_GET, => $_GET, 'POST' => $_POST);

$init = IDS_Init::init(dirname(__FILE__) . '/../../../phpids/lib/IDS/Config/Config.ini.php');

$init->config['General']['base_path'] = '/phpids/lib/IDS/';
$init->config['General']['filter_type'] = 'xml';
$init->config['Caching']['caching'] = 'none';

// Initiate the PHPIDS and fetch the results
$ids = new IDS_Monitor($request, $init);
$result = $ids->run();

if (!$result->isEmpty())
{
require_once (dirname(__FILE__) . '/../../../phpids/lib/IDS/Log/File.php');
require_once (dirname(__FILE__) . '/../../../phpids/lib/IDS/Log/Composite.php');

$compositeLog = new IDS_Log_Composite();
$compositeLog->addLogger(IDS_Log_File::getInstance($init));
$compositeLog->execute($result);

echo "WARNING: XSS/SQL Injection attack is detected!";
exit();
}
}

}
?>


Next you will need to set your hook setting by modifying hooks.php which is located in System->Config->Hooks. Add these line of codes into that file:

$hook['post_controller_constructor'] = array(
'class' => 'PHPIDSHook',
'function' => 'run',
'filename' => 'PHPIDSHook.php',
'filepath' => 'hooks',
);

Finally, go to System->Config->Config.php to set
$config['enable_hooks'] = TRUE;

You have done it. To verify your CI's hooking is working, put any XSS or SQL injection string in any input field of your web form. You should get a alert box by now.

Cheers!
Signing off...


1 comment: