Prevent Your CakePHP App From XSS Attacks

By default Cakephp will protect app against SQL Injection if you use CakePHP’s ORM methods (such as find() and save()) and proper array notation (ie. array(‘field’ => $value)) instead of raw SQL. But this does not potect you from XSS attacks.
Prevent Your CakePHP App From XSS Attacks
To Understand XSS attack, i will show a simple example. Create a php code where it will show user posted data. Like this

<?php
if(isset($_POST['msg']) and $_POST['msg']!='')
{
	echo $_POST['msg'];
}
?>
<form action="" method="post">
<input type="text" name="msg" />
<input type="submit" value="submit" />
</form>

Now when adding a comment put the following code

<script type='text/javascript'>top.location.href="google.com"</script>

Now it will go to google.com.

luckily CakePHP has something that is pretty strong for these type of attacks. The hero is App::import(‘Sanitize’). You can sanitize not only a string but a array with clean function. As book said “This function is an industrial-strength, multi-purpose cleaner, meant to be used on entire arrays (like $this->data, for example). The function takes an array (or string) and returns the clean version.” . So import it in app_controller.php. then try it in you code.

$this->data = Sanitize::clean($this->data, array('dollar' => true, 
'carriage'=>true,'encode' => true, 'remove_html'=>true));

There is one draw back using the shown code here you have to use html_entity_decode.

<?php echo html_entity_decode($text['Test']['title'])?>

About Zakir Hyder

This entry was written by .

11. August 2011 by Zakir Hyder
Categories: CakePHP, Web Development | Tags: , , , , , , | Comments

Comments

  1. […] Prevent Your CakePHP App From XSS Attacks By default Cakephp will protect app against SQL Injection if you use CakePHP’s ORM methods (such as find() and save()) and proper array notation (ie. array(‘field’ => $value)) instead of raw SQL. But this does not potect you from XSS attacks. To Understand XSS attack, i will show a simple example. Create a php code […] […]