Problem/Motivation

If a field containing an inline SVG is passed through views rewrite results the SVG is stripped and mostly removed (normally just leaving the the title left).

The same field containing an inline SVG can be used on a normal node page without being stripped.

Views rewrite uses \Drupal\Component\Utility\Xss::filterAdmin() which has protected strings of protected static $adminTags = array('a', 'abbr', 'acronym', 'address', 'article', 'aside', 'b', 'bdi', 'bdo', 'big', 'blockquote', 'br', 'caption', 'cite', 'code', 'col', 'colgroup', 'command', 'dd', 'del', 'details', 'dfn', 'div', 'dl', 'dt', 'em', 'figcaption', 'figure', 'footer', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'mark', 'menu', 'meter', 'nav', 'ol', 'output', 'p', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'small', 'span', 'strong', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'time', 'tr', 'tt', 'u', 'ul', 'var', 'wbr');

Adding some SVG specific strings such as those found in the following popular purifiers would allow common SVG markup and keep it safe from XSS.
https://github.com/cure53/DOMPurify/blob/master/src/purify.js
or
https://github.com/darylldoyle/svg-sanitizer/blob/master/src/data/AllowedTags.php

A section (not full list) by way of example of some strings those purifiers allow is:

 'accent-height','accumulate','additivive','alignment-baseline', 'ascent','azimuth','baseline-shift','bias','clip','clip-path',
'clip-rule','color','color-interpolation','color-interpolation-filters', 'color-profile','color-rendering','cx','cy','d','dy','dy','direction',
'display','divisor','dur','elevation','end','fill','fill-opacity', 'fill-rule','filter','flood-color','flood-opacity','font-family',
'font-size','font-size-adjust','font-stretch','font-style','font-variant', 'font-weight','image-rendering','in','in2','k1','k2','k3','k4','kerning', 'letter-spacing','lighting-color','local','marker-end','marker-mid',
'marker-start','max','mask','mode','min','offset','operator','opacity', 'order','orient','overflow','paint-order','path','points','r','rx','ry','radius', 'restart','scale','seed','shape-rendering','stop-color','stop-opacity',
'stroke-dasharray','stroke-dashoffset','stroke-linecap','stroke-linejoin', 'stroke-miterlimit','stroke-opacity','stroke','stroke-width','transform', 'text-anchor','text-decoration','text-rendering','u1','u2','viewbox', 'visibility','word-spacing','wrap','writing-mode','x','x1','x2','y', 'y1','y2','z',

The issue can be worked around by simply not passing SVGs through views Rewrite results.

It would be worthwhile confirm that adding common SVG strings to the existing XSS filtering would be safe. Is it?
Are there other HTML elements that are safe to add but which we do not permit? (broaden issue?)

Please note that the same applies to Global: Custom text fields in twig. Technically it just uses the same alter_text=TRUE flag.

The description says:

The text to display for this field. You may enter data from this view as per the "Replacement patterns" below. You may include Twig or the following allowed HTML tags: <a> <abbr> <acronym> <address> <article> <aside> <b> <bdi> <bdo> <big> <blockquote> <br> <caption> <cite> <code> <col> <colgroup> <command> <dd> <del> <details> <dfn> <div> <dl> <dt> <em> <figcaption> <figure> <footer> <h1> <h2> <h3> <h4> <h5> <h6> <header> <hgroup> <hr> <i> <img> <ins> <kbd> <li> <mark> <menu> <meter> <nav> <ol> <output> <p> <pre> <progress> <q> <rp> <rt> <ruby> <s> <samp> <section> <small> <span> <strong> <sub> <summary> <sup> <table> <tbody> <td> <tfoot> <th> <thead> <time> <tr> <tt> <u> <ul> <var> <wbr>

Please note the OR which seems incorrect then. In the case @thomas.frobieter describes we're trying to use
{{ icon('my_custom_theme', 'clock', { color: 'warning' }) }}
but that gets filtered out, while it should be fine through Twig?

Some related issues for reference:

Steps to reproduce

Proposed resolution

Remaining tasks

User interface changes

Introduced terminology

API changes

Data model changes

Release notes snippet

Issue fork drupal-2840938

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

serg2 created an issue. See original summary.

lendude’s picture

Title: Views Rewrite Results strips inline SVGs » Allow Views Rewrite Results to include inline SVGs
Category: Bug report » Feature request

Since this is done by XSS::filterAdmin I would say that this is working as designed, so any changes we make would be a new feature.

There are more requests floating around about people trying to get around the restrictions of only using XSS allowed tags, so maybe it would be worthwhile to allow admins to swap out the used filter in some way. Don't know, just thinking out loud.

serg2’s picture

Yes, there are quite a few open issues about XSS in general. Initially it would be good to establish if adding these is safe. I will take me a while to find good authoritative sources on this but once I do I will add them in here.

serg2’s picture

Issue summary: View changes
serg2’s picture

There was a core issue #2099741: Protect WYSIWYG Editors from XSS Without Destroying User Data which dealt with preventing XSS in Ckeditor. The documentation within the patch is the best information I can find about making user submitted content XSS safe without destroying the content.

It is worth noting that SVGs can be uploaded into WYSIWYG (CKEditor) and used safely because of that patch. It focuses on blacklisting bad, rather than whitelisting good. Some SVG features are stripped but only a few and 'simple' SVGs will get through unharmed.

The core of this issue, allowing SVGs through Views-rewrite results, comes down to:
What is the purpose of the filtering that occurs at the rewrite stage?

It seems like it is 'old code' but it does ensure super safe output. If, for instance, content is being passed though rewrite results which has not previously been filtered it will make it safe.

One solution could be, now that CKeditor is in core, is to use its filter set-up at views rewrite.

That would mean that all the issues that are currently open regarding views rewrite stripping get either fixed or moved into the CKeditor (and the obvious benefits of removing and re-using code).

Should I change this issue to that: "Use CKEditor filtering in views re-write results" ?

lendude’s picture

Should I change this issue to that: "Use CKEditor filtering in views re-write results" ?

that might work as long as we don't create a dependency on CKEditor in Views. Haven't looked at what CKEditor does so don't know how viable this is, but somehow being able to switch to different filter settings sounds something that would be attractive for a lot of people.

Version: 8.2.x-dev » 8.3.x-dev

Drupal 8.2.6 was released on February 1, 2017 and is the final full bugfix release for the Drupal 8.2.x series. Drupal 8.2.x will not receive any further development aside from critical and security fixes. Sites should prepare to update to 8.3.0 on April 5, 2017. (Drupal 8.3.0-alpha1 is available for testing.)

Bug reports should be targeted against the 8.3.x-dev branch from now on, and new development or disruptive changes should be targeted against the 8.4.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Version: 8.3.x-dev » 8.4.x-dev

Drupal 8.3.6 was released on August 2, 2017 and is the final full bugfix release for the Drupal 8.3.x series. Drupal 8.3.x will not receive any further development aside from critical and security fixes. Sites should prepare to update to 8.4.0 on October 4, 2017. (Drupal 8.4.0-alpha1 is available for testing.)

Bug reports should be targeted against the 8.4.x-dev branch from now on, and new development or disruptive changes should be targeted against the 8.5.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Version: 8.4.x-dev » 8.5.x-dev

Drupal 8.4.4 was released on January 3, 2018 and is the final full bugfix release for the Drupal 8.4.x series. Drupal 8.4.x will not receive any further development aside from critical and security fixes. Sites should prepare to update to 8.5.0 on March 7, 2018. (Drupal 8.5.0-alpha1 is available for testing.)

Bug reports should be targeted against the 8.5.x-dev branch from now on, and new development or disruptive changes should be targeted against the 8.6.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Version: 8.5.x-dev » 8.6.x-dev

Drupal 8.5.6 was released on August 1, 2018 and is the final bugfix release for the Drupal 8.5.x series. Drupal 8.5.x will not receive any further development aside from security fixes. Sites should prepare to update to 8.6.0 on September 5, 2018. (Drupal 8.6.0-rc1 is available for testing.)

Bug reports should be targeted against the 8.6.x-dev branch from now on, and new development or disruptive changes should be targeted against the 8.7.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Version: 8.6.x-dev » 8.8.x-dev

Drupal 8.6.x will not receive any further development aside from security fixes. Bug reports should be targeted against the 8.8.x-dev branch from now on, and new development or disruptive changes should be targeted against the 8.9.x-dev branch. For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

kenton.r’s picture

I just ran into the need of adding an SVG in views rewrite. I would also like to see this feature added.

Version: 8.8.x-dev » 8.9.x-dev

Drupal 8.8.7 was released on June 3, 2020 and is the final full bugfix release for the Drupal 8.8.x series. Drupal 8.8.x will not receive any further development aside from security fixes. Sites should prepare to update to Drupal 8.9.0 or Drupal 9.0.0 for ongoing support.

Bug reports should be targeted against the 8.9.x-dev branch from now on, and new development or disruptive changes should be targeted against the 9.1.x-dev branch. For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

markdc’s picture

@kenton.r Ditto that.

marcoka’s picture

Very important. I use it like that and that will not work in views because stripped out

This is no special custom tag: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/use
Guess i need to hack core again because of a tag.

#2687479: Responsive Image not working in rewritten Views field/area due to XSS filtering

juc1’s picture

@marcoka or anyone - do I still need to hack core to allow the svg tag in my View? If so what do I need to do?

juc1’s picture

reply to myself - permitted html tags are listed in /core/lib/Drupal/Component/Utility/Xss.php but a better option is to use a views template (such as views-view-fields--my-view-here.html.twig) which has no html restrictions.

marcoka’s picture

Juc1 yes you need to. DI it today, again.

Version: 8.9.x-dev » 9.2.x-dev

Drupal 8 is end-of-life as of November 17, 2021. There will not be further changes made to Drupal 8. Bugfixes are now made to the 9.3.x and higher branches only. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

Version: 9.2.x-dev » 9.3.x-dev
c13l0’s picture

Following this issue as it is a feature that we need.

Version: 9.3.x-dev » 9.4.x-dev

Drupal 9.3.15 was released on June 1st, 2022 and is the final full bugfix release for the Drupal 9.3.x series. Drupal 9.3.x will not receive any further development aside from security fixes. Drupal 9 bug reports should be targeted for the 9.4.x-dev branch from now on, and new development or disruptive changes should be targeted for the 9.5.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

Version: 9.4.x-dev » 9.5.x-dev

Drupal 9.4.9 was released on December 7, 2022 and is the final full bugfix release for the Drupal 9.4.x series. Drupal 9.4.x will not receive any further development aside from security fixes. Drupal 9 bug reports should be targeted for the 9.5.x-dev branch from now on, and new development or disruptive changes should be targeted for the 10.1.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

vensires’s picture

Version: 9.5.x-dev » 11.x-dev
vensires’s picture

Until a better solution gets used (ex. override through settings.php or alter hook), I attach a patch which targets the whole Xss class and not Views specifically and adds the SVG and PATH tags to the adminTags array.

I would even consider removing the "views.module" from the issue's "Component" value - either way it's core though it's usually depicted when using views.

beerendlauwers’s picture

I also encountered this issue. Ideally, there should be another toggle under "Rewrite Results" to skip the Xss::filterAdmin filter.

For now, I'm using the "Rewrite Results" toggle itself for this purpose. See the attached patch. It was written for Drupal 10.1.4, but it'll probably work on other versions.

vensires’s picture

Well, I would say that your patch goes to a more opinionated and insecure approach which would work in my scenario too, yes, but it would compromise all views - even if it is not required. From adding two extra tags as allowed to throwing filtering completely out, well there definitely is a gap.

From what I had read in code and comments etc and understood, I would have expected the HTML template coming from Drupal Views UI to be XssAdmin-filtered, yes, but when TWIG is used no extra processing should be done. In that case I could have separate TWIG files in my theme containing the SVG file only and then be able to include these TWIG files from Drupal Views UI textarea - and we should be safe.

When talking about the "Custom" Views Field Plugin, it's more or less easily done, we just have to remove Xss::filterAdmin(...) from this:

/**
 * {@inheritdoc}
 */
public function render(ResultRow $values) {
  // Return the text, so the code never thinks the value is empty.
  return ViewsRenderPipelineMarkup::create(Xss::filterAdmin($this->options['alter']['text']));
}

But you did mention the field rewriting functionality in general - which might also be easy too, though I haven't studied that far yet. But in general we should be ok from any security issues since FieldPluginBase::renderText() already does the following (among other things):

if (!empty($alter['alter_text']) && $alter['text'] !== '') {
  $tokens = $this->getRenderTokens($alter);
  $value = $this->renderAltered($alter, $tokens);
  // $alter['text'] is entered through the views admin UI and will be safe
  // because the output of $this->renderAltered() is run through
  // Xss::filterAdmin().
  // @see \Drupal\views\Plugin\views\PluginBase::viewsTokenReplace()
  // @see \Drupal\Component\Utility\Xss::filterAdmin()
  $value_is_safe = TRUE;

Version: 11.x-dev » main

Drupal core is now using the main branch as the primary development branch. New developments and disruptive changes should now be targeted to the main branch.

Read more in the announcement.

vensires’s picture

Attaching patch from MR after rebasing.

thomas.frobieter’s picture

This behavior prevents the direct use of the Icon API in Views via Twig's {{ icon() }}, which in most cases also returns an inline SVG.

anybody’s picture

Issue summary: View changes

Please note that the same applies to Global: Custom text fields in twig. Technically it just uses the same alter_text=TRUE flag.

The description says:

The text to display for this field. You may enter data from this view as per the "Replacement patterns" below. You may include Twig or the following allowed HTML tags: <a> <abbr> <acronym> <address> <article> <aside> <b> <bdi> <bdo> <big> <blockquote> <br> <caption> <cite> <code> <col> <colgroup> <command> <dd> <del> <details> <dfn> <div> <dl> <dt> <em> <figcaption> <figure> <footer> <h1> <h2> <h3> <h4> <h5> <h6> <header> <hgroup> <hr> <i> <img> <ins> <kbd> <li> <mark> <menu> <meter> <nav> <ol> <output> <p> <pre> <progress> <q> <rp> <rt> <ruby> <s> <samp> <section> <small> <span> <strong> <sub> <summary> <sup> <table> <tbody> <td> <tfoot> <th> <thead> <time> <tr> <tt> <u> <ul> <var> <wbr>

Please note the OR which seems incorrect then. In the case @thomas.frobieter describes we're trying to use
{{ icon('my_custom_theme', 'clock', { color: 'warning' }) }}
but that gets filtered out, while it should be fine through Twig?

I've added this to the issue summary.

anybody’s picture

Issue summary: View changes
anybody’s picture

#27 mentions the relevant parts. Combining this with #32 I was thinking if we could turn it around and first Xss::filterAdmin() maybe and then run the twig afterwards? But I'm not sure about possible risks and if we want to trust entered twig code here?

Would be great to get views core maintainer feedback first.

Attaching the rebased static patch from MR!13949 but I see risks in that approach. Wouldn't recommend to use it in production. Furthermore it's not specific to views.

thomas.frobieter’s picture

Please note the OR which seems incorrect then. In the case @thomas.frobieter describes we're trying to use
{{ icon('my_custom_theme', 'clock', { color: 'warning' }) }}
but that gets filtered out, while it should be fine through Twig?

In this specific case, we use “Global: Custom text” to group multiple Views fields and add further custom Markup:

<!-- The field_availability template is overridden and holds an Icon API SVG Icon, which is removed -->
{{ field_availability }}
<div class="line-item__availability-delayed-components-messsage mt-2">
  <!-- This SVG icon has also been removed, of course -->
  {{ icon('icon_pack', 'clock', { color: 'warning' }) }}
 <p>...</p>
</div>
anybody’s picture

Status: Active » Needs review
Issue tags: +Needs subsystem maintainer review
StatusFileSize
new3.91 KB

MR!13949 works around the problem successfully, but as written I don't think it's a good and safe solution. We need to find something better.

I also asked Claude about possible solutions for this issue:

Summary

Views rewrite output (Rewrite results and Global: Custom text) is filtered with Xss::filterAdmin(). As I understand PluginBase::viewsTokenReplace(), the Twig template is rendered first and the result is filtered afterwards in a #post_render callback. This is deliberate, because filtering first would mangle Twig syntax. The consequence is that anything outside the admin tag list is stripped, including inline SVG and the output of Twig functions like {{ icon() }}. The same mechanism has produced many related reports (responsive images, iframes, and now the Icon API).

There are two separable problems:

  1. Icons: icon() returns inline &lt;svg&gt;, which the filter strips.
  2. General: the filter is hardcoded and not configurable.

Options

  1. Add svg/path to Xss::$adminTags (MR !13949). Small diff, wrong layer. It changes every filterAdmin() caller globally, doesn't scale (icons also need g, use, circle, defs, ...), and introduces SVG foreign-content parsing into a string-based filter. I'd expect the security team to want a close look.
  2. Skip the filter (patch in #26, or removing filterAdmin from Custom text as discussed in #27). Works as a local workaround. As a core default it removes defense in depth, since token values can derive from user content.
  3. Filter first, then run Twig (idea in #34). Not recommended. It breaks Twig syntax and moves the filter off the rendered output, which is where the risk is.
  4. Per-field choice of filter, ideally a text format. The default stays the admin XSS filter. Sites can opt in to a dedicated "Views output" format that allows exactly what they need. It's access-controlled via format permissions and solves the whole family of related issues. It's also the largest change: UI, schema and dependencies, and handling users without access to the format.
  5. Views-scoped extra allowed tags (config). A new views.settings:rewrite.extra_allowed_tags, empty by default, merged with Xss::getAdminTagList() and used in viewsTokenReplace() and the Custom field. It doesn't touch Xss, changes nothing unless configured, and still strips event handlers, style and bad protocols. It's site-wide rather than per-field. A draft patch is attached (hand-written, may need rebasing, and has no tests yet).
  6. Icon API returns an image URL instead of inline SVG. &lt;img&gt; is already allowed by filterAdmin(), so &lt;img src="{{ icon_url }}" alt=""&gt; survives with no filter change at all. SVG in &lt;img&gt; is inert (no scripts, no external loads), so it's the safest way to embed SVG. This would need ui_icons or the Icon API to be extended with a way to output an &lt;img&gt; pointing at the SVG file, instead of inline markup. Limitations:
    • No currentColor or CSS styling of the icon, so the color argument has no effect unless variants are baked into the files.
    • data: URIs are stripped, so it must be a real file URL.
    • One cacheable request per distinct icon.
    • It doesn't help with arbitrary inline SVG in rewrites.
  7. Template override or custom field plugin (#17). Works today because theme templates aren't filtered. Not a core fix.

Recommendation

  • For the Icon API case: pursue option 6, probably as an issue in the Icon API / ui_icons queue. It needs no change to filtering and no new security surface, and it fixes {{ icon() }} in Views for icons that don't need CSS color control.
  • For icons that must follow text color, and for everything else (inline SVG in general, iframes, responsive images): fix the filter side. Option 4 is the cleanest long-term design. Option 5 is a pragmatic first step that can ship sooner and doesn't conflict with 4.
  • Not recommended: options 1 and 3. Use option 2 only as an explicit opt-in, ideally folded into option 4 as a "no filtering" choice.
  • Separate small fix: the help text says "You may include Twig or the following allowed HTML tags", which is misleading, because the tags apply to the output after Twig runs.

Attachment: 2840938-views-rewrite-extra-allowed-tags.patch (option 5)

Let's wait for maintainer feedback now, surely this will need (more general) work!

anybody’s picture

Some related issues for reference:

Discussing this with @thomas.frobieter he pointed out that it might be just fine to allow inline svg and path because dangerous tags within the inline svg would still get filtered out? (In constrast to uploaded svg files #3494583: Filter SVGs before uploading by default)

jwilson3’s picture

Building on #17, #26, and #27, two possible approaches:

  • Allow the value to come from a Twig template file. Views could provide an option to select a template instead of entering the markup in the UI. This would let themers and developers keep it in a normal Twig file rather than embedded in Views YAML configuration.
  • Provide an option to bypass HTML filtering. Since the UI-editable value already supports Twig, we could retain Twig’s auto-escaping for variable output without actually running the rendered result through Xss::filterAdmin(). The idea would be to trust the administrator/developer/themer-authored markup, similar to how Full HTML permits unrestricted HTML for trusted users. If necessary, an extra trust level could be controlled through a separate permission.

Edit: Added a permission suggestion and references to earlier comments; revised with AI assistance for clarity.