Skip to content
Tutorials Center
My learning

Topics

Lesson 113 of 122 ยท Accessibility and Best Practices

HTML Security: CSP, sandbox and Subresource Integrity

Harden your pages with HTML features: a Content-Security-Policy meta tag, the iframe sandbox attribute, Subresource Integrity hashes and rel=noopener on links.

Most security work happens on the server, but HTML has a few attributes that make a real difference. They limit what a page may load, restrict what embedded content may do, check that a downloaded file is the one you expected and stop a link you opened from reaching back into your page. None of them replaces careful server code, but each one shrinks the damage when something goes wrong.

Think of them as seatbelts. You hope you never need them, and you add them anyway. This lesson covers four: Content Security Policy, the iframe sandbox, Subresource Integrity and rel="noopener".

The problem they solve

The worst web attack is cross-site scripting (XSS): an attacker gets their own JavaScript to run inside your page, for example through a comment you forgot to escape. That script then has all of your page's powers. It can read what the visitor sees, send requests as the visitor and change what the page displays.

The first defense is always to escape user input (see HTML Entities). The tools below are the second line of defense, for the day the first one fails.

flowchart LR
  A["Untrusted input"] --> B["Escaping (first defense)"]
  B --> C["CSP blocks unexpected scripts"]
  C --> D["Sandbox limits embedded pages"]
  D --> E["SRI checks third-party files"]

Layers of defense: each one catches what the previous layer missed.

Content Security Policy (CSP)

A Content Security Policy is a list of rules that tells the browser where a page may load scripts, styles, images, fonts and frames from, and whether inline code may run. If an attacker injects a <script> that violates the rules, the browser refuses to run it.

The best way to deliver a policy is the Content-Security-Policy HTTP response header, set by your server. When you cannot change headers (static hosting, for example), you can put the policy in a <meta> tag:

HTML
<meta http-equiv="Content-Security-Policy"
      content="default-src 'self'; img-src 'self' https://images.example.com; script-src 'self'">

Each rule is a directive followed by allowed sources, separated by semicolons:

Directive Controls
default-src Fallback for everything not listed separately
script-src JavaScript files and inline scripts
style-src Stylesheets and inline styles
img-src Images
connect-src fetch, XHR and WebSocket targets
frame-src Which pages you may embed
base-uri Which values <base href> may have
form-action Where forms may submit

Source values are 'self' (your own origin), a host such as https://cdn.example.com, a scheme such as data:, 'none' (nothing allowed) and a few keywords. Quote the keywords exactly as shown, including the single quotes.

A policy with script-src 'self' has a powerful side effect: inline scripts and inline event handlers stop working, because injected code looks exactly like inline code. That is the point, but it means you move your JavaScript into files. If you really need an inline script, you can allow that one script with a random nonce that changes on every response:

HTML
<!-- Header: Content-Security-Policy: script-src 'nonce-r4nd0m123' -->
<script nonce="r4nd0m123">
  console.log("This inline script is allowed; injected ones have no nonce.");
</script>

The nonce must be unpredictable and generated per response, so it needs server support. A static meta tag cannot do that safely.

A <meta> policy only affects what comes after it in the document, so put it first in <head>. It also cannot use frame-ancestors, report-uri or sandbox; those work only as real headers.

The live example below sets a policy that allows no images at all, then tries to show one. A small listener reports the violation the browser detects.

A policy that blocks images

Remove the <meta> line and press Run again: the image loads and no violation appears.

Rolling out a policy safely

A strict policy can break your own site, so start in report-only mode. The Content-Security-Policy-Report-Only header logs violations without blocking anything. Fix what the reports show, then switch to enforcing. Browser DevTools also print every violation in the console, which makes local testing easy.

The iframe sandbox attribute

An <iframe> embeds another page (see Iframes). If you do not fully trust that page, add sandbox. With no value at all, it applies every restriction:

HTML
<iframe src="https://widgets.example.com/poll" sandbox title="Community poll"></iframe>

A fully sandboxed frame cannot run scripts, submit forms, open popups, use plugins, navigate the top page or access cookies and storage of its own origin. You then give back only the powers you need as space-separated tokens:

Token Gives back
allow-scripts Running JavaScript
allow-forms Submitting forms
allow-popups Opening new windows with window.open and target="_blank"
allow-modals alert, confirm and prompt
allow-same-origin Treating the content as its real origin instead of a unique, opaque one
allow-top-navigation Changing the URL of the page that contains the frame
allow-downloads Downloads started by the frame

Never combine allow-scripts and allow-same-origin for content from your own origin. The framed script can then reach into its own <iframe> element, delete the sandbox attribute and reload itself without any restrictions. The combination is only safe for content on a different origin than the page that embeds it.

The demo below embeds the same small page twice using srcdoc. The first frame is fully sandboxed, so its script never runs. The second has allow-scripts, so it runs and sends a message to this page.

Sandbox with and without scripts

Every live example in this course runs in a sandbox like frame 2, without allow-same-origin. That is why a TryIt cannot read our cookies, even though you can run any code in it.

Subresource Integrity (SRI)

When you load a library from a CDN, you trust that server completely. If it is hacked, every site using that file runs the attacker's code. Subresource Integrity lets you pin the exact content you expect: you add a cryptographic hash, and the browser refuses the file if its hash differs.

HTML
<script src="https://cdn.example.com/lib/widget-2.4.1.min.js"
        integrity="sha384-tdnWtBkj5+038HkeFOzlN0GdBuwDpXaWFs1Dhs560d67HmXunuEg4R3e+iEGk0Ho"
        crossorigin="anonymous"></script>
  • integrity holds the algorithm (sha256, sha384 or sha512), a hyphen and the base64 hash. Several space-separated hashes are allowed.
  • crossorigin="anonymous" is required for files from another origin, so the browser can read the bytes it needs to hash.
  • It works on <script> and on <link rel="stylesheet"> (and rel="preload" and modulepreload).

You can compute a hash in a terminal with openssl dgst -sha384 -binary file.js | openssl base64 -A, or with a build tool. Always pin an exact version in the URL: a latest URL changes, and the hash would then fail.

sequenceDiagram
  participant B as Browser
  participant C as CDN
  B->>C: GET widget-2.4.1.min.js
  C-->>B: File bytes
  B->>B: Hash the bytes, compare with integrity
  alt hashes match
    B->>B: Run the script
  else hashes differ
    B->>B: Block it and log an error
  end

SRI: the browser compares the downloaded file's hash with the one in your HTML before using it.

The code below shows the hashing idea in plain JavaScript. Secure-context rules in the preview may block crypto.subtle, so the example catches that case.

Hashing a file the way SRI does

If the hash is shown, it equals the value used in the earlier <script> example. Change one character in the text and the whole hash changes. That sensitivity is exactly what makes SRI work.

A link that opens a new tab (target="_blank") used to give the new page a reference to yours through window.opener. A malicious page could use it to redirect your tab to a fake login page. See Link Targets for the basics.

Modern browsers now treat target="_blank" as if rel="noopener" were set, so the risk is much smaller. Writing it explicitly is still good practice, because it documents your intent and protects visitors on old browsers:

HTML
<a href="https://partner.example.com" target="_blank" rel="noopener">Our partner</a>
<a href="https://other.example.com" target="_blank" rel="noopener noreferrer">Private link</a>
  • noopener cuts the window.opener connection.
  • noreferrer also stops the browser from sending the Referer header, which tells the destination which page the visitor came from. It implies noopener.
  • For links in user-submitted content, also add nofollow ugc so search engines do not treat them as your endorsement.

Other small habits

  • Escape on output, not just on input, for every context (HTML text, attributes, URLs, JavaScript).
  • Use HTTPS everywhere. A page on HTTPS that loads a script over HTTP can have that script swapped by anyone on the network.
  • Add autocomplete="current-password" and the right type to password fields so password managers work (see Forms).
  • Treat <meta> tags as hints, not secrets: anyone can read your HTML source.
  • Keep a short list of third-party scripts. Each one runs with the full power of your page.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a policy with script-src 'self' do to an inline script that an attacker injects?

    Without a nonce or hash, inline script code does not match 'self', so the browser refuses to run it. That is how CSP limits the damage of XSS.
  2. 2. Which iframe sandbox combination is dangerous for content from your own origin?

    With both tokens, the framed script can remove its own sandbox attribute and reload without restrictions.
  3. 3. Why does an integrity attribute on a CDN script also need crossorigin="anonymous"?

    Cross-origin responses are opaque unless fetched with CORS. The browser needs the actual bytes to verify the hash.
  4. 4. What does rel="noreferrer" do beyond what rel="noopener" does?

    noreferrer implies noopener and additionally hides which page the visitor came from.

Summary

  • Escape untrusted data first; use CSP, sandboxing and SRI as extra layers.
  • A Content Security Policy lists allowed sources per resource type. Prefer the HTTP header; a <meta> tag works for the basics. Start with report-only mode.
  • script-src 'self' blocks inline scripts, so move code into files or use a per-response nonce.
  • <iframe sandbox> removes powers; add them back with tokens. Never pair allow-scripts with allow-same-origin for your own content.
  • integrity plus crossorigin="anonymous" makes the browser reject a changed third-party file.
  • Add rel="noopener" (or noopener noreferrer) to links that open new tabs.

Next, learn how HTML works in a very different environment in HTML Email Basics.