Reputation: 6608
For an image upload API that we’re building, is there any guidance on checking/sanitising for malicious content ?
I’ve seen examples in the internet where we can add JavaScript inside an image and upload it to any file upload API. If we were to render the image as-is using element elsewhere, that embedded JS code is executed by the browser.
While searching for mitigation advice, I came across this link in OWASP docs. Their recommendation is to rewrite images using Apache Commons Imaging library but I’m not sure if it’s actively maintained (last update in 2020)
Is there a better way of detecting embedded JS in images (or) some safe way of rendering these images in browser to mitigate against Stored XSS attacks ?
Appreciate any help on this.
Upvotes: 2
Views: 3271
Reputation: 344
There are multiple ways to mitigate xss on image file uploads.
Follow these steps,
image/png
, image/jpg
, image/jpeg
, image/gif
)image/<type>
. (Browsers won't execute any javascript if the content type is image/*
)<img src="[path-to-img]">
tag to render the image and don't allow the user to control any values of HTML here.svg
images, then you should sanitize the content of the file because SVG files are built with XML. So, use something like sanitize-svg to remove malicious content from the uploaded data.If you follow above steps, there is pretty much zero chance to get XSS. (Currently - 2022-04-09)
So, if you want to only protect against XSS attacks, there is no need to sanitize or detect malicious content of the uploaded data.
[WARNING]: If you process uploaded data server-side for anything else (resizing,cropping), you have to remove any malicious content before doing that.
Finally, make sure to check this XSS Mitigation Cheatsheet by OWASP.
Hope this helps.
Upvotes: 7
Reputation: 161
The image handling process you found in the OWASP docs is generally a good approach.
If you are really concerned about some malicious content than:
Edit:
Plus you can use Content Security Policy to protect - on the client side - the users against XSS attacks.
Upvotes: 0