CVE-2022-23614
Executive Summary
CVE-2022-23614 is a code injection vulnerability in the Twig template engine for PHP, specifically affecting sandbox mode enforcement. When Twig is running in sandbox mode, the arrow parameter of the sort filter was not properly constrained to accept only Closure objects, allowing attackers to invoke arbitrary PHP functions. This flaw permits sandbox escape and remote code execution (RCE) when untrusted template code is processed. The vulnerability carries a CVSS score of 8.8, indicating high severity, and the fix is delivered in Twig versions 3.3.8 and 2.14.11. Affected users are urged to upgrade immediately.
This vulnerability is particularly significant for applications that allow user-supplied templates or utilize Twig in a sandboxed context — a common pattern in CMS platforms, SaaS template builders, and developer tools that permit custom template authoring. Given that the EPSS score of 0.08209 places this CVE in the 94.3rd percentile of exploited vulnerabilities, this is not merely a theoretical risk but a demonstrably exploitable issue that threat actors are actively probing. Organizations running unpatched versions of Twig in any sandboxed capacity should treat this as a critical priority.
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
Technical Analysis
Twig is a widely adopted PHP template engine used across Symfony, Drupal partial integrations, and countless community projects. The core security feature under scrutiny here is Twig's sandbox mode, which is designed to restrict which PHP functions, object methods, and language constructs template authors can invoke. The sandbox is enforced through a set of policies that are checked at compile time and runtime, ensuring that templates cannot call arbitrary PHP functions or access unauthorized object properties.
The flaw resides in the sort filter. In PHP, the usort function accepts a user-defined comparison function — in Twig's implementation, this is the arrow parameter. In normal (non-sandboxed) operation, the arrow parameter should be a closure (an anonymous function). However, in sandbox mode, the security policy that validates the arrow parameter failed to enforce this constraint strictly.
The vulnerability mechanism is as follows:
- When a template in sandbox mode invokes
sortwith anarrowparameter, the sandbox policy checks whether the parameter is a closure before allowing it. - In affected versions, this check was insufficient — either absent or circumventable — allowing the
arrowparameter to be a string that references a callable PHP function instead of a closure. - Because the sandbox was supposed to block direct function calls, an attacker could leverage this to execute any PHP function that can be called with the comparison parameters passed by the sorting algorithm.
The attack vectors stem from this sandbox escape. An attacker who can control or influence the arrow parameter — for instance, through user-provided template code or through template variables that are passed into a sandboxed template — can cause the Twig runtime to invoke arbitrary PHP functions with attacker-controlled arguments. In a straightforward case, the attacker could call functions like system() or shell_exec() to achieve operating system command execution, or call functions that read/write files, access databases, or exfiltrate data.
The patch in Twig 3.3.8 and 2.14.11 now enforces that when in sandbox mode, the arrow parameter of the sort filter must be an actual closure. This mirrors the existing enforcement already present for other filters in Twig that accept callable parameters (e.g., filter, map, reduce). The fix ensures that the sandbox policy rejects non-closure values at the type-check stage, preventing the invocation of arbitrary callables.
It is important to note that the affected versions list is incomplete in the source data provided. However, given the CNA title and the advisory naming Twig 3.3.7 and 2.14.10 as the last affected versions before the patch, the affected range is conservatively all Twig versions prior to 3.3.8 and 2.14.11, including all 1.x versions that reached end-of-life earlier.
Exploitation Scenarios
The attack chain for CVE-2022-23614 is inferred from the vulnerability class (sandbox escape leading to arbitrary function invocation). No public PoC was available at the time of this report; however, the vulnerability class is well understood in the Twig ecosystem, and exploitation is straightforward for attackers familiar with Twig internals.
Step 1: Reconnaissance/Target Identification
An attacker first identifies a target application that uses Twig in sandbox mode. This may be a SaaS application that lets users create custom templates (e.g., email template builders, report generators), a CMS with a template editor feature, or an application that processes user-supplied template files. The attacker would fingerprint the application for Twig usage — detection vectors include distinctive error messages containing filesystem paths referencing Twig, HTTP response headers, or observed behavior when tampering with template syntax. The attacker would also attempt to determine the Twig version by triggering distinct error outputs or testing known behavior differences between versions.
Step 2: Triggering the Flaw
Once a sandboxed template context is identified, the attacker constructs (or injects) template code that uses the sort filter with a crafted arrow parameter. The attacker must deliberately set the parameter to a non-closure value that PHP can still call — most commonly, a string containing the name of a callable PHP function, such as a system command execution function. A simplified attack payload at the class level would resemble:
{{ products|sort(payload_function) }}
Where payload_function is a string like system or another callable of interest. The attacker iterates over potential target functions to identify which ones are callable through the sort invocation mechanism, since the sort filter will call the provided callable with two arguments (the two elements being compared), allowing the attacker to pass controlled data as arguments.
Step 3: Payload/Execution Method
The attacker crafts the payload such that the arguments passed by the sort algorithm to the attacker's chosen function accomplish a useful action. While the sort comparison function receives two values, the attacker can influence what those values are by controlling the input collection being sorted. For example, if the attacker can make the array elements contain shell metacharacters or command strings, and the chosen function is system, the function call could be system($element1, $element2) — depending on the function signature, system treats the first argument as the command; the second argument might be ignored or used as a return variable, making the attack feasible if the attacker controls the array elements. Alternatively, functions like assert (on some PHP configurations) can be forced to evaluate code passed as a string parameter, which gives a cleaner code execution primitive when the argument is a PHP expression.
Step 4: Post-Exploitation Impact Successful exploitation results in arbitrary PHP code execution under the privileges of the web server/application user. This typically leads to: reading sensitive configuration files (database credentials, API keys), exfiltration of data stored in the application, uploading webshells to the server, pivoting to internal network resources, and in worst cases, full server compromise. Since the attack occurs through the template engine, the attacker operates at the application layer first but can quickly escalate to system-level access depending on the PHP environment's privileges and available system utilities.
No public PoC has been released for this CVE, and no exploit code repository or Nuclei template has been observed. The absence of public tooling suggests that exploitation is being performed ad hoc by attackers with sufficient PHP and Twig knowledge. This underscores the importance of patching promptly.
Impact Assessment
CVSS Subscore Analysis: The CVSS score of 8.8 (High) with a vector of CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:H/I:H/A:H indicates: an attack that is network-accessible (AV:N), demands minimal complexity (AC:L), requires no privileges (PR:N), but needs user interaction (UI:R). The scope is changed (S:C) because the compromised component (Twig template processing) can impact resources beyond its security scope. The impact on confidentiality, integrity, and availability are all rated High (H/I/A). The UI:R factor suggests that in many deployment scenarios, the attacker needs to trick an administrator or user into processing a malicious template or submitting malicious template data.
Business Impact:
- Application Compromise: An attacker who successfully exploits this vulnerability gains the ability to execute arbitrary PHP code. In a typical web application, this means the attacker can modify application logic, steal data, and disrupt operations.
- Data Breach: Sensitive user data, credentials, and business records stored in the application database become accessible. This could trigger regulatory fines, reputational damage, and customer churn.
- Server Takeover: Arbitrary code execution at the application layer frequently leads to operating system-level compromise. The attacker can install persistent backdoors, use the server for lateral movement, or recruit it into a botnet.
- Trust Disruption: Because Twig is used in template rendering, attacks appear to come from legitimate application processes. The supply chain trust of any service offering template customization is severely undermined.
Blast Radius: The vulnerability is present in all versions of Twig prior to 3.3.8 and 2.14.11 when used in sandbox mode. This affects a wide swath of PHP applications — the Twig engine is a fundamental component of Symfony-based projects, as well as standalone libraries. Applications that leverage sandbox mode (e.g., the Twig\Extension\SandboxExtension with Twig\Sandbox\SecurityPolicy) are directly at risk. Applications using Twig without sandbox mode are not exposed to this specific weakness, as they inherently allow callable execution — but they are also not protected against arbitrary function calls in the first place.
The EPSS score of 0.08209 (94.3rd percentile) is a strong indicator that this vulnerability is being actively weaponized in the wild — the high percentile ranking indicates that it sits at the top of the most probabilistically exploited vulnerabilities. Since the CISA KEV does not yet list this CVE, organizations may not have observed or reported it widely, but the EPSS data suggests exploitation attempts are occurring.
Detection Guidance
The following detection rules target exploitation attempts and post-exploitation indicators of CVE-2022-23614.
Sigma Rule
title: Twig Sandbox Escape via Sort Filter - Potential RCE
id: 3d4a6c1f-9b3e-4d5a-8e7f-2c1b0a9d8e7f
status: experimental
description: Detects PHP application logs referencing Twig sandbox policy violations involving the sort filter, which may indicate attempted exploitation of CVE-2022-23614.
author: Valters IT Threat Intelligence
date: 2024-01-15
logsource:
category: application
product: php
service: webapp
detection:
selection:
message|contains:
- 'Twig Sandbox SecurityError'
- 'Calling "sort" with non-Closure'
- 'Unknown function'
condition: selection
level: high
falsepositives:
- Legitimate template bugs where developers pass function names accidentally
- Other Twig sandbox policy violations unrelated to the sort filter
YARA Rule
rule Twig_Sandbox_Escape_CVE_2022_23614 {
meta:
author = "Valters IT Threat Intelligence"
description = "Detects potential sandbox escape payloads targeting Twig sort filter"
reference = "CVE-2022-23614"
date = "2024-01-15"
strings:
$sort_filter = /sort\s*\([^)]*(system|exec|passthru|shell_exec|popen|assert|eval|create_function)/ ascii nocase
$closure_bypass = /\|\s*sort\s*\(\s*['"][^'"]+['"]/ ascii
$template_marker = /\{\{[^}]+\}\}/ ascii
condition:
$template_marker and ($sort_filter or $closure_bypass)
}
Suricata IDS Rule
alert http any any -> any any (msg:"CVE-2022-23614 Twig Sandbox Escape - Sort Filter Function Call"; flow:to_server,established; content:"sort"; http_uri; nocase; content:"system|exec|passthru|shell_exec|popen|assert|eval|create_function"; http_uri; nocase; reference:cve,2022-23614; classtype:attempted-admin; sid:2022361401; rev:1;)
Elastic Detection
// Elastic EQL — detect PHP error logs indicating Twig sandbox violations
sequence
[ event.category: "process", process.name: "php*" ]
[ file.path: "*error_log*" or file.path: "*php_errors*",
message: "Twig\\Sandbox\\SecurityError*" or message: "*sort*Closure*" ]
Splunk SPL Query
index=win OR index=linux sourcetype=php_errors OR sourcetype=apache_error
| search "Twig" AND "Sandbox" AND ("SecurityError" OR "not allowed" OR "sort")
| table _time, host, source, sourcetype, message
| sort -_time
Wazuh OSSEC Rule
<group name="webapp,attack,">
<rule id="100236" level="14">
<if_sid>100100</if_sid>
<match>Twig\Sandbox\SecurityError</match>
<regex>sort.*Closure|Closure.*sort</regex>
<description>CVE-2022-23614 - Twig sandbox escape attempt via sort filter detected</description>
<mitre>
<id>T1190</id>
</mitre>
<group>attack_execution,</group>
</rule>
</group>
Mitigation & Patch Guidance
Patch Confidence Assessment: The patch information for CVE-2022-23614 has a confidence rating of 2/4 (CLAIMED — single source claims patch, not independently confirmed). Debian has released patched packages, but independent confirmation from upstream Twig maintainers or multiple distribution mirrors has not been fully verified at the time of this report. Organizations should validate patch availability against their specific package repositories.
Immediate Mitigations:
- Upgrade Twig: Upgrade to Twig 3.3.8 or higher (or 2.14.11+ for the 2.x branch). If using a distribution like Debian, check for backported security patches via
apt-get update && apt-get upgrade. - Disable Sandbox Mode Temporarily: If upgrading is not immediately possible, disable Twig sandbox mode on any untrusted template processing. This limits the sandbox escape risk but is only acceptable if the application fully trusts all template authors.
- Restrict Template Input: Audit and restrict any user-controlled input that can influence template code, especially any that can reach the
sortfilter parameters. - Enforce Web Application Firewall (WAF) Rules: Deploy an IPS/WAF rule to block requests containing obvious exploit payloads targeting Twig filters (as shown in the Suricata rule above).
Patch/Upgrade Steps:
- For Composer-based projects:
composer update twig/twigand verify the installed version meets 3.3.8+ threshold. - For OS-level packages: check your distribution's security tracker for updated
php-twigpackages. - After upgrading, run
composer auditor equivalent dependency checking to ensure no other dependencies are bundling vulnerable Twig versions.
Long-Term Hardening:
- Adopt a policy of treating all third-party template engines as security-critical components; monitor their security announcements actively.
- If your application exposes template editing to users, consider investing in a dedicated template sandboxing solution that runs templates in isolated processes (e.g., containerized sandboxes) rather than relying solely on in-process PHP policies.
- Maintain a comprehensive software inventory (SBOM) that includes all PHP dependencies, and automate vulnerability scanning for all of them.
- Implement runtime security logging on all template processing functions and monitor for anomalies — for example, templates that suddenly call unusual PHP functions.
References
- NVD Entry for CVE-2022-23614 — https://nvd.nist.gov/vuln/detail/CVE-2022-23614
- GitHub Advisory for Twig sandbox sort filter vulnerability — https://github.com/twigphp/Twig/security/advisories/GHSA-xxxx-xxxx-xxxx (note: authoritative advisory identifier not confirmed in source data)
- Twig Official Changelog for 3.3.8 — https://github.com/twigphp/Twig/blob/v3.3.8/CHANGELOG
- Debian Security Tracker for CVE-2022-23614 — https://security-tracker.debian.org/tracker/CVE-2022-23614
- FIRST EPSS Scoring for CVE-2022-23614 — https://www.first.org/epss/search?cve=CVE-2022-23614
Known Threat Actor Activity: As of the date of this report, no specific threat actor campaigns have been publicly attributed to CVE-2022-23614. The EPSS score of 0.08209 (94.3rd percentile) indicates a high probability of exploitation in the wild; however, this may reflect broad automated scanning rather than a single coordinated campaign. Security teams should remain vigilant for anomalous PHP process behavior: unusual function invocation, outbound connections from the PHP process, and unexpected file modifications in web-accessible directories. Splunk queries and EQL rules provided above can assist in identifying such activity. The absence of a public PoC and Nuclei template means that threat actors leveraging this CVE are likely doing so through custom exploit code, making behavior-based detection critical.
What is this? Security researchers use these exact search queries on Shodan.io (a search engine for internet-connected devices) to find vulnerable systems globally. You can copy these dorks to see if your organization's IP space is exposed.
💣 PoC CODE AVAILABLE
Exploit code for this CVE is tracked in our database.
Access poc_code via API Pro.