↓ Skip to main content
  1. Writeups/
  2. Try Hack Me/

Dead Endpoint

Description
#

01 // MISSION

Staff arrived to find their internal photo gallery unusable and its images unreadable. The Linux server’s disk has been preserved, but the cause is still unclear. Reconstruct how the application was compromised, analyze the executable left behind, and find a way to recover the affected images.

Describe the challenge and what the analyst is trying to determine.

02 // OBJECTIVES

  1. Establish how the gallery application was compromised.
  2. Identify the executable responsible for the affected images.
  3. Analyze its behavior and determine how the files were encrypted.
  4. Recover the images and retrieve the inspection checklist.

Check the challenge here.

Solution
#

In this lab we are provided access to an analyst Linux machine that contains the tools that we need to analyze the disk. We can find the file at ~/Desktop/artifacts/disk.img.

Before looking for answers to the questions, let’s see how we can explore the disk image. I am not a specialist in forensics, so let me know if there is a more professional way of doing this. 😅

First I checked the partition layout to explore the filesystems on the disk image with mmls:

Partition Layout

Then I tried to mount each partition to the /mnt/ev mounting point. I succeeded with slot 008:

sudo mkdir /mnt/ev
sudo mount -o ro,loop,noload,offset=$((2099200*512)) ~/Desktop/artifacts/disk.img /mnt/ev

Now we have the whole filesystem of the compromised server in /mnt/ev.


Question 1
#

Which application endpoint was abused to execute commands on the server?

Now that we can hop in the filesystem, we can start looking for evidence. Two things come into my mind when starting these kinds of challenges: finding the server source code, and finding the server logs.

In Linux we can usually find logs in /var/log, and for this case the nginx folder had the files we are looking for (starting with gallery-*). We can take a look to see if there are any traces left:

Nginx Logs

We can see someone performed some actions on the web server. It would be useful to read the code now and see what happened. I found the code at /mnt/ev/srv/gallery/app/gallery.py.

I found this endpoint that appears to be creating a new thread of execution using a job provided by a user:

Vulnerable Endpoint

This endpoint seems to be the answer to this question.


Question 2
#

What was the full path of the executable responsible for encrypting the images?

In the entrypoint Python code (see screenshot above) we can also see that the payload is saved to the database in the exports table. We can find the database at /mnt/ev/srv/gallery/data/ and we can inspect it using sqlite3:

Payload in Database

The payload exploits a command injection vulnerability to download malware on the system, and there we can see the exact path of the executable.


Question 3
#

What is the SHA-256 hash of that executable?

Now that we have the location of the executable we can extract the hash using the sha256sum Linux utility:

SHA-256 Hash


Question 4
#

Which encryption algorithm and mode protected the images?

To find out the encryption algorithm we need to study the malware file. First let’s check what kind of file it is:

Malware File Type

We have a 64-bit elf file. We can use ghidra to decompile and analyze it.

After playing around I found that the function FUN_00101574() is probably the function used to encrypt a single file. There we can find the objects used to encrypt and also the algorithm (note that the format of the flag is a bit different: ***-***-***):

Encryption Algorithm


Question 5
#

What initial seed value was used to generate the encryption key?

Now we need to go into the depths of this binary and see how the encryption was made. There are two functions that contain the majority of the logic (FUN_00101574() which is responsible for encrypting individual files, and FUN_001019fe() where the broad logic of encrypting all files happens), and there are two more specialized functions that we will discuss later.

General Malware Logic
#

Usually I prefer to go directly to the juicy part of the code, understand the most important behaviour and then figure out the details. Let’s start with FUN_001019fe(), here is the most interesting part of the code:

Main Encryption Loop

We can instantly observe that FUN_00101574() is called for each of the .jpg files, which means that every file is encrypted there (we already knew this from the previous questions). We can also see that in this function the ransomware notice is dropped in the RESTORE.txt file.

Let’s take a look at FUN_00101574()’s parameters, especially the third one:

Parameters of FUN_00101574

Key Passed to EVP_EncryptInit_ex

We can see that the third parameter is used in EVP_EncryptInit_ex() which is a function from the OpenSSL C library. We can check the documentation (link here) and see that the parameter is used as the key for encryption.

Now let’s go back to FUN_001019fe() and see how this key is generated.

Key Generation
#

The key appears to be generated in this snippet of the function:

Key Generation Snippet

In order to understand what is happening there we need to explore two other functions. Let’s start with FUN_00101509().

SplitMix64 PRNG

I gave this code to an LLM to see if it can spot clues, and I found that this is actually a pseudo-random number generator called SplitMix64. This means that the malware uses a seed to create a random number that is passed further to FUN_00101554(), let’s explore it now:

Little-Endian Buffer Writer

This function seems to perform some buffer operations. I made an LLM translate this snippet into something more readable and I got this equivalent C code:

#include <stdint.h>

void write_uint64_le(uint8_t *buffer, uint64_t value)
{
    for (int i = 0; i < 8; i++)
    {
        buffer[i] = (uint8_t)(value >> (i * 8));
    }
}

It just looks like a function that is copying 8 bytes at a time into the buffer (in little endian).

Alright now we have the full picture: the malware is using a seed to generate a random value using SplitMix64, that random value is our encryption / decryption key. The final piece is to see where the seed is coming from.

Let’s check another snippet:

Seed From Timestamp

The local_1f8 object is a timestamp of the current time when the executable is running, and the seed is computed based on that timestamp.

Building the solver
#

Here is our solution so far:

  1. Find the time when the malware executed: a time interval.
  2. Go through all the timestamps in the interval and compute the seeds.
  3. For each seed generate the key and try to decrypt one file, since the encryption was done with AES-GCM, the decryption should fail (because of the authentication step) if the key is incorrect.
  4. In the end one key should be valid.

Now we just need to figure out how to decrypt an encrypted file.

To find out the encryption process and how the encrypted files are stored we can go deeper into FUN_00101574(). In this snippet we can see some interesting details:

Cipher Context Allocations

The double allocation is interesting: the first one pointing to the in variable is the same size as the target file for encryption, which suggests that this might be the place where the ciphertext will be stored. And the other allocation (pointing to in_00) might suggest some additional data that can be stored about the file (like the IV, tag, etc.).

Here we can see how the two allocated spaces are used for encryption:

Encryption Process

Figuring this out would take a lot of time for a human, so I used an LLM to help me understand faster and more precisely how the files are stored. It generated this very useful file layout:

Encrypted File Layout

Alright now we have all the ingredients to build a solver Python script and try to crack the encryption key. We will use the timestamps provided in the database (see screenshot from Question 2).

Solver:

import struct
from datetime import datetime, timezone
from pathlib import Path
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

MASK64 = 0xFFFFFFFFFFFFFFFF
GAMMA = 0x9e3779b97f4a7c15
MUL1  = 0xbf58476d1ce4e5b9
MUL2  = 0x94d049bb133111eb
START = "2026-10-20T05:36:54.547+00:00"
END   = "2026-10-20T05:36:54.753+00:00"

def timestamp_to_ms(timestamp):
    dt = datetime.fromisoformat(timestamp)
    epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
    delta = dt - epoch

    return (
        delta.days * 86400000
        + delta.seconds * 1000
        + delta.microseconds // 1000
    )

def splitmix64(state):
    state = (state + GAMMA) & MASK64
    z = state
    z = ((z ^ (z >> 30)) * MUL1) & MASK64
    z = ((z ^ (z >> 27)) * MUL2) & MASK64
    return state, z ^ (z >> 31)

def generate_key(seed):
    state = seed
    key = bytearray()
    for _ in range(4):
        state, value = splitmix64(state)
        key.extend(value.to_bytes(8, "little"))
    return bytes(key)

def recover_key(filepath):
    data = Path(filepath).read_bytes()
    if len(data) < 48 or data[:5] != b"GPH1\x01":
        print("[-] Invalid encrypted file")
        return

    original_size = struct.unpack_from("<Q", data, 8)[0]
    nonce = data[16:28]
    tag = data[28:44]
    aad = data[:28]
    ciphertext = data[48:]

    if len(ciphertext) != original_size:
        print("[-] Invalid ciphertext size")
        return

    encrypted_data = ciphertext + tag
    start_ms = timestamp_to_ms(START)
    end_ms = timestamp_to_ms(END)
    print(f"[*] Testing {end_ms - start_ms + 1} seeds...")

    for seed in range(start_ms, end_ms + 1):
        key = generate_key(seed)
        try:
            AESGCM(key).decrypt(
                nonce,
                encrypted_data,
                aad
            )

            print("\n[+] KEY FOUND!")
            print(f"Seed: {seed}")
            print(f"Key:  {key.hex()}")
            print(f"Nonce: {nonce.hex()}")
            return seed, key

        except Exception:
            continue

    print("[-] No matching key found")
    return None

if __name__ == "__main__":
    import sys

    if len(sys.argv) != 2:
        print(f"Usage: python3 {sys.argv[0]} file.locked")
        sys.exit(1)
    recover_key(sys.argv[1])

This script tries every key that could have been generated in the interval found in the database. A key is found when the decryption is successful. Let’s run it against one of the encrypted files.

Recovered Key

And we found the key!


Question 6
#

What flag appears in the recovered inspection checklist?

We’ve done the hard work, now we only need a Python script to decrypt the locked files.

Decryption script:

import argparse
import struct
from pathlib import Path
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

KEY = bytes.fromhex(
    "[REDACTED]"
)

def decrypt_file(filepath, aes):
    data = filepath.read_bytes()

    # Validate minimum size and file header
    if len(data) < 48 or data[:5] != b"GPH1\x01":
        raise ValueError("Invalid encrypted file format")

    # Extract original file size
    original_size = struct.unpack_from("<Q", data, 8)[0]

    # Extract AES-GCM parameters
    aad = data[:28]
    nonce = data[16:28]
    tag = data[28:44]
    ciphertext = data[48:]

    if len(ciphertext) != original_size:
        raise ValueError("Ciphertext size mismatch")

    # Decrypt and authenticate
    plaintext = aes.decrypt(
        nonce,
        ciphertext + tag,
        aad
    )

    # Output filename without .locked
    output_path = filepath.with_name(
        filepath.name[:-len(".locked")]
    )

    if output_path.exists():
        raise FileExistsError(f"Output already exists: {output_path}")

    output_path.write_bytes(plaintext)
    return output_path

def main():
    parser = argparse.ArgumentParser(
        description="Recover files encrypted with AES-GCM"
    )
    parser.add_argument(
        "folder",
        type=Path,
        help="Folder containing .locked files"
    )

    args = parser.parse_args()
    folder = args.folder

    if not folder.is_dir():
        parser.error("Specified path is not a directory")

    aes = AESGCM(KEY)
    files = sorted(folder.glob("*.locked"))

    if not files:
        print("[-] No .locked files found")
        return

    print(f"[*] Found {len(files)} encrypted files\n")

    recovered = 0
    failed = 0

    for filepath in files:
        print(f"[*] Processing: {filepath.name}")
        try:
            output = decrypt_file(filepath, aes)

            print(f"[+] Recovered: {output.name}\n")
            recovered += 1

        except Exception as e:
            print(f"[-] Failed: {e}\n")
            failed += 1

    print("=" * 50)
    print(f"Recovery complete")
    print(f"Successfully recovered: {recovered}")
    print(f"Failed:                 {failed}")
    print("=" * 50)

if __name__ == "__main__":
    main()

Let’s copy our files and run the script:

Decrypting the Files

Great, it worked! The flag is located in yard_0152.jpg:

Flag in Decrypted Image


Conclusion
#

Very interesting challenge! I learned that LLMs can be very useful in reverse engineering, they are very good at understanding the abstract decompiled Ghidra code, and they are so helpful when building Python scripts!


Reference
#

Splitmix64

OpenSSL Documentation - EVP_EncryptInit

Vlad Șteopoaie
Author
Vlad Șteopoaie
A.K.A. h3pha