Reputation: 23
Is there a way to configure PHP/server (over Nginx php-fpm) to prevent javascript execution from php file_get_contents?
right now, if I allow users to upload html files with js embedded, JS get executed when file is displayed through file_get_contents() call.
I plan to add HTML filtering (ie deny html upload) but it will be even better if I can have a second layer of security on the ouput, instead of only on the upload (in case the first layer failed to take into account so scenario).
Thanks
Upvotes: 1
Views: 782
Reputation: 48367
Kudos to jcubic for providing a link to an explanation of why his solution won't work ;)
There are only 2 robust solutions I know of:
1) use a markup language other than HTML which has a provable grammar and does not allow embedded scripting (BBCode?). This still requires that you validate the submission for compliance - but is simpler than for HTML.
2) apply a content security policy which does not allow inline javascript - this would be my preferred solution, not least because you can specify a reporting URL, allowing you to police what is happenning on the browser rather than relying on filtering on the server.
Upvotes: 2
Reputation: 66590
You can try to strip JavaScript before you echo the content of the file:
echo preg_replace("%<script[^>]*>.*</script>%si", "", file_get_contents());
or you can call this when you upload the file so you don't have to do that each time.
you may also want to remove events like onclick and style that have url with javascript:
protocol, to remove those you probably be better with a xml parser.
Here is a list of XSS vectors attacks that you can take into account: XSS Filter Evasion Cheat Sheet
Upvotes: 0