146Web Application Penetration Testingprocess, and using fuzzing techniques.Gray Box testingWhen reviewing code, one must realize that there are severalavenues where heap related vulnerabilities may arise. Code thatseems innocuous at the first glance can actually be vulnerableunder certain conditions. Since there are several variants of thisvulnerability, we will cover only the issues that are predominant.Most of the time, heap buffers are considered safe by a lot of developerswho do not hesitate to perform insecure operations likestrcpy( ) on them. The myth that a stack overflow and instructionpointer overwrite are the only means to execute arbitrary codeproves to be hazardous in case of code shown below:-int main(int argc, char *argv[]){……}vulnerable(argv[1]);return 0;int vulnerable(char *buf){}……..HANDLE hp = HeapCreate(0, 0, 0);HLOCAL chunk = HeapAlloc(hp, 0, 260);strcpy(chunk, buf); ‘’’ Vulnerability’’’return 0;In this case, if buf exceeds 260 bytes, it will overwrite pointers inthe adjacent boundary tag, facilitating the overwrite of an arbitrarymemory location with 4 bytes of data once the heap managementroutine kicks in.Lately, several products, especially anti-virus libraries, havebeen affected by variants that are combinations of an integeroverflow and copy operations to a heap buffer. As an example,consider a vulnerable code snippet, a part of code responsible forprocessing TNEF filetypes, from Clam Anti Virus 0.86.1, sourcefile tnef.c and function tnef_message( ):string = cli_malloc(length + 1); ‘’’ Vulnerability’’’if(fread(string, 1, length, fp) != length) {‘’’ Vulnerability’’’free(string);return -1;}The malloc in line 1 allocates memory based on the value oflength, which happens to be a 32 bit integer. In this particular example,length is user-controllable and a malicious TNEF file canbe crafted to set length to ‘-1’, which would result in malloc( 0 ).Therefore, this malloc would allocate a small heap buffer, whichwould be 16 bytes on most 32 bit platforms (as indicated in malloc.h).And now, in line 2, a heap overflow occurs in the call to fread(). The 3rd argument, in this case length, is expected to be asize_t variable. But if it’s going to be ‘-1’, the argument wraps to0xFFFFFFFF, thus copying 0xFFFFFFFF bytes into the 16 bytebuffer.Static code analysis tools can also help in locating heap relatedvulnerabilities such as “double free” etc. A variety of tools likeRATS, Flawfinder and ITS4 are available for analyzing C-stylelanguages.Tools• OllyDbg: “A windows based debugger used for analyzing bufferoverflow vulnerabilities” - http://www.ollydbg.de• Spike, A fuzzer framework that can be used to explorevulnerabilities and perform length testing -http://www.immunitysec.com/downloads/SPIKE2.9.tgz• Brute Force Binary Tester (BFB), A proactive binary checker -http://bfbtester.sourceforge.net• Metasploit, A rapid exploit development and Testing framework - http://www.metasploit.comReferencesWhitepapers• w00w00: “Heap Overflow Tutorial” -http://www.cgsecurity.org/exploit/heaptut.txt• David Litchfield: “Windows Heap Overflows” -http://www.blackhat.com/presentations/win-usa-04/bhwin-04-litchfield/bh-win-04-litchfield.pptTesting for Stack OverflowSummaryStack overflows occur when variable size data is copied into fixedlength buffers located on the program stack without any boundschecking. Vulnerabilities of this class are generally considered tobe of high severity since their exploitation would mostly permitarbitrary code execution or Denial of Service. Rarely found in interpretedplatforms, code written in C and similar languages isoften ridden with instances of this vulnerability. In fact almostevery platform is vulnerable to stack overflows with the followingnotable exceptions:• J2EE – as long as native methods or system calls are notinvoked• .NET – as long as /unsafe or unmanaged code is not invoked(such as the use of P/Invoke or COM Interop)• PHP – as long as external programs and vulnerable PHPextensions written in C or C++ are not called can suffer fromstack overflow issues.Stack overflow vulnerabilities often allow an attacker to directlytake control of the instruction pointer and, therefore, alter theexecution of the program and execute arbitrary code. Besides
147Web Application Penetration Testingoverwriting the instruction pointer, similar results can also beobtained by overwriting other variables and structures, like ExceptionHandlers, which are located on the stack.On opening the executable with the supplied arguments andcontinuing execution the following results are obtained.How to TestBlack Box testingThe key to testing an application for stack overflow vulnerabilitiesis supplying overly large input data as compared to what isexpected. However, subjecting the application to arbitrarily largedata is not sufficient. It becomes necessary to inspect the application’sexecution flow and responses to ascertain whether anoverflow has actually been triggered or not. Therefore, the stepsrequired to locate and validate stack overflows would be to attacha debugger to the target application or process, generatemalformed input for the application, subject the application tomalformed input, and inspect responses in a debugger. The debuggerallows the tester to view the execution flow and the stateof the registers when the vulnerability gets triggered.On the other hand, a more passive form of testing can be employed,which involves inspecting assembly code of the applicationby using disassemblers. In this case, various sections arescanned for signatures of vulnerable assembly fragments. Thisis often termed as reverse engineering and is a tedious process.As a simple example, consider the following technique employedwhile testing an executable “sample.exe” for stack overflows:#includeint main(int argc, char *argv[]){char buff[20];printf(“copying into buffer”);strcpy(buff,argv[1]);return 0;}File sample.exe is launched in a debugger, in our case OllyDbg.As shown in the registers window of the debugger, the EIP or ExtendedInstruction Pointer, which points to the next instructionto be executed, contains the value ‘41414141’. ‘41’ is a hexadecimalrepresentation for the character ‘A’ and therefore the string‘AAAA’ translates to 41414141.This clearly demonstrates how input data can be used to overwritethe instruction pointer with user-supplied values and controlprogram execution. A stack overflow can also allow overwritingof stack-based structures like SEH (Structured ExceptionHandler) to control code execution and bypass certain stack protectionmechanisms.As mentioned previously, other methods of testing such vulnerabilitiesinclude reverse engineering the application binaries,which is a complex and tedious process, and using fuzzing techniques.Gray Box testingWhen reviewing code for stack overflows, it is advisable tosearch for calls to insecure library functions like gets(), strcpy(),strcat() etc which do not validate the length of source strings andblindly copy data into fixed size buffers.For example consider the following function:-void log_create(int severity, char *inpt) {Since the application is expecting command line arguments, alarge sequence of characters such as ‘A’, can be supplied in theargument field shown above.char b[1024];