Disable Javascript execution on specific pages (HT

2019-06-22 07:15发布

问题:

is there any HTTP-header to disable Javascript for a specific page? My website delivers user-generated HTML-content (that is why I cannot just use htmlenitities) and I would like to prevent scripting (JavaScript injections).

I already use HttpOnly-cookies being set for authentication on the main domain only, while user content is only displayed on subdomains where the cookie cannot be read. The problem is that there are still too many possibilities to execute JavaScript - for example using event attributes like onclick and Internet Explorer has even a property in CSS to allow JavaScript executions (expression) which I had never heard of before. Another interesting idea I have read of, was about throwing an exception in order to block the code following. One more idea would be defining a list containing all allowed tags and additionally an array with each allowed attribute name but this is very hard work and I guess this would not cover all possible injections.

I guess I am not the only person having this problem, so does anybody know a possiblility covering all possible harmful code - at least in modern browsers?

A simple imaginary header similar to X-Scripting: disabled would make life so much easier!

回答1:

Yes, there is an experimental HTTP header called the Content Security Policy that allows you to control where JavaScript comes from, which can make XSS impossible. However it is currently only supported by Chrome and Firefox.

It is a good idea to enable HttpOnly-cookies, however this will prevent exactly ZERO attacks. You can still exploit XSS by reading CSRF tokens, and carrying out requests with an XHR.

There are many ways of obtaining XSS, and a Vulnerability Scanner like ShieldSeal will find (nearly) all of them. Skipfish is an open source vulnerability scanner that is very primitive, but its free. This is how most web applications deal with wide spread vulnerabilities. (I work for SheildSeal and I help build their vulnerability scanner and I love my job.)

When an issue is found you should use htmlspecialchars($var) or htmlspecialchars($var,ENT_QUOTES) to sanitize input. ENT_QUOTES can prevent an attacker from introducing an onclick or other JavaScript event.