Twig is a popular, fast, and flexible template engine for PHP, used by various content management systems like Drupal, eZ Publish, and phpBB. A vulnerability has been identified in some versions of Twig, where output escaping is missing for the expression on the left side of the Null Coalescing (??) Operator. This post aims to discuss the details of this vulnerability (CVE-2025-24374), its effects, and ways to fix the issue. The vulnerability is fixed in Twig version 3.19..

Vulnerability Details (CVE-2025-24374)

The output of a Twig template is generally considered safe and does not require additional escaping. However, in certain circumstances, this assumption does not hold, allowing potential security risks like Cross-Site Scripting (XSS). The Null Coalescing Operator (??) in Twig helps avoid some undefined variable errors when rendering templates by providing a default value when a variable is not set. The vulnerability lies in the improper escaping of the left side of the operator.

Template

{{ var1 ?? var2 }}

Context

[
    'var1' => '<script>alert(1)</script>',
    'var2' => 'some safe text'
]

Expected Output (Safe)

&lt;script&gt;alert(1)&lt;/script&gt; // (Escaped representation of <script>alert(1)</script>)

Actual Output (Unsafe)

<script>alert(1)</script>

As demonstrated, the output includes unescaped content that can lead to potential security risks like XSS when rendered in a browser. It's important to note that the vulnerability only exists when the Null Coalescing Operator is used (??). Other operators and features of the Twig template engine follow proper output escaping.

Affected Versions & Patch

Any application using Twig version before 3.19. may be affected by this vulnerability. It is highly recommended to update to Twig version 3.19. or later, which contains the appropriate fix for the vulnerability. The links to the official Twig release and the corresponding changelog are provided below:

- Official Twig release: https://github.com/twigphp/Twig/releases/tag/v3.19.
- Changelog: https://github.com/twigphp/Twig/blob/3.x/CHANGELOG

Mitigation

To fix the vulnerability, simply update the Twig library to version 3.19. or later. Alternatively, avoid using the Null Coalescing Operator (??) and ensure the proper escaping of all variables before using them in templates.

Conclusion

In summary, the CVE-2025-24374 vulnerability exists in the Twig template engine when using the Null Coalescing Operator (??), leading to potential security risks. To mitigate this issue, it is recommended to update Twig to version 3.19. or later and always follow best practices for safe output handling. By staying up to date with the latest security patches and releases, developers can protect their applications and users from potential attacks.

Timeline

Published on: 01/29/2025 16:15:44 UTC