October 14, 2011

How to prevent SQL Injection attack in applications programmed in Zend Framework?

Question by Kamil Mroczek

I don’t have any concept about ZF safety. Do I have to use Filter when operating on database? Maybe binding is enough ? How about this:

$users->update($data, 'id=1');

Should $data array be filtered somehow ? Feel free to write anything you know about the issue.

Could you give some links to good articles about safety in ZF (mainly about SQL Injection and XSS)?

Answer by Gordon

Short answer
While ZF takes and provides some measures to secure your app, you should still apply the same precautions that you’d use without Zend Framework.


Regarding your code snippet, check out the Chapter on Zend_Db in the Reference Guide:

By default, the values in your data array are inserted using parameters. This reduces risk of some types of security issues. You don’t need to apply escaping or quoting to values in the data array.

This doesn’t mean you don’t have to bother about security. For instance, for the Update method above

The third argument is a string containing an SQL expression that is used as criteria for the rows to change. The values and identifiers in this argument are not quoted or escaped. You are responsible for ensuring that any dynamic content is interpolated into this string safely. See Quoting Values and Identifiers for methods to help you do this.

Note since you are using Zend_Db_Table obviously, third argument is second argument. Internally, the table instance will delegate the call to the db adapter with the first param being the table instance’s tablename.


Regarding Zend_View and XSS attack vectors:

Zend_View comes with an initial set of helper classes, most of which relate to form element generation and perform the appropriate output escaping automatically.

Again most of which does not mean all. Zend_View does provide Zend_View::escape() to help you sanitize output, but this nothing special.

Answer by Starx

I will suggest the Use of Zend Filters, wherever you need something specific. You can use this at anypoint in your application.

Request Parameter

$alpha = new Zend_Filter_Alpha();
$name = $alpha -> filter($this -> _request -> getParam('name')); //while processing url parameters

Database

$int = new Zend_Filter_Int();
$select -> where("id = ?", $int -> filter($id)); //during db processing also

Also in Form Elements . I will skip this as example of this can be found abudantly.

...

Please fill the form - I will response as fast as I can!