Il mio blog-spazio.

OverTheWire Bandit : Hack Game via SSH [episodio 1]

I giochi offerti da OverTheWire
possono aiutarti ad imparare e praticare i concetti di sicurezza sotto forma di giochi divertenti.
Vediamo di cosa si tratta!



In Italia non ne parla nessuno ( :'( chissà perchè ), si tratta di una serie di giochi,
definiti come WarGame, realizzati dalla Community di OverTheWire.

I giochi sono i seguenti:
Bandit
Natas
Leviathan
Narnia
Krypton
Behemoth
Utumno
Maze
Vortex
Semtex
Manpage
Drifter


e sono in Ordine di difficoltà.

Li trovate qui:
http://overthewire.org/wargames/


Si consiglia di partire con Bandit, vi spiego in cosa consiste.
Si tratta di un -game- via ssh.
Per accedervi vi basterà una console o putty / kitty.
(scaricateli nel mio repo (qui), in versione portable da pochissimi Kb)

Una volta prelevato il client, si inizia il gioco.
Bisogna inserire l'host del gioco, ovvero:

bandit.labs.overthewire.org su porta 2220
come username: bandit0
e come password, la stessa: bandit0



Siete dentro al gioco.

Si tratta di 26 livelli da superare.
Gli indizi sono disponibili sul sito ufficiale.

Vi spiego il primo livello,
http://overthewire.org/wargames/bandit/bandit1.html
Come da link,
dovete trovare la password dell'user bandit1 (ora siete loggati dentro la macchina come bandit0)
per farlo, nella home
quindi
/home/bandit0

avete un file chiamato
readme
(leggimi)
dovete usare il comando "cat"
in questa maniera:
cat file.txt

nel nostro caso
cat readme


Avete ottenuto la password dell'utente bandit1


Ora da putty/kitty/console bash,
potete riloggarvi con
nome utente : bandit1
pwd: boJ9jbbUNNfktd78OOpsqOltutMc3MY1

e potete passare al Livello 2.

Ogni volta che trovate una password per un livello, usate SSH (sulla porta 2220) per accedere al livello successivo e continuare il gioco.

Al secondo livello vi si chiede questo:
http://overthewire.org/wargames/bandit/bandit2.html

Siamo alle basi, comunque risulta essere molto divertente.

Vi posto le soluzioni qui in basso, ma non andate a guardarle subito.
Prima provate da voi.




SEGUE SPOILERONE



Livello 2
un file, chiamato - non può essere letto semplicemente facendo
cat -
essendo - l'estensione di un comando.
Dovete fare il seguente comando
cat ./-

potete ora loggarvi con bandit2 e password: CV1DtqXWVFXTvM2F0k09SHz0YwRINYA9

Livello 3
La password si trova in un file chiamato spaces in this filename
quindi il file contiene degli spazi,
Come facciamo cat su un file con gli spazi?
Si può inserire un \ prima del file, ma io consiglio sempre di richiamarlo con delle ""
quindi
bandit2@bandit:~$ cat "spaces in this filename"
UmHadQclWmgdLOKQ3YNgjWxGoRMb5luK
bandit2@bandit:~$


ok,
user bandit3
pwd UmHadQclWmgdLOKQ3YNgjWxGoRMb5luK

Livello 4
C'è un file nascosto, dentro la cartella inhere
per mostrare i file nascosti si usa la funzione ls -a
il file si chiama .hidden


cat inhere/.hidden

la password è : pIwrPrtPN36QITSp3EQaw936yaFoFgAB
potete loggarvi con l'user bandit4

Livello 5
nella cartella inhere
avete diversi file, molti sono nulli, altri illeggibili,
-file00 -file02 -file04 -file06 -file08 .
-file01 -file03 -file05 -file07 -file09 ..

iniziano tutti con la dicitura -file
per cui è semplice, le leggiamo tutti con un colpo solo, essendo il 95% di questi vuoti;
quindi invece di fare cat per ogni file usiamo strings
entriamo in inhere ( cd inhere )
diamo un strings ./-file*



avete ottenuto la password: koReBOKuIDDepwhWk7jZC0RTdopnAYKh
user del prossimo login: bandit5

Livello 6
ci chiedono di trovare un file con le seguenti caratteristiche
human-readable
1033 bytes in size
not executable

andiamo per grandezza, usiamo il find

si trovano diversi file sempre nella cartella inhere
. maybehere02 maybehere06 maybehere10 maybehere14 maybehere18
.. maybehere03 maybehere07 maybehere11 maybehere15 maybehere19
maybehere00 maybehere04 maybehere08 maybehere12 maybehere16
maybehere01 maybehere05 maybehere09 maybehere13 maybehere17

diamo quindi
find inhere/ -size 1033c



ci troverà il file, risulta essere il .file2
cat "inhere/maybehere07/.file2"

abbiamo la pass:
DXjZPULLxYr17uwoI01bNLQbtFemEgo7
prox username bandit6

Livello 7
Come per il livello 6, ci chiedono di trovare un file, questa volta però è da qualche parte nel server, non in una cartella nota.
The password for the next level is stored somewhere on the server and has all of the following properties:

owned by user bandit7
owned by group bandit6
33 bytes in size


ci affidiamo sempre al find
find / -size 33c -user bandit7 -group bandit6

diciamo che pesa 33bytes che il file è dell'utente bandit7 gruppo bandit6
avrete una serie di access denied non essendo root della macchina, districatevi tra questi,
ci sarà un file che contiene la password.
questo:
/var/lib/dpkg/info/bandit7.password


cat /var/lib/dpkg/info/bandit7.password

abbiamo ottenuto la passwd:
HKBPTKQnIay4Fw76bEy8PVxKEDQRKTzs
prossimo login: bandit7

Livello 8
ci chiedono
The password for the next level is stored in the file data.txt next to the word millionth

chiaro l'uso di grep.
cat data.txt | grep millionth



il risultato sarà :
millionth cvX2JJa4CFALtqS87jk27qwqGhBM9plV
quindi la password: cvX2JJa4CFALtqS87jk27qwqGhBM9plV
login: bandit8

Livello 9
richiesta: The password for the next level is stored in the file data.txt and is the only line of text that occurs only once

Dentro al file data.txt troverete una marea di password, solo una di queste non si ripete.
(le altre si ripetono 10volte)

ci viene in soccorso uniq -u
sort data.txt | uniq -u
ci indicherà quante volte si ripete una riga (tutte 10 volte, meno una, la nostra, che si ripetera onlyone)

bandit9
UsvVyFSfZZWbi6wgC7dAFyFuR6jQQUhR

Livello 10
richiesta:The password for the next level is stored in the file data.txt in one of the few human-readable strings, beginning with several ‘=’ characters.

Ci dice che ci sono caratteri illeggibili, ma che qualcosa è leggibile, ed inizia con diversi ==
abbiamo bisogno sempre di grep + strings

strings data.txt | grep '===='




login bandit10
pwd truKLdjsbJ5g7yyJ2X2R0o3a5HQJFuLk

Livello 11
The password for the next level is stored in the file data.txt, which contains base64 encoded data
quindi dentro a file data.txt abbiamo un hash encodado in base64
quindi sarà da decodificare.
L'hash è questo :
VGhlIHBhc3N3b3JkIGlzIElGdWt3S0dzRlc4TU9xM0lSRnFyeEUxaHhUTkViVVBSCg==
direttamente dalla console, diamo un bel
base64 -d data.txt




come ci risponde base64,
The password is IFukwKGsFW8MOq3IRFqrxE1hxTNEbUPR
Login bandit11

Livello 12
The password for the next level is stored in the file data.txt, where all lowercase (a-z) and uppercase (A-Z) letters have been rotated by 13 positions

Giulio Cesare è noto anche per la sua crittografia,
Il Cifrario di Cesare
è uno dei più antichi algoritmi crittografici di cui si abbia traccia storica.

Qui abbiamo un cifrario monoalfabetico che non si vedeva online tipo dal 2003.
Ammetto di averlo usato su IRC.
La codifica si chiama ROT13
dettagli su wiki https://it.wikipedia.org/wiki/ROT13
ogni lettera è sostituita con quella posta 13 posizioni più avanti nell'alfabeto

Uso l'esempio di Wiki:
Originale LA SCENA IN CUI IL PERSONAGGIO PRINCIPALE MUORE NON MI PIACE
Criptato YN FPRAN VA PHV VY CREFBANTTVB CEVAPVCNYR ZHBER ABA ZV CVNPR

:-O 8-) Una figata dai.
Torniamo a noi,

$ cat data.txt
Gur cnffjbeq vf 5Gr8L4qetPEsPk8htqjhRK8XSP6x2RHh


Siccome sono nel 2018 e non mi pare il caso di prendere carta e penna,
possiamo risolverlo in tanti modi, mi viene in mente
bash o php, ma anche python o ruby.

Ruby
ruby -ne 'print $_.tr( "A-Za-z", "N-ZA-Mn-za-m") ' file


Python
echo "test" | python -c 'import sys; print sys.stdin.read().encode("rot13")'


purtroppo sulla macchina non sono installati come package, quindi vediamo cosa abbiamo.
Tocca usare Bash,
facciamo un alias ed usiamo tr (transliterate)
esempio pratico:
alias rot13="tr '[A-Za-z]' '[N-ZA-Mn-za-m]'"
echo -e "Gur cnffjbeq vf 5Gr8L4qetPEsPk8htqjhRK8XSP6x2RHh"|rot13





Ci siamo.
The password is 5Te8Y4drgCRfCx8ugdwuEX8KFC6k2EUu
Username: bandit12

Livello 13
The password for the next level is stored in the file data.txt, which is a hexdump of a file that has been repeatedly compressed. For this level it may be useful to create a directory under /tmp in which you can work using mkdir. For example: mkdir /tmp/myname123. Then copy the datafile using cp, and rename it using mv (read the manpages!)

Ammetto di non aver mai usato hexdumps, è una cosa nuova per me.
(lo vedi che serve a qualcosa questo giochino?)

Dopo una breve lettura del manuale ( comando: man xxd )

dovendo manipolare il file e non potendo in cartella /home/bandit12
vado in tmp

mkdir /tmp/alessio;
cp data.txt /tmp/alessio/;
cd /tmp/alessio/;
ls


ho copiato il file data.txt in /tmp/alessio
e mi ci sono spostato.

Ora inizia l'impazzimento:
xxd - make a hexdump or do the reverse.
xxd -r data.txt prova.bin


controlliamo che roba abbiamo creato:
$ file prova.bin
prova.bin: gzip compressed data, was "data2.bin", last modified: Thu Dec 28 13:34:36 2017, max compression, from Unix


compresso con gzip, quindi operiamo con gunzip
ma prima dobbiamo rinominarloda prova.bin a prova.gz
mv prova.bin prova.gz


gunzip -d prova.gz


ci viene fuori un file, ora si chiama prova senza alcuna estensione.
Vediamo di cosa si tratta.

$ file prova
prova: bzip2 compressed data, block size = 900k


Si sono divertiti, ora è compresso con bzip2.
quindi
bzip2 -d prova

e controlliamo cosa abbiamo tirato fuori.
Adesso il file si chiama prova.out

$ ls
data.txt prova.out
$ file prova.out
prova.out: gzip compressed data, was "data4.bin", last modified: Thu Dec 28 13:34:36 2017, max compression, from Unix


Di nuovo GZIP maledetti :-P

rinominiamo quindi in .gz

$ mv prova.out prova.out.gz


gunzip -d prova.out.gz


controllando dando sempre il comando file

$ file prova.out
prova.out: POSIX tar archive (GNU)


Archivio tar compresso, ci stanno trollando.
Avrà mai una fine?
Vediamo..

$ tar -xvf prova.out
data5.bin


Diamo sempre file data5.bin
uff, ancora tar..

mv data5.bin data5.bin.tar


$ tar -xvf data5.bin.tar
data6.bin


$ file data6.bin
data6.bin: bzip2 compressed data, block size = 900k


Ora, i più pazienti andranno avanti, gli altri possono iniziare a bestemmiare.

mv data6.bin data6.bin.gz2


$ bzip2 -d data6.bin.gz2
bzip2: Can't guess original name for data6.bin.gz2 -- using data6.bin.gz2.out
$ ls
data.txt data5.bin.tar data6.bin.gz2.out prova.out


che sarebbe sto out?

$ file data6.bin.gz2.out
data6.bin.gz2.out: POSIX tar archive (GNU)


Secondo me hanno esagerato. Comunque..

$ mv data6.bin.gz2.out data6.bin.gz2.out.tar
$ tar -xvf data6.bin.gz2.out.tar
data8.bin


$ file data8.bin
data8.bin: gzip compressed data, was "data9.bin", last modified: Thu Dec 28 13:34:36 2017, max compression, from Unix


....

$ mv data8.bin data8.bin.gz
$ gunzip data8.bin.gz
$ file data8.bin
data8.bin: ASCII text


Ci siamo!

$ cat data8.bin
The password is 8ZjyCRiBWFYkneahHwxCv3wb2a1ORpYL



Alleluja!

Username: bandit13
Password 8ZjyCRiBWFYkneahHwxCv3wb2a1ORpYL


Livello 14
The password for the next level is stored in /etc/bandit_pass/bandit14 and can only be read by user bandit14. For this level, you don’t get the next password, but you get a private SSH key that can be used to log into the next level. Note: localhost is a hostname that refers to the machine you are working on

il 14 è facile, appena dentro, troverete
$ ls
sshkey.private


quindi non servirà una password per andare al prossimo livello, ma si usa questa RSA Key.
dando
ssh -i sshkey.private bandit14@localhost

siamo dentro con user bandit14
quindi si potrà accedere al file /etc/bandit_pass/bandit14
che contiene la password per il prossimo livello

$ cat /etc/bandit_pass/bandit14
4wcYUJFw0k0XLShlDzztnTBHiqxU3b3e


user bandit14
pass 4wcYUJFw0k0XLShlDzztnTBHiqxU3b3e


Livello 15
The password for the next level can be retrieved by submitting the password of the current level to port 30000 on localhost.

;-) La password la si ottiene connettendosi alla porta 30000, proviamo con telnet..

$ telnet localhost 30000
Trying ::1...
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.

Wrong! Please enter the correct current password
Connection closed by foreign host.


Ho semplicemente premuto Invio, e mi ha dato un errore, di password errata, ah!
E che passowrd gli dò? Ho provato quella della sessione appena aperta di SSH
4wcYUJFw0k0XLShlDzztnTBHiqxU3b3e
Correct! :-O 8-)

Escape character is '^]'.
4wcYUJFw0k0XLShlDzztnTBHiqxU3b3e
Correct!
BfMYroe26WYalil77FoDi9qh59eK5xNr


Ottenuta la password anche qui.

user bandit15
pass BfMYroe26WYalil77FoDi9qh59eK5xNr


Livello 16

The password for the next level can be retrieved by submitting the password of the current level to port 30001 on localhost using SSL encryption.

Helpful note: Getting “HEARTBEATING” and “Read R BLOCK”? Use -ign_eof and read the “CONNECTED COMMANDS” section in the manpage. Next to ‘R’ and ‘Q’, the ‘B’ command also works in this version of that command…

Come per il 15, ma adesso bisogna collegarsi tramite una sessioni di openssl quindi criptata.
Sono andato spedito sparando un

openssl s_client -connect localhost:30001


effettivamente andava in errore con un
HEARTBEATING
read R BLOCK


Come ci suggerisce la nota sul sito, bisogna usare il -ign_eof
quindi
openssl s_client -ign_eof -connect localhost:30001


Verify return code: 18 (self signed certificate)
---
BfMYroe26WYalil77FoDi9qh59eK5xNr
Correct!
cluFn7wTiGryunymYOu4RcffSxQluehd

closed



user bandit16
pass cluFn7wTiGryunymYOu4RcffSxQluehd


Livello 17
The credentials for the next level can be retrieved by submitting the password of the current level to a port on localhost in the range 31000 to 32000. First find out which of these ports have a server listening on them. Then find out which of those speak SSL and which don’t. There is only 1 server that will give the next credentials, the others will simply send back to you whatever you send to it.

Dobbiamo scansionare un range di porte, alla ricerca di quella aperta con ssl.

nmap localhost -p 31000-32000


$ nmap localhost -p 31000-32000

Starting Nmap 7.01 ( https://nmap.org ) at 2018-03-19 18:14 CET
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00020s latency).
Other addresses for localhost (not scanned): ::1
Not shown: 996 closed ports
PORT STATE SERVICE
31046/tcp open unknown
31518/tcp open unknown
31691/tcp open unknown
31790/tcp open unknown
31960/tcp open unknown

Nmap done: 1 IP address (1 host up) scanned in 0.07 seconds


Non sono un grande esperto di nmap, sicuramente esiste un modo per dirgli di controllare quale di queste usa SSL,
ma senza fare una ricerca su san google non saprei come impostare lo scanner.
Essendo solo 5 porte, me ne frego e deciso di testarle da solo, sono 5 comandi, 10secondi scarsi

openssl s_client -connect localhost:31046
openssl s_client -connect localhost:31518
openssl s_client -connect localhost:31691
openssl s_client -connect localhost:31790
openssl s_client -connect localhost:31960


fino a che uno di questi non mi mostra un certificato al momento dell'ingresso.

bam trovato.

$ openssl s_client -connect localhost:31790
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: 4F607D1767257FF707F8F6F6123544F00CE1667859832C1A45C19E13D82B5C7B
Session-ID-ctx:
Master-Key: 64B9C90FB29E104F249F9603727C34DF58A1DEE35E28FCD3A7E4D708AE006C794F8F070FAC231C513C6DC5E45800B0A1
Key-Arg : None
PSK identity: None
PSK identity hint: None
SRP username: None
TLS session ticket lifetime hint: 7200 (seconds)
TLS session ticket:
0000 - 99 5c e0 c0 7e 5c 93 8f-9d 42 b4 48 1f 45 3b ac .\..~\...B.H.E;.
0010 - f9 21 62 3b cb 0e 61 6a-cf 50 69 9b 11 28 a4 8e .!b;..aj.Pi..(..
0020 - b3 86 1a 16 ce 39 a4 18-5f aa e0 ae 9a f9 91 5d .....9.._......]
0030 - 44 3e 1c a2 a7 51 dd a7-da a8 ec 69 f5 4e ca d9 D>...Q.....i.N..
0040 - 38 47 ba 60 50 cb 75 f3-5f 58 87 4e 7b 92 e3 67 8G.`P.u._X.N{..g
0050 - b8 29 87 3a f8 82 6a 31-76 cb f7 33 ca 14 5f a3 .).:..j1v..3.._.
0060 - 26 25 bc 28 c9 27 5e f5-7c 52 3b 43 13 ee 15 ac &%.(.'^.|R;C....
0070 - e8 97 48 25 4e 03 27 ae-1a fa e9 3d e8 9a ea 40 ..H%N.'....=...@
0080 - 41 f6 94 c0 3a ed 49 7d-7b 4a 46 6c 44 76 1e fd A...:.I}{JFlDv..
0090 - 95 d5 43 49 78 86 0c 90-ed 81 90 a0 38 6f 69 7c ..CIx.......8oi|

Start Time: 1521479864
Timeout : 300 (sec)
Verify return code: 18 (self signed certificate)
---
cluFn7wTiGryunymYOu4RcffSxQluehd
Correct!
-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAK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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


Ok mi ha risposto con una RSA Key, come per il livello 14, per passare al next level non servirà una password,
ma questa key.
Salviamola in tmp

mkdir /tmp/alessiokey; nano /tmp/alessiokey/key


copio la key

-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAvmOkuifmMg6HL2YPIOjon6iWfbp7c3jx34YkYWqUH57SUdyJ
imZzeyGC0gtZPGujUSxiJSWI/oTqexh+cAMTSMlOJf7+BrJObArnxd9Y7YT2bRPQ
Ja6Lzb558YW3FZl87ORiO+rW4LCDCNd2lUvLE/GL2GWyuKN0K5iCd5TbtJzEkQTu
DSt2mcNn4rhAL+JFr56o4T6z8WWAW18BR6yGrMq7Q/kALHYW3OekePQAzL0VUYbW
JGTi65CxbCnzc/w4+mqQyvmzpWtMAzJTzAzQxNbkR2MBGySxDLrjg0LWN6sK7wNX
x0YVztz/zbIkPjfkU1jHS+9EbVNj+D1XFOJuaQIDAQABAoIBABagpxpM1aoLWfvD
KHcj10nqcoBc4oE11aFYQw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dxviW8+TFVEBl1O4f7HVm6EpTscdDxU+bCXWkfjuRb7Dy9GOtt9JPsX8MBTakzh3
vBgsyi/sN3RqRBcGU40fOoZyfAMT8s1m/uYv52O6IgeuZ/ujbjY=
-----END RSA PRIVATE KEY-----


quindi
CTRL + X confermare il salvataggio con Y
cambio i permessi al file creato,
chmod 700 /tmp/alessiokey/key


entro:
ssh -i /tmp/alessiokey/key bandit17@localhost

Dentro!


Livello 18
There are 2 files in the homedirectory: passwords.old and passwords.new. The password for the next level is in passwords.new and is the only line that has been changed between passwords.old and passwords.new

NOTE: if you have solved this level and see ‘Byebye!’ when trying to log into bandit18, this is related to the next level, bandit19

Sappiamo che la password si ottiene con la differenza di parole tra i due file presenti nella home
(passwords.old passwords.new)
usiamo il comando diff

$ diff passwords.new passwords.old
42c42
< kfBf3eYk5BPBRzwjqutbbfE887SVc5Yd
---
> 6vcSC74ROI95NqkKaeEC2ABVMDX9TyUr



Abbiamo la password: kfBf3eYk5BPBRzwjqutbbfE887SVc5Yd
user bandit18

Livello 19
The password for the next level is stored in a file readme in the homedirectory. Unfortunately, someone has modified .bashrc to log you out when you log in with SSH.

Praticamente, modificando il file .bashrc hanno inserito una stringa che, al login,
si viene espulsi con un "Byebye!"

Noi sappiamo che esiste un file nella home che si chiama readme,
dopo un 2minuti di riflessione mi è venuto in mente solo un metodo, scp.

SCP è un protocollo per trasferire in modo sicuro un file tra un computer locale ed un host remoto o tra due host remoti, usando il protocollo Secure Shell (SSH)

Mi faccio una cartella in /tmp
$ mkdir /tmp/alessiotestscp


e ci provo

$ scp -i /tmp/alessiotestscp/ bandit18@localhost:readme /tmp/alessiotestscp/readme
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
This is a OverTheWire game server. More information on http://www.overthewire.org/wargames
bandit18@localhost's password:

readme 100% 33 0.0KB/s 00:00

$


Vediamo se ha trasferito!

$ cat /tmp/alessiotestscp/readme
IueksS7Ubh8G3DCwVzrTd8rAVOwq3M5x


Yessa!

Abbiamo la password per il prossimo step.
user bandit19
pass IueksS7Ubh8G3DCwVzrTd8rAVOwq3M5x


Livello 20
To gain access to the next level, you should use the setuid binary in the homedirectory. Execute it without arguments to find out how to use it. The password for this level can be found in the usual place (/etc/bandit_pass), after you have used the setuid binary.


Tutte le info su set uid qui : https://it.wikipedia.org/wiki/Setuid_e_setgid

Praticamente, se dò il comando con l'user loggato (bandit19) avrò un access denied

$ cat /etc/bandit_pass/bandit20
cat: /etc/bandit_pass/bandit20: Permission denied


"bandit20-do" può essere considerato un esempio di exploit, privilege escalation

bandit19@bandit:~$ ./bandit20-do whoami
bandit20

$ ./bandit20-do id
uid=11019(bandit19) gid=11019(bandit19) euid=11020(bandit20) groups=11019(bandit19)



Pur essendo bandit19@ con bandit20-do ho un UID di bandit20

essendo quindi il file /etc/bandit_pass/bandit20 accessibile solo a euid=11020(bandit20)
tramite bandit20-do posso leggerlo.

$ ./bandit20-do cat /etc/bandit_pass/bandit20
GbKksEFF4yrVs6il55v6gwY5aVje5f0j


Abbiamo la password!

user: bandit20
pass: GbKksEFF4yrVs6il55v6gwY5aVje5f0j

Livello 21
There is a setuid binary in the homedirectory that does the following: it makes a connection to localhost on the port you specify as a commandline argument. It then reads a line of text from the connection and compares it to the password in the previous level (bandit20). If the password is correct, it will transmit the password for the next level (bandit21).

NOTE: Try connecting to your own network daemon to see if it works as you think

$ ls
suconnect

$ ./suconnect
Usage: ./suconnect
This program will connect to the given port on localhost using TCP. If it receives the correct password from the other side, the next password is transmitted back.




Praticamente, mettiamo una porta in ascolto a nostra scelta, tramite Netcat,
e ci connettiamo con suconnect a questa.
Vediamo che succede.
metto in ascolto netcat sulla porta 6666
nc -l 6666

apro un altra console/shell
e digito ./suconnect 6666
inserisco la password in netcat
e dovrebbe rispondermi con la nuova password.



Infatti!

Eccola, gE269g2h3mw3pwgrj0Ha9Uoqen1c9DGr
prossimo user: bandit21

Livello 22
A program is running automatically at regular intervals from cron, the time-based job scheduler. Look in /etc/cron.d/ for the configuration and see what command is being executed.


In questo livello, l'utente precedente mi ha rovinato il quadro,
ho fatto un ps x, per vedere i processi aperti,
e l'utente precedente a me ha lasciato attivo un processo con cui ha concluso il livello;
come un pollo sono andato a vedere di cosa si trattava ed era proprio la password.
Stupida curiosità!



Però analizziamo comunque il livello e vediamo come il nostro amico haxor ci è riuscito.

il Cron è un demone che esegue lavori schedulati, più info qui
https://it.wikipedia.org/wiki/Crontab

Ci viene detti di andare a controllare in /etc/cron.d/
andiamo!

$ cd /etc/cron.d
$ ls
cronjob_bandit22 cronjob_bandit23 cronjob_bandit24 popularity-contest
$


controlliamo questi file con cat



E' bastato il primo file.

$ cat /usr/bin/cronjob_bandit22.sh
#!/bin/bash
chmod 644 /tmp/t7O6lds9S0RqQh9aMcz6ShpAoZKF7fgv
cat /etc/bandit_pass/bandit22 > /tmp/t7O6lds9S0RqQh9aMcz6ShpAoZKF7fgv
$ cat /tmp/t7O6lds9S0RqQh9aMcz6ShpAoZKF7fgv
Yk7owGAcWjwMVRwrTesJEwB7WVOiILLI


Pass Yk7owGAcWjwMVRwrTesJEwB7WVOiILLI
prossimo username: bandit22

Livello 23
A program is running automatically at regular intervals from cron, the time-based job scheduler. Look in /etc/cron.d/ for the configuration and see what command is being executed.

NOTE: Looking at shell scripts written by other people is a very useful skill. The script for this level is intentionally made easy to read. If you are having problems understanding what it does, try executing it to see the debug information it prints.

Si lavora ancora con il CronJob.
Andiamo ancora una volta in /etc/cron.d/ sappiamo già che file ci sono,
ci interesserà sicuramente il file cronjob_bandit23, visto che prima ci è servito il cronjob_bandit22;


$ cat cronjob_bandit23
x x x x x bandit23 /usr/bin/cronjob_bandit23.sh &> /dev/null
$ 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



Qui ci ho perso 15minuti buoni, come un fesso.
Quel che si capisce subito e che, lui scrive l'hash md5 in tmp.
Conviene scoprire subito quale hash generata quel comando, io credevo fosse questa la password,
per questo ho perso del tempo, ci sono arrivato dopo rileggendo bene lo script.

Sparo il comando che fà lui
sostituendo myname con l'uid da ottenere (bandit23) avevo provato anche con bandit22, se lo avete fatto,
non vergognatevi.

$ echo I am user bandit23 | md5sum | cut -d ' ' -f 1

risponde con questo hash:
8ca319486bfbbc3663ea0fbe81326349

come dicevo, ci ho messo un pò,
ma bisogna considerare l'hash come un file.

$ cat /tmp/8ca319486bfbbc3663ea0fbe81326349
jc1udXuA1tiHqjIsL8yaapX5XIAI6i0n


Supercool 8-), bastava leggere meglio.

next username: bandit23
password: jc1udXuA1tiHqjIsL8yaapX5XIAI6i0n

Livello 24
A program is running automatically at regular intervals from cron, the time-based job scheduler. Look in /etc/cron.d/ for the configuration and see what command is being executed.

NOTE: This level requires you to create your own first shell-script. This is a very big step and you should be proud of yourself when you beat this level!

NOTE 2: Keep in mind that your shell script is removed once executed, so you may want to keep a copy around…

Come sopra, più di sopra.
Sempre il Cron.
Andiamo ancora una volta in /etc/cron.d/ sappiamo già che file ci sono,
ci interesserà sicuramente il file cronjob_bandit24, visto che prima ci è servito il cronjob_bandit23 e ancor prima il 22;


$ cat cronjob_bandit24
@reboot bandit24 /usr/bin/cronjob_bandit24.sh &> /dev/null
x x x x x x bandit24 /usr/bin/cronjob_bandit24.sh &> /dev/null
$ 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


La risposta è nella cartella /var/spool/bandit24?
no!
ls: cannot open directory '/var/spool/bandit24': Permission denied

Sarebbe stato troppo facile.

Abbiamo capito che lo script esegue tutti i file nella cartella /var/spool/bandit24 e poi li cancella.
Dobbiamo ottenere un elenco dei file che si creano in quella cartella, per capire cosa c'è e cosa possiamo fare.

Il colpo di genio!

$ ls -la /var/spool/
total 20
drwxr-xr-x 5 root root 4096 Dec 28 14:34 .
drwxr-xr-x 12 root root 4096 Dec 28 14:34 ..
drwx-wx--- 23 bandit24 bandit23 4096 Mar 19 19:56 bandit24
drwxr-xr-x 5 root root 4096 Oct 31 13:20 cron
lrwxrwxrwx 1 root root 7 Oct 31 13:09 mail -> ../mail
drwx------ 2 syslog adm 4096 Apr 5 2016 rsyslog


Ma che permessi sono?
Posso scrivere in quella cartella, ma non posso leggere :-O
Vabbè, mi organizzo.
Visto che posso scrivere, creo uno script lì dentro,
tanto Cron lo esegue, mi faccio dare la risposta in /tmp dove posso leggerla.

creo un file/script con vi o con nano dentro a /var/spool/bandit24
il mio comando sarà semplice, un ls -a

quindi
creo la cartella
mkdir /tmp/alessioinfofile


creo lo script
vi /var/spool/bandit24/tibuco.sh


scrivo al suo interno

#!/bin/bash
ls -a >> /tmp/alessioinfofile/lista


CTRL + X e premo Y per salvare > nano
esc :wq! > vi


cd /tmp/alessioinfofile/

aspetto che cron esegua lo script

:-( non funziona!
dopo 10minuti, la mia zucca vuota si è ricordata di dare i permessi allo script per essere eseguito.
tanto che ero disperato ho dato i permessi anche alla cartella tmp

per cui
chmod -R 777 /tmp/alessioinfofile
chmod +x /var/spool/bandit24/tibuco.sh


ricordatevi che molto probabilmente cron ha cancellato il file /var/spool/bandit24/tibuco.sh
quindi dovete ricrearlo e dare lui subito i permessi.

Ora sì!

$ ls
lista

$ cat lista
asd
bandit23
cat
check
dddd
dpi
dyglo
GiuBugger
here
holder
LetsGo
mydir
myscript
output
p
pass
pp
pwd
shaggi
spider
tibuco.sh
tmp


Questi sono file/cartelle all'interno di /var/spool/bandit24, che ricordiamo non era leggibile.
così ad occhio, mi sono piaciuti i file pass, pp, pwd
purtroppo sono tutti script, più o meno simili al mio.
Quindi non è questo il sistema giusto.

Mi sono ricordato, dopo altri 10min buoni,
che nell'esercizio 14,
la password era contenuta in /etc/bandit_pass/bandit14
ed ho pensato:
dico a cron di fare un check per vedere se esiste il file /etc/bandit_pass/bandit24
vediamo se ha i permessi di leggere il file (sempre se esiste.)

Signori il file esiste, e la soluzione funziona.

Come sopra creiamo uno script
con dentro scritto
#!/bin/bash
cat /etc/bandit_pass/bandit24 >> /tmp/alessioinfofile/daje

stessa storia dei permessi di cui sopra.
Aspettiamo che Cron faccia il suo lavoro,
una volta generato il file: daje
al suo interno troveremo la password:

UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ
user: bandit24

8-)

Livello 25
A daemon is listening on port 30002 and will give you the password for bandit25 if given the password for bandit24 and a secret numeric 4-digit pincode. There is no way to retrieve the pincode except by going through all of the 10000 combinations, called brute-forcing.

Abbiamo un demone in ascolto sulla 30002;
non appena riceverà la password attuale + la giusta combinazione di 4 numeri restituirà la password per il livello successivo.

Oddio, fare un brute force di 10000 combinazioni non è poi così tanto come sembra.
Visto che nel passaggio precedente ci ho rimesso 25minuti, qui direi che lascio fare il brute e faccio due passi.

Ho googlato un secondo per vedere come procedere al meglio per il brute.
Deciso!
Faccio qualcosa in stile film,
sai,
quando con quei cosini superfighi si collegano al terminale del caveau della banca
ed iniziano ad uscire mille numeri fino a trovare la giusta combinazione :-O :'(
Proprio così.

requisiti:
la password precedente UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ
netcat sulla 30002 così nc localhost 30002

dubbi:
il demone avrà qualche controllo per le troppe richieste? (flood)

Vediamo,
creo la solita cartella in tmp,

mkdir /tmp/brutegogo

ci vado
cd /tmp/brutegogo


il pin è di 4 cifre, non ha senso iniziare da 0, 10, 100 o 999,
si starta da 0000. (4 appunto)

for i in $(seq -w 0000 9999); do echo "UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ $i" ; done>> test
nc localhost 30002 < test >>output


un vero HAX aprirebbe sicuramente più shell, e darebbe sicuramente dei comandi così

console1
for i in $(seq -w 0000 2999); do echo "UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ $i" ; done>> test
nc localhost 30002 < test >>output

console2
for i in $(seq -w 3000 4999); do echo "UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ $i" ; done>> test
nc localhost 30002 < test >>output

console3
for i in $(seq -w 5000 6999); do echo "UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ $i" ; done>> test
nc localhost 30002 < test >>output

console4
for i in $(seq -w 7000 9999); do echo "UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ $i" ; done>> test
nc localhost 30002 < test >>output


così da dimezzare nettamente il tempo di crack.

Dopo una serie di WRONG, WRONG, WRONG, ecco trovato il pin, ed il demone ci risponde con la nuova password.



$ cat output

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


user bandit25
pass uNG9O58gUE7snukf3bvZ0rxhtnjzSGzG

Livello 26
Logging in to bandit26 from bandit25 should be fairly easy… The shell for user bandit26 is not /bin/bash, but something else. Find out what it is, how it works and how to break out of it.

Ok, vediamo che shell stiamo usando, su etc passwd
$ cat /etc/passwd | grep bandit26
bandit26:x:11026:11026:bandit level 26:/home/bandit26:/usr/bin/showtext
bandit25@bandit:~$ cat /etc/passwd | grep bandit25
bandit25:x:11025:11025:bandit level 25:/home/bandit25:/bin/bash


showtext.

$ cat /usr/bin/showtext
#!/bin/sh

export TERM=linux

more ~/text.txt
exit 0


La password è dentro al text.txt, in teoria.

$ cat /home/bandit26/text.txt
cat: /home/bandit26/text.txt: Permission denied

Ma non ci posso accedere :'(

Nella home, ho una key
$ ls
bandit26.sshkey


$ ssh -i bandit26.sshkey bandit26@localhost -p22


Funziona, però chiude la connessione in faccia.

Enjoy your stay!

_ _ _ _ ___ __
| | | (_) | |__ \ / /
| |__ __ __ __| |_| |_ ) / /_
| '_ \ / _` | '_ \ / _` | | __| / / '_ \
| |_) | (_| | | | | (_| | | |_ / /| (_) |
|_.__/ __,_|_| |_|__,_|_|__|_______/
Connection to localhost closed.


Mi sono bloccato.
Ci riprovo domani mattina.

Buongiorno! Dopo mille prove sono riuscito.
Ovviamente qui si tratta di una bastardata bella e buona.
Praticamente dopo aver provato di tutto con "more"
ho capito perchè della loro scelta.

Se io ridimensiono il terminale, more si ferma non essendo visualizzato bene,
quindi non chiude la sessione.

Guardate:


..... No comment.
Premo il tasto v così parte l'editor, posso ingrandire la console,
adesso senza uscire dall'editor, chiamo alla modifica il file dove credo sia la password:
scrivendo
:r /etc/bandit_pass/bandit26



quindi eccola :-D


5czgV9L3Xx8JPOyRbXh6lQbmIOWvPT6Z

Loro dicono che il Livello 27
At this moment, level 27 does not exist yet.
Credo sia un inganno, esiste, però dopo il lvl 26 non ho altro tempo da perdere, per cui mi fido
Grazie mille
è stato divertente ma anche no.