Obfuscation

script nonce

Definition: Obfuscation-related term: script nonce.

Overview

A script nonce is a unique, randomly generated value used in HTML and JavaScript contexts to ensure that a script element executes only when it matches an expected value. It is primarily used in conjunction with Content Security Policy (CSP) to allow specific inline scripts to run while blocking others, thus enhancing security by mitigating the risk of cross-site scripting (XSS) attacks.

Developers use script nonces when they must include inline JavaScript within HTML documents, particularly in server-rendered applications. Instead of disabling CSP entirely or using unsafe-inline, which weakens security, a nonce allows fine-grained control over script execution. It is especially relevant in frameworks like React, Vue, or Angular when server-side rendering (SSR) is used and inline scripts are necessary for hydration or initial rendering.

script nonce developer glossary illustration

Why It Matters

Script nonces are critical for developers implementing CSP in production environments. They provide a secure mechanism to allow specific inline scripts to execute, thereby reducing the attack surface by preventing arbitrary script injection. Without nonces, CSP policies that disallow inline scripts can break functionality in applications that rely on inline JavaScript, forcing developers to choose between security and compatibility.

For maintainers, nonces ensure that only scripts explicitly permitted by the server-side policy are executed. This prevents attackers from injecting malicious code through user inputs, such as in reflected or stored XSS vulnerabilities. In web applications where CSP is enforced, nonces are a key part of the defense-in-depth strategy, particularly when combined with other security practices like input sanitization and secure headers.

How It Works

Script nonces function as a one-time token passed from the server to the client. The server generates a unique, unpredictable value and embeds it in both the CSP header and the corresponding <script> tag. The browser then validates that the script's nonce matches the expected value in the CSP policy before executing it.

  • The nonce is typically a Base64-encoded string generated by the server at runtime, ensuring unpredictability and uniqueness.
  • The CSP header must include a script-src directive with the 'nonce-' prefix followed by the generated value.
  • The <script> tag must have a nonce attribute set to the same value used in the CSP header.
  • Nonces are valid only for a single execution and must be regenerated for each new page load or script insertion.
  • Nonces are not supported in older browsers; they require modern browser support for CSP Level 2 or higher.

Quick Reference

ItemPurposeNotes
nonce attributeIdentifies a script block for CSP validationMust match value in CSP header
Content-Security-Policy headerEnforces CSP rules including script-srcMust include 'nonce-' prefix
Base64 encodingFormat for nonce valuesGenerated server-side, unpredictable
script-src directiveDefines allowed script sourcesSupports 'nonce-' for inline scripts
UniquenessEnsures one-time useReused nonces are invalid

Basic Example

This example demonstrates a basic use of a script nonce in an HTML document with a CSP header.

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'nonce-abc123';">
</head>
<body>
  <script nonce="abc123">
    console.log("This script runs because the nonce matches CSP.");
  </script>
</body>
</html>

The nonce attribute on the <script> tag matches the value in the CSP header. If the values do not match, the script will be blocked by the browser.

Production Example

This example shows how a server-side framework might generate and inject a nonce into an HTML document for a production application.

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'nonce-{{nonce}}';">
</head>
<body>
  <script nonce="{{nonce}}">
    window.__INITIAL_STATE__ = {{initialState}};
  </script>
</body>
</html>

This version is production-ready because it dynamically injects the nonce value from the server, ensuring each page load has a unique and secure token. It also prevents XSS by ensuring inline scripts only run if they are part of the expected server-rendered output.

Common Mistakes

  • Reusing nonces across multiple pages or script blocks, which allows attackers to inject scripts with previously valid nonces.
  • Using predictable or static nonces, which undermines their security purpose and makes them vulnerable to attack.
  • Not properly encoding nonces in CSP headers, leading to CSP bypasses or browser errors.
  • Forgetting to include the nonce in the CSP header when the script tag has a nonce attribute, causing script execution to fail.
  • Generating nonces client-side instead of server-side, which can lead to insecure or predictable values.

Security And Production Notes

  • Nonces must be generated server-side using a cryptographically secure random number generator to prevent predictability.
  • Each nonce should be used only once per page load; reusing a nonce invalidates its security.
  • Nonces are not supported in older browsers, so fallback strategies or feature detection may be required.
  • Nonces are most effective when used in combination with other CSP directives like script-src and unsafe-inline.
  • Incorrectly formatted or escaped nonces in CSP headers can lead to CSP violations or script blocking, affecting application functionality.

Related Concepts

Script nonces are closely related to several core web security and development concepts:

  • Content Security Policy (CSP): A security standard that allows developers to define which sources of content are allowed to be executed in a browser.
  • Inline script execution: Scripts embedded directly in HTML that bypass CSP unless explicitly allowed via a nonce or hash.
  • Server-side rendering (SSR): A technique where HTML is generated on the server, often requiring inline scripts for hydration or initial state.
  • Cross-site scripting (XSS): An attack vector that script nonces help defend against by limiting which scripts can execute.
  • Hydration: The process of attaching JavaScript to server-rendered HTML, often requiring inline scripts with nonces in frameworks like React or Vue.

Further Reading

Continue Exploring

More Obfuscation Terms

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