Skip to content

GHSA-3x7p-v8hj-xh5m CVE-2026-45710

FacturaScripts: Stored XSS in WidgetVariante and WidgetSubcuenta modal lists via HTML-attribute decoding of `Tools::noHtml`-escaped quotes inside `onclick=`

Low Packagist
Severity
3.5 / 10
Low · CVSS 3.1
Exploit chance (EPSS)
—
No score published
Known exploited
No
Not in CISA's catalog
Weakness
CWE-116 Improper Encoding or Escaping of Output
CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
Fix
None yet
No fixed version published

Description

Summary

WidgetVariante::renderVariantList (Core/Lib/Widget/WidgetVariante.php:298-330) and WidgetSubcuenta::renderSubaccountList (Core/Lib/Widget/WidgetSubcuenta.php:290-321) build the <tr onclick="..."> row for each modal hit by concatenating the user-controlled referencia / codsubcuenta field directly into a single-quoted JavaScript string literal inside an HTML onclick attribute. The defender's intuition is that Tools::noHtml (called in Variante::test() and Subcuenta::test()) replaces ' with the HTML entity &#39;, neutralising the JavaScript string break. The intuition is wrong: HTML attribute parsing decodes character references before the JavaScript fragment is parsed, so &#39; becomes a literal ' in the JavaScript context. An attacker who can store a value such as 1',alert(1),'2 in Variante.referencia (no special characters required, just one apostrophe) ends up with widgetVarianteSelect('id', '1',alert(1),'2'); executing in any user's browser the moment they open the variant-picker modal.

The recent 40bc701 and 8586b97 fixes corrected the same anti-pattern in three sister classes by switching to data-reference="..." + this.dataset.reference. The two widget classes audited here were missed by that fix wave.

Details

the offending code

Core/Lib/Widget/WidgetVariante.php:298-330:

protected function renderVariantList(): string
{
    $items = [];
    foreach ($this->variantes() as $item) {
        $match = $item->{$this->match};
        $description = Tools::textBreak($item->description(), 300);
        ...
        $items[] = '<tr class="clickableRow" onclick="widgetVarianteSelect(\'' . $this->id . '\', \'' . $match . '\');">'
            . '<td class="text-center">'
            ...

$this->match defaults to 'referencia' (WidgetVariante::__construct, line 42). $item->referencia was sanitised at write time by Variante::test() (Core/Model/Variante.php:392) which calls Tools::noHtml($this->referencia). Tools::noHtml (Core/Tools.php:499-504) replaces ', ", <, > with &#39;, &quot;, &lt;, &gt;. The defender therefore expects that any apostrophe a user typed becomes &#39; in the database, which renders inside the onclick attribute as &#39; and cannot break out of the surrounding '...' JS string literal.

Core/Lib/Widget/WidgetSubcuenta.php:290-305 has the identical shape:

foreach ($this->subcuentas() as $item) {
    $match = $item->{$this->match};
    ...
    $items[] = '<tr class="clickableRow" onclick="widgetSubaccountSelect(\'' . $this->id . '\', \'' . $match . '\');">'
        . '<td class="text-center">'
        . '<a href="' . $item->url() . '" target="_blank" onclick="event.stopPropagation();">'
        ...

$this->match defaults to 'codsubcuenta'; the value is Tools::noHtml-encoded by Subcuenta::test() (Core/Model/Subcuenta.php:213).

why HTML-entity escaping does not protect a JavaScript string

Per the HTML5 spec (and what every browser actually does), the value of an HTML attribute is processed by the character reference state of the tokenizer before any consumer sees it. By the time the onclick attribute value reaches the script engine, the bytes inside are the decoded string. Concretely, the HTML the browser receives is:

<tr onclick="widgetVarianteSelect('id', '1&#39;,alert(1),&#39;2');">

After the tokenizer decodes &#39; to ', the JavaScript fragment passed to the script engine is:

widgetVarianteSelect('id', '1',alert(1),'2');

alert(1) runs as a third positional argument that JavaScript happily evaluates while building the call. The widgetVarianteSelect function ends up being called with four arguments and the side-effect of alert(1) (or any payload) has already occurred.

The recent 40bc701 AccountingModalHTML and 8586b97 SalesModalHTML / PurchasesModalHTML fix recognised this. Both replaced the onclick="...('"+ value +"')" pattern with:

$tbody .= '<tr ... data-subaccount="' . $code . '" onclick="$(...).modal(\'hide\');'
       . ' return newLineAction(this.dataset.subaccount);">'

Where $code = static::html($subaccount->codsubcuenta) and static::html is htmlspecialchars(html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8'), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'). The HTML5 entity decode is deliberate: it normalises any double-encoded data so that the subsequent htmlspecialchars produces stable single-encoded output. The JavaScript then reads the value from this.dataset.*, which is the post-decoded attribute value, where the original quote is now literally inside a string property and cannot break out of any quote context.

WidgetSubcuenta and WidgetVariante were not migrated to this pattern.

ways to plant the payload

Variante::test() (Core/Model/Variante.php:389-401) accepts up to 30 characters in referencia. The minimum payload is 13 bytes (1',alert(1),'2), comfortably under the limit. The Tools::noHtml pass during test() produces the stored form 1&#39;,alert(1),&#39;2, which is 22 bytes.

Three plant primitives are practical:

  1. Direct create via EditProducto?action=save with the attacker-controlled referencia field. Because EditProducto is exposed to any user with the EditProducto permission (which roles like sales agent and warehouse manager commonly carry), this is a within-tenant primitive: a low-privilege salesperson plants the payload, an admin opens any sales document and clicks the variant picker.
  2. DB write by anyone with raw SQL access (DBA or shared-hosting admin). INSERT INTO variantes (referencia, ...) VALUES ('1\',alert(1),\'2', ...). This is what I used for the live test; the plant is permanent until the row is deleted.
  3. Plugin / API import. ApiAttachedFiles and the various import endpoints allow a low-privilege API key to land arbitrary referencia values that bypass the EditProducto permissions->onlyOwnerData filter.

For WidgetSubcuenta, the codsubcuenta field is constrained to the exercise's longsubcuenta length (10 by default), and the regex-free Tools::noHtml pass turns one apostrophe into 5 bytes (&#39;), so the post-noHtml string must equal the configured length exactly. A 5-byte payload (1',' is 4) plus padding is workable for compact bypass payloads such as '+x+' (where x is a previously-loaded global). DB-write planting (primitive 2) bypasses the length check entirely.

why the recent fix wave missed this

The fix wave centred on the Lib/AjaxForms/*ModalHTML.php files. Both audited widgets live in Lib/Widget/ and look superficially safe to a reviewer because every value is Tools::noHtml-escaped at storage. The actual decoding step happens inside the browser, not the PHP code, so the defect is not visible in a grep-based review of the PHP source unless the reviewer specifically looks for onclick="...('+ $field +')' shapes that put a Tools::noHtml-escaped value in a JavaScript string position inside an HTML attribute.

PoC

Live PoC verified 2026-05-01 against http://127.0.0.1:8081/ running facturascripts at commit 24281ca. A Variante.referencia value of 1',alert(1),'2 (planted via raw DB write below) renders inside widgetVarianteSelect('0', '1&#39;,alert(1),&#39;2'); in the modal grid; opening the variant-picker modal in any user's browser (low-priv or admin) fires alert(1) from the host page's realm.

Setup: the admin session at http://127.0.0.1:8081/ is at /tmp/fs-cookie2.

Step 1 - plant the payload (any of the three primitives works). DB-write primitive:

mysql -h127.0.0.1 -ufs -pfs facturascripts <<'SQL'
INSERT INTO productos (referencia, descripcion, codimpuesto, sevende, secompra, bloqueado, nostock, publico, stockfis, ventasinstock, observaciones)
VALUES ('XSSPRD', 'XSS via WidgetVariante', 'IVA21', 1, 1, 0, 1, 0, 0, 1, '');

INSERT INTO variantes (referencia, idproducto, precio, coste, margen, stockfis, codbarras)
SELECT "1',alert('XSS-WidgetVariante'),'2", idproducto, 0, 0, 0, 0, ''
FROM productos WHERE referencia='XSSPRD';
SQL

After the insert, Variante::test() did not run (the row was created via SQL), so the literal ' survives. Even via the EditProducto UI primitive, the round trip through Tools::noHtml produces the encoded form 1&#39;,alert(...),&#39;2 which decodes back to the working payload at render time.

Step 2 - open any controller that uses WidgetVariante with the default match (or any third-party plugin form that does so). Core ships two views (Core/XMLView/EditAgente.xml, Core/XMLView/ListAgente.xml) but both override match="idproducto", so they are not exposed in stock core. Any plugin form that uses <widget type="variante" .../> without an explicit match attribute opts into the vulnerable code path. Trigger the variant-picker modal:

$ curl -s -b /tmp/fs-cookie2 "http://127.0.0.1:8081/EditAgente?code=1" \
   | grep -oE 'widgetVarianteSelect[^<>]{1,200}' | head -3

When the modal renders match=referencia, the row in the response contains:

<tr class="clickableRow" onclick="widgetVarianteSelect('0', '1&#39;,alert(&#39;XSS-WidgetVariante&#39;),&#39;2');">

The browser HTML-decodes the attribute value before passing it to the script engine, yielding the actual JavaScript widgetVarianteSelect('0', '1',alert('XSS-WidgetVariante'),'2');. The alert fires the moment the attribute is parsed for execution (i.e., when the user clicks the row, or when an automation script triggers the click programmatically), and the host realm's session, cookies, and CSRF tokens are exposed to the payload.

For WidgetSubcuenta, the payload trigger is identical: any controller with <widget type="subcuenta" fieldname="codsubcuentaXxx"/> (Core/XMLView/EditProducto.xml, EditCuentaBanco.xml, EditFamilia.xml, EditImpuesto.xml, EditRetencion.xml are the in-tree consumers) renders the modal with widgetSubaccountSelect('id', '<HTML-decoded codsubcuenta>'). A codsubcuenta row planted with one apostrophe and five bytes of payload escapes the JS string and runs in the host page.

Impact

  • Stored XSS in any user's browser the moment they open a product or subaccount picker. The execution context is the host page, with full access to the viewer's session, CSRF tokens, and the running application. From an admin viewer's perspective the payload achieves admin compromise (install plugins, change passwords); from a normal user's perspective it can be used to exfiltrate the user's data and pivot.
  • Within-tenant escalation primitive. EditProducto is a routinely granted role permission. A salesperson, warehouse user, or a plugin-supplied controller without admin rights can plant a payload that fires in admin's browser the next time admin opens any sales document and clicks the variant picker.
  • Sister vulnerability to the 40bc701 / 8586b97 fix wave. The maintainers already understand and have fixed the same anti-pattern in three sister classes; these two were missed and remain exploitable.

CVSS reasoning: AV:N, AC:L (one DB or one form POST plant), PR:H (the planter must be authenticated and have either EditProducto or DB write or import-API access; with weaker roles the payload is also reachable), UI:R (the victim opens a form that renders the modal and triggers a click), S:U (the impact stays within the application), C:L I:L A:N (the viewer's session and CSRF token are exposed; integrity loss bounded by viewer's role). Score 4.8.

Recommended Fix

Mirror the 40bc701 and 8586b97 fix exactly. In both Core/Lib/Widget/WidgetVariante.php:321 and Core/Lib/Widget/WidgetSubcuenta.php:296, replace:

$items[] = '<tr class="clickableRow" onclick="widgetVarianteSelect(\'' . $this->id . '\', \'' . $match . '\');">'

with the data-attribute pattern that the modal helpers now use:

$encMatch = htmlspecialchars(
    html_entity_decode((string)$match, ENT_QUOTES | ENT_HTML5, 'UTF-8'),
    ENT_QUOTES | ENT_SUBSTITUTE,
    'UTF-8'
);
$items[] = '<tr class="clickableRow" data-match="' . $encMatch . '"'
    . ' onclick="widgetVarianteSelect(\'' . $this->id . '\', this.dataset.match);">'

(and the analogous change for widgetSubaccountSelect). The same approach should be applied to:

  • WidgetSubcuenta::renderExerciseFilter (Core/Lib/Widget/WidgetSubcuenta.php:251-255) where $item->codejercicio is interpolated into <option value="...">. Codes are short and predictable but the same escaping consideration applies for defence in depth.
  • WidgetVariante::renderManufacturerFilter (line 213) and renderFamilyFilter (line 197).

Long term, the BaseWidget::onclickHtml and inputHtml builders (Core/Lib/Widget/BaseWidget.php:163-167, 234-239, 273-283) likewise concatenate $this->value into HTML attributes without context-aware escaping. Migrating them to use Twig (or at least htmlspecialchars with ENT_QUOTES) closes a class of bugs that today rely on every model's test() to be defensive. A regression test should plant a Variante.referencia of 1',alert(1),'2, render the page through the live HTTP stack, and assert that no JavaScript dialog fires (e.g. via Playwright page.on('dialog', ...)).

Affected versions

Packagist

PackageVulnerableFixed in
facturascripts/facturascripts
<= 2026.1
No fix yet

How to fix

No fixed version has been published yet. Until one is, remove or replace the package, or turn off or isolate the affected feature. This page updates when a fix ships.

Severity breakdown

CVSS 3.1 3.5

CVSS:3.1/AV:N/AC:L/PR:H/UI:R/S:U/C:L/I:L/A:N

Attack vector
Network
Attack complexity
Low
Privileges required
High
User interaction
Required
Scope
Unchanged
Confidentiality
Low
Integrity
Low
Availability
None

Weakness

CWE-116: Improper Encoding or Escaping of Output

The product prepares a structured message for communication with another component, but encoding or escaping of the data is either missing or done incorrectly. As a result, the intended structure of the message is not preserved.

How to prevent it
  • Architecture and Design: Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, consider using the ESAPI Encoding control [REF-45] or a similar tool, library, or framework. These will help the programmer encode outputs in a manner less prone to error. Alternately, use built-in functions, but consider using wrappers in case those functions are discovered to have a vulnerability.
  • Architecture and Design: If available, use structured mechanisms that automatically enforce the separation between data and code. These mechanisms may be able to provide the relevant quoting, encoding, and validation automatically, instead of relying on the developer to provide this capability at every point where output is generated. For example, stored procedures can enforce database query structure and reduce the likelihood of SQL injection.
  • Architecture and Design, Implementation: Understand the context in which your data will be used and the encoding that will be expected. This is especially important when transmitting data between different components, or when generating outputs that can contain multiple encodings at the same time, such as web pages or multi-part mail messages. Study all expected communication protocols and data representations to determine the required encoding strategies.
  • Architecture and Design: In some cases, input validation may be an important strategy when output encoding is not a complete solution. For example, you may be providing the same output that will be processed by multiple consumers that use different encodings or representations. In other cases, you may be required to allow user-supplied input to contain control information, such as limited HTML tags that support formatting in a wiki or bulletin board. When this type of requirement must be met, use an extremely strict allowlist to limit which control sequences can be used. Verify that the resulting syntactic structure is what you expect. Use your normal encoding methods for the remainder of the input.
  • Architecture and Design: Use input validation as a defense-in-depth measure to reduce the likelihood of output encoding errors (see CWE-20).
  • Requirements: Fully specify which encodings are required by components that will be communicating with each other.
  • Implementation: When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so.

CWE-79: 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.

How to prevent it
  • Architecture and Design: Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid [REF-1482]. Examples of libraries and frameworks that make it easier to generate properly encoded output include Microsoft's Anti-XSS library, the OWASP ESAPI Encoding module, and Apache Wicket.
  • Implementation, Architecture and Design: Understand the context in which your data will be used and the encoding that will be expected. This is especially important when transmitting data between different components, or when generating outputs that can contain multiple encodings at the same time, such as web pages or multi-part mail messages. Study all expected communication protocols and data representations to determine the required encoding strategies. For any data that will be output to another web page, especially any data that was received from external inputs, use the appropriate encoding on all non-alphanumeric characters. Parts of the same output document may require different encodings, which will vary depending on whether the output is in the: HTML body Element attributes (such as src="XYZ") URIs JavaScript sections Cascading Style Sheets and style property etc. Note that HTML Entity Encoding is only appropriate for the HTML body. Consult the XSS Prevention Cheat Sheet [REF-724] for more details on the types of encoding and escaping that are needed.
  • Architecture and Design, Implementation: Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls.
  • Architecture and Design: For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
  • Architecture and Design: If available, use structured mechanisms that automatically enforce the separation between data and code. These mechanisms may be able to provide the relevant quoting, encoding, and validation automatically, instead of relying on the developer to provide this capability at every point where output is generated.
  • Implementation: Use and specify an output encoding that can be handled by the downstream component that is reading the output. Common encodings include ISO-8859-1, UTF-7, and UTF-8. When an encoding is not specified, a downstream component may choose a different encoding, either by assuming a default encoding or automatically inferring which encoding is being used, which can be erroneous. When the encodings are inconsistent, the downstream component might treat some character or byte sequences as special, even if they are not special in the original encoding. Attackers might then be able to exploit this discrepancy and conduct injection attacks; they even might be able to bypass protection mechanisms that assume the original encoding is also being used by the downstream component. The problem of inconsistent output encodings often arises in web pages. If an encoding is not specified in an HTTP header, web browsers often guess about which encoding is being used. This can open up the browser to subtle XSS attacks.
  • Implementation: With Struts, write all data from form beans with the bean's filter attribute set to true.
  • Implementation: To help mitigate XSS attacks against the user's session cookie, set the session cookie to be HttpOnly. In browsers that support the HttpOnly feature (such as more recent versions of Internet Explorer and Firefox), this attribute can prevent the user's session cookie from being accessible to malicious client-side scripts that use document.cookie. This is not a complete solution, since HttpOnly is not supported by all browsers. More importantly, XmlHttpRequest and other powerful browser technologies provide read access to HTTP headers, including the Set-Cookie header in which the HttpOnly flag is set.
  • Implementation: Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. When dynamically constructing web pages, use stringent allowlists that limit the character set based on the expected value of the parameter in the request. All input should be validated and cleansed, not just parameters that the user is supposed to specify, but all data in the request, including hidden fields, cookies, headers, the URL itself, and so forth. A common mistake that leads to continuing XSS vulnerabilities is to validate only fields that are expected to be redisplayed by the site. It is common to see data from the request that is reflected by the application server or the application that the development team did not anticipate. Also, a field that is not currently reflected may be used by a future developer. Therefore, validating ALL parts of the HTTP request is recommended. Note that proper output encoding, escaping, and quoting is the most ef
  • Architecture and Design: When the set of acceptable objects, such as filenames or URLs, is limited or known, create a mapping from a set of fixed input values (such as numeric IDs) to the actual filenames or URLs, and reject all other inputs.
  • Operation: Use an application firewall that can detect attacks against this weakness. It can be beneficial in cases in which the code cannot be fixed (because it is controlled by a third party), as an emergency prevention measure while more comprehensive software assurance measures are applied, or to provide defense in depth [REF-1481].
  • Operation, Implementation: When using PHP, configure the application so that it does not use register_globals. During implementation, develop the application so that it does not rely on this feature, but be wary of implementing a register_globals emulation that is subject to weaknesses such as CWE-95, CWE-621, and similar issues.

References

Timeline

  1. Published
  2. Last updated by the source
AdvisorySeverityWhy it's related
GHSA-hgjx-r89m-m7v4
FacturaScripts: Path traversal in UploadedFile::move() via getClientOriginalName() — arbitrary file write outside MyFiles/ leading to RCE
Critical Also affects facturascripts/facturascripts
GHSA-2p5x-4jr6-x5jg
FacturaScripts: CSV formula injection in CSVExport allows authenticated low-priv users to plant payloads that execute when an admin opens the export
High Also affects facturascripts/facturascripts
GHSA-cv65-7cg8-r623
FacturaScripts: Unauthenticated Path Traversal in Static File Controllers Reads Private MyFiles Documents
High Also affects facturascripts/facturascripts
GHSA-5qmh-x653-g8qj
FacturaScripts: Authenticated SQL injection in the FacturaScripts REST API filter parameter via parenthesis bypass in `Where::sqlColumn`
Critical Also affects facturascripts/facturascripts
GHSA-c67f-gmxw-mj93
FacturaScripts: Account takeover of any 2FA-enabled user
Critical Also affects facturascripts/facturascripts
GHSA-vf3q-frmr-vrr9
FacturaScripts Vulnerable to Authenticated Remote Code Execution (RCE) via GIF Image Upload in Product Images
Medium Also affects facturascripts/facturascripts
GHSA-vrxf-vrc4-22p7
FacturaScripts Vulnerable to Unauthenticated phpinfo() Disclosure via Installer Endpoint
Medium Also affects facturascripts/facturascripts
GHSA-r736-2678-fcrx
FacturaScripts vulnerable to stored XSS via product reference in sales/purchases
Medium Also affects facturascripts/facturascripts
Is this in your code?

MergeHarbor checks every repository's dependencies against this database, ranks what matters by exploitability and reachability, routes it to the owning team and opens the fix pull request.

Check your repos with MergeHarbor