Resolviendo un reto criptográfico mediante análisis de frecuencias

Debido a que lo he pasado bastante mal para encontrar tiempo para publicar el wargame de bandit completo he decidido saltarme un poco el planning de publicación que tengo para pasar a un reto que me resultó bastante interesante que resolví en verano y que me tuvo unos días entretenido. El reto que publico aqui se engloba en uno mayor pero el interesante es el que voy a publicar.

La idea es que te dan un texto tal que asi:

Y las pistas de que el texto plano está en inglés y se ha usado la misma clave para cifrar todo el texto. El reto consiste en hacer criptoanalisis a este texto y poder sacar el texto plano de él. Por lo general cuando se cifra texto de esta manera los espacios y la longitud de la palabra no tienen ninguna utilidad salvo molestar en el proceso de desencriptado.

Como nos han dicho que se usa la misma clave podemos hacer un analisis de frecuencias para ver cuales son los caracteres más repetidos y además podemos incluir los n-gramas más repetidos en el texto cifrado

Obviando la última parte que son mis intentos por descifrar el texto lo que hace el programa es sacar las veces que un caracter aparece repetido en el texto (también hace lo mismo con los n-gramas). Si ejecutamos el programa con el texto cifrado y pasamos un segundo parametro igual a 3 para indicar que queremos sacar como máximo por 3-gramas obtenemos:

Analsiis de frecuencia

El siguiente paso es hallar las frecuencias del idioma inglés. Esto podriamos hacerlo pasando un texto largo al programa en python o directamente buscarlo por internet. Si lo buscamos por internet encontramos:

ngramas en inglés

Si observamos la letra más repetida en el texto cifrado es la S y la letra más frecuente en inglés es la E. Podemos concluir que la S se descifra como E, aunque no siempre es así y tendremos que hacer un proceso manual hasta poder obtener el texto en su totalidad.

Podemos volver a usar el programa en python para hacer las sustituciones. Podemos modificar el diccionario de la parte final para probar a descifrar. Al final obtenemos lo siguiente:

Texto en plano

Bandit wargame - II

Nivel 12 -> Nivel 13

En este nivel nis dan un fichero data.txt el cual es un dumpeado de un fichero el cual ha sido comprimido repetidas veces. Pa resolver este nivel tenemos que pasar data.txt a formato binario mediante xxd y mediante el comando file obtener información sobre el fichero e ir aplicando las descompresiones correspondientes.

bandit12@bandit:~$ mkdir /tmp/an
bandit12@bandit:~$ cp data.txt /tmp/an
bandit12@bandit:~$ cd /tmp/an
bandit12@bandit:/tmp/an$ xxd -r data.txt > data1
bandit12@bandit:/tmp/an$ ls
data.txt  data1
bandit12@bandit:/tmp/an$ file data1    
data1: gzip compressed data, was "data2.bin", last modified: Thu Dec 28 13:34:36 2017, max compression, from Unix
bandit12@bandit:/tmp/an$ mv data1 c.gz
bandit12@bandit:/tmp/an$ gzip -d c.gz 
bandit12@bandit:/tmp/an$ ls
c  data.txt
bandit12@bandit:/tmp/an$ file c
c: bzip2 compressed data, block size = 900k
bandit12@bandit:/tmp/an$ bzip2 -d c
bandit12@bandit:/tmp/an$ file c.out 
c.out: gzip compressed data, was "data4.bin", last modified: Thu Dec 28 13:34:36 2017, max compression, from Unix
bandit12@bandit:/tmp/an$ mv c.out c.gz
bandit12@bandit:/tmp/an$ gzip -d c.gz 
bandit12@bandit:/tmp/an$ file c
c: POSIX tar archive (GNU)
bandit12@bandit:/tmp/an$ mv c c.tar
bandit12@bandit:/tmp/an$ tar x c.tar 
tar: Refusing to read archive contents from terminal (missing -f option?)
tar: Error is not recoverable: exiting now
bandit12@bandit:/tmp/an$ tar fx c.tar 
bandit12@bandit:/tmp/an$ ls
c.tar  data.txt  data5.bin
bandit12@bandit:/tmp/an$ file data5.bin 
data5.bin: POSIX tar archive (GNU)
bandit12@bandit:/tmp/an$ mv data5.bin data5.tar
bandit12@bandit:/tmp/an$ tar xf data5.tar 
bandit12@bandit:/tmp/an$ ls
c.tar  data.txt  data5.tar  data6.bin
bandit12@bandit:/tmp/an$ file data6.bin 
data6.bin: bzip2 compressed data, block size = 900k
bandit12@bandit:/tmp/an$ mv data6.bin data6.bzip
bandit12@bandit:/tmp/an$ bzip2 -d data6.bzip
bzip2: Can't guess original name for data6.bzip -- using data6.bzip.out
bandit12@bandit:/tmp/an$ file data6.bzip.out 
data6.bzip.out: POSIX tar archive (GNU)
bandit12@bandit:/tmp/an$ mv data6.bzip.out data6.tar
bandit12@bandit:/tmp/an$ tar xf data6.tar 
bandit12@bandit:/tmp/an$ ls
c.tar  data.txt  data5.tar  data6.tar  data8.bin
bandit12@bandit:/tmp/an$ file data8.bin 
data8.bin: gzip compressed data, was "data9.bin", last modified: Thu Dec 28 13:34:36 2017, max compression, from Unix
bandit12@bandit:/tmp/an$ mv data8.bin data8.gz
bandit12@bandit:/tmp/an$ gzip -d data8.gz 
bandit12@bandit:/tmp/an$ ls
c.tar  data.txt  data5.tar  data6.tar  data8
bandit12@bandit:/tmp/an$ file data8
data8: ASCII text
bandit12@bandit:/tmp/an$ cat data8
The password is 8ZjyCRiBWFYkneahHwxCv3wb2a1ORpYL

Nivel 13 -> Nivel 14

En este nivel nos dice que la bandera se encuentra en /etc/bandit_pass/bandit14 pero solo puede ser leido por el usuarios bandit14 y para ello nos facilitan una clave privada ssh que debemos usar para poder acceder a la contrasña.

bandit13@bandit:~$ ls
sshkey.private
bandit13@bandit:~$ ssh -i sshkey.private bandit14@localhost
Could not create directory '/home/bandit13/.ssh'.
The authenticity of host 'localhost (127.0.0.1)' can't be established.
ECDSA key fingerprint is SHA256:98UL0ZWr85496EtCRkKlo20X3OPnyPSB5tB5RPbhczc.
Are you sure you want to continue connecting (yes/no)? yes
Failed to add the host to the list of known hosts (/home/bandit13/.ssh/known_hosts).
bandit14@bandit:~$ cat /etc/bandit_pass/bandit14
4wcYUJFw0k0XLShlDzztnTBHiqxU3b3e

Nivel 14 -> Nivel 15

En este nivel se indica que la contraseña para el siguiente nivel puede ser obtenida si enviamos al puerto 30000 de localhost la contraseña del nuvel actual.

bandit14@bandit:~$ telnet localhost 30000
Trying ::1...
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
4wcYUJFw0k0XLShlDzztnTBHiqxU3b3e
Correct!
BfMYroe26WYalil77FoDi9qh59eK5xNr

Connection closed by foreign host.

Nivel 15 -> Nivel 16

Este nivel es parecido al anterior, se nos pide que enviemos la clave actual al puerto 30001 en localhost pero con la diferencia de que tenemos que hacerlo mediante un canal encriptado.

bandit15@bandit:~$ openssl s_client -connect localhost:30001 -ign_eof
CONNECTED(00000003)
depth=0 CN = bandit
verify error:num=18:self signed certificate
verify return:1
depth=0 CN = bandit
verify return:1
---
Certificate chain
 0 s:/CN=bandit
   i:/CN=bandit
---
Server certificate
-----BEGIN CERTIFICATE-----
MIICsjCCAZqgAwIBAgIJAKZI1xYeoXFuMA0GCSqGSIb3DQEBCwUAMBExDzANBgNV
BAMMBmJhbmRpdDAeFw0xNzEyMjgxMzIzNDBaFw0yNzEyMjYxMzIzNDBaMBExDzAN
BgNVBAMMBmJhbmRpdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOcX
ruVcnQUBeHJeNpSYayQExCJmcHzSCktnOnF/H4efWzxvLRWt5z4gYaKvTC9ixLrb
K7a255GEaUbP/NVFpB/sn56uJc1ijz8u0hWQ3DwVe5ZrHUkNzAuvC2OeQgh2HanV
5LwB1nmRZn90PG1puKxktMjXsGY7f9Yvx1/yVnZqu2Ev2uDA0RXij/T+hEqgDMI7
y4ZFmuYD8z4b2kAUwj7RHh9LUKXKQlO+Pn8hchdR/4IK+Xc4+GFOin0XdQdUJaBD
8quOUma424ejF5aB6QCSE82MmHlLBO2tzC9yKv8L8w+fUeQFECH1WfPC56GcAq3U
IvgdjGrU/7EKN5XkONcCAwEAAaMNMAswCQYDVR0TBAIwADANBgkqhkiG9w0BAQsF
AAOCAQEAnrOty7WAOpDGhuu0V8FqPoKNwFrqGuQCTeqhQ9LP0bFNhuH34pZ0JFsH
L+Y/q4Um7+66mNJUFpMDykm51xLY2Y4oDNCzugy+fm5Q0EWKRwrq+hIM+5hs0RdC
nARP+719ddmUiXF7r7IVP2gK+xqpa8+YcYnLuoXEtpKkrrQCCUiqabltU5yRMR77
3wqB54txrB4IhwnXqpO23kTuRNrkG+JqDUkaVpvct+FAdT3PODMONP/oHII3SH9i
ar/rI9k+4hjlg4NqOoduxX9M+iLJ0Zgj6HAg3EQVn4NHsgmuTgmknbhqTU3o4IwB
XFnxdxVy0ImGYtvmnZDQCGivDok6jA==
-----END CERTIFICATE-----
subject=/CN=bandit
issuer=/CN=bandit
---
No client certificate CA names sent
---
SSL handshake has read 1015 bytes and written 631 bytes
---
New, TLSv1/SSLv3, Cipher is AES128-SHA
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1
    Cipher    : AES128-SHA
    Session-ID: 390D38ED94122F6FD7F9B68BD31EB1043DB14D5D24F9DEB823AAD3D4B970E546
    Session-ID-ctx: 
    Master-Key: 3F4FFA74A9CF8627193150E8708AD0E42E97873854682EAF00585A669DC4D1BA8992C051D40063B299F25086F9D760AE
    Key-Arg   : None
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    TLS session ticket lifetime hint: 7200 (seconds)
    TLS session ticket:
    0000 - 08 f0 15 a5 d6 6f a0 e8-06 d6 bb a4 0c 33 eb 04   .....o.......3..
    0010 - b1 4a 10 2e 1d 99 ff 39-10 5c 43 5f 20 15 08 4a   .J.....9.\C_ ..J
    0020 - d1 17 17 9f 9a 10 d6 31-7f 19 9d 0b 1d 6f ce ed   .......1.....o..
    0030 - 34 4b 63 f4 3d 8e 56 98-73 ce ca 2c a6 34 6f 86   4Kc.=.V.s..,.4o.
    0040 - 68 27 77 b6 9e 6d f6 f2-74 f5 d7 31 1a b0 a2 c6   h'w..m..t..1....
    0050 - 58 98 0e 37 ae d1 65 e1-9c ee b8 01 61 22 ba 94   X..7..e.....a"..
    0060 - 6f f1 9c 36 e6 e5 1c 63-74 1b 6d 44 65 20 a3 35   o..6...ct.mDe .5
    0070 - 8b fc 33 7d a0 af 3c a6-36 84 c4 b8 b5 92 d6 bd   ..3}..<.6.......
    0080 - a3 23 ff a9 e3 81 b9 7d-1f 6b 8b 6c 2b 80 c2 65   .#.....}.k.l+..e
    0090 - b4 67 ed 1a b5 6b 2e 86-8e ef 37 38 b5 47 35 5f   .g...k....78.G5_

    Start Time: 1534092520
    Timeout   : 300 (sec)
    Verify return code: 18 (self signed certificate)
---
BfMYroe26WYalil77FoDi9qh59eK5xNr
Correct!
cluFn7wTiGryunymYOu4RcffSxQluehd

closed

Nivel 16 -> Nivel 17

Este nivel vuelve a ser muy parecido a los anteriores, pero con la diferencia de que hay multiples servidores escuchando en puertos que van desde el 31ooo al 32000. Para solucionarlo podemos usar nc para saber cuales son los que están abiertos y como son pocos probar uno a uno.

bandit16@bandit:~$ mkdir /tmp/ang/hola
bandit16@bandit:~$ nc -zv localhost 31000-32000 2> /tmp/ang/hola
bandit16@bandit:~$ cat /tmp/ang/hola | grep suc
Connection to localhost 31046 port [tcp/*] succeeded!
Connection to localhost 31518 port [tcp/*] succeeded!
Connection to localhost 31691 port [tcp/*] succeeded!
Connection to localhost 31790 port [tcp/*] succeeded!
Connection to localhost 31960 port [tcp/*] succeeded!
bandit16@bandit:~$ openssl s_client -connect localhost:31790 -ign_eof
CONNECTED(00000003)
depth=0 CN = bandit
verify error:num=18:self signed certificate
verify return:1
depth=0 CN = bandit
verify return:1
---
Certificate chain
 0 s:/CN=bandit
   i:/CN=bandit
---
Server certificate
-----BEGIN CERTIFICATE-----
MIICsjCCAZqgAwIBAgIJAKZI1xYeoXFuMA0GCSqGSIb3DQEBCwUAMBExDzANBgNV
BAMMBmJhbmRpdDAeFw0xNzEyMjgxMzIzNDBaFw0yNzEyMjYxMzIzNDBaMBExDzAN
BgNVBAMMBmJhbmRpdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOcX
ruVcnQUBeHJeNpSYayQExCJmcHzSCktnOnF/H4efWzxvLRWt5z4gYaKvTC9ixLrb
K7a255GEaUbP/NVFpB/sn56uJc1ijz8u0hWQ3DwVe5ZrHUkNzAuvC2OeQgh2HanV
5LwB1nmRZn90PG1puKxktMjXsGY7f9Yvx1/yVnZqu2Ev2uDA0RXij/T+hEqgDMI7
y4ZFmuYD8z4b2kAUwj7RHh9LUKXKQlO+Pn8hchdR/4IK+Xc4+GFOin0XdQdUJaBD
8quOUma424ejF5aB6QCSE82MmHlLBO2tzC9yKv8L8w+fUeQFECH1WfPC56GcAq3U
IvgdjGrU/7EKN5XkONcCAwEAAaMNMAswCQYDVR0TBAIwADANBgkqhkiG9w0BAQsF
AAOCAQEAnrOty7WAOpDGhuu0V8FqPoKNwFrqGuQCTeqhQ9LP0bFNhuH34pZ0JFsH
L+Y/q4Um7+66mNJUFpMDykm51xLY2Y4oDNCzugy+fm5Q0EWKRwrq+hIM+5hs0RdC
nARP+719ddmUiXF7r7IVP2gK+xqpa8+YcYnLuoXEtpKkrrQCCUiqabltU5yRMR77
3wqB54txrB4IhwnXqpO23kTuRNrkG+JqDUkaVpvct+FAdT3PODMONP/oHII3SH9i
ar/rI9k+4hjlg4NqOoduxX9M+iLJ0Zgj6HAg3EQVn4NHsgmuTgmknbhqTU3o4IwB
XFnxdxVy0ImGYtvmnZDQCGivDok6jA==
-----END CERTIFICATE-----
subject=/CN=bandit
issuer=/CN=bandit
---
No client certificate CA names sent
---
SSL handshake has read 1015 bytes and written 631 bytes
---
New, TLSv1/SSLv3, Cipher is AES128-SHA
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1
    Cipher    : AES128-SHA
    Session-ID: 06DABAB6C4656E9FC34A5F6ED53A0865A49857C66A73BFBAA740F3EB2208B805
    Session-ID-ctx: 
    Master-Key: F1E42EEC279D5777BA24D8870F643F51DD8661008DC05F87E6FA0CDACDE2E9CEB5D170044269AC96A949246730235B36
    Key-Arg   : None
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    TLS session ticket lifetime hint: 7200 (seconds)
    TLS session ticket:
    0000 - aa 3d 08 f7 55 9a 83 cb-75 cb f1 ae ef 7b e3 4c   .=..U...u....{.L
    0010 - 3c 2a b3 78 e8 49 43 1b-d5 b3 ef 50 a8 26 79 cb   <*.x.IC....P.&y.
    0020 - 52 aa 50 0b 04 e1 14 28-35 24 25 63 70 d4 aa 54   R.P....(5$%cp..T
    0030 - da ab 09 82 19 45 b6 ef-31 9f 91 27 df 93 5c 8c   .....E..1..'..\.
    0040 - fb f8 67 c1 47 52 20 11-94 19 f2 bc 66 25 9e 23   ..g.GR .....f%.#
    0050 - 60 3c b6 e9 53 7e 34 78-e9 24 46 74 90 eb 4f a4   `<..S~4x.$Ft..O.
    0060 - 75 75 46 9a dd bb 69 10-cc e9 30 14 91 2b d9 8f   uuF...i...0..+..
    0070 - 0a 81 6e 27 11 d4 c3 fe-88 c8 93 55 f7 ee 9a e6   ..n'.......U....
    0080 - 1a 06 83 30 72 c7 17 cf-1a 3e b8 fa 1f e3 ae 5d   ...0r....>.....]
    0090 - 87 93 9b 0e 3a d0 da a8-50 4d e7 63 5b 50 ff d2   ....:...PM.c[P..

    Start Time: 1534093610
    Timeout   : 300 (sec)
    Verify return code: 18 (self signed certificate)
---
cluFn7wTiGryunymYOu4RcffSxQluehd
Correct!
-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAvmOkuifmMg6HL2YPIOjon6iWfbp7c3jx34YkYWqUH57SUdyJ
imZzeyGC0gtZPGujUSxiJSWI/oTqexh+cAMTSMlOJf7+BrJObArnxd9Y7YT2bRPQ
Ja6Lzb558YW3FZl87ORiO+rW4LCDCNd2lUvLE/GL2GWyuKN0K5iCd5TbtJzEkQTu
DSt2mcNn4rhAL+JFr56o4T6z8WWAW18BR6yGrMq7Q/kALHYW3OekePQAzL0VUYbW
JGTi65CxbCnzc/w4+mqQyvmzpWtMAzJTzAzQxNbkR2MBGySxDLrjg0LWN6sK7wNX
x0YVztz/zbIkPjfkU1jHS+9EbVNj+D1XFOJuaQIDAQABAoIBABagpxpM1aoLWfvD
KHcj10nqcoBc4oE11aFYQwik7xfW+24pRNuDE6SFthOar69jp5RlLwD1NhPx3iBl
J9nOM8OJ0VToum43UOS8YxF8WwhXriYGnc1sskbwpXOUDc9uX4+UESzH22P29ovd
d8WErY0gPxun8pbJLmxkAtWNhpMvfe0050vk9TL5wqbu9AlbssgTcCXkMQnPw9nC
YNN6DDP2lbcBrvgT9YCNL6C+ZKufD52yOQ9qOkwFTEQpjtF4uNtJom+asvlpmS8A
vLY9r60wYSvmZhNqBUrj7lyCtXMIu1kkd4w7F77k+DjHoAXyxcUp1DGL51sOmama
+TOWWgECgYEA8JtPxP0GRJ+IQkX262jM3dEIkza8ky5moIwUqYdsx0NxHgRRhORT
8c8hAuRBb2G82so8vUHk/fur85OEfc9TncnCY2crpoqsghifKLxrLgtT+qDpfZnx
SatLdt8GfQ85yA7hnWWJ2MxF3NaeSDm75Lsm+tBbAiyc9P2jGRNtMSkCgYEAypHd
HCctNi/FwjulhttFx/rHYKhLidZDFYeiE/v45bN4yFm8x7R/b0iE7KaszX+Exdvt
SghaTdcG0Knyw1bpJVyusavPzpaJMjdJ6tcFhVAbAjm7enCIvGCSx+X3l5SiWg0A
R57hJglezIiVjv3aGwHwvlZvtszK6zV6oXFAu0ECgYAbjo46T4hyP5tJi93V5HDi
Ttiek7xRVxUl+iU7rWkGAXFpMLFteQEsRr7PJ/lemmEY5eTDAFMLy9FL2m9oQWCg
R8VdwSk8r9FGLS+9aKcV5PI/WEKlwgXinB3OhYimtiG2Cg5JCqIZFHxD6MjEGOiu
L8ktHMPvodBwNsSBULpG0QKBgBAplTfC1HOnWiMGOU3KPwYWt0O6CdTkmJOmL8Ni
blh9elyZ9FsGxsgtRBXRsqXuz7wtsQAgLHxbdLq/ZJQ7YfzOKU4ZxEnabvXnvWkU
YOdjHdSOoKvDQNWu6ucyLRAWFuISeXw9a/9p7ftpxm0TSgyvmfLF2MIAEwyzRqaM
77pBAoGAMmjmIJdjp+Ez8duyn3ieo36yrttF5NSsJLAbxFpdlc1gvtGCWW+9Cq0b
dxviW8+TFVEBl1O4f7HVm6EpTscdDxU+bCXWkfjuRb7Dy9GOtt9JPsX8MBTakzh3
vBgsyi/sN3RqRBcGU40fOoZyfAMT8s1m/uYv52O6IgeuZ/ujbjY=
-----END RSA PRIVATE KEY-----

closed

bandit16@bandit:~$ chmod og-rw /tmp/ang/key 
bandit16@bandit:~$ ssh -i /tmp/ang/key bandit17@localhost
Could not create directory '/home/bandit16/.ssh'.
The authenticity of host 'localhost (127.0.0.1)' can't be established.
ECDSA key fingerprint is SHA256:98UL0ZWr85496EtCRkKlo20X3OPnyPSB5tB5RPbhczc.
Are you sure you want to continue connecting (yes/no)? yes
bandit17@bandit:~$ cat /etc/bandit_pass/bandit17 
xLYVMN9WE5zQ5vHacb0sZEVqbrp7nBTn

Nivel 17 -> Nivel 18

En este nivel nos indican que tenemos dos ficheros (passwords.old y passwords.new) y que el password correcto para el siguiente nivel es el único que cambia entre los 2 ficheros, así que basta hacer un diff entre ambos ficheros para hallar dicho password.

 bandit17@bandit:~$ diff passwords.new passwords.old 
42c42
< kfBf3eYk5BPBRzwjqutbbfE887SVc5Yd
---
> 6vcSC74ROI95NqkKaeEC2ABVMDX9TyUr

Nivel 18 -> Nivel 19

En este nivel nos dice que el password del siguiente nivel está en una fichero llamado readme, el problema es que cuando accedemos por ssh el sistema nos echa sin poder hacer nada más. La solución pasa por indicarle a ssh el comando a ejecutar (cat /home/bandit18/readme) en vez de usar ssh para entrar en el sistema.

angelluis@sunny:~$ ssh bandit18@bandit.labs.overthewire.org -p 2220 cat /home/bandit18/readme
This is a OverTheWire game server. More information on http://www.overthewire.org/wargames
bandit18@bandit.labs.overthewire.org's password: 
IueksS7Ubh8G3DCwVzrTd8rAVOwq3M5x

Nivel 19 -> Nivel 20

En este caso se nos dice que ejecutemos el binario que tenemos en el home el cual tiene activado el bit s. Para resolver este nivel vemos que podemos pasar un comando a este binario y será ejecutado como el propietario del binario. Como se puede observar el propietario es bandit20 por tanto al ejecutarlo tenemos los permisos de dicho usuario y podemos leer el fichero /etc/bandit_pass/bandit20.

 bandit19@bandit:~$ ./bandit20-do 
Run a command as another user.
  Example: ./bandit20-do id
bandit19@bandit:~$ ./bandit20-do cat /etc/bandit_pass/bandit20
GbKksEFF4yrVs6il55v6gwY5aVje5f0j

Nivel 20 -> Nivel 21

Para resolver este nivel tendremos que trabajar con la gestión de trabajos de linux, para ello ejecutamos un netcat en un puerto cualquiera (en este caso 1234) y dejarlo ejecutando en segundo plano. Acto seguido ejecutamos el binario que está en el home especificando como argumento 1234 y dejando que se ejecute en segundo plano. Ahora podemos listar los trabajos activos con jobs y traer al primer proceso a primer plano e introduce la contraseña actual para que nos devuelva la del siguiente nivel.

bandit20@bandit:~$ nc -l 1234 &
[1] 29215
bandit20@bandit:~$ ./suconnect 1234 &
[2] 29355
bandit20@bandit:~$ jobs
[1]-  Running                 nc -l 1234 &
[2]+  Running                 ./suconnect 1234 &
bandit20@bandit:~$ fg %1
nc -l 1234
GbKksEFF4yrVs6il55v6gwY5aVje5f0j
Read: GbKksEFF4yrVs6il55v6gwY5aVje5f0j
Password matches, sending next password
gE269g2h3mw3pwgrj0Ha9Uoqen1c9DGr
[2]-  Done                    ./suconnect 1234

Nivel 21 -> Nivel 22

En este nivel nos dice que hay un cron que se está ejecutando periodicamente. Para resolverlo basta con acceder a cron y ver que se está escribiendo la contraseña para el siguiente nivel en un fichero determinado.

 bandit21@bandit:~$ ls /etc/cron.d
cronjob_bandit22  cronjob_bandit23  cronjob_bandit24  popularity-contest
bandit21@bandit:~$ cat /etc/cron.d/cronjob_bandit22 
@reboot bandit22 /usr/bin/cronjob_bandit22.sh &> /dev/null
* * * * * bandit22 /usr/bin/cronjob_bandit22.sh &> /dev/null
bandit21@bandit:~$ cat /usr/bin/cron
cronjob_bandit22.sh  cronjob_bandit24.sh  
cronjob_bandit23.sh  crontab              
bandit21@bandit:~$ cat /usr/bin/cronjob_bandit22.sh 
#!/bin/bash
chmod 644 /tmp/t7O6lds9S0RqQh9aMcz6ShpAoZKF7fgv
cat /etc/bandit_pass/bandit22 > /tmp/t7O6lds9S0RqQh9aMcz6ShpAoZKF7fgv
bandit21@bandit:~$ cat /tmp/t7O6lds9S0RqQh9aMcz6ShpAoZKF7fgv
Yk7owGAcWjwMVRwrTesJEwB7WVOiILLI

Nivel 22 -> Nivel 23

Nuevamente este nivel consiste en inspeccionar cron y saber leer el script que está ejecutando. Lo que hace el script es ejecutar como bandit23 el comando echo y después un md5, así que si manualmente hacemos el comando echo y obtenemos su md5 sabremos donde está alacenando la contraseña para el siguiente nivel.

bandit22@bandit:~$ cat /etc/cron.d/cronjob_bandit23 
@reboot bandit23 /usr/bin/cronjob_bandit23.sh  &> /dev/null
* * * * * bandit23 /usr/bin/cronjob_bandit23.sh  &> /dev/null
bandit22@bandit:~$ cat /usr/bin/cronjob_bandit23.sh 
#!/bin/bash

myname=$(whoami)
mytarget=$(echo I am user $myname | md5sum | cut -d ' ' -f 1)

echo "Copying passwordfile /etc/bandit_pass/$myname to /tmp/$mytarget"

cat /etc/bandit_pass/$myname > /tmp/$mytarget
bandit22@bandit:~$ echo "I am user bandit23" | md5sum
8ca319486bfbbc3663ea0fbe81326349  -
bandit22@bandit:~$ cat /tmp/8ca319486bfbbc3663ea0fbe81326349
jc1udXuA1tiHqjIsL8yaapX5XIAI6i0n

Nivel 23 -> Nivel 24

Muy parecido al anterior con la diferencia de que esta vez tendremos que crear un script para obtener la contraseña del siguiente nivel.

 bandit23@bandit:~$ cat /etc/cron.d/cronjob_bandit24 
@reboot bandit24 /usr/bin/cronjob_bandit24.sh &> /dev/null
* * * * * bandit24 /usr/bin/cronjob_bandit24.sh &> /dev/null
bandit23@bandit:~$ cat /usr/bin/cronjob_bandit24.sh 
#!/bin/bash

myname=$(whoami)

cd /var/spool/$myname
echo "Executing and deleting all scripts in /var/spool/$myname:"
for i in * .*;
do
    if [ "$i" != "." -a "$i" != ".." ];
    then
    echo "Handling $i"
    timeout -s 9 60 ./$i
    rm -f ./$i
    fi
done
bandit23@bandit:~$ nano /tmp/ang1/script.sh
bandit23@bandit:~$ cat /tmp/ang1/script.sh 
cat /etc/bandit_pass/bandit24 > /tmp/ang1/pass
bandit23@bandit:~$ chmod 777 /tmp/ang1
bandit23@bandit:~$ chmod 777 /tmp/ang1/script.sh
bandit23@bandit:~$ cp /tmp/ang1/script.sh /var/spool/bandit24/
bandit23@bandit:~$ date
Sun Aug 12 20:48:55 CEST 2018
bandit23@bandit:~$ date
Sun Aug 12 20:49:01 CEST 2018
bandit23@bandit:~$ ll /var/spool/bandit24/script.sh
ls: cannot access '/var/spool/bandit24/script.sh': No such file or directory
bandit23@bandit:~$ cat /tmp/ang1/pass
UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ

Nivel 24 -> Nivel 25

En este nivel, de nuevo, hay un demonio corriendo en el puerto 30002 el cual nos pide la contraseña actual y un pin de 4 cifras para que nos devuelva la contraseña del siguiente nivel. En este nivel empleo 2 enfoques, el primero era hacer un bucle del 0 al 10000 y hacer un llamada a nc para cada pasada del bucle, este enfoque es muy lento y lo abandone (el codigo lo sigo dejando al principio). El segundo enfoque fue generar un fichero con todos los pin posibles y pasarselo directamente a netcat lo cual es mucho mas eficiente y devuelve la clave para el siguiente nivel.

bandit24@bandit:/tmp/brute$ cat /tmp/brute/brute.sh
#/bin/bash

for i in {0..10000}; do
  echo "UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ $i" | nc localhost 30002 | grep -v -e pincode -e Wrong -e Exiting
  echo "Try $i"; 
done
# TARDA MUCHO



#!/bin/bash

for i in {1..10000}

do
 echo "UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ $i" >> ./out
done

cat out | nc localhost 30002
I am the pincode checker for user bandit25. Please enter the password for user bandit24 and the secret pincode on a single line, separated by a space.
Wrong! Please enter the correct pincode. Try again.
Wrong! Please enter the correct pincode. Try again.
Wrong! Please enter the correct pincode. Try again.
Wrong! Please enter the correct pincode. Try again.
Wrong! Please enter the correct pincode. Try again.
Wrong! Please enter the correct pincode. Try again.
Wrong! Please enter the correct pincode. Try again.

Wrong! Please enter the correct pincode. Try again.
Wrong! Please enter the correct pincode. Try again.
Correct!
The password of user bandit25 is uNG9O58gUE7snukf3bvZ0rxhtnjzSGzG

Exiting.

Nivel 25 -> Nivel 26

Este nivel fue bastante interesante. Para empezar tienes que usar la clave ssh que tienes en home para loguearte en el siguiente nivel. Cuando accedemos al siguiente nivel con la clave ssh vemos que nos echa fuera. Si miramos la shell que está usando dicho usuarios vemos que es un script que hace uso del programa more. More tiene una peculiaridad, si el texto cabe en pantalla el programa muestra el texto y se cierra el programa, pero si el texto no cabe en pantalla nos da la opción de poder subir y bajar por el texto y además poder escribir comandos si pulsamos dos puntos (:). Para resolver este nivel debemos hacer la ventana pequeña para que nos permita ejecutar comandos y escribir:

:set shell=/bin/bash
:shell
 bandit25@bandit:~$ ls
bandit26.sshkey
bandit25@bandit:~$ ssh bandit26@localhost -i bandit26.sshkey 
Could not create directory '/home/bandit25/.ssh'.
The authenticity of host 'localhost (127.0.0.1)' can't be established.
ECDSA key fingerprint is SHA256:98UL0ZWr85496EtCRkKlo20X3OPnyPSB5tB5RPbhczc.
Are you sure you want to continue connecting (yes/no)? yes
Failed to add the host to the list of known hosts (/home/bandit25/.ssh/known_hosts).
This is a OverTheWire game server. More information on http://www.overthewire.org/wargames
               
      ,----..            ,----,          .---. 
     /   /   \         ,/   .`|         /. ./|
    /   .     :      ,`   .'  :     .--'.  ' ;
   .   /   ;.  \   ;    ;     /    /__./ \ : |
  .   ;   /  ` ; .'___,/    ,' .--'.  '   \' .
  ;   |  ; \ ; | |    :     | /___/ \ |    ' ' 
  |   :  | ; | ' ;    |.';  ; ;   \  \;      : 
  .   |  ' ' ' : `----'  |  |  \   ;  `      |
  '   ;  \; /  |     '   :  ;   .   \    .\  ; 
   \   \  ',  /      |   |  '    \   \   ' \ |
    ;   :    /       '   :  |     :   '  |--"  
     \   \ .'        ;   |.'       \   \ ;     
  www. `---` ver     '---' he       '---" ire.org     
               
              
Welcome to OverTheWire!

If you find any problems, please report them to Steven or morla on
irc.overthewire.org.

--[ Playing the games ]--

  This machine might hold several wargames. 
  If you are playing "somegame", then:

    * USERNAMES are somegame0, somegame1, ...
    * Most LEVELS are stored in /somegame/.
    * PASSWORDS for each level are stored in /etc/somegame_pass/.

  Write-access to homedirectories is disabled. It is advised to create a
  working directory with a hard-to-guess name in /tmp/.  You can use the
  command "mktemp -d" in order to generate a random and hard to guess
  directory in /tmp/.  Read-access to both /tmp/ and /proc/ is disabled
  so that users can not snoop on eachother. Files and directories with 
  easily guessable or short names will be periodically deleted!
    
  Please play nice:
      
    * don't leave orphan processes running
    * don't leave exploit-files laying around
    * don't annoy other players
    * don't post passwords or spoilers
    * again, DONT POST SPOILERS! 
      This includes writeups of your solution on your blog or website!

--[ Tips ]--

  This machine has a 64bit processor and many security-features enabled
  by default, although ASLR has been switched off.  The following
  compiler flags might be interesting:

    -m32                    compile for 32bit
    -fno-stack-protector    disable ProPolice
    -Wl,-z,norelro          disable relro 

  In addition, the execstack tool can be used to flag the stack as
  executable on ELF binaries.

  Finally, network-access is limited for most levels by a local
  firewall.

--[ Tools ]--

 For your convenience we have installed a few usefull tools which you can find
 in the following locations:

    * peda (https://github.com/longld/peda.git) in /usr/local/peda/
    * gdbinit (https://github.com/gdbinit/Gdbinit) in /usr/local/gdbinit/
    * pwntools (https://github.com/Gallopsled/pwntools)
    * radare2 (http://www.radare.org/)
    * checksec.sh (http://www.trapkit.de/tools/checksec.html) in /usr/local/bin/checksec.sh

--[ More information ]--

  For more information regarding individual wargames, visit
  http://www.overthewire.org/wargames/

  For support, questions or comments, contact us through IRC on
  irc.overthewire.org #wargames.

  Enjoy your stay!

  _                     _ _ _   ___   __  
 | |                   | (_) | |__ \ / /  
 | |__   __ _ _ __   __| |_| |_   ) / /_  
 | '_ \ / _` | '_ \ / _` | | __| / / '_ \ 
 | |_) | (_| | | | | (_| | | |_ / /| (_) |
 |_.__/ \__,_|_| |_|\__,_|_|\__|____\___/ 
Connection to localhost closed.
bandit25@bandit:~$ cat /etc/passwd | grep bandit26
bandit26:x:11026:11026:bandit level 26:/home/bandit26:/usr/bin/showtext
bandit25@bandit:~$ file /usr/bin/showtext 
/usr/bin/showtext: POSIX shell script, ASCII text executable
bandit25@bandit:~$ cat /usr/bin/showtext 
#!/bin/sh

export TERM=linux

more ~/text.txt
exit 0
bandit25@bandit:~$ ssh bandit26@localhost -i bandit26.sshkey 
:! /bin/bash
:set shell=/bin/bash
:shell
[No write since last change]
bandit26@bandit:~$ cat /etc/bandit_pass/bandit26
5czgV9L3Xx8JPOyRbXh6lQbmIOWvPT6Z

Nivel 26 -> Nivel 27

En este nivel de nuevo tenemos que hacer uso de un binario con el bit s activo.

bandit26@bandit:~$ ls
bandit27-do  text.txt
bandit26@bandit:~$ ./bandit27-do cat /etc/bandit_pass/bandit27
3ba3118a22e93127a4ed485be72ef5ea

Nivel 27 -> Nivel 28

En este nivel aparece algo nuevo y que es tenemos que hacer un clone al repositorio ssh://bandit27-git@localhost/home/bandit27-git/repo y buscar la contraseña en dicho repositorio. En este caso es bastante sencillo, haciendo un simple cat a repo/README nos encontramos con la contraseña.

bandit27@bandit:/tmp/git/repo$ mkdir /tmp/repository
bandit27@bandit:/tmp/git/repo$ cd /tmp/repository
bandit27@bandit:/tmp/repository$ git clone ssh://bandit27-git@localhost/home/bandit27-git/repo
Cloning into 'repo'...
Could not create directory '/home/bandit27/.ssh'.
The authenticity of host 'localhost (127.0.0.1)' can't be established.
ECDSA key fingerprint is SHA256:98UL0ZWr85496EtCRkKlo20X3OPnyPSB5tB5RPbhczc.
Are you sure you want to continue connecting (yes/no)? yes
Failed to add the host to the list of known hosts (/home/bandit27/.ssh/known_hosts).
This is a OverTheWire game server. More information on http://www.overthewire.org/wargames
bandit27-git@localhost's password: 
remote: Counting objects: 3, done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 3 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (3/3), done.
Checking connectivity... done.
bandit27@bandit:/tmp/repository$ cat repo/README 
The password to the next level is: 0ef186ac70e04ea33b4c1853d2526fa2

Nivel 28 -> Nivel 29

Este nivel es parecido al anterior, pero si intentamos hacer un cat a repo/README.md observamos que la contraseña ha sido eliminada. Para solucionar el nivel podemos ver los comit que se han hecho y echar un ojo al log para ver la contraseña.

bandit28@bandit:~$ mkdir /tmp/repository1
bandit28@bandit:~$ cd /tmp/repository1
bandit28@bandit:/tmp/repository1$ git clone ssh://bandit28-git@localhost/home/bandit28-git/repo
Cloning into 'repo'...
Could not create directory '/home/bandit28/.ssh'.
The authenticity of host 'localhost (127.0.0.1)' can't be established.
ECDSA key fingerprint is SHA256:98UL0ZWr85496EtCRkKlo20X3OPnyPSB5tB5RPbhczc.
Are you sure you want to continue connecting (yes/no)? yes
Failed to add the host to the list of known hosts (/home/bandit28/.ssh/known_hosts).
This is a OverTheWire game server. More information on http://www.overthewire.org/wargames
bandit28-git@localhost's password: 
remote: Counting objects: 9, done.
remote: Compressing objects: 100% (6/6), done.
remote: Total 9 (delta 2), reused 0 (delta 0)
Receiving objects: 100% (9/9), done.
Resolving deltas: 100% (2/2), done.
Checking connectivity... done.
bandit28@bandit:/tmp/repository1$ cat repo/README.md 
# Bandit Notes
Some notes for level29 of bandit.

## credentials

- username: bandit29
- password: xxxxxxxxxx

bandit28@bandit:/tmp/repository1$ cd repo/
bandit28@bandit:/tmp/repository1/repo$ git log
commit 04e2414585ba775805a49b78d662d0946d08f27a
Author: Morla Porla <morla@overthewire.org>
Date:   Sun Jul 22 14:47:13 2018 +0200

    fix info leak

commit 196c3edc79e362fe89e0d75cfeef079d8c67beef
Author: Morla Porla <morla@overthewire.org>
Date:   Sun Jul 22 14:47:13 2018 +0200

    add missing data

commit 80383714fa509a363756866425b0b697e87824a0
Author: Ben Dover <noone@overthewire.org>
Date:   Sun Jul 22 14:47:13 2018 +0200

    initial commit of README.md
bandit28@bandit:/tmp/repository1/repo$ git log -p -2
commit 04e2414585ba775805a49b78d662d0946d08f27a
Author: Morla Porla <morla@overthewire.org>
Date:   Sun Jul 22 14:47:13 2018 +0200

    fix info leak

diff --git a/README.md b/README.md
index 3f7cee8..5c6457b 100644
--- a/README.md
+++ b/README.md
@@ -4,5 +4,5 @@ Some notes for level29 of bandit.
 ## credentials
 
 - username: bandit29
-- password: bbc96594b4e001778eee9975372716b2
+- password: xxxxxxxxxx
 

commit 196c3edc79e362fe89e0d75cfeef079d8c67beef
Author: Morla Porla <morla@overthewire.org>
Date:   Sun Jul 22 14:47:13 2018 +0200

    add missing data

diff --git a/README.md b/README.md
index 7ba2d2f..3f7cee8 100644
--- a/README.md
+++ b/README.md
@@ -4,5 +4,5 @@ Some notes for level29 of bandit.
 ## credentials
 
 - username: bandit29
-- password: <TBD>
+- password: bbc96594b4e001778eee9975372716b2

Nivel 29 -> Nivel 30

Este nivel es muy parecido a los dos anteriores, la diferencia ahora es que la contraseña correcta está en la rama dev.

bandit29@bandit:~$ mkdir /tmp/repository2
bandit29@bandit:~$ cd /tmp/repository2
bandit29@bandit:/tmp/repository2$ git clone ssh://bandit29-git@localhost/home/bandit29-git/repo
Cloning into 'repo'...
Could not create directory '/home/bandit29/.ssh'.
The authenticity of host 'localhost (127.0.0.1)' can't be established.
ECDSA key fingerprint is SHA256:98UL0ZWr85496EtCRkKlo20X3OPnyPSB5tB5RPbhczc.
Are you sure you want to continue connecting (yes/no)? yes
Failed to add the host to the list of known hosts (/home/bandit29/.ssh/known_hosts).
This is a OverTheWire game server. More information on http://www.overthewire.org/wargames
bandit29-git@localhost's password: 
remote: Counting objects: 16, done.
remote: Compressing objects: 100% (11/11), done.
remote: Total 16 (delta 2), reused 0 (delta 0)
Receiving objects: 100% (16/16), done.
Resolving deltas: 100% (2/2), done.
Checking connectivity... done.
bandit29@bandit:/tmp/repository2$ cd repo
bandit29@bandit:/tmp/repository2/repo$ git show-branch -a
* [master] fix username
 ! [origin/HEAD] fix username
  ! [origin/dev] add data needed for development
   ! [origin/master] fix username
    ! [origin/sploits-dev] add some silly exploit, just for shit and giggles
-----
    + [origin/sploits-dev] add some silly exploit, just for shit and giggles
  +   [origin/dev] add data needed for development
  +   [origin/dev^] add gif2ascii
*++++ [master] fix username
bandit29@bandit:/tmp/repository2/repo$ git branch -a
* master
  remotes/origin/HEAD -> origin/master
  remotes/origin/dev
  remotes/origin/master
  remotes/origin/sploits-dev
bandit29@bandit:/tmp/repository2/repo$ git checkout remotes/origin/dev        
Previous HEAD position was d59303d... add some silly exploit, just for shit and giggles
HEAD is now at 77ec80e... add data needed for development
bandit29@bandit:/tmp/repository2/repo$ cat README.md 
# Bandit Notes
Some notes for bandit30 of bandit.

## credentials

- username: bandit30
- password: 5b90576bedb2cc04c86a9e924ce42faf

Nivel 30 -> Nivel 31

Parecido a los anteriores, esta vez parece ser que hay un tag llamado "secret" que al intentar movernos a él nos dice que nos existe. Si comprobamos el contenido de .git/packed-refs observamos el hash de secret, si comprobamos el tipo con cat-file -t observamos que es un blob, para listar su contenido podemos usar el comando cat-file -p.

bandit30@bandit:~$ mkdir /tmp/repository3
bandit30@bandit:~$ cd /tmp/repository3
bandit30@bandit:/tmp/repository3$ git clone ssh://bandit30-git@localhost/home/bandit30-git/repo
Cloning into 'repo'...
Could not create directory '/home/bandit30/.ssh'.
The authenticity of host 'localhost (127.0.0.1)' can't be established.
ECDSA key fingerprint is SHA256:98UL0ZWr85496EtCRkKlo20X3OPnyPSB5tB5RPbhczc.
Are you sure you want to continue connecting (yes/no)? yes
Failed to add the host to the list of known hosts (/home/bandit30/.ssh/known_hosts).
This is a OverTheWire game server. More information on http://www.overthewire.org/wargames
bandit30-git@localhost's password: 
remote: Counting objects: 4, done.
remote: Total 4 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (4/4), done.
Checking connectivity... done.
bandit30@bandit:/tmp/repository3$ cd repo/
bandit30@bandit:/tmp/repository3/repo$ cat README.md 
just an epmty file... muahaha
bandit30@bandit:/tmp/repository3/repo$ git branch -a
* master
  remotes/origin/HEAD -> origin/master
  remotes/origin/master
bandit30@bandit:/tmp/repository3/repo$ git tag
secret
bandit30@bandit:/tmp/repository3/repo$ git checkout tags/secret
fatal: reference is not a tree: tags/secret
bandit30@bandit:/tmp/repository3/repo$ cat .git/packed-refs 
# pack-refs with: peeled fully-peeled 
1791c9d4a559bffa4e6e89c15f7723167da10bb8 refs/remotes/origin/master
f17132340e8ee6c159e0a4a6bc6f80e1da3b1aea refs/tags/secret
bandit30@bandit:/tmp/repository3/repo$ git cat-file -t f17132340e8ee6c159e0a4a6bc6f80e1da3b1aea
blob
bandit30@bandit:/tmp/repository3/repo$ git cat-file -p f17132340e8ee6c159e0a4a6bc6f80e1da3b1aea
47e603bb428404d265f59c42920d81e5

Nivel 31 -> Nivel 32

Parecido a los anteriores. En este caso basta con hacer un push al servidor remoto, pero antes debemos crear un fichero con un contenido especial, el problema es que la extensión de este fichero (.txt) es ignorado por git, ya que está en .gitignore. Para solucionar este nivel tendremos que eliminar el fichero .gitignore y hacer el push.

bandit31@bandit:~$ mkdir /tmp/repository4
bandit31@bandit:~$ cd /tmp/repository4
bandit31@bandit:/tmp/repository4$ git clone ssh://bandit31-git@localhost/home/bandit31-git/repo
Cloning into 'repo'...
Could not create directory '/home/bandit31/.ssh'.
The authenticity of host 'localhost (127.0.0.1)' can't be established.
ECDSA key fingerprint is SHA256:98UL0ZWr85496EtCRkKlo20X3OPnyPSB5tB5RPbhczc.
Are you sure you want to continue connecting (yes/no)? yes
Failed to add the host to the list of known hosts (/home/bandit31/.ssh/known_hosts).
This is a OverTheWire game server. More information on http://www.overthewire.org/wargames
bandit31-git@localhost's password: 
remote: Counting objects: 4, done.
remote: Compressing objects: 100% (3/3), done.
remote: Total 4 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (4/4), done.
Checking connectivity... done.
bandit31@bandit:/tmp/repository4$ cd repo/
bandit31@bandit:/tmp/repository4/repo$ ls
README.md
bandit31@bandit:/tmp/repository4/repo$ cat README.md 
This time your task is to push a file to the remote repository.

Details:
    File name: key.txt
    Content: 'May I come in?'
    Branch: master

bandit31@bandit:/tmp/repository4/repo$ git branch -a
* master
  remotes/origin/HEAD -> origin/master
  remotes/origin/master
bandit31@bandit:/tmp/repository4/repo$ git tag
bandit31@bandit:/tmp/repository4/repo$ echo "May I come in?" >> key.txt
bandit31@bandit:/tmp/repository4/repo$ git add key.txt 
The following paths are ignored by one of your .gitignore files:
key.txt
Use -f if you really want to add them.
bandit31@bandit:/tmp/repository4/repo$ cat .gitignore 
*.txt
bandit31@bandit:/tmp/repository4/repo$ rm .gitignore 
bandit31@bandit:/tmp/repository4/repo$ git add key.txt 
bandit31@bandit:/tmp/repository4/repo$ git commit -m "commit"
[master 8a91364] commit
 1 file changed, 1 insertion(+)
 create mode 100644 key.txt
bandit31@bandit:/tmp/repository4/repo$ git push origin master
Could not create directory '/home/bandit31/.ssh'.
The authenticity of host 'localhost (127.0.0.1)' can't be established.
ECDSA key fingerprint is SHA256:98UL0ZWr85496EtCRkKlo20X3OPnyPSB5tB5RPbhczc.
Are you sure you want to continue connecting (yes/no)? yes
Failed to add the host to the list of known hosts (/home/bandit31/.ssh/known_hosts).
This is a OverTheWire game server. More information on http://www.overthewire.org/wargames
bandit31-git@localhost's password: 
Counting objects: 3, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 315 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
remote: ### Attempting to validate files... ####
remote: 
remote: .oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.
remote: 
remote: Well done! Here is the password for the next level:
remote: 56a9bf19c63d650ce78e6ec0354ee45e
remote: 
remote: .oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.
remote: 
To ssh://bandit31-git@localhost/home/bandit31-git/repo
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'ssh://bandit31-git@localhost/home/bandit31-git/repo'

Nivel 32 -> Nivel 33

Este nivel se trata de evadir las medidas de seguridad de un binario con el bit s activo. Aquí emplee dos enfoques, uno con ingeniería inversa, que fue una ida de olla pero lo dejo porque puede ser interesante y otro que es la forma correcta en la que se me ocurrió solucionar el reto.

El objetivo se trata de hacer un cat a un fichero en /etc/bandit_pass que contiene la contraseña. Para ello hay que usar el binario con el bit s activo (como en otros nivel). La diferencia es que este binario te habilita una shell donde puedes escribir comandos, pero al ejecutarlos se ejecutan en mayúsculas.

El primer enfoque que usé fue hacer uso de GDB y parquear (nopear, 0x90) las instrucciones que pasan a mayúsculas el comando introducido. El problema con este enfoque es que al depurar programas que tienen el bit s activo este se deshabilita automaticamente por tanto no es posible conseguir la contraseña de esta forma, aún así lo dejo porque puede resultar interesante.

 bandit32@bandit:~$ ls
uppershell
bandit32@bandit:~$ ll
total 28
drwxr-xr-x  2 root     root     4096 Jul 22 18:59 ./
drwxr-xr-x 42 root     root     4096 Jul 22 18:42 ../
-rw-r--r--  1 root     root      220 Sep  1  2015 .bash_logout
-rw-r--r--  1 root     root     3771 Sep  1  2015 .bashrc
-rw-r--r--  1 root     root      655 Jun 24  2016 .profile
-rwsr-x---  1 bandit33 bandit32 7668 Jul 22 18:59 uppershell*
bandit32@bandit:~$ file uppershell 
uppershell: setuid ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=cdff8f7c7d0798f2f0b06721115c5dce7db6ed1e, not stripped
bandit32@bandit:~$ ./uppershell 
WELCOME TO THE UPPERCASE SHELL
>> ls
sh: 1: LS: not found
>> ^C
bandit32@bandit:~$ gdb -q ./uppershell
Reading symbols from ./uppershell...(no debugging symbols found)...done.
(gdb) break main
Breakpoint 1 at 0x80485c1
(gdb) run
Starting program: /home/bandit32/uppershell 

Breakpoint 1, 0x080485c1 in main ()
(gdb) disassemble 
Dump of assembler code for function main:
   0x080485bd <+0>:    push   %ebp
   0x080485be <+1>:    mov    %esp,%ebp
   0x080485c0 <+3>:    push   %ebx
=> 0x080485c1 <+4>:    and    $0xfffffff0,%esp
   0x080485c4 <+7>:    sub    $0x420,%esp
   0x080485ca <+13>:    mov    0xc(%ebp),%eax
   0x080485cd <+16>:    mov    %eax,0xc(%esp)
   0x080485d1 <+20>:    mov    %gs:0x14,%eax
   0x080485d7 <+26>:    mov    %eax,0x41c(%esp)
   0x080485de <+33>:    xor    %eax,%eax
   0x080485e0 <+35>:    call   0x8048440 <geteuid@plt>
   0x080485e5 <+40>:    mov    %eax,%ebx
   0x080485e7 <+42>:    call   0x8048440 <geteuid@plt>
   0x080485ec <+47>:    mov    %ebx,0x4(%esp)
   0x080485f0 <+51>:    mov    %eax,(%esp)
   0x080485f3 <+54>:    call   0x8048480 <setreuid@plt>
   0x080485f8 <+59>:    movl   $0x8048720,(%esp)
   0x080485ff <+66>:    call   0x8048450 <puts@plt>
   0x08048604 <+71>:    movl   $0x804873f,(%esp)
   0x0804860b <+78>:    call   0x8048410 <printf@plt>
   0x08048610 <+83>:    movl   $0x0,(%esp)
   0x08048617 <+90>:    call   0x8048420 <fflush@plt>
   0x0804861c <+95>:    mov    0x804a040,%eax
   0x08048621 <+100>:    mov    %eax,0x8(%esp)
   0x08048625 <+104>:    movl   $0x3ff,0x4(%esp)
   0x0804862d <+112>:    lea    0x1c(%esp),%eax
   0x08048631 <+116>:    mov    %eax,(%esp)
   0x08048634 <+119>:    call   0x8048430 <fgets@plt>
   0x08048639 <+124>:    test   %eax,%eax
   0x0804863b <+126>:    jne    0x8048649 <main+140>
   0x0804863d <+128>:    movl   $0x1,(%esp)
   0x08048644 <+135>:    call   0x8048470 <exit@plt>
   0x08048649 <+140>:    movl   $0x0,0x18(%esp)
   0x08048651 <+148>:    jmp    0x804867c <main+191>
   0x08048653 <+150>:    lea    0x1c(%esp),%edx
   0x08048657 <+154>:    mov    0x18(%esp),%eax
   0x0804865b <+158>:    add    %edx,%eax
---Type <return> to continue, or q <return> to quit---
   0x0804865d <+160>:    movzbl (%eax),%eax
   0x08048660 <+163>:    movsbl %al,%eax
   0x08048663 <+166>:    mov    %eax,(%esp)
   0x08048666 <+169>:    call   0x80484a0 <toupper@plt>
   0x0804866b <+174>:    lea    0x1c(%esp),%ecx
   0x0804866f <+178>:    mov    0x18(%esp),%edx
   0x08048673 <+182>:    add    %ecx,%edx
   0x08048675 <+184>:    mov    %al,(%edx)
   0x08048677 <+186>:    addl   $0x1,0x18(%esp)
   0x0804867c <+191>:    lea    0x1c(%esp),%edx
   0x08048680 <+195>:    mov    0x18(%esp),%eax
   0x08048684 <+199>:    add    %edx,%eax
   0x08048686 <+201>:    movzbl (%eax),%eax
   0x08048689 <+204>:    test   %al,%al
   0x0804868b <+206>:    jne    0x8048653 <main+150>
   0x0804868d <+208>:    lea    0x1c(%esp),%eax
   0x08048691 <+212>:    mov    %eax,(%esp)
   0x08048694 <+215>:    call   0x8048460 <system@plt>
   0x08048699 <+220>:    jmp    0x8048604 <main+71>
End of assembler dump.
(gdb) set *(char*)0x08048666 = 0x90
(gdb) set *(char*)0x08048667 = 0x90
(gdb) set *(char*)0x08048668 = 0x90
(gdb) set *(char*)0x08048669 = 0x90
(gdb) set *(char*)0x0804866a = 0x90
(gdb) disassemble 
Dump of assembler code for function main:
   0x080485bd <+0>:    push   %ebp
   0x080485be <+1>:    mov    %esp,%ebp
   0x080485c0 <+3>:    push   %ebx
=> 0x080485c1 <+4>:    and    $0xfffffff0,%esp
   0x080485c4 <+7>:    sub    $0x420,%esp
   0x080485ca <+13>:    mov    0xc(%ebp),%eax
   0x080485cd <+16>:    mov    %eax,0xc(%esp)
   0x080485d1 <+20>:    mov    %gs:0x14,%eax
   0x080485d7 <+26>:    mov    %eax,0x41c(%esp)
   0x080485de <+33>:    xor    %eax,%eax
   0x080485e0 <+35>:    call   0x8048440 <geteuid@plt>
   0x080485e5 <+40>:    mov    %eax,%ebx
   0x080485e7 <+42>:    call   0x8048440 <geteuid@plt>
   0x080485ec <+47>:    mov    %ebx,0x4(%esp)
   0x080485f0 <+51>:    mov    %eax,(%esp)
   0x080485f3 <+54>:    call   0x8048480 <setreuid@plt>
   0x080485f8 <+59>:    movl   $0x8048720,(%esp)
   0x080485ff <+66>:    call   0x8048450 <puts@plt>
   0x08048604 <+71>:    movl   $0x804873f,(%esp)
   0x0804860b <+78>:    call   0x8048410 <printf@plt>
   0x08048610 <+83>:    movl   $0x0,(%esp)
   0x08048617 <+90>:    call   0x8048420 <fflush@plt>
   0x0804861c <+95>:    mov    0x804a040,%eax
   0x08048621 <+100>:    mov    %eax,0x8(%esp)
   0x08048625 <+104>:    movl   $0x3ff,0x4(%esp)
   0x0804862d <+112>:    lea    0x1c(%esp),%eax
   0x08048631 <+116>:    mov    %eax,(%esp)
   0x08048634 <+119>:    call   0x8048430 <fgets@plt>
   0x08048639 <+124>:    test   %eax,%eax
   0x0804863b <+126>:    jne    0x8048649 <main+140>
   0x0804863d <+128>:    movl   $0x1,(%esp)
   0x08048644 <+135>:    call   0x8048470 <exit@plt>
   0x08048649 <+140>:    movl   $0x0,0x18(%esp)
   0x08048651 <+148>:    jmp    0x804867c <main+191>
   0x08048653 <+150>:    lea    0x1c(%esp),%edx
   0x08048657 <+154>:    mov    0x18(%esp),%eax
   0x0804865b <+158>:    add    %edx,%eax
---Type <return> to continue, or q <return> to quit---
   0x0804865d <+160>:    movzbl (%eax),%eax
   0x08048660 <+163>:    movsbl %al,%eax
   0x08048663 <+166>:    mov    %eax,(%esp)
   0x08048666 <+169>:    nop
   0x08048667 <+170>:    nop
   0x08048668 <+171>:    nop
   0x08048669 <+172>:    nop
   0x0804866a <+173>:    nop
   0x0804866b <+174>:    lea    0x1c(%esp),%ecx
   0x0804866f <+178>:    mov    0x18(%esp),%edx
   0x08048673 <+182>:    add    %ecx,%edx
   0x08048675 <+184>:    mov    %al,(%edx)
   0x08048677 <+186>:    addl   $0x1,0x18(%esp)
   0x0804867c <+191>:    lea    0x1c(%esp),%edx
   0x08048680 <+195>:    mov    0x18(%esp),%eax
   0x08048684 <+199>:    add    %edx,%eax
   0x08048686 <+201>:    movzbl (%eax),%eax
   0x08048689 <+204>:    test   %al,%al
   0x0804868b <+206>:    jne    0x8048653 <main+150>
   0x0804868d <+208>:    lea    0x1c(%esp),%eax
   0x08048691 <+212>:    mov    %eax,(%esp)
   0x08048694 <+215>:    call   0x8048460 <system@plt>
   0x08048699 <+220>:    jmp    0x8048604 <main+71>
End of assembler dump.
(gdb) c
Continuing.
WELCOME TO THE UPPERCASE SHELL
>> ls
uppershell
>> cat /etc/bandit_pass/bandit33
56a9bf19c63d650ce78e6ec0354ee45e

El segundo enfoque es almacenar en una variable de entorno el comando que se quiere ejecutar dentro de la shell y dentro de esta shell hacer una llamada a dicha variable (que contiene el comando a ejecutar).

bandit32@bandit:~$ ls
uppershell
bandit32@bandit:~$ ll
total 28
drwxr-xr-x  2 root     root     4096 Jul 22 18:59 ./
drwxr-xr-x 42 root     root     4096 Jul 22 18:42 ../
-rw-r--r--  1 root     root      220 Sep  1  2015 .bash_logout
-rw-r--r--  1 root     root     3771 Sep  1  2015 .bashrc
-rw-r--r--  1 root     root      655 Jun 24  2016 .profile
-rwsr-x---  1 bandit33 bandit32 7668 Jul 22 18:59 uppershell*
bandit32@bandit:~$ file uppershell 
uppershell: setuid ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=cdff8f7c7d0798f2f0b06721115c5dce7db6ed1e, not stripped
bandit32@bandit:~$ ./uppershell 
WELCOME TO THE UPPERCASE SHELL
>> cat /etc/bandit_pass/bandit33
sh: 1: CAT: not found
bandit32@bandit:~$ ls
uppershell
bandit32@bandit:~$ COMMAND="cat /etc/bandit_pass/bandit33" ./uppershell 
WELCOME TO THE UPPERCASE SHELL
>> $COMMAND
c9c3199ddf4121b10cf581a98d51caee

Nivel 33 -> Nivel 34

Llegados a este nivel hemos terminado todos los retos de bandit!

bandit33@bandit:~$ ls
README.txt
bandit33@bandit:~$ cat README.txt 
Congratulations on solving the last level of this game!

At this moment, there are no more levels to play in this game. However, we are constantly working
on new levels and will most likely expand this game with more levels soon.
Keep an eye out for an announcement on our usual communication channels!
In the meantime, you could play some of our other wargames.

If you have an idea for an awesome new level, please let us know!