Web Security: Clickjacking and Frame Busting Mitigation
One of the common web security questions that checks browser layout protection knowledge is:
What is a Clickjacking attack, and how do you protect your site from being loaded inside unauthorized iframes?
Clickjacking (UI Redress Attack) is a malicious technique where an attacker tricks a user into clicking on a hidden, transparent element of a trusted webpage that has been embedded inside an iframe on an untrusted page.
1. How Clickjacking Works
An attacker builds a malicious webpage (e.g. https://attacker-site.com) containing:
- An appealing button (e.g., "Win a Free iPhone").
- A completely transparent
<iframe>(CSS opacity:0) loading a victim webpage (e.g.,https://my-bank.com/transfer) positioned precisely on top of the "Win a Free iPhone" button.
When the user attempts to click "Win a Free iPhone", they are actually clicking the transparent "Submit Transfer" button on the bank page, executing transactions without their knowledge.
Attacker UI (Visible) Bank UI (Invisible Frame)
┌───────────────────────┐ ┌───────────────────────┐
│ WIN A FREE IPHONE │ ◄──────│ SUBMIT TRANSFER │
│ [ Click! ] │ │ [ Click! ] │
└───────────────────────┘ └───────────────────────┘2. Mitigation #1: CSP frame-ancestors (Recommended)
The modern, standard way to block unauthorized iframe embedding is using the Content Security Policy frame-ancestors directive:
- Block all embedding:
Content-Security-Policy: frame-ancestors 'none'; - Allow only the same origin:
Content-Security-Policy: frame-ancestors 'self'; - Allow specific trusted origins:
Content-Security-Policy: frame-ancestors 'self' https://trusted-partner.com;
3. Mitigation #2: X-Frame-Options Header
For older browsers that do not support CSP level 2, you should also send the legacy X-Frame-Options HTTP header:
DENY: The page cannot be displayed in a frame, regardless of the site attempting to do so.SAMEORIGIN: The page can only be displayed in a frame on the same origin as the page itself.
X-Frame-Options: SAMEORIGIN[!IMPORTANT] If a webpage sends both
Content-Security-Policywithframe-ancestorsandX-Frame-Options, modern browsers will prioritize the CSP directive and ignore the legacy header.
Key Takeaways
- UI Redress Attack: Clickjacking redresses the user interface using transparent iframes to steal click interactions.
- frame-ancestors rules: Use CSP
frame-ancestorsto restrict which domains can frame your application pages. - Avoid JS Frame Busting: Legacy JavaScript frame-busting scripts (e.g. checking
top !== self) are unreliable and can be bypassed by settingsandboxattributes on the parent iframe. - Set Headers Server-Side: Always emit security headers at the web server (e.g. Nginx, Vercel configs) or middleware level to ensure they cover all application paths.