写安全的drupal代码

now about a security issue? Please alert the security team.

Whether you're writing a PHP snippet or an entire module, it's important to keep your code secure.

Here's how you prevent three major security risks:

  1. Cross site scripting attacks by properly checking output
  2. SQL injection attacks by using the database abstraction layer
  3. Node access restrictions bypass by using db_rewrite_sql

To prevent Cross site scripting (XSS) attacks, read the How to handle text in a secure fashion page. To sum up that page: If something that you output is not surrounded by one of the various check_* functions, it is very likely that it's insecure.

Second, you need to utilize the database layer correctly. Never, ever write user data into your SQL. You need to read db_query docs on the syntax. Common and very insecure practice is to simply end your query with something like

db_query('SELECT foo FROM {table} t WHERE t.name = '. $_GET['user']);

Instead, you must use
db_query("SELECT foo FROM {table} t WHERE t.name = '%s' ", $_GET['user']);

A non-trivial example is when you want to list all nids that are in an array $content_types:

<?php
$args = $content_types;
$placeholders = array_fill(0, count($args), "'%s'");
pager_query(db_rewrite_sql('SELECT n.nid, n.title FROM {node} n INNER JOIN {term_node} tn ON n.nid = tn.nid WHERE n.type in ('. implode(',', $placeholders) .') AND n.status = 1 ORDER BY n.created DESC'), 10, 0, NULL, $args);
?>

We are using array_fill to create an appropriate number of placeholders and then we utilize the possibility to pass the arguments in one array. As there is a variable in the SQL query, we should be very cautious. But as we just created this variable, it's OK.

Another very important point to note: we are dealing with nodes and the node access mechanism kicks in via db_rewrite_sql so we are utilizing it. It's really easy and yet it's so often neglected! See When to use db_rewrite_sql for further details.

So, once more; There are three kind of errors you need to avoid: XSS with proper checking, SQL injections with proper db_query usage and node access bypass by utilizing db_rewrite_sql.


同步内容