Optionally sanitize svg file during upload

Created on 13 November 2024, 2 days ago

Problem/Motivation

Currently sanitization will happen when the svg file is rendered on page. However, SVG image field module allows uploading an SVG file even if it contains for example a script tag or an iframe tag. The original file will be preserved on the server filesystem and it can be directly loaded from there and the scripts will be executed in the user's browser.

It would be great if the sanitization could also be applied to the upload process as well. It could possibly be optional if needed?

I included a mock-up screenshot of some quickly made example how it could look like when an uploaded svg file does not validate because of suspicious tags.

Steps to reproduce

  • Follow the installation and configuration steps of the SVG image field module
  • Create an svg file that contains suspicious content like iframes or script tags
  • Upload this file to your site via svg image field
  • View the original file in your browser and you will notice that those suspicious tags will be present in the svg file

Proposed resolution

Add new upload validator in svg_image_field/src/Plugin/Field/FieldWidget/SvgImageFieldWidget.php
For example something like this

public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element = parent::formElement($items, $delta, $element, $form, $form_state);

    $field_settings = $this->getFieldSettings();
    $element['#upload_validators']['file_validate_extensions'][0] = 'svg';
    $element['#upload_validators']['svg_image_field_validate_mime_type'] = [];
   $element['#upload_validators']['svg_image_field_validate_sanitize'] = [];

After that, utilize the svg sanitizer in hook_file_validate() in a similar way as the mime type is validated

function svg_image_field_validate_sanitize(FileInterface $file) {

Something along these lines

...
$svgSanitizer = new Sanitizer();
$svg_data = $svgSanitizer->sanitize($svg_data);
if ($issues = $svgSanitizer->getXmlIssues()) {
  foreach ($issues as $issue) {
    $errors[] = $issue['message'];
  }
}
...

In addition to this there could be settings for this, if someone doesn't want their svg files to be sanitized during upload. This could maybe be controlled in the field or form settings?

Remaining tasks

  • create the upload validator
  • create settings for it
  • create tests?

User interface changes

  • An error message will be displayed during upload if there are any validation errors
  • Settings form where sanitizing during upload can be disabled/enabled?
Feature request
Status

Active

Version

2.3

Component

Code

Created by

🇫🇮Finland hartsak

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024