This is the conclusion of a three part series discussing the ramifications of unbounded string manipulations in an example program called 'synscan'. In case you missed it, you might want to check out the previous parts before reading on:
In order to execute arbitrary code (i.e. the payload) through this bug, first we must have a way to get the payload into memory at a known address. (It is also important to note that the payload must be in a page marked as executable which can vary based on security hardening measures but in this case we are considering a system with an executable stack.) Once a suitable memory location has been found, we need to overwrite the stored return address with the address of our payload. The payload in this case is a set of instructions used to spawn a shell commonly referred to as shellcode. For the sake of keeping a narrow scope, I feel that it makes the most sense to reuse the shellcode which is derived in AlephOne’s article in Phrack #49. (Google ‘Smashing the Stack For Fun and Profit’ for a complete explanation of how this was developed.)
As I have alluded to, the role of the exploit code is to put the shellcode in memory (on the stack in this example), locate the address where the instructions start, construct a command line argument to overflow the buffer, and then finally to execute the vulnerable program with the crafted argument string. In this basic buffer overflow it will only be necessary for the argument to contain the payload address repeated enough times to overwrite the saved EIP.
The call to execle() (line 21) begins execution of synscan with the payload buffer set as an environment variable. The address of the shellcode is found (line 14) by subtracting the shellcode length and the length of the invoked program’s name from the known starting address for BASH variables (0xbffffffa). The resulting address is repeated to build a buffer for the command line argument on lines 17 & 18. Since the return address should be 4-byte aligned, it is sufficient to simply repeat the calculated return address and see that the saved EIP gets perfectly replaced by the target. The only thing left to do is compile and test the exploit as shown below.
If you are a developer concerned about this type of attack, I encourage you to perform some static analysis of your code. Unbounded string manipulation has no place in secure software so any instances of strcpy, strcat, or sprintf (as well as a few others) should stand out like a sore thumb.
This concludes ‘VERT Vuln School: Stack Buffer Overflows 101’ – please feel free to create a free nCircle Connect account to comment on this post with any questions or comments for the author related to this or other security topics.