Search code examples
phpxssbase64filteringsrc

Is it safe to put base64-encoded user data into src of img?


Is it safe to accept POST data that is supposed to be base64-encoded image data and use it as the src attribute of an img?

<img src="data:image/png;base64,[data here]" />

Obviously, with no filtering one could easily break out of the src attribute and the img tag and insert malicious <script /> or other tags, so my idea is to

base64_decode($rawPostData)

check if it is decoded OK and then

base64_encode($decodedData)

to put it in the src attribute.

Are there any vulnerabilities (such as XSS, maybe buffer overflow?) with this approach?

Background

I need this for a page that transforms a third-party svg to canvas to base64-encoded data using JavaScript (using "canvg" to be precise). I need to have the image passed to server-side scripts to do some other tasks using the image, but also to show the image to the user / client.


Solution

  • I would accept the image as an image, then base64_encode that. It saves the quite unnecessary middle-step of you checking it was submitted as expected and also makes it impossible to cause XSS.

    If you must validate base64 as in image, simply checking it only contains base64 characters would be sufficient, since you are only embedding it within an img tag (and tag breaking characters are not allowed in base64.

    Use inbuilt functions:

    if (base64_decode($mystring, true)) {
        // is valid
    } else {
        // not valid
    }