Writing secure code

Writing secure code in Drupal 7.

Overview

Whether you are writing a PHP snippet or an entire module, it is important to keep your code secure.

Avoid using data from $form_state['input']

In the Form API, using data from $form_state['input'], $_POST, and/or \Drupal::request()->request (Drupal 8) are a security risk.

Create forms in a safe way to avoid cross-site request forgeries (CSRF)

Cross-site request forgery (CSRF or XSRF) is a process where a request is made to a site which takes an action when the user did not intend

Database access

Drupal provides several functions to send queries to the database. The canonical form is db_query. Always use functions provided by Drupal

Do not use /e in preg_replace() - use preg_replace_callback() instead

Security advisories such as SA-CONTRIB-2010-027 and SA-CONTRIB-2010-030 have pointed out the risk of passing user input through regular

File uploads, downloads and management

[This section is a work in progress]

Directories

For starters, always make sure that actions on uploaded files (upload, view, download, delete) are taking place in the 'files' directory or

Handle text in a secure fashion

When handling and outputting text in HTML, you need to be careful that proper filtering or escaping is done. Otherwise, there might be bugs

Handling Private/Personally Identifiable Information

When working with certain kinds of sensitive data, it is important to carefully evaluate Drupal's handling of that information and determine

Session IDs

Session support in PHP allows one to preserve data across subsequent accesses. A visitor accessing your website is assigned a unique ID,

Use of hash functions

For Drupal 7 and later core and contributed modules, the md5() and sha1() hash functions should never be used in any code, since they are

Using PHP with eval() or drupal_eval()

Using eval() or drupal_eval() in your module's code could have a security risk if the PHP input provided to the function contains malicious

When to use db_rewrite_sql or ->addTag()

db_rewrite_sql() in Drupal 6 and db_select() tagged with (for example) 'node_access' in Drupal 7 provide a method for modules to extend your

Safely Impersonating Another User

Impersonating Possibilities

Guide maintainers