Drupal - Prevent Cross-site scripting

Sanitizing on output to avoid Cross Site Scripting (XSS) attacks

Use Twig templates The Twig theme engine now auto escapes everything by default. That means that every string printed from a Twig template (e.g. anything between {{ }}) gets automatically sanitized if no filters are used.

See Filters - Modifying Variables In Twig Templates for the Twig filters available in Drupal.

In order to take advantage of Twig’s automatic escaping (and avoid safe markup being escaped) ideally all HTML should be outputted from Twig templates.

API functions Use t() and \Drupal::translation()->formatPlural() with @ or % placeholders to construct safe, translatable strings. See Code text translation API in Drupal 8 for more details.

  • Use Html::escape() for plain text.
  • Use Xss::filter() for text that should allow some HTML tags.
  • Use Xss::filterAdmin() for text entered by a admin users that should allow most HTML.

Strings sanitized by t(), Html::escape(), Xss::filter() or Xss::filterAdmin() are automatically marked safe, as are markup strings created from render arrays via Renderer.

While it can also sanitize text, it's almost never correct to use check_markup in a theme or module except in the context of something like a text area with an associated text format.

Source: Drupal 8: Writing secure code by: Rade, Shyamala, Robert Castelo, and Pere Orga.

Tags:

Security

8