Preventing Clickjacking Attacks in JavaScript
Rigal Patel

Rigal Patel @rigalpatel001

About: Founder of Rumiante Software | Tech Visionary with 10+ years in Full-Stack Development | Expertise in JavaScript, React, Node.js, AWS | Committed to continuous learning and knowledge sharing

Location:
Surat
Joined:
Jan 17, 2019

Preventing Clickjacking Attacks in JavaScript

Publish Date: Jul 22 '24
56 6

Clickjacking, also known as UI redressing, is a type of attack where malicious actors trick users into clicking on something different from what they perceive by embedding web pages within iframes. This can lead to unauthorized actions and compromise user security. In this blog, we will explore how to prevent clickjacking attacks using JavaScript and server configurations for Apache and Nginx, along with user-friendly examples.

Understanding Clickjacking

Clickjacking involves placing a transparent or opaque iframe over a legitimate webpage element, causing users to unknowingly perform actions such as changing settings or transferring funds.

Real-World Example

Consider a scenario where an attacker embeds a hidden iframe from a banking site into a trusted webpage. When a user clicks on a seemingly harmless button, they might actually be authorizing a bank transaction.

Here’s an example of a vulnerable page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Clickjacking Example</title>
</head>
<body>
    <h1>Welcome to Our Site</h1>
    <button onclick="alert('Clicked!')">Click Me</button>
    <iframe src="https://example-bank.com/transfer" style="opacity:0; position:absolute; top:0; left:0; width:100%; height:100%;"></iframe>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

Preventing Clickjacking with JavaScript

To prevent clickjacking attacks, you can use JavaScript to ensure that your website is not being framed. Here’s a step-by-step guide on how to implement this protection:

1. JavaScript Frame Busting
Frame busting involves using JavaScript to detect if your website is loaded inside an iframe and breaking out of it.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Frame Busting Example</title>
    <script>
        if (window.top !== window.self) {
            window.top.location = window.self.location;
        }
    </script>
</head>
<body>
    <h1>Secure Site</h1>
    <p>This site is protected from clickjacking attacks.</p>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

In this example, the JavaScript checks if the current window (window.self) is not the topmost window (window.top). If it's not, it redirects the topmost window to the current window's URL, effectively breaking out of the iframe.

2. Enhanced Frame Busting with Event Listeners
You can further enhance your frame busting technique by using event listeners to continuously check if your page is framed.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Enhanced Frame Busting</title>
    <script>
        function preventClickjacking() {
            if (window.top !== window.self) {
                window.top.location = window.self.location;
            }
        }

        window.addEventListener('DOMContentLoaded', preventClickjacking);
        window.addEventListener('load', preventClickjacking);
        window.addEventListener('resize', preventClickjacking);
    </script>
</head>
<body>
    <h1>Secure Site</h1>
    <p>This site is protected from clickjacking attacks.</p>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

In this example, the preventClickjacking function is called on the DOMContentLoaded, load, and resize events to ensure continuous protection.

Server-Side Protection

While JavaScript methods are useful, implementing server-side protections provides an additional layer of security. Here’s how to set up HTTP headers in Apache and Nginx to prevent clickjacking:

1. X-Frame-Options Header
The X-Frame-Options header allows you to specify whether your site can be embedded in iframes. There are three options:

DENY: Prevents any domain from embedding your page.
SAMEORIGIN: Allows embedding only from the same origin.
ALLOW-FROM uri: Allows embedding from the specified URI.
Example:

X-Frame-Options: DENY
Enter fullscreen mode Exit fullscreen mode

Apache Configuration
Add this header to your server configuration:

# Apache
Header always set X-Frame-Options "DENY"
Enter fullscreen mode Exit fullscreen mode

Nginx Configuration
Add this header to your server configuration:

2. Content-Security-Policy (CSP) Frame Ancestors
CSP provides a more flexible approach through the frame-ancestors directive, which specifies valid parents that may embed the page using iframes.

Example:

Content-Security-Policy: frame-ancestors 'self'
Enter fullscreen mode Exit fullscreen mode

Apache Configuration
Add this header to your server configuration:

Example:

# Apache
Header always set Content-Security-Policy "frame-ancestors 'self'"

Enter fullscreen mode Exit fullscreen mode

Nginx Configuration
Add this header to your server configuration:

# Nginx
add_header Content-Security-Policy "frame-ancestors 'self'";

Enter fullscreen mode Exit fullscreen mode

Conclusion

Clickjacking is a serious threat to web security, but by implementing JavaScript frame busting techniques and server-side protections like X-Frame-Options and Content-Security-Policy headers, you can effectively safeguard your web applications. Use the examples provided to enhance your site’s security and provide a safer experience for your users.

Comments 6 total

  • Himanshu Sorathiya
    Himanshu Sorathiya Jul 22, 2024

    Great article about enhancing security, thanks for this

  • a.infosecflavour
    a.infosecflavourJul 22, 2024

    Very useful! 🌟

  • jake soine
    jake soineJul 23, 2024

    Learned this time

  • WTP | WhatThePortal.com
    WTP | WhatThePortal.comJul 23, 2024

    Decent recap of an age-old problem. This is also a big way folks try to utilize 3rd party cookies for setting/retrieving data outside the origin domain - like fingerprinting to track a user on a checkout screen from it's content source.

    If you had to allow 3rd party cookies and allow your site to be framed, what are some ways you'd suggest maintaining this security while allowing the functionality?

  • Michael Casile
    Michael CasileJul 24, 2024

    This is one of those articles I didn't know I needed to read ... until I read it. Thanks for this important info.

  • I miss U
    I miss UJul 24, 2024

    I think it is helpful for me.

Add comment