18.10.2016 Views

Drupal 7 Module Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Security<br />

For output to the browser, check_markup() may be configured to escape HTML or<br />

other content. The check_plain() function takes a somewhat more sledge-hammer<br />

approach, escaping all HTML in a string so that it displays verbatim on the page for<br />

the user to see.<br />

SQL injection<br />

For writing to the database, <strong>Drupal</strong>'s database layer is built on the concept of<br />

prepared statements. Prepared statements, among other things, cleanly separate<br />

the SQL query from the variable data in it. That allows the database server itself to<br />

sanely construct a query while escaping input itself, avoiding the common attack<br />

known as "SQL injection". For example, a value that contains an apostrophe causes a<br />

syntax error in an SQL statement (since single quotes have meaning in SQL) at best,<br />

or allows an arbitrary extra SQL query to sneak into the command at worst.<br />

To avoid that problem, never, ever put a variable into an SQL string directly. When<br />

writing a query against <strong>Drupal</strong>'s database, always ensure that the query portion is a<br />

single string literal using placeholders and then provide values for the placeholders.<br />

Doing so will allow the database to separate the query template from the variable<br />

content and avoid SQL injection. If the query itself is variable, use the dynamic query<br />

builder, db_select().<br />

SQL injection from badly written queries is the most common, and<br />

the most easily avoidable, form of security vulnerability.<br />

Node access control<br />

A particularly <strong>Drupal</strong>-specific security question is how to control access to nodes.<br />

While <strong>Drupal</strong>'s permission system handles the common use case of globally-readable<br />

nodes and limited access to edit or delete nodes, there are plenty of cases where we<br />

need more complex access control. <strong>Drupal</strong>'s node access system handles those cases,<br />

but it requires that we tie into it every time we look up nodes, that is, any time we<br />

run a query that tries to find records in the node table.<br />

Since there are so many varied situations where nodes could be used, such additional<br />

access checks can only be done at the database level, that is, in the query itself.<br />

Fortunately, <strong>Drupal</strong> allows modules to manipulate certain types of queries before<br />

they are executed to add any sort of filtering. In order to allow <strong>Drupal</strong> to modify<br />

our queries, we need to "tag" them appropriately.<br />

[ 378 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!