Obfuscation

CSP nonce

Definition: Obfuscation-related term: CSP nonce.

Overview

A CSP nonce (number used once) is a unique, randomly generated value used in Content Security Policy (CSP) directives to allow specific inline scripts or styles to execute while maintaining overall security. It is a critical component of CSP's script-src and style-src directives, enabling dynamic or generated content to bypass the policy's restrictions without compromising security.

Developers typically use CSP nonces when inline JavaScript or CSS is required for dynamic behavior or templating. The nonce ensures that only scripts or styles with the correct, one-time value are allowed to run, even if they are inline. This is especially useful in environments where CSP is enforced but dynamic content generation makes it difficult to pre-define all allowed sources.

CSP nonce developer glossary illustration

Why It Matters

CSP nonces provide a secure middle ground for developers who need to use inline scripts or styles. They prevent attackers from injecting malicious code through inline script tags, as the attacker cannot predict or replicate the nonce value. Without nonces, enforcing CSP with strict script-src or style-src policies would make inline code impossible, which is often necessary for modern web applications.

In production, nonces are essential for balancing security and flexibility. They are particularly critical in applications that rely on server-side rendering or dynamic template injection, where inline code is unavoidable. If nonces are improperly implemented or omitted, CSP enforcement can be bypassed, exposing the application to script injection vulnerabilities.

How It Works

CSP nonces function by generating a unique, unpredictable value for each HTTP response and embedding it into both the CSP header and the corresponding inline script or style tag. The browser checks that the value in the policy matches the value in the tag before allowing execution.

  • The nonce is a base64-encoded string generated per HTTP response and must be unpredictable to prevent attackers from guessing or reusing it.
  • The value must be included in both the CSP header and the inline script or style tag as a nonce attribute.
  • Nonces are only valid for a single HTTP response and must not be reused across requests.
  • Nonces are supported in both script-src and style-src CSP directives.
  • If a nonce is used in a CSP directive but not in the corresponding inline tag, or vice versa, the browser blocks the script or style.

Quick Reference

ItemPurposeNotes
nonce attributeIdentifies inline script or style for CSP validationMust match value in CSP header
CSP header directiveDefines allowed sources including noncesUses 'nonce-' prefix
Base64 encodingFormat of the nonce valueMust be securely random
Per-response generationNonce is unique per HTTP requestReused nonces are insecure
Inline script/styleExecutes only if nonce matchesEnables dynamic content

Basic Example

This example shows a basic CSP nonce implementation in an HTML response. The server generates a nonce and includes it in both the CSP header and an inline script.

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'nonce-abc123';">
</head>
<body>
  <script nonce="abc123">
    console.log('Secure inline script');
  </script>
</body>
</html>

The nonce="abc123" in the script tag must match the value in the CSP header. The header script-src 'self' 'nonce-abc123' allows scripts from the same origin and those with the matching nonce.

Production Example

This example demonstrates a secure, production-ready nonce implementation in a Node.js server using Express. The server generates a unique nonce for each request and injects it into the CSP header and template.

const express = require('express');
const crypto = require('crypto');
const app = express();

app.use((req, res, next) => {
  const nonce = crypto.randomBytes(16).toString('base64');
  res.locals.nonce = nonce;
  next();
});

app.get('/', (req, res) => {
  const nonce = res.locals.nonce;
  res.send(`
    <html>
    <head>
      <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'nonce-${nonce}';">
    </head>
    <body>
      <script nonce="${nonce}">
        console.log('Dynamic script with nonce');
      </script>
    </body>
    </html>
  `);
});

app.listen(3000);

This version ensures that each request has a unique, secure nonce. The server generates a new nonce per request and injects it into both the CSP header and the inline script, preventing reuse and mitigating injection risks.

Common Mistakes

  • Reusing nonces across multiple requests. This breaks the one-time nature of nonces and makes CSP enforcement ineffective.
  • Using predictable or static nonces. An attacker can guess or reproduce the value, undermining security.
  • Forgetting to include the nonce in the CSP header or inline tag. The browser blocks execution if the values do not match.
  • Using nonces with unsafe-inline in the CSP policy. This negates the purpose of nonces and reduces security.
  • Generating nonces on the client side. Nonces must be generated server-side to ensure unpredictability and security.

Security And Production Notes

  • Always generate nonces using a cryptographically secure random number generator to ensure unpredictability.
  • Never reuse nonces across HTTP requests; each nonce must be unique per response.
  • Nonces are only effective when used with strict CSP policies and not mixed with unsafe-inline.
  • Ensure that the nonce value is correctly encoded and injected into both the CSP header and inline tags.
  • Nonces do not protect against all types of vulnerabilities; they are part of a layered security strategy.

Related Concepts

CSP nonces are closely related to several web security concepts. They work in conjunction with Content Security Policy (CSP) to restrict script execution, similar to how CSP directives like script-src and style-src define allowed sources. They also connect to secure coding practices like avoiding inline scripts and using secure headers. Additionally, nonces are used alongside other obfuscation and sandboxing techniques to reduce attack surface. Finally, they are part of the broader ecosystem of CSP features such as report-uri and report-to, which help monitor policy compliance.

Further Reading

Continue Exploring

More Obfuscation Terms

Browse the full topic index or move directly into related glossary entries.