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.
CodePudding user response:
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:
- Handle the image rewrite in a disposable environment (VM or container) where it is not a problem if it gets compromised.
- Keep/store the uploaded file in 2-3 fregments on the host and only assemble it in the vm.
Edit:
Plus you can use Content Security Policy to protect - on the client side - the users against XSS attacks.
CodePudding user response:
There are multiple ways to mitigate xss on image file uploads.
Follow these steps,
- Don't allow any other file types apart from images. (For example: only accept files with content-type:
image/png
,image/jpg
,image/jpeg
,image/gif
) - Always, save the file using an appropriate extension, never allow the user to control the extension of the filename. (You can save the file using a completely randomname to mitigate this, use GUID/UUID to generate a random name for the image)
- Set the HTTP Response's content type to
image/<type>
. (Browsers won't execute any javascript if the content type isimage/*
) - Only use
<img src="[path-to-img]">
tag to render the image and don't allow the user to control any values of HTML here. - If you are allowing users to upload
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. - Use CSP to prevent XSS (Optional, better if you can implement)
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.