Drupal Security - User Input - Part I
This will be a multipart series on Drupal security.
The first rule of security on a Drupal site, or any site for that matter, is: "never trust user input." User input can be used to gain access to your database (SQL injection), steal other user's session cookies and impersonate them (Cross-Site Scripting or XSS), inject unwanted spam into your pages, or to execute code (gasp shudder) on your server.
Drupal's approach to user input is to store it in its original form, then filter it when it is retrieved to be displayed. So how do we filter it? By using the check_plain(), check_xss(), check_markup(), check_url(), drupal_urlencode(), and mime_header_encode() functions. Also, by using the t() function with place-holder variables. It's a good idea to use the t() function whenever possible, for the purpose of language translation, but that's another story. In part I of this series we're going to talk about check_plain(). Here is an example of why and how to use this function:
Use check_plain() when, you guessed it, you expect nothing but plain text in the user input. This is the most strict of the Drupal security filter functions. There shouldn't be any HTML markup, rich text (e.g. wiki markup), or scripting in the user's input. Let's say you want to display a list of most recently registered user names in a block on your Drupal site. The code might look like:
$cuttoff = time() - 3600 * 24; // last 24 hours
$result = db_query("SELECT name FROM {users} WHERE created > $cuttoff");
while ($data = db_fetch_object($result)) {
$list[] = check_plain($data->name);
}Here the user input is their user name. Don't trust it! We fetch a list of user names who've registered for new accounts in the last 24 hours. Each one is passed through the check_plain() function before being added to the $list array. Now the array can be used to populate the block with a clear conscience.
Next post we'll talk about check_xss(). A bit of trivia to think about until then: according to Symantec, as of 2007, cross-site scripting, or XSS, carried out on websites were roughly 80% of all documented security vulnerabilities.


Post new comment