views:

566

answers:

3

I read from the cookbook (sec. 4.2)

CakePHP already protects you 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. For sanitization against XSS its generally better to save raw HTML in database without modification and sanitize at the time of output/display.

So are we sure that we NEVER need to manually sanitize user data against SQL, provided we restrict to methods such as find() and save()? Especially, is this true if I take my data from $_POST directly instead than from $this->data? In other words suppose I do a find() query using $this->data. Then CakePHP sanitize against SQL when writing the array $this->data or when writing the query for find()?

My second question is for sanitizing data to be displayed. Is Sanitize::html idempotent? So, can I use it in my beforeSave() method, or will it break the second time I save beacuse it is applied again and gives a new result?

A: 

Woah - If your taking your data directly from $_POST than you should absolutely sanitize the data if you are planning on publishing the data on any pages to come. I remember about 2 years ago a large scare because it was revealed that simple SQL injection would allow cake 1.1 sites to be exploited due to the layout of select queries used to login.

However many users intentionally used the old rule for input fields that would be used in SQL:

"To protect against SQL injection, user input must not directly be embedded in SQL statements. Instead, user input must be escaped....."

SO, yes, that was a seperate issue, but same idea -- although CakePHP is boss, and does alot for us, we should never trust its security blindy. The performance impact of scrubbing data yourself is nearly nil. So just do it.

Eddie
Ok, I am doing it, but just to understand. Suppose I do a find() query using $this->data. Then CakePHP sanitize against SQL when writing the array $this->data or when writing the query for $this->find()? In the second case sanitizing still seems superflous even if I use $_POST
Andrea
By the way, I am sanitizing data which will be displayed. I am asking for data to be used in SQL queries.
Andrea
A: 

No it wont affect you. You can use it in before_save(). You will need sanitisation if you use any custom query function i.e functions where you can use your own query

Web Developer
+1  A: 

About this question:

CakePHP sanitize against SQL when writing the array $this->data or when writing the query for find()?

Cakephp does not sanitize $this->data in the controller, if you check the cake code, in Dispatcher::parseParams() http://api13.cakephp.org/view_source/dispatcher/#line-244 you will see that when $_POST is copied to controller data the values are not sanitized.

However, using $_POST is not recommended because you will loose all the cake's magic that you gain when using the form helper

Mauro Zadunaisky