CVE-2024-51754
Executive Summary
CVE-2024-51754 is a low-severity (CVSS 2.2) security bypass vulnerability in the Twig template language for PHP. The flaw allows an attacker operating within a sandboxed environment to call the __toString() method on an object, even when that method is explicitly disallowed by the security policy. This bypass is possible when the object is part of an array or an argument list (e.g., arguments to a function or filter). The vulnerability has been patched in Twig versions 3.11.2 and 3.14.1. There are no known workarounds, and the EPSS score is 0.0%, indicating very low exploitation activity in the wild.
This record — and 170,000+ others — are available via the ValtersIT API. One endpoint replaces five: NVD + GitHub CVE + CISA KEV + EPSS + Nuclei + Exploit-DB, unified.
No signup required
Supply Chain & Package Security
Twig is a widely used PHP template engine, often distributed via Composer. This vulnerability affects the core sandboxing mechanism, which is a critical security feature for multi-tenant or user-submitted template environments. Organizations using Twig in such contexts should treat this as a supply chain risk, as a compromised template or user input could bypass intended restrictions. The package maintainers have released patches, and immediate upgrade is recommended.
CVSS Breakdown & Threat Level
- CVSS Score: 2.2 (Low)
- Vector: CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:U/C:L/I:N/A:N
- Attack Vector (AV): Network – the attack can be launched remotely.
- Attack Complexity (AC): High – the attacker must have sandbox access and craft a specific payload.
- Privileges Required (PR): Low – the attacker needs a low-privileged account or ability to submit templates.
- User Interaction (UI): None – no user action required beyond the attacker’s own actions.
- Scope (S): Unchanged – the vulnerable component and the security policy are in the same security authority.
- Confidentiality (C): Low – limited information disclosure via
__toString()output. - Integrity (I): None – no data modification.
- Availability (A): None – no denial of service.
Threat Level: Low. The high attack complexity and low impact make this a low-priority vulnerability for most environments, but it should still be patched in sandboxed template contexts.
Deep Dive & Mechanics
The Twig sandbox is designed to restrict which methods and properties can be accessed on objects within templates. The security policy defines a list of allowed methods. The __toString() method is often excluded to prevent unintended information disclosure or code execution.
The vulnerability lies in how the sandbox handles method calls on objects that are part of arrays or argument lists. When an object is passed as an argument to a function or filter, or when it is an element of an array, the sandbox fails to properly check the __toString() method against the security policy. This allows an attacker to trigger __toString() on an object that would otherwise be blocked.
Technical Root Cause: The sandbox’s method call interception logic does not recursively validate method calls on objects that are not the direct subject of a method call in the template. For example, in {{ array|join }}, if array contains objects, the join filter may internally call __toString() on those objects without the sandbox checking the policy for that method.
Attack Scenario: An attacker with the ability to submit or modify Twig templates (e.g., in a CMS or SaaS platform) can craft a template that passes a restricted object as an argument to a filter like join or merge. The filter will then invoke __toString() on the object, bypassing the sandbox policy.
Vulnerable vs. Patched Code
Vulnerable Code (Twig < 3.11.2, < 3.14.1):
The sandbox’s checkAllowedMethod() function does not inspect method calls that occur indirectly through filters or array operations.
// Simplified vulnerable logic
public function checkAllowedMethod($obj, $method) {
// Only checks direct method calls in templates
if ($this->isMethodAllowed($method)) {
return;
}
throw new SecurityError("Method $method is not allowed.");
}
Patched Code (Twig >= 3.11.2, >= 3.14.1):
The patched version adds a recursive check for __toString() calls on objects that are part of arrays or argument lists.
// Simplified patched logic
public function checkAllowedMethod($obj, $method) {
if ($method === '__toString') {
// Always check __toString even for indirect calls
if (!$this->isMethodAllowed('__toString')) {
throw new SecurityError("Method __toString is not allowed.");
}
}
// Existing checks for other methods
}
The patch ensures that __toString() is always validated against the security policy, regardless of how the object is used in the template.
Exploitation & Lab Setup
Red Team (Exploitation)
Prerequisites:
- Access to a Twig template rendering environment with sandbox enabled.
- Ability to submit or modify templates.
- An object class that has a
__toString()method that is not allowed by the sandbox policy.
Exploitation Steps:
Identify a restricted object: Find a class in the application that has a
__toString()method that is not in the sandbox’s allowed methods list. For example, aUserobject that returns sensitive data in__toString().Craft the payload: Create a Twig template that passes the object as an argument to a filter that triggers
__toString(). Thejoinfilter is a common choice.{{ [restrictedObject]|join(',') }}Render the template: Submit the template to the vulnerable application. The
joinfilter will call__toString()on the object, bypassing the sandbox.Extract information: The output of
__toString()will be included in the rendered template, potentially leaking sensitive data.
Example Payload:
{% set user = get_user_object() %}
{{ [user]|join }}
If get_user_object() returns a User object whose __toString() returns the user’s email or password hash, that data will be displayed.
Blue Team (Detection & Defense)
Detection:
- Monitor for unusual Twig template submissions that use filters like
join,merge, orsorton arrays containing objects. - Look for templates that attempt to call
__toString()indirectly. - Use the YARA and Sigma rules provided in the Detection Engineering section.
Defense:
- Immediate: Upgrade to Twig 3.11.2 or 3.14.1.
- Mitigation (if patching is delayed): Disable the
joinfilter and other filters that might trigger__toString()on objects. This can be done by removing them from the sandbox’s allowed filters list. - Long-term: Implement strict input validation on template submissions. Use a Web Application Firewall (WAF) to block suspicious template patterns.
Indicators of Compromise (IOCs)
- Network: HTTP requests containing Twig templates with
join,merge, orsortfilters applied to arrays of objects. - Logs: Twig sandbox exceptions or security errors related to
__toString()method calls. - File System: Modified Twig template files that include payloads like
{{ [object]|join }}. - Memory: Objects with
__toString()methods being invoked outside of allowed contexts.
Detection Engineering
YARA Rule
rule CVE_2024_51754_Twig_Sandbox_Bypass {
meta:
description = "Detects Twig templates attempting to bypass sandbox via __toString()"
author = "Valters IT"
date = "2025-04-10"
reference = "CVE-2024-51754"
severity = "low"
strings:
$twig_filter = /\[.*\]\|(join|merge|sort|filter|reduce|column)/
$toString = "__toString"
condition:
$twig_filter and $toString
}
Sigma Rule
title: Twig Sandbox Bypass via __toString
id: 7a8b9c0d-1e2f-3a4b-5c6d-7e8f9a0b1c2d
status: experimental
description: Detects Twig templates that attempt to bypass sandbox by calling __toString on objects in arrays
author: Valters IT
date: 2025-04-10
references:
- https://nvd.nist.gov/vuln/detail/CVE-2024-51754
logsource:
category: webserver
product: php
detection:
selection:
http.request.body|contains:
- "|join"
- "|merge"
- "|sort"
condition: selection
falsepositives:
- Legitimate use of join filter on arrays of strings
level: low
Suricata Rule
alert http any any -> any any (msg:"CVE-2024-51754 Twig Sandbox Bypass Attempt"; flow:to_server; content:"|join"; http_client_body; nocase; content:"__toString"; distance:0; within:100; classtype:attempted-recon; sid:1000001; rev:1;)
Remediation & Mitigation
Immediate Remediation:
- Upgrade Twig to version 3.11.2 or 3.14.1 (or later). This is the only complete fix.
- Run
composer update twig/twigto apply the patch.
Mitigation (if patching is delayed):
- Remove or disable filters that can trigger
__toString()on objects (e.g.,join,merge,sort) from the sandbox’s allowed filters list. - Implement a custom sandbox extension that explicitly blocks
__toString()calls on all objects. - Monitor logs for sandbox exceptions and block IPs that trigger them.
Long-Term Recommendations:
- Regularly update all dependencies, especially security-critical ones like Twig.
- Use a Web Application Firewall (WAF) to inspect template submissions.
- Conduct regular security audits of template rendering environments.
Valters IT
Securing Digital Frontiers