JavaScript > Security > Security Best Practices > Content Security Policy (CSP)

Content Security Policy: Inline Script Protection

This snippet demonstrates how to use Content Security Policy (CSP) to prevent the execution of inline JavaScript, mitigating Cross-Site Scripting (XSS) attacks.

CSP Header Configuration

This CSP header is set on the server-side. It instructs the browser to only allow scripts from the same origin ('self'). Any inline scripts, or scripts from a different domain, will be blocked. The `default-src 'self'` part defines a fallback policy for all resource types when a specific directive isn't set.

Content-Security-Policy: default-src 'self'; script-src 'self'

Example HTML with Inline Script (Blocked)

When this HTML is served with the CSP header defined above, the inline script `alert('This inline script will be blocked by CSP.');` will be blocked by the browser. The browser's developer console will show a CSP error message indicating the violation. You may need to adjust the CSP to see the blocking in action and confirm how CSP works.

<!DOCTYPE html>
<html>
<head>
  <title>CSP Demo</title>
</head>
<body>
  <h1>CSP Inline Script Demo</h1>
  <script>
    alert('This inline script will be blocked by CSP.');
  </script>
</body>
</html>

External Script (Allowed)

Place this JavaScript code in a file named `external-script.js` and host it on the same domain as the HTML file.

// external-script.js
alert('This external script is allowed by CSP.');

Example HTML with External Script (Allowed)

This HTML file loads the `external-script.js` file, which is served from the same origin. Since the `script-src` directive in the CSP allows scripts from the same origin ('self'), this script will execute without any issues.

<!DOCTYPE html>
<html>
<head>
  <title>CSP Demo</title>
</head>
<body>
  <h1>CSP External Script Demo</h1>
  <script src="external-script.js"></script>
</body>
</html>

Concepts Behind the Snippet

CSP is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross-Site Scripting (XSS). XSS attacks are enabled when the web server allows user-supplied data to be included on the page without proper validation or escaping. CSP makes it more difficult for an attacker to inject malicious scripts into your website. By explicitly whitelisting the sources of content the browser should be allowed to load, you can significantly reduce the risk of XSS attacks. The key is to specify the `Content-Security-Policy` HTTP header on your web server.

Real-Life Use Case

Consider a social media platform where users can post comments. Without CSP, a malicious user could inject JavaScript code into a comment. This code could steal other users' cookies or perform actions on their behalf. By implementing CSP, the platform can prevent the execution of such injected scripts, as they would be considered inline or from an untrusted source. The platform admin sets CSP on the server to block execution from untrusted sources.

Best Practices

  • Start with a restrictive policy: Begin by only allowing content from your own domain (`'self'`).
  • Use a nonce or hash for inline scripts: If you must use inline scripts, use a cryptographic nonce ('nonce-value') or hash ('sha256-hash') to whitelist specific inline script blocks.
  • Monitor your CSP: Use the `report-uri` or `report-to` directives to collect information about CSP violations. This helps you fine-tune your policy.
  • Avoid `unsafe-inline` and `unsafe-eval`: These directives weaken your CSP and should be avoided unless absolutely necessary. They essentially disable the protection CSP offers against inline scripts and dynamic code execution.
  • Test thoroughly: Ensure your CSP doesn't break existing functionality. Test in a staging environment before deploying to production.

Interview Tip

When discussing CSP in an interview, emphasize your understanding of how it mitigates XSS attacks and your experience in configuring and testing CSP policies. Be prepared to discuss the various directives (e.g., `script-src`, `style-src`, `img-src`) and the trade-offs involved in choosing a restrictive vs. permissive policy. Mentioning the importance of monitoring CSP violations demonstrates a proactive approach to security.

When to Use CSP

CSP should be used on any website where security is a concern, particularly websites that handle sensitive user data or allow user-generated content. It's a fundamental security measure that should be implemented as part of a comprehensive security strategy. Even on static websites, CSP can provide a defense-in-depth against certain types of attacks.

Alternatives

While CSP is the most robust way to control resources, other methods to improve security include:

  • Input validation: Sanitize and validate all user input to prevent XSS.
  • Output encoding: Encode data before displaying it to prevent interpretation as code.
  • Regular security audits: Periodically assess your website's security posture.
CSP complements these techniques but should not be considered a replacement for them.

Pros

  • Mitigates XSS attacks: Significantly reduces the risk of XSS vulnerabilities.
  • Fine-grained control: Allows precise control over the sources of content allowed on your website.
  • Defense in depth: Adds an extra layer of security to your application.

Cons

  • Complexity: Configuring CSP can be complex and requires careful planning.
  • Potential for breakage: An overly restrictive CSP can break existing functionality.
  • Browser compatibility: While most modern browsers support CSP, older browsers may not.

FAQ

  • What is a nonce in CSP?

    A nonce is a cryptographically random number used to whitelist specific inline scripts. The server generates a unique nonce for each request and includes it in both the CSP header and the `nonce` attribute of the script tag. This ensures that only scripts with the correct nonce are allowed to execute.
  • How do I report CSP violations?

    Use the `report-uri` or `report-to` directives in your CSP header to specify an endpoint where the browser should send reports of CSP violations. The `report-uri` directive is deprecated, and `report-to` is the preferred method. You'll need to configure a server-side script to receive and process these reports.