Affected versions
Twig versions <3.31.1 are affected by this security issue.
The issue has been fixed in Twig 3.31.1.
Description
The sandbox allows every method of Twig\Markup objects, including their public constructor. A sandboxed template can therefore call __construct() on any Markup object that it reaches, and replace its content:
1
{% do banner.__construct('<script>alert(1)</script>', 'UTF-8') %}
A template gains nothing by rewriting its own output. The impact is on the Markup objects that come from the application and are also rendered elsewhere, like a global in a long-running worker. Their new content then ends up in trusted pages that aren't sandboxed.
Resolution
The sandbox no longer allows calling the constructor of Markup objects.
The patch for this issue is available here for branch 3.x.
Credits
We would like to thank Fabien Potencier for reporting the issue and providing the fix.