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?

Ry-
  • 218,210
  • 55
  • 464
  • 476
nope123
  • 349
  • 2
  • 6
  • 13
  • 4
    Possible duplicate of [Why is inline script forbidden (Content Security Policy)?](https://stackoverflow.com/questions/15780918/why-is-inline-script-forbidden-content-security-policy) – Arber Sylejmani Feb 07 '18 at 20:24

1 Answers1

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.

Ry-
  • 218,210
  • 55
  • 464
  • 476