2

Ever since CSP 3 introduced strict-dynamic, Google has recommended its usage. Indeed, the idea of maintaining one "root" script, which in turn loads all other necessary scripts, sets up event handlers, etc. instead of maintaining a whitelist of allowed domains or hashes for every inline script seems positive.

However, whenever I read about strict-dynamic, I always read about the inclusion of a nonce. This can prove to be difficult, if for instance the page is generated by an application server, yet the header is added via a reverse proxy later down the line.

In order to mitigate this, I tried to use the other mechanism to identify scripts: hashes. More specifically, the 'sha256-...' keyword.

The complete Conent Security Policy would look like this then:

script-src 'strict-dynamic' 'sha256-XBQNNdy0amIuLO3171zDY4zf/RwRjJMx+MhGafC3R4M=' 'unsafe-inline' http: https:;
object-src 'none';
base-uri 'none';
report-uri https://csp.example.com;

Is there any reason why this might be less safe than a nonce-based approach?

1 Answer 1

3

Your policy is perfectly fine (you can paste it into the CSP Evaluator to confirm) -- hashes are a good alternative to nonces, particularly in static applications.

There are two reasons why most of the advice about policies with strict-dynamic focus on nonces rather than hashes:

  • Applications often dynamically interpolate values inside <script> blocks (e.g. a JS object with some user-controlled data, a string with the user's email, etc.). In these cases you cannot use hashes because you don't know what the contents of the script are ahead of time, whereas a nonce will bless the script regardless of its contents.
  • External scripts (<script src="...">) must be blessed by nonces because hashes apply only to inline script blocks. So if your site has external scripts it would have to use an inline bootstrapping script blessed by a hash, which would then load any external JS. This requires some refactoring and can affect the performance of the page because external scripts will only start to load once the bootstrap script executes.

But if your application doesn't have these problems, then a hash-based policy is a good approach.

1

You must log in to answer this question.