2

I know that inline JS is bad for performance, but why is it bad for security? Can you please explain to me why? With some examples?

1

1 Answer 1

5

A restrictive content security policy can help to reduce the impact of script injection vulnerabilities by disallowing all scripts except those with a certain hash¹.

  • If you use inline JavaScript in the form of on* attributes or javascript: URLs, you can’t implement this type of policy at all, so that’s definitely less safe.

  • If you use inline JavaScript in the form of <script>s without a src, it’s less convenient to create a hash or nonce for use in a CSP, which might tempt people not to add one at all. A nonce policy also allows for dynamic scripts, which are generally bad ideas (just about the only use for dynamic scripts – inserting JSON in a <script> because it looks compatible with JavaScript – is a recipe for bugs and script injection²).

¹ or located on a certain domain that you only use for static content. careful about allowing domains (including the origin!) serving user content that can act as scripts!
² caused by not escaping <, U+2028, and U+2029 – JSON’s 3 incompatibilities with inline JavaScript. I recommend using your typical HTML escaping and reading from a data- attribute instead.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.