myHotTake

Tag: prevent XSS attacks

  • How Do You Detect and Prevent DOM-Based XSS Attacks?

    Hey there, if you find this story intriguing or helpful, feel free to give it a like or share it with your fellow tech enthusiasts!


    I’m a researcher in an old library. This library is unlike any other; it’s filled with not just books, but portals that transport me into the stories themselves. Each portal represents a webpage, and I’m on a quest to uncover the secrets of DOM-based XSS attacks, which are like mischievous imps hiding in the pages.

    As I wander through the library, I realize that these imps don’t come from outside the library; instead, they’re sneakily embedded within the pages of the books themselves, waiting for an unsuspecting reader to activate them. I need to be vigilant to detect these imps before they cause chaos. I begin by carefully examining each portal’s frame. If I notice any text that seems out of place or too eager to escape the page, I know I’ve found an imp.

    To prevent them from wreaking havoc, I decide to fortify the portals. I start by ensuring that the library’s quills—akin to JavaScript functions—are sanitized. This means I’m scrubbing them clean of any impish influence before they interact with the portals. I avoid directly inserting any untrusted text I find into the portals, preferring instead to pass it through a rigorous cleansing process.

    Next, I enchant the portals with spells that limit their power, known as Content Security Policies. These spells restrict the imps’ ability to summon external resources, thus keeping them contained within the pages they inhabit.

    Finally, I employ a mystical barrier called a Trusted Types policy. This powerful enchantment ensures that only authorized quills can craft the links within the portals, effectively barring any imp from weaving its own mischief.


    In the world of JavaScript, these imps often exploit the Document Object Model (DOM) by using unsafe methods to insert untrusted data into the pages. To illustrate, let’s look at a common scenario: dynamically updating the content of a page using JavaScript.

    // Unsafe way that might invite imps
    let userInput = "<img src='x' onerror='alert(1)'>";
    document.getElementById("output").innerHTML = userInput;

    Here, I’ve inadvertently invited an imp by directly inserting user input into the page’s HTML. To detect this, I’d be wary of any code that mixes user input with DOM manipulation functions like innerHTML, document.write(), or eval().

    To prevent the imp from causing trouble, I adopt safer practices:

    1. Sanitization and Encoding:
      I ensure the input is sanitized or encoded, so it cannot execute harmful scripts.
    // Using textContent for safer insertion
    let safeOutput = document.createElement('div');
    safeOutput.textContent = userInput;
    document.getElementById("output").appendChild(safeOutput);
    1. Content Security Policy (CSP):
      I set up a CSP to restrict the types of resources that can be loaded. This acts like a barrier, allowing only trusted scripts to run.
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    1. Trusted Types:
      By using Trusted Types, I ensure that the only code allowed to interact with the DOM is pre-approved, keeping the imps at bay.
    // Example setup for Trusted Types
    if (window.trustedTypes) {
      const policy = trustedTypes.createPolicy('default', {
        createHTML: (string) => string
      });
    }

    Key Takeaways:

    • Detection: Always be suspicious of any code that directly manipulates the DOM with untrusted data. Review your use of methods like innerHTML and eval().
    • Prevention:
    • Use safer methods like textContent and createElement.
    • Implement Content Security Policies to restrict script execution.
    • Leverage Trusted Types to control which scripts can write to the DOM.
  • How Does the HttpOnly Flag Protect Your Cookies?

    Hey there, if you enjoy this tale of chameleons and cookies, give it a like or share it with your fellow story lovers!


    I’m a chameleon, perched on a tree branch, effortlessly blending into my environment. I’m an expert at this, just like how web developers use the HttpOnly flag to make cookies blend seamlessly into the protective layers of a web application. Let me take you on a journey into my world to explain this concept.

    In my chameleon world, there’s this cloak called HttpOnly. When I wear it, I become invisible to certain prying eyes—much like a cookie marked with this special flag. This cloak ensures that only the server can see me, keeping me hidden from the curious eyes of JavaScript running on the client side. Just as I remain camouflaged, safely watching the world from my leafy perch, the HttpOnly flag shields cookies from client-side scripts, protecting them from potential attacks like cross-site scripting (XSS).

    Picture a forest with creatures unaware of my presence. Similarly, when a cookie is marked as HttpOnly, it silently sits in the background, performing its essential duties without being exposed to the risks of the digital wilderness. My camouflaged state means I can observe and react without drawing attention, providing a layer of security and peace of mind.

    So, as I bask under the warmth of the sun, blending into my surroundings, I think of how the HttpOnly flag works its magic, ensuring cookies remain secure and unseen by unwanted eyes. It’s a dance of protection and invisibility, much like my own existence on this lively branch.


    Suppose I’m working with an Express.js application on Node.js. To set an HttpOnly cookie, I would write something like this:

    app.get('/set-cookie', (req, res) => {
      // Setting a cookie named "session_id"
      res.cookie('session_id', '123456', {
        httpOnly: true, // This is the HttpOnly flag
        secure: true,   // Often used in conjunction with https
        maxAge: 3600000 // Cookie expiry time in milliseconds
      });
      res.send('HttpOnly cookie has been set!');
    });

    In this snippet, the httpOnly: true line is where the magic happens. It tells the browser to hide this cookie from JavaScript, ensuring that it’s only sent over HTTP(S) requests. This is akin to how I, the chameleon, remain hidden from predators or curious onlookers in the forest.

    While JavaScript can manipulate many aspects of the client-side experience, with the HttpOnly flag in place, any attempts to access this cookie via document.cookie on the client side will result in failure. Here’s an example of how it won’t work:

    console.log(document.cookie); // "session_id" cookie won't appear here if marked HttpOnly

    Key Takeaways and Final Thoughts:

    1. Security Enhancement: The HttpOnly flag prevents client-side scripts from accessing sensitive cookies, reducing the risk of attacks like XSS.
    2. Server-Side Setting: This flag is set server-side when cookies are being created or modified. It’s a server’s way of saying, “Keep this cookie hidden from the client-side scripts.”
    3. Peace of Mind: Just as I find peace blending into my environment, web developers can rest assured that their sensitive data is protected from the prying eyes of malicious scripts.