SlideShare ist ein Scribd-Unternehmen logo
1 von 38
Penetration Testing con Python
Scrivere i propri strumenti
Networking - Sniffer
Simone Onofri
@simoneonofri
mailto:simone@onofri.org
CC BY-ND-NC
Agenda
• Introduzione e FAQ
• Perché scrivere i propri
strumenti
• Questioni religiose
• Brevissima introduzione a
Python
• Lo Sniffer TCP/HTTP «a proprie
spese» e «la via breve»
• Prossimi passi
• Conclusioni
Introduzione
http://onofri.org/u/ld16
«Ricordatevi, la differenza tra uno
script kiddie e un professionista è la
differenza tra chi meramente utilizza
gli strumenti di altri e chi scrive i
propri»
-- Charlie Miller (Prefazione a Black Hat Python)
Penetration Testing e strumenti
L’OSSTMM indica che l’analista deve conoscere i propri strumenti, da
dove vengono, come funzionano e li deve aver provati prima in un
ambiente controllato.
Sono molte le implicazioni di questo concetto. Focalizziamoci su due
casi specifici. Gli hanno fatti altri, sappiamo come funzionano e se
funzionano? Possono fare danni? Contenere back door o codice
malevolo? Se li abbiamo fatti noi, conosciamo bene l’attacco che
stiamo facendo? I protocolli? I sistemi o la rete bersaglio?
«se ascolto dimentico, se vedo
ricordo, se faccio capisco»
-- Antico proverbio cinese || Confucio
Perché Python e non <inserire-altro-linguaggio>? E perché Python 2.7 e non Python
3?
https://wiki.python.org/moin/Python2orPython3
Perché Python
«Python è un linguaggio a ridotta
complessità, ha molte librerie di
terze parti* e un basso costo
d’ingresso. Su OSX e Linux è già
installato. Molti altri strumenti
sono già fatti in Python.»
-- TJ O'Connor (Violent Python)
https://github.com/dloss/python-pentest-tools
Hello World
• E’ un linguaggio interpretato
• Abbiamo tre modi principali per
farlo girare:
• Codice nella riga di comando
$ python -c "print 'Hello
World'"
• Codice in un file
$ python helloworld.py
• Codice interattivo
$ python
>>> print 'Hello World'
Python da Zero in tre passi
• Anzitutto va installato python (se non lo è già) e.g. su debian
$ sudo apt-get install python
• Si installa PIP (il gestore di pacchetti di python)
$ sudo apt-get install python-pip
• Si installa virtualenv – che serve per creare ambienti virtuali (rende
tutto può portabile e si evita di appesantire il sistema dove
lavoriamo)
$ sudo pip install virtualenv
http://docs.python-guide.org/en/latest/starting/installation/
https://packaging.python.org/installing/
http://docs.python-guide.org/en/latest/dev/virtualenvs/
Iniziamo a «codare»
• Quando si parte, a livello di prototipazione e testare quello che
facciamo, conviene utilizzare l’interprete in maniera interattiva e
vedere quello che succede, eventuali errori ecc….
• Lo scopo di questa introduzione è guidarci verso lo sviluppo di
strumenti di rete, alcune cose saranno intro, man mano che vediamo
il codice, l’importante è capire l’approccio!
• Quando ci sono delle cose nuovo le introduciamo, per alcuni alcune
cose saranno scontate, per altre nuove. Intanto si possono prendere
«così come sono» e poi fare con calma debug.
Use case: Sniffer HTTP con i RAW Socket
• Una delle attività tipiche che si fa sulla rete è quello di sniffare il
traffico, magari siamo già in una posizione di rete privilegiata (oppure
su un hub) e quindi non abbiamo bisogno di utilizzare tecniche
particolari per farci arrivare il traffico (quelle le vediamo dopo).
• A livello teorico dobbiamo conoscere quindi come funziona la suite di
protocolli TCP/IP e, considerando che il nostro scopo è quello di
leggere il traffico HTTP, dobbiamo partire dai protocolli che sono più
in basso.
La suite di protocolli TCP/IP
• Application: Servizi applicativi
per l’utente (nel nostro caso
HTTP).
• Transport: Organizza I dati per il
trasporto e la loro trasmissioni
(nel nostro caso TCP).
• Internet/Gateway: Gestisce
l’indirizzamento logico tra due
sistemi, anche quelli che ono
sono connessi direttamente,
come anche il percordo per
arrivare a questi sistemi (nel
nostro caso IPv4).
• Network : Converte le
informazioni logiche sui
dispositivi fisici (nel nostro caso
Ethernet).
+------+ +-----+ +-----+ +-----+
|Telnet| | FTP | |Voice| ... | | Application Level
+------+ +-----+ +-----+ +-----+
| | | |
+-----+ +-----+ +-----+
| TCP | | RTP | ... | | Host Level
+-----+ +-----+ +-----+
| | |
+-------------------------------+
| Internet Protocol & ICMP | Gateway Level
+-------------------------------+
|
+---------------------------+
| Local Network Protocol | Network Level
+---------------------------+
Protocol Relationships
https://tools.ietf.org/html/rfc793
Incapsulamento
Frame
Header
IP
Header
TCP/UDP
Header
Applicat
ion Data
Frame
Trailer
Ethernet Frame
IP
Header
TCP/UDP
Header
Applicat
ion Data
IP Datagram
TCP/UDP
Header
Applicat
ion Data
TCP Segment
Applicat
ion Data
HTTP Data
Quando catturiamo il traffico
sulla rete (nel pratico un
flusso di bit) troviamo una
serie di informazioni
incapsulate che vanno
recuperate, strutturate e
interpretate. Questa
operazione viene anche
chiamata dissezione.
Vediamo i pacchetti con un RAW socket
1. $ sudo python # serve sudo per l’accesso ai RAW socket
2. >>> import socket # importo il modulo per i raw socket BSD
3. >>> s = socket.socket(socket.SOCK_RAW, socket.AF_INET, socket.IPPROTO_TCP) #
creo il socket per avere i pacchetti RAW, con IP v4 e TCP
>>> packets = [] # creo una lista per contenere i miei pacchetti (poi vediamo
come ci si accede)
4. >>> for i in range(5): # prendi 5 pacchetti
5. ... packet = s.recvfrom(65565) # da notare che siamo indentati (4 spazi),
ricevi i pacchetti con un buffer passato dall’utente
6. ... packets.append(packet) # mette i pacchetti catturati nella lista
7. ...
>>> len(packets) # controllo quanti pacchetti ho effettivamente catturato
8. 5 # bene, abbiamo i nostri pacchetti, 5
9. >>> packets # vediamo il contenuto, il fatidico flusso di bit
10.[('Ex00x00LB=@x00x80x06xdex9bxc0xa8,x01xc0xa8,x81x9cx8ex00x165
xc8x856x19xfdF
Px18x00xffxcbx00x00xadx85xfd6yx06>xabxffxfa>:xe4xaex06xaex05
Zxcexf2xae7xc1xfbx9fmXxd3x84x0f:x83xb8ux11xef', ('192.168.44.1',
0)),
11.…
La nostra prima parte dello sniffer
1. #!/usr/bin/env python
2. import socket
3. import struct
4. s = socket.socket(socket.SOCK_RAW,
socket.AF_INET,socket.IPPROTO_TCP)
5. while 1: # qui modifico in un while
6. print s.recvfrom(65565) # stampo
direttamente
7. '''
8. Come possiamo vedere per controllare il
flusso abbiamo usato un while, in python non
abbiamo le parentesi come in C – per esempio
– ma l’indentazione, di norma deve essere
fatta con quattro spazi. Le varie regole su
come scrivere codice con stile in Pyhon sono
contenuti nella PEP-008
9. ''' https://www.python.org/dev/peps/pep-0008/
Andiamo in profondità
Quando abbiamo creato il socket, abbiamo visto alcune impostazioni
inserite, se le voglio sapere tutte, in modalità interattiva dopo aver
importato il modulo possiamo usare ‘dir()’ per avere la lista di elementi
che possiamo avere (e.g. le costanti) e help() per avere l’aiuto.
>>> dir(socket)
>>> help(socket)
Inoltre, dato che stiamo usando i socket BSD, quando andiamo a
cercare variabili e informazioni, possiamo fare riferimento alla
documentazione relativa e ai file sul nostro sistema.
Attenzione a cercare le informazioni su Google / Stack Overflow
Dissezionare i protocolli
• Con i RAW socket abbiamo sicuramente i
pacchetti ma le informazioni sono in
formato binario, per renderle leggibili
dobbiamo scrivere dei dissector per
poterle leggerle in formato «umano».
• Utilizzeremo quindi il modulo struct che
serve ad interpretare i dati binari e poterli
leggere.
• In caso di emergenza fare riferimento a:
• RFC (attenzione agli aggiornamenti)
• file di inclusione che troviamo nel nostro
sistema (l’open source sia lodato)
• man.
Dissezionare IP – RFC 791
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|Version| IHL |Type of Service| Total Length |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Identification |Flags| Fragment Offset |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Time to Live | Protocol | Header Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Source Address |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Destination Address |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Options | Padding |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
https://tools.ietf.org/rfc/rfc791.txt
• Version: 4 bits
• IHL (Internet Header Lenght): 4 bits
• ToS: 8 bits
• Total Lenght: 16 bits
• Identification 16 bits
• Flags: 3 bits
• Fragment Offset: 13 bits
• TTL: 8 bits
• Protocol: 8 bits
• Header Checksum: 16 bits
• Source Address: 32 bits
• Destination Address: 32 bits
• Options: variable
• Padding: variable
Il formato di struct
Format C Type Python type Standard size Notes
x pad byte no value
c char string of length 1 1
b signed char integer 1 (3)
B unsigned char integer 1 (3)
? _Bool bool 1 (1)
h short integer 2 (3)
H unsigned short integer 2 (3)
i int integer 4 (3)
I unsigned int integer 4 (3)
l long integer 4 (3)
L unsigned long integer 4 (3)
q long long integer 8 (2), (3)
Q unsigned long long integer 8 (2), (3)
f float float 4 (4)
d double float 8 (4)
s char[] string
p char[] string
P void * integer (5), (3)
https://docs.python.org/2/library/struct.html#format-characters
Dissezionare IP - /usr/include/linux/ip.h
1.struct iphdr {
2.#if defined(__LITTLE_ENDIAN_BITFIELD)
3.#elif defined (__BIG_ENDIAN_BITFIELD)
4. __u8 version:4,
ihl:4;
5.#else
#error "Please fix <asm/byteorder.h>«
#endif
__u8 tos;
__be16 tot_len;
__be16 id;
__be16 frag_off;
__u8 ttl;
__u8 protocol;
__sum16 check;
__be32 saddr;
__be32 daddr;
/*The options start here. */
6.};
Big Endian (Network) !
[0] __u8 > unsigned char > B # version ihl
[1] __u8 > unsigned char > B # tos
[2] __be16 > unsigned short > H # tot_len
[3] __be16 > unsigned short > H # id
[4] __be16 > unsigned short > H #frag_off;
[5] __u8 > unsigned char > B #ttl;
[6]__u8 > unsigned char > B # protocol;
[7]__sum16 > unsigned short > H # check;
[8]__be32 > unsigned int > I # source address
[9]__be32 > unsigned int > I # destination address
Il nostro formato corretto è !BBHHHBBHII ma possiamo anche usare !BBHHHBBH4s4s
- sostituendo i due unsigned int (32 bit) con quattro byte - per praticità di conversione
Dissezionare IP - Logica
1. ip_size = 20 # prendo la prima parte dell’hueader IP
2. ip_start = 0 # partiamo da 0 (secondo il tipo di RAW socket che usiamo)
3. ip_finish = ip_start + ip_size # calcolo la fine
4. ip_header_slice = packet[0][ip_start:ip_finish] # prendo il pezzo – slice – che
miinteressa, il primo campo del pacchetto e lo ‘taglio’ come mi interessa
5. ip_header_unpack = unpack('!BBHHHBBH4s4s' , ip_header_slice) # uso il formato che abbiamo
ottenuto
6. ip_version_ihl = ip_header_unpack[0] # prendo la prima parte che mi interessa
7. ip_version = ip_version_ihl >> 4 # recupero i primi bit della versione
8. ip_ihl = ip_version_ihl & 0xF # recupero la lunghezza
9. ip_header_length = ip_ihl * 4 # converto per avere la lunghezza
10.ip_tos = ip_header_unpack[1] # prendo il TOS
11.ip_lenght = ip_header_unpack[2] # prendo la lunghezza
12.ip_id = ip_header_unpack[3] # prendo l’IPID*
13.ip_fragmentation = ip_header_unpack[4] # prendo la frammentazione
14.ip_ttl = ip_header_unpack[5] # prendo il TTL
15.ip_protocol = ip_header_unpack[6] # prendo il protocollo
16.ip_checksum = ip_header_unpack[7] # prendo il checksum
17.ip_source_address = socket.inet_ntoa(ip_header_unpack[8]) # prendo l’IP sorgente e lo
converto tramite una funziona che converte il binario il notazione dotted (questo il
motivo per cui abbiamo preso dei byte e non degli unsigned int, per praticità)
18.ip_destination_address = socket.inet_ntoa(ip_header_unpack[9]) # prendo l’IP destinazione
Dissezionare IP – Stampa
1. print "= IP ========="
2. print "tIP Version: " +
str(ip_version)
3. print "tIP Header Length: " +
str(ip_header_length)
4. print "tIP TOS: " + str(ip_tos)
5. print "tIP length: " + str(ip_lenght)
6. print "tIPID: " + str(ip_id)
7. print "tIP Fragmentation: " +
str(ip_fragmentation)
8. print "tIP TTL: " + str(ip_ttl)
9. print "tIP Protocol: " +
str(ip_protocol)
10.print "tIP Source: " +
ip_source_address
11.print "tIP Destination: " +
ip_destination_address
= IP =========
IP Version: 4
IP Header Length: 20
IP TOS: 0
IP length: 5
IPID: 1640
IP Fragmentation: 0
IP TTL: 128
IP Protocol: 6
IP Source: 104.28.13.52
IP Destination: 192.168.44.129
Dissezionare TCP
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Source Port | Destination Port |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Sequence Number |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Acknowledgment Number |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Data | |U|A|P|R|S|F| |
| Offset| Reserved |R|C|S|S|Y|I| Window |
| | |G|K|H|T|N|N| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Checksum | Urgent Pointer |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Options | Padding |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| data |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
https://www.ietf.org/rfc/rfc793.txt
• Sport: 16 bits
• Dport: 16 bits
• Sequence Number: 32 bits
• Acknoledgment Number: 32
bits
• Data offset: 4 bits
• Reserved: 6 bits
• Control Bits: 6 bits (left-right)
• Window: 16 bits
• Checksum: 16 bits
• Urgent Pointer: 16 bits
• Options: variable
• Padding: variable
Dissezionare TCP - /usr/include/linux/tcp.h
Big Endian (Network) !
[0] 16bit >>> sport H
[1] 16bit >>> dport H
[2] 32bit >>> sequence L
[3] 32bit >>> ack-number L
[4] 4bit >>> offset H
4bit >>> reserved
6bit >>> flags
1bit >>> CWR
1bit >>> ECE
1bit >>> URG
1bit >>> ACK
1bit >>> PSH
1bit >>> RST
1bit >>> SYN
1bit >>> FIN
[5] 16bit >>> window H
[6] 16bit >>> check H
[7] 16bit >>> urg_ptr H
1. struct tcphdr {
2. __be16 source;
3. __be16 dest;
4. __be32 seq;
5. __be32 ack_seq;
6. #if defined(__LITTLE_ENDIAN_BITFIELD)
7. #elif defined(__BIG_ENDIAN_BITFIELD)
8. __u16 doff:4,
9. res1:4,
10. cwr:1,
11. ece:1,
12. urg:1,
13. ack:1,
14. psh:1,
15. rst:1,
16. syn:1,
17. fin:1;
18.#else
19.#error "Adjust your <asm/byteorder.h> defines"
20.#endif
21. __be16 window;
22. __sum16 check;
23. __be16 urg_ptr;
24.};
Il nostro formato corretto è !HHLLHHHH
Dissezionare TCP – RFC 3168
https://tools.ietf.org/html/rfc3168
The Transmission Control Protocol (TCP) included a 6-bit Reserved
field defined in RFC 793, reserved for future use, in bytes 13 and 14
of the TCP header, as illustrated below. The other six Control bits
are defined separately by RFC 793.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| | | U | A | P | R | S | F |
| Header Length | Reserved | R | C | S | S | Y | I |
| | | G | K | H | T | N | N |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
RFC 3168 defines two of the six bits from the Reserved field to be
used for ECN, as follows:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| | | C | E | U | A | P | R | S | F |
| Header Length | Reserved | W | C | R | C | S | S | Y | I |
| | | R | E | G | K | H | T | N | N |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
Dissezionare TCP - Codice
1. tcp_size = 20 # dimensione di un header TCP minimz
2. tcp_start = ip_header_length # inizio da dove finisce IP
3. tcp_finish = tcp_start + tcp_size # fine
4. tcp_header_slice = packet[0][tcp_start:tcp_finish] # prendo la parte che mi interessa
5. tcp_header_unpack = unpack('!HHLLHHHH' , tcp_header_slice) # spacchetto con il formato
6. tcp_source_port = tcp_header_unpack[0] # prendo la porta sorgente
7. tcp_dest_port = tcp_header_unpack[1] # prendo la porta destinazione
8. tcp_sequence = tcp_header_unpack[2] # prendo il sequence number
9. tcp_acknowledgement = tcp_header_unpack[3] # prendo l’acknowledge number
10.tcp_osf = bin(tcp_header_unpack[4])[2:].zfill(16) # prendo la porzione dei bit di controllo
11.tcp_offset = tcp_osf[0:4] # prendo l’offset
12.tcp_reserved = tcp_osf[4:8] # prendo la parte riservata
13.tcp_cwr = tcp_osf[8:9] # prendo il flag specifico CWR **
14.tcp_ece = tcp_osf[9:10] # prendo il flag specifico ECE **
15.tcp_urg = tcp_osf[10:11] # prendo il flag specifico URG **
16.tcp_ack = tcp_osf[11:12] # prendo il flag specifico ACK **
17.tcp_psh = tcp_osf[12:13] # prendo il flag specifico PSH **
18.tcp_rst = tcp_osf[13:14] # prendo il flag specifico RST **
19.tcp_syn = tcp_osf[14:15] # prendo il flag specifico SYN **
20.tcp_fin = tcp_osf[15:16] # prendo il flag specifico FIN **
21.tcp_window = tcp_header_unpack[5] # prendo la window
22.tcp_checksum = tcp_header_unpack[6] # prendo il checksum
23.tcp_urg_ptr = tcp_header_unpack[7] # prendo l’urgent pointer
24.tcp_header_length = int(tcp_offset,2) * 4 # mi serve la lunghezza per tagliare correttamente il
layer 7
Dissezionare TCP – Stampa e Output
1. print "= TCP ========«
2. print "tTCP Source Port: " +
str(tcp_source_port)
3. print "tTCP Destination Port: " +
str(tcp_dest_port)
4. print "tTCP Sequence Number: " +
str(tcp_sequence)
5. print "tTCP Acknowledge Number: " +
str(tcp_acknowledgement)
6. print "tTCP Offset: " + tcp_offset
7. print "tTCP Reserved: " + tcp_reserved
8. print "tTCP Flags: " + tcp_osf
9. print "ttFIN: " + str(tcp_fin)
10.print "ttSYN: " + str(tcp_syn)
11.print "ttRST: " + str(tcp_syn)
12.print "ttPSH: " + str(tcp_psh)
13.print "ttACK: " + str(tcp_ack)
14.print "ttURG: " + str(tcp_urg)
15.print "ttECE: " + str(tcp_ece)
16.print "ttCWR: " + str(tcp_cwr)
17.print "tTCP Window: " +
str(socket.ntohs(tcp_window)) # inverse is
socket.htons
18.print "tTCP Checksum: " + str(tcp_checksum)
19.print "tTCP Urgent: " + str(tcp_urg_ptr)
= TCP ========
TCP Source Port: 80
TCP Destination Port: 51666
TCP Sequence Number: 405830337
TCP Acknowledge Number: 3434543485
TCP Offset: 0101
TCP Reserved: 0000
TCP Flags: 0101000000011000
FIN: 0
SYN: 0
RST: 0
PSH: 1
ACK: 1
URG: 0
ECE: 0
CWR: 0
TCP Window: 61690
TCP Checksum: 5442
TCP Urgent: 0
Sopra il TCP… HTTP
Sappiamo che HTTP è un protocollo non
binario. Quindi per ora limitiamo vedere le
stringhe
header_size = ip_start + ip_header_length +
tcp_header_length # ecco a cosa mi serviva la
dimnesione
data = packet[0][header_size:] # recupero il payload
print "= Data ========"
print "tData: " + data # converto la stringa e
stampo (per HTML funziona abbastanza bene*)
print "nnn"
Il nostro HTTP*
1. = Data ======== Data: HTTP/1.1 302 Found
2. Date: Sat, 22 Oct 2016 00:14:13 GMT
3. Content-Type: text/plain; charset=utf-8
4. Content-Length: 46
5. Connection: keep-alive
6. Set-Cookie: __cfduid=de732197c8620f117376fe065378573e81477095253;
expires=Sun, 22-Oct-17 00:14:13 GMT; path=/; domain=.lugroma3.org;
HttpOnly
7. X-Powered-By: Express
8. Location: http://ld16.lugroma3.org
9. Vary: Accept
10. set-cookie:
connect.sid=s%3A9xJsdl9k5L8gS9czLmdxSxMKZ6ZiKUls.Iscr5N2kRxapQg0jCSlwvS
d9J6qrYjE%2BU6zao0Fgd3U; Path=/; HttpOnly
11. CF-Cache-Status: MISS
12. Expires: Sat, 22 Oct 2016 04:14:13 GMT
13. Cache-Control: public, max-age=14400
14. Server: cloudflare-nginx
15. CF-RAY: 2f58bf74b6e142fe-MXP
16. Found. Redirecting to http://ld16.lugroma3.org
Introduzione a Scapy
• Ora che abbiamo imparato a dissezionare tramite «la via
difficile», vediamo come si può fare in maniera più facile.
• Python ha un’ottima libreria – chiamata Scapy – che è
on-top ai raw socket e che ha una grande quantità di
dissector.
• E’ quindi veloce, facile da usare ed estendibile.
• Ci sono però dei contro:
• A livello «didattico» molte cose sono già pronte quindi se ci può
essere utile per fare degli script in velocità va bene, ma può non
essere il massimo per approfondire totalmente la materia.
• Inoltre se dobbiamo fare il deploy di alcuni script, dobbiamo
necessariamente portarci dietro la libreria.
• Fare il debug potrebbe essere più complesso, al netto di
studiarsi a fondo la libreria.
• Si installa e.g. su debian con $ sudo apt-get
install scapy
http://www.secdev.org/project
s/scapy/doc/
Il nostro «sudato» HTTP sniffer con scapy
1. #!/usr/bin/env python
2. from scapy.all import *
3. sniff(filter="port 80", prn=lambda
x:x.sprintf("{IP:%IP.src%:%TCP.sport% >
%IP.dst%:%TCP.dport%n}{Raw:%Raw.load%n}"))
# abilito lo sniffing filtrano per la porta 80 –
default di HTTP – e uso una funzione lambda
(funzione in una riga, derivata dal LISP).
Running Sniffer - Summary
>>> sniff(filter="port 80", prn=lambda x:x.summary())
Ether / IP / TCP 192.168.44.129:33842 > 104.28.12.52:http S
Ether / IP / TCP 104.28.12.52:http > 192.168.44.129:33842 SA / Padding
Ether / IP / TCP 192.168.44.129:33842 > 104.28.12.52:http A
Ether / IP / TCP 192.168.44.129:33842 > 104.28.12.52:http PA / Raw
Ether / IP / TCP 104.28.12.52:http > 192.168.44.129:33842 A / Padding
Ether / IP / TCP 104.28.12.52:http > 192.168.44.129:33842 PA / Raw
Ether / IP / TCP 192.168.44.129:33842 > 104.28.12.52:http A
Ether / IP / TCP 104.28.12.52:http > 192.168.44.129:33842 PA / Raw
Ether / IP / TCP 192.168.44.129:33842 > 104.28.12.52:http A
Running Sniffer - show
>>> sniff(filter="port 80", prn=lambda x:x.show())
###[ Raw ]###
load = 'GET / HTTP/1.1rnUser-
Agent: Wget/1.17.1 (linux-gnu)rnAccept:
*/*rnAccept-Encoding: identityrnHost:
ld16.lugroma3.orgrnConnection: Keep-
Alivernrn'
###[ Ethernet ]###
dst = 00:50:56:f2:8f:ed
src = 00:0c:29:15:7d:b4
type = 0x800
###[ IP ]###
version = 4L
ihl = 5L
tos = 0x0
len = 40
id = 20386
flags = DF
frag = 0L
ttl = 64
proto = tcp
chksum = 0x89b4
src = 192.168.44.129
dst = 104.28.12.52
options 
###[ TCP ]###
sport = 33854
dport = http
seq = 4174054303
ack = 1672679894
dataofs = 5L
reserved = 0L
flags = A
window = 29200
chksum = 0x6194
urgptr = 0
options = {}
Running Sniffer – Stampa campi
>>> sniff(filter="port 80", prn=lambda x:x.sprintf("{IP:%IP.src%:%TCP.sport% >
%IP.dst%:%TCP.dport%n}{Raw:%Raw.load%n}"))
192.168.44.129:51510 > 104.28.13.52:http
'GET /images/ld16/logo.png HTTP/1.1rnReferer: http://ld16.lugroma3.org/stylesheets/style-ld16.cssrnIf-
Modified-Since: Fri, 21 Oct 2016 17:32:00 GMTrnUser-Agent: Wget/1.17.1 (linux-gnu)rnAccept:
*/*rnAccept-Encoding: identityrnHost: ld16.lugroma3.orgrnConnection: Keep-AlivernCookie:
connect.sid=s%3A1YiIo3FZNlLwGFEG-WJ89jlG77BTYl7j.MbRExRQTaEBk%2FCMwip75wkaAP38LSWgWBsEKw0WjJQM;
__cfduid=d9e77fbf2df651e3b203dfc5bd65fd8401477084930rnrn'
104.28.13.52:http > 192.168.44.129:51510
104.28.13.52:http > 192.168.44.129:51510
'HTTP/1.1 200 OKrnDate: Fri, 21 Oct 2016 21:22:11 GMTrnContent-Type: image/pngrnContent-Length:
27300rnConnection: keep-alivernX-Powered-By: ExpressrnAccept-Ranges: bytesrnCache-Control: public,
max-age=14400rnLast-Modified: Fri, 21 Oct 2016 17:32:00 GMTrnETag: W/"6aa4-157e84ca79a"rnCF-Cache-
Status: MISSrnVary: Accept-EncodingrnExpires: Sat, 22 Oct 2016 01:22:11 GMTrnServer: cloudflare-
nginxrnCF-RAY: 2f57c378b7b34340-
MXPrnrnx89PNGrnx1anx00x00x00rIHDRx00x00x01xc1x00x00x00rx08x06x00x00x00+x92jx87x0
0x00x00x19tEXtSoftwarex00Adobe
ImageReadyqxc9e<x00x00x03qiTXtXML:com.adobe.xmpx00x00x00x00x00<?xpacket begin="xefxbbxbf"
id="W5M0MpCehiHzreSzNTczkc9d"?> <x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.5-c021
79.154911, 2013/10/29-11:47:16 "> <rdf:RDF
Prossimi passi
• Fare quando scritto nelle diapositive nel
pratico
• Segnalare eventuali problemi
• Cambiare tipologia di socket per leggere
anche i pacchetti inviati e fare il dissector
per ARP
• Fare dei test con Scapy
Grazie
simone@onofri.org
@simoneonofri
https://onofri.org/
https://linkedin.com/in/simoneonofri
http://onofri.org/u/ld16
Riferimenti
• TJ O'Connor – Violent Python (2012)
• Justin Seitz – Black Hat Python (2014)
• Pete Herzog et al. – OSSTMM v3 (2010)
https://tools.ietf.org/html/rfc3168
https://tools.ietf.org/rfc/rfc791.txt
https://www.python.org/dev/peps/pep-0008/
https://tools.ietf.org/html/rfc793
http://docs.python-guide.org/en/latest/starting/installation/
https://packaging.python.org/installing/
http://docs.python-guide.org/en/latest/dev/virtualenvs/
https://github.com/dloss/python-pentest-tools
https://wiki.python.org/moin/Python2orPython3

Weitere ähnliche Inhalte

Was ist angesagt?

The Hunter Games: How to Find the Adversary with Event Query Language
The Hunter Games: How to Find the Adversary with Event Query LanguageThe Hunter Games: How to Find the Adversary with Event Query Language
The Hunter Games: How to Find the Adversary with Event Query LanguageRoss Wolf
 
モバイルアプリケーション管理(MAM) 自社アプリ開発手法
モバイルアプリケーション管理(MAM)自社アプリ開発手法モバイルアプリケーション管理(MAM)自社アプリ開発手法
モバイルアプリケーション管理(MAM) 自社アプリ開発手法Dai Matsui
 
コンピュータフォレンジックにちょっとだけ触れてみる
コンピュータフォレンジックにちょっとだけ触れてみるコンピュータフォレンジックにちょっとだけ触れてみる
コンピュータフォレンジックにちょっとだけ触れてみるinfinite_loop
 
MongoDBとAjaxで作る解析フロントエンド&GraphDBを用いたソーシャルデータ解析
MongoDBとAjaxで作る解析フロントエンド&GraphDBを用いたソーシャルデータ解析MongoDBとAjaxで作る解析フロントエンド&GraphDBを用いたソーシャルデータ解析
MongoDBとAjaxで作る解析フロントエンド&GraphDBを用いたソーシャルデータ解析Takahiro Inoue
 
Mastdonインスタンス立ててみた in Azure #ssmjp
Mastdonインスタンス立ててみた in Azure #ssmjpMastdonインスタンス立ててみた in Azure #ssmjp
Mastdonインスタンス立ててみた in Azure #ssmjpMasahiro NAKAYAMA
 
The DevOps Journey
The DevOps JourneyThe DevOps Journey
The DevOps JourneyMicro Focus
 
WkWebViewのキャッシュについて調べた
WkWebViewのキャッシュについて調べたWkWebViewのキャッシュについて調べた
WkWebViewのキャッシュについて調べたfirewood
 
Alphorm.com Formation CEHV9 I
Alphorm.com Formation CEHV9 IAlphorm.com Formation CEHV9 I
Alphorm.com Formation CEHV9 IAlphorm
 
JJUG CCC 2013 Fall「JVMコードリーディング入門-JVMのOS抽象化レイヤーについて-」
JJUG CCC 2013 Fall「JVMコードリーディング入門-JVMのOS抽象化レイヤーについて-」JJUG CCC 2013 Fall「JVMコードリーディング入門-JVMのOS抽象化レイヤーについて-」
JJUG CCC 2013 Fall「JVMコードリーディング入門-JVMのOS抽象化レイヤーについて-」y torazuka
 
インフラエンジニアに送るVSCode 入門
インフラエンジニアに送るVSCode 入門インフラエンジニアに送るVSCode 入門
インフラエンジニアに送るVSCode 入門Shinsuke Saito
 
OWASP Dependency-Track Introduction
OWASP Dependency-Track IntroductionOWASP Dependency-Track Introduction
OWASP Dependency-Track IntroductionSergey Sotnikov
 
130821 owasp zed attack proxyをぶん回せ
130821 owasp zed attack  proxyをぶん回せ 130821 owasp zed attack  proxyをぶん回せ
130821 owasp zed attack proxyをぶん回せ Minoru Sakai
 
イベント駆動プログラミングとI/O多重化
イベント駆動プログラミングとI/O多重化イベント駆動プログラミングとI/O多重化
イベント駆動プログラミングとI/O多重化Gosuke Miyashita
 
악성코드 개념 및 대응 기술 (사이버 게놈 기술)
악성코드 개념 및 대응 기술 (사이버 게놈 기술)악성코드 개념 및 대응 기술 (사이버 게놈 기술)
악성코드 개념 및 대응 기술 (사이버 게놈 기술)seungdols
 
Software design as a cooperative game with EventStorming
Software design as a cooperative game with EventStormingSoftware design as a cooperative game with EventStorming
Software design as a cooperative game with EventStormingAlberto Brandolini
 
RESTful API (JAX-RS) 書くだけで仕様書も 自動で作られていく話 with MicroProfile Open API
RESTful API (JAX-RS) 書くだけで仕様書も自動で作られていく話 with MicroProfile Open APIRESTful API (JAX-RS) 書くだけで仕様書も自動で作られていく話 with MicroProfile Open API
RESTful API (JAX-RS) 書くだけで仕様書も 自動で作られていく話 with MicroProfile Open APIKohei Saito
 
社内の遊休PCをAzurePipelinesでCICDに活用しよう
社内の遊休PCをAzurePipelinesでCICDに活用しよう社内の遊休PCをAzurePipelinesでCICDに活用しよう
社内の遊休PCをAzurePipelinesでCICDに活用しようShinya Nakajima
 

Was ist angesagt? (20)

The Hunter Games: How to Find the Adversary with Event Query Language
The Hunter Games: How to Find the Adversary with Event Query LanguageThe Hunter Games: How to Find the Adversary with Event Query Language
The Hunter Games: How to Find the Adversary with Event Query Language
 
モバイルアプリケーション管理(MAM) 自社アプリ開発手法
モバイルアプリケーション管理(MAM)自社アプリ開発手法モバイルアプリケーション管理(MAM)自社アプリ開発手法
モバイルアプリケーション管理(MAM) 自社アプリ開発手法
 
HCL AppScan 10 のご紹介
HCL AppScan 10 のご紹介HCL AppScan 10 のご紹介
HCL AppScan 10 のご紹介
 
コンピュータフォレンジックにちょっとだけ触れてみる
コンピュータフォレンジックにちょっとだけ触れてみるコンピュータフォレンジックにちょっとだけ触れてみる
コンピュータフォレンジックにちょっとだけ触れてみる
 
MongoDBとAjaxで作る解析フロントエンド&GraphDBを用いたソーシャルデータ解析
MongoDBとAjaxで作る解析フロントエンド&GraphDBを用いたソーシャルデータ解析MongoDBとAjaxで作る解析フロントエンド&GraphDBを用いたソーシャルデータ解析
MongoDBとAjaxで作る解析フロントエンド&GraphDBを用いたソーシャルデータ解析
 
Mastdonインスタンス立ててみた in Azure #ssmjp
Mastdonインスタンス立ててみた in Azure #ssmjpMastdonインスタンス立ててみた in Azure #ssmjp
Mastdonインスタンス立ててみた in Azure #ssmjp
 
The DevOps Journey
The DevOps JourneyThe DevOps Journey
The DevOps Journey
 
WkWebViewのキャッシュについて調べた
WkWebViewのキャッシュについて調べたWkWebViewのキャッシュについて調べた
WkWebViewのキャッシュについて調べた
 
Alphorm.com Formation CEHV9 I
Alphorm.com Formation CEHV9 IAlphorm.com Formation CEHV9 I
Alphorm.com Formation CEHV9 I
 
JJUG CCC 2013 Fall「JVMコードリーディング入門-JVMのOS抽象化レイヤーについて-」
JJUG CCC 2013 Fall「JVMコードリーディング入門-JVMのOS抽象化レイヤーについて-」JJUG CCC 2013 Fall「JVMコードリーディング入門-JVMのOS抽象化レイヤーについて-」
JJUG CCC 2013 Fall「JVMコードリーディング入門-JVMのOS抽象化レイヤーについて-」
 
Nmapの真実
Nmapの真実Nmapの真実
Nmapの真実
 
インフラエンジニアに送るVSCode 入門
インフラエンジニアに送るVSCode 入門インフラエンジニアに送るVSCode 入門
インフラエンジニアに送るVSCode 入門
 
OWASP Dependency-Track Introduction
OWASP Dependency-Track IntroductionOWASP Dependency-Track Introduction
OWASP Dependency-Track Introduction
 
Proxy War
Proxy WarProxy War
Proxy War
 
130821 owasp zed attack proxyをぶん回せ
130821 owasp zed attack  proxyをぶん回せ 130821 owasp zed attack  proxyをぶん回せ
130821 owasp zed attack proxyをぶん回せ
 
イベント駆動プログラミングとI/O多重化
イベント駆動プログラミングとI/O多重化イベント駆動プログラミングとI/O多重化
イベント駆動プログラミングとI/O多重化
 
악성코드 개념 및 대응 기술 (사이버 게놈 기술)
악성코드 개념 및 대응 기술 (사이버 게놈 기술)악성코드 개념 및 대응 기술 (사이버 게놈 기술)
악성코드 개념 및 대응 기술 (사이버 게놈 기술)
 
Software design as a cooperative game with EventStorming
Software design as a cooperative game with EventStormingSoftware design as a cooperative game with EventStorming
Software design as a cooperative game with EventStorming
 
RESTful API (JAX-RS) 書くだけで仕様書も 自動で作られていく話 with MicroProfile Open API
RESTful API (JAX-RS) 書くだけで仕様書も自動で作られていく話 with MicroProfile Open APIRESTful API (JAX-RS) 書くだけで仕様書も自動で作られていく話 with MicroProfile Open API
RESTful API (JAX-RS) 書くだけで仕様書も 自動で作られていく話 with MicroProfile Open API
 
社内の遊休PCをAzurePipelinesでCICDに活用しよう
社内の遊休PCをAzurePipelinesでCICDに活用しよう社内の遊休PCをAzurePipelinesでCICDに活用しよう
社内の遊休PCをAzurePipelinesでCICDに活用しよう
 

Andere mochten auch

Mamma, da grande voglio essere un Penetration Tester HackInBo 2016 Winter
Mamma, da grande voglio essere un Penetration Tester HackInBo  2016 WinterMamma, da grande voglio essere un Penetration Tester HackInBo  2016 Winter
Mamma, da grande voglio essere un Penetration Tester HackInBo 2016 WinterSimone Onofri
 
Python base 01-numeristringhe
Python base 01-numeristringhePython base 01-numeristringhe
Python base 01-numeristringheStudiabo
 
Hackers vs Developers: vulnerabilità e soluzioni nello sviluppo di applicazio...
Hackers vs Developers: vulnerabilità e soluzioni nello sviluppo di applicazio...Hackers vs Developers: vulnerabilità e soluzioni nello sviluppo di applicazio...
Hackers vs Developers: vulnerabilità e soluzioni nello sviluppo di applicazio...Simone Onofri
 
Hackers vs Developers - SQL Injection - Attacco e Difesa
Hackers vs Developers - SQL Injection - Attacco e DifesaHackers vs Developers - SQL Injection - Attacco e Difesa
Hackers vs Developers - SQL Injection - Attacco e DifesaSimone Onofri
 
Hackers vs Developers - Nuove e vecchie vulnerabilità con la OWASP TOP 10 2013
Hackers vs Developers - Nuove e vecchie vulnerabilità con la OWASP TOP 10 2013Hackers vs Developers - Nuove e vecchie vulnerabilità con la OWASP TOP 10 2013
Hackers vs Developers - Nuove e vecchie vulnerabilità con la OWASP TOP 10 2013Simone Onofri
 
Project management: Gestire progetto web con Agilità (con DSDM, Agile Project...
Project management: Gestire progetto web con Agilità (con DSDM, Agile Project...Project management: Gestire progetto web con Agilità (con DSDM, Agile Project...
Project management: Gestire progetto web con Agilità (con DSDM, Agile Project...Simone Onofri
 
Agile Lean Management - MoSCoW, Timeboxing e Kanban
Agile Lean Management - MoSCoW, Timeboxing e KanbanAgile Lean Management - MoSCoW, Timeboxing e Kanban
Agile Lean Management - MoSCoW, Timeboxing e KanbanSimone Onofri
 
Diventare ricchi con Python
Diventare ricchi con PythonDiventare ricchi con Python
Diventare ricchi con Pythonantonio.cangiano
 
TEDX TorVergataU - Intuition, Hacking e Nuove Tecnologie
TEDX TorVergataU -  Intuition, Hacking e Nuove TecnologieTEDX TorVergataU -  Intuition, Hacking e Nuove Tecnologie
TEDX TorVergataU - Intuition, Hacking e Nuove TecnologieSimone Onofri
 
Agile e Lean Management
 Agile e Lean Management Agile e Lean Management
Agile e Lean ManagementSimone Onofri
 
ISACA - Gestire progetti di Ethical Hacking secondo le best practices
ISACA - Gestire progetti di Ethical Hacking secondo le best practicesISACA - Gestire progetti di Ethical Hacking secondo le best practices
ISACA - Gestire progetti di Ethical Hacking secondo le best practicesSimone Onofri
 
Python - Primi passi
Python - Primi passi Python - Primi passi
Python - Primi passi orestJump
 
Come costruire un'azienda distribuita con Python
Come costruire un'azienda distribuita con PythonCome costruire un'azienda distribuita con Python
Come costruire un'azienda distribuita con PythonMaurizio Delmonte
 
Come diventare data scientist - Paolo Pellegrini
Come diventare data scientist - Paolo PellegriniCome diventare data scientist - Paolo Pellegrini
Come diventare data scientist - Paolo PellegriniDonatella Cambosu
 
OWASP AppSec EU 2016 - Security Project Management - How to be Agile in Secu...
OWASP AppSec EU 2016 - Security Project Management -  How to be Agile in Secu...OWASP AppSec EU 2016 - Security Project Management -  How to be Agile in Secu...
OWASP AppSec EU 2016 - Security Project Management - How to be Agile in Secu...Simone Onofri
 
socket e SocketServer: il framework per i server Internet in Python
socket e SocketServer: il framework per i server Internet in Pythonsocket e SocketServer: il framework per i server Internet in Python
socket e SocketServer: il framework per i server Internet in PythonPyCon Italia
 
Scenario reclutamento INFN al 17 Novembre 2008
Scenario reclutamento INFN al 17 Novembre 2008Scenario reclutamento INFN al 17 Novembre 2008
Scenario reclutamento INFN al 17 Novembre 2008dael.maselli
 
Python nel primo biennio della scuola superiore
Python nel primo biennio della scuola superiorePython nel primo biennio della scuola superiore
Python nel primo biennio della scuola superioreguestc11532
 

Andere mochten auch (20)

Mamma, da grande voglio essere un Penetration Tester HackInBo 2016 Winter
Mamma, da grande voglio essere un Penetration Tester HackInBo  2016 WinterMamma, da grande voglio essere un Penetration Tester HackInBo  2016 Winter
Mamma, da grande voglio essere un Penetration Tester HackInBo 2016 Winter
 
Py t1 python-intro
Py t1 python-introPy t1 python-intro
Py t1 python-intro
 
Python base 01-numeristringhe
Python base 01-numeristringhePython base 01-numeristringhe
Python base 01-numeristringhe
 
Hackers vs Developers: vulnerabilità e soluzioni nello sviluppo di applicazio...
Hackers vs Developers: vulnerabilità e soluzioni nello sviluppo di applicazio...Hackers vs Developers: vulnerabilità e soluzioni nello sviluppo di applicazio...
Hackers vs Developers: vulnerabilità e soluzioni nello sviluppo di applicazio...
 
Hackers vs Developers - SQL Injection - Attacco e Difesa
Hackers vs Developers - SQL Injection - Attacco e DifesaHackers vs Developers - SQL Injection - Attacco e Difesa
Hackers vs Developers - SQL Injection - Attacco e Difesa
 
Hackers vs Developers - Nuove e vecchie vulnerabilità con la OWASP TOP 10 2013
Hackers vs Developers - Nuove e vecchie vulnerabilità con la OWASP TOP 10 2013Hackers vs Developers - Nuove e vecchie vulnerabilità con la OWASP TOP 10 2013
Hackers vs Developers - Nuove e vecchie vulnerabilità con la OWASP TOP 10 2013
 
Project management: Gestire progetto web con Agilità (con DSDM, Agile Project...
Project management: Gestire progetto web con Agilità (con DSDM, Agile Project...Project management: Gestire progetto web con Agilità (con DSDM, Agile Project...
Project management: Gestire progetto web con Agilità (con DSDM, Agile Project...
 
Agile Lean Management - MoSCoW, Timeboxing e Kanban
Agile Lean Management - MoSCoW, Timeboxing e KanbanAgile Lean Management - MoSCoW, Timeboxing e Kanban
Agile Lean Management - MoSCoW, Timeboxing e Kanban
 
Diventare ricchi con Python
Diventare ricchi con PythonDiventare ricchi con Python
Diventare ricchi con Python
 
TEDX TorVergataU - Intuition, Hacking e Nuove Tecnologie
TEDX TorVergataU -  Intuition, Hacking e Nuove TecnologieTEDX TorVergataU -  Intuition, Hacking e Nuove Tecnologie
TEDX TorVergataU - Intuition, Hacking e Nuove Tecnologie
 
Agile e Lean Management
 Agile e Lean Management Agile e Lean Management
Agile e Lean Management
 
ISACA - Gestire progetti di Ethical Hacking secondo le best practices
ISACA - Gestire progetti di Ethical Hacking secondo le best practicesISACA - Gestire progetti di Ethical Hacking secondo le best practices
ISACA - Gestire progetti di Ethical Hacking secondo le best practices
 
Python - Primi passi
Python - Primi passi Python - Primi passi
Python - Primi passi
 
Come costruire un'azienda distribuita con Python
Come costruire un'azienda distribuita con PythonCome costruire un'azienda distribuita con Python
Come costruire un'azienda distribuita con Python
 
Come diventare data scientist - Paolo Pellegrini
Come diventare data scientist - Paolo PellegriniCome diventare data scientist - Paolo Pellegrini
Come diventare data scientist - Paolo Pellegrini
 
ORM Injection
ORM InjectionORM Injection
ORM Injection
 
OWASP AppSec EU 2016 - Security Project Management - How to be Agile in Secu...
OWASP AppSec EU 2016 - Security Project Management -  How to be Agile in Secu...OWASP AppSec EU 2016 - Security Project Management -  How to be Agile in Secu...
OWASP AppSec EU 2016 - Security Project Management - How to be Agile in Secu...
 
socket e SocketServer: il framework per i server Internet in Python
socket e SocketServer: il framework per i server Internet in Pythonsocket e SocketServer: il framework per i server Internet in Python
socket e SocketServer: il framework per i server Internet in Python
 
Scenario reclutamento INFN al 17 Novembre 2008
Scenario reclutamento INFN al 17 Novembre 2008Scenario reclutamento INFN al 17 Novembre 2008
Scenario reclutamento INFN al 17 Novembre 2008
 
Python nel primo biennio della scuola superiore
Python nel primo biennio della scuola superiorePython nel primo biennio della scuola superiore
Python nel primo biennio della scuola superiore
 

Ähnlich wie Penetration Testing con Python - Network Sniffer

Azure IoTHub - Roboval 2018
Azure IoTHub - Roboval 2018Azure IoTHub - Roboval 2018
Azure IoTHub - Roboval 2018Andrea Tosato
 
OSINT su siti web
OSINT su siti webOSINT su siti web
OSINT su siti webdalchecco
 
Network_Forensics_Analysis_Tool.pptx
Network_Forensics_Analysis_Tool.pptxNetwork_Forensics_Analysis_Tool.pptx
Network_Forensics_Analysis_Tool.pptxManlioSantonastaso
 
TOR - The Onion Router
TOR - The Onion Router TOR - The Onion Router
TOR - The Onion Router Marcello Viti
 
Alla scoperta di gRPC
Alla scoperta di gRPCAlla scoperta di gRPC
Alla scoperta di gRPCAndrea Dottor
 
Da e verso odoo xml rpc, erppeek e python
Da e verso odoo  xml rpc, erppeek e pythonDa e verso odoo  xml rpc, erppeek e python
Da e verso odoo xml rpc, erppeek e pythonOpenCode
 
Internet of Things for Dummies
Internet of Things for DummiesInternet of Things for Dummies
Internet of Things for DummiesPaolo Aliverti
 
TechDay: Internet delle cose - Paolo Aliverti
TechDay: Internet delle cose - Paolo Aliverti TechDay: Internet delle cose - Paolo Aliverti
TechDay: Internet delle cose - Paolo Aliverti Codemotion
 
Installazione di Joomla nel cloud di Red Hat
Installazione di Joomla nel cloud di Red HatInstallazione di Joomla nel cloud di Red Hat
Installazione di Joomla nel cloud di Red HatBabel
 
Industrial Iot - IotSaturday
Industrial Iot - IotSaturday Industrial Iot - IotSaturday
Industrial Iot - IotSaturday Riccardo Zamana
 
Snort React per Webfiltering : "Soluzioni per le Leggi-Lista"
Snort React per Webfiltering : "Soluzioni per le Leggi-Lista"Snort React per Webfiltering : "Soluzioni per le Leggi-Lista"
Snort React per Webfiltering : "Soluzioni per le Leggi-Lista"Camelug Fava
 
Gli HTTP Security Header e altri elementi da sapere su HTTP in un Web Applica...
Gli HTTP Security Header e altri elementi da sapere su HTTP in un Web Applica...Gli HTTP Security Header e altri elementi da sapere su HTTP in un Web Applica...
Gli HTTP Security Header e altri elementi da sapere su HTTP in un Web Applica...Simone Onofri
 
php: back to basics
php: back to basicsphp: back to basics
php: back to basicsFabio Mora
 
Introduzione ad ubuntu core - Qt day 2017
Introduzione ad ubuntu core  - Qt day 2017Introduzione ad ubuntu core  - Qt day 2017
Introduzione ad ubuntu core - Qt day 2017Marco Trevisan
 
Traffic Shaping Su Linux
Traffic Shaping Su LinuxTraffic Shaping Su Linux
Traffic Shaping Su LinuxMajong DevJfu
 
Installare i server via rete con Cobbler
Installare i server via rete con CobblerInstallare i server via rete con Cobbler
Installare i server via rete con CobblerBabel
 

Ähnlich wie Penetration Testing con Python - Network Sniffer (20)

Packet Sniffing
Packet SniffingPacket Sniffing
Packet Sniffing
 
Azure IoTHub - Roboval 2018
Azure IoTHub - Roboval 2018Azure IoTHub - Roboval 2018
Azure IoTHub - Roboval 2018
 
OSINT su siti web
OSINT su siti webOSINT su siti web
OSINT su siti web
 
Network_Forensics_Analysis_Tool.pptx
Network_Forensics_Analysis_Tool.pptxNetwork_Forensics_Analysis_Tool.pptx
Network_Forensics_Analysis_Tool.pptx
 
TOR - The Onion Router
TOR - The Onion Router TOR - The Onion Router
TOR - The Onion Router
 
Alla scoperta di gRPC
Alla scoperta di gRPCAlla scoperta di gRPC
Alla scoperta di gRPC
 
Da e verso odoo xml rpc, erppeek e python
Da e verso odoo  xml rpc, erppeek e pythonDa e verso odoo  xml rpc, erppeek e python
Da e verso odoo xml rpc, erppeek e python
 
Progetto Netkit
Progetto NetkitProgetto Netkit
Progetto Netkit
 
Internet of Things for Dummies
Internet of Things for DummiesInternet of Things for Dummies
Internet of Things for Dummies
 
TechDay: Internet delle cose - Paolo Aliverti
TechDay: Internet delle cose - Paolo Aliverti TechDay: Internet delle cose - Paolo Aliverti
TechDay: Internet delle cose - Paolo Aliverti
 
Installazione di Joomla nel cloud di Red Hat
Installazione di Joomla nel cloud di Red HatInstallazione di Joomla nel cloud di Red Hat
Installazione di Joomla nel cloud di Red Hat
 
Slide Bit Torrent
Slide Bit TorrentSlide Bit Torrent
Slide Bit Torrent
 
Industrial Iot - IotSaturday
Industrial Iot - IotSaturday Industrial Iot - IotSaturday
Industrial Iot - IotSaturday
 
Snort React per Webfiltering : "Soluzioni per le Leggi-Lista"
Snort React per Webfiltering : "Soluzioni per le Leggi-Lista"Snort React per Webfiltering : "Soluzioni per le Leggi-Lista"
Snort React per Webfiltering : "Soluzioni per le Leggi-Lista"
 
Gli HTTP Security Header e altri elementi da sapere su HTTP in un Web Applica...
Gli HTTP Security Header e altri elementi da sapere su HTTP in un Web Applica...Gli HTTP Security Header e altri elementi da sapere su HTTP in un Web Applica...
Gli HTTP Security Header e altri elementi da sapere su HTTP in un Web Applica...
 
php: back to basics
php: back to basicsphp: back to basics
php: back to basics
 
Introduzione ad ubuntu core - Qt day 2017
Introduzione ad ubuntu core  - Qt day 2017Introduzione ad ubuntu core  - Qt day 2017
Introduzione ad ubuntu core - Qt day 2017
 
Traffic Shaping Su Linux
Traffic Shaping Su LinuxTraffic Shaping Su Linux
Traffic Shaping Su Linux
 
Installare i server via rete con Cobbler
Installare i server via rete con CobblerInstallare i server via rete con Cobbler
Installare i server via rete con Cobbler
 
Il nuovo Bryar.pm
Il nuovo Bryar.pmIl nuovo Bryar.pm
Il nuovo Bryar.pm
 

Mehr von Simone Onofri

Attacking and Exploiting Ethereum Smart Contracts: Auditing 101
Attacking and Exploiting Ethereum Smart Contracts: Auditing 101Attacking and Exploiting Ethereum Smart Contracts: Auditing 101
Attacking and Exploiting Ethereum Smart Contracts: Auditing 101Simone Onofri
 
Attacking IoT Devices from a Web Perspective - Linux Day
Attacking IoT Devices from a Web Perspective - Linux Day Attacking IoT Devices from a Web Perspective - Linux Day
Attacking IoT Devices from a Web Perspective - Linux Day Simone Onofri
 
Attacking Ethereum Smart Contracts a deep dive after ~9 years of deployment
Attacking Ethereum Smart Contracts  a deep dive after ~9 years of deploymentAttacking Ethereum Smart Contracts  a deep dive after ~9 years of deployment
Attacking Ethereum Smart Contracts a deep dive after ~9 years of deploymentSimone Onofri
 
Linux Day 2018 Roma - Web Application Penetration Test (WAPT) con Linux
Linux Day 2018 Roma - Web Application Penetration Test (WAPT) con LinuxLinux Day 2018 Roma - Web Application Penetration Test (WAPT) con Linux
Linux Day 2018 Roma - Web Application Penetration Test (WAPT) con LinuxSimone Onofri
 
Agile Lean Conference 2017 - Leadership e facilitazione
Agile Lean Conference 2017 - Leadership e facilitazioneAgile Lean Conference 2017 - Leadership e facilitazione
Agile Lean Conference 2017 - Leadership e facilitazioneSimone Onofri
 
Agile Business Consortium - LEGO SERIOUS PLAY e i Principi di Agile Project M...
Agile Business Consortium - LEGO SERIOUS PLAY e i Principi di Agile Project M...Agile Business Consortium - LEGO SERIOUS PLAY e i Principi di Agile Project M...
Agile Business Consortium - LEGO SERIOUS PLAY e i Principi di Agile Project M...Simone Onofri
 
Agile Project Framework
Agile Project FrameworkAgile Project Framework
Agile Project FrameworkSimone Onofri
 
Agile nei servizi di cyber security (Security Summit Edition)
Agile nei servizi di cyber security (Security Summit Edition)Agile nei servizi di cyber security (Security Summit Edition)
Agile nei servizi di cyber security (Security Summit Edition)Simone Onofri
 
Security Project Management - Agile nei servizi di Cyber Security
Security Project Management - Agile nei servizi di Cyber SecuritySecurity Project Management - Agile nei servizi di Cyber Security
Security Project Management - Agile nei servizi di Cyber SecuritySimone Onofri
 
Cyber Defense - How to be prepared to APT
Cyber Defense - How to be prepared to APTCyber Defense - How to be prepared to APT
Cyber Defense - How to be prepared to APTSimone Onofri
 
Nuove minacce nella Cyber Security, come proteggersi
Nuove minacce nella Cyber Security, come proteggersiNuove minacce nella Cyber Security, come proteggersi
Nuove minacce nella Cyber Security, come proteggersiSimone Onofri
 
Hackers vs Developers - Cross Site Scripting (XSS) Attacco e difesa
Hackers vs Developers - Cross Site Scripting (XSS) Attacco e difesaHackers vs Developers - Cross Site Scripting (XSS) Attacco e difesa
Hackers vs Developers - Cross Site Scripting (XSS) Attacco e difesaSimone Onofri
 
Agile lean conference - Agile, Lean & Business
Agile lean conference - Agile, Lean & BusinessAgile lean conference - Agile, Lean & Business
Agile lean conference - Agile, Lean & BusinessSimone Onofri
 
Lean Startup Machine - Rome - Agile e Lean Project Management
Lean Startup Machine - Rome - Agile e Lean Project ManagementLean Startup Machine - Rome - Agile e Lean Project Management
Lean Startup Machine - Rome - Agile e Lean Project ManagementSimone Onofri
 
ITSMF Conferenza 2014 - L'officina Agile per innovare l'IT Service Management
ITSMF Conferenza 2014 - L'officina Agile per innovare l'IT Service ManagementITSMF Conferenza 2014 - L'officina Agile per innovare l'IT Service Management
ITSMF Conferenza 2014 - L'officina Agile per innovare l'IT Service ManagementSimone Onofri
 
IPMA 2014 World Congress - Stakeholder Engagement between Traditional and Ag...
IPMA 2014 World Congress -  Stakeholder Engagement between Traditional and Ag...IPMA 2014 World Congress -  Stakeholder Engagement between Traditional and Ag...
IPMA 2014 World Congress - Stakeholder Engagement between Traditional and Ag...Simone Onofri
 
Meetmagento 2014 hackers_onofri
Meetmagento 2014 hackers_onofriMeetmagento 2014 hackers_onofri
Meetmagento 2014 hackers_onofriSimone Onofri
 

Mehr von Simone Onofri (17)

Attacking and Exploiting Ethereum Smart Contracts: Auditing 101
Attacking and Exploiting Ethereum Smart Contracts: Auditing 101Attacking and Exploiting Ethereum Smart Contracts: Auditing 101
Attacking and Exploiting Ethereum Smart Contracts: Auditing 101
 
Attacking IoT Devices from a Web Perspective - Linux Day
Attacking IoT Devices from a Web Perspective - Linux Day Attacking IoT Devices from a Web Perspective - Linux Day
Attacking IoT Devices from a Web Perspective - Linux Day
 
Attacking Ethereum Smart Contracts a deep dive after ~9 years of deployment
Attacking Ethereum Smart Contracts  a deep dive after ~9 years of deploymentAttacking Ethereum Smart Contracts  a deep dive after ~9 years of deployment
Attacking Ethereum Smart Contracts a deep dive after ~9 years of deployment
 
Linux Day 2018 Roma - Web Application Penetration Test (WAPT) con Linux
Linux Day 2018 Roma - Web Application Penetration Test (WAPT) con LinuxLinux Day 2018 Roma - Web Application Penetration Test (WAPT) con Linux
Linux Day 2018 Roma - Web Application Penetration Test (WAPT) con Linux
 
Agile Lean Conference 2017 - Leadership e facilitazione
Agile Lean Conference 2017 - Leadership e facilitazioneAgile Lean Conference 2017 - Leadership e facilitazione
Agile Lean Conference 2017 - Leadership e facilitazione
 
Agile Business Consortium - LEGO SERIOUS PLAY e i Principi di Agile Project M...
Agile Business Consortium - LEGO SERIOUS PLAY e i Principi di Agile Project M...Agile Business Consortium - LEGO SERIOUS PLAY e i Principi di Agile Project M...
Agile Business Consortium - LEGO SERIOUS PLAY e i Principi di Agile Project M...
 
Agile Project Framework
Agile Project FrameworkAgile Project Framework
Agile Project Framework
 
Agile nei servizi di cyber security (Security Summit Edition)
Agile nei servizi di cyber security (Security Summit Edition)Agile nei servizi di cyber security (Security Summit Edition)
Agile nei servizi di cyber security (Security Summit Edition)
 
Security Project Management - Agile nei servizi di Cyber Security
Security Project Management - Agile nei servizi di Cyber SecuritySecurity Project Management - Agile nei servizi di Cyber Security
Security Project Management - Agile nei servizi di Cyber Security
 
Cyber Defense - How to be prepared to APT
Cyber Defense - How to be prepared to APTCyber Defense - How to be prepared to APT
Cyber Defense - How to be prepared to APT
 
Nuove minacce nella Cyber Security, come proteggersi
Nuove minacce nella Cyber Security, come proteggersiNuove minacce nella Cyber Security, come proteggersi
Nuove minacce nella Cyber Security, come proteggersi
 
Hackers vs Developers - Cross Site Scripting (XSS) Attacco e difesa
Hackers vs Developers - Cross Site Scripting (XSS) Attacco e difesaHackers vs Developers - Cross Site Scripting (XSS) Attacco e difesa
Hackers vs Developers - Cross Site Scripting (XSS) Attacco e difesa
 
Agile lean conference - Agile, Lean & Business
Agile lean conference - Agile, Lean & BusinessAgile lean conference - Agile, Lean & Business
Agile lean conference - Agile, Lean & Business
 
Lean Startup Machine - Rome - Agile e Lean Project Management
Lean Startup Machine - Rome - Agile e Lean Project ManagementLean Startup Machine - Rome - Agile e Lean Project Management
Lean Startup Machine - Rome - Agile e Lean Project Management
 
ITSMF Conferenza 2014 - L'officina Agile per innovare l'IT Service Management
ITSMF Conferenza 2014 - L'officina Agile per innovare l'IT Service ManagementITSMF Conferenza 2014 - L'officina Agile per innovare l'IT Service Management
ITSMF Conferenza 2014 - L'officina Agile per innovare l'IT Service Management
 
IPMA 2014 World Congress - Stakeholder Engagement between Traditional and Ag...
IPMA 2014 World Congress -  Stakeholder Engagement between Traditional and Ag...IPMA 2014 World Congress -  Stakeholder Engagement between Traditional and Ag...
IPMA 2014 World Congress - Stakeholder Engagement between Traditional and Ag...
 
Meetmagento 2014 hackers_onofri
Meetmagento 2014 hackers_onofriMeetmagento 2014 hackers_onofri
Meetmagento 2014 hackers_onofri
 

Penetration Testing con Python - Network Sniffer

  • 1. Penetration Testing con Python Scrivere i propri strumenti Networking - Sniffer Simone Onofri @simoneonofri mailto:simone@onofri.org CC BY-ND-NC
  • 2. Agenda • Introduzione e FAQ • Perché scrivere i propri strumenti • Questioni religiose • Brevissima introduzione a Python • Lo Sniffer TCP/HTTP «a proprie spese» e «la via breve» • Prossimi passi • Conclusioni
  • 4. «Ricordatevi, la differenza tra uno script kiddie e un professionista è la differenza tra chi meramente utilizza gli strumenti di altri e chi scrive i propri» -- Charlie Miller (Prefazione a Black Hat Python)
  • 5. Penetration Testing e strumenti L’OSSTMM indica che l’analista deve conoscere i propri strumenti, da dove vengono, come funzionano e li deve aver provati prima in un ambiente controllato. Sono molte le implicazioni di questo concetto. Focalizziamoci su due casi specifici. Gli hanno fatti altri, sappiamo come funzionano e se funzionano? Possono fare danni? Contenere back door o codice malevolo? Se li abbiamo fatti noi, conosciamo bene l’attacco che stiamo facendo? I protocolli? I sistemi o la rete bersaglio?
  • 6. «se ascolto dimentico, se vedo ricordo, se faccio capisco» -- Antico proverbio cinese || Confucio
  • 7. Perché Python e non <inserire-altro-linguaggio>? E perché Python 2.7 e non Python 3? https://wiki.python.org/moin/Python2orPython3
  • 8. Perché Python «Python è un linguaggio a ridotta complessità, ha molte librerie di terze parti* e un basso costo d’ingresso. Su OSX e Linux è già installato. Molti altri strumenti sono già fatti in Python.» -- TJ O'Connor (Violent Python) https://github.com/dloss/python-pentest-tools
  • 9. Hello World • E’ un linguaggio interpretato • Abbiamo tre modi principali per farlo girare: • Codice nella riga di comando $ python -c "print 'Hello World'" • Codice in un file $ python helloworld.py • Codice interattivo $ python >>> print 'Hello World'
  • 10. Python da Zero in tre passi • Anzitutto va installato python (se non lo è già) e.g. su debian $ sudo apt-get install python • Si installa PIP (il gestore di pacchetti di python) $ sudo apt-get install python-pip • Si installa virtualenv – che serve per creare ambienti virtuali (rende tutto può portabile e si evita di appesantire il sistema dove lavoriamo) $ sudo pip install virtualenv http://docs.python-guide.org/en/latest/starting/installation/ https://packaging.python.org/installing/ http://docs.python-guide.org/en/latest/dev/virtualenvs/
  • 11. Iniziamo a «codare» • Quando si parte, a livello di prototipazione e testare quello che facciamo, conviene utilizzare l’interprete in maniera interattiva e vedere quello che succede, eventuali errori ecc…. • Lo scopo di questa introduzione è guidarci verso lo sviluppo di strumenti di rete, alcune cose saranno intro, man mano che vediamo il codice, l’importante è capire l’approccio! • Quando ci sono delle cose nuovo le introduciamo, per alcuni alcune cose saranno scontate, per altre nuove. Intanto si possono prendere «così come sono» e poi fare con calma debug.
  • 12. Use case: Sniffer HTTP con i RAW Socket • Una delle attività tipiche che si fa sulla rete è quello di sniffare il traffico, magari siamo già in una posizione di rete privilegiata (oppure su un hub) e quindi non abbiamo bisogno di utilizzare tecniche particolari per farci arrivare il traffico (quelle le vediamo dopo). • A livello teorico dobbiamo conoscere quindi come funziona la suite di protocolli TCP/IP e, considerando che il nostro scopo è quello di leggere il traffico HTTP, dobbiamo partire dai protocolli che sono più in basso.
  • 13. La suite di protocolli TCP/IP • Application: Servizi applicativi per l’utente (nel nostro caso HTTP). • Transport: Organizza I dati per il trasporto e la loro trasmissioni (nel nostro caso TCP). • Internet/Gateway: Gestisce l’indirizzamento logico tra due sistemi, anche quelli che ono sono connessi direttamente, come anche il percordo per arrivare a questi sistemi (nel nostro caso IPv4). • Network : Converte le informazioni logiche sui dispositivi fisici (nel nostro caso Ethernet). +------+ +-----+ +-----+ +-----+ |Telnet| | FTP | |Voice| ... | | Application Level +------+ +-----+ +-----+ +-----+ | | | | +-----+ +-----+ +-----+ | TCP | | RTP | ... | | Host Level +-----+ +-----+ +-----+ | | | +-------------------------------+ | Internet Protocol & ICMP | Gateway Level +-------------------------------+ | +---------------------------+ | Local Network Protocol | Network Level +---------------------------+ Protocol Relationships https://tools.ietf.org/html/rfc793
  • 14. Incapsulamento Frame Header IP Header TCP/UDP Header Applicat ion Data Frame Trailer Ethernet Frame IP Header TCP/UDP Header Applicat ion Data IP Datagram TCP/UDP Header Applicat ion Data TCP Segment Applicat ion Data HTTP Data Quando catturiamo il traffico sulla rete (nel pratico un flusso di bit) troviamo una serie di informazioni incapsulate che vanno recuperate, strutturate e interpretate. Questa operazione viene anche chiamata dissezione.
  • 15. Vediamo i pacchetti con un RAW socket 1. $ sudo python # serve sudo per l’accesso ai RAW socket 2. >>> import socket # importo il modulo per i raw socket BSD 3. >>> s = socket.socket(socket.SOCK_RAW, socket.AF_INET, socket.IPPROTO_TCP) # creo il socket per avere i pacchetti RAW, con IP v4 e TCP >>> packets = [] # creo una lista per contenere i miei pacchetti (poi vediamo come ci si accede) 4. >>> for i in range(5): # prendi 5 pacchetti 5. ... packet = s.recvfrom(65565) # da notare che siamo indentati (4 spazi), ricevi i pacchetti con un buffer passato dall’utente 6. ... packets.append(packet) # mette i pacchetti catturati nella lista 7. ... >>> len(packets) # controllo quanti pacchetti ho effettivamente catturato 8. 5 # bene, abbiamo i nostri pacchetti, 5 9. >>> packets # vediamo il contenuto, il fatidico flusso di bit 10.[('Ex00x00LB=@x00x80x06xdex9bxc0xa8,x01xc0xa8,x81x9cx8ex00x165 xc8x856x19xfdF Px18x00xffxcbx00x00xadx85xfd6yx06>xabxffxfa>:xe4xaex06xaex05 Zxcexf2xae7xc1xfbx9fmXxd3x84x0f:x83xb8ux11xef', ('192.168.44.1', 0)), 11.…
  • 16. La nostra prima parte dello sniffer 1. #!/usr/bin/env python 2. import socket 3. import struct 4. s = socket.socket(socket.SOCK_RAW, socket.AF_INET,socket.IPPROTO_TCP) 5. while 1: # qui modifico in un while 6. print s.recvfrom(65565) # stampo direttamente 7. ''' 8. Come possiamo vedere per controllare il flusso abbiamo usato un while, in python non abbiamo le parentesi come in C – per esempio – ma l’indentazione, di norma deve essere fatta con quattro spazi. Le varie regole su come scrivere codice con stile in Pyhon sono contenuti nella PEP-008 9. ''' https://www.python.org/dev/peps/pep-0008/
  • 17. Andiamo in profondità Quando abbiamo creato il socket, abbiamo visto alcune impostazioni inserite, se le voglio sapere tutte, in modalità interattiva dopo aver importato il modulo possiamo usare ‘dir()’ per avere la lista di elementi che possiamo avere (e.g. le costanti) e help() per avere l’aiuto. >>> dir(socket) >>> help(socket) Inoltre, dato che stiamo usando i socket BSD, quando andiamo a cercare variabili e informazioni, possiamo fare riferimento alla documentazione relativa e ai file sul nostro sistema. Attenzione a cercare le informazioni su Google / Stack Overflow
  • 18. Dissezionare i protocolli • Con i RAW socket abbiamo sicuramente i pacchetti ma le informazioni sono in formato binario, per renderle leggibili dobbiamo scrivere dei dissector per poterle leggerle in formato «umano». • Utilizzeremo quindi il modulo struct che serve ad interpretare i dati binari e poterli leggere. • In caso di emergenza fare riferimento a: • RFC (attenzione agli aggiornamenti) • file di inclusione che troviamo nel nostro sistema (l’open source sia lodato) • man.
  • 19. Dissezionare IP – RFC 791 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |Version| IHL |Type of Service| Total Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Identification |Flags| Fragment Offset | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Time to Live | Protocol | Header Checksum | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Source Address | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Destination Address | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Options | Padding | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ https://tools.ietf.org/rfc/rfc791.txt • Version: 4 bits • IHL (Internet Header Lenght): 4 bits • ToS: 8 bits • Total Lenght: 16 bits • Identification 16 bits • Flags: 3 bits • Fragment Offset: 13 bits • TTL: 8 bits • Protocol: 8 bits • Header Checksum: 16 bits • Source Address: 32 bits • Destination Address: 32 bits • Options: variable • Padding: variable
  • 20. Il formato di struct Format C Type Python type Standard size Notes x pad byte no value c char string of length 1 1 b signed char integer 1 (3) B unsigned char integer 1 (3) ? _Bool bool 1 (1) h short integer 2 (3) H unsigned short integer 2 (3) i int integer 4 (3) I unsigned int integer 4 (3) l long integer 4 (3) L unsigned long integer 4 (3) q long long integer 8 (2), (3) Q unsigned long long integer 8 (2), (3) f float float 4 (4) d double float 8 (4) s char[] string p char[] string P void * integer (5), (3) https://docs.python.org/2/library/struct.html#format-characters
  • 21. Dissezionare IP - /usr/include/linux/ip.h 1.struct iphdr { 2.#if defined(__LITTLE_ENDIAN_BITFIELD) 3.#elif defined (__BIG_ENDIAN_BITFIELD) 4. __u8 version:4, ihl:4; 5.#else #error "Please fix <asm/byteorder.h>« #endif __u8 tos; __be16 tot_len; __be16 id; __be16 frag_off; __u8 ttl; __u8 protocol; __sum16 check; __be32 saddr; __be32 daddr; /*The options start here. */ 6.}; Big Endian (Network) ! [0] __u8 > unsigned char > B # version ihl [1] __u8 > unsigned char > B # tos [2] __be16 > unsigned short > H # tot_len [3] __be16 > unsigned short > H # id [4] __be16 > unsigned short > H #frag_off; [5] __u8 > unsigned char > B #ttl; [6]__u8 > unsigned char > B # protocol; [7]__sum16 > unsigned short > H # check; [8]__be32 > unsigned int > I # source address [9]__be32 > unsigned int > I # destination address Il nostro formato corretto è !BBHHHBBHII ma possiamo anche usare !BBHHHBBH4s4s - sostituendo i due unsigned int (32 bit) con quattro byte - per praticità di conversione
  • 22. Dissezionare IP - Logica 1. ip_size = 20 # prendo la prima parte dell’hueader IP 2. ip_start = 0 # partiamo da 0 (secondo il tipo di RAW socket che usiamo) 3. ip_finish = ip_start + ip_size # calcolo la fine 4. ip_header_slice = packet[0][ip_start:ip_finish] # prendo il pezzo – slice – che miinteressa, il primo campo del pacchetto e lo ‘taglio’ come mi interessa 5. ip_header_unpack = unpack('!BBHHHBBH4s4s' , ip_header_slice) # uso il formato che abbiamo ottenuto 6. ip_version_ihl = ip_header_unpack[0] # prendo la prima parte che mi interessa 7. ip_version = ip_version_ihl >> 4 # recupero i primi bit della versione 8. ip_ihl = ip_version_ihl & 0xF # recupero la lunghezza 9. ip_header_length = ip_ihl * 4 # converto per avere la lunghezza 10.ip_tos = ip_header_unpack[1] # prendo il TOS 11.ip_lenght = ip_header_unpack[2] # prendo la lunghezza 12.ip_id = ip_header_unpack[3] # prendo l’IPID* 13.ip_fragmentation = ip_header_unpack[4] # prendo la frammentazione 14.ip_ttl = ip_header_unpack[5] # prendo il TTL 15.ip_protocol = ip_header_unpack[6] # prendo il protocollo 16.ip_checksum = ip_header_unpack[7] # prendo il checksum 17.ip_source_address = socket.inet_ntoa(ip_header_unpack[8]) # prendo l’IP sorgente e lo converto tramite una funziona che converte il binario il notazione dotted (questo il motivo per cui abbiamo preso dei byte e non degli unsigned int, per praticità) 18.ip_destination_address = socket.inet_ntoa(ip_header_unpack[9]) # prendo l’IP destinazione
  • 23. Dissezionare IP – Stampa 1. print "= IP =========" 2. print "tIP Version: " + str(ip_version) 3. print "tIP Header Length: " + str(ip_header_length) 4. print "tIP TOS: " + str(ip_tos) 5. print "tIP length: " + str(ip_lenght) 6. print "tIPID: " + str(ip_id) 7. print "tIP Fragmentation: " + str(ip_fragmentation) 8. print "tIP TTL: " + str(ip_ttl) 9. print "tIP Protocol: " + str(ip_protocol) 10.print "tIP Source: " + ip_source_address 11.print "tIP Destination: " + ip_destination_address = IP ========= IP Version: 4 IP Header Length: 20 IP TOS: 0 IP length: 5 IPID: 1640 IP Fragmentation: 0 IP TTL: 128 IP Protocol: 6 IP Source: 104.28.13.52 IP Destination: 192.168.44.129
  • 24. Dissezionare TCP 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Source Port | Destination Port | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Sequence Number | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Acknowledgment Number | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Data | |U|A|P|R|S|F| | | Offset| Reserved |R|C|S|S|Y|I| Window | | | |G|K|H|T|N|N| | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Checksum | Urgent Pointer | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Options | Padding | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | data | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ https://www.ietf.org/rfc/rfc793.txt • Sport: 16 bits • Dport: 16 bits • Sequence Number: 32 bits • Acknoledgment Number: 32 bits • Data offset: 4 bits • Reserved: 6 bits • Control Bits: 6 bits (left-right) • Window: 16 bits • Checksum: 16 bits • Urgent Pointer: 16 bits • Options: variable • Padding: variable
  • 25. Dissezionare TCP - /usr/include/linux/tcp.h Big Endian (Network) ! [0] 16bit >>> sport H [1] 16bit >>> dport H [2] 32bit >>> sequence L [3] 32bit >>> ack-number L [4] 4bit >>> offset H 4bit >>> reserved 6bit >>> flags 1bit >>> CWR 1bit >>> ECE 1bit >>> URG 1bit >>> ACK 1bit >>> PSH 1bit >>> RST 1bit >>> SYN 1bit >>> FIN [5] 16bit >>> window H [6] 16bit >>> check H [7] 16bit >>> urg_ptr H 1. struct tcphdr { 2. __be16 source; 3. __be16 dest; 4. __be32 seq; 5. __be32 ack_seq; 6. #if defined(__LITTLE_ENDIAN_BITFIELD) 7. #elif defined(__BIG_ENDIAN_BITFIELD) 8. __u16 doff:4, 9. res1:4, 10. cwr:1, 11. ece:1, 12. urg:1, 13. ack:1, 14. psh:1, 15. rst:1, 16. syn:1, 17. fin:1; 18.#else 19.#error "Adjust your <asm/byteorder.h> defines" 20.#endif 21. __be16 window; 22. __sum16 check; 23. __be16 urg_ptr; 24.}; Il nostro formato corretto è !HHLLHHHH
  • 26. Dissezionare TCP – RFC 3168 https://tools.ietf.org/html/rfc3168 The Transmission Control Protocol (TCP) included a 6-bit Reserved field defined in RFC 793, reserved for future use, in bytes 13 and 14 of the TCP header, as illustrated below. The other six Control bits are defined separately by RFC 793. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ | | | U | A | P | R | S | F | | Header Length | Reserved | R | C | S | S | Y | I | | | | G | K | H | T | N | N | +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ RFC 3168 defines two of the six bits from the Reserved field to be used for ECN, as follows: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ | | | C | E | U | A | P | R | S | F | | Header Length | Reserved | W | C | R | C | S | S | Y | I | | | | R | E | G | K | H | T | N | N | +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
  • 27. Dissezionare TCP - Codice 1. tcp_size = 20 # dimensione di un header TCP minimz 2. tcp_start = ip_header_length # inizio da dove finisce IP 3. tcp_finish = tcp_start + tcp_size # fine 4. tcp_header_slice = packet[0][tcp_start:tcp_finish] # prendo la parte che mi interessa 5. tcp_header_unpack = unpack('!HHLLHHHH' , tcp_header_slice) # spacchetto con il formato 6. tcp_source_port = tcp_header_unpack[0] # prendo la porta sorgente 7. tcp_dest_port = tcp_header_unpack[1] # prendo la porta destinazione 8. tcp_sequence = tcp_header_unpack[2] # prendo il sequence number 9. tcp_acknowledgement = tcp_header_unpack[3] # prendo l’acknowledge number 10.tcp_osf = bin(tcp_header_unpack[4])[2:].zfill(16) # prendo la porzione dei bit di controllo 11.tcp_offset = tcp_osf[0:4] # prendo l’offset 12.tcp_reserved = tcp_osf[4:8] # prendo la parte riservata 13.tcp_cwr = tcp_osf[8:9] # prendo il flag specifico CWR ** 14.tcp_ece = tcp_osf[9:10] # prendo il flag specifico ECE ** 15.tcp_urg = tcp_osf[10:11] # prendo il flag specifico URG ** 16.tcp_ack = tcp_osf[11:12] # prendo il flag specifico ACK ** 17.tcp_psh = tcp_osf[12:13] # prendo il flag specifico PSH ** 18.tcp_rst = tcp_osf[13:14] # prendo il flag specifico RST ** 19.tcp_syn = tcp_osf[14:15] # prendo il flag specifico SYN ** 20.tcp_fin = tcp_osf[15:16] # prendo il flag specifico FIN ** 21.tcp_window = tcp_header_unpack[5] # prendo la window 22.tcp_checksum = tcp_header_unpack[6] # prendo il checksum 23.tcp_urg_ptr = tcp_header_unpack[7] # prendo l’urgent pointer 24.tcp_header_length = int(tcp_offset,2) * 4 # mi serve la lunghezza per tagliare correttamente il layer 7
  • 28. Dissezionare TCP – Stampa e Output 1. print "= TCP ========« 2. print "tTCP Source Port: " + str(tcp_source_port) 3. print "tTCP Destination Port: " + str(tcp_dest_port) 4. print "tTCP Sequence Number: " + str(tcp_sequence) 5. print "tTCP Acknowledge Number: " + str(tcp_acknowledgement) 6. print "tTCP Offset: " + tcp_offset 7. print "tTCP Reserved: " + tcp_reserved 8. print "tTCP Flags: " + tcp_osf 9. print "ttFIN: " + str(tcp_fin) 10.print "ttSYN: " + str(tcp_syn) 11.print "ttRST: " + str(tcp_syn) 12.print "ttPSH: " + str(tcp_psh) 13.print "ttACK: " + str(tcp_ack) 14.print "ttURG: " + str(tcp_urg) 15.print "ttECE: " + str(tcp_ece) 16.print "ttCWR: " + str(tcp_cwr) 17.print "tTCP Window: " + str(socket.ntohs(tcp_window)) # inverse is socket.htons 18.print "tTCP Checksum: " + str(tcp_checksum) 19.print "tTCP Urgent: " + str(tcp_urg_ptr) = TCP ======== TCP Source Port: 80 TCP Destination Port: 51666 TCP Sequence Number: 405830337 TCP Acknowledge Number: 3434543485 TCP Offset: 0101 TCP Reserved: 0000 TCP Flags: 0101000000011000 FIN: 0 SYN: 0 RST: 0 PSH: 1 ACK: 1 URG: 0 ECE: 0 CWR: 0 TCP Window: 61690 TCP Checksum: 5442 TCP Urgent: 0
  • 29. Sopra il TCP… HTTP Sappiamo che HTTP è un protocollo non binario. Quindi per ora limitiamo vedere le stringhe header_size = ip_start + ip_header_length + tcp_header_length # ecco a cosa mi serviva la dimnesione data = packet[0][header_size:] # recupero il payload print "= Data ========" print "tData: " + data # converto la stringa e stampo (per HTML funziona abbastanza bene*) print "nnn"
  • 30. Il nostro HTTP* 1. = Data ======== Data: HTTP/1.1 302 Found 2. Date: Sat, 22 Oct 2016 00:14:13 GMT 3. Content-Type: text/plain; charset=utf-8 4. Content-Length: 46 5. Connection: keep-alive 6. Set-Cookie: __cfduid=de732197c8620f117376fe065378573e81477095253; expires=Sun, 22-Oct-17 00:14:13 GMT; path=/; domain=.lugroma3.org; HttpOnly 7. X-Powered-By: Express 8. Location: http://ld16.lugroma3.org 9. Vary: Accept 10. set-cookie: connect.sid=s%3A9xJsdl9k5L8gS9czLmdxSxMKZ6ZiKUls.Iscr5N2kRxapQg0jCSlwvS d9J6qrYjE%2BU6zao0Fgd3U; Path=/; HttpOnly 11. CF-Cache-Status: MISS 12. Expires: Sat, 22 Oct 2016 04:14:13 GMT 13. Cache-Control: public, max-age=14400 14. Server: cloudflare-nginx 15. CF-RAY: 2f58bf74b6e142fe-MXP 16. Found. Redirecting to http://ld16.lugroma3.org
  • 31. Introduzione a Scapy • Ora che abbiamo imparato a dissezionare tramite «la via difficile», vediamo come si può fare in maniera più facile. • Python ha un’ottima libreria – chiamata Scapy – che è on-top ai raw socket e che ha una grande quantità di dissector. • E’ quindi veloce, facile da usare ed estendibile. • Ci sono però dei contro: • A livello «didattico» molte cose sono già pronte quindi se ci può essere utile per fare degli script in velocità va bene, ma può non essere il massimo per approfondire totalmente la materia. • Inoltre se dobbiamo fare il deploy di alcuni script, dobbiamo necessariamente portarci dietro la libreria. • Fare il debug potrebbe essere più complesso, al netto di studiarsi a fondo la libreria. • Si installa e.g. su debian con $ sudo apt-get install scapy http://www.secdev.org/project s/scapy/doc/
  • 32. Il nostro «sudato» HTTP sniffer con scapy 1. #!/usr/bin/env python 2. from scapy.all import * 3. sniff(filter="port 80", prn=lambda x:x.sprintf("{IP:%IP.src%:%TCP.sport% > %IP.dst%:%TCP.dport%n}{Raw:%Raw.load%n}")) # abilito lo sniffing filtrano per la porta 80 – default di HTTP – e uso una funzione lambda (funzione in una riga, derivata dal LISP).
  • 33. Running Sniffer - Summary >>> sniff(filter="port 80", prn=lambda x:x.summary()) Ether / IP / TCP 192.168.44.129:33842 > 104.28.12.52:http S Ether / IP / TCP 104.28.12.52:http > 192.168.44.129:33842 SA / Padding Ether / IP / TCP 192.168.44.129:33842 > 104.28.12.52:http A Ether / IP / TCP 192.168.44.129:33842 > 104.28.12.52:http PA / Raw Ether / IP / TCP 104.28.12.52:http > 192.168.44.129:33842 A / Padding Ether / IP / TCP 104.28.12.52:http > 192.168.44.129:33842 PA / Raw Ether / IP / TCP 192.168.44.129:33842 > 104.28.12.52:http A Ether / IP / TCP 104.28.12.52:http > 192.168.44.129:33842 PA / Raw Ether / IP / TCP 192.168.44.129:33842 > 104.28.12.52:http A
  • 34. Running Sniffer - show >>> sniff(filter="port 80", prn=lambda x:x.show()) ###[ Raw ]### load = 'GET / HTTP/1.1rnUser- Agent: Wget/1.17.1 (linux-gnu)rnAccept: */*rnAccept-Encoding: identityrnHost: ld16.lugroma3.orgrnConnection: Keep- Alivernrn' ###[ Ethernet ]### dst = 00:50:56:f2:8f:ed src = 00:0c:29:15:7d:b4 type = 0x800 ###[ IP ]### version = 4L ihl = 5L tos = 0x0 len = 40 id = 20386 flags = DF frag = 0L ttl = 64 proto = tcp chksum = 0x89b4 src = 192.168.44.129 dst = 104.28.12.52 options ###[ TCP ]### sport = 33854 dport = http seq = 4174054303 ack = 1672679894 dataofs = 5L reserved = 0L flags = A window = 29200 chksum = 0x6194 urgptr = 0 options = {}
  • 35. Running Sniffer – Stampa campi >>> sniff(filter="port 80", prn=lambda x:x.sprintf("{IP:%IP.src%:%TCP.sport% > %IP.dst%:%TCP.dport%n}{Raw:%Raw.load%n}")) 192.168.44.129:51510 > 104.28.13.52:http 'GET /images/ld16/logo.png HTTP/1.1rnReferer: http://ld16.lugroma3.org/stylesheets/style-ld16.cssrnIf- Modified-Since: Fri, 21 Oct 2016 17:32:00 GMTrnUser-Agent: Wget/1.17.1 (linux-gnu)rnAccept: */*rnAccept-Encoding: identityrnHost: ld16.lugroma3.orgrnConnection: Keep-AlivernCookie: connect.sid=s%3A1YiIo3FZNlLwGFEG-WJ89jlG77BTYl7j.MbRExRQTaEBk%2FCMwip75wkaAP38LSWgWBsEKw0WjJQM; __cfduid=d9e77fbf2df651e3b203dfc5bd65fd8401477084930rnrn' 104.28.13.52:http > 192.168.44.129:51510 104.28.13.52:http > 192.168.44.129:51510 'HTTP/1.1 200 OKrnDate: Fri, 21 Oct 2016 21:22:11 GMTrnContent-Type: image/pngrnContent-Length: 27300rnConnection: keep-alivernX-Powered-By: ExpressrnAccept-Ranges: bytesrnCache-Control: public, max-age=14400rnLast-Modified: Fri, 21 Oct 2016 17:32:00 GMTrnETag: W/"6aa4-157e84ca79a"rnCF-Cache- Status: MISSrnVary: Accept-EncodingrnExpires: Sat, 22 Oct 2016 01:22:11 GMTrnServer: cloudflare- nginxrnCF-RAY: 2f57c378b7b34340- MXPrnrnx89PNGrnx1anx00x00x00rIHDRx00x00x01xc1x00x00x00rx08x06x00x00x00+x92jx87x0 0x00x00x19tEXtSoftwarex00Adobe ImageReadyqxc9e<x00x00x03qiTXtXML:com.adobe.xmpx00x00x00x00x00<?xpacket begin="xefxbbxbf" id="W5M0MpCehiHzreSzNTczkc9d"?> <x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.5-c021 79.154911, 2013/10/29-11:47:16 "> <rdf:RDF
  • 36. Prossimi passi • Fare quando scritto nelle diapositive nel pratico • Segnalare eventuali problemi • Cambiare tipologia di socket per leggere anche i pacchetti inviati e fare il dissector per ARP • Fare dei test con Scapy
  • 38. Riferimenti • TJ O'Connor – Violent Python (2012) • Justin Seitz – Black Hat Python (2014) • Pete Herzog et al. – OSSTMM v3 (2010) https://tools.ietf.org/html/rfc3168 https://tools.ietf.org/rfc/rfc791.txt https://www.python.org/dev/peps/pep-0008/ https://tools.ietf.org/html/rfc793 http://docs.python-guide.org/en/latest/starting/installation/ https://packaging.python.org/installing/ http://docs.python-guide.org/en/latest/dev/virtualenvs/ https://github.com/dloss/python-pentest-tools https://wiki.python.org/moin/Python2orPython3