Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 37 ยท Users, Roles and Security

Drupal Security Practices

Keep Drupal sites safe: output escaping, database API placeholders, CSRF tokens, text formats, file uploads, trusted hosts, updates, security advisories and secure coding stand-ins.

Drupal has a strong security record and a dedicated security team, but a site is only as safe as its configuration, its modules and the code you write. Most real incidents come from unpatched software, weak permissions and custom code that forgets to escape output or use placeholders. This lesson covers the habits that prevent them.

Drupal cannot run on this site, so the PHP is read-only. The TryIt blocks demonstrate the principles (escaping, parameterized queries, tokens) with JavaScript stand-ins.

Escape output (cross-site scripting)

Cross-site scripting (XSS) happens when user-supplied text reaches the page as markup. Drupal's defences:

  • Twig autoescapes every variable. Do not use |raw on user data (Twig basics).
  • Render arrays: #markup is run through an XSS filter, #plain_text is escaped completely, and translatable strings use placeholders: t('Hello @name', ['@name' => $name]) escapes, %name escapes and emphasises, :url sanitises a URL, @name is the safe default. Never concatenate user input into the first argument of t().
  • Helpers: Html::escape($text), Xss::filter($html), Xss::filterAdmin(), UrlHelper::stripDangerousProtocols().

Bad and good:

PHP
// Bad: user text becomes markup.
$build['#markup'] = '<p>' . $request->query->get('q') . '</p>';

// Good.
$build['#plain_text'] = $request->query->get('q');
// Also good: placeholders.
$build['#markup'] = $this->t('You searched for @q', ['@q' => $request->query->get('q')]);
Node.js Stand-in: escaping versus raw output

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Use the database API with placeholders (SQL injection)

SQL injection happens when user input is joined into a query string. Always use the query builder or named placeholders:

PHP
// Good: query builder.
$result = $connection->select('node_field_data', 'n')
  ->fields('n', ['nid', 'title'])
  ->condition('title', '%' . $connection->escapeLike($text) . '%', 'LIKE')
  ->condition('status', 1)
  ->range(0, 10)
  ->execute();

// Good: placeholders.
$result = $connection->query('SELECT nid FROM {node_field_data} WHERE title = :title', [':title' => $title]);

// Bad: concatenation.
$result = $connection->query("SELECT nid FROM {node_field_data} WHERE title = '$title'");

For entities, use entity queries ($storage->getQuery()->condition(...)), which also check access when you call ->accessCheck(TRUE). Forgetting accessCheck() throws an exception in current Drupal on purpose: you must decide.

Node.js Stand-in: concatenation versus placeholders

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Forms, CSRF and tokens

The Form API adds a form_token and checks it (Form API). For links that change data (delete, flag, toggle), use a route with _csrf_token: 'TRUE' in its requirements, and generate links with Url::fromRoute(), which appends the token. Never change data on a GET request without a token.

Input: text formats and file uploads

  • Text formats decide which HTML a user may enter. Give anonymous and authenticated users "Basic HTML" (restricted tags), and keep "Full HTML" for trusted roles only. Never grant anonymous users a format that allows scripts.
  • File uploads (managed_file): restrict extensions with #upload_validators (FileExtension), set a size limit, and store public files outside the code folder. Drupal renames dangerous files (.php.txt) and blocks PHP execution in sites/default/files with .htaccess/nginx rules; confirm your web server enforces it.
  • Validate with the Form API and entity constraints, not only in JavaScript.

Configuration hardening

  • Use HTTPS everywhere; redirect HTTP, set HSTS at the server.
  • Set $settings['trusted_host_patterns'] in settings.php so only your host names are accepted (prevents host header attacks).
  • Keep settings.php and services.yml unwritable and out of version control when they hold secrets; use environment variables for credentials.
  • Disable error display in production (error_level: hide), and turn off Twig debug.
  • Remove or restrict modules you do not use; uninstall development modules (Devel, Kint, Webprofiler) on production.
  • Set a strong hash_salt and password policy; enable two-factor with a contributed module for editors and admins.
  • Restrict /user/register, /admin access by IP or VPN where possible, and use rate limiting (the flood control in core limits failed logins).
PHP
$settings['trusted_host_patterns'] = [
  '^www\.example\.com$',
  '^example\.com$',
];
$settings['file_private_path'] = '../private';
$config['system.logging']['error_level'] = 'hide';

Updates and advisories

Most successful attacks use known flaws in software that was not updated. Subscribe to Drupal security advisories (drupal.org/security) and run updates as part of normal work:

Terminal
composer outdated "drupal/*"
composer update "drupal/core-*" --with-all-dependencies
composer require drupal/some_module:^2.0
drush updatedb --yes
drush cache:rebuild
drush pm:security          # lists known advisories for your installed projects

The Update Manager module (status report) also shows available security updates. Keep Composer's lock file in version control, and test updates on a staging copy first (deployment).

Securing custom code

  • Never trust request data: $request->query->get(), $request->request->all() and headers are user input.
  • Check access in every route; avoid _access: 'TRUE' except for truly public pages.
  • Do not log secrets; \Drupal::logger() messages are visible to admins.
  • Do not store passwords yourself: use user accounts and the password service if you must hash a value.
  • Do not run eval, unserialize on user data or shell_exec with input.
  • Use the Drupal coding standards and the PHPStan Drupal extension to catch mistakes early.

Reporting and backups

Test restores, not only backups: nightly database dumps (drush sql:dump --gzip) and file backups kept off the server. Review Reports > Status report and Recent log messages regularly. If you find a vulnerability in core or a project, report it privately to the Drupal security team.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which is safe for printing user text in a render array?

    #plain_text escapes everything; #markup with concatenated input can create XSS.
  2. 2. How should values be added to a database query?

    Placeholders keep data separate from SQL and prevent injection.
  3. 3. What is the best protection against known vulnerabilities?

    Most attacks target known, patched issues.
  4. 4. What does trusted_host_patterns do?

    It prevents host header attacks by rejecting unexpected host names.

Summary

  • Escape output: autoescape in Twig, #plain_text, placeholders in t().
  • Use the database API, never concatenated SQL.
  • Rely on form and route CSRF tokens; restrict text formats and file uploads.
  • Harden settings.php: trusted hosts, hidden errors, secrets outside Git.
  • Update regularly, remove unused modules and test backups.

Next: Access Control and Entity Access