Table of Contents
Change Log Frequently Asked Questions Background Information Required Tools Optional Tools Linux Shellcoding - Example 1 - Making a Quick Exit - Example 2 - Saying Hello - Example 3 - Spawning a Shell Windows Shellcoding - Example 1 - Sleep is for the Weak - Example 2 - A Message to say "Hey" - Example 3 - Adding an Administrative Account Advanced Shellcoding Methods - Printable Shellcode Conclusion Further Reading/Attributions
Change Log
1. Created - July 2004
2. Advanced Shellcoding Methods Section Added - Sept 2005
3. Updated Faq regarding stack randomization. - June 2007
Frequently Asked Questions
1. What is shellcoding?
In computer security, shellcoding in its most literal sense, means writing code that will return a remote shell when executed. The meaning of shellcode has evolved,it now represents any byte code that will be inserted into an exploit to accomplish adesired task.
2. There are tons of shellcode repositories all around the internet, why should I write my own?
Yes, you are correct, there are tons of repositories all around the internet for shellcoding. Namely, the metasploit project seems to be the best. Writing an exploit can be difficult, what happens when all of the prewritten blocks of codecease to work? You need to write your own! Hopefully this tutorial will give you a good head start.
3. What do I need to know before I begin?
A decent understanding of x86 assembly, C, and knowledge of theLinux and Windows operating systems.
4. What are the differences between windows shellcode and Linux shellcode?
Linux, unlike windows, provides a direct way to interface with the kernel throughthe int 0x80 interface. A complete listing of the Linux syscall table can be found here.Windows on the other hand, does not have a direct kernel interface. The system must be interfaced by loading theaddress of the function that needs to be executed from a DLL (Dynamic Link Library). The key difference betweenthe two is the fact that the address of the functions found in windows will vary from OS version to OS versionwhile the int 0x80 syscall numbers will remain constant. Windows programmers did this so that they could make any change needed to the kernel without any hassle; Linux on the contrary has fixed numbering system for all kernel level functions, and if they were to change, there would be a million angry programmers (and a lot of broken code).
5. So, what about windows? How do I find the addresses of my needed DLL functions? Don't these addresses change with every service pack upgrade?
There are multitudes of ways to find the addresses of the functions that you need to use in your shellcode. There are two methods for addressing functions; you can find the desired function at runtime or use hard coded addresses. This tutorial will mostly discuss the hard coded method. The only DLL that is guaranteed to be mapped into the shellcode's address space is kernel32.dll. This DLL will hold LoadLibrary and GetProcAddress, the two functions needed to obtain any functions address that can be mapped into the exploits process space. There is a problem with this method though, the address offsets will change with every new release of Windows (service packs, patches etc.). So, if you use this method your shellcode will ONLY work for a specific version of Windows. Further dynamic addressing will be referenced at the end of the paper in the Further Reading section.
6. What's the hype with making sure the shellcode won't have any NULL bytes in it? Normal programs have lots of NULL bytes!
Well this isn't a normal program! The main problem arises in the fact that when the exploit is inserted it will be a string.As we all know, strings are terminated with a NULL byte (C style strings anyhow). If we have a NULL byte in our shellcode things won't work correctly.
7. Why does my shellcode program crash when I run it?
Well, in most shellcode the assembly contained within has some sort of self modifying qualities. Since we are working in protected mode operating systems the .code segment of the executable image is read only. That is why the shell program needs to copy itself to the stack before attempting execution.
8. Can I contact you?
Sure, just email shanna@uiuc.edu. Feel free to ask questions, comments, or correct something that is wrong in this tutorial.
9. Why did you use intel syntax, UGHHH?!
I don't know! I honestly prefer at&t syntax, but for some reason I felt compelled to do this in intel syntax. I am really sorry!
10. Why does my program keep segfaulting? Yes, I read item 7 above, but it STILL crashes.
You probably are using an operating system with randomized stack and address space and possibly a protection mechanism that prevents you from executing code on the stack. All Linux based operating systems are not the same, so I present a solution for Fedora that should adapt easily.
Background Information
- EAX, EBX, ECX, and EDX are all 32-bit General Purpose Registers on the x86 platform.
- AH, BH, CH and DH access the upper 16-bits of the GPRs.
- AL, BL, CL, and DL access the lower 8-bits of the GPRs.
- ESI and EDI are used when making Linux syscalls.
- Syscalls with 6 arguments or less are passed via the GPRs.
- XOR EAX, EAX is a great way to zero out a register (while staying away from the nefarious NULL byte!)
- In Windows, all function arguments are passed on the stack according to their calling convention.
Required Tools
- gcc
- ld
- nasm
- objdump
Optional Tools
- odfhex.c - a utility created by me to extract the shellcode from "objdump -d" and turn it into escaped hex code (very useful!).
- arwin.c - a utility created by me to find the absolute addresses of windows functions within a specified DLL.
- shellcodetest.c - this is just a copy of the c code found below. it is a small skeleton program to test shellcode.
- exit.asm hello.asm msgbox.asm shellex.asm sleep.asm adduser.asm - the source code found in this document (the win32 shellcode was written with Windows XP SP1).
Linux Shellcoding
When testing shellcode, it is nice to just plop it into a program and let it run. The C program belowwill be used to test all of our code.
/*shellcodetest.c*/
Example 1 - Making a Quick Exit
The easiest way to begin would be to demonstrate the exit syscall due to it's simplicity. Here is some simpleasm code to call exit. Notice the al and XOR trick to ensure that no NULL bytes will get into our code.
The bytes we need are b0 01 31 db cd 80.
Replace the code at the top with: char code[] = "\xb0\x01\x31\xdb\xcd\x80";
Now, run the program. We have a successful piece of shellcode! One can strace the program to ensure that itis calling exit.
Example 2 - Saying Hello
For this next piece, let's ease our way into something useful. In this block of code one will find an exampleon how to load the address of a string in a piece of our code at runtime. This is important because while runningshellcode in an unknown environment, the address of the string will be unknown because the program is not runningin its normal address space.
Example 3 - Spawning a Shell
This code combines what we have been doing so far. This code attempts to set root privileges if they are droppedand then spawns a shell. Note: system("/bin/sh") would have been a lot simpler right? Well the only problem withthat approach is the fact that system always drops privileges.
Remember when reading this code:
execve (const char *filename, const char** argv, const char** envp);
So, the second two argument expect pointers to pointers. That's why I load the address of the "/bin/sh" into the string memory and thenpass the address of the string memory to the function. When the pointers are dereferenced the target memory will be the "/bin/sh" string.
Windows Shellcoding
Example 1 - Sleep is for the Weak!
In order to write successful code, we first need to decide what functions we wish to use for this shellcodeand then find their absolute addresses. For this example we just want a thread to sleep for an allotted amount of time. Let's load up arwin (found above) and get started. Remember, the only module guaranteed to be mapped into the processes address space is kernel32.dll. So for this example, Sleep seems to be the simplest function, accepting the amount of time the thread should suspend as its only argument.
When this code is inserted it will cause the parent thread to suspend for five seconds (note: it will then probably crash because the stack is smashed at this point :-D).
Example 2 - A Message to say "Hey"
This second example is useful in the fact that it will show a shellcoder how to do several things within the bounds of windows shellcoding. Although this example does nothing more than pop up a message box and say "hey", it demonstrates absolute addressing as well as the dynamic addressing using LoadLibrary and GetProcAddress. The library functions we will be using are LoadLibraryA, GetProcAddress, MessageBoxA, and ExitProcess (note: the A after the function name specifies we will be using a normal character set, as opposed to a W which would signify a wide character set; such as unicode). Let's load up arwin and find the addresses we need to use. We will not retrieve the address of MessageBoxA at this time, we will dynamically load that address.
This example, while not useful in the fact that it only pops up a message box, illustrates several important concepts when using windows shellcoding. Static addressing as used in most of the example above can be a powerful (and easy) way to whip up working shellcode within minutes. This example shows the process of ensuring that certain DLLs are loaded into a process space. Once the address of the MessageBoxA function is obtained ExitProcess is called to make sure that the program ends without crashing.
Example 3 - Adding an Administrative Account
This third example is actually quite a bit simpler than the previous shellcode, but this code allows the exploiter to add a user to the remote system and give that user administrative privileges. This code does not require the loading of extra libraries into the process space because the only functions we will be using are WinExec and ExitProcess. Note: the idea for this code was taken from the Metasploit project mentioned above. The difference between the shellcode is that this code is quite a bit smaller than its counterpart, and it can be made even smaller by removing the ExitProcess function!
When this code is executed it will add a user to the system with the specified password, then adds that user to the local Administrators group. After that codeis done executing, the parent process is exited by calling ExitProcess.
Advanced Shellcoding
This section covers some more advanced topics in shellcoding. Over time I hope to add quite a bit more content here but for the time beingI am very busy. If you have any specific requests for topics in this section, please do not hesitate to email me.
Printable Shellcode
The basis for this section is the fact that many Intrustion Detection Systems detect shellcode because of the non-printable charactersthat are common to all binary data. The IDS observes that a packet containts some binary data (with for instance a NOP sled withinthis binary data) and as a result may drop the packet. In addition to this, many programs filter input unless it is alpha-numeric. The motivation behind printable alpha-numeric shellcode should be quite obvious. By increasing the size of our shellcode we can implementa method in which our entire shellcode block in in printable characters. This section will differ a bit from the others presented in thispaper. This section will simply demonstrate the tactic with small examples without an all encompassing final example.
Our first discussion starts with obfuscating the ever blatant NOP sled. When an IDS sees an arbitrarily long string of NOPs (0x90)it will most likely drop the packet. To get around this we observe the decrement and increment op codes:
It should be pretty obvious that if we insert these operations instead of a NOP sled then the code will not affect the output. This is due to the factthat whenever we use a register in our shellcode we wither move a value into it or we xor it. Incrementing or decrementing the register before ourcode executes will not change the desired operation.
So, the next portion of this printable shellcode section will discuss a method for making one's entire block of shellcode alpha-numeric-- by meansof some major tomfoolery. We must first discuss the few opcodes that fall in the printable ascii range (0x33 through 0x7e).
sub eax, 0xHEXINRANGE push eax pop eax push esp pop esp and eax, 0xHEXINRANGE
Surprisingly, we can actually do whatever we want with these instructions. I did my best to keep diagrams out of this talk, but I decided to gracethe world with my wonderful ASCII art. Below you can find a diagram of the basic plan for constructing the shellcode.
The plan works as follows: -make space on stack for shellcode and loader -execute loader code to construct shellcode -use a NOP bridge to ensure that there aren't any extraneous bytes that will crash our code. -profit
But now I hear you clamoring that we can't use move nor can we subtract from esp because they don't fall into printable characters!!! Settle down, haveI got a solution for you! We will use subtract to place values into EAX, push the value to the stack, then pop it into ESP.
Now you're wondering why I said subtract to put values into EAX, the problem is we can't use add, and we can't directly assign nonprintable bytes.How can we overcome this? We can use the fact that each register has only 32 bits, so if we force a wrap around, we can arbitrarily assign values to a registerusing only printable characters with two to three subtract instructions.
If the gears in your head aren't cranking yet, you should probably stop reading right now.
The log awaited ASCII diagram 1) EIP(loader code) --------ALLOCATED STACK SPACE--------ESP 2) ---(loader code)---EIP-------STACK------ESP--(shellcode-- 3) ----loadercode---EIP@ESP----shellcode that was builts---
So, that diagram probably warrants some explanation. Basically, we take our already written shellcode, and generate two to three subtract instructionsper four bytes and do the push EAX, pop ESP trick. This basically places the constructed shellcode at the end of the stack and works towards the EIP.So we construct 4 bytes at a time for the entirety of the code and then insert a small NOP bridge (indicated by @) between the builder code and the shellcode.The NOP bridge is used to word align the end of the builder code.
Example code:
and eax, 0x454e4f4a ; example of how to zero out eax(unrelated)
and eax, 0x3a313035
push esp
pop eax
sub eax, 0x39393333 ; construct 860 bytes of room on the stack
sub eax, 0x72727550
sub eax, 0x54545421
push eax ; save into esp
pop esp
Oh, and I forgot to mention, the code must be inserted in reverse order and the bytes must adhere to the little endian standard.That job sounds incredibly tedious, thank god that matrix
wrote a tool that does it for us!The point is that now you can use this utility only once you understand the concepts presented above. Remember, if you don't understand it, you're justanother script kiddie.
Further Reading
Below is a list of great resources that relate to shellcoding. I suggest picking up a copy of all of the documents listed, but if that is an impossibility, at the very least get The Shellcoder's Handbook; it is a pure goldmine of information.
- The Shellcoder's Handbook by Jack Koziol et al
- Hacking - The Art of Exploitation by Jon Erickson
- "Understanding Windows Shellcode" by nologin.org
Conclusion
At this point the reader should be able to write at the very least basic shellcode to exploit applications on either the windows or linux platforms. The tricks demonstrated here will help a shellcoder understand other's shellcode and modify prewritten shellcode to fit the situation at hand. Shellcoding is always looked at as a minor detail of hacking a piece of software but invariably, a hack is only as strong enough as its weakest link. If the shellcode doesn't work, then the attempt at breaking the software fails; that is why it is important to understand all aspect of the process. Otherwise, good luck and have fun shellcoding!
Copyright 2004 Steve Hanna