I have a website where users can set a description using html. I want them to be able to do everything with html except use js. Is there anyway to disable all javascript within a tag? Keep in mind I mean all javascript including things like onclick. If not, is there some sort of regular expression I can use to filter out all xss attacks?
2 Answers 2
You could use CSP (Content Security Policy), although it could be a bit cumbersome to configure. Also it's not 100% safe, as it depends on the client (the browser)
you could load all you scripts externally and block all inlined scripts. This can be done with CSP 1 - the browser support is pretty good for CSP 1.
Policy would looks something like this:
Content-Security-Policy: script-src 'self';and/or you could whitelist your inline scripts blocks and all others will be blocked. You need CSP 2 for that, the browser support is lower for that one. The browser support is more limited, e.g. no IE
examples of the policy:
Nonce based
Content-Security-Policy: script-src 'nonce-123'allow executing
<script nonce="123">safemethod()</script>, block othersHash bashed
Content-Security-Policy: script-src 'sha256-07123e1f482356c415f684407a3b8723e10b2cbbc0b8fcd6282c49d37c9c1abc'allow executing the script that has the sha 256 hash (hash of the content) of
07123e1f482356c415f684407a3b8723e10b2cbbc0b8fcd6282c49d37c9c1abc, block others.
Comments
Is there anyway to disable all javascript within a tag? If not, is there some sort of regular expression I can use to filter out all xss attacks?
No and no.
Don't allow users to use unrestricted HTML. Even if your filter were perfect (which it won't be), you will inevitably be caught out when new HTML features are added which your filter did not account for. Moreover, there are numerous malicious things which users could do which don't involve Javascript, such as obscuring parts of your web page with links to malicious sites.
If you are committed to allowing users to input a description as HTML, pass it through a filter based on an HTML parser (such as tidy in PHP, or HTML::Parser in Perl), and only allow tags and attributes through which you have specifically confirmed to be safe.
Is there anyway to disable all javascript within a tag?No, in fact I can simplify that a bit more.No you can't disable Javascript, end of..It's the users PC not yours.