How to Use the Content Security Policy Header to Enable Inline Script Restrictions

The Content Security Policy (CSP) header is a powerful security feature that helps protect websites from cross-site scripting (XSS) attacks. One of its key functions is to control which scripts are allowed to run on your webpage, including inline scripts. Properly configuring CSP can significantly enhance your website’s security posture.

Understanding the Content Security Policy Header

The CSP header is sent by your web server and instructs the browser on which resources are permitted to load and execute. It can specify sources for scripts, styles, images, and other content types. When configured correctly, it prevents malicious scripts from executing, even if they are injected into your page.

Enabling Inline Script Restrictions

By default, many websites allow inline scripts, which can be a security risk. To restrict inline scripts, you need to set the script-src directive in your CSP header and use the ‘nonce- or ‘strict-dynamic’ keywords. This approach allows only scripts with a specific nonce or hash to run.

Using Nonces

A nonce is a random token generated for each page load. You include this nonce in your CSP header and add it to your inline scripts. For example, your CSP header might look like:

Content-Security-Policy: script-src 'nonce-'; object-src 'none';

Then, in your HTML, your inline scripts should include the nonce attribute:

<script nonce="<random>"> // Your inline script </script>

Using Hashes

Alternatively, you can specify a hash of the inline script content in your CSP header. This method is static and suitable for scripts that do not change. An example:

Content-Security-Policy: script-src 'sha256-abc123...';

And your inline script remains unchanged:

<script> // Your inline script </script>

Implementing CSP in Your Website

To implement CSP, add the header to your web server configuration or through your website’s backend. For example, in Apache, you can add:

Header set Content-Security-Policy "script-src 'nonce-'; object-src 'none';"

Ensure you generate a new nonce for each page load and include it in your inline scripts.

Best Practices and Tips

  • Always generate a unique nonce for each page load.
  • Use hashes for static inline scripts whenever possible.
  • Combine CSP with other security measures like HTTPS and secure cookies.
  • Test your CSP policies thoroughly to avoid breaking site functionality.

Properly configuring your Content Security Policy header to restrict inline scripts enhances your website’s security by reducing the risk of XSS attacks. Regularly review and update your policies to adapt to new security challenges.