EthicsComputerCourses
Join training +91 90532 10052

Clickjacking Protection

HTML · Lesson 170 of 234 Advanced 11 min read Updated

By the end of this lesson you will be able to explain how a clickjacking attack works, build a harmless demo of one on your own page, protect a real site with the right response headers in PHP, Node.js and Apache, and check that the protection really works.

What you should know first: Same-Origin Policy, Secure Iframes & Sandbox Attributes, which compared X-Frame-Options and frame-ancestors in a short table, and Content Security Policy (CSP). This lesson builds on that table and adds the attack itself, the reasons old fixes fail, and testing.

How clickjacking works

Clickjacking (also called a UI redress attack) tricks a visitor into clicking something on your page while they think they are clicking something on the attacker's page. The attacker:

  1. Builds a page with bait, such as "Claim your free IPL ticket".
  2. Loads your real page, for example a bank transfer or "delete account" screen, in an <iframe>.
  3. Makes the frame invisible with opacity: 0 and places it exactly on top of the bait button.
  4. Waits. The visitor clicks the bait, but the click goes to your button underneath the glass.

Think of carbon paper. You sign what looks like a birthday card for a friend in Lucknow, but a cheque is hidden under it, and your signature goes through to the cheque.

Why does this work? The visitor is already logged in to your site, so the framed page loads with their session cookie and shows their real account. The same-origin policy stops the attacker's script from reading the frame, but it does not stop the user from clicking it. Variants exist for likes and follows, camera permission prompts, and even dragging text into a framed form.

Step 1: a harmless demo on your own page

This demo frames a page built right here in the editor, so nothing outside it is ever loaded. Leave the slider at 0 and click Claim my ticket. Then raise the slider to see what was really under your mouse.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Clickjacking demo on your own page</title>
  <style>
    body { font-family: sans-serif; padding: 1rem; }
    .stage { position: relative; inline-size: 20rem; block-size: 9rem; border: 2px dashed #999; }
    .bait { position: absolute; inset-block-start: 4.5rem; inset-inline-start: 2rem;
            padding: 0.6rem 1rem; background: #2e7d32; color: white; border: 0; font-size: 1rem; }
    #victim { position: absolute; inset: 0; inline-size: 100%; block-size: 100%; border: 0; opacity: 0; }
  </style>
</head>
<body>
  <label for="see">Frame opacity (0 = invisible):</label>
  <input id="see" type="range" min="0" max="1" step="0.1" value="0">
  <div class="stage">
    <p>&nbsp;Win a free IPL ticket!</p>
    <button class="bait" id="bait">Claim my ticket</button>
    <iframe id="victim" title="My account page" sandbox="allow-scripts"></iframe>
  </div>
  <ol id="log"></ol>
  <script>
    const victim = document.querySelector("#victim");
    // Your OWN account page, built here so nothing outside this demo is framed.
    victim.srcdoc = `<body style="margin:0;font-family:sans-serif;background:#fff">
      <p style="margin:0.5rem">Rohan's account</p>
      <button id="del" style="margin:2.6rem 0 0 2rem;padding:0.6rem 1rem;font-size:1rem">Delete my account</button>
      <script>
        document.getElementById("del").addEventListener("click", () =>
          parent.postMessage("Delete my account was clicked inside the frame", "*"));
      <\/script></body>`;

    function note(text) {
      const li = document.createElement("li");
      li.textContent = text;
      document.querySelector("#log").append(li);
    }
    document.querySelector("#bait").addEventListener("click", () => note("The bait button got the click"));
    window.addEventListener("message", (event) => {
      if (event.source === victim.contentWindow) note(event.data);
    });
    document.querySelector("#see").addEventListener("input", (event) => {
      victim.style.opacity = event.target.value;
    });
  </script>
</body>
</html>

What you should see: after the click, the list says Delete my account was clicked inside the frame. The line "The bait button got the click" never appears, because the frame sits on top and catches every click. At opacity 0.5 you can see the "Delete my account" button sitting exactly over the green button.

The fix: say who may frame you

The page cannot detect the trick reliably by itself, so the defence must come from the server, as an HTTP response header. The browser reads it before showing the page inside a frame, and refuses if the framing page is not allowed.

CSP frame-ancestors (the modern way)

The frame-ancestors directive of Content Security Policy lists who may embed your page:

ValueWho may frame the page
frame-ancestors 'none'Nobody
frame-ancestors 'self'Only pages from your own origin
frame-ancestors 'self' https://partner.example.inYour origin and that partner
frame-ancestors https:Any HTTPS site (rarely what you want)

It checks every ancestor in the chain, not only the direct parent, so an attacker cannot hide your page inside a frame inside a frame. It works only as a response header. In a <meta> tag it is ignored, and Chrome 157 says so in the Console: The Content Security Policy directive 'frame-ancestors' is ignored when delivered via a <meta> element.

X-Frame-Options (the older header)

Before CSP existed, browsers added X-Frame-Options with two useful values: DENY (nobody) and SAMEORIGIN (your own origin). A third value, ALLOW-FROM uri, was never widely supported and modern browsers ignore it; use frame-ancestors to allow a partner. When a response has both headers, browsers that understand frame-ancestors follow it and ignore X-Frame-Options. Sending both costs nothing and covers very old browsers, as long as the two say the same thing.

Setting the headers

Here is an account page in PHP that nobody may frame, with a login cookie that also helps (more on SameSite below):

PHP
<?php
declare(strict_types=1);

// Nobody may frame this page, not even our own site.
header("Content-Security-Policy: frame-ancestors 'none'");
header('X-Frame-Options: DENY');   // for very old browsers

// The login cookie is not sent when another site frames or posts to us.
setcookie('session_id', bin2hex(random_bytes(16)), [
    'path' => '/',
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Lax',
]);

Run with PHP 8.4's built-in server and checked with curl -s -I http://127.0.0.1:8474/account.php | grep -i "^HTTP\|^content-security\|^x-frame\|^set-cookie" (the session value is random, so yours will differ):

Output
HTTP/1.1 200 OK
Content-Security-Policy: frame-ancestors 'none'
X-Frame-Options: DENY
Set-Cookie: session_id=654c4f700c813e0c473dc90ffcd2939c; path=/; secure; HttpOnly; SameSite=Lax

If your site already sends a CSP, add frame-ancestors to that same header instead of sending a second one. In Node.js, set the headers before the body:

JavaScript
res.setHeader("Content-Security-Policy", "frame-ancestors 'self'");
res.setHeader("X-Frame-Options", "SAMEORIGIN");

For a whole Apache site, put this in .htaccess (needs mod_headers). It was tested on Apache 2.4 from XAMPP, and curl -I showed both headers on every page in the folder:

Text
<IfModule mod_headers.c>
    Header always set Content-Security-Policy "frame-ancestors 'none'"
    Header always set X-Frame-Options "DENY"
</IfModule>

When a page with frame-ancestors 'none' is framed by another site, the frame shows a browser error page instead of your content, and Chrome 157 explains in the Console (tested with a local server): Framing '...' violates the following Content Security Policy directive: "frame-ancestors 'none'". The request has been blocked.

Which pages need it

The simplest safe rule is: send frame-ancestors 'self' (or 'none') on every page, then make exceptions on purpose.

  • Logged-in pages, settings, payment, admin panels and anything with a "confirm" button: 'none' or 'self'.
  • A page you want embedded, such as a public "Book a table" widget for partner restaurant sites in Jaipur: list those partners, and keep risky actions out of the widget itself.
  • Pages that frame your own other pages, such as a dashboard that embeds a report: 'self'.

Frame-busting scripts (legacy)

Before these headers, sites tried to escape frames with JavaScript, often if (top !== self) top.location = self.location;. You will still find this in old code. It fails against a modern attacker, who can wrap your page in a sandbox frame.

Step 2: watch a frame-buster fail

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Why frame-busting scripts fail</title>
  <style>
    body { font-family: sans-serif; padding: 1rem; }
    iframe { inline-size: 22rem; block-size: 7rem; border: 1px solid #999; display: block; margin-block-end: 0.5rem; }
  </style>
</head>
<body>
  <p>The same "protected" page, framed in two ways an attacker could choose:</p>
  <iframe id="scripts" title="Framed with sandbox allow-scripts" sandbox="allow-scripts"></iframe>
  <iframe id="noscripts" title="Framed with an empty sandbox" sandbox=""></iframe>
  <script>
    // Old-style defence inside the page: "if I am framed, take over the whole tab".
    const protectedPage = `<body style="font-family:sans-serif">
      <p>Transfer &#8377;5,000 to Farhan? <button>Confirm</button></p>
      <p id="status">Frame-buster has not run.</p>
      <script>
        const status = document.getElementById("status");
        if (top !== self) {
          try {
            top.location = self.location.href;
            status.textContent = "Frame-buster worked.";
          } catch (error) {
            status.textContent = "Frame-buster failed: " + error.name;
          }
        }
      <\/script></body>`;
    document.querySelector("#scripts").srcdoc = protectedPage;
    document.querySelector("#noscripts").srcdoc = protectedPage;
  </script>
</body>
</html>

The first frame allows scripts but not top-level navigation, so the buster runs and fails with SecurityError. Chrome's full message ends with The current window does not have permission to navigate the target frame to 'about:srcdoc'. The second frame has an empty sandbox, so the buster never runs at all. In both frames the Confirm button is still there to be clicked.

SameSite cookies: the extra layer

A page loaded inside a frame on another site makes a cross-site request. A cookie with SameSite=Lax or SameSite=Strict is not sent with cross-site frame requests. So even if a page forgot its header, the attacker's frame would show your site logged out, with nothing worth clicking.

  • Strict: never sent from another site, not even when the visitor follows a link to you.
  • Lax: sent when the visitor follows a normal link to you, but not in cross-site frames, images or POST forms. A good default for login cookies.
  • None: always sent; it must also have Secure. Use it only for cookies that really must work in cross-site frames.

Chromium browsers treat a cookie with no SameSite attribute as Lax, but not every browser does, so always set it yourself. Remember that SameSite compares sites, not origins: an attacker page on another subdomain of your own site is same-site, so the cookie is sent. The headers are still your main defence.

Testing your headers

  1. From the terminal: curl -s -I https://your-site.example.in/account | grep -i "frame" should show your Content-Security-Policy with frame-ancestors and your X-Frame-Options.
  2. In DevTools: open the Network panel, click the page request and read its Response Headers.
  3. With a frame test on your own machine: make a local HTML file containing <iframe src="https://your-site.example.in/account"></iframe> and open it. Only test sites you own or are allowed to test. You should see an error page in the frame and a framing message in the Console.
  4. With a header scanner: Mozilla's HTTP Observatory, now part of MDN, grades security headers, including framing protection.

Test every kind of page: home, login, account, checkout and error pages. A missing header on a single form page is all an attacker needs.

Common mistakes

  • Putting frame-ancestors in a <meta> tag. It is ignored; send it as a header.
  • Using X-Frame-Options: ALLOW-FROM. Modern browsers ignore it; use frame-ancestors.
  • Protecting only the home page. Attackers frame the page with the dangerous button.
  • Relying on a frame-busting script. A sandbox attribute defeats it.
  • Sending SameSite=None for the login cookie "to be safe". It makes framed attacks easier.
  • Two CSP headers that disagree. Merge frame-ancestors into your existing policy.

Interview questions

1. What is clickjacking?

It is an attack where your real page is loaded inside an invisible frame on the attacker's page, placed over a bait button. The victim thinks they click the bait but actually clicks a button on your page, using their own logged-in session. It needs no script access to your page, so the same-origin policy does not stop it.

2. How do you prevent clickjacking?

Send the Content-Security-Policy: frame-ancestors response header with 'none', 'self' or a list of trusted origins. Also send X-Frame-Options: DENY or SAMEORIGIN for old browsers. Set login cookies with SameSite=Lax or Strict as an extra layer.

3. Why can't frame-ancestors be set with a meta tag?

The browser must decide whether to show a framed page before it has parsed that page's HTML, and a meta tag could also be injected or arrive too late. The CSP specification therefore ignores frame-ancestors, report-uri and sandbox in meta tags. Only the response header counts.

4. Why do JavaScript frame-busters fail?

The attacker controls the frame. With sandbox="allow-scripts", the script runs but cannot navigate the top window; with an empty sandbox, the script never runs. Headers are enforced by the browser before the page appears, so the attacker cannot switch them off.

5. What is wrong with X-Frame-Options: ALLOW-FROM https://partner.example.in?

ALLOW-FROM was never supported by Chrome or Safari and is obsolete, so those browsers ignore the header and the page can be framed by anyone. Use Content-Security-Policy: frame-ancestors https://partner.example.in instead, which also allows several partners.

Key points

  • Clickjacking hides your logged-in page in a transparent frame and steals the visitor's clicks.
  • The fix is a response header: Content-Security-Policy: frame-ancestors 'none' or 'self' or a list of partners.
  • X-Frame-Options: DENY or SAMEORIGIN covers very old browsers; ALLOW-FROM is obsolete.
  • frame-ancestors in a <meta> tag is ignored, and frame-busting scripts are defeated by sandbox.
  • SameSite=Lax or Strict login cookies make framed pages appear logged out.
  • Test every page type with curl -I, DevTools and a local framing test of your own site.

Exercise

Isha runs an online fee-payment portal for a school in Kochi. The payment page /pay has a "Pay ₹12,500" button. The school's news site https://news.school.example.in must be able to embed the public /timetable page, but nobody should frame anything else. The login cookie is set with setcookie('sid', $id). Write the PHP for /pay and for /timetable, fix the cookie, and list the commands and checks Isha should use to confirm the protection.

Show solution

For /pay (and every other page by default):

PHP
<?php
declare(strict_types=1);

header("Content-Security-Policy: frame-ancestors 'none'");
header('X-Frame-Options: DENY');
// $id is the session id created when the user logs in
setcookie('sid', $id, ['path' => '/', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax']);

For /timetable, only the news site may frame it:

PHP
<?php
declare(strict_types=1);

header("Content-Security-Policy: frame-ancestors 'self' https://news.school.example.in");

No X-Frame-Options is sent for the timetable, because ALLOW-FROM is obsolete and SAMEORIGIN would block the news site in old browsers. To check, Isha runs curl -s -I https://fees.school.example.in/pay | grep -i frame, reads the response headers in DevTools, and opens a local test file that frames /pay (it must show an error page) and /timetable from the news site (it must load).

Quick Quiz

1. What makes a clickjacking attack possible?

2. Which header stops every site, including your own, from framing a page?

3. Where does frame-ancestors work?

4. Why does if (top !== self) top.location = self.location not protect you?

Learn HTML with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call