I have a form for users who want to add new content on my Drupal 8 website. I render node field on a twig template :

{{ node_field_title.value }}

But field are not sanitized by Drupal. Is it the normal behaviour ?

--> If the title is <script>alert('XSS problem!')</script> the script will be executed.

Drupal 8 documentation says : '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.'

  • Do you see the script tag on the screen? Then it is auto escaped and can't be executed. – 4k4 Jun 28 '19 at 16:15
  • In case it is executed then post the entire code what you put into the variable and what else the template contains which might be relevant for autoescaping. – 4k4 Jun 29 '19 at 15:34
  • The value of the field is : <script>alert('XSS problem')</script>. The script is exexcuted and if i click on 'OK' to close the alert windows, i can see the script written on the page. – Romain Jul 1 '19 at 9:11
  • Please add the information as asked to reproduce this behavior. – 4k4 Jul 1 '19 at 9:29
  • Ok, It's because of a breadcrumb block who render my field_title. with a |raw . Not a good idea.. Thank you for your help ! – Romain Jul 1 '19 at 9:35

It seems that there is no autoescaping, at least for Drupal 8.7.3 which the version I tested.
For example:

{{ "<div>Is this escaped?</div>" }}
{{ "<script>alert('NOO!');</script> "}}

These lines are not escaped by default. However:

{{ "<div>Is this escaped?</div>"|escape }}
{{ "<script>alert('NOO!');</script>"|escape}}

These are escaped, so better be safe than sorry and use |escape for the input you're getting from your users.

  • Static expressions are not auto escaped, only variables or objects. – 4k4 Jun 29 '19 at 15:35
  • Thanks for clarifying – Ismail Cherri Jun 29 '19 at 19:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.