Drupal 8 security features: user-submitted data sanitization

This is the fourth part of the blog series about the Drupal 8 security features. We already covered Drupal community’s general approach to security, Cross site scripting, SQL injection and Cross site forgery request. I strongly recommend you to read the first, second and third part if you didn’t do that yet.

Sanitization of the user-submitted data in forms

Values that forms submit to the server are not strictly typed or limited in any way. This allows potential attackers to submit values that were not part of the form originally or to change their value or even data type (array instead of a string, ...).

This can potentially be dangerous if the code that processes the submitted values doesn’t check that.

Drupal protects us from that by relying on the Form API to automatically handle sanitization of the data submitted through the forms. It will validate it, remove any unknown fields that might have been added, ...

Drupal’s guidelines strongly recommend to never use raw $_POST or $_GET data. Data sanitized by the Form API should be used instead.

Example

Someone tries to submit a field that is not part of the original form:

Submitted value can be seen in the $_POST superglobal:

But it was removed from the sanitized data (values in the form state accessible via $form_state->getValues()):

It is also worth mentioning that the exact copy of the $_POST/$_GET superglobals gets saved in the form state too (accessible via FormStateInterface::getUserInput()). This values are intended for internal use only. They should never be used in the custom code. If you need to use it then you’re doing something wrong.

Drupal 8: 3, Hackers: 0. Wait… it is probably 5 vs. 0 at this point. Whatever, you get the message, right? :)

Conclusion

We’ve come to the last part of our series about the Drupal 8 security features. We’ve shown how Drupal 8 protects us from some of the most common vulnerabilities on the web. Some of the protecting elements will work automatically and some others will rely on developer’s knowledge and consideration. And this leads to the main message of this post. You should never stop learning and exploring new things. If you do that you risk exposing yourself and your clients to various dangers. And this is not only sloppy but also irresponsible towards people that rely on your skills to sleep peacefully at night.

Did you like it? Follow us on Twitter to get more content as soon as we release it!

Do you need security review of your Drupal site or module? Get in touch!