Shield Your Website Against Clickjacking Attacks
Published: 2023-11-21 10:01:16

by [Barbara Odozi](https://blog.openreplay.com/authors/barbara-odozi)


<blockquote><em>
In the interconnected world of the internet, where websites and web applications handle a lot of user interactions, we cannot overlook the importance of security. Clickjacking stands as a security threat, often overlooked, and has the potential to wreak havoc on website developers, owners, and unsuspecting users. This article will teach you about clickjacking, its potential for attacking websites and web applications directly from the UI, and the proven strategies to safeguard against falling victim to this deceptive attack.
</em></blockquote>


<div style="background-color:#efefef; border-radius:8px; padding:10px; display:block;">
<hr/>
<h3><em>Session Replay for Developers</em></h3> 
<p><em>Uncover frustrations, understand bugs and fix slowdowns like never before with <strong><a href="https://github.com/openreplay/openreplay" target="_blank">OpenReplay</a></strong> — an open-source session replay suite for developers. It can be <strong>self-hosted</strong> in minutes, giving you complete control over your customer data.</em></p>
<img alt="OpenReplay" style="margin-top:5px; margin-bottom:5px;" width="768" height="400" src="https://raw.githubusercontent.com/openreplay/openreplay/main/static/openreplay-git-hero.svg" class="astro-UXNKDZ4E" loading="lazy" decoding="async">
<p><em>Happy debugging! <a href="https://openreplay.com" target="_blank">Try using OpenReplay today.</a></em><p>
<hr/>
</div>

Clickjacking, also referred to as a User Interface(UI) redress attack, is a deceptive technique employed by malicious actors to manipulate user interactions on websites or web applications. 

It relies on multiple layers, transparent or opaque, to trick users into clicking on a button or link on one web page while intending to interact with the top-level page.

## Understanding Clickjacking
Clickjacking is concerning because it operates unnoticed by users, taking advantage of the trust people place in web interfaces to manipulate their actions. This manipulation can lead to people unknowingly doing harmful things, which is extremely dangerous.

Have you ever innocently clicked on a social media Like or Download button, only to find yourself unwittingly sharing sensitive information or performing actions you never intended?

These hidden actions, triggered by harmless clicks, unlock problems like data breaches, identity theft, financial losses, insidious malware infections, and damage to your reputation. 

As such, it is of utmost importance for website developers and owners to be aware of this technique and take proactive steps in safeguarding their digital domains.

### Here are some notable cases that demonstrate the impact of clickjacking
In 2010, Facebook fell victim to a likejacking attack that exploited the Like button of the social media platform. 

A malicious link was hidden under the button, tricking users into endorsing and sharing questionable content on their profiles. This attack tarnished its reputation and highlighted the severe consequences of clickjacking.

In the same year, Twitter also suffered a clickjacking attack that tricked users into retweeting messages they had no intention to share, leaving users confused and putting the integrity of shared content at risk.

More recently, in 2015, attackers placed fake install buttons over Adobe Flash Player updates on legitimate websites and unsuspecting users, hoping to keep their software secure, downloaded malware.

These real-life examples remind us of the risks posed by clickjacking and highlight the potential harm from inadequate defenses if not implemented.

Now we know how dangerous clickjacking is, let us dive deeper into how it works to understand it better.

## Mechanism of Clickjacking
Clickjacking occurs through various methods like exploitation of User Interface (UI) components, iframes, and Cascading Style Sheets ([CSS](https:/https://developer.mozilla.org/en-US/docs/Web/CSS/)).

### Method 1: Exploiting UI Components
In this method, attackers manipulate visible components like buttons, links, and forms that users interact with on a website, overlaying these components with hidden elements or making them transparent.

This manipulation triggers unintended actions when clicked; for instance, they might place a fake login button over a genuine one, leading users to share private information instead of logging in.

### Method 2: Exploiting iframes
In the second method, attackers exploit `iframes`—windows within a webpage that load content from other websites. They (attackers) position a target website inside an `iframe` in a manner that tricks users into interacting with the host website. 

For instance, a malicious site may load your online banking page in an `iframe` and deceive you into entering your credentials on the malicious site.

### Method 3: Exploiting CSS
This method exploits CSS, which controls the layout and appearance of web elements. Attackers use CSS to create transparent overlays, move them off-screen, or resize them to hide a Like button on a social media site, leading users to click a hidden Share button instead.


<CTA_Middle_Security />



## Mitigation Strategies
To effectively defend against clickjacking, it is crucial to employ robust defense mechanisms. Various techniques can be used individually or in combination to ensure comprehensive protection. They include:

### Frame busting
Frame busting, also known as frame-breaking, is a technique that prevents a web page from being displayed within an iframe on another website. It involves implementing a [JavaScript](https:/https://developer.mozilla.org/en-US/docs/Web/JavaScript/) code that detects whether a web page is being framed and takes appropriate action to break out of the frame. You can easily integrate this into your web application or website by adding a script to your [HTML](https:/https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/HTML_basics/) or JavaScript file.

**Implementation steps:**
1. Create a simple HTML page in your code editor.
2. Add the following script to your file.


```html
<html>
  <head>
    <style id="antiClickjack">
      body {
        display: none !important;
      }
    </style>
  </head>
  <body>
    <h1>This is your web page content</h1>
    <script type="text/javascript" id="antiClickjackJS">
      if (self === top) {
        var antiClickjack = document.getElementById('antiClickjack');
        antiClickjack.parentNode.removeChild(antiClickjack);
      } else {
        top.location = self.location;
      }
    </script>
  </body>
</html>
```

The code above is effective when used correctly. The CSS code hides the entire body of the page by setting its `display` property to `none`, making the page invisible if loaded within an iframe. Meanwhile, the JavaScript code checks whether the current browser window is the top-level window `(self === top)`. If it is, indicating the page is not in an iframe, it removes the applied CSS that hides the body. If it's not the top-level window(i.e., `iframe`), it attempts to redirect the top-level window to the `iframe`'s location, breaking out of it.

***Note:*** Be sure to host the first web page created to proceed with testing out.

3. Test it out by creating another HTML file to embed the first web page you created. You can choose any name for the file; I named mine `test.html`. After that, add the following code and the link to the hosted web page.

```html
<html>
  <body>
    <iframe src="https://demo-article.vercel.app" width="500" height="500"></iframe>
  </body>
</html>
```

4. Open the HTML file in your browser. You will notice that you cannot view the first web page we created and hosted.

The script tries to break out of the `iframe` by redirecting or reloading itself in the top window. However, some browsers may block this automatic reloading, reducing its effectiveness. To ensure comprehensive coverage, combine this method with X-frame Options and Content Security Policy directives, as mentioned earlier.

To ensure comprehensive coverage, combine this method with X-frame Options and Content Security Policy directives, as mentioned earlier.

### X-Frame-Options HTTP header
The HTTP header also plays a vital role in preventing click-jacking attacks by controlling the embedding of web pages within `frame`,  `iframe`, `embed`, or `object`. While some directives like `ALLOW-FROM uri` lack support in widely used browsers such as Chrome and Safari, it is best to use the `SAMEORIGIN` directive.

**Note:** X-Frame-Options only work when set through the HTTP header, not within the `meta` element.

You can set the X-Frame Options header like this:

```javascript
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;

// Routes & Middleware

// Set X-Frame-Options header to 'same-origin' for all responses
app.use((req, res, next) => {
  res.setHeader('X-Frame-Options', 'sameorigin');
  next();
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});
```

This restriction makes it difficult for an attacker to capture the user clicks by blocking the `iframe` content.

### Content Security Policy
Another standard approach to prevent clickjacking attacks is to use specific Content Security Policy (CSP) directives. When you implement the Content-Security-Policy header with the frame-ancestors directive, you achieve greater control over the origins allowed to frame your content, as opposed to using the X-Frame-Options header. This approach provides a more fine-grained level of control, significantly enhancing your web application security.

```javascript
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;

// Define your routes and middleware next

// Set X-Frame-Options header to 'same-origin' for all responses
app.use((req, res, next) => {
  res.setHeader('X-Frame-Options', 'sameorigin');
  next();
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});
```

The content-Security-Policy header contains alternative values to control `iframe` embedding, such as `frame-ancestors-none`, which prevents any attempt to include the page in a frame.

### Conclusion
As a website owner, prioritize website protection practices to enhance security for yourself and your users against clickjacking attacks and learn how to identify potentially malicious pages. Also, conduct routine security audits and penetration testing to identify and mitigate vulnerabilities, including clickjacking threats.

Remember that security is not the sole responsibility of back-end engineers; vulnerabilities also exist in the front-end. Therefore, a collaboration between front-end and back-end engineers is essential to establish a robust defense against clickjacking. This shared responsibility highlights the importance of safeguarding the digital world and ensuring a safer online experience for all users.

### Additional Resources
For more on clickjacking prevention and web security, check these articles out:

* [Clickjacking (Wikipedia)](https://en.wikipedia.org/wiki/Clickjacking)
* [OWASP Clickjacking Defense Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Clickjacking_Defense_Cheat_Sheet.html)
* [Mozilla Developer Network: Content Security Policy (CSP)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)
* [The Ultimate Guide to Web Security](https://www.example.com/web-security-guide)

Until next time, **ciao!!!**