64 lines
2.0 KiB
Plaintext
64 lines
2.0 KiB
Plaintext
![]() |
=== How to fix it in Symfony
|
||
|
|
||
|
The following code is vulnerable to cross-site scripting because it returns an HTML response that contains user input.
|
||
|
|
||
|
If you do not intend to send HTML code to clients, the vulnerability can be fixed by specifying the type of data returned in the response.
|
||
|
For example, you can use the class `JsonResponse` to return JSON messages safely.
|
||
|
|
||
|
[cols="a,a"]
|
||
|
|===
|
||
|
|
|
||
|
[source,php]
|
||
|
----
|
||
|
use Symfony\Component\HttpFoundation\Response;
|
||
|
|
||
|
$response = new Response();
|
||
|
$response->setContent(json_encode(['data' => $input])); // Noncompliant
|
||
|
----
|
||
|
|
|
||
|
[source,php]
|
||
|
----
|
||
|
use Symfony\Component\HttpFoundation\JsonResponse;
|
||
|
|
||
|
$response = new JsonResponse(['data' => $input]);
|
||
|
----
|
||
|
|===
|
||
|
|
||
|
It is also possible to set the content-type manually using the `headers` attribute.
|
||
|
|
||
|
[cols="a,a"]
|
||
|
|===
|
||
|
|
|
||
|
[source,php]
|
||
|
----
|
||
|
use Symfony\Component\HttpFoundation\Response;
|
||
|
|
||
|
$response = new Response();
|
||
|
$response->setContent($input); // Noncompliant
|
||
|
----
|
||
|
|
|
||
|
[source,php]
|
||
|
----
|
||
|
use Symfony\Component\HttpFoundation\Response;
|
||
|
|
||
|
$response = new Response();
|
||
|
$response->headers->set('Content-Type', 'text/plain');
|
||
|
$response->setContent($input);
|
||
|
----
|
||
|
|===
|
||
|
|
||
|
=== How does this work?
|
||
|
|
||
|
If the HTTP response is HTML code, it is highly recommended to use a template engine like https://twig.symfony.com/[Twig] to generate it.
|
||
|
This template engine separates the view from the business logic and automatically encodes the output of variables, drastically reducing the risk of cross-site scripting vulnerabilities.
|
||
|
|
||
|
If you do not intend to send HTML code to clients, the vulnerability can be fixed by specifying the type of data returned in the response with the `content-type` HTTP header.
|
||
|
This header tells the browser that the response does not contain HTML code and should not be parsed and interpreted as HTML.
|
||
|
Thus, the response is not vulnerable to reflected cross-site scripting.
|
||
|
|
||
|
For example, setting the content-type to `text/plain` allows to safely reflect user input since browsers will not try to parse and execute the response.
|
||
|
|
||
|
=== Pitfalls
|
||
|
|
||
|
include::../../common/pitfalls/content-types.adoc[]
|