Solving SaaS from ImaginaryCTF 2021

Posted on Tue 27 July 2021 in CTF by 0xm4v3rick


The author note for this CTF challenge.

1
Welcome to Sed as a Service! Now you can filter lorem ipsum to your heart's desire!

Attachment(source code) is provided along with the challenge URL. After visiting the URL we see a page to provide inputs to sed utility as shown below. Putting in some random input as per the provided syntax will output contents of some file.

landing

landing

Looking at the provided source code gives us some idea of how the input is processed. Lets go through the important parts of the code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from flask import Flask, render_template, request
import html
import os

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

blacklist = ["flag", "cat", "|", "&", ";", "`", "$"]

@app.route('/backend')
def backend():
    for word in blacklist:
        if word in request.args['query']:
            return "Stop hacking.\n"
    return html.escape(os.popen(f"sed {request.args['query']} stuff.txt").read())

On line 13 we see a route to backend where our request gets sent. The code at line 16 than checks the blacklist mentioned at line 11 against our input in variable query. If any of the blacklisted words are found our input will be rejected. Otherwise line 18 processes the input and returns the output.

My first thought was to see if I can get the code to execute any commands of my own by bypassing the blacklist. So I searched around for some resources that could help in that direction. After trying a few things I realized that executing my command might be difficult than I thought considering the blacklisted special characters which allows for chaining commands.

It was time to check other avenues to break the code. Having used sed utility a few times I realized that it outputs the contents of the provided file by default to show the changes. So as long as we are able to use it on flag file we should be able to retrieve its contents. Now we needed to figure out how to bypass the word flag. That was easy as most command injection bypass resources will highlight multiple methods to use common words in different ways.

For example linux command line will match fla? as flat or flap, so on and so forth. ? will be replaced by any character available in the list of files in this case. With that all we had to do is provide the input similar to the below and that gave us the flag. Sometimes we just need to use the provided options instead of bypassing them ;)

's/hello/hewwo/g' fl?g.txt

landing

That was a nice little chal from the Imaginary CTF team. Thanks to them. Feel free to ping me on twitter for feedback or queries.
- 0xm4v3rick