3

I'm using HTMLPurifier to make sure there is no malicious user input.

I'm having a hard time with base64 images. The regular one is already solved.
$config->set('URI.AllowedSchemes', ['data' => true]);

But how about the following?
<img src="data:image/svg+xml;base64,PHN2Zy...4MTEpIi8+PC9zdmc+Cg==" />

Gordon Freeman
  • 3,260
  • 1
  • 22
  • 42
  • Does this answer your question? https://stackoverflow.com/questions/18447970/content-security-policy-data-not-working-for-base64-images-in-chrome-28 – Daniel W. Feb 01 '22 at 13:50
  • No, I have no issues with regular `data` stuff and/or chrome. Its only the base64 svg. And I solved it already. But thanks – Gordon Freeman Feb 01 '22 at 13:52
  • What is the issue then? You don't write anything about the error you receive. – Daniel W. Feb 01 '22 at 13:53
  • There is no error. HTMLPurifier removes stuff from given markup. So it removes my base64 svg images which I would like to keep. I think its obvious – Gordon Freeman Feb 01 '22 at 13:58

1 Answers1

3

For everyone looking for a solution.. there is no built in way to allow base64 svg images. But there is a way to solve it.

I could not find an official documentation, but you can write custom validations.

<?php

namespace App\Services\HTMLPurifier;

use HTMLPurifier_AttrDef_URI;

/**
 * Class ParameterURIDef
 * @author Artem Schander
 */
class ParameterURIDef extends HTMLPurifier_AttrDef_URI
{
    public function validate($uri, $config, $context)
    {
        if (preg_match('/^data:image\/svg\+xml;base64,([^\"]*)$/', $uri)) {
            return true;
        }

        return parent::validate($uri, $config, $context);
    }
}
$config = HTMLPurifier_Config::createDefault();
$config->set('URI.AllowedSchemes', ['data' => true]);
$definition = $config->getHTMLDefinition(true);
$definition->addAttribute('img', 'src', new \App\Services\HTMLPurifier\ParameterURIDef());

$HTMLPurifier = new HTMLPurifier($config);
Gordon Freeman
  • 3,260
  • 1
  • 22
  • 42